Compare commits
47
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7154e7cec3 | ||
|
|
52b04b947e | ||
|
|
e9ed70c5b9 | ||
|
|
ffae5410e8 | ||
|
|
31dfe3596e | ||
|
|
c2776c2336 | ||
|
|
22f021ed69 | ||
|
|
a4964b3b36 | ||
|
|
c6c64918f8 | ||
|
|
4abf8b46c5 | ||
|
|
3083d712ee | ||
|
|
6672a1d210 | ||
|
|
92e54fb96c | ||
|
|
8cc9a6fa6b | ||
|
|
b2d17b7108 | ||
|
|
fb1034546f | ||
|
|
f5f98cf0ae | ||
|
|
37ac970e28 | ||
|
|
8919ae7c53 | ||
|
|
c1e2408e1f | ||
|
|
8b993bc9ff | ||
|
|
ea52bb1dbd | ||
|
|
28107e89c2 | ||
|
|
82a9bcc7f4 | ||
|
|
61f8d46fa2 | ||
|
|
0debebafbb | ||
|
|
2a29de7502 | ||
|
|
8c1605b383 | ||
|
|
90074e359f | ||
|
|
6155f5cf64 | ||
|
|
e3970e755b | ||
|
|
3c246f56b4 | ||
|
|
cebbe6ff19 | ||
|
|
e4a84a348e | ||
|
|
61e6d89d69 | ||
|
|
1b2f39d018 | ||
|
|
8c2d33abde | ||
|
|
60dc4af916 | ||
|
|
d389cfd4e3 | ||
|
|
6fc79737c3 | ||
|
|
cdd03591ef | ||
|
|
2fbb0565d7 | ||
|
|
a3dadc04bf | ||
|
|
1a59277dc8 | ||
|
|
6424197a19 | ||
|
|
8d4a8b4f31 | ||
|
|
23ab75e84a |
No files matched your search
@@ -48,7 +48,9 @@ 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.
|
||||
@@ -56,6 +58,9 @@ 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
|
||||
|
||||
@@ -73,4 +78,6 @@ 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. If there are no findings, report exactly `All clear`.
|
||||
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.
|
||||
@@ -100,25 +100,41 @@ function shellSingleQuote(value) {
|
||||
return `'${value.replaceAll("'", "'\\''")}'`;
|
||||
}
|
||||
|
||||
function writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath) {
|
||||
const mainEntryPath = NodePath.join(desktopDir, "dist-electron", "main.cjs");
|
||||
export function makeDevelopmentLauncherScript({
|
||||
electronBinaryPath,
|
||||
mainEntryPath,
|
||||
desktopRoot,
|
||||
environment,
|
||||
}) {
|
||||
const envEntries = [
|
||||
["VITE_DEV_SERVER_URL", process.env.VITE_DEV_SERVER_URL],
|
||||
["T3CODE_PORT", process.env.T3CODE_PORT],
|
||||
["T3CODE_HOME", process.env.T3CODE_HOME],
|
||||
["T3CODE_COMMIT_HASH", process.env.T3CODE_COMMIT_HASH],
|
||||
["T3CODE_OTLP_TRACES_URL", process.env.T3CODE_OTLP_TRACES_URL],
|
||||
["T3CODE_OTLP_EXPORT_INTERVAL_MS", process.env.T3CODE_OTLP_EXPORT_INTERVAL_MS],
|
||||
["VITE_DEV_SERVER_URL", environment.VITE_DEV_SERVER_URL],
|
||||
["T3CODE_PORT", environment.T3CODE_PORT],
|
||||
["T3CODE_HOME", environment.T3CODE_HOME],
|
||||
["T3CODE_COMMIT_HASH", environment.T3CODE_COMMIT_HASH],
|
||||
["T3CODE_OTLP_TRACES_URL", environment.T3CODE_OTLP_TRACES_URL],
|
||||
["T3CODE_OTLP_EXPORT_INTERVAL_MS", environment.T3CODE_OTLP_EXPORT_INTERVAL_MS],
|
||||
["T3CODE_DESKTOP_APP_USER_MODEL_ID", APP_BUNDLE_ID],
|
||||
].filter((entry) => typeof entry[1] === "string" && entry[1].trim().length > 0);
|
||||
return [
|
||||
"#!/bin/sh",
|
||||
...envEntries.map(
|
||||
([name, value]) =>
|
||||
`if [ -z "\${${name}:-}" ]; then export ${name}=${shellSingleQuote(value)}; fi`,
|
||||
),
|
||||
`exec ${shellSingleQuote(electronBinaryPath)} --t3code-dev-root=${shellSingleQuote(desktopRoot)} ${shellSingleQuote(mainEntryPath)} "$@"`,
|
||||
"",
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
function writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath) {
|
||||
NodeFS.writeFileSync(
|
||||
targetBinaryPath,
|
||||
[
|
||||
"#!/bin/sh",
|
||||
...envEntries.map(([name, value]) => `export ${name}=${shellSingleQuote(value)}`),
|
||||
`exec ${shellSingleQuote(electronBinaryPath)} --t3code-dev-root=${shellSingleQuote(desktopDir)} ${shellSingleQuote(mainEntryPath)} "$@"`,
|
||||
"",
|
||||
].join("\n"),
|
||||
makeDevelopmentLauncherScript({
|
||||
electronBinaryPath,
|
||||
mainEntryPath: NodePath.join(desktopDir, "dist-electron", "main.cjs"),
|
||||
desktopRoot: desktopDir,
|
||||
environment: process.env,
|
||||
}),
|
||||
);
|
||||
NodeFS.chmodSync(targetBinaryPath, 0o755);
|
||||
}
|
||||
@@ -286,6 +302,12 @@ function buildMacLauncher(electronBinaryPath) {
|
||||
currentMetadata &&
|
||||
JSON.stringify(currentMetadata) === JSON.stringify(expectedMetadata)
|
||||
) {
|
||||
if (isDevelopment) {
|
||||
// The launcher also handles protocol activations outside the dev runner,
|
||||
// so refresh its fallback environment on every launch. Never let a value
|
||||
// captured by an older parent app override the live dev-runner environment.
|
||||
writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath);
|
||||
}
|
||||
registerMacLauncherBundle(targetAppBundlePath);
|
||||
return targetBinaryPath;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
import { assert, describe, it } from "vite-plus/test";
|
||||
|
||||
import { makeDevelopmentLauncherScript } from "./electron-launcher.mjs";
|
||||
|
||||
describe("electron development launcher", () => {
|
||||
it("uses captured values only as fallbacks for a live runner environment", () => {
|
||||
const script = makeDevelopmentLauncherScript({
|
||||
electronBinaryPath: "/repo/node_modules/electron/Electron",
|
||||
mainEntryPath: "/repo/apps/desktop/dist-electron/main.cjs",
|
||||
desktopRoot: "/repo/apps/desktop",
|
||||
environment: {
|
||||
VITE_DEV_SERVER_URL: "http://127.0.0.1:8526",
|
||||
T3CODE_PORT: "16566",
|
||||
T3CODE_HOME: "/tmp/t3",
|
||||
},
|
||||
});
|
||||
|
||||
assert.include(
|
||||
script,
|
||||
"if [ -z \"${VITE_DEV_SERVER_URL:-}\" ]; then export VITE_DEV_SERVER_URL='http://127.0.0.1:8526'; fi",
|
||||
);
|
||||
assert.notInclude(script, "\nexport VITE_DEV_SERVER_URL=");
|
||||
assert.include(
|
||||
script,
|
||||
"exec '/repo/node_modules/electron/Electron' --t3code-dev-root='/repo/apps/desktop' '/repo/apps/desktop/dist-electron/main.cjs' \"$@\"",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -43,7 +43,16 @@ describe("ElectronProtocol", () => {
|
||||
assert.isDefined(handler);
|
||||
|
||||
const response = yield* Effect.promise(() =>
|
||||
handler!(new Request("t3code-dev://app/api/health?verbose=1")),
|
||||
handler!(
|
||||
new Request("t3code-dev://app/api/health?verbose=1", {
|
||||
headers: {
|
||||
accept: "application/json",
|
||||
origin: "t3code-dev://app",
|
||||
referer: "t3code-dev://app/",
|
||||
"sec-fetch-site": "same-origin",
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
assert.equal(yield* Effect.promise(() => response.text()), "ok");
|
||||
assert.include(
|
||||
@@ -70,6 +79,11 @@ describe("ElectronProtocol", () => {
|
||||
["t3code-dev"],
|
||||
);
|
||||
assert.equal(netFetchMock.mock.calls[0]?.[0], "http://127.0.0.1:3773/api/health?verbose=1");
|
||||
const forwardedHeaders = new Headers(netFetchMock.mock.calls[0]?.[1]?.headers);
|
||||
assert.equal(forwardedHeaders.get("accept"), "application/json");
|
||||
assert.isNull(forwardedHeaders.get("origin"));
|
||||
assert.isNull(forwardedHeaders.get("referer"));
|
||||
assert.isNull(forwardedHeaders.get("sec-fetch-site"));
|
||||
assert.deepEqual(unhandleMock.mock.calls, [["t3code-dev"]]);
|
||||
}).pipe(Effect.provide(ElectronProtocol.layer)),
|
||||
);
|
||||
@@ -99,6 +113,34 @@ describe("ElectronProtocol", () => {
|
||||
}).pipe(Effect.provide(ElectronProtocol.layer)),
|
||||
);
|
||||
|
||||
it.effect("retries transient renderer target failures", () =>
|
||||
Effect.gen(function* () {
|
||||
let handler: ((request: Request) => Promise<Response>) | undefined;
|
||||
handleMock.mockImplementation((_scheme, nextHandler) => {
|
||||
handler = nextHandler;
|
||||
});
|
||||
netFetchMock
|
||||
.mockRejectedValueOnce(new Error("connect ECONNREFUSED 127.0.0.1:5733"))
|
||||
.mockResolvedValueOnce(new Response("ready"));
|
||||
|
||||
const response = yield* Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const protocol = yield* ElectronProtocol.ElectronProtocol;
|
||||
yield* protocol.registerDesktopProtocol({
|
||||
scheme: "t3code-dev",
|
||||
targetOrigin: new URL("http://127.0.0.1:5733/"),
|
||||
backendOrigin: new URL("http://127.0.0.1:3773/"),
|
||||
clerkFrontendApiHostname: undefined,
|
||||
});
|
||||
return yield* Effect.promise(() => handler!(new Request("t3code-dev://app/")));
|
||||
}),
|
||||
);
|
||||
|
||||
assert.equal(yield* Effect.promise(() => response.text()), "ready");
|
||||
assert.equal(netFetchMock.mock.calls.length, 2);
|
||||
}).pipe(Effect.provide(ElectronProtocol.layer)),
|
||||
);
|
||||
|
||||
it.effect("preserves protocol registration failures", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("protocol registration failed");
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as NodeTimersPromises from "node:timers/promises";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Scope from "effect/Scope";
|
||||
@@ -114,18 +115,60 @@ async function proxyRequest(
|
||||
}
|
||||
|
||||
const targetUrl = new URL(`${requestUrl.pathname}${requestUrl.search}`, targetOrigin);
|
||||
const headers = new Headers(request.headers);
|
||||
const headersToRemove: string[] = [];
|
||||
for (const name of headers.keys()) {
|
||||
if (
|
||||
name === "host" ||
|
||||
name === "origin" ||
|
||||
name === "referer" ||
|
||||
name === "connection" ||
|
||||
name === "content-length" ||
|
||||
name === "accept-encoding" ||
|
||||
name === "upgrade-insecure-requests" ||
|
||||
name.startsWith("sec-fetch-")
|
||||
) {
|
||||
headersToRemove.push(name);
|
||||
}
|
||||
}
|
||||
for (const name of headersToRemove) {
|
||||
headers.delete(name);
|
||||
}
|
||||
const init: RequestInit = {
|
||||
method: request.method,
|
||||
headers: request.headers,
|
||||
headers,
|
||||
};
|
||||
if (request.method !== "GET" && request.method !== "HEAD") {
|
||||
init.body = request.body;
|
||||
(init as RequestInit & { duplex: "half" }).duplex = "half";
|
||||
}
|
||||
const response = await Electron.net.fetch(targetUrl.toString(), init);
|
||||
const response =
|
||||
request.method === "GET" || request.method === "HEAD"
|
||||
? await fetchWithTransientRetry(targetUrl.toString(), init)
|
||||
: await Electron.net.fetch(targetUrl.toString(), init);
|
||||
return withContentSecurityPolicy(response, contentSecurityPolicy);
|
||||
}
|
||||
|
||||
const TRANSIENT_FETCH_RETRY_DELAYS_MS = [0, 50, 150] as const;
|
||||
|
||||
async function fetchWithTransientRetry(url: string, init: RequestInit): Promise<Response> {
|
||||
let lastError: unknown;
|
||||
|
||||
for (const delayMs of TRANSIENT_FETCH_RETRY_DELAYS_MS) {
|
||||
if (delayMs > 0) {
|
||||
await NodeTimersPromises.setTimeout(delayMs);
|
||||
}
|
||||
|
||||
try {
|
||||
return await Electron.net.fetch(url, init);
|
||||
} catch (error) {
|
||||
lastError = error;
|
||||
}
|
||||
}
|
||||
|
||||
throw lastError;
|
||||
}
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const registered = yield* Ref.make(false);
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { it as effectIt } from "@effect/vitest";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
@@ -18,16 +19,25 @@ import * as ElectronWindow from "../electron/ElectronWindow.ts";
|
||||
import * as BrowserSession from "./BrowserSession.ts";
|
||||
import * as PreviewManager from "./Manager.ts";
|
||||
|
||||
const { createFromPath, fromId, mkdir, showItemInFolder, webviewSend, writeFile, writeImage } =
|
||||
vi.hoisted(() => ({
|
||||
createFromPath: vi.fn((): { readonly isEmpty: () => boolean } => ({ isEmpty: () => false })),
|
||||
fromId: vi.fn(() => null),
|
||||
mkdir: vi.fn((_path: string) => undefined),
|
||||
showItemInFolder: vi.fn(),
|
||||
webviewSend: vi.fn(),
|
||||
writeFile: vi.fn((_path: string, _data: Uint8Array) => undefined),
|
||||
writeImage: vi.fn(),
|
||||
}));
|
||||
const {
|
||||
createFromPath,
|
||||
fromId,
|
||||
getFocusedWebContents,
|
||||
mkdir,
|
||||
showItemInFolder,
|
||||
webviewSend,
|
||||
writeFile,
|
||||
writeImage,
|
||||
} = vi.hoisted(() => ({
|
||||
createFromPath: vi.fn((): { readonly isEmpty: () => boolean } => ({ isEmpty: () => false })),
|
||||
fromId: vi.fn(() => null),
|
||||
getFocusedWebContents: vi.fn(() => null),
|
||||
mkdir: vi.fn((_path: string) => undefined),
|
||||
showItemInFolder: vi.fn(),
|
||||
webviewSend: vi.fn(),
|
||||
writeFile: vi.fn((_path: string, _data: Uint8Array) => undefined),
|
||||
writeImage: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("electron", () => ({
|
||||
clipboard: {
|
||||
@@ -44,6 +54,7 @@ vi.mock("electron", () => ({
|
||||
},
|
||||
webContents: {
|
||||
fromId,
|
||||
getFocusedWebContents,
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -81,6 +92,7 @@ const layer = PreviewManager.layer.pipe(
|
||||
Layer.provideMerge(environmentLayer),
|
||||
Layer.provideMerge(fileSystemLayer),
|
||||
Layer.provideMerge(Path.layer),
|
||||
Layer.provideMerge(Layer.succeed(HostProcessPlatform, "linux")),
|
||||
);
|
||||
const encodePreviewManagerError = Schema.encodeSync(PreviewManager.PreviewManagerError);
|
||||
|
||||
@@ -97,6 +109,8 @@ const withManager = <A>(
|
||||
describe("PreviewManager", () => {
|
||||
beforeEach(() => {
|
||||
fromId.mockClear();
|
||||
getFocusedWebContents.mockReset();
|
||||
getFocusedWebContents.mockReturnValue(null);
|
||||
mkdir.mockClear();
|
||||
writeFile.mockClear();
|
||||
showItemInFolder.mockClear();
|
||||
@@ -250,6 +264,197 @@ describe("PreviewManager", () => {
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("mirrors Electron's effective zoom across registration and navigation", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
let effectiveZoom = 0.9;
|
||||
let zoomReadable = true;
|
||||
let url = "https://example.com";
|
||||
const listeners = new Map<string, (...args: unknown[]) => void>();
|
||||
const setZoomFactor = vi.fn();
|
||||
fromId.mockReturnValue({
|
||||
id: 42,
|
||||
isDestroyed: () => false,
|
||||
getType: () => "webview",
|
||||
getURL: () => url,
|
||||
getTitle: () => "Example",
|
||||
isLoading: () => false,
|
||||
getZoomFactor: () => {
|
||||
if (!zoomReadable) throw new Error("zoom unavailable");
|
||||
return effectiveZoom;
|
||||
},
|
||||
setZoomFactor,
|
||||
on: vi.fn((event: string, listener: (...args: unknown[]) => void) => {
|
||||
listeners.set(event, listener);
|
||||
}),
|
||||
off: vi.fn(),
|
||||
ipc: { on: vi.fn(), off: vi.fn() },
|
||||
send: webviewSend,
|
||||
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
debugger: {
|
||||
isAttached: () => false,
|
||||
attach: vi.fn(),
|
||||
sendCommand: vi.fn(async () => undefined),
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
},
|
||||
} as never);
|
||||
const states: PreviewManager.PreviewTabState[] = [];
|
||||
|
||||
yield* manager.subscribeStateChanges((_tabId, state) =>
|
||||
Effect.sync(() => {
|
||||
states.push(state);
|
||||
}),
|
||||
);
|
||||
yield* manager.createTab("tab_zoom");
|
||||
yield* manager.registerWebview("tab_zoom", 42);
|
||||
|
||||
expect(states.at(-1)?.zoomFactor).toBe(0.9);
|
||||
expect(setZoomFactor).not.toHaveBeenCalled();
|
||||
|
||||
effectiveZoom = 1.25;
|
||||
listeners.get("did-navigate")?.();
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
expect(states.at(-1)?.zoomFactor).toBe(1.25);
|
||||
expect(setZoomFactor).not.toHaveBeenCalled();
|
||||
|
||||
zoomReadable = false;
|
||||
url = "https://example.com/after-zoom-read-failed";
|
||||
listeners.get("did-navigate")?.();
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
expect(states.at(-1)?.navStatus).toEqual({
|
||||
kind: "Success",
|
||||
url,
|
||||
title: "Example",
|
||||
});
|
||||
expect(states.at(-1)?.zoomFactor).toBe(1.25);
|
||||
|
||||
const replacementSetZoomFactor = vi.fn();
|
||||
fromId.mockReturnValue({
|
||||
id: 43,
|
||||
isDestroyed: () => false,
|
||||
getType: () => "webview",
|
||||
getURL: () => url,
|
||||
getTitle: () => "Example",
|
||||
isLoading: () => false,
|
||||
getZoomFactor: () => 1,
|
||||
setZoomFactor: replacementSetZoomFactor,
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
ipc: { on: vi.fn(), off: vi.fn() },
|
||||
send: webviewSend,
|
||||
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
debugger: {
|
||||
isAttached: () => false,
|
||||
attach: vi.fn(),
|
||||
sendCommand: vi.fn(async () => undefined),
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
},
|
||||
} as never);
|
||||
|
||||
yield* manager.registerWebview("tab_zoom", 43);
|
||||
|
||||
expect(replacementSetZoomFactor).toHaveBeenCalledWith(1.25);
|
||||
expect(states.at(-1)?.zoomFactor).toBe(1.25);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("keeps a main-frame load failure visible until a retry starts", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
const url = "http://localhost:5733/";
|
||||
let loading = false;
|
||||
const listeners = new Map<string, (...args: unknown[]) => void>();
|
||||
fromId.mockReturnValue({
|
||||
id: 42,
|
||||
isDestroyed: () => false,
|
||||
getType: () => "webview",
|
||||
getURL: () => url,
|
||||
getTitle: () => "localhost:5733",
|
||||
isLoading: () => loading,
|
||||
getZoomFactor: () => 1,
|
||||
setZoomFactor: vi.fn(),
|
||||
on: vi.fn((event: string, listener: (...args: unknown[]) => void) => {
|
||||
listeners.set(event, listener);
|
||||
}),
|
||||
off: vi.fn(),
|
||||
ipc: { on: vi.fn(), off: vi.fn() },
|
||||
send: webviewSend,
|
||||
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
debugger: {
|
||||
isAttached: () => false,
|
||||
attach: vi.fn(),
|
||||
sendCommand: vi.fn(async () => undefined),
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
},
|
||||
} as never);
|
||||
const statuses: PreviewManager.PreviewNavStatus[] = [];
|
||||
|
||||
yield* manager.subscribeStateChanges((_tabId, state) =>
|
||||
Effect.sync(() => {
|
||||
statuses.push(state.navStatus);
|
||||
}),
|
||||
);
|
||||
yield* manager.createTab("tab_failed");
|
||||
yield* manager.registerWebview("tab_failed", 42);
|
||||
|
||||
listeners.get("did-fail-load")?.(
|
||||
{},
|
||||
-105,
|
||||
"ERR_NAME_NOT_RESOLVED",
|
||||
"https://missing-frame.example/",
|
||||
false,
|
||||
);
|
||||
yield* Effect.yieldNow;
|
||||
expect(statuses.at(-1)?.kind).toBe("Success");
|
||||
|
||||
loading = true;
|
||||
listeners.get("did-start-loading")?.();
|
||||
yield* Effect.yieldNow;
|
||||
expect(statuses.at(-1)?.kind).toBe("Loading");
|
||||
|
||||
loading = false;
|
||||
listeners.get("did-fail-load")?.({}, -102, "ERR_CONNECTION_REFUSED", url, true);
|
||||
listeners.get("did-stop-loading")?.();
|
||||
listeners.get("page-title-updated")?.();
|
||||
yield* Effect.yieldNow;
|
||||
expect(statuses.at(-1)).toEqual({
|
||||
kind: "LoadFailed",
|
||||
url,
|
||||
title: "localhost:5733",
|
||||
code: -102,
|
||||
description: "ERR_CONNECTION_REFUSED",
|
||||
});
|
||||
|
||||
loading = true;
|
||||
listeners.get("did-start-loading")?.();
|
||||
yield* Effect.yieldNow;
|
||||
expect(statuses.at(-1)?.kind).toBe("Loading");
|
||||
|
||||
loading = false;
|
||||
listeners.get("did-stop-loading")?.();
|
||||
yield* Effect.yieldNow;
|
||||
expect(statuses.at(-1)?.kind).toBe("Success");
|
||||
|
||||
listeners.get("did-fail-load")?.({}, -102, "ERR_CONNECTION_REFUSED", url, true);
|
||||
yield* Effect.yieldNow;
|
||||
expect(statuses.at(-1)?.kind).toBe("LoadFailed");
|
||||
|
||||
listeners.get("did-navigate")?.();
|
||||
yield* Effect.yieldNow;
|
||||
expect(statuses.at(-1)?.kind).toBe("Success");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("captures a PNG screenshot into browser artifacts", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
@@ -511,6 +716,178 @@ describe("PreviewManager", () => {
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("types in background webviews and enables native key input", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
let failKeyDown = false;
|
||||
let humanInput: ((_event: unknown, signal: unknown) => void) | undefined;
|
||||
const sendCommand = vi.fn(async (method: string, params?: Record<string, unknown>) => {
|
||||
if (
|
||||
failKeyDown &&
|
||||
method === "Input.dispatchKeyEvent" &&
|
||||
(params?.["type"] === "keyDown" || params?.["type"] === "rawKeyDown")
|
||||
) {
|
||||
throw new Error("key dispatch failed");
|
||||
}
|
||||
if (
|
||||
method === "Input.dispatchKeyEvent" &&
|
||||
(params?.["type"] === "keyDown" || params?.["type"] === "rawKeyDown")
|
||||
) {
|
||||
humanInput?.(
|
||||
{},
|
||||
{
|
||||
kind: "key",
|
||||
key: params["key"],
|
||||
code: params["code"] ?? "Digit1",
|
||||
},
|
||||
);
|
||||
}
|
||||
return method === "Runtime.evaluate" ? { result: { value: { ok: true } } } : undefined;
|
||||
});
|
||||
const restoreFocus = vi.fn();
|
||||
const focus = vi.fn();
|
||||
getFocusedWebContents.mockReturnValue({
|
||||
id: 7,
|
||||
isDestroyed: () => false,
|
||||
focus: restoreFocus,
|
||||
} as never);
|
||||
fromId.mockReturnValue({
|
||||
id: 42,
|
||||
isDestroyed: () => false,
|
||||
getType: () => "webview",
|
||||
getURL: () => "https://example.com",
|
||||
getTitle: () => "Example",
|
||||
isLoading: () => false,
|
||||
isDevToolsOpened: () => false,
|
||||
focus,
|
||||
getZoomFactor: () => 1,
|
||||
setZoomFactor: vi.fn(),
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
ipc: {
|
||||
on: vi.fn((channel: string, listener: typeof humanInput) => {
|
||||
if (channel === "preview:human-input") humanInput = listener;
|
||||
}),
|
||||
off: vi.fn(),
|
||||
},
|
||||
send: webviewSend,
|
||||
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
debugger: {
|
||||
isAttached: () => false,
|
||||
attach: vi.fn(),
|
||||
sendCommand,
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
},
|
||||
} as never);
|
||||
|
||||
yield* manager.createTab("tab_input");
|
||||
yield* manager.registerWebview("tab_input", 42);
|
||||
yield* manager.automationType("tab_input", { text: "hello", clear: true });
|
||||
yield* manager.automationType("tab_input", { text: "", clear: true });
|
||||
yield* manager.automationPress("tab_input", { key: "x" });
|
||||
|
||||
const calls = sendCommand.mock.calls;
|
||||
const methods = calls.map(([method]) => method);
|
||||
const enableIndex = methods.indexOf("Input.setIgnoreInputEvents");
|
||||
const focusOnIndex = calls.findIndex(
|
||||
([method, params]) =>
|
||||
method === "Emulation.setFocusEmulationEnabled" && params?.["enabled"] === true,
|
||||
);
|
||||
const keyDownIndex = calls.findIndex(
|
||||
([method, params]) =>
|
||||
method === "Input.dispatchKeyEvent" && params?.["type"] === "keyDown",
|
||||
);
|
||||
const keyUpIndex = calls.findIndex(
|
||||
([method, params]) => method === "Input.dispatchKeyEvent" && params?.["type"] === "keyUp",
|
||||
);
|
||||
const focusOffIndex = calls.findIndex(
|
||||
([method, params]) =>
|
||||
method === "Emulation.setFocusEmulationEnabled" && params?.["enabled"] === false,
|
||||
);
|
||||
const typeEvaluation = sendCommand.mock.calls.find(
|
||||
([method, params]) =>
|
||||
method === "Runtime.evaluate" &&
|
||||
typeof params === "object" &&
|
||||
params !== null &&
|
||||
"expression" in params &&
|
||||
typeof params.expression === "string" &&
|
||||
params.expression.includes('document.execCommand("insertText"'),
|
||||
);
|
||||
expect(typeEvaluation).toBeDefined();
|
||||
const clearOnlyEvaluation = sendCommand.mock.calls.find(
|
||||
([method, params]) =>
|
||||
method === "Runtime.evaluate" &&
|
||||
typeof params === "object" &&
|
||||
params !== null &&
|
||||
"expression" in params &&
|
||||
typeof params.expression === "string" &&
|
||||
params.expression.includes('const text = ""') &&
|
||||
params.expression.includes("Object.getOwnPropertyDescriptor"),
|
||||
);
|
||||
expect(clearOnlyEvaluation).toBeDefined();
|
||||
expect(methods).not.toContain("Input.insertText");
|
||||
expect(enableIndex).toBeGreaterThanOrEqual(0);
|
||||
expect(focus).toHaveBeenCalledOnce();
|
||||
expect(restoreFocus).toHaveBeenCalledOnce();
|
||||
expect(methods).toContain("Page.bringToFront");
|
||||
expect(enableIndex).toBeLessThan(focusOnIndex);
|
||||
expect(focusOnIndex).toBeLessThan(keyDownIndex);
|
||||
expect(keyDownIndex).toBeLessThan(keyUpIndex);
|
||||
expect(keyUpIndex).toBeLessThan(focusOffIndex);
|
||||
expect(
|
||||
calls.filter(
|
||||
([method, params]) =>
|
||||
method === "Input.dispatchKeyEvent" && params?.["type"] === "keyUp",
|
||||
),
|
||||
).toHaveLength(1);
|
||||
expect(sendCommand).toHaveBeenCalledWith("Input.setIgnoreInputEvents", { ignore: false });
|
||||
|
||||
sendCommand.mockClear();
|
||||
failKeyDown = true;
|
||||
const failedPress = yield* Effect.exit(manager.automationPress("tab_input", { key: "y" }));
|
||||
|
||||
expect(Exit.isFailure(failedPress)).toBe(true);
|
||||
expect(sendCommand).toHaveBeenCalledWith("Input.dispatchKeyEvent", {
|
||||
type: "keyUp",
|
||||
key: "y",
|
||||
code: "KeyY",
|
||||
modifiers: 0,
|
||||
windowsVirtualKeyCode: 89,
|
||||
location: 0,
|
||||
isKeypad: false,
|
||||
});
|
||||
expect(sendCommand).toHaveBeenCalledWith("Emulation.setFocusEmulationEnabled", {
|
||||
enabled: false,
|
||||
});
|
||||
expect(restoreFocus).toHaveBeenCalledTimes(2);
|
||||
expect(
|
||||
sendCommand.mock.calls.filter(
|
||||
([method, params]) =>
|
||||
method === "Input.dispatchKeyEvent" && params?.["type"] === "keyUp",
|
||||
),
|
||||
).toHaveLength(1);
|
||||
|
||||
sendCommand.mockClear();
|
||||
failKeyDown = false;
|
||||
yield* manager.automationPress("tab_input", { key: "!" });
|
||||
expect(sendCommand).toHaveBeenCalledWith("Input.dispatchKeyEvent", {
|
||||
type: "keyDown",
|
||||
key: "!",
|
||||
code: "Digit1",
|
||||
modifiers: 0,
|
||||
windowsVirtualKeyCode: 49,
|
||||
location: 0,
|
||||
isKeypad: false,
|
||||
text: "!",
|
||||
unmodifiedText: "!",
|
||||
});
|
||||
expect(restoreFocus).toHaveBeenCalledTimes(3);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("still interrupts agent control for a different human pointer event", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
|
||||
@@ -25,6 +25,7 @@ import type {
|
||||
PreviewAutomationTypeInput,
|
||||
PreviewAutomationWaitForInput,
|
||||
} from "@t3tools/contracts";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import { normalizePreviewUrl } from "@t3tools/shared/preview";
|
||||
import {
|
||||
type BrowserWindow,
|
||||
@@ -62,6 +63,7 @@ import {
|
||||
} from "./GuestProtocol.ts";
|
||||
import { isPreviewAnnotationPayload } from "./PickedElementPayload.ts";
|
||||
import { playwrightInjectedRuntimeInstallExpression } from "./PlaywrightInjectedRuntime.ts";
|
||||
import { makePreviewAutomationKeySequence } from "./PreviewKeyboard.ts";
|
||||
|
||||
export type PreviewNavStatus =
|
||||
| { kind: "Idle" }
|
||||
@@ -378,6 +380,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
artifactDirectory: string,
|
||||
) {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const hostPlatform = yield* HostProcessPlatform;
|
||||
const path = yield* Path.Path;
|
||||
const parentScope = yield* Scope.Scope;
|
||||
const context = yield* Effect.context<never>();
|
||||
@@ -854,11 +857,24 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
commandParams?: Record<string, unknown>,
|
||||
) => Effect.Effect<unknown, PreviewManagerError>;
|
||||
|
||||
const prepareAutomationInput = Effect.fn("PreviewManager.prepareAutomationInput")(function* (
|
||||
send: SendCommand,
|
||||
enableRuntime: boolean,
|
||||
) {
|
||||
yield* Effect.all(
|
||||
[
|
||||
...(enableRuntime ? [send("Runtime.enable")] : []),
|
||||
send("Input.setIgnoreInputEvents", { ignore: false }),
|
||||
],
|
||||
{ concurrency: 2, discard: true },
|
||||
);
|
||||
});
|
||||
|
||||
const withControlSession = Effect.fn("PreviewManager.withControlSession")(function* <A>(
|
||||
tabId: string,
|
||||
wc: Electron.WebContents,
|
||||
action: string,
|
||||
use: (send: SendCommand) => Effect.Effect<A, PreviewManagerError>,
|
||||
use: (send: SendCommand, sendCleanup: SendCommand) => Effect.Effect<A, PreviewManagerError>,
|
||||
) {
|
||||
const sequence = yield* nextCounter(actionSequenceRef);
|
||||
const startedAt = yield* currentIso;
|
||||
@@ -899,7 +915,22 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
return result;
|
||||
},
|
||||
);
|
||||
return yield* use(send);
|
||||
// Cleanup commands must still run after human input invalidates the action's
|
||||
// control epoch. Otherwise a partially dispatched input can leave Chromium
|
||||
// with a held key or focus emulation enabled for subsequent actions.
|
||||
const sendCleanup: SendCommand = Effect.fn("PreviewManager.sendCleanupCommand")(
|
||||
function* (method, commandParams) {
|
||||
return yield* attemptPromise(
|
||||
{
|
||||
operation: `${action}.cleanup.${method}`,
|
||||
tabId,
|
||||
webContentsId: wc.id,
|
||||
},
|
||||
() => wc.debugger.sendCommand(method, commandParams),
|
||||
);
|
||||
},
|
||||
);
|
||||
return yield* use(send, sendCleanup);
|
||||
});
|
||||
const finalize = Effect.fn("PreviewManager.finalizeControlAction")(function* (
|
||||
exit: Exit.Exit<A, PreviewManagerError>,
|
||||
@@ -1091,22 +1122,62 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
wc: Electron.WebContents,
|
||||
) {
|
||||
const scope = yield* Scope.fork(parentScope, "sequential");
|
||||
const syncState = Effect.fn("PreviewManager.syncWebContentsState")(function* () {
|
||||
const syncState = Effect.fn("PreviewManager.syncWebContentsState")(function* (
|
||||
preserveLoadFailure: boolean,
|
||||
) {
|
||||
if (wc.isDestroyed()) return;
|
||||
yield* update(tabId, {
|
||||
navStatus: computeNavStatus(wc),
|
||||
canGoBack: wc.navigationHistory.canGoBack(),
|
||||
canGoForward: wc.navigationHistory.canGoForward(),
|
||||
const zoomFactor = yield* attempt(
|
||||
{ operation: "syncWebContentsState.getZoomFactor", tabId, webContentsId: wc.id },
|
||||
() => wc.getZoomFactor(),
|
||||
).pipe(Effect.option);
|
||||
const computedNavStatus = computeNavStatus(wc);
|
||||
const canGoBack = wc.navigationHistory.canGoBack();
|
||||
const canGoForward = wc.navigationHistory.canGoForward();
|
||||
const updatedAt = yield* currentIso;
|
||||
const next = yield* SynchronizedRef.modify(tabsRef, (tabs) => {
|
||||
const current = tabs.get(tabId);
|
||||
if (!current) return [Option.none<PreviewTabState>(), tabs] as const;
|
||||
// Electron emits did-stop-loading after did-fail-load. At that point the
|
||||
// failed guest is no longer "loading", but it has not successfully
|
||||
// navigated anywhere. Keep the failure until a new load actually starts.
|
||||
const navStatus =
|
||||
preserveLoadFailure &&
|
||||
current.navStatus.kind === "LoadFailed" &&
|
||||
computedNavStatus.kind === "Success"
|
||||
? current.navStatus
|
||||
: computedNavStatus;
|
||||
const state: PreviewTabState = {
|
||||
...current,
|
||||
navStatus,
|
||||
canGoBack,
|
||||
canGoForward,
|
||||
...(Option.isSome(zoomFactor) ? { zoomFactor: zoomFactor.value } : {}),
|
||||
updatedAt,
|
||||
};
|
||||
return [
|
||||
Option.some(state),
|
||||
replaceMap(tabs, (copy) => {
|
||||
copy.set(tabId, state);
|
||||
}),
|
||||
] as const;
|
||||
});
|
||||
if (Option.isSome(next)) yield* emit(tabId, next.value);
|
||||
});
|
||||
const sync = () => runFork(syncState());
|
||||
const failed = (_event: Event, code: number, description: string): void => {
|
||||
if (code === -3) return;
|
||||
const sync = () => runFork(syncState(true));
|
||||
const syncNavigation = () => runFork(syncState(false));
|
||||
const failed = (
|
||||
_event: Event,
|
||||
code: number,
|
||||
description: string,
|
||||
validatedUrl: string,
|
||||
isMainFrame: boolean,
|
||||
): void => {
|
||||
if (code === -3 || !isMainFrame) return;
|
||||
runFork(
|
||||
update(tabId, {
|
||||
navStatus: {
|
||||
kind: "LoadFailed",
|
||||
url: wc.getURL(),
|
||||
url: validatedUrl || wc.getURL(),
|
||||
title: wc.getTitle(),
|
||||
code,
|
||||
description,
|
||||
@@ -1161,8 +1232,8 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
yield* Scope.addFinalizer(
|
||||
scope,
|
||||
attempt({ operation: "detachListeners", tabId, webContentsId: wc.id }, () => {
|
||||
wc.off("did-navigate", sync);
|
||||
wc.off("did-navigate-in-page", sync);
|
||||
wc.off("did-navigate", syncNavigation);
|
||||
wc.off("did-navigate-in-page", syncNavigation);
|
||||
wc.off("page-title-updated", sync);
|
||||
wc.off("did-start-loading", sync);
|
||||
wc.off("did-stop-loading", sync);
|
||||
@@ -1173,8 +1244,8 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
);
|
||||
const install = Effect.fn("PreviewManager.installWebContentsListeners")(function* () {
|
||||
yield* attempt({ operation: "attachListeners", tabId, webContentsId: wc.id }, () => {
|
||||
wc.on("did-navigate", sync);
|
||||
wc.on("did-navigate-in-page", sync);
|
||||
wc.on("did-navigate", syncNavigation);
|
||||
wc.on("did-navigate-in-page", syncNavigation);
|
||||
wc.on("page-title-updated", sync);
|
||||
wc.on("did-start-loading", sync);
|
||||
wc.on("did-stop-loading", sync);
|
||||
@@ -1280,21 +1351,40 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
const attached = yield* Ref.get(attachedRef);
|
||||
const annotationTheme = yield* Ref.get(annotationThemeRef);
|
||||
if (tab.webContentsId === webContentsId && attached.has(webContentsId)) {
|
||||
const zoomFactor = yield* attempt(
|
||||
{ operation: "registerWebview.getZoomFactor", tabId, webContentsId },
|
||||
() => wc.getZoomFactor(),
|
||||
);
|
||||
yield* update(tabId, { zoomFactor });
|
||||
yield* attempt({ operation: "registerWebview.sendTheme", tabId, webContentsId }, () =>
|
||||
wc.send(ANNOTATION_THEME_CHANNEL, annotationTheme),
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (tab.webContentsId != null && tab.webContentsId !== webContentsId) {
|
||||
const replacedWebContentsId =
|
||||
tab.webContentsId != null && tab.webContentsId !== webContentsId ? tab.webContentsId : null;
|
||||
if (replacedWebContentsId !== null) {
|
||||
yield* Effect.all(
|
||||
[
|
||||
detachControlSession(tab.webContentsId),
|
||||
detachListeners(tab.webContentsId),
|
||||
detachControlSession(replacedWebContentsId),
|
||||
detachListeners(replacedWebContentsId),
|
||||
cancelPickElement(tabId),
|
||||
],
|
||||
{ concurrency: 3, discard: true },
|
||||
);
|
||||
}
|
||||
const zoomFactor =
|
||||
replacedWebContentsId !== null
|
||||
? yield* attempt(
|
||||
{ operation: "registerWebview.restoreZoomFactor", tabId, webContentsId },
|
||||
() => {
|
||||
wc.setZoomFactor(tab.zoomFactor);
|
||||
return tab.zoomFactor;
|
||||
},
|
||||
)
|
||||
: yield* attempt({ operation: "registerWebview.getZoomFactor", tabId, webContentsId }, () =>
|
||||
wc.getZoomFactor(),
|
||||
);
|
||||
yield* attachListeners(tabId, wc);
|
||||
runFork(ensureControlSession(wc).pipe(Effect.ignore));
|
||||
const registeredAt = yield* currentIso;
|
||||
@@ -1313,6 +1403,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
navStatus: pendingUrl === null ? computeNavStatus(wc) : current.navStatus,
|
||||
canGoBack: wc.navigationHistory.canGoBack(),
|
||||
canGoForward: wc.navigationHistory.canGoForward(),
|
||||
zoomFactor,
|
||||
updatedAt: registeredAt,
|
||||
};
|
||||
return [
|
||||
@@ -1330,11 +1421,6 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
}
|
||||
const { state: registered, pendingUrl } = registration.value;
|
||||
yield* emit(tabId, registered);
|
||||
if (Math.abs(registered.zoomFactor - DEFAULT_ZOOM_FACTOR) > ZOOM_EPSILON) {
|
||||
yield* attempt({ operation: "registerWebview.restoreZoom", tabId, webContentsId }, () =>
|
||||
wc.setZoomFactor(registered.zoomFactor),
|
||||
).pipe(Effect.ignore);
|
||||
}
|
||||
yield* attempt({ operation: "registerWebview.sendTheme", tabId, webContentsId }, () =>
|
||||
wc.send(ANNOTATION_THEME_CHANNEL, annotationTheme),
|
||||
);
|
||||
@@ -1946,10 +2032,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
input: PreviewAutomationClickInput,
|
||||
send: SendCommand,
|
||||
) {
|
||||
yield* Effect.all(
|
||||
[send("Runtime.enable"), send("Input.setIgnoreInputEvents", { ignore: false })],
|
||||
{ concurrency: 2, discard: true },
|
||||
);
|
||||
yield* prepareAutomationInput(send, true);
|
||||
const point = yield* resolveClickPoint(tabId, send, input);
|
||||
const viewport = yield* evaluateWithDebugger<{ width: number; height: number }>(
|
||||
tabId,
|
||||
@@ -2011,7 +2094,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
);
|
||||
});
|
||||
|
||||
const focusAutomationTarget = Effect.fn("PreviewManager.focusAutomationTarget")(function* (
|
||||
const typeIntoAutomationTarget = Effect.fn("PreviewManager.typeIntoAutomationTarget")(function* (
|
||||
tabId: string,
|
||||
send: SendCommand,
|
||||
input: PreviewAutomationTypeInput,
|
||||
@@ -2021,8 +2104,15 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
const locatorJson = locator
|
||||
? yield* encodeJson({ operation: "automationType.encodeLocator", tabId }, locator)
|
||||
: null;
|
||||
const textJson = yield* encodeJson(
|
||||
{ operation: "automationType.encodeText", tabId },
|
||||
input.text,
|
||||
);
|
||||
const result = yield* evaluateWithDebugger<
|
||||
{ ok: true } | { invalidSelector: true; message: string } | { notFound: true }
|
||||
| { ok: true }
|
||||
| { invalidSelector: true; message: string }
|
||||
| { notEditable: true }
|
||||
| { notFound: true }
|
||||
>(
|
||||
tabId,
|
||||
send,
|
||||
@@ -2030,12 +2120,54 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
try {
|
||||
const element = ${locatorJson ? `(() => { const injected = globalThis.__t3PlaywrightInjected; return injected.querySelector(injected.parseSelector(${locatorJson}), document, true); })()` : "document.activeElement"};
|
||||
if (!element) return { notFound: true };
|
||||
const textControl =
|
||||
element instanceof HTMLTextAreaElement ||
|
||||
(element instanceof HTMLInputElement &&
|
||||
!new Set(["button", "checkbox", "color", "file", "hidden", "image", "radio", "range", "reset", "submit"]).has(element.type));
|
||||
const editable = textControl || element.isContentEditable;
|
||||
if (!editable || element.disabled || element.readOnly) return { notEditable: true };
|
||||
element.focus();
|
||||
if (${input.clear ?? false}) {
|
||||
if ("value" in element) element.value = "";
|
||||
else if (element.isContentEditable) element.textContent = "";
|
||||
element.dispatchEvent(new InputEvent("input", { bubbles: true, inputType: "deleteContentBackward" }));
|
||||
if (document.activeElement !== element) return { notEditable: true };
|
||||
const clear = ${input.clear ?? false};
|
||||
if (clear) {
|
||||
if (textControl) {
|
||||
element.select();
|
||||
} else {
|
||||
const range = document.createRange();
|
||||
range.selectNodeContents(element);
|
||||
const selection = document.getSelection();
|
||||
selection?.removeAllRanges();
|
||||
selection?.addRange(range);
|
||||
}
|
||||
}
|
||||
const text = ${textJson};
|
||||
let inserted = true;
|
||||
if (text.length > 0) {
|
||||
inserted = document.execCommand("insertText", false, text);
|
||||
} else if (clear) {
|
||||
document.execCommand("delete", false);
|
||||
const cleared = textControl
|
||||
? element.value.length === 0
|
||||
: (element.textContent ?? "").length === 0;
|
||||
if (!cleared) {
|
||||
if (textControl) {
|
||||
const prototype = element instanceof HTMLTextAreaElement
|
||||
? HTMLTextAreaElement.prototype
|
||||
: HTMLInputElement.prototype;
|
||||
const valueSetter = Object.getOwnPropertyDescriptor(prototype, "value")?.set;
|
||||
if (valueSetter) valueSetter.call(element, "");
|
||||
else element.value = "";
|
||||
} else {
|
||||
element.replaceChildren();
|
||||
}
|
||||
element.dispatchEvent(new InputEvent("input", {
|
||||
bubbles: true,
|
||||
inputType: "deleteContentBackward",
|
||||
}));
|
||||
}
|
||||
}
|
||||
if (!inserted) return { notEditable: true };
|
||||
element.dispatchEvent(new Event("change", { bubbles: true }));
|
||||
return { ok: true };
|
||||
} catch (error) {
|
||||
return { invalidSelector: true, message: String(error) };
|
||||
@@ -2059,6 +2191,12 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
...automationSelectorDiagnostics(input),
|
||||
});
|
||||
}
|
||||
if ("notEditable" in result) {
|
||||
return yield* new PreviewAutomationTargetNotEditableError({
|
||||
tabId,
|
||||
...automationSelectorDiagnostics(input),
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
const performAutomationType = Effect.fn("PreviewManager.performAutomationType")(function* (
|
||||
@@ -2066,23 +2204,10 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
input: PreviewAutomationTypeInput,
|
||||
send: SendCommand,
|
||||
) {
|
||||
yield* send("Runtime.enable");
|
||||
yield* focusAutomationTarget(tabId, send, input);
|
||||
yield* send("Input.insertText", { text: input.text });
|
||||
const textJson = yield* encodeJson(
|
||||
{ operation: "automationType.encodeText", tabId },
|
||||
input.text,
|
||||
);
|
||||
yield* evaluateWithDebugger(
|
||||
tabId,
|
||||
send,
|
||||
`(() => {
|
||||
const element = document.activeElement;
|
||||
element?.dispatchEvent(new InputEvent("input", { bubbles: true, inputType: "insertText", data: ${textJson} }));
|
||||
element?.dispatchEvent(new Event("change", { bubbles: true }));
|
||||
})()`,
|
||||
false,
|
||||
);
|
||||
// CDP Input.insertText silently drops text until Electron has activated a hidden
|
||||
// guest WebContents with a pointer event. Editing in the page runtime keeps
|
||||
// background automation deterministic without stealing foreground app focus.
|
||||
yield* typeIntoAutomationTarget(tabId, send, input);
|
||||
});
|
||||
|
||||
const automationType = Effect.fn("PreviewManager.automationType")(function* (
|
||||
@@ -2097,32 +2222,54 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
|
||||
const performAutomationPress = Effect.fn("PreviewManager.performAutomationPress")(function* (
|
||||
tabId: string,
|
||||
wc: Electron.WebContents,
|
||||
input: PreviewAutomationPressInput,
|
||||
send: SendCommand,
|
||||
sendCleanup: SendCommand,
|
||||
) {
|
||||
const modifiers = (input.modifiers ?? []).reduce((value, modifier) => {
|
||||
switch (modifier) {
|
||||
case "Alt":
|
||||
return value | 1;
|
||||
case "Control":
|
||||
return value | 2;
|
||||
case "Meta":
|
||||
return value | 4;
|
||||
case "Shift":
|
||||
return value | 8;
|
||||
yield* prepareAutomationInput(send, false);
|
||||
const keySequence = makePreviewAutomationKeySequence(input, {
|
||||
isMac: hostPlatform === "darwin",
|
||||
});
|
||||
const previouslyFocused = yield* attempt(
|
||||
{ operation: "automationPress.getFocusedWebContents", tabId, webContentsId: wc.id },
|
||||
() => webContents.getFocusedWebContents(),
|
||||
);
|
||||
let keyDownAttempted = false;
|
||||
const releaseInput = Effect.gen(function* () {
|
||||
if (keyDownAttempted) {
|
||||
yield* sendCleanup("Input.dispatchKeyEvent", keySequence.keyUp).pipe(Effect.ignore);
|
||||
}
|
||||
}, 0);
|
||||
const key = input.key;
|
||||
const text = key.length === 1 ? key : undefined;
|
||||
const params = {
|
||||
key,
|
||||
code: key.length === 1 ? `Key${key.toUpperCase()}` : key,
|
||||
modifiers,
|
||||
...(text ? { text, unmodifiedText: text } : {}),
|
||||
};
|
||||
yield* expectAgentInput(tabId, { kind: "key", key, code: params.code });
|
||||
yield* send("Input.dispatchKeyEvent", { type: "keyDown", ...params });
|
||||
yield* send("Input.dispatchKeyEvent", { type: "keyUp", ...params });
|
||||
yield* sendCleanup("Emulation.setFocusEmulationEnabled", { enabled: false }).pipe(
|
||||
Effect.ignore,
|
||||
);
|
||||
if (previouslyFocused && previouslyFocused.id !== wc.id && !previouslyFocused.isDestroyed()) {
|
||||
yield* attempt(
|
||||
{
|
||||
operation: "automationPress.restoreFocusedWebContents",
|
||||
tabId,
|
||||
webContentsId: previouslyFocused.id,
|
||||
},
|
||||
() => previouslyFocused.focus(),
|
||||
).pipe(Effect.ignore);
|
||||
}
|
||||
});
|
||||
|
||||
// Focus the guest WebContents itself, not its containing BrowserWindow. This
|
||||
// activates native keyboard behavior for hidden/background previews without
|
||||
// changing which thread is mounted in the UI. Restore the previous renderer
|
||||
// after dispatch so automation never leaves the app's input focus behind.
|
||||
yield* Effect.gen(function* () {
|
||||
yield* attempt(
|
||||
{ operation: "automationPress.focusWebContents", tabId, webContentsId: wc.id },
|
||||
() => wc.focus(),
|
||||
);
|
||||
yield* send("Page.bringToFront");
|
||||
yield* send("Emulation.setFocusEmulationEnabled", { enabled: true });
|
||||
yield* expectAgentInput(tabId, keySequence.signal);
|
||||
keyDownAttempted = true;
|
||||
yield* send("Input.dispatchKeyEvent", keySequence.keyDown);
|
||||
}).pipe(Effect.ensuring(releaseInput));
|
||||
});
|
||||
|
||||
const automationPress = Effect.fn("PreviewManager.automationPress")(function* (
|
||||
@@ -2130,8 +2277,8 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
input: PreviewAutomationPressInput,
|
||||
) {
|
||||
const wc = yield* requireWebContents(tabId);
|
||||
yield* withControlSession(tabId, wc, "press", (send) =>
|
||||
performAutomationPress(tabId, input, send),
|
||||
yield* withControlSession(tabId, wc, "press", (send, sendCleanup) =>
|
||||
performAutomationPress(tabId, wc, input, send, sendCleanup),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -2529,6 +2676,20 @@ export class PreviewAutomationTargetNotFoundError extends Schema.TaggedErrorClas
|
||||
}
|
||||
}
|
||||
|
||||
export class PreviewAutomationTargetNotEditableError extends Schema.TaggedErrorClass<PreviewAutomationTargetNotEditableError>()(
|
||||
"PreviewAutomationTargetNotEditableError",
|
||||
{
|
||||
tabId: Schema.String,
|
||||
selectorKind: PreviewAutomationSelectorKind,
|
||||
selectorLength: Schema.optionalKey(Schema.Number),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
const target = previewAutomationTargetLabel(this.selectorKind, this.selectorLength);
|
||||
return `Preview automation type found ${target}, but it is not editable in tab ${this.tabId}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class PreviewAutomationCoordinatesOutsideViewportError extends Schema.TaggedErrorClass<PreviewAutomationCoordinatesOutsideViewportError>()(
|
||||
"PreviewAutomationCoordinatesOutsideViewportError",
|
||||
{
|
||||
@@ -2631,6 +2792,7 @@ export const PreviewManagerError = Schema.Union([
|
||||
PreviewAutomationDebuggerAttachedError,
|
||||
PreviewAutomationEvaluationError,
|
||||
PreviewAutomationTargetNotFoundError,
|
||||
PreviewAutomationTargetNotEditableError,
|
||||
PreviewAutomationCoordinatesOutsideViewportError,
|
||||
PreviewAutomationInvalidSelectorError,
|
||||
PreviewAutomationResultTooLargeError,
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { makePreviewAutomationKeySequence } from "./PreviewKeyboard.ts";
|
||||
|
||||
describe("preview keyboard packets", () => {
|
||||
it("includes the Chromium virtual key code and Enter text", () => {
|
||||
expect(makePreviewAutomationKeySequence({ key: "Enter" })).toEqual({
|
||||
keyDown: {
|
||||
type: "keyDown",
|
||||
key: "Enter",
|
||||
code: "Enter",
|
||||
modifiers: 0,
|
||||
windowsVirtualKeyCode: 13,
|
||||
location: 0,
|
||||
isKeypad: false,
|
||||
text: "\r",
|
||||
unmodifiedText: "\r",
|
||||
},
|
||||
keyUp: {
|
||||
type: "keyUp",
|
||||
key: "Enter",
|
||||
code: "Enter",
|
||||
modifiers: 0,
|
||||
windowsVirtualKeyCode: 13,
|
||||
location: 0,
|
||||
isKeypad: false,
|
||||
},
|
||||
signal: { kind: "key", key: "Enter", code: "Enter" },
|
||||
});
|
||||
});
|
||||
|
||||
it("dispatches printable keys as text key-down events", () => {
|
||||
const sequence = makePreviewAutomationKeySequence({ key: "z" });
|
||||
expect(sequence.keyDown).toMatchObject({
|
||||
type: "keyDown",
|
||||
key: "z",
|
||||
code: "KeyZ",
|
||||
windowsVirtualKeyCode: 90,
|
||||
text: "z",
|
||||
});
|
||||
expect(sequence.keyUp).not.toHaveProperty("text");
|
||||
});
|
||||
|
||||
it("suppresses text and uses raw key-down for shortcuts", () => {
|
||||
expect(
|
||||
makePreviewAutomationKeySequence({ key: "a", modifiers: ["Meta"] }, { isMac: true }).keyDown,
|
||||
).toEqual({
|
||||
type: "rawKeyDown",
|
||||
key: "a",
|
||||
code: "KeyA",
|
||||
modifiers: 4,
|
||||
windowsVirtualKeyCode: 65,
|
||||
location: 0,
|
||||
isKeypad: false,
|
||||
commands: ["selectAll"],
|
||||
});
|
||||
});
|
||||
|
||||
it("maps common macOS editing shortcuts without changing other platforms", () => {
|
||||
expect(
|
||||
makePreviewAutomationKeySequence({ key: "z", modifiers: ["Shift", "Meta"] }, { isMac: true })
|
||||
.keyDown.commands,
|
||||
).toEqual(["redo"]);
|
||||
expect(
|
||||
makePreviewAutomationKeySequence({ key: "a", modifiers: ["Meta"] }).keyDown,
|
||||
).not.toHaveProperty("commands");
|
||||
});
|
||||
|
||||
it("resolves shifted printable keys to their browser values", () => {
|
||||
const sequence = makePreviewAutomationKeySequence({ key: "1", modifiers: ["Shift"] });
|
||||
expect(sequence.keyDown).toMatchObject({
|
||||
key: "!",
|
||||
code: "Digit1",
|
||||
modifiers: 8,
|
||||
windowsVirtualKeyCode: 49,
|
||||
text: "!",
|
||||
});
|
||||
expect(sequence.signal).toEqual({ kind: "key", key: "!", code: "Digit1" });
|
||||
});
|
||||
|
||||
it("keeps shifted key values while suppressing text for modified chords", () => {
|
||||
const sequence = makePreviewAutomationKeySequence({
|
||||
key: "1",
|
||||
modifiers: ["Control", "Shift"],
|
||||
});
|
||||
expect(sequence.keyDown).toEqual({
|
||||
type: "rawKeyDown",
|
||||
key: "!",
|
||||
code: "Digit1",
|
||||
modifiers: 10,
|
||||
windowsVirtualKeyCode: 49,
|
||||
location: 0,
|
||||
isKeypad: false,
|
||||
});
|
||||
expect(sequence.signal).toEqual({ kind: "key", key: "!", code: "Digit1" });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,203 @@
|
||||
import type { PreviewAutomationPressInput } from "@t3tools/contracts";
|
||||
|
||||
interface KeyDefinition {
|
||||
readonly code: string;
|
||||
readonly key: string;
|
||||
readonly keyCode: number;
|
||||
readonly text?: string;
|
||||
readonly location?: number;
|
||||
readonly shiftedKey?: string;
|
||||
}
|
||||
|
||||
export interface PreviewAutomationKeyEvent {
|
||||
readonly [key: string]: unknown;
|
||||
readonly type: "keyDown" | "rawKeyDown" | "keyUp";
|
||||
readonly key: string;
|
||||
readonly code: string;
|
||||
readonly modifiers: number;
|
||||
readonly windowsVirtualKeyCode: number;
|
||||
readonly location: number;
|
||||
readonly isKeypad: boolean;
|
||||
readonly text?: string;
|
||||
readonly unmodifiedText?: string;
|
||||
readonly commands?: ReadonlyArray<string>;
|
||||
}
|
||||
|
||||
export interface PreviewAutomationKeySequence {
|
||||
readonly keyDown: PreviewAutomationKeyEvent;
|
||||
readonly keyUp: PreviewAutomationKeyEvent;
|
||||
readonly signal: {
|
||||
readonly kind: "key";
|
||||
readonly key: string;
|
||||
readonly code: string;
|
||||
};
|
||||
}
|
||||
|
||||
const NAMED_KEYS: Readonly<Record<string, KeyDefinition>> = {
|
||||
Escape: { code: "Escape", key: "Escape", keyCode: 27 },
|
||||
Backspace: { code: "Backspace", key: "Backspace", keyCode: 8 },
|
||||
Tab: { code: "Tab", key: "Tab", keyCode: 9 },
|
||||
Enter: { code: "Enter", key: "Enter", keyCode: 13, text: "\r" },
|
||||
Shift: { code: "ShiftLeft", key: "Shift", keyCode: 16, location: 1 },
|
||||
Control: { code: "ControlLeft", key: "Control", keyCode: 17, location: 1 },
|
||||
Alt: { code: "AltLeft", key: "Alt", keyCode: 18, location: 1 },
|
||||
Meta: { code: "MetaLeft", key: "Meta", keyCode: 91, location: 1 },
|
||||
CapsLock: { code: "CapsLock", key: "CapsLock", keyCode: 20 },
|
||||
Space: { code: "Space", key: " ", keyCode: 32, text: " " },
|
||||
PageUp: { code: "PageUp", key: "PageUp", keyCode: 33 },
|
||||
PageDown: { code: "PageDown", key: "PageDown", keyCode: 34 },
|
||||
End: { code: "End", key: "End", keyCode: 35 },
|
||||
Home: { code: "Home", key: "Home", keyCode: 36 },
|
||||
ArrowLeft: { code: "ArrowLeft", key: "ArrowLeft", keyCode: 37 },
|
||||
ArrowUp: { code: "ArrowUp", key: "ArrowUp", keyCode: 38 },
|
||||
ArrowRight: { code: "ArrowRight", key: "ArrowRight", keyCode: 39 },
|
||||
ArrowDown: { code: "ArrowDown", key: "ArrowDown", keyCode: 40 },
|
||||
Insert: { code: "Insert", key: "Insert", keyCode: 45 },
|
||||
Delete: { code: "Delete", key: "Delete", keyCode: 46 },
|
||||
};
|
||||
|
||||
const PRINTABLE_KEYS: ReadonlyArray<KeyDefinition> = [
|
||||
{ code: "Backquote", key: "`", shiftedKey: "~", keyCode: 192 },
|
||||
{ code: "Digit1", key: "1", shiftedKey: "!", keyCode: 49 },
|
||||
{ code: "Digit2", key: "2", shiftedKey: "@", keyCode: 50 },
|
||||
{ code: "Digit3", key: "3", shiftedKey: "#", keyCode: 51 },
|
||||
{ code: "Digit4", key: "4", shiftedKey: "$", keyCode: 52 },
|
||||
{ code: "Digit5", key: "5", shiftedKey: "%", keyCode: 53 },
|
||||
{ code: "Digit6", key: "6", shiftedKey: "^", keyCode: 54 },
|
||||
{ code: "Digit7", key: "7", shiftedKey: "&", keyCode: 55 },
|
||||
{ code: "Digit8", key: "8", shiftedKey: "*", keyCode: 56 },
|
||||
{ code: "Digit9", key: "9", shiftedKey: "(", keyCode: 57 },
|
||||
{ code: "Digit0", key: "0", shiftedKey: ")", keyCode: 48 },
|
||||
{ code: "Minus", key: "-", shiftedKey: "_", keyCode: 189 },
|
||||
{ code: "Equal", key: "=", shiftedKey: "+", keyCode: 187 },
|
||||
{ code: "Backslash", key: "\\", shiftedKey: "|", keyCode: 220 },
|
||||
{ code: "BracketLeft", key: "[", shiftedKey: "{", keyCode: 219 },
|
||||
{ code: "BracketRight", key: "]", shiftedKey: "}", keyCode: 221 },
|
||||
{ code: "Semicolon", key: ";", shiftedKey: ":", keyCode: 186 },
|
||||
{ code: "Quote", key: "'", shiftedKey: '"', keyCode: 222 },
|
||||
{ code: "Comma", key: ",", shiftedKey: "<", keyCode: 188 },
|
||||
{ code: "Period", key: ".", shiftedKey: ">", keyCode: 190 },
|
||||
{ code: "Slash", key: "/", shiftedKey: "?", keyCode: 191 },
|
||||
];
|
||||
|
||||
/**
|
||||
* Chromium does not infer macOS editing commands from synthetic Meta chords.
|
||||
* Keep the common browser editing/navigation shortcuts explicit so dispatched
|
||||
* key events behave like their physical-key equivalents.
|
||||
*/
|
||||
const MAC_EDITING_COMMANDS: Readonly<Record<string, string>> = {
|
||||
"Meta+Backspace": "deleteToBeginningOfLine",
|
||||
"Meta+ArrowUp": "moveToBeginningOfDocument",
|
||||
"Meta+ArrowDown": "moveToEndOfDocument",
|
||||
"Meta+ArrowLeft": "moveToLeftEndOfLine",
|
||||
"Meta+ArrowRight": "moveToRightEndOfLine",
|
||||
"Shift+Meta+ArrowUp": "moveToBeginningOfDocumentAndModifySelection",
|
||||
"Shift+Meta+ArrowDown": "moveToEndOfDocumentAndModifySelection",
|
||||
"Shift+Meta+ArrowLeft": "moveToLeftEndOfLineAndModifySelection",
|
||||
"Shift+Meta+ArrowRight": "moveToRightEndOfLineAndModifySelection",
|
||||
"Meta+KeyA": "selectAll",
|
||||
"Meta+KeyC": "copy",
|
||||
"Meta+KeyX": "cut",
|
||||
"Meta+KeyV": "paste",
|
||||
"Meta+KeyZ": "undo",
|
||||
"Shift+Meta+KeyZ": "redo",
|
||||
};
|
||||
const SHORTCUT_MODIFIER_ORDER = ["Shift", "Control", "Alt", "Meta"] as const;
|
||||
|
||||
const macEditingCommands = (
|
||||
code: string,
|
||||
modifiers: PreviewAutomationPressInput["modifiers"],
|
||||
): ReadonlyArray<string> => {
|
||||
const shortcut = [
|
||||
...SHORTCUT_MODIFIER_ORDER.filter((modifier) => modifiers?.includes(modifier)),
|
||||
code,
|
||||
].join("+");
|
||||
const command = MAC_EDITING_COMMANDS[shortcut];
|
||||
return command ? [command] : [];
|
||||
};
|
||||
|
||||
const modifierMask = (modifiers: PreviewAutomationPressInput["modifiers"]): number =>
|
||||
(modifiers ?? []).reduce((value, modifier) => {
|
||||
switch (modifier) {
|
||||
case "Alt":
|
||||
return value | 1;
|
||||
case "Control":
|
||||
return value | 2;
|
||||
case "Meta":
|
||||
return value | 4;
|
||||
case "Shift":
|
||||
return value | 8;
|
||||
}
|
||||
}, 0);
|
||||
|
||||
function resolveKeyDefinition(input: PreviewAutomationPressInput): KeyDefinition {
|
||||
const named = NAMED_KEYS[input.key];
|
||||
if (named) return named;
|
||||
|
||||
const functionKey = /^F([1-9]|1[0-2])$/.exec(input.key);
|
||||
if (functionKey) {
|
||||
const number = Number(functionKey[1]);
|
||||
return { code: input.key, key: input.key, keyCode: 111 + number };
|
||||
}
|
||||
|
||||
if (/^[a-z]$/i.test(input.key)) {
|
||||
const upper = input.key.toUpperCase();
|
||||
const shifted = input.modifiers?.includes("Shift") ?? false;
|
||||
const key = shifted || input.key === upper ? upper : input.key;
|
||||
return { code: `Key${upper}`, key, keyCode: upper.charCodeAt(0), text: key };
|
||||
}
|
||||
|
||||
const printable = PRINTABLE_KEYS.find(
|
||||
(definition) => definition.key === input.key || definition.shiftedKey === input.key,
|
||||
);
|
||||
if (printable) {
|
||||
const shifted = input.modifiers?.includes("Shift") ?? false;
|
||||
const key =
|
||||
printable.shiftedKey && (shifted || input.key === printable.shiftedKey)
|
||||
? printable.shiftedKey
|
||||
: printable.key;
|
||||
return { ...printable, key, text: key };
|
||||
}
|
||||
|
||||
return {
|
||||
code: input.key.length > 1 ? input.key : "",
|
||||
key: input.key,
|
||||
keyCode: 0,
|
||||
...(input.key.length === 1 ? { text: input.key } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Build Chromium CDP key packets using the same required fields and down-event
|
||||
* choice as Playwright's pinned Chromium keyboard implementation.
|
||||
*/
|
||||
export function makePreviewAutomationKeySequence(
|
||||
input: PreviewAutomationPressInput,
|
||||
options?: { readonly isMac?: boolean },
|
||||
): PreviewAutomationKeySequence {
|
||||
const definition = resolveKeyDefinition(input);
|
||||
const modifiers = modifierMask(input.modifiers);
|
||||
const suppressText = input.modifiers?.some((modifier) => modifier !== "Shift") ?? false;
|
||||
const text = suppressText ? "" : (definition.text ?? "");
|
||||
const location = definition.location ?? 0;
|
||||
const commands = options?.isMac ? macEditingCommands(definition.code, input.modifiers) : [];
|
||||
const shared = {
|
||||
key: definition.key,
|
||||
code: definition.code,
|
||||
modifiers,
|
||||
windowsVirtualKeyCode: definition.keyCode,
|
||||
location,
|
||||
isKeypad: location === 3,
|
||||
};
|
||||
|
||||
return {
|
||||
keyDown: {
|
||||
type: text ? "keyDown" : "rawKeyDown",
|
||||
...shared,
|
||||
...(text ? { text, unmodifiedText: text } : {}),
|
||||
...(commands.length > 0 ? { commands } : {}),
|
||||
},
|
||||
keyUp: { type: "keyUp", ...shared },
|
||||
signal: { kind: "key", key: definition.key, code: definition.code },
|
||||
};
|
||||
}
|
||||
@@ -18,7 +18,6 @@ const clientSettings: ClientSettings = {
|
||||
confirmThreadDelete: false,
|
||||
dismissedProviderUpdateNotificationKeys: [],
|
||||
diffIgnoreWhitespace: true,
|
||||
diffWordWrap: true,
|
||||
favorites: [],
|
||||
providerModelPreferences: {},
|
||||
sidebarProjectGroupingMode: "repository_path",
|
||||
@@ -29,6 +28,7 @@ const clientSettings: ClientSettings = {
|
||||
sidebarThreadSortOrder: "created_at",
|
||||
sidebarThreadPreviewCount: 6,
|
||||
timestampFormat: "24-hour",
|
||||
wordWrap: true,
|
||||
};
|
||||
|
||||
const decodeClientSettingsJson = Schema.decodeEffect(Schema.fromJsonString(ClientSettingsSchema));
|
||||
|
||||
@@ -4,6 +4,7 @@ import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
|
||||
import type * as Electron from "electron";
|
||||
import { vi } from "vite-plus/test";
|
||||
@@ -47,12 +48,14 @@ function makeFakeBrowserWindow() {
|
||||
const webContentsListeners = new Map<string, (...args: readonly unknown[]) => void>();
|
||||
const webContents = {
|
||||
copyImageAt: vi.fn(),
|
||||
getURL: vi.fn(() => "t3code-dev://app/"),
|
||||
isLoadingMainFrame: vi.fn(() => false),
|
||||
on: vi.fn((eventName: string, listener: (...args: readonly unknown[]) => void) => {
|
||||
webContentsListeners.set(eventName, listener);
|
||||
}),
|
||||
once: vi.fn(),
|
||||
openDevTools: vi.fn(),
|
||||
reload: vi.fn(),
|
||||
replaceMisspelling: vi.fn(),
|
||||
send: vi.fn(),
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
@@ -79,6 +82,7 @@ function makeFakeBrowserWindow() {
|
||||
window: window as unknown as Electron.BrowserWindow,
|
||||
loadURL: window.loadURL,
|
||||
openDevTools: webContents.openDevTools,
|
||||
reload: webContents.reload,
|
||||
setAutoHideCursor: window.setAutoHideCursor,
|
||||
webContentsListeners,
|
||||
};
|
||||
@@ -237,6 +241,73 @@ describe("DesktopWindow", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("recovers when the development renderer is temporarily unreachable", () =>
|
||||
Effect.gen(function* () {
|
||||
const fakeWindow = makeFakeBrowserWindow();
|
||||
const createCount = yield* Ref.make(0);
|
||||
const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
|
||||
const layer = makeTestLayer({
|
||||
window: fakeWindow.window,
|
||||
createCount,
|
||||
mainWindow,
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const desktopWindow = yield* DesktopWindow.DesktopWindow;
|
||||
yield* desktopWindow.handleBackendReady;
|
||||
|
||||
const didFailLoad = fakeWindow.webContentsListeners.get("did-fail-load");
|
||||
const didFinishLoad = fakeWindow.webContentsListeners.get("did-finish-load");
|
||||
if (!didFailLoad || !didFinishLoad) {
|
||||
return yield* Effect.die("renderer load listeners were not registered");
|
||||
}
|
||||
|
||||
didFailLoad({}, -9, "ERR_UNEXPECTED", "t3code-dev://app/", true);
|
||||
assert.equal(fakeWindow.loadURL.mock.calls.length, 1);
|
||||
|
||||
yield* TestClock.adjust(100);
|
||||
assert.deepEqual(fakeWindow.loadURL.mock.calls, [
|
||||
["t3code-dev://app/"],
|
||||
["t3code-dev://app/"],
|
||||
]);
|
||||
assert.equal(fakeWindow.reload.mock.calls.length, 0);
|
||||
|
||||
didFailLoad({}, -9, "ERR_UNEXPECTED", "t3code-dev://app/", true);
|
||||
didFinishLoad();
|
||||
yield* TestClock.adjust(250);
|
||||
assert.equal(fakeWindow.loadURL.mock.calls.length, 2);
|
||||
assert.equal(fakeWindow.reload.mock.calls.length, 0);
|
||||
}).pipe(Effect.provide(layer));
|
||||
}),
|
||||
);
|
||||
|
||||
it("retries only transient failures for the development renderer", () => {
|
||||
assert.isTrue(
|
||||
DesktopWindow.isRetryableDevelopmentRendererLoadFailure({
|
||||
applicationUrl: "t3code-dev://app/",
|
||||
errorCode: -102,
|
||||
isMainFrame: true,
|
||||
validatedUrl: "t3code-dev://app/",
|
||||
}),
|
||||
);
|
||||
assert.isFalse(
|
||||
DesktopWindow.isRetryableDevelopmentRendererLoadFailure({
|
||||
applicationUrl: "t3code-dev://app/",
|
||||
errorCode: -3,
|
||||
isMainFrame: true,
|
||||
validatedUrl: "t3code-dev://app/",
|
||||
}),
|
||||
);
|
||||
assert.isFalse(
|
||||
DesktopWindow.isRetryableDevelopmentRendererLoadFailure({
|
||||
applicationUrl: "t3code-dev://app/",
|
||||
errorCode: -102,
|
||||
isMainFrame: true,
|
||||
validatedUrl: "https://example.com/",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("opens safe off-origin renderer navigations in the system browser", () =>
|
||||
Effect.gen(function* () {
|
||||
const fakeWindow = makeFakeBrowserWindow();
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
@@ -22,6 +23,16 @@ const TITLEBAR_HEIGHT = 40;
|
||||
const TITLEBAR_COLOR = "#01000000"; // #00000000 does not work correctly on Linux
|
||||
const TITLEBAR_LIGHT_SYMBOL_COLOR = "#1f2937";
|
||||
const TITLEBAR_DARK_SYMBOL_COLOR = "#f8fafc";
|
||||
const DEVELOPMENT_LOAD_RETRY_DELAYS_MS = [100, 250, 500, 1_000, 2_000] as const;
|
||||
const DEVELOPMENT_RETRYABLE_LOAD_ERROR_CODES = new Set([
|
||||
-2, // ERR_FAILED
|
||||
-7, // ERR_TIMED_OUT
|
||||
-9, // ERR_UNEXPECTED (custom protocol handler rejected)
|
||||
-102, // ERR_CONNECTION_REFUSED
|
||||
-105, // ERR_NAME_NOT_RESOLVED
|
||||
-106, // ERR_INTERNET_DISCONNECTED
|
||||
-118, // ERR_CONNECTION_TIMED_OUT
|
||||
]);
|
||||
|
||||
type WindowTitleBarOptions = Pick<
|
||||
Electron.BrowserWindowConstructorOptions,
|
||||
@@ -86,6 +97,22 @@ export function isSameOriginRendererNavigation(input: {
|
||||
}
|
||||
}
|
||||
|
||||
export function isRetryableDevelopmentRendererLoadFailure(input: {
|
||||
readonly applicationUrl: string;
|
||||
readonly errorCode: number;
|
||||
readonly isMainFrame: boolean;
|
||||
readonly validatedUrl: string;
|
||||
}): boolean {
|
||||
return (
|
||||
input.isMainFrame &&
|
||||
DEVELOPMENT_RETRYABLE_LOAD_ERROR_CODES.has(input.errorCode) &&
|
||||
isSameOriginRendererNavigation({
|
||||
applicationUrl: input.applicationUrl,
|
||||
navigationUrl: input.validatedUrl,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
function getWindowTitleBarOptions(
|
||||
shouldUseDarkColors: boolean,
|
||||
platform: NodeJS.Platform,
|
||||
@@ -152,6 +179,7 @@ export const make = Effect.gen(function* () {
|
||||
const previewManager = yield* PreviewManager.PreviewManager;
|
||||
const state = yield* DesktopState.DesktopState;
|
||||
const context = yield* Effect.context<DesktopWindowRuntimeServices>();
|
||||
const runFork = Effect.runForkWith(context);
|
||||
const runPromise = Effect.runPromiseWith(context);
|
||||
|
||||
const createWindow = Effect.fn("desktop.window.createWindow")(function* (): Effect.fn.Return<
|
||||
@@ -277,7 +305,61 @@ export const make = Effect.gen(function* () {
|
||||
event.preventDefault();
|
||||
window.setTitle(environment.displayName);
|
||||
});
|
||||
|
||||
let developmentLoadRetryIndex = 0;
|
||||
let developmentLoadRetryFiber: Fiber.Fiber<void, never> | undefined;
|
||||
const clearDevelopmentLoadRetry = () => {
|
||||
if (developmentLoadRetryFiber === undefined) {
|
||||
return;
|
||||
}
|
||||
const retryFiber = developmentLoadRetryFiber;
|
||||
developmentLoadRetryFiber = undefined;
|
||||
runFork(Fiber.interrupt(retryFiber));
|
||||
};
|
||||
const loadApplication = () => {
|
||||
if (window.isDestroyed()) {
|
||||
return;
|
||||
}
|
||||
void window.loadURL(applicationUrl).catch(() => undefined);
|
||||
};
|
||||
const scheduleDevelopmentLoadRetry = () => {
|
||||
if (developmentLoadRetryFiber !== undefined || window.isDestroyed()) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const retryIndex = Math.min(
|
||||
developmentLoadRetryIndex,
|
||||
DEVELOPMENT_LOAD_RETRY_DELAYS_MS.length - 1,
|
||||
);
|
||||
const retryInMs = DEVELOPMENT_LOAD_RETRY_DELAYS_MS[retryIndex] ?? 2_000;
|
||||
developmentLoadRetryIndex += 1;
|
||||
developmentLoadRetryFiber = runFork(
|
||||
Effect.sleep(retryInMs).pipe(
|
||||
Effect.andThen(
|
||||
Effect.sync(() => {
|
||||
developmentLoadRetryFiber = undefined;
|
||||
if (!window.isDestroyed()) {
|
||||
loadApplication();
|
||||
}
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
return retryInMs;
|
||||
};
|
||||
|
||||
window.webContents.on("did-finish-load", () => {
|
||||
if (
|
||||
environment.isDevelopment &&
|
||||
!isSameOriginRendererNavigation({
|
||||
applicationUrl,
|
||||
navigationUrl: window.webContents.getURL(),
|
||||
})
|
||||
) {
|
||||
return;
|
||||
}
|
||||
clearDevelopmentLoadRetry();
|
||||
developmentLoadRetryIndex = 0;
|
||||
window.setTitle(environment.displayName);
|
||||
});
|
||||
window.webContents.on(
|
||||
@@ -286,11 +368,22 @@ export const make = Effect.gen(function* () {
|
||||
if (!isMainFrame) {
|
||||
return;
|
||||
}
|
||||
const retryInMs =
|
||||
environment.isDevelopment &&
|
||||
isRetryableDevelopmentRendererLoadFailure({
|
||||
applicationUrl,
|
||||
errorCode,
|
||||
isMainFrame,
|
||||
validatedUrl: validatedURL,
|
||||
})
|
||||
? scheduleDevelopmentLoadRetry()
|
||||
: undefined;
|
||||
void runPromise(
|
||||
logWindowWarning("main window failed to load", {
|
||||
errorCode,
|
||||
errorDescription,
|
||||
url: validatedURL,
|
||||
...(retryInMs === undefined ? {} : { retryInMs }),
|
||||
}),
|
||||
);
|
||||
},
|
||||
@@ -312,14 +405,13 @@ export const make = Effect.gen(function* () {
|
||||
void runPromise(electronWindow.reveal(window));
|
||||
});
|
||||
|
||||
loadApplication();
|
||||
if (environment.isDevelopment) {
|
||||
void window.loadURL(applicationUrl);
|
||||
window.webContents.openDevTools({ mode: "detach" });
|
||||
} else {
|
||||
void window.loadURL(applicationUrl);
|
||||
}
|
||||
|
||||
window.on("closed", () => {
|
||||
clearDevelopmentLoadRetry();
|
||||
void runPromise(electronWindow.clearMain(Option.some(window)));
|
||||
});
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
"typecheck": "astro check"
|
||||
},
|
||||
"dependencies": {
|
||||
"astro": "^6.0.4"
|
||||
"astro": "^7.0.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@astrojs/check": "^0.9.7",
|
||||
|
||||
@@ -44,7 +44,7 @@
|
||||
"@effect/atom-react": "catalog:",
|
||||
"@expo-google-fonts/dm-sans": "^0.4.2",
|
||||
"@expo/ui": "~56.0.8",
|
||||
"@legendapp/list": "3.0.0-beta.44",
|
||||
"@legendapp/list": "3.2.0",
|
||||
"@noble/curves": "catalog:",
|
||||
"@noble/hashes": "catalog:",
|
||||
"@pierre/diffs": "catalog:",
|
||||
@@ -93,9 +93,9 @@
|
||||
"react-native": "0.85.3",
|
||||
"react-native-gesture-handler": "~2.31.1",
|
||||
"react-native-image-viewing": "^0.2.2",
|
||||
"react-native-keyboard-controller": "1.21.6",
|
||||
"react-native-keyboard-controller": "1.21.7",
|
||||
"react-native-nitro-markdown": "^0.5.0",
|
||||
"react-native-nitro-modules": "^0.35.4",
|
||||
"react-native-nitro-modules": "0.35.9",
|
||||
"react-native-reanimated": "4.3.1",
|
||||
"react-native-safe-area-context": "~5.7.0",
|
||||
"react-native-screens": "4.25.2",
|
||||
|
||||
@@ -18,8 +18,7 @@ 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.`,
|
||||
cause,
|
||||
detail: `Could not ${operation} the local connection catalog: ${String(cause)}`,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -58,8 +58,23 @@ const LegacyStoredShellSnapshot = Schema.Struct({
|
||||
function catalogError(operation: string, cause: unknown) {
|
||||
return new ConnectionTransientError({
|
||||
reason: "remote-unavailable",
|
||||
detail: `Could not ${operation} the local connection catalog.`,
|
||||
cause,
|
||||
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)}`,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -85,7 +100,7 @@ const threadSnapshotDirectory = Effect.fn("mobile.connectionStorage.threadSnapsh
|
||||
}
|
||||
return directory;
|
||||
},
|
||||
catch: (cause) => new ConnectionPersistenceError({ operation, cause }),
|
||||
catch: (cause) => shellPersistenceError(operation, cause),
|
||||
});
|
||||
},
|
||||
);
|
||||
@@ -102,6 +117,16 @@ 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({
|
||||
@@ -138,7 +163,7 @@ const shellSnapshotFileInDirectory = Effect.fn(
|
||||
directory.create({ idempotent: true, intermediates: true });
|
||||
return new File(directory, shellSnapshotFileName(environmentId));
|
||||
},
|
||||
catch: (cause) => new ConnectionPersistenceError({ operation, cause }),
|
||||
catch: (cause) => shellPersistenceError(operation, cause),
|
||||
});
|
||||
});
|
||||
|
||||
@@ -159,29 +184,18 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
const targetStore = ConnectionTargetStore.of({
|
||||
list: catalog.read.pipe(
|
||||
Effect.map((document) => document.targets),
|
||||
Effect.mapError(
|
||||
(cause) => new ConnectionPersistenceError({ operation: "list-targets", cause }),
|
||||
),
|
||||
Effect.mapError((error) => targetPersistenceError("list-targets", error)),
|
||||
),
|
||||
});
|
||||
const registrationStore = ConnectionRegistrationStore.of({
|
||||
register: (registration) =>
|
||||
catalog
|
||||
.update((document) => registerConnectionInCatalog(document, registration))
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ConnectionPersistenceError({ operation: "register-connection", cause }),
|
||||
),
|
||||
),
|
||||
.pipe(Effect.mapError((error) => targetPersistenceError("register-connection", error))),
|
||||
remove: (target) =>
|
||||
catalog
|
||||
.update((document) => removeConnectionFromCatalog(document, target))
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new ConnectionPersistenceError({ operation: "remove-connection", cause }),
|
||||
),
|
||||
),
|
||||
.pipe(Effect.mapError((error) => targetPersistenceError("remove-connection", error))),
|
||||
});
|
||||
const profileStore = ProfileStore.make({
|
||||
get: (connectionId) =>
|
||||
@@ -269,19 +283,15 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
if (file.exists) {
|
||||
const raw = yield* Effect.tryPromise({
|
||||
try: () => file.text(),
|
||||
catch: (cause) => new ConnectionPersistenceError({ operation: "load-shell", cause }),
|
||||
catch: (cause) => shellPersistenceError("load-shell", cause),
|
||||
});
|
||||
const parsed = yield* Effect.try({
|
||||
try: () => JSON.parse(raw) as unknown,
|
||||
catch: (cause) => new ConnectionPersistenceError({ operation: "load-shell", cause }),
|
||||
catch: (cause) => shellPersistenceError("load-shell", cause),
|
||||
});
|
||||
const stored = yield* Effect.fromResult(
|
||||
Schema.decodeUnknownResult(StoredShellSnapshot)(parsed),
|
||||
).pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new ConnectionPersistenceError({ operation: "load-shell", cause }),
|
||||
),
|
||||
);
|
||||
).pipe(Effect.mapError((cause) => shellPersistenceError("load-shell", cause)));
|
||||
return stored.environmentId === environmentId
|
||||
? Option.some(stored.snapshot)
|
||||
: Option.none();
|
||||
@@ -293,19 +303,15 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
}
|
||||
const legacyRaw = yield* Effect.tryPromise({
|
||||
try: () => legacyFile.text(),
|
||||
catch: (cause) => new ConnectionPersistenceError({ operation: "load-shell", cause }),
|
||||
catch: (cause) => shellPersistenceError("load-shell", cause),
|
||||
});
|
||||
const legacyParsed = yield* Effect.try({
|
||||
try: () => JSON.parse(legacyRaw) as unknown,
|
||||
catch: (cause) => new ConnectionPersistenceError({ operation: "load-shell", cause }),
|
||||
catch: (cause) => shellPersistenceError("load-shell", cause),
|
||||
});
|
||||
const legacyStored = yield* Effect.fromResult(
|
||||
Schema.decodeUnknownResult(LegacyStoredShellSnapshot)(legacyParsed),
|
||||
).pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new ConnectionPersistenceError({ operation: "load-shell", cause }),
|
||||
),
|
||||
);
|
||||
).pipe(Effect.mapError((cause) => shellPersistenceError("load-shell", cause)));
|
||||
return legacyStored.environmentId === environmentId
|
||||
? Option.some(legacyStored.snapshot)
|
||||
: Option.none();
|
||||
@@ -320,11 +326,7 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
} as const;
|
||||
const encoded = yield* Effect.fromResult(
|
||||
Schema.encodeUnknownResult(StoredShellSnapshot)(stored),
|
||||
).pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new ConnectionPersistenceError({ operation: "save-shell", cause }),
|
||||
),
|
||||
);
|
||||
).pipe(Effect.mapError((cause) => shellPersistenceError("save-shell", cause)));
|
||||
yield* Effect.try({
|
||||
try: () => {
|
||||
if (!file.exists) {
|
||||
@@ -332,7 +334,7 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
}
|
||||
file.write(JSON.stringify(encoded));
|
||||
},
|
||||
catch: (cause) => new ConnectionPersistenceError({ operation: "save-shell", cause }),
|
||||
catch: (cause) => shellPersistenceError("save-shell", cause),
|
||||
});
|
||||
}),
|
||||
loadThread: (environmentId, threadId) =>
|
||||
@@ -343,19 +345,15 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
}
|
||||
const raw = yield* Effect.tryPromise({
|
||||
try: () => file.text(),
|
||||
catch: (cause) => new ConnectionPersistenceError({ operation: "load-thread", cause }),
|
||||
catch: (cause) => shellPersistenceError("load-thread", cause),
|
||||
});
|
||||
const parsed = yield* Effect.try({
|
||||
try: () => JSON.parse(raw) as unknown,
|
||||
catch: (cause) => new ConnectionPersistenceError({ operation: "load-thread", cause }),
|
||||
catch: (cause) => shellPersistenceError("load-thread", cause),
|
||||
});
|
||||
const stored = yield* Effect.fromResult(
|
||||
Schema.decodeUnknownResult(StoredThreadSnapshot)(parsed),
|
||||
).pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new ConnectionPersistenceError({ operation: "load-thread", cause }),
|
||||
),
|
||||
);
|
||||
).pipe(Effect.mapError((cause) => shellPersistenceError("load-thread", cause)));
|
||||
return stored.environmentId === environmentId && stored.threadId === threadId
|
||||
? Option.some(stored.thread)
|
||||
: Option.none();
|
||||
@@ -370,11 +368,7 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
threadId: thread.id,
|
||||
thread,
|
||||
}),
|
||||
).pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new ConnectionPersistenceError({ operation: "save-thread", cause }),
|
||||
),
|
||||
);
|
||||
).pipe(Effect.mapError((cause) => shellPersistenceError("save-thread", cause)));
|
||||
yield* Effect.try({
|
||||
try: () => {
|
||||
if (!file.exists) {
|
||||
@@ -382,7 +376,7 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
}
|
||||
file.write(JSON.stringify(encoded));
|
||||
},
|
||||
catch: (cause) => new ConnectionPersistenceError({ operation: "save-thread", cause }),
|
||||
catch: (cause) => shellPersistenceError("save-thread", cause),
|
||||
});
|
||||
}),
|
||||
removeThread: (environmentId, threadId) =>
|
||||
@@ -395,7 +389,7 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
Effect.mapError((cause) =>
|
||||
cause._tag === "ConnectionPersistenceError"
|
||||
? cause
|
||||
: new ConnectionPersistenceError({ operation: "remove-thread", cause }),
|
||||
: shellPersistenceError("remove-thread", cause),
|
||||
),
|
||||
),
|
||||
clear: (environmentId) =>
|
||||
@@ -404,16 +398,14 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
if (file.exists) {
|
||||
yield* Effect.try({
|
||||
try: () => file.delete(),
|
||||
catch: (cause) =>
|
||||
new ConnectionPersistenceError({ operation: "clear-environment", cause }),
|
||||
catch: (cause) => shellPersistenceError("clear-environment", cause),
|
||||
});
|
||||
}
|
||||
const legacyFile = yield* legacyShellSnapshotFile(environmentId, "clear-environment");
|
||||
if (legacyFile.exists) {
|
||||
yield* Effect.try({
|
||||
try: () => legacyFile.delete(),
|
||||
catch: (cause) =>
|
||||
new ConnectionPersistenceError({ operation: "clear-environment", cause }),
|
||||
catch: (cause) => shellPersistenceError("clear-environment", cause),
|
||||
});
|
||||
}
|
||||
const threadDirectory = yield* threadSnapshotDirectory(
|
||||
@@ -423,8 +415,7 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
if (threadDirectory.exists) {
|
||||
yield* Effect.try({
|
||||
try: () => threadDirectory.delete(),
|
||||
catch: (cause) =>
|
||||
new ConnectionPersistenceError({ operation: "clear-environment", cause }),
|
||||
catch: (cause) => shellPersistenceError("clear-environment", cause),
|
||||
});
|
||||
}
|
||||
}),
|
||||
|
||||
@@ -30,7 +30,9 @@ import {
|
||||
resolveProviderOptionDescriptors,
|
||||
} from "../../lib/providerOptions";
|
||||
import { buildThreadRoutePath } from "../../lib/routes";
|
||||
import { scopedProjectKey } from "../../lib/scopedEntities";
|
||||
import { MOBILE_TYPOGRAPHY } from "../../lib/typography";
|
||||
import { getComposerDraftSnapshot } from "../../state/use-composer-drafts";
|
||||
import { useProjects } from "../../state/entities";
|
||||
import { branchBadgeLabel, useNewTaskFlow } from "./new-task-flow-provider";
|
||||
import { useCreateProjectThread } from "./use-project-actions";
|
||||
@@ -63,6 +65,7 @@ export function NewTaskDraftScreen(props: {
|
||||
const controlsBottomPadding = isKeyboardVisible ? 8 : Math.max(insets.bottom, 10);
|
||||
const { logicalProjects, selectedProject, setProject } = flow;
|
||||
const promptInputRef = useRef<ComposerEditorHandle>(null);
|
||||
const loadedBranchesProjectKeyRef = useRef<string | null>(null);
|
||||
|
||||
const borderColor = useThemeColor("--color-border");
|
||||
const sheetFadeOpaque = colorScheme === "dark" ? "rgba(14,14,14,0.98)" : "rgba(242,242,247,0.98)";
|
||||
@@ -78,6 +81,12 @@ export function NewTaskDraftScreen(props: {
|
||||
) ?? null;
|
||||
|
||||
if (directProject) {
|
||||
if (
|
||||
selectedProject?.environmentId === directProject.environmentId &&
|
||||
selectedProject.id === directProject.id
|
||||
) {
|
||||
return;
|
||||
}
|
||||
setProject(directProject);
|
||||
return;
|
||||
}
|
||||
@@ -105,10 +114,16 @@ export function NewTaskDraftScreen(props: {
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedProject) {
|
||||
loadedBranchesProjectKeyRef.current = null;
|
||||
return;
|
||||
}
|
||||
const projectKey = `${selectedProject.environmentId}:${selectedProject.id}`;
|
||||
if (loadedBranchesProjectKeyRef.current === projectKey) {
|
||||
return;
|
||||
}
|
||||
loadedBranchesProjectKeyRef.current = projectKey;
|
||||
void flow.loadBranches();
|
||||
}, [flow, selectedProject]);
|
||||
}, [flow.loadBranches, selectedProject]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedProject) {
|
||||
@@ -292,11 +307,7 @@ export function NewTaskDraftScreen(props: {
|
||||
if (!event.startsWith("model:")) {
|
||||
return;
|
||||
}
|
||||
// Defer state update so the native menu dismiss animation completes
|
||||
// before re-rendering the menu actions (prevents submenu jump).
|
||||
setTimeout(() => {
|
||||
flow.setSelectedModelKey(event.slice("model:".length));
|
||||
}, 150);
|
||||
flow.setSelectedModelKey(event.slice("model:".length));
|
||||
}
|
||||
|
||||
function handleEnvironmentMenuAction(event: string) {
|
||||
@@ -366,27 +377,42 @@ export function NewTaskDraftScreen(props: {
|
||||
);
|
||||
|
||||
async function handleStart(): Promise<void> {
|
||||
const selectedProject = flow.selectedProject;
|
||||
if (!selectedProject) {
|
||||
return;
|
||||
}
|
||||
const draft = getComposerDraftSnapshot(
|
||||
`new-task:${scopedProjectKey(selectedProject.environmentId, selectedProject.id)}`,
|
||||
);
|
||||
const modelSelection = draft.modelSelection ?? flow.selectedModel;
|
||||
const workspaceMode = draft.workspaceSelection?.mode ?? flow.workspaceMode;
|
||||
const selectedBranchName = draft.workspaceSelection?.branch ?? flow.selectedBranchName;
|
||||
const selectedWorktreePath =
|
||||
draft.workspaceSelection?.worktreePath ?? flow.selectedWorktreePath;
|
||||
const runtimeMode = draft.runtimeMode ?? flow.runtimeMode;
|
||||
const interactionMode = draft.interactionMode ?? flow.interactionMode;
|
||||
const initialMessageText = draft.text.trim();
|
||||
|
||||
if (
|
||||
!flow.selectedProject ||
|
||||
!flow.selectedModel ||
|
||||
flow.prompt.trim().length === 0 ||
|
||||
!modelSelection ||
|
||||
initialMessageText.length === 0 ||
|
||||
flow.submitting ||
|
||||
(flow.workspaceMode === "worktree" && !flow.selectedBranchName)
|
||||
(workspaceMode === "worktree" && !selectedBranchName)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
flow.setSubmitting(true);
|
||||
const result = await createProjectThread({
|
||||
project: flow.selectedProject,
|
||||
modelSelection: flow.selectedModel,
|
||||
envMode: flow.workspaceMode,
|
||||
branch: flow.selectedBranchName,
|
||||
worktreePath: flow.workspaceMode === "worktree" ? null : flow.selectedWorktreePath,
|
||||
runtimeMode: flow.runtimeMode,
|
||||
interactionMode: flow.interactionMode,
|
||||
initialMessageText: flow.prompt.trim(),
|
||||
initialAttachments: flow.attachments,
|
||||
project: selectedProject,
|
||||
modelSelection,
|
||||
envMode: workspaceMode,
|
||||
branch: selectedBranchName,
|
||||
worktreePath: workspaceMode === "worktree" ? null : selectedWorktreePath,
|
||||
runtimeMode,
|
||||
interactionMode,
|
||||
initialMessageText,
|
||||
initialAttachments: draft.attachments,
|
||||
});
|
||||
flow.setSubmitting(false);
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { isLiquidGlassSupported, LiquidGlassView } from "@callstack/liquid-glass";
|
||||
import type {
|
||||
EnvironmentId,
|
||||
MessageId,
|
||||
ModelSelection,
|
||||
OrchestrationThreadShell,
|
||||
ProviderInteractionMode,
|
||||
@@ -91,7 +92,7 @@ export interface ThreadComposerProps {
|
||||
readonly onNativePasteImages: (uris: ReadonlyArray<string>) => Promise<void>;
|
||||
readonly onRemoveDraftImage: (imageId: string) => void;
|
||||
readonly onStopThread: () => void;
|
||||
readonly onSendMessage: () => Promise<void>;
|
||||
readonly onSendMessage: () => Promise<MessageId | null>;
|
||||
readonly onUpdateModelSelection: (modelSelection: ModelSelection) => void;
|
||||
readonly onUpdateRuntimeMode: (runtimeMode: RuntimeMode) => void;
|
||||
readonly onUpdateInteractionMode: (interactionMode: ProviderInteractionMode) => void;
|
||||
@@ -447,9 +448,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
const { onChangeDraftMessage, onUpdateInteractionMode, draftMessage, onSendMessage } = props;
|
||||
|
||||
const handleSend = useCallback(() => {
|
||||
void onSendMessage().then(() => {
|
||||
inputRef.current?.blur();
|
||||
});
|
||||
void onSendMessage();
|
||||
}, [onSendMessage]);
|
||||
const handleCommandSelect = useCallback(
|
||||
(item: ComposerCommandItem) => {
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
import { type EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";
|
||||
import { useKeyboardChatComposerInset, useKeyboardScrollToEnd } from "@legendapp/list/keyboard";
|
||||
import type { LegendListRef } from "@legendapp/list/react-native";
|
||||
import type {
|
||||
ApprovalRequestId,
|
||||
EnvironmentId,
|
||||
MessageId,
|
||||
ModelSelection,
|
||||
OrchestrationThreadShell,
|
||||
ProviderApprovalDecision,
|
||||
@@ -13,8 +16,8 @@ import type {
|
||||
import { formatElapsed } from "@t3tools/shared/orchestrationTiming";
|
||||
import * as Haptics from "expo-haptics";
|
||||
import { useHeaderHeight } from "expo-router/build/react-navigation/elements";
|
||||
import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { View, type GestureResponderEvent, type LayoutChangeEvent } from "react-native";
|
||||
import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
|
||||
import { View, type GestureResponderEvent } from "react-native";
|
||||
import { Gesture, GestureDetector } from "react-native-gesture-handler";
|
||||
import { KeyboardStickyView } from "react-native-keyboard-controller";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
@@ -25,7 +28,7 @@ import type { ComposerEditorHandle } from "../../components/ComposerEditor";
|
||||
import type { StatusTone } from "../../components/StatusPill";
|
||||
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
|
||||
import type { LayoutVariant } from "../../lib/layout";
|
||||
import { resolveThreadFeedBottomInset } from "../../lib/threadFeedLayout";
|
||||
import { scopedThreadKey } from "../../lib/scopedEntities";
|
||||
import type {
|
||||
PendingApproval,
|
||||
PendingUserInput,
|
||||
@@ -73,7 +76,7 @@ export interface ThreadDetailScreenProps {
|
||||
readonly onNativePasteImages: (uris: ReadonlyArray<string>) => Promise<void>;
|
||||
readonly onRemoveDraftImage: (imageId: string) => void;
|
||||
readonly onStopThread: () => void;
|
||||
readonly onSendMessage: () => Promise<void>;
|
||||
readonly onSendMessage: () => Promise<MessageId | null>;
|
||||
readonly onReconnectEnvironment: () => void;
|
||||
readonly onUpdateThreadModelSelection: (modelSelection: ModelSelection) => void;
|
||||
readonly onUpdateThreadRuntimeMode: (runtimeMode: RuntimeMode) => void;
|
||||
@@ -206,25 +209,33 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
const insets = useSafeAreaInsets();
|
||||
const headerHeight = useHeaderHeight();
|
||||
const agentLabel = `${props.selectedThread.modelSelection.instanceId} agent`;
|
||||
const composerRef = useRef<ComposerEditorHandle>(null);
|
||||
const selectedThreadKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
|
||||
const composerEditorRef = useRef<ComposerEditorHandle>(null);
|
||||
const composerOverlayRef = useRef<View>(null);
|
||||
const listRef = useRef<LegendListRef>(null);
|
||||
const feedTouchStartRef = useRef<{ pageX: number; pageY: number } | null>(null);
|
||||
const selectedThreadKeyRef = useRef(selectedThreadKey);
|
||||
const lastScrolledAnchorMessageIdRef = useRef<MessageId | null>(null);
|
||||
const [composerExpanded, setComposerExpanded] = useState(false);
|
||||
const [anchorMessageId, setAnchorMessageId] = useState<MessageId | null>(null);
|
||||
const composerBottomInset = composerExpanded ? 0 : Math.max(insets.bottom, 12);
|
||||
const contentPresentationKind = props.contentPresentation.kind;
|
||||
const selectedThreadFeed = props.selectedThreadFeed;
|
||||
const composerChrome = composerExpanded ? COMPOSER_EXPANDED_CHROME : COMPOSER_COLLAPSED_CHROME;
|
||||
const composerOverlapHeight = composerChrome + composerBottomInset;
|
||||
const activeWorkIndicatorHeight = props.activeWorkStartedAt ? WORKING_INDICATOR_HEIGHT : 0;
|
||||
const estimatedOverlayHeight = composerOverlapHeight + activeWorkIndicatorHeight;
|
||||
const [measuredOverlayHeight, setMeasuredOverlayHeight] = useState(0);
|
||||
const estimatedOverlayHeight = composerOverlapHeight + activeWorkIndicatorHeight + 8;
|
||||
const { contentInsetEndAdjustment, onComposerLayout } = useKeyboardChatComposerInset(
|
||||
listRef,
|
||||
composerOverlayRef,
|
||||
estimatedOverlayHeight,
|
||||
);
|
||||
const { freeze, scrollMessageToEnd } = useKeyboardScrollToEnd({ listRef });
|
||||
const showContent = props.showContent ?? true;
|
||||
const layoutVariant = props.layoutVariant ?? "compact";
|
||||
const isSplitLayout = layoutVariant === "split";
|
||||
const selectedInstanceId = props.selectedThread.modelSelection.instanceId;
|
||||
useStreamingHaptics(props.selectedThread.id, props.selectedThreadFeed);
|
||||
const feedBottomInset = resolveThreadFeedBottomInset({
|
||||
estimatedOverlayHeight,
|
||||
measuredOverlayHeight,
|
||||
gap: 8,
|
||||
});
|
||||
const selectedProviderSkills = useMemo(
|
||||
() =>
|
||||
props.serverConfig?.providers.find((provider) => provider.instanceId === selectedInstanceId)
|
||||
@@ -254,15 +265,67 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
[completeDrawerGesture, isSplitLayout],
|
||||
);
|
||||
|
||||
const handleOverlayLayout = useCallback((event: LayoutChangeEvent) => {
|
||||
const nextHeight = Math.ceil(event.nativeEvent.layout.height);
|
||||
setMeasuredOverlayHeight((current) =>
|
||||
Math.abs(current - nextHeight) > 1 ? nextHeight : current,
|
||||
);
|
||||
}, []);
|
||||
useLayoutEffect(() => {
|
||||
selectedThreadKeyRef.current = selectedThreadKey;
|
||||
}, [selectedThreadKey]);
|
||||
|
||||
useEffect(() => {
|
||||
setAnchorMessageId(null);
|
||||
lastScrolledAnchorMessageIdRef.current = null;
|
||||
freeze.set(false);
|
||||
}, [freeze, selectedThreadKey]);
|
||||
|
||||
useEffect(() => {
|
||||
if (
|
||||
anchorMessageId === null ||
|
||||
lastScrolledAnchorMessageIdRef.current === anchorMessageId ||
|
||||
contentPresentationKind !== "ready" ||
|
||||
!selectedThreadFeed.some((entry) => entry.type === "message" && entry.id === anchorMessageId)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
const targetThreadKey = selectedThreadKey;
|
||||
const frame = requestAnimationFrame(() => {
|
||||
if (selectedThreadKeyRef.current !== targetThreadKey) {
|
||||
return;
|
||||
}
|
||||
lastScrolledAnchorMessageIdRef.current = anchorMessageId;
|
||||
void scrollMessageToEnd({ animated: true, closeKeyboard: false }).catch(() => {
|
||||
if (
|
||||
selectedThreadKeyRef.current !== targetThreadKey ||
|
||||
lastScrolledAnchorMessageIdRef.current !== anchorMessageId
|
||||
) {
|
||||
return;
|
||||
}
|
||||
lastScrolledAnchorMessageIdRef.current = null;
|
||||
freeze.set(false);
|
||||
});
|
||||
});
|
||||
return () => cancelAnimationFrame(frame);
|
||||
}, [
|
||||
anchorMessageId,
|
||||
freeze,
|
||||
contentPresentationKind,
|
||||
selectedThreadFeed,
|
||||
scrollMessageToEnd,
|
||||
selectedThreadKey,
|
||||
]);
|
||||
|
||||
const handleSendMessage = useCallback(async () => {
|
||||
const targetThreadKey = selectedThreadKey;
|
||||
const messageId = await props.onSendMessage();
|
||||
if (messageId === null || selectedThreadKeyRef.current !== targetThreadKey) {
|
||||
return messageId;
|
||||
}
|
||||
|
||||
setAnchorMessageId(messageId);
|
||||
composerEditorRef.current?.blur();
|
||||
return messageId;
|
||||
}, [props.onSendMessage, selectedThreadKey]);
|
||||
|
||||
const collapseComposer = useCallback(() => {
|
||||
composerRef.current?.blur();
|
||||
composerEditorRef.current?.blur();
|
||||
}, []);
|
||||
|
||||
const handleFeedTouchStart = useCallback((event: GestureResponderEvent) => {
|
||||
@@ -315,10 +378,13 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
contentPresentation={props.contentPresentation}
|
||||
agentLabel={agentLabel}
|
||||
latestTurn={props.selectedThread.latestTurn}
|
||||
listRef={listRef}
|
||||
freeze={freeze}
|
||||
anchorMessageId={anchorMessageId}
|
||||
contentInsetEndAdjustment={contentInsetEndAdjustment}
|
||||
contentTopInset={headerHeight}
|
||||
contentBottomInset={feedBottomInset}
|
||||
contentBottomInset={estimatedOverlayHeight}
|
||||
layoutVariant={layoutVariant}
|
||||
composerExpanded={composerExpanded}
|
||||
skills={selectedProviderSkills}
|
||||
/>
|
||||
</View>
|
||||
@@ -332,7 +398,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}
|
||||
offset={{ closed: 0, opened: 0 }}
|
||||
>
|
||||
<View onLayout={handleOverlayLayout}>
|
||||
<View ref={composerOverlayRef} onLayout={onComposerLayout} style={{ paddingTop: 8 }}>
|
||||
{props.activeWorkStartedAt ? (
|
||||
<WorkingDurationPill startedAt={props.activeWorkStartedAt} />
|
||||
) : null}
|
||||
@@ -361,7 +427,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
) : null}
|
||||
|
||||
<ThreadComposer
|
||||
editorRef={composerRef}
|
||||
editorRef={composerEditorRef}
|
||||
draftMessage={props.draftMessage}
|
||||
draftAttachments={props.draftAttachments}
|
||||
placeholder="Ask the repo agent, or run a command…"
|
||||
@@ -380,7 +446,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
onNativePasteImages={props.onNativePasteImages}
|
||||
onRemoveDraftImage={props.onRemoveDraftImage}
|
||||
onStopThread={props.onStopThread}
|
||||
onSendMessage={props.onSendMessage}
|
||||
onSendMessage={handleSendMessage}
|
||||
onReconnectEnvironment={props.onReconnectEnvironment}
|
||||
onUpdateModelSelection={props.onUpdateThreadModelSelection}
|
||||
onUpdateRuntimeMode={props.onUpdateThreadRuntimeMode}
|
||||
|
||||
@@ -1,10 +1,20 @@
|
||||
import * as Haptics from "expo-haptics";
|
||||
import { KeyboardAvoidingLegendList } from "@legendapp/list/keyboard";
|
||||
import { KeyboardAwareLegendList } from "@legendapp/list/keyboard";
|
||||
import { type LegendListRef } from "@legendapp/list/react-native";
|
||||
import type { EnvironmentId, ThreadId, TurnId } from "@t3tools/contracts";
|
||||
import type { EnvironmentId, MessageId, ThreadId, TurnId } from "@t3tools/contracts";
|
||||
import { CHAT_LIST_ANCHOR_OFFSET, resolveChatListAnchoredEndSpace } from "@t3tools/shared/chatList";
|
||||
import { SymbolView } from "expo-symbols";
|
||||
import { useRouter } from "expo-router";
|
||||
import { memo, useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
|
||||
import {
|
||||
memo,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
type ReactNode,
|
||||
type RefObject,
|
||||
} from "react";
|
||||
import {
|
||||
Markdown,
|
||||
type CustomRenderers,
|
||||
@@ -15,8 +25,6 @@ import {
|
||||
ActivityIndicator,
|
||||
Image,
|
||||
Linking,
|
||||
type NativeScrollEvent,
|
||||
type NativeSyntheticEvent,
|
||||
Pressable,
|
||||
ScrollView,
|
||||
StyleSheet,
|
||||
@@ -29,6 +37,7 @@ import {
|
||||
import { TouchableOpacity } from "react-native-gesture-handler";
|
||||
import ImageViewing from "react-native-image-viewing";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import type { SharedValue } from "react-native-reanimated";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
|
||||
import {
|
||||
@@ -64,14 +73,11 @@ import {
|
||||
type ThreadFeedEntry,
|
||||
type ThreadFeedLatestTurn,
|
||||
} from "../../lib/threadActivity";
|
||||
import { isThreadFeedNearEnd } from "../../lib/threadFeedLayout";
|
||||
import { relativeTime } from "../../lib/time";
|
||||
import type { ThreadContentPresentation } from "./threadContentPresentation";
|
||||
import { ThreadWorkLog } from "./thread-work-log";
|
||||
import { useAssetUrl } from "../../state/assets";
|
||||
import { resolveWorkspaceRelativeFilePath } from "../files/filePath";
|
||||
|
||||
const THREAD_FEED_END_THRESHOLD = 80;
|
||||
const MESSAGE_TIME_FORMATTER = new Intl.DateTimeFormat(undefined, {
|
||||
hour: "numeric",
|
||||
minute: "2-digit",
|
||||
@@ -93,10 +99,13 @@ export interface ThreadFeedProps {
|
||||
readonly contentPresentation: ThreadContentPresentation;
|
||||
readonly agentLabel: string;
|
||||
readonly latestTurn: ThreadFeedLatestTurn | null;
|
||||
readonly listRef: RefObject<LegendListRef | null>;
|
||||
readonly freeze: SharedValue<boolean>;
|
||||
readonly anchorMessageId: MessageId | null;
|
||||
readonly contentInsetEndAdjustment: SharedValue<number>;
|
||||
readonly contentTopInset?: number;
|
||||
readonly contentBottomInset?: number;
|
||||
readonly layoutVariant?: LayoutVariant;
|
||||
readonly composerExpanded?: boolean;
|
||||
readonly skills?: ReadonlyArray<SelectableMarkdownSkill>;
|
||||
}
|
||||
|
||||
@@ -812,30 +821,6 @@ function renderFeedEntry(
|
||||
);
|
||||
}
|
||||
|
||||
if (entry.type === "queued-message") {
|
||||
return (
|
||||
<View className="mb-5 items-end">
|
||||
<View
|
||||
className="max-w-[85%] gap-2 rounded-[22px] rounded-br-[6px] px-3.5 py-2.5 opacity-60"
|
||||
style={{ backgroundColor: userBubbleColor }}
|
||||
>
|
||||
<Text className="font-sans text-base leading-[22px] text-white">
|
||||
{entry.queuedMessage.text}
|
||||
</Text>
|
||||
{entry.queuedMessage.attachments.length > 0 ? (
|
||||
<Text className="font-t3-medium text-xs text-white/75">
|
||||
{entry.queuedMessage.attachments.length} image
|
||||
{entry.queuedMessage.attachments.length === 1 ? "" : "s"} attached
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
<Text className="mt-1.5 px-1 text-right font-t3-medium text-xs text-neutral-600 dark:text-neutral-400">
|
||||
{entry.sending ? "dispatching" : `${relativeTime(entry.createdAt)} • pending`}
|
||||
</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<ThreadWorkLog
|
||||
activities={entry.activities}
|
||||
@@ -1122,17 +1107,12 @@ function ThreadFeedPlaceholder(props: {
|
||||
|
||||
export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
const router = useRouter();
|
||||
const listRef = useRef<LegendListRef>(null);
|
||||
const copyFeedbackTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const scrollFrameRef = useRef<number | null>(null);
|
||||
const foldSettleFrameRef = useRef<number | null>(null);
|
||||
const foldSettleSecondFrameRef = useRef<number | null>(null);
|
||||
const suppressAutoFollowRef = useRef(false);
|
||||
const previousLatestTurnRef = useRef(props.latestTurn);
|
||||
const isNearEndRef = useRef(true);
|
||||
const initialScrollReadyRef = useRef(false);
|
||||
const lastContentHeightRef = useRef(0);
|
||||
const { width: viewportWidth } = useWindowDimensions();
|
||||
const [foldToggleSettling, setFoldToggleSettling] = useState(false);
|
||||
const [interactionState, setInteractionState] = useState<{
|
||||
readonly copiedRowId: string | null;
|
||||
readonly expandedWorkGroups: Record<string, boolean>;
|
||||
@@ -1214,6 +1194,16 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
() => deriveThreadFeedPresentation(props.feed, props.latestTurn, expandedTurnIds),
|
||||
[expandedTurnIds, props.feed, props.latestTurn],
|
||||
);
|
||||
const anchoredEndSpace = useMemo(
|
||||
() =>
|
||||
resolveChatListAnchoredEndSpace(
|
||||
presentedFeed,
|
||||
props.anchorMessageId,
|
||||
(entry) => (entry.type === "message" ? entry.id : null),
|
||||
{ anchorOffset: topContentInset + CHAT_LIST_ANCHOR_OFFSET },
|
||||
),
|
||||
[presentedFeed, props.anchorMessageId, topContentInset],
|
||||
);
|
||||
const terminalAssistantMessageIds = useMemo(() => {
|
||||
const terminalIdsByTurn = new Map<TurnId, string>();
|
||||
for (const entry of props.feed) {
|
||||
@@ -1229,54 +1219,6 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
? props.latestTurn.turnId
|
||||
: null;
|
||||
|
||||
const scrollToEnd = useCallback(() => {
|
||||
if (scrollFrameRef.current !== null) {
|
||||
return;
|
||||
}
|
||||
scrollFrameRef.current = requestAnimationFrame(() => {
|
||||
scrollFrameRef.current = null;
|
||||
listRef.current?.scrollToEnd({ animated: false });
|
||||
});
|
||||
}, []);
|
||||
|
||||
const onListScroll = useCallback(
|
||||
(event: NativeSyntheticEvent<NativeScrollEvent> | NativeScrollEvent) => {
|
||||
const scrollEvent = "nativeEvent" in event ? event.nativeEvent : event;
|
||||
const { contentInset, contentOffset, contentSize, layoutMeasurement } = scrollEvent;
|
||||
isNearEndRef.current = isThreadFeedNearEnd(
|
||||
{
|
||||
contentHeight: contentSize.height,
|
||||
viewportHeight: layoutMeasurement.height,
|
||||
offsetY: contentOffset.y,
|
||||
bottomInset: contentInset.bottom,
|
||||
},
|
||||
THREAD_FEED_END_THRESHOLD,
|
||||
);
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const onListContentSizeChange = useCallback(
|
||||
(_width: number, height: number) => {
|
||||
const contentGrew = height > lastContentHeightRef.current + 0.5;
|
||||
lastContentHeightRef.current = height;
|
||||
|
||||
if (
|
||||
initialScrollReadyRef.current &&
|
||||
contentGrew &&
|
||||
isNearEndRef.current &&
|
||||
!suppressAutoFollowRef.current
|
||||
) {
|
||||
scrollToEnd();
|
||||
}
|
||||
},
|
||||
[scrollToEnd],
|
||||
);
|
||||
|
||||
const onListLoad = useCallback(() => {
|
||||
initialScrollReadyRef.current = true;
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const previous = previousLatestTurnRef.current;
|
||||
previousLatestTurnRef.current = props.latestTurn;
|
||||
@@ -1308,9 +1250,6 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
if (copyFeedbackTimeoutRef.current) {
|
||||
clearTimeout(copyFeedbackTimeoutRef.current);
|
||||
}
|
||||
if (scrollFrameRef.current !== null) {
|
||||
cancelAnimationFrame(scrollFrameRef.current);
|
||||
}
|
||||
if (foldSettleFrameRef.current !== null) {
|
||||
cancelAnimationFrame(foldSettleFrameRef.current);
|
||||
}
|
||||
@@ -1358,7 +1297,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
}, []);
|
||||
|
||||
const onToggleTurnFold = useCallback((turnId: TurnId) => {
|
||||
suppressAutoFollowRef.current = true;
|
||||
setFoldToggleSettling(true);
|
||||
if (foldSettleFrameRef.current !== null) {
|
||||
cancelAnimationFrame(foldSettleFrameRef.current);
|
||||
}
|
||||
@@ -1376,7 +1315,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
});
|
||||
foldSettleFrameRef.current = requestAnimationFrame(() => {
|
||||
foldSettleSecondFrameRef.current = requestAnimationFrame(() => {
|
||||
suppressAutoFollowRef.current = false;
|
||||
setFoldToggleSettling(false);
|
||||
foldSettleFrameRef.current = null;
|
||||
foldSettleSecondFrameRef.current = null;
|
||||
});
|
||||
@@ -1458,59 +1397,60 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
);
|
||||
}
|
||||
|
||||
if (props.feed.length === 0) {
|
||||
return (
|
||||
<ThreadFeedPlaceholder
|
||||
title="No conversation yet"
|
||||
detail="Ask the agent to inspect the repo, run a command, or continue the active thread."
|
||||
topInset={topContentInset}
|
||||
bottomInset={bottomContentInset}
|
||||
horizontalPadding={horizontalPadding}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<View style={{ flex: 1 }}>
|
||||
<KeyboardAvoidingLegendList
|
||||
ref={listRef}
|
||||
<KeyboardAwareLegendList
|
||||
ref={props.listRef}
|
||||
key={props.threadId}
|
||||
style={{ flex: 1 }}
|
||||
automaticallyAdjustsScrollIndicatorInsets={false}
|
||||
contentInset={{ top: 0, bottom: 0 }}
|
||||
scrollIndicatorInsets={{ top: topContentInset, bottom: 0 }}
|
||||
alignItemsAtEnd
|
||||
maintainScrollAtEnd={{
|
||||
animated: false,
|
||||
on: {
|
||||
dataChange: true,
|
||||
itemLayout: true,
|
||||
layout: true,
|
||||
},
|
||||
}}
|
||||
{...(anchoredEndSpace ? { anchoredEndSpace } : {})}
|
||||
contentInsetEndAdjustment={props.contentInsetEndAdjustment}
|
||||
freeze={props.freeze}
|
||||
maintainScrollAtEnd={
|
||||
foldToggleSettling
|
||||
? false
|
||||
: {
|
||||
animated: false,
|
||||
on: {
|
||||
dataChange: true,
|
||||
itemLayout: true,
|
||||
layout: true,
|
||||
},
|
||||
}
|
||||
}
|
||||
maintainVisibleContentPosition
|
||||
data={presentedFeed}
|
||||
extraData={listAppearanceData}
|
||||
renderItem={renderItem}
|
||||
keyExtractor={(entry) => `${entry.type}:${entry.id}`}
|
||||
keyExtractor={(entry) => entry.id}
|
||||
getItemType={(entry) =>
|
||||
entry.type === "message" ? `message:${entry.message.role}` : entry.type
|
||||
}
|
||||
keyboardShouldPersistTaps="always"
|
||||
keyboardDismissMode="none"
|
||||
keyboardLiftBehavior="whenAtEnd"
|
||||
estimatedItemSize={180}
|
||||
initialScrollAtEnd
|
||||
onContentSizeChange={onListContentSizeChange}
|
||||
onLoad={onListLoad}
|
||||
onScroll={onListScroll}
|
||||
scrollEventThrottle={16}
|
||||
ListHeaderComponent={<View style={{ height: topContentInset }} />}
|
||||
contentContainerStyle={{
|
||||
paddingTop: 12,
|
||||
paddingBottom: bottomContentInset,
|
||||
paddingHorizontal: horizontalPadding,
|
||||
}}
|
||||
/>
|
||||
{props.feed.length === 0 ? (
|
||||
<View pointerEvents="none" style={StyleSheet.absoluteFill}>
|
||||
<ThreadFeedPlaceholder
|
||||
title="No conversation yet"
|
||||
detail="Ask the agent to inspect the repo, run a command, or continue the active thread."
|
||||
topInset={topContentInset}
|
||||
bottomInset={bottomContentInset}
|
||||
horizontalPadding={horizontalPadding}
|
||||
/>
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
|
||||
<ImageViewing
|
||||
|
||||
@@ -1,13 +1,7 @@
|
||||
import { Stack, useLocalSearchParams, useRouter } from "expo-router";
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
import * as Option from "effect/Option";
|
||||
import {
|
||||
EnvironmentId,
|
||||
type ModelSelection,
|
||||
type ProjectScript,
|
||||
type ProviderInteractionMode,
|
||||
type RuntimeMode,
|
||||
} from "@t3tools/contracts";
|
||||
import { EnvironmentId, type ProjectScript } from "@t3tools/contracts";
|
||||
import { projectScriptCwd, projectScriptRuntimeEnv } from "@t3tools/shared/projectScripts";
|
||||
import { Pressable, ScrollView, Text as RNText, View } from "react-native";
|
||||
import { useWorkspaceState } from "../../state/workspace";
|
||||
@@ -79,18 +73,6 @@ export function ThreadRouteScreen() {
|
||||
const gitState = useSelectedThreadGitState();
|
||||
const gitActions = useSelectedThreadGitActions();
|
||||
const requests = useSelectedThreadRequests();
|
||||
const updateThreadMetadata = useAtomCommand(
|
||||
threadEnvironment.updateMetadata,
|
||||
"thread metadata update",
|
||||
);
|
||||
const setThreadRuntimeMode = useAtomCommand(
|
||||
threadEnvironment.setRuntimeMode,
|
||||
"thread runtime mode",
|
||||
);
|
||||
const setThreadInteractionMode = useAtomCommand(
|
||||
threadEnvironment.setInteractionMode,
|
||||
"thread interaction mode",
|
||||
);
|
||||
const interruptThreadTurn = useAtomCommand(threadEnvironment.interruptTurn, "thread interrupt");
|
||||
const router = useRouter();
|
||||
const params = useLocalSearchParams<{
|
||||
@@ -105,6 +87,18 @@ export function ThreadRouteScreen() {
|
||||
const routeConnectionState =
|
||||
routeEnvironmentRuntime?.connectionState ?? (environmentId ? "available" : connectionState);
|
||||
const routeConnectionError = routeEnvironmentRuntime?.connectionError ?? null;
|
||||
const selectedThreadWithDraftSettings = useMemo(
|
||||
() =>
|
||||
selectedThread
|
||||
? {
|
||||
...selectedThread,
|
||||
modelSelection: composer.modelSelection ?? selectedThread.modelSelection,
|
||||
runtimeMode: composer.runtimeMode ?? selectedThread.runtimeMode,
|
||||
interactionMode: composer.interactionMode ?? selectedThread.interactionMode,
|
||||
}
|
||||
: null,
|
||||
[composer.interactionMode, composer.modelSelection, composer.runtimeMode, selectedThread],
|
||||
);
|
||||
|
||||
/* ─── Native header theming ──────────────────────────────────────── */
|
||||
const iconColor = String(useThemeColor("--color-icon"));
|
||||
@@ -157,51 +151,6 @@ export function ThreadRouteScreen() {
|
||||
const handleOpenConnectionEditor = useCallback(() => {
|
||||
void router.push("/connections");
|
||||
}, [router]);
|
||||
const handleUpdateThreadModelSelection = useCallback(
|
||||
(modelSelection: ModelSelection) => {
|
||||
if (!selectedThread) {
|
||||
return;
|
||||
}
|
||||
return updateThreadMetadata({
|
||||
environmentId: selectedThread.environmentId,
|
||||
input: {
|
||||
threadId: selectedThread.id,
|
||||
modelSelection,
|
||||
},
|
||||
});
|
||||
},
|
||||
[selectedThread, updateThreadMetadata],
|
||||
);
|
||||
const handleUpdateThreadRuntimeMode = useCallback(
|
||||
(runtimeMode: RuntimeMode) => {
|
||||
if (!selectedThread) {
|
||||
return;
|
||||
}
|
||||
return setThreadRuntimeMode({
|
||||
environmentId: selectedThread.environmentId,
|
||||
input: {
|
||||
threadId: selectedThread.id,
|
||||
runtimeMode,
|
||||
},
|
||||
});
|
||||
},
|
||||
[selectedThread, setThreadRuntimeMode],
|
||||
);
|
||||
const handleUpdateThreadInteractionMode = useCallback(
|
||||
(interactionMode: ProviderInteractionMode) => {
|
||||
if (!selectedThread) {
|
||||
return;
|
||||
}
|
||||
return setThreadInteractionMode({
|
||||
environmentId: selectedThread.environmentId,
|
||||
input: {
|
||||
threadId: selectedThread.id,
|
||||
interactionMode,
|
||||
},
|
||||
});
|
||||
},
|
||||
[selectedThread, setThreadInteractionMode],
|
||||
);
|
||||
const handleStopThread = useCallback(() => {
|
||||
if (
|
||||
!selectedThread ||
|
||||
@@ -435,7 +384,7 @@ export function ThreadRouteScreen() {
|
||||
|
||||
<View className="flex-1 bg-screen">
|
||||
<ThreadDetailScreen
|
||||
selectedThread={selectedThread}
|
||||
selectedThread={selectedThreadWithDraftSettings ?? selectedThread}
|
||||
contentPresentation={contentPresentation}
|
||||
screenTone={connectionTone(routeConnectionState)}
|
||||
connectionError={routeConnectionError}
|
||||
@@ -466,9 +415,9 @@ export function ThreadRouteScreen() {
|
||||
onStopThread={handleStopThread}
|
||||
onSendMessage={composer.onSendMessage}
|
||||
onReconnectEnvironment={handleReconnectEnvironment}
|
||||
onUpdateThreadModelSelection={handleUpdateThreadModelSelection}
|
||||
onUpdateThreadRuntimeMode={handleUpdateThreadRuntimeMode}
|
||||
onUpdateThreadInteractionMode={handleUpdateThreadInteractionMode}
|
||||
onUpdateThreadModelSelection={composer.onUpdateModelSelection}
|
||||
onUpdateThreadRuntimeMode={composer.onUpdateRuntimeMode}
|
||||
onUpdateThreadInteractionMode={composer.onUpdateInteractionMode}
|
||||
onRespondToApproval={requests.onRespondToApproval}
|
||||
onSelectUserInputOption={requests.onSelectUserInputOption}
|
||||
onChangeUserInputCustomAnswer={requests.onChangeUserInputCustomAnswer}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, { useCallback, useMemo, useRef, useState } from "react";
|
||||
import React, { useCallback, useEffect, useMemo, useState } from "react";
|
||||
|
||||
import type {
|
||||
EnvironmentId,
|
||||
@@ -23,6 +23,7 @@ import {
|
||||
removeComposerDraftAttachment,
|
||||
replaceComposerDraftAttachments,
|
||||
setComposerDraftText,
|
||||
updateComposerDraftSettings,
|
||||
useComposerDraft,
|
||||
} from "../../state/use-composer-drafts";
|
||||
import { useBranches } from "../../state/queries";
|
||||
@@ -158,34 +159,15 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
? selectedEnvironmentIdOverride
|
||||
: (projects[0]?.environmentId ?? null);
|
||||
const [selectedProjectKey, setSelectedProjectKey] = useState<string | null>(null);
|
||||
const [selectedModelKey, setSelectedModelKey] = useState<string | null>(null);
|
||||
const [workspaceMode, setWorkspaceMode] = useState<WorkspaceMode>("local");
|
||||
const [selectedBranchName, setSelectedBranchName] = useState<string | null>(null);
|
||||
const [selectedWorktreePath, setSelectedWorktreePath] = useState<string | null>(null);
|
||||
const branchLoadVersionRef = useRef(0);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [branchQuery, setBranchQuery] = useState("");
|
||||
const [runtimeMode, setRuntimeMode] = useState<RuntimeMode>(DEFAULT_RUNTIME_MODE);
|
||||
const [interactionMode, setInteractionMode] = useState<ProviderInteractionMode>(
|
||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
);
|
||||
const [modelSelectionOverrides, setModelSelectionOverrides] = useState<
|
||||
Record<string, ModelSelection>
|
||||
>({});
|
||||
const [expandedProvider, setExpandedProvider] = useState<string | null>(null);
|
||||
|
||||
const reset = useCallback(() => {
|
||||
setSelectedEnvironmentId(null);
|
||||
setSelectedProjectKey(null);
|
||||
setSelectedModelKey(null);
|
||||
setWorkspaceMode("local");
|
||||
setSelectedBranchName(null);
|
||||
setSelectedWorktreePath(null);
|
||||
setSubmitting(false);
|
||||
setBranchQuery("");
|
||||
setRuntimeMode(DEFAULT_RUNTIME_MODE);
|
||||
setInteractionMode(DEFAULT_PROVIDER_INTERACTION_MODE);
|
||||
setModelSelectionOverrides({});
|
||||
setExpandedProvider(null);
|
||||
}, []);
|
||||
|
||||
@@ -247,33 +229,33 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
const selectedProjectDraft = useComposerDraft(selectedProjectDraftKey);
|
||||
const prompt = selectedProjectDraft.text;
|
||||
const attachments = selectedProjectDraft.attachments;
|
||||
const workspaceMode = selectedProjectDraft.workspaceSelection?.mode ?? "local";
|
||||
const selectedBranchName = selectedProjectDraft.workspaceSelection?.branch ?? null;
|
||||
const selectedWorktreePath = selectedProjectDraft.workspaceSelection?.worktreePath ?? null;
|
||||
const runtimeMode = selectedProjectDraft.runtimeMode ?? DEFAULT_RUNTIME_MODE;
|
||||
const interactionMode = selectedProjectDraft.interactionMode ?? DEFAULT_PROVIDER_INTERACTION_MODE;
|
||||
|
||||
const modelOptions = useMemo(
|
||||
() =>
|
||||
buildModelOptions(
|
||||
selectedEnvironmentServerConfig,
|
||||
selectedProject?.defaultModelSelection ?? null,
|
||||
selectedProjectDraft.modelSelection ?? selectedProject?.defaultModelSelection ?? null,
|
||||
),
|
||||
[selectedEnvironmentServerConfig, selectedProject?.defaultModelSelection],
|
||||
[
|
||||
selectedEnvironmentServerConfig,
|
||||
selectedProject?.defaultModelSelection,
|
||||
selectedProjectDraft.modelSelection,
|
||||
],
|
||||
);
|
||||
|
||||
const defaultModelKey = selectedProject?.defaultModelSelection
|
||||
? `${selectedProject.defaultModelSelection.instanceId}:${selectedProject.defaultModelSelection.model}`
|
||||
: null;
|
||||
const baseSelectedModel =
|
||||
modelOptions.find((option) => option.key === selectedModelKey)?.selection ??
|
||||
(defaultModelKey
|
||||
? modelOptions.find((option) => option.key === defaultModelKey)?.selection
|
||||
: null) ??
|
||||
const selectedModel =
|
||||
selectedProjectDraft.modelSelection ??
|
||||
selectedProject?.defaultModelSelection ??
|
||||
modelOptions[0]?.selection ??
|
||||
null;
|
||||
const selectedModelIdentity = baseSelectedModel
|
||||
? `${baseSelectedModel.instanceId}:${baseSelectedModel.model}`
|
||||
const selectedModelKey = selectedModel
|
||||
? `${selectedModel.instanceId}:${selectedModel.model}`
|
||||
: null;
|
||||
const selectedModel =
|
||||
(selectedModelIdentity ? modelSelectionOverrides[selectedModelIdentity] : null) ??
|
||||
baseSelectedModel;
|
||||
|
||||
const selectedModelOption =
|
||||
modelOptions.find(
|
||||
@@ -282,13 +264,31 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
option.selection.instanceId === selectedModel.instanceId &&
|
||||
option.selection.model === selectedModel.model,
|
||||
) ?? null;
|
||||
const selectedProviderSkills =
|
||||
selectedEnvironmentServerConfig?.providers.find(
|
||||
(provider) => provider.instanceId === selectedModel?.instanceId,
|
||||
)?.skills ?? [];
|
||||
const selectedProviderSkills = useMemo(
|
||||
() =>
|
||||
selectedEnvironmentServerConfig?.providers.find(
|
||||
(provider) => provider.instanceId === selectedModel?.instanceId,
|
||||
)?.skills ?? [],
|
||||
[selectedEnvironmentServerConfig, selectedModel?.instanceId],
|
||||
);
|
||||
const setSelectedModelKey = useCallback(
|
||||
(key: string | null) => {
|
||||
if (!key || !selectedProjectDraftKey) {
|
||||
return;
|
||||
}
|
||||
const option = modelOptions.find((candidate) => candidate.key === key);
|
||||
if (!option) {
|
||||
return;
|
||||
}
|
||||
updateComposerDraftSettings(selectedProjectDraftKey, {
|
||||
modelSelection: option.selection,
|
||||
});
|
||||
},
|
||||
[modelOptions, selectedProjectDraftKey],
|
||||
);
|
||||
const setSelectedModelOptions = useCallback(
|
||||
(options: ReadonlyArray<ProviderOptionSelection> | undefined) => {
|
||||
if (!selectedModel || !selectedModelIdentity) {
|
||||
if (!selectedModel || !selectedProjectDraftKey) {
|
||||
return;
|
||||
}
|
||||
const nextSelection: ModelSelection = options
|
||||
@@ -297,12 +297,11 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
instanceId: selectedModel.instanceId,
|
||||
model: selectedModel.model,
|
||||
};
|
||||
setModelSelectionOverrides((current) => ({
|
||||
...current,
|
||||
[selectedModelIdentity]: nextSelection,
|
||||
}));
|
||||
updateComposerDraftSettings(selectedProjectDraftKey, {
|
||||
modelSelection: nextSelection,
|
||||
});
|
||||
},
|
||||
[selectedModel, selectedModelIdentity],
|
||||
[selectedModel, selectedProjectDraftKey],
|
||||
);
|
||||
|
||||
const providerGroups = useMemo(() => groupByProvider(modelOptions), [modelOptions]);
|
||||
@@ -381,62 +380,85 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
|
||||
const setProject = useCallback((project: EnvironmentProject) => {
|
||||
const nextProjectKey = scopedProjectKey(project.environmentId, project.id);
|
||||
branchLoadVersionRef.current += 1;
|
||||
setSelectedEnvironmentId(project.environmentId);
|
||||
setSelectedProjectKey(nextProjectKey);
|
||||
setSelectedBranchName(null);
|
||||
setSelectedWorktreePath(null);
|
||||
setModelSelectionOverrides({});
|
||||
}, []);
|
||||
|
||||
const selectEnvironment = useCallback((environmentId: EnvironmentId) => {
|
||||
branchLoadVersionRef.current += 1;
|
||||
setSelectedEnvironmentId(environmentId);
|
||||
setSelectedProjectKey(null);
|
||||
setSelectedBranchName(null);
|
||||
setSelectedWorktreePath(null);
|
||||
setModelSelectionOverrides({});
|
||||
}, []);
|
||||
|
||||
const setWorkspaceMode = useCallback(
|
||||
(mode: WorkspaceMode) => {
|
||||
if (!selectedProjectDraftKey) {
|
||||
return;
|
||||
}
|
||||
updateComposerDraftSettings(selectedProjectDraftKey, {
|
||||
workspaceSelection: {
|
||||
mode,
|
||||
branch: selectedBranchName,
|
||||
worktreePath: selectedWorktreePath,
|
||||
},
|
||||
});
|
||||
},
|
||||
[selectedBranchName, selectedProjectDraftKey, selectedWorktreePath],
|
||||
);
|
||||
|
||||
const selectBranch = useCallback(
|
||||
(branch: VcsRef) => {
|
||||
setSelectedBranchName(branch.name);
|
||||
setSelectedWorktreePath(
|
||||
selectedProject ? normalizeSelectedWorktreePath(selectedProject, branch) : null,
|
||||
);
|
||||
if (!selectedProject || !selectedProjectDraftKey) {
|
||||
return;
|
||||
}
|
||||
updateComposerDraftSettings(selectedProjectDraftKey, {
|
||||
workspaceSelection: {
|
||||
mode: workspaceMode,
|
||||
branch: branch.name,
|
||||
worktreePath: normalizeSelectedWorktreePath(selectedProject, branch),
|
||||
},
|
||||
});
|
||||
},
|
||||
[selectedProject],
|
||||
[selectedProject, selectedProjectDraftKey, workspaceMode],
|
||||
);
|
||||
|
||||
const refreshBranches = branchState.refresh;
|
||||
const loadBranches = useCallback(async () => {
|
||||
if (!selectedProject) {
|
||||
return;
|
||||
}
|
||||
setPendingConnectionError(null);
|
||||
refreshBranches();
|
||||
}, [refreshBranches, selectedProject]);
|
||||
|
||||
const loadVersion = ++branchLoadVersionRef.current;
|
||||
const projectKey = scopedProjectKey(selectedProject.environmentId, selectedProject.id);
|
||||
branchState.refresh();
|
||||
if (loadVersion !== branchLoadVersionRef.current || selectedProjectKey !== projectKey) {
|
||||
useEffect(() => {
|
||||
if (workspaceMode !== "worktree" || selectedBranchName !== null) {
|
||||
return;
|
||||
}
|
||||
setPendingConnectionError(null);
|
||||
if (workspaceMode === "worktree" && !selectedBranchName) {
|
||||
const preferredBranch =
|
||||
availableBranches.find((branch) => branch.current)?.name ??
|
||||
availableBranches.find((branch) => branch.isDefault)?.name ??
|
||||
null;
|
||||
if (preferredBranch) {
|
||||
setSelectedBranchName(preferredBranch);
|
||||
}
|
||||
const preferredBranch =
|
||||
availableBranches.find((branch) => branch.current) ??
|
||||
availableBranches.find((branch) => branch.isDefault) ??
|
||||
null;
|
||||
if (preferredBranch) {
|
||||
selectBranch(preferredBranch);
|
||||
}
|
||||
}, [
|
||||
availableBranches,
|
||||
branchState,
|
||||
selectedBranchName,
|
||||
selectedProject,
|
||||
selectedProjectKey,
|
||||
workspaceMode,
|
||||
]);
|
||||
}, [availableBranches, selectBranch, selectedBranchName, workspaceMode]);
|
||||
|
||||
const setRuntimeMode = useCallback(
|
||||
(value: RuntimeMode) => {
|
||||
if (selectedProjectDraftKey) {
|
||||
updateComposerDraftSettings(selectedProjectDraftKey, { runtimeMode: value });
|
||||
}
|
||||
},
|
||||
[selectedProjectDraftKey],
|
||||
);
|
||||
const setInteractionMode = useCallback(
|
||||
(value: ProviderInteractionMode) => {
|
||||
if (selectedProjectDraftKey) {
|
||||
updateComposerDraftSettings(selectedProjectDraftKey, { interactionMode: value });
|
||||
}
|
||||
},
|
||||
[selectedProjectDraftKey],
|
||||
);
|
||||
|
||||
const value = useMemo<NewTaskFlowContextValue>(
|
||||
() => ({
|
||||
@@ -513,6 +535,11 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
setProject,
|
||||
selectBranch,
|
||||
selectEnvironment,
|
||||
setInteractionMode,
|
||||
setPrompt,
|
||||
setRuntimeMode,
|
||||
setSelectedModelKey,
|
||||
setWorkspaceMode,
|
||||
submitting,
|
||||
workspaceMode,
|
||||
appendAttachments,
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
export const DraftComposerImageAttachmentSchema = Schema.Struct({
|
||||
id: Schema.String,
|
||||
previewUri: Schema.String,
|
||||
type: Schema.Literal("image"),
|
||||
name: Schema.String,
|
||||
mimeType: Schema.String,
|
||||
sizeBytes: Schema.Number,
|
||||
dataUrl: Schema.String,
|
||||
});
|
||||
@@ -86,7 +86,7 @@ describe("buildThreadFeed", () => {
|
||||
],
|
||||
});
|
||||
|
||||
const feed = buildThreadFeed(thread, [], null);
|
||||
const feed = buildThreadFeed(thread);
|
||||
expect(feed).toMatchObject([
|
||||
{
|
||||
type: "activity-group",
|
||||
@@ -144,7 +144,7 @@ describe("buildThreadFeed", () => {
|
||||
],
|
||||
});
|
||||
|
||||
const feed = buildThreadFeed(thread, [], null);
|
||||
const feed = buildThreadFeed(thread);
|
||||
const group = feed[0];
|
||||
|
||||
expect(group).toMatchObject({
|
||||
@@ -209,7 +209,7 @@ describe("buildThreadFeed", () => {
|
||||
],
|
||||
});
|
||||
|
||||
const group = buildThreadFeed(thread, [], null)[0];
|
||||
const group = buildThreadFeed(thread)[0];
|
||||
expect(group).toMatchObject({ type: "activity-group" });
|
||||
if (!group || group.type !== "activity-group") {
|
||||
return;
|
||||
@@ -271,7 +271,7 @@ describe("buildThreadFeed", () => {
|
||||
],
|
||||
});
|
||||
|
||||
const feed = buildThreadFeed(thread, [], null);
|
||||
const feed = buildThreadFeed(thread);
|
||||
const collapsed = deriveThreadFeedPresentation(feed, thread.latestTurn, new Set());
|
||||
expect(collapsed.map((entry) => entry.id)).toEqual(["turn-fold:turn-1", "assistant-final"]);
|
||||
expect(collapsed[0]).toMatchObject({
|
||||
@@ -359,7 +359,7 @@ describe("buildThreadFeed", () => {
|
||||
],
|
||||
});
|
||||
|
||||
const feed = buildThreadFeed(thread, [], null);
|
||||
const feed = buildThreadFeed(thread);
|
||||
const collapsed = deriveThreadFeedPresentation(feed, thread.latestTurn, new Set());
|
||||
expect(collapsed.find((entry) => entry.type === "turn-fold")).toMatchObject({
|
||||
turnId: firstTurnId,
|
||||
@@ -399,7 +399,7 @@ describe("buildThreadFeed", () => {
|
||||
],
|
||||
});
|
||||
|
||||
const feed = buildThreadFeed(thread, [], null);
|
||||
const feed = buildThreadFeed(thread);
|
||||
expect(deriveThreadFeedPresentation(feed, thread.latestTurn, new Set())).toEqual(feed);
|
||||
expect(feed[0]).toMatchObject({
|
||||
type: "activity-group",
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { ApprovalRequestId, isToolLifecycleItemType } from "@t3tools/contracts";
|
||||
import type {
|
||||
MessageId,
|
||||
OrchestrationLatestTurn,
|
||||
OrchestrationThread,
|
||||
OrchestrationThreadActivity,
|
||||
@@ -10,7 +9,6 @@ import type {
|
||||
} from "@t3tools/contracts";
|
||||
import { formatDuration } from "@t3tools/shared/orchestrationTiming";
|
||||
|
||||
import type { QueuedThreadMessage } from "../state/thread-outbox-model";
|
||||
import * as Arr from "effect/Array";
|
||||
import * as Order from "effect/Order";
|
||||
|
||||
@@ -88,13 +86,6 @@ type RawThreadFeedEntry =
|
||||
readonly createdAt: string;
|
||||
readonly message: OrchestrationThread["messages"][number];
|
||||
}
|
||||
| {
|
||||
readonly type: "queued-message";
|
||||
readonly id: string;
|
||||
readonly createdAt: string;
|
||||
readonly queuedMessage: QueuedThreadMessage;
|
||||
readonly sending: boolean;
|
||||
}
|
||||
| {
|
||||
readonly type: "activity";
|
||||
readonly id: string;
|
||||
@@ -104,7 +95,7 @@ type RawThreadFeedEntry =
|
||||
};
|
||||
|
||||
export type ThreadFeedEntry =
|
||||
| Extract<RawThreadFeedEntry, { type: "message" | "queued-message" }>
|
||||
| Extract<RawThreadFeedEntry, { type: "message" }>
|
||||
| {
|
||||
readonly type: "activity-group";
|
||||
readonly id: string;
|
||||
@@ -1255,8 +1246,6 @@ export function buildPendingUserInputAnswers(
|
||||
|
||||
export function buildThreadFeed(
|
||||
thread: OrchestrationThread,
|
||||
queuedMessages: ReadonlyArray<QueuedThreadMessage>,
|
||||
dispatchingQueuedMessageId: MessageId | null,
|
||||
options?: {
|
||||
readonly loadedMessages?: ReadonlyArray<OrchestrationThread["messages"][number]>;
|
||||
},
|
||||
@@ -1273,13 +1262,6 @@ export function buildThreadFeed(
|
||||
createdAt: message.createdAt,
|
||||
message,
|
||||
})),
|
||||
...queuedMessages.map<RawThreadFeedEntry>((queuedMessage) => ({
|
||||
type: "queued-message",
|
||||
id: queuedMessage.messageId,
|
||||
createdAt: queuedMessage.createdAt,
|
||||
queuedMessage,
|
||||
sending: queuedMessage.messageId === dispatchingQueuedMessageId,
|
||||
})),
|
||||
...workLogEntries
|
||||
.filter((entry) => {
|
||||
if (options?.loadedMessages === undefined) {
|
||||
|
||||
@@ -1,32 +0,0 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
isThreadFeedNearEnd,
|
||||
resolveThreadFeedBottomInset,
|
||||
threadFeedDistanceFromEnd,
|
||||
} from "./threadFeedLayout";
|
||||
|
||||
describe("thread feed layout", () => {
|
||||
it("accounts for the bottom inset when measuring distance from the end", () => {
|
||||
const metrics = {
|
||||
contentHeight: 900,
|
||||
viewportHeight: 600,
|
||||
offsetY: 380,
|
||||
bottomInset: 100,
|
||||
};
|
||||
|
||||
expect(threadFeedDistanceFromEnd(metrics)).toBe(20);
|
||||
expect(isThreadFeedNearEnd(metrics, 50)).toBe(true);
|
||||
expect(isThreadFeedNearEnd(metrics, 10)).toBe(false);
|
||||
});
|
||||
|
||||
it("does not double count chrome already included in the measured composer overlay", () => {
|
||||
expect(
|
||||
resolveThreadFeedBottomInset({
|
||||
estimatedOverlayHeight: 162,
|
||||
measuredOverlayHeight: 182,
|
||||
gap: 8,
|
||||
}),
|
||||
).toBe(190);
|
||||
});
|
||||
});
|
||||
@@ -1,22 +0,0 @@
|
||||
export interface ThreadFeedScrollMetrics {
|
||||
readonly contentHeight: number;
|
||||
readonly viewportHeight: number;
|
||||
readonly offsetY: number;
|
||||
readonly bottomInset: number;
|
||||
}
|
||||
|
||||
export function threadFeedDistanceFromEnd(metrics: ThreadFeedScrollMetrics): number {
|
||||
return metrics.contentHeight + metrics.bottomInset - metrics.viewportHeight - metrics.offsetY;
|
||||
}
|
||||
|
||||
export function isThreadFeedNearEnd(metrics: ThreadFeedScrollMetrics, threshold: number): boolean {
|
||||
return threadFeedDistanceFromEnd(metrics) <= threshold;
|
||||
}
|
||||
|
||||
export function resolveThreadFeedBottomInset(input: {
|
||||
readonly estimatedOverlayHeight: number;
|
||||
readonly measuredOverlayHeight: number;
|
||||
readonly gap: number;
|
||||
}): number {
|
||||
return Math.max(input.estimatedOverlayHeight, input.measuredOverlayHeight) + input.gap;
|
||||
}
|
||||
@@ -1,32 +1,38 @@
|
||||
import { isTransportConnectionErrorMessage } from "@t3tools/client-runtime/errors";
|
||||
import type { EnvironmentShellStatus } from "@t3tools/client-runtime/state/shell";
|
||||
import { CommandId, EnvironmentId, IsoDateTime, MessageId, ThreadId } from "@t3tools/contracts";
|
||||
import {
|
||||
CommandId,
|
||||
EnvironmentId,
|
||||
IsoDateTime,
|
||||
MessageId,
|
||||
ModelSelection,
|
||||
ProviderInteractionMode,
|
||||
RuntimeMode,
|
||||
ThreadId,
|
||||
type ModelSelection as ModelSelectionType,
|
||||
type ProviderInteractionMode as ProviderInteractionModeType,
|
||||
type RuntimeMode as RuntimeModeType,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import { DraftComposerImageAttachmentSchema } from "../lib/composer-image-schema";
|
||||
import type { DraftComposerImageAttachment } from "../lib/composerImages";
|
||||
import { scopedThreadKey } from "../lib/scopedEntities";
|
||||
|
||||
const THREAD_OUTBOX_SCHEMA_VERSION = 1;
|
||||
const THREAD_OUTBOX_SCHEMA_VERSION = 2;
|
||||
const THREAD_OUTBOX_MAX_RETRY_DELAY_MS = 16_000;
|
||||
|
||||
const DraftComposerImageAttachmentSchema = Schema.Struct({
|
||||
id: Schema.String,
|
||||
previewUri: Schema.String,
|
||||
type: Schema.Literal("image"),
|
||||
name: Schema.String,
|
||||
mimeType: Schema.String,
|
||||
sizeBytes: Schema.Number,
|
||||
dataUrl: Schema.String,
|
||||
});
|
||||
|
||||
export const QueuedThreadMessageSchema = Schema.Struct({
|
||||
schemaVersion: Schema.Literal(THREAD_OUTBOX_SCHEMA_VERSION),
|
||||
schemaVersion: Schema.Literals([1, THREAD_OUTBOX_SCHEMA_VERSION]),
|
||||
environmentId: EnvironmentId,
|
||||
threadId: ThreadId,
|
||||
messageId: MessageId,
|
||||
commandId: CommandId,
|
||||
text: Schema.String,
|
||||
attachments: Schema.Array(DraftComposerImageAttachmentSchema),
|
||||
modelSelection: Schema.optional(ModelSelection),
|
||||
runtimeMode: Schema.optional(RuntimeMode),
|
||||
interactionMode: Schema.optional(ProviderInteractionMode),
|
||||
createdAt: IsoDateTime,
|
||||
});
|
||||
|
||||
@@ -40,9 +46,37 @@ export interface QueuedThreadMessage {
|
||||
readonly commandId: CommandId;
|
||||
readonly text: string;
|
||||
readonly attachments: ReadonlyArray<DraftComposerImageAttachment>;
|
||||
readonly modelSelection?: ModelSelectionType;
|
||||
readonly runtimeMode?: RuntimeModeType;
|
||||
readonly interactionMode?: ProviderInteractionModeType;
|
||||
readonly createdAt: string;
|
||||
}
|
||||
|
||||
export interface ThreadSettingsSnapshot {
|
||||
readonly modelSelection: ModelSelectionType;
|
||||
readonly runtimeMode: RuntimeModeType;
|
||||
readonly interactionMode: ProviderInteractionModeType;
|
||||
}
|
||||
|
||||
export function resolveQueuedThreadSettings(
|
||||
message: QueuedThreadMessage,
|
||||
thread: ThreadSettingsSnapshot,
|
||||
): ThreadSettingsSnapshot {
|
||||
return {
|
||||
modelSelection: message.modelSelection ?? thread.modelSelection,
|
||||
runtimeMode: message.runtimeMode ?? thread.runtimeMode,
|
||||
interactionMode: message.interactionMode ?? thread.interactionMode,
|
||||
};
|
||||
}
|
||||
|
||||
export function modelSelectionsEqual(left: ModelSelectionType, right: ModelSelectionType): boolean {
|
||||
return (
|
||||
left.instanceId === right.instanceId &&
|
||||
left.model === right.model &&
|
||||
JSON.stringify(left.options ?? null) === JSON.stringify(right.options ?? null)
|
||||
);
|
||||
}
|
||||
|
||||
export function encodeQueuedThreadMessage(message: QueuedThreadMessage): unknown {
|
||||
return encodeStoredQueuedThreadMessage({
|
||||
schemaVersion: THREAD_OUTBOX_SCHEMA_VERSION,
|
||||
@@ -119,3 +153,21 @@ export function shouldRetryThreadOutboxDelivery(error: unknown): boolean {
|
||||
}
|
||||
return isTransportConnectionErrorMessage(errorMessage(error));
|
||||
}
|
||||
|
||||
export type ThreadOutboxCommandStage = "settings-sync" | "start-turn";
|
||||
export type ThreadOutboxFailureAction = "retry" | "discard";
|
||||
|
||||
export function resolveThreadOutboxFailureAction(input: {
|
||||
readonly stage: ThreadOutboxCommandStage;
|
||||
readonly error: unknown;
|
||||
readonly interrupted: boolean;
|
||||
}): ThreadOutboxFailureAction {
|
||||
if (
|
||||
input.stage === "settings-sync" ||
|
||||
input.interrupted ||
|
||||
shouldRetryThreadOutboxDelivery(input.error)
|
||||
) {
|
||||
return "retry";
|
||||
}
|
||||
return "discard";
|
||||
}
|
||||
@@ -1,11 +1,21 @@
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import { CommandId, EnvironmentId, MessageId, ThreadId } from "@t3tools/contracts";
|
||||
import {
|
||||
CommandId,
|
||||
EnvironmentId,
|
||||
MessageId,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { AtomRegistry } from "effect/unstable/reactivity";
|
||||
|
||||
import {
|
||||
decodeQueuedThreadMessage,
|
||||
encodeQueuedThreadMessage,
|
||||
groupQueuedThreadMessages,
|
||||
modelSelectionsEqual,
|
||||
resolveThreadOutboxDeliveryAction,
|
||||
resolveThreadOutboxFailureAction,
|
||||
resolveQueuedThreadSettings,
|
||||
shouldRetryThreadOutboxDelivery,
|
||||
threadOutboxRetryDelayMs,
|
||||
type QueuedThreadMessage,
|
||||
@@ -66,6 +76,54 @@ describe("thread outbox", () => {
|
||||
).toThrow();
|
||||
});
|
||||
|
||||
it("persists the exact selector snapshot while remaining compatible with v1 messages", () => {
|
||||
const legacyMessage = queuedMessage({
|
||||
messageId: "message-1",
|
||||
createdAt: "2026-06-08T10:00:01.000Z",
|
||||
});
|
||||
const selectedMessage = {
|
||||
...legacyMessage,
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5.4",
|
||||
options: [{ id: "reasoningEffort", value: "xhigh" }],
|
||||
},
|
||||
runtimeMode: "approval-required",
|
||||
interactionMode: "plan",
|
||||
} satisfies QueuedThreadMessage;
|
||||
|
||||
expect(decodeQueuedThreadMessage(encodeQueuedThreadMessage(selectedMessage))).toEqual(
|
||||
selectedMessage,
|
||||
);
|
||||
expect(
|
||||
resolveQueuedThreadSettings(legacyMessage, {
|
||||
modelSelection: selectedMessage.modelSelection,
|
||||
runtimeMode: selectedMessage.runtimeMode,
|
||||
interactionMode: selectedMessage.interactionMode,
|
||||
}),
|
||||
).toEqual({
|
||||
modelSelection: selectedMessage.modelSelection,
|
||||
runtimeMode: selectedMessage.runtimeMode,
|
||||
interactionMode: selectedMessage.interactionMode,
|
||||
});
|
||||
});
|
||||
|
||||
it("compares model options as part of the queued settings change", () => {
|
||||
const base = {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5.4",
|
||||
options: [{ id: "reasoningEffort", value: "medium" }],
|
||||
} as const;
|
||||
|
||||
expect(modelSelectionsEqual(base, base)).toBe(true);
|
||||
expect(
|
||||
modelSelectionsEqual(base, {
|
||||
...base,
|
||||
options: [{ id: "reasoningEffort", value: "xhigh" }],
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("backs off queued delivery retries and caps them at sixteen seconds", () => {
|
||||
expect([1, 2, 3, 4, 5, 6].map(threadOutboxRetryDelayMs)).toEqual([
|
||||
1_000, 2_000, 4_000, 8_000, 16_000, 16_000,
|
||||
@@ -271,4 +329,23 @@ describe("thread outbox", () => {
|
||||
).toBe(true);
|
||||
expect(shouldRetryThreadOutboxDelivery(new Error("Thread no longer exists"))).toBe(false);
|
||||
});
|
||||
|
||||
it("retains queued messages when settings synchronization fails before startTurn", () => {
|
||||
const deterministicFailure = new Error("Thread no longer exists");
|
||||
|
||||
expect(
|
||||
resolveThreadOutboxFailureAction({
|
||||
stage: "settings-sync",
|
||||
error: deterministicFailure,
|
||||
interrupted: false,
|
||||
}),
|
||||
).toBe("retry");
|
||||
expect(
|
||||
resolveThreadOutboxFailureAction({
|
||||
stage: "start-turn",
|
||||
error: deterministicFailure,
|
||||
interrupted: false,
|
||||
}),
|
||||
).toBe("discard");
|
||||
});
|
||||
});
|
||||
@@ -1,14 +1,136 @@
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import { EnvironmentId } from "@t3tools/contracts";
|
||||
import { afterEach, describe, expect, it } from "@effect/vitest";
|
||||
import { EnvironmentId, ProviderInstanceId } from "@t3tools/contracts";
|
||||
|
||||
import { type ComposerDraft, removeComposerDraftsForEnvironment } from "./use-composer-drafts";
|
||||
import { appAtomRegistry } from "./atom-registry";
|
||||
import {
|
||||
clearComposerDraftContentState,
|
||||
composerDraftsAtom,
|
||||
decodePersistedComposerDrafts,
|
||||
type ComposerDraft,
|
||||
getComposerDraftSnapshot,
|
||||
removeComposerDraftsForEnvironment,
|
||||
} from "./use-composer-drafts";
|
||||
|
||||
const DRAFT: ComposerDraft = {
|
||||
text: "hello",
|
||||
attachments: [],
|
||||
};
|
||||
|
||||
afterEach(() => {
|
||||
appAtomRegistry.set(composerDraftsAtom, {});
|
||||
});
|
||||
|
||||
describe("mobile composer drafts", () => {
|
||||
it("hydrates selector state even when the message content is empty", () => {
|
||||
expect(
|
||||
decodePersistedComposerDrafts({
|
||||
schemaVersion: 1,
|
||||
drafts: {
|
||||
"new-task:environment-1:project-1": {
|
||||
text: "",
|
||||
attachments: [],
|
||||
modelSelection: {
|
||||
instanceId: "codex",
|
||||
model: "gpt-5.4",
|
||||
options: [{ id: "reasoningEffort", value: "xhigh" }],
|
||||
},
|
||||
runtimeMode: "approval-required",
|
||||
interactionMode: "plan",
|
||||
workspaceSelection: {
|
||||
mode: "worktree",
|
||||
branch: "main",
|
||||
worktreePath: null,
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
"new-task:environment-1:project-1": {
|
||||
text: "",
|
||||
attachments: [],
|
||||
modelSelection: {
|
||||
instanceId: "codex",
|
||||
model: "gpt-5.4",
|
||||
options: [{ id: "reasoningEffort", value: "xhigh" }],
|
||||
},
|
||||
runtimeMode: "approval-required",
|
||||
interactionMode: "plan",
|
||||
workspaceSelection: {
|
||||
mode: "worktree",
|
||||
branch: "main",
|
||||
worktreePath: null,
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps legacy content-only drafts and rejects invalid selector state", () => {
|
||||
expect(
|
||||
decodePersistedComposerDrafts({
|
||||
schemaVersion: 1,
|
||||
drafts: {
|
||||
"environment-1:thread-1": DRAFT,
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
"environment-1:thread-1": DRAFT,
|
||||
});
|
||||
|
||||
expect(() =>
|
||||
decodePersistedComposerDrafts({
|
||||
schemaVersion: 1,
|
||||
drafts: {
|
||||
"environment-1:thread-1": {
|
||||
...DRAFT,
|
||||
runtimeMode: "sometimes-safe",
|
||||
},
|
||||
},
|
||||
}),
|
||||
).toThrow();
|
||||
});
|
||||
|
||||
it("clears sent content without clearing the selected model or workspace", () => {
|
||||
const draftKey = "environment-1:thread-1";
|
||||
const draft: ComposerDraft = {
|
||||
text: "send this",
|
||||
attachments: [],
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5.4",
|
||||
options: [{ id: "reasoningEffort", value: "xhigh" }],
|
||||
},
|
||||
workspaceSelection: {
|
||||
mode: "worktree",
|
||||
branch: "main",
|
||||
worktreePath: null,
|
||||
},
|
||||
};
|
||||
|
||||
expect(clearComposerDraftContentState({ [draftKey]: draft }, draftKey)).toEqual({
|
||||
[draftKey]: {
|
||||
...draft,
|
||||
text: "",
|
||||
attachments: [],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("reads the latest selector state synchronously for send", () => {
|
||||
const draftKey = "environment-1:thread-1";
|
||||
const selectedDraft: ComposerDraft = {
|
||||
text: "send this",
|
||||
attachments: [],
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5.4",
|
||||
options: [{ id: "reasoningEffort", value: "xhigh" }],
|
||||
},
|
||||
};
|
||||
appAtomRegistry.set(composerDraftsAtom, { [draftKey]: selectedDraft });
|
||||
|
||||
expect(getComposerDraftSnapshot(draftKey)).toEqual(selectedDraft);
|
||||
});
|
||||
|
||||
it("removes only drafts owned by the selected environment", () => {
|
||||
const environmentId = EnvironmentId.make("environment-cloud");
|
||||
const retainedEnvironmentId = EnvironmentId.make("environment-local");
|
||||
@@ -17,12 +139,15 @@ describe("mobile composer drafts", () => {
|
||||
removeComposerDraftsForEnvironment(
|
||||
{
|
||||
[`${environmentId}:thread-cloud`]: DRAFT,
|
||||
[`new-task:${environmentId}:project-cloud`]: DRAFT,
|
||||
[`${retainedEnvironmentId}:thread-local`]: DRAFT,
|
||||
[`new-task:${retainedEnvironmentId}:project-local`]: DRAFT,
|
||||
},
|
||||
environmentId,
|
||||
),
|
||||
).toEqual({
|
||||
[`${retainedEnvironmentId}:thread-local`]: DRAFT,
|
||||
[`new-task:${retainedEnvironmentId}:project-local`]: DRAFT,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,9 +1,18 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import {
|
||||
ModelSelection as ModelSelectionSchema,
|
||||
ProviderInteractionMode as ProviderInteractionModeSchema,
|
||||
RuntimeMode as RuntimeModeSchema,
|
||||
type EnvironmentId,
|
||||
type ModelSelection,
|
||||
type ProviderInteractionMode,
|
||||
type RuntimeMode,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { useEffect } from "react";
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
|
||||
import { DraftComposerImageAttachmentSchema } from "../lib/composer-image-schema";
|
||||
import type { DraftComposerImageAttachment } from "../lib/composerImages";
|
||||
import { appAtomRegistry } from "./atom-registry";
|
||||
|
||||
@@ -29,13 +38,47 @@ export class ComposerDraftPersistenceError extends Schema.TaggedErrorClass<Compo
|
||||
export interface ComposerDraft {
|
||||
readonly text: string;
|
||||
readonly attachments: ReadonlyArray<DraftComposerImageAttachment>;
|
||||
readonly modelSelection?: ModelSelection;
|
||||
readonly runtimeMode?: RuntimeMode;
|
||||
readonly interactionMode?: ProviderInteractionMode;
|
||||
readonly workspaceSelection?: ComposerDraftWorkspaceSelection;
|
||||
}
|
||||
|
||||
interface PersistedComposerDrafts {
|
||||
readonly schemaVersion: typeof COMPOSER_DRAFTS_SCHEMA_VERSION;
|
||||
readonly drafts: Record<string, ComposerDraft>;
|
||||
export interface ComposerDraftWorkspaceSelection {
|
||||
readonly mode: "local" | "worktree";
|
||||
readonly branch: string | null;
|
||||
readonly worktreePath: string | null;
|
||||
}
|
||||
|
||||
export type ComposerDraftSettingsUpdate = Pick<
|
||||
ComposerDraft,
|
||||
"modelSelection" | "runtimeMode" | "interactionMode" | "workspaceSelection"
|
||||
>;
|
||||
|
||||
const ComposerDraftWorkspaceSelectionSchema = Schema.Struct({
|
||||
mode: Schema.Literals(["local", "worktree"]),
|
||||
branch: Schema.NullOr(Schema.String),
|
||||
worktreePath: Schema.NullOr(Schema.String),
|
||||
});
|
||||
|
||||
const ComposerDraftSchema = Schema.Struct({
|
||||
text: Schema.String,
|
||||
attachments: Schema.Array(DraftComposerImageAttachmentSchema),
|
||||
modelSelection: Schema.optional(ModelSelectionSchema),
|
||||
runtimeMode: Schema.optional(RuntimeModeSchema),
|
||||
interactionMode: Schema.optional(ProviderInteractionModeSchema),
|
||||
workspaceSelection: Schema.optional(ComposerDraftWorkspaceSelectionSchema),
|
||||
});
|
||||
|
||||
const PersistedComposerDraftsSchema = Schema.Struct({
|
||||
schemaVersion: Schema.Literal(COMPOSER_DRAFTS_SCHEMA_VERSION),
|
||||
drafts: Schema.Record(Schema.String, ComposerDraftSchema),
|
||||
});
|
||||
|
||||
const decodePersistedComposerDraftsDocument = Schema.decodeUnknownSync(
|
||||
PersistedComposerDraftsSchema,
|
||||
);
|
||||
|
||||
const EMPTY_DRAFT: ComposerDraft = {
|
||||
text: "",
|
||||
attachments: [],
|
||||
@@ -54,13 +97,32 @@ function normalizeDraft(draft: ComposerDraft | undefined): ComposerDraft {
|
||||
return EMPTY_DRAFT;
|
||||
}
|
||||
return {
|
||||
...draft,
|
||||
text: draft.text,
|
||||
attachments: draft.attachments,
|
||||
};
|
||||
}
|
||||
|
||||
export function getComposerDraftSnapshot(draftKey: string): ComposerDraft {
|
||||
return normalizeDraft(appAtomRegistry.get(composerDraftsAtom)[draftKey]);
|
||||
}
|
||||
|
||||
function isEmptyDraft(draft: ComposerDraft): boolean {
|
||||
return draft.text.length === 0 && draft.attachments.length === 0;
|
||||
return (
|
||||
draft.text.length === 0 &&
|
||||
draft.attachments.length === 0 &&
|
||||
draft.modelSelection === undefined &&
|
||||
draft.runtimeMode === undefined &&
|
||||
draft.interactionMode === undefined &&
|
||||
draft.workspaceSelection === undefined
|
||||
);
|
||||
}
|
||||
|
||||
export function decodePersistedComposerDrafts(value: unknown): Record<string, ComposerDraft> {
|
||||
const parsed = decodePersistedComposerDraftsDocument(value);
|
||||
return Object.fromEntries(
|
||||
Object.entries(parsed.drafts).filter(([, draft]) => !isEmptyDraft(draft)),
|
||||
);
|
||||
}
|
||||
|
||||
async function getComposerDraftsFile() {
|
||||
@@ -80,20 +142,7 @@ async function loadPersistedComposerDrafts(): Promise<Record<string, ComposerDra
|
||||
operation = "read";
|
||||
const raw = await file.text();
|
||||
operation = "decode";
|
||||
const parsed = JSON.parse(raw) as Partial<PersistedComposerDrafts>;
|
||||
if (parsed.schemaVersion !== COMPOSER_DRAFTS_SCHEMA_VERSION || !parsed.drafts) {
|
||||
return {};
|
||||
}
|
||||
return Object.fromEntries(
|
||||
Object.entries(parsed.drafts).filter((entry): entry is [string, ComposerDraft] => {
|
||||
const draft = entry[1];
|
||||
return (
|
||||
typeof draft?.text === "string" &&
|
||||
Array.isArray(draft.attachments) &&
|
||||
!isEmptyDraft(draft)
|
||||
);
|
||||
}),
|
||||
);
|
||||
return decodePersistedComposerDrafts(JSON.parse(raw) as unknown);
|
||||
} catch (cause) {
|
||||
console.warn(
|
||||
"[composer-drafts] ignored persisted draft failure",
|
||||
@@ -116,10 +165,10 @@ async function writePersistedComposerDrafts(drafts: Record<string, ComposerDraft
|
||||
const nonEmptyDrafts = Object.fromEntries(
|
||||
Object.entries(drafts).filter(([, draft]) => !isEmptyDraft(draft)),
|
||||
);
|
||||
const document: PersistedComposerDrafts = {
|
||||
const document = {
|
||||
schemaVersion: COMPOSER_DRAFTS_SCHEMA_VERSION,
|
||||
drafts: nonEmptyDrafts,
|
||||
};
|
||||
} as const;
|
||||
const encoded = JSON.stringify(document);
|
||||
operation = "write";
|
||||
if (!file.exists) {
|
||||
@@ -282,6 +331,55 @@ export function removeComposerDraftAttachment(draftKey: string, imageId: string)
|
||||
});
|
||||
}
|
||||
|
||||
export function updateComposerDraftSettings(
|
||||
draftKey: string,
|
||||
settings: Partial<ComposerDraftSettingsUpdate>,
|
||||
): void {
|
||||
updateComposerDrafts((current) => {
|
||||
const draft = {
|
||||
...normalizeDraft(current[draftKey]),
|
||||
...settings,
|
||||
};
|
||||
if (isEmptyDraft(draft)) {
|
||||
const next = { ...current };
|
||||
delete next[draftKey];
|
||||
return next;
|
||||
}
|
||||
return {
|
||||
...current,
|
||||
[draftKey]: draft,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export function clearComposerDraftContentState(
|
||||
current: Record<string, ComposerDraft>,
|
||||
draftKey: string,
|
||||
): Record<string, ComposerDraft> {
|
||||
const existing = current[draftKey];
|
||||
if (!existing) {
|
||||
return current;
|
||||
}
|
||||
const draft = {
|
||||
...existing,
|
||||
text: "",
|
||||
attachments: [],
|
||||
};
|
||||
if (isEmptyDraft(draft)) {
|
||||
const next = { ...current };
|
||||
delete next[draftKey];
|
||||
return next;
|
||||
}
|
||||
return {
|
||||
...current,
|
||||
[draftKey]: draft,
|
||||
};
|
||||
}
|
||||
|
||||
export function clearComposerDraftContent(draftKey: string): void {
|
||||
updateComposerDrafts((current) => clearComposerDraftContentState(current, draftKey));
|
||||
}
|
||||
|
||||
export function clearComposerDraft(draftKey: string): void {
|
||||
updateComposerDrafts((current) => {
|
||||
if (!current[draftKey]) {
|
||||
@@ -298,8 +396,12 @@ export function removeComposerDraftsForEnvironment(
|
||||
environmentId: EnvironmentId,
|
||||
): Record<string, ComposerDraft> {
|
||||
const environmentPrefix = `${environmentId}:`;
|
||||
const newTaskPrefix = `new-task:${environmentId}:`;
|
||||
return Object.fromEntries(
|
||||
Object.entries(drafts).filter(([draftKey]) => !draftKey.startsWith(environmentPrefix)),
|
||||
Object.entries(drafts).filter(
|
||||
([draftKey]) =>
|
||||
!draftKey.startsWith(environmentPrefix) && !draftKey.startsWith(newTaskPrefix),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,15 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { useCallback, useEffect, useMemo } from "react";
|
||||
|
||||
import { CommandId, MessageId, type EnvironmentId, type ThreadId } from "@t3tools/contracts";
|
||||
import {
|
||||
CommandId,
|
||||
MessageId,
|
||||
type EnvironmentId,
|
||||
type ModelSelection,
|
||||
type ProviderInteractionMode,
|
||||
type RuntimeMode,
|
||||
type ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors";
|
||||
import { deriveActiveWorkStartedAt } from "@t3tools/shared/orchestrationTiming";
|
||||
|
||||
@@ -18,11 +26,13 @@ import { appAtomRegistry } from "../state/atom-registry";
|
||||
import {
|
||||
appendComposerDraftAttachments,
|
||||
appendComposerDraftText,
|
||||
clearComposerDraft,
|
||||
clearComposerDraftContent,
|
||||
composerDraftsAtom,
|
||||
ensureComposerDraftsLoaded,
|
||||
getComposerDraftSnapshot,
|
||||
removeComposerDraftAttachment,
|
||||
setComposerDraftText,
|
||||
updateComposerDraftSettings,
|
||||
useComposerDraft,
|
||||
} from "./use-composer-drafts";
|
||||
import { setPendingConnectionError } from "../state/use-remote-environment-registry";
|
||||
@@ -30,7 +40,6 @@ import { useSelectedThreadDetail } from "../state/use-thread-detail";
|
||||
import { useThreadSelection } from "../state/use-thread-selection";
|
||||
import { enqueueThreadOutboxMessage } from "./thread-outbox";
|
||||
import { useThreadOutboxMessages } from "./use-thread-outbox";
|
||||
import { dispatchingQueuedMessageIdAtom } from "./use-thread-outbox-drain";
|
||||
|
||||
export function appendReviewCommentToDraft(input: {
|
||||
readonly environmentId: EnvironmentId;
|
||||
@@ -67,7 +76,6 @@ export function useThreadComposerState() {
|
||||
const { selectedThread: selectedThreadShell } = useThreadSelection();
|
||||
const selectedThreadDetail = useSelectedThreadDetail();
|
||||
const composerDrafts = useAtomValue(composerDraftsAtom);
|
||||
const dispatchingQueuedMessageId = useAtomValue(dispatchingQueuedMessageIdAtom);
|
||||
const queuedMessagesByThreadKey = useThreadOutboxMessages();
|
||||
|
||||
useEffect(() => {
|
||||
@@ -81,23 +89,19 @@ export function useThreadComposerState() {
|
||||
() => (selectedThreadKey ? (queuedMessagesByThreadKey[selectedThreadKey] ?? []) : []),
|
||||
[queuedMessagesByThreadKey, selectedThreadKey],
|
||||
);
|
||||
|
||||
const selectedThreadFeed = useMemo(
|
||||
() =>
|
||||
selectedThreadDetail
|
||||
? buildThreadFeed(
|
||||
selectedThreadDetail,
|
||||
selectedThreadQueuedMessages,
|
||||
dispatchingQueuedMessageId,
|
||||
)
|
||||
: [],
|
||||
[dispatchingQueuedMessageId, selectedThreadDetail, selectedThreadQueuedMessages],
|
||||
() => (selectedThreadDetail ? buildThreadFeed(selectedThreadDetail) : []),
|
||||
[selectedThreadDetail],
|
||||
);
|
||||
|
||||
const selectedDraft = selectedThreadKey ? composerDrafts[selectedThreadKey] : null;
|
||||
const draftMessage = selectedDraft?.text ?? "";
|
||||
const draftAttachments = selectedDraft?.attachments ?? [];
|
||||
const selectedThreadQueueCount = selectedThreadQueuedMessages.length;
|
||||
const selectedThread = selectedThreadDetail ?? selectedThreadShell;
|
||||
const modelSelection = selectedDraft?.modelSelection ?? selectedThread?.modelSelection ?? null;
|
||||
const runtimeMode = selectedDraft?.runtimeMode ?? selectedThread?.runtimeMode ?? null;
|
||||
const interactionMode = selectedDraft?.interactionMode ?? selectedThread?.interactionMode ?? null;
|
||||
|
||||
const selectedThreadSessionActivity = useMemo(() => {
|
||||
const selectedThread = selectedThreadDetail ?? selectedThreadShell;
|
||||
@@ -111,7 +115,6 @@ export function useThreadComposerState() {
|
||||
};
|
||||
}, [selectedThreadDetail, selectedThreadShell]);
|
||||
|
||||
const queuedSendStartedAt = selectedThreadQueuedMessages[0]?.createdAt ?? null;
|
||||
const activeWorkStartedAt = useMemo(() => {
|
||||
const selectedThread = selectedThreadDetail ?? selectedThreadShell;
|
||||
if (!selectedThread) {
|
||||
@@ -121,51 +124,52 @@ export function useThreadComposerState() {
|
||||
return deriveActiveWorkStartedAt(
|
||||
selectedThread.latestTurn,
|
||||
selectedThreadSessionActivity,
|
||||
queuedSendStartedAt,
|
||||
null,
|
||||
);
|
||||
}, [
|
||||
queuedSendStartedAt,
|
||||
selectedThreadDetail,
|
||||
selectedThreadSessionActivity,
|
||||
selectedThreadShell,
|
||||
]);
|
||||
}, [selectedThreadDetail, selectedThreadSessionActivity, selectedThreadShell]);
|
||||
|
||||
const selectedThread = selectedThreadDetail ?? selectedThreadShell;
|
||||
const activeThreadBusy =
|
||||
!!selectedThread &&
|
||||
(selectedThread.session?.status === "running" || selectedThread.session?.status === "starting");
|
||||
|
||||
const onSendMessage = useCallback(async () => {
|
||||
if (!selectedThreadShell) {
|
||||
return;
|
||||
return null;
|
||||
}
|
||||
|
||||
const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
|
||||
const draft = composerDrafts[threadKey];
|
||||
const text = (draft?.text ?? "").trim();
|
||||
const attachments = draft?.attachments ?? [];
|
||||
const draft = getComposerDraftSnapshot(threadKey);
|
||||
const thread = selectedThreadDetail ?? selectedThreadShell;
|
||||
const text = draft.text.trim();
|
||||
const attachments = draft.attachments;
|
||||
if (text.length === 0 && attachments.length === 0) {
|
||||
return;
|
||||
return null;
|
||||
}
|
||||
|
||||
const metadata = makeQueuedMessageMetadata();
|
||||
const messageId = MessageId.make(metadata.messageId);
|
||||
try {
|
||||
await enqueueThreadOutboxMessage({
|
||||
environmentId: selectedThreadShell.environmentId,
|
||||
threadId: selectedThreadShell.id,
|
||||
messageId: MessageId.make(metadata.messageId),
|
||||
messageId,
|
||||
commandId: CommandId.make(metadata.commandId),
|
||||
text,
|
||||
attachments,
|
||||
modelSelection: draft.modelSelection ?? thread.modelSelection,
|
||||
runtimeMode: draft.runtimeMode ?? thread.runtimeMode,
|
||||
interactionMode: draft.interactionMode ?? thread.interactionMode,
|
||||
createdAt: metadata.createdAt,
|
||||
});
|
||||
clearComposerDraft(threadKey);
|
||||
clearComposerDraftContent(threadKey);
|
||||
return messageId;
|
||||
} catch (error) {
|
||||
setPendingConnectionError(
|
||||
error instanceof Error ? error.message : "Failed to save the queued message.",
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}, [composerDrafts, selectedThreadShell]);
|
||||
}, [selectedThreadDetail, selectedThreadShell]);
|
||||
|
||||
const onChangeDraftMessage = useCallback(
|
||||
(value: string) => {
|
||||
@@ -255,12 +259,45 @@ export function useThreadComposerState() {
|
||||
[selectedThreadShell],
|
||||
);
|
||||
|
||||
const onUpdateModelSelection = useCallback(
|
||||
(value: ModelSelection) => {
|
||||
if (!selectedThreadKey) {
|
||||
return;
|
||||
}
|
||||
updateComposerDraftSettings(selectedThreadKey, { modelSelection: value });
|
||||
},
|
||||
[selectedThreadKey],
|
||||
);
|
||||
|
||||
const onUpdateRuntimeMode = useCallback(
|
||||
(value: RuntimeMode) => {
|
||||
if (!selectedThreadKey) {
|
||||
return;
|
||||
}
|
||||
updateComposerDraftSettings(selectedThreadKey, { runtimeMode: value });
|
||||
},
|
||||
[selectedThreadKey],
|
||||
);
|
||||
|
||||
const onUpdateInteractionMode = useCallback(
|
||||
(value: ProviderInteractionMode) => {
|
||||
if (!selectedThreadKey) {
|
||||
return;
|
||||
}
|
||||
updateComposerDraftSettings(selectedThreadKey, { interactionMode: value });
|
||||
},
|
||||
[selectedThreadKey],
|
||||
);
|
||||
|
||||
return {
|
||||
selectedThreadFeed,
|
||||
selectedThreadQueueCount,
|
||||
activeWorkStartedAt,
|
||||
draftMessage,
|
||||
draftAttachments,
|
||||
modelSelection,
|
||||
runtimeMode,
|
||||
interactionMode,
|
||||
activeThreadBusy,
|
||||
onChangeDraftMessage,
|
||||
onPickDraftImages,
|
||||
@@ -268,5 +305,8 @@ export function useThreadComposerState() {
|
||||
onNativePasteImages,
|
||||
onRemoveDraftImage,
|
||||
onSendMessage,
|
||||
onUpdateModelSelection,
|
||||
onUpdateRuntimeMode,
|
||||
onUpdateInteractionMode,
|
||||
};
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
|
||||
import { type MessageId } from "@t3tools/contracts";
|
||||
import type { AtomCommandResult } from "@t3tools/client-runtime/state/runtime";
|
||||
import { CommandId, type MessageId } from "@t3tools/contracts";
|
||||
import * as Cause from "effect/Cause";
|
||||
import { AsyncResult, Atom } from "effect/unstable/reactivity";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
@@ -10,10 +11,13 @@ import { appAtomRegistry } from "./atom-registry";
|
||||
import { useThreadShells } from "./entities";
|
||||
import { ensureThreadOutboxLoaded, removeThreadOutboxMessage } from "./thread-outbox";
|
||||
import {
|
||||
modelSelectionsEqual,
|
||||
resolveThreadOutboxDeliveryAction,
|
||||
shouldRetryThreadOutboxDelivery,
|
||||
resolveThreadOutboxFailureAction,
|
||||
resolveQueuedThreadSettings,
|
||||
threadOutboxRetryDelayMs,
|
||||
type QueuedThreadMessage,
|
||||
type ThreadOutboxCommandStage,
|
||||
} from "./thread-outbox-model";
|
||||
import { threadEnvironment } from "./threads";
|
||||
import { useAtomCommand } from "./use-atom-command";
|
||||
@@ -44,8 +48,21 @@ function findThread(
|
||||
);
|
||||
}
|
||||
|
||||
function settingsCommandId(message: QueuedThreadMessage, setting: string): CommandId {
|
||||
return CommandId.make(`${message.commandId}:${setting}`);
|
||||
}
|
||||
|
||||
export function useThreadOutboxDrain(): void {
|
||||
const startTurn = useAtomCommand(threadEnvironment.startTurn, { reportFailure: false });
|
||||
const updateThreadMetadata = useAtomCommand(threadEnvironment.updateMetadata, {
|
||||
reportFailure: false,
|
||||
});
|
||||
const setThreadRuntimeMode = useAtomCommand(threadEnvironment.setRuntimeMode, {
|
||||
reportFailure: false,
|
||||
});
|
||||
const setThreadInteractionMode = useAtomCommand(threadEnvironment.setInteractionMode, {
|
||||
reportFailure: false,
|
||||
});
|
||||
const dispatchingQueuedMessageId = useAtomValue(dispatchingQueuedMessageIdAtom);
|
||||
const queuedMessagesByThreadKey = useThreadOutboxMessages();
|
||||
const shellStatuses = useThreadOutboxShellStatuses();
|
||||
@@ -68,6 +85,98 @@ export function useThreadOutboxDrain(): void {
|
||||
|
||||
const sendQueuedMessage = useCallback(
|
||||
async (queuedMessage: QueuedThreadMessage, thread: EnvironmentThreadShell) => {
|
||||
const settings = resolveQueuedThreadSettings(queuedMessage, thread);
|
||||
const reportFailure = (
|
||||
commandResult: AtomCommandResult<unknown, unknown>,
|
||||
stage: ThreadOutboxCommandStage,
|
||||
): boolean => {
|
||||
if (!AsyncResult.isFailure(commandResult)) {
|
||||
return false;
|
||||
}
|
||||
const action = resolveThreadOutboxFailureAction({
|
||||
stage,
|
||||
error: Cause.squash(commandResult.cause),
|
||||
interrupted: Cause.hasInterruptsOnly(commandResult.cause),
|
||||
});
|
||||
const retry = action === "retry";
|
||||
console.warn("[thread-outbox] queued message delivery failed", {
|
||||
environmentId: queuedMessage.environmentId,
|
||||
threadId: queuedMessage.threadId,
|
||||
messageId: queuedMessage.messageId,
|
||||
stage,
|
||||
cause: commandResult.cause,
|
||||
retry,
|
||||
});
|
||||
return retry;
|
||||
};
|
||||
const completeDelivery = async (
|
||||
deliveryResult: AtomCommandResult<unknown, unknown>,
|
||||
): Promise<boolean> => {
|
||||
if (reportFailure(deliveryResult, "start-turn")) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
await removeThreadOutboxMessage(queuedMessage);
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.warn("[thread-outbox] failed to remove delivered queued message", {
|
||||
environmentId: queuedMessage.environmentId,
|
||||
threadId: queuedMessage.threadId,
|
||||
messageId: queuedMessage.messageId,
|
||||
error,
|
||||
});
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
if (!modelSelectionsEqual(settings.modelSelection, thread.modelSelection)) {
|
||||
const updateResult = await updateThreadMetadata({
|
||||
environmentId: queuedMessage.environmentId,
|
||||
input: {
|
||||
commandId: settingsCommandId(queuedMessage, "model-selection"),
|
||||
threadId: queuedMessage.threadId,
|
||||
modelSelection: settings.modelSelection,
|
||||
},
|
||||
});
|
||||
if (AsyncResult.isFailure(updateResult)) {
|
||||
reportFailure(updateResult, "settings-sync");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (settings.runtimeMode !== thread.runtimeMode) {
|
||||
const runtimeResult = await setThreadRuntimeMode({
|
||||
environmentId: queuedMessage.environmentId,
|
||||
input: {
|
||||
commandId: settingsCommandId(queuedMessage, "runtime-mode"),
|
||||
threadId: queuedMessage.threadId,
|
||||
runtimeMode: settings.runtimeMode,
|
||||
createdAt: queuedMessage.createdAt,
|
||||
},
|
||||
});
|
||||
if (AsyncResult.isFailure(runtimeResult)) {
|
||||
reportFailure(runtimeResult, "settings-sync");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (settings.interactionMode !== thread.interactionMode) {
|
||||
const interactionResult = await setThreadInteractionMode({
|
||||
environmentId: queuedMessage.environmentId,
|
||||
input: {
|
||||
commandId: settingsCommandId(queuedMessage, "interaction-mode"),
|
||||
threadId: queuedMessage.threadId,
|
||||
interactionMode: settings.interactionMode,
|
||||
createdAt: queuedMessage.createdAt,
|
||||
},
|
||||
});
|
||||
if (AsyncResult.isFailure(interactionResult)) {
|
||||
reportFailure(interactionResult, "settings-sync");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
const deliveryResult = await startTurn({
|
||||
environmentId: queuedMessage.environmentId,
|
||||
input: {
|
||||
@@ -79,41 +188,15 @@ export function useThreadOutboxDrain(): void {
|
||||
text: queuedMessage.text,
|
||||
attachments: queuedMessage.attachments,
|
||||
},
|
||||
runtimeMode: thread.runtimeMode,
|
||||
interactionMode: thread.interactionMode,
|
||||
modelSelection: settings.modelSelection,
|
||||
runtimeMode: settings.runtimeMode,
|
||||
interactionMode: settings.interactionMode,
|
||||
createdAt: queuedMessage.createdAt,
|
||||
},
|
||||
});
|
||||
if (AsyncResult.isFailure(deliveryResult)) {
|
||||
const error = Cause.squash(deliveryResult.cause);
|
||||
const retry =
|
||||
Cause.hasInterruptsOnly(deliveryResult.cause) || shouldRetryThreadOutboxDelivery(error);
|
||||
console.warn("[thread-outbox] queued message delivery failed", {
|
||||
environmentId: queuedMessage.environmentId,
|
||||
threadId: queuedMessage.threadId,
|
||||
messageId: queuedMessage.messageId,
|
||||
cause: deliveryResult.cause,
|
||||
retry,
|
||||
});
|
||||
if (retry) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
await removeThreadOutboxMessage(queuedMessage);
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.warn("[thread-outbox] failed to remove delivered queued message", {
|
||||
environmentId: queuedMessage.environmentId,
|
||||
threadId: queuedMessage.threadId,
|
||||
messageId: queuedMessage.messageId,
|
||||
error,
|
||||
});
|
||||
return false;
|
||||
}
|
||||
return completeDelivery(deliveryResult);
|
||||
},
|
||||
[startTurn],
|
||||
[setThreadInteractionMode, setThreadRuntimeMode, startTurn, updateThreadMetadata],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
|
||||
@@ -19,6 +19,23 @@ const emitInterleavedAssistantToolCalls =
|
||||
const emitGenericToolPlaceholders = process.env.T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS === "1";
|
||||
const emitAskQuestion = process.env.T3_ACP_EMIT_ASK_QUESTION === "1";
|
||||
const emitXAiAskUserQuestion = process.env.T3_ACP_EMIT_XAI_ASK_USER_QUESTION === "1";
|
||||
const emitXAiPromptCompleteThenHang = process.env.T3_ACP_EMIT_XAI_PROMPT_COMPLETE_THEN_HANG === "1";
|
||||
const emitForeignSessionUpdates = process.env.T3_ACP_EMIT_FOREIGN_SESSION_UPDATES === "1";
|
||||
const hangPromptForever = process.env.T3_ACP_HANG_PROMPT_FOREVER === "1";
|
||||
const hangFirstPromptForever = process.env.T3_ACP_HANG_FIRST_PROMPT_FOREVER === "1";
|
||||
const emitLateUpdateAfterCancel = process.env.T3_ACP_EMIT_LATE_UPDATE_AFTER_CANCEL === "1";
|
||||
const omitXAiPromptCompleteStopReason =
|
||||
process.env.T3_ACP_OMIT_XAI_PROMPT_COMPLETE_STOP_REASON === "1";
|
||||
const failLoadSession = process.env.T3_ACP_FAIL_LOAD_SESSION === "1";
|
||||
const emitLoadReplay = process.env.T3_ACP_EMIT_LOAD_REPLAY === "1";
|
||||
const hangLoadSessionAfterReplay = process.env.T3_ACP_HANG_LOAD_SESSION_AFTER_REPLAY === "1";
|
||||
const delayLoadSessionAfterReplay = process.env.T3_ACP_DELAY_LOAD_SESSION_AFTER_REPLAY === "1";
|
||||
const loadSessionDelayMs = Number(process.env.T3_ACP_LOAD_SESSION_DELAY_MS ?? "5000");
|
||||
const emitStaleXAiPromptCompleteBeforeSecondHang =
|
||||
process.env.T3_ACP_EMIT_STALE_XAI_PROMPT_COMPLETE_BEFORE_SECOND_HANG === "1";
|
||||
const emitOverlappingXAiPromptCompleteOutOfOrder =
|
||||
process.env.T3_ACP_EMIT_OVERLAPPING_XAI_PROMPT_COMPLETE_OUT_OF_ORDER === "1";
|
||||
const failPrompt = process.env.T3_ACP_FAIL_PROMPT === "1";
|
||||
const failSetConfigOption = process.env.T3_ACP_FAIL_SET_CONFIG_OPTION === "1";
|
||||
const exitOnSetConfigOption = process.env.T3_ACP_EXIT_ON_SET_CONFIG_OPTION === "1";
|
||||
const promptResponseText = process.env.T3_ACP_PROMPT_RESPONSE_TEXT;
|
||||
@@ -36,8 +53,21 @@ let parameterizedModelPicker = false;
|
||||
let currentReasoning = "medium";
|
||||
let currentContext = "272k";
|
||||
let currentFast = false;
|
||||
let promptCount = 0;
|
||||
let overlappingFirstPromptId: string | undefined;
|
||||
const cancelledSessions = new Set<string>();
|
||||
|
||||
function promptIdFromRequestMeta(
|
||||
request: Pick<AcpSchema.PromptRequest, "_meta">,
|
||||
): string | undefined {
|
||||
const meta = request._meta;
|
||||
if (meta === null || typeof meta !== "object") {
|
||||
return undefined;
|
||||
}
|
||||
const promptId = meta.promptId ?? meta.requestId;
|
||||
return typeof promptId === "string" && promptId.length > 0 ? promptId : undefined;
|
||||
}
|
||||
|
||||
function logExit(reason: string): void {
|
||||
if (!exitLogPath) {
|
||||
return;
|
||||
@@ -45,6 +75,10 @@ function logExit(reason: string): void {
|
||||
NodeFS.appendFileSync(exitLogPath, `${reason}\n`, "utf8");
|
||||
}
|
||||
|
||||
function writeJsonRpcNotification(method: string, params: unknown): void {
|
||||
process.stdout.write(`${JSON.stringify({ jsonrpc: "2.0", method, params })}\n`);
|
||||
}
|
||||
|
||||
process.once("SIGTERM", () => {
|
||||
logExit("SIGTERM");
|
||||
process.exit(0);
|
||||
@@ -284,22 +318,66 @@ const program = Effect.gen(function* () {
|
||||
}),
|
||||
);
|
||||
|
||||
const emitLoadReplayNotifications = (requestedSessionId: string) => {
|
||||
writeJsonRpcNotification("session/update", {
|
||||
_meta: { isReplay: true },
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId: "replay-tool-1",
|
||||
title: "Replay tool",
|
||||
kind: "search",
|
||||
status: "completed",
|
||||
},
|
||||
});
|
||||
writeJsonRpcNotification("session/update", {
|
||||
_meta: { isReplay: true },
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "replayed assistant text" },
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
yield* agent.handleLoadSession((request) =>
|
||||
agent.client
|
||||
.sessionUpdate({
|
||||
sessionId: String(request.sessionId ?? sessionId),
|
||||
Effect.gen(function* () {
|
||||
const requestedSessionId = String(request.sessionId ?? sessionId);
|
||||
if (failLoadSession) {
|
||||
return yield* AcpError.AcpRequestError.internalError("Mock load session failure");
|
||||
}
|
||||
if (hangLoadSessionAfterReplay || delayLoadSessionAfterReplay) {
|
||||
emitLoadReplayNotifications(requestedSessionId);
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "user_message_chunk",
|
||||
content: { type: "text", text: "replay-tail" },
|
||||
},
|
||||
});
|
||||
yield* Effect.sleep(loadSessionDelayMs);
|
||||
return {
|
||||
modes: modeState(),
|
||||
models: modelState(),
|
||||
configOptions: configOptions(),
|
||||
};
|
||||
}
|
||||
if (emitLoadReplay) {
|
||||
emitLoadReplayNotifications(requestedSessionId);
|
||||
}
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "user_message_chunk",
|
||||
content: { type: "text", text: "replay" },
|
||||
},
|
||||
})
|
||||
.pipe(
|
||||
Effect.as({
|
||||
modes: modeState(),
|
||||
models: modelState(),
|
||||
configOptions: configOptions(),
|
||||
}),
|
||||
),
|
||||
});
|
||||
return {
|
||||
modes: modeState(),
|
||||
models: modelState(),
|
||||
configOptions: configOptions(),
|
||||
};
|
||||
}),
|
||||
);
|
||||
|
||||
yield* agent.handleSetSessionModel((request) =>
|
||||
@@ -356,19 +434,152 @@ const program = Effect.gen(function* () {
|
||||
);
|
||||
|
||||
yield* agent.handleCancel(({ sessionId }) =>
|
||||
Effect.sync(() => {
|
||||
cancelledSessions.add(String(sessionId ?? "mock-session-1"));
|
||||
Effect.gen(function* () {
|
||||
const cancelledSessionId = String(sessionId ?? "mock-session-1");
|
||||
cancelledSessions.add(cancelledSessionId);
|
||||
if (emitLateUpdateAfterCancel) {
|
||||
yield* Effect.sleep("50 millis");
|
||||
yield* Effect.sync(() => {
|
||||
writeJsonRpcNotification("session/update", {
|
||||
sessionId: cancelledSessionId,
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "late after cancel" },
|
||||
},
|
||||
});
|
||||
});
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
yield* agent.handlePrompt((request) =>
|
||||
Effect.gen(function* () {
|
||||
const requestedSessionId = String(request.sessionId ?? sessionId);
|
||||
promptCount += 1;
|
||||
|
||||
if (Number.isFinite(promptDelayMs) && promptDelayMs > 0) {
|
||||
yield* Effect.sleep(`${promptDelayMs} millis`);
|
||||
}
|
||||
|
||||
if (failPrompt) {
|
||||
return yield* AcpError.AcpRequestError.internalError("Mock prompt failure");
|
||||
}
|
||||
|
||||
if (emitStaleXAiPromptCompleteBeforeSecondHang && promptCount === 1) {
|
||||
return {
|
||||
stopReason: "end_turn",
|
||||
_meta: {
|
||||
promptId: "mock-stale-xai-prompt-1",
|
||||
requestId: "mock-stale-xai-prompt-1",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
if (emitStaleXAiPromptCompleteBeforeSecondHang && promptCount === 2) {
|
||||
const currentPromptId = promptIdFromRequestMeta(request) ?? "mock-current-xai-prompt-2";
|
||||
writeJsonRpcNotification("_x.ai/session/prompt_complete", {
|
||||
sessionId: requestedSessionId,
|
||||
promptId: "mock-stale-xai-prompt-1",
|
||||
stopReason: "end_turn",
|
||||
agentResult: null,
|
||||
});
|
||||
|
||||
writeJsonRpcNotification("_x.ai/session/prompt_complete", {
|
||||
sessionId: requestedSessionId,
|
||||
promptId: currentPromptId,
|
||||
stopReason: "end_turn",
|
||||
agentResult: null,
|
||||
});
|
||||
|
||||
return yield* Effect.never;
|
||||
}
|
||||
|
||||
if (emitOverlappingXAiPromptCompleteOutOfOrder && promptCount === 1) {
|
||||
overlappingFirstPromptId = promptIdFromRequestMeta(request);
|
||||
return yield* Effect.never;
|
||||
}
|
||||
|
||||
if (emitOverlappingXAiPromptCompleteOutOfOrder && promptCount === 2) {
|
||||
const secondPromptId = promptIdFromRequestMeta(request);
|
||||
if (overlappingFirstPromptId !== undefined && secondPromptId !== undefined) {
|
||||
writeJsonRpcNotification("_x.ai/session/prompt_complete", {
|
||||
sessionId: requestedSessionId,
|
||||
promptId: secondPromptId,
|
||||
stopReason: "end_turn",
|
||||
agentResult: null,
|
||||
});
|
||||
writeJsonRpcNotification("_x.ai/session/prompt_complete", {
|
||||
sessionId: requestedSessionId,
|
||||
promptId: overlappingFirstPromptId,
|
||||
stopReason: "end_turn",
|
||||
agentResult: null,
|
||||
});
|
||||
}
|
||||
return yield* Effect.never;
|
||||
}
|
||||
|
||||
if (hangPromptForever || (hangFirstPromptForever && promptCount === 1)) {
|
||||
return yield* Effect.never;
|
||||
}
|
||||
|
||||
if (emitXAiPromptCompleteThenHang) {
|
||||
writeJsonRpcNotification("session/update", {
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "hello from " },
|
||||
},
|
||||
});
|
||||
|
||||
if (emitForeignSessionUpdates) {
|
||||
writeJsonRpcNotification("session/update", {
|
||||
sessionId: "mock-child-session-1",
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "child before completion" },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
writeJsonRpcNotification("_x.ai/session/prompt_complete", {
|
||||
sessionId: requestedSessionId,
|
||||
promptId: promptIdFromRequestMeta(request) ?? "mock-xai-prompt-1",
|
||||
...(omitXAiPromptCompleteStopReason ? {} : { stopReason: "end_turn" }),
|
||||
agentResult: null,
|
||||
});
|
||||
|
||||
if (emitForeignSessionUpdates) {
|
||||
writeJsonRpcNotification("session/update", {
|
||||
sessionId: "mock-child-session-1",
|
||||
update: {
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId: "child-tool-call-1",
|
||||
title: "Child-only tool",
|
||||
kind: "other",
|
||||
status: "pending",
|
||||
rawInput: {},
|
||||
},
|
||||
});
|
||||
writeJsonRpcNotification("session/update", {
|
||||
sessionId: "mock-child-session-1",
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "child after completion" },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
writeJsonRpcNotification("session/update", {
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "mock" },
|
||||
},
|
||||
});
|
||||
|
||||
return yield* Effect.never;
|
||||
}
|
||||
|
||||
if (emitInterleavedAssistantToolCalls) {
|
||||
const toolCallId = "tool-call-1";
|
||||
|
||||
@@ -599,6 +810,42 @@ const program = Effect.gen(function* () {
|
||||
return { stopReason: "end_turn" };
|
||||
}
|
||||
|
||||
if (emitForeignSessionUpdates) {
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "root before child" },
|
||||
},
|
||||
});
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: "mock-child-session-1",
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "child content" },
|
||||
},
|
||||
});
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: "mock-child-session-1",
|
||||
update: {
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId: "child-tool-call-1",
|
||||
title: "Child-only tool",
|
||||
kind: "other",
|
||||
status: "pending",
|
||||
rawInput: {},
|
||||
},
|
||||
});
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: " root after child" },
|
||||
},
|
||||
});
|
||||
return { stopReason: "end_turn" };
|
||||
}
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
|
||||
@@ -44,8 +44,8 @@ const failingSessionLookupRepositoryLayer = Layer.succeed(AuthSessions.AuthSessi
|
||||
create: () => Effect.void,
|
||||
getById: () => Effect.fail(repositoryFailure),
|
||||
listActive: () => Effect.succeed([]),
|
||||
revoke: () => Effect.succeed(false),
|
||||
revokeAllExcept: () => Effect.succeed([]),
|
||||
revoke: () => Effect.fail(repositoryFailure),
|
||||
revokeAllExcept: () => Effect.fail(repositoryFailure),
|
||||
setLastConnectedAt: () => Effect.void,
|
||||
});
|
||||
|
||||
@@ -104,11 +104,29 @@ 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", () =>
|
||||
@@ -145,7 +163,52 @@ it.layer(NodeServices.layer)("SessionStore.layer", (it) => {
|
||||
yield* TestClock.adjust(Duration.seconds(2));
|
||||
|
||||
const error = yield* Effect.flip(sessions.verifyWebSocketToken(websocket.token));
|
||||
expect(error.message).toContain("expired");
|
||||
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,
|
||||
);
|
||||
}
|
||||
}).pipe(Effect.provide(Layer.merge(makeSessionStoreLayer(), TestClock.layer()))),
|
||||
);
|
||||
|
||||
@@ -173,12 +236,16 @@ 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(
|
||||
@@ -194,7 +261,16 @@ it.layer(NodeServices.layer)("SessionStore.layer", (it) => {
|
||||
expect(revokedCount).toBe(1);
|
||||
expect(afterRevoke).toHaveLength(1);
|
||||
expect(afterRevoke[0]?.sessionId).toBe(administrative.sessionId);
|
||||
expect(revokedClient.message).toContain("revoked");
|
||||
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);
|
||||
}
|
||||
}).pipe(Effect.provide(makeSessionStoreLayer())),
|
||||
);
|
||||
|
||||
|
||||
@@ -7,7 +7,6 @@ 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";
|
||||
@@ -93,7 +92,11 @@ 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.";
|
||||
@@ -102,7 +105,9 @@ 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.";
|
||||
@@ -111,7 +116,10 @@ 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.";
|
||||
@@ -120,7 +128,10 @@ 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";
|
||||
@@ -158,7 +169,11 @@ 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.";
|
||||
@@ -167,7 +182,9 @@ 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.";
|
||||
@@ -176,7 +193,11 @@ 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.";
|
||||
@@ -185,7 +206,10 @@ 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.";
|
||||
@@ -218,6 +242,7 @@ const sessionCredentialInternalErrorContext = {
|
||||
export class SessionClaimsEncodingError extends Schema.TaggedErrorClass<SessionClaimsEncodingError>()(
|
||||
"SessionClaimsEncodingError",
|
||||
{
|
||||
sessionId: AuthSessionId,
|
||||
operation: Schema.Literals(["encode_session_claims", "encode_websocket_claims"]),
|
||||
...sessionCredentialInternalErrorContext,
|
||||
},
|
||||
@@ -230,6 +255,7 @@ export class SessionClaimsEncodingError extends Schema.TaggedErrorClass<SessionC
|
||||
export class SessionCredentialIssueError extends Schema.TaggedErrorClass<SessionCredentialIssueError>()(
|
||||
"SessionCredentialIssueError",
|
||||
{
|
||||
sessionId: Schema.optional(AuthSessionId),
|
||||
...sessionCredentialInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
@@ -241,6 +267,7 @@ export class SessionCredentialIssueError extends Schema.TaggedErrorClass<Session
|
||||
export class SessionCredentialVerificationError extends Schema.TaggedErrorClass<SessionCredentialVerificationError>()(
|
||||
"SessionCredentialVerificationError",
|
||||
{
|
||||
sessionId: AuthSessionId,
|
||||
...sessionCredentialInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
@@ -252,6 +279,7 @@ export class SessionCredentialVerificationError extends Schema.TaggedErrorClass<
|
||||
export class WebSocketTokenIssueError extends Schema.TaggedErrorClass<WebSocketTokenIssueError>()(
|
||||
"WebSocketTokenIssueError",
|
||||
{
|
||||
sessionId: AuthSessionId,
|
||||
...sessionCredentialInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
@@ -263,6 +291,7 @@ export class WebSocketTokenIssueError extends Schema.TaggedErrorClass<WebSocketT
|
||||
export class WebSocketTokenVerificationError extends Schema.TaggedErrorClass<WebSocketTokenVerificationError>()(
|
||||
"WebSocketTokenVerificationError",
|
||||
{
|
||||
sessionId: AuthSessionId,
|
||||
...sessionCredentialInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
@@ -285,6 +314,7 @@ export class ActiveSessionsListError extends Schema.TaggedErrorClass<ActiveSessi
|
||||
export class SessionRevocationError extends Schema.TaggedErrorClass<SessionRevocationError>()(
|
||||
"SessionRevocationError",
|
||||
{
|
||||
sessionId: AuthSessionId,
|
||||
...sessionCredentialInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
@@ -296,6 +326,7 @@ export class SessionRevocationError extends Schema.TaggedErrorClass<SessionRevoc
|
||||
export class OtherSessionsRevocationError extends Schema.TaggedErrorClass<OtherSessionsRevocationError>()(
|
||||
"OtherSessionsRevocationError",
|
||||
{
|
||||
currentSessionId: AuthSessionId,
|
||||
...sessionCredentialInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
@@ -539,7 +570,11 @@ 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);
|
||||
const sessionId = AuthSessionId.make(
|
||||
yield* crypto.randomUUIDv4.pipe(
|
||||
Effect.mapError((cause) => new SessionCredentialIssueError({ cause })),
|
||||
),
|
||||
);
|
||||
const issuedAt = yield* DateTime.now;
|
||||
const expiresAt = DateTime.add(issuedAt, {
|
||||
milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_SESSION_TTL),
|
||||
@@ -559,27 +594,37 @@ export const make = Effect.gen(function* () {
|
||||
const encodedPayload = yield* encodeClaims(claims).pipe(
|
||||
Effect.map(base64UrlEncode),
|
||||
Effect.mapError(
|
||||
(cause) => new SessionClaimsEncodingError({ operation: "encode_session_claims", cause }),
|
||||
(cause) =>
|
||||
new SessionCredentialIssueError({
|
||||
sessionId,
|
||||
cause: new SessionClaimsEncodingError({
|
||||
sessionId,
|
||||
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,
|
||||
});
|
||||
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* emitUpsert(
|
||||
toAuthClientSession({
|
||||
sessionId,
|
||||
@@ -604,7 +649,6 @@ 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")(
|
||||
@@ -623,22 +667,37 @@ export const make = Effect.gen(function* () {
|
||||
Effect.mapError((cause) => new InvalidSessionTokenPayloadError({ cause })),
|
||||
);
|
||||
|
||||
const now = yield* Clock.currentTimeMillis;
|
||||
if (claims.exp <= now) {
|
||||
return yield* new SessionTokenExpiredError({});
|
||||
}
|
||||
|
||||
const row = yield* authSessions.getById({ sessionId: claims.sid });
|
||||
if (Option.isNone(row)) {
|
||||
return yield* new UnknownSessionTokenError({});
|
||||
}
|
||||
if (row.value.revokedAt !== null) {
|
||||
return yield* new SessionTokenRevokedError({});
|
||||
}
|
||||
|
||||
const observedAt = yield* DateTime.now;
|
||||
const expiresAt = DateTime.make(claims.exp);
|
||||
if (Option.isNone(expiresAt)) {
|
||||
return yield* new InvalidSessionExpirationClaimError({});
|
||||
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 row = yield* authSessions
|
||||
.getById({ sessionId: claims.sid })
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new SessionCredentialVerificationError({ sessionId: claims.sid, cause }),
|
||||
),
|
||||
);
|
||||
if (Option.isNone(row)) {
|
||||
return yield* new UnknownSessionTokenError({ sessionId: claims.sid });
|
||||
}
|
||||
if (row.value.revokedAt !== null) {
|
||||
return yield* new SessionTokenRevokedError({
|
||||
sessionId: claims.sid,
|
||||
revokedAt: row.value.revokedAt,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -652,95 +711,111 @@ 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 SessionClaimsEncodingError({ operation: "encode_websocket_claims", cause }),
|
||||
),
|
||||
);
|
||||
const signature = signPayload(encodedPayload, signingSecret);
|
||||
return {
|
||||
token: `${encodedPayload}.${signature}`,
|
||||
expiresAt,
|
||||
};
|
||||
},
|
||||
Effect.mapError((cause) => new WebSocketTokenIssueError({ cause })),
|
||||
);
|
||||
)(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,
|
||||
};
|
||||
});
|
||||
|
||||
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 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 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),
|
||||
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,
|
||||
subject: row.value.subject,
|
||||
scopes: row.value.scopes,
|
||||
} satisfies VerifiedSession;
|
||||
},
|
||||
Effect.mapError((cause) =>
|
||||
isSessionCredentialInvalidError(cause)
|
||||
? cause
|
||||
: new WebSocketTokenVerificationError({ cause }),
|
||||
),
|
||||
);
|
||||
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 listActive: SessionStore["Service"]["listActive"] = Effect.fn("SessionStore.listActive")(
|
||||
function* () {
|
||||
@@ -768,10 +843,12 @@ 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,
|
||||
});
|
||||
const revoked = yield* authSessions
|
||||
.revoke({
|
||||
sessionId,
|
||||
revokedAt,
|
||||
})
|
||||
.pipe(Effect.mapError((cause) => new SessionRevocationError({ sessionId, cause })));
|
||||
if (revoked) {
|
||||
yield* Ref.update(connectedSessionsRef, (current) => {
|
||||
const next = new Map(current);
|
||||
@@ -782,39 +859,41 @@ 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;
|
||||
});
|
||||
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 })),
|
||||
);
|
||||
yield* Effect.forEach(
|
||||
revokedSessionIds,
|
||||
(revokedSessionId) => emitRemoved(revokedSessionId),
|
||||
{
|
||||
concurrency: "unbounded",
|
||||
discard: true,
|
||||
},
|
||||
);
|
||||
}
|
||||
return revokedSessionIds.length;
|
||||
});
|
||||
|
||||
return SessionStore.of({
|
||||
cookieName,
|
||||
|
||||
@@ -3,7 +3,8 @@ import * as Crypto from "effect/Crypto";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Encoding from "effect/Encoding";
|
||||
import type * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
|
||||
import * as Option from "effect/Option";
|
||||
import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
|
||||
|
||||
import {
|
||||
ServerAuthDpopReplayKeyCalculationError,
|
||||
@@ -13,22 +14,6 @@ import {
|
||||
} from "./EnvironmentAuth.ts";
|
||||
import * as ServerSecretStore from "./ServerSecretStore.ts";
|
||||
|
||||
function firstHeaderValue(value: string | undefined): string | undefined {
|
||||
const first = value?.split(",")[0]?.trim();
|
||||
return first && first.length > 0 ? first : undefined;
|
||||
}
|
||||
|
||||
export function requestAbsoluteUrl(request: HttpServerRequest.HttpServerRequest): string {
|
||||
try {
|
||||
return new URL(request.originalUrl).href;
|
||||
} catch {
|
||||
const host = firstHeaderValue(request.headers.host) ?? "127.0.0.1";
|
||||
const forwardedProto = firstHeaderValue(request.headers["x-forwarded-proto"]);
|
||||
const proto = forwardedProto === "https" || forwardedProto === "http" ? forwardedProto : "http";
|
||||
return new URL(request.originalUrl, `${proto}://${host}`).href;
|
||||
}
|
||||
}
|
||||
|
||||
export const mapDpopReplayStoreError = (
|
||||
error: ServerSecretStore.SecretStoreError,
|
||||
): ServerAuthInvalidCredentialError | ServerAuthInternalError =>
|
||||
@@ -48,11 +33,17 @@ export const verifyRequestDpopProof = (input: {
|
||||
}) =>
|
||||
Effect.gen(function* () {
|
||||
const proof = input.request.headers.dpop;
|
||||
const url = HttpServerRequest.toURL(input.request);
|
||||
if (Option.isNone(url)) {
|
||||
return yield* new ServerAuthInvalidCredentialError({
|
||||
diagnostic: "Invalid DPoP request URL.",
|
||||
});
|
||||
}
|
||||
const now = yield* DateTime.now;
|
||||
const result = verifyDpopProof({
|
||||
proof,
|
||||
method: input.request.method,
|
||||
url: requestAbsoluteUrl(input.request),
|
||||
url: url.value.href,
|
||||
nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
|
||||
...(input.expectedThumbprint ? { expectedThumbprint: input.expectedThumbprint } : {}),
|
||||
...(input.expectedAccessToken ? { expectedAccessToken: input.expectedAccessToken } : {}),
|
||||
|
||||
@@ -2,7 +2,11 @@ import { assert, it } from "@effect/vitest";
|
||||
|
||||
import { EnvironmentInternalError } from "@t3tools/contracts";
|
||||
|
||||
import { ProjectCommandError } from "./project.ts";
|
||||
import {
|
||||
ProjectLiveServerDeclaredResponseError,
|
||||
ProjectLiveServerRequestError,
|
||||
projectCommandErrorFromLiveServerRequest,
|
||||
} from "./project.ts";
|
||||
|
||||
it("maps declared server failures into structural project command errors", () => {
|
||||
const cause = new EnvironmentInternalError({
|
||||
@@ -11,8 +15,9 @@ it("maps declared server failures into structural project command errors", () =>
|
||||
traceId: "trace-123",
|
||||
});
|
||||
|
||||
const error = ProjectCommandError.fromLiveServerRequest(cause);
|
||||
const error = projectCommandErrorFromLiveServerRequest(cause);
|
||||
|
||||
assert.instanceOf(error, ProjectLiveServerDeclaredResponseError);
|
||||
assert.strictEqual(error.operation, "callLiveServer");
|
||||
assert.strictEqual(error.code, "internal_error");
|
||||
assert.strictEqual(error.traceId, "trace-123");
|
||||
@@ -23,10 +28,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 = ProjectCommandError.fromLiveServerRequest(cause);
|
||||
const error = projectCommandErrorFromLiveServerRequest(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);
|
||||
});
|
||||
+138
-49
@@ -51,62 +51,148 @@ type ProjectCliDispatchCommand = Extract<
|
||||
>;
|
||||
|
||||
const isEnvironmentHttpCommonError = Schema.is(EnvironmentHttpCommonError);
|
||||
const ProjectCommandOperation = Schema.Literals([
|
||||
"generateProjectCommandId",
|
||||
"callLiveServer",
|
||||
"validateProjectTitle",
|
||||
"resolveProjectTarget",
|
||||
"addProject",
|
||||
]);
|
||||
|
||||
export class ProjectCommandError extends Schema.TaggedErrorClass<ProjectCommandError>()(
|
||||
"ProjectCommandError",
|
||||
export class ProjectCommandIdGenerationError extends Schema.TaggedErrorClass<ProjectCommandIdGenerationError>()(
|
||||
"ProjectCommandIdGenerationError",
|
||||
{
|
||||
operation: ProjectCommandOperation,
|
||||
detail: Schema.String,
|
||||
code: Schema.optional(Schema.String),
|
||||
traceId: Schema.optional(Schema.String),
|
||||
status: Schema.optional(Schema.Number),
|
||||
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,
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {
|
||||
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({
|
||||
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({
|
||||
operation: "callLiveServer",
|
||||
detail: "Failed to call the running server.",
|
||||
code: cause.code,
|
||||
traceId: cause.traceId,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
if (HttpClientError.isHttpClientError(cause) && cause.response !== undefined) {
|
||||
return new ProjectLiveServerUndeclaredStatusError({
|
||||
operation: "callLiveServer",
|
||||
status: cause.response.status,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return this.detail;
|
||||
}
|
||||
return new ProjectLiveServerRequestError({ operation: "callLiveServer", cause });
|
||||
}
|
||||
|
||||
const projectCommandUuid = Crypto.Crypto.pipe(
|
||||
Effect.flatMap((crypto) => crypto.randomUUIDv4),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProjectCommandError({
|
||||
new ProjectCommandIdGenerationError({
|
||||
operation: "generateProjectCommandId",
|
||||
detail: "Failed to generate a project command identifier.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
@@ -158,9 +244,9 @@ const resolveProjectTitle = Effect.fn("resolveProjectTitle")(function* (
|
||||
if (trimmed.length > 0) {
|
||||
return trimmed;
|
||||
}
|
||||
return yield* new ProjectCommandError({
|
||||
return yield* new ProjectTitleEmptyError({
|
||||
operation: "validateProjectTitle",
|
||||
detail: "Project title cannot be empty.",
|
||||
title: explicitTitle,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -175,9 +261,9 @@ const findActiveProjectTarget = Effect.fn("findActiveProjectTarget")(function* (
|
||||
}) {
|
||||
const trimmedIdentifier = input.identifier.trim();
|
||||
if (trimmedIdentifier.length === 0) {
|
||||
return yield* new ProjectCommandError({
|
||||
return yield* new ProjectIdentifierEmptyError({
|
||||
operation: "resolveProjectTarget",
|
||||
detail: "Project identifier cannot be empty.",
|
||||
identifier: input.identifier,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -204,9 +290,11 @@ const findActiveProjectTarget = Effect.fn("findActiveProjectTarget")(function* (
|
||||
|
||||
const resolved = exactWorkspaceMatch;
|
||||
if (!resolved) {
|
||||
return yield* new ProjectCommandError({
|
||||
return yield* new ProjectNotFoundError({
|
||||
operation: "resolveProjectTarget",
|
||||
detail: `No active project found for '${trimmedIdentifier}'.`,
|
||||
identifier: trimmedIdentifier,
|
||||
activeProjectCount: activeProjects.length,
|
||||
...(normalizedWorkspaceRoot === null ? {} : { normalizedWorkspaceRoot }),
|
||||
...(normalizedWorkspaceRootResult._tag === "Failure"
|
||||
? { cause: normalizedWorkspaceRootResult.failure }
|
||||
: {}),
|
||||
@@ -228,7 +316,7 @@ const fetchLiveOrchestrationSnapshot = (origin: string, bearerToken: string) =>
|
||||
});
|
||||
}).pipe(
|
||||
withProjectCliLiveServerTimeout,
|
||||
Effect.mapError(ProjectCommandError.fromLiveServerRequest),
|
||||
Effect.mapError(projectCommandErrorFromLiveServerRequest),
|
||||
);
|
||||
|
||||
const dispatchLiveOrchestrationCommand = (
|
||||
@@ -244,7 +332,7 @@ const dispatchLiveOrchestrationCommand = (
|
||||
} as Parameters<typeof client.orchestration.dispatch>[0]);
|
||||
}).pipe(
|
||||
withProjectCliLiveServerTimeout,
|
||||
Effect.mapError(ProjectCommandError.fromLiveServerRequest),
|
||||
Effect.mapError(projectCommandErrorFromLiveServerRequest),
|
||||
);
|
||||
|
||||
const getOfflineSnapshot = Effect.fn("getOfflineSnapshot")(function* () {
|
||||
@@ -376,9 +464,10 @@ const projectAddCommand = Command.make("add", {
|
||||
(project) => project.deletedAt === null && project.workspaceRoot === workspaceRoot,
|
||||
);
|
||||
if (existingProject) {
|
||||
return yield* new ProjectCommandError({
|
||||
return yield* new ProjectAlreadyExistsError({
|
||||
operation: "addProject",
|
||||
detail: `An active project already exists for '${workspaceRoot}'.`,
|
||||
projectId: existingProject.id,
|
||||
workspaceRoot,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -171,20 +171,8 @@ function runGitSyncForFakeGh(cwd: string, args: readonly string[]): void {
|
||||
if (result.status === 0) {
|
||||
return;
|
||||
}
|
||||
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"
|
||||
throw new Error(
|
||||
`Failed to simulate gh checkout with git ${args.join(" ")}: ${result.stderr?.trim() || "unknown error"}`,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -478,16 +466,12 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
|
||||
return fakeGhOutput("");
|
||||
},
|
||||
catch: (error) =>
|
||||
isGitHubCliError(error)
|
||||
GitHubCli.isGitHubCliError(error)
|
||||
? error
|
||||
: new GitHubCli.GitHubCliError({
|
||||
operation: "execute",
|
||||
: new GitHubCli.GitHubCliCommandError({
|
||||
command: "gh",
|
||||
cwd: input.cwd,
|
||||
detail:
|
||||
error instanceof Error
|
||||
? `Failed to simulate gh checkout: ${error.message}`
|
||||
: "Failed to simulate gh checkout.",
|
||||
cause: error,
|
||||
}),
|
||||
});
|
||||
}
|
||||
@@ -498,11 +482,10 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
|
||||
const cloneUrls = scenario.repositoryCloneUrls?.[repository];
|
||||
if (!cloneUrls) {
|
||||
return Effect.fail(
|
||||
new GitHubCli.GitHubCliError({
|
||||
operation: "execute",
|
||||
new GitHubCli.GitHubCliCommandError({
|
||||
command: "gh",
|
||||
cwd: input.cwd,
|
||||
detail: `Unexpected repository lookup: ${repository}`,
|
||||
cause: new Error(`Unexpected repository lookup: ${repository}`),
|
||||
}),
|
||||
);
|
||||
}
|
||||
@@ -520,11 +503,10 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
|
||||
}
|
||||
|
||||
return Effect.fail(
|
||||
new GitHubCli.GitHubCliError({
|
||||
operation: "execute",
|
||||
new GitHubCli.GitHubCliCommandError({
|
||||
command: "gh",
|
||||
cwd: input.cwd,
|
||||
detail: `Unexpected gh command: ${args.join(" ")}`,
|
||||
cause: new Error(`Unexpected gh command: ${args.join(" ")}`),
|
||||
}),
|
||||
);
|
||||
};
|
||||
@@ -601,11 +583,10 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
|
||||
}).pipe(Effect.map((result) => JSON.parse(result.stdout))),
|
||||
createRepository: (input) =>
|
||||
Effect.fail(
|
||||
new GitHubCli.GitHubCliError({
|
||||
operation: "createRepository",
|
||||
new GitHubCli.GitHubCliCommandError({
|
||||
command: "gh",
|
||||
cwd: input.cwd,
|
||||
detail: `Unexpected repository create: ${input.repository}`,
|
||||
cause: new Error(`Unexpected repository create: ${input.repository}`),
|
||||
}),
|
||||
),
|
||||
checkoutPullRequest: (input) =>
|
||||
@@ -1341,11 +1322,10 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
failWith: new GitHubCli.GitHubCliError({
|
||||
operation: "execute",
|
||||
failWith: new GitHubCli.GitHubCliUnavailableError({
|
||||
command: "gh",
|
||||
cwd: repoDir,
|
||||
detail: "GitHub CLI (`gh`) is required but not available on PATH.",
|
||||
cause: new Error("gh is not available on PATH"),
|
||||
}),
|
||||
},
|
||||
});
|
||||
@@ -2483,11 +2463,10 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
failWith: new GitHubCli.GitHubCliError({
|
||||
operation: "execute",
|
||||
failWith: new GitHubCli.GitHubCliUnavailableError({
|
||||
command: "gh",
|
||||
cwd: repoDir,
|
||||
detail: "GitHub CLI (`gh`) is required but not available on PATH.",
|
||||
cause: new Error("gh is not available on PATH"),
|
||||
}),
|
||||
},
|
||||
});
|
||||
@@ -2514,11 +2493,10 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
failWith: new GitHubCli.GitHubCliError({
|
||||
operation: "execute",
|
||||
failWith: new GitHubCli.GitHubCliAuthenticationError({
|
||||
command: "gh",
|
||||
cwd: repoDir,
|
||||
detail: "GitHub CLI is not authenticated. Run `gh auth login` and retry.",
|
||||
cause: new Error("gh is not authenticated"),
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -44,13 +44,18 @@ import { browserApiCorsAllowedHeaders, browserApiCorsAllowedMethods } from "./ht
|
||||
|
||||
const OTLP_TRACES_PROXY_PATH = "/api/observability/v1/traces";
|
||||
const LOOPBACK_HOSTNAMES = new Set(["127.0.0.1", "::1", "localhost"]);
|
||||
const DESKTOP_RENDERER_ORIGINS = ["t3code://app", "t3code-dev://app"];
|
||||
|
||||
export const browserApiCorsLayer = Layer.unwrap(
|
||||
Effect.gen(function* () {
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
const devOrigin = config.devUrl?.origin;
|
||||
// Dev uses credentialed requests from Vite or the Electron custom origin, so both must be
|
||||
// explicit. Packaged desktop omits credentials and uses Effect's default wildcard origin.
|
||||
return HttpRouter.cors({
|
||||
...(devOrigin ? { allowedOrigins: [devOrigin], credentials: true } : {}),
|
||||
...(devOrigin
|
||||
? { allowedOrigins: [devOrigin, ...DESKTOP_RENDERER_ORIGINS], credentials: true }
|
||||
: {}),
|
||||
allowedMethods: browserApiCorsAllowedMethods,
|
||||
allowedHeaders: browserApiCorsAllowedHeaders,
|
||||
maxAge: 600,
|
||||
|
||||
@@ -198,6 +198,7 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
|
||||
assert.equal(defaultsByCommand.get("thread.jump.1"), "mod+1");
|
||||
assert.equal(defaultsByCommand.get("thread.jump.9"), "mod+9");
|
||||
assert.equal(defaultsByCommand.get("modelPicker.toggle"), "mod+shift+m");
|
||||
assert.equal(defaultsByCommand.get("sidebar.toggle"), "mod+b");
|
||||
assert.equal(defaultsByCommand.get("rightPanel.toggle"), "mod+alt+b");
|
||||
assert.equal(defaultsByCommand.get("terminal.splitVertical"), "mod+shift+d");
|
||||
assert.equal(defaultsByCommand.get("modelPicker.jump.1"), "mod+1");
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import { NodeHttpServer } from "@effect/platform-node";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { EnvironmentId, PreviewTabId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
@@ -34,7 +35,7 @@ const client = McpSchema.McpServerClient.of({
|
||||
});
|
||||
const TestLayer = McpHttpServer.PreviewToolkitRegistrationLive.pipe(
|
||||
Layer.provideMerge(McpServer.McpServer.layer),
|
||||
Layer.provideMerge(PreviewAutomationBroker.layer),
|
||||
Layer.provideMerge(PreviewAutomationBroker.layer.pipe(Layer.provide(NodeServices.layer))),
|
||||
);
|
||||
|
||||
it("normalizes empty successful notification responses to accepted", () => {
|
||||
@@ -54,36 +55,26 @@ it.effect("returns bounded structural preview snapshot failures", () =>
|
||||
Effect.gen(function* () {
|
||||
const server = yield* McpServer.McpServer;
|
||||
const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
|
||||
const requests = yield* broker.connect({
|
||||
const events = yield* broker.connect({
|
||||
clientId: "mcp-failure-client",
|
||||
environmentId,
|
||||
threadId,
|
||||
tabId,
|
||||
visible: true,
|
||||
supportsAutomation: true,
|
||||
focusedAt: "2026-06-11T00:00:00.000Z",
|
||||
});
|
||||
yield* Stream.runForEach(requests, (request) =>
|
||||
broker.respond({
|
||||
requestId: request.requestId,
|
||||
ok: false,
|
||||
error: {
|
||||
_tag: "PreviewAutomationExecutionError",
|
||||
message: "sensitive renderer failure",
|
||||
detail: { consoleOutput: "sensitive browser output" },
|
||||
},
|
||||
}),
|
||||
yield* Stream.runForEach(events, (event) =>
|
||||
event.type === "connected"
|
||||
? Effect.void
|
||||
: broker.respond({
|
||||
clientId: "mcp-failure-client",
|
||||
connectionId: event.connectionId,
|
||||
requestId: event.request.requestId,
|
||||
ok: false,
|
||||
error: {
|
||||
_tag: "PreviewAutomationExecutionError",
|
||||
message: "sensitive renderer failure",
|
||||
detail: { consoleOutput: "sensitive browser output" },
|
||||
},
|
||||
}),
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
yield* broker.reportOwner({
|
||||
clientId: "mcp-failure-client",
|
||||
environmentId,
|
||||
threadId,
|
||||
tabId,
|
||||
visible: true,
|
||||
supportsAutomation: true,
|
||||
focusedAt: "2026-06-11T00:00:00.000Z",
|
||||
});
|
||||
|
||||
const snapshot = yield* server
|
||||
.callTool({ name: "preview_snapshot", arguments: {} })
|
||||
@@ -163,60 +154,50 @@ it.effect("registers annotated tools and preserves authenticated request context
|
||||
Effect.gen(function* () {
|
||||
const server = yield* McpServer.McpServer;
|
||||
const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
|
||||
const requests = yield* broker.connect({
|
||||
const events = yield* broker.connect({
|
||||
clientId: "mcp-test-client",
|
||||
environmentId,
|
||||
threadId,
|
||||
tabId,
|
||||
visible: true,
|
||||
supportsAutomation: true,
|
||||
focusedAt: "2026-06-11T00:00:00.000Z",
|
||||
});
|
||||
yield* Stream.runForEach(requests, (request) =>
|
||||
broker.respond({
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
result:
|
||||
request.operation === "snapshot"
|
||||
? {
|
||||
url: "http://example.test/",
|
||||
title: "Example",
|
||||
loading: false,
|
||||
visibleText: "Example",
|
||||
interactiveElements: [],
|
||||
accessibilityTree: {},
|
||||
consoleEntries: [],
|
||||
networkEntries: [],
|
||||
actionTimeline: [],
|
||||
screenshot: {
|
||||
mimeType: "image/png",
|
||||
data: Buffer.from("png").toString("base64"),
|
||||
width: 10,
|
||||
height: 5,
|
||||
},
|
||||
}
|
||||
: request.operation === "press"
|
||||
? undefined
|
||||
: {
|
||||
available: true,
|
||||
visible: true,
|
||||
tabId,
|
||||
url: "http://example.test/",
|
||||
title: "Example",
|
||||
loading: false,
|
||||
},
|
||||
}),
|
||||
yield* Stream.runForEach(events, (event) =>
|
||||
event.type === "connected"
|
||||
? Effect.void
|
||||
: broker.respond({
|
||||
clientId: "mcp-test-client",
|
||||
connectionId: event.connectionId,
|
||||
requestId: event.request.requestId,
|
||||
ok: true,
|
||||
result:
|
||||
event.request.operation === "snapshot"
|
||||
? {
|
||||
url: "http://example.test/",
|
||||
title: "Example",
|
||||
loading: false,
|
||||
visibleText: "Example",
|
||||
interactiveElements: [],
|
||||
accessibilityTree: {},
|
||||
consoleEntries: [],
|
||||
networkEntries: [],
|
||||
actionTimeline: [],
|
||||
screenshot: {
|
||||
mimeType: "image/png",
|
||||
data: Buffer.from("png").toString("base64"),
|
||||
width: 10,
|
||||
height: 5,
|
||||
},
|
||||
}
|
||||
: event.request.operation === "press"
|
||||
? undefined
|
||||
: {
|
||||
available: true,
|
||||
visible: true,
|
||||
tabId,
|
||||
url: "http://example.test/",
|
||||
title: "Example",
|
||||
loading: false,
|
||||
},
|
||||
}),
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
yield* broker.reportOwner({
|
||||
clientId: "mcp-test-client",
|
||||
environmentId,
|
||||
threadId,
|
||||
tabId,
|
||||
visible: true,
|
||||
supportsAutomation: true,
|
||||
focusedAt: "2026-06-11T00:00:00.000Z",
|
||||
});
|
||||
|
||||
const statusTool = server.tools.find(({ tool }) => tool.name === "preview_status");
|
||||
expect(statusTool?.tool.annotations?.readOnlyHint).toBe(true);
|
||||
|
||||
@@ -214,7 +214,4 @@ const McpTransportLive = McpServer.layerHttp({
|
||||
path: "/mcp",
|
||||
}).pipe(Layer.provide(McpAuthMiddlewareLive));
|
||||
|
||||
export const layer = PreviewToolkitRegistrationLive.pipe(
|
||||
Layer.provideMerge(McpTransportLive),
|
||||
Layer.provide(PreviewAutomationBroker.layer),
|
||||
);
|
||||
export const layer = PreviewToolkitRegistrationLive.pipe(Layer.provideMerge(McpTransportLive));
|
||||
@@ -0,0 +1,39 @@
|
||||
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.");
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,9 @@
|
||||
import type { EnvironmentId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
|
||||
import { PreviewAutomationUnavailableError } from "@t3tools/contracts";
|
||||
import {
|
||||
type EnvironmentId,
|
||||
PreviewAutomationUnavailableError,
|
||||
type ProviderInstanceId,
|
||||
type ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
@@ -26,7 +30,11 @@ export const requireMcpCapability = Effect.fn("mcp.requireCapability")(function*
|
||||
const invocation = yield* McpInvocationContext;
|
||||
if (!invocation.capabilities.has(capability)) {
|
||||
return yield* new PreviewAutomationUnavailableError({
|
||||
message: `MCP credential does not grant the ${capability} capability.`,
|
||||
capability,
|
||||
environmentId: invocation.environmentId,
|
||||
threadId: invocation.threadId,
|
||||
providerSessionId: invocation.providerSessionId,
|
||||
providerInstanceId: invocation.providerInstanceId,
|
||||
});
|
||||
}
|
||||
return invocation;
|
||||
|
||||
@@ -1,20 +1,28 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import {
|
||||
EnvironmentId,
|
||||
PreviewAutomationClientDisconnectedError,
|
||||
PreviewAutomationInvalidSelectorError,
|
||||
PreviewAutomationMalformedResponseError,
|
||||
PreviewAutomationNoFocusedOwnerError,
|
||||
PreviewAutomationNoAvailableHostError,
|
||||
PreviewAutomationTargetNotEditableError,
|
||||
PreviewTabId,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
type PreviewAutomationOwner,
|
||||
type PreviewAutomationHost,
|
||||
type PreviewAutomationRequest,
|
||||
type PreviewAutomationStreamEvent,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Result from "effect/Result";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import * as PreviewAutomationBroker from "./PreviewAutomationBroker.ts";
|
||||
|
||||
const makeBroker = PreviewAutomationBroker.make.pipe(Effect.provide(NodeServices.layer));
|
||||
|
||||
const scope = {
|
||||
environmentId: EnvironmentId.make("environment-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
@@ -22,27 +30,42 @@ const scope = {
|
||||
providerInstanceId: ProviderInstanceId.make("codex"),
|
||||
capabilities: new Set(["preview"] as const),
|
||||
issuedAt: 1,
|
||||
expiresAt: 2,
|
||||
expiresAt: Number.MAX_SAFE_INTEGER,
|
||||
};
|
||||
|
||||
const makeOwner = (overrides: Partial<PreviewAutomationOwner> = {}): PreviewAutomationOwner => ({
|
||||
const makeHost = (overrides: Partial<PreviewAutomationHost> = {}): PreviewAutomationHost => ({
|
||||
clientId: "client-1",
|
||||
environmentId: scope.environmentId,
|
||||
threadId: scope.threadId,
|
||||
tabId: null,
|
||||
visible: false,
|
||||
supportsAutomation: true,
|
||||
focusedAt: "2026-06-11T00:00:00.000Z",
|
||||
...overrides,
|
||||
});
|
||||
|
||||
it.effect("atomically registers a connected owner and correlates its response", () =>
|
||||
type RoutedRequest = PreviewAutomationRequest & {
|
||||
readonly connectionId: PreviewAutomationStreamEvent["connectionId"];
|
||||
};
|
||||
|
||||
const requestsFrom = (
|
||||
events: Stream.Stream<PreviewAutomationStreamEvent>,
|
||||
onConnected: (connectionId: PreviewAutomationStreamEvent["connectionId"]) => void = () => {},
|
||||
): Stream.Stream<RoutedRequest> =>
|
||||
events.pipe(
|
||||
Stream.filterMap((event) => {
|
||||
if (event.type === "connected") {
|
||||
onConnected(event.connectionId);
|
||||
return Result.failVoid;
|
||||
}
|
||||
return Result.succeed({ ...event.request, connectionId: event.connectionId });
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("atomically registers a connected host and correlates its response", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* PreviewAutomationBroker.make;
|
||||
const requests = yield* broker.connect(makeOwner());
|
||||
const broker = yield* makeBroker;
|
||||
const requests = requestsFrom(yield* broker.connect(makeHost()));
|
||||
yield* Stream.runForEach(requests, (request) =>
|
||||
broker.respond({
|
||||
clientId: "client-1",
|
||||
connectionId: request.connectionId,
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
result: { available: true },
|
||||
@@ -61,6 +84,39 @@ it.effect("atomically registers a connected owner and correlates its response",
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("announces a live replacement stream before delivering requests", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* makeBroker;
|
||||
const events = yield* broker.connect(makeHost());
|
||||
const receivedTypes: PreviewAutomationStreamEvent["type"][] = [];
|
||||
const consumer = yield* events.pipe(
|
||||
Stream.take(2),
|
||||
Stream.runForEach((event) => {
|
||||
receivedTypes.push(event.type);
|
||||
return event.type === "connected"
|
||||
? Effect.void
|
||||
: broker.respond({
|
||||
clientId: "client-1",
|
||||
connectionId: event.connectionId,
|
||||
requestId: event.request.requestId,
|
||||
ok: true,
|
||||
result: "ready",
|
||||
});
|
||||
}),
|
||||
Effect.forkScoped,
|
||||
);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
const result = yield* broker.invoke<string>({ scope, operation: "status", input: {} });
|
||||
yield* Fiber.join(consumer);
|
||||
|
||||
expect(receivedTypes).toEqual(["connected", "request"]);
|
||||
expect(result).toBe("ready");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("preserves bounded request and remote selector diagnostics", () => {
|
||||
const locator = "role=button[name='request-secret']";
|
||||
const remoteMessage = "Unexpected token near remote-secret.";
|
||||
@@ -72,10 +128,12 @@ it.effect("preserves bounded request and remote selector diagnostics", () => {
|
||||
|
||||
return Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* PreviewAutomationBroker.make;
|
||||
const requests = yield* broker.connect(makeOwner({ tabId: "tab-1" }));
|
||||
const broker = yield* makeBroker;
|
||||
const requests = requestsFrom(yield* broker.connect(makeHost()));
|
||||
yield* Stream.runForEach(requests, (request) =>
|
||||
broker.respond({
|
||||
clientId: "client-1",
|
||||
connectionId: request.connectionId,
|
||||
requestId: request.requestId,
|
||||
ok: false,
|
||||
error: remoteError,
|
||||
@@ -88,6 +146,7 @@ it.effect("preserves bounded request and remote selector diagnostics", () => {
|
||||
scope,
|
||||
operation: "click",
|
||||
input: { locator },
|
||||
tabId: PreviewTabId.make("tab-1"),
|
||||
timeoutMs: 1_234,
|
||||
})
|
||||
.pipe(Effect.flip);
|
||||
@@ -121,13 +180,61 @@ it.effect("preserves bounded request and remote selector diagnostics", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("classifies a remote non-editable target without collapsing it to execution", () => {
|
||||
const remoteError = {
|
||||
_tag: "PreviewAutomationTargetNotEditableError",
|
||||
message: "remote target details",
|
||||
detail: { selectorKind: "focused-element" },
|
||||
} as const;
|
||||
|
||||
return Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* makeBroker;
|
||||
const requests = requestsFrom(yield* broker.connect(makeHost()));
|
||||
yield* Stream.runForEach(requests, (request) =>
|
||||
broker.respond({
|
||||
clientId: "client-1",
|
||||
connectionId: request.connectionId,
|
||||
requestId: request.requestId,
|
||||
ok: false,
|
||||
error: remoteError,
|
||||
}),
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
const error = yield* broker
|
||||
.invoke<void>({
|
||||
scope,
|
||||
operation: "type",
|
||||
input: { text: "hello" },
|
||||
tabId: PreviewTabId.make("tab-1"),
|
||||
})
|
||||
.pipe(Effect.flip);
|
||||
|
||||
expect(error).toBeInstanceOf(PreviewAutomationTargetNotEditableError);
|
||||
expect(error).toMatchObject({
|
||||
operation: "type",
|
||||
tabId: "tab-1",
|
||||
selectorKind: "focused-element",
|
||||
remoteTag: "PreviewAutomationTargetNotEditableError",
|
||||
});
|
||||
expect(error.message).toBe("Preview automation type requires an editable focused element.");
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("distinguishes malformed remote failures", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* PreviewAutomationBroker.make;
|
||||
const requests = yield* broker.connect(makeOwner());
|
||||
const broker = yield* makeBroker;
|
||||
const requests = requestsFrom(yield* broker.connect(makeHost()));
|
||||
yield* Stream.runForEach(requests, (request) =>
|
||||
broker.respond({ requestId: request.requestId, ok: false }),
|
||||
broker.respond({
|
||||
clientId: "client-1",
|
||||
connectionId: request.connectionId,
|
||||
requestId: request.requestId,
|
||||
ok: false,
|
||||
}),
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
@@ -150,13 +257,14 @@ it.effect("distinguishes malformed remote failures", () =>
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("rejects calls when no focused owner exists", () =>
|
||||
it.effect("rejects calls when no connected host exists", () =>
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* PreviewAutomationBroker.make;
|
||||
const broker = yield* makeBroker;
|
||||
const error = yield* broker
|
||||
.invoke<void>({ scope, operation: "status", input: {} })
|
||||
.pipe(Effect.flip);
|
||||
expect(error).toBeInstanceOf(PreviewAutomationNoFocusedOwnerError);
|
||||
|
||||
expect(error).toBeInstanceOf(PreviewAutomationNoAvailableHostError);
|
||||
expect(error).toMatchObject({
|
||||
operation: "status",
|
||||
environmentId: scope.environmentId,
|
||||
@@ -167,32 +275,425 @@ it.effect("rejects calls when no focused owner exists", () =>
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("routes interactive commands to a hidden durable browser host", () =>
|
||||
it.effect("does not create host state from focus updates without a live stream", () =>
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* makeBroker;
|
||||
yield* broker.focusHost({
|
||||
clientId: "client-1",
|
||||
environmentId: scope.environmentId,
|
||||
connectionId: "connection-missing",
|
||||
focused: true,
|
||||
});
|
||||
|
||||
const error = yield* broker
|
||||
.invoke<void>({ scope, operation: "status", input: {} })
|
||||
.pipe(Effect.flip);
|
||||
expect(error).toBeInstanceOf(PreviewAutomationNoAvailableHostError);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("removes host availability when the authoritative request stream disconnects", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* PreviewAutomationBroker.make;
|
||||
const requests = yield* broker.connect(
|
||||
makeOwner({ clientId: "client-hidden", tabId: "tab-hidden" }),
|
||||
);
|
||||
yield* Stream.runForEach(requests, (request) =>
|
||||
broker.respond({ requestId: request.requestId, ok: true }),
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
const broker = yield* makeBroker;
|
||||
const requests = requestsFrom(yield* broker.connect(makeHost()));
|
||||
const beforeAcquisition = yield* broker
|
||||
.invoke<void>({ scope, operation: "status", input: {} })
|
||||
.pipe(Effect.flip);
|
||||
expect(beforeAcquisition).toBeInstanceOf(PreviewAutomationNoAvailableHostError);
|
||||
|
||||
yield* broker.invoke<void>({ scope, operation: "click", input: { x: 10, y: 10 } });
|
||||
const consumer = yield* Stream.runDrain(requests).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
yield* Fiber.interrupt(consumer);
|
||||
|
||||
const error = yield* broker
|
||||
.invoke<void>({ scope, operation: "status", input: {} })
|
||||
.pipe(Effect.flip);
|
||||
expect(error).toBeInstanceOf(PreviewAutomationNoAvailableHostError);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("lets the browser host resolve an active tab that has not been reported yet", () =>
|
||||
it.effect("routes requests for background threads through an environment-level host", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* PreviewAutomationBroker.make;
|
||||
const requests = yield* broker.connect(makeOwner({ tabId: null }));
|
||||
const broker = yield* makeBroker;
|
||||
const backgroundThreadId = ThreadId.make("thread-background");
|
||||
const requests = requestsFrom(yield* broker.connect(makeHost()));
|
||||
let routedThreadId: string | undefined;
|
||||
yield* Stream.runForEach(requests, (request) => {
|
||||
routedThreadId = request.threadId;
|
||||
return broker.respond({
|
||||
clientId: "client-1",
|
||||
connectionId: request.connectionId,
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
result: "background",
|
||||
});
|
||||
}).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
const result = yield* broker.invoke<string>({
|
||||
scope: {
|
||||
...scope,
|
||||
threadId: backgroundThreadId,
|
||||
providerSessionId: "provider-session-background",
|
||||
},
|
||||
operation: "status",
|
||||
input: {},
|
||||
});
|
||||
|
||||
expect(result).toBe("background");
|
||||
expect(routedThreadId).toBe(backgroundThreadId);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("never routes a provider session to a host from another environment", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* makeBroker;
|
||||
const matchingRequests = requestsFrom(
|
||||
yield* broker.connect(makeHost({ clientId: "client-matching" })),
|
||||
);
|
||||
const foreignRequests = requestsFrom(
|
||||
yield* broker.connect(
|
||||
makeHost({
|
||||
clientId: "client-foreign",
|
||||
environmentId: EnvironmentId.make("environment-foreign"),
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* Stream.runForEach(matchingRequests, (request) =>
|
||||
broker.respond({
|
||||
clientId: "client-matching",
|
||||
connectionId: request.connectionId,
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
result: "matching",
|
||||
}),
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* Stream.runForEach(foreignRequests, (request) =>
|
||||
broker.respond({
|
||||
clientId: "client-foreign",
|
||||
connectionId: request.connectionId,
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
result: "foreign",
|
||||
}),
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
expect(yield* broker.invoke<string>({ scope, operation: "status", input: {} })).toBe(
|
||||
"matching",
|
||||
);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("pins a provider session to its initial host despite later focus changes", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* makeBroker;
|
||||
let firstConnectionId = "";
|
||||
let secondConnectionId = "";
|
||||
const firstRequests = requestsFrom(
|
||||
yield* broker.connect(makeHost({ clientId: "client-first" })),
|
||||
(connectionId) => {
|
||||
firstConnectionId = connectionId;
|
||||
},
|
||||
);
|
||||
const secondRequests = requestsFrom(
|
||||
yield* broker.connect(makeHost({ clientId: "client-second" })),
|
||||
(connectionId) => {
|
||||
secondConnectionId = connectionId;
|
||||
},
|
||||
);
|
||||
yield* Stream.runForEach(firstRequests, (request) =>
|
||||
broker.respond({
|
||||
clientId: "client-first",
|
||||
connectionId: request.connectionId,
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
result: "first",
|
||||
}),
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* Stream.runForEach(secondRequests, (request) =>
|
||||
broker.respond({
|
||||
clientId: "client-second",
|
||||
connectionId: request.connectionId,
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
result: "second",
|
||||
}),
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
yield* broker.focusHost({
|
||||
clientId: "client-first",
|
||||
environmentId: scope.environmentId,
|
||||
connectionId: "connection-stale",
|
||||
focused: true,
|
||||
});
|
||||
expect(yield* broker.invoke<string>({ scope, operation: "status", input: {} })).toBe(
|
||||
"second",
|
||||
);
|
||||
yield* broker.focusHost({
|
||||
clientId: "client-first",
|
||||
environmentId: scope.environmentId,
|
||||
connectionId: firstConnectionId,
|
||||
focused: true,
|
||||
});
|
||||
|
||||
const firstPinnedScope = {
|
||||
...scope,
|
||||
providerSessionId: "provider-session-first-pinned",
|
||||
};
|
||||
expect(
|
||||
yield* broker.invoke<string>({ scope: firstPinnedScope, operation: "status", input: {} }),
|
||||
).toBe("first");
|
||||
|
||||
yield* broker.focusHost({
|
||||
clientId: "client-second",
|
||||
environmentId: scope.environmentId,
|
||||
connectionId: secondConnectionId,
|
||||
focused: true,
|
||||
});
|
||||
|
||||
expect(
|
||||
yield* broker.invoke<string>({ scope: firstPinnedScope, operation: "status", input: {} }),
|
||||
).toBe("first");
|
||||
expect(
|
||||
yield* broker.invoke<string>({
|
||||
scope: { ...scope, providerSessionId: "provider-session-second-pinned" },
|
||||
operation: "status",
|
||||
input: {},
|
||||
}),
|
||||
).toBe("second");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("does not route new operations to legacy hosts that did not advertise support", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* makeBroker;
|
||||
const legacyEvents = yield* broker.connect(makeHost());
|
||||
yield* Stream.runDrain(legacyEvents).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
const error = yield* broker
|
||||
.invoke<void>({ scope, operation: "resize", input: { mode: "fill" } })
|
||||
.pipe(Effect.flip);
|
||||
|
||||
expect(error).toBeInstanceOf(PreviewAutomationNoAvailableHostError);
|
||||
expect(error).toMatchObject({ operation: "resize", environmentId: scope.environmentId });
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("routes resize to a capable host instead of a newer legacy connection", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* makeBroker;
|
||||
const capableRequests = requestsFrom(
|
||||
yield* broker.connect(
|
||||
makeHost({ clientId: "client-capable", supportedOperations: ["resize"] }),
|
||||
),
|
||||
);
|
||||
const legacyRequests = requestsFrom(
|
||||
yield* broker.connect(makeHost({ clientId: "client-legacy" })),
|
||||
);
|
||||
yield* Stream.runForEach(capableRequests, (request) =>
|
||||
broker.respond({
|
||||
clientId: "client-capable",
|
||||
connectionId: request.connectionId,
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
result: "capable",
|
||||
}),
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* Stream.runForEach(legacyRequests, (request) =>
|
||||
broker.respond({
|
||||
clientId: "client-legacy",
|
||||
connectionId: request.connectionId,
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
result: "legacy",
|
||||
}),
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
expect(
|
||||
yield* broker.invoke<string>({ scope, operation: "resize", input: { mode: "fill" } }),
|
||||
).toBe("capable");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("does not move a live legacy assignment to another runtime for resize", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* makeBroker;
|
||||
const legacyRequests = requestsFrom(
|
||||
yield* broker.connect(makeHost({ clientId: "client-legacy" })),
|
||||
);
|
||||
yield* Stream.runForEach(legacyRequests, (request) =>
|
||||
broker.respond({
|
||||
clientId: "client-legacy",
|
||||
connectionId: request.connectionId,
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
result: "legacy",
|
||||
}),
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
expect(yield* broker.invoke<string>({ scope, operation: "status", input: {} })).toBe(
|
||||
"legacy",
|
||||
);
|
||||
|
||||
const capableRequests = requestsFrom(
|
||||
yield* broker.connect(
|
||||
makeHost({ clientId: "client-capable", supportedOperations: ["resize"] }),
|
||||
),
|
||||
);
|
||||
yield* Stream.runForEach(capableRequests, (request) =>
|
||||
broker.respond({
|
||||
clientId: "client-capable",
|
||||
connectionId: request.connectionId,
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
result: "capable",
|
||||
}),
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
const error = yield* broker
|
||||
.invoke<void>({ scope, operation: "resize", input: { mode: "fill" } })
|
||||
.pipe(Effect.flip);
|
||||
expect(error).toBeInstanceOf(PreviewAutomationNoAvailableHostError);
|
||||
expect(yield* broker.invoke<string>({ scope, operation: "status", input: {} })).toBe(
|
||||
"legacy",
|
||||
);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("ignores stale focus updates for a different environment", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* makeBroker;
|
||||
let firstConnectionId = "";
|
||||
const firstRequests = requestsFrom(
|
||||
yield* broker.connect(makeHost({ clientId: "client-first" })),
|
||||
(connectionId) => {
|
||||
firstConnectionId = connectionId;
|
||||
},
|
||||
);
|
||||
const secondRequests = requestsFrom(
|
||||
yield* broker.connect(makeHost({ clientId: "client-second" })),
|
||||
);
|
||||
yield* Stream.runForEach(firstRequests, (request) =>
|
||||
broker.respond({
|
||||
clientId: "client-first",
|
||||
connectionId: request.connectionId,
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
result: "first",
|
||||
}),
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* Stream.runForEach(secondRequests, (request) =>
|
||||
broker.respond({
|
||||
clientId: "client-second",
|
||||
connectionId: request.connectionId,
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
result: "second",
|
||||
}),
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
yield* broker.focusHost({
|
||||
clientId: "client-first",
|
||||
environmentId: EnvironmentId.make("environment-stale"),
|
||||
connectionId: firstConnectionId,
|
||||
focused: true,
|
||||
});
|
||||
|
||||
expect(yield* broker.invoke<string>({ scope, operation: "status", input: {} })).toBe(
|
||||
"second",
|
||||
);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("fails over a pinned provider session only after its host disconnects", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* makeBroker;
|
||||
let firstConnectionId = "";
|
||||
const firstRequests = requestsFrom(
|
||||
yield* broker.connect(makeHost({ clientId: "client-first" })),
|
||||
(connectionId) => {
|
||||
firstConnectionId = connectionId;
|
||||
},
|
||||
);
|
||||
const secondRequests = requestsFrom(
|
||||
yield* broker.connect(makeHost({ clientId: "client-second" })),
|
||||
);
|
||||
const firstConsumer = yield* Stream.runForEach(firstRequests, (request) =>
|
||||
broker.respond({
|
||||
clientId: "client-first",
|
||||
connectionId: request.connectionId,
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
result: "first",
|
||||
}),
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* Stream.runForEach(secondRequests, (request) =>
|
||||
broker.respond({
|
||||
clientId: "client-second",
|
||||
connectionId: request.connectionId,
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
result: "second",
|
||||
}),
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
yield* broker.focusHost({
|
||||
clientId: "client-first",
|
||||
environmentId: scope.environmentId,
|
||||
connectionId: firstConnectionId,
|
||||
focused: true,
|
||||
});
|
||||
expect(yield* broker.invoke<string>({ scope, operation: "status", input: {} })).toBe("first");
|
||||
|
||||
yield* Fiber.interrupt(firstConsumer);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
expect(yield* broker.invoke<string>({ scope, operation: "status", input: {} })).toBe(
|
||||
"second",
|
||||
);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("lets the browser host resolve an active tab locally", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* makeBroker;
|
||||
const requests = requestsFrom(yield* broker.connect(makeHost()));
|
||||
let routedTabId: string | undefined;
|
||||
yield* Stream.runForEach(requests, (request) => {
|
||||
routedTabId = request.tabId;
|
||||
return broker.respond({ requestId: request.requestId, ok: true });
|
||||
return broker.respond({
|
||||
clientId: "client-1",
|
||||
connectionId: request.connectionId,
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
});
|
||||
}).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
@@ -203,61 +704,55 @@ it.effect("lets the browser host resolve an active tab that has not been reporte
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("preserves current owner metadata when its request stream reconnects", () =>
|
||||
it.effect("keeps a replacement stream authoritative when the old stream finalizes", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* PreviewAutomationBroker.make;
|
||||
const firstRequests = yield* broker.connect(makeOwner());
|
||||
const broker = yield* makeBroker;
|
||||
let firstConnectionId = "";
|
||||
let replacementConnectionId = "";
|
||||
const firstRequests = requestsFrom(yield* broker.connect(makeHost()), (connectionId) => {
|
||||
firstConnectionId = connectionId;
|
||||
});
|
||||
yield* Stream.runDrain(firstRequests).pipe(Effect.forkScoped);
|
||||
yield* broker.reportOwner(makeOwner({ tabId: "tab-current", visible: true }));
|
||||
|
||||
const reconnectedRequests = yield* broker.connect(makeOwner());
|
||||
let routedTabId: string | undefined;
|
||||
yield* Stream.runForEach(reconnectedRequests, (request) => {
|
||||
routedTabId = request.tabId;
|
||||
return broker.respond({ requestId: request.requestId, ok: true });
|
||||
}).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
yield* broker.invoke<void>({ scope, operation: "click", input: { x: 10, y: 10 } });
|
||||
|
||||
expect(routedTabId).toBe("tab-current");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("ignores stale owner cleanup after the client moves to another thread", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* PreviewAutomationBroker.make;
|
||||
const requests = yield* broker.connect(makeOwner());
|
||||
yield* Stream.runForEach(requests, (request) =>
|
||||
broker.respond({ requestId: request.requestId, ok: true }),
|
||||
const replacementRequests = requestsFrom(
|
||||
yield* broker.connect(makeHost()),
|
||||
(connectionId) => {
|
||||
replacementConnectionId = connectionId;
|
||||
},
|
||||
);
|
||||
yield* Stream.runForEach(replacementRequests, (request) =>
|
||||
broker.respond({
|
||||
clientId: "client-1",
|
||||
connectionId: request.connectionId,
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
result: "replacement",
|
||||
}),
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
yield* broker.clearOwner({
|
||||
clientId: "client-1",
|
||||
environmentId: scope.environmentId,
|
||||
threadId: ThreadId.make("thread-stale"),
|
||||
});
|
||||
|
||||
yield* broker.invoke<void>({ scope, operation: "status", input: {} });
|
||||
expect(replacementConnectionId).not.toBe(firstConnectionId);
|
||||
const result = yield* broker.invoke<string>({ scope, operation: "status", input: {} });
|
||||
expect(result).toBe("replacement");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("fails requests assigned to a browser stream when that stream reconnects", () =>
|
||||
it.effect("fails requests assigned to the stream that is replaced", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* PreviewAutomationBroker.make;
|
||||
const _requests = yield* broker.connect(makeOwner());
|
||||
const broker = yield* makeBroker;
|
||||
const requests = requestsFrom(yield* broker.connect(makeHost()));
|
||||
yield* Stream.runDrain(requests).pipe(Effect.forkScoped);
|
||||
const pending = yield* broker
|
||||
.invoke<void>({ scope, operation: "status", input: {} })
|
||||
.pipe(Effect.flip, Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
const _replacementRequests = yield* broker.connect(makeOwner());
|
||||
const replacementRequests = requestsFrom(yield* broker.connect(makeHost()));
|
||||
yield* Stream.runDrain(replacementRequests).pipe(Effect.forkScoped);
|
||||
|
||||
const error = yield* Fiber.join(pending);
|
||||
expect(error).toBeInstanceOf(PreviewAutomationClientDisconnectedError);
|
||||
@@ -275,25 +770,40 @@ it.effect("fails requests assigned to a browser stream when that stream reconnec
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("falls back to an older connected owner when a newer report is not connected", () =>
|
||||
it.effect("accepts responses only from the host that received the request", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* PreviewAutomationBroker.make;
|
||||
const requests = yield* broker.connect(makeOwner({ clientId: "client-connected" }));
|
||||
const broker = yield* makeBroker;
|
||||
const requests = requestsFrom(yield* broker.connect(makeHost()));
|
||||
yield* Stream.runForEach(requests, (request) =>
|
||||
broker.respond({ requestId: request.requestId, ok: true, result: "connected" }),
|
||||
Effect.gen(function* () {
|
||||
yield* broker.respond({
|
||||
clientId: "client-foreign",
|
||||
connectionId: request.connectionId,
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
result: "foreign",
|
||||
});
|
||||
yield* broker.respond({
|
||||
clientId: "client-1",
|
||||
connectionId: "connection-stale",
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
result: "stale",
|
||||
});
|
||||
yield* broker.respond({
|
||||
clientId: "client-1",
|
||||
connectionId: request.connectionId,
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
result: "owner",
|
||||
});
|
||||
}),
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
yield* broker.reportOwner(
|
||||
makeOwner({
|
||||
clientId: "client-report-only",
|
||||
focusedAt: "2026-06-11T00:00:01.000Z",
|
||||
}),
|
||||
);
|
||||
|
||||
const result = yield* broker.invoke<string>({ scope, operation: "status", input: {} });
|
||||
|
||||
expect(result).toBe("connected");
|
||||
expect(result).toBe("owner");
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -1,26 +1,29 @@
|
||||
import {
|
||||
PREVIEW_AUTOMATION_V1_OPERATIONS,
|
||||
PreviewAutomationClientDisconnectedError,
|
||||
PreviewAutomationControlInterruptedError,
|
||||
PreviewAutomationExecutionError,
|
||||
PreviewAutomationHostNotConnectedError,
|
||||
PreviewAutomationInvalidSelectorError,
|
||||
PreviewAutomationMalformedResponseError,
|
||||
PreviewAutomationNoFocusedOwnerError,
|
||||
PreviewAutomationNoAvailableHostError,
|
||||
PreviewAutomationRemoteUnavailableError,
|
||||
PreviewAutomationRequestQueueClosedError,
|
||||
PreviewAutomationResultTooLargeError,
|
||||
PreviewAutomationTabNotFoundError,
|
||||
PreviewAutomationTargetNotEditableError,
|
||||
PreviewAutomationTimeoutError,
|
||||
PreviewAutomationUnsupportedClientError,
|
||||
type PreviewAutomationError,
|
||||
type PreviewAutomationOperation,
|
||||
type PreviewAutomationOwner,
|
||||
type PreviewAutomationOwnerIdentity,
|
||||
type PreviewAutomationRequest,
|
||||
type PreviewAutomationHost,
|
||||
type PreviewAutomationHostFocus,
|
||||
type PreviewAutomationResponse,
|
||||
type PreviewAutomationStreamEvent,
|
||||
type PreviewTabId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Clock from "effect/Clock";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
@@ -43,12 +46,9 @@ export class PreviewAutomationBroker extends Context.Service<
|
||||
PreviewAutomationBroker,
|
||||
{
|
||||
readonly connect: (
|
||||
owner: PreviewAutomationOwner,
|
||||
) => Effect.Effect<Stream.Stream<PreviewAutomationRequest>>;
|
||||
readonly reportOwner: (
|
||||
owner: PreviewAutomationOwner,
|
||||
) => Effect.Effect<void, PreviewAutomationError>;
|
||||
readonly clearOwner: (owner: PreviewAutomationOwnerIdentity) => Effect.Effect<void>;
|
||||
host: PreviewAutomationHost,
|
||||
) => Effect.Effect<Stream.Stream<PreviewAutomationStreamEvent>>;
|
||||
readonly focusHost: (host: PreviewAutomationHostFocus) => Effect.Effect<void>;
|
||||
readonly respond: (
|
||||
response: PreviewAutomationResponse,
|
||||
) => Effect.Effect<void, PreviewAutomationError>;
|
||||
@@ -60,7 +60,12 @@ export class PreviewAutomationBroker extends Context.Service<
|
||||
|
||||
interface ClientConnection {
|
||||
readonly clientId: string;
|
||||
readonly queue: Queue.Queue<PreviewAutomationRequest>;
|
||||
readonly connectionId: string;
|
||||
readonly environmentId: PreviewAutomationHost["environmentId"];
|
||||
readonly supportedOperations: ReadonlySet<PreviewAutomationOperation>;
|
||||
readonly focused: boolean;
|
||||
readonly focusOrder: number;
|
||||
readonly queue: Queue.Queue<PreviewAutomationStreamEvent>;
|
||||
}
|
||||
|
||||
interface PendingRequest {
|
||||
@@ -69,6 +74,13 @@ interface PendingRequest {
|
||||
readonly context: PreviewAutomationRequestErrorContext;
|
||||
}
|
||||
|
||||
interface HostAssignment {
|
||||
readonly clientId: ClientConnection["clientId"];
|
||||
readonly connectionId: ClientConnection["connectionId"];
|
||||
readonly queue: ClientConnection["queue"];
|
||||
readonly expiresAt: number;
|
||||
}
|
||||
|
||||
interface PreviewAutomationRequestErrorContext {
|
||||
readonly operation: PreviewAutomationOperation;
|
||||
readonly environmentId: McpInvocationContext.McpInvocationScope["environmentId"];
|
||||
@@ -76,6 +88,7 @@ interface PreviewAutomationRequestErrorContext {
|
||||
readonly providerSessionId: string;
|
||||
readonly providerInstanceId: McpInvocationContext.McpInvocationScope["providerInstanceId"];
|
||||
readonly clientId: string;
|
||||
readonly connectionId: ClientConnection["connectionId"];
|
||||
readonly requestId: string;
|
||||
readonly tabId?: PreviewTabId;
|
||||
readonly timeoutMs: number;
|
||||
@@ -85,11 +98,36 @@ interface PreviewAutomationRequestErrorContext {
|
||||
|
||||
interface BrokerState {
|
||||
readonly clients: ReadonlyMap<string, ClientConnection>;
|
||||
readonly owners: ReadonlyMap<string, PreviewAutomationOwner>;
|
||||
readonly assignments: ReadonlyMap<string, HostAssignment>;
|
||||
readonly pending: ReadonlyMap<string, PendingRequest>;
|
||||
readonly requestSequence: number;
|
||||
readonly focusSequence: number;
|
||||
}
|
||||
|
||||
const removeConnectionFromState = (
|
||||
current: BrokerState,
|
||||
clientId: string,
|
||||
queue: ClientConnection["queue"],
|
||||
): { readonly state: BrokerState; readonly disconnected: ReadonlyArray<PendingRequest> } => {
|
||||
const clients = new Map(current.clients);
|
||||
const assignments = new Map(current.assignments);
|
||||
const pending = new Map(current.pending);
|
||||
const disconnected: PendingRequest[] = [];
|
||||
if (current.clients.get(clientId)?.queue === queue) clients.delete(clientId);
|
||||
for (const [assignmentKey, assignment] of assignments) {
|
||||
if (assignment.queue === queue) assignments.delete(assignmentKey);
|
||||
}
|
||||
for (const [requestId, entry] of pending) {
|
||||
if (entry.queue !== queue) continue;
|
||||
pending.delete(requestId);
|
||||
disconnected.push(entry);
|
||||
}
|
||||
return {
|
||||
state: { ...current, clients, assignments, pending },
|
||||
disconnected,
|
||||
};
|
||||
};
|
||||
|
||||
const selectorDiagnosticsFromInput = (
|
||||
input: unknown,
|
||||
): Pick<PreviewAutomationRequestErrorContext, "selectorKind" | "selectorLength"> => {
|
||||
@@ -103,6 +141,14 @@ const selectorDiagnosticsFromInput = (
|
||||
return {};
|
||||
};
|
||||
|
||||
const hostAssignmentKey = (scope: McpInvocationContext.McpInvocationScope): string =>
|
||||
`${scope.environmentId}\u0000${scope.providerSessionId}`;
|
||||
|
||||
const supportsOperation = (
|
||||
connection: ClientConnection,
|
||||
operation: PreviewAutomationOperation,
|
||||
): boolean => connection.supportedOperations.has(operation);
|
||||
|
||||
type RemoteDetailKind = "null" | "array" | "object" | "string" | "number" | "boolean";
|
||||
|
||||
function remoteDetailKind(detail: unknown): RemoteDetailKind {
|
||||
@@ -131,8 +177,8 @@ const classifyResponseError = (
|
||||
cause: error,
|
||||
};
|
||||
switch (error._tag) {
|
||||
case "PreviewAutomationNoFocusedOwnerError":
|
||||
return new PreviewAutomationNoFocusedOwnerError({
|
||||
case "PreviewAutomationNoAvailableHostError":
|
||||
return new PreviewAutomationNoAvailableHostError({
|
||||
...context,
|
||||
...remoteDiagnostics,
|
||||
});
|
||||
@@ -162,6 +208,36 @@ const classifyResponseError = (
|
||||
...remoteDiagnostics,
|
||||
});
|
||||
}
|
||||
case "PreviewAutomationTargetNotEditableError": {
|
||||
const detail =
|
||||
typeof error.detail === "object" && error.detail !== null ? error.detail : undefined;
|
||||
const remoteSelectorKind =
|
||||
detail &&
|
||||
"selectorKind" in detail &&
|
||||
(detail.selectorKind === "focused-element" ||
|
||||
detail.selectorKind === "locator" ||
|
||||
detail.selectorKind === "selector")
|
||||
? detail.selectorKind
|
||||
: undefined;
|
||||
const remoteSelectorLength =
|
||||
detail &&
|
||||
"selectorLength" in detail &&
|
||||
typeof detail.selectorLength === "number" &&
|
||||
Number.isInteger(detail.selectorLength) &&
|
||||
detail.selectorLength >= 0
|
||||
? detail.selectorLength
|
||||
: undefined;
|
||||
return new PreviewAutomationTargetNotEditableError({
|
||||
...context,
|
||||
...remoteDiagnostics,
|
||||
...(remoteSelectorKind === undefined && context.selectorKind === undefined
|
||||
? {}
|
||||
: { selectorKind: remoteSelectorKind ?? context.selectorKind }),
|
||||
...(remoteSelectorLength === undefined && context.selectorLength === undefined
|
||||
? {}
|
||||
: { selectorLength: remoteSelectorLength ?? context.selectorLength }),
|
||||
});
|
||||
}
|
||||
case "PreviewAutomationResultTooLargeError": {
|
||||
const detail =
|
||||
typeof error.detail === "object" && error.detail !== null ? error.detail : undefined;
|
||||
@@ -193,36 +269,21 @@ const classifyResponseError = (
|
||||
};
|
||||
|
||||
export const make = Effect.gen(function* PreviewAutomationBrokerMake() {
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const state = yield* SynchronizedRef.make<BrokerState>({
|
||||
clients: new Map(),
|
||||
owners: new Map(),
|
||||
assignments: new Map(),
|
||||
pending: new Map(),
|
||||
requestSequence: 0,
|
||||
focusSequence: 0,
|
||||
});
|
||||
|
||||
const disconnect = Effect.fn("PreviewAutomationBroker.disconnect")(function* (
|
||||
clientId: string,
|
||||
const closeConnection = Effect.fn("PreviewAutomationBroker.closeConnection")(function* (
|
||||
queue: ClientConnection["queue"],
|
||||
disconnected: ReadonlyArray<PendingRequest>,
|
||||
) {
|
||||
const toFail = yield* SynchronizedRef.modify(state, (current) => {
|
||||
const clients = new Map(current.clients);
|
||||
const owners = new Map(current.owners);
|
||||
const pending = new Map(current.pending);
|
||||
const disconnected: PendingRequest[] = [];
|
||||
if (current.clients.get(clientId)?.queue === queue) {
|
||||
clients.delete(clientId);
|
||||
owners.delete(clientId);
|
||||
}
|
||||
for (const [requestId, entry] of pending) {
|
||||
if (entry.queue === queue) {
|
||||
pending.delete(requestId);
|
||||
disconnected.push(entry);
|
||||
}
|
||||
}
|
||||
return [disconnected, { ...current, clients, owners, pending }] as const;
|
||||
});
|
||||
yield* Effect.forEach(
|
||||
toFail,
|
||||
disconnected,
|
||||
({ deferred, context }) =>
|
||||
Deferred.fail(deferred, new PreviewAutomationClientDisconnectedError(context)),
|
||||
{ discard: true },
|
||||
@@ -230,54 +291,89 @@ export const make = Effect.gen(function* PreviewAutomationBrokerMake() {
|
||||
yield* Queue.shutdown(queue);
|
||||
});
|
||||
|
||||
const disconnect = Effect.fn("PreviewAutomationBroker.disconnect")(function* (
|
||||
clientId: string,
|
||||
queue: ClientConnection["queue"],
|
||||
) {
|
||||
const disconnected = yield* SynchronizedRef.modify(state, (current) => {
|
||||
const removed = removeConnectionFromState(current, clientId, queue);
|
||||
return [removed.disconnected, removed.state] as const;
|
||||
});
|
||||
yield* closeConnection(queue, disconnected);
|
||||
});
|
||||
|
||||
const acquireConnection = Effect.fn("PreviewAutomationBroker.acquireConnection")(function* (
|
||||
host: PreviewAutomationHost,
|
||||
) {
|
||||
const clientId = host.clientId;
|
||||
const queue = yield* Queue.unbounded<PreviewAutomationStreamEvent>();
|
||||
const connectionId = yield* crypto.randomUUIDv4.pipe(Effect.orDie);
|
||||
yield* Queue.offer(queue, { type: "connected", connectionId });
|
||||
const connection: ClientConnection = {
|
||||
clientId,
|
||||
connectionId,
|
||||
environmentId: host.environmentId,
|
||||
supportedOperations: new Set(host.supportedOperations ?? PREVIEW_AUTOMATION_V1_OPERATIONS),
|
||||
focused: false,
|
||||
focusOrder: 0,
|
||||
queue,
|
||||
};
|
||||
const registration = yield* SynchronizedRef.modify(state, (current) => {
|
||||
const previousConnection = current.clients.get(clientId);
|
||||
const removed = previousConnection
|
||||
? removeConnectionFromState(current, clientId, previousConnection.queue)
|
||||
: { state: current, disconnected: [] };
|
||||
const clients = new Map(removed.state.clients);
|
||||
const focusSequence = removed.state.focusSequence + 1;
|
||||
const registeredConnection = { ...connection, focusOrder: focusSequence };
|
||||
clients.set(clientId, registeredConnection);
|
||||
return [
|
||||
{
|
||||
previousConnection,
|
||||
disconnected: removed.disconnected,
|
||||
registeredConnection,
|
||||
},
|
||||
{ ...removed.state, clients, focusSequence },
|
||||
] as const;
|
||||
});
|
||||
if (registration.previousConnection) {
|
||||
yield* closeConnection(registration.previousConnection.queue, registration.disconnected);
|
||||
}
|
||||
return registration.registeredConnection;
|
||||
});
|
||||
|
||||
const connect: PreviewAutomationBroker["Service"]["connect"] = Effect.fn(
|
||||
"PreviewAutomationBroker.connect",
|
||||
)(function* (owner) {
|
||||
const clientId = owner.clientId;
|
||||
const queue = yield* Queue.unbounded<import("@t3tools/contracts").PreviewAutomationRequest>();
|
||||
const previous = yield* SynchronizedRef.modify(state, (current) => {
|
||||
const clients = new Map(current.clients);
|
||||
const owners = new Map(current.owners);
|
||||
const existingOwner = current.owners.get(clientId);
|
||||
clients.set(clientId, { clientId, queue });
|
||||
owners.set(
|
||||
clientId,
|
||||
existingOwner?.environmentId === owner.environmentId &&
|
||||
existingOwner.threadId === owner.threadId
|
||||
? { ...existingOwner, supportsAutomation: owner.supportsAutomation }
|
||||
: owner,
|
||||
);
|
||||
return [current.clients.get(clientId), { ...current, clients, owners }] as const;
|
||||
});
|
||||
if (previous) yield* disconnect(clientId, previous.queue);
|
||||
return Stream.fromQueue(queue).pipe(Stream.ensuring(disconnect(clientId, queue)));
|
||||
});
|
||||
)((host) =>
|
||||
Effect.succeed(
|
||||
Stream.unwrap(
|
||||
Effect.acquireRelease(acquireConnection(host), (connection) =>
|
||||
disconnect(connection.clientId, connection.queue),
|
||||
).pipe(Effect.map((connection) => Stream.fromQueue(connection.queue))),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const reportOwner: PreviewAutomationBroker["Service"]["reportOwner"] = Effect.fn(
|
||||
"PreviewAutomationBroker.reportOwner",
|
||||
)(function* (owner) {
|
||||
const focusHost: PreviewAutomationBroker["Service"]["focusHost"] = Effect.fn(
|
||||
"PreviewAutomationBroker.focusHost",
|
||||
)(function* (host) {
|
||||
yield* SynchronizedRef.update(state, (current) => {
|
||||
const owners = new Map(current.owners);
|
||||
owners.set(owner.clientId, owner);
|
||||
return { ...current, owners };
|
||||
});
|
||||
});
|
||||
|
||||
const clearOwner: PreviewAutomationBroker["Service"]["clearOwner"] = Effect.fn(
|
||||
"PreviewAutomationBroker.clearOwner",
|
||||
)(function* (owner) {
|
||||
yield* SynchronizedRef.update(state, (current) => {
|
||||
const currentOwner = current.owners.get(owner.clientId);
|
||||
const currentHost = current.clients.get(host.clientId);
|
||||
if (
|
||||
!currentOwner ||
|
||||
currentOwner.environmentId !== owner.environmentId ||
|
||||
currentOwner.threadId !== owner.threadId
|
||||
!currentHost ||
|
||||
currentHost.environmentId !== host.environmentId ||
|
||||
currentHost.connectionId !== host.connectionId
|
||||
) {
|
||||
return current;
|
||||
}
|
||||
const owners = new Map(current.owners);
|
||||
owners.delete(owner.clientId);
|
||||
return { ...current, owners };
|
||||
const clients = new Map(current.clients);
|
||||
const focusSequence = host.focused ? current.focusSequence + 1 : current.focusSequence;
|
||||
clients.set(host.clientId, {
|
||||
...currentHost,
|
||||
focused: host.focused,
|
||||
focusOrder: host.focused ? focusSequence : currentHost.focusOrder,
|
||||
});
|
||||
return { ...current, clients, focusSequence };
|
||||
});
|
||||
});
|
||||
|
||||
@@ -286,7 +382,13 @@ export const make = Effect.gen(function* PreviewAutomationBrokerMake() {
|
||||
)(function* (response) {
|
||||
const pending = yield* SynchronizedRef.modify(state, (current) => {
|
||||
const entry = current.pending.get(response.requestId);
|
||||
if (!entry) return [undefined, current] as const;
|
||||
if (
|
||||
!entry ||
|
||||
entry.context.clientId !== response.clientId ||
|
||||
entry.context.connectionId !== response.connectionId
|
||||
) {
|
||||
return [undefined, current] as const;
|
||||
}
|
||||
const next = new Map(current.pending);
|
||||
next.delete(response.requestId);
|
||||
return [entry, { ...current, pending: next }] as const;
|
||||
@@ -307,52 +409,60 @@ export const make = Effect.gen(function* PreviewAutomationBrokerMake() {
|
||||
const invoke = Effect.fn("PreviewAutomationBroker.invoke")(function* <A = unknown>(
|
||||
input: Parameters<PreviewAutomationBroker["Service"]["invoke"]>[0],
|
||||
): Effect.fn.Return<A, PreviewAutomationError> {
|
||||
const current = yield* SynchronizedRef.get(state);
|
||||
const candidates = Array.from(current.owners.values())
|
||||
.filter(
|
||||
(owner) =>
|
||||
owner.environmentId === input.scope.environmentId &&
|
||||
owner.threadId === input.scope.threadId &&
|
||||
owner.supportsAutomation,
|
||||
)
|
||||
.sort((left, right) => right.focusedAt.localeCompare(left.focusedAt));
|
||||
const owner = candidates.find((candidate) => current.clients.has(candidate.clientId));
|
||||
if (!owner) {
|
||||
const disconnectedOwner = candidates[0];
|
||||
if (disconnectedOwner) {
|
||||
return yield* new PreviewAutomationHostNotConnectedError({
|
||||
operation: input.operation,
|
||||
environmentId: input.scope.environmentId,
|
||||
threadId: input.scope.threadId,
|
||||
providerSessionId: input.scope.providerSessionId,
|
||||
providerInstanceId: input.scope.providerInstanceId,
|
||||
clientId: disconnectedOwner.clientId,
|
||||
});
|
||||
}
|
||||
return yield* new PreviewAutomationNoFocusedOwnerError({
|
||||
operation: input.operation,
|
||||
environmentId: input.scope.environmentId,
|
||||
threadId: input.scope.threadId,
|
||||
providerSessionId: input.scope.providerSessionId,
|
||||
providerInstanceId: input.scope.providerInstanceId,
|
||||
});
|
||||
}
|
||||
const connection = current.clients.get(owner.clientId);
|
||||
if (!connection) {
|
||||
return yield* new PreviewAutomationHostNotConnectedError({
|
||||
operation: input.operation,
|
||||
environmentId: input.scope.environmentId,
|
||||
threadId: input.scope.threadId,
|
||||
providerSessionId: input.scope.providerSessionId,
|
||||
providerInstanceId: input.scope.providerInstanceId,
|
||||
clientId: owner.clientId,
|
||||
});
|
||||
}
|
||||
const timeoutMs = input.timeoutMs ?? 15_000;
|
||||
const deferred = yield* Deferred.make<unknown, PreviewAutomationError>();
|
||||
const [requestId, requestContext] = yield* SynchronizedRef.modify(state, (next) => {
|
||||
const requestId = `preview-${next.requestSequence}`;
|
||||
const tabId = input.tabId ?? owner.tabId ?? undefined;
|
||||
const now = yield* Clock.currentTimeMillis;
|
||||
const route = yield* SynchronizedRef.modify(state, (current) => {
|
||||
const assignments = new Map(
|
||||
Array.from(current.assignments).filter(([, assignment]) => {
|
||||
const connection = current.clients.get(assignment.clientId);
|
||||
return (
|
||||
assignment.expiresAt > now &&
|
||||
connection?.connectionId === assignment.connectionId &&
|
||||
connection.queue === assignment.queue
|
||||
);
|
||||
}),
|
||||
);
|
||||
const assignmentKey = hostAssignmentKey(input.scope);
|
||||
const assigned = assignments.get(assignmentKey);
|
||||
const assignedConnection = assigned ? current.clients.get(assigned.clientId) : undefined;
|
||||
const hasLiveAssignment = assignedConnection?.environmentId === input.scope.environmentId;
|
||||
// Keep one provider session on one physical desktop runtime so a
|
||||
// multi-step browser interaction cannot jump between independent
|
||||
// Electron cookie/DOM state. A live assignment that predates an
|
||||
// operation is not silently moved to a newer client: the caller gets a
|
||||
// capability failure and can deliberately start a fresh provider
|
||||
// session. A dead lease is pruned above and may fail over.
|
||||
const connection =
|
||||
hasLiveAssignment && supportsOperation(assignedConnection, input.operation)
|
||||
? assignedConnection
|
||||
: hasLiveAssignment
|
||||
? undefined
|
||||
: Array.from(current.clients.values())
|
||||
.filter(
|
||||
(host) =>
|
||||
host.environmentId === input.scope.environmentId &&
|
||||
supportsOperation(host, input.operation),
|
||||
)
|
||||
.sort(
|
||||
(left, right) =>
|
||||
right.supportedOperations.size - left.supportedOperations.size ||
|
||||
Number(right.focused) - Number(left.focused) ||
|
||||
right.focusOrder - left.focusOrder,
|
||||
)[0];
|
||||
if (!connection) {
|
||||
if (!hasLiveAssignment) assignments.delete(assignmentKey);
|
||||
return [undefined, { ...current, assignments }] as const;
|
||||
}
|
||||
assignments.set(assignmentKey, {
|
||||
clientId: connection.clientId,
|
||||
connectionId: connection.connectionId,
|
||||
queue: connection.queue,
|
||||
expiresAt: input.scope.expiresAt,
|
||||
});
|
||||
|
||||
const requestId = `preview-${current.requestSequence}`;
|
||||
const tabId = input.tabId;
|
||||
const selectorDiagnostics = selectorDiagnosticsFromInput(input.input);
|
||||
const context: PreviewAutomationRequestErrorContext = {
|
||||
operation: input.operation,
|
||||
@@ -360,19 +470,30 @@ export const make = Effect.gen(function* PreviewAutomationBrokerMake() {
|
||||
threadId: input.scope.threadId,
|
||||
providerSessionId: input.scope.providerSessionId,
|
||||
providerInstanceId: input.scope.providerInstanceId,
|
||||
clientId: owner.clientId,
|
||||
clientId: connection.clientId,
|
||||
connectionId: connection.connectionId,
|
||||
requestId,
|
||||
...(tabId === undefined ? {} : { tabId }),
|
||||
timeoutMs,
|
||||
...selectorDiagnostics,
|
||||
};
|
||||
const pending = new Map(next.pending);
|
||||
const pending = new Map(current.pending);
|
||||
pending.set(requestId, { queue: connection.queue, deferred, context });
|
||||
return [
|
||||
[requestId, context] as const,
|
||||
{ ...next, pending, requestSequence: next.requestSequence + 1 },
|
||||
{ connection, requestId, requestContext: context },
|
||||
{ ...current, assignments, pending, requestSequence: current.requestSequence + 1 },
|
||||
] as const;
|
||||
});
|
||||
if (!route) {
|
||||
return yield* new PreviewAutomationNoAvailableHostError({
|
||||
operation: input.operation,
|
||||
environmentId: input.scope.environmentId,
|
||||
threadId: input.scope.threadId,
|
||||
providerSessionId: input.scope.providerSessionId,
|
||||
providerInstanceId: input.scope.providerInstanceId,
|
||||
});
|
||||
}
|
||||
const { connection, requestId, requestContext } = route;
|
||||
const removePending = SynchronizedRef.update(state, (next) => {
|
||||
if (!next.pending.has(requestId)) return next;
|
||||
const pending = new Map(next.pending);
|
||||
@@ -381,12 +502,16 @@ export const make = Effect.gen(function* PreviewAutomationBrokerMake() {
|
||||
});
|
||||
const awaitResponse = Effect.fn("PreviewAutomationBroker.awaitResponse")(function* () {
|
||||
const offered = yield* Queue.offer(connection.queue, {
|
||||
requestId,
|
||||
threadId: input.scope.threadId,
|
||||
tabId: requestContext.tabId,
|
||||
operation: input.operation,
|
||||
input: input.input,
|
||||
timeoutMs,
|
||||
type: "request",
|
||||
connectionId: connection.connectionId,
|
||||
request: {
|
||||
requestId,
|
||||
threadId: input.scope.threadId,
|
||||
tabId: requestContext.tabId,
|
||||
operation: input.operation,
|
||||
input: input.input,
|
||||
timeoutMs,
|
||||
},
|
||||
});
|
||||
if (!offered) {
|
||||
const completion = yield* Deferred.poll(deferred);
|
||||
@@ -404,7 +529,7 @@ export const make = Effect.gen(function* PreviewAutomationBrokerMake() {
|
||||
return yield* awaitResponse().pipe(Effect.ensuring(removePending));
|
||||
});
|
||||
|
||||
return PreviewAutomationBroker.of({ connect, reportOwner, clearOwner, respond, invoke });
|
||||
return PreviewAutomationBroker.of({ connect, focusHost, respond, invoke });
|
||||
}).pipe(Effect.withSpan("PreviewAutomationBroker.make"));
|
||||
|
||||
export const layer = Layer.effect(PreviewAutomationBroker, make);
|
||||
@@ -3,6 +3,7 @@ import type {
|
||||
PreviewAutomationOperation,
|
||||
PreviewAutomationRecordingArtifact,
|
||||
PreviewAutomationRecordingStatus,
|
||||
PreviewAutomationResizeResult,
|
||||
PreviewAutomationSnapshot,
|
||||
PreviewAutomationStatus,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -39,6 +40,8 @@ const handlers = {
|
||||
reuseExistingTab: input.reuseExistingTab ?? true,
|
||||
}),
|
||||
preview_navigate: (input) => invoke<PreviewAutomationStatus>("navigate", input, input.timeoutMs),
|
||||
preview_resize: (input) =>
|
||||
invoke<PreviewAutomationResizeResult>("resize", input, input.timeoutMs),
|
||||
preview_snapshot: () => invoke<PreviewAutomationSnapshot>("snapshot", {}),
|
||||
preview_click: (input) => invoke<void>("click", input, input.timeoutMs).pipe(Effect.as(null)),
|
||||
preview_type: (input) => invoke<void>("type", input, input.timeoutMs).pipe(Effect.as(null)),
|
||||
|
||||
@@ -7,6 +7,8 @@ import {
|
||||
PreviewAutomationPressInput,
|
||||
PreviewAutomationRecordingArtifact,
|
||||
PreviewAutomationRecordingStatus,
|
||||
PreviewAutomationResizeInput,
|
||||
PreviewAutomationResizeResult,
|
||||
PreviewAutomationScrollInput,
|
||||
PreviewAutomationSnapshot,
|
||||
PreviewAutomationStatus,
|
||||
@@ -35,7 +37,7 @@ const readonlyBrowserTool = <T extends Tool.Any>(tool: T): T =>
|
||||
|
||||
export const PreviewStatusTool = Tool.make("preview_status", {
|
||||
description:
|
||||
"Report whether the scoped thread has an automation-capable desktop preview, including its active tab, URL, title, visibility, and loading state.",
|
||||
"Report whether the scoped thread has an automation-capable desktop preview, including its active tab, URL, title, visibility, loading state, viewport mode, and measured CSS-pixel size.",
|
||||
success: PreviewAutomationStatus,
|
||||
failure: PreviewAutomationError,
|
||||
dependencies,
|
||||
@@ -69,6 +71,19 @@ export const PreviewNavigateTool = safeBrowserTool(
|
||||
}).annotate(Tool.Title, "Navigate browser preview"),
|
||||
);
|
||||
|
||||
export const PreviewResizeTool = safeBrowserTool(
|
||||
Tool.make("preview_resize", {
|
||||
description:
|
||||
"Set the active collaborative browser tab to fill-panel sizing, an independently resizable freeform size, or a Chrome-standard device preset. Use {mode:'fill'}, {mode:'freeform',width:1024,height:768}, or {mode:'preset',preset:'iphone-12-pro',orientation:'portrait'}. This changes CSS layout breakpoints without changing the desktop browser user agent.",
|
||||
parameters: PreviewAutomationResizeInput,
|
||||
success: PreviewAutomationResizeResult,
|
||||
failure: PreviewAutomationError,
|
||||
dependencies,
|
||||
})
|
||||
.annotate(Tool.Title, "Resize browser viewport")
|
||||
.annotate(Tool.Idempotent, true),
|
||||
);
|
||||
|
||||
export const PreviewSnapshotTool = readonlyBrowserTool(
|
||||
Tool.make("preview_snapshot", {
|
||||
description:
|
||||
@@ -168,6 +183,7 @@ export const PreviewToolkit = Toolkit.make(
|
||||
PreviewStatusTool,
|
||||
PreviewOpenTool,
|
||||
PreviewNavigateTool,
|
||||
PreviewResizeTool,
|
||||
PreviewSnapshotTool,
|
||||
PreviewClickTool,
|
||||
PreviewTypeTool,
|
||||
@@ -183,6 +199,7 @@ export const PreviewStandardToolkit = Toolkit.make(
|
||||
PreviewStatusTool,
|
||||
PreviewOpenTool,
|
||||
PreviewNavigateTool,
|
||||
PreviewResizeTool,
|
||||
PreviewClickTool,
|
||||
PreviewTypeTool,
|
||||
PreviewPressTool,
|
||||
|
||||
@@ -151,6 +151,61 @@ it.layer(PreviewManager.layer)("PreviewManager", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("resizes a tab and preserves its viewport across navigation reports", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = freshThreadId();
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
const collector = yield* collectEvents;
|
||||
const opened = yield* manager.open({ threadId, url: "http://localhost:5173" });
|
||||
|
||||
const resized = yield* manager.resize({
|
||||
threadId,
|
||||
tabId: opened.tabId,
|
||||
viewport: { _tag: "freeform", width: 1024, height: 768 },
|
||||
});
|
||||
expect(resized.viewport).toEqual({ _tag: "freeform", width: 1024, height: 768 });
|
||||
|
||||
const navigated = yield* manager.navigate({
|
||||
threadId,
|
||||
tabId: opened.tabId,
|
||||
url: "http://localhost:5173/resized",
|
||||
});
|
||||
expect(navigated.viewport).toEqual(resized.viewport);
|
||||
|
||||
yield* manager.reportStatus({
|
||||
threadId,
|
||||
tabId: opened.tabId,
|
||||
navStatus: { _tag: "Success", url: "http://localhost:5173/resized", title: "Resized" },
|
||||
canGoBack: true,
|
||||
canGoForward: false,
|
||||
});
|
||||
const listed = yield* manager.list({ threadId });
|
||||
expect(listed.sessions[0]?.viewport).toEqual(resized.viewport);
|
||||
|
||||
const events = yield* collector.drain;
|
||||
expect(events.map((event) => event.type)).toEqual([
|
||||
"opened",
|
||||
"resized",
|
||||
"navigated",
|
||||
"navigated",
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects resize for an unknown tab", () =>
|
||||
Effect.gen(function* () {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
const error = yield* Effect.flip(
|
||||
manager.resize({
|
||||
threadId: freshThreadId(),
|
||||
tabId: "tab_missing",
|
||||
viewport: { _tag: "fill" },
|
||||
}),
|
||||
);
|
||||
expect(error._tag).toBe("PreviewSessionLookupError");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reportStatus emits failed for LoadFailed nav", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = freshThreadId();
|
||||
|
||||
@@ -20,6 +20,8 @@ import {
|
||||
type PreviewOpenInput,
|
||||
type PreviewRefreshInput,
|
||||
type PreviewReportStatusInput,
|
||||
type PreviewResizeInput,
|
||||
FILL_PREVIEW_VIEWPORT,
|
||||
PreviewSessionLookupError,
|
||||
type PreviewSessionSnapshot,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -45,6 +47,9 @@ export class PreviewManager extends Context.Service<
|
||||
input: PreviewNavigateInput,
|
||||
) => Effect.Effect<PreviewSessionSnapshot, PreviewError>;
|
||||
readonly reportStatus: (input: PreviewReportStatusInput) => Effect.Effect<void, PreviewError>;
|
||||
readonly resize: (
|
||||
input: PreviewResizeInput,
|
||||
) => Effect.Effect<PreviewSessionSnapshot, PreviewError>;
|
||||
readonly refresh: (input: PreviewRefreshInput) => Effect.Effect<void, PreviewError>;
|
||||
readonly close: (input: PreviewCloseInput) => Effect.Effect<void, PreviewError>;
|
||||
readonly list: (input: PreviewListInput) => Effect.Effect<PreviewListResult>;
|
||||
@@ -114,6 +119,7 @@ const buildLoadingSnapshot = (input: {
|
||||
navStatus: { _tag: "Loading", url: input.url, title: input.title },
|
||||
canGoBack: false,
|
||||
canGoForward: false,
|
||||
viewport: FILL_PREVIEW_VIEWPORT,
|
||||
updatedAt: input.updatedAt,
|
||||
});
|
||||
|
||||
@@ -127,6 +133,7 @@ const buildIdleSnapshot = (input: {
|
||||
navStatus: { _tag: "Idle" },
|
||||
canGoBack: false,
|
||||
canGoForward: false,
|
||||
viewport: FILL_PREVIEW_VIEWPORT,
|
||||
updatedAt: input.updatedAt,
|
||||
});
|
||||
|
||||
@@ -237,6 +244,7 @@ export const make = Effect.gen(function* PreviewManagerMake() {
|
||||
navStatus: { _tag: "Success", url, title: resolvedTitle },
|
||||
canGoBack: session.snapshot.canGoBack,
|
||||
canGoForward: session.snapshot.canGoForward,
|
||||
viewport: session.snapshot.viewport ?? FILL_PREVIEW_VIEWPORT,
|
||||
updatedAt,
|
||||
};
|
||||
return {
|
||||
@@ -269,6 +277,7 @@ export const make = Effect.gen(function* PreviewManagerMake() {
|
||||
navStatus: input.navStatus,
|
||||
canGoBack: input.canGoBack,
|
||||
canGoForward: input.canGoForward,
|
||||
viewport: session.snapshot.viewport ?? FILL_PREVIEW_VIEWPORT,
|
||||
updatedAt,
|
||||
};
|
||||
const emit: PreviewEvent =
|
||||
@@ -299,6 +308,34 @@ export const make = Effect.gen(function* PreviewManagerMake() {
|
||||
);
|
||||
});
|
||||
|
||||
const resize: PreviewManager["Service"]["resize"] = Effect.fn("PreviewManager.resize")(
|
||||
function* (input) {
|
||||
return yield* mutateExistingSession(
|
||||
input.threadId,
|
||||
input.tabId,
|
||||
Effect.fn("PreviewManager.resizeSession")(function* (session) {
|
||||
const updatedAt = yield* currentIsoTimestamp;
|
||||
const snapshot: PreviewSessionSnapshot = {
|
||||
...session.snapshot,
|
||||
viewport: input.viewport,
|
||||
updatedAt,
|
||||
};
|
||||
return {
|
||||
next: { ...session, snapshot },
|
||||
emit: {
|
||||
type: "resized",
|
||||
threadId: session.threadId,
|
||||
tabId: session.tabId,
|
||||
createdAt: snapshot.updatedAt,
|
||||
snapshot,
|
||||
},
|
||||
result: snapshot,
|
||||
};
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
const refresh: PreviewManager["Service"]["refresh"] = Effect.fn("PreviewManager.refresh")(
|
||||
function* (input) {
|
||||
// Verify the session exists; the desktop bridge handles the actual reload
|
||||
@@ -360,6 +397,7 @@ export const make = Effect.gen(function* PreviewManagerMake() {
|
||||
open,
|
||||
navigate,
|
||||
reportStatus,
|
||||
resize,
|
||||
refresh,
|
||||
close,
|
||||
list,
|
||||
|
||||
@@ -113,6 +113,23 @@ async function waitForFileContent(filePath: string, attempts = 40) {
|
||||
throw new Error(`Timed out waiting for file content at ${filePath}`);
|
||||
}
|
||||
|
||||
function waitForJsonLogMatch(
|
||||
filePath: string,
|
||||
predicate: (entry: Record<string, unknown>) => boolean,
|
||||
attempts = 40,
|
||||
) {
|
||||
return Effect.gen(function* () {
|
||||
for (let attempt = 0; attempt < attempts; attempt += 1) {
|
||||
const requests = yield* Effect.promise(() => readJsonLines(filePath));
|
||||
if (requests.some(predicate)) {
|
||||
return requests;
|
||||
}
|
||||
yield* Effect.yieldNow;
|
||||
}
|
||||
return yield* Effect.promise(() => readJsonLines(filePath));
|
||||
});
|
||||
}
|
||||
|
||||
// Tests mutate `ServerSettingsService` mid-flight (e.g. setting
|
||||
// `providers.cursor.binaryPath` to a mock ACP wrapper). The adapter
|
||||
// captures `cursorSettings` once at construction, so without a resolver
|
||||
@@ -1004,7 +1021,10 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
|
||||
assert.equal(turnCompleted.payload.stopReason, "cancelled");
|
||||
}
|
||||
|
||||
const requests = yield* Effect.promise(() => readJsonLines(requestLogPath));
|
||||
const requests = yield* waitForJsonLogMatch(
|
||||
requestLogPath,
|
||||
(entry) => entry.method === "session/cancel",
|
||||
);
|
||||
assert.isTrue(requests.some((entry) => entry.method === "session/cancel"));
|
||||
assert.isTrue(
|
||||
requests.some(
|
||||
|
||||
@@ -785,6 +785,9 @@ export function makeCursorAdapter(
|
||||
Stream.mapEffect(acp.getEvents(), (event) =>
|
||||
Effect.gen(function* () {
|
||||
switch (event._tag) {
|
||||
case "EventStreamBarrier":
|
||||
yield* Deferred.succeed(event.acknowledge, undefined);
|
||||
return;
|
||||
case "ModeChanged":
|
||||
return;
|
||||
case "AssistantItemStarted":
|
||||
|
||||
@@ -4,6 +4,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Path from "effect/Path";
|
||||
import type * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
import type * as EffectAcpSchema from "effect-acp/schema";
|
||||
import type { CursorSettings } from "@t3tools/contracts";
|
||||
@@ -24,7 +25,11 @@ import {
|
||||
} from "./CursorProvider.ts";
|
||||
|
||||
const runNode = <A, E>(
|
||||
effect: Effect.Effect<A, E, FileSystem.FileSystem | Path.Path>,
|
||||
effect: Effect.Effect<
|
||||
A,
|
||||
E,
|
||||
ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
|
||||
>,
|
||||
): Promise<A> => Effect.runPromise(effect.pipe(Effect.provide(NodeServices.layer)));
|
||||
|
||||
const resolveMockAgentPath = Effect.fn("resolveMockAgentPath")(function* () {
|
||||
@@ -293,6 +298,18 @@ const baseCursorSettings: CursorSettings = {
|
||||
apiEndpoint: "",
|
||||
customModels: [],
|
||||
};
|
||||
const cursorAcpDiscoveryFailedMessage = [
|
||||
"Cursor ACP model discovery failed.",
|
||||
"Cursor CLI setup may be incomplete; install or enable the Cursor CLI, restart T3 Code, and try again.",
|
||||
"See https://cursor.com/docs/cli/installation.",
|
||||
"Check server logs for ACP details.",
|
||||
].join(" ");
|
||||
const missingCursorBinaryPath = "/definitely/not/installed/t3-cursor-agent";
|
||||
const cursorCliCommandMissingMessage = [
|
||||
`Cursor CLI command \`${missingCursorBinaryPath}\` was not found.`,
|
||||
`Install or enable the Cursor CLI, make sure \`${missingCursorBinaryPath}\` is on PATH, then restart T3 Code.`,
|
||||
"See https://cursor.com/docs/cli/installation.",
|
||||
].join(" ");
|
||||
|
||||
describe("getCursorFallbackModels", () => {
|
||||
it("does not publish any built-in cursor models before ACP discovery", () => {
|
||||
@@ -338,12 +355,11 @@ describe("buildCursorProviderSnapshot", () => {
|
||||
auth: { status: "unauthenticated" },
|
||||
message: "Cursor Agent is not authenticated. Run `agent login` and try again.",
|
||||
},
|
||||
discoveryWarning: "Cursor ACP model discovery failed. Check server logs for details.",
|
||||
discoveryWarning: cursorAcpDiscoveryFailedMessage,
|
||||
}),
|
||||
).toMatchObject({
|
||||
status: "error",
|
||||
message:
|
||||
"Cursor Agent is not authenticated. Run `agent login` and try again. Cursor ACP model discovery failed. Check server logs for details.",
|
||||
message: `Cursor Agent is not authenticated. Run \`agent login\` and try again. ${cursorAcpDiscoveryFailedMessage}`,
|
||||
models: [
|
||||
{
|
||||
slug: "claude-sonnet-4-6",
|
||||
@@ -411,10 +427,28 @@ describe("buildCursorCapabilitiesFromConfigOptions", () => {
|
||||
});
|
||||
|
||||
describe("checkCursorProviderStatus", () => {
|
||||
it("reports the install docs when the Cursor CLI command is missing", async () => {
|
||||
const provider = await runNode(
|
||||
checkCursorProviderStatus({
|
||||
enabled: true,
|
||||
binaryPath: missingCursorBinaryPath,
|
||||
apiEndpoint: "",
|
||||
customModels: [],
|
||||
}),
|
||||
);
|
||||
|
||||
expect(provider).toMatchObject({
|
||||
installed: false,
|
||||
status: "error",
|
||||
auth: { status: "unknown" },
|
||||
message: cursorCliCommandMissingMessage,
|
||||
});
|
||||
});
|
||||
|
||||
it("passes the injected environment to ACP model discovery", async () => {
|
||||
const { requestLogPath, wrapperPath } = await runNode(makeProviderStatusEnvFixture());
|
||||
|
||||
const provider = await Effect.runPromise(
|
||||
const provider = await runNode(
|
||||
checkCursorProviderStatus(
|
||||
{
|
||||
enabled: true,
|
||||
@@ -426,7 +460,7 @@ describe("checkCursorProviderStatus", () => {
|
||||
...process.env,
|
||||
T3_ACP_REQUEST_LOG_PATH: requestLogPath,
|
||||
},
|
||||
).pipe(Effect.provide(NodeServices.layer)),
|
||||
),
|
||||
);
|
||||
|
||||
expect(provider.models.map((model) => model.slug)).toEqual([
|
||||
@@ -443,13 +477,13 @@ describe("discoverCursorModelsViaAcp", () => {
|
||||
it("keeps the ACP probe runtime alive long enough to discover models", async () => {
|
||||
const wrapperPath = await runNode(makeMockAgentWrapper());
|
||||
|
||||
const models = await Effect.runPromise(
|
||||
const models = await runNode(
|
||||
discoverCursorModelsViaAcp({
|
||||
enabled: true,
|
||||
binaryPath: wrapperPath,
|
||||
apiEndpoint: "",
|
||||
customModels: [],
|
||||
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
|
||||
}).pipe(Effect.scoped),
|
||||
);
|
||||
|
||||
expect(models.map((model) => model.slug)).toEqual([
|
||||
@@ -465,13 +499,13 @@ describe("discoverCursorModelsViaAcp", () => {
|
||||
makeExitLogFixture("cursor-provider-exit-log-"),
|
||||
);
|
||||
|
||||
await Effect.runPromise(
|
||||
await runNode(
|
||||
discoverCursorModelsViaAcp({
|
||||
enabled: true,
|
||||
binaryPath: wrapperPath,
|
||||
apiEndpoint: "",
|
||||
customModels: [],
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
}),
|
||||
);
|
||||
|
||||
const exitLog = await runNode(waitForFileContent(exitLogPath));
|
||||
|
||||
@@ -62,6 +62,13 @@ const EMPTY_CAPABILITIES: ModelCapabilities = createModelCapabilities({
|
||||
|
||||
const CURSOR_ACP_MODEL_DISCOVERY_TIMEOUT_MS = 15_000;
|
||||
const CURSOR_PARAMETERIZED_MODEL_PICKER_MIN_VERSION_DATE = 2026_04_08;
|
||||
const CURSOR_CLI_INSTALLATION_DOCS_URL = "https://cursor.com/docs/cli/installation";
|
||||
const CURSOR_ACP_MODEL_DISCOVERY_FAILED_MESSAGE = [
|
||||
"Cursor ACP model discovery failed.",
|
||||
"Cursor CLI setup may be incomplete; install or enable the Cursor CLI, restart T3 Code, and try again.",
|
||||
`See ${CURSOR_CLI_INSTALLATION_DOCS_URL}.`,
|
||||
"Check server logs for ACP details.",
|
||||
].join(" ");
|
||||
export const CURSOR_PARAMETERIZED_MODEL_PICKER_CAPABILITIES = {
|
||||
_meta: {
|
||||
parameterizedModelPicker: true,
|
||||
@@ -608,6 +615,14 @@ function joinProviderMessages(...messages: ReadonlyArray<string | undefined>): s
|
||||
return parts.length > 0 ? parts.join(" ") : undefined;
|
||||
}
|
||||
|
||||
function buildCursorCliCommandMissingMessage(binaryPath: string): string {
|
||||
return [
|
||||
`Cursor CLI command \`${binaryPath}\` was not found.`,
|
||||
`Install or enable the Cursor CLI, make sure \`${binaryPath}\` is on PATH, then restart T3 Code.`,
|
||||
`See ${CURSOR_CLI_INSTALLATION_DOCS_URL}.`,
|
||||
].join(" ");
|
||||
}
|
||||
|
||||
export function buildCursorProviderSnapshot(input: {
|
||||
readonly checkedAt: string;
|
||||
readonly cursorSettings: CursorSettings;
|
||||
@@ -1020,7 +1035,7 @@ export const checkCursorProviderStatus = Effect.fn("checkCursorProviderStatus")(
|
||||
status: "error",
|
||||
auth: { status: "unknown" },
|
||||
message: isCommandMissingCause(error)
|
||||
? "Cursor Agent CLI (`agent`) is not installed or not on PATH."
|
||||
? buildCursorCliCommandMissingMessage(cursorSettings.binaryPath)
|
||||
: "Failed to execute Cursor Agent CLI health check.",
|
||||
},
|
||||
});
|
||||
@@ -1079,7 +1094,7 @@ export const checkCursorProviderStatus = Effect.fn("checkCursorProviderStatus")(
|
||||
yield* Effect.logWarning("Cursor ACP model discovery failed", {
|
||||
errorTag: causeErrorTag(discoveryExit.cause),
|
||||
});
|
||||
discoveryWarning = "Cursor ACP model discovery failed. Check server logs for details.";
|
||||
discoveryWarning = CURSOR_ACP_MODEL_DISCOVERY_FAILED_MESSAGE;
|
||||
} else if (Option.isNone(discoveryExit.value)) {
|
||||
discoveryWarning = `Cursor ACP model discovery timed out after ${CURSOR_ACP_MODEL_DISCOVERY_TIMEOUT_MS}ms.`;
|
||||
} else if (discoveryExit.value.value.length === 0) {
|
||||
|
||||
@@ -10,20 +10,23 @@ import * as Deferred from "effect/Deferred";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
GrokSettings,
|
||||
ProviderDriverKind,
|
||||
ThreadId,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
type ProviderRuntimeEvent,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { makeGrokAdapter } from "./GrokAdapter.ts";
|
||||
import { grokPromptSettlementBelongsToContext, makeGrokAdapter } from "./GrokAdapter.ts";
|
||||
const decodeGrokSettings = Schema.decodeSync(GrokSettings);
|
||||
|
||||
const __dirname = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url));
|
||||
@@ -45,7 +48,11 @@ exec ${JSON.stringify(mockAgentCommand)} ${JSON.stringify(mockAgentPath)} "$@"
|
||||
return wrapperPath;
|
||||
}
|
||||
|
||||
function waitForFileContent(filePath: string, attempts = 40): Effect.Effect<string> {
|
||||
function waitForFileContent(
|
||||
filePath: string,
|
||||
attempts = 40,
|
||||
expectedContent?: string,
|
||||
): Effect.Effect<string> {
|
||||
const readAttempt = (remainingAttempts: number): Effect.Effect<string> =>
|
||||
Effect.gen(function* () {
|
||||
if (remainingAttempts <= 0) {
|
||||
@@ -54,7 +61,10 @@ function waitForFileContent(filePath: string, attempts = 40): Effect.Effect<stri
|
||||
const raw = yield* Effect.tryPromise(() => NodeFSP.readFile(filePath, "utf8")).pipe(
|
||||
Effect.orElseSucceed(() => ""),
|
||||
);
|
||||
if (raw.trim().length > 0) {
|
||||
if (
|
||||
raw.trim().length > 0 &&
|
||||
(expectedContent === undefined || raw.includes(expectedContent))
|
||||
) {
|
||||
return raw;
|
||||
}
|
||||
yield* Effect.sleep("25 millis");
|
||||
@@ -79,6 +89,39 @@ const grokAdapterTestLayer = ServerConfig.layerTest(process.cwd(), {
|
||||
const makeTestAdapter = (binaryPath: string, options?: Parameters<typeof makeGrokAdapter>[1]) =>
|
||||
makeGrokAdapter(decodeGrokSettings({ binaryPath }), options).pipe(Effect.orDie);
|
||||
|
||||
it("requires a settlement to match the live Grok turn", () => {
|
||||
const staleTurnId = TurnId.make("stale-turn");
|
||||
const replacementTurnId = TurnId.make("replacement-turn");
|
||||
|
||||
assert.isFalse(
|
||||
grokPromptSettlementBelongsToContext({
|
||||
liveAcpSessionId: "session-1",
|
||||
expectedAcpSessionId: "session-1",
|
||||
liveActiveTurnId: replacementTurnId,
|
||||
liveSessionActiveTurnId: replacementTurnId,
|
||||
turnId: staleTurnId,
|
||||
}),
|
||||
);
|
||||
assert.isFalse(
|
||||
grokPromptSettlementBelongsToContext({
|
||||
liveAcpSessionId: "replacement-session",
|
||||
expectedAcpSessionId: "stale-session",
|
||||
liveActiveTurnId: staleTurnId,
|
||||
liveSessionActiveTurnId: staleTurnId,
|
||||
turnId: staleTurnId,
|
||||
}),
|
||||
);
|
||||
assert.isTrue(
|
||||
grokPromptSettlementBelongsToContext({
|
||||
liveAcpSessionId: "session-1",
|
||||
expectedAcpSessionId: "session-1",
|
||||
liveActiveTurnId: staleTurnId,
|
||||
liveSessionActiveTurnId: staleTurnId,
|
||||
turnId: staleTurnId,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.layer(grokAdapterTestLayer)("GrokAdapterLive", (it) => {
|
||||
it.effect("starts a session and maps mock ACP prompt flow to runtime events", () =>
|
||||
Effect.gen(function* () {
|
||||
@@ -175,6 +218,783 @@ it.layer(grokAdapterTestLayer)("GrokAdapterLive", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reports a Grok session running only while the prompt is in flight", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("grok-session-ready-after-prompt");
|
||||
const wrapperPath = yield* Effect.promise(() =>
|
||||
makeMockGrokWrapper({
|
||||
T3_ACP_EMIT_TOOL_CALLS: "1",
|
||||
}),
|
||||
);
|
||||
const adapter = yield* makeTestAdapter(wrapperPath);
|
||||
const requestOpened =
|
||||
yield* Deferred.make<Extract<ProviderRuntimeEvent, { type: "request.opened" }>>();
|
||||
const eventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
|
||||
event.type === "request.opened"
|
||||
? Deferred.succeed(requestOpened, event).pipe(Effect.ignore)
|
||||
: Effect.void,
|
||||
).pipe(Effect.forkChild);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("grok"),
|
||||
cwd: process.cwd(),
|
||||
runtimeMode: "approval-required",
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok-build" },
|
||||
});
|
||||
|
||||
const sendTurnFiber = yield* adapter
|
||||
.sendTurn({ threadId, input: "check lifecycle", attachments: [] })
|
||||
.pipe(Effect.forkChild);
|
||||
const requestOpenedEvent = yield* Deferred.await(requestOpened);
|
||||
|
||||
const runningSessions = yield* adapter.listSessions();
|
||||
const runningSession = runningSessions.find((session) => session.threadId === threadId);
|
||||
assert.equal(runningSession?.status, "running");
|
||||
assert.isDefined(runningSession?.activeTurnId);
|
||||
|
||||
yield* adapter.respondToRequest(
|
||||
threadId,
|
||||
ApprovalRequestId.make(String(requestOpenedEvent.requestId)),
|
||||
"accept",
|
||||
);
|
||||
yield* Fiber.join(sendTurnFiber);
|
||||
|
||||
const readySessions = yield* adapter.listSessions();
|
||||
const readySession = readySessions.find((session) => session.threadId === threadId);
|
||||
assert.equal(readySession?.status, "ready");
|
||||
assert.isUndefined(readySession?.activeTurnId);
|
||||
|
||||
yield* Fiber.interrupt(eventsFiber);
|
||||
yield* adapter.stopSession(threadId);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("restores ready without completing an unstarted turn when preparation fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("grok-preparation-failure-while-connecting");
|
||||
const wrapperPath = yield* Effect.promise(() => makeMockGrokWrapper());
|
||||
const adapter = yield* makeTestAdapter(wrapperPath);
|
||||
|
||||
const runtimeEvents: ProviderRuntimeEvent[] = [];
|
||||
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
|
||||
Effect.sync(() => {
|
||||
runtimeEvents.push(event);
|
||||
}),
|
||||
).pipe(Effect.forkChild);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("grok"),
|
||||
cwd: process.cwd(),
|
||||
runtimeMode: "full-access",
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok-build" },
|
||||
});
|
||||
|
||||
const error = yield* Effect.flip(
|
||||
adapter.sendTurn({
|
||||
threadId,
|
||||
input: "prepare invalid attachment",
|
||||
attachments: [
|
||||
{
|
||||
type: "image",
|
||||
id: "missing-image",
|
||||
name: "missing.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 1,
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
for (let yieldAttempt = 0; yieldAttempt < 4; yieldAttempt += 1) {
|
||||
yield* Effect.yieldNow;
|
||||
}
|
||||
|
||||
const turnCompletedEvent = runtimeEvents.find(
|
||||
(event): event is Extract<ProviderRuntimeEvent, { type: "turn.completed" }> =>
|
||||
event.type === "turn.completed",
|
||||
);
|
||||
const readySessions = yield* adapter.listSessions();
|
||||
const readySession = readySessions.find((session) => session.threadId === threadId);
|
||||
|
||||
assert.equal(error._tag, "ProviderAdapterRequestError");
|
||||
assert.isUndefined(turnCompletedEvent);
|
||||
assert.equal(readySession?.status, "ready");
|
||||
assert.isUndefined(readySession?.activeTurnId);
|
||||
|
||||
yield* Fiber.interrupt(runtimeEventsFiber);
|
||||
yield* adapter.stopSession(threadId);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("completes a Grok turn from xAI prompt completion when the prompt RPC hangs", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("grok-xai-prompt-complete-fallback");
|
||||
const wrapperPath = yield* Effect.promise(() =>
|
||||
makeMockGrokWrapper({
|
||||
T3_ACP_EMIT_XAI_PROMPT_COMPLETE_THEN_HANG: "1",
|
||||
T3_ACP_EMIT_FOREIGN_SESSION_UPDATES: "1",
|
||||
}),
|
||||
);
|
||||
const adapter = yield* makeTestAdapter(wrapperPath);
|
||||
|
||||
const runtimeEvents: ProviderRuntimeEvent[] = [];
|
||||
const turnCompleted = yield* Deferred.make<void>();
|
||||
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
|
||||
Effect.sync(() => {
|
||||
runtimeEvents.push(event);
|
||||
}).pipe(
|
||||
Effect.andThen(
|
||||
event.type === "turn.completed"
|
||||
? Deferred.succeed(turnCompleted, undefined)
|
||||
: Effect.void,
|
||||
),
|
||||
),
|
||||
).pipe(Effect.forkChild);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("grok"),
|
||||
cwd: process.cwd(),
|
||||
runtimeMode: "full-access",
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok-build" },
|
||||
});
|
||||
|
||||
const sendTurnResult = yield* adapter.sendTurn({
|
||||
threadId,
|
||||
input: "exercise fallback",
|
||||
attachments: [],
|
||||
});
|
||||
|
||||
yield* Deferred.await(turnCompleted);
|
||||
for (let yieldAttempt = 0; yieldAttempt < 8; yieldAttempt += 1) {
|
||||
yield* Effect.yieldNow;
|
||||
}
|
||||
const readySessions = yield* adapter.listSessions();
|
||||
const readySession = readySessions.find((session) => session.threadId === threadId);
|
||||
const turnCompletedEvent = runtimeEvents.find(
|
||||
(event): event is Extract<ProviderRuntimeEvent, { type: "turn.completed" }> =>
|
||||
event.type === "turn.completed",
|
||||
);
|
||||
const eventTypes = runtimeEvents.map((event) => event.type);
|
||||
const content = runtimeEvents
|
||||
.filter(
|
||||
(event): event is Extract<ProviderRuntimeEvent, { type: "content.delta" }> =>
|
||||
event.type === "content.delta" && String(event.threadId) === String(threadId),
|
||||
)
|
||||
.map((event) => event.payload.delta)
|
||||
.join("");
|
||||
const terminalIndex = runtimeEvents.findIndex(
|
||||
(event) => event.type === "turn.completed" && String(event.threadId) === String(threadId),
|
||||
);
|
||||
const turnOutputTypes = new Set([
|
||||
"content.delta",
|
||||
"item.started",
|
||||
"item.updated",
|
||||
"item.completed",
|
||||
"turn.plan.updated",
|
||||
]);
|
||||
const outputAfterTerminal = runtimeEvents
|
||||
.slice(terminalIndex + 1)
|
||||
.filter(
|
||||
(event) => String(event.threadId) === String(threadId) && turnOutputTypes.has(event.type),
|
||||
);
|
||||
const toolTitles = runtimeEvents.flatMap((event) =>
|
||||
event.type === "item.updated" && event.payload.title ? [event.payload.title] : [],
|
||||
);
|
||||
|
||||
assert.equal(sendTurnResult.threadId, threadId);
|
||||
assert.include(eventTypes, "turn.completed");
|
||||
assert.equal(content, "hello from mock");
|
||||
assert.isAtLeast(terminalIndex, 0);
|
||||
assert.deepEqual(outputAfterTerminal, []);
|
||||
assert.notInclude(toolTitles, "Child-only tool");
|
||||
assert.equal(turnCompletedEvent?.payload.stopReason, "end_turn");
|
||||
assert.equal(readySession?.status, "ready");
|
||||
assert.isUndefined(readySession?.activeTurnId);
|
||||
|
||||
yield* Fiber.interrupt(runtimeEventsFiber);
|
||||
yield* adapter.stopSession(threadId);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("retains turn transcript when sendTurn is interrupted after prompt success", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("grok-send-turn-interrupt-after-prompt");
|
||||
const wrapperPath = yield* Effect.promise(() =>
|
||||
makeMockGrokWrapper({
|
||||
T3_ACP_EMIT_XAI_PROMPT_COMPLETE_THEN_HANG: "1",
|
||||
}),
|
||||
);
|
||||
const adapter = yield* makeTestAdapter(wrapperPath);
|
||||
const contentDelta = yield* Deferred.make<void>();
|
||||
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
|
||||
event.type === "content.delta" ? Deferred.succeed(contentDelta, undefined) : Effect.void,
|
||||
).pipe(Effect.forkChild);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("grok"),
|
||||
cwd: process.cwd(),
|
||||
runtimeMode: "full-access",
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok-build" },
|
||||
});
|
||||
|
||||
const sendTurnFiber = yield* adapter
|
||||
.sendTurn({
|
||||
threadId,
|
||||
input: "interrupt after prompt",
|
||||
attachments: [],
|
||||
})
|
||||
.pipe(Effect.forkChild);
|
||||
|
||||
yield* Deferred.await(contentDelta);
|
||||
for (let yieldAttempt = 0; yieldAttempt < 6; yieldAttempt += 1) {
|
||||
yield* Effect.yieldNow;
|
||||
}
|
||||
yield* Fiber.interrupt(sendTurnFiber);
|
||||
for (let yieldAttempt = 0; yieldAttempt < 4; yieldAttempt += 1) {
|
||||
yield* Effect.yieldNow;
|
||||
}
|
||||
|
||||
const snapshot = yield* adapter.readThread(threadId);
|
||||
assert.equal(snapshot.turns.length, 1);
|
||||
assert.equal(snapshot.turns[0]?.items.length, 1);
|
||||
|
||||
yield* Fiber.interrupt(runtimeEventsFiber);
|
||||
yield* adapter.stopSession(threadId);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not report a synthetic stop reason when xAI omits one", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("grok-xai-prompt-complete-missing-stop-reason");
|
||||
const wrapperPath = yield* Effect.promise(() =>
|
||||
makeMockGrokWrapper({
|
||||
T3_ACP_EMIT_XAI_PROMPT_COMPLETE_THEN_HANG: "1",
|
||||
T3_ACP_OMIT_XAI_PROMPT_COMPLETE_STOP_REASON: "1",
|
||||
}),
|
||||
);
|
||||
const adapter = yield* makeTestAdapter(wrapperPath);
|
||||
|
||||
const runtimeEvents: ProviderRuntimeEvent[] = [];
|
||||
const turnCompleted = yield* Deferred.make<void>();
|
||||
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
|
||||
Effect.sync(() => {
|
||||
runtimeEvents.push(event);
|
||||
}).pipe(
|
||||
Effect.andThen(
|
||||
event.type === "turn.completed"
|
||||
? Deferred.succeed(turnCompleted, undefined)
|
||||
: Effect.void,
|
||||
),
|
||||
),
|
||||
).pipe(Effect.forkChild);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("grok"),
|
||||
cwd: process.cwd(),
|
||||
runtimeMode: "full-access",
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok-build" },
|
||||
});
|
||||
|
||||
yield* adapter.sendTurn({
|
||||
threadId,
|
||||
input: "exercise missing stop reason",
|
||||
attachments: [],
|
||||
});
|
||||
|
||||
yield* Deferred.await(turnCompleted);
|
||||
const turnCompletedEvent = runtimeEvents.find(
|
||||
(event): event is Extract<ProviderRuntimeEvent, { type: "turn.completed" }> =>
|
||||
event.type === "turn.completed",
|
||||
);
|
||||
|
||||
assert.equal(turnCompletedEvent?.payload.state, "completed");
|
||||
assert.isNull(turnCompletedEvent?.payload.stopReason);
|
||||
|
||||
yield* Fiber.interrupt(runtimeEventsFiber);
|
||||
yield* adapter.stopSession(threadId);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("lets Stop unblock a fully silent Grok prompt and accept a follow-up turn", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("grok-stop-after-full-silence");
|
||||
const wrapperPath = yield* Effect.promise(() =>
|
||||
makeMockGrokWrapper({
|
||||
T3_ACP_HANG_FIRST_PROMPT_FOREVER: "1",
|
||||
}),
|
||||
);
|
||||
const adapter = yield* makeTestAdapter(wrapperPath);
|
||||
|
||||
const runtimeEvents: ProviderRuntimeEvent[] = [];
|
||||
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
|
||||
Effect.sync(() => {
|
||||
runtimeEvents.push(event);
|
||||
}),
|
||||
).pipe(Effect.forkChild);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("grok"),
|
||||
cwd: process.cwd(),
|
||||
runtimeMode: "full-access",
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok-build" },
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
yield* Effect.sleep("500 millis");
|
||||
yield* adapter.interruptTurn(threadId);
|
||||
}).pipe(Effect.forkChild({ startImmediately: true }));
|
||||
|
||||
yield* adapter.sendTurn({
|
||||
threadId,
|
||||
input: "hang forever",
|
||||
attachments: [],
|
||||
});
|
||||
for (let yieldAttempt = 0; yieldAttempt < 8; yieldAttempt += 1) {
|
||||
yield* Effect.yieldNow;
|
||||
}
|
||||
|
||||
const cancelledEvents = runtimeEvents.filter(
|
||||
(event): event is Extract<ProviderRuntimeEvent, { type: "turn.completed" }> =>
|
||||
event.type === "turn.completed" && String(event.threadId) === String(threadId),
|
||||
);
|
||||
const readySessions = yield* adapter.listSessions();
|
||||
const readySession = readySessions.find((session) => session.threadId === threadId);
|
||||
|
||||
assert.lengthOf(cancelledEvents, 1);
|
||||
assert.equal(cancelledEvents[0]?.payload.state, "cancelled");
|
||||
assert.equal(readySession?.status, "ready");
|
||||
assert.isUndefined(readySession?.activeTurnId);
|
||||
|
||||
const followUpEventsBefore = runtimeEvents.length;
|
||||
yield* adapter.sendTurn({
|
||||
threadId,
|
||||
input: "continue after stop",
|
||||
attachments: [],
|
||||
});
|
||||
for (let yieldAttempt = 0; yieldAttempt < 8; yieldAttempt += 1) {
|
||||
yield* Effect.yieldNow;
|
||||
}
|
||||
|
||||
const followUpCompletedEvents = runtimeEvents
|
||||
.slice(followUpEventsBefore)
|
||||
.filter(
|
||||
(event): event is Extract<ProviderRuntimeEvent, { type: "turn.completed" }> =>
|
||||
event.type === "turn.completed" && String(event.threadId) === String(threadId),
|
||||
);
|
||||
assert.lengthOf(followUpCompletedEvents, 1);
|
||||
assert.equal(followUpCompletedEvents[0]?.payload.state, "completed");
|
||||
|
||||
yield* Fiber.interrupt(runtimeEventsFiber);
|
||||
yield* adapter.stopSession(threadId);
|
||||
}).pipe(TestClock.withLive),
|
||||
);
|
||||
|
||||
it.effect("does not let a cancelled prompt settlement consume the follow-up prompt slot", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("grok-cancelled-settlement-before-follow-up");
|
||||
const tempDir = yield* Effect.promise(() =>
|
||||
NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "grok-acp-cancel-race-")),
|
||||
);
|
||||
const requestLogPath = NodePath.join(tempDir, "requests.ndjson");
|
||||
const wrapperPath = yield* Effect.promise(() =>
|
||||
makeMockGrokWrapper({
|
||||
T3_ACP_HANG_FIRST_PROMPT_FOREVER: "1",
|
||||
T3_ACP_REQUEST_LOG_PATH: requestLogPath,
|
||||
}),
|
||||
);
|
||||
const adapter = yield* makeTestAdapter(wrapperPath);
|
||||
|
||||
const runtimeEvents: ProviderRuntimeEvent[] = [];
|
||||
const firstTurnStarted = yield* Deferred.make<TurnId>();
|
||||
const twoTurnsCompleted = yield* Deferred.make<void>();
|
||||
const completedCountRef = yield* Ref.make(0);
|
||||
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
|
||||
Effect.gen(function* () {
|
||||
runtimeEvents.push(event);
|
||||
if (String(event.threadId) !== String(threadId)) {
|
||||
return;
|
||||
}
|
||||
if (event.type === "turn.started" && event.turnId !== undefined) {
|
||||
yield* Deferred.succeed(firstTurnStarted, event.turnId).pipe(Effect.ignore);
|
||||
return;
|
||||
}
|
||||
if (event.type !== "turn.completed") {
|
||||
return;
|
||||
}
|
||||
const completedCount = yield* Ref.updateAndGet(completedCountRef, (count) => count + 1);
|
||||
if (completedCount === 2) {
|
||||
yield* Deferred.succeed(twoTurnsCompleted, undefined);
|
||||
}
|
||||
}),
|
||||
).pipe(Effect.forkChild);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("grok"),
|
||||
cwd: process.cwd(),
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
const firstSendTurnFiber = yield* adapter
|
||||
.sendTurn({ threadId, input: "cancel this prompt", attachments: [] })
|
||||
.pipe(Effect.forkChild);
|
||||
const firstTurnId = yield* Deferred.await(firstTurnStarted).pipe(Effect.timeout("2 seconds"));
|
||||
yield* waitForFileContent(requestLogPath, 80, '"method":"session/prompt"');
|
||||
|
||||
yield* adapter.interruptTurn(threadId, firstTurnId).pipe(Effect.timeout("2 seconds"));
|
||||
const followUp = yield* adapter
|
||||
.sendTurn({ threadId, input: "complete the follow-up", attachments: [] })
|
||||
.pipe(Effect.timeout("2 seconds"));
|
||||
yield* Fiber.join(firstSendTurnFiber).pipe(Effect.timeout("2 seconds"));
|
||||
yield* Deferred.await(twoTurnsCompleted).pipe(Effect.timeout("2 seconds"));
|
||||
|
||||
const turnCompletedEvents = runtimeEvents.filter(
|
||||
(event): event is Extract<ProviderRuntimeEvent, { type: "turn.completed" }> =>
|
||||
event.type === "turn.completed" && String(event.threadId) === String(threadId),
|
||||
);
|
||||
const readySessions = yield* adapter.listSessions();
|
||||
const readySession = readySessions.find((session) => session.threadId === threadId);
|
||||
|
||||
assert.notEqual(String(followUp.turnId), String(firstTurnId));
|
||||
assert.deepEqual(
|
||||
turnCompletedEvents.map((event) => [String(event.turnId), event.payload.state]),
|
||||
[
|
||||
[String(firstTurnId), "cancelled"],
|
||||
[String(followUp.turnId), "completed"],
|
||||
],
|
||||
);
|
||||
assert.equal(readySession?.status, "ready");
|
||||
assert.isUndefined(readySession?.activeTurnId);
|
||||
|
||||
yield* Fiber.interrupt(runtimeEventsFiber);
|
||||
yield* adapter.stopSession(threadId);
|
||||
}).pipe(TestClock.withLive),
|
||||
);
|
||||
|
||||
it.effect("drops late ACP notifications after a turn is cancelled", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("grok-drop-late-cancelled-notifications");
|
||||
const wrapperPath = yield* Effect.promise(() =>
|
||||
makeMockGrokWrapper({
|
||||
T3_ACP_HANG_PROMPT_FOREVER: "1",
|
||||
T3_ACP_EMIT_LATE_UPDATE_AFTER_CANCEL: "1",
|
||||
}),
|
||||
);
|
||||
const lateNativeUpdate = yield* Deferred.make<void>();
|
||||
const adapter = yield* makeTestAdapter(wrapperPath, {
|
||||
nativeEventLogger: {
|
||||
filePath: "memory://grok-cancelled-native-events",
|
||||
write: (record: unknown) =>
|
||||
JSON.stringify(record).includes("late after cancel")
|
||||
? Deferred.succeed(lateNativeUpdate, undefined).pipe(Effect.asVoid)
|
||||
: Effect.void,
|
||||
close: () => Effect.void,
|
||||
},
|
||||
});
|
||||
|
||||
const runtimeEvents: ProviderRuntimeEvent[] = [];
|
||||
const turnStarted = yield* Deferred.make<TurnId>();
|
||||
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
|
||||
Effect.sync(() => {
|
||||
runtimeEvents.push(event);
|
||||
}).pipe(
|
||||
Effect.andThen(
|
||||
event.type === "turn.started" &&
|
||||
event.turnId !== undefined &&
|
||||
String(event.threadId) === String(threadId)
|
||||
? Deferred.succeed(turnStarted, event.turnId).pipe(Effect.asVoid)
|
||||
: Effect.void,
|
||||
),
|
||||
),
|
||||
).pipe(Effect.forkChild);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("grok"),
|
||||
cwd: process.cwd(),
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
const sendTurnFiber = yield* adapter
|
||||
.sendTurn({ threadId, input: "cancel before the late update", attachments: [] })
|
||||
.pipe(Effect.forkChild);
|
||||
const turnId = yield* Deferred.await(turnStarted).pipe(Effect.timeout("2 seconds"));
|
||||
yield* adapter.interruptTurn(threadId, turnId).pipe(Effect.timeout("2 seconds"));
|
||||
yield* Fiber.join(sendTurnFiber).pipe(Effect.timeout("2 seconds"));
|
||||
yield* Deferred.await(lateNativeUpdate).pipe(Effect.timeout("2 seconds"));
|
||||
for (let yieldAttempt = 0; yieldAttempt < 8; yieldAttempt += 1) {
|
||||
yield* Effect.yieldNow;
|
||||
}
|
||||
|
||||
const cancelledIndex = runtimeEvents.findIndex(
|
||||
(event) =>
|
||||
event.type === "turn.completed" &&
|
||||
String(event.threadId) === String(threadId) &&
|
||||
String(event.turnId) === String(turnId) &&
|
||||
event.payload.state === "cancelled",
|
||||
);
|
||||
const turnOutputTypes = new Set([
|
||||
"content.delta",
|
||||
"item.started",
|
||||
"item.updated",
|
||||
"item.completed",
|
||||
"turn.plan.updated",
|
||||
]);
|
||||
const outputAfterCancellation = runtimeEvents
|
||||
.slice(cancelledIndex + 1)
|
||||
.filter(
|
||||
(event) => String(event.threadId) === String(threadId) && turnOutputTypes.has(event.type),
|
||||
);
|
||||
|
||||
assert.isAtLeast(cancelledIndex, 0);
|
||||
assert.deepEqual(outputAfterCancellation, []);
|
||||
|
||||
yield* Fiber.interrupt(runtimeEventsFiber);
|
||||
yield* adapter.stopSession(threadId);
|
||||
}).pipe(TestClock.withLive),
|
||||
);
|
||||
|
||||
it.effect("lets Stop cancel during the xAI completion drain window", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("grok-stop-during-completion-drain");
|
||||
const wrapperPath = yield* Effect.promise(() =>
|
||||
makeMockGrokWrapper({
|
||||
T3_ACP_EMIT_XAI_PROMPT_COMPLETE_THEN_HANG: "1",
|
||||
}),
|
||||
);
|
||||
const adapter = yield* makeTestAdapter(wrapperPath);
|
||||
|
||||
const runtimeEvents: ProviderRuntimeEvent[] = [];
|
||||
const activeTurnIdRef = yield* Ref.make<TurnId | undefined>(undefined);
|
||||
const trailingChunkTurnId = yield* Deferred.make<TurnId>();
|
||||
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
|
||||
Effect.gen(function* () {
|
||||
runtimeEvents.push(event);
|
||||
if (String(event.threadId) !== String(threadId)) {
|
||||
return;
|
||||
}
|
||||
if (event.type === "turn.started") {
|
||||
yield* Ref.set(activeTurnIdRef, event.turnId);
|
||||
}
|
||||
if (event.type !== "content.delta" || event.payload.delta !== "mock") {
|
||||
return;
|
||||
}
|
||||
const turnId = event.turnId ?? (yield* Ref.get(activeTurnIdRef));
|
||||
if (turnId === undefined) {
|
||||
return;
|
||||
}
|
||||
yield* Deferred.succeed(trailingChunkTurnId, turnId).pipe(Effect.ignore);
|
||||
}),
|
||||
).pipe(Effect.forkChild);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("grok"),
|
||||
cwd: process.cwd(),
|
||||
runtimeMode: "full-access",
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok-build" },
|
||||
});
|
||||
|
||||
const sendTurnFiber = yield* adapter
|
||||
.sendTurn({
|
||||
threadId,
|
||||
input: "cancel during completion drain",
|
||||
attachments: [],
|
||||
})
|
||||
.pipe(Effect.forkChild);
|
||||
|
||||
const turnId = yield* Deferred.await(trailingChunkTurnId).pipe(Effect.timeout("2 seconds"));
|
||||
yield* adapter.interruptTurn(threadId, turnId).pipe(Effect.timeout("2 seconds"));
|
||||
yield* Fiber.join(sendTurnFiber).pipe(Effect.timeout("2 seconds"));
|
||||
|
||||
const turnCompletedEvents = runtimeEvents.filter(
|
||||
(event): event is Extract<ProviderRuntimeEvent, { type: "turn.completed" }> =>
|
||||
event.type === "turn.completed" && String(event.threadId) === String(threadId),
|
||||
);
|
||||
const readySessions = yield* adapter.listSessions();
|
||||
const readySession = readySessions.find((session) => session.threadId === threadId);
|
||||
|
||||
assert.lengthOf(turnCompletedEvents, 1);
|
||||
assert.equal(turnCompletedEvents[0]?.payload.state, "cancelled");
|
||||
assert.equal(readySession?.status, "ready");
|
||||
assert.isUndefined(readySession?.activeTurnId);
|
||||
|
||||
yield* Fiber.interrupt(runtimeEventsFiber);
|
||||
yield* adapter.stopSession(threadId);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("settles the in-flight prompt before emitting completion", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("grok-completion-before-next-turn");
|
||||
const wrapperPath = yield* Effect.promise(() => makeMockGrokWrapper());
|
||||
const adapter = yield* makeTestAdapter(wrapperPath);
|
||||
const completedCountRef = yield* Ref.make(0);
|
||||
const secondTurnCompleted = yield* Deferred.make<void>();
|
||||
|
||||
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) => {
|
||||
if (event.type !== "turn.completed" || String(event.threadId) !== String(threadId)) {
|
||||
return Effect.void;
|
||||
}
|
||||
|
||||
return Ref.modify(completedCountRef, (count) => {
|
||||
const nextCount = count + 1;
|
||||
return [nextCount, nextCount] as const;
|
||||
}).pipe(
|
||||
Effect.flatMap((count) => {
|
||||
if (count === 1) {
|
||||
return adapter
|
||||
.sendTurn({
|
||||
threadId,
|
||||
input: "second turn after completion",
|
||||
attachments: [],
|
||||
})
|
||||
.pipe(Effect.forkChild, Effect.asVoid);
|
||||
}
|
||||
if (count === 2) {
|
||||
return Deferred.succeed(secondTurnCompleted, undefined).pipe(Effect.asVoid);
|
||||
}
|
||||
return Effect.void;
|
||||
}),
|
||||
);
|
||||
}).pipe(Effect.forkChild);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("grok"),
|
||||
cwd: process.cwd(),
|
||||
runtimeMode: "full-access",
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok-build" },
|
||||
});
|
||||
|
||||
yield* adapter.sendTurn({
|
||||
threadId,
|
||||
input: "first turn",
|
||||
attachments: [],
|
||||
});
|
||||
yield* Deferred.await(secondTurnCompleted);
|
||||
|
||||
const completedCount = yield* Ref.get(completedCountRef);
|
||||
const readySessions = yield* adapter.listSessions();
|
||||
const readySession = readySessions.find((session) => session.threadId === threadId);
|
||||
|
||||
assert.equal(completedCount, 2);
|
||||
assert.equal(readySession?.status, "ready");
|
||||
assert.isUndefined(readySession?.activeTurnId);
|
||||
|
||||
yield* Fiber.interrupt(runtimeEventsFiber);
|
||||
yield* adapter.stopSession(threadId);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("restores a Grok session to ready when the prompt RPC fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("grok-prompt-failure-ready");
|
||||
const wrapperPath = yield* Effect.promise(() =>
|
||||
makeMockGrokWrapper({
|
||||
T3_ACP_FAIL_PROMPT: "1",
|
||||
}),
|
||||
);
|
||||
const adapter = yield* makeTestAdapter(wrapperPath);
|
||||
const runtimeEvents: ProviderRuntimeEvent[] = [];
|
||||
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
|
||||
Effect.sync(() => {
|
||||
runtimeEvents.push(event);
|
||||
}),
|
||||
).pipe(Effect.forkChild);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("grok"),
|
||||
cwd: process.cwd(),
|
||||
runtimeMode: "full-access",
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok-build" },
|
||||
});
|
||||
|
||||
const error = yield* Effect.flip(
|
||||
adapter.sendTurn({
|
||||
threadId,
|
||||
input: "fail prompt",
|
||||
attachments: [],
|
||||
}),
|
||||
);
|
||||
const readySessions = yield* adapter.listSessions();
|
||||
const readySession = readySessions.find((session) => session.threadId === threadId);
|
||||
const failedTurnCompleted = runtimeEvents.find(
|
||||
(event) => event.type === "turn.completed" && event.threadId === threadId,
|
||||
);
|
||||
|
||||
assert.equal(error._tag, "ProviderAdapterRequestError");
|
||||
assert.equal(readySession?.status, "ready");
|
||||
assert.isUndefined(readySession?.activeTurnId);
|
||||
assert.equal(failedTurnCompleted?.type, "turn.completed");
|
||||
if (failedTurnCompleted?.type === "turn.completed") {
|
||||
assert.equal(failedTurnCompleted.payload.state, "failed");
|
||||
assert.isString(failedTurnCompleted.payload.errorMessage);
|
||||
}
|
||||
|
||||
yield* Fiber.interrupt(runtimeEventsFiber);
|
||||
yield* adapter.stopSession(threadId);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("ignores replayed session/load updates when resuming a Grok session", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("grok-load-replay-filter");
|
||||
const wrapperPath = yield* Effect.promise(() =>
|
||||
makeMockGrokWrapper({
|
||||
T3_ACP_EMIT_LOAD_REPLAY: "1",
|
||||
}),
|
||||
);
|
||||
const adapter = yield* makeTestAdapter(wrapperPath);
|
||||
const runtimeEvents: ProviderRuntimeEvent[] = [];
|
||||
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
|
||||
Effect.sync(() => {
|
||||
runtimeEvents.push(event);
|
||||
}),
|
||||
).pipe(Effect.forkChild);
|
||||
|
||||
const session = yield* adapter.startSession({
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("grok"),
|
||||
cwd: process.cwd(),
|
||||
runtimeMode: "full-access",
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok-build" },
|
||||
resumeCursor: { schemaVersion: 1, sessionId: "mock-session-1" },
|
||||
});
|
||||
|
||||
yield* adapter.sendTurn({
|
||||
threadId,
|
||||
input: "after resume",
|
||||
attachments: [],
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(session.resumeCursor, {
|
||||
schemaVersion: 1,
|
||||
sessionId: "mock-session-1",
|
||||
});
|
||||
assert.isFalse(
|
||||
runtimeEvents.some(
|
||||
(event) => event.type === "item.completed" && event.payload.title === "Replay tool",
|
||||
),
|
||||
);
|
||||
assert.isFalse(
|
||||
runtimeEvents.some(
|
||||
(event) =>
|
||||
event.type === "content.delta" && event.payload.delta === "replayed assistant text",
|
||||
),
|
||||
);
|
||||
|
||||
yield* Fiber.interrupt(runtimeEventsFiber);
|
||||
yield* adapter.stopSession(threadId);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects startSession when provider mismatches", () =>
|
||||
Effect.gen(function* () {
|
||||
const wrapperPath = yield* Effect.promise(() => makeMockGrokWrapper());
|
||||
@@ -331,6 +1151,7 @@ it.layer(grokAdapterTestLayer)("GrokAdapterLive", (it) => {
|
||||
assert.deepEqual(resolvedEvent.payload.answers, {
|
||||
"Which scope should Grok use?": "Workspace",
|
||||
});
|
||||
assert.equal(String(resolvedEvent.turnId), String(requestedEvent.turnId));
|
||||
yield* Fiber.join(sendTurnFiber);
|
||||
|
||||
yield* Fiber.interrupt(eventsFiber);
|
||||
|
||||
@@ -22,6 +22,7 @@ import * as FileSystem from "effect/FileSystem";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as PubSub from "effect/PubSub";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
@@ -62,6 +63,7 @@ import {
|
||||
extractXAiAskUserQuestions,
|
||||
makeXAiAskUserQuestionCancelledResponse,
|
||||
makeXAiAskUserQuestionResponse,
|
||||
promptResponseHasMissingXAiStopReason,
|
||||
XAiAskUserQuestionRequest,
|
||||
} from "../acp/XAiAcpExtension.ts";
|
||||
import { type GrokAdapterShape } from "../Services/GrokAdapter.ts";
|
||||
@@ -108,6 +110,8 @@ interface GrokSessionContext {
|
||||
turns: Array<{ id: TurnId; items: Array<unknown> }>;
|
||||
lastPlanFingerprint: string | undefined;
|
||||
activeTurnId: TurnId | undefined;
|
||||
/** Turns already interrupted; late prompt RPCs must not resurrect them. */
|
||||
interruptedTurnIds: Set<TurnId>;
|
||||
/** Number of sendTurn prompts currently in flight or being prepared.
|
||||
* >0 means a turn is actively running, so a new sendTurn is a steer that
|
||||
* continues it, and only the last remaining prompt settles the turn. */
|
||||
@@ -136,10 +140,38 @@ function settlePendingUserInputsAsCancelled(
|
||||
);
|
||||
}
|
||||
|
||||
function appendPromptResultToTurn(
|
||||
ctx: GrokSessionContext,
|
||||
turnId: TurnId,
|
||||
promptParts: ReadonlyArray<EffectAcpSchema.ContentBlock>,
|
||||
result: EffectAcpSchema.PromptResponse,
|
||||
): void {
|
||||
const existingTurnRecord = ctx.turns.find((turn) => turn.id === turnId);
|
||||
ctx.turns = existingTurnRecord
|
||||
? ctx.turns.map((turn) =>
|
||||
turn.id === turnId
|
||||
? { ...turn, items: [...turn.items, { prompt: promptParts, result }] }
|
||||
: turn,
|
||||
)
|
||||
: [...ctx.turns, { id: turnId, items: [{ prompt: promptParts, result }] }];
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
const resolveNotificationTurnId = (ctx: GrokSessionContext): TurnId | undefined => ctx.activeTurnId;
|
||||
|
||||
const resolveCallbackTurnId = (ctx: GrokSessionContext): TurnId | undefined => ctx.activeTurnId;
|
||||
|
||||
const resolveSessionCallbackTurnId = (
|
||||
sessions: ReadonlyMap<ThreadId, GrokSessionContext>,
|
||||
threadId: ThreadId,
|
||||
): TurnId | undefined => {
|
||||
const ctx = sessions.get(threadId);
|
||||
return ctx ? resolveCallbackTurnId(ctx) : undefined;
|
||||
};
|
||||
|
||||
function parseGrokResume(raw: unknown): { sessionId: string } | undefined {
|
||||
if (!isRecord(raw)) return undefined;
|
||||
if (raw.schemaVersion !== GROK_RESUME_VERSION) return undefined;
|
||||
@@ -170,6 +202,28 @@ function selectAutoApprovedPermissionOption(
|
||||
);
|
||||
}
|
||||
|
||||
function completedStopReasonFromPromptResponse(
|
||||
response: EffectAcpSchema.PromptResponse | undefined,
|
||||
): EffectAcpSchema.StopReason | null {
|
||||
if (response === undefined || promptResponseHasMissingXAiStopReason(response)) {
|
||||
return null;
|
||||
}
|
||||
return response.stopReason;
|
||||
}
|
||||
|
||||
export function grokPromptSettlementBelongsToContext(input: {
|
||||
readonly liveAcpSessionId: string;
|
||||
readonly expectedAcpSessionId: string;
|
||||
readonly liveActiveTurnId: TurnId | undefined;
|
||||
readonly liveSessionActiveTurnId: TurnId | undefined;
|
||||
readonly turnId: TurnId;
|
||||
}): boolean {
|
||||
return (
|
||||
input.liveAcpSessionId === input.expectedAcpSessionId &&
|
||||
(input.liveActiveTurnId === input.turnId || input.liveSessionActiveTurnId === input.turnId)
|
||||
);
|
||||
}
|
||||
|
||||
export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapterLiveOptions) {
|
||||
return Effect.gen(function* () {
|
||||
const boundInstanceId = options?.instanceId ?? ProviderInstanceId.make("grok");
|
||||
@@ -240,6 +294,144 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
const withThreadLock = <A, E, R>(threadId: string, effect: Effect.Effect<A, E, R>) =>
|
||||
Effect.flatMap(getThreadSemaphore(threadId), (semaphore) => semaphore.withPermit(effect));
|
||||
|
||||
const settlePromptInFlight = (
|
||||
threadId: ThreadId,
|
||||
turnId: TurnId,
|
||||
expectedAcpSessionId: string,
|
||||
options?: {
|
||||
readonly errorMessage?: string;
|
||||
readonly completedStopReason?: EffectAcpSchema.StopReason | null;
|
||||
readonly emitTurnCompletion?: boolean;
|
||||
/** Interrupt/cancel: drop every outstanding prompt slot and settle once. */
|
||||
readonly settleAllPrompts?: boolean;
|
||||
},
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const liveCtx = sessions.get(threadId);
|
||||
if (!liveCtx) {
|
||||
return;
|
||||
}
|
||||
const settlementBelongsToLiveContext = grokPromptSettlementBelongsToContext({
|
||||
liveAcpSessionId: liveCtx.acpSessionId,
|
||||
expectedAcpSessionId,
|
||||
liveActiveTurnId: liveCtx.activeTurnId,
|
||||
liveSessionActiveTurnId: liveCtx.session.activeTurnId,
|
||||
turnId,
|
||||
});
|
||||
if (!settlementBelongsToLiveContext) {
|
||||
// interruptTurn already consumed every prompt slot for this turn. A
|
||||
// late prompt result must neither emit a second terminal event nor
|
||||
// consume a slot belonging to a newer turn on the same ACP session.
|
||||
if (
|
||||
liveCtx.acpSessionId !== expectedAcpSessionId ||
|
||||
liveCtx.interruptedTurnIds.has(turnId)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
if (options?.emitTurnCompletion !== false) {
|
||||
if (options?.errorMessage !== undefined) {
|
||||
yield* offerRuntimeEvent({
|
||||
type: "turn.completed",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: PROVIDER,
|
||||
threadId,
|
||||
turnId,
|
||||
payload: {
|
||||
state: "failed",
|
||||
errorMessage: options.errorMessage,
|
||||
},
|
||||
});
|
||||
} else if (options?.completedStopReason !== undefined) {
|
||||
yield* offerRuntimeEvent({
|
||||
type: "turn.completed",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: PROVIDER,
|
||||
threadId,
|
||||
turnId,
|
||||
payload: {
|
||||
state: options.completedStopReason === "cancelled" ? "cancelled" : "completed",
|
||||
stopReason: options.completedStopReason ?? null,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
let settleTurnId = turnId;
|
||||
if (options?.settleAllPrompts) {
|
||||
liveCtx.promptsInFlight = 0;
|
||||
if (liveCtx.activeTurnId !== turnId && liveCtx.session.activeTurnId !== turnId) {
|
||||
const fallbackTurnId = liveCtx.activeTurnId ?? liveCtx.session.activeTurnId;
|
||||
if (!fallbackTurnId) {
|
||||
if (liveCtx.session.status === "running" || liveCtx.session.status === "connecting") {
|
||||
const updatedAt = yield* nowIso;
|
||||
const { activeTurnId: _activeTurnId, ...readySession } = liveCtx.session;
|
||||
liveCtx.activeTurnId = undefined;
|
||||
liveCtx.session = {
|
||||
...readySession,
|
||||
status: "ready",
|
||||
updatedAt,
|
||||
};
|
||||
}
|
||||
return;
|
||||
}
|
||||
settleTurnId = fallbackTurnId;
|
||||
}
|
||||
} else {
|
||||
const remainingPrompts = Math.max(0, liveCtx.promptsInFlight - 1);
|
||||
if (
|
||||
remainingPrompts > 0 ||
|
||||
liveCtx.activeTurnId !== settleTurnId ||
|
||||
liveCtx.session.activeTurnId !== settleTurnId
|
||||
) {
|
||||
liveCtx.promptsInFlight = remainingPrompts;
|
||||
return;
|
||||
}
|
||||
liveCtx.promptsInFlight = remainingPrompts;
|
||||
}
|
||||
const updatedAt = yield* nowIso;
|
||||
const canEmitTurnCompletion =
|
||||
liveCtx.session.status === "running" || liveCtx.session.status === "connecting";
|
||||
const shouldEmitFailedTurn = options?.errorMessage !== undefined && canEmitTurnCompletion;
|
||||
const shouldEmitCompletedTurn =
|
||||
options?.completedStopReason !== undefined && canEmitTurnCompletion;
|
||||
const { activeTurnId: _activeTurnId, ...readySession } = liveCtx.session;
|
||||
liveCtx.activeTurnId = undefined;
|
||||
liveCtx.session = {
|
||||
...readySession,
|
||||
status: "ready",
|
||||
updatedAt,
|
||||
};
|
||||
if (options?.emitTurnCompletion === false) {
|
||||
return;
|
||||
}
|
||||
if (shouldEmitFailedTurn) {
|
||||
yield* offerRuntimeEvent({
|
||||
type: "turn.completed",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: PROVIDER,
|
||||
threadId,
|
||||
turnId: settleTurnId,
|
||||
payload: {
|
||||
state: "failed",
|
||||
errorMessage: options.errorMessage,
|
||||
},
|
||||
});
|
||||
} else if (shouldEmitCompletedTurn) {
|
||||
yield* offerRuntimeEvent({
|
||||
type: "turn.completed",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: PROVIDER,
|
||||
threadId,
|
||||
turnId: settleTurnId,
|
||||
payload: {
|
||||
state: options.completedStopReason === "cancelled" ? "cancelled" : "completed",
|
||||
stopReason: options.completedStopReason ?? null,
|
||||
},
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
const logNative = (threadId: ThreadId, method: string, payload: unknown) =>
|
||||
Effect.gen(function* () {
|
||||
if (!nativeEventLogger) return;
|
||||
@@ -271,6 +463,8 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
|
||||
const emitPlanUpdate = (
|
||||
ctx: GrokSessionContext,
|
||||
turnId: TurnId | undefined,
|
||||
stamp: { readonly eventId: EventId; readonly createdAt: string },
|
||||
payload: {
|
||||
readonly explanation?: string | null;
|
||||
readonly plan: ReadonlyArray<{
|
||||
@@ -282,17 +476,17 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
method: string,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const fingerprint = `${ctx.activeTurnId ?? "no-turn"}:${encodeJsonStringForDiagnostics(payload) ?? "[unserializable payload]"}`;
|
||||
const fingerprint = `${turnId ?? "no-turn"}:${encodeJsonStringForDiagnostics(payload) ?? "[unserializable payload]"}`;
|
||||
if (ctx.lastPlanFingerprint === fingerprint) {
|
||||
return;
|
||||
}
|
||||
ctx.lastPlanFingerprint = fingerprint;
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpPlanUpdatedEvent({
|
||||
stamp: yield* makeEventStamp(),
|
||||
stamp,
|
||||
provider: PROVIDER,
|
||||
threadId: ctx.threadId,
|
||||
turnId: ctx.activeTurnId,
|
||||
turnId,
|
||||
payload,
|
||||
source: "acp.jsonrpc",
|
||||
method,
|
||||
@@ -424,13 +618,14 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
const requestId = ApprovalRequestId.make(yield* randomUUIDv4);
|
||||
const runtimeRequestId = RuntimeRequestId.make(requestId);
|
||||
const resolution = yield* Deferred.make<PendingUserInputResolution>();
|
||||
const turnId = resolveSessionCallbackTurnId(sessions, input.threadId);
|
||||
pendingUserInputs.set(requestId, { resolution });
|
||||
yield* offerRuntimeEvent({
|
||||
type: "user-input.requested",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
turnId: sessions.get(input.threadId)?.activeTurnId,
|
||||
turnId,
|
||||
requestId: runtimeRequestId,
|
||||
payload: { questions: extractXAiAskUserQuestions(params) },
|
||||
raw: {
|
||||
@@ -447,7 +642,7 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
...(yield* makeEventStamp()),
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
turnId: sessions.get(input.threadId)?.activeTurnId,
|
||||
turnId,
|
||||
requestId: runtimeRequestId,
|
||||
payload: { answers: resolvedAnswers },
|
||||
raw: {
|
||||
@@ -486,13 +681,14 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
const requestId = ApprovalRequestId.make(yield* randomUUIDv4);
|
||||
const runtimeRequestId = RuntimeRequestId.make(requestId);
|
||||
const decision = yield* Deferred.make<ProviderApprovalDecision>();
|
||||
const turnId = resolveSessionCallbackTurnId(sessions, input.threadId);
|
||||
pendingApprovals.set(requestId, { decision });
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpRequestOpenedEvent({
|
||||
stamp: yield* makeEventStamp(),
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
turnId: sessions.get(input.threadId)?.activeTurnId,
|
||||
turnId,
|
||||
requestId: runtimeRequestId,
|
||||
permissionRequest,
|
||||
detail:
|
||||
@@ -512,7 +708,7 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
stamp: yield* makeEventStamp(),
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
turnId: sessions.get(input.threadId)?.activeTurnId,
|
||||
turnId,
|
||||
requestId: runtimeRequestId,
|
||||
permissionRequest,
|
||||
decision: resolved,
|
||||
@@ -578,6 +774,7 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
turns: [],
|
||||
lastPlanFingerprint: undefined,
|
||||
activeTurnId: undefined,
|
||||
interruptedTurnIds: new Set(),
|
||||
promptsInFlight: 0,
|
||||
currentModelId: boundModelId,
|
||||
stopped: false,
|
||||
@@ -586,14 +783,39 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
const nf = yield* Stream.runDrain(
|
||||
Stream.mapEffect(acp.getEvents(), (event) =>
|
||||
Effect.gen(function* () {
|
||||
if (event._tag === "EventStreamBarrier") {
|
||||
yield* Deferred.succeed(event.acknowledge, undefined);
|
||||
return;
|
||||
}
|
||||
if (
|
||||
event._tag === "PlanUpdated" ||
|
||||
event._tag === "ToolCallUpdated" ||
|
||||
event._tag === "ContentDelta"
|
||||
) {
|
||||
yield* logNative(ctx.threadId, "session/update", event.rawPayload);
|
||||
}
|
||||
|
||||
if (event._tag === "ModeChanged") {
|
||||
return;
|
||||
}
|
||||
|
||||
const notificationTurnId = resolveNotificationTurnId(ctx);
|
||||
if (
|
||||
notificationTurnId === undefined ||
|
||||
ctx.interruptedTurnIds.has(notificationTurnId)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const stamp = yield* makeEventStamp();
|
||||
|
||||
switch (event._tag) {
|
||||
case "AssistantItemStarted":
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpAssistantItemEvent({
|
||||
stamp: yield* makeEventStamp(),
|
||||
stamp,
|
||||
provider: PROVIDER,
|
||||
threadId: ctx.threadId,
|
||||
turnId: ctx.activeTurnId,
|
||||
turnId: notificationTurnId,
|
||||
itemId: event.itemId,
|
||||
lifecycle: "item.started",
|
||||
}),
|
||||
@@ -602,40 +824,44 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
case "AssistantItemCompleted":
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpAssistantItemEvent({
|
||||
stamp: yield* makeEventStamp(),
|
||||
stamp,
|
||||
provider: PROVIDER,
|
||||
threadId: ctx.threadId,
|
||||
turnId: ctx.activeTurnId,
|
||||
turnId: notificationTurnId,
|
||||
itemId: event.itemId,
|
||||
lifecycle: "item.completed",
|
||||
}),
|
||||
);
|
||||
return;
|
||||
case "PlanUpdated":
|
||||
yield* logNative(ctx.threadId, "session/update", event.rawPayload);
|
||||
yield* emitPlanUpdate(ctx, event.payload, event.rawPayload, "session/update");
|
||||
yield* emitPlanUpdate(
|
||||
ctx,
|
||||
notificationTurnId,
|
||||
stamp,
|
||||
event.payload,
|
||||
event.rawPayload,
|
||||
"session/update",
|
||||
);
|
||||
return;
|
||||
case "ToolCallUpdated":
|
||||
yield* logNative(ctx.threadId, "session/update", event.rawPayload);
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpToolCallEvent({
|
||||
stamp: yield* makeEventStamp(),
|
||||
stamp,
|
||||
provider: PROVIDER,
|
||||
threadId: ctx.threadId,
|
||||
turnId: ctx.activeTurnId,
|
||||
turnId: notificationTurnId,
|
||||
toolCall: event.toolCall,
|
||||
rawPayload: event.rawPayload,
|
||||
}),
|
||||
);
|
||||
return;
|
||||
case "ContentDelta":
|
||||
yield* logNative(ctx.threadId, "session/update", event.rawPayload);
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpContentDeltaEvent({
|
||||
stamp: yield* makeEventStamp(),
|
||||
stamp,
|
||||
provider: PROVIDER,
|
||||
threadId: ctx.threadId,
|
||||
turnId: ctx.activeTurnId,
|
||||
turnId: notificationTurnId,
|
||||
...(event.itemId ? { itemId: event.itemId } : {}),
|
||||
text: event.text,
|
||||
rawPayload: event.rawPayload,
|
||||
@@ -697,6 +923,15 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
// resolving from here on does not settle the turn; decremented on
|
||||
// preparation failure here, and after the prompt below otherwise.
|
||||
ctx.promptsInFlight += 1;
|
||||
// Bind the turn id before cooperative yields so interruptTurn can
|
||||
// settle this prompt even if stop arrives during preparation.
|
||||
ctx.activeTurnId = turnId;
|
||||
ctx.session = {
|
||||
...ctx.session,
|
||||
status: steeringTurnId === undefined ? "connecting" : "running",
|
||||
activeTurnId: turnId,
|
||||
updatedAt: yield* nowIso,
|
||||
};
|
||||
|
||||
return yield* Effect.gen(function* () {
|
||||
const turnModelSelection =
|
||||
@@ -765,12 +1000,27 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
const displayModel = currentModelId
|
||||
? resolveGrokAcpBaseModelId(currentModelId)
|
||||
: undefined;
|
||||
ctx.activeTurnId = turnId;
|
||||
for (let yieldAttempt = 0; yieldAttempt < 8; yieldAttempt += 1) {
|
||||
yield* Effect.yieldNow;
|
||||
}
|
||||
if (ctx.interruptedTurnIds.has(turnId)) {
|
||||
yield* settlePromptInFlight(input.threadId, turnId, ctx.acpSessionId, {
|
||||
completedStopReason: "cancelled",
|
||||
emitTurnCompletion: false,
|
||||
settleAllPrompts: true,
|
||||
});
|
||||
return yield* new ProviderAdapterRequestError({
|
||||
provider: PROVIDER,
|
||||
method: "session/prompt",
|
||||
detail: "Grok prompt was interrupted during preparation.",
|
||||
});
|
||||
}
|
||||
if (steeringTurnId === undefined) {
|
||||
ctx.lastPlanFingerprint = undefined;
|
||||
}
|
||||
ctx.session = {
|
||||
...ctx.session,
|
||||
status: "running",
|
||||
activeTurnId: turnId,
|
||||
updatedAt: yield* nowIso,
|
||||
...(displayModel ? { model: displayModel } : {}),
|
||||
@@ -796,13 +1046,27 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
};
|
||||
}).pipe(
|
||||
Effect.tapCause(() =>
|
||||
Effect.sync(() => {
|
||||
ctx.promptsInFlight = Math.max(0, ctx.promptsInFlight - 1);
|
||||
Effect.gen(function* () {
|
||||
const liveCtx = sessions.get(input.threadId);
|
||||
if (!liveCtx) {
|
||||
return;
|
||||
}
|
||||
yield* settlePromptInFlight(input.threadId, turnId, liveCtx.acpSessionId, {
|
||||
errorMessage: "Grok prompt preparation failed.",
|
||||
emitTurnCompletion: false,
|
||||
});
|
||||
}),
|
||||
),
|
||||
);
|
||||
}),
|
||||
);
|
||||
const promptSettled = yield* Ref.make(false);
|
||||
const promptRpcSucceeded = yield* Ref.make(false);
|
||||
const promptResultRef = yield* Ref.make<EffectAcpSchema.PromptResponse | undefined>(
|
||||
undefined,
|
||||
);
|
||||
|
||||
const promptFailureMessageRef = yield* Ref.make<string | undefined>(undefined);
|
||||
|
||||
return yield* Effect.gen(function* () {
|
||||
const result = yield* prepared.acp
|
||||
@@ -810,6 +1074,18 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
prompt: prepared.promptParts,
|
||||
})
|
||||
.pipe(
|
||||
Effect.tap((promptResult) =>
|
||||
Effect.all([
|
||||
Ref.set(promptRpcSucceeded, true),
|
||||
Ref.set(promptResultRef, promptResult),
|
||||
]),
|
||||
),
|
||||
Effect.tapError((error) =>
|
||||
Ref.set(
|
||||
promptFailureMessageRef,
|
||||
mapAcpToAdapterError(PROVIDER, input.threadId, "session/prompt", error).message,
|
||||
).pipe(Effect.andThen(prepared.acp.drainEvents)),
|
||||
),
|
||||
Effect.mapError((error) =>
|
||||
mapAcpToAdapterError(PROVIDER, input.threadId, "session/prompt", error),
|
||||
),
|
||||
@@ -820,38 +1096,88 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
Effect.gen(function* () {
|
||||
const ctx = yield* requireSession(input.threadId);
|
||||
if (ctx.acpSessionId !== prepared.acpSessionId) {
|
||||
yield* settlePromptInFlight(
|
||||
input.threadId,
|
||||
prepared.turnId,
|
||||
prepared.acpSessionId,
|
||||
{
|
||||
errorMessage: "Grok session changed before the turn completed.",
|
||||
settleAllPrompts: true,
|
||||
},
|
||||
);
|
||||
yield* Ref.set(promptSettled, true);
|
||||
return yield* new ProviderAdapterRequestError({
|
||||
provider: PROVIDER,
|
||||
method: "session/prompt",
|
||||
detail: "Grok session changed before the turn completed.",
|
||||
});
|
||||
}
|
||||
// Keep prompt settlement atomic with respect to Stop and steering.
|
||||
// interruptTurn marks its target before waiting for this lock, so
|
||||
// cancellation can still win while queued ACP events are drained.
|
||||
for (let yieldAttempt = 0; yieldAttempt < 8; yieldAttempt += 1) {
|
||||
yield* Effect.yieldNow;
|
||||
}
|
||||
yield* prepared.acp.drainEvents;
|
||||
if (ctx.interruptedTurnIds.has(prepared.turnId)) {
|
||||
yield* Ref.set(promptSettled, true);
|
||||
return {
|
||||
threadId: input.threadId,
|
||||
turnId: prepared.turnId,
|
||||
resumeCursor: ctx.session.resumeCursor,
|
||||
};
|
||||
}
|
||||
|
||||
const existingTurnRecord = ctx.turns.find((turn) => turn.id === prepared.turnId);
|
||||
ctx.turns = existingTurnRecord
|
||||
? ctx.turns.map((turn) =>
|
||||
turn.id === prepared.turnId
|
||||
? {
|
||||
...turn,
|
||||
items: [...turn.items, { prompt: prepared.promptParts, result }],
|
||||
}
|
||||
: turn,
|
||||
)
|
||||
: [
|
||||
...ctx.turns,
|
||||
{ id: prepared.turnId, items: [{ prompt: prepared.promptParts, result }] },
|
||||
];
|
||||
if (
|
||||
ctx.promptsInFlight <= 0 ||
|
||||
ctx.activeTurnId !== prepared.turnId ||
|
||||
ctx.session.activeTurnId !== prepared.turnId
|
||||
) {
|
||||
yield* Ref.set(promptSettled, true);
|
||||
return {
|
||||
threadId: input.threadId,
|
||||
turnId: prepared.turnId,
|
||||
resumeCursor: ctx.session.resumeCursor,
|
||||
};
|
||||
}
|
||||
|
||||
appendPromptResultToTurn(ctx, prepared.turnId, prepared.promptParts, result);
|
||||
ctx.session = {
|
||||
...ctx.session,
|
||||
status: "running",
|
||||
activeTurnId: prepared.turnId,
|
||||
updatedAt: yield* nowIso,
|
||||
...(prepared.displayModel ? { model: prepared.displayModel } : {}),
|
||||
};
|
||||
const remainingPrompts = Math.max(0, ctx.promptsInFlight - 1);
|
||||
ctx.promptsInFlight = remainingPrompts;
|
||||
|
||||
// Only the last remaining prompt settles the turn — a steer-
|
||||
// superseded prompt resolving (usually cancelled) while another
|
||||
// is in flight or pending must leave the merged turn running.
|
||||
if (ctx.promptsInFlight === 1) {
|
||||
// Only the last remaining prompt settles the turn. A steer-
|
||||
// superseded prompt resolving while another is in flight or
|
||||
// pending must leave the merged turn running.
|
||||
if (
|
||||
remainingPrompts === 0 &&
|
||||
ctx.activeTurnId === prepared.turnId &&
|
||||
ctx.session.activeTurnId === prepared.turnId
|
||||
) {
|
||||
if (ctx.interruptedTurnIds.has(prepared.turnId)) {
|
||||
yield* Ref.set(promptSettled, true);
|
||||
return {
|
||||
threadId: input.threadId,
|
||||
turnId: prepared.turnId,
|
||||
resumeCursor: ctx.session.resumeCursor,
|
||||
};
|
||||
}
|
||||
const completedAt = yield* nowIso;
|
||||
const { activeTurnId: _completedTurnId, ...readySession } = ctx.session;
|
||||
ctx.activeTurnId = undefined;
|
||||
ctx.session = {
|
||||
...readySession,
|
||||
status: "ready",
|
||||
updatedAt: completedAt,
|
||||
...(prepared.displayModel ? { model: prepared.displayModel } : {}),
|
||||
};
|
||||
const completedStopReason = completedStopReasonFromPromptResponse(result);
|
||||
yield* offerRuntimeEvent({
|
||||
type: "turn.completed",
|
||||
...(yield* makeEventStamp()),
|
||||
@@ -860,9 +1186,13 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
turnId: prepared.turnId,
|
||||
payload: {
|
||||
state: result.stopReason === "cancelled" ? "cancelled" : "completed",
|
||||
stopReason: result.stopReason ?? null,
|
||||
stopReason: completedStopReason,
|
||||
},
|
||||
});
|
||||
ctx.interruptedTurnIds.delete(prepared.turnId);
|
||||
yield* Ref.set(promptSettled, true);
|
||||
} else if (remainingPrompts > 0) {
|
||||
yield* Ref.set(promptSettled, true);
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -874,27 +1204,153 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
);
|
||||
}).pipe(
|
||||
Effect.ensuring(
|
||||
Effect.sync(() => {
|
||||
const liveCtx = sessions.get(input.threadId);
|
||||
if (liveCtx) {
|
||||
liveCtx.promptsInFlight = Math.max(0, liveCtx.promptsInFlight - 1);
|
||||
Effect.gen(function* () {
|
||||
if (yield* Ref.get(promptSettled)) {
|
||||
return;
|
||||
}
|
||||
}),
|
||||
|
||||
if (yield* Ref.get(promptRpcSucceeded)) {
|
||||
const promptResult = yield* Ref.get(promptResultRef);
|
||||
if (promptResult === undefined) {
|
||||
return;
|
||||
}
|
||||
yield* withThreadLock(
|
||||
input.threadId,
|
||||
Effect.gen(function* () {
|
||||
const ctx = yield* requireSession(input.threadId);
|
||||
if (ctx.acpSessionId !== prepared.acpSessionId) {
|
||||
yield* settlePromptInFlight(
|
||||
input.threadId,
|
||||
prepared.turnId,
|
||||
prepared.acpSessionId,
|
||||
{
|
||||
errorMessage: "Grok session changed before the turn completed.",
|
||||
settleAllPrompts: true,
|
||||
},
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (ctx.interruptedTurnIds.has(prepared.turnId)) {
|
||||
return;
|
||||
}
|
||||
if (
|
||||
ctx.promptsInFlight <= 0 ||
|
||||
ctx.activeTurnId !== prepared.turnId ||
|
||||
ctx.session.activeTurnId !== prepared.turnId
|
||||
) {
|
||||
return;
|
||||
}
|
||||
appendPromptResultToTurn(
|
||||
ctx,
|
||||
prepared.turnId,
|
||||
prepared.promptParts,
|
||||
promptResult,
|
||||
);
|
||||
yield* settlePromptInFlight(
|
||||
input.threadId,
|
||||
prepared.turnId,
|
||||
prepared.acpSessionId,
|
||||
{
|
||||
completedStopReason: completedStopReasonFromPromptResponse(promptResult),
|
||||
},
|
||||
);
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const errorMessage = yield* Ref.get(promptFailureMessageRef);
|
||||
yield* withThreadLock(
|
||||
input.threadId,
|
||||
settlePromptInFlight(input.threadId, prepared.turnId, prepared.acpSessionId, {
|
||||
errorMessage: errorMessage ?? "Grok prompt request failed.",
|
||||
}),
|
||||
);
|
||||
}).pipe(Effect.catch(() => Effect.void)),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
const interruptTurn: GrokAdapterShape["interruptTurn"] = (threadId) =>
|
||||
const interruptTurn: GrokAdapterShape["interruptTurn"] = (threadId, turnId) =>
|
||||
Effect.gen(function* () {
|
||||
const ctx = yield* requireSession(threadId);
|
||||
yield* settlePendingApprovalsAsCancelled(ctx.pendingApprovals);
|
||||
yield* settlePendingUserInputsAsCancelled(ctx.pendingUserInputs);
|
||||
yield* Effect.ignore(
|
||||
ctx.acp.cancel.pipe(
|
||||
Effect.mapError((error) =>
|
||||
mapAcpToAdapterError(PROVIDER, threadId, "session/cancel", error),
|
||||
),
|
||||
),
|
||||
const observed = yield* Effect.sync(() => {
|
||||
const ctx = sessions.get(threadId);
|
||||
if (!ctx || ctx.stopped) {
|
||||
return {
|
||||
_tag: "Proceed" as const,
|
||||
acpSessionId: undefined,
|
||||
interruptedTurnId: turnId,
|
||||
};
|
||||
}
|
||||
const activeTurnId = ctx.activeTurnId ?? ctx.session.activeTurnId;
|
||||
if (turnId !== undefined && activeTurnId !== undefined && activeTurnId !== turnId) {
|
||||
return { _tag: "Ignore" as const };
|
||||
}
|
||||
const interruptedTurnId = turnId ?? activeTurnId;
|
||||
if (interruptedTurnId !== undefined) {
|
||||
ctx.interruptedTurnIds.add(interruptedTurnId);
|
||||
}
|
||||
return {
|
||||
_tag: "Proceed" as const,
|
||||
acpSessionId: ctx.acpSessionId,
|
||||
interruptedTurnId,
|
||||
};
|
||||
});
|
||||
if (observed._tag === "Ignore") {
|
||||
return;
|
||||
}
|
||||
|
||||
yield* withThreadLock(
|
||||
threadId,
|
||||
Effect.gen(function* () {
|
||||
const ctx = yield* requireSession(threadId);
|
||||
if (observed.acpSessionId !== undefined && ctx.acpSessionId !== observed.acpSessionId) {
|
||||
return;
|
||||
}
|
||||
const activeTurnId = ctx.activeTurnId ?? ctx.session.activeTurnId;
|
||||
if (turnId !== undefined && activeTurnId !== undefined && activeTurnId !== turnId) {
|
||||
return;
|
||||
}
|
||||
if (
|
||||
observed.interruptedTurnId !== undefined &&
|
||||
activeTurnId !== undefined &&
|
||||
activeTurnId !== observed.interruptedTurnId
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const interruptedTurnId =
|
||||
observed.interruptedTurnId ?? turnId ?? activeTurnId ?? ctx.session.activeTurnId;
|
||||
yield* settlePendingApprovalsAsCancelled(ctx.pendingApprovals);
|
||||
yield* settlePendingUserInputsAsCancelled(ctx.pendingUserInputs);
|
||||
yield* Effect.ignore(
|
||||
ctx.acp.cancel.pipe(
|
||||
Effect.mapError((error) =>
|
||||
mapAcpToAdapterError(PROVIDER, threadId, "session/cancel", error),
|
||||
),
|
||||
),
|
||||
);
|
||||
if (interruptedTurnId) {
|
||||
ctx.interruptedTurnIds.add(interruptedTurnId);
|
||||
yield* settlePromptInFlight(threadId, interruptedTurnId, ctx.acpSessionId, {
|
||||
completedStopReason: "cancelled",
|
||||
settleAllPrompts: true,
|
||||
});
|
||||
} else if (
|
||||
ctx.promptsInFlight > 0 ||
|
||||
ctx.session.status === "running" ||
|
||||
ctx.session.status === "connecting"
|
||||
) {
|
||||
const updatedAt = yield* nowIso;
|
||||
ctx.promptsInFlight = 0;
|
||||
ctx.activeTurnId = undefined;
|
||||
const { activeTurnId: _activeTurnId, ...readySession } = ctx.session;
|
||||
ctx.session = {
|
||||
...readySession,
|
||||
status: "ready",
|
||||
updatedAt,
|
||||
};
|
||||
}
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@@ -7,6 +7,9 @@ import * as NodeFS from "node:fs";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Option from "effect/Option";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { describe, expect } from "vite-plus/test";
|
||||
|
||||
@@ -113,6 +116,122 @@ describe("AcpSessionRuntime", () => {
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("drops session updates emitted for a child ACP session", () =>
|
||||
Effect.gen(function* () {
|
||||
const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
|
||||
yield* runtime.start();
|
||||
|
||||
const promptResult = yield* runtime.prompt({
|
||||
prompt: [{ type: "text", text: "hi" }],
|
||||
});
|
||||
expect(promptResult).toMatchObject({ stopReason: "end_turn" });
|
||||
|
||||
const notes = Array.from(yield* Stream.runCollect(Stream.take(runtime.getEvents(), 4)));
|
||||
expect(notes.map((note) => note._tag)).toEqual([
|
||||
"AssistantItemStarted",
|
||||
"ContentDelta",
|
||||
"ContentDelta",
|
||||
"AssistantItemCompleted",
|
||||
]);
|
||||
expect(
|
||||
notes
|
||||
.filter((note) => note._tag === "ContentDelta")
|
||||
.map((note) => note.text)
|
||||
.join(""),
|
||||
).toBe("root before child root after child");
|
||||
expect(notes.some((note) => note._tag === "ToolCallUpdated")).toBe(false);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
AcpSessionRuntime.layer({
|
||||
spawn: {
|
||||
command: mockAgentCommand,
|
||||
args: mockAgentArgs,
|
||||
env: {
|
||||
T3_ACP_EMIT_FOREIGN_SESSION_UPDATES: "1",
|
||||
},
|
||||
},
|
||||
cwd: process.cwd(),
|
||||
clientInfo: { name: "t3-test", version: "0.0.0" },
|
||||
authMethodId: "test",
|
||||
}),
|
||||
),
|
||||
Effect.scoped,
|
||||
Effect.provide(NodeServices.layer),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("supports successive standard ACP prompts", () =>
|
||||
Effect.gen(function* () {
|
||||
const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
|
||||
yield* runtime.start();
|
||||
|
||||
const firstPromptResult = yield* runtime.prompt({
|
||||
prompt: [{ type: "text", text: "first" }],
|
||||
});
|
||||
const secondPromptResult = yield* runtime.prompt({
|
||||
prompt: [{ type: "text", text: "second" }],
|
||||
});
|
||||
|
||||
expect(firstPromptResult).toMatchObject({ stopReason: "end_turn" });
|
||||
expect(secondPromptResult).toMatchObject({ stopReason: "end_turn" });
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
AcpSessionRuntime.layer({
|
||||
spawn: {
|
||||
command: mockAgentCommand,
|
||||
args: mockAgentArgs,
|
||||
},
|
||||
cwd: process.cwd(),
|
||||
clientInfo: { name: "t3-test", version: "0.0.0" },
|
||||
authMethodId: "test",
|
||||
}),
|
||||
),
|
||||
Effect.scoped,
|
||||
Effect.provide(NodeServices.layer),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("releases a fully silent prompt when session/cancel is requested", () =>
|
||||
Effect.gen(function* () {
|
||||
const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
|
||||
yield* runtime.start();
|
||||
|
||||
const promptFiber = yield* runtime
|
||||
.prompt({
|
||||
prompt: [{ type: "text", text: "hang forever" }],
|
||||
})
|
||||
.pipe(Effect.forkChild({ startImmediately: true }));
|
||||
|
||||
yield* TestClock.adjust("500 millis");
|
||||
yield* runtime.cancel;
|
||||
|
||||
const firstPromptResult = yield* Fiber.join(promptFiber);
|
||||
expect(firstPromptResult).toMatchObject({ stopReason: "cancelled" });
|
||||
|
||||
const secondPromptResult = yield* runtime.prompt({
|
||||
prompt: [{ type: "text", text: "second" }],
|
||||
});
|
||||
expect(secondPromptResult).toMatchObject({ stopReason: "end_turn" });
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
AcpSessionRuntime.layer({
|
||||
spawn: {
|
||||
command: mockAgentCommand,
|
||||
args: mockAgentArgs,
|
||||
env: {
|
||||
T3_ACP_HANG_FIRST_PROMPT_FOREVER: "1",
|
||||
},
|
||||
},
|
||||
cwd: process.cwd(),
|
||||
clientInfo: { name: "t3-test", version: "0.0.0" },
|
||||
authMethodId: "test",
|
||||
}),
|
||||
),
|
||||
Effect.scoped,
|
||||
Effect.provide(NodeServices.layer),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("segments assistant text around ACP tool calls", () =>
|
||||
Effect.gen(function* () {
|
||||
const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
|
||||
@@ -346,6 +465,109 @@ describe("AcpSessionRuntime", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("fails session startup when session/load returns an error", () =>
|
||||
Effect.gen(function* () {
|
||||
const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
|
||||
const error = yield* runtime.start().pipe(Effect.flip);
|
||||
|
||||
expect(error._tag).toBe("AcpRequestError");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
AcpSessionRuntime.layer({
|
||||
authMethodId: "test",
|
||||
spawn: {
|
||||
command: mockAgentCommand,
|
||||
args: mockAgentArgs,
|
||||
env: {
|
||||
T3_ACP_FAIL_LOAD_SESSION: "1",
|
||||
},
|
||||
},
|
||||
cwd: process.cwd(),
|
||||
resumeSessionId: "stale-session-id",
|
||||
clientInfo: { name: "t3-test", version: "0.0.0" },
|
||||
}),
|
||||
),
|
||||
Effect.scoped,
|
||||
Effect.provide(NodeServices.layer),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("ignores session/update replay notifications during session/load", () =>
|
||||
Effect.gen(function* () {
|
||||
const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
|
||||
yield* runtime.start();
|
||||
|
||||
yield* runtime.prompt({
|
||||
prompt: [{ type: "text", text: "hi" }],
|
||||
});
|
||||
const notes = Array.from(yield* Stream.runCollect(Stream.take(runtime.getEvents(), 4)));
|
||||
expect(notes.map((note) => note._tag)).toEqual([
|
||||
"PlanUpdated",
|
||||
"AssistantItemStarted",
|
||||
"ContentDelta",
|
||||
"AssistantItemCompleted",
|
||||
]);
|
||||
expect(notes.some((note) => note._tag === "ToolCallUpdated")).toBe(false);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
AcpSessionRuntime.layer({
|
||||
authMethodId: "test",
|
||||
spawn: {
|
||||
command: mockAgentCommand,
|
||||
args: mockAgentArgs,
|
||||
env: {
|
||||
T3_ACP_EMIT_LOAD_REPLAY: "1",
|
||||
},
|
||||
},
|
||||
cwd: process.cwd(),
|
||||
resumeSessionId: "mock-session-1",
|
||||
clientInfo: { name: "t3-test", version: "0.0.0" },
|
||||
}),
|
||||
),
|
||||
Effect.scoped,
|
||||
Effect.provide(NodeServices.layer),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("completes session/load after replay becomes idle while its RPC stays pending", () =>
|
||||
Effect.gen(function* () {
|
||||
const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
|
||||
const started = yield* runtime.start().pipe(Effect.timeout("2 seconds"));
|
||||
|
||||
expect(started.sessionId).toBe("mock-session-1");
|
||||
expect(started.sessionSetupResult._meta).toMatchObject({
|
||||
t3SessionLoadReady: "replay_idle",
|
||||
});
|
||||
|
||||
const unexpectedReplayEvent = yield* Stream.runHead(runtime.getEvents()).pipe(
|
||||
Effect.timeoutOption("100 millis"),
|
||||
);
|
||||
expect(Option.isNone(unexpectedReplayEvent)).toBe(true);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
AcpSessionRuntime.layer({
|
||||
authMethodId: "test",
|
||||
spawn: {
|
||||
command: mockAgentCommand,
|
||||
args: mockAgentArgs,
|
||||
env: {
|
||||
T3_ACP_HANG_LOAD_SESSION_AFTER_REPLAY: "1",
|
||||
T3_ACP_LOAD_SESSION_DELAY_MS: "10000",
|
||||
},
|
||||
},
|
||||
cwd: process.cwd(),
|
||||
resumeSessionId: "mock-session-1",
|
||||
sessionLoadReplayIdleGap: "50 millis",
|
||||
sessionLoadTimeout: "1 second",
|
||||
clientInfo: { name: "t3-test", version: "0.0.0" },
|
||||
}),
|
||||
),
|
||||
Effect.scoped,
|
||||
Effect.provide(NodeServices.layer),
|
||||
TestClock.withLive,
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("rejects invalid config option values before sending session/set_config_option", () => {
|
||||
const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "acp-runtime-"));
|
||||
const requestLogPath = NodePath.join(tempDir, "requests.ndjson");
|
||||
|
||||
@@ -8,6 +8,8 @@ import {
|
||||
parsePermissionRequest,
|
||||
parseSessionModeState,
|
||||
parseSessionUpdateEvent,
|
||||
sessionUpdateIsReplay,
|
||||
syntheticLoadSessionResponseFromInitialize,
|
||||
} from "./AcpRuntimeModel.ts";
|
||||
|
||||
describe("AcpRuntimeModel", () => {
|
||||
@@ -59,6 +61,95 @@ describe("AcpRuntimeModel", () => {
|
||||
expect(modelConfigId).toBe("model");
|
||||
});
|
||||
|
||||
it("detects Grok session replay updates from _meta.isReplay", () => {
|
||||
expect(
|
||||
sessionUpdateIsReplay({
|
||||
_meta: { isReplay: true },
|
||||
sessionId: "session-1",
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "replayed" },
|
||||
},
|
||||
} satisfies EffectAcpSchema.SessionNotification),
|
||||
).toBe(true);
|
||||
expect(
|
||||
sessionUpdateIsReplay({
|
||||
sessionId: "session-1",
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "live" },
|
||||
},
|
||||
} satisfies EffectAcpSchema.SessionNotification),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("builds a synthetic load response from initialize model state", () => {
|
||||
const response = syntheticLoadSessionResponseFromInitialize({
|
||||
protocolVersion: 1,
|
||||
_meta: {
|
||||
modelState: {
|
||||
currentModelId: "grok-build",
|
||||
availableModels: [{ modelId: "grok-build", name: "Grok Build" }],
|
||||
},
|
||||
},
|
||||
} satisfies EffectAcpSchema.InitializeResponse);
|
||||
|
||||
expect(response.models?.currentModelId).toBe("grok-build");
|
||||
expect(response._meta).toMatchObject({ t3SessionLoadReady: "replay_idle" });
|
||||
});
|
||||
|
||||
it("accepts initialize model descriptions with null", () => {
|
||||
const response = syntheticLoadSessionResponseFromInitialize({
|
||||
protocolVersion: 1,
|
||||
_meta: {
|
||||
modelState: {
|
||||
currentModelId: "grok-build",
|
||||
availableModels: [{ modelId: "grok-build", name: "Grok Build", description: null }],
|
||||
},
|
||||
},
|
||||
} satisfies EffectAcpSchema.InitializeResponse);
|
||||
|
||||
expect(response.models?.availableModels[0]?.description).toBeNull();
|
||||
});
|
||||
|
||||
it("ignores malformed initialize model state in synthetic load responses", () => {
|
||||
const response = syntheticLoadSessionResponseFromInitialize({
|
||||
protocolVersion: 1,
|
||||
_meta: {
|
||||
modelState: {
|
||||
currentModelId: "grok-build",
|
||||
availableModels: [null],
|
||||
},
|
||||
modeState: {
|
||||
currentModeId: "code",
|
||||
availableModes: [{ id: "code", name: 12 }],
|
||||
},
|
||||
},
|
||||
} as EffectAcpSchema.InitializeResponse);
|
||||
|
||||
expect(response.models).toBeUndefined();
|
||||
expect(response.modes).toBeUndefined();
|
||||
expect(response._meta).toMatchObject({ t3SessionLoadReady: "replay_idle" });
|
||||
});
|
||||
|
||||
it("builds a synthetic load response with initialize mode state", () => {
|
||||
const response = syntheticLoadSessionResponseFromInitialize({
|
||||
protocolVersion: 1,
|
||||
_meta: {
|
||||
modeState: {
|
||||
currentModeId: "code",
|
||||
availableModes: [
|
||||
{ id: "ask", name: "Ask" },
|
||||
{ id: "code", name: "Code" },
|
||||
],
|
||||
},
|
||||
},
|
||||
} satisfies EffectAcpSchema.InitializeResponse);
|
||||
|
||||
expect(response.modes?.currentModeId).toBe("code");
|
||||
expect(response.modes?.availableModes).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("projects typed ACP tool call updates into runtime events", () => {
|
||||
const created = parseSessionUpdateEvent({
|
||||
sessionId: "session-1",
|
||||
|
||||
@@ -1,3 +1,8 @@
|
||||
import * as Clock from "effect/Clock";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
import type * as EffectAcpSchema from "effect-acp/schema";
|
||||
import { deriveToolActivityPresentation } from "@t3tools/shared/toolActivity";
|
||||
import type { ToolLifecycleItemType } from "@t3tools/contracts";
|
||||
@@ -6,6 +11,40 @@ function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function isSessionModelState(value: unknown): value is EffectAcpSchema.SessionModelState {
|
||||
if (!isRecord(value) || typeof value.currentModelId !== "string") {
|
||||
return false;
|
||||
}
|
||||
if (!Array.isArray(value.availableModels)) {
|
||||
return false;
|
||||
}
|
||||
return value.availableModels.every(
|
||||
(model) =>
|
||||
isRecord(model) &&
|
||||
typeof model.modelId === "string" &&
|
||||
typeof model.name === "string" &&
|
||||
(model.description === undefined ||
|
||||
model.description === null ||
|
||||
typeof model.description === "string"),
|
||||
);
|
||||
}
|
||||
|
||||
function isSessionModeState(value: unknown): value is EffectAcpSchema.SessionModeState {
|
||||
if (!isRecord(value) || typeof value.currentModeId !== "string") {
|
||||
return false;
|
||||
}
|
||||
if (!Array.isArray(value.availableModes)) {
|
||||
return false;
|
||||
}
|
||||
return value.availableModes.every(
|
||||
(mode) =>
|
||||
isRecord(mode) &&
|
||||
typeof mode.id === "string" &&
|
||||
typeof mode.name === "string" &&
|
||||
(mode.description === undefined || typeof mode.description === "string"),
|
||||
);
|
||||
}
|
||||
|
||||
export interface AcpSessionMode {
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
@@ -414,6 +453,58 @@ export function parsePermissionRequest(
|
||||
};
|
||||
}
|
||||
|
||||
export function sessionUpdateIsReplay(params: EffectAcpSchema.SessionNotification): boolean {
|
||||
const meta = params._meta;
|
||||
return isRecord(meta) && meta.isReplay === true;
|
||||
}
|
||||
|
||||
export interface SessionLoadGate {
|
||||
readonly active: boolean;
|
||||
readonly lastActivityAtMillis: number | undefined;
|
||||
readonly idleGap: Duration.Duration;
|
||||
readonly initializeResult: EffectAcpSchema.InitializeResponse;
|
||||
}
|
||||
|
||||
export const waitForSessionLoadReplayIdle = (input: {
|
||||
readonly gateRef: Ref.Ref<Option.Option<SessionLoadGate>>;
|
||||
}): Effect.Effect<EffectAcpSchema.LoadSessionResponse, never> =>
|
||||
Effect.gen(function* () {
|
||||
const pollInterval = Duration.millis(25);
|
||||
while (true) {
|
||||
const gate = yield* Ref.get(input.gateRef);
|
||||
if (
|
||||
Option.isSome(gate) &&
|
||||
gate.value.active &&
|
||||
gate.value.lastActivityAtMillis !== undefined
|
||||
) {
|
||||
const idleGapMillis = Duration.toMillis(gate.value.idleGap);
|
||||
const nowMillis = yield* Clock.currentTimeMillis;
|
||||
if (nowMillis - gate.value.lastActivityAtMillis >= idleGapMillis) {
|
||||
return syntheticLoadSessionResponseFromInitialize(gate.value.initializeResult);
|
||||
}
|
||||
}
|
||||
yield* Effect.sleep(pollInterval);
|
||||
}
|
||||
});
|
||||
|
||||
export function syntheticLoadSessionResponseFromInitialize(
|
||||
initializeResult: EffectAcpSchema.InitializeResponse,
|
||||
): EffectAcpSchema.LoadSessionResponse {
|
||||
const meta = initializeResult._meta;
|
||||
const modelState = isRecord(meta) ? meta.modelState : undefined;
|
||||
const modeState = isRecord(meta) ? meta.modeState : undefined;
|
||||
const models = isSessionModelState(modelState) ? modelState : undefined;
|
||||
const modes = isSessionModeState(modeState) ? modeState : undefined;
|
||||
|
||||
return {
|
||||
...(models ? { models } : {}),
|
||||
...(modes ? { modes } : {}),
|
||||
_meta: {
|
||||
t3SessionLoadReady: "replay_idle",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function parseSessionUpdateEvent(params: EffectAcpSchema.SessionNotification): {
|
||||
readonly modeId?: string;
|
||||
readonly events: ReadonlyArray<AcpParsedSessionEvent>;
|
||||
|
||||
@@ -1,12 +1,16 @@
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Clock from "effect/Clock";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Queue from "effect/Queue";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as ChildProcess from "effect/unstable/process/ChildProcess";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
@@ -23,6 +27,9 @@ import {
|
||||
mergeToolCallState,
|
||||
parseSessionModeState,
|
||||
parseSessionUpdateEvent,
|
||||
sessionUpdateIsReplay,
|
||||
waitForSessionLoadReplayIdle,
|
||||
type SessionLoadGate,
|
||||
type AcpParsedSessionEvent,
|
||||
type AcpSessionModeState,
|
||||
type AcpToolCallState,
|
||||
@@ -32,6 +39,16 @@ function formatConfigOptionValue(value: string | boolean): string {
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
|
||||
export interface AcpSessionEventStreamBarrier {
|
||||
readonly _tag: "EventStreamBarrier";
|
||||
readonly acknowledge: Deferred.Deferred<void>;
|
||||
}
|
||||
|
||||
export type AcpSessionRuntimeEvent = AcpParsedSessionEvent | AcpSessionEventStreamBarrier;
|
||||
|
||||
const defaultSessionLoadTimeout = Duration.seconds(90);
|
||||
const defaultSessionLoadReplayIdleGap = Duration.seconds(2);
|
||||
|
||||
export interface AcpSpawnInput {
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
@@ -43,6 +60,8 @@ export interface AcpSessionRuntimeOptions {
|
||||
readonly spawn: AcpSpawnInput;
|
||||
readonly cwd: string;
|
||||
readonly resumeSessionId?: string;
|
||||
readonly sessionLoadTimeout?: Duration.Input;
|
||||
readonly sessionLoadReplayIdleGap?: Duration.Input;
|
||||
readonly clientCapabilities?: EffectAcpSchema.InitializeRequest["clientCapabilities"];
|
||||
readonly clientInfo: {
|
||||
readonly name: string;
|
||||
@@ -160,7 +179,9 @@ export class AcpSessionRuntime extends Context.Service<
|
||||
*/
|
||||
readonly start: () => Effect.Effect<AcpSessionRuntimeStartResult, EffectAcpErrors.AcpError>;
|
||||
/** Stream of parsed ACP session events emitted after startup. */
|
||||
readonly getEvents: () => Stream.Stream<AcpParsedSessionEvent, never>;
|
||||
readonly getEvents: () => Stream.Stream<AcpSessionRuntimeEvent, never>;
|
||||
/** Waits until the current event consumer has processed every queued event. */
|
||||
readonly drainEvents: Effect.Effect<void>;
|
||||
/** Latest mode state observed from session setup and `session/update` notifications. */
|
||||
readonly getModeState: Effect.Effect<AcpSessionModeState | undefined>;
|
||||
/** Latest configuration options observed from session setup and configuration writes. */
|
||||
@@ -254,12 +275,17 @@ export const make = (
|
||||
Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const runtimeScope = yield* Scope.Scope;
|
||||
const eventQueue = yield* Queue.unbounded<AcpParsedSessionEvent>();
|
||||
const eventQueue = yield* Queue.unbounded<AcpSessionRuntimeEvent>();
|
||||
const modeStateRef = yield* Ref.make<AcpSessionModeState | undefined>(undefined);
|
||||
const toolCallsRef = yield* Ref.make(new Map<string, AcpToolCallState>());
|
||||
const assistantSegmentRef = yield* Ref.make<AcpAssistantSegmentState>({ nextSegmentIndex: 0 });
|
||||
const configOptionsRef = yield* Ref.make(sessionConfigOptionsFromSetup(undefined));
|
||||
const startStateRef = yield* Ref.make<AcpStartState>({ _tag: "NotStarted" });
|
||||
const promptSerializationSemaphore = yield* Semaphore.make(1);
|
||||
const activePromptFiberRef = yield* Ref.make<
|
||||
Option.Option<Fiber.Fiber<EffectAcpSchema.PromptResponse, EffectAcpErrors.AcpError>>
|
||||
>(Option.none());
|
||||
const sessionLoadGateRef = yield* Ref.make<Option.Option<SessionLoadGate>>(Option.none());
|
||||
|
||||
const logRequest = (event: AcpSessionRequestLogEvent) =>
|
||||
options.requestLogger ? options.requestLogger(event) : Effect.void;
|
||||
@@ -331,15 +357,40 @@ export const make = (
|
||||
const acp = yield* Effect.service(EffectAcpClient.AcpClient).pipe(Effect.provide(acpContext));
|
||||
|
||||
yield* acp.handleSessionUpdate((notification) =>
|
||||
handleSessionUpdate({
|
||||
queue: eventQueue,
|
||||
modeStateRef,
|
||||
toolCallsRef,
|
||||
assistantSegmentRef,
|
||||
params: notification,
|
||||
Effect.gen(function* () {
|
||||
const gate = yield* Ref.get(sessionLoadGateRef);
|
||||
if (Option.isSome(gate) && gate.value.active) {
|
||||
const lastActivityAtMillis = yield* Clock.currentTimeMillis;
|
||||
yield* Ref.set(
|
||||
sessionLoadGateRef,
|
||||
Option.some({
|
||||
...gate.value,
|
||||
lastActivityAtMillis,
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (sessionUpdateIsReplay(notification)) {
|
||||
return;
|
||||
}
|
||||
const startState = yield* Ref.get(startStateRef);
|
||||
// One runtime projects one root ACP session. Child-session updates need
|
||||
// explicit lineage routing and must never be flattened into this stream.
|
||||
if (
|
||||
startState._tag !== "Started" ||
|
||||
notification.sessionId !== startState.result.sessionId
|
||||
) {
|
||||
return;
|
||||
}
|
||||
yield* handleSessionUpdate({
|
||||
queue: eventQueue,
|
||||
modeStateRef,
|
||||
toolCallsRef,
|
||||
assistantSegmentRef,
|
||||
params: notification,
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
const initializeClientCapabilities = {
|
||||
fs: {
|
||||
readTextFile: false,
|
||||
@@ -499,27 +550,74 @@ export const make = (
|
||||
cwd: options.cwd,
|
||||
mcpServers: options.mcpServers ?? [],
|
||||
} satisfies EffectAcpSchema.LoadSessionRequest;
|
||||
const resumed = yield* runLoggedRequest(
|
||||
"session/load",
|
||||
loadPayload,
|
||||
acp.agent.loadSession(loadPayload),
|
||||
).pipe(Effect.exit);
|
||||
if (Exit.isSuccess(resumed)) {
|
||||
sessionId = options.resumeSessionId;
|
||||
sessionSetupResult = resumed.value;
|
||||
} else {
|
||||
const createPayload = {
|
||||
cwd: options.cwd,
|
||||
mcpServers: options.mcpServers ?? [],
|
||||
} satisfies EffectAcpSchema.NewSessionRequest;
|
||||
const created = yield* runLoggedRequest(
|
||||
"session/new",
|
||||
createPayload,
|
||||
acp.agent.createSession(createPayload),
|
||||
const sessionLoadTimeout = Duration.fromInputUnsafe(
|
||||
options.sessionLoadTimeout ?? defaultSessionLoadTimeout,
|
||||
);
|
||||
const sessionLoadReplayIdleGap = Duration.fromInputUnsafe(
|
||||
options.sessionLoadReplayIdleGap ?? defaultSessionLoadReplayIdleGap,
|
||||
);
|
||||
|
||||
yield* Ref.set(
|
||||
sessionLoadGateRef,
|
||||
Option.some({
|
||||
active: true,
|
||||
lastActivityAtMillis: undefined,
|
||||
idleGap: sessionLoadReplayIdleGap,
|
||||
initializeResult,
|
||||
}),
|
||||
);
|
||||
|
||||
sessionId = options.resumeSessionId;
|
||||
sessionSetupResult = yield* Effect.gen(function* () {
|
||||
yield* logRequest({
|
||||
method: "session/load",
|
||||
payload: loadPayload,
|
||||
status: "started",
|
||||
});
|
||||
|
||||
const idleFiber = yield* waitForSessionLoadReplayIdle({
|
||||
gateRef: sessionLoadGateRef,
|
||||
}).pipe(Effect.forkIn(runtimeScope));
|
||||
const loaded = yield* Effect.raceFirst(
|
||||
acp.agent.loadSession(loadPayload),
|
||||
Fiber.join(idleFiber),
|
||||
).pipe(
|
||||
Effect.ensuring(Fiber.interrupt(idleFiber).pipe(Effect.ignore)),
|
||||
Effect.timeoutOption(sessionLoadTimeout),
|
||||
Effect.flatMap((result) =>
|
||||
Option.match(result, {
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
new EffectAcpErrors.AcpTransportError({
|
||||
operation: "call-rpc",
|
||||
method: "session/load",
|
||||
detail: "session/load timed out waiting for RPC response or replay idle gap",
|
||||
cause: undefined,
|
||||
}),
|
||||
),
|
||||
onSome: Effect.succeed,
|
||||
}),
|
||||
),
|
||||
Effect.tap((result) =>
|
||||
logRequest({
|
||||
method: "session/load",
|
||||
payload: loadPayload,
|
||||
status: "succeeded",
|
||||
result,
|
||||
}),
|
||||
),
|
||||
Effect.onError((cause) =>
|
||||
logRequest({
|
||||
method: "session/load",
|
||||
payload: loadPayload,
|
||||
status: "failed",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
sessionId = created.sessionId;
|
||||
sessionSetupResult = created;
|
||||
}
|
||||
|
||||
return loaded;
|
||||
}).pipe(Effect.ensuring(Ref.set(sessionLoadGateRef, Option.none())));
|
||||
} else {
|
||||
const createPayload = {
|
||||
cwd: options.cwd,
|
||||
@@ -596,25 +694,48 @@ export const make = (
|
||||
handleExtNotification: acp.handleExtNotification,
|
||||
start: () => start,
|
||||
getEvents: () => Stream.fromQueue(eventQueue),
|
||||
drainEvents: Effect.gen(function* () {
|
||||
const acknowledge = yield* Deferred.make<void>();
|
||||
yield* Queue.offer(eventQueue, {
|
||||
_tag: "EventStreamBarrier",
|
||||
acknowledge,
|
||||
});
|
||||
yield* Deferred.await(acknowledge);
|
||||
}),
|
||||
getModeState: Ref.get(modeStateRef),
|
||||
getConfigOptions: Ref.get(configOptionsRef),
|
||||
prompt: (payload) =>
|
||||
getStartedState.pipe(
|
||||
Effect.flatMap((started) => {
|
||||
promptSerializationSemaphore.withPermit(
|
||||
Effect.gen(function* () {
|
||||
const started = yield* getStartedState;
|
||||
yield* closeActiveAssistantSegment({
|
||||
queue: eventQueue,
|
||||
assistantSegmentRef,
|
||||
});
|
||||
const requestPayload = {
|
||||
sessionId: started.sessionId,
|
||||
...payload,
|
||||
} satisfies EffectAcpSchema.PromptRequest;
|
||||
return closeActiveAssistantSegment({
|
||||
queue: eventQueue,
|
||||
assistantSegmentRef,
|
||||
}).pipe(
|
||||
Effect.andThen(
|
||||
runLoggedRequest(
|
||||
"session/prompt",
|
||||
requestPayload,
|
||||
acp.agent.prompt(requestPayload),
|
||||
),
|
||||
const cancelledResponse = {
|
||||
stopReason: "cancelled",
|
||||
} satisfies EffectAcpSchema.PromptResponse;
|
||||
const promptRpcFiber = yield* runLoggedRequest(
|
||||
"session/prompt",
|
||||
requestPayload,
|
||||
acp.agent.prompt(requestPayload),
|
||||
).pipe(Effect.forkIn(runtimeScope));
|
||||
yield* Ref.set(activePromptFiberRef, Option.some(promptRpcFiber));
|
||||
return yield* Fiber.join(promptRpcFiber).pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
Cause.hasInterruptsOnly(cause)
|
||||
? Effect.succeed(cancelledResponse)
|
||||
: Effect.failCause(cause),
|
||||
),
|
||||
Effect.ensuring(
|
||||
Effect.gen(function* () {
|
||||
yield* Fiber.interrupt(promptRpcFiber).pipe(Effect.ignore);
|
||||
yield* Ref.set(activePromptFiberRef, Option.none());
|
||||
}),
|
||||
),
|
||||
Effect.tap(() =>
|
||||
closeActiveAssistantSegment({
|
||||
@@ -626,7 +747,17 @@ export const make = (
|
||||
}),
|
||||
),
|
||||
cancel: getStartedState.pipe(
|
||||
Effect.flatMap((started) => acp.agent.cancel({ sessionId: started.sessionId })),
|
||||
Effect.flatMap((started) =>
|
||||
Effect.gen(function* () {
|
||||
const activePromptFiber = yield* Ref.get(activePromptFiberRef);
|
||||
if (Option.isSome(activePromptFiber)) {
|
||||
yield* Fiber.interrupt(activePromptFiber.value).pipe(Effect.ignore);
|
||||
}
|
||||
yield* acp.agent
|
||||
.cancel({ sessionId: started.sessionId })
|
||||
.pipe(Effect.ignore, Effect.forkIn(runtimeScope));
|
||||
}),
|
||||
),
|
||||
),
|
||||
setMode: (modeId) =>
|
||||
Ref.get(modeStateRef).pipe(
|
||||
@@ -705,7 +836,7 @@ const handleSessionUpdate = ({
|
||||
assistantSegmentRef,
|
||||
params,
|
||||
}: {
|
||||
readonly queue: Queue.Queue<AcpParsedSessionEvent>;
|
||||
readonly queue: Queue.Queue<AcpSessionRuntimeEvent>;
|
||||
readonly modeStateRef: Ref.Ref<AcpSessionModeState | undefined>;
|
||||
readonly toolCallsRef: Ref.Ref<Map<string, AcpToolCallState>>;
|
||||
readonly assistantSegmentRef: Ref.Ref<AcpAssistantSegmentState>;
|
||||
@@ -801,7 +932,7 @@ const ensureActiveAssistantSegment = ({
|
||||
assistantSegmentRef,
|
||||
sessionId,
|
||||
}: {
|
||||
readonly queue: Queue.Queue<AcpParsedSessionEvent>;
|
||||
readonly queue: Queue.Queue<AcpSessionRuntimeEvent>;
|
||||
readonly assistantSegmentRef: Ref.Ref<AcpAssistantSegmentState>;
|
||||
readonly sessionId: string;
|
||||
}) =>
|
||||
@@ -838,7 +969,7 @@ const closeActiveAssistantSegment = ({
|
||||
queue,
|
||||
assistantSegmentRef,
|
||||
}: {
|
||||
readonly queue: Queue.Queue<AcpParsedSessionEvent>;
|
||||
readonly queue: Queue.Queue<AcpSessionRuntimeEvent>;
|
||||
readonly assistantSegmentRef: Ref.Ref<AcpAssistantSegmentState>;
|
||||
}) =>
|
||||
Ref.modify(assistantSegmentRef, (current) => {
|
||||
|
||||
@@ -8,6 +8,7 @@ import type * as EffectAcpSchema from "effect-acp/schema";
|
||||
import { normalizeModelSlug } from "@t3tools/shared/model";
|
||||
|
||||
import * as AcpSessionRuntime from "./AcpSessionRuntime.ts";
|
||||
import { makeXAiPromptCompletionRuntime } from "./XAiAcpExtension.ts";
|
||||
|
||||
const GROK_API_KEY_ENV = "XAI_API_KEY";
|
||||
const GROK_OAUTH2_REFERRER_ENV = "GROK_OAUTH2_REFERRER";
|
||||
@@ -68,9 +69,10 @@ export const makeGrokAcpRuntime = (
|
||||
),
|
||||
),
|
||||
);
|
||||
return yield* Effect.service(AcpSessionRuntime.AcpSessionRuntime).pipe(
|
||||
const runtime = yield* Effect.service(AcpSessionRuntime.AcpSessionRuntime).pipe(
|
||||
Effect.provide(acpContext),
|
||||
);
|
||||
return yield* makeXAiPromptCompletionRuntime(runtime);
|
||||
});
|
||||
|
||||
export function resolveGrokAcpBaseModelId(model: string | null | undefined): string {
|
||||
|
||||
@@ -1,12 +1,39 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
// @effect-diagnostics nodeBuiltinImport:off
|
||||
import * as NodePath from "node:path";
|
||||
import * as NodeURL from "node:url";
|
||||
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { describe, expect } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
extractXAiAskUserQuestions,
|
||||
makeXAiAskUserQuestionCancelledResponse,
|
||||
makeXAiAskUserQuestionResponse,
|
||||
makeXAiPromptCompletionRuntime,
|
||||
XAiAskUserQuestionRequest,
|
||||
} from "./XAiAcpExtension.ts";
|
||||
import * as AcpSessionRuntime from "./AcpSessionRuntime.ts";
|
||||
|
||||
const __dirname = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url));
|
||||
const mockAgentPath = NodePath.join(__dirname, "../../../scripts/acp-mock-agent.ts");
|
||||
|
||||
const makePromptCompletionRuntime = (env: NodeJS.ProcessEnv) =>
|
||||
Effect.gen(function* () {
|
||||
const runtime = yield* AcpSessionRuntime.make({
|
||||
spawn: {
|
||||
command: process.execPath,
|
||||
args: [mockAgentPath],
|
||||
env,
|
||||
},
|
||||
cwd: process.cwd(),
|
||||
clientInfo: { name: "t3-test", version: "0.0.0" },
|
||||
authMethodId: "test",
|
||||
});
|
||||
return yield* makeXAiPromptCompletionRuntime(runtime);
|
||||
});
|
||||
|
||||
const decodeXAiAskUserQuestionRequest = Schema.decodeUnknownSync(XAiAskUserQuestionRequest);
|
||||
|
||||
@@ -247,4 +274,59 @@ describe("XAiAcpExtension", () => {
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("resolves a hung standard prompt from xAI prompt completion", () =>
|
||||
Effect.gen(function* () {
|
||||
const runtime = yield* makePromptCompletionRuntime({
|
||||
T3_ACP_EMIT_XAI_PROMPT_COMPLETE_THEN_HANG: "1",
|
||||
});
|
||||
yield* runtime.start();
|
||||
|
||||
const promptResult = yield* runtime.prompt({
|
||||
prompt: [{ type: "text", text: "hi" }],
|
||||
});
|
||||
const promptId = promptResult._meta?.promptId;
|
||||
|
||||
expect(typeof promptId).toBe("string");
|
||||
expect(promptResult).toMatchObject({
|
||||
stopReason: "end_turn",
|
||||
_meta: {
|
||||
sessionId: "mock-session-1",
|
||||
promptId,
|
||||
requestId: promptId,
|
||||
},
|
||||
});
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("ignores stale xAI completion from an already settled prompt", () =>
|
||||
Effect.gen(function* () {
|
||||
const runtime = yield* makePromptCompletionRuntime({
|
||||
T3_ACP_EMIT_STALE_XAI_PROMPT_COMPLETE_BEFORE_SECOND_HANG: "1",
|
||||
});
|
||||
yield* runtime.start();
|
||||
|
||||
const firstPromptResult = yield* runtime.prompt({
|
||||
prompt: [{ type: "text", text: "first" }],
|
||||
});
|
||||
expect(firstPromptResult).toMatchObject({
|
||||
stopReason: "end_turn",
|
||||
_meta: { promptId: "mock-stale-xai-prompt-1" },
|
||||
});
|
||||
|
||||
const secondPromptResult = yield* runtime.prompt({
|
||||
prompt: [{ type: "text", text: "second" }],
|
||||
});
|
||||
const secondPromptId = secondPromptResult._meta?.promptId;
|
||||
expect(typeof secondPromptId).toBe("string");
|
||||
expect(secondPromptId).not.toBe("mock-stale-xai-prompt-1");
|
||||
expect(secondPromptResult).toMatchObject({
|
||||
stopReason: "end_turn",
|
||||
_meta: {
|
||||
promptId: secondPromptId,
|
||||
requestId: secondPromptId,
|
||||
},
|
||||
});
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
});
|
||||
@@ -1,5 +1,29 @@
|
||||
import type { ProviderUserInputAnswers, UserInputQuestion } from "@t3tools/contracts";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import type * as EffectAcpSchema from "effect-acp/schema";
|
||||
|
||||
import type * as AcpSessionRuntime from "./AcpSessionRuntime.ts";
|
||||
|
||||
const XAiPromptCompleteNotification = Schema.Struct({
|
||||
sessionId: Schema.String,
|
||||
promptId: Schema.optional(Schema.String),
|
||||
stopReason: Schema.optional(Schema.String),
|
||||
agentResult: Schema.optional(Schema.NullOr(Schema.Unknown)),
|
||||
});
|
||||
|
||||
type XAiPromptCompleteNotification = typeof XAiPromptCompleteNotification.Type;
|
||||
|
||||
interface PendingXAiPromptCompletion {
|
||||
readonly sessionId: string;
|
||||
readonly promptId: string;
|
||||
readonly deferred: Deferred.Deferred<EffectAcpSchema.PromptResponse>;
|
||||
}
|
||||
|
||||
const completedXAiPromptIdLimit = 128;
|
||||
const xAiStopReasonMissingMetaKey = "xAiStopReasonMissing";
|
||||
|
||||
const XAiAskUserQuestionOption = Schema.Struct({
|
||||
label: Schema.String,
|
||||
@@ -171,3 +195,238 @@ export function makeXAiAskUserQuestionResponse(
|
||||
export function makeXAiAskUserQuestionCancelledResponse(): XAiAskUserQuestionCancelledResponse {
|
||||
return { outcome: "cancelled" };
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds Grok's private prompt-completion fallback around a standards-only ACP runtime.
|
||||
* The underlying runtime remains unaware of xAI methods and metadata.
|
||||
*/
|
||||
export const makeXAiPromptCompletionRuntime = Effect.fn("makeXAiPromptCompletionRuntime")(
|
||||
function* (runtime: AcpSessionRuntime.AcpSessionRuntime["Service"]) {
|
||||
const activeSessionIdRef = yield* Ref.make<string | undefined>(undefined);
|
||||
const pendingRef = yield* Ref.make<ReadonlyArray<PendingXAiPromptCompletion>>([]);
|
||||
const completedPromptIdsRef = yield* Ref.make<ReadonlyArray<string>>([]);
|
||||
let nextPromptFallbackId = 0;
|
||||
const allocatePromptFallbackId = Effect.sync(() => {
|
||||
nextPromptFallbackId += 1;
|
||||
return `t3-xai-prompt-${nextPromptFallbackId}`;
|
||||
});
|
||||
|
||||
yield* runtime.handleExtNotification(
|
||||
"_x.ai/session/prompt_complete",
|
||||
XAiPromptCompleteNotification,
|
||||
(notification) =>
|
||||
resolveXAiPromptCompletionFallback({
|
||||
pendingRef,
|
||||
completedPromptIdsRef,
|
||||
notification,
|
||||
}),
|
||||
);
|
||||
|
||||
return {
|
||||
...runtime,
|
||||
start: () =>
|
||||
runtime
|
||||
.start()
|
||||
.pipe(Effect.tap((started) => Ref.set(activeSessionIdRef, started.sessionId))),
|
||||
prompt: (payload) =>
|
||||
Effect.gen(function* () {
|
||||
const sessionId = yield* Ref.get(activeSessionIdRef);
|
||||
if (sessionId === undefined) {
|
||||
return yield* runtime.prompt(payload);
|
||||
}
|
||||
|
||||
const promptId = yield* allocatePromptFallbackId;
|
||||
const fallback = yield* registerXAiPromptCompletionFallback(
|
||||
pendingRef,
|
||||
sessionId,
|
||||
promptId,
|
||||
);
|
||||
const requestPayload = {
|
||||
...payload,
|
||||
_meta: {
|
||||
...payload._meta,
|
||||
promptId: fallback.promptId,
|
||||
requestId: fallback.promptId,
|
||||
},
|
||||
} satisfies Omit<EffectAcpSchema.PromptRequest, "sessionId">;
|
||||
|
||||
return yield* Effect.raceFirst(
|
||||
runtime.prompt(requestPayload),
|
||||
Deferred.await(fallback.deferred),
|
||||
).pipe(
|
||||
Effect.tap((response) =>
|
||||
rememberCompletedXAiPromptId(completedPromptIdsRef, response, fallback.promptId),
|
||||
),
|
||||
Effect.ensuring(unregisterXAiPromptCompletionFallback(pendingRef, fallback.deferred)),
|
||||
);
|
||||
}),
|
||||
cancel: Ref.get(activeSessionIdRef).pipe(
|
||||
Effect.flatMap((sessionId) =>
|
||||
sessionId === undefined
|
||||
? runtime.cancel
|
||||
: abortPendingPromptCompletions(pendingRef, sessionId).pipe(
|
||||
Effect.andThen(runtime.cancel),
|
||||
),
|
||||
),
|
||||
),
|
||||
} satisfies AcpSessionRuntime.AcpSessionRuntime["Service"];
|
||||
},
|
||||
);
|
||||
|
||||
const registerXAiPromptCompletionFallback = (
|
||||
pendingRef: Ref.Ref<ReadonlyArray<PendingXAiPromptCompletion>>,
|
||||
sessionId: string,
|
||||
promptId: string,
|
||||
) =>
|
||||
Deferred.make<EffectAcpSchema.PromptResponse>().pipe(
|
||||
Effect.tap((deferred) =>
|
||||
Ref.update(pendingRef, (pending) => [...pending, { sessionId, promptId, deferred }]),
|
||||
),
|
||||
Effect.map((deferred) => ({ deferred, promptId })),
|
||||
);
|
||||
|
||||
const unregisterXAiPromptCompletionFallback = (
|
||||
pendingRef: Ref.Ref<ReadonlyArray<PendingXAiPromptCompletion>>,
|
||||
deferred: Deferred.Deferred<EffectAcpSchema.PromptResponse>,
|
||||
) => Ref.update(pendingRef, (pending) => pending.filter((entry) => entry.deferred !== deferred));
|
||||
|
||||
const abortPendingPromptCompletions = (
|
||||
pendingRef: Ref.Ref<ReadonlyArray<PendingXAiPromptCompletion>>,
|
||||
sessionId: string,
|
||||
) =>
|
||||
Ref.modify(pendingRef, (pending) => {
|
||||
const [toAbort, remaining] = pending.reduce<
|
||||
[ReadonlyArray<PendingXAiPromptCompletion>, ReadonlyArray<PendingXAiPromptCompletion>]
|
||||
>(
|
||||
([aborting, kept], entry) =>
|
||||
entry.sessionId === sessionId ? [[...aborting, entry], kept] : [aborting, [...kept, entry]],
|
||||
[[], []],
|
||||
);
|
||||
if (toAbort.length === 0) {
|
||||
return [Effect.void, pending] as const;
|
||||
}
|
||||
return [
|
||||
Effect.forEach(
|
||||
toAbort,
|
||||
(entry) =>
|
||||
Deferred.succeed(
|
||||
entry.deferred,
|
||||
promptResponseFromXAi({
|
||||
sessionId: entry.sessionId,
|
||||
promptId: entry.promptId,
|
||||
stopReason: "cancelled",
|
||||
agentResult: null,
|
||||
}),
|
||||
),
|
||||
{ concurrency: "unbounded" },
|
||||
).pipe(Effect.asVoid),
|
||||
remaining,
|
||||
] as const;
|
||||
}).pipe(Effect.flatten);
|
||||
|
||||
const resolveXAiPromptCompletionFallback = ({
|
||||
pendingRef,
|
||||
completedPromptIdsRef,
|
||||
notification,
|
||||
}: {
|
||||
readonly pendingRef: Ref.Ref<ReadonlyArray<PendingXAiPromptCompletion>>;
|
||||
readonly completedPromptIdsRef: Ref.Ref<ReadonlyArray<string>>;
|
||||
readonly notification: XAiPromptCompleteNotification;
|
||||
}) =>
|
||||
Ref.get(completedPromptIdsRef).pipe(
|
||||
Effect.flatMap((completedPromptIds) => {
|
||||
if (
|
||||
notification.promptId !== undefined &&
|
||||
completedPromptIds.includes(notification.promptId)
|
||||
) {
|
||||
return Effect.void;
|
||||
}
|
||||
return Ref.modify(pendingRef, (pending) => {
|
||||
const index =
|
||||
notification.promptId !== undefined
|
||||
? pending.findIndex(
|
||||
(entry) =>
|
||||
entry.sessionId === notification.sessionId &&
|
||||
entry.promptId === notification.promptId,
|
||||
)
|
||||
: pending.findIndex((entry) => entry.sessionId === notification.sessionId);
|
||||
if (index < 0) {
|
||||
return [Effect.void, pending] as const;
|
||||
}
|
||||
const entry = pending[index];
|
||||
if (!entry) {
|
||||
return [Effect.void, pending] as const;
|
||||
}
|
||||
return [
|
||||
Deferred.succeed(entry.deferred, promptResponseFromXAi(notification)).pipe(Effect.asVoid),
|
||||
[...pending.slice(0, index), ...pending.slice(index + 1)],
|
||||
] as const;
|
||||
}).pipe(Effect.flatten);
|
||||
}),
|
||||
);
|
||||
|
||||
const rememberCompletedXAiPromptId = (
|
||||
completedPromptIdsRef: Ref.Ref<ReadonlyArray<string>>,
|
||||
response: EffectAcpSchema.PromptResponse,
|
||||
fallbackPromptId: string,
|
||||
) => {
|
||||
const promptId = promptIdFromResponse(response) ?? fallbackPromptId;
|
||||
return Ref.update(completedPromptIdsRef, (completedPromptIds) => {
|
||||
if (completedPromptIds.includes(promptId)) {
|
||||
return completedPromptIds;
|
||||
}
|
||||
return [...completedPromptIds, promptId].slice(-completedXAiPromptIdLimit);
|
||||
});
|
||||
};
|
||||
|
||||
function promptIdFromResponse(response: EffectAcpSchema.PromptResponse): string | undefined {
|
||||
const meta = response._meta;
|
||||
if (meta === null || typeof meta !== "object") {
|
||||
return undefined;
|
||||
}
|
||||
const promptId = meta.promptId ?? meta.requestId;
|
||||
return typeof promptId === "string" && promptId.length > 0 ? promptId : undefined;
|
||||
}
|
||||
|
||||
export function promptResponseHasMissingXAiStopReason(
|
||||
response: EffectAcpSchema.PromptResponse,
|
||||
): boolean {
|
||||
const meta = response._meta;
|
||||
return meta !== null && typeof meta === "object" && meta[xAiStopReasonMissingMetaKey] === true;
|
||||
}
|
||||
|
||||
function promptResponseFromXAi(
|
||||
notification: XAiPromptCompleteNotification,
|
||||
): EffectAcpSchema.PromptResponse {
|
||||
const stopReason = normalizeXAiStopReason(notification.stopReason);
|
||||
const meta: Record<string, unknown> = {
|
||||
sessionId: notification.sessionId,
|
||||
};
|
||||
if (notification.stopReason === undefined) {
|
||||
meta[xAiStopReasonMissingMetaKey] = true;
|
||||
}
|
||||
if (notification.promptId !== undefined) {
|
||||
meta.promptId = notification.promptId;
|
||||
meta.requestId = notification.promptId;
|
||||
}
|
||||
if (notification.agentResult !== undefined) {
|
||||
meta.agentResult = notification.agentResult;
|
||||
}
|
||||
return {
|
||||
stopReason,
|
||||
_meta: meta,
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeXAiStopReason(value: string | undefined): EffectAcpSchema.StopReason {
|
||||
switch (value) {
|
||||
case "cancelled":
|
||||
case "end_turn":
|
||||
case "max_tokens":
|
||||
case "max_turn_requests":
|
||||
case "refusal":
|
||||
return value;
|
||||
default:
|
||||
return "end_turn";
|
||||
}
|
||||
}
|
||||
@@ -653,6 +653,7 @@ const buildAppUnderTest = (options?: {
|
||||
Layer.mock(PreviewManager.PreviewManager)({
|
||||
open: () => Effect.die("PreviewManager not stubbed in this test"),
|
||||
navigate: () => Effect.die("PreviewManager not stubbed in this test"),
|
||||
resize: () => Effect.die("PreviewManager not stubbed in this test"),
|
||||
reportStatus: () => Effect.void,
|
||||
refresh: () => Effect.void,
|
||||
close: () => Effect.void,
|
||||
@@ -3233,6 +3234,32 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
for (const desktopOrigin of ["t3code://app", "t3code-dev://app"]) {
|
||||
it.effect(`allows credentialed preflights from ${desktopOrigin} in development`, () =>
|
||||
Effect.gen(function* () {
|
||||
yield* buildAppUnderTest({
|
||||
config: { devUrl: new URL(crossOriginClientOrigin) },
|
||||
});
|
||||
|
||||
const sessionUrl = yield* getHttpServerUrl("/api/auth/session");
|
||||
const response = yield* fetchEffect(sessionUrl, {
|
||||
method: "OPTIONS",
|
||||
headers: {
|
||||
origin: desktopOrigin,
|
||||
"access-control-request-method": "GET",
|
||||
"access-control-request-headers": "content-type",
|
||||
},
|
||||
});
|
||||
|
||||
assert.equal(response.status, 204);
|
||||
assertBrowserApiCorsPreflightHeaders(response.headers, {
|
||||
origin: desktopOrigin,
|
||||
credentials: true,
|
||||
});
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
}
|
||||
|
||||
it.effect("includes CORS headers on remote websocket-ticket auth failures", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* buildAppUnderTest();
|
||||
@@ -4099,6 +4126,46 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("shares one preview automation broker across websocket sessions", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
yield* buildAppUnderTest();
|
||||
|
||||
const wsUrl = yield* getWsServerUrl("/ws");
|
||||
const firstConnected = yield* Deferred.make<string>();
|
||||
const firstClosed = yield* Deferred.make<void>();
|
||||
const host = {
|
||||
clientId: "shared-preview-host",
|
||||
environmentId: testEnvironmentDescriptor.environmentId,
|
||||
} as const;
|
||||
|
||||
yield* withWsRpcClient(wsUrl, (client) =>
|
||||
client[WS_METHODS.previewAutomationConnect](host).pipe(
|
||||
Stream.tap((event) =>
|
||||
event.type === "connected"
|
||||
? Deferred.succeed(firstConnected, event.connectionId)
|
||||
: Effect.void,
|
||||
),
|
||||
Stream.runDrain,
|
||||
Effect.ensuring(Deferred.succeed(firstClosed, undefined)),
|
||||
),
|
||||
).pipe(Effect.forkScoped);
|
||||
|
||||
const firstConnectionId = yield* Deferred.await(firstConnected);
|
||||
const replacementEvent = yield* withWsRpcClient(wsUrl, (client) =>
|
||||
client[WS_METHODS.previewAutomationConnect](host).pipe(Stream.runHead),
|
||||
).pipe(Effect.map(Option.getOrThrow));
|
||||
const firstStreamClosed = yield* Deferred.await(firstClosed).pipe(
|
||||
Effect.timeoutOption("2 seconds"),
|
||||
);
|
||||
|
||||
assert.equal(replacementEvent.type, "connected");
|
||||
assert.notEqual(replacementEvent.connectionId, firstConnectionId);
|
||||
assert.isTrue(Option.isSome(firstStreamClosed));
|
||||
}),
|
||||
).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("rejects websocket rpc handshake when session authentication is missing", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
|
||||
@@ -36,6 +36,7 @@ import { ProviderInstanceRegistryHydrationLive } from "./provider/Layers/Provide
|
||||
import * as TerminalManager from "./terminal/Manager.ts";
|
||||
import * as McpHttpServer from "./mcp/McpHttpServer.ts";
|
||||
import * as McpSessionRegistry from "./mcp/McpSessionRegistry.ts";
|
||||
import * as PreviewAutomationBroker from "./mcp/PreviewAutomationBroker.ts";
|
||||
import * as PreviewManager from "./preview/Manager.ts";
|
||||
import * as PortScanner from "./preview/PortScanner.ts";
|
||||
import * as ProcessRunner from "./processRunner.ts";
|
||||
@@ -357,7 +358,7 @@ export const makeRoutesLayer = Layer.mergeAll(
|
||||
websocketRpcRouteLayer,
|
||||
),
|
||||
McpHttpServer.layer.pipe(Layer.provide(McpSessionRegistry.layer)),
|
||||
).pipe(Layer.provide(browserApiCorsLayer));
|
||||
).pipe(Layer.provide(PreviewAutomationBroker.layer), Layer.provide(browserApiCorsLayer));
|
||||
|
||||
export const makeServerLayer = Layer.unwrap(
|
||||
Effect.gen(function* () {
|
||||
|
||||
@@ -4,8 +4,9 @@ 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 } from "@t3tools/contracts";
|
||||
import { VcsProcessExitError, VcsProcessSpawnError } from "@t3tools/contracts";
|
||||
|
||||
import * as VcsProcess from "../vcs/VcsProcess.ts";
|
||||
import * as AzureDevOpsCli from "./AzureDevOpsCli.ts";
|
||||
@@ -345,11 +346,63 @@ 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)),
|
||||
);
|
||||
});
|
||||
@@ -1,9 +1,11 @@
|
||||
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,
|
||||
@@ -19,16 +21,61 @@ import * as SourceControlProvider from "./SourceControlProvider.ts";
|
||||
|
||||
const DEFAULT_TIMEOUT_MS = 30_000;
|
||||
|
||||
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()),
|
||||
},
|
||||
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,
|
||||
) {
|
||||
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}`;
|
||||
}
|
||||
@@ -38,53 +85,109 @@ export class AzureDevOpsCliError extends Schema.TaggedErrorClass<AzureDevOpsCliE
|
||||
readonly operation: "execute";
|
||||
readonly command: "az";
|
||||
readonly cwd: string;
|
||||
readonly argumentCount: number;
|
||||
},
|
||||
error: VcsError | unknown,
|
||||
cause: VcsError,
|
||||
): AzureDevOpsCliError {
|
||||
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,
|
||||
});
|
||||
}
|
||||
const fields = { ...context, cause };
|
||||
|
||||
if (
|
||||
lower.includes("az devops login") ||
|
||||
lower.includes("please run az login") ||
|
||||
lower.includes("not logged in") ||
|
||||
lower.includes("authentication failed") ||
|
||||
lower.includes("unauthorized")
|
||||
cause._tag === "VcsProcessSpawnError" &&
|
||||
cause.cause instanceof PlatformError.PlatformError &&
|
||||
cause.cause.reason._tag === "NotFound" &&
|
||||
cause.cause.reason.pathOrDescriptor !== context.cwd &&
|
||||
cause.cause.reason.syscall !== "chdir"
|
||||
) {
|
||||
return new AzureDevOpsCliError({
|
||||
...context,
|
||||
detail: "Azure DevOps CLI is not authenticated. Run `az devops login` and retry.",
|
||||
cause: error,
|
||||
});
|
||||
return new AzureDevOpsCliUnavailableError(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,
|
||||
});
|
||||
if (cause._tag === "VcsProcessExitError") {
|
||||
if (cause.failureKind === "authentication") {
|
||||
return new AzureDevOpsCliAuthenticationError(fields);
|
||||
}
|
||||
if (cause.failureKind === "not-found") {
|
||||
return new AzureDevOpsPullRequestNotFoundError(fields);
|
||||
}
|
||||
}
|
||||
|
||||
return new AzureDevOpsCliError({
|
||||
...context,
|
||||
detail: "Azure DevOps CLI command failed.",
|
||||
cause: error,
|
||||
});
|
||||
return new AzureDevOpsCommandFailedError(fields);
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
@@ -146,17 +249,6 @@ 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);
|
||||
@@ -225,19 +317,18 @@ function parseRepositorySpecifier(repository: string): {
|
||||
function decodeAzureDevOpsJson<S extends Schema.Top>(
|
||||
raw: string,
|
||||
schema: S,
|
||||
operation: "getRepositoryCloneUrls" | "getDefaultBranch" | "createRepository",
|
||||
invalidDetail: string,
|
||||
operation: typeof AzureDevOpsRepositoryDecodeOperation.Type,
|
||||
cwd: string,
|
||||
): Effect.Effect<S["Type"], AzureDevOpsCliError, S["DecodingServices"]> {
|
||||
): Effect.Effect<S["Type"], AzureDevOpsRepositoryDecodeError, S["DecodingServices"]> {
|
||||
return Schema.decodeEffect(Schema.fromJsonString(schema))(raw).pipe(
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new AzureDevOpsCliError({
|
||||
(cause) =>
|
||||
new AzureDevOpsRepositoryDecodeError({
|
||||
operation,
|
||||
command: "az",
|
||||
cwd,
|
||||
detail: invalidDetail,
|
||||
cause: error,
|
||||
outputLength: raw.length,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -257,8 +348,13 @@ export const make = Effect.gen(function* () {
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError((error) =>
|
||||
AzureDevOpsCliError.fromVcsError(
|
||||
{ operation: "execute", command: "az", cwd: input.cwd },
|
||||
AzureDevOpsCommandFailedError.fromVcsError(
|
||||
{
|
||||
operation: "execute",
|
||||
command: "az",
|
||||
cwd: input.cwd,
|
||||
argumentCount: input.args.length,
|
||||
},
|
||||
error,
|
||||
),
|
||||
),
|
||||
@@ -297,11 +393,11 @@ export const make = Effect.gen(function* () {
|
||||
Effect.flatMap((decoded) => {
|
||||
if (!Result.isSuccess(decoded)) {
|
||||
return Effect.fail(
|
||||
new AzureDevOpsCliError({
|
||||
new AzureDevOpsPullRequestListDecodeError({
|
||||
operation: "listPullRequests",
|
||||
command: "az",
|
||||
cwd: input.cwd,
|
||||
detail: "Azure DevOps CLI returned invalid PR list JSON.",
|
||||
outputLength: raw.length,
|
||||
cause: decoded.failure,
|
||||
}),
|
||||
);
|
||||
@@ -331,11 +427,11 @@ export const make = Effect.gen(function* () {
|
||||
Effect.flatMap((decoded) => {
|
||||
if (!Result.isSuccess(decoded)) {
|
||||
return Effect.fail(
|
||||
new AzureDevOpsCliError({
|
||||
new AzureDevOpsPullRequestDecodeError({
|
||||
operation: "getPullRequest",
|
||||
command: "az",
|
||||
cwd: input.cwd,
|
||||
detail: "Azure DevOps CLI returned invalid pull request JSON.",
|
||||
outputLength: raw.length,
|
||||
cause: decoded.failure,
|
||||
}),
|
||||
);
|
||||
@@ -357,7 +453,6 @@ export const make = Effect.gen(function* () {
|
||||
raw,
|
||||
RawAzureDevOpsRepositorySchema,
|
||||
"getRepositoryCloneUrls",
|
||||
"Azure DevOps CLI returned invalid repository JSON.",
|
||||
input.cwd,
|
||||
),
|
||||
),
|
||||
@@ -383,13 +478,7 @@ export const make = Effect.gen(function* () {
|
||||
}).pipe(
|
||||
Effect.map((result) => result.stdout.trim()),
|
||||
Effect.flatMap((raw) =>
|
||||
decodeAzureDevOpsJson(
|
||||
raw,
|
||||
RawAzureDevOpsRepositorySchema,
|
||||
"createRepository",
|
||||
"Azure DevOps CLI returned invalid repository JSON.",
|
||||
input.cwd,
|
||||
),
|
||||
decodeAzureDevOpsJson(raw, RawAzureDevOpsRepositorySchema, "createRepository", input.cwd),
|
||||
),
|
||||
Effect.map(normalizeRepositoryCloneUrls),
|
||||
);
|
||||
@@ -421,13 +510,7 @@ export const make = Effect.gen(function* () {
|
||||
}).pipe(
|
||||
Effect.map((result) => result.stdout.trim()),
|
||||
Effect.flatMap((raw) =>
|
||||
decodeAzureDevOpsJson(
|
||||
raw,
|
||||
RawAzureDevOpsRepositorySchema,
|
||||
"getDefaultBranch",
|
||||
"Azure DevOps CLI returned invalid repository JSON.",
|
||||
input.cwd,
|
||||
),
|
||||
decodeAzureDevOpsJson(raw, RawAzureDevOpsRepositorySchema, "getDefaultBranch", 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.AzureDevOpsCliError({
|
||||
const cause = new AzureDevOpsCli.AzureDevOpsCommandFailedError({
|
||||
operation: "execute",
|
||||
command: "az",
|
||||
cwd: "/repo",
|
||||
detail: "Azure DevOps CLI command failed.",
|
||||
argumentCount: 2,
|
||||
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,6 +544,61 @@ 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: () =>
|
||||
@@ -630,8 +685,9 @@ it.effect("preserves Git checkout failures without deriving the domain message f
|
||||
}),
|
||||
);
|
||||
|
||||
assert.strictEqual(error.operation, "checkoutPullRequest");
|
||||
assert.strictEqual(error.detail, "Failed to check out the Bitbucket pull request.");
|
||||
assert.instanceOf(error, BitbucketApi.BitbucketCheckoutError);
|
||||
assert.strictEqual(error.cwd, "/repo");
|
||||
assert.strictEqual(error.reference, "42");
|
||||
assert.strictEqual(
|
||||
error.message,
|
||||
"Bitbucket API failed in checkoutPullRequest: Failed to check out the Bitbucket pull request.",
|
||||
|
||||
@@ -6,6 +6,7 @@ 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,
|
||||
@@ -36,20 +37,156 @@ const BitbucketApiEnvConfig = Config.all({
|
||||
apiToken: Config.string("T3CODE_BITBUCKET_API_TOKEN").pipe(Config.option),
|
||||
});
|
||||
|
||||
export class BitbucketApiError extends Schema.TaggedErrorClass<BitbucketApiError>()(
|
||||
"BitbucketApiError",
|
||||
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",
|
||||
{
|
||||
operation: Schema.String,
|
||||
detail: Schema.String,
|
||||
status: Schema.optional(Schema.Number),
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
repository: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Bitbucket API failed in ${this.operation}: ${this.detail}`;
|
||||
return "Bitbucket API failed in createRepository: Bitbucket repositories must be specified as workspace/repository.";
|
||||
}
|
||||
}
|
||||
const isBitbucketApiError = Schema.is(BitbucketApiError);
|
||||
|
||||
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 RawBitbucketRepositorySchema = Schema.Struct({
|
||||
full_name: TrimmedNonEmptyString,
|
||||
@@ -209,16 +346,14 @@ 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 BitbucketApiError({
|
||||
operation,
|
||||
detail: "Bitbucket repositories must be specified as workspace/repository.",
|
||||
new BitbucketRepositoryLocatorError({
|
||||
repository,
|
||||
}),
|
||||
);
|
||||
}
|
||||
@@ -339,20 +474,24 @@ function authFromConfig(
|
||||
}
|
||||
|
||||
function responseError(
|
||||
operation: string,
|
||||
operation: BitbucketApiOperation,
|
||||
response: HttpClientResponse.HttpClientResponse,
|
||||
): Effect.Effect<never, BitbucketApiError> {
|
||||
return response.text.pipe(
|
||||
Effect.orElseSucceed(() => ""),
|
||||
Effect.flatMap((body) =>
|
||||
Effect.fail(
|
||||
new BitbucketApiError({
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new BitbucketResponseBodyReadError({
|
||||
operation,
|
||||
status: response.status,
|
||||
detail:
|
||||
body.trim().length > 0
|
||||
? `Bitbucket returned HTTP ${response.status}: ${body.trim()}`
|
||||
: `Bitbucket returned HTTP ${response.status}.`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.flatMap((body) =>
|
||||
Effect.fail(
|
||||
new BitbucketResponseError({
|
||||
operation,
|
||||
status: response.status,
|
||||
responseBodyLength: body.length,
|
||||
}),
|
||||
),
|
||||
),
|
||||
@@ -379,7 +518,7 @@ export const make = Effect.gen(function* () {
|
||||
};
|
||||
|
||||
const decodeResponse = <S extends Schema.Top>(
|
||||
operation: string,
|
||||
operation: BitbucketApiOperation,
|
||||
schema: S,
|
||||
response: HttpClientResponse.HttpClientResponse,
|
||||
): Effect.Effect<S["Type"], BitbucketApiError, S["DecodingServices"]> =>
|
||||
@@ -388,9 +527,9 @@ export const make = Effect.gen(function* () {
|
||||
HttpClientResponse.schemaBodyJson(schema)(success).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new BitbucketApiError({
|
||||
new BitbucketResponseDecodeError({
|
||||
operation,
|
||||
detail: "Bitbucket returned invalid JSON for the requested resource.",
|
||||
status: success.status,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
@@ -399,16 +538,15 @@ export const make = Effect.gen(function* () {
|
||||
})(response);
|
||||
|
||||
const executeJson = <S extends Schema.Top>(
|
||||
operation: string,
|
||||
operation: BitbucketApiOperation,
|
||||
request: HttpClientRequest.HttpClientRequest,
|
||||
schema: S,
|
||||
): Effect.Effect<S["Type"], BitbucketApiError, S["DecodingServices"]> =>
|
||||
httpClient.execute(withAuth(request.pipe(HttpClientRequest.acceptJson))).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new BitbucketApiError({
|
||||
new BitbucketRequestError({
|
||||
operation,
|
||||
detail: "Failed to send the Bitbucket request.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
@@ -433,9 +571,8 @@ export const make = Effect.gen(function* () {
|
||||
const handle = yield* vcsRegistry.resolve({ cwd: input.cwd }).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new BitbucketApiError({
|
||||
operation: "resolveRepository",
|
||||
detail: `Failed to resolve VCS repository for ${input.cwd}.`,
|
||||
new BitbucketRepositoryVcsResolveError({
|
||||
cwd: input.cwd,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
@@ -443,9 +580,8 @@ export const make = Effect.gen(function* () {
|
||||
const remotes = yield* handle.driver.listRemotes(input.cwd).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new BitbucketApiError({
|
||||
operation: "resolveRepository",
|
||||
detail: `Failed to list remotes for ${input.cwd}.`,
|
||||
new BitbucketRepositoryRemotesListError({
|
||||
cwd: input.cwd,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
@@ -457,9 +593,8 @@ export const make = Effect.gen(function* () {
|
||||
if (parsed) return parsed;
|
||||
}
|
||||
|
||||
return yield* new BitbucketApiError({
|
||||
operation: "resolveRepository",
|
||||
detail: `No Bitbucket repository remote was detected for ${input.cwd}.`,
|
||||
return yield* new BitbucketRepositoryRemoteNotFoundError({
|
||||
cwd: input.cwd,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -600,7 +735,7 @@ export const make = Effect.gen(function* () {
|
||||
getRepositoryCloneUrls: (input) =>
|
||||
getRepository(input).pipe(Effect.map(normalizeRepositoryCloneUrls)),
|
||||
createRepository: (input) =>
|
||||
requireRepositoryLocator("createRepository", input.repository).pipe(
|
||||
requireRepositoryLocator(input.repository).pipe(
|
||||
Effect.flatMap((repository) =>
|
||||
executeJson(
|
||||
"createRepository",
|
||||
@@ -625,9 +760,9 @@ export const make = Effect.gen(function* () {
|
||||
const description = yield* fileSystem.readFileString(input.bodyFile).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new BitbucketApiError({
|
||||
operation: "createPullRequest",
|
||||
detail: `Failed to read pull request body file ${input.bodyFile}.`,
|
||||
new BitbucketPullRequestBodyReadError({
|
||||
cwd: input.cwd,
|
||||
bodyFile: input.bodyFile,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
@@ -743,9 +878,9 @@ export const make = Effect.gen(function* () {
|
||||
Effect.mapError((cause) =>
|
||||
isBitbucketApiError(cause)
|
||||
? cause
|
||||
: new BitbucketApiError({
|
||||
operation: "checkoutPullRequest",
|
||||
detail: "Failed to check out the Bitbucket pull request.",
|
||||
: new BitbucketCheckoutError({
|
||||
cwd: input.cwd,
|
||||
reference: input.reference,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
|
||||
@@ -53,11 +53,10 @@ 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 cause = new BitbucketApi.BitbucketApiError({
|
||||
const upstreamCause = new Error("raw upstream failure");
|
||||
const cause = new BitbucketApi.BitbucketRequestError({
|
||||
operation: "getRepository",
|
||||
detail: "upstream detail that should remain in the cause",
|
||||
status: 503,
|
||||
cause: new Error("raw upstream failure"),
|
||||
cause: upstreamCause,
|
||||
});
|
||||
const provider = yield* makeProvider({
|
||||
getRepositoryCloneUrls: () => Effect.fail(cause),
|
||||
@@ -86,7 +85,7 @@ it.effect("adds repository context while retaining Bitbucket API causes", () =>
|
||||
},
|
||||
);
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.equal(error.message.includes(cause.detail), false);
|
||||
assert.equal(error.message.includes(upstreamCause.message), false);
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
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 } from "@t3tools/contracts";
|
||||
import { VcsProcessExitError, VcsProcessSpawnError } from "@t3tools/contracts";
|
||||
|
||||
import * as VcsProcess from "../vcs/VcsProcess.ts";
|
||||
import * as GitHubCli from "./GitHubCli.ts";
|
||||
@@ -30,6 +31,27 @@ 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(
|
||||
@@ -274,6 +296,7 @@ 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)",
|
||||
});
|
||||
@@ -288,6 +311,7 @@ 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);
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
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";
|
||||
|
||||
@@ -18,69 +19,165 @@ import {
|
||||
|
||||
const DEFAULT_TIMEOUT_MS = 30_000;
|
||||
|
||||
export class GitHubCliError extends Schema.TaggedErrorClass<GitHubCliError>()("GitHubCliError", {
|
||||
operation: Schema.String,
|
||||
command: Schema.String,
|
||||
const gitHubCliFailureFields = {
|
||||
command: Schema.Literal("gh"),
|
||||
cwd: Schema.String,
|
||||
detail: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
}) {
|
||||
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.";
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `GitHub CLI failed in ${this.operation}: ${this.detail}`;
|
||||
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.";
|
||||
}
|
||||
|
||||
static fromVcsError(
|
||||
context: {
|
||||
readonly operation: "execute";
|
||||
readonly command: "gh";
|
||||
readonly cwd: string;
|
||||
},
|
||||
error: VcsError | unknown,
|
||||
): GitHubCliError {
|
||||
const lower = errorText(error).toLowerCase();
|
||||
|
||||
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 (
|
||||
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,
|
||||
});
|
||||
override get message(): string {
|
||||
return `GitHub CLI failed in execute: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
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 (error.failureKind === "not-found") {
|
||||
return new GitHubPullRequestNotFoundError({ ...context, cause: error });
|
||||
}
|
||||
}
|
||||
|
||||
return new GitHubCliCommandError({ ...context, cause: error });
|
||||
}
|
||||
|
||||
export interface GitHubPullRequestSummary {
|
||||
readonly number: number;
|
||||
readonly title: string;
|
||||
@@ -150,22 +247,14 @@ 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>,
|
||||
@@ -214,27 +303,6 @@ 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;
|
||||
|
||||
@@ -247,14 +315,7 @@ export const make = Effect.gen(function* () {
|
||||
cwd: input.cwd,
|
||||
timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError((error) =>
|
||||
GitHubCliError.fromVcsError(
|
||||
{ operation: "execute", command: "gh", cwd: input.cwd },
|
||||
error,
|
||||
),
|
||||
),
|
||||
);
|
||||
.pipe(Effect.mapError((error) => fromVcsError({ command: "gh", cwd: input.cwd }, error)));
|
||||
|
||||
return GitHubCli.of({
|
||||
execute,
|
||||
@@ -282,11 +343,9 @@ export const make = Effect.gen(function* () {
|
||||
Effect.flatMap((decoded) => {
|
||||
if (!Result.isSuccess(decoded)) {
|
||||
return Effect.fail(
|
||||
new GitHubCliError({
|
||||
operation: "listOpenPullRequests",
|
||||
new GitHubPullRequestListDecodeError({
|
||||
command: "gh",
|
||||
cwd: input.cwd,
|
||||
detail: "GitHub CLI returned invalid PR list JSON.",
|
||||
cause: decoded.failure,
|
||||
}),
|
||||
);
|
||||
@@ -316,11 +375,9 @@ export const make = Effect.gen(function* () {
|
||||
Effect.flatMap((decoded) => {
|
||||
if (!Result.isSuccess(decoded)) {
|
||||
return Effect.fail(
|
||||
new GitHubCliError({
|
||||
operation: "getPullRequest",
|
||||
new GitHubPullRequestDecodeError({
|
||||
command: "gh",
|
||||
cwd: input.cwd,
|
||||
detail: "GitHub CLI returned invalid pull request JSON.",
|
||||
cause: decoded.failure,
|
||||
}),
|
||||
);
|
||||
@@ -340,12 +397,15 @@ export const make = Effect.gen(function* () {
|
||||
}).pipe(
|
||||
Effect.map((result) => result.stdout.trim()),
|
||||
Effect.flatMap((raw) =>
|
||||
decodeGitHubJson(
|
||||
raw,
|
||||
RawGitHubRepositoryCloneUrlsSchema,
|
||||
"getRepositoryCloneUrls",
|
||||
"GitHub CLI returned invalid repository JSON.",
|
||||
input.cwd,
|
||||
decodeRawGitHubRepositoryCloneUrls(raw).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new GitHubRepositoryDecodeError({
|
||||
command: "gh",
|
||||
cwd: input.cwd,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
Effect.map(normalizeRepositoryCloneUrls),
|
||||
|
||||
@@ -70,11 +70,9 @@ 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.GitHubCliError({
|
||||
operation: "execute",
|
||||
const cause = new GitHubCli.GitHubPullRequestNotFoundError({
|
||||
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,23 +158,17 @@ export const make = Effect.gen(function* () {
|
||||
})),
|
||||
)
|
||||
: Effect.fail(
|
||||
new SourceControlProviderError({
|
||||
provider: "github",
|
||||
operation: "listChangeRequests",
|
||||
new GitHubCli.GitHubChangeRequestListDecodeError({
|
||||
command: "gh",
|
||||
cwd: input.cwd,
|
||||
reference: SourceControlProvider.transportSafeSourceControlErrorValue(
|
||||
input.headSelector,
|
||||
),
|
||||
detail: "GitHub CLI returned invalid change request JSON.",
|
||||
cause: decoded.failure,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
}),
|
||||
Effect.catchTags({
|
||||
GitHubCliError: (error) =>
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new SourceControlProviderError({
|
||||
provider: "github",
|
||||
operation: "listChangeRequests",
|
||||
@@ -186,7 +180,7 @@ export const make = Effect.gen(function* () {
|
||||
detail: error.detail,
|
||||
cause: error,
|
||||
}),
|
||||
}),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
@@ -315,10 +315,11 @@ layer("GitLabCli.layer", (it) => {
|
||||
Effect.gen(function* () {
|
||||
const cause = new VcsProcessExitError({
|
||||
operation: "GitLabCli.execute",
|
||||
command: "glab mr view 4888",
|
||||
command: "glab",
|
||||
cwd: "/repo",
|
||||
exitCode: 1,
|
||||
detail: "GET 404 merge request not found",
|
||||
failureKind: "not-found",
|
||||
});
|
||||
mockedRun.mockReturnValueOnce(Effect.fail(cause));
|
||||
|
||||
@@ -330,11 +331,37 @@ layer("GitLabCli.layer", (it) => {
|
||||
});
|
||||
}).pipe(Effect.flip);
|
||||
|
||||
assert.equal(error.message.includes("Merge request not found"), true);
|
||||
assert.equal(error.message.includes("Merge request 4888 was not found"), true);
|
||||
assert.strictEqual(error._tag, "GitLabMergeRequestNotFoundError");
|
||||
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);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,6 +1,7 @@
|
||||
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";
|
||||
@@ -21,13 +22,92 @@ import type * as SourceControlProvider from "./SourceControlProvider.ts";
|
||||
|
||||
const DEFAULT_TIMEOUT_MS = 30_000;
|
||||
|
||||
export class GitLabCliError extends Schema.TaggedErrorClass<GitLabCliError>()("GitLabCliError", {
|
||||
operation: Schema.String,
|
||||
command: Schema.String,
|
||||
const gitLabCliExecutionErrorContext = {
|
||||
operation: Schema.Literal("execute"),
|
||||
command: Schema.Literal("glab"),
|
||||
cwd: Schema.String,
|
||||
detail: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
}) {
|
||||
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.`;
|
||||
}
|
||||
|
||||
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;
|
||||
readonly reference: string;
|
||||
},
|
||||
error: VcsError,
|
||||
): GitLabCliError {
|
||||
if (error._tag === "VcsProcessExitError" && error.failureKind === "not-found") {
|
||||
return new GitLabMergeRequestNotFoundError({ ...context, cause: error });
|
||||
}
|
||||
|
||||
return GitLabCliCommandError.fromVcsError(
|
||||
{
|
||||
operation: context.operation,
|
||||
command: context.command,
|
||||
cwd: context.cwd,
|
||||
},
|
||||
error,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export class GitLabCliCommandError extends Schema.TaggedErrorClass<GitLabCliCommandError>()(
|
||||
"GitLabCliCommandError",
|
||||
gitLabCliExecutionErrorContext,
|
||||
) {
|
||||
get detail(): string {
|
||||
return "GitLab CLI command failed.";
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
@@ -38,51 +118,111 @@ export class GitLabCliError extends Schema.TaggedErrorClass<GitLabCliError>()("G
|
||||
readonly command: "glab";
|
||||
readonly cwd: string;
|
||||
},
|
||||
error: VcsError | unknown,
|
||||
error: VcsError,
|
||||
): GitLabCliError {
|
||||
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,
|
||||
});
|
||||
}
|
||||
|
||||
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,
|
||||
});
|
||||
}
|
||||
|
||||
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,
|
||||
});
|
||||
}
|
||||
|
||||
return new GitLabCliError({
|
||||
...context,
|
||||
detail: "GitLab CLI command failed.",
|
||||
cause: error,
|
||||
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 }),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
@@ -102,17 +242,6 @@ 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,
|
||||
{
|
||||
@@ -168,15 +297,6 @@ 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,
|
||||
@@ -192,6 +312,14 @@ 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 {
|
||||
@@ -202,27 +330,6 @@ 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":
|
||||
@@ -283,7 +390,10 @@ function parseRepositoryPath(repository: string): {
|
||||
export const make = Effect.gen(function* () {
|
||||
const process = yield* VcsProcess.VcsProcess;
|
||||
|
||||
const execute: GitLabCli["Service"]["execute"] = (input) =>
|
||||
const run = (
|
||||
input: Parameters<GitLabCli["Service"]["execute"]>[0],
|
||||
mapError: (error: VcsError) => GitLabCliError,
|
||||
) =>
|
||||
process
|
||||
.run({
|
||||
operation: "GitLabCli.execute",
|
||||
@@ -292,14 +402,32 @@ export const make = Effect.gen(function* () {
|
||||
cwd: input.cwd,
|
||||
timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError((error) =>
|
||||
GitLabCliError.fromVcsError(
|
||||
{ operation: "execute", command: "glab", cwd: input.cwd },
|
||||
error,
|
||||
),
|
||||
),
|
||||
);
|
||||
.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,
|
||||
),
|
||||
);
|
||||
|
||||
return GitLabCli.of({
|
||||
execute,
|
||||
@@ -326,11 +454,10 @@ export const make = Effect.gen(function* () {
|
||||
Effect.flatMap((decoded) => {
|
||||
if (!Result.isSuccess(decoded)) {
|
||||
return Effect.fail(
|
||||
new GitLabCliError({
|
||||
new GitLabMergeRequestListDecodeError({
|
||||
operation: "listMergeRequests",
|
||||
command: "glab",
|
||||
cwd: input.cwd,
|
||||
detail: "GitLab CLI returned invalid MR list JSON.",
|
||||
cause: decoded.failure,
|
||||
}),
|
||||
);
|
||||
@@ -342,8 +469,9 @@ export const make = Effect.gen(function* () {
|
||||
),
|
||||
),
|
||||
getMergeRequest: (input) =>
|
||||
execute({
|
||||
executeMergeRequest({
|
||||
cwd: input.cwd,
|
||||
reference: input.reference,
|
||||
args: ["mr", "view", input.reference, "--output", "json"],
|
||||
}).pipe(
|
||||
Effect.map((result) => result.stdout.trim()),
|
||||
@@ -352,11 +480,11 @@ export const make = Effect.gen(function* () {
|
||||
Effect.flatMap((decoded) => {
|
||||
if (!Result.isSuccess(decoded)) {
|
||||
return Effect.fail(
|
||||
new GitLabCliError({
|
||||
new GitLabMergeRequestDecodeError({
|
||||
operation: "getMergeRequest",
|
||||
command: "glab",
|
||||
cwd: input.cwd,
|
||||
detail: "GitLab CLI returned invalid merge request JSON.",
|
||||
reference: input.reference,
|
||||
cause: decoded.failure,
|
||||
}),
|
||||
);
|
||||
@@ -374,12 +502,17 @@ export const make = Effect.gen(function* () {
|
||||
}).pipe(
|
||||
Effect.map((result) => result.stdout.trim()),
|
||||
Effect.flatMap((raw) =>
|
||||
decodeGitLabJson(
|
||||
raw,
|
||||
RawGitLabRepositoryCloneUrlsSchema,
|
||||
"getRepositoryCloneUrls",
|
||||
"GitLab CLI returned invalid repository JSON.",
|
||||
input.cwd,
|
||||
decodeGitLabRepositoryCloneUrls(raw).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new GitLabRepositoryDecodeError({
|
||||
operation: "getRepositoryCloneUrls",
|
||||
command: "glab",
|
||||
cwd: input.cwd,
|
||||
repository: input.repository,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
Effect.map(normalizeRepositoryCloneUrls),
|
||||
@@ -393,12 +526,17 @@ export const make = Effect.gen(function* () {
|
||||
}).pipe(
|
||||
Effect.map((result) => result.stdout.trim()),
|
||||
Effect.flatMap((raw) =>
|
||||
decodeGitLabJson(
|
||||
raw,
|
||||
RawGitLabNamespaceSchema,
|
||||
"createRepository",
|
||||
"GitLab CLI returned invalid namespace JSON.",
|
||||
input.cwd,
|
||||
decodeGitLabNamespace(raw).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new GitLabNamespaceDecodeError({
|
||||
operation: "createRepository",
|
||||
command: "glab",
|
||||
cwd: input.cwd,
|
||||
namespacePath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
Effect.map((namespace) => namespace.id),
|
||||
@@ -428,12 +566,17 @@ export const make = Effect.gen(function* () {
|
||||
),
|
||||
Effect.map((result) => result.stdout.trim()),
|
||||
Effect.flatMap((raw) =>
|
||||
decodeGitLabJson(
|
||||
raw,
|
||||
RawGitLabRepositoryCloneUrlsSchema,
|
||||
"createRepository",
|
||||
"GitLab CLI returned invalid repository JSON.",
|
||||
input.cwd,
|
||||
decodeGitLabRepositoryCloneUrls(raw).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new GitLabRepositoryDecodeError({
|
||||
operation: "createRepository",
|
||||
command: "glab",
|
||||
cwd: input.cwd,
|
||||
repository: input.repository,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
Effect.map(normalizeRepositoryCloneUrls),
|
||||
@@ -467,19 +610,24 @@ export const make = Effect.gen(function* () {
|
||||
}).pipe(
|
||||
Effect.map((result) => result.stdout.trim()),
|
||||
Effect.flatMap((raw) =>
|
||||
decodeGitLabJson(
|
||||
raw,
|
||||
RawGitLabDefaultBranchSchema,
|
||||
"getDefaultBranch",
|
||||
"GitLab CLI returned invalid repository JSON.",
|
||||
input.cwd,
|
||||
decodeGitLabDefaultBranch(raw).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new GitLabRepositoryDecodeError({
|
||||
operation: "getDefaultBranch",
|
||||
command: "glab",
|
||||
cwd: input.cwd,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
Effect.map((value) => value.default_branch ?? null),
|
||||
),
|
||||
checkoutMergeRequest: (input) =>
|
||||
execute({
|
||||
executeMergeRequest({
|
||||
cwd: input.cwd,
|
||||
reference: input.reference,
|
||||
args: ["mr", "checkout", input.reference],
|
||||
}).pipe(Effect.asVoid),
|
||||
});
|
||||
|
||||
@@ -54,11 +54,10 @@ 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.GitLabCliError({
|
||||
const cause = new GitLabCli.GitLabCliCommandError({
|
||||
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 } from "@t3tools/contracts";
|
||||
import { OpenCodeSettings, ProviderInstanceId, TextGenerationError } 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,8 +20,11 @@ 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<{ type: string; text?: string }> } }
|
||||
| { data?: { info?: { error?: unknown }; parts?: Array<unknown> } }
|
||||
| undefined,
|
||||
},
|
||||
reset() {
|
||||
@@ -29,6 +32,9 @@ 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;
|
||||
},
|
||||
};
|
||||
@@ -61,12 +67,20 @@ const OpenCodeRuntimeTestDouble: OpenCodeRuntime.OpenCodeRuntimeShape = {
|
||||
createOpenCodeSdkClient: ({ baseUrl, serverPassword }) =>
|
||||
({
|
||||
session: {
|
||||
create: async () => ({ data: { id: `${baseUrl}/session` } }),
|
||||
create: async () => {
|
||||
if (runtimeMock.state.sessionCreateError !== undefined) {
|
||||
throw runtimeMock.state.sessionCreateError;
|
||||
}
|
||||
return runtimeMock.state.sessionResult ?? { 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: {
|
||||
@@ -99,6 +113,13 @@ 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;
|
||||
|
||||
@@ -142,7 +163,7 @@ function withOpenCodeTextGeneration<A, E, R>(
|
||||
effectFn: (textGeneration: TextGeneration.TextGeneration["Service"]) => Effect.Effect<A, E, R>,
|
||||
) {
|
||||
return Effect.gen(function* () {
|
||||
const textGeneration = yield* makeOpenCodeTextGeneration(settings);
|
||||
const textGeneration = yield* OpenCodeTextGeneration.makeOpenCodeTextGeneration(settings);
|
||||
return yield* effectFn(textGeneration);
|
||||
}).pipe(Effect.scoped);
|
||||
}
|
||||
@@ -221,22 +242,99 @@ it.layer(OpenCodeTextGenerationTestLayer)("OpenCodeTextGeneration", (it) => {
|
||||
).pipe(Effect.provide(TestClock.layer())),
|
||||
);
|
||||
|
||||
it.effect("returns a typed empty-output error when OpenCode returns no text parts", () =>
|
||||
it.effect("preserves the SDK cause when session creation fails", () =>
|
||||
withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) =>
|
||||
Effect.gen(function* () {
|
||||
runtimeMock.state.promptResult = { data: {} };
|
||||
const sdkCause = new Error("session endpoint unavailable");
|
||||
runtimeMock.state.sessionCreateError = sdkCause;
|
||||
|
||||
const error = yield* textGeneration
|
||||
.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,
|
||||
})
|
||||
.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)
|
||||
.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");
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -289,16 +387,21 @@ it.layer(OpenCodeTextGenerationTestLayer)("OpenCodeTextGeneration", (it) => {
|
||||
};
|
||||
|
||||
const error = yield* textGeneration
|
||||
.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,
|
||||
})
|
||||
.generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT)
|
||||
.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,6 +6,7 @@ import * as Scope from "effect/Scope";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
|
||||
import {
|
||||
NonNegativeInt,
|
||||
TextGenerationError,
|
||||
type ChatAttachment,
|
||||
type ModelSelection,
|
||||
@@ -33,11 +34,106 @@ import * as OpenCodeRuntime from "../provider/opencodeRuntime.ts";
|
||||
|
||||
const OPENCODE_TEXT_GENERATION_IDLE_TTL = "30 seconds";
|
||||
|
||||
function getOpenCodePromptErrorMessage(error: unknown): string | null {
|
||||
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 {
|
||||
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 &&
|
||||
@@ -47,31 +143,34 @@ function getOpenCodePromptErrorMessage(error: unknown): string | null {
|
||||
? error.data.message.trim()
|
||||
: "";
|
||||
if (message.length > 0) {
|
||||
return message;
|
||||
return {
|
||||
...(name ? { name } : {}),
|
||||
message,
|
||||
};
|
||||
}
|
||||
|
||||
if ("name" in error && typeof error.name === "string") {
|
||||
const name = error.name.trim();
|
||||
return name.length > 0 ? name : null;
|
||||
if (name) {
|
||||
return { name, message: name };
|
||||
}
|
||||
|
||||
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 ?? [])
|
||||
.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];
|
||||
})
|
||||
.filter(isOpenCodeTextPart)
|
||||
.map((part) => part.text)
|
||||
.join("")
|
||||
.trim();
|
||||
}
|
||||
@@ -260,11 +359,7 @@ export const makeOpenCodeTextGeneration = Effect.fn("makeOpenCodeTextGeneration"
|
||||
);
|
||||
|
||||
const runOpenCodeJson = Effect.fn("runOpenCodeJson")(function* <S extends Schema.Top>(input: {
|
||||
readonly operation:
|
||||
| "generateCommitMessage"
|
||||
| "generatePrContent"
|
||||
| "generateBranchName"
|
||||
| "generateThreadTitle";
|
||||
readonly operation: OpenCodeTextGenerationOperation;
|
||||
readonly cwd: string;
|
||||
readonly prompt: string;
|
||||
readonly outputSchemaJson: S;
|
||||
@@ -285,54 +380,121 @@ export const makeOpenCodeTextGeneration = Effect.fn("makeOpenCodeTextGeneration"
|
||||
resolveAttachmentPath({ attachmentsDir: serverConfig.attachmentsDir, attachment }),
|
||||
});
|
||||
|
||||
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 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 = await client.session.prompt({
|
||||
sessionID: session.data.id,
|
||||
model: parsedModel,
|
||||
...(selectedAgent ? { agent: selectedAgent } : {}),
|
||||
...(selectedVariant ? { variant: selectedVariant } : {}),
|
||||
parts: [{ type: "text", text: input.prompt }, ...fileParts],
|
||||
});
|
||||
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({
|
||||
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,
|
||||
detail: OpenCodeRuntime.openCodeRuntimeErrorDetail(cause),
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
cwd: input.cwd,
|
||||
});
|
||||
}
|
||||
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 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 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 rawOutput =
|
||||
openCodeSettings.serverUrl.length > 0
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
VcsProcessSpawnError,
|
||||
VcsProcessTimeoutError,
|
||||
} from "@t3tools/contracts";
|
||||
import * as ProcessRunner from "../processRunner.ts";
|
||||
import * as VcsProcess from "./VcsProcess.ts";
|
||||
|
||||
const run = (input: VcsProcess.VcsProcessInput) =>
|
||||
@@ -24,6 +25,25 @@ 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* () {
|
||||
@@ -141,6 +161,51 @@ 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,11 +5,14 @@ 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";
|
||||
@@ -114,19 +117,32 @@ export const make = Effect.gen(function* () {
|
||||
ProcessSpawnError: (error) =>
|
||||
VcsProcessSpawnError.fromProcessSpawnError(baseError, error),
|
||||
ProcessOutputLimitError: (error) =>
|
||||
VcsOutputDecodeError.fromProcessOutputLimitError(baseError, error),
|
||||
new VcsProcessOutputLimitError({
|
||||
...baseError,
|
||||
stream: error.stream,
|
||||
maxBytes: error.maxBytes,
|
||||
observedBytes: error.observedBytes,
|
||||
}),
|
||||
ProcessTimeoutError: (error) =>
|
||||
VcsProcessTimeoutError.fromProcessTimeoutError(baseError, error),
|
||||
ProcessStdinError: (error) =>
|
||||
VcsOutputDecodeError.fromProcessStdinError(baseError, error),
|
||||
new VcsProcessStdinWriteError({
|
||||
...baseError,
|
||||
stdinBytes: error.stdinBytes,
|
||||
cause: error.cause,
|
||||
}),
|
||||
ProcessReadError: (error) =>
|
||||
VcsOutputDecodeError.fromProcessReadError(baseError, error),
|
||||
new VcsProcessOutputReadError({
|
||||
...baseError,
|
||||
stream: error.stream,
|
||||
cause: error.cause,
|
||||
}),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
if (result.code === null) {
|
||||
return yield* VcsOutputDecodeError.missingExitCode(baseError);
|
||||
return yield* new VcsProcessMissingExitCodeError(baseError);
|
||||
}
|
||||
|
||||
if (!input.allowNonZeroExit && result.code !== 0) {
|
||||
|
||||
@@ -96,16 +96,19 @@ 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");
|
||||
assert.equal(message, "Failed to inspect VCS project config at " + failedCandidate + ".");
|
||||
assert.deepInclude(context, {
|
||||
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, {
|
||||
operation: "inspect",
|
||||
cwd,
|
||||
configPath: failedCandidate,
|
||||
errorTag: "VcsProjectConfigError",
|
||||
_tag: "VcsProjectConfigError",
|
||||
});
|
||||
assert.equal("cause" in context, false);
|
||||
}).pipe(Effect.provide(Logger.layer([logger], { mergeWithExisting: false })));
|
||||
});
|
||||
});
|
||||
@@ -146,18 +149,19 @@ describe("VcsProjectConfig", () => {
|
||||
const kind = yield* config.resolveKind({ cwd: root });
|
||||
|
||||
assert.equal(kind, "auto");
|
||||
const [message, context] = messages[0] as [string, Record<string, unknown>];
|
||||
const [error] = messages[0] as ReadonlyArray<unknown>;
|
||||
assert.instanceOf(error, VcsProjectConfig.VcsProjectConfigError);
|
||||
assert.equal(
|
||||
message,
|
||||
error.message,
|
||||
"Failed to decode VCS project config at " + path.join(configDir, "vcs.json") + ".",
|
||||
);
|
||||
assert.deepInclude(context, {
|
||||
assert.deepInclude(error.cause, { _tag: "SchemaError" });
|
||||
assert.deepInclude(error, {
|
||||
operation: "decode",
|
||||
cwd: root,
|
||||
configPath: path.join(configDir, "vcs.json"),
|
||||
errorTag: "VcsProjectConfigError",
|
||||
_tag: "VcsProjectConfigError",
|
||||
});
|
||||
assert.equal("cause" in context, false);
|
||||
}).pipe(Effect.provide(Logger.layer([logger], { mergeWithExisting: false })));
|
||||
});
|
||||
});
|
||||
@@ -182,15 +186,16 @@ describe("VcsProjectConfig", () => {
|
||||
const kind = yield* config.resolveKind({ cwd: root });
|
||||
|
||||
assert.equal(kind, "auto");
|
||||
const [message, context] = messages[0] as [string, Record<string, unknown>];
|
||||
assert.equal(message, "Failed to read VCS project config at " + configPath + ".");
|
||||
assert.deepInclude(context, {
|
||||
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, {
|
||||
operation: "read",
|
||||
cwd: root,
|
||||
configPath,
|
||||
errorTag: "VcsProjectConfigError",
|
||||
_tag: "VcsProjectConfigError",
|
||||
});
|
||||
assert.equal("cause" in context, false);
|
||||
}).pipe(Effect.provide(Logger.layer([logger], { mergeWithExisting: false })));
|
||||
});
|
||||
});
|
||||
|
||||
@@ -55,13 +55,14 @@ function configuredKind(config: ProjectVcsConfigFile): VcsDriverKindType | "auto
|
||||
}
|
||||
|
||||
const logVcsProjectConfigError = (error: VcsProjectConfigError) =>
|
||||
Effect.logWarning(error.message, {
|
||||
operation: error.operation,
|
||||
cwd: error.cwd,
|
||||
configPath: error.configPath,
|
||||
errorTag: error._tag,
|
||||
stack: error.stack,
|
||||
});
|
||||
Effect.logWarning(error).pipe(
|
||||
Effect.annotateLogs({
|
||||
operation: error.operation,
|
||||
cwd: error.cwd,
|
||||
configPath: error.configPath,
|
||||
errorTag: error._tag,
|
||||
}),
|
||||
);
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
|
||||
@@ -151,20 +151,29 @@ 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.catch((cause) =>
|
||||
Effect.gen(function* () {
|
||||
yield* Effect.logWarning("Failed to refresh workspace search index", {
|
||||
cwd,
|
||||
cause,
|
||||
});
|
||||
yield* workspaceSearchIndexes.invalidate(normalizedCwd);
|
||||
}),
|
||||
),
|
||||
Effect.catchTags({
|
||||
WorkspaceSearchIndexCreateFailed: recoverRefreshFailure,
|
||||
WorkspaceSearchIndexScanTimedOut: recoverRefreshFailure,
|
||||
WorkspaceSearchIndexRefreshFailed: recoverRefreshFailure,
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
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";
|
||||
@@ -49,6 +51,35 @@ 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* () {
|
||||
|
||||
@@ -71,6 +71,18 @@ export class WorkspaceSearchIndexRefreshFailed extends Schema.TaggedErrorClass<W
|
||||
}
|
||||
}
|
||||
|
||||
export class WorkspaceSearchIndexDestroyFailed extends Schema.TaggedErrorClass<WorkspaceSearchIndexDestroyFailed>()(
|
||||
"WorkspaceSearchIndexDestroyFailed",
|
||||
{
|
||||
cwd: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to destroy the workspace search index for '${this.cwd}'.`;
|
||||
}
|
||||
}
|
||||
|
||||
export type WorkspaceSearchIndexError =
|
||||
| WorkspaceSearchIndexCreateFailed
|
||||
| WorkspaceSearchIndexScanTimedOut
|
||||
@@ -201,7 +213,10 @@ const waitForScan = <E>(cwd: string, finder: FileFinder, onFailure: (cause: unkn
|
||||
|
||||
export const make = Effect.fn("WorkspaceSearchIndex.make")(function* (cwd: string) {
|
||||
const finder = yield* Effect.acquireRelease(createFinder(cwd), (finder) =>
|
||||
Effect.sync(() => finder.destroy()),
|
||||
Effect.try({
|
||||
try: () => finder.destroy(),
|
||||
catch: (cause) => new WorkspaceSearchIndexDestroyFailed({ cwd, cause }),
|
||||
}).pipe(Effect.orDie),
|
||||
);
|
||||
yield* waitForScan(
|
||||
cwd,
|
||||
|
||||
+19
-19
@@ -330,14 +330,14 @@ const RPC_REQUIRED_SCOPE = new Map<string, AuthEnvironmentScope>([
|
||||
[WS_METHODS.subscribeTerminalMetadata, AuthTerminalOperateScope],
|
||||
[WS_METHODS.previewOpen, AuthOrchestrationOperateScope],
|
||||
[WS_METHODS.previewNavigate, AuthOrchestrationOperateScope],
|
||||
[WS_METHODS.previewResize, AuthOrchestrationOperateScope],
|
||||
[WS_METHODS.previewRefresh, AuthOrchestrationOperateScope],
|
||||
[WS_METHODS.previewClose, AuthOrchestrationOperateScope],
|
||||
[WS_METHODS.previewList, AuthOrchestrationReadScope],
|
||||
[WS_METHODS.previewReportStatus, AuthOrchestrationOperateScope],
|
||||
[WS_METHODS.previewAutomationConnect, AuthOrchestrationOperateScope],
|
||||
[WS_METHODS.previewAutomationRespond, AuthOrchestrationOperateScope],
|
||||
[WS_METHODS.previewAutomationReportOwner, AuthOrchestrationOperateScope],
|
||||
[WS_METHODS.previewAutomationClearOwner, AuthOrchestrationOperateScope],
|
||||
[WS_METHODS.previewAutomationFocusHost, AuthOrchestrationOperateScope],
|
||||
[WS_METHODS.subscribePreviewEvents, AuthOrchestrationReadScope],
|
||||
[WS_METHODS.subscribeDiscoveredLocalServers, AuthOrchestrationReadScope],
|
||||
[WS_METHODS.subscribeServerConfig, AuthOrchestrationReadScope],
|
||||
@@ -385,7 +385,10 @@ function toAuthAccessStreamEvent(
|
||||
}
|
||||
}
|
||||
|
||||
const makeWsRpcLayer = (currentSession: EnvironmentAuth.AuthenticatedSession) =>
|
||||
const makeWsRpcLayer = (
|
||||
currentSession: EnvironmentAuth.AuthenticatedSession,
|
||||
previewAutomationBroker: PreviewAutomationBroker.PreviewAutomationBroker["Service"],
|
||||
) =>
|
||||
WsRpcGroup.toLayer(
|
||||
Effect.gen(function* () {
|
||||
const currentSessionId = currentSession.sessionId;
|
||||
@@ -400,7 +403,6 @@ const makeWsRpcLayer = (currentSession: EnvironmentAuth.AuthenticatedSession) =>
|
||||
const vcsProvisioning = yield* VcsProvisioningService.VcsProvisioningService;
|
||||
const vcsStatusBroadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
|
||||
const terminalManager = yield* TerminalManager.TerminalManager;
|
||||
const previewAutomationBroker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
|
||||
const previewManager = yield* PreviewManager.PreviewManager;
|
||||
const portDiscovery = yield* PortScanner.PortDiscovery;
|
||||
const providerRegistry = yield* ProviderRegistry.ProviderRegistry;
|
||||
@@ -1622,6 +1624,10 @@ const makeWsRpcLayer = (currentSession: EnvironmentAuth.AuthenticatedSession) =>
|
||||
observeRpcEffect(WS_METHODS.previewNavigate, previewManager.navigate(input), {
|
||||
"rpc.aggregate": "preview",
|
||||
}),
|
||||
[WS_METHODS.previewResize]: (input) =>
|
||||
observeRpcEffect(WS_METHODS.previewResize, previewManager.resize(input), {
|
||||
"rpc.aggregate": "preview",
|
||||
}),
|
||||
[WS_METHODS.previewRefresh]: (input) =>
|
||||
observeRpcEffect(WS_METHODS.previewRefresh, previewManager.refresh(input), {
|
||||
"rpc.aggregate": "preview",
|
||||
@@ -1650,16 +1656,10 @@ const makeWsRpcLayer = (currentSession: EnvironmentAuth.AuthenticatedSession) =>
|
||||
previewAutomationBroker.respond(input),
|
||||
{ "rpc.aggregate": "preview-automation" },
|
||||
),
|
||||
[WS_METHODS.previewAutomationReportOwner]: (input) =>
|
||||
[WS_METHODS.previewAutomationFocusHost]: (input) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.previewAutomationReportOwner,
|
||||
previewAutomationBroker.reportOwner(input),
|
||||
{ "rpc.aggregate": "preview-automation" },
|
||||
),
|
||||
[WS_METHODS.previewAutomationClearOwner]: (input) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.previewAutomationClearOwner,
|
||||
previewAutomationBroker.clearOwner(input),
|
||||
WS_METHODS.previewAutomationFocusHost,
|
||||
previewAutomationBroker.focusHost(input),
|
||||
{ "rpc.aggregate": "preview-automation" },
|
||||
),
|
||||
[WS_METHODS.subscribePreviewEvents]: (_input) =>
|
||||
@@ -1791,8 +1791,9 @@ const makeWsRpcLayer = (currentSession: EnvironmentAuth.AuthenticatedSession) =>
|
||||
);
|
||||
|
||||
export const websocketRpcRouteLayer = Layer.unwrap(
|
||||
Effect.succeed(
|
||||
HttpRouter.add(
|
||||
Effect.gen(function* () {
|
||||
const previewAutomationBroker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
|
||||
return HttpRouter.add(
|
||||
"GET",
|
||||
"/ws",
|
||||
Effect.gen(function* () {
|
||||
@@ -1811,9 +1812,8 @@ export const websocketRpcRouteLayer = Layer.unwrap(
|
||||
disableTracing: true,
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeWsRpcLayer(session).pipe(
|
||||
makeWsRpcLayer(session, previewAutomationBroker).pipe(
|
||||
Layer.provideMerge(RpcSerialization.layerJson),
|
||||
Layer.provide(PreviewAutomationBroker.layer),
|
||||
Layer.provide(ProviderMaintenanceRunner.layer),
|
||||
Layer.provide(
|
||||
SourceControlDiscovery.layer.pipe(
|
||||
@@ -1850,6 +1850,6 @@ export const websocketRpcRouteLayer = Layer.unwrap(
|
||||
EnvironmentInternalError: HttpServerRespondable.toResponse,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}),
|
||||
);
|
||||
@@ -22,7 +22,7 @@
|
||||
"@fontsource-variable/dm-sans": "^5.2.8",
|
||||
"@fontsource/jetbrains-mono": "^5.2.8",
|
||||
"@formkit/auto-animate": "^0.9.0",
|
||||
"@legendapp/list": "3.0.0-beta.44",
|
||||
"@legendapp/list": "3.2.0",
|
||||
"@lexical/react": "^0.41.0",
|
||||
"@pierre/diffs": "catalog:",
|
||||
"@pierre/trees": "1.0.0-beta.4",
|
||||
|
||||
@@ -3,20 +3,22 @@ import { RouterProvider } from "@tanstack/react-router";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { ElectronBrowserHost } from "./browser/ElectronBrowserHost";
|
||||
import { PreviewAutomationHosts } from "./components/preview/PreviewAutomationHosts";
|
||||
import { AppAtomRegistryProvider } from "./rpc/atomRegistry";
|
||||
import type { AppRouter } from "./router";
|
||||
import { AppRoot } from "./AppRoot";
|
||||
|
||||
describe("AppRoot", () => {
|
||||
it("shares the application atom registry with routed UI and the Electron browser host", () => {
|
||||
it("shares the application atom registry with routed UI and renderer-wide desktop hosts", () => {
|
||||
const root = AppRoot({ router: {} as AppRouter });
|
||||
|
||||
expect(root.type).toBe(AppAtomRegistryProvider);
|
||||
const children = Children.toArray(
|
||||
(root as ReactElement<{ readonly children: ReactNode }>).props.children,
|
||||
);
|
||||
expect(children).toHaveLength(2);
|
||||
expect(children).toHaveLength(3);
|
||||
expect(isValidElement(children[0]) && children[0].type).toBe(RouterProvider);
|
||||
expect(isValidElement(children[1]) && children[1].type).toBe(ElectronBrowserHost);
|
||||
expect(isValidElement(children[1]) && children[1].type).toBe(PreviewAutomationHosts);
|
||||
expect(isValidElement(children[2]) && children[2].type).toBe(ElectronBrowserHost);
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,7 @@
|
||||
import { RouterProvider } from "@tanstack/react-router";
|
||||
|
||||
import { ElectronBrowserHost } from "./browser/ElectronBrowserHost";
|
||||
import { PreviewAutomationHosts } from "./components/preview/PreviewAutomationHosts";
|
||||
import { AppAtomRegistryProvider } from "./rpc/atomRegistry";
|
||||
import type { AppRouter } from "./router";
|
||||
|
||||
@@ -13,6 +14,7 @@ export function AppRoot({ router }: { readonly router: AppRouter }) {
|
||||
return (
|
||||
<AppAtomRegistryProvider>
|
||||
<RouterProvider router={router} />
|
||||
<PreviewAutomationHosts />
|
||||
<ElectronBrowserHost />
|
||||
</AppAtomRegistryProvider>
|
||||
);
|
||||
|
||||
@@ -71,6 +71,18 @@ function installTestBrowser(url: string) {
|
||||
return testWindow;
|
||||
}
|
||||
|
||||
function installDesktopBootstrap() {
|
||||
const testWindow = installTestBrowser("http://localhost/");
|
||||
testWindow.desktopBridge = {
|
||||
getLocalEnvironmentBootstrap: () => ({
|
||||
label: "Local environment",
|
||||
httpBaseUrl: "http://localhost:3773",
|
||||
wsBaseUrl: "ws://localhost:3773",
|
||||
bootstrapToken: "desktop-bootstrap-token",
|
||||
}),
|
||||
} as DesktopBridge;
|
||||
}
|
||||
|
||||
function sequence<A>(...values: ReadonlyArray<A>) {
|
||||
let index = 0;
|
||||
return () => values[Math.min(index++, values.length - 1)]!;
|
||||
@@ -131,15 +143,7 @@ describe("resolveInitialServerAuthGateState", () => {
|
||||
browserSession: () => Effect.succeed(browserSession(["orchestration:read", "access:write"])),
|
||||
});
|
||||
|
||||
const testWindow = installTestBrowser("http://localhost/");
|
||||
testWindow.desktopBridge = {
|
||||
getLocalEnvironmentBootstrap: () => ({
|
||||
label: "Local environment",
|
||||
httpBaseUrl: "http://localhost:3773",
|
||||
wsBaseUrl: "ws://localhost:3773",
|
||||
bootstrapToken: "desktop-bootstrap-token",
|
||||
}),
|
||||
} as DesktopBridge;
|
||||
installDesktopBootstrap();
|
||||
|
||||
const { resolveInitialServerAuthGateState } = await import("./environments/primary");
|
||||
|
||||
@@ -289,6 +293,23 @@ describe("resolveInitialServerAuthGateState", () => {
|
||||
expect(testApi.calls.session).toBe(2);
|
||||
});
|
||||
|
||||
it("rejects a blank pairing token with a structured validation error", async () => {
|
||||
const { PrimaryEnvironmentPairingCredentialRequiredError, submitServerAuthCredential } =
|
||||
await import("./environments/primary/auth");
|
||||
|
||||
const error = await submitServerAuthCredential(" ").then(
|
||||
() => null,
|
||||
(failure: unknown) => failure,
|
||||
);
|
||||
|
||||
expect(error).toBeInstanceOf(PrimaryEnvironmentPairingCredentialRequiredError);
|
||||
expect(error).toMatchObject({
|
||||
_tag: "PrimaryEnvironmentPairingCredentialRequiredError",
|
||||
providedLength: 3,
|
||||
message: "Enter a pairing token to continue.",
|
||||
});
|
||||
});
|
||||
|
||||
it("surfaces a friendly error message when an invalid pairing token is submitted", async () => {
|
||||
const cause = new EnvironmentAuthInvalidError({
|
||||
code: "auth_invalid",
|
||||
@@ -299,7 +320,7 @@ describe("resolveInitialServerAuthGateState", () => {
|
||||
browserSession: () => Effect.fail(cause),
|
||||
});
|
||||
|
||||
const { isPrimaryEnvironmentRequestError, submitServerAuthCredential } =
|
||||
const { isPrimaryEnvironmentPairingCredentialRejectedError, submitServerAuthCredential } =
|
||||
await import("./environments/primary");
|
||||
|
||||
const error = await submitServerAuthCredential("bad-token").then(
|
||||
@@ -307,14 +328,13 @@ describe("resolveInitialServerAuthGateState", () => {
|
||||
(failure: unknown) => failure,
|
||||
);
|
||||
expect(error).toMatchObject({
|
||||
_tag: "PrimaryEnvironmentRequestError",
|
||||
operation: "exchange-bootstrap-credential",
|
||||
status: 401,
|
||||
detail: "Invalid pairing token. Check the token and try again.",
|
||||
_tag: "PrimaryEnvironmentPairingCredentialRejectedError",
|
||||
providedLength: 9,
|
||||
message: "Invalid pairing token. Check the token and try again.",
|
||||
});
|
||||
expect(isPrimaryEnvironmentRequestError(error)).toBe(true);
|
||||
if (!isPrimaryEnvironmentRequestError(error)) {
|
||||
throw new Error("Expected a structured primary environment request error.");
|
||||
expect(isPrimaryEnvironmentPairingCredentialRejectedError(error)).toBe(true);
|
||||
if (!isPrimaryEnvironmentPairingCredentialRejectedError(error)) {
|
||||
throw new Error("Expected a structured rejected pairing credential error.");
|
||||
}
|
||||
expect(error.cause).toMatchObject({
|
||||
_tag: "EnvironmentAuthInvalidError",
|
||||
@@ -325,6 +345,22 @@ describe("resolveInitialServerAuthGateState", () => {
|
||||
expect(testApi.calls.browserSession).toEqual([{ credential: "bad-token" }]);
|
||||
});
|
||||
|
||||
it("derives primary request messages from structural request context", async () => {
|
||||
const cause = new Error("private transport detail");
|
||||
const { PrimaryEnvironmentRequestError } = await import("./environments/primary");
|
||||
const error = PrimaryEnvironmentRequestError.fromCause({
|
||||
operation: "list-pairing-links",
|
||||
cause,
|
||||
});
|
||||
|
||||
expect(error.status).toBe(500);
|
||||
expect(error.cause).toBe(cause);
|
||||
expect(error.message).toBe(
|
||||
"Primary environment request failed during list-pairing-links (HTTP 500).",
|
||||
);
|
||||
expect(error.message).not.toContain(cause.message);
|
||||
});
|
||||
|
||||
it("waits for the authenticated session to become observable after silent desktop bootstrap", async () => {
|
||||
vi.useFakeTimers();
|
||||
const nextSession = sequence(
|
||||
@@ -337,15 +373,7 @@ describe("resolveInitialServerAuthGateState", () => {
|
||||
browserSession: () => Effect.succeed(browserSession(["orchestration:read", "access:write"])),
|
||||
});
|
||||
|
||||
const testWindow = installTestBrowser("http://localhost/");
|
||||
testWindow.desktopBridge = {
|
||||
getLocalEnvironmentBootstrap: () => ({
|
||||
label: "Local environment",
|
||||
httpBaseUrl: "http://localhost:3773",
|
||||
wsBaseUrl: "ws://localhost:3773",
|
||||
bootstrapToken: "desktop-bootstrap-token",
|
||||
}),
|
||||
} as DesktopBridge;
|
||||
installDesktopBootstrap();
|
||||
|
||||
const { resolveInitialServerAuthGateState } = await import("./environments/primary");
|
||||
|
||||
@@ -356,6 +384,28 @@ describe("resolveInitialServerAuthGateState", () => {
|
||||
expect(testApi.calls.session).toBe(3);
|
||||
});
|
||||
|
||||
it("preserves the timeout message when a bootstrapped session never becomes observable", async () => {
|
||||
vi.useFakeTimers();
|
||||
const testApi = await installAuthApi({
|
||||
session: () => unauthenticatedSession(DESKTOP_AUTH),
|
||||
browserSession: () => Effect.succeed(browserSession(["orchestration:read", "access:write"])),
|
||||
});
|
||||
|
||||
installDesktopBootstrap();
|
||||
|
||||
const { resolveInitialServerAuthGateState } = await import("./environments/primary");
|
||||
|
||||
const gateStatePromise = resolveInitialServerAuthGateState();
|
||||
await vi.advanceTimersByTimeAsync(2_000);
|
||||
|
||||
await expect(gateStatePromise).resolves.toEqual({
|
||||
status: "requires-auth",
|
||||
auth: DESKTOP_AUTH,
|
||||
errorMessage: "Timed out waiting for authenticated session after bootstrap.",
|
||||
});
|
||||
expect(testApi.calls.browserSession).toEqual([{ credential: "desktop-bootstrap-token" }]);
|
||||
});
|
||||
|
||||
it("memoizes the authenticated gate state after the first successful read", async () => {
|
||||
const testApi = await installAuthApi({
|
||||
session: sequence(authenticatedSession(LOOPBACK_AUTH), unauthenticatedSession(LOOPBACK_AUTH)),
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import type { PreviewViewportSetting } from "@t3tools/contracts";
|
||||
import { describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
commitViewportAndAspectRatio,
|
||||
reconcileLockedAspectRatio,
|
||||
} from "./browserDeviceToolbarState";
|
||||
|
||||
describe("commitViewportAndAspectRatio", () => {
|
||||
it("commits the aspect ratio only after the viewport succeeds", async () => {
|
||||
let resolveChange: (() => void) | undefined;
|
||||
const onChange = vi.fn(
|
||||
() =>
|
||||
new Promise<void>((resolve) => {
|
||||
resolveChange = resolve;
|
||||
}),
|
||||
);
|
||||
const onAspectRatioChange = vi.fn();
|
||||
const setting: PreviewViewportSetting = { _tag: "freeform", width: 900, height: 600 };
|
||||
|
||||
const commit = commitViewportAndAspectRatio(setting, 1.5, onChange, onAspectRatioChange);
|
||||
expect(onAspectRatioChange).not.toHaveBeenCalled();
|
||||
|
||||
resolveChange?.();
|
||||
await commit;
|
||||
expect(onAspectRatioChange).toHaveBeenCalledWith(1.5);
|
||||
});
|
||||
|
||||
it("keeps the previous aspect ratio when the viewport commit fails", async () => {
|
||||
const onAspectRatioChange = vi.fn();
|
||||
await expect(
|
||||
commitViewportAndAspectRatio(
|
||||
{ _tag: "fill" },
|
||||
null,
|
||||
async () => Promise.reject(new Error("resize failed")),
|
||||
onAspectRatioChange,
|
||||
),
|
||||
).rejects.toThrow("resize failed");
|
||||
expect(onAspectRatioChange).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("reconcileLockedAspectRatio", () => {
|
||||
it("tracks external viewport ratios only while the lock remains active", () => {
|
||||
expect(reconcileLockedAspectRatio(1.5, 16 / 9)).toBe(16 / 9);
|
||||
expect(reconcileLockedAspectRatio(null, 16 / 9)).toBeNull();
|
||||
expect(reconcileLockedAspectRatio(1.5, null)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,340 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
PREVIEW_VIEWPORT_MAX_AREA,
|
||||
PREVIEW_VIEWPORT_MAX_DIMENSION,
|
||||
PREVIEW_VIEWPORT_MIN_DIMENSION,
|
||||
type PreviewViewportSetting,
|
||||
} from "@t3tools/contracts";
|
||||
import { PREVIEW_VIEWPORT_PRESETS, resolvePreviewViewport } from "@t3tools/shared/previewViewport";
|
||||
import { Link2, X } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
|
||||
import { Button } from "~/components/ui/button";
|
||||
import { Input } from "~/components/ui/input";
|
||||
import {
|
||||
Select,
|
||||
SelectGroup,
|
||||
SelectGroupLabel,
|
||||
SelectItem,
|
||||
SelectPopup,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "~/components/ui/select";
|
||||
import { cn } from "~/lib/utils";
|
||||
|
||||
import { BROWSER_DEVICE_TOOLBAR_HEIGHT, resizeFreeformViewport } from "./browserViewportLayout";
|
||||
import { commitViewportAndAspectRatio } from "./browserDeviceToolbarState";
|
||||
|
||||
const RESPONSIVE_VALUE = "responsive";
|
||||
const SELECT_ITEMS = [
|
||||
{ value: RESPONSIVE_VALUE, label: "Responsive" },
|
||||
...PREVIEW_VIEWPORT_PRESETS.map((preset) => ({ value: preset.id, label: preset.label })),
|
||||
];
|
||||
|
||||
function ScreenRotationIcon() {
|
||||
return (
|
||||
<svg
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<rect x="7.25" y="7.25" width="9.5" height="9.5" rx="1.4" transform="rotate(-45 12 12)" />
|
||||
<path d="M12.5 2a10 10 0 0 1 8.4 5.4" />
|
||||
<path d="M20.8 3.5v4h-4" />
|
||||
<path d="M11.5 22a10 10 0 0 1-8.4-5.4" />
|
||||
<path d="M3.2 20.5v-4h4" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
interface Props {
|
||||
readonly setting: Exclude<PreviewViewportSetting, { readonly _tag: "fill" }>;
|
||||
readonly width: number;
|
||||
readonly aspectRatio: number | null;
|
||||
readonly onAspectRatioChange: (aspectRatio: number | null) => void;
|
||||
readonly onChange: (setting: PreviewViewportSetting) => Promise<void>;
|
||||
}
|
||||
|
||||
export function BrowserDeviceToolbar({
|
||||
setting,
|
||||
width,
|
||||
aspectRatio,
|
||||
onAspectRatioChange,
|
||||
onChange,
|
||||
}: Props) {
|
||||
const [pending, setPending] = useState(false);
|
||||
const [customSize, setCustomSize] = useState<{
|
||||
readonly width: string;
|
||||
readonly height: string;
|
||||
} | null>(null);
|
||||
const presentedSize = customSize ?? {
|
||||
width: String(setting.width),
|
||||
height: String(setting.height),
|
||||
};
|
||||
const selectedValue =
|
||||
setting._tag === "preset" &&
|
||||
PREVIEW_VIEWPORT_PRESETS.some((preset) => preset.id === setting.presetId)
|
||||
? setting.presetId
|
||||
: RESPONSIVE_VALUE;
|
||||
const customWidth = Number(presentedSize.width);
|
||||
const customHeight = Number(presentedSize.height);
|
||||
const customValid =
|
||||
Number.isInteger(customWidth) &&
|
||||
Number.isInteger(customHeight) &&
|
||||
customWidth >= PREVIEW_VIEWPORT_MIN_DIMENSION &&
|
||||
customWidth <= PREVIEW_VIEWPORT_MAX_DIMENSION &&
|
||||
customHeight >= PREVIEW_VIEWPORT_MIN_DIMENSION &&
|
||||
customHeight <= PREVIEW_VIEWPORT_MAX_DIMENSION &&
|
||||
customWidth * customHeight <= PREVIEW_VIEWPORT_MAX_AREA;
|
||||
|
||||
const apply = (next: PreviewViewportSetting, nextAspectRatio = aspectRatio) => {
|
||||
setPending(true);
|
||||
void commitViewportAndAspectRatio(next, nextAspectRatio, onChange, onAspectRatioChange).then(
|
||||
() => {
|
||||
setPending(false);
|
||||
setCustomSize(null);
|
||||
},
|
||||
() => setPending(false),
|
||||
);
|
||||
};
|
||||
|
||||
const applyCustomSize = () => {
|
||||
if (!customValid || (customWidth === setting.width && customHeight === setting.height)) {
|
||||
setCustomSize(null);
|
||||
return;
|
||||
}
|
||||
apply({ _tag: "freeform", width: customWidth, height: customHeight });
|
||||
};
|
||||
|
||||
const updateCustomDimension = (axis: "width" | "height", value: string) => {
|
||||
setCustomSize((current) => {
|
||||
const next = {
|
||||
width: axis === "width" ? value : (current?.width ?? String(setting.width)),
|
||||
height: axis === "height" ? value : (current?.height ?? String(setting.height)),
|
||||
};
|
||||
const numeric = Number(value);
|
||||
if (
|
||||
aspectRatio === null ||
|
||||
!Number.isInteger(numeric) ||
|
||||
numeric < PREVIEW_VIEWPORT_MIN_DIMENSION ||
|
||||
numeric > PREVIEW_VIEWPORT_MAX_DIMENSION
|
||||
) {
|
||||
return next;
|
||||
}
|
||||
const resized = resizeFreeformViewport(
|
||||
setting,
|
||||
axis === "width"
|
||||
? { x: numeric - setting.width, y: 0 }
|
||||
: { x: 0, y: numeric - setting.height },
|
||||
1,
|
||||
axis === "width" ? "east" : "south",
|
||||
aspectRatio,
|
||||
);
|
||||
return { width: String(resized.width), height: String(resized.height) };
|
||||
});
|
||||
};
|
||||
|
||||
const selectViewport = (value: string | null) => {
|
||||
if (!value) return;
|
||||
if (value === RESPONSIVE_VALUE) {
|
||||
if (setting._tag === "freeform") return;
|
||||
apply({ _tag: "freeform", width: setting.width, height: setting.height });
|
||||
return;
|
||||
}
|
||||
const preset = PREVIEW_VIEWPORT_PRESETS.find((candidate) => candidate.id === value);
|
||||
if (!preset) return;
|
||||
apply(
|
||||
resolvePreviewViewport({ mode: "preset", preset: preset.id }),
|
||||
aspectRatio === null ? null : preset.width / preset.height,
|
||||
);
|
||||
};
|
||||
|
||||
const rotate = () => {
|
||||
const hasCustomSize =
|
||||
customValid && (customWidth !== setting.width || customHeight !== setting.height);
|
||||
const source = hasCustomSize
|
||||
? ({ _tag: "freeform", width: customWidth, height: customHeight } as const)
|
||||
: setting;
|
||||
apply(
|
||||
{ ...source, width: source.height, height: source.width },
|
||||
aspectRatio === null ? null : 1 / aspectRatio,
|
||||
);
|
||||
};
|
||||
|
||||
const toggleAspectRatio = () => {
|
||||
onAspectRatioChange(aspectRatio === null ? customWidth / customHeight : null);
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
className="sticky left-0 top-0 z-50 flex items-center gap-0.5 overflow-x-auto border-b border-border/70 bg-background/95 px-1.5 shadow-xs backdrop-blur-md [scrollbar-width:none] [&::-webkit-scrollbar]:hidden"
|
||||
style={{ width, height: BROWSER_DEVICE_TOOLBAR_HEIGHT }}
|
||||
role="toolbar"
|
||||
aria-label="Browser device toolbar"
|
||||
data-browser-device-toolbar
|
||||
onBlur={(event) => {
|
||||
const nextTarget = event.relatedTarget;
|
||||
if (nextTarget instanceof Node && event.currentTarget.contains(nextTarget)) return;
|
||||
const eventTarget = event.target;
|
||||
if (
|
||||
(nextTarget instanceof HTMLElement &&
|
||||
nextTarget.closest('[data-slot="select-positioner"]')) ||
|
||||
(eventTarget instanceof HTMLElement &&
|
||||
eventTarget.closest('[data-slot="select-positioner"]'))
|
||||
) {
|
||||
return;
|
||||
}
|
||||
applyCustomSize();
|
||||
}}
|
||||
>
|
||||
{width >= 560 ? (
|
||||
<span className="mr-0.5 shrink-0 text-[11px] font-medium text-muted-foreground">
|
||||
Dimensions
|
||||
</span>
|
||||
) : null}
|
||||
<Select
|
||||
modal={false}
|
||||
value={selectedValue}
|
||||
onValueChange={selectViewport}
|
||||
items={SELECT_ITEMS}
|
||||
disabled={pending}
|
||||
>
|
||||
<SelectTrigger
|
||||
variant="ghost"
|
||||
size="xs"
|
||||
className={cn(
|
||||
"shrink-0 justify-between px-1.5 font-medium",
|
||||
width >= 440 ? "w-36" : "w-24",
|
||||
)}
|
||||
aria-label="Browser device preset"
|
||||
>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectPopup align="start" alignItemWithTrigger={false} className="min-w-64">
|
||||
<SelectItem value={RESPONSIVE_VALUE}>Responsive</SelectItem>
|
||||
<SelectGroup>
|
||||
<SelectGroupLabel>Standard</SelectGroupLabel>
|
||||
{PREVIEW_VIEWPORT_PRESETS.map((preset) => (
|
||||
<SelectItem key={preset.id} value={preset.id}>
|
||||
<span className="flex w-full items-center justify-between gap-5">
|
||||
<span>{preset.label}</span>
|
||||
<span className="text-xs tabular-nums text-muted-foreground">
|
||||
{preset.detail}
|
||||
</span>
|
||||
</span>
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectGroup>
|
||||
</SelectPopup>
|
||||
</Select>
|
||||
|
||||
<form
|
||||
className="m-0 flex min-w-0 shrink-0 items-center gap-0.5 border-0 p-0"
|
||||
aria-label="Viewport dimensions"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
applyCustomSize();
|
||||
}}
|
||||
>
|
||||
<Input
|
||||
nativeInput
|
||||
type="number"
|
||||
inputMode="numeric"
|
||||
size="sm"
|
||||
min={PREVIEW_VIEWPORT_MIN_DIMENSION}
|
||||
max={PREVIEW_VIEWPORT_MAX_DIMENSION}
|
||||
value={presentedSize.width}
|
||||
disabled={pending}
|
||||
onFocus={() =>
|
||||
setCustomSize(
|
||||
(current) =>
|
||||
current ?? {
|
||||
width: String(setting.width),
|
||||
height: String(setting.height),
|
||||
},
|
||||
)
|
||||
}
|
||||
onChange={(event) => updateCustomDimension("width", event.target.value)}
|
||||
aria-label="Viewport width"
|
||||
aria-invalid={!customValid}
|
||||
className={cn(
|
||||
"h-6 rounded-md text-center tabular-nums [&_[data-slot=input]]:h-full [&_[data-slot=input]]:px-1 [&_[data-slot=input]]:text-xs [&_[data-slot=input]]:leading-none [&_[data-slot=input]::-webkit-inner-spin-button]:appearance-none [&_[data-slot=input]]:[appearance:textfield]",
|
||||
width >= 360 ? "w-14" : "w-11",
|
||||
)}
|
||||
/>
|
||||
<span className="text-xs text-muted-foreground">×</span>
|
||||
<Input
|
||||
nativeInput
|
||||
type="number"
|
||||
inputMode="numeric"
|
||||
size="sm"
|
||||
min={PREVIEW_VIEWPORT_MIN_DIMENSION}
|
||||
max={PREVIEW_VIEWPORT_MAX_DIMENSION}
|
||||
value={presentedSize.height}
|
||||
disabled={pending}
|
||||
onFocus={() =>
|
||||
setCustomSize(
|
||||
(current) =>
|
||||
current ?? {
|
||||
width: String(setting.width),
|
||||
height: String(setting.height),
|
||||
},
|
||||
)
|
||||
}
|
||||
onChange={(event) => updateCustomDimension("height", event.target.value)}
|
||||
aria-label="Viewport height"
|
||||
aria-invalid={!customValid}
|
||||
className={cn(
|
||||
"h-6 rounded-md text-center tabular-nums [&_[data-slot=input]]:h-full [&_[data-slot=input]]:px-1 [&_[data-slot=input]]:text-xs [&_[data-slot=input]]:leading-none [&_[data-slot=input]::-webkit-inner-spin-button]:appearance-none [&_[data-slot=input]]:[appearance:textfield]",
|
||||
width >= 360 ? "w-14" : "w-11",
|
||||
)}
|
||||
/>
|
||||
</form>
|
||||
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-xs"
|
||||
type="button"
|
||||
aria-label={
|
||||
aspectRatio === null ? "Lock viewport aspect ratio" : "Unlock viewport aspect ratio"
|
||||
}
|
||||
aria-pressed={aspectRatio !== null}
|
||||
title={aspectRatio === null ? "Lock aspect ratio" : "Unlock aspect ratio"}
|
||||
className={cn(aspectRatio !== null && "bg-accent text-foreground")}
|
||||
disabled={pending || !customValid}
|
||||
onPointerDown={(event) => event.preventDefault()}
|
||||
onClick={toggleAspectRatio}
|
||||
>
|
||||
<Link2 className={cn(aspectRatio !== null && "text-foreground")} />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-xs"
|
||||
type="button"
|
||||
aria-label="Rotate viewport"
|
||||
disabled={pending}
|
||||
onClick={rotate}
|
||||
>
|
||||
<ScreenRotationIcon />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-xs"
|
||||
type="button"
|
||||
aria-label="Close device toolbar"
|
||||
className="sticky right-0 ml-auto bg-background/95"
|
||||
disabled={pending}
|
||||
onClick={() => {
|
||||
apply({ _tag: "fill" }, null);
|
||||
}}
|
||||
>
|
||||
<X />
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
"use client";
|
||||
|
||||
import type {
|
||||
CSSProperties,
|
||||
KeyboardEvent as ReactKeyboardEvent,
|
||||
PointerEvent as ReactPointerEvent,
|
||||
} from "react";
|
||||
|
||||
import { cn } from "~/lib/utils";
|
||||
|
||||
import {
|
||||
BROWSER_VIEWPORT_RESIZE_RAIL_SIZE,
|
||||
type BrowserViewportLayout,
|
||||
type BrowserViewportResizeDirection,
|
||||
} from "./browserViewportLayout";
|
||||
|
||||
interface Props {
|
||||
readonly layout: BrowserViewportLayout;
|
||||
readonly activeDirection: BrowserViewportResizeDirection | null;
|
||||
readonly onPointerDown: (
|
||||
direction: BrowserViewportResizeDirection,
|
||||
event: ReactPointerEvent<HTMLButtonElement>,
|
||||
) => void;
|
||||
readonly onKeyDown: (
|
||||
direction: BrowserViewportResizeDirection,
|
||||
event: ReactKeyboardEvent<HTMLButtonElement>,
|
||||
) => void;
|
||||
}
|
||||
|
||||
type HandleKind = "horizontal" | "vertical" | "corner";
|
||||
|
||||
const EDGE_BUTTON_CLASS =
|
||||
"group absolute z-20 touch-none border-0 bg-transparent p-0 outline-none before:absolute before:-inset-1 before:content-[''] focus-visible:bg-foreground/[0.04]";
|
||||
const EDGE_GRIP_CLASS =
|
||||
"pointer-events-none absolute left-1/2 top-1/2 flex -translate-x-1/2 -translate-y-1/2 items-center justify-center text-muted-foreground/55 transition-colors duration-150 group-hover:text-foreground/85 group-focus-visible:text-foreground group-active:text-foreground";
|
||||
|
||||
function ResizeHandle(props: {
|
||||
readonly direction: BrowserViewportResizeDirection;
|
||||
readonly label: string;
|
||||
readonly kind: HandleKind;
|
||||
readonly cursorClassName: string;
|
||||
readonly style: CSSProperties;
|
||||
readonly active: boolean;
|
||||
readonly mirrorCorner?: boolean;
|
||||
readonly onPointerDown: Props["onPointerDown"];
|
||||
readonly onKeyDown: Props["onKeyDown"];
|
||||
}) {
|
||||
const {
|
||||
direction,
|
||||
label,
|
||||
kind,
|
||||
cursorClassName,
|
||||
style,
|
||||
active,
|
||||
mirrorCorner = false,
|
||||
onPointerDown,
|
||||
onKeyDown,
|
||||
} = props;
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`${label}. Use arrow keys to resize.`}
|
||||
className={cn(EDGE_BUTTON_CLASS, kind === "corner" && "z-30", cursorClassName)}
|
||||
style={style}
|
||||
onPointerDown={(event) => onPointerDown(direction, event)}
|
||||
onKeyDown={(event) => onKeyDown(direction, event)}
|
||||
>
|
||||
<span
|
||||
className={cn(
|
||||
EDGE_GRIP_CLASS,
|
||||
kind === "vertical" && "h-8 w-1.5",
|
||||
kind === "horizontal" && "h-1.5 w-8",
|
||||
kind === "corner" && "size-3",
|
||||
active && "text-foreground",
|
||||
)}
|
||||
>
|
||||
{kind === "vertical" ? (
|
||||
<span className="flex gap-px" aria-hidden="true">
|
||||
<span className="h-6 w-px rounded-full bg-current" />
|
||||
<span className="h-6 w-px rounded-full bg-current" />
|
||||
</span>
|
||||
) : kind === "horizontal" ? (
|
||||
<span className="flex flex-col gap-px" aria-hidden="true">
|
||||
<span className="h-px w-6 rounded-full bg-current" />
|
||||
<span className="h-px w-6 rounded-full bg-current" />
|
||||
</span>
|
||||
) : (
|
||||
<span
|
||||
className={cn("relative block size-3", mirrorCorner && "-scale-x-100")}
|
||||
aria-hidden="true"
|
||||
>
|
||||
<span className="absolute bottom-[3px] left-0 h-px w-3 -rotate-45 rounded-full bg-current" />
|
||||
<span className="absolute bottom-0 left-[5px] h-px w-2 -rotate-45 rounded-full bg-current" />
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
export function BrowserViewportResizeHandles({
|
||||
layout,
|
||||
activeDirection,
|
||||
onPointerDown,
|
||||
onKeyDown,
|
||||
}: Props) {
|
||||
const left = layout.viewportX;
|
||||
const top = layout.viewportY;
|
||||
const right = left + layout.viewportWidth;
|
||||
const bottom = top + layout.viewportHeight;
|
||||
const railSize = BROWSER_VIEWPORT_RESIZE_RAIL_SIZE;
|
||||
|
||||
const shared = { activeDirection, onPointerDown, onKeyDown };
|
||||
return (
|
||||
<>
|
||||
<ResizeHandle
|
||||
direction="west"
|
||||
label="Resize browser viewport from left edge"
|
||||
kind="vertical"
|
||||
cursorClassName="cursor-ew-resize"
|
||||
style={{ left: left - railSize, top, width: railSize, height: layout.viewportHeight }}
|
||||
active={shared.activeDirection === "west"}
|
||||
onPointerDown={shared.onPointerDown}
|
||||
onKeyDown={shared.onKeyDown}
|
||||
/>
|
||||
<ResizeHandle
|
||||
direction="east"
|
||||
label="Resize browser viewport from right edge"
|
||||
kind="vertical"
|
||||
cursorClassName="cursor-ew-resize"
|
||||
style={{ left: right, top, width: railSize, height: layout.viewportHeight }}
|
||||
active={shared.activeDirection === "east"}
|
||||
onPointerDown={shared.onPointerDown}
|
||||
onKeyDown={shared.onKeyDown}
|
||||
/>
|
||||
<ResizeHandle
|
||||
direction="south"
|
||||
label="Resize browser viewport from bottom edge"
|
||||
kind="horizontal"
|
||||
cursorClassName="cursor-ns-resize"
|
||||
style={{ left, top: bottom, width: layout.viewportWidth, height: railSize }}
|
||||
active={shared.activeDirection === "south"}
|
||||
onPointerDown={shared.onPointerDown}
|
||||
onKeyDown={shared.onKeyDown}
|
||||
/>
|
||||
<ResizeHandle
|
||||
direction="southwest"
|
||||
label="Resize browser viewport from bottom-left corner"
|
||||
kind="corner"
|
||||
cursorClassName="cursor-nesw-resize"
|
||||
style={{ left: left - railSize, top: bottom, width: railSize, height: railSize }}
|
||||
active={shared.activeDirection === "southwest"}
|
||||
mirrorCorner
|
||||
onPointerDown={shared.onPointerDown}
|
||||
onKeyDown={shared.onKeyDown}
|
||||
/>
|
||||
<ResizeHandle
|
||||
direction="southeast"
|
||||
label="Resize browser viewport from bottom-right corner"
|
||||
kind="corner"
|
||||
cursorClassName="cursor-nwse-resize"
|
||||
style={{ left: right, top: bottom, width: railSize, height: railSize }}
|
||||
active={shared.activeDirection === "southeast"}
|
||||
onPointerDown={shared.onPointerDown}
|
||||
onKeyDown={shared.onKeyDown}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import { parseScopedThreadKey } from "@t3tools/client-runtime/environment";
|
||||
import { FILL_PREVIEW_VIEWPORT } from "@t3tools/contracts";
|
||||
import { useEffect, useMemo } from "react";
|
||||
|
||||
import { isElectron } from "~/env";
|
||||
@@ -22,7 +23,7 @@ export function ElectronBrowserHost() {
|
||||
? Object.values(previewState.sessions).map((snapshot) => ({
|
||||
threadRef,
|
||||
snapshot,
|
||||
active: previewState.activeTabId === snapshot.tabId,
|
||||
zoomFactor: previewState.desktopByTabId[snapshot.tabId]?.zoomFactor ?? 1,
|
||||
}))
|
||||
: [];
|
||||
}),
|
||||
@@ -73,7 +74,7 @@ export function ElectronBrowserHost() {
|
||||
if (!isElectron) return null;
|
||||
return (
|
||||
<div className="contents" data-electron-browser-host>
|
||||
{sessions.map(({ threadRef, snapshot }) => {
|
||||
{sessions.map(({ threadRef, snapshot, zoomFactor }) => {
|
||||
const url = snapshot.navStatus._tag === "Idle" ? null : snapshot.navStatus.url;
|
||||
return (
|
||||
<HostedBrowserWebview
|
||||
@@ -81,6 +82,8 @@ export function ElectronBrowserHost() {
|
||||
threadRef={threadRef}
|
||||
tabId={snapshot.tabId}
|
||||
initialUrl={url}
|
||||
viewport={snapshot.viewport ?? FILL_PREVIEW_VIEWPORT}
|
||||
zoomFactor={zoomFactor}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
|
||||
@@ -1,16 +1,22 @@
|
||||
"use client";
|
||||
|
||||
import type { ScopedThreadRef } from "@t3tools/contracts";
|
||||
import type { PreviewViewportSetting, ScopedThreadRef } from "@t3tools/contracts";
|
||||
import { useShallow } from "zustand/react/shallow";
|
||||
import { useCallback, useEffect, useRef } from "react";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
|
||||
import { previewBridge } from "~/components/preview/previewBridge";
|
||||
import { usePreviewBridge } from "~/components/preview/usePreviewBridge";
|
||||
import { cn } from "~/lib/utils";
|
||||
|
||||
import { useActiveBrowserRecordingTabId } from "./browserRecording";
|
||||
import { useBrowserSurfaceStore } from "./browserSurfaceStore";
|
||||
import { resolveBrowserSurfacePanelRect, useBrowserSurfaceStore } from "./browserSurfaceStore";
|
||||
import { browserViewportSettingKey } from "./browserViewportLayout";
|
||||
import { reconcileLockedAspectRatio } from "./browserDeviceToolbarState";
|
||||
import { BrowserDeviceToolbar } from "./BrowserDeviceToolbar";
|
||||
import { BrowserViewportResizeHandles } from "./BrowserViewportResizeHandles";
|
||||
import { acquireDesktopTab, type AcquiredDesktopTab } from "./desktopTabLifetime";
|
||||
import { usePreviewWebviewConfig } from "./previewWebviewConfigState";
|
||||
import { useBrowserViewportResize } from "./useBrowserViewportResize";
|
||||
|
||||
interface ElectronWebview extends HTMLElement {
|
||||
src: string;
|
||||
@@ -18,6 +24,7 @@ interface ElectronWebview extends HTMLElement {
|
||||
preload?: string;
|
||||
webpreferences?: string;
|
||||
getWebContentsId: () => number;
|
||||
executeJavaScript: (code: string, userGesture?: boolean) => Promise<unknown>;
|
||||
}
|
||||
|
||||
declare global {
|
||||
@@ -30,13 +37,25 @@ export function HostedBrowserWebview(props: {
|
||||
readonly threadRef: ScopedThreadRef;
|
||||
readonly tabId: string;
|
||||
readonly initialUrl: string | null;
|
||||
readonly viewport: PreviewViewportSetting;
|
||||
readonly zoomFactor: number;
|
||||
}) {
|
||||
const { threadRef, tabId, initialUrl } = props;
|
||||
const { threadRef, tabId, initialUrl, viewport, zoomFactor } = props;
|
||||
const config = usePreviewWebviewConfig(threadRef.environmentId);
|
||||
const initialSrcRef = useRef(initialUrl ?? "about:blank");
|
||||
const [initialSrc] = useState(() => initialUrl ?? "about:blank");
|
||||
const tabLeaseRef = useRef<AcquiredDesktopTab | null>(null);
|
||||
const wrapperRef = useRef<HTMLDivElement | null>(null);
|
||||
const webviewRef = useRef<ElectronWebview | null>(null);
|
||||
const presentation = useBrowserSurfaceStore(useShallow((state) => state.byTabId[tabId] ?? null));
|
||||
const [lockedAspectRatio, setLockedAspectRatio] = useState<number | null>(null);
|
||||
const presentation = useBrowserSurfaceStore(
|
||||
useShallow((state) => {
|
||||
const current = state.byTabId[tabId];
|
||||
return {
|
||||
rect: resolveBrowserSurfacePanelRect(state.byTabId, tabId),
|
||||
visible: current?.visible ?? false,
|
||||
};
|
||||
}),
|
||||
);
|
||||
const recording = useActiveBrowserRecordingTabId() === tabId;
|
||||
|
||||
usePreviewBridge({ threadRef, tabId });
|
||||
@@ -89,10 +108,69 @@ export function HostedBrowserWebview(props: {
|
||||
};
|
||||
}, [config, tabId]);
|
||||
|
||||
const active = presentation.visible && presentation.rect !== null;
|
||||
const lastRect = presentation.rect;
|
||||
const normalizedZoomFactor = Number.isFinite(zoomFactor) && zoomFactor > 0 ? zoomFactor : 1;
|
||||
const viewportWidth = viewport._tag === "fill" ? null : viewport.width;
|
||||
const viewportHeight = viewport._tag === "fill" ? null : viewport.height;
|
||||
const viewportAspectRatio =
|
||||
viewportWidth === null || viewportHeight === null ? null : viewportWidth / viewportHeight;
|
||||
useEffect(() => {
|
||||
setLockedAspectRatio((current) => reconcileLockedAspectRatio(current, viewportAspectRatio));
|
||||
}, [viewportAspectRatio]);
|
||||
const hiddenSize =
|
||||
viewport._tag !== "fill"
|
||||
? {
|
||||
width: viewport.width * normalizedZoomFactor,
|
||||
height: viewport.height * normalizedZoomFactor,
|
||||
}
|
||||
: { width: lastRect?.width ?? 1280, height: lastRect?.height ?? 800 };
|
||||
const containerSize = active && lastRect ? lastRect : hiddenSize;
|
||||
const deviceToolbarVisible = active && viewport._tag !== "fill";
|
||||
const {
|
||||
activeDrag,
|
||||
commitViewportChange,
|
||||
effectiveViewport,
|
||||
handleResizeKeyDown,
|
||||
handleResizePointerDown,
|
||||
layout,
|
||||
} = useBrowserViewportResize({
|
||||
tabId,
|
||||
viewport,
|
||||
zoomFactor,
|
||||
containerSize,
|
||||
deviceToolbarVisible,
|
||||
aspectRatio: lockedAspectRatio,
|
||||
});
|
||||
|
||||
const syncContentPresentation = useCallback(() => {
|
||||
const wrapper = wrapperRef.current;
|
||||
if (!wrapper) return;
|
||||
useBrowserSurfaceStore.getState().presentContent(tabId, {
|
||||
x: layout.viewportX,
|
||||
y: layout.viewportY,
|
||||
width: layout.viewportWidth,
|
||||
height: layout.viewportHeight,
|
||||
scale: layout.viewportScale,
|
||||
scrollLeft: wrapper.scrollLeft,
|
||||
scrollTop: wrapper.scrollTop,
|
||||
});
|
||||
}, [layout, tabId]);
|
||||
|
||||
useEffect(() => {
|
||||
const frameId = window.requestAnimationFrame(syncContentPresentation);
|
||||
return () => window.cancelAnimationFrame(frameId);
|
||||
}, [syncContentPresentation]);
|
||||
|
||||
useEffect(() => {
|
||||
const wrapper = wrapperRef.current;
|
||||
if (!wrapper) return;
|
||||
wrapper.scrollTo({ left: 0, top: 0 });
|
||||
}, [tabId, viewport._tag, viewportHeight, viewportWidth]);
|
||||
|
||||
if (!config) return null;
|
||||
const active = presentation?.visible === true && presentation.rect !== null;
|
||||
const lastRect = presentation?.rect;
|
||||
const style =
|
||||
|
||||
const wrapperStyle =
|
||||
active && lastRect
|
||||
? {
|
||||
left: lastRect.x,
|
||||
@@ -105,23 +183,86 @@ export function HostedBrowserWebview(props: {
|
||||
: {
|
||||
left: 0,
|
||||
top: 0,
|
||||
width: lastRect?.width ?? 1280,
|
||||
height: lastRect?.height ?? 800,
|
||||
width: hiddenSize.width,
|
||||
height: hiddenSize.height,
|
||||
zIndex: recording ? 0 : -1,
|
||||
pointerEvents: "none" as const,
|
||||
};
|
||||
|
||||
return (
|
||||
<webview
|
||||
ref={setWebviewRef}
|
||||
src={initialSrcRef.current}
|
||||
partition={config.partition}
|
||||
webpreferences={config.webPreferences}
|
||||
{...(config.preloadUrl ? { preload: config.preloadUrl } : {})}
|
||||
data-preview-tab={tabId}
|
||||
aria-hidden={active ? undefined : true}
|
||||
className="fixed flex overflow-hidden bg-background"
|
||||
style={style}
|
||||
/>
|
||||
<div
|
||||
ref={wrapperRef}
|
||||
className="fixed overflow-hidden bg-muted/35"
|
||||
style={{ ...wrapperStyle, overscrollBehavior: "contain" }}
|
||||
onScroll={syncContentPresentation}
|
||||
data-preview-viewport={tabId}
|
||||
>
|
||||
<div className="relative" style={{ width: layout.canvasWidth, height: layout.canvasHeight }}>
|
||||
{deviceToolbarVisible && effectiveViewport._tag !== "fill" ? (
|
||||
<BrowserDeviceToolbar
|
||||
setting={effectiveViewport}
|
||||
width={Math.max(1, Math.round(containerSize.width))}
|
||||
aspectRatio={lockedAspectRatio}
|
||||
onAspectRatioChange={setLockedAspectRatio}
|
||||
onChange={commitViewportChange}
|
||||
/>
|
||||
) : null}
|
||||
<webview
|
||||
ref={setWebviewRef}
|
||||
src={initialSrc}
|
||||
partition={config.partition}
|
||||
webpreferences={config.webPreferences}
|
||||
{...(config.preloadUrl ? { preload: config.preloadUrl } : {})}
|
||||
data-preview-tab={tabId}
|
||||
data-preview-viewport-mode={effectiveViewport._tag}
|
||||
data-preview-viewport-key={browserViewportSettingKey(effectiveViewport)}
|
||||
data-preview-css-width={
|
||||
effectiveViewport._tag === "fill"
|
||||
? Math.max(1, Math.round(layout.viewportWidth / normalizedZoomFactor))
|
||||
: effectiveViewport.width
|
||||
}
|
||||
data-preview-css-height={
|
||||
effectiveViewport._tag === "fill"
|
||||
? Math.max(1, Math.round(layout.viewportHeight / normalizedZoomFactor))
|
||||
: effectiveViewport.height
|
||||
}
|
||||
aria-hidden={active ? undefined : true}
|
||||
className={cn(
|
||||
"absolute flex overflow-hidden bg-background",
|
||||
active && !layout.fillsPanel && "ring-1 ring-border/70 shadow-sm",
|
||||
)}
|
||||
style={{
|
||||
left: layout.viewportX,
|
||||
top: layout.viewportY,
|
||||
width: layout.viewportWidth / layout.viewportScale,
|
||||
height: layout.viewportHeight / layout.viewportScale,
|
||||
transform: layout.viewportScale < 1 ? `scale(${layout.viewportScale})` : undefined,
|
||||
transformOrigin: "top left",
|
||||
}}
|
||||
/>
|
||||
{active && effectiveViewport._tag !== "fill" ? (
|
||||
<>
|
||||
<BrowserViewportResizeHandles
|
||||
layout={layout}
|
||||
activeDirection={activeDrag?.direction ?? null}
|
||||
onPointerDown={handleResizePointerDown}
|
||||
onKeyDown={handleResizeKeyDown}
|
||||
/>
|
||||
{activeDrag ? (
|
||||
<div
|
||||
className="pointer-events-none absolute z-40 -translate-x-1/2 rounded-md border border-border/80 bg-background/95 px-2 py-1 text-[11px] font-medium tabular-nums text-foreground shadow-md backdrop-blur-sm"
|
||||
style={{
|
||||
left: layout.viewportX + layout.viewportWidth / 2,
|
||||
top: layout.viewportY + 10,
|
||||
}}
|
||||
aria-hidden="true"
|
||||
>
|
||||
{activeDrag.width} × {activeDrag.height}
|
||||
</div>
|
||||
) : null}
|
||||
</>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import type { PreviewViewportSetting } from "@t3tools/contracts";
|
||||
|
||||
export function reconcileLockedAspectRatio(
|
||||
current: number | null,
|
||||
viewportAspectRatio: number | null,
|
||||
): number | null {
|
||||
return current === null || viewportAspectRatio === null ? null : viewportAspectRatio;
|
||||
}
|
||||
|
||||
export async function commitViewportAndAspectRatio(
|
||||
setting: PreviewViewportSetting,
|
||||
aspectRatio: number | null,
|
||||
onChange: (setting: PreviewViewportSetting) => Promise<void>,
|
||||
onAspectRatioChange: (aspectRatio: number | null) => void,
|
||||
): Promise<void> {
|
||||
await onChange(setting);
|
||||
onAspectRatioChange(aspectRatio);
|
||||
}
|
||||
Loaded 100 of 235 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user