Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f0537a8420 | ||
|
|
4d6a3bab77 | ||
|
|
8fd276f69e | ||
|
|
a7d56b3e9d | ||
|
|
9e0c536560 | ||
|
|
e4a440b636 | ||
|
|
2efb859b94 | ||
|
|
3b109689e1 | ||
|
|
ff76f76de1 | ||
|
|
973d3c12ce | ||
|
|
71c5fdc834 | ||
|
|
249a5adc6a | ||
|
|
d407d90156 | ||
|
|
babf6f4c9a | ||
|
|
57cf3169f1 | ||
|
|
96e4579244 | ||
|
|
72191777b4 | ||
|
|
65ed5d9909 | ||
|
|
252622a255 | ||
|
|
15bacdba45 | ||
|
|
eb8c3f5d68 | ||
|
|
0dd63500b2 | ||
|
|
f9cf047b6f | ||
|
|
a14abc6665 | ||
|
|
77a8eb2970 | ||
|
|
cc21e541b7 | ||
|
|
1ea4c823f9 | ||
|
|
1fc31fa042 | ||
|
|
c861bb86f7 | ||
|
|
6715d1651f | ||
|
|
025fd6f5e8 | ||
|
|
52701266ac | ||
|
|
c60d2b1de2 |
No files matched your search
@@ -48,9 +48,7 @@ Review changed TypeScript and directly affected call sites for the conventions b
|
||||
- Define service failures with `Schema.TaggedErrorClass` and structured attributes. Derive `message` from those attributes rather than storing an unstructured message as the only data.
|
||||
- `Schema.Defect()` is not a substitute for modeling a generic error: its tag, fields, or both must identify the failure structurally, and its `message` must not merely stringify an opaque cause. A semantically precise error tag may preserve a real `cause` without inventing a redundant singleton field when no additional variable context exists; still retain any real path, resource, request, or entity context available at the wrapping site.
|
||||
- Capture stable, serializable domain context such as the operation or stage, resource/path or entity identifier, and normalized category/status. Map failures where that context is known instead of wrapping an entire multi-step pipeline in one generic error. Do not add a `detail` field that merely copies `cause.message` and then use it to construct the wrapper message.
|
||||
- Keep direct error attributes and log annotations safe and bounded. Do not copy raw wire payloads, command arguments or output, signed URLs, credentials, query strings, fragments, selectors, or arbitrary defect text into `detail`, `reason`, `message`, or a parallel log payload. Preserve the exact underlying value only as `cause`; expose normalized categories plus lengths/counts and safe URL protocol/hostname diagnostics where useful. Logging a sanitized error must not reintroduce a removed legacy `detail` or serialized `cause` field beside it.
|
||||
- When translating or wrapping a real failure, preserve the immediate underlying error itself as `cause` alongside the structural fields so the complete error chain and stack remain available. If every construction wraps a failure, `cause` should be required; make it optional only when the same error can legitimately originate without an underlying failure.
|
||||
- At a translation boundary, pass through an already structured domain error when it is part of the declared target error channel. Wrap only unknown or genuinely lower-level failures. A static factory or mapper may perform this classification when it is reused and keeps the policy next to the target error type.
|
||||
- Derive the wrapper's `message` exclusively from its stable structural attributes, never from `cause`, `cause.message`, or a stringified defect. Do not replace the immediate error with only `error.cause`, erase a structured upstream error into a string, or manufacture an `Error` merely to populate `cause`. Pure validation/domain errors created without an underlying failure do not need a cause.
|
||||
- Do not encode the same distinction twice with both a specific error tag and a single-value `operation`, `reason`, `kind`, or `phase` literal. Choose one coherent model: use distinct error classes and omit the redundant discriminator when callers or messages treat the failures as genuinely different, or use one service-level error with a multi-value operation discriminator and a generic message derived from that operation when the failures share the same semantics.
|
||||
- Treat an error message exposed through an HTTP/RPC response, persisted state, UI, or another caller-visible boundary as behavior. Preserve those messages during a structural refactor. Existing distinct caller-visible messages are evidence that the failures should normally remain distinct error tags without redundant singleton discriminators, rather than being collapsed into a generic operation error.
|
||||
@@ -58,9 +56,6 @@ Review changed TypeScript and directly affected call sites for the conventions b
|
||||
- Use `Schema.Union` of error classes when a shared schema, predicate, or helper type is useful.
|
||||
- Export direct schema predicates such as `export const isFoo = Schema.is(Foo)`. Flag a private `Schema.is` constant wrapped by a redundant function with the same signature.
|
||||
- Do not introduce a large `switch` or lookup table in an error's `message` getter to model failures that deserve separate error classes.
|
||||
- Catch statically known tagged failures with `Effect.catchTags({ ... })`, including when handling only one tag. Do not use `catchIf` with a schema predicate merely to recover one or more known `_tag` variants, and do not use `catchTag`. `Effect.catch` is appropriate when the entire error channel is intentionally handled; `catchIf` remains appropriate for genuinely structural predicates such as inspecting an underlying platform error code.
|
||||
- Do not add a helper whose only behavior is `(...args) => new SomeError({ ...args })`, including curried aliases used once with `mapError`. Construct the error at the failure boundary so its attributes and cause remain visible. Keep a mapper only when it performs real normalization, passes through existing domain errors, or adds reusable context/control flow.
|
||||
- When a reusable error-to-error translation clearly belongs to the target error type, prefer a descriptive static factory on that error class over a detached production-side switch. Do not force a static method for one-off inline mappings.
|
||||
|
||||
## File layout and migrations
|
||||
|
||||
@@ -78,6 +73,4 @@ Review changed TypeScript and directly affected call sites for the conventions b
|
||||
|
||||
## Reporting
|
||||
|
||||
Report only concrete violations introduced or retained in the pull request's changed scope. Prefer precise inline comments on the smallest relevant line range and state the expected fix. A clear convention violation may fail the check. Do not fail for optional style preferences or unrelated legacy code.
|
||||
|
||||
This check defaults to failure. When there are no findings, stop immediately and make the entire final response exactly `All clear` on one line. Do not add a title, explanation, punctuation, Markdown, JSON, or trailing analysis, and do not continue reasoning after deciding the review is clean.
|
||||
Report only concrete violations introduced or retained in the pull request's changed scope. Prefer precise inline comments on the smallest relevant line range and state the expected fix. A clear convention violation may fail the check. Do not fail for optional style preferences or unrelated legacy code. If there are no findings, report exactly `All clear`.
|
||||
@@ -100,41 +100,25 @@ function shellSingleQuote(value) {
|
||||
return `'${value.replaceAll("'", "'\\''")}'`;
|
||||
}
|
||||
|
||||
export function makeDevelopmentLauncherScript({
|
||||
electronBinaryPath,
|
||||
mainEntryPath,
|
||||
desktopRoot,
|
||||
environment,
|
||||
}) {
|
||||
function writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath) {
|
||||
const mainEntryPath = NodePath.join(desktopDir, "dist-electron", "main.cjs");
|
||||
const envEntries = [
|
||||
["VITE_DEV_SERVER_URL", environment.VITE_DEV_SERVER_URL],
|
||||
["T3CODE_PORT", environment.T3CODE_PORT],
|
||||
["T3CODE_HOME", environment.T3CODE_HOME],
|
||||
["T3CODE_COMMIT_HASH", environment.T3CODE_COMMIT_HASH],
|
||||
["T3CODE_OTLP_TRACES_URL", environment.T3CODE_OTLP_TRACES_URL],
|
||||
["T3CODE_OTLP_EXPORT_INTERVAL_MS", environment.T3CODE_OTLP_EXPORT_INTERVAL_MS],
|
||||
["VITE_DEV_SERVER_URL", process.env.VITE_DEV_SERVER_URL],
|
||||
["T3CODE_PORT", process.env.T3CODE_PORT],
|
||||
["T3CODE_HOME", process.env.T3CODE_HOME],
|
||||
["T3CODE_COMMIT_HASH", process.env.T3CODE_COMMIT_HASH],
|
||||
["T3CODE_OTLP_TRACES_URL", process.env.T3CODE_OTLP_TRACES_URL],
|
||||
["T3CODE_OTLP_EXPORT_INTERVAL_MS", process.env.T3CODE_OTLP_EXPORT_INTERVAL_MS],
|
||||
["T3CODE_DESKTOP_APP_USER_MODEL_ID", APP_BUNDLE_ID],
|
||||
].filter((entry) => typeof entry[1] === "string" && entry[1].trim().length > 0);
|
||||
return [
|
||||
"#!/bin/sh",
|
||||
...envEntries.map(
|
||||
([name, value]) =>
|
||||
`if [ -z "\${${name}:-}" ]; then export ${name}=${shellSingleQuote(value)}; fi`,
|
||||
),
|
||||
`exec ${shellSingleQuote(electronBinaryPath)} --t3code-dev-root=${shellSingleQuote(desktopRoot)} ${shellSingleQuote(mainEntryPath)} "$@"`,
|
||||
"",
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
function writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath) {
|
||||
NodeFS.writeFileSync(
|
||||
targetBinaryPath,
|
||||
makeDevelopmentLauncherScript({
|
||||
electronBinaryPath,
|
||||
mainEntryPath: NodePath.join(desktopDir, "dist-electron", "main.cjs"),
|
||||
desktopRoot: desktopDir,
|
||||
environment: process.env,
|
||||
}),
|
||||
[
|
||||
"#!/bin/sh",
|
||||
...envEntries.map(([name, value]) => `export ${name}=${shellSingleQuote(value)}`),
|
||||
`exec ${shellSingleQuote(electronBinaryPath)} --t3code-dev-root=${shellSingleQuote(desktopDir)} ${shellSingleQuote(mainEntryPath)} "$@"`,
|
||||
"",
|
||||
].join("\n"),
|
||||
);
|
||||
NodeFS.chmodSync(targetBinaryPath, 0o755);
|
||||
}
|
||||
@@ -302,12 +286,6 @@ function buildMacLauncher(electronBinaryPath) {
|
||||
currentMetadata &&
|
||||
JSON.stringify(currentMetadata) === JSON.stringify(expectedMetadata)
|
||||
) {
|
||||
if (isDevelopment) {
|
||||
// The launcher also handles protocol activations outside the dev runner,
|
||||
// so refresh its fallback environment on every launch. Never let a value
|
||||
// captured by an older parent app override the live dev-runner environment.
|
||||
writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath);
|
||||
}
|
||||
registerMacLauncherBundle(targetAppBundlePath);
|
||||
return targetBinaryPath;
|
||||
}
|
||||
|
||||
@@ -1,28 +0,0 @@
|
||||
import { assert, describe, it } from "vite-plus/test";
|
||||
|
||||
import { makeDevelopmentLauncherScript } from "./electron-launcher.mjs";
|
||||
|
||||
describe("electron development launcher", () => {
|
||||
it("uses captured values only as fallbacks for a live runner environment", () => {
|
||||
const script = makeDevelopmentLauncherScript({
|
||||
electronBinaryPath: "/repo/node_modules/electron/Electron",
|
||||
mainEntryPath: "/repo/apps/desktop/dist-electron/main.cjs",
|
||||
desktopRoot: "/repo/apps/desktop",
|
||||
environment: {
|
||||
VITE_DEV_SERVER_URL: "http://127.0.0.1:8526",
|
||||
T3CODE_PORT: "16566",
|
||||
T3CODE_HOME: "/tmp/t3",
|
||||
},
|
||||
});
|
||||
|
||||
assert.include(
|
||||
script,
|
||||
"if [ -z \"${VITE_DEV_SERVER_URL:-}\" ]; then export VITE_DEV_SERVER_URL='http://127.0.0.1:8526'; fi",
|
||||
);
|
||||
assert.notInclude(script, "\nexport VITE_DEV_SERVER_URL=");
|
||||
assert.include(
|
||||
script,
|
||||
"exec '/repo/node_modules/electron/Electron' --t3code-dev-root='/repo/apps/desktop' '/repo/apps/desktop/dist-electron/main.cjs' \"$@\"",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -43,16 +43,7 @@ describe("ElectronProtocol", () => {
|
||||
assert.isDefined(handler);
|
||||
|
||||
const response = yield* Effect.promise(() =>
|
||||
handler!(
|
||||
new Request("t3code-dev://app/api/health?verbose=1", {
|
||||
headers: {
|
||||
accept: "application/json",
|
||||
origin: "t3code-dev://app",
|
||||
referer: "t3code-dev://app/",
|
||||
"sec-fetch-site": "same-origin",
|
||||
},
|
||||
}),
|
||||
),
|
||||
handler!(new Request("t3code-dev://app/api/health?verbose=1")),
|
||||
);
|
||||
assert.equal(yield* Effect.promise(() => response.text()), "ok");
|
||||
assert.include(
|
||||
@@ -79,11 +70,6 @@ describe("ElectronProtocol", () => {
|
||||
["t3code-dev"],
|
||||
);
|
||||
assert.equal(netFetchMock.mock.calls[0]?.[0], "http://127.0.0.1:3773/api/health?verbose=1");
|
||||
const forwardedHeaders = new Headers(netFetchMock.mock.calls[0]?.[1]?.headers);
|
||||
assert.equal(forwardedHeaders.get("accept"), "application/json");
|
||||
assert.isNull(forwardedHeaders.get("origin"));
|
||||
assert.isNull(forwardedHeaders.get("referer"));
|
||||
assert.isNull(forwardedHeaders.get("sec-fetch-site"));
|
||||
assert.deepEqual(unhandleMock.mock.calls, [["t3code-dev"]]);
|
||||
}).pipe(Effect.provide(ElectronProtocol.layer)),
|
||||
);
|
||||
@@ -113,34 +99,6 @@ describe("ElectronProtocol", () => {
|
||||
}).pipe(Effect.provide(ElectronProtocol.layer)),
|
||||
);
|
||||
|
||||
it.effect("retries transient renderer target failures", () =>
|
||||
Effect.gen(function* () {
|
||||
let handler: ((request: Request) => Promise<Response>) | undefined;
|
||||
handleMock.mockImplementation((_scheme, nextHandler) => {
|
||||
handler = nextHandler;
|
||||
});
|
||||
netFetchMock
|
||||
.mockRejectedValueOnce(new Error("connect ECONNREFUSED 127.0.0.1:5733"))
|
||||
.mockResolvedValueOnce(new Response("ready"));
|
||||
|
||||
const response = yield* Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const protocol = yield* ElectronProtocol.ElectronProtocol;
|
||||
yield* protocol.registerDesktopProtocol({
|
||||
scheme: "t3code-dev",
|
||||
targetOrigin: new URL("http://127.0.0.1:5733/"),
|
||||
backendOrigin: new URL("http://127.0.0.1:3773/"),
|
||||
clerkFrontendApiHostname: undefined,
|
||||
});
|
||||
return yield* Effect.promise(() => handler!(new Request("t3code-dev://app/")));
|
||||
}),
|
||||
);
|
||||
|
||||
assert.equal(yield* Effect.promise(() => response.text()), "ready");
|
||||
assert.equal(netFetchMock.mock.calls.length, 2);
|
||||
}).pipe(Effect.provide(ElectronProtocol.layer)),
|
||||
);
|
||||
|
||||
it.effect("preserves protocol registration failures", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("protocol registration failed");
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as NodeTimersPromises from "node:timers/promises";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Scope from "effect/Scope";
|
||||
@@ -115,60 +114,18 @@ async function proxyRequest(
|
||||
}
|
||||
|
||||
const targetUrl = new URL(`${requestUrl.pathname}${requestUrl.search}`, targetOrigin);
|
||||
const headers = new Headers(request.headers);
|
||||
const headersToRemove: string[] = [];
|
||||
for (const name of headers.keys()) {
|
||||
if (
|
||||
name === "host" ||
|
||||
name === "origin" ||
|
||||
name === "referer" ||
|
||||
name === "connection" ||
|
||||
name === "content-length" ||
|
||||
name === "accept-encoding" ||
|
||||
name === "upgrade-insecure-requests" ||
|
||||
name.startsWith("sec-fetch-")
|
||||
) {
|
||||
headersToRemove.push(name);
|
||||
}
|
||||
}
|
||||
for (const name of headersToRemove) {
|
||||
headers.delete(name);
|
||||
}
|
||||
const init: RequestInit = {
|
||||
method: request.method,
|
||||
headers,
|
||||
headers: request.headers,
|
||||
};
|
||||
if (request.method !== "GET" && request.method !== "HEAD") {
|
||||
init.body = request.body;
|
||||
(init as RequestInit & { duplex: "half" }).duplex = "half";
|
||||
}
|
||||
const response =
|
||||
request.method === "GET" || request.method === "HEAD"
|
||||
? await fetchWithTransientRetry(targetUrl.toString(), init)
|
||||
: await Electron.net.fetch(targetUrl.toString(), init);
|
||||
const response = await Electron.net.fetch(targetUrl.toString(), init);
|
||||
return withContentSecurityPolicy(response, contentSecurityPolicy);
|
||||
}
|
||||
|
||||
const TRANSIENT_FETCH_RETRY_DELAYS_MS = [0, 50, 150] as const;
|
||||
|
||||
async function fetchWithTransientRetry(url: string, init: RequestInit): Promise<Response> {
|
||||
let lastError: unknown;
|
||||
|
||||
for (const delayMs of TRANSIENT_FETCH_RETRY_DELAYS_MS) {
|
||||
if (delayMs > 0) {
|
||||
await NodeTimersPromises.setTimeout(delayMs);
|
||||
}
|
||||
|
||||
try {
|
||||
return await Electron.net.fetch(url, init);
|
||||
} catch (error) {
|
||||
lastError = error;
|
||||
}
|
||||
}
|
||||
|
||||
throw lastError;
|
||||
}
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const registered = yield* Ref.make(false);
|
||||
|
||||
|
||||
@@ -46,14 +46,49 @@ describe("ElectronShell", () => {
|
||||
}).pipe(Effect.provide(ElectronShell.layer)),
|
||||
);
|
||||
|
||||
it.effect("returns false when Electron rejects openExternal", () =>
|
||||
it.effect("preserves safe URL context and cause when Electron rejects openExternal", () =>
|
||||
Effect.gen(function* () {
|
||||
openExternalMock.mockRejectedValue(new Error("open failed"));
|
||||
const cause = new Error("open failed");
|
||||
openExternalMock.mockRejectedValue(cause);
|
||||
const externalUrl =
|
||||
"HTTPS://user:[email protected]:443/signed-secret-token/path?access_token=secret#fragment";
|
||||
|
||||
const electronShell = yield* ElectronShell.ElectronShell;
|
||||
const result = yield* electronShell.openExternal("https://example.com/path");
|
||||
const error = yield* Effect.flip(electronShell.openExternal(externalUrl));
|
||||
|
||||
assert.equal(result, false);
|
||||
assert.instanceOf(error, ElectronShell.ElectronShellOpenExternalError);
|
||||
assert.isTrue(ElectronShell.isElectronShellError(error));
|
||||
assert.strictEqual(error.urlHostname, "example.com");
|
||||
assert.strictEqual(error.urlLength, externalUrl.length);
|
||||
assert.strictEqual(error.urlProtocol, "https:");
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.notProperty(error, "externalUrl");
|
||||
assert.notProperty(error, "requestTarget");
|
||||
assert.notMatch(
|
||||
error.message,
|
||||
/user|password|signed-secret-token|path|access_token|secret|fragment/,
|
||||
);
|
||||
assert.notInclude(error.message, cause.message);
|
||||
}).pipe(Effect.provide(ElectronShell.layer)),
|
||||
);
|
||||
|
||||
it.effect("preserves non-sensitive clipboard context and cause", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("clipboard failed");
|
||||
writeTextMock.mockImplementation(() => {
|
||||
throw cause;
|
||||
});
|
||||
|
||||
const electronShell = yield* ElectronShell.ElectronShell;
|
||||
const error = yield* Effect.flip(electronShell.copyText("secret text"));
|
||||
|
||||
assert.instanceOf(error, ElectronShell.ElectronShellCopyTextError);
|
||||
assert.isTrue(ElectronShell.isElectronShellError(error));
|
||||
assert.strictEqual(error.textLength, 11);
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.include(error.message, "11 characters");
|
||||
assert.notInclude(error.message, "secret text");
|
||||
assert.notInclude(error.message, cause.message);
|
||||
}).pipe(Effect.provide(ElectronShell.layer)),
|
||||
);
|
||||
});
|
||||
@@ -1,12 +1,47 @@
|
||||
import { getUrlDiagnostics } from "@t3tools/shared/urlDiagnostics";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as Electron from "electron";
|
||||
|
||||
const SAFE_EXTERNAL_PROTOCOLS = new Set(["http:", "https:"]);
|
||||
|
||||
export class ElectronShellOpenExternalError extends Schema.TaggedErrorClass<ElectronShellOpenExternalError>()(
|
||||
"ElectronShellOpenExternalError",
|
||||
{
|
||||
urlHostname: Schema.String,
|
||||
urlLength: Schema.Number,
|
||||
urlProtocol: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to open external URL for ${this.urlHostname} (${this.urlProtocol}, input length ${this.urlLength}).`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ElectronShellCopyTextError extends Schema.TaggedErrorClass<ElectronShellCopyTextError>()(
|
||||
"ElectronShellCopyTextError",
|
||||
{
|
||||
textLength: Schema.Number,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to copy ${this.textLength} characters to the clipboard.`;
|
||||
}
|
||||
}
|
||||
|
||||
export const ElectronShellError = Schema.Union([
|
||||
ElectronShellOpenExternalError,
|
||||
ElectronShellCopyTextError,
|
||||
]);
|
||||
export type ElectronShellError = typeof ElectronShellError.Type;
|
||||
export const isElectronShellError = Schema.is(ElectronShellError);
|
||||
|
||||
export function parseSafeExternalUrl(rawUrl: unknown): Option.Option<string> {
|
||||
if (typeof rawUrl !== "string") {
|
||||
return Option.none();
|
||||
@@ -20,29 +55,46 @@ export function parseSafeExternalUrl(rawUrl: unknown): Option.Option<string> {
|
||||
}
|
||||
}
|
||||
|
||||
function describeExternalUrl(externalUrl: string, inputLength: number) {
|
||||
const diagnostics = getUrlDiagnostics(externalUrl);
|
||||
return {
|
||||
urlHostname: diagnostics.hostname ?? "",
|
||||
urlLength: inputLength,
|
||||
urlProtocol: diagnostics.protocol ?? "",
|
||||
};
|
||||
}
|
||||
|
||||
export class ElectronShell extends Context.Service<
|
||||
ElectronShell,
|
||||
{
|
||||
readonly openExternal: (rawUrl: unknown) => Effect.Effect<boolean>;
|
||||
readonly copyText: (text: string) => Effect.Effect<void>;
|
||||
readonly openExternal: (
|
||||
rawUrl: unknown,
|
||||
) => Effect.Effect<boolean, ElectronShellOpenExternalError>;
|
||||
readonly copyText: (text: string) => Effect.Effect<void, ElectronShellCopyTextError>;
|
||||
}
|
||||
>()("@t3tools/desktop/electron/ElectronShell") {}
|
||||
|
||||
export const make = ElectronShell.of({
|
||||
openExternal: (rawUrl) =>
|
||||
Option.match(parseSafeExternalUrl(rawUrl), {
|
||||
openExternal: (rawUrl) => {
|
||||
const inputLength = typeof rawUrl === "string" ? rawUrl.length : 0;
|
||||
|
||||
return Option.match(parseSafeExternalUrl(rawUrl), {
|
||||
onNone: () => Effect.succeed(false),
|
||||
onSome: (externalUrl) =>
|
||||
Effect.promise(() =>
|
||||
Electron.shell.openExternal(externalUrl).then(
|
||||
() => true,
|
||||
() => false,
|
||||
),
|
||||
),
|
||||
}),
|
||||
Effect.tryPromise({
|
||||
try: () => Electron.shell.openExternal(externalUrl),
|
||||
catch: (cause) =>
|
||||
new ElectronShellOpenExternalError({
|
||||
...describeExternalUrl(externalUrl, inputLength),
|
||||
cause,
|
||||
}),
|
||||
}).pipe(Effect.as(true)),
|
||||
});
|
||||
},
|
||||
copyText: (text) =>
|
||||
Effect.sync(() => {
|
||||
Electron.clipboard.writeText(text);
|
||||
Effect.try({
|
||||
try: () => Electron.clipboard.writeText(text),
|
||||
catch: (cause) => new ElectronShellCopyTextError({ textLength: text.length, cause }),
|
||||
}),
|
||||
});
|
||||
|
||||
|
||||
@@ -32,7 +32,6 @@ export const GET_SERVER_EXPOSURE_STATE_CHANNEL = "desktop:get-server-exposure-st
|
||||
export const SET_SERVER_EXPOSURE_MODE_CHANNEL = "desktop:set-server-exposure-mode";
|
||||
export const SET_TAILSCALE_SERVE_ENABLED_CHANNEL = "desktop:set-tailscale-serve-enabled";
|
||||
export const GET_ADVERTISED_ENDPOINTS_CHANNEL = "desktop:get-advertised-endpoints";
|
||||
export const SSH_PASSWORD_PROMPT_CANCELLED_RESULT = "ssh-password-prompt-cancelled";
|
||||
export const PREVIEW_CREATE_TAB_CHANNEL = "desktop:preview-create-tab";
|
||||
export const PREVIEW_CLOSE_TAB_CHANNEL = "desktop:preview-close-tab";
|
||||
export const PREVIEW_REGISTER_WEBVIEW_CHANNEL = "desktop:preview-register-webview";
|
||||
|
||||
@@ -1,16 +1,28 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import { SshHttpBridgeError } from "@t3tools/ssh/errors";
|
||||
import {
|
||||
DesktopSshEnvironmentEnsureResultSchema,
|
||||
DesktopSshPasswordPromptCancellationError,
|
||||
} from "@t3tools/contracts";
|
||||
import { SshHttpBridgeError, SshPasswordPromptError } from "@t3tools/ssh/errors";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
|
||||
|
||||
import {
|
||||
DesktopSshEnvironmentRequestError,
|
||||
ensureSshEnvironment,
|
||||
fetchSshEnvironmentDescriptor,
|
||||
} from "./sshEnvironment.ts";
|
||||
import * as DesktopSshEnvironment from "../../ssh/DesktopSshEnvironment.ts";
|
||||
import * as DesktopSshPasswordPrompts from "../../ssh/DesktopSshPasswordPrompts.ts";
|
||||
|
||||
const decodeDesktopSshEnvironmentEnsureResult = Schema.decodeUnknownEffect(
|
||||
DesktopSshEnvironmentEnsureResultSchema,
|
||||
);
|
||||
|
||||
function jsonResponse(request: HttpClientRequest.HttpClientRequest, body: unknown, status = 200) {
|
||||
return HttpClientResponse.fromWeb(
|
||||
@@ -34,6 +46,44 @@ function makeHttpClientLayer(
|
||||
}
|
||||
|
||||
describe("SSH environment IPC", () => {
|
||||
it.effect("encodes password prompt cancellations with structured context and their cause", () => {
|
||||
const promptCause = new DesktopSshPasswordPrompts.DesktopSshPromptWindowClosedError({
|
||||
requestId: "prompt-1",
|
||||
destination: "[email protected]",
|
||||
});
|
||||
const cause = new SshPasswordPromptError({
|
||||
message: promptCause.message,
|
||||
cause: promptCause,
|
||||
});
|
||||
const layer = Layer.succeed(
|
||||
DesktopSshEnvironment.DesktopSshEnvironment,
|
||||
DesktopSshEnvironment.DesktopSshEnvironment.of({
|
||||
discoverHosts: () => Effect.die("unexpected host discovery"),
|
||||
ensureEnvironment: () => Effect.fail(cause),
|
||||
disconnectEnvironment: () => Effect.die("unexpected disconnect"),
|
||||
}),
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const encoded = yield* ensureSshEnvironment.handler({
|
||||
target: {
|
||||
alias: "devbox",
|
||||
hostname: "devbox.example.test",
|
||||
username: "developer",
|
||||
port: 22,
|
||||
},
|
||||
});
|
||||
const error = yield* decodeDesktopSshEnvironmentEnsureResult(encoded);
|
||||
|
||||
assert.instanceOf(error, DesktopSshPasswordPromptCancellationError);
|
||||
assert.equal(error.reason, "window-closed");
|
||||
assert.equal(error.requestId, "prompt-1");
|
||||
assert.equal(error.destination, "[email protected]");
|
||||
assert.instanceOf(error.cause, Error);
|
||||
assert.instanceOf(error.cause.cause, Error);
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
it.effect("fetches and decodes the remote environment descriptor", () => {
|
||||
const requestUrls: string[] = [];
|
||||
const layer = makeHttpClientLayer((request) =>
|
||||
|
||||
@@ -2,7 +2,7 @@ import {
|
||||
bootstrapRemoteBearerSession,
|
||||
fetchRemoteSessionState,
|
||||
issueRemoteWebSocketTicket,
|
||||
RemoteEnvironmentAuthUndeclaredStatusError,
|
||||
isRemoteEnvironmentAuthUndeclaredStatusError,
|
||||
type RemoteEnvironmentAuthError,
|
||||
} from "@t3tools/client-runtime/authorization";
|
||||
import { fetchRemoteEnvironmentDescriptor } from "@t3tools/client-runtime/environment";
|
||||
@@ -15,7 +15,7 @@ import {
|
||||
DesktopSshEnvironmentEnsureResultSchema,
|
||||
DesktopSshEnvironmentTargetSchema,
|
||||
DesktopSshHttpBaseUrlInputSchema,
|
||||
DesktopSshPasswordPromptCancelledType,
|
||||
DesktopSshPasswordPromptCancellationError,
|
||||
DesktopSshPasswordPromptResolutionInputSchema,
|
||||
ExecutionEnvironmentDescriptor,
|
||||
EnvironmentInternalError,
|
||||
@@ -45,6 +45,13 @@ type DesktopSshEnvironmentRequestOperation =
|
||||
|
||||
type DesktopSshEnvironmentRequestCause = RemoteEnvironmentAuthError | SshHttpBridgeError;
|
||||
|
||||
const desktopSshPasswordPromptCancellationReasons = {
|
||||
DesktopSshPromptCancelledError: "user-cancelled",
|
||||
DesktopSshPromptWindowClosedError: "window-closed",
|
||||
DesktopSshPromptServiceStoppedError: "service-stopped",
|
||||
DesktopSshPromptTimedOutError: "timed-out",
|
||||
} as const;
|
||||
|
||||
const isEnvironmentAuthInvalidError = Schema.is(EnvironmentAuthInvalidError);
|
||||
const isEnvironmentInternalError = Schema.is(EnvironmentInternalError);
|
||||
const isEnvironmentOperationForbiddenError = Schema.is(EnvironmentOperationForbiddenError);
|
||||
@@ -52,10 +59,7 @@ const isEnvironmentRequestInvalidError = Schema.is(EnvironmentRequestInvalidErro
|
||||
const isEnvironmentScopeRequiredError = Schema.is(EnvironmentScopeRequiredError);
|
||||
|
||||
function readSshHttpStatus(cause: DesktopSshEnvironmentRequestCause): number | null {
|
||||
if (
|
||||
cause instanceof RemoteEnvironmentAuthUndeclaredStatusError ||
|
||||
cause instanceof SshHttpBridgeError
|
||||
) {
|
||||
if (isRemoteEnvironmentAuthUndeclaredStatusError(cause) || cause instanceof SshHttpBridgeError) {
|
||||
return cause.status ?? null;
|
||||
}
|
||||
if (isEnvironmentRequestInvalidError(cause)) {
|
||||
@@ -127,14 +131,19 @@ export const ensureSshEnvironment = DesktopIpc.makeIpcMethod({
|
||||
}) {
|
||||
const sshEnvironment = yield* DesktopSshEnvironment.DesktopSshEnvironment;
|
||||
return yield* sshEnvironment.ensureEnvironment(target, options).pipe(
|
||||
Effect.catch((error) =>
|
||||
DesktopSshEnvironment.isDesktopSshPasswordPromptCancellation(error)
|
||||
? Effect.succeed({
|
||||
type: DesktopSshPasswordPromptCancelledType,
|
||||
message: error.message,
|
||||
})
|
||||
: Effect.fail(error),
|
||||
),
|
||||
Effect.catchTags({
|
||||
SshPasswordPromptError: (error) =>
|
||||
DesktopSshEnvironment.isDesktopSshPasswordPromptCancellation(error)
|
||||
? Effect.succeed(
|
||||
new DesktopSshPasswordPromptCancellationError({
|
||||
reason: desktopSshPasswordPromptCancellationReasons[error.cause._tag],
|
||||
requestId: error.cause.requestId,
|
||||
destination: error.cause.destination,
|
||||
cause: error,
|
||||
}),
|
||||
)
|
||||
: Effect.fail(error),
|
||||
}),
|
||||
);
|
||||
}),
|
||||
});
|
||||
|
||||
+15
-12
@@ -1,28 +1,31 @@
|
||||
import type {
|
||||
DesktopBridge,
|
||||
DesktopPreviewPointerEvent,
|
||||
DesktopPreviewRecordingFrame,
|
||||
DesktopPreviewTabState,
|
||||
import {
|
||||
DesktopSshPasswordPromptCancellationError,
|
||||
DesktopSshPasswordPromptCancellationErrorTag,
|
||||
type DesktopBridge,
|
||||
type DesktopPreviewPointerEvent,
|
||||
type DesktopPreviewRecordingFrame,
|
||||
type DesktopPreviewTabState,
|
||||
} from "@t3tools/contracts";
|
||||
import { exposeClerkBridge } from "@clerk/electron/preload";
|
||||
import { contextBridge, ipcRenderer } from "electron";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as IpcChannels from "./ipc/channels.ts";
|
||||
|
||||
exposeClerkBridge({ passkeys: true });
|
||||
|
||||
const decodeDesktopSshPasswordPromptCancellationError = Schema.decodeUnknownSync(
|
||||
DesktopSshPasswordPromptCancellationError,
|
||||
);
|
||||
|
||||
function unwrapEnsureSshEnvironmentResult(result: unknown) {
|
||||
if (
|
||||
typeof result === "object" &&
|
||||
result !== null &&
|
||||
"type" in result &&
|
||||
result.type === IpcChannels.SSH_PASSWORD_PROMPT_CANCELLED_RESULT
|
||||
"_tag" in result &&
|
||||
result._tag === DesktopSshPasswordPromptCancellationErrorTag
|
||||
) {
|
||||
const message =
|
||||
"message" in result && typeof result.message === "string"
|
||||
? result.message
|
||||
: "SSH authentication cancelled.";
|
||||
throw new Error(message);
|
||||
throw decodeDesktopSshPasswordPromptCancellationError(result);
|
||||
}
|
||||
return result as Awaited<ReturnType<DesktopBridge["ensureSshEnvironment"]>>;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { it as effectIt } from "@effect/vitest";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
@@ -19,25 +18,16 @@ import * as ElectronWindow from "../electron/ElectronWindow.ts";
|
||||
import * as BrowserSession from "./BrowserSession.ts";
|
||||
import * as PreviewManager from "./Manager.ts";
|
||||
|
||||
const {
|
||||
createFromPath,
|
||||
fromId,
|
||||
getFocusedWebContents,
|
||||
mkdir,
|
||||
showItemInFolder,
|
||||
webviewSend,
|
||||
writeFile,
|
||||
writeImage,
|
||||
} = vi.hoisted(() => ({
|
||||
createFromPath: vi.fn((): { readonly isEmpty: () => boolean } => ({ isEmpty: () => false })),
|
||||
fromId: vi.fn(() => null),
|
||||
getFocusedWebContents: vi.fn(() => null),
|
||||
mkdir: vi.fn((_path: string) => undefined),
|
||||
showItemInFolder: vi.fn(),
|
||||
webviewSend: vi.fn(),
|
||||
writeFile: vi.fn((_path: string, _data: Uint8Array) => undefined),
|
||||
writeImage: vi.fn(),
|
||||
}));
|
||||
const { createFromPath, fromId, mkdir, showItemInFolder, webviewSend, writeFile, writeImage } =
|
||||
vi.hoisted(() => ({
|
||||
createFromPath: vi.fn((): { readonly isEmpty: () => boolean } => ({ isEmpty: () => false })),
|
||||
fromId: vi.fn(() => null),
|
||||
mkdir: vi.fn((_path: string) => undefined),
|
||||
showItemInFolder: vi.fn(),
|
||||
webviewSend: vi.fn(),
|
||||
writeFile: vi.fn((_path: string, _data: Uint8Array) => undefined),
|
||||
writeImage: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("electron", () => ({
|
||||
clipboard: {
|
||||
@@ -54,7 +44,6 @@ vi.mock("electron", () => ({
|
||||
},
|
||||
webContents: {
|
||||
fromId,
|
||||
getFocusedWebContents,
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -92,7 +81,6 @@ const layer = PreviewManager.layer.pipe(
|
||||
Layer.provideMerge(environmentLayer),
|
||||
Layer.provideMerge(fileSystemLayer),
|
||||
Layer.provideMerge(Path.layer),
|
||||
Layer.provideMerge(Layer.succeed(HostProcessPlatform, "linux")),
|
||||
);
|
||||
const encodePreviewManagerError = Schema.encodeSync(PreviewManager.PreviewManagerError);
|
||||
|
||||
@@ -109,8 +97,6 @@ const withManager = <A>(
|
||||
describe("PreviewManager", () => {
|
||||
beforeEach(() => {
|
||||
fromId.mockClear();
|
||||
getFocusedWebContents.mockReset();
|
||||
getFocusedWebContents.mockReturnValue(null);
|
||||
mkdir.mockClear();
|
||||
writeFile.mockClear();
|
||||
showItemInFolder.mockClear();
|
||||
@@ -264,197 +250,6 @@ describe("PreviewManager", () => {
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("mirrors Electron's effective zoom across registration and navigation", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
let effectiveZoom = 0.9;
|
||||
let zoomReadable = true;
|
||||
let url = "https://example.com";
|
||||
const listeners = new Map<string, (...args: unknown[]) => void>();
|
||||
const setZoomFactor = vi.fn();
|
||||
fromId.mockReturnValue({
|
||||
id: 42,
|
||||
isDestroyed: () => false,
|
||||
getType: () => "webview",
|
||||
getURL: () => url,
|
||||
getTitle: () => "Example",
|
||||
isLoading: () => false,
|
||||
getZoomFactor: () => {
|
||||
if (!zoomReadable) throw new Error("zoom unavailable");
|
||||
return effectiveZoom;
|
||||
},
|
||||
setZoomFactor,
|
||||
on: vi.fn((event: string, listener: (...args: unknown[]) => void) => {
|
||||
listeners.set(event, listener);
|
||||
}),
|
||||
off: vi.fn(),
|
||||
ipc: { on: vi.fn(), off: vi.fn() },
|
||||
send: webviewSend,
|
||||
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
debugger: {
|
||||
isAttached: () => false,
|
||||
attach: vi.fn(),
|
||||
sendCommand: vi.fn(async () => undefined),
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
},
|
||||
} as never);
|
||||
const states: PreviewManager.PreviewTabState[] = [];
|
||||
|
||||
yield* manager.subscribeStateChanges((_tabId, state) =>
|
||||
Effect.sync(() => {
|
||||
states.push(state);
|
||||
}),
|
||||
);
|
||||
yield* manager.createTab("tab_zoom");
|
||||
yield* manager.registerWebview("tab_zoom", 42);
|
||||
|
||||
expect(states.at(-1)?.zoomFactor).toBe(0.9);
|
||||
expect(setZoomFactor).not.toHaveBeenCalled();
|
||||
|
||||
effectiveZoom = 1.25;
|
||||
listeners.get("did-navigate")?.();
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
expect(states.at(-1)?.zoomFactor).toBe(1.25);
|
||||
expect(setZoomFactor).not.toHaveBeenCalled();
|
||||
|
||||
zoomReadable = false;
|
||||
url = "https://example.com/after-zoom-read-failed";
|
||||
listeners.get("did-navigate")?.();
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
expect(states.at(-1)?.navStatus).toEqual({
|
||||
kind: "Success",
|
||||
url,
|
||||
title: "Example",
|
||||
});
|
||||
expect(states.at(-1)?.zoomFactor).toBe(1.25);
|
||||
|
||||
const replacementSetZoomFactor = vi.fn();
|
||||
fromId.mockReturnValue({
|
||||
id: 43,
|
||||
isDestroyed: () => false,
|
||||
getType: () => "webview",
|
||||
getURL: () => url,
|
||||
getTitle: () => "Example",
|
||||
isLoading: () => false,
|
||||
getZoomFactor: () => 1,
|
||||
setZoomFactor: replacementSetZoomFactor,
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
ipc: { on: vi.fn(), off: vi.fn() },
|
||||
send: webviewSend,
|
||||
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
debugger: {
|
||||
isAttached: () => false,
|
||||
attach: vi.fn(),
|
||||
sendCommand: vi.fn(async () => undefined),
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
},
|
||||
} as never);
|
||||
|
||||
yield* manager.registerWebview("tab_zoom", 43);
|
||||
|
||||
expect(replacementSetZoomFactor).toHaveBeenCalledWith(1.25);
|
||||
expect(states.at(-1)?.zoomFactor).toBe(1.25);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("keeps a main-frame load failure visible until a retry starts", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
const url = "http://localhost:5733/";
|
||||
let loading = false;
|
||||
const listeners = new Map<string, (...args: unknown[]) => void>();
|
||||
fromId.mockReturnValue({
|
||||
id: 42,
|
||||
isDestroyed: () => false,
|
||||
getType: () => "webview",
|
||||
getURL: () => url,
|
||||
getTitle: () => "localhost:5733",
|
||||
isLoading: () => loading,
|
||||
getZoomFactor: () => 1,
|
||||
setZoomFactor: vi.fn(),
|
||||
on: vi.fn((event: string, listener: (...args: unknown[]) => void) => {
|
||||
listeners.set(event, listener);
|
||||
}),
|
||||
off: vi.fn(),
|
||||
ipc: { on: vi.fn(), off: vi.fn() },
|
||||
send: webviewSend,
|
||||
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
debugger: {
|
||||
isAttached: () => false,
|
||||
attach: vi.fn(),
|
||||
sendCommand: vi.fn(async () => undefined),
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
},
|
||||
} as never);
|
||||
const statuses: PreviewManager.PreviewNavStatus[] = [];
|
||||
|
||||
yield* manager.subscribeStateChanges((_tabId, state) =>
|
||||
Effect.sync(() => {
|
||||
statuses.push(state.navStatus);
|
||||
}),
|
||||
);
|
||||
yield* manager.createTab("tab_failed");
|
||||
yield* manager.registerWebview("tab_failed", 42);
|
||||
|
||||
listeners.get("did-fail-load")?.(
|
||||
{},
|
||||
-105,
|
||||
"ERR_NAME_NOT_RESOLVED",
|
||||
"https://missing-frame.example/",
|
||||
false,
|
||||
);
|
||||
yield* Effect.yieldNow;
|
||||
expect(statuses.at(-1)?.kind).toBe("Success");
|
||||
|
||||
loading = true;
|
||||
listeners.get("did-start-loading")?.();
|
||||
yield* Effect.yieldNow;
|
||||
expect(statuses.at(-1)?.kind).toBe("Loading");
|
||||
|
||||
loading = false;
|
||||
listeners.get("did-fail-load")?.({}, -102, "ERR_CONNECTION_REFUSED", url, true);
|
||||
listeners.get("did-stop-loading")?.();
|
||||
listeners.get("page-title-updated")?.();
|
||||
yield* Effect.yieldNow;
|
||||
expect(statuses.at(-1)).toEqual({
|
||||
kind: "LoadFailed",
|
||||
url,
|
||||
title: "localhost:5733",
|
||||
code: -102,
|
||||
description: "ERR_CONNECTION_REFUSED",
|
||||
});
|
||||
|
||||
loading = true;
|
||||
listeners.get("did-start-loading")?.();
|
||||
yield* Effect.yieldNow;
|
||||
expect(statuses.at(-1)?.kind).toBe("Loading");
|
||||
|
||||
loading = false;
|
||||
listeners.get("did-stop-loading")?.();
|
||||
yield* Effect.yieldNow;
|
||||
expect(statuses.at(-1)?.kind).toBe("Success");
|
||||
|
||||
listeners.get("did-fail-load")?.({}, -102, "ERR_CONNECTION_REFUSED", url, true);
|
||||
yield* Effect.yieldNow;
|
||||
expect(statuses.at(-1)?.kind).toBe("LoadFailed");
|
||||
|
||||
listeners.get("did-navigate")?.();
|
||||
yield* Effect.yieldNow;
|
||||
expect(statuses.at(-1)?.kind).toBe("Success");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("captures a PNG screenshot into browser artifacts", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
@@ -716,178 +511,6 @@ describe("PreviewManager", () => {
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("types in background webviews and enables native key input", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
let failKeyDown = false;
|
||||
let humanInput: ((_event: unknown, signal: unknown) => void) | undefined;
|
||||
const sendCommand = vi.fn(async (method: string, params?: Record<string, unknown>) => {
|
||||
if (
|
||||
failKeyDown &&
|
||||
method === "Input.dispatchKeyEvent" &&
|
||||
(params?.["type"] === "keyDown" || params?.["type"] === "rawKeyDown")
|
||||
) {
|
||||
throw new Error("key dispatch failed");
|
||||
}
|
||||
if (
|
||||
method === "Input.dispatchKeyEvent" &&
|
||||
(params?.["type"] === "keyDown" || params?.["type"] === "rawKeyDown")
|
||||
) {
|
||||
humanInput?.(
|
||||
{},
|
||||
{
|
||||
kind: "key",
|
||||
key: params["key"],
|
||||
code: params["code"] ?? "Digit1",
|
||||
},
|
||||
);
|
||||
}
|
||||
return method === "Runtime.evaluate" ? { result: { value: { ok: true } } } : undefined;
|
||||
});
|
||||
const restoreFocus = vi.fn();
|
||||
const focus = vi.fn();
|
||||
getFocusedWebContents.mockReturnValue({
|
||||
id: 7,
|
||||
isDestroyed: () => false,
|
||||
focus: restoreFocus,
|
||||
} as never);
|
||||
fromId.mockReturnValue({
|
||||
id: 42,
|
||||
isDestroyed: () => false,
|
||||
getType: () => "webview",
|
||||
getURL: () => "https://example.com",
|
||||
getTitle: () => "Example",
|
||||
isLoading: () => false,
|
||||
isDevToolsOpened: () => false,
|
||||
focus,
|
||||
getZoomFactor: () => 1,
|
||||
setZoomFactor: vi.fn(),
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
ipc: {
|
||||
on: vi.fn((channel: string, listener: typeof humanInput) => {
|
||||
if (channel === "preview:human-input") humanInput = listener;
|
||||
}),
|
||||
off: vi.fn(),
|
||||
},
|
||||
send: webviewSend,
|
||||
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
debugger: {
|
||||
isAttached: () => false,
|
||||
attach: vi.fn(),
|
||||
sendCommand,
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
},
|
||||
} as never);
|
||||
|
||||
yield* manager.createTab("tab_input");
|
||||
yield* manager.registerWebview("tab_input", 42);
|
||||
yield* manager.automationType("tab_input", { text: "hello", clear: true });
|
||||
yield* manager.automationType("tab_input", { text: "", clear: true });
|
||||
yield* manager.automationPress("tab_input", { key: "x" });
|
||||
|
||||
const calls = sendCommand.mock.calls;
|
||||
const methods = calls.map(([method]) => method);
|
||||
const enableIndex = methods.indexOf("Input.setIgnoreInputEvents");
|
||||
const focusOnIndex = calls.findIndex(
|
||||
([method, params]) =>
|
||||
method === "Emulation.setFocusEmulationEnabled" && params?.["enabled"] === true,
|
||||
);
|
||||
const keyDownIndex = calls.findIndex(
|
||||
([method, params]) =>
|
||||
method === "Input.dispatchKeyEvent" && params?.["type"] === "keyDown",
|
||||
);
|
||||
const keyUpIndex = calls.findIndex(
|
||||
([method, params]) => method === "Input.dispatchKeyEvent" && params?.["type"] === "keyUp",
|
||||
);
|
||||
const focusOffIndex = calls.findIndex(
|
||||
([method, params]) =>
|
||||
method === "Emulation.setFocusEmulationEnabled" && params?.["enabled"] === false,
|
||||
);
|
||||
const typeEvaluation = sendCommand.mock.calls.find(
|
||||
([method, params]) =>
|
||||
method === "Runtime.evaluate" &&
|
||||
typeof params === "object" &&
|
||||
params !== null &&
|
||||
"expression" in params &&
|
||||
typeof params.expression === "string" &&
|
||||
params.expression.includes('document.execCommand("insertText"'),
|
||||
);
|
||||
expect(typeEvaluation).toBeDefined();
|
||||
const clearOnlyEvaluation = sendCommand.mock.calls.find(
|
||||
([method, params]) =>
|
||||
method === "Runtime.evaluate" &&
|
||||
typeof params === "object" &&
|
||||
params !== null &&
|
||||
"expression" in params &&
|
||||
typeof params.expression === "string" &&
|
||||
params.expression.includes('const text = ""') &&
|
||||
params.expression.includes("Object.getOwnPropertyDescriptor"),
|
||||
);
|
||||
expect(clearOnlyEvaluation).toBeDefined();
|
||||
expect(methods).not.toContain("Input.insertText");
|
||||
expect(enableIndex).toBeGreaterThanOrEqual(0);
|
||||
expect(focus).toHaveBeenCalledOnce();
|
||||
expect(restoreFocus).toHaveBeenCalledOnce();
|
||||
expect(methods).toContain("Page.bringToFront");
|
||||
expect(enableIndex).toBeLessThan(focusOnIndex);
|
||||
expect(focusOnIndex).toBeLessThan(keyDownIndex);
|
||||
expect(keyDownIndex).toBeLessThan(keyUpIndex);
|
||||
expect(keyUpIndex).toBeLessThan(focusOffIndex);
|
||||
expect(
|
||||
calls.filter(
|
||||
([method, params]) =>
|
||||
method === "Input.dispatchKeyEvent" && params?.["type"] === "keyUp",
|
||||
),
|
||||
).toHaveLength(1);
|
||||
expect(sendCommand).toHaveBeenCalledWith("Input.setIgnoreInputEvents", { ignore: false });
|
||||
|
||||
sendCommand.mockClear();
|
||||
failKeyDown = true;
|
||||
const failedPress = yield* Effect.exit(manager.automationPress("tab_input", { key: "y" }));
|
||||
|
||||
expect(Exit.isFailure(failedPress)).toBe(true);
|
||||
expect(sendCommand).toHaveBeenCalledWith("Input.dispatchKeyEvent", {
|
||||
type: "keyUp",
|
||||
key: "y",
|
||||
code: "KeyY",
|
||||
modifiers: 0,
|
||||
windowsVirtualKeyCode: 89,
|
||||
location: 0,
|
||||
isKeypad: false,
|
||||
});
|
||||
expect(sendCommand).toHaveBeenCalledWith("Emulation.setFocusEmulationEnabled", {
|
||||
enabled: false,
|
||||
});
|
||||
expect(restoreFocus).toHaveBeenCalledTimes(2);
|
||||
expect(
|
||||
sendCommand.mock.calls.filter(
|
||||
([method, params]) =>
|
||||
method === "Input.dispatchKeyEvent" && params?.["type"] === "keyUp",
|
||||
),
|
||||
).toHaveLength(1);
|
||||
|
||||
sendCommand.mockClear();
|
||||
failKeyDown = false;
|
||||
yield* manager.automationPress("tab_input", { key: "!" });
|
||||
expect(sendCommand).toHaveBeenCalledWith("Input.dispatchKeyEvent", {
|
||||
type: "keyDown",
|
||||
key: "!",
|
||||
code: "Digit1",
|
||||
modifiers: 0,
|
||||
windowsVirtualKeyCode: 49,
|
||||
location: 0,
|
||||
isKeypad: false,
|
||||
text: "!",
|
||||
unmodifiedText: "!",
|
||||
});
|
||||
expect(restoreFocus).toHaveBeenCalledTimes(3);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("still interrupts agent control for a different human pointer event", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
|
||||
@@ -25,7 +25,6 @@ import type {
|
||||
PreviewAutomationTypeInput,
|
||||
PreviewAutomationWaitForInput,
|
||||
} from "@t3tools/contracts";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import { normalizePreviewUrl } from "@t3tools/shared/preview";
|
||||
import {
|
||||
type BrowserWindow,
|
||||
@@ -63,7 +62,6 @@ import {
|
||||
} from "./GuestProtocol.ts";
|
||||
import { isPreviewAnnotationPayload } from "./PickedElementPayload.ts";
|
||||
import { playwrightInjectedRuntimeInstallExpression } from "./PlaywrightInjectedRuntime.ts";
|
||||
import { makePreviewAutomationKeySequence } from "./PreviewKeyboard.ts";
|
||||
|
||||
export type PreviewNavStatus =
|
||||
| { kind: "Idle" }
|
||||
@@ -380,7 +378,6 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
artifactDirectory: string,
|
||||
) {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const hostPlatform = yield* HostProcessPlatform;
|
||||
const path = yield* Path.Path;
|
||||
const parentScope = yield* Scope.Scope;
|
||||
const context = yield* Effect.context<never>();
|
||||
@@ -857,24 +854,11 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
commandParams?: Record<string, unknown>,
|
||||
) => Effect.Effect<unknown, PreviewManagerError>;
|
||||
|
||||
const prepareAutomationInput = Effect.fn("PreviewManager.prepareAutomationInput")(function* (
|
||||
send: SendCommand,
|
||||
enableRuntime: boolean,
|
||||
) {
|
||||
yield* Effect.all(
|
||||
[
|
||||
...(enableRuntime ? [send("Runtime.enable")] : []),
|
||||
send("Input.setIgnoreInputEvents", { ignore: false }),
|
||||
],
|
||||
{ concurrency: 2, discard: true },
|
||||
);
|
||||
});
|
||||
|
||||
const withControlSession = Effect.fn("PreviewManager.withControlSession")(function* <A>(
|
||||
tabId: string,
|
||||
wc: Electron.WebContents,
|
||||
action: string,
|
||||
use: (send: SendCommand, sendCleanup: SendCommand) => Effect.Effect<A, PreviewManagerError>,
|
||||
use: (send: SendCommand) => Effect.Effect<A, PreviewManagerError>,
|
||||
) {
|
||||
const sequence = yield* nextCounter(actionSequenceRef);
|
||||
const startedAt = yield* currentIso;
|
||||
@@ -915,22 +899,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
return result;
|
||||
},
|
||||
);
|
||||
// Cleanup commands must still run after human input invalidates the action's
|
||||
// control epoch. Otherwise a partially dispatched input can leave Chromium
|
||||
// with a held key or focus emulation enabled for subsequent actions.
|
||||
const sendCleanup: SendCommand = Effect.fn("PreviewManager.sendCleanupCommand")(
|
||||
function* (method, commandParams) {
|
||||
return yield* attemptPromise(
|
||||
{
|
||||
operation: `${action}.cleanup.${method}`,
|
||||
tabId,
|
||||
webContentsId: wc.id,
|
||||
},
|
||||
() => wc.debugger.sendCommand(method, commandParams),
|
||||
);
|
||||
},
|
||||
);
|
||||
return yield* use(send, sendCleanup);
|
||||
return yield* use(send);
|
||||
});
|
||||
const finalize = Effect.fn("PreviewManager.finalizeControlAction")(function* (
|
||||
exit: Exit.Exit<A, PreviewManagerError>,
|
||||
@@ -1122,62 +1091,22 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
wc: Electron.WebContents,
|
||||
) {
|
||||
const scope = yield* Scope.fork(parentScope, "sequential");
|
||||
const syncState = Effect.fn("PreviewManager.syncWebContentsState")(function* (
|
||||
preserveLoadFailure: boolean,
|
||||
) {
|
||||
const syncState = Effect.fn("PreviewManager.syncWebContentsState")(function* () {
|
||||
if (wc.isDestroyed()) return;
|
||||
const zoomFactor = yield* attempt(
|
||||
{ operation: "syncWebContentsState.getZoomFactor", tabId, webContentsId: wc.id },
|
||||
() => wc.getZoomFactor(),
|
||||
).pipe(Effect.option);
|
||||
const computedNavStatus = computeNavStatus(wc);
|
||||
const canGoBack = wc.navigationHistory.canGoBack();
|
||||
const canGoForward = wc.navigationHistory.canGoForward();
|
||||
const updatedAt = yield* currentIso;
|
||||
const next = yield* SynchronizedRef.modify(tabsRef, (tabs) => {
|
||||
const current = tabs.get(tabId);
|
||||
if (!current) return [Option.none<PreviewTabState>(), tabs] as const;
|
||||
// Electron emits did-stop-loading after did-fail-load. At that point the
|
||||
// failed guest is no longer "loading", but it has not successfully
|
||||
// navigated anywhere. Keep the failure until a new load actually starts.
|
||||
const navStatus =
|
||||
preserveLoadFailure &&
|
||||
current.navStatus.kind === "LoadFailed" &&
|
||||
computedNavStatus.kind === "Success"
|
||||
? current.navStatus
|
||||
: computedNavStatus;
|
||||
const state: PreviewTabState = {
|
||||
...current,
|
||||
navStatus,
|
||||
canGoBack,
|
||||
canGoForward,
|
||||
...(Option.isSome(zoomFactor) ? { zoomFactor: zoomFactor.value } : {}),
|
||||
updatedAt,
|
||||
};
|
||||
return [
|
||||
Option.some(state),
|
||||
replaceMap(tabs, (copy) => {
|
||||
copy.set(tabId, state);
|
||||
}),
|
||||
] as const;
|
||||
yield* update(tabId, {
|
||||
navStatus: computeNavStatus(wc),
|
||||
canGoBack: wc.navigationHistory.canGoBack(),
|
||||
canGoForward: wc.navigationHistory.canGoForward(),
|
||||
});
|
||||
if (Option.isSome(next)) yield* emit(tabId, next.value);
|
||||
});
|
||||
const sync = () => runFork(syncState(true));
|
||||
const syncNavigation = () => runFork(syncState(false));
|
||||
const failed = (
|
||||
_event: Event,
|
||||
code: number,
|
||||
description: string,
|
||||
validatedUrl: string,
|
||||
isMainFrame: boolean,
|
||||
): void => {
|
||||
if (code === -3 || !isMainFrame) return;
|
||||
const sync = () => runFork(syncState());
|
||||
const failed = (_event: Event, code: number, description: string): void => {
|
||||
if (code === -3) return;
|
||||
runFork(
|
||||
update(tabId, {
|
||||
navStatus: {
|
||||
kind: "LoadFailed",
|
||||
url: validatedUrl || wc.getURL(),
|
||||
url: wc.getURL(),
|
||||
title: wc.getTitle(),
|
||||
code,
|
||||
description,
|
||||
@@ -1232,8 +1161,8 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
yield* Scope.addFinalizer(
|
||||
scope,
|
||||
attempt({ operation: "detachListeners", tabId, webContentsId: wc.id }, () => {
|
||||
wc.off("did-navigate", syncNavigation);
|
||||
wc.off("did-navigate-in-page", syncNavigation);
|
||||
wc.off("did-navigate", sync);
|
||||
wc.off("did-navigate-in-page", sync);
|
||||
wc.off("page-title-updated", sync);
|
||||
wc.off("did-start-loading", sync);
|
||||
wc.off("did-stop-loading", sync);
|
||||
@@ -1244,8 +1173,8 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
);
|
||||
const install = Effect.fn("PreviewManager.installWebContentsListeners")(function* () {
|
||||
yield* attempt({ operation: "attachListeners", tabId, webContentsId: wc.id }, () => {
|
||||
wc.on("did-navigate", syncNavigation);
|
||||
wc.on("did-navigate-in-page", syncNavigation);
|
||||
wc.on("did-navigate", sync);
|
||||
wc.on("did-navigate-in-page", sync);
|
||||
wc.on("page-title-updated", sync);
|
||||
wc.on("did-start-loading", sync);
|
||||
wc.on("did-stop-loading", sync);
|
||||
@@ -1351,40 +1280,21 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
const attached = yield* Ref.get(attachedRef);
|
||||
const annotationTheme = yield* Ref.get(annotationThemeRef);
|
||||
if (tab.webContentsId === webContentsId && attached.has(webContentsId)) {
|
||||
const zoomFactor = yield* attempt(
|
||||
{ operation: "registerWebview.getZoomFactor", tabId, webContentsId },
|
||||
() => wc.getZoomFactor(),
|
||||
);
|
||||
yield* update(tabId, { zoomFactor });
|
||||
yield* attempt({ operation: "registerWebview.sendTheme", tabId, webContentsId }, () =>
|
||||
wc.send(ANNOTATION_THEME_CHANNEL, annotationTheme),
|
||||
);
|
||||
return;
|
||||
}
|
||||
const replacedWebContentsId =
|
||||
tab.webContentsId != null && tab.webContentsId !== webContentsId ? tab.webContentsId : null;
|
||||
if (replacedWebContentsId !== null) {
|
||||
if (tab.webContentsId != null && tab.webContentsId !== webContentsId) {
|
||||
yield* Effect.all(
|
||||
[
|
||||
detachControlSession(replacedWebContentsId),
|
||||
detachListeners(replacedWebContentsId),
|
||||
detachControlSession(tab.webContentsId),
|
||||
detachListeners(tab.webContentsId),
|
||||
cancelPickElement(tabId),
|
||||
],
|
||||
{ concurrency: 3, discard: true },
|
||||
);
|
||||
}
|
||||
const zoomFactor =
|
||||
replacedWebContentsId !== null
|
||||
? yield* attempt(
|
||||
{ operation: "registerWebview.restoreZoomFactor", tabId, webContentsId },
|
||||
() => {
|
||||
wc.setZoomFactor(tab.zoomFactor);
|
||||
return tab.zoomFactor;
|
||||
},
|
||||
)
|
||||
: yield* attempt({ operation: "registerWebview.getZoomFactor", tabId, webContentsId }, () =>
|
||||
wc.getZoomFactor(),
|
||||
);
|
||||
yield* attachListeners(tabId, wc);
|
||||
runFork(ensureControlSession(wc).pipe(Effect.ignore));
|
||||
const registeredAt = yield* currentIso;
|
||||
@@ -1403,7 +1313,6 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
navStatus: pendingUrl === null ? computeNavStatus(wc) : current.navStatus,
|
||||
canGoBack: wc.navigationHistory.canGoBack(),
|
||||
canGoForward: wc.navigationHistory.canGoForward(),
|
||||
zoomFactor,
|
||||
updatedAt: registeredAt,
|
||||
};
|
||||
return [
|
||||
@@ -1421,6 +1330,11 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
}
|
||||
const { state: registered, pendingUrl } = registration.value;
|
||||
yield* emit(tabId, registered);
|
||||
if (Math.abs(registered.zoomFactor - DEFAULT_ZOOM_FACTOR) > ZOOM_EPSILON) {
|
||||
yield* attempt({ operation: "registerWebview.restoreZoom", tabId, webContentsId }, () =>
|
||||
wc.setZoomFactor(registered.zoomFactor),
|
||||
).pipe(Effect.ignore);
|
||||
}
|
||||
yield* attempt({ operation: "registerWebview.sendTheme", tabId, webContentsId }, () =>
|
||||
wc.send(ANNOTATION_THEME_CHANNEL, annotationTheme),
|
||||
);
|
||||
@@ -2032,7 +1946,10 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
input: PreviewAutomationClickInput,
|
||||
send: SendCommand,
|
||||
) {
|
||||
yield* prepareAutomationInput(send, true);
|
||||
yield* Effect.all(
|
||||
[send("Runtime.enable"), send("Input.setIgnoreInputEvents", { ignore: false })],
|
||||
{ concurrency: 2, discard: true },
|
||||
);
|
||||
const point = yield* resolveClickPoint(tabId, send, input);
|
||||
const viewport = yield* evaluateWithDebugger<{ width: number; height: number }>(
|
||||
tabId,
|
||||
@@ -2094,7 +2011,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
);
|
||||
});
|
||||
|
||||
const typeIntoAutomationTarget = Effect.fn("PreviewManager.typeIntoAutomationTarget")(function* (
|
||||
const focusAutomationTarget = Effect.fn("PreviewManager.focusAutomationTarget")(function* (
|
||||
tabId: string,
|
||||
send: SendCommand,
|
||||
input: PreviewAutomationTypeInput,
|
||||
@@ -2104,15 +2021,8 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
const locatorJson = locator
|
||||
? yield* encodeJson({ operation: "automationType.encodeLocator", tabId }, locator)
|
||||
: null;
|
||||
const textJson = yield* encodeJson(
|
||||
{ operation: "automationType.encodeText", tabId },
|
||||
input.text,
|
||||
);
|
||||
const result = yield* evaluateWithDebugger<
|
||||
| { ok: true }
|
||||
| { invalidSelector: true; message: string }
|
||||
| { notEditable: true }
|
||||
| { notFound: true }
|
||||
{ ok: true } | { invalidSelector: true; message: string } | { notFound: true }
|
||||
>(
|
||||
tabId,
|
||||
send,
|
||||
@@ -2120,54 +2030,12 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
try {
|
||||
const element = ${locatorJson ? `(() => { const injected = globalThis.__t3PlaywrightInjected; return injected.querySelector(injected.parseSelector(${locatorJson}), document, true); })()` : "document.activeElement"};
|
||||
if (!element) return { notFound: true };
|
||||
const textControl =
|
||||
element instanceof HTMLTextAreaElement ||
|
||||
(element instanceof HTMLInputElement &&
|
||||
!new Set(["button", "checkbox", "color", "file", "hidden", "image", "radio", "range", "reset", "submit"]).has(element.type));
|
||||
const editable = textControl || element.isContentEditable;
|
||||
if (!editable || element.disabled || element.readOnly) return { notEditable: true };
|
||||
element.focus();
|
||||
if (document.activeElement !== element) return { notEditable: true };
|
||||
const clear = ${input.clear ?? false};
|
||||
if (clear) {
|
||||
if (textControl) {
|
||||
element.select();
|
||||
} else {
|
||||
const range = document.createRange();
|
||||
range.selectNodeContents(element);
|
||||
const selection = document.getSelection();
|
||||
selection?.removeAllRanges();
|
||||
selection?.addRange(range);
|
||||
}
|
||||
if (${input.clear ?? false}) {
|
||||
if ("value" in element) element.value = "";
|
||||
else if (element.isContentEditable) element.textContent = "";
|
||||
element.dispatchEvent(new InputEvent("input", { bubbles: true, inputType: "deleteContentBackward" }));
|
||||
}
|
||||
const text = ${textJson};
|
||||
let inserted = true;
|
||||
if (text.length > 0) {
|
||||
inserted = document.execCommand("insertText", false, text);
|
||||
} else if (clear) {
|
||||
document.execCommand("delete", false);
|
||||
const cleared = textControl
|
||||
? element.value.length === 0
|
||||
: (element.textContent ?? "").length === 0;
|
||||
if (!cleared) {
|
||||
if (textControl) {
|
||||
const prototype = element instanceof HTMLTextAreaElement
|
||||
? HTMLTextAreaElement.prototype
|
||||
: HTMLInputElement.prototype;
|
||||
const valueSetter = Object.getOwnPropertyDescriptor(prototype, "value")?.set;
|
||||
if (valueSetter) valueSetter.call(element, "");
|
||||
else element.value = "";
|
||||
} else {
|
||||
element.replaceChildren();
|
||||
}
|
||||
element.dispatchEvent(new InputEvent("input", {
|
||||
bubbles: true,
|
||||
inputType: "deleteContentBackward",
|
||||
}));
|
||||
}
|
||||
}
|
||||
if (!inserted) return { notEditable: true };
|
||||
element.dispatchEvent(new Event("change", { bubbles: true }));
|
||||
return { ok: true };
|
||||
} catch (error) {
|
||||
return { invalidSelector: true, message: String(error) };
|
||||
@@ -2191,12 +2059,6 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
...automationSelectorDiagnostics(input),
|
||||
});
|
||||
}
|
||||
if ("notEditable" in result) {
|
||||
return yield* new PreviewAutomationTargetNotEditableError({
|
||||
tabId,
|
||||
...automationSelectorDiagnostics(input),
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
const performAutomationType = Effect.fn("PreviewManager.performAutomationType")(function* (
|
||||
@@ -2204,10 +2066,23 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
input: PreviewAutomationTypeInput,
|
||||
send: SendCommand,
|
||||
) {
|
||||
// CDP Input.insertText silently drops text until Electron has activated a hidden
|
||||
// guest WebContents with a pointer event. Editing in the page runtime keeps
|
||||
// background automation deterministic without stealing foreground app focus.
|
||||
yield* typeIntoAutomationTarget(tabId, send, input);
|
||||
yield* send("Runtime.enable");
|
||||
yield* focusAutomationTarget(tabId, send, input);
|
||||
yield* send("Input.insertText", { text: input.text });
|
||||
const textJson = yield* encodeJson(
|
||||
{ operation: "automationType.encodeText", tabId },
|
||||
input.text,
|
||||
);
|
||||
yield* evaluateWithDebugger(
|
||||
tabId,
|
||||
send,
|
||||
`(() => {
|
||||
const element = document.activeElement;
|
||||
element?.dispatchEvent(new InputEvent("input", { bubbles: true, inputType: "insertText", data: ${textJson} }));
|
||||
element?.dispatchEvent(new Event("change", { bubbles: true }));
|
||||
})()`,
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
const automationType = Effect.fn("PreviewManager.automationType")(function* (
|
||||
@@ -2222,54 +2097,32 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
|
||||
const performAutomationPress = Effect.fn("PreviewManager.performAutomationPress")(function* (
|
||||
tabId: string,
|
||||
wc: Electron.WebContents,
|
||||
input: PreviewAutomationPressInput,
|
||||
send: SendCommand,
|
||||
sendCleanup: SendCommand,
|
||||
) {
|
||||
yield* prepareAutomationInput(send, false);
|
||||
const keySequence = makePreviewAutomationKeySequence(input, {
|
||||
isMac: hostPlatform === "darwin",
|
||||
});
|
||||
const previouslyFocused = yield* attempt(
|
||||
{ operation: "automationPress.getFocusedWebContents", tabId, webContentsId: wc.id },
|
||||
() => webContents.getFocusedWebContents(),
|
||||
);
|
||||
let keyDownAttempted = false;
|
||||
const releaseInput = Effect.gen(function* () {
|
||||
if (keyDownAttempted) {
|
||||
yield* sendCleanup("Input.dispatchKeyEvent", keySequence.keyUp).pipe(Effect.ignore);
|
||||
const modifiers = (input.modifiers ?? []).reduce((value, modifier) => {
|
||||
switch (modifier) {
|
||||
case "Alt":
|
||||
return value | 1;
|
||||
case "Control":
|
||||
return value | 2;
|
||||
case "Meta":
|
||||
return value | 4;
|
||||
case "Shift":
|
||||
return value | 8;
|
||||
}
|
||||
yield* sendCleanup("Emulation.setFocusEmulationEnabled", { enabled: false }).pipe(
|
||||
Effect.ignore,
|
||||
);
|
||||
if (previouslyFocused && previouslyFocused.id !== wc.id && !previouslyFocused.isDestroyed()) {
|
||||
yield* attempt(
|
||||
{
|
||||
operation: "automationPress.restoreFocusedWebContents",
|
||||
tabId,
|
||||
webContentsId: previouslyFocused.id,
|
||||
},
|
||||
() => previouslyFocused.focus(),
|
||||
).pipe(Effect.ignore);
|
||||
}
|
||||
});
|
||||
|
||||
// Focus the guest WebContents itself, not its containing BrowserWindow. This
|
||||
// activates native keyboard behavior for hidden/background previews without
|
||||
// changing which thread is mounted in the UI. Restore the previous renderer
|
||||
// after dispatch so automation never leaves the app's input focus behind.
|
||||
yield* Effect.gen(function* () {
|
||||
yield* attempt(
|
||||
{ operation: "automationPress.focusWebContents", tabId, webContentsId: wc.id },
|
||||
() => wc.focus(),
|
||||
);
|
||||
yield* send("Page.bringToFront");
|
||||
yield* send("Emulation.setFocusEmulationEnabled", { enabled: true });
|
||||
yield* expectAgentInput(tabId, keySequence.signal);
|
||||
keyDownAttempted = true;
|
||||
yield* send("Input.dispatchKeyEvent", keySequence.keyDown);
|
||||
}).pipe(Effect.ensuring(releaseInput));
|
||||
}, 0);
|
||||
const key = input.key;
|
||||
const text = key.length === 1 ? key : undefined;
|
||||
const params = {
|
||||
key,
|
||||
code: key.length === 1 ? `Key${key.toUpperCase()}` : key,
|
||||
modifiers,
|
||||
...(text ? { text, unmodifiedText: text } : {}),
|
||||
};
|
||||
yield* expectAgentInput(tabId, { kind: "key", key, code: params.code });
|
||||
yield* send("Input.dispatchKeyEvent", { type: "keyDown", ...params });
|
||||
yield* send("Input.dispatchKeyEvent", { type: "keyUp", ...params });
|
||||
});
|
||||
|
||||
const automationPress = Effect.fn("PreviewManager.automationPress")(function* (
|
||||
@@ -2277,8 +2130,8 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
input: PreviewAutomationPressInput,
|
||||
) {
|
||||
const wc = yield* requireWebContents(tabId);
|
||||
yield* withControlSession(tabId, wc, "press", (send, sendCleanup) =>
|
||||
performAutomationPress(tabId, wc, input, send, sendCleanup),
|
||||
yield* withControlSession(tabId, wc, "press", (send) =>
|
||||
performAutomationPress(tabId, input, send),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -2676,20 +2529,6 @@ export class PreviewAutomationTargetNotFoundError extends Schema.TaggedErrorClas
|
||||
}
|
||||
}
|
||||
|
||||
export class PreviewAutomationTargetNotEditableError extends Schema.TaggedErrorClass<PreviewAutomationTargetNotEditableError>()(
|
||||
"PreviewAutomationTargetNotEditableError",
|
||||
{
|
||||
tabId: Schema.String,
|
||||
selectorKind: PreviewAutomationSelectorKind,
|
||||
selectorLength: Schema.optionalKey(Schema.Number),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
const target = previewAutomationTargetLabel(this.selectorKind, this.selectorLength);
|
||||
return `Preview automation type found ${target}, but it is not editable in tab ${this.tabId}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class PreviewAutomationCoordinatesOutsideViewportError extends Schema.TaggedErrorClass<PreviewAutomationCoordinatesOutsideViewportError>()(
|
||||
"PreviewAutomationCoordinatesOutsideViewportError",
|
||||
{
|
||||
@@ -2792,7 +2631,6 @@ export const PreviewManagerError = Schema.Union([
|
||||
PreviewAutomationDebuggerAttachedError,
|
||||
PreviewAutomationEvaluationError,
|
||||
PreviewAutomationTargetNotFoundError,
|
||||
PreviewAutomationTargetNotEditableError,
|
||||
PreviewAutomationCoordinatesOutsideViewportError,
|
||||
PreviewAutomationInvalidSelectorError,
|
||||
PreviewAutomationResultTooLargeError,
|
||||
|
||||
@@ -1,97 +0,0 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { makePreviewAutomationKeySequence } from "./PreviewKeyboard.ts";
|
||||
|
||||
describe("preview keyboard packets", () => {
|
||||
it("includes the Chromium virtual key code and Enter text", () => {
|
||||
expect(makePreviewAutomationKeySequence({ key: "Enter" })).toEqual({
|
||||
keyDown: {
|
||||
type: "keyDown",
|
||||
key: "Enter",
|
||||
code: "Enter",
|
||||
modifiers: 0,
|
||||
windowsVirtualKeyCode: 13,
|
||||
location: 0,
|
||||
isKeypad: false,
|
||||
text: "\r",
|
||||
unmodifiedText: "\r",
|
||||
},
|
||||
keyUp: {
|
||||
type: "keyUp",
|
||||
key: "Enter",
|
||||
code: "Enter",
|
||||
modifiers: 0,
|
||||
windowsVirtualKeyCode: 13,
|
||||
location: 0,
|
||||
isKeypad: false,
|
||||
},
|
||||
signal: { kind: "key", key: "Enter", code: "Enter" },
|
||||
});
|
||||
});
|
||||
|
||||
it("dispatches printable keys as text key-down events", () => {
|
||||
const sequence = makePreviewAutomationKeySequence({ key: "z" });
|
||||
expect(sequence.keyDown).toMatchObject({
|
||||
type: "keyDown",
|
||||
key: "z",
|
||||
code: "KeyZ",
|
||||
windowsVirtualKeyCode: 90,
|
||||
text: "z",
|
||||
});
|
||||
expect(sequence.keyUp).not.toHaveProperty("text");
|
||||
});
|
||||
|
||||
it("suppresses text and uses raw key-down for shortcuts", () => {
|
||||
expect(
|
||||
makePreviewAutomationKeySequence({ key: "a", modifiers: ["Meta"] }, { isMac: true }).keyDown,
|
||||
).toEqual({
|
||||
type: "rawKeyDown",
|
||||
key: "a",
|
||||
code: "KeyA",
|
||||
modifiers: 4,
|
||||
windowsVirtualKeyCode: 65,
|
||||
location: 0,
|
||||
isKeypad: false,
|
||||
commands: ["selectAll"],
|
||||
});
|
||||
});
|
||||
|
||||
it("maps common macOS editing shortcuts without changing other platforms", () => {
|
||||
expect(
|
||||
makePreviewAutomationKeySequence({ key: "z", modifiers: ["Shift", "Meta"] }, { isMac: true })
|
||||
.keyDown.commands,
|
||||
).toEqual(["redo"]);
|
||||
expect(
|
||||
makePreviewAutomationKeySequence({ key: "a", modifiers: ["Meta"] }).keyDown,
|
||||
).not.toHaveProperty("commands");
|
||||
});
|
||||
|
||||
it("resolves shifted printable keys to their browser values", () => {
|
||||
const sequence = makePreviewAutomationKeySequence({ key: "1", modifiers: ["Shift"] });
|
||||
expect(sequence.keyDown).toMatchObject({
|
||||
key: "!",
|
||||
code: "Digit1",
|
||||
modifiers: 8,
|
||||
windowsVirtualKeyCode: 49,
|
||||
text: "!",
|
||||
});
|
||||
expect(sequence.signal).toEqual({ kind: "key", key: "!", code: "Digit1" });
|
||||
});
|
||||
|
||||
it("keeps shifted key values while suppressing text for modified chords", () => {
|
||||
const sequence = makePreviewAutomationKeySequence({
|
||||
key: "1",
|
||||
modifiers: ["Control", "Shift"],
|
||||
});
|
||||
expect(sequence.keyDown).toEqual({
|
||||
type: "rawKeyDown",
|
||||
key: "!",
|
||||
code: "Digit1",
|
||||
modifiers: 10,
|
||||
windowsVirtualKeyCode: 49,
|
||||
location: 0,
|
||||
isKeypad: false,
|
||||
});
|
||||
expect(sequence.signal).toEqual({ kind: "key", key: "!", code: "Digit1" });
|
||||
});
|
||||
});
|
||||
@@ -1,203 +0,0 @@
|
||||
import type { PreviewAutomationPressInput } from "@t3tools/contracts";
|
||||
|
||||
interface KeyDefinition {
|
||||
readonly code: string;
|
||||
readonly key: string;
|
||||
readonly keyCode: number;
|
||||
readonly text?: string;
|
||||
readonly location?: number;
|
||||
readonly shiftedKey?: string;
|
||||
}
|
||||
|
||||
export interface PreviewAutomationKeyEvent {
|
||||
readonly [key: string]: unknown;
|
||||
readonly type: "keyDown" | "rawKeyDown" | "keyUp";
|
||||
readonly key: string;
|
||||
readonly code: string;
|
||||
readonly modifiers: number;
|
||||
readonly windowsVirtualKeyCode: number;
|
||||
readonly location: number;
|
||||
readonly isKeypad: boolean;
|
||||
readonly text?: string;
|
||||
readonly unmodifiedText?: string;
|
||||
readonly commands?: ReadonlyArray<string>;
|
||||
}
|
||||
|
||||
export interface PreviewAutomationKeySequence {
|
||||
readonly keyDown: PreviewAutomationKeyEvent;
|
||||
readonly keyUp: PreviewAutomationKeyEvent;
|
||||
readonly signal: {
|
||||
readonly kind: "key";
|
||||
readonly key: string;
|
||||
readonly code: string;
|
||||
};
|
||||
}
|
||||
|
||||
const NAMED_KEYS: Readonly<Record<string, KeyDefinition>> = {
|
||||
Escape: { code: "Escape", key: "Escape", keyCode: 27 },
|
||||
Backspace: { code: "Backspace", key: "Backspace", keyCode: 8 },
|
||||
Tab: { code: "Tab", key: "Tab", keyCode: 9 },
|
||||
Enter: { code: "Enter", key: "Enter", keyCode: 13, text: "\r" },
|
||||
Shift: { code: "ShiftLeft", key: "Shift", keyCode: 16, location: 1 },
|
||||
Control: { code: "ControlLeft", key: "Control", keyCode: 17, location: 1 },
|
||||
Alt: { code: "AltLeft", key: "Alt", keyCode: 18, location: 1 },
|
||||
Meta: { code: "MetaLeft", key: "Meta", keyCode: 91, location: 1 },
|
||||
CapsLock: { code: "CapsLock", key: "CapsLock", keyCode: 20 },
|
||||
Space: { code: "Space", key: " ", keyCode: 32, text: " " },
|
||||
PageUp: { code: "PageUp", key: "PageUp", keyCode: 33 },
|
||||
PageDown: { code: "PageDown", key: "PageDown", keyCode: 34 },
|
||||
End: { code: "End", key: "End", keyCode: 35 },
|
||||
Home: { code: "Home", key: "Home", keyCode: 36 },
|
||||
ArrowLeft: { code: "ArrowLeft", key: "ArrowLeft", keyCode: 37 },
|
||||
ArrowUp: { code: "ArrowUp", key: "ArrowUp", keyCode: 38 },
|
||||
ArrowRight: { code: "ArrowRight", key: "ArrowRight", keyCode: 39 },
|
||||
ArrowDown: { code: "ArrowDown", key: "ArrowDown", keyCode: 40 },
|
||||
Insert: { code: "Insert", key: "Insert", keyCode: 45 },
|
||||
Delete: { code: "Delete", key: "Delete", keyCode: 46 },
|
||||
};
|
||||
|
||||
const PRINTABLE_KEYS: ReadonlyArray<KeyDefinition> = [
|
||||
{ code: "Backquote", key: "`", shiftedKey: "~", keyCode: 192 },
|
||||
{ code: "Digit1", key: "1", shiftedKey: "!", keyCode: 49 },
|
||||
{ code: "Digit2", key: "2", shiftedKey: "@", keyCode: 50 },
|
||||
{ code: "Digit3", key: "3", shiftedKey: "#", keyCode: 51 },
|
||||
{ code: "Digit4", key: "4", shiftedKey: "$", keyCode: 52 },
|
||||
{ code: "Digit5", key: "5", shiftedKey: "%", keyCode: 53 },
|
||||
{ code: "Digit6", key: "6", shiftedKey: "^", keyCode: 54 },
|
||||
{ code: "Digit7", key: "7", shiftedKey: "&", keyCode: 55 },
|
||||
{ code: "Digit8", key: "8", shiftedKey: "*", keyCode: 56 },
|
||||
{ code: "Digit9", key: "9", shiftedKey: "(", keyCode: 57 },
|
||||
{ code: "Digit0", key: "0", shiftedKey: ")", keyCode: 48 },
|
||||
{ code: "Minus", key: "-", shiftedKey: "_", keyCode: 189 },
|
||||
{ code: "Equal", key: "=", shiftedKey: "+", keyCode: 187 },
|
||||
{ code: "Backslash", key: "\\", shiftedKey: "|", keyCode: 220 },
|
||||
{ code: "BracketLeft", key: "[", shiftedKey: "{", keyCode: 219 },
|
||||
{ code: "BracketRight", key: "]", shiftedKey: "}", keyCode: 221 },
|
||||
{ code: "Semicolon", key: ";", shiftedKey: ":", keyCode: 186 },
|
||||
{ code: "Quote", key: "'", shiftedKey: '"', keyCode: 222 },
|
||||
{ code: "Comma", key: ",", shiftedKey: "<", keyCode: 188 },
|
||||
{ code: "Period", key: ".", shiftedKey: ">", keyCode: 190 },
|
||||
{ code: "Slash", key: "/", shiftedKey: "?", keyCode: 191 },
|
||||
];
|
||||
|
||||
/**
|
||||
* Chromium does not infer macOS editing commands from synthetic Meta chords.
|
||||
* Keep the common browser editing/navigation shortcuts explicit so dispatched
|
||||
* key events behave like their physical-key equivalents.
|
||||
*/
|
||||
const MAC_EDITING_COMMANDS: Readonly<Record<string, string>> = {
|
||||
"Meta+Backspace": "deleteToBeginningOfLine",
|
||||
"Meta+ArrowUp": "moveToBeginningOfDocument",
|
||||
"Meta+ArrowDown": "moveToEndOfDocument",
|
||||
"Meta+ArrowLeft": "moveToLeftEndOfLine",
|
||||
"Meta+ArrowRight": "moveToRightEndOfLine",
|
||||
"Shift+Meta+ArrowUp": "moveToBeginningOfDocumentAndModifySelection",
|
||||
"Shift+Meta+ArrowDown": "moveToEndOfDocumentAndModifySelection",
|
||||
"Shift+Meta+ArrowLeft": "moveToLeftEndOfLineAndModifySelection",
|
||||
"Shift+Meta+ArrowRight": "moveToRightEndOfLineAndModifySelection",
|
||||
"Meta+KeyA": "selectAll",
|
||||
"Meta+KeyC": "copy",
|
||||
"Meta+KeyX": "cut",
|
||||
"Meta+KeyV": "paste",
|
||||
"Meta+KeyZ": "undo",
|
||||
"Shift+Meta+KeyZ": "redo",
|
||||
};
|
||||
const SHORTCUT_MODIFIER_ORDER = ["Shift", "Control", "Alt", "Meta"] as const;
|
||||
|
||||
const macEditingCommands = (
|
||||
code: string,
|
||||
modifiers: PreviewAutomationPressInput["modifiers"],
|
||||
): ReadonlyArray<string> => {
|
||||
const shortcut = [
|
||||
...SHORTCUT_MODIFIER_ORDER.filter((modifier) => modifiers?.includes(modifier)),
|
||||
code,
|
||||
].join("+");
|
||||
const command = MAC_EDITING_COMMANDS[shortcut];
|
||||
return command ? [command] : [];
|
||||
};
|
||||
|
||||
const modifierMask = (modifiers: PreviewAutomationPressInput["modifiers"]): number =>
|
||||
(modifiers ?? []).reduce((value, modifier) => {
|
||||
switch (modifier) {
|
||||
case "Alt":
|
||||
return value | 1;
|
||||
case "Control":
|
||||
return value | 2;
|
||||
case "Meta":
|
||||
return value | 4;
|
||||
case "Shift":
|
||||
return value | 8;
|
||||
}
|
||||
}, 0);
|
||||
|
||||
function resolveKeyDefinition(input: PreviewAutomationPressInput): KeyDefinition {
|
||||
const named = NAMED_KEYS[input.key];
|
||||
if (named) return named;
|
||||
|
||||
const functionKey = /^F([1-9]|1[0-2])$/.exec(input.key);
|
||||
if (functionKey) {
|
||||
const number = Number(functionKey[1]);
|
||||
return { code: input.key, key: input.key, keyCode: 111 + number };
|
||||
}
|
||||
|
||||
if (/^[a-z]$/i.test(input.key)) {
|
||||
const upper = input.key.toUpperCase();
|
||||
const shifted = input.modifiers?.includes("Shift") ?? false;
|
||||
const key = shifted || input.key === upper ? upper : input.key;
|
||||
return { code: `Key${upper}`, key, keyCode: upper.charCodeAt(0), text: key };
|
||||
}
|
||||
|
||||
const printable = PRINTABLE_KEYS.find(
|
||||
(definition) => definition.key === input.key || definition.shiftedKey === input.key,
|
||||
);
|
||||
if (printable) {
|
||||
const shifted = input.modifiers?.includes("Shift") ?? false;
|
||||
const key =
|
||||
printable.shiftedKey && (shifted || input.key === printable.shiftedKey)
|
||||
? printable.shiftedKey
|
||||
: printable.key;
|
||||
return { ...printable, key, text: key };
|
||||
}
|
||||
|
||||
return {
|
||||
code: input.key.length > 1 ? input.key : "",
|
||||
key: input.key,
|
||||
keyCode: 0,
|
||||
...(input.key.length === 1 ? { text: input.key } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Build Chromium CDP key packets using the same required fields and down-event
|
||||
* choice as Playwright's pinned Chromium keyboard implementation.
|
||||
*/
|
||||
export function makePreviewAutomationKeySequence(
|
||||
input: PreviewAutomationPressInput,
|
||||
options?: { readonly isMac?: boolean },
|
||||
): PreviewAutomationKeySequence {
|
||||
const definition = resolveKeyDefinition(input);
|
||||
const modifiers = modifierMask(input.modifiers);
|
||||
const suppressText = input.modifiers?.some((modifier) => modifier !== "Shift") ?? false;
|
||||
const text = suppressText ? "" : (definition.text ?? "");
|
||||
const location = definition.location ?? 0;
|
||||
const commands = options?.isMac ? macEditingCommands(definition.code, input.modifiers) : [];
|
||||
const shared = {
|
||||
key: definition.key,
|
||||
code: definition.code,
|
||||
modifiers,
|
||||
windowsVirtualKeyCode: definition.keyCode,
|
||||
location,
|
||||
isKeypad: location === 3,
|
||||
};
|
||||
|
||||
return {
|
||||
keyDown: {
|
||||
type: text ? "keyDown" : "rawKeyDown",
|
||||
...shared,
|
||||
...(text ? { text, unmodifiedText: text } : {}),
|
||||
...(commands.length > 0 ? { commands } : {}),
|
||||
},
|
||||
keyUp: { type: "keyUp", ...shared },
|
||||
signal: { kind: "key", key: definition.key, code: definition.code },
|
||||
};
|
||||
}
|
||||
@@ -18,6 +18,7 @@ const clientSettings: ClientSettings = {
|
||||
confirmThreadDelete: false,
|
||||
dismissedProviderUpdateNotificationKeys: [],
|
||||
diffIgnoreWhitespace: true,
|
||||
diffWordWrap: true,
|
||||
favorites: [],
|
||||
providerModelPreferences: {},
|
||||
sidebarProjectGroupingMode: "repository_path",
|
||||
@@ -28,7 +29,6 @@ const clientSettings: ClientSettings = {
|
||||
sidebarThreadSortOrder: "created_at",
|
||||
sidebarThreadPreviewCount: 6,
|
||||
timestampFormat: "24-hour",
|
||||
wordWrap: true,
|
||||
};
|
||||
|
||||
const decodeClientSettingsJson = Schema.decodeEffect(Schema.fromJsonString(ClientSettingsSchema));
|
||||
|
||||
@@ -75,7 +75,9 @@ function discoverDesktopSshHostsEffect(input?: { readonly homeDir?: string }) {
|
||||
|
||||
export function isDesktopSshPasswordPromptCancellation(
|
||||
error: unknown,
|
||||
): error is SshPasswordPromptError {
|
||||
): error is SshPasswordPromptError & {
|
||||
readonly cause: DesktopSshPasswordPrompts.DesktopSshPasswordPromptCancellation;
|
||||
} {
|
||||
return (
|
||||
error instanceof SshPasswordPromptError &&
|
||||
DesktopSshPasswordPrompts.isDesktopSshPasswordPromptCancellation(error.cause)
|
||||
|
||||
@@ -4,7 +4,6 @@ import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
|
||||
import type * as Electron from "electron";
|
||||
import { vi } from "vite-plus/test";
|
||||
@@ -48,14 +47,12 @@ function makeFakeBrowserWindow() {
|
||||
const webContentsListeners = new Map<string, (...args: readonly unknown[]) => void>();
|
||||
const webContents = {
|
||||
copyImageAt: vi.fn(),
|
||||
getURL: vi.fn(() => "t3code-dev://app/"),
|
||||
isLoadingMainFrame: vi.fn(() => false),
|
||||
on: vi.fn((eventName: string, listener: (...args: readonly unknown[]) => void) => {
|
||||
webContentsListeners.set(eventName, listener);
|
||||
}),
|
||||
once: vi.fn(),
|
||||
openDevTools: vi.fn(),
|
||||
reload: vi.fn(),
|
||||
replaceMisspelling: vi.fn(),
|
||||
send: vi.fn(),
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
@@ -82,7 +79,6 @@ function makeFakeBrowserWindow() {
|
||||
window: window as unknown as Electron.BrowserWindow,
|
||||
loadURL: window.loadURL,
|
||||
openDevTools: webContents.openDevTools,
|
||||
reload: webContents.reload,
|
||||
setAutoHideCursor: window.setAutoHideCursor,
|
||||
webContentsListeners,
|
||||
};
|
||||
@@ -241,73 +237,6 @@ describe("DesktopWindow", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("recovers when the development renderer is temporarily unreachable", () =>
|
||||
Effect.gen(function* () {
|
||||
const fakeWindow = makeFakeBrowserWindow();
|
||||
const createCount = yield* Ref.make(0);
|
||||
const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
|
||||
const layer = makeTestLayer({
|
||||
window: fakeWindow.window,
|
||||
createCount,
|
||||
mainWindow,
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const desktopWindow = yield* DesktopWindow.DesktopWindow;
|
||||
yield* desktopWindow.handleBackendReady;
|
||||
|
||||
const didFailLoad = fakeWindow.webContentsListeners.get("did-fail-load");
|
||||
const didFinishLoad = fakeWindow.webContentsListeners.get("did-finish-load");
|
||||
if (!didFailLoad || !didFinishLoad) {
|
||||
return yield* Effect.die("renderer load listeners were not registered");
|
||||
}
|
||||
|
||||
didFailLoad({}, -9, "ERR_UNEXPECTED", "t3code-dev://app/", true);
|
||||
assert.equal(fakeWindow.loadURL.mock.calls.length, 1);
|
||||
|
||||
yield* TestClock.adjust(100);
|
||||
assert.deepEqual(fakeWindow.loadURL.mock.calls, [
|
||||
["t3code-dev://app/"],
|
||||
["t3code-dev://app/"],
|
||||
]);
|
||||
assert.equal(fakeWindow.reload.mock.calls.length, 0);
|
||||
|
||||
didFailLoad({}, -9, "ERR_UNEXPECTED", "t3code-dev://app/", true);
|
||||
didFinishLoad();
|
||||
yield* TestClock.adjust(250);
|
||||
assert.equal(fakeWindow.loadURL.mock.calls.length, 2);
|
||||
assert.equal(fakeWindow.reload.mock.calls.length, 0);
|
||||
}).pipe(Effect.provide(layer));
|
||||
}),
|
||||
);
|
||||
|
||||
it("retries only transient failures for the development renderer", () => {
|
||||
assert.isTrue(
|
||||
DesktopWindow.isRetryableDevelopmentRendererLoadFailure({
|
||||
applicationUrl: "t3code-dev://app/",
|
||||
errorCode: -102,
|
||||
isMainFrame: true,
|
||||
validatedUrl: "t3code-dev://app/",
|
||||
}),
|
||||
);
|
||||
assert.isFalse(
|
||||
DesktopWindow.isRetryableDevelopmentRendererLoadFailure({
|
||||
applicationUrl: "t3code-dev://app/",
|
||||
errorCode: -3,
|
||||
isMainFrame: true,
|
||||
validatedUrl: "t3code-dev://app/",
|
||||
}),
|
||||
);
|
||||
assert.isFalse(
|
||||
DesktopWindow.isRetryableDevelopmentRendererLoadFailure({
|
||||
applicationUrl: "t3code-dev://app/",
|
||||
errorCode: -102,
|
||||
isMainFrame: true,
|
||||
validatedUrl: "https://example.com/",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("opens safe off-origin renderer navigations in the system browser", () =>
|
||||
Effect.gen(function* () {
|
||||
const fakeWindow = makeFakeBrowserWindow();
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
@@ -23,16 +22,6 @@ const TITLEBAR_HEIGHT = 40;
|
||||
const TITLEBAR_COLOR = "#01000000"; // #00000000 does not work correctly on Linux
|
||||
const TITLEBAR_LIGHT_SYMBOL_COLOR = "#1f2937";
|
||||
const TITLEBAR_DARK_SYMBOL_COLOR = "#f8fafc";
|
||||
const DEVELOPMENT_LOAD_RETRY_DELAYS_MS = [100, 250, 500, 1_000, 2_000] as const;
|
||||
const DEVELOPMENT_RETRYABLE_LOAD_ERROR_CODES = new Set([
|
||||
-2, // ERR_FAILED
|
||||
-7, // ERR_TIMED_OUT
|
||||
-9, // ERR_UNEXPECTED (custom protocol handler rejected)
|
||||
-102, // ERR_CONNECTION_REFUSED
|
||||
-105, // ERR_NAME_NOT_RESOLVED
|
||||
-106, // ERR_INTERNET_DISCONNECTED
|
||||
-118, // ERR_CONNECTION_TIMED_OUT
|
||||
]);
|
||||
|
||||
type WindowTitleBarOptions = Pick<
|
||||
Electron.BrowserWindowConstructorOptions,
|
||||
@@ -97,22 +86,6 @@ export function isSameOriginRendererNavigation(input: {
|
||||
}
|
||||
}
|
||||
|
||||
export function isRetryableDevelopmentRendererLoadFailure(input: {
|
||||
readonly applicationUrl: string;
|
||||
readonly errorCode: number;
|
||||
readonly isMainFrame: boolean;
|
||||
readonly validatedUrl: string;
|
||||
}): boolean {
|
||||
return (
|
||||
input.isMainFrame &&
|
||||
DEVELOPMENT_RETRYABLE_LOAD_ERROR_CODES.has(input.errorCode) &&
|
||||
isSameOriginRendererNavigation({
|
||||
applicationUrl: input.applicationUrl,
|
||||
navigationUrl: input.validatedUrl,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
function getWindowTitleBarOptions(
|
||||
shouldUseDarkColors: boolean,
|
||||
platform: NodeJS.Platform,
|
||||
@@ -179,7 +152,6 @@ export const make = Effect.gen(function* () {
|
||||
const previewManager = yield* PreviewManager.PreviewManager;
|
||||
const state = yield* DesktopState.DesktopState;
|
||||
const context = yield* Effect.context<DesktopWindowRuntimeServices>();
|
||||
const runFork = Effect.runForkWith(context);
|
||||
const runPromise = Effect.runPromiseWith(context);
|
||||
|
||||
const createWindow = Effect.fn("desktop.window.createWindow")(function* (): Effect.fn.Return<
|
||||
@@ -254,7 +226,9 @@ export const make = Effect.gen(function* () {
|
||||
{
|
||||
label: "Copy Link",
|
||||
click: () => {
|
||||
void runPromise(electronShell.copyText(params.linkURL));
|
||||
void runPromise(
|
||||
electronShell.copyText(params.linkURL).pipe(Effect.ignore({ log: true })),
|
||||
);
|
||||
},
|
||||
},
|
||||
{ type: "separator" },
|
||||
@@ -281,7 +255,7 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
window.webContents.setWindowOpenHandler(({ url }) => {
|
||||
if (Option.isSome(ElectronShell.parseSafeExternalUrl(url))) {
|
||||
void runPromise(electronShell.openExternal(url));
|
||||
void runPromise(electronShell.openExternal(url).pipe(Effect.ignore({ log: true })));
|
||||
}
|
||||
return { action: "deny" };
|
||||
});
|
||||
@@ -297,7 +271,7 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
event.preventDefault();
|
||||
if (Option.isSome(ElectronShell.parseSafeExternalUrl(url))) {
|
||||
void runPromise(electronShell.openExternal(url));
|
||||
void runPromise(electronShell.openExternal(url).pipe(Effect.ignore({ log: true })));
|
||||
}
|
||||
});
|
||||
|
||||
@@ -305,61 +279,7 @@ export const make = Effect.gen(function* () {
|
||||
event.preventDefault();
|
||||
window.setTitle(environment.displayName);
|
||||
});
|
||||
|
||||
let developmentLoadRetryIndex = 0;
|
||||
let developmentLoadRetryFiber: Fiber.Fiber<void, never> | undefined;
|
||||
const clearDevelopmentLoadRetry = () => {
|
||||
if (developmentLoadRetryFiber === undefined) {
|
||||
return;
|
||||
}
|
||||
const retryFiber = developmentLoadRetryFiber;
|
||||
developmentLoadRetryFiber = undefined;
|
||||
runFork(Fiber.interrupt(retryFiber));
|
||||
};
|
||||
const loadApplication = () => {
|
||||
if (window.isDestroyed()) {
|
||||
return;
|
||||
}
|
||||
void window.loadURL(applicationUrl).catch(() => undefined);
|
||||
};
|
||||
const scheduleDevelopmentLoadRetry = () => {
|
||||
if (developmentLoadRetryFiber !== undefined || window.isDestroyed()) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const retryIndex = Math.min(
|
||||
developmentLoadRetryIndex,
|
||||
DEVELOPMENT_LOAD_RETRY_DELAYS_MS.length - 1,
|
||||
);
|
||||
const retryInMs = DEVELOPMENT_LOAD_RETRY_DELAYS_MS[retryIndex] ?? 2_000;
|
||||
developmentLoadRetryIndex += 1;
|
||||
developmentLoadRetryFiber = runFork(
|
||||
Effect.sleep(retryInMs).pipe(
|
||||
Effect.andThen(
|
||||
Effect.sync(() => {
|
||||
developmentLoadRetryFiber = undefined;
|
||||
if (!window.isDestroyed()) {
|
||||
loadApplication();
|
||||
}
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
return retryInMs;
|
||||
};
|
||||
|
||||
window.webContents.on("did-finish-load", () => {
|
||||
if (
|
||||
environment.isDevelopment &&
|
||||
!isSameOriginRendererNavigation({
|
||||
applicationUrl,
|
||||
navigationUrl: window.webContents.getURL(),
|
||||
})
|
||||
) {
|
||||
return;
|
||||
}
|
||||
clearDevelopmentLoadRetry();
|
||||
developmentLoadRetryIndex = 0;
|
||||
window.setTitle(environment.displayName);
|
||||
});
|
||||
window.webContents.on(
|
||||
@@ -368,22 +288,11 @@ export const make = Effect.gen(function* () {
|
||||
if (!isMainFrame) {
|
||||
return;
|
||||
}
|
||||
const retryInMs =
|
||||
environment.isDevelopment &&
|
||||
isRetryableDevelopmentRendererLoadFailure({
|
||||
applicationUrl,
|
||||
errorCode,
|
||||
isMainFrame,
|
||||
validatedUrl: validatedURL,
|
||||
})
|
||||
? scheduleDevelopmentLoadRetry()
|
||||
: undefined;
|
||||
void runPromise(
|
||||
logWindowWarning("main window failed to load", {
|
||||
errorCode,
|
||||
errorDescription,
|
||||
url: validatedURL,
|
||||
...(retryInMs === undefined ? {} : { retryInMs }),
|
||||
}),
|
||||
);
|
||||
},
|
||||
@@ -405,13 +314,14 @@ export const make = Effect.gen(function* () {
|
||||
void runPromise(electronWindow.reveal(window));
|
||||
});
|
||||
|
||||
loadApplication();
|
||||
if (environment.isDevelopment) {
|
||||
void window.loadURL(applicationUrl);
|
||||
window.webContents.openDevTools({ mode: "detach" });
|
||||
} else {
|
||||
void window.loadURL(applicationUrl);
|
||||
}
|
||||
|
||||
window.on("closed", () => {
|
||||
clearDevelopmentLoadRetry();
|
||||
void runPromise(electronWindow.clearMain(Option.some(window)));
|
||||
});
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
"typecheck": "astro check"
|
||||
},
|
||||
"dependencies": {
|
||||
"astro": "^7.0.3"
|
||||
"astro": "^6.0.4"
|
||||
},
|
||||
"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.2.0",
|
||||
"@legendapp/list": "3.0.0-beta.44",
|
||||
"@noble/curves": "catalog:",
|
||||
"@noble/hashes": "catalog:",
|
||||
"@pierre/diffs": "catalog:",
|
||||
@@ -93,9 +93,9 @@
|
||||
"react-native": "0.85.3",
|
||||
"react-native-gesture-handler": "~2.31.1",
|
||||
"react-native-image-viewing": "^0.2.2",
|
||||
"react-native-keyboard-controller": "1.21.7",
|
||||
"react-native-keyboard-controller": "1.21.6",
|
||||
"react-native-nitro-markdown": "^0.5.0",
|
||||
"react-native-nitro-modules": "0.35.9",
|
||||
"react-native-nitro-modules": "^0.35.4",
|
||||
"react-native-reanimated": "4.3.1",
|
||||
"react-native-safe-area-context": "~5.7.0",
|
||||
"react-native-screens": "4.25.2",
|
||||
|
||||
@@ -3,7 +3,10 @@ import {
|
||||
type ConnectionCatalogDocument as ConnectionCatalogDocumentType,
|
||||
EMPTY_CONNECTION_CATALOG_DOCUMENT,
|
||||
} from "@t3tools/client-runtime/platform";
|
||||
import { ConnectionTransientError } from "@t3tools/client-runtime/connection";
|
||||
import {
|
||||
ConnectionStorageOperationError,
|
||||
ConnectionTransientError,
|
||||
} from "@t3tools/client-runtime/connection";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
@@ -15,30 +18,38 @@ import { migrateLegacyConnectionCatalog } from "./migration";
|
||||
export const CONNECTION_CATALOG_KEY = "t3code.connection-catalog.v1";
|
||||
export const LEGACY_CONNECTIONS_KEY = "t3code.connections";
|
||||
|
||||
function catalogError(operation: string, cause: unknown) {
|
||||
return new ConnectionTransientError({
|
||||
reason: "remote-unavailable",
|
||||
detail: `Could not ${operation} the local connection catalog: ${String(cause)}`,
|
||||
});
|
||||
}
|
||||
const ConnectionCatalogDocumentJson = Schema.fromJsonString(ConnectionCatalogDocument);
|
||||
const decodeConnectionCatalogDocument = Schema.decodeUnknownEffect(ConnectionCatalogDocumentJson);
|
||||
const encodeConnectionCatalogDocument = Schema.encodeEffect(ConnectionCatalogDocumentJson);
|
||||
|
||||
const decodeCatalog = Effect.fn("mobile.connectionStorage.decodeCatalog")(function* (raw: string) {
|
||||
const parsed = yield* Effect.try({
|
||||
try: () => JSON.parse(raw) as unknown,
|
||||
catch: (cause) => catalogError("decode", cause),
|
||||
});
|
||||
return yield* Effect.fromResult(
|
||||
Schema.decodeUnknownResult(ConnectionCatalogDocument)(parsed),
|
||||
).pipe(Effect.mapError((cause) => catalogError("decode", cause)));
|
||||
return yield* decodeConnectionCatalogDocument(raw).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
ConnectionTransientError.fromStorageFailure(
|
||||
new ConnectionStorageOperationError({
|
||||
operation: "decode",
|
||||
backend: "schema",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
const encodeCatalog = Effect.fn("mobile.connectionStorage.encodeCatalog")(function* (
|
||||
catalog: ConnectionCatalogDocumentType,
|
||||
) {
|
||||
const encoded = yield* Effect.fromResult(
|
||||
Schema.encodeUnknownResult(ConnectionCatalogDocument)(catalog),
|
||||
).pipe(Effect.mapError((cause) => catalogError("encode", cause)));
|
||||
return JSON.stringify(encoded);
|
||||
return yield* encodeConnectionCatalogDocument(catalog).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
ConnectionTransientError.fromStorageFailure(
|
||||
new ConnectionStorageOperationError({
|
||||
operation: "encode",
|
||||
backend: "schema",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
interface CatalogStore {
|
||||
@@ -66,12 +77,21 @@ export const makeCatalogStore = Effect.fn("mobile.connectionStorage.makeCatalogS
|
||||
legacyRaw === null || legacyRaw.trim() === ""
|
||||
? EMPTY_CONNECTION_CATALOG_DOCUMENT
|
||||
: yield* migrateLegacyConnectionCatalog(legacyRaw).pipe(
|
||||
Effect.mapError((cause) => catalogError("migrate", cause)),
|
||||
Effect.catch((error) =>
|
||||
Effect.logWarning("Discarding corrupt legacy mobile connections", error).pipe(
|
||||
Effect.as(EMPTY_CONNECTION_CATALOG_DOCUMENT),
|
||||
Effect.mapError((cause) =>
|
||||
ConnectionTransientError.fromStorageFailure(
|
||||
new ConnectionStorageOperationError({
|
||||
operation: "migrate",
|
||||
backend: "legacy-migration",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
Effect.catchTags({
|
||||
ConnectionTransientError: (error) =>
|
||||
Effect.logWarning("Discarding corrupt legacy mobile connections", error).pipe(
|
||||
Effect.as(EMPTY_CONNECTION_CATALOG_DOCUMENT),
|
||||
),
|
||||
}),
|
||||
);
|
||||
if (legacyRaw !== null && legacyRaw.trim() !== "") {
|
||||
const encoded = yield* encodeCatalog(catalog);
|
||||
@@ -90,12 +110,13 @@ export const makeCatalogStore = Effect.fn("mobile.connectionStorage.makeCatalogS
|
||||
let catalog: ConnectionCatalogDocumentType;
|
||||
if (raw !== null && raw.trim() !== "") {
|
||||
catalog = yield* decodeCatalog(raw).pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.logWarning("Discarding corrupt mobile connection catalog", error).pipe(
|
||||
Effect.andThen(storage.deleteItem(CONNECTION_CATALOG_KEY)),
|
||||
Effect.andThen(loadLegacyCatalog()),
|
||||
),
|
||||
),
|
||||
Effect.catchTags({
|
||||
ConnectionTransientError: (error) =>
|
||||
Effect.logWarning("Discarding corrupt mobile connection catalog", error).pipe(
|
||||
Effect.andThen(storage.deleteItem(CONNECTION_CATALOG_KEY)),
|
||||
Effect.andThen(loadLegacyCatalog()),
|
||||
),
|
||||
}),
|
||||
);
|
||||
} else {
|
||||
catalog = yield* loadLegacyCatalog();
|
||||
|
||||
@@ -2,7 +2,7 @@ import { describe, expect, it } from "@effect/vitest";
|
||||
import { EnvironmentId } from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
import { migrateLegacyConnectionCatalog } from "./migration";
|
||||
import { LegacyConnectionMigrationError, migrateLegacyConnectionCatalog } from "./migration";
|
||||
|
||||
describe("migrateLegacyConnectionCatalog", () => {
|
||||
it.effect("migrates bearer and relay-managed connections into the new catalog", () =>
|
||||
@@ -75,4 +75,28 @@ describe("migrateLegacyConnectionCatalog", () => {
|
||||
expect(catalog.targets).toEqual([]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves parse failures with a stable structural error", () =>
|
||||
Effect.gen(function* () {
|
||||
const error = yield* migrateLegacyConnectionCatalog("{not-json").pipe(Effect.flip);
|
||||
|
||||
expect(error).toBeInstanceOf(LegacyConnectionMigrationError);
|
||||
expect(error.stage).toBe("parse");
|
||||
expect(error.cause).toBeInstanceOf(SyntaxError);
|
||||
expect(error.message).toBe("Could not parse the legacy mobile connection catalog.");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("distinguishes catalog decoding failures", () =>
|
||||
Effect.gen(function* () {
|
||||
const error = yield* migrateLegacyConnectionCatalog('{"connections":"invalid"}').pipe(
|
||||
Effect.flip,
|
||||
);
|
||||
|
||||
expect(error).toBeInstanceOf(LegacyConnectionMigrationError);
|
||||
expect(error.stage).toBe("decode");
|
||||
expect(error.cause).toBeDefined();
|
||||
expect(error.message).toBe("Could not decode the legacy mobile connection catalog.");
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -36,9 +36,14 @@ const decodeLegacyConnectionDocument = Schema.decodeUnknownEffect(LegacyConnecti
|
||||
export class LegacyConnectionMigrationError extends Schema.TaggedErrorClass<LegacyConnectionMigrationError>()(
|
||||
"LegacyConnectionMigrationError",
|
||||
{
|
||||
message: Schema.String,
|
||||
stage: Schema.Literals(["parse", "decode"]),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {}
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Could not ${this.stage} the legacy mobile connection catalog.`;
|
||||
}
|
||||
}
|
||||
|
||||
function isRelayManaged(connection: typeof LegacySavedRemoteConnection.Type): boolean {
|
||||
return connection.relayManaged === true || connection.authenticationMethod === "dpop";
|
||||
@@ -92,18 +97,10 @@ export const migrateLegacyConnectionCatalog = Effect.fn(
|
||||
)(function* (raw: string) {
|
||||
const parsed = yield* Effect.try({
|
||||
try: () => JSON.parse(raw) as unknown,
|
||||
catch: (cause) =>
|
||||
new LegacyConnectionMigrationError({
|
||||
message: `Could not parse the legacy mobile connection catalog: ${String(cause)}`,
|
||||
}),
|
||||
catch: (cause) => new LegacyConnectionMigrationError({ stage: "parse", cause }),
|
||||
});
|
||||
const legacy = yield* decodeLegacyConnectionDocument(parsed).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new LegacyConnectionMigrationError({
|
||||
message: `Could not decode the legacy mobile connection catalog: ${String(cause)}`,
|
||||
}),
|
||||
),
|
||||
Effect.mapError((cause) => new LegacyConnectionMigrationError({ stage: "decode", cause })),
|
||||
);
|
||||
|
||||
return (legacy.connections ?? []).reduce(migrateConnection, EMPTY_CONNECTION_CATALOG_DOCUMENT);
|
||||
|
||||
@@ -100,7 +100,8 @@ const capabilitiesLayer = Layer.succeedContext(
|
||||
(error) =>
|
||||
new ConnectionTransientError({
|
||||
reason: "network",
|
||||
detail: error.message,
|
||||
detail: "Could not read the T3 Cloud session token.",
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -126,7 +127,8 @@ const capabilitiesLayer = Layer.succeedContext(
|
||||
catch: (cause) =>
|
||||
new ConnectionTransientError({
|
||||
reason: "remote-unavailable",
|
||||
detail: `Could not load the mobile device identity: ${String(cause)}`,
|
||||
detail: "Could not load the mobile device identity.",
|
||||
cause,
|
||||
}),
|
||||
}).pipe(Effect.map(Option.some)),
|
||||
}),
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
} from "@t3tools/client-runtime/platform";
|
||||
import { TokenStore } from "@t3tools/client-runtime/authorization";
|
||||
import {
|
||||
ConnectionStorageOperationError,
|
||||
ConnectionTransientError,
|
||||
CredentialStore,
|
||||
ProfileStore,
|
||||
@@ -54,29 +55,11 @@ const LegacyStoredShellSnapshot = Schema.Struct({
|
||||
snapshotReceivedAt: Schema.String,
|
||||
snapshot: OrchestrationShellSnapshot,
|
||||
});
|
||||
|
||||
function catalogError(operation: string, cause: unknown) {
|
||||
return new ConnectionTransientError({
|
||||
reason: "remote-unavailable",
|
||||
detail: `Could not ${operation} the local connection catalog: ${String(cause)}`,
|
||||
});
|
||||
}
|
||||
|
||||
function shellPersistenceError(
|
||||
operation:
|
||||
| "load-shell"
|
||||
| "save-shell"
|
||||
| "load-thread"
|
||||
| "save-thread"
|
||||
| "remove-thread"
|
||||
| "clear-environment",
|
||||
cause: unknown,
|
||||
) {
|
||||
return new ConnectionPersistenceError({
|
||||
operation,
|
||||
message: `Could not ${operation.replaceAll("-", " ")}: ${String(cause)}`,
|
||||
});
|
||||
}
|
||||
const decodeStoredShellSnapshot = Schema.decodeUnknownEffect(StoredShellSnapshot);
|
||||
const encodeStoredShellSnapshot = Schema.encodeEffect(StoredShellSnapshot);
|
||||
const decodeStoredThreadSnapshot = Schema.decodeUnknownEffect(StoredThreadSnapshot);
|
||||
const encodeStoredThreadSnapshot = Schema.encodeEffect(StoredThreadSnapshot);
|
||||
const decodeLegacyStoredShellSnapshot = Schema.decodeUnknownEffect(LegacyStoredShellSnapshot);
|
||||
|
||||
function threadSnapshotFileName(threadId: ThreadId): string {
|
||||
return `${encodeURIComponent(threadId)}.json`;
|
||||
@@ -100,7 +83,14 @@ const threadSnapshotDirectory = Effect.fn("mobile.connectionStorage.threadSnapsh
|
||||
}
|
||||
return directory;
|
||||
},
|
||||
catch: (cause) => shellPersistenceError(operation, cause),
|
||||
catch: (cause) =>
|
||||
new ConnectionPersistenceError({
|
||||
operation,
|
||||
stage: "resolve",
|
||||
resource: "thread-cache",
|
||||
environmentId,
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
},
|
||||
);
|
||||
@@ -110,38 +100,63 @@ const threadSnapshotFile = Effect.fn("mobile.connectionStorage.threadSnapshotFil
|
||||
threadId: ThreadId,
|
||||
operation: "load-thread" | "save-thread" | "remove-thread",
|
||||
) {
|
||||
const { File } = yield* Effect.promise(() => import("expo-file-system"));
|
||||
return new File(
|
||||
yield* threadSnapshotDirectory(environmentId, operation),
|
||||
threadSnapshotFileName(threadId),
|
||||
);
|
||||
});
|
||||
|
||||
function targetPersistenceError(
|
||||
operation: "list-targets" | "register-connection" | "remove-connection",
|
||||
error: ConnectionTransientError,
|
||||
) {
|
||||
return new ConnectionPersistenceError({
|
||||
operation,
|
||||
message: error.message,
|
||||
const directory = yield* threadSnapshotDirectory(environmentId, operation);
|
||||
return yield* Effect.tryPromise({
|
||||
try: async () => {
|
||||
const { File } = await import("expo-file-system");
|
||||
return new File(directory, threadSnapshotFileName(threadId));
|
||||
},
|
||||
catch: (cause) =>
|
||||
new ConnectionPersistenceError({
|
||||
operation,
|
||||
stage: "resolve",
|
||||
resource: "thread-cache",
|
||||
environmentId,
|
||||
threadId,
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
const secureCatalogStorage: SecureCatalogStorage = {
|
||||
getItem: (key) =>
|
||||
Effect.tryPromise({
|
||||
try: () => SecureStore.getItemAsync(key),
|
||||
catch: (cause) => catalogError("load", cause),
|
||||
catch: (cause) =>
|
||||
ConnectionTransientError.fromStorageFailure(
|
||||
new ConnectionStorageOperationError({
|
||||
operation: "load",
|
||||
backend: "mobile-secure-storage",
|
||||
key,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
setItem: (key, value) =>
|
||||
Effect.tryPromise({
|
||||
try: () => SecureStore.setItemAsync(key, value),
|
||||
catch: (cause) => catalogError("save", cause),
|
||||
catch: (cause) =>
|
||||
ConnectionTransientError.fromStorageFailure(
|
||||
new ConnectionStorageOperationError({
|
||||
operation: "save",
|
||||
backend: "mobile-secure-storage",
|
||||
key,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
deleteItem: (key) =>
|
||||
Effect.tryPromise({
|
||||
try: () => SecureStore.deleteItemAsync(key),
|
||||
catch: (cause) => catalogError("delete", cause),
|
||||
catch: (cause) =>
|
||||
ConnectionTransientError.fromStorageFailure(
|
||||
new ConnectionStorageOperationError({
|
||||
operation: "delete",
|
||||
backend: "mobile-secure-storage",
|
||||
key,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
};
|
||||
|
||||
@@ -156,6 +171,8 @@ const shellSnapshotFileInDirectory = Effect.fn(
|
||||
operation: "load-shell" | "save-shell" | "clear-environment",
|
||||
directoryName: string,
|
||||
) {
|
||||
const resource =
|
||||
directoryName === LEGACY_SHELL_SNAPSHOT_CACHE_DIRECTORY ? "legacy-shell-cache" : "shell-cache";
|
||||
return yield* Effect.tryPromise({
|
||||
try: async () => {
|
||||
const { Directory, File, Paths } = await import("expo-file-system");
|
||||
@@ -163,7 +180,14 @@ const shellSnapshotFileInDirectory = Effect.fn(
|
||||
directory.create({ idempotent: true, intermediates: true });
|
||||
return new File(directory, shellSnapshotFileName(environmentId));
|
||||
},
|
||||
catch: (cause) => shellPersistenceError(operation, cause),
|
||||
catch: (cause) =>
|
||||
new ConnectionPersistenceError({
|
||||
operation,
|
||||
stage: "resolve",
|
||||
resource,
|
||||
environmentId,
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
@@ -184,18 +208,45 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
const targetStore = ConnectionTargetStore.of({
|
||||
list: catalog.read.pipe(
|
||||
Effect.map((document) => document.targets),
|
||||
Effect.mapError((error) => targetPersistenceError("list-targets", error)),
|
||||
Effect.mapError((cause) =>
|
||||
ConnectionPersistenceError.fromStorageFailure({
|
||||
operation: "list-targets",
|
||||
fallbackStage: "read",
|
||||
resource: "connection-catalog",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
});
|
||||
const registrationStore = ConnectionRegistrationStore.of({
|
||||
register: (registration) =>
|
||||
catalog
|
||||
.update((document) => registerConnectionInCatalog(document, registration))
|
||||
.pipe(Effect.mapError((error) => targetPersistenceError("register-connection", error))),
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
ConnectionPersistenceError.fromStorageFailure({
|
||||
operation: "register-connection",
|
||||
fallbackStage: "write",
|
||||
resource: "connection-catalog",
|
||||
environmentId: registration.target.environmentId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
remove: (target) =>
|
||||
catalog
|
||||
.update((document) => removeConnectionFromCatalog(document, target))
|
||||
.pipe(Effect.mapError((error) => targetPersistenceError("remove-connection", error))),
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
ConnectionPersistenceError.fromStorageFailure({
|
||||
operation: "remove-connection",
|
||||
fallbackStage: "write",
|
||||
resource: "connection-catalog",
|
||||
environmentId: target.environmentId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
});
|
||||
const profileStore = ProfileStore.make({
|
||||
get: (connectionId) =>
|
||||
@@ -283,15 +334,38 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
if (file.exists) {
|
||||
const raw = yield* Effect.tryPromise({
|
||||
try: () => file.text(),
|
||||
catch: (cause) => shellPersistenceError("load-shell", cause),
|
||||
catch: (cause) =>
|
||||
new ConnectionPersistenceError({
|
||||
operation: "load-shell",
|
||||
stage: "read",
|
||||
resource: "shell-cache",
|
||||
environmentId,
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
const parsed = yield* Effect.try({
|
||||
try: () => JSON.parse(raw) as unknown,
|
||||
catch: (cause) => shellPersistenceError("load-shell", cause),
|
||||
catch: (cause) =>
|
||||
new ConnectionPersistenceError({
|
||||
operation: "load-shell",
|
||||
stage: "parse",
|
||||
resource: "shell-cache",
|
||||
environmentId,
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
const stored = yield* Effect.fromResult(
|
||||
Schema.decodeUnknownResult(StoredShellSnapshot)(parsed),
|
||||
).pipe(Effect.mapError((cause) => shellPersistenceError("load-shell", cause)));
|
||||
const stored = yield* decodeStoredShellSnapshot(parsed).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ConnectionPersistenceError({
|
||||
operation: "load-shell",
|
||||
stage: "decode",
|
||||
resource: "shell-cache",
|
||||
environmentId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
return stored.environmentId === environmentId
|
||||
? Option.some(stored.snapshot)
|
||||
: Option.none();
|
||||
@@ -303,15 +377,38 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
}
|
||||
const legacyRaw = yield* Effect.tryPromise({
|
||||
try: () => legacyFile.text(),
|
||||
catch: (cause) => shellPersistenceError("load-shell", cause),
|
||||
catch: (cause) =>
|
||||
new ConnectionPersistenceError({
|
||||
operation: "load-shell",
|
||||
stage: "read",
|
||||
resource: "legacy-shell-cache",
|
||||
environmentId,
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
const legacyParsed = yield* Effect.try({
|
||||
try: () => JSON.parse(legacyRaw) as unknown,
|
||||
catch: (cause) => shellPersistenceError("load-shell", cause),
|
||||
catch: (cause) =>
|
||||
new ConnectionPersistenceError({
|
||||
operation: "load-shell",
|
||||
stage: "parse",
|
||||
resource: "legacy-shell-cache",
|
||||
environmentId,
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
const legacyStored = yield* Effect.fromResult(
|
||||
Schema.decodeUnknownResult(LegacyStoredShellSnapshot)(legacyParsed),
|
||||
).pipe(Effect.mapError((cause) => shellPersistenceError("load-shell", cause)));
|
||||
const legacyStored = yield* decodeLegacyStoredShellSnapshot(legacyParsed).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ConnectionPersistenceError({
|
||||
operation: "load-shell",
|
||||
stage: "decode",
|
||||
resource: "legacy-shell-cache",
|
||||
environmentId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
return legacyStored.environmentId === environmentId
|
||||
? Option.some(legacyStored.snapshot)
|
||||
: Option.none();
|
||||
@@ -324,9 +421,18 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
environmentId,
|
||||
snapshot,
|
||||
} as const;
|
||||
const encoded = yield* Effect.fromResult(
|
||||
Schema.encodeUnknownResult(StoredShellSnapshot)(stored),
|
||||
).pipe(Effect.mapError((cause) => shellPersistenceError("save-shell", cause)));
|
||||
const encoded = yield* encodeStoredShellSnapshot(stored).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ConnectionPersistenceError({
|
||||
operation: "save-shell",
|
||||
stage: "encode",
|
||||
resource: "shell-cache",
|
||||
environmentId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* Effect.try({
|
||||
try: () => {
|
||||
if (!file.exists) {
|
||||
@@ -334,7 +440,14 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
}
|
||||
file.write(JSON.stringify(encoded));
|
||||
},
|
||||
catch: (cause) => shellPersistenceError("save-shell", cause),
|
||||
catch: (cause) =>
|
||||
new ConnectionPersistenceError({
|
||||
operation: "save-shell",
|
||||
stage: "write",
|
||||
resource: "shell-cache",
|
||||
environmentId,
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
}),
|
||||
loadThread: (environmentId, threadId) =>
|
||||
@@ -345,15 +458,41 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
}
|
||||
const raw = yield* Effect.tryPromise({
|
||||
try: () => file.text(),
|
||||
catch: (cause) => shellPersistenceError("load-thread", cause),
|
||||
catch: (cause) =>
|
||||
new ConnectionPersistenceError({
|
||||
operation: "load-thread",
|
||||
stage: "read",
|
||||
resource: "thread-cache",
|
||||
environmentId,
|
||||
threadId,
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
const parsed = yield* Effect.try({
|
||||
try: () => JSON.parse(raw) as unknown,
|
||||
catch: (cause) => shellPersistenceError("load-thread", cause),
|
||||
catch: (cause) =>
|
||||
new ConnectionPersistenceError({
|
||||
operation: "load-thread",
|
||||
stage: "parse",
|
||||
resource: "thread-cache",
|
||||
environmentId,
|
||||
threadId,
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
const stored = yield* Effect.fromResult(
|
||||
Schema.decodeUnknownResult(StoredThreadSnapshot)(parsed),
|
||||
).pipe(Effect.mapError((cause) => shellPersistenceError("load-thread", cause)));
|
||||
const stored = yield* decodeStoredThreadSnapshot(parsed).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ConnectionPersistenceError({
|
||||
operation: "load-thread",
|
||||
stage: "decode",
|
||||
resource: "thread-cache",
|
||||
environmentId,
|
||||
threadId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
return stored.environmentId === environmentId && stored.threadId === threadId
|
||||
? Option.some(stored.thread)
|
||||
: Option.none();
|
||||
@@ -361,14 +500,24 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
saveThread: (environmentId, thread) =>
|
||||
Effect.gen(function* () {
|
||||
const file = yield* threadSnapshotFile(environmentId, thread.id, "save-thread");
|
||||
const encoded = yield* Effect.fromResult(
|
||||
Schema.encodeUnknownResult(StoredThreadSnapshot)({
|
||||
schemaVersion: THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION,
|
||||
environmentId,
|
||||
threadId: thread.id,
|
||||
thread,
|
||||
}),
|
||||
).pipe(Effect.mapError((cause) => shellPersistenceError("save-thread", cause)));
|
||||
const encoded = yield* encodeStoredThreadSnapshot({
|
||||
schemaVersion: THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION,
|
||||
environmentId,
|
||||
threadId: thread.id,
|
||||
thread,
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ConnectionPersistenceError({
|
||||
operation: "save-thread",
|
||||
stage: "encode",
|
||||
resource: "thread-cache",
|
||||
environmentId,
|
||||
threadId: thread.id,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* Effect.try({
|
||||
try: () => {
|
||||
if (!file.exists) {
|
||||
@@ -376,36 +525,63 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
}
|
||||
file.write(JSON.stringify(encoded));
|
||||
},
|
||||
catch: (cause) => shellPersistenceError("save-thread", cause),
|
||||
catch: (cause) =>
|
||||
new ConnectionPersistenceError({
|
||||
operation: "save-thread",
|
||||
stage: "write",
|
||||
resource: "thread-cache",
|
||||
environmentId,
|
||||
threadId: thread.id,
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
}),
|
||||
removeThread: (environmentId, threadId) =>
|
||||
Effect.gen(function* () {
|
||||
const file = yield* threadSnapshotFile(environmentId, threadId, "remove-thread");
|
||||
if (file.exists) {
|
||||
file.delete();
|
||||
yield* Effect.try({
|
||||
try: () => file.delete(),
|
||||
catch: (cause) =>
|
||||
new ConnectionPersistenceError({
|
||||
operation: "remove-thread",
|
||||
stage: "remove",
|
||||
resource: "thread-cache",
|
||||
environmentId,
|
||||
threadId,
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
}
|
||||
}).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
cause._tag === "ConnectionPersistenceError"
|
||||
? cause
|
||||
: shellPersistenceError("remove-thread", cause),
|
||||
),
|
||||
),
|
||||
}),
|
||||
clear: (environmentId) =>
|
||||
Effect.gen(function* () {
|
||||
const file = yield* shellSnapshotFile(environmentId, "clear-environment");
|
||||
if (file.exists) {
|
||||
yield* Effect.try({
|
||||
try: () => file.delete(),
|
||||
catch: (cause) => shellPersistenceError("clear-environment", cause),
|
||||
catch: (cause) =>
|
||||
new ConnectionPersistenceError({
|
||||
operation: "clear-environment",
|
||||
stage: "remove",
|
||||
resource: "shell-cache",
|
||||
environmentId,
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
}
|
||||
const legacyFile = yield* legacyShellSnapshotFile(environmentId, "clear-environment");
|
||||
if (legacyFile.exists) {
|
||||
yield* Effect.try({
|
||||
try: () => legacyFile.delete(),
|
||||
catch: (cause) => shellPersistenceError("clear-environment", cause),
|
||||
catch: (cause) =>
|
||||
new ConnectionPersistenceError({
|
||||
operation: "clear-environment",
|
||||
stage: "remove",
|
||||
resource: "legacy-shell-cache",
|
||||
environmentId,
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
}
|
||||
const threadDirectory = yield* threadSnapshotDirectory(
|
||||
@@ -415,7 +591,14 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
if (threadDirectory.exists) {
|
||||
yield* Effect.try({
|
||||
try: () => threadDirectory.delete(),
|
||||
catch: (cause) => shellPersistenceError("clear-environment", cause),
|
||||
catch: (cause) =>
|
||||
new ConnectionPersistenceError({
|
||||
operation: "clear-environment",
|
||||
stage: "remove",
|
||||
resource: "thread-cache",
|
||||
environmentId,
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
}
|
||||
}),
|
||||
|
||||
@@ -9,8 +9,11 @@ import * as Effect from "effect/Effect";
|
||||
import { verifyDpopProof } from "@t3tools/shared/dpop";
|
||||
|
||||
import {
|
||||
CloudDpopProofError,
|
||||
CloudDpopStorageError,
|
||||
createDpopProof,
|
||||
generateDpopProofKeyPair,
|
||||
isCloudDpopError,
|
||||
loadOrCreateDpopProofKeyPair,
|
||||
cryptoLayer,
|
||||
} from "./dpop";
|
||||
@@ -95,7 +98,82 @@ describe("mobile DPoP", () => {
|
||||
|
||||
const error = yield* loadOrCreateDpopProofKeyPair().pipe(Effect.flip);
|
||||
|
||||
expect(error.message).toBe("Stored DPoP proof key is invalid.");
|
||||
expect(error).toBeInstanceOf(CloudDpopStorageError);
|
||||
expect(error).toMatchObject({
|
||||
operation: "decode",
|
||||
storageKey: "t3code.cloud.dpop-proof-key",
|
||||
});
|
||||
expect(isCloudDpopError(error)).toBe(true);
|
||||
}).pipe(Effect.provide(cryptoLayer)),
|
||||
);
|
||||
|
||||
it.effect("rejects stored key material whose public coordinates do not match", () =>
|
||||
Effect.gen(function* () {
|
||||
secureStore.clear();
|
||||
const generated = yield* generateDpopProofKeyPair();
|
||||
secureStore.set(
|
||||
"t3code.cloud.dpop-proof-key",
|
||||
JSON.stringify({ ...generated.privateJwk, x: generated.privateJwk.y }),
|
||||
);
|
||||
|
||||
const error = yield* loadOrCreateDpopProofKeyPair().pipe(Effect.flip);
|
||||
|
||||
expect(error).toBeInstanceOf(CloudDpopStorageError);
|
||||
expect(error).toMatchObject({
|
||||
operation: "restore",
|
||||
storageKey: "t3code.cloud.dpop-proof-key",
|
||||
});
|
||||
}).pipe(Effect.provide(cryptoLayer)),
|
||||
);
|
||||
|
||||
it.effect("preserves request context for an invalid proof URL", () =>
|
||||
Effect.gen(function* () {
|
||||
const proofKey = yield* generateDpopProofKeyPair();
|
||||
const error = yield* createDpopProof({
|
||||
method: "POST",
|
||||
url: "http://",
|
||||
proofKey,
|
||||
}).pipe(Effect.flip);
|
||||
|
||||
expect(error).toBeInstanceOf(CloudDpopProofError);
|
||||
expect(error).toMatchObject({
|
||||
operation: "normalize-url",
|
||||
method: "POST",
|
||||
requestTarget: "<invalid-url>",
|
||||
urlLength: "http://".length,
|
||||
thumbprint: proofKey.thumbprint,
|
||||
});
|
||||
expect(isCloudDpopError(error)).toBe(true);
|
||||
}).pipe(Effect.provide(cryptoLayer)),
|
||||
);
|
||||
|
||||
it.effect("redacts credentials and non-HTU URL components from proof failures", () =>
|
||||
Effect.gen(function* () {
|
||||
const proofKey = yield* generateDpopProofKeyPair();
|
||||
const url = "https://user:[email protected]/oauth/token?access_token=secret#fragment";
|
||||
const error = yield* createDpopProof({
|
||||
method: "POST",
|
||||
url,
|
||||
proofKey: {
|
||||
...proofKey,
|
||||
privateJwk: { ...proofKey.privateJwk, d: "%" },
|
||||
},
|
||||
}).pipe(Effect.flip);
|
||||
|
||||
expect(error).toBeInstanceOf(CloudDpopProofError);
|
||||
expect(error).toMatchObject({
|
||||
operation: "import-private-key",
|
||||
method: "POST",
|
||||
requestTarget: "https://example.com/oauth/token",
|
||||
urlLength: url.length,
|
||||
thumbprint: proofKey.thumbprint,
|
||||
});
|
||||
expect(error).not.toHaveProperty("url");
|
||||
expect(error.message).not.toContain("user");
|
||||
expect(error.message).not.toContain("password");
|
||||
expect(error.message).not.toContain("access_token");
|
||||
expect(error.message).not.toContain("secret");
|
||||
expect(error.message).not.toContain("fragment");
|
||||
}).pipe(Effect.provide(cryptoLayer)),
|
||||
);
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import * as Clock from "effect/Clock";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Encoding from "effect/Encoding";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Result from "effect/Result";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as ExpoCrypto from "expo-crypto";
|
||||
@@ -12,19 +12,91 @@ import {
|
||||
computeDpopAccessTokenHash,
|
||||
computeDpopJwkThumbprint,
|
||||
DpopPublicJwk,
|
||||
normalizeDpopHtu,
|
||||
redactDpopRequestTarget,
|
||||
} from "@t3tools/shared/dpop";
|
||||
import * as Layer from "effect/Layer";
|
||||
|
||||
export class CloudDpopError extends Data.TaggedError("CloudDpopError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
function cloudDpopError(message: string) {
|
||||
return (cause: unknown) => new CloudDpopError({ message, cause });
|
||||
export class CloudDpopStorageError extends Schema.TaggedErrorClass<CloudDpopStorageError>()(
|
||||
"CloudDpopStorageError",
|
||||
{
|
||||
operation: Schema.Literals(["read", "decode", "restore", "encode", "write"]),
|
||||
storageKey: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Mobile DPoP key storage operation "${this.operation}" failed for key "${this.storageKey}".`;
|
||||
}
|
||||
}
|
||||
|
||||
export class CloudDpopKeyError extends Schema.TaggedErrorClass<CloudDpopKeyError>()(
|
||||
"CloudDpopKeyError",
|
||||
{
|
||||
operation: Schema.Literals(["generate-randomness", "derive-public-key"]),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Mobile DPoP key operation "${this.operation}" failed.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class CloudDpopProofError extends Schema.TaggedErrorClass<CloudDpopProofError>()(
|
||||
"CloudDpopProofError",
|
||||
{
|
||||
operation: Schema.Literals([
|
||||
"import-private-key",
|
||||
"generate-id",
|
||||
"normalize-url",
|
||||
"encode-header",
|
||||
"encode-payload",
|
||||
"hash-signing-input",
|
||||
"sign",
|
||||
]),
|
||||
method: Schema.String,
|
||||
requestTarget: Schema.String,
|
||||
urlLength: Schema.Number,
|
||||
thumbprint: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Mobile DPoP proof operation "${this.operation}" failed for ${this.method.toUpperCase()} ${this.requestTarget}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DpopPublicKeyFormatError extends Schema.TaggedErrorClass<DpopPublicKeyFormatError>()(
|
||||
"DpopPublicKeyFormatError",
|
||||
{
|
||||
byteLength: Schema.Number,
|
||||
firstByte: Schema.optional(Schema.Number),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
const prefix =
|
||||
this.firstByte === undefined
|
||||
? "no prefix byte"
|
||||
: `prefix 0x${this.firstByte.toString(16).padStart(2, "0")}`;
|
||||
return `Expected a 65-byte uncompressed P-256 public key beginning with 0x04; received ${this.byteLength} bytes with ${prefix}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DpopStoredPublicKeyMismatchError extends Schema.TaggedErrorClass<DpopStoredPublicKeyMismatchError>()(
|
||||
"DpopStoredPublicKeyMismatchError",
|
||||
{},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Stored DPoP private and public key material do not match.";
|
||||
}
|
||||
}
|
||||
|
||||
export const CloudDpopError = Schema.Union([
|
||||
CloudDpopStorageError,
|
||||
CloudDpopKeyError,
|
||||
CloudDpopProofError,
|
||||
]);
|
||||
export type CloudDpopError = typeof CloudDpopError.Type;
|
||||
export const isCloudDpopError = Schema.is(CloudDpopError);
|
||||
|
||||
const DpopPrivateJwkSchema = Schema.Struct({
|
||||
...DpopPublicJwk.fields,
|
||||
d: Schema.String,
|
||||
@@ -97,29 +169,12 @@ function base64UrlToBytes(value: string): Uint8Array {
|
||||
return Result.getOrThrow(Encoding.decodeBase64Url(value));
|
||||
}
|
||||
|
||||
function sha256Digest(
|
||||
data: Uint8Array,
|
||||
message: string,
|
||||
): Effect.Effect<Uint8Array, CloudDpopError, Crypto.Crypto> {
|
||||
return Crypto.Crypto.pipe(
|
||||
Effect.flatMap((crypto) => crypto.digest("SHA-256", data)),
|
||||
Effect.mapError(cloudDpopError(message)),
|
||||
);
|
||||
}
|
||||
|
||||
function secureRandomBytes(
|
||||
byteCount: number,
|
||||
message: string,
|
||||
): Effect.Effect<Uint8Array, CloudDpopError, Crypto.Crypto> {
|
||||
return Crypto.Crypto.pipe(
|
||||
Effect.flatMap((crypto) => crypto.randomBytes(byteCount)),
|
||||
Effect.mapError(cloudDpopError(message)),
|
||||
);
|
||||
}
|
||||
|
||||
function publicJwkFromUncompressedPublicKey(publicKey: Uint8Array): DpopPublicJwk {
|
||||
if (publicKey.length !== 65 || publicKey[0] !== 0x04) {
|
||||
throw new Error("Generated DPoP public key is not an uncompressed P-256 point.");
|
||||
throw new DpopPublicKeyFormatError({
|
||||
byteLength: publicKey.length,
|
||||
...(publicKey[0] === undefined ? {} : { firstByte: publicKey[0] }),
|
||||
});
|
||||
}
|
||||
return {
|
||||
kty: "EC",
|
||||
@@ -144,14 +199,16 @@ export function generateDpopProofKeyPair(): Effect.Effect<
|
||||
return Effect.gen(function* () {
|
||||
let privateKey: Uint8Array;
|
||||
do {
|
||||
privateKey = yield* secureRandomBytes(
|
||||
p256.CURVE.nByteLength,
|
||||
"Could not generate DPoP key pair randomness.",
|
||||
privateKey = yield* Crypto.Crypto.pipe(
|
||||
Effect.flatMap((crypto) => crypto.randomBytes(p256.CURVE.nByteLength)),
|
||||
Effect.mapError(
|
||||
(cause) => new CloudDpopKeyError({ operation: "generate-randomness", cause }),
|
||||
),
|
||||
);
|
||||
} while (!p256.utils.isValidPrivateKey(privateKey));
|
||||
const publicJwk = yield* Effect.try({
|
||||
try: () => publicJwkFromUncompressedPublicKey(p256.getPublicKey(privateKey, false)),
|
||||
catch: cloudDpopError("Generated DPoP public key is invalid."),
|
||||
catch: (cause) => new CloudDpopKeyError({ operation: "derive-public-key", cause }),
|
||||
});
|
||||
const thumbprint = computeDpopJwkThumbprint(publicJwk);
|
||||
return {
|
||||
@@ -170,11 +227,23 @@ export function loadOrCreateDpopProofKeyPair(): Effect.Effect<
|
||||
return Effect.gen(function* () {
|
||||
const stored = yield* Effect.tryPromise({
|
||||
try: () => SecureStore.getItemAsync(DPOP_PROOF_KEY_STORAGE_KEY),
|
||||
catch: cloudDpopError("Could not read the DPoP proof key."),
|
||||
catch: (cause) =>
|
||||
new CloudDpopStorageError({
|
||||
operation: "read",
|
||||
storageKey: DPOP_PROOF_KEY_STORAGE_KEY,
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
if (stored) {
|
||||
const storedPrivateJwk = yield* decodeDpopPrivateJwkJson(stored).pipe(
|
||||
Effect.mapError(cloudDpopError("Stored DPoP proof key is invalid.")),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new CloudDpopStorageError({
|
||||
operation: "decode",
|
||||
storageKey: DPOP_PROOF_KEY_STORAGE_KEY,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const restored = yield* Effect.try({
|
||||
try: () => {
|
||||
@@ -183,11 +252,16 @@ export function loadOrCreateDpopProofKeyPair(): Effect.Effect<
|
||||
p256.getPublicKey(privateKey, false),
|
||||
);
|
||||
if (publicJwk.x !== storedPrivateJwk.x || publicJwk.y !== storedPrivateJwk.y) {
|
||||
throw new Error("Stored DPoP key does not match its public key.");
|
||||
throw new DpopStoredPublicKeyMismatchError();
|
||||
}
|
||||
return { privateJwk: storedPrivateJwk, publicJwk };
|
||||
},
|
||||
catch: cloudDpopError("Stored DPoP proof key is invalid."),
|
||||
catch: (cause) =>
|
||||
new CloudDpopStorageError({
|
||||
operation: "restore",
|
||||
storageKey: DPOP_PROOF_KEY_STORAGE_KEY,
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
return {
|
||||
...restored,
|
||||
@@ -196,23 +270,28 @@ export function loadOrCreateDpopProofKeyPair(): Effect.Effect<
|
||||
}
|
||||
const generated = yield* generateDpopProofKeyPair();
|
||||
const encodedPrivateJwk = yield* encodeDpopPrivateJwkJson(generated.privateJwk).pipe(
|
||||
Effect.mapError(cloudDpopError("Could not encode the DPoP proof key.")),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new CloudDpopStorageError({
|
||||
operation: "encode",
|
||||
storageKey: DPOP_PROOF_KEY_STORAGE_KEY,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* Effect.tryPromise({
|
||||
try: () => SecureStore.setItemAsync(DPOP_PROOF_KEY_STORAGE_KEY, encodedPrivateJwk),
|
||||
catch: cloudDpopError("Could not store the DPoP proof key."),
|
||||
catch: (cause) =>
|
||||
new CloudDpopStorageError({
|
||||
operation: "write",
|
||||
storageKey: DPOP_PROOF_KEY_STORAGE_KEY,
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
return generated;
|
||||
});
|
||||
}
|
||||
|
||||
function normalizeHtu(url: string): Effect.Effect<string, CloudDpopError> {
|
||||
const normalized = normalizeDpopHtu(url);
|
||||
return normalized
|
||||
? Effect.succeed(normalized)
|
||||
: Effect.fail(new CloudDpopError({ message: "DPoP URL is invalid." }));
|
||||
}
|
||||
|
||||
export function createDpopProof(input: {
|
||||
readonly method: string;
|
||||
readonly url: string;
|
||||
@@ -225,23 +304,69 @@ export function createDpopProof(input: {
|
||||
> {
|
||||
return Effect.gen(function* () {
|
||||
const keyPair = input.proofKey ?? (yield* generateDpopProofKeyPair());
|
||||
const requestTarget = redactDpopRequestTarget(input.url);
|
||||
const urlLength = input.url.length;
|
||||
const privateKey = yield* Effect.try({
|
||||
try: () => base64UrlToBytes(keyPair.privateJwk.d),
|
||||
catch: cloudDpopError("Could not import DPoP private key."),
|
||||
catch: (cause) =>
|
||||
new CloudDpopProofError({
|
||||
operation: "import-private-key",
|
||||
method: input.method,
|
||||
requestTarget,
|
||||
urlLength,
|
||||
thumbprint: keyPair.thumbprint,
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
const nowMs = yield* Clock.currentTimeMillis;
|
||||
const jti = yield* Crypto.Crypto.pipe(
|
||||
Effect.flatMap((crypto) => crypto.randomUUIDv4),
|
||||
Effect.mapError(cloudDpopError("Could not generate DPoP proof identifier.")),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new CloudDpopProofError({
|
||||
operation: "generate-id",
|
||||
method: input.method,
|
||||
requestTarget,
|
||||
urlLength,
|
||||
thumbprint: keyPair.thumbprint,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const htu = yield* normalizeHtu(input.url);
|
||||
const htu = yield* Effect.try({
|
||||
try: () => {
|
||||
const parsed = new URL(input.url);
|
||||
parsed.hash = "";
|
||||
parsed.search = "";
|
||||
return parsed.toString();
|
||||
},
|
||||
catch: (cause) =>
|
||||
new CloudDpopProofError({
|
||||
operation: "normalize-url",
|
||||
method: input.method,
|
||||
requestTarget,
|
||||
urlLength,
|
||||
thumbprint: keyPair.thumbprint,
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
const header = yield* encodeDpopJwtHeaderJson({
|
||||
typ: "dpop+jwt",
|
||||
alg: "ES256",
|
||||
jwk: keyPair.publicJwk,
|
||||
}).pipe(
|
||||
Effect.map(Encoding.encodeBase64Url),
|
||||
Effect.mapError(cloudDpopError("Could not encode DPoP proof header.")),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new CloudDpopProofError({
|
||||
operation: "encode-header",
|
||||
method: input.method,
|
||||
requestTarget,
|
||||
urlLength,
|
||||
thumbprint: keyPair.thumbprint,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const ath = input.accessToken ? computeDpopAccessTokenHash(input.accessToken) : null;
|
||||
const payload = yield* encodeDpopJwtPayloadJson({
|
||||
@@ -252,15 +377,45 @@ export function createDpopProof(input: {
|
||||
...(ath ? { ath } : {}),
|
||||
}).pipe(
|
||||
Effect.map(Encoding.encodeBase64Url),
|
||||
Effect.mapError(cloudDpopError("Could not encode DPoP proof payload.")),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new CloudDpopProofError({
|
||||
operation: "encode-payload",
|
||||
method: input.method,
|
||||
requestTarget,
|
||||
urlLength,
|
||||
thumbprint: keyPair.thumbprint,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const signatureInputHash = yield* sha256Digest(
|
||||
new TextEncoder().encode(`${header}.${payload}`),
|
||||
"Could not hash DPoP signing input.",
|
||||
const signatureInputHash = yield* Crypto.Crypto.pipe(
|
||||
Effect.flatMap((crypto) =>
|
||||
crypto.digest("SHA-256", new TextEncoder().encode(`${header}.${payload}`)),
|
||||
),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new CloudDpopProofError({
|
||||
operation: "hash-signing-input",
|
||||
method: input.method,
|
||||
requestTarget,
|
||||
urlLength,
|
||||
thumbprint: keyPair.thumbprint,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const signature = yield* Effect.try({
|
||||
try: () => p256.sign(signatureInputHash, privateKey, { prehash: false }).toCompactRawBytes(),
|
||||
catch: cloudDpopError("Could not sign DPoP proof."),
|
||||
catch: (cause) =>
|
||||
new CloudDpopProofError({
|
||||
operation: "sign",
|
||||
method: input.method,
|
||||
requestTarget,
|
||||
urlLength,
|
||||
thumbprint: keyPair.thumbprint,
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
return {
|
||||
proof: `${header}.${payload}.${Encoding.encodeBase64Url(signature)}`,
|
||||
|
||||
@@ -9,9 +9,11 @@ import { remoteHttpClientLayer } from "@t3tools/client-runtime/rpc";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
|
||||
import {
|
||||
CloudEnvironmentLinkOperationError,
|
||||
cloudEnvironmentsPendingStatus,
|
||||
linkEnvironmentToCloud,
|
||||
connectCloudEnvironment,
|
||||
isCloudEnvironmentLinkError,
|
||||
listCloudEnvironments,
|
||||
listCloudEnvironmentsWithStatus,
|
||||
normalizeRelayBaseUrl,
|
||||
@@ -148,6 +150,46 @@ describe("mobile cloud link environment client", () => {
|
||||
createProofMock.mockClear();
|
||||
});
|
||||
|
||||
it("keeps URL secrets out of operation error diagnostics", () => {
|
||||
const relayUrl =
|
||||
"https://relay-user:[email protected]/private/workspace?access_token=relay-secret#relay-fragment";
|
||||
const httpBaseUrl =
|
||||
"https://desktop-user:[email protected]/private/workspace?access_token=desktop-secret#desktop-fragment";
|
||||
const cause = new Error("request failed");
|
||||
|
||||
const error = CloudEnvironmentLinkOperationError.fromCause({
|
||||
action: "link the environment",
|
||||
cause,
|
||||
environmentId: "env-1",
|
||||
relayUrl,
|
||||
httpBaseUrl,
|
||||
});
|
||||
|
||||
expect(error).toMatchObject({
|
||||
relayUrlInputLength: relayUrl.length,
|
||||
relayUrlProtocol: "https:",
|
||||
relayUrlHostname: "relay.example.test",
|
||||
httpBaseUrlInputLength: httpBaseUrl.length,
|
||||
httpBaseUrlProtocol: "https:",
|
||||
httpBaseUrlHostname: "desktop.example.test",
|
||||
});
|
||||
const serialized = JSON.stringify(error);
|
||||
for (const secret of [
|
||||
"relay-user",
|
||||
"relay-password",
|
||||
"relay-secret",
|
||||
"relay-fragment",
|
||||
"/private/workspace",
|
||||
"desktop-user",
|
||||
"desktop-password",
|
||||
"desktop-secret",
|
||||
"desktop-fragment",
|
||||
]) {
|
||||
expect(serialized).not.toContain(secret);
|
||||
expect(error.message).not.toContain(secret);
|
||||
}
|
||||
});
|
||||
|
||||
it("normalizes configured relay base URLs before building DPoP-bound requests", () => {
|
||||
expect(normalizeRelayBaseUrl(" https://relay.example.test/// ")).toBe(
|
||||
"https://relay.example.test",
|
||||
@@ -235,9 +277,14 @@ describe("mobile cloud link environment client", () => {
|
||||
listCloudEnvironments({ clerkToken: "clerk-token" }),
|
||||
).pipe(Effect.flip);
|
||||
expect(error).toMatchObject({
|
||||
_tag: "CloudEnvironmentLinkError",
|
||||
message: "https://relay.example.test/v1/environments failed",
|
||||
_tag: "CloudEnvironmentLinkOperationError",
|
||||
action: "list cloud environments",
|
||||
relayUrlInputLength: "https://relay.example.test".length,
|
||||
relayUrlProtocol: "https:",
|
||||
relayUrlHostname: "relay.example.test",
|
||||
});
|
||||
expect(error.message).toBe("Could not list cloud environments.");
|
||||
expect(isCloudEnvironmentLinkError(error)).toBe(true);
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -498,7 +545,7 @@ describe("mobile cloud link environment client", () => {
|
||||
label: "Desktop",
|
||||
},
|
||||
status: null,
|
||||
statusError: "https://relay.example.test/v1/environments/env-1/status failed",
|
||||
statusError: 'Could not read cloud environment status for environment "env-1".',
|
||||
},
|
||||
]);
|
||||
}),
|
||||
@@ -562,7 +609,8 @@ describe("mobile cloud link environment client", () => {
|
||||
label: "Desktop",
|
||||
},
|
||||
status: null,
|
||||
statusError: "Relay returned status for a different environment.",
|
||||
statusError:
|
||||
'The environment status response identified environment "env-other" instead of "env-1".',
|
||||
},
|
||||
]);
|
||||
}),
|
||||
@@ -590,13 +638,55 @@ describe("mobile cloud link environment client", () => {
|
||||
}),
|
||||
).pipe(Effect.flip);
|
||||
expect(error).toMatchObject({
|
||||
_tag: "CloudEnvironmentLinkError",
|
||||
message: "Relay returned credentials for a different environment.",
|
||||
_tag: "CloudEnvironmentIdMismatchError",
|
||||
source: "environment link response",
|
||||
expectedEnvironmentId: "env-1",
|
||||
actualEnvironmentId: "env-other",
|
||||
});
|
||||
expect(fetchMock).toHaveBeenCalledTimes(3);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reports invalid endpoint URLs with redacted diagnostics", () =>
|
||||
Effect.gen(function* () {
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi.fn(() => Promise.resolve(Response.json(validLinkChallengeResponse()))),
|
||||
);
|
||||
|
||||
const httpBaseUrl =
|
||||
"https://desktop-user:desktop-password@[invalid-host]/private/workspace?access_token=desktop-secret#desktop-fragment";
|
||||
const error = yield* withCloudServices(
|
||||
linkEnvironmentToCloud({
|
||||
clerkToken: "clerk-token",
|
||||
connection: {
|
||||
...savedConnection,
|
||||
httpBaseUrl,
|
||||
},
|
||||
}),
|
||||
).pipe(Effect.flip);
|
||||
|
||||
expect(error).toMatchObject({
|
||||
_tag: "CloudEnvironmentLinkOperationError",
|
||||
action: "derive the environment endpoint origin",
|
||||
environmentId: "env-1",
|
||||
httpBaseUrlInputLength: httpBaseUrl.length,
|
||||
});
|
||||
expect(error).not.toHaveProperty("httpBaseUrl");
|
||||
const serialized = JSON.stringify({ ...error, cause: undefined });
|
||||
for (const secret of [
|
||||
"desktop-user",
|
||||
"desktop-password",
|
||||
"/private/workspace",
|
||||
"desktop-secret",
|
||||
"desktop-fragment",
|
||||
]) {
|
||||
expect(serialized).not.toContain(secret);
|
||||
expect(error.message).not.toContain(secret);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves typed local environment failures while obtaining a link proof", () =>
|
||||
Effect.gen(function* () {
|
||||
const fetchMock = vi.fn((url: string | URL) => {
|
||||
@@ -607,7 +697,8 @@ describe("mobile cloud link environment client", () => {
|
||||
Response.json(
|
||||
{
|
||||
_tag: "EnvironmentHttpUnauthorizedError",
|
||||
message: "Invalid environment bearer session.",
|
||||
reason: "cloud_cli_authorization_required",
|
||||
message: "Run `t3 connect link` to authorize this environment.",
|
||||
},
|
||||
{ status: 401 },
|
||||
),
|
||||
@@ -621,9 +712,20 @@ describe("mobile cloud link environment client", () => {
|
||||
connection: savedConnection,
|
||||
}),
|
||||
).pipe(Effect.flip);
|
||||
expect(error._tag).toBe("CloudEnvironmentLinkError");
|
||||
expect(error).toMatchObject({
|
||||
_tag: "CloudEnvironmentLinkOperationError",
|
||||
action: "obtain an environment link proof",
|
||||
environmentId: "env-1",
|
||||
httpBaseUrlInputLength: "https://desktop.example.test/".length,
|
||||
httpBaseUrlProtocol: "https:",
|
||||
httpBaseUrlHostname: "desktop.example.test",
|
||||
environmentError: {
|
||||
_tag: "EnvironmentHttpUnauthorizedError",
|
||||
reason: "cloud_cli_authorization_required",
|
||||
},
|
||||
});
|
||||
expect(error.message).toBe(
|
||||
"Could not obtain environment link proof: Invalid environment bearer session.",
|
||||
'Could not obtain an environment link proof for environment "env-1".',
|
||||
);
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2);
|
||||
}),
|
||||
@@ -659,11 +761,19 @@ describe("mobile cloud link environment client", () => {
|
||||
}),
|
||||
).pipe(Effect.flip);
|
||||
expect(error).toMatchObject({
|
||||
_tag: "CloudEnvironmentLinkError",
|
||||
message:
|
||||
"https://relay.example.test/v1/client/environment-links failed: Relay rejected the environment link proof (origin_not_allowed).",
|
||||
_tag: "CloudEnvironmentLinkOperationError",
|
||||
action: "link the environment",
|
||||
environmentId: "env-1",
|
||||
relayUrlInputLength: "https://relay.example.test".length,
|
||||
relayUrlProtocol: "https:",
|
||||
relayUrlHostname: "relay.example.test",
|
||||
traceId: "trace-test",
|
||||
relayError: {
|
||||
_tag: "RelayEnvironmentLinkProofInvalidError",
|
||||
reason: "origin_not_allowed",
|
||||
},
|
||||
});
|
||||
expect(error.message).toBe('Could not link the environment for environment "env-1".');
|
||||
expect(fetchMock).toHaveBeenCalledTimes(3);
|
||||
}),
|
||||
);
|
||||
@@ -696,8 +806,10 @@ describe("mobile cloud link environment client", () => {
|
||||
}),
|
||||
).pipe(Effect.flip);
|
||||
expect(error).toMatchObject({
|
||||
_tag: "CloudEnvironmentLinkError",
|
||||
message: "Relay returned credentials for a different endpoint provider.",
|
||||
_tag: "CloudEnvironmentEndpointProviderMismatchError",
|
||||
environmentId: "env-1",
|
||||
expectedProviderKind: "cloudflare_tunnel",
|
||||
actualProviderKind: "manual",
|
||||
});
|
||||
expect(fetchMock).toHaveBeenCalledTimes(3);
|
||||
}),
|
||||
@@ -962,8 +1074,10 @@ describe("mobile cloud link environment client", () => {
|
||||
}),
|
||||
).pipe(Effect.flip);
|
||||
expect(error).toMatchObject({
|
||||
_tag: "CloudEnvironmentLinkError",
|
||||
message: "Relay returned credentials for a different environment.",
|
||||
_tag: "CloudEnvironmentIdMismatchError",
|
||||
source: "environment connect response",
|
||||
expectedEnvironmentId: "env-1",
|
||||
actualEnvironmentId: "env-other",
|
||||
});
|
||||
}),
|
||||
);
|
||||
@@ -1005,11 +1119,21 @@ describe("mobile cloud link environment client", () => {
|
||||
}),
|
||||
).pipe(Effect.flip);
|
||||
expect(error).toMatchObject({
|
||||
_tag: "CloudEnvironmentLinkError",
|
||||
message:
|
||||
"https://relay.example.test/v1/environments/env-1/connect failed: Relay rejected the DPoP proof.",
|
||||
_tag: "CloudEnvironmentLinkOperationError",
|
||||
action: "connect to the cloud environment",
|
||||
environmentId: "env-1",
|
||||
relayUrlInputLength: "https://relay.example.test".length,
|
||||
relayUrlProtocol: "https:",
|
||||
relayUrlHostname: "relay.example.test",
|
||||
traceId: "trace-connect",
|
||||
relayError: {
|
||||
_tag: "RelayAuthInvalidError",
|
||||
reason: "invalid_dpop",
|
||||
},
|
||||
});
|
||||
expect(error.message).toBe(
|
||||
'Could not connect to the cloud environment for environment "env-1".',
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -1051,8 +1175,23 @@ describe("mobile cloud link environment client", () => {
|
||||
}),
|
||||
).pipe(Effect.flip);
|
||||
expect(error).toMatchObject({
|
||||
_tag: "CloudEnvironmentLinkError",
|
||||
message: "Relay returned credentials for a different endpoint.",
|
||||
_tag: "CloudEnvironmentEndpointMismatchError",
|
||||
source: "environment connect response",
|
||||
environmentId: "env-1",
|
||||
expectedProviderKind: "cloudflare_tunnel",
|
||||
expectedHttpBaseUrlInputLength: "https://desktop.example.test/".length,
|
||||
expectedHttpBaseUrlProtocol: "https:",
|
||||
expectedHttpBaseUrlHostname: "desktop.example.test",
|
||||
expectedWsBaseUrlInputLength: "wss://desktop.example.test/ws".length,
|
||||
expectedWsBaseUrlProtocol: "wss:",
|
||||
expectedWsBaseUrlHostname: "desktop.example.test",
|
||||
actualProviderKind: "cloudflare_tunnel",
|
||||
actualHttpBaseUrlInputLength: "https://other-desktop.example.test/".length,
|
||||
actualHttpBaseUrlProtocol: "https:",
|
||||
actualHttpBaseUrlHostname: "other-desktop.example.test",
|
||||
actualWsBaseUrlInputLength: "wss://other-desktop.example.test/ws".length,
|
||||
actualWsBaseUrlProtocol: "wss:",
|
||||
actualWsBaseUrlHostname: "other-desktop.example.test",
|
||||
});
|
||||
}),
|
||||
);
|
||||
@@ -1105,8 +1244,10 @@ describe("mobile cloud link environment client", () => {
|
||||
}),
|
||||
).pipe(Effect.flip);
|
||||
expect(error).toMatchObject({
|
||||
_tag: "CloudEnvironmentLinkError",
|
||||
message: "Connected endpoint descriptor does not match the selected environment.",
|
||||
_tag: "CloudEnvironmentIdMismatchError",
|
||||
source: "connected environment descriptor",
|
||||
expectedEnvironmentId: "env-1",
|
||||
actualEnvironmentId: "env-other",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
@@ -17,16 +16,17 @@ import {
|
||||
RelayEnvironmentConnectScope,
|
||||
RelayEnvironmentStatusScope,
|
||||
type RelayDpopAccessTokenScope,
|
||||
type RelayProtectedError as RelayProtectedErrorType,
|
||||
type RelayClientEnvironmentRecord,
|
||||
type RelayEnvironmentStatusResponse as RelayEnvironmentStatusResponseType,
|
||||
type RelayManagedEndpointProviderKind,
|
||||
RelayManagedEndpointProviderKind,
|
||||
RelayProtectedError,
|
||||
} from "@t3tools/contracts/relay";
|
||||
import { exchangeRemoteDpopAccessToken } from "@t3tools/client-runtime/authorization";
|
||||
import { fetchRemoteEnvironmentDescriptor } from "@t3tools/client-runtime/environment";
|
||||
import { findErrorTraceId } from "@t3tools/client-runtime/errors";
|
||||
import { ManagedRelay } from "@t3tools/client-runtime/relay";
|
||||
import { makeEnvironmentHttpApiClient } from "@t3tools/client-runtime/rpc";
|
||||
import { getUrlDiagnostics } from "@t3tools/shared/urlDiagnostics";
|
||||
|
||||
import { authClientMetadata } from "../../lib/authClientMetadata";
|
||||
import type { SavedRemoteConnection } from "../../lib/connection";
|
||||
@@ -50,11 +50,268 @@ function readRelayUrl(): string | null {
|
||||
return resolveCloudPublicConfig().relay.url;
|
||||
}
|
||||
|
||||
export class CloudEnvironmentLinkError extends Data.TaggedError("CloudEnvironmentLinkError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
readonly traceId?: string;
|
||||
}> {}
|
||||
const EnvironmentCloudApiError = Schema.Union([
|
||||
EnvironmentHttpBadRequestError,
|
||||
EnvironmentHttpUnauthorizedError,
|
||||
EnvironmentHttpForbiddenError,
|
||||
EnvironmentHttpConflictError,
|
||||
EnvironmentHttpInternalServerError,
|
||||
EnvironmentCloudEndpointUnavailableError,
|
||||
]);
|
||||
type EnvironmentCloudApiError = typeof EnvironmentCloudApiError.Type;
|
||||
const isEnvironmentCloudApiError = Schema.is(EnvironmentCloudApiError);
|
||||
const isManagedRelayRequestFailedError = Schema.is(ManagedRelay.ManagedRelayRequestFailedError);
|
||||
|
||||
export const CloudEnvironmentLinkAction = Schema.Literals([
|
||||
"load the mobile device id",
|
||||
"load mobile notification preferences",
|
||||
"create an environment link challenge",
|
||||
"obtain an environment link proof",
|
||||
"link the environment",
|
||||
"configure environment relay access",
|
||||
"list cloud environments",
|
||||
"read cloud environment status",
|
||||
"connect to the cloud environment",
|
||||
"fetch the connected environment descriptor",
|
||||
"create a bootstrap DPoP proof",
|
||||
"exchange a managed endpoint DPoP access token",
|
||||
"derive the environment endpoint origin",
|
||||
"initialize the environment HTTP client",
|
||||
"parse the managed endpoint URL",
|
||||
]);
|
||||
export type CloudEnvironmentLinkAction = typeof CloudEnvironmentLinkAction.Type;
|
||||
|
||||
function relayUrlDiagnosticFields(relayUrl: string | undefined) {
|
||||
if (relayUrl === undefined) {
|
||||
return {};
|
||||
}
|
||||
const diagnostics = getUrlDiagnostics(relayUrl);
|
||||
return {
|
||||
relayUrlInputLength: diagnostics.inputLength,
|
||||
...(diagnostics.protocol === undefined ? {} : { relayUrlProtocol: diagnostics.protocol }),
|
||||
...(diagnostics.hostname === undefined ? {} : { relayUrlHostname: diagnostics.hostname }),
|
||||
};
|
||||
}
|
||||
|
||||
function httpBaseUrlDiagnosticFields(httpBaseUrl: string | undefined) {
|
||||
if (httpBaseUrl === undefined) {
|
||||
return {};
|
||||
}
|
||||
const diagnostics = getUrlDiagnostics(httpBaseUrl);
|
||||
return {
|
||||
httpBaseUrlInputLength: diagnostics.inputLength,
|
||||
...(diagnostics.protocol === undefined ? {} : { httpBaseUrlProtocol: diagnostics.protocol }),
|
||||
...(diagnostics.hostname === undefined ? {} : { httpBaseUrlHostname: diagnostics.hostname }),
|
||||
};
|
||||
}
|
||||
|
||||
export class CloudEnvironmentLinkOperationError extends Schema.TaggedErrorClass<CloudEnvironmentLinkOperationError>()(
|
||||
"CloudEnvironmentLinkOperationError",
|
||||
{
|
||||
action: CloudEnvironmentLinkAction,
|
||||
environmentId: Schema.optionalKey(Schema.String),
|
||||
relayUrlInputLength: Schema.optionalKey(Schema.Number),
|
||||
relayUrlProtocol: Schema.optionalKey(Schema.String),
|
||||
relayUrlHostname: Schema.optionalKey(Schema.String),
|
||||
httpBaseUrlInputLength: Schema.optionalKey(Schema.Number),
|
||||
httpBaseUrlProtocol: Schema.optionalKey(Schema.String),
|
||||
httpBaseUrlHostname: Schema.optionalKey(Schema.String),
|
||||
traceId: Schema.optionalKey(Schema.String),
|
||||
relayError: Schema.optionalKey(RelayProtectedError),
|
||||
environmentError: Schema.optionalKey(EnvironmentCloudApiError),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
static fromCause(input: {
|
||||
readonly action: CloudEnvironmentLinkAction;
|
||||
readonly cause: unknown;
|
||||
readonly environmentId?: string;
|
||||
readonly relayUrl?: string;
|
||||
readonly httpBaseUrl?: string;
|
||||
}): CloudEnvironmentLinkOperationError {
|
||||
const relayFailure = isManagedRelayRequestFailedError(input.cause) ? input.cause : undefined;
|
||||
const environmentError = CloudEnvironmentLinkOperationError.findEnvironmentApiError(
|
||||
input.cause,
|
||||
);
|
||||
const traceId = relayFailure?.traceId ?? findErrorTraceId(input.cause);
|
||||
return new CloudEnvironmentLinkOperationError({
|
||||
action: input.action,
|
||||
cause: input.cause,
|
||||
...(input.environmentId === undefined ? {} : { environmentId: input.environmentId }),
|
||||
...relayUrlDiagnosticFields(input.relayUrl),
|
||||
...httpBaseUrlDiagnosticFields(input.httpBaseUrl),
|
||||
...(traceId === null || traceId === undefined ? {} : { traceId }),
|
||||
...(relayFailure?.relayError === undefined ? {} : { relayError: relayFailure.relayError }),
|
||||
...(environmentError === undefined ? {} : { environmentError }),
|
||||
});
|
||||
}
|
||||
|
||||
private static findEnvironmentApiError(cause: unknown): EnvironmentCloudApiError | undefined {
|
||||
const seen = new Set<unknown>();
|
||||
let current = cause;
|
||||
while (typeof current === "object" && current !== null && !seen.has(current)) {
|
||||
if (isEnvironmentCloudApiError(current)) {
|
||||
return current;
|
||||
}
|
||||
seen.add(current);
|
||||
current = "cause" in current ? current.cause : undefined;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
const environment =
|
||||
this.environmentId === undefined ? "" : ` for environment "${this.environmentId}"`;
|
||||
return `Could not ${this.action}${environment}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class CloudRelayUrlNotConfiguredError extends Schema.TaggedErrorClass<CloudRelayUrlNotConfiguredError>()(
|
||||
"CloudRelayUrlNotConfiguredError",
|
||||
{},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Relay URL is not configured.";
|
||||
}
|
||||
}
|
||||
|
||||
export class CloudEnvironmentLocalBearerRequiredError extends Schema.TaggedErrorClass<CloudEnvironmentLocalBearerRequiredError>()(
|
||||
"CloudEnvironmentLocalBearerRequiredError",
|
||||
{
|
||||
environmentId: Schema.String,
|
||||
httpBaseUrlInputLength: Schema.Number,
|
||||
httpBaseUrlProtocol: Schema.optionalKey(Schema.String),
|
||||
httpBaseUrlHostname: Schema.optionalKey(Schema.String),
|
||||
},
|
||||
) {
|
||||
static fromConnection(input: {
|
||||
readonly environmentId: string;
|
||||
readonly httpBaseUrl: string;
|
||||
}): CloudEnvironmentLocalBearerRequiredError {
|
||||
const diagnostics = getUrlDiagnostics(input.httpBaseUrl);
|
||||
return new CloudEnvironmentLocalBearerRequiredError({
|
||||
environmentId: input.environmentId,
|
||||
httpBaseUrlInputLength: diagnostics.inputLength,
|
||||
...(diagnostics.protocol === undefined ? {} : { httpBaseUrlProtocol: diagnostics.protocol }),
|
||||
...(diagnostics.hostname === undefined ? {} : { httpBaseUrlHostname: diagnostics.hostname }),
|
||||
});
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return "Only a locally paired bearer connection can be linked to the cloud.";
|
||||
}
|
||||
}
|
||||
|
||||
export class CloudEnvironmentIdMismatchError extends Schema.TaggedErrorClass<CloudEnvironmentIdMismatchError>()(
|
||||
"CloudEnvironmentIdMismatchError",
|
||||
{
|
||||
source: Schema.Literals([
|
||||
"environment link response",
|
||||
"environment status response",
|
||||
"environment status descriptor",
|
||||
"environment connect response",
|
||||
"connected environment descriptor",
|
||||
]),
|
||||
expectedEnvironmentId: Schema.String,
|
||||
actualEnvironmentId: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `The ${this.source} identified environment "${this.actualEnvironmentId}" instead of "${this.expectedEnvironmentId}".`;
|
||||
}
|
||||
}
|
||||
|
||||
export class CloudEnvironmentEndpointMismatchError extends Schema.TaggedErrorClass<CloudEnvironmentEndpointMismatchError>()(
|
||||
"CloudEnvironmentEndpointMismatchError",
|
||||
{
|
||||
source: Schema.Literals(["environment status response", "environment connect response"]),
|
||||
environmentId: Schema.String,
|
||||
expectedProviderKind: RelayManagedEndpointProviderKind,
|
||||
expectedHttpBaseUrlInputLength: Schema.Number,
|
||||
expectedHttpBaseUrlProtocol: Schema.optionalKey(Schema.String),
|
||||
expectedHttpBaseUrlHostname: Schema.optionalKey(Schema.String),
|
||||
expectedWsBaseUrlInputLength: Schema.Number,
|
||||
expectedWsBaseUrlProtocol: Schema.optionalKey(Schema.String),
|
||||
expectedWsBaseUrlHostname: Schema.optionalKey(Schema.String),
|
||||
actualProviderKind: RelayManagedEndpointProviderKind,
|
||||
actualHttpBaseUrlInputLength: Schema.Number,
|
||||
actualHttpBaseUrlProtocol: Schema.optionalKey(Schema.String),
|
||||
actualHttpBaseUrlHostname: Schema.optionalKey(Schema.String),
|
||||
actualWsBaseUrlInputLength: Schema.Number,
|
||||
actualWsBaseUrlProtocol: Schema.optionalKey(Schema.String),
|
||||
actualWsBaseUrlHostname: Schema.optionalKey(Schema.String),
|
||||
},
|
||||
) {
|
||||
static fromEndpoints(input: {
|
||||
readonly source: "environment status response" | "environment connect response";
|
||||
readonly environmentId: string;
|
||||
readonly expectedEndpoint: RelayClientEnvironmentRecord["endpoint"];
|
||||
readonly actualEndpoint: RelayClientEnvironmentRecord["endpoint"];
|
||||
}): CloudEnvironmentEndpointMismatchError {
|
||||
const expectedHttp = getUrlDiagnostics(input.expectedEndpoint.httpBaseUrl);
|
||||
const expectedWs = getUrlDiagnostics(input.expectedEndpoint.wsBaseUrl);
|
||||
const actualHttp = getUrlDiagnostics(input.actualEndpoint.httpBaseUrl);
|
||||
const actualWs = getUrlDiagnostics(input.actualEndpoint.wsBaseUrl);
|
||||
return new CloudEnvironmentEndpointMismatchError({
|
||||
source: input.source,
|
||||
environmentId: input.environmentId,
|
||||
expectedProviderKind: input.expectedEndpoint.providerKind,
|
||||
expectedHttpBaseUrlInputLength: expectedHttp.inputLength,
|
||||
...(expectedHttp.protocol === undefined
|
||||
? {}
|
||||
: { expectedHttpBaseUrlProtocol: expectedHttp.protocol }),
|
||||
...(expectedHttp.hostname === undefined
|
||||
? {}
|
||||
: { expectedHttpBaseUrlHostname: expectedHttp.hostname }),
|
||||
expectedWsBaseUrlInputLength: expectedWs.inputLength,
|
||||
...(expectedWs.protocol === undefined
|
||||
? {}
|
||||
: { expectedWsBaseUrlProtocol: expectedWs.protocol }),
|
||||
...(expectedWs.hostname === undefined
|
||||
? {}
|
||||
: { expectedWsBaseUrlHostname: expectedWs.hostname }),
|
||||
actualProviderKind: input.actualEndpoint.providerKind,
|
||||
actualHttpBaseUrlInputLength: actualHttp.inputLength,
|
||||
...(actualHttp.protocol === undefined
|
||||
? {}
|
||||
: { actualHttpBaseUrlProtocol: actualHttp.protocol }),
|
||||
...(actualHttp.hostname === undefined
|
||||
? {}
|
||||
: { actualHttpBaseUrlHostname: actualHttp.hostname }),
|
||||
actualWsBaseUrlInputLength: actualWs.inputLength,
|
||||
...(actualWs.protocol === undefined ? {} : { actualWsBaseUrlProtocol: actualWs.protocol }),
|
||||
...(actualWs.hostname === undefined ? {} : { actualWsBaseUrlHostname: actualWs.hostname }),
|
||||
});
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `The ${this.source} returned a different endpoint for environment "${this.environmentId}".`;
|
||||
}
|
||||
}
|
||||
|
||||
export class CloudEnvironmentEndpointProviderMismatchError extends Schema.TaggedErrorClass<CloudEnvironmentEndpointProviderMismatchError>()(
|
||||
"CloudEnvironmentEndpointProviderMismatchError",
|
||||
{
|
||||
environmentId: Schema.String,
|
||||
expectedProviderKind: RelayManagedEndpointProviderKind,
|
||||
actualProviderKind: RelayManagedEndpointProviderKind,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Relay returned link credentials with endpoint provider "${this.actualProviderKind}" instead of "${this.expectedProviderKind}".`;
|
||||
}
|
||||
}
|
||||
|
||||
export const CloudEnvironmentLinkError = Schema.Union([
|
||||
CloudEnvironmentLinkOperationError,
|
||||
CloudRelayUrlNotConfiguredError,
|
||||
CloudEnvironmentLocalBearerRequiredError,
|
||||
CloudEnvironmentIdMismatchError,
|
||||
CloudEnvironmentEndpointMismatchError,
|
||||
CloudEnvironmentEndpointProviderMismatchError,
|
||||
]);
|
||||
export type CloudEnvironmentLinkError = typeof CloudEnvironmentLinkError.Type;
|
||||
export const isCloudEnvironmentLinkError = Schema.is(CloudEnvironmentLinkError);
|
||||
|
||||
export interface CloudEnvironmentRecordWithStatus {
|
||||
readonly environment: RelayClientEnvironmentRecord;
|
||||
@@ -62,132 +319,47 @@ export interface CloudEnvironmentRecordWithStatus {
|
||||
readonly statusError: string | null;
|
||||
}
|
||||
|
||||
const isEnvironmentCloudApiError = Schema.is(
|
||||
Schema.Union([
|
||||
EnvironmentHttpBadRequestError,
|
||||
EnvironmentHttpUnauthorizedError,
|
||||
EnvironmentHttpForbiddenError,
|
||||
EnvironmentHttpConflictError,
|
||||
EnvironmentHttpInternalServerError,
|
||||
EnvironmentCloudEndpointUnavailableError,
|
||||
]),
|
||||
);
|
||||
|
||||
const MANAGED_ENDPOINT_PROVIDER_KIND =
|
||||
"cloudflare_tunnel" satisfies RelayManagedEndpointProviderKind;
|
||||
|
||||
function cloudEnvironmentLinkError(message: string) {
|
||||
return (cause: unknown) => {
|
||||
const environmentError = findEnvironmentCloudApiError(cause);
|
||||
const traceId = findErrorTraceId(cause);
|
||||
return new CloudEnvironmentLinkError({
|
||||
message: environmentError
|
||||
? `${message.replace(/[.:]$/, "")}: ${environmentError.message}`
|
||||
: withDevCause(message, cause),
|
||||
cause,
|
||||
...(traceId === null ? {} : { traceId }),
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
function isDevRuntime(): boolean {
|
||||
return typeof __DEV__ !== "undefined" && __DEV__;
|
||||
}
|
||||
|
||||
function causeMessage(cause: unknown): string | null {
|
||||
if (cause instanceof Error && cause.message) {
|
||||
return cause.message;
|
||||
}
|
||||
if (typeof cause === "object" && cause !== null) {
|
||||
const record = cause as { readonly message?: unknown; readonly cause?: unknown };
|
||||
if (typeof record.message === "string" && record.message.length > 0) {
|
||||
const nested = causeMessage(record.cause);
|
||||
return nested ? `${record.message}: ${nested}` : record.message;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function withDevCause(message: string, cause: unknown): string {
|
||||
if (!isDevRuntime()) {
|
||||
return message;
|
||||
}
|
||||
const detail = causeMessage(cause);
|
||||
return detail ? `${message} (${detail})` : message;
|
||||
}
|
||||
|
||||
function relayProtectedErrorMessage(error: RelayProtectedErrorType): string {
|
||||
switch (error._tag) {
|
||||
case "RelayAuthInvalidError":
|
||||
switch (error.reason) {
|
||||
case "missing_bearer":
|
||||
case "invalid_bearer":
|
||||
return "Relay rejected the cloud session token.";
|
||||
case "invalid_dpop":
|
||||
return "Relay rejected the DPoP proof.";
|
||||
case "not_authorized":
|
||||
return "Relay rejected the authenticated request.";
|
||||
}
|
||||
case "RelayEnvironmentLinkProofExpiredError":
|
||||
return "Relay rejected an expired environment link proof.";
|
||||
case "RelayEnvironmentLinkProofInvalidError":
|
||||
return `Relay rejected the environment link proof (${error.reason}).`;
|
||||
case "RelayEnvironmentConnectNotAuthorizedError":
|
||||
return "Relay rejected the environment connection request.";
|
||||
case "RelayEnvironmentEndpointUnavailableError":
|
||||
return `Relay could not reach the environment endpoint (${error.reason}).`;
|
||||
case "RelayEnvironmentEndpointTimedOutError":
|
||||
return "Relay timed out while contacting the environment endpoint.";
|
||||
case "RelayEnvironmentLinkFailedError":
|
||||
return `Relay could not link the environment (${error.reason}).`;
|
||||
case "RelayEnvironmentLinkUnavailableError":
|
||||
return `Relay cannot provision the managed endpoint (${error.reason}).`;
|
||||
case "RelayAgentActivityPublishProofExpiredError":
|
||||
return "Relay rejected an expired agent activity publish proof.";
|
||||
case "RelayAgentActivityPublishProofInvalidError":
|
||||
return `Relay rejected the agent activity publish proof (${error.reason}).`;
|
||||
case "RelayInternalError":
|
||||
return `Relay encountered an internal error (${error.reason}).`;
|
||||
}
|
||||
}
|
||||
|
||||
function decodedRelayClientError(message: string) {
|
||||
return (cause: ManagedRelay.ManagedRelayClientError) => {
|
||||
const relayError =
|
||||
cause._tag === "ManagedRelayRequestFailedError" ? cause.relayError : undefined;
|
||||
const traceId = cause._tag === "ManagedRelayRequestFailedError" ? cause.traceId : undefined;
|
||||
const detail = relayError ? relayProtectedErrorMessage(relayError) : null;
|
||||
return new CloudEnvironmentLinkError({
|
||||
message: detail ? `${message}: ${detail}` : message,
|
||||
cause,
|
||||
...(traceId ? { traceId } : {}),
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
function findEnvironmentCloudApiError(cause: unknown): { readonly message: string } | null {
|
||||
if (isEnvironmentCloudApiError(cause)) {
|
||||
return cause;
|
||||
}
|
||||
if (typeof cause !== "object" || cause === null) {
|
||||
return null;
|
||||
}
|
||||
return "cause" in cause ? findEnvironmentCloudApiError(cause.cause) : null;
|
||||
}
|
||||
|
||||
function requireRelayUrl(): Effect.Effect<string, CloudEnvironmentLinkError> {
|
||||
const relayUrl = readRelayUrl();
|
||||
return relayUrl
|
||||
? Effect.succeed(relayUrl)
|
||||
: Effect.fail(new CloudEnvironmentLinkError({ message: "Relay URL is not configured." }));
|
||||
return relayUrl ? Effect.succeed(relayUrl) : Effect.fail(new CloudRelayUrlNotConfiguredError());
|
||||
}
|
||||
|
||||
function endpointOrigin(httpBaseUrl: string) {
|
||||
const url = new URL(httpBaseUrl);
|
||||
return {
|
||||
localHttpHost: "127.0.0.1",
|
||||
localHttpPort: Number(url.port || (url.protocol === "https:" ? 443 : 80)),
|
||||
};
|
||||
function endpointOrigin(input: { readonly environmentId: string; readonly httpBaseUrl: string }) {
|
||||
return Effect.try({
|
||||
try: () => {
|
||||
const url = new URL(input.httpBaseUrl);
|
||||
return {
|
||||
localHttpHost: "127.0.0.1",
|
||||
localHttpPort: Number(url.port || (url.protocol === "https:" ? 443 : 80)),
|
||||
};
|
||||
},
|
||||
catch: (cause) =>
|
||||
CloudEnvironmentLinkOperationError.fromCause({
|
||||
action: "derive the environment endpoint origin",
|
||||
environmentId: input.environmentId,
|
||||
httpBaseUrl: input.httpBaseUrl,
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
function makeCloudEnvironmentHttpApiClient(input: {
|
||||
readonly environmentId: string;
|
||||
readonly httpBaseUrl: string;
|
||||
}) {
|
||||
return Effect.try({
|
||||
try: () => makeEnvironmentHttpApiClient(input.httpBaseUrl),
|
||||
catch: (cause) =>
|
||||
CloudEnvironmentLinkOperationError.fromCause({
|
||||
action: "initialize the environment HTTP client",
|
||||
environmentId: input.environmentId,
|
||||
httpBaseUrl: input.httpBaseUrl,
|
||||
cause,
|
||||
}),
|
||||
}).pipe(Effect.flatten);
|
||||
}
|
||||
|
||||
function ensureLinkedEnvironmentMatches(input: {
|
||||
@@ -196,13 +368,17 @@ function ensureLinkedEnvironmentMatches(input: {
|
||||
readonly link: RelayEnvironmentLinkResponseType;
|
||||
}): Effect.Effect<void, CloudEnvironmentLinkError> {
|
||||
if (input.link.environmentId !== input.expectedEnvironmentId) {
|
||||
return new CloudEnvironmentLinkError({
|
||||
message: "Relay returned credentials for a different environment.",
|
||||
return new CloudEnvironmentIdMismatchError({
|
||||
source: "environment link response",
|
||||
expectedEnvironmentId: input.expectedEnvironmentId,
|
||||
actualEnvironmentId: input.link.environmentId,
|
||||
});
|
||||
}
|
||||
if (input.link.endpoint.providerKind !== input.expectedProviderKind) {
|
||||
return new CloudEnvironmentLinkError({
|
||||
message: "Relay returned credentials for a different endpoint provider.",
|
||||
return new CloudEnvironmentEndpointProviderMismatchError({
|
||||
environmentId: input.expectedEnvironmentId,
|
||||
expectedProviderKind: input.expectedProviderKind,
|
||||
actualProviderKind: input.link.endpoint.providerKind,
|
||||
});
|
||||
}
|
||||
return Effect.void;
|
||||
@@ -224,21 +400,28 @@ function ensureStatusMatchesEnvironment(input: {
|
||||
readonly status: RelayEnvironmentStatusResponseType;
|
||||
}): Effect.Effect<void, CloudEnvironmentLinkError> {
|
||||
if (input.status.environmentId !== input.environment.environmentId) {
|
||||
return new CloudEnvironmentLinkError({
|
||||
message: "Relay returned status for a different environment.",
|
||||
return new CloudEnvironmentIdMismatchError({
|
||||
source: "environment status response",
|
||||
expectedEnvironmentId: input.environment.environmentId,
|
||||
actualEnvironmentId: input.status.environmentId,
|
||||
});
|
||||
}
|
||||
if (!endpointMatches(input.status.endpoint, input.environment.endpoint)) {
|
||||
return new CloudEnvironmentLinkError({
|
||||
message: "Relay returned status for a different endpoint.",
|
||||
return CloudEnvironmentEndpointMismatchError.fromEndpoints({
|
||||
source: "environment status response",
|
||||
environmentId: input.environment.environmentId,
|
||||
expectedEndpoint: input.environment.endpoint,
|
||||
actualEndpoint: input.status.endpoint,
|
||||
});
|
||||
}
|
||||
if (
|
||||
input.status.descriptor &&
|
||||
input.status.descriptor.environmentId !== input.environment.environmentId
|
||||
) {
|
||||
return new CloudEnvironmentLinkError({
|
||||
message: "Relay returned status descriptor for a different environment.",
|
||||
return new CloudEnvironmentIdMismatchError({
|
||||
source: "environment status descriptor",
|
||||
expectedEnvironmentId: input.environment.environmentId,
|
||||
actualEnvironmentId: input.status.descriptor.environmentId,
|
||||
});
|
||||
}
|
||||
return Effect.void;
|
||||
@@ -249,8 +432,11 @@ function ensureConnectEndpointMatchesEnvironment(input: {
|
||||
readonly connect: RelayEnvironmentConnectResponseType;
|
||||
}): Effect.Effect<void, CloudEnvironmentLinkError> {
|
||||
if (!endpointMatches(input.connect.endpoint, input.environment.endpoint)) {
|
||||
return new CloudEnvironmentLinkError({
|
||||
message: "Relay returned credentials for a different endpoint.",
|
||||
return CloudEnvironmentEndpointMismatchError.fromEndpoints({
|
||||
source: "environment connect response",
|
||||
environmentId: input.environment.environmentId,
|
||||
expectedEndpoint: input.environment.endpoint,
|
||||
actualEndpoint: input.connect.endpoint,
|
||||
});
|
||||
}
|
||||
return Effect.void;
|
||||
@@ -266,8 +452,9 @@ export function linkEnvironmentToCloud(input: {
|
||||
> {
|
||||
return Effect.gen(function* () {
|
||||
if (!input.connection.bearerToken) {
|
||||
return yield* new CloudEnvironmentLinkError({
|
||||
message: "Only a locally paired bearer connection can be linked to the cloud.",
|
||||
return yield* CloudEnvironmentLocalBearerRequiredError.fromConnection({
|
||||
environmentId: input.connection.environmentId,
|
||||
httpBaseUrl: input.connection.httpBaseUrl,
|
||||
});
|
||||
}
|
||||
const localBearerToken = input.connection.bearerToken;
|
||||
@@ -275,11 +462,21 @@ export function linkEnvironmentToCloud(input: {
|
||||
const relayClient = yield* ManagedRelay.ManagedRelayClient;
|
||||
const deviceId = yield* Effect.tryPromise({
|
||||
try: () => loadOrCreateAgentAwarenessDeviceId(),
|
||||
catch: cloudEnvironmentLinkError("Could not load the mobile device id."),
|
||||
catch: (cause) =>
|
||||
CloudEnvironmentLinkOperationError.fromCause({
|
||||
action: "load the mobile device id",
|
||||
environmentId: input.connection.environmentId,
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
const preferences = yield* Effect.tryPromise({
|
||||
try: () => loadPreferences(),
|
||||
catch: cloudEnvironmentLinkError("Could not load mobile notification preferences."),
|
||||
catch: (cause) =>
|
||||
CloudEnvironmentLinkOperationError.fromCause({
|
||||
action: "load mobile notification preferences",
|
||||
environmentId: input.connection.environmentId,
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
const liveActivitiesEnabled = preferences.liveActivitiesEnabled !== false;
|
||||
const challenge = yield* relayClient
|
||||
@@ -292,11 +489,23 @@ export function linkEnvironmentToCloud(input: {
|
||||
},
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
decodedRelayClientError(`${relayUrl}/v1/client/environment-link-challenges failed`),
|
||||
Effect.mapError((cause) =>
|
||||
CloudEnvironmentLinkOperationError.fromCause({
|
||||
action: "create an environment link challenge",
|
||||
environmentId: input.connection.environmentId,
|
||||
relayUrl,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const environmentClient = yield* makeEnvironmentHttpApiClient(input.connection.httpBaseUrl);
|
||||
const origin = yield* endpointOrigin({
|
||||
environmentId: input.connection.environmentId,
|
||||
httpBaseUrl: input.connection.httpBaseUrl,
|
||||
});
|
||||
const environmentClient = yield* makeCloudEnvironmentHttpApiClient({
|
||||
environmentId: input.connection.environmentId,
|
||||
httpBaseUrl: input.connection.httpBaseUrl,
|
||||
});
|
||||
const proof = yield* environmentClient.connect
|
||||
.linkProof({
|
||||
headers: { authorization: `Bearer ${localBearerToken}` },
|
||||
@@ -308,10 +517,19 @@ export function linkEnvironmentToCloud(input: {
|
||||
wsBaseUrl: input.connection.wsBaseUrl,
|
||||
providerKind: MANAGED_ENDPOINT_PROVIDER_KIND,
|
||||
},
|
||||
origin: endpointOrigin(input.connection.httpBaseUrl),
|
||||
origin,
|
||||
},
|
||||
})
|
||||
.pipe(Effect.mapError(cloudEnvironmentLinkError("Could not obtain environment link proof.")));
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
CloudEnvironmentLinkOperationError.fromCause({
|
||||
action: "obtain an environment link proof",
|
||||
environmentId: input.connection.environmentId,
|
||||
httpBaseUrl: input.connection.httpBaseUrl,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const link = yield* relayClient
|
||||
.linkEnvironment({
|
||||
clerkToken: input.clerkToken,
|
||||
@@ -324,7 +542,14 @@ export function linkEnvironmentToCloud(input: {
|
||||
},
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(decodedRelayClientError(`${relayUrl}/v1/client/environment-links failed`)),
|
||||
Effect.mapError((cause) =>
|
||||
CloudEnvironmentLinkOperationError.fromCause({
|
||||
action: "link the environment",
|
||||
environmentId: input.connection.environmentId,
|
||||
relayUrl,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* ensureLinkedEnvironmentMatches({
|
||||
expectedEnvironmentId: input.connection.environmentId,
|
||||
@@ -345,7 +570,14 @@ export function linkEnvironmentToCloud(input: {
|
||||
},
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(cloudEnvironmentLinkError("Could not configure environment relay access.")),
|
||||
Effect.mapError((cause) =>
|
||||
CloudEnvironmentLinkOperationError.fromCause({
|
||||
action: "configure environment relay access",
|
||||
environmentId: input.connection.environmentId,
|
||||
httpBaseUrl: input.connection.httpBaseUrl,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -361,11 +593,15 @@ export function listCloudEnvironments(input: {
|
||||
const relayUrl = yield* requireRelayUrl();
|
||||
const relayClient = yield* ManagedRelay.ManagedRelayClient;
|
||||
|
||||
return yield* relayClient
|
||||
.listEnvironments({
|
||||
clerkToken: input.clerkToken,
|
||||
})
|
||||
.pipe(Effect.mapError(decodedRelayClientError(`${relayUrl}/v1/environments failed`)));
|
||||
return yield* relayClient.listEnvironments({ clerkToken: input.clerkToken }).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
CloudEnvironmentLinkOperationError.fromCause({
|
||||
action: "list cloud environments",
|
||||
relayUrl,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -388,10 +624,13 @@ export function getCloudEnvironmentStatus(input: {
|
||||
environmentId: input.environment.environmentId,
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
decodedRelayClientError(
|
||||
`${relayUrl}/v1/environments/${encodeURIComponent(input.environment.environmentId)}/status failed`,
|
||||
),
|
||||
Effect.mapError((cause) =>
|
||||
CloudEnvironmentLinkOperationError.fromCause({
|
||||
action: "read cloud environment status",
|
||||
environmentId: input.environment.environmentId,
|
||||
relayUrl,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* ensureStatusMatchesEnvironment({ environment: input.environment, status });
|
||||
@@ -458,14 +697,19 @@ export function listCloudEnvironmentsWithStatus(input: {
|
||||
});
|
||||
}
|
||||
|
||||
const loadAgentAwarenessDeviceId = Effect.fn("mobile.cloud.loadAgentAwarenessDeviceId")(
|
||||
function* () {
|
||||
return yield* Effect.tryPromise({
|
||||
try: () => loadOrCreateAgentAwarenessDeviceId(),
|
||||
catch: cloudEnvironmentLinkError("Could not load the mobile device id."),
|
||||
});
|
||||
},
|
||||
);
|
||||
const loadAgentAwarenessDeviceId = Effect.fn("mobile.cloud.loadAgentAwarenessDeviceId")(function* (
|
||||
environmentId: string,
|
||||
) {
|
||||
return yield* Effect.tryPromise({
|
||||
try: () => loadOrCreateAgentAwarenessDeviceId(),
|
||||
catch: (cause) =>
|
||||
CloudEnvironmentLinkOperationError.fromCause({
|
||||
action: "load the mobile device id",
|
||||
environmentId,
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
const connectRelayManagedEnvironment = Effect.fn("mobile.cloud.connectRelayManagedEnvironment")(
|
||||
function* (input: {
|
||||
@@ -477,7 +721,7 @@ const connectRelayManagedEnvironment = Effect.fn("mobile.cloud.connectRelayManag
|
||||
const relayUrl = yield* requireRelayUrl();
|
||||
const relayClient = yield* ManagedRelay.ManagedRelayClient;
|
||||
|
||||
const deviceId = yield* loadAgentAwarenessDeviceId();
|
||||
const deviceId = yield* loadAgentAwarenessDeviceId(input.environmentId);
|
||||
const connect = yield* relayClient
|
||||
.connectEnvironment({
|
||||
clerkToken: input.clerkToken,
|
||||
@@ -486,15 +730,20 @@ const connectRelayManagedEnvironment = Effect.fn("mobile.cloud.connectRelayManag
|
||||
deviceId,
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
decodedRelayClientError(
|
||||
`${relayUrl}/v1/environments/${encodeURIComponent(input.environmentId)}/connect failed`,
|
||||
),
|
||||
Effect.mapError((cause) =>
|
||||
CloudEnvironmentLinkOperationError.fromCause({
|
||||
action: "connect to the cloud environment",
|
||||
environmentId: input.environmentId,
|
||||
relayUrl,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (connect.environmentId !== input.environmentId) {
|
||||
return yield* new CloudEnvironmentLinkError({
|
||||
message: "Relay returned credentials for a different environment.",
|
||||
return yield* new CloudEnvironmentIdMismatchError({
|
||||
source: "environment connect response",
|
||||
expectedEnvironmentId: input.environmentId,
|
||||
actualEnvironmentId: connect.environmentId,
|
||||
});
|
||||
}
|
||||
if (input.expectedEnvironment) {
|
||||
@@ -507,39 +756,69 @@ const connectRelayManagedEnvironment = Effect.fn("mobile.cloud.connectRelayManag
|
||||
const descriptor = yield* fetchRemoteEnvironmentDescriptor({
|
||||
httpBaseUrl: connect.endpoint.httpBaseUrl,
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
cloudEnvironmentLinkError("Could not fetch the connected environment descriptor."),
|
||||
Effect.mapError((cause) =>
|
||||
CloudEnvironmentLinkOperationError.fromCause({
|
||||
action: "fetch the connected environment descriptor",
|
||||
environmentId: input.environmentId,
|
||||
httpBaseUrl: connect.endpoint.httpBaseUrl,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (descriptor.environmentId !== connect.environmentId) {
|
||||
return yield* new CloudEnvironmentLinkError({
|
||||
message: "Connected endpoint descriptor does not match the selected environment.",
|
||||
return yield* new CloudEnvironmentIdMismatchError({
|
||||
source: "connected environment descriptor",
|
||||
expectedEnvironmentId: connect.environmentId,
|
||||
actualEnvironmentId: descriptor.environmentId,
|
||||
});
|
||||
}
|
||||
const endpointUrl = yield* Effect.try({
|
||||
try: () => new URL(connect.endpoint.httpBaseUrl),
|
||||
catch: (cause) =>
|
||||
CloudEnvironmentLinkOperationError.fromCause({
|
||||
action: "parse the managed endpoint URL",
|
||||
environmentId: input.environmentId,
|
||||
httpBaseUrl: connect.endpoint.httpBaseUrl,
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
const signer = yield* ManagedRelay.ManagedRelayDpopSigner;
|
||||
const bootstrapDpop = yield* signer
|
||||
.createProof({
|
||||
method: "POST",
|
||||
url: new URL("/oauth/token", connect.endpoint.httpBaseUrl).toString(),
|
||||
url: new URL("/oauth/token", endpointUrl).toString(),
|
||||
})
|
||||
.pipe(Effect.mapError(cloudEnvironmentLinkError("Could not create bootstrap DPoP proof.")));
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
CloudEnvironmentLinkOperationError.fromCause({
|
||||
action: "create a bootstrap DPoP proof",
|
||||
environmentId: input.environmentId,
|
||||
httpBaseUrl: connect.endpoint.httpBaseUrl,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const bootstrap = yield* exchangeRemoteDpopAccessToken({
|
||||
httpBaseUrl: connect.endpoint.httpBaseUrl,
|
||||
credential: connect.credential,
|
||||
dpopProof: bootstrapDpop,
|
||||
clientMetadata: authClientMetadata(),
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
cloudEnvironmentLinkError("Could not exchange a managed endpoint DPoP access token."),
|
||||
Effect.mapError((cause) =>
|
||||
CloudEnvironmentLinkOperationError.fromCause({
|
||||
action: "exchange a managed endpoint DPoP access token",
|
||||
environmentId: input.environmentId,
|
||||
httpBaseUrl: connect.endpoint.httpBaseUrl,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const pairingUrl = new URL(connect.endpoint.httpBaseUrl);
|
||||
pairingUrl.hash = new URLSearchParams([["token", connect.credential]]).toString();
|
||||
endpointUrl.hash = new URLSearchParams([["token", connect.credential]]).toString();
|
||||
|
||||
return {
|
||||
environmentId: descriptor.environmentId,
|
||||
environmentLabel: descriptor.label,
|
||||
pairingUrl: stripPairingTokenFromUrl(pairingUrl).toString(),
|
||||
pairingUrl: stripPairingTokenFromUrl(endpointUrl).toString(),
|
||||
displayUrl: connect.endpoint.httpBaseUrl,
|
||||
httpBaseUrl: connect.endpoint.httpBaseUrl,
|
||||
wsBaseUrl: connect.endpoint.wsBaseUrl,
|
||||
|
||||
@@ -28,25 +28,24 @@ const relayDpopSignerLayer = Layer.effect(
|
||||
),
|
||||
createProof: Effect.fn("mobile.managedRelayDpopSigner.createProof")(function* (input) {
|
||||
const proofKey = yield* loadProofKey.pipe(
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new ManagedRelay.ManagedRelayDpopProofCreationError({
|
||||
method: input.method,
|
||||
url: input.url,
|
||||
cause: error,
|
||||
}),
|
||||
Effect.mapError((error) =>
|
||||
ManagedRelay.ManagedRelayDpopKeyLoadError.fromTarget({
|
||||
keyStore: "expo-secure-store",
|
||||
method: input.method,
|
||||
url: input.url,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
);
|
||||
return yield* createDpopProof({ ...input, proofKey }).pipe(
|
||||
Effect.provideService(Crypto.Crypto, crypto),
|
||||
Effect.map((proof) => proof.proof),
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new ManagedRelay.ManagedRelayDpopProofCreationError({
|
||||
method: input.method,
|
||||
url: input.url,
|
||||
cause: error,
|
||||
}),
|
||||
Effect.mapError((error) =>
|
||||
ManagedRelay.ManagedRelayDpopProofCreationError.fromTarget({
|
||||
method: input.method,
|
||||
url: input.url,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}),
|
||||
|
||||
@@ -58,7 +58,7 @@ export function useConnectionController() {
|
||||
environment: entry.environment,
|
||||
availability: entry.availability,
|
||||
status: Option.getOrNull(entry.status),
|
||||
error: Option.getOrNull(entry.error)?.message ?? null,
|
||||
error: Option.getOrNull(entry.error)?.detail ?? null,
|
||||
traceId: Option.getOrNull(entry.error)?.traceId ?? null,
|
||||
})),
|
||||
[discovery.environments],
|
||||
@@ -112,7 +112,7 @@ export function useConnectionController() {
|
||||
relayDiscovery: {
|
||||
isRefreshing: discovery.refreshing,
|
||||
isOffline: discovery.offline,
|
||||
error: Option.getOrNull(discovery.error)?.message ?? null,
|
||||
error: Option.getOrNull(discovery.error)?.detail ?? null,
|
||||
errorTraceId: Option.getOrNull(discovery.error)?.traceId ?? null,
|
||||
},
|
||||
connectPairingUrl,
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import * as Cause from "effect/Cause";
|
||||
import { AtomRegistry } from "effect/unstable/reactivity";
|
||||
import * as AsyncResult from "effect/unstable/reactivity/AsyncResult";
|
||||
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
createSourceHighlightAtomFamily,
|
||||
SourceHighlightError,
|
||||
type SourceHighlightTokens,
|
||||
} from "./sourceHighlightingState";
|
||||
|
||||
@@ -100,22 +102,29 @@ describe("sourceHighlightingState", () => {
|
||||
registry.dispose();
|
||||
});
|
||||
|
||||
it("exposes highlighter errors as a failed async result", async () => {
|
||||
const highlight = vi.fn(async () => {
|
||||
throw new Error("highlight failed");
|
||||
});
|
||||
it("preserves highlighter failures with the source path and theme", async () => {
|
||||
const cause = new Error("highlight failed");
|
||||
const highlight = vi.fn(() => Promise.reject(cause));
|
||||
const sourceHighlightAtom = createSourceHighlightAtomFamily({ highlight });
|
||||
const registry = AtomRegistry.make();
|
||||
const path = "src/example.ts";
|
||||
const theme = "light" as const;
|
||||
const atom = sourceHighlightAtom({
|
||||
path: "src/example.ts",
|
||||
path,
|
||||
contents: "const value = 1;",
|
||||
theme: "light",
|
||||
theme,
|
||||
});
|
||||
const unmount = registry.mount(atom);
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(AsyncResult.isFailure(registry.get(atom))).toBe(true);
|
||||
});
|
||||
const result = registry.get(atom);
|
||||
if (AsyncResult.isFailure(result)) {
|
||||
const error = Cause.squash(result.cause);
|
||||
expect(error).toEqual(new SourceHighlightError({ path, theme, cause }));
|
||||
expect((error as SourceHighlightError).cause).toBe(cause);
|
||||
}
|
||||
|
||||
unmount();
|
||||
registry.dispose();
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
|
||||
import {
|
||||
@@ -22,9 +23,18 @@ type SourceHighlighter = (input: SourceHighlightInput) => Promise<SourceHighligh
|
||||
|
||||
class SourceHighlightCacheKey extends Data.Class<SourceHighlightInput> {}
|
||||
|
||||
class SourceHighlightError extends Data.TaggedError("SourceHighlightError")<{
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
export class SourceHighlightError extends Schema.TaggedErrorClass<SourceHighlightError>()(
|
||||
"SourceHighlightError",
|
||||
{
|
||||
path: Schema.String,
|
||||
theme: Schema.Literals(["light", "dark"]),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Could not highlight ${this.path} with the ${this.theme} theme.`;
|
||||
}
|
||||
}
|
||||
|
||||
export function createSourceHighlightAtomFamily(options?: {
|
||||
readonly highlight?: SourceHighlighter;
|
||||
@@ -36,7 +46,8 @@ export function createSourceHighlightAtomFamily(options?: {
|
||||
Atom.make(
|
||||
Effect.tryPromise({
|
||||
try: () => highlight(request),
|
||||
catch: (cause) => new SourceHighlightError({ cause }),
|
||||
catch: (cause) =>
|
||||
new SourceHighlightError({ path: request.path, theme: request.theme, cause }),
|
||||
}),
|
||||
).pipe(
|
||||
Atom.setIdleTTL(idleTtlMs),
|
||||
|
||||
@@ -1,8 +1,14 @@
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Hash from "effect/Hash";
|
||||
import { AtomRegistry } from "effect/unstable/reactivity";
|
||||
import * as AsyncResult from "effect/unstable/reactivity/AsyncResult";
|
||||
import { describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import { createWorkspaceFileImageAtomFamily } from "./workspace-file-image-cache";
|
||||
import {
|
||||
createWorkspaceFileImageAtomFamily,
|
||||
WorkspaceImagePrefetchFailedError,
|
||||
WorkspaceImagePrefetchUnavailableError,
|
||||
} from "./workspace-file-image-cache";
|
||||
|
||||
describe("workspaceFileImageAtom", () => {
|
||||
it("reuses a prefetched image across route remounts", async () => {
|
||||
@@ -48,15 +54,65 @@ describe("workspaceFileImageAtom", () => {
|
||||
registry.dispose();
|
||||
});
|
||||
|
||||
it("exposes prefetch failures", async () => {
|
||||
it("reports an unavailable image when prefetch completes without caching it", async () => {
|
||||
const uri = "https://example.test/api/assets/signed-secret-token/missing.png?signature=private";
|
||||
const imageAtom = createWorkspaceFileImageAtomFamily({ prefetch: async () => false });
|
||||
const registry = AtomRegistry.make();
|
||||
const atom = imageAtom("https://example.test/missing.png");
|
||||
const atom = imageAtom(uri);
|
||||
expect(atom.label?.[0]).not.toContain("signed-secret-token");
|
||||
expect(atom.label?.[0]).not.toContain("signature=private");
|
||||
const unmount = registry.mount(atom);
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(AsyncResult.isFailure(registry.get(atom))).toBe(true);
|
||||
});
|
||||
const result = registry.get(atom);
|
||||
if (AsyncResult.isFailure(result)) {
|
||||
const error = Cause.squash(result.cause);
|
||||
expect(error).toEqual(
|
||||
new WorkspaceImagePrefetchUnavailableError({
|
||||
uriHash: Hash.hash(uri),
|
||||
uriLength: uri.length,
|
||||
uriProtocol: "https:",
|
||||
}),
|
||||
);
|
||||
expect(error).not.toHaveProperty("uri");
|
||||
expect(String(error)).not.toContain("signed-secret-token");
|
||||
expect(String(error)).not.toContain("signature=private");
|
||||
}
|
||||
|
||||
unmount();
|
||||
registry.dispose();
|
||||
});
|
||||
|
||||
it("preserves rejected prefetch causes without retaining the signed image URI", async () => {
|
||||
const uri =
|
||||
"https://example.test/api/assets/signed-secret-token/rejected.png?signature=private";
|
||||
const cause = new Error("native image loader failed");
|
||||
const imageAtom = createWorkspaceFileImageAtomFamily({ prefetch: () => Promise.reject(cause) });
|
||||
const registry = AtomRegistry.make();
|
||||
const atom = imageAtom(uri);
|
||||
const unmount = registry.mount(atom);
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(AsyncResult.isFailure(registry.get(atom))).toBe(true);
|
||||
});
|
||||
const result = registry.get(atom);
|
||||
if (AsyncResult.isFailure(result)) {
|
||||
const error = Cause.squash(result.cause);
|
||||
expect(error).toEqual(
|
||||
new WorkspaceImagePrefetchFailedError({
|
||||
uriHash: Hash.hash(uri),
|
||||
uriLength: uri.length,
|
||||
uriProtocol: "https:",
|
||||
cause,
|
||||
}),
|
||||
);
|
||||
expect((error as WorkspaceImagePrefetchFailedError).cause).toBe(cause);
|
||||
expect(error).not.toHaveProperty("uri");
|
||||
expect(String(error)).not.toContain("signed-secret-token");
|
||||
expect(String(error)).not.toContain("signature=private");
|
||||
}
|
||||
|
||||
unmount();
|
||||
registry.dispose();
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
import { getUrlDiagnostics } from "@t3tools/shared/urlDiagnostics";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Hash from "effect/Hash";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
|
||||
const WORKSPACE_IMAGE_IDLE_TTL_MS = 30 * 60_000;
|
||||
@@ -8,39 +11,77 @@ type ImagePrefetch = (uri: string) => Promise<boolean>;
|
||||
|
||||
class WorkspaceImageCacheKey extends Data.Class<{ readonly uri: string }> {}
|
||||
|
||||
export class WorkspaceImagePrefetchError extends Data.TaggedError("WorkspaceImagePrefetchError")<{
|
||||
readonly cause?: unknown;
|
||||
readonly uri: string;
|
||||
}> {}
|
||||
export class WorkspaceImagePrefetchUnavailableError extends Schema.TaggedErrorClass<WorkspaceImagePrefetchUnavailableError>()(
|
||||
"WorkspaceImagePrefetchUnavailableError",
|
||||
{
|
||||
uriHash: Schema.Number,
|
||||
uriLength: Schema.Number,
|
||||
uriProtocol: Schema.NullOr(Schema.String),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Image prefetch did not cache the requested ${this.uriProtocol ?? "unknown-protocol"} resource (URI length ${this.uriLength}).`;
|
||||
}
|
||||
}
|
||||
|
||||
export class WorkspaceImagePrefetchFailedError extends Schema.TaggedErrorClass<WorkspaceImagePrefetchFailedError>()(
|
||||
"WorkspaceImagePrefetchFailedError",
|
||||
{
|
||||
uriHash: Schema.Number,
|
||||
uriLength: Schema.Number,
|
||||
uriProtocol: Schema.NullOr(Schema.String),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Image prefetch failed for the requested ${this.uriProtocol ?? "unknown-protocol"} resource (URI length ${this.uriLength}).`;
|
||||
}
|
||||
}
|
||||
|
||||
export const WorkspaceImagePrefetchError = Schema.Union([
|
||||
WorkspaceImagePrefetchUnavailableError,
|
||||
WorkspaceImagePrefetchFailedError,
|
||||
]);
|
||||
export type WorkspaceImagePrefetchError = typeof WorkspaceImagePrefetchError.Type;
|
||||
|
||||
async function prefetchWithNativeImage(uri: string): Promise<boolean> {
|
||||
const { Image } = await import("react-native");
|
||||
return Image.prefetch(uri);
|
||||
}
|
||||
|
||||
function describeWorkspaceImageUri(uri: string) {
|
||||
const diagnostics = getUrlDiagnostics(uri);
|
||||
return {
|
||||
uriHash: Hash.hash(uri),
|
||||
uriLength: diagnostics.inputLength,
|
||||
uriProtocol: diagnostics.protocol ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
export function createWorkspaceFileImageAtomFamily(options?: {
|
||||
readonly idleTtlMs?: number;
|
||||
readonly prefetch?: ImagePrefetch;
|
||||
}) {
|
||||
const idleTtlMs = options?.idleTtlMs ?? WORKSPACE_IMAGE_IDLE_TTL_MS;
|
||||
const prefetch = options?.prefetch ?? prefetchWithNativeImage;
|
||||
const family = Atom.family((key: WorkspaceImageCacheKey) =>
|
||||
Atom.make(
|
||||
Effect.tryPromise({
|
||||
try: async () => {
|
||||
const cached = await prefetch(key.uri);
|
||||
if (!cached) {
|
||||
throw new WorkspaceImagePrefetchError({ uri: key.uri });
|
||||
}
|
||||
return key.uri;
|
||||
},
|
||||
catch: (cause) =>
|
||||
cause instanceof WorkspaceImagePrefetchError
|
||||
? cause
|
||||
: new WorkspaceImagePrefetchError({ uri: key.uri, cause }),
|
||||
const family = Atom.family((key: WorkspaceImageCacheKey) => {
|
||||
const uriContext = describeWorkspaceImageUri(key.uri);
|
||||
return Atom.make(
|
||||
Effect.gen(function* () {
|
||||
const cached = yield* Effect.tryPromise({
|
||||
try: () => prefetch(key.uri),
|
||||
catch: (cause) => new WorkspaceImagePrefetchFailedError({ ...uriContext, cause }),
|
||||
});
|
||||
if (!cached) {
|
||||
return yield* new WorkspaceImagePrefetchUnavailableError(uriContext);
|
||||
}
|
||||
return key.uri;
|
||||
}),
|
||||
).pipe(Atom.setIdleTTL(idleTtlMs), Atom.withLabel(`mobile:workspace-image:${key.uri}`)),
|
||||
);
|
||||
).pipe(
|
||||
Atom.setIdleTTL(idleTtlMs),
|
||||
Atom.withLabel(`mobile:workspace-image:${uriContext.uriHash.toString(36)}`),
|
||||
);
|
||||
});
|
||||
|
||||
return (uri: string) => family(new WorkspaceImageCacheKey({ uri }));
|
||||
}
|
||||
|
||||
@@ -30,9 +30,7 @@ import {
|
||||
resolveProviderOptionDescriptors,
|
||||
} from "../../lib/providerOptions";
|
||||
import { buildThreadRoutePath } from "../../lib/routes";
|
||||
import { scopedProjectKey } from "../../lib/scopedEntities";
|
||||
import { MOBILE_TYPOGRAPHY } from "../../lib/typography";
|
||||
import { getComposerDraftSnapshot } from "../../state/use-composer-drafts";
|
||||
import { useProjects } from "../../state/entities";
|
||||
import { branchBadgeLabel, useNewTaskFlow } from "./new-task-flow-provider";
|
||||
import { useCreateProjectThread } from "./use-project-actions";
|
||||
@@ -65,7 +63,6 @@ export function NewTaskDraftScreen(props: {
|
||||
const controlsBottomPadding = isKeyboardVisible ? 8 : Math.max(insets.bottom, 10);
|
||||
const { logicalProjects, selectedProject, setProject } = flow;
|
||||
const promptInputRef = useRef<ComposerEditorHandle>(null);
|
||||
const loadedBranchesProjectKeyRef = useRef<string | null>(null);
|
||||
|
||||
const borderColor = useThemeColor("--color-border");
|
||||
const sheetFadeOpaque = colorScheme === "dark" ? "rgba(14,14,14,0.98)" : "rgba(242,242,247,0.98)";
|
||||
@@ -81,12 +78,6 @@ export function NewTaskDraftScreen(props: {
|
||||
) ?? null;
|
||||
|
||||
if (directProject) {
|
||||
if (
|
||||
selectedProject?.environmentId === directProject.environmentId &&
|
||||
selectedProject.id === directProject.id
|
||||
) {
|
||||
return;
|
||||
}
|
||||
setProject(directProject);
|
||||
return;
|
||||
}
|
||||
@@ -114,16 +105,10 @@ export function NewTaskDraftScreen(props: {
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedProject) {
|
||||
loadedBranchesProjectKeyRef.current = null;
|
||||
return;
|
||||
}
|
||||
const projectKey = `${selectedProject.environmentId}:${selectedProject.id}`;
|
||||
if (loadedBranchesProjectKeyRef.current === projectKey) {
|
||||
return;
|
||||
}
|
||||
loadedBranchesProjectKeyRef.current = projectKey;
|
||||
void flow.loadBranches();
|
||||
}, [flow.loadBranches, selectedProject]);
|
||||
}, [flow, selectedProject]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedProject) {
|
||||
@@ -307,7 +292,11 @@ export function NewTaskDraftScreen(props: {
|
||||
if (!event.startsWith("model:")) {
|
||||
return;
|
||||
}
|
||||
flow.setSelectedModelKey(event.slice("model:".length));
|
||||
// Defer state update so the native menu dismiss animation completes
|
||||
// before re-rendering the menu actions (prevents submenu jump).
|
||||
setTimeout(() => {
|
||||
flow.setSelectedModelKey(event.slice("model:".length));
|
||||
}, 150);
|
||||
}
|
||||
|
||||
function handleEnvironmentMenuAction(event: string) {
|
||||
@@ -377,42 +366,27 @@ export function NewTaskDraftScreen(props: {
|
||||
);
|
||||
|
||||
async function handleStart(): Promise<void> {
|
||||
const selectedProject = flow.selectedProject;
|
||||
if (!selectedProject) {
|
||||
return;
|
||||
}
|
||||
const draft = getComposerDraftSnapshot(
|
||||
`new-task:${scopedProjectKey(selectedProject.environmentId, selectedProject.id)}`,
|
||||
);
|
||||
const modelSelection = draft.modelSelection ?? flow.selectedModel;
|
||||
const workspaceMode = draft.workspaceSelection?.mode ?? flow.workspaceMode;
|
||||
const selectedBranchName = draft.workspaceSelection?.branch ?? flow.selectedBranchName;
|
||||
const selectedWorktreePath =
|
||||
draft.workspaceSelection?.worktreePath ?? flow.selectedWorktreePath;
|
||||
const runtimeMode = draft.runtimeMode ?? flow.runtimeMode;
|
||||
const interactionMode = draft.interactionMode ?? flow.interactionMode;
|
||||
const initialMessageText = draft.text.trim();
|
||||
|
||||
if (
|
||||
!modelSelection ||
|
||||
initialMessageText.length === 0 ||
|
||||
!flow.selectedProject ||
|
||||
!flow.selectedModel ||
|
||||
flow.prompt.trim().length === 0 ||
|
||||
flow.submitting ||
|
||||
(workspaceMode === "worktree" && !selectedBranchName)
|
||||
(flow.workspaceMode === "worktree" && !flow.selectedBranchName)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
flow.setSubmitting(true);
|
||||
const result = await createProjectThread({
|
||||
project: selectedProject,
|
||||
modelSelection,
|
||||
envMode: workspaceMode,
|
||||
branch: selectedBranchName,
|
||||
worktreePath: workspaceMode === "worktree" ? null : selectedWorktreePath,
|
||||
runtimeMode,
|
||||
interactionMode,
|
||||
initialMessageText,
|
||||
initialAttachments: draft.attachments,
|
||||
project: flow.selectedProject,
|
||||
modelSelection: flow.selectedModel,
|
||||
envMode: flow.workspaceMode,
|
||||
branch: flow.selectedBranchName,
|
||||
worktreePath: flow.workspaceMode === "worktree" ? null : flow.selectedWorktreePath,
|
||||
runtimeMode: flow.runtimeMode,
|
||||
interactionMode: flow.interactionMode,
|
||||
initialMessageText: flow.prompt.trim(),
|
||||
initialAttachments: flow.attachments,
|
||||
});
|
||||
flow.setSubmitting(false);
|
||||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { isLiquidGlassSupported, LiquidGlassView } from "@callstack/liquid-glass";
|
||||
import type {
|
||||
EnvironmentId,
|
||||
MessageId,
|
||||
ModelSelection,
|
||||
OrchestrationThreadShell,
|
||||
ProviderInteractionMode,
|
||||
@@ -92,7 +91,7 @@ export interface ThreadComposerProps {
|
||||
readonly onNativePasteImages: (uris: ReadonlyArray<string>) => Promise<void>;
|
||||
readonly onRemoveDraftImage: (imageId: string) => void;
|
||||
readonly onStopThread: () => void;
|
||||
readonly onSendMessage: () => Promise<MessageId | null>;
|
||||
readonly onSendMessage: () => Promise<void>;
|
||||
readonly onUpdateModelSelection: (modelSelection: ModelSelection) => void;
|
||||
readonly onUpdateRuntimeMode: (runtimeMode: RuntimeMode) => void;
|
||||
readonly onUpdateInteractionMode: (interactionMode: ProviderInteractionMode) => void;
|
||||
@@ -448,7 +447,9 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
const { onChangeDraftMessage, onUpdateInteractionMode, draftMessage, onSendMessage } = props;
|
||||
|
||||
const handleSend = useCallback(() => {
|
||||
void onSendMessage();
|
||||
void onSendMessage().then(() => {
|
||||
inputRef.current?.blur();
|
||||
});
|
||||
}, [onSendMessage]);
|
||||
const handleCommandSelect = useCallback(
|
||||
(item: ComposerCommandItem) => {
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
import { type EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";
|
||||
import { useKeyboardChatComposerInset, useKeyboardScrollToEnd } from "@legendapp/list/keyboard";
|
||||
import type { LegendListRef } from "@legendapp/list/react-native";
|
||||
import type {
|
||||
ApprovalRequestId,
|
||||
EnvironmentId,
|
||||
MessageId,
|
||||
ModelSelection,
|
||||
OrchestrationThreadShell,
|
||||
ProviderApprovalDecision,
|
||||
@@ -16,8 +13,8 @@ import type {
|
||||
import { formatElapsed } from "@t3tools/shared/orchestrationTiming";
|
||||
import * as Haptics from "expo-haptics";
|
||||
import { useHeaderHeight } from "expo-router/build/react-navigation/elements";
|
||||
import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
|
||||
import { View, type GestureResponderEvent } from "react-native";
|
||||
import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { View, type GestureResponderEvent, type LayoutChangeEvent } from "react-native";
|
||||
import { Gesture, GestureDetector } from "react-native-gesture-handler";
|
||||
import { KeyboardStickyView } from "react-native-keyboard-controller";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
@@ -28,7 +25,7 @@ import type { ComposerEditorHandle } from "../../components/ComposerEditor";
|
||||
import type { StatusTone } from "../../components/StatusPill";
|
||||
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
|
||||
import type { LayoutVariant } from "../../lib/layout";
|
||||
import { scopedThreadKey } from "../../lib/scopedEntities";
|
||||
import { resolveThreadFeedBottomInset } from "../../lib/threadFeedLayout";
|
||||
import type {
|
||||
PendingApproval,
|
||||
PendingUserInput,
|
||||
@@ -76,7 +73,7 @@ export interface ThreadDetailScreenProps {
|
||||
readonly onNativePasteImages: (uris: ReadonlyArray<string>) => Promise<void>;
|
||||
readonly onRemoveDraftImage: (imageId: string) => void;
|
||||
readonly onStopThread: () => void;
|
||||
readonly onSendMessage: () => Promise<MessageId | null>;
|
||||
readonly onSendMessage: () => Promise<void>;
|
||||
readonly onReconnectEnvironment: () => void;
|
||||
readonly onUpdateThreadModelSelection: (modelSelection: ModelSelection) => void;
|
||||
readonly onUpdateThreadRuntimeMode: (runtimeMode: RuntimeMode) => void;
|
||||
@@ -209,33 +206,25 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
const insets = useSafeAreaInsets();
|
||||
const headerHeight = useHeaderHeight();
|
||||
const agentLabel = `${props.selectedThread.modelSelection.instanceId} agent`;
|
||||
const selectedThreadKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
|
||||
const composerEditorRef = useRef<ComposerEditorHandle>(null);
|
||||
const composerOverlayRef = useRef<View>(null);
|
||||
const listRef = useRef<LegendListRef>(null);
|
||||
const composerRef = useRef<ComposerEditorHandle>(null);
|
||||
const feedTouchStartRef = useRef<{ pageX: number; pageY: number } | null>(null);
|
||||
const selectedThreadKeyRef = useRef(selectedThreadKey);
|
||||
const lastScrolledAnchorMessageIdRef = useRef<MessageId | null>(null);
|
||||
const [composerExpanded, setComposerExpanded] = useState(false);
|
||||
const [anchorMessageId, setAnchorMessageId] = useState<MessageId | null>(null);
|
||||
const composerBottomInset = composerExpanded ? 0 : Math.max(insets.bottom, 12);
|
||||
const contentPresentationKind = props.contentPresentation.kind;
|
||||
const selectedThreadFeed = props.selectedThreadFeed;
|
||||
const composerChrome = composerExpanded ? COMPOSER_EXPANDED_CHROME : COMPOSER_COLLAPSED_CHROME;
|
||||
const composerOverlapHeight = composerChrome + composerBottomInset;
|
||||
const activeWorkIndicatorHeight = props.activeWorkStartedAt ? WORKING_INDICATOR_HEIGHT : 0;
|
||||
const estimatedOverlayHeight = composerOverlapHeight + activeWorkIndicatorHeight + 8;
|
||||
const { contentInsetEndAdjustment, onComposerLayout } = useKeyboardChatComposerInset(
|
||||
listRef,
|
||||
composerOverlayRef,
|
||||
estimatedOverlayHeight,
|
||||
);
|
||||
const { freeze, scrollMessageToEnd } = useKeyboardScrollToEnd({ listRef });
|
||||
const estimatedOverlayHeight = composerOverlapHeight + activeWorkIndicatorHeight;
|
||||
const [measuredOverlayHeight, setMeasuredOverlayHeight] = useState(0);
|
||||
const showContent = props.showContent ?? true;
|
||||
const layoutVariant = props.layoutVariant ?? "compact";
|
||||
const isSplitLayout = layoutVariant === "split";
|
||||
const selectedInstanceId = props.selectedThread.modelSelection.instanceId;
|
||||
useStreamingHaptics(props.selectedThread.id, props.selectedThreadFeed);
|
||||
const feedBottomInset = resolveThreadFeedBottomInset({
|
||||
estimatedOverlayHeight,
|
||||
measuredOverlayHeight,
|
||||
gap: 8,
|
||||
});
|
||||
const selectedProviderSkills = useMemo(
|
||||
() =>
|
||||
props.serverConfig?.providers.find((provider) => provider.instanceId === selectedInstanceId)
|
||||
@@ -265,67 +254,15 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
[completeDrawerGesture, isSplitLayout],
|
||||
);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
selectedThreadKeyRef.current = selectedThreadKey;
|
||||
}, [selectedThreadKey]);
|
||||
|
||||
useEffect(() => {
|
||||
setAnchorMessageId(null);
|
||||
lastScrolledAnchorMessageIdRef.current = null;
|
||||
freeze.set(false);
|
||||
}, [freeze, selectedThreadKey]);
|
||||
|
||||
useEffect(() => {
|
||||
if (
|
||||
anchorMessageId === null ||
|
||||
lastScrolledAnchorMessageIdRef.current === anchorMessageId ||
|
||||
contentPresentationKind !== "ready" ||
|
||||
!selectedThreadFeed.some((entry) => entry.type === "message" && entry.id === anchorMessageId)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
const targetThreadKey = selectedThreadKey;
|
||||
const frame = requestAnimationFrame(() => {
|
||||
if (selectedThreadKeyRef.current !== targetThreadKey) {
|
||||
return;
|
||||
}
|
||||
lastScrolledAnchorMessageIdRef.current = anchorMessageId;
|
||||
void scrollMessageToEnd({ animated: true, closeKeyboard: false }).catch(() => {
|
||||
if (
|
||||
selectedThreadKeyRef.current !== targetThreadKey ||
|
||||
lastScrolledAnchorMessageIdRef.current !== anchorMessageId
|
||||
) {
|
||||
return;
|
||||
}
|
||||
lastScrolledAnchorMessageIdRef.current = null;
|
||||
freeze.set(false);
|
||||
});
|
||||
});
|
||||
return () => cancelAnimationFrame(frame);
|
||||
}, [
|
||||
anchorMessageId,
|
||||
freeze,
|
||||
contentPresentationKind,
|
||||
selectedThreadFeed,
|
||||
scrollMessageToEnd,
|
||||
selectedThreadKey,
|
||||
]);
|
||||
|
||||
const handleSendMessage = useCallback(async () => {
|
||||
const targetThreadKey = selectedThreadKey;
|
||||
const messageId = await props.onSendMessage();
|
||||
if (messageId === null || selectedThreadKeyRef.current !== targetThreadKey) {
|
||||
return messageId;
|
||||
}
|
||||
|
||||
setAnchorMessageId(messageId);
|
||||
composerEditorRef.current?.blur();
|
||||
return messageId;
|
||||
}, [props.onSendMessage, selectedThreadKey]);
|
||||
const handleOverlayLayout = useCallback((event: LayoutChangeEvent) => {
|
||||
const nextHeight = Math.ceil(event.nativeEvent.layout.height);
|
||||
setMeasuredOverlayHeight((current) =>
|
||||
Math.abs(current - nextHeight) > 1 ? nextHeight : current,
|
||||
);
|
||||
}, []);
|
||||
|
||||
const collapseComposer = useCallback(() => {
|
||||
composerEditorRef.current?.blur();
|
||||
composerRef.current?.blur();
|
||||
}, []);
|
||||
|
||||
const handleFeedTouchStart = useCallback((event: GestureResponderEvent) => {
|
||||
@@ -378,13 +315,10 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
contentPresentation={props.contentPresentation}
|
||||
agentLabel={agentLabel}
|
||||
latestTurn={props.selectedThread.latestTurn}
|
||||
listRef={listRef}
|
||||
freeze={freeze}
|
||||
anchorMessageId={anchorMessageId}
|
||||
contentInsetEndAdjustment={contentInsetEndAdjustment}
|
||||
contentTopInset={headerHeight}
|
||||
contentBottomInset={estimatedOverlayHeight}
|
||||
contentBottomInset={feedBottomInset}
|
||||
layoutVariant={layoutVariant}
|
||||
composerExpanded={composerExpanded}
|
||||
skills={selectedProviderSkills}
|
||||
/>
|
||||
</View>
|
||||
@@ -398,7 +332,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}
|
||||
offset={{ closed: 0, opened: 0 }}
|
||||
>
|
||||
<View ref={composerOverlayRef} onLayout={onComposerLayout} style={{ paddingTop: 8 }}>
|
||||
<View onLayout={handleOverlayLayout}>
|
||||
{props.activeWorkStartedAt ? (
|
||||
<WorkingDurationPill startedAt={props.activeWorkStartedAt} />
|
||||
) : null}
|
||||
@@ -427,7 +361,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
) : null}
|
||||
|
||||
<ThreadComposer
|
||||
editorRef={composerEditorRef}
|
||||
editorRef={composerRef}
|
||||
draftMessage={props.draftMessage}
|
||||
draftAttachments={props.draftAttachments}
|
||||
placeholder="Ask the repo agent, or run a command…"
|
||||
@@ -446,7 +380,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
onNativePasteImages={props.onNativePasteImages}
|
||||
onRemoveDraftImage={props.onRemoveDraftImage}
|
||||
onStopThread={props.onStopThread}
|
||||
onSendMessage={handleSendMessage}
|
||||
onSendMessage={props.onSendMessage}
|
||||
onReconnectEnvironment={props.onReconnectEnvironment}
|
||||
onUpdateModelSelection={props.onUpdateThreadModelSelection}
|
||||
onUpdateRuntimeMode={props.onUpdateThreadRuntimeMode}
|
||||
|
||||
@@ -1,20 +1,10 @@
|
||||
import * as Haptics from "expo-haptics";
|
||||
import { KeyboardAwareLegendList } from "@legendapp/list/keyboard";
|
||||
import { KeyboardAvoidingLegendList } from "@legendapp/list/keyboard";
|
||||
import { type LegendListRef } from "@legendapp/list/react-native";
|
||||
import type { EnvironmentId, MessageId, ThreadId, TurnId } from "@t3tools/contracts";
|
||||
import { CHAT_LIST_ANCHOR_OFFSET, resolveChatListAnchoredEndSpace } from "@t3tools/shared/chatList";
|
||||
import type { EnvironmentId, ThreadId, TurnId } from "@t3tools/contracts";
|
||||
import { SymbolView } from "expo-symbols";
|
||||
import { useRouter } from "expo-router";
|
||||
import {
|
||||
memo,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
type ReactNode,
|
||||
type RefObject,
|
||||
} from "react";
|
||||
import { memo, useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
|
||||
import {
|
||||
Markdown,
|
||||
type CustomRenderers,
|
||||
@@ -25,6 +15,8 @@ import {
|
||||
ActivityIndicator,
|
||||
Image,
|
||||
Linking,
|
||||
type NativeScrollEvent,
|
||||
type NativeSyntheticEvent,
|
||||
Pressable,
|
||||
ScrollView,
|
||||
StyleSheet,
|
||||
@@ -37,7 +29,6 @@ import {
|
||||
import { TouchableOpacity } from "react-native-gesture-handler";
|
||||
import ImageViewing from "react-native-image-viewing";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import type { SharedValue } from "react-native-reanimated";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
|
||||
import {
|
||||
@@ -73,11 +64,14 @@ import {
|
||||
type ThreadFeedEntry,
|
||||
type ThreadFeedLatestTurn,
|
||||
} from "../../lib/threadActivity";
|
||||
import { isThreadFeedNearEnd } from "../../lib/threadFeedLayout";
|
||||
import { relativeTime } from "../../lib/time";
|
||||
import type { ThreadContentPresentation } from "./threadContentPresentation";
|
||||
import { ThreadWorkLog } from "./thread-work-log";
|
||||
import { useAssetUrl } from "../../state/assets";
|
||||
import { resolveWorkspaceRelativeFilePath } from "../files/filePath";
|
||||
|
||||
const THREAD_FEED_END_THRESHOLD = 80;
|
||||
const MESSAGE_TIME_FORMATTER = new Intl.DateTimeFormat(undefined, {
|
||||
hour: "numeric",
|
||||
minute: "2-digit",
|
||||
@@ -99,13 +93,10 @@ export interface ThreadFeedProps {
|
||||
readonly contentPresentation: ThreadContentPresentation;
|
||||
readonly agentLabel: string;
|
||||
readonly latestTurn: ThreadFeedLatestTurn | null;
|
||||
readonly listRef: RefObject<LegendListRef | null>;
|
||||
readonly freeze: SharedValue<boolean>;
|
||||
readonly anchorMessageId: MessageId | null;
|
||||
readonly contentInsetEndAdjustment: SharedValue<number>;
|
||||
readonly contentTopInset?: number;
|
||||
readonly contentBottomInset?: number;
|
||||
readonly layoutVariant?: LayoutVariant;
|
||||
readonly composerExpanded?: boolean;
|
||||
readonly skills?: ReadonlyArray<SelectableMarkdownSkill>;
|
||||
}
|
||||
|
||||
@@ -821,6 +812,30 @@ 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}
|
||||
@@ -1107,12 +1122,17 @@ function ThreadFeedPlaceholder(props: {
|
||||
|
||||
export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
const router = useRouter();
|
||||
const listRef = useRef<LegendListRef>(null);
|
||||
const copyFeedbackTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const scrollFrameRef = useRef<number | null>(null);
|
||||
const foldSettleFrameRef = useRef<number | null>(null);
|
||||
const foldSettleSecondFrameRef = useRef<number | null>(null);
|
||||
const 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>;
|
||||
@@ -1194,16 +1214,6 @@ 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) {
|
||||
@@ -1219,6 +1229,54 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
? props.latestTurn.turnId
|
||||
: null;
|
||||
|
||||
const scrollToEnd = useCallback(() => {
|
||||
if (scrollFrameRef.current !== null) {
|
||||
return;
|
||||
}
|
||||
scrollFrameRef.current = requestAnimationFrame(() => {
|
||||
scrollFrameRef.current = null;
|
||||
listRef.current?.scrollToEnd({ animated: false });
|
||||
});
|
||||
}, []);
|
||||
|
||||
const onListScroll = useCallback(
|
||||
(event: NativeSyntheticEvent<NativeScrollEvent> | NativeScrollEvent) => {
|
||||
const scrollEvent = "nativeEvent" in event ? event.nativeEvent : event;
|
||||
const { contentInset, contentOffset, contentSize, layoutMeasurement } = scrollEvent;
|
||||
isNearEndRef.current = isThreadFeedNearEnd(
|
||||
{
|
||||
contentHeight: contentSize.height,
|
||||
viewportHeight: layoutMeasurement.height,
|
||||
offsetY: contentOffset.y,
|
||||
bottomInset: contentInset.bottom,
|
||||
},
|
||||
THREAD_FEED_END_THRESHOLD,
|
||||
);
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const onListContentSizeChange = useCallback(
|
||||
(_width: number, height: number) => {
|
||||
const contentGrew = height > lastContentHeightRef.current + 0.5;
|
||||
lastContentHeightRef.current = height;
|
||||
|
||||
if (
|
||||
initialScrollReadyRef.current &&
|
||||
contentGrew &&
|
||||
isNearEndRef.current &&
|
||||
!suppressAutoFollowRef.current
|
||||
) {
|
||||
scrollToEnd();
|
||||
}
|
||||
},
|
||||
[scrollToEnd],
|
||||
);
|
||||
|
||||
const onListLoad = useCallback(() => {
|
||||
initialScrollReadyRef.current = true;
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const previous = previousLatestTurnRef.current;
|
||||
previousLatestTurnRef.current = props.latestTurn;
|
||||
@@ -1250,6 +1308,9 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
if (copyFeedbackTimeoutRef.current) {
|
||||
clearTimeout(copyFeedbackTimeoutRef.current);
|
||||
}
|
||||
if (scrollFrameRef.current !== null) {
|
||||
cancelAnimationFrame(scrollFrameRef.current);
|
||||
}
|
||||
if (foldSettleFrameRef.current !== null) {
|
||||
cancelAnimationFrame(foldSettleFrameRef.current);
|
||||
}
|
||||
@@ -1297,7 +1358,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
}, []);
|
||||
|
||||
const onToggleTurnFold = useCallback((turnId: TurnId) => {
|
||||
setFoldToggleSettling(true);
|
||||
suppressAutoFollowRef.current = true;
|
||||
if (foldSettleFrameRef.current !== null) {
|
||||
cancelAnimationFrame(foldSettleFrameRef.current);
|
||||
}
|
||||
@@ -1315,7 +1376,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
});
|
||||
foldSettleFrameRef.current = requestAnimationFrame(() => {
|
||||
foldSettleSecondFrameRef.current = requestAnimationFrame(() => {
|
||||
setFoldToggleSettling(false);
|
||||
suppressAutoFollowRef.current = false;
|
||||
foldSettleFrameRef.current = null;
|
||||
foldSettleSecondFrameRef.current = null;
|
||||
});
|
||||
@@ -1397,60 +1458,59 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
);
|
||||
}
|
||||
|
||||
if (props.feed.length === 0) {
|
||||
return (
|
||||
<ThreadFeedPlaceholder
|
||||
title="No conversation yet"
|
||||
detail="Ask the agent to inspect the repo, run a command, or continue the active thread."
|
||||
topInset={topContentInset}
|
||||
bottomInset={bottomContentInset}
|
||||
horizontalPadding={horizontalPadding}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<View style={{ flex: 1 }}>
|
||||
<KeyboardAwareLegendList
|
||||
ref={props.listRef}
|
||||
<KeyboardAvoidingLegendList
|
||||
ref={listRef}
|
||||
key={props.threadId}
|
||||
style={{ flex: 1 }}
|
||||
automaticallyAdjustsScrollIndicatorInsets={false}
|
||||
contentInset={{ top: 0, bottom: 0 }}
|
||||
scrollIndicatorInsets={{ top: topContentInset, bottom: 0 }}
|
||||
{...(anchoredEndSpace ? { anchoredEndSpace } : {})}
|
||||
contentInsetEndAdjustment={props.contentInsetEndAdjustment}
|
||||
freeze={props.freeze}
|
||||
maintainScrollAtEnd={
|
||||
foldToggleSettling
|
||||
? false
|
||||
: {
|
||||
animated: false,
|
||||
on: {
|
||||
dataChange: true,
|
||||
itemLayout: true,
|
||||
layout: true,
|
||||
},
|
||||
}
|
||||
}
|
||||
maintainVisibleContentPosition
|
||||
alignItemsAtEnd
|
||||
maintainScrollAtEnd={{
|
||||
animated: false,
|
||||
on: {
|
||||
dataChange: true,
|
||||
itemLayout: true,
|
||||
layout: true,
|
||||
},
|
||||
}}
|
||||
data={presentedFeed}
|
||||
extraData={listAppearanceData}
|
||||
renderItem={renderItem}
|
||||
keyExtractor={(entry) => entry.id}
|
||||
keyExtractor={(entry) => `${entry.type}:${entry.id}`}
|
||||
getItemType={(entry) =>
|
||||
entry.type === "message" ? `message:${entry.message.role}` : entry.type
|
||||
}
|
||||
keyboardShouldPersistTaps="always"
|
||||
keyboardDismissMode="none"
|
||||
keyboardLiftBehavior="whenAtEnd"
|
||||
estimatedItemSize={180}
|
||||
initialScrollAtEnd
|
||||
onContentSizeChange={onListContentSizeChange}
|
||||
onLoad={onListLoad}
|
||||
onScroll={onListScroll}
|
||||
scrollEventThrottle={16}
|
||||
ListHeaderComponent={<View style={{ height: topContentInset }} />}
|
||||
contentContainerStyle={{
|
||||
paddingTop: 12,
|
||||
paddingBottom: bottomContentInset,
|
||||
paddingHorizontal: horizontalPadding,
|
||||
}}
|
||||
/>
|
||||
{props.feed.length === 0 ? (
|
||||
<View pointerEvents="none" style={StyleSheet.absoluteFill}>
|
||||
<ThreadFeedPlaceholder
|
||||
title="No conversation yet"
|
||||
detail="Ask the agent to inspect the repo, run a command, or continue the active thread."
|
||||
topInset={topContentInset}
|
||||
bottomInset={bottomContentInset}
|
||||
horizontalPadding={horizontalPadding}
|
||||
/>
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
|
||||
<ImageViewing
|
||||
|
||||
@@ -1,7 +1,13 @@
|
||||
import { Stack, useLocalSearchParams, useRouter } from "expo-router";
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
import * as Option from "effect/Option";
|
||||
import { EnvironmentId, type ProjectScript } from "@t3tools/contracts";
|
||||
import {
|
||||
EnvironmentId,
|
||||
type ModelSelection,
|
||||
type ProjectScript,
|
||||
type ProviderInteractionMode,
|
||||
type RuntimeMode,
|
||||
} from "@t3tools/contracts";
|
||||
import { projectScriptCwd, projectScriptRuntimeEnv } from "@t3tools/shared/projectScripts";
|
||||
import { Pressable, ScrollView, Text as RNText, View } from "react-native";
|
||||
import { useWorkspaceState } from "../../state/workspace";
|
||||
@@ -73,6 +79,18 @@ export function ThreadRouteScreen() {
|
||||
const gitState = useSelectedThreadGitState();
|
||||
const gitActions = useSelectedThreadGitActions();
|
||||
const requests = useSelectedThreadRequests();
|
||||
const updateThreadMetadata = useAtomCommand(
|
||||
threadEnvironment.updateMetadata,
|
||||
"thread metadata update",
|
||||
);
|
||||
const setThreadRuntimeMode = useAtomCommand(
|
||||
threadEnvironment.setRuntimeMode,
|
||||
"thread runtime mode",
|
||||
);
|
||||
const setThreadInteractionMode = useAtomCommand(
|
||||
threadEnvironment.setInteractionMode,
|
||||
"thread interaction mode",
|
||||
);
|
||||
const interruptThreadTurn = useAtomCommand(threadEnvironment.interruptTurn, "thread interrupt");
|
||||
const router = useRouter();
|
||||
const params = useLocalSearchParams<{
|
||||
@@ -87,18 +105,6 @@ export function ThreadRouteScreen() {
|
||||
const routeConnectionState =
|
||||
routeEnvironmentRuntime?.connectionState ?? (environmentId ? "available" : connectionState);
|
||||
const routeConnectionError = routeEnvironmentRuntime?.connectionError ?? null;
|
||||
const selectedThreadWithDraftSettings = useMemo(
|
||||
() =>
|
||||
selectedThread
|
||||
? {
|
||||
...selectedThread,
|
||||
modelSelection: composer.modelSelection ?? selectedThread.modelSelection,
|
||||
runtimeMode: composer.runtimeMode ?? selectedThread.runtimeMode,
|
||||
interactionMode: composer.interactionMode ?? selectedThread.interactionMode,
|
||||
}
|
||||
: null,
|
||||
[composer.interactionMode, composer.modelSelection, composer.runtimeMode, selectedThread],
|
||||
);
|
||||
|
||||
/* ─── Native header theming ──────────────────────────────────────── */
|
||||
const iconColor = String(useThemeColor("--color-icon"));
|
||||
@@ -151,6 +157,51 @@ export function ThreadRouteScreen() {
|
||||
const handleOpenConnectionEditor = useCallback(() => {
|
||||
void router.push("/connections");
|
||||
}, [router]);
|
||||
const handleUpdateThreadModelSelection = useCallback(
|
||||
(modelSelection: ModelSelection) => {
|
||||
if (!selectedThread) {
|
||||
return;
|
||||
}
|
||||
return updateThreadMetadata({
|
||||
environmentId: selectedThread.environmentId,
|
||||
input: {
|
||||
threadId: selectedThread.id,
|
||||
modelSelection,
|
||||
},
|
||||
});
|
||||
},
|
||||
[selectedThread, updateThreadMetadata],
|
||||
);
|
||||
const handleUpdateThreadRuntimeMode = useCallback(
|
||||
(runtimeMode: RuntimeMode) => {
|
||||
if (!selectedThread) {
|
||||
return;
|
||||
}
|
||||
return setThreadRuntimeMode({
|
||||
environmentId: selectedThread.environmentId,
|
||||
input: {
|
||||
threadId: selectedThread.id,
|
||||
runtimeMode,
|
||||
},
|
||||
});
|
||||
},
|
||||
[selectedThread, setThreadRuntimeMode],
|
||||
);
|
||||
const handleUpdateThreadInteractionMode = useCallback(
|
||||
(interactionMode: ProviderInteractionMode) => {
|
||||
if (!selectedThread) {
|
||||
return;
|
||||
}
|
||||
return setThreadInteractionMode({
|
||||
environmentId: selectedThread.environmentId,
|
||||
input: {
|
||||
threadId: selectedThread.id,
|
||||
interactionMode,
|
||||
},
|
||||
});
|
||||
},
|
||||
[selectedThread, setThreadInteractionMode],
|
||||
);
|
||||
const handleStopThread = useCallback(() => {
|
||||
if (
|
||||
!selectedThread ||
|
||||
@@ -384,7 +435,7 @@ export function ThreadRouteScreen() {
|
||||
|
||||
<View className="flex-1 bg-screen">
|
||||
<ThreadDetailScreen
|
||||
selectedThread={selectedThreadWithDraftSettings ?? selectedThread}
|
||||
selectedThread={selectedThread}
|
||||
contentPresentation={contentPresentation}
|
||||
screenTone={connectionTone(routeConnectionState)}
|
||||
connectionError={routeConnectionError}
|
||||
@@ -415,9 +466,9 @@ export function ThreadRouteScreen() {
|
||||
onStopThread={handleStopThread}
|
||||
onSendMessage={composer.onSendMessage}
|
||||
onReconnectEnvironment={handleReconnectEnvironment}
|
||||
onUpdateThreadModelSelection={composer.onUpdateModelSelection}
|
||||
onUpdateThreadRuntimeMode={composer.onUpdateRuntimeMode}
|
||||
onUpdateThreadInteractionMode={composer.onUpdateInteractionMode}
|
||||
onUpdateThreadModelSelection={handleUpdateThreadModelSelection}
|
||||
onUpdateThreadRuntimeMode={handleUpdateThreadRuntimeMode}
|
||||
onUpdateThreadInteractionMode={handleUpdateThreadInteractionMode}
|
||||
onRespondToApproval={requests.onRespondToApproval}
|
||||
onSelectUserInputOption={requests.onSelectUserInputOption}
|
||||
onChangeUserInputCustomAnswer={requests.onChangeUserInputCustomAnswer}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import React, { useCallback, useMemo, useRef, useState } from "react";
|
||||
|
||||
import type {
|
||||
EnvironmentId,
|
||||
@@ -23,7 +23,6 @@ import {
|
||||
removeComposerDraftAttachment,
|
||||
replaceComposerDraftAttachments,
|
||||
setComposerDraftText,
|
||||
updateComposerDraftSettings,
|
||||
useComposerDraft,
|
||||
} from "../../state/use-composer-drafts";
|
||||
import { useBranches } from "../../state/queries";
|
||||
@@ -159,15 +158,34 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
? selectedEnvironmentIdOverride
|
||||
: (projects[0]?.environmentId ?? null);
|
||||
const [selectedProjectKey, setSelectedProjectKey] = useState<string | null>(null);
|
||||
const [selectedModelKey, setSelectedModelKey] = useState<string | null>(null);
|
||||
const [workspaceMode, setWorkspaceMode] = useState<WorkspaceMode>("local");
|
||||
const [selectedBranchName, setSelectedBranchName] = useState<string | null>(null);
|
||||
const [selectedWorktreePath, setSelectedWorktreePath] = useState<string | null>(null);
|
||||
const branchLoadVersionRef = useRef(0);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [branchQuery, setBranchQuery] = useState("");
|
||||
const [runtimeMode, setRuntimeMode] = useState<RuntimeMode>(DEFAULT_RUNTIME_MODE);
|
||||
const [interactionMode, setInteractionMode] = useState<ProviderInteractionMode>(
|
||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
);
|
||||
const [modelSelectionOverrides, setModelSelectionOverrides] = useState<
|
||||
Record<string, ModelSelection>
|
||||
>({});
|
||||
const [expandedProvider, setExpandedProvider] = useState<string | null>(null);
|
||||
|
||||
const reset = useCallback(() => {
|
||||
setSelectedEnvironmentId(null);
|
||||
setSelectedProjectKey(null);
|
||||
setSelectedModelKey(null);
|
||||
setWorkspaceMode("local");
|
||||
setSelectedBranchName(null);
|
||||
setSelectedWorktreePath(null);
|
||||
setSubmitting(false);
|
||||
setBranchQuery("");
|
||||
setRuntimeMode(DEFAULT_RUNTIME_MODE);
|
||||
setInteractionMode(DEFAULT_PROVIDER_INTERACTION_MODE);
|
||||
setModelSelectionOverrides({});
|
||||
setExpandedProvider(null);
|
||||
}, []);
|
||||
|
||||
@@ -229,33 +247,33 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
const selectedProjectDraft = useComposerDraft(selectedProjectDraftKey);
|
||||
const prompt = selectedProjectDraft.text;
|
||||
const attachments = selectedProjectDraft.attachments;
|
||||
const workspaceMode = selectedProjectDraft.workspaceSelection?.mode ?? "local";
|
||||
const selectedBranchName = selectedProjectDraft.workspaceSelection?.branch ?? null;
|
||||
const selectedWorktreePath = selectedProjectDraft.workspaceSelection?.worktreePath ?? null;
|
||||
const runtimeMode = selectedProjectDraft.runtimeMode ?? DEFAULT_RUNTIME_MODE;
|
||||
const interactionMode = selectedProjectDraft.interactionMode ?? DEFAULT_PROVIDER_INTERACTION_MODE;
|
||||
|
||||
const modelOptions = useMemo(
|
||||
() =>
|
||||
buildModelOptions(
|
||||
selectedEnvironmentServerConfig,
|
||||
selectedProjectDraft.modelSelection ?? selectedProject?.defaultModelSelection ?? null,
|
||||
selectedProject?.defaultModelSelection ?? null,
|
||||
),
|
||||
[
|
||||
selectedEnvironmentServerConfig,
|
||||
selectedProject?.defaultModelSelection,
|
||||
selectedProjectDraft.modelSelection,
|
||||
],
|
||||
[selectedEnvironmentServerConfig, selectedProject?.defaultModelSelection],
|
||||
);
|
||||
|
||||
const selectedModel =
|
||||
selectedProjectDraft.modelSelection ??
|
||||
const defaultModelKey = selectedProject?.defaultModelSelection
|
||||
? `${selectedProject.defaultModelSelection.instanceId}:${selectedProject.defaultModelSelection.model}`
|
||||
: null;
|
||||
const baseSelectedModel =
|
||||
modelOptions.find((option) => option.key === selectedModelKey)?.selection ??
|
||||
(defaultModelKey
|
||||
? modelOptions.find((option) => option.key === defaultModelKey)?.selection
|
||||
: null) ??
|
||||
selectedProject?.defaultModelSelection ??
|
||||
modelOptions[0]?.selection ??
|
||||
null;
|
||||
const selectedModelKey = selectedModel
|
||||
? `${selectedModel.instanceId}:${selectedModel.model}`
|
||||
const selectedModelIdentity = baseSelectedModel
|
||||
? `${baseSelectedModel.instanceId}:${baseSelectedModel.model}`
|
||||
: null;
|
||||
const selectedModel =
|
||||
(selectedModelIdentity ? modelSelectionOverrides[selectedModelIdentity] : null) ??
|
||||
baseSelectedModel;
|
||||
|
||||
const selectedModelOption =
|
||||
modelOptions.find(
|
||||
@@ -264,31 +282,13 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
option.selection.instanceId === selectedModel.instanceId &&
|
||||
option.selection.model === selectedModel.model,
|
||||
) ?? null;
|
||||
const selectedProviderSkills = useMemo(
|
||||
() =>
|
||||
selectedEnvironmentServerConfig?.providers.find(
|
||||
(provider) => provider.instanceId === selectedModel?.instanceId,
|
||||
)?.skills ?? [],
|
||||
[selectedEnvironmentServerConfig, selectedModel?.instanceId],
|
||||
);
|
||||
const setSelectedModelKey = useCallback(
|
||||
(key: string | null) => {
|
||||
if (!key || !selectedProjectDraftKey) {
|
||||
return;
|
||||
}
|
||||
const option = modelOptions.find((candidate) => candidate.key === key);
|
||||
if (!option) {
|
||||
return;
|
||||
}
|
||||
updateComposerDraftSettings(selectedProjectDraftKey, {
|
||||
modelSelection: option.selection,
|
||||
});
|
||||
},
|
||||
[modelOptions, selectedProjectDraftKey],
|
||||
);
|
||||
const selectedProviderSkills =
|
||||
selectedEnvironmentServerConfig?.providers.find(
|
||||
(provider) => provider.instanceId === selectedModel?.instanceId,
|
||||
)?.skills ?? [];
|
||||
const setSelectedModelOptions = useCallback(
|
||||
(options: ReadonlyArray<ProviderOptionSelection> | undefined) => {
|
||||
if (!selectedModel || !selectedProjectDraftKey) {
|
||||
if (!selectedModel || !selectedModelIdentity) {
|
||||
return;
|
||||
}
|
||||
const nextSelection: ModelSelection = options
|
||||
@@ -297,11 +297,12 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
instanceId: selectedModel.instanceId,
|
||||
model: selectedModel.model,
|
||||
};
|
||||
updateComposerDraftSettings(selectedProjectDraftKey, {
|
||||
modelSelection: nextSelection,
|
||||
});
|
||||
setModelSelectionOverrides((current) => ({
|
||||
...current,
|
||||
[selectedModelIdentity]: nextSelection,
|
||||
}));
|
||||
},
|
||||
[selectedModel, selectedProjectDraftKey],
|
||||
[selectedModel, selectedModelIdentity],
|
||||
);
|
||||
|
||||
const providerGroups = useMemo(() => groupByProvider(modelOptions), [modelOptions]);
|
||||
@@ -380,85 +381,62 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
|
||||
const setProject = useCallback((project: EnvironmentProject) => {
|
||||
const nextProjectKey = scopedProjectKey(project.environmentId, project.id);
|
||||
branchLoadVersionRef.current += 1;
|
||||
setSelectedEnvironmentId(project.environmentId);
|
||||
setSelectedProjectKey(nextProjectKey);
|
||||
setSelectedBranchName(null);
|
||||
setSelectedWorktreePath(null);
|
||||
setModelSelectionOverrides({});
|
||||
}, []);
|
||||
|
||||
const selectEnvironment = useCallback((environmentId: EnvironmentId) => {
|
||||
branchLoadVersionRef.current += 1;
|
||||
setSelectedEnvironmentId(environmentId);
|
||||
setSelectedProjectKey(null);
|
||||
setSelectedBranchName(null);
|
||||
setSelectedWorktreePath(null);
|
||||
setModelSelectionOverrides({});
|
||||
}, []);
|
||||
|
||||
const setWorkspaceMode = useCallback(
|
||||
(mode: WorkspaceMode) => {
|
||||
if (!selectedProjectDraftKey) {
|
||||
return;
|
||||
}
|
||||
updateComposerDraftSettings(selectedProjectDraftKey, {
|
||||
workspaceSelection: {
|
||||
mode,
|
||||
branch: selectedBranchName,
|
||||
worktreePath: selectedWorktreePath,
|
||||
},
|
||||
});
|
||||
},
|
||||
[selectedBranchName, selectedProjectDraftKey, selectedWorktreePath],
|
||||
);
|
||||
|
||||
const selectBranch = useCallback(
|
||||
(branch: VcsRef) => {
|
||||
if (!selectedProject || !selectedProjectDraftKey) {
|
||||
return;
|
||||
}
|
||||
updateComposerDraftSettings(selectedProjectDraftKey, {
|
||||
workspaceSelection: {
|
||||
mode: workspaceMode,
|
||||
branch: branch.name,
|
||||
worktreePath: normalizeSelectedWorktreePath(selectedProject, branch),
|
||||
},
|
||||
});
|
||||
setSelectedBranchName(branch.name);
|
||||
setSelectedWorktreePath(
|
||||
selectedProject ? normalizeSelectedWorktreePath(selectedProject, branch) : null,
|
||||
);
|
||||
},
|
||||
[selectedProject, selectedProjectDraftKey, workspaceMode],
|
||||
[selectedProject],
|
||||
);
|
||||
|
||||
const refreshBranches = branchState.refresh;
|
||||
const loadBranches = useCallback(async () => {
|
||||
if (!selectedProject) {
|
||||
return;
|
||||
}
|
||||
setPendingConnectionError(null);
|
||||
refreshBranches();
|
||||
}, [refreshBranches, selectedProject]);
|
||||
|
||||
useEffect(() => {
|
||||
if (workspaceMode !== "worktree" || selectedBranchName !== null) {
|
||||
const loadVersion = ++branchLoadVersionRef.current;
|
||||
const projectKey = scopedProjectKey(selectedProject.environmentId, selectedProject.id);
|
||||
branchState.refresh();
|
||||
if (loadVersion !== branchLoadVersionRef.current || selectedProjectKey !== projectKey) {
|
||||
return;
|
||||
}
|
||||
const preferredBranch =
|
||||
availableBranches.find((branch) => branch.current) ??
|
||||
availableBranches.find((branch) => branch.isDefault) ??
|
||||
null;
|
||||
if (preferredBranch) {
|
||||
selectBranch(preferredBranch);
|
||||
setPendingConnectionError(null);
|
||||
if (workspaceMode === "worktree" && !selectedBranchName) {
|
||||
const preferredBranch =
|
||||
availableBranches.find((branch) => branch.current)?.name ??
|
||||
availableBranches.find((branch) => branch.isDefault)?.name ??
|
||||
null;
|
||||
if (preferredBranch) {
|
||||
setSelectedBranchName(preferredBranch);
|
||||
}
|
||||
}
|
||||
}, [availableBranches, selectBranch, selectedBranchName, workspaceMode]);
|
||||
|
||||
const setRuntimeMode = useCallback(
|
||||
(value: RuntimeMode) => {
|
||||
if (selectedProjectDraftKey) {
|
||||
updateComposerDraftSettings(selectedProjectDraftKey, { runtimeMode: value });
|
||||
}
|
||||
},
|
||||
[selectedProjectDraftKey],
|
||||
);
|
||||
const setInteractionMode = useCallback(
|
||||
(value: ProviderInteractionMode) => {
|
||||
if (selectedProjectDraftKey) {
|
||||
updateComposerDraftSettings(selectedProjectDraftKey, { interactionMode: value });
|
||||
}
|
||||
},
|
||||
[selectedProjectDraftKey],
|
||||
);
|
||||
}, [
|
||||
availableBranches,
|
||||
branchState,
|
||||
selectedBranchName,
|
||||
selectedProject,
|
||||
selectedProjectKey,
|
||||
workspaceMode,
|
||||
]);
|
||||
|
||||
const value = useMemo<NewTaskFlowContextValue>(
|
||||
() => ({
|
||||
@@ -535,11 +513,6 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
setProject,
|
||||
selectBranch,
|
||||
selectEnvironment,
|
||||
setInteractionMode,
|
||||
setPrompt,
|
||||
setRuntimeMode,
|
||||
setSelectedModelKey,
|
||||
setWorkspaceMode,
|
||||
submitting,
|
||||
workspaceMode,
|
||||
appendAttachments,
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
export const DraftComposerImageAttachmentSchema = Schema.Struct({
|
||||
id: Schema.String,
|
||||
previewUri: Schema.String,
|
||||
type: Schema.Literal("image"),
|
||||
name: Schema.String,
|
||||
mimeType: Schema.String,
|
||||
sizeBytes: Schema.Number,
|
||||
dataUrl: Schema.String,
|
||||
});
|
||||
@@ -1,6 +1,7 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
import { PROVIDER_SEND_TURN_MAX_ATTACHMENTS } from "@t3tools/contracts";
|
||||
|
||||
const missingFileCause = new Error("missing file");
|
||||
const files = new Map<string, { base64: string; deleted: boolean }>();
|
||||
|
||||
vi.mock("expo-file-system", () => ({
|
||||
@@ -18,7 +19,7 @@ vi.mock("expo-file-system", () => ({
|
||||
async base64(): Promise<string> {
|
||||
const entry = files.get(this.uri);
|
||||
if (!entry || entry.deleted) {
|
||||
throw new Error("missing file");
|
||||
throw missingFileCause;
|
||||
}
|
||||
return entry.base64;
|
||||
}
|
||||
@@ -91,4 +92,30 @@ describe("native pasted image cleanup", () => {
|
||||
expect(files.get(overflow)?.deleted).toBe(true);
|
||||
expect(files.get(userOwned)?.deleted).toBe(false);
|
||||
});
|
||||
|
||||
it("reports structured context when reading a pasted image fails", async () => {
|
||||
const uri = "file:///private/var/mobile/photos/signed-secret-token/missing.png?token=private";
|
||||
const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined);
|
||||
|
||||
await expect(
|
||||
convertPastedImagesToAttachments({ uris: [uri], existingCount: 0 }),
|
||||
).resolves.toEqual([]);
|
||||
expect(warn).toHaveBeenCalledWith(
|
||||
"[composer-images] failed to read pasted image",
|
||||
expect.objectContaining({
|
||||
_tag: "ComposerImageOperationError",
|
||||
operation: "read-pasted-image",
|
||||
uriLength: uri.length,
|
||||
uriProtocol: "file:",
|
||||
cause: missingFileCause,
|
||||
message: `Composer image operation read-pasted-image failed for a file: URI (length ${uri.length}).`,
|
||||
}),
|
||||
);
|
||||
const error = warn.mock.calls[0]?.[1];
|
||||
expect(error).not.toHaveProperty("uri");
|
||||
expect(String(error)).not.toContain("signed-secret-token");
|
||||
expect(String(error)).not.toContain("token=private");
|
||||
|
||||
warn.mockRestore();
|
||||
});
|
||||
});
|
||||
@@ -3,6 +3,8 @@ import {
|
||||
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
|
||||
type UploadChatImageAttachment,
|
||||
} from "@t3tools/contracts";
|
||||
import { getUrlDiagnostics } from "@t3tools/shared/urlDiagnostics";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { uuidv4 } from "./uuid";
|
||||
|
||||
export interface DraftComposerImageAttachment extends UploadChatImageAttachment {
|
||||
@@ -12,6 +14,31 @@ export interface DraftComposerImageAttachment extends UploadChatImageAttachment
|
||||
|
||||
const OWNED_PASTED_IMAGE_DIRECTORY = "t3-composer-paste";
|
||||
|
||||
export class ComposerImageOperationError extends Schema.TaggedErrorClass<ComposerImageOperationError>()(
|
||||
"ComposerImageOperationError",
|
||||
{
|
||||
operation: Schema.Literals([
|
||||
"load-image-picker",
|
||||
"request-media-library-permission",
|
||||
"launch-image-library",
|
||||
"load-clipboard",
|
||||
"check-clipboard-image",
|
||||
"read-clipboard-image",
|
||||
"check-clipboard-text",
|
||||
"read-clipboard-text",
|
||||
"read-pasted-image",
|
||||
"remove-pasted-image",
|
||||
]),
|
||||
uriLength: Schema.optional(Schema.Number),
|
||||
uriProtocol: Schema.optional(Schema.String),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Composer image operation ${this.operation} failed${this.uriLength === undefined ? "" : ` for a ${this.uriProtocol ?? "unknown-protocol"} URI (length ${this.uriLength})`}.`;
|
||||
}
|
||||
}
|
||||
|
||||
function estimateBase64ByteSize(base64: string): number {
|
||||
const padding = base64.endsWith("==") ? 2 : base64.endsWith("=") ? 1 : 0;
|
||||
return Math.floor((base64.length * 3) / 4) - padding;
|
||||
@@ -20,16 +47,22 @@ function estimateBase64ByteSize(base64: string): number {
|
||||
async function loadImagePicker() {
|
||||
try {
|
||||
return await import("expo-image-picker");
|
||||
} catch (error) {
|
||||
throw new Error("Image attachments are unavailable right now.", { cause: error });
|
||||
} catch (cause) {
|
||||
throw new ComposerImageOperationError({
|
||||
operation: "load-image-picker",
|
||||
cause,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function loadClipboard() {
|
||||
try {
|
||||
return await import("expo-clipboard");
|
||||
} catch (error) {
|
||||
throw new Error("Clipboard paste is unavailable right now.", { cause: error });
|
||||
} catch (cause) {
|
||||
throw new ComposerImageOperationError({
|
||||
operation: "load-clipboard",
|
||||
cause,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -49,14 +82,19 @@ export async function pickComposerImages(input: { readonly existingCount: number
|
||||
try {
|
||||
imagePicker = await loadImagePicker();
|
||||
} catch (error) {
|
||||
console.warn("[composer-images] image picker unavailable", error);
|
||||
return {
|
||||
images: [],
|
||||
error:
|
||||
error instanceof Error ? error.message : "Image attachments are unavailable right now.",
|
||||
error: "Image attachments are unavailable right now.",
|
||||
};
|
||||
}
|
||||
|
||||
const permission = await imagePicker.requestMediaLibraryPermissionsAsync();
|
||||
const permission = await imagePicker.requestMediaLibraryPermissionsAsync().catch((cause) => {
|
||||
throw new ComposerImageOperationError({
|
||||
operation: "request-media-library-permission",
|
||||
cause,
|
||||
});
|
||||
});
|
||||
if (!permission.granted) {
|
||||
return {
|
||||
images: [],
|
||||
@@ -64,13 +102,20 @@ export async function pickComposerImages(input: { readonly existingCount: number
|
||||
};
|
||||
}
|
||||
|
||||
const result = await imagePicker.launchImageLibraryAsync({
|
||||
mediaTypes: ["images"],
|
||||
allowsMultipleSelection: true,
|
||||
selectionLimit: remainingSlots,
|
||||
base64: true,
|
||||
quality: 1,
|
||||
});
|
||||
const result = await imagePicker
|
||||
.launchImageLibraryAsync({
|
||||
mediaTypes: ["images"],
|
||||
allowsMultipleSelection: true,
|
||||
selectionLimit: remainingSlots,
|
||||
base64: true,
|
||||
quality: 1,
|
||||
})
|
||||
.catch((cause) => {
|
||||
throw new ComposerImageOperationError({
|
||||
operation: "launch-image-library",
|
||||
cause,
|
||||
});
|
||||
});
|
||||
|
||||
if (result.canceled) {
|
||||
return {
|
||||
@@ -127,16 +172,23 @@ export async function pasteComposerClipboard(input: { readonly existingCount: nu
|
||||
try {
|
||||
clipboard = await loadClipboard();
|
||||
} catch (error) {
|
||||
console.warn("[composer-images] clipboard unavailable", error);
|
||||
return {
|
||||
images: [],
|
||||
text: null,
|
||||
error: error instanceof Error ? error.message : "Clipboard paste is unavailable right now.",
|
||||
error: "Clipboard paste is unavailable right now.",
|
||||
};
|
||||
}
|
||||
|
||||
const remainingSlots = PROVIDER_SEND_TURN_MAX_ATTACHMENTS - input.existingCount;
|
||||
|
||||
if (await clipboard.hasImageAsync()) {
|
||||
const hasImage = await clipboard.hasImageAsync().catch((cause) => {
|
||||
throw new ComposerImageOperationError({
|
||||
operation: "check-clipboard-image",
|
||||
cause,
|
||||
});
|
||||
});
|
||||
if (hasImage) {
|
||||
if (remainingSlots <= 0) {
|
||||
return {
|
||||
images: [],
|
||||
@@ -144,7 +196,12 @@ export async function pasteComposerClipboard(input: { readonly existingCount: nu
|
||||
error: `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} images per message.`,
|
||||
};
|
||||
}
|
||||
const image = await clipboard.getImageAsync({ format: "png" });
|
||||
const image = await clipboard.getImageAsync({ format: "png" }).catch((cause) => {
|
||||
throw new ComposerImageOperationError({
|
||||
operation: "read-clipboard-image",
|
||||
cause,
|
||||
});
|
||||
});
|
||||
if (!image) {
|
||||
return {
|
||||
images: [],
|
||||
@@ -180,8 +237,19 @@ export async function pasteComposerClipboard(input: { readonly existingCount: nu
|
||||
};
|
||||
}
|
||||
|
||||
if (await clipboard.hasStringAsync()) {
|
||||
const text = await clipboard.getStringAsync();
|
||||
const hasText = await clipboard.hasStringAsync().catch((cause) => {
|
||||
throw new ComposerImageOperationError({
|
||||
operation: "check-clipboard-text",
|
||||
cause,
|
||||
});
|
||||
});
|
||||
if (hasText) {
|
||||
const text = await clipboard.getStringAsync().catch((cause) => {
|
||||
throw new ComposerImageOperationError({
|
||||
operation: "read-clipboard-text",
|
||||
cause,
|
||||
});
|
||||
});
|
||||
return {
|
||||
images: [],
|
||||
text: text.length > 0 ? text : null,
|
||||
@@ -230,6 +298,14 @@ export function isOwnedPastedImageUri(uri: string): boolean {
|
||||
}
|
||||
}
|
||||
|
||||
function describeComposerImageUri(uri: string) {
|
||||
const diagnostics = getUrlDiagnostics(uri);
|
||||
return {
|
||||
uriLength: diagnostics.inputLength,
|
||||
...(diagnostics.protocol === undefined ? {} : { uriProtocol: diagnostics.protocol }),
|
||||
};
|
||||
}
|
||||
|
||||
export async function convertPastedImagesToAttachments(input: {
|
||||
readonly uris: ReadonlyArray<string>;
|
||||
readonly existingCount: number;
|
||||
@@ -260,8 +336,15 @@ export async function convertPastedImagesToAttachments(input: {
|
||||
dataUrl: `data:${mimeType};base64,${base64}`,
|
||||
previewUri: ownedTemporaryFile ? `data:${mimeType};base64,${base64}` : uri,
|
||||
});
|
||||
} catch (error) {
|
||||
console.warn("Failed to read pasted image", uri, error);
|
||||
} catch (cause) {
|
||||
console.warn(
|
||||
"[composer-images] failed to read pasted image",
|
||||
new ComposerImageOperationError({
|
||||
operation: "read-pasted-image",
|
||||
...describeComposerImageUri(uri),
|
||||
cause,
|
||||
}),
|
||||
);
|
||||
} finally {
|
||||
if (ownedTemporaryFile) {
|
||||
try {
|
||||
@@ -269,8 +352,15 @@ export async function convertPastedImagesToAttachments(input: {
|
||||
if (file.exists) {
|
||||
file.delete();
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn("Failed to remove temporary pasted image", uri, error);
|
||||
} catch (cause) {
|
||||
console.warn(
|
||||
"[composer-images] failed to remove temporary pasted image",
|
||||
new ComposerImageOperationError({
|
||||
operation: "remove-pasted-image",
|
||||
...describeComposerImageUri(uri),
|
||||
cause,
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -86,7 +86,7 @@ describe("buildThreadFeed", () => {
|
||||
],
|
||||
});
|
||||
|
||||
const feed = buildThreadFeed(thread);
|
||||
const feed = buildThreadFeed(thread, [], null);
|
||||
expect(feed).toMatchObject([
|
||||
{
|
||||
type: "activity-group",
|
||||
@@ -144,7 +144,7 @@ describe("buildThreadFeed", () => {
|
||||
],
|
||||
});
|
||||
|
||||
const feed = buildThreadFeed(thread);
|
||||
const feed = buildThreadFeed(thread, [], null);
|
||||
const group = feed[0];
|
||||
|
||||
expect(group).toMatchObject({
|
||||
@@ -209,7 +209,7 @@ describe("buildThreadFeed", () => {
|
||||
],
|
||||
});
|
||||
|
||||
const group = buildThreadFeed(thread)[0];
|
||||
const group = buildThreadFeed(thread, [], null)[0];
|
||||
expect(group).toMatchObject({ type: "activity-group" });
|
||||
if (!group || group.type !== "activity-group") {
|
||||
return;
|
||||
@@ -271,7 +271,7 @@ describe("buildThreadFeed", () => {
|
||||
],
|
||||
});
|
||||
|
||||
const feed = buildThreadFeed(thread);
|
||||
const feed = buildThreadFeed(thread, [], null);
|
||||
const collapsed = deriveThreadFeedPresentation(feed, thread.latestTurn, new Set());
|
||||
expect(collapsed.map((entry) => entry.id)).toEqual(["turn-fold:turn-1", "assistant-final"]);
|
||||
expect(collapsed[0]).toMatchObject({
|
||||
@@ -359,7 +359,7 @@ describe("buildThreadFeed", () => {
|
||||
],
|
||||
});
|
||||
|
||||
const feed = buildThreadFeed(thread);
|
||||
const feed = buildThreadFeed(thread, [], null);
|
||||
const collapsed = deriveThreadFeedPresentation(feed, thread.latestTurn, new Set());
|
||||
expect(collapsed.find((entry) => entry.type === "turn-fold")).toMatchObject({
|
||||
turnId: firstTurnId,
|
||||
@@ -399,7 +399,7 @@ describe("buildThreadFeed", () => {
|
||||
],
|
||||
});
|
||||
|
||||
const feed = buildThreadFeed(thread);
|
||||
const feed = buildThreadFeed(thread, [], null);
|
||||
expect(deriveThreadFeedPresentation(feed, thread.latestTurn, new Set())).toEqual(feed);
|
||||
expect(feed[0]).toMatchObject({
|
||||
type: "activity-group",
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { ApprovalRequestId, isToolLifecycleItemType } from "@t3tools/contracts";
|
||||
import type {
|
||||
MessageId,
|
||||
OrchestrationLatestTurn,
|
||||
OrchestrationThread,
|
||||
OrchestrationThreadActivity,
|
||||
@@ -9,6 +10,7 @@ import type {
|
||||
} from "@t3tools/contracts";
|
||||
import { formatDuration } from "@t3tools/shared/orchestrationTiming";
|
||||
|
||||
import type { QueuedThreadMessage } from "../state/thread-outbox-model";
|
||||
import * as Arr from "effect/Array";
|
||||
import * as Order from "effect/Order";
|
||||
|
||||
@@ -86,6 +88,13 @@ type RawThreadFeedEntry =
|
||||
readonly createdAt: string;
|
||||
readonly message: OrchestrationThread["messages"][number];
|
||||
}
|
||||
| {
|
||||
readonly type: "queued-message";
|
||||
readonly id: string;
|
||||
readonly createdAt: string;
|
||||
readonly queuedMessage: QueuedThreadMessage;
|
||||
readonly sending: boolean;
|
||||
}
|
||||
| {
|
||||
readonly type: "activity";
|
||||
readonly id: string;
|
||||
@@ -95,7 +104,7 @@ type RawThreadFeedEntry =
|
||||
};
|
||||
|
||||
export type ThreadFeedEntry =
|
||||
| Extract<RawThreadFeedEntry, { type: "message" }>
|
||||
| Extract<RawThreadFeedEntry, { type: "message" | "queued-message" }>
|
||||
| {
|
||||
readonly type: "activity-group";
|
||||
readonly id: string;
|
||||
@@ -1246,6 +1255,8 @@ export function buildPendingUserInputAnswers(
|
||||
|
||||
export function buildThreadFeed(
|
||||
thread: OrchestrationThread,
|
||||
queuedMessages: ReadonlyArray<QueuedThreadMessage>,
|
||||
dispatchingQueuedMessageId: MessageId | null,
|
||||
options?: {
|
||||
readonly loadedMessages?: ReadonlyArray<OrchestrationThread["messages"][number]>;
|
||||
},
|
||||
@@ -1262,6 +1273,13 @@ export function buildThreadFeed(
|
||||
createdAt: message.createdAt,
|
||||
message,
|
||||
})),
|
||||
...queuedMessages.map<RawThreadFeedEntry>((queuedMessage) => ({
|
||||
type: "queued-message",
|
||||
id: queuedMessage.messageId,
|
||||
createdAt: queuedMessage.createdAt,
|
||||
queuedMessage,
|
||||
sending: queuedMessage.messageId === dispatchingQueuedMessageId,
|
||||
})),
|
||||
...workLogEntries
|
||||
.filter((entry) => {
|
||||
if (options?.loadedMessages === undefined) {
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
isThreadFeedNearEnd,
|
||||
resolveThreadFeedBottomInset,
|
||||
threadFeedDistanceFromEnd,
|
||||
} from "./threadFeedLayout";
|
||||
|
||||
describe("thread feed layout", () => {
|
||||
it("accounts for the bottom inset when measuring distance from the end", () => {
|
||||
const metrics = {
|
||||
contentHeight: 900,
|
||||
viewportHeight: 600,
|
||||
offsetY: 380,
|
||||
bottomInset: 100,
|
||||
};
|
||||
|
||||
expect(threadFeedDistanceFromEnd(metrics)).toBe(20);
|
||||
expect(isThreadFeedNearEnd(metrics, 50)).toBe(true);
|
||||
expect(isThreadFeedNearEnd(metrics, 10)).toBe(false);
|
||||
});
|
||||
|
||||
it("does not double count chrome already included in the measured composer overlay", () => {
|
||||
expect(
|
||||
resolveThreadFeedBottomInset({
|
||||
estimatedOverlayHeight: 162,
|
||||
measuredOverlayHeight: 182,
|
||||
gap: 8,
|
||||
}),
|
||||
).toBe(190);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,22 @@
|
||||
export interface ThreadFeedScrollMetrics {
|
||||
readonly contentHeight: number;
|
||||
readonly viewportHeight: number;
|
||||
readonly offsetY: number;
|
||||
readonly bottomInset: number;
|
||||
}
|
||||
|
||||
export function threadFeedDistanceFromEnd(metrics: ThreadFeedScrollMetrics): number {
|
||||
return metrics.contentHeight + metrics.bottomInset - metrics.viewportHeight - metrics.offsetY;
|
||||
}
|
||||
|
||||
export function isThreadFeedNearEnd(metrics: ThreadFeedScrollMetrics, threshold: number): boolean {
|
||||
return threadFeedDistanceFromEnd(metrics) <= threshold;
|
||||
}
|
||||
|
||||
export function resolveThreadFeedBottomInset(input: {
|
||||
readonly estimatedOverlayHeight: number;
|
||||
readonly measuredOverlayHeight: number;
|
||||
readonly gap: number;
|
||||
}): number {
|
||||
return Math.max(input.estimatedOverlayHeight, input.measuredOverlayHeight) + input.gap;
|
||||
}
|
||||
@@ -1,38 +1,33 @@
|
||||
import { isTransportConnectionErrorMessage } from "@t3tools/client-runtime/errors";
|
||||
import { isEnvironmentRpcUnavailableError } from "@t3tools/client-runtime/rpc";
|
||||
import type { EnvironmentShellStatus } from "@t3tools/client-runtime/state/shell";
|
||||
import {
|
||||
CommandId,
|
||||
EnvironmentId,
|
||||
IsoDateTime,
|
||||
MessageId,
|
||||
ModelSelection,
|
||||
ProviderInteractionMode,
|
||||
RuntimeMode,
|
||||
ThreadId,
|
||||
type ModelSelection as ModelSelectionType,
|
||||
type ProviderInteractionMode as ProviderInteractionModeType,
|
||||
type RuntimeMode as RuntimeModeType,
|
||||
} from "@t3tools/contracts";
|
||||
import { CommandId, EnvironmentId, IsoDateTime, MessageId, ThreadId } from "@t3tools/contracts";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import { DraftComposerImageAttachmentSchema } from "../lib/composer-image-schema";
|
||||
import type { DraftComposerImageAttachment } from "../lib/composerImages";
|
||||
import { scopedThreadKey } from "../lib/scopedEntities";
|
||||
|
||||
const THREAD_OUTBOX_SCHEMA_VERSION = 2;
|
||||
const THREAD_OUTBOX_SCHEMA_VERSION = 1;
|
||||
const THREAD_OUTBOX_MAX_RETRY_DELAY_MS = 16_000;
|
||||
|
||||
const DraftComposerImageAttachmentSchema = Schema.Struct({
|
||||
id: Schema.String,
|
||||
previewUri: Schema.String,
|
||||
type: Schema.Literal("image"),
|
||||
name: Schema.String,
|
||||
mimeType: Schema.String,
|
||||
sizeBytes: Schema.Number,
|
||||
dataUrl: Schema.String,
|
||||
});
|
||||
|
||||
export const QueuedThreadMessageSchema = Schema.Struct({
|
||||
schemaVersion: Schema.Literals([1, THREAD_OUTBOX_SCHEMA_VERSION]),
|
||||
schemaVersion: Schema.Literal(THREAD_OUTBOX_SCHEMA_VERSION),
|
||||
environmentId: EnvironmentId,
|
||||
threadId: ThreadId,
|
||||
messageId: MessageId,
|
||||
commandId: CommandId,
|
||||
text: Schema.String,
|
||||
attachments: Schema.Array(DraftComposerImageAttachmentSchema),
|
||||
modelSelection: Schema.optional(ModelSelection),
|
||||
runtimeMode: Schema.optional(RuntimeMode),
|
||||
interactionMode: Schema.optional(ProviderInteractionMode),
|
||||
createdAt: IsoDateTime,
|
||||
});
|
||||
|
||||
@@ -46,37 +41,9 @@ export interface QueuedThreadMessage {
|
||||
readonly commandId: CommandId;
|
||||
readonly text: string;
|
||||
readonly attachments: ReadonlyArray<DraftComposerImageAttachment>;
|
||||
readonly modelSelection?: ModelSelectionType;
|
||||
readonly runtimeMode?: RuntimeModeType;
|
||||
readonly interactionMode?: ProviderInteractionModeType;
|
||||
readonly createdAt: string;
|
||||
}
|
||||
|
||||
export interface ThreadSettingsSnapshot {
|
||||
readonly modelSelection: ModelSelectionType;
|
||||
readonly runtimeMode: RuntimeModeType;
|
||||
readonly interactionMode: ProviderInteractionModeType;
|
||||
}
|
||||
|
||||
export function resolveQueuedThreadSettings(
|
||||
message: QueuedThreadMessage,
|
||||
thread: ThreadSettingsSnapshot,
|
||||
): ThreadSettingsSnapshot {
|
||||
return {
|
||||
modelSelection: message.modelSelection ?? thread.modelSelection,
|
||||
runtimeMode: message.runtimeMode ?? thread.runtimeMode,
|
||||
interactionMode: message.interactionMode ?? thread.interactionMode,
|
||||
};
|
||||
}
|
||||
|
||||
export function modelSelectionsEqual(left: ModelSelectionType, right: ModelSelectionType): boolean {
|
||||
return (
|
||||
left.instanceId === right.instanceId &&
|
||||
left.model === right.model &&
|
||||
JSON.stringify(left.options ?? null) === JSON.stringify(right.options ?? null)
|
||||
);
|
||||
}
|
||||
|
||||
export function encodeQueuedThreadMessage(message: QueuedThreadMessage): unknown {
|
||||
return encodeStoredQueuedThreadMessage({
|
||||
schemaVersion: THREAD_OUTBOX_SCHEMA_VERSION,
|
||||
@@ -143,6 +110,9 @@ function errorMessage(error: unknown): string | null {
|
||||
}
|
||||
|
||||
export function shouldRetryThreadOutboxDelivery(error: unknown): boolean {
|
||||
if (isEnvironmentRpcUnavailableError(error)) {
|
||||
return true;
|
||||
}
|
||||
if (
|
||||
typeof error === "object" &&
|
||||
error !== null &&
|
||||
@@ -153,21 +123,3 @@ export function shouldRetryThreadOutboxDelivery(error: unknown): boolean {
|
||||
}
|
||||
return isTransportConnectionErrorMessage(errorMessage(error));
|
||||
}
|
||||
|
||||
export type ThreadOutboxCommandStage = "settings-sync" | "start-turn";
|
||||
export type ThreadOutboxFailureAction = "retry" | "discard";
|
||||
|
||||
export function resolveThreadOutboxFailureAction(input: {
|
||||
readonly stage: ThreadOutboxCommandStage;
|
||||
readonly error: unknown;
|
||||
readonly interrupted: boolean;
|
||||
}): ThreadOutboxFailureAction {
|
||||
if (
|
||||
input.stage === "settings-sync" ||
|
||||
input.interrupted ||
|
||||
shouldRetryThreadOutboxDelivery(input.error)
|
||||
) {
|
||||
return "retry";
|
||||
}
|
||||
return "discard";
|
||||
}
|
||||
@@ -1,21 +1,12 @@
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import {
|
||||
CommandId,
|
||||
EnvironmentId,
|
||||
MessageId,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { EnvironmentRpcUnavailableError } from "@t3tools/client-runtime/rpc";
|
||||
import { CommandId, EnvironmentId, MessageId, ThreadId } from "@t3tools/contracts";
|
||||
import { AtomRegistry } from "effect/unstable/reactivity";
|
||||
|
||||
import {
|
||||
decodeQueuedThreadMessage,
|
||||
encodeQueuedThreadMessage,
|
||||
groupQueuedThreadMessages,
|
||||
modelSelectionsEqual,
|
||||
resolveThreadOutboxDeliveryAction,
|
||||
resolveThreadOutboxFailureAction,
|
||||
resolveQueuedThreadSettings,
|
||||
shouldRetryThreadOutboxDelivery,
|
||||
threadOutboxRetryDelayMs,
|
||||
type QueuedThreadMessage,
|
||||
@@ -76,54 +67,6 @@ describe("thread outbox", () => {
|
||||
).toThrow();
|
||||
});
|
||||
|
||||
it("persists the exact selector snapshot while remaining compatible with v1 messages", () => {
|
||||
const legacyMessage = queuedMessage({
|
||||
messageId: "message-1",
|
||||
createdAt: "2026-06-08T10:00:01.000Z",
|
||||
});
|
||||
const selectedMessage = {
|
||||
...legacyMessage,
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5.4",
|
||||
options: [{ id: "reasoningEffort", value: "xhigh" }],
|
||||
},
|
||||
runtimeMode: "approval-required",
|
||||
interactionMode: "plan",
|
||||
} satisfies QueuedThreadMessage;
|
||||
|
||||
expect(decodeQueuedThreadMessage(encodeQueuedThreadMessage(selectedMessage))).toEqual(
|
||||
selectedMessage,
|
||||
);
|
||||
expect(
|
||||
resolveQueuedThreadSettings(legacyMessage, {
|
||||
modelSelection: selectedMessage.modelSelection,
|
||||
runtimeMode: selectedMessage.runtimeMode,
|
||||
interactionMode: selectedMessage.interactionMode,
|
||||
}),
|
||||
).toEqual({
|
||||
modelSelection: selectedMessage.modelSelection,
|
||||
runtimeMode: selectedMessage.runtimeMode,
|
||||
interactionMode: selectedMessage.interactionMode,
|
||||
});
|
||||
});
|
||||
|
||||
it("compares model options as part of the queued settings change", () => {
|
||||
const base = {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5.4",
|
||||
options: [{ id: "reasoningEffort", value: "medium" }],
|
||||
} as const;
|
||||
|
||||
expect(modelSelectionsEqual(base, base)).toBe(true);
|
||||
expect(
|
||||
modelSelectionsEqual(base, {
|
||||
...base,
|
||||
options: [{ id: "reasoningEffort", value: "xhigh" }],
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("backs off queued delivery retries and caps them at sixteen seconds", () => {
|
||||
expect([1, 2, 3, 4, 5, 6].map(threadOutboxRetryDelayMs)).toEqual([
|
||||
1_000, 2_000, 4_000, 8_000, 16_000, 16_000,
|
||||
@@ -320,6 +263,15 @@ describe("thread outbox", () => {
|
||||
});
|
||||
|
||||
it("retries transport failures but drops deterministic command failures", () => {
|
||||
expect(
|
||||
shouldRetryThreadOutboxDelivery(
|
||||
new EnvironmentRpcUnavailableError({
|
||||
environmentId: EnvironmentId.make("environment-1"),
|
||||
environmentLabel: "Test environment",
|
||||
method: "thread.turn.start",
|
||||
}),
|
||||
),
|
||||
).toBe(true);
|
||||
expect(shouldRetryThreadOutboxDelivery(new Error("Socket is not connected"))).toBe(true);
|
||||
expect(
|
||||
shouldRetryThreadOutboxDelivery({
|
||||
@@ -329,23 +281,4 @@ describe("thread outbox", () => {
|
||||
).toBe(true);
|
||||
expect(shouldRetryThreadOutboxDelivery(new Error("Thread no longer exists"))).toBe(false);
|
||||
});
|
||||
|
||||
it("retains queued messages when settings synchronization fails before startTurn", () => {
|
||||
const deterministicFailure = new Error("Thread no longer exists");
|
||||
|
||||
expect(
|
||||
resolveThreadOutboxFailureAction({
|
||||
stage: "settings-sync",
|
||||
error: deterministicFailure,
|
||||
interrupted: false,
|
||||
}),
|
||||
).toBe("retry");
|
||||
expect(
|
||||
resolveThreadOutboxFailureAction({
|
||||
stage: "start-turn",
|
||||
error: deterministicFailure,
|
||||
interrupted: false,
|
||||
}),
|
||||
).toBe("discard");
|
||||
});
|
||||
});
|
||||
@@ -1,136 +1,14 @@
|
||||
import { afterEach, describe, expect, it } from "@effect/vitest";
|
||||
import { EnvironmentId, ProviderInstanceId } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import { EnvironmentId } from "@t3tools/contracts";
|
||||
|
||||
import { appAtomRegistry } from "./atom-registry";
|
||||
import {
|
||||
clearComposerDraftContentState,
|
||||
composerDraftsAtom,
|
||||
decodePersistedComposerDrafts,
|
||||
type ComposerDraft,
|
||||
getComposerDraftSnapshot,
|
||||
removeComposerDraftsForEnvironment,
|
||||
} from "./use-composer-drafts";
|
||||
import { type ComposerDraft, removeComposerDraftsForEnvironment } from "./use-composer-drafts";
|
||||
|
||||
const DRAFT: ComposerDraft = {
|
||||
text: "hello",
|
||||
attachments: [],
|
||||
};
|
||||
|
||||
afterEach(() => {
|
||||
appAtomRegistry.set(composerDraftsAtom, {});
|
||||
});
|
||||
|
||||
describe("mobile composer drafts", () => {
|
||||
it("hydrates selector state even when the message content is empty", () => {
|
||||
expect(
|
||||
decodePersistedComposerDrafts({
|
||||
schemaVersion: 1,
|
||||
drafts: {
|
||||
"new-task:environment-1:project-1": {
|
||||
text: "",
|
||||
attachments: [],
|
||||
modelSelection: {
|
||||
instanceId: "codex",
|
||||
model: "gpt-5.4",
|
||||
options: [{ id: "reasoningEffort", value: "xhigh" }],
|
||||
},
|
||||
runtimeMode: "approval-required",
|
||||
interactionMode: "plan",
|
||||
workspaceSelection: {
|
||||
mode: "worktree",
|
||||
branch: "main",
|
||||
worktreePath: null,
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
"new-task:environment-1:project-1": {
|
||||
text: "",
|
||||
attachments: [],
|
||||
modelSelection: {
|
||||
instanceId: "codex",
|
||||
model: "gpt-5.4",
|
||||
options: [{ id: "reasoningEffort", value: "xhigh" }],
|
||||
},
|
||||
runtimeMode: "approval-required",
|
||||
interactionMode: "plan",
|
||||
workspaceSelection: {
|
||||
mode: "worktree",
|
||||
branch: "main",
|
||||
worktreePath: null,
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps legacy content-only drafts and rejects invalid selector state", () => {
|
||||
expect(
|
||||
decodePersistedComposerDrafts({
|
||||
schemaVersion: 1,
|
||||
drafts: {
|
||||
"environment-1:thread-1": DRAFT,
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
"environment-1:thread-1": DRAFT,
|
||||
});
|
||||
|
||||
expect(() =>
|
||||
decodePersistedComposerDrafts({
|
||||
schemaVersion: 1,
|
||||
drafts: {
|
||||
"environment-1:thread-1": {
|
||||
...DRAFT,
|
||||
runtimeMode: "sometimes-safe",
|
||||
},
|
||||
},
|
||||
}),
|
||||
).toThrow();
|
||||
});
|
||||
|
||||
it("clears sent content without clearing the selected model or workspace", () => {
|
||||
const draftKey = "environment-1:thread-1";
|
||||
const draft: ComposerDraft = {
|
||||
text: "send this",
|
||||
attachments: [],
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5.4",
|
||||
options: [{ id: "reasoningEffort", value: "xhigh" }],
|
||||
},
|
||||
workspaceSelection: {
|
||||
mode: "worktree",
|
||||
branch: "main",
|
||||
worktreePath: null,
|
||||
},
|
||||
};
|
||||
|
||||
expect(clearComposerDraftContentState({ [draftKey]: draft }, draftKey)).toEqual({
|
||||
[draftKey]: {
|
||||
...draft,
|
||||
text: "",
|
||||
attachments: [],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("reads the latest selector state synchronously for send", () => {
|
||||
const draftKey = "environment-1:thread-1";
|
||||
const selectedDraft: ComposerDraft = {
|
||||
text: "send this",
|
||||
attachments: [],
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5.4",
|
||||
options: [{ id: "reasoningEffort", value: "xhigh" }],
|
||||
},
|
||||
};
|
||||
appAtomRegistry.set(composerDraftsAtom, { [draftKey]: selectedDraft });
|
||||
|
||||
expect(getComposerDraftSnapshot(draftKey)).toEqual(selectedDraft);
|
||||
});
|
||||
|
||||
it("removes only drafts owned by the selected environment", () => {
|
||||
const environmentId = EnvironmentId.make("environment-cloud");
|
||||
const retainedEnvironmentId = EnvironmentId.make("environment-local");
|
||||
@@ -139,15 +17,12 @@ describe("mobile composer drafts", () => {
|
||||
removeComposerDraftsForEnvironment(
|
||||
{
|
||||
[`${environmentId}:thread-cloud`]: DRAFT,
|
||||
[`new-task:${environmentId}:project-cloud`]: DRAFT,
|
||||
[`${retainedEnvironmentId}:thread-local`]: DRAFT,
|
||||
[`new-task:${retainedEnvironmentId}:project-local`]: DRAFT,
|
||||
},
|
||||
environmentId,
|
||||
),
|
||||
).toEqual({
|
||||
[`${retainedEnvironmentId}:thread-local`]: DRAFT,
|
||||
[`new-task:${retainedEnvironmentId}:project-local`]: DRAFT,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,18 +1,9 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import {
|
||||
ModelSelection as ModelSelectionSchema,
|
||||
ProviderInteractionMode as ProviderInteractionModeSchema,
|
||||
RuntimeMode as RuntimeModeSchema,
|
||||
type EnvironmentId,
|
||||
type ModelSelection,
|
||||
type ProviderInteractionMode,
|
||||
type RuntimeMode,
|
||||
} from "@t3tools/contracts";
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { useEffect } from "react";
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
|
||||
import { DraftComposerImageAttachmentSchema } from "../lib/composer-image-schema";
|
||||
import type { DraftComposerImageAttachment } from "../lib/composerImages";
|
||||
import { appAtomRegistry } from "./atom-registry";
|
||||
|
||||
@@ -38,47 +29,13 @@ export class ComposerDraftPersistenceError extends Schema.TaggedErrorClass<Compo
|
||||
export interface ComposerDraft {
|
||||
readonly text: string;
|
||||
readonly attachments: ReadonlyArray<DraftComposerImageAttachment>;
|
||||
readonly modelSelection?: ModelSelection;
|
||||
readonly runtimeMode?: RuntimeMode;
|
||||
readonly interactionMode?: ProviderInteractionMode;
|
||||
readonly workspaceSelection?: ComposerDraftWorkspaceSelection;
|
||||
}
|
||||
|
||||
export interface ComposerDraftWorkspaceSelection {
|
||||
readonly mode: "local" | "worktree";
|
||||
readonly branch: string | null;
|
||||
readonly worktreePath: string | null;
|
||||
interface PersistedComposerDrafts {
|
||||
readonly schemaVersion: typeof COMPOSER_DRAFTS_SCHEMA_VERSION;
|
||||
readonly drafts: Record<string, ComposerDraft>;
|
||||
}
|
||||
|
||||
export type ComposerDraftSettingsUpdate = Pick<
|
||||
ComposerDraft,
|
||||
"modelSelection" | "runtimeMode" | "interactionMode" | "workspaceSelection"
|
||||
>;
|
||||
|
||||
const ComposerDraftWorkspaceSelectionSchema = Schema.Struct({
|
||||
mode: Schema.Literals(["local", "worktree"]),
|
||||
branch: Schema.NullOr(Schema.String),
|
||||
worktreePath: Schema.NullOr(Schema.String),
|
||||
});
|
||||
|
||||
const ComposerDraftSchema = Schema.Struct({
|
||||
text: Schema.String,
|
||||
attachments: Schema.Array(DraftComposerImageAttachmentSchema),
|
||||
modelSelection: Schema.optional(ModelSelectionSchema),
|
||||
runtimeMode: Schema.optional(RuntimeModeSchema),
|
||||
interactionMode: Schema.optional(ProviderInteractionModeSchema),
|
||||
workspaceSelection: Schema.optional(ComposerDraftWorkspaceSelectionSchema),
|
||||
});
|
||||
|
||||
const PersistedComposerDraftsSchema = Schema.Struct({
|
||||
schemaVersion: Schema.Literal(COMPOSER_DRAFTS_SCHEMA_VERSION),
|
||||
drafts: Schema.Record(Schema.String, ComposerDraftSchema),
|
||||
});
|
||||
|
||||
const decodePersistedComposerDraftsDocument = Schema.decodeUnknownSync(
|
||||
PersistedComposerDraftsSchema,
|
||||
);
|
||||
|
||||
const EMPTY_DRAFT: ComposerDraft = {
|
||||
text: "",
|
||||
attachments: [],
|
||||
@@ -97,32 +54,13 @@ function normalizeDraft(draft: ComposerDraft | undefined): ComposerDraft {
|
||||
return EMPTY_DRAFT;
|
||||
}
|
||||
return {
|
||||
...draft,
|
||||
text: draft.text,
|
||||
attachments: draft.attachments,
|
||||
};
|
||||
}
|
||||
|
||||
export function getComposerDraftSnapshot(draftKey: string): ComposerDraft {
|
||||
return normalizeDraft(appAtomRegistry.get(composerDraftsAtom)[draftKey]);
|
||||
}
|
||||
|
||||
function isEmptyDraft(draft: ComposerDraft): boolean {
|
||||
return (
|
||||
draft.text.length === 0 &&
|
||||
draft.attachments.length === 0 &&
|
||||
draft.modelSelection === undefined &&
|
||||
draft.runtimeMode === undefined &&
|
||||
draft.interactionMode === undefined &&
|
||||
draft.workspaceSelection === undefined
|
||||
);
|
||||
}
|
||||
|
||||
export function decodePersistedComposerDrafts(value: unknown): Record<string, ComposerDraft> {
|
||||
const parsed = decodePersistedComposerDraftsDocument(value);
|
||||
return Object.fromEntries(
|
||||
Object.entries(parsed.drafts).filter(([, draft]) => !isEmptyDraft(draft)),
|
||||
);
|
||||
return draft.text.length === 0 && draft.attachments.length === 0;
|
||||
}
|
||||
|
||||
async function getComposerDraftsFile() {
|
||||
@@ -142,7 +80,20 @@ async function loadPersistedComposerDrafts(): Promise<Record<string, ComposerDra
|
||||
operation = "read";
|
||||
const raw = await file.text();
|
||||
operation = "decode";
|
||||
return decodePersistedComposerDrafts(JSON.parse(raw) as unknown);
|
||||
const parsed = JSON.parse(raw) as Partial<PersistedComposerDrafts>;
|
||||
if (parsed.schemaVersion !== COMPOSER_DRAFTS_SCHEMA_VERSION || !parsed.drafts) {
|
||||
return {};
|
||||
}
|
||||
return Object.fromEntries(
|
||||
Object.entries(parsed.drafts).filter((entry): entry is [string, ComposerDraft] => {
|
||||
const draft = entry[1];
|
||||
return (
|
||||
typeof draft?.text === "string" &&
|
||||
Array.isArray(draft.attachments) &&
|
||||
!isEmptyDraft(draft)
|
||||
);
|
||||
}),
|
||||
);
|
||||
} catch (cause) {
|
||||
console.warn(
|
||||
"[composer-drafts] ignored persisted draft failure",
|
||||
@@ -165,10 +116,10 @@ async function writePersistedComposerDrafts(drafts: Record<string, ComposerDraft
|
||||
const nonEmptyDrafts = Object.fromEntries(
|
||||
Object.entries(drafts).filter(([, draft]) => !isEmptyDraft(draft)),
|
||||
);
|
||||
const document = {
|
||||
const document: PersistedComposerDrafts = {
|
||||
schemaVersion: COMPOSER_DRAFTS_SCHEMA_VERSION,
|
||||
drafts: nonEmptyDrafts,
|
||||
} as const;
|
||||
};
|
||||
const encoded = JSON.stringify(document);
|
||||
operation = "write";
|
||||
if (!file.exists) {
|
||||
@@ -331,55 +282,6 @@ export function removeComposerDraftAttachment(draftKey: string, imageId: string)
|
||||
});
|
||||
}
|
||||
|
||||
export function updateComposerDraftSettings(
|
||||
draftKey: string,
|
||||
settings: Partial<ComposerDraftSettingsUpdate>,
|
||||
): void {
|
||||
updateComposerDrafts((current) => {
|
||||
const draft = {
|
||||
...normalizeDraft(current[draftKey]),
|
||||
...settings,
|
||||
};
|
||||
if (isEmptyDraft(draft)) {
|
||||
const next = { ...current };
|
||||
delete next[draftKey];
|
||||
return next;
|
||||
}
|
||||
return {
|
||||
...current,
|
||||
[draftKey]: draft,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export function clearComposerDraftContentState(
|
||||
current: Record<string, ComposerDraft>,
|
||||
draftKey: string,
|
||||
): Record<string, ComposerDraft> {
|
||||
const existing = current[draftKey];
|
||||
if (!existing) {
|
||||
return current;
|
||||
}
|
||||
const draft = {
|
||||
...existing,
|
||||
text: "",
|
||||
attachments: [],
|
||||
};
|
||||
if (isEmptyDraft(draft)) {
|
||||
const next = { ...current };
|
||||
delete next[draftKey];
|
||||
return next;
|
||||
}
|
||||
return {
|
||||
...current,
|
||||
[draftKey]: draft,
|
||||
};
|
||||
}
|
||||
|
||||
export function clearComposerDraftContent(draftKey: string): void {
|
||||
updateComposerDrafts((current) => clearComposerDraftContentState(current, draftKey));
|
||||
}
|
||||
|
||||
export function clearComposerDraft(draftKey: string): void {
|
||||
updateComposerDrafts((current) => {
|
||||
if (!current[draftKey]) {
|
||||
@@ -396,12 +298,8 @@ export function removeComposerDraftsForEnvironment(
|
||||
environmentId: EnvironmentId,
|
||||
): Record<string, ComposerDraft> {
|
||||
const environmentPrefix = `${environmentId}:`;
|
||||
const newTaskPrefix = `new-task:${environmentId}:`;
|
||||
return Object.fromEntries(
|
||||
Object.entries(drafts).filter(
|
||||
([draftKey]) =>
|
||||
!draftKey.startsWith(environmentPrefix) && !draftKey.startsWith(newTaskPrefix),
|
||||
),
|
||||
Object.entries(drafts).filter(([draftKey]) => !draftKey.startsWith(environmentPrefix)),
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,15 +1,7 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { useCallback, useEffect, useMemo } from "react";
|
||||
|
||||
import {
|
||||
CommandId,
|
||||
MessageId,
|
||||
type EnvironmentId,
|
||||
type ModelSelection,
|
||||
type ProviderInteractionMode,
|
||||
type RuntimeMode,
|
||||
type ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { CommandId, MessageId, type EnvironmentId, type ThreadId } from "@t3tools/contracts";
|
||||
import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors";
|
||||
import { deriveActiveWorkStartedAt } from "@t3tools/shared/orchestrationTiming";
|
||||
|
||||
@@ -26,13 +18,11 @@ import { appAtomRegistry } from "../state/atom-registry";
|
||||
import {
|
||||
appendComposerDraftAttachments,
|
||||
appendComposerDraftText,
|
||||
clearComposerDraftContent,
|
||||
clearComposerDraft,
|
||||
composerDraftsAtom,
|
||||
ensureComposerDraftsLoaded,
|
||||
getComposerDraftSnapshot,
|
||||
removeComposerDraftAttachment,
|
||||
setComposerDraftText,
|
||||
updateComposerDraftSettings,
|
||||
useComposerDraft,
|
||||
} from "./use-composer-drafts";
|
||||
import { setPendingConnectionError } from "../state/use-remote-environment-registry";
|
||||
@@ -40,6 +30,7 @@ import { useSelectedThreadDetail } from "../state/use-thread-detail";
|
||||
import { useThreadSelection } from "../state/use-thread-selection";
|
||||
import { enqueueThreadOutboxMessage } from "./thread-outbox";
|
||||
import { useThreadOutboxMessages } from "./use-thread-outbox";
|
||||
import { dispatchingQueuedMessageIdAtom } from "./use-thread-outbox-drain";
|
||||
|
||||
export function appendReviewCommentToDraft(input: {
|
||||
readonly environmentId: EnvironmentId;
|
||||
@@ -76,6 +67,7 @@ export function useThreadComposerState() {
|
||||
const { selectedThread: selectedThreadShell } = useThreadSelection();
|
||||
const selectedThreadDetail = useSelectedThreadDetail();
|
||||
const composerDrafts = useAtomValue(composerDraftsAtom);
|
||||
const dispatchingQueuedMessageId = useAtomValue(dispatchingQueuedMessageIdAtom);
|
||||
const queuedMessagesByThreadKey = useThreadOutboxMessages();
|
||||
|
||||
useEffect(() => {
|
||||
@@ -89,19 +81,23 @@ export function useThreadComposerState() {
|
||||
() => (selectedThreadKey ? (queuedMessagesByThreadKey[selectedThreadKey] ?? []) : []),
|
||||
[queuedMessagesByThreadKey, selectedThreadKey],
|
||||
);
|
||||
|
||||
const selectedThreadFeed = useMemo(
|
||||
() => (selectedThreadDetail ? buildThreadFeed(selectedThreadDetail) : []),
|
||||
[selectedThreadDetail],
|
||||
() =>
|
||||
selectedThreadDetail
|
||||
? buildThreadFeed(
|
||||
selectedThreadDetail,
|
||||
selectedThreadQueuedMessages,
|
||||
dispatchingQueuedMessageId,
|
||||
)
|
||||
: [],
|
||||
[dispatchingQueuedMessageId, selectedThreadDetail, selectedThreadQueuedMessages],
|
||||
);
|
||||
|
||||
const selectedDraft = selectedThreadKey ? composerDrafts[selectedThreadKey] : null;
|
||||
const draftMessage = selectedDraft?.text ?? "";
|
||||
const draftAttachments = selectedDraft?.attachments ?? [];
|
||||
const selectedThreadQueueCount = selectedThreadQueuedMessages.length;
|
||||
const selectedThread = selectedThreadDetail ?? selectedThreadShell;
|
||||
const modelSelection = selectedDraft?.modelSelection ?? selectedThread?.modelSelection ?? null;
|
||||
const runtimeMode = selectedDraft?.runtimeMode ?? selectedThread?.runtimeMode ?? null;
|
||||
const interactionMode = selectedDraft?.interactionMode ?? selectedThread?.interactionMode ?? null;
|
||||
|
||||
const selectedThreadSessionActivity = useMemo(() => {
|
||||
const selectedThread = selectedThreadDetail ?? selectedThreadShell;
|
||||
@@ -115,6 +111,7 @@ export function useThreadComposerState() {
|
||||
};
|
||||
}, [selectedThreadDetail, selectedThreadShell]);
|
||||
|
||||
const queuedSendStartedAt = selectedThreadQueuedMessages[0]?.createdAt ?? null;
|
||||
const activeWorkStartedAt = useMemo(() => {
|
||||
const selectedThread = selectedThreadDetail ?? selectedThreadShell;
|
||||
if (!selectedThread) {
|
||||
@@ -124,52 +121,51 @@ export function useThreadComposerState() {
|
||||
return deriveActiveWorkStartedAt(
|
||||
selectedThread.latestTurn,
|
||||
selectedThreadSessionActivity,
|
||||
null,
|
||||
queuedSendStartedAt,
|
||||
);
|
||||
}, [selectedThreadDetail, selectedThreadSessionActivity, selectedThreadShell]);
|
||||
}, [
|
||||
queuedSendStartedAt,
|
||||
selectedThreadDetail,
|
||||
selectedThreadSessionActivity,
|
||||
selectedThreadShell,
|
||||
]);
|
||||
|
||||
const selectedThread = selectedThreadDetail ?? selectedThreadShell;
|
||||
const activeThreadBusy =
|
||||
!!selectedThread &&
|
||||
(selectedThread.session?.status === "running" || selectedThread.session?.status === "starting");
|
||||
|
||||
const onSendMessage = useCallback(async () => {
|
||||
if (!selectedThreadShell) {
|
||||
return null;
|
||||
return;
|
||||
}
|
||||
|
||||
const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
|
||||
const draft = getComposerDraftSnapshot(threadKey);
|
||||
const thread = selectedThreadDetail ?? selectedThreadShell;
|
||||
const text = draft.text.trim();
|
||||
const attachments = draft.attachments;
|
||||
const draft = composerDrafts[threadKey];
|
||||
const text = (draft?.text ?? "").trim();
|
||||
const attachments = draft?.attachments ?? [];
|
||||
if (text.length === 0 && attachments.length === 0) {
|
||||
return null;
|
||||
return;
|
||||
}
|
||||
|
||||
const metadata = makeQueuedMessageMetadata();
|
||||
const messageId = MessageId.make(metadata.messageId);
|
||||
try {
|
||||
await enqueueThreadOutboxMessage({
|
||||
environmentId: selectedThreadShell.environmentId,
|
||||
threadId: selectedThreadShell.id,
|
||||
messageId,
|
||||
messageId: MessageId.make(metadata.messageId),
|
||||
commandId: CommandId.make(metadata.commandId),
|
||||
text,
|
||||
attachments,
|
||||
modelSelection: draft.modelSelection ?? thread.modelSelection,
|
||||
runtimeMode: draft.runtimeMode ?? thread.runtimeMode,
|
||||
interactionMode: draft.interactionMode ?? thread.interactionMode,
|
||||
createdAt: metadata.createdAt,
|
||||
});
|
||||
clearComposerDraftContent(threadKey);
|
||||
return messageId;
|
||||
clearComposerDraft(threadKey);
|
||||
} catch (error) {
|
||||
setPendingConnectionError(
|
||||
error instanceof Error ? error.message : "Failed to save the queued message.",
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}, [selectedThreadDetail, selectedThreadShell]);
|
||||
}, [composerDrafts, selectedThreadShell]);
|
||||
|
||||
const onChangeDraftMessage = useCallback(
|
||||
(value: string) => {
|
||||
@@ -259,45 +255,12 @@ export function useThreadComposerState() {
|
||||
[selectedThreadShell],
|
||||
);
|
||||
|
||||
const onUpdateModelSelection = useCallback(
|
||||
(value: ModelSelection) => {
|
||||
if (!selectedThreadKey) {
|
||||
return;
|
||||
}
|
||||
updateComposerDraftSettings(selectedThreadKey, { modelSelection: value });
|
||||
},
|
||||
[selectedThreadKey],
|
||||
);
|
||||
|
||||
const onUpdateRuntimeMode = useCallback(
|
||||
(value: RuntimeMode) => {
|
||||
if (!selectedThreadKey) {
|
||||
return;
|
||||
}
|
||||
updateComposerDraftSettings(selectedThreadKey, { runtimeMode: value });
|
||||
},
|
||||
[selectedThreadKey],
|
||||
);
|
||||
|
||||
const onUpdateInteractionMode = useCallback(
|
||||
(value: ProviderInteractionMode) => {
|
||||
if (!selectedThreadKey) {
|
||||
return;
|
||||
}
|
||||
updateComposerDraftSettings(selectedThreadKey, { interactionMode: value });
|
||||
},
|
||||
[selectedThreadKey],
|
||||
);
|
||||
|
||||
return {
|
||||
selectedThreadFeed,
|
||||
selectedThreadQueueCount,
|
||||
activeWorkStartedAt,
|
||||
draftMessage,
|
||||
draftAttachments,
|
||||
modelSelection,
|
||||
runtimeMode,
|
||||
interactionMode,
|
||||
activeThreadBusy,
|
||||
onChangeDraftMessage,
|
||||
onPickDraftImages,
|
||||
@@ -305,8 +268,5 @@ export function useThreadComposerState() {
|
||||
onNativePasteImages,
|
||||
onRemoveDraftImage,
|
||||
onSendMessage,
|
||||
onUpdateModelSelection,
|
||||
onUpdateRuntimeMode,
|
||||
onUpdateInteractionMode,
|
||||
};
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
|
||||
import type { AtomCommandResult } from "@t3tools/client-runtime/state/runtime";
|
||||
import { CommandId, type MessageId } from "@t3tools/contracts";
|
||||
import { type MessageId } from "@t3tools/contracts";
|
||||
import * as Cause from "effect/Cause";
|
||||
import { AsyncResult, Atom } from "effect/unstable/reactivity";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
@@ -11,13 +10,10 @@ import { appAtomRegistry } from "./atom-registry";
|
||||
import { useThreadShells } from "./entities";
|
||||
import { ensureThreadOutboxLoaded, removeThreadOutboxMessage } from "./thread-outbox";
|
||||
import {
|
||||
modelSelectionsEqual,
|
||||
resolveThreadOutboxDeliveryAction,
|
||||
resolveThreadOutboxFailureAction,
|
||||
resolveQueuedThreadSettings,
|
||||
shouldRetryThreadOutboxDelivery,
|
||||
threadOutboxRetryDelayMs,
|
||||
type QueuedThreadMessage,
|
||||
type ThreadOutboxCommandStage,
|
||||
} from "./thread-outbox-model";
|
||||
import { threadEnvironment } from "./threads";
|
||||
import { useAtomCommand } from "./use-atom-command";
|
||||
@@ -48,21 +44,8 @@ function findThread(
|
||||
);
|
||||
}
|
||||
|
||||
function settingsCommandId(message: QueuedThreadMessage, setting: string): CommandId {
|
||||
return CommandId.make(`${message.commandId}:${setting}`);
|
||||
}
|
||||
|
||||
export function useThreadOutboxDrain(): void {
|
||||
const startTurn = useAtomCommand(threadEnvironment.startTurn, { reportFailure: false });
|
||||
const updateThreadMetadata = useAtomCommand(threadEnvironment.updateMetadata, {
|
||||
reportFailure: false,
|
||||
});
|
||||
const setThreadRuntimeMode = useAtomCommand(threadEnvironment.setRuntimeMode, {
|
||||
reportFailure: false,
|
||||
});
|
||||
const setThreadInteractionMode = useAtomCommand(threadEnvironment.setInteractionMode, {
|
||||
reportFailure: false,
|
||||
});
|
||||
const dispatchingQueuedMessageId = useAtomValue(dispatchingQueuedMessageIdAtom);
|
||||
const queuedMessagesByThreadKey = useThreadOutboxMessages();
|
||||
const shellStatuses = useThreadOutboxShellStatuses();
|
||||
@@ -85,98 +68,6 @@ export function useThreadOutboxDrain(): void {
|
||||
|
||||
const sendQueuedMessage = useCallback(
|
||||
async (queuedMessage: QueuedThreadMessage, thread: EnvironmentThreadShell) => {
|
||||
const settings = resolveQueuedThreadSettings(queuedMessage, thread);
|
||||
const reportFailure = (
|
||||
commandResult: AtomCommandResult<unknown, unknown>,
|
||||
stage: ThreadOutboxCommandStage,
|
||||
): boolean => {
|
||||
if (!AsyncResult.isFailure(commandResult)) {
|
||||
return false;
|
||||
}
|
||||
const action = resolveThreadOutboxFailureAction({
|
||||
stage,
|
||||
error: Cause.squash(commandResult.cause),
|
||||
interrupted: Cause.hasInterruptsOnly(commandResult.cause),
|
||||
});
|
||||
const retry = action === "retry";
|
||||
console.warn("[thread-outbox] queued message delivery failed", {
|
||||
environmentId: queuedMessage.environmentId,
|
||||
threadId: queuedMessage.threadId,
|
||||
messageId: queuedMessage.messageId,
|
||||
stage,
|
||||
cause: commandResult.cause,
|
||||
retry,
|
||||
});
|
||||
return retry;
|
||||
};
|
||||
const completeDelivery = async (
|
||||
deliveryResult: AtomCommandResult<unknown, unknown>,
|
||||
): Promise<boolean> => {
|
||||
if (reportFailure(deliveryResult, "start-turn")) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
await removeThreadOutboxMessage(queuedMessage);
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.warn("[thread-outbox] failed to remove delivered queued message", {
|
||||
environmentId: queuedMessage.environmentId,
|
||||
threadId: queuedMessage.threadId,
|
||||
messageId: queuedMessage.messageId,
|
||||
error,
|
||||
});
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
if (!modelSelectionsEqual(settings.modelSelection, thread.modelSelection)) {
|
||||
const updateResult = await updateThreadMetadata({
|
||||
environmentId: queuedMessage.environmentId,
|
||||
input: {
|
||||
commandId: settingsCommandId(queuedMessage, "model-selection"),
|
||||
threadId: queuedMessage.threadId,
|
||||
modelSelection: settings.modelSelection,
|
||||
},
|
||||
});
|
||||
if (AsyncResult.isFailure(updateResult)) {
|
||||
reportFailure(updateResult, "settings-sync");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (settings.runtimeMode !== thread.runtimeMode) {
|
||||
const runtimeResult = await setThreadRuntimeMode({
|
||||
environmentId: queuedMessage.environmentId,
|
||||
input: {
|
||||
commandId: settingsCommandId(queuedMessage, "runtime-mode"),
|
||||
threadId: queuedMessage.threadId,
|
||||
runtimeMode: settings.runtimeMode,
|
||||
createdAt: queuedMessage.createdAt,
|
||||
},
|
||||
});
|
||||
if (AsyncResult.isFailure(runtimeResult)) {
|
||||
reportFailure(runtimeResult, "settings-sync");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (settings.interactionMode !== thread.interactionMode) {
|
||||
const interactionResult = await setThreadInteractionMode({
|
||||
environmentId: queuedMessage.environmentId,
|
||||
input: {
|
||||
commandId: settingsCommandId(queuedMessage, "interaction-mode"),
|
||||
threadId: queuedMessage.threadId,
|
||||
interactionMode: settings.interactionMode,
|
||||
createdAt: queuedMessage.createdAt,
|
||||
},
|
||||
});
|
||||
if (AsyncResult.isFailure(interactionResult)) {
|
||||
reportFailure(interactionResult, "settings-sync");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
const deliveryResult = await startTurn({
|
||||
environmentId: queuedMessage.environmentId,
|
||||
input: {
|
||||
@@ -188,15 +79,41 @@ export function useThreadOutboxDrain(): void {
|
||||
text: queuedMessage.text,
|
||||
attachments: queuedMessage.attachments,
|
||||
},
|
||||
modelSelection: settings.modelSelection,
|
||||
runtimeMode: settings.runtimeMode,
|
||||
interactionMode: settings.interactionMode,
|
||||
runtimeMode: thread.runtimeMode,
|
||||
interactionMode: thread.interactionMode,
|
||||
createdAt: queuedMessage.createdAt,
|
||||
},
|
||||
});
|
||||
return completeDelivery(deliveryResult);
|
||||
if (AsyncResult.isFailure(deliveryResult)) {
|
||||
const error = Cause.squash(deliveryResult.cause);
|
||||
const retry =
|
||||
Cause.hasInterruptsOnly(deliveryResult.cause) || shouldRetryThreadOutboxDelivery(error);
|
||||
console.warn("[thread-outbox] queued message delivery failed", {
|
||||
environmentId: queuedMessage.environmentId,
|
||||
threadId: queuedMessage.threadId,
|
||||
messageId: queuedMessage.messageId,
|
||||
cause: deliveryResult.cause,
|
||||
retry,
|
||||
});
|
||||
if (retry) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
await removeThreadOutboxMessage(queuedMessage);
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.warn("[thread-outbox] failed to remove delivered queued message", {
|
||||
environmentId: queuedMessage.environmentId,
|
||||
threadId: queuedMessage.threadId,
|
||||
messageId: queuedMessage.messageId,
|
||||
error,
|
||||
});
|
||||
return false;
|
||||
}
|
||||
},
|
||||
[setThreadInteractionMode, setThreadRuntimeMode, startTurn, updateThreadMetadata],
|
||||
[startTurn],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
|
||||
@@ -19,23 +19,6 @@ const emitInterleavedAssistantToolCalls =
|
||||
const emitGenericToolPlaceholders = process.env.T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS === "1";
|
||||
const emitAskQuestion = process.env.T3_ACP_EMIT_ASK_QUESTION === "1";
|
||||
const emitXAiAskUserQuestion = process.env.T3_ACP_EMIT_XAI_ASK_USER_QUESTION === "1";
|
||||
const emitXAiPromptCompleteThenHang = process.env.T3_ACP_EMIT_XAI_PROMPT_COMPLETE_THEN_HANG === "1";
|
||||
const emitForeignSessionUpdates = process.env.T3_ACP_EMIT_FOREIGN_SESSION_UPDATES === "1";
|
||||
const hangPromptForever = process.env.T3_ACP_HANG_PROMPT_FOREVER === "1";
|
||||
const hangFirstPromptForever = process.env.T3_ACP_HANG_FIRST_PROMPT_FOREVER === "1";
|
||||
const emitLateUpdateAfterCancel = process.env.T3_ACP_EMIT_LATE_UPDATE_AFTER_CANCEL === "1";
|
||||
const omitXAiPromptCompleteStopReason =
|
||||
process.env.T3_ACP_OMIT_XAI_PROMPT_COMPLETE_STOP_REASON === "1";
|
||||
const failLoadSession = process.env.T3_ACP_FAIL_LOAD_SESSION === "1";
|
||||
const emitLoadReplay = process.env.T3_ACP_EMIT_LOAD_REPLAY === "1";
|
||||
const hangLoadSessionAfterReplay = process.env.T3_ACP_HANG_LOAD_SESSION_AFTER_REPLAY === "1";
|
||||
const delayLoadSessionAfterReplay = process.env.T3_ACP_DELAY_LOAD_SESSION_AFTER_REPLAY === "1";
|
||||
const loadSessionDelayMs = Number(process.env.T3_ACP_LOAD_SESSION_DELAY_MS ?? "5000");
|
||||
const emitStaleXAiPromptCompleteBeforeSecondHang =
|
||||
process.env.T3_ACP_EMIT_STALE_XAI_PROMPT_COMPLETE_BEFORE_SECOND_HANG === "1";
|
||||
const emitOverlappingXAiPromptCompleteOutOfOrder =
|
||||
process.env.T3_ACP_EMIT_OVERLAPPING_XAI_PROMPT_COMPLETE_OUT_OF_ORDER === "1";
|
||||
const failPrompt = process.env.T3_ACP_FAIL_PROMPT === "1";
|
||||
const failSetConfigOption = process.env.T3_ACP_FAIL_SET_CONFIG_OPTION === "1";
|
||||
const exitOnSetConfigOption = process.env.T3_ACP_EXIT_ON_SET_CONFIG_OPTION === "1";
|
||||
const promptResponseText = process.env.T3_ACP_PROMPT_RESPONSE_TEXT;
|
||||
@@ -53,21 +36,8 @@ let parameterizedModelPicker = false;
|
||||
let currentReasoning = "medium";
|
||||
let currentContext = "272k";
|
||||
let currentFast = false;
|
||||
let promptCount = 0;
|
||||
let overlappingFirstPromptId: string | undefined;
|
||||
const cancelledSessions = new Set<string>();
|
||||
|
||||
function promptIdFromRequestMeta(
|
||||
request: Pick<AcpSchema.PromptRequest, "_meta">,
|
||||
): string | undefined {
|
||||
const meta = request._meta;
|
||||
if (meta === null || typeof meta !== "object") {
|
||||
return undefined;
|
||||
}
|
||||
const promptId = meta.promptId ?? meta.requestId;
|
||||
return typeof promptId === "string" && promptId.length > 0 ? promptId : undefined;
|
||||
}
|
||||
|
||||
function logExit(reason: string): void {
|
||||
if (!exitLogPath) {
|
||||
return;
|
||||
@@ -75,10 +45,6 @@ function logExit(reason: string): void {
|
||||
NodeFS.appendFileSync(exitLogPath, `${reason}\n`, "utf8");
|
||||
}
|
||||
|
||||
function writeJsonRpcNotification(method: string, params: unknown): void {
|
||||
process.stdout.write(`${JSON.stringify({ jsonrpc: "2.0", method, params })}\n`);
|
||||
}
|
||||
|
||||
process.once("SIGTERM", () => {
|
||||
logExit("SIGTERM");
|
||||
process.exit(0);
|
||||
@@ -318,66 +284,22 @@ const program = Effect.gen(function* () {
|
||||
}),
|
||||
);
|
||||
|
||||
const emitLoadReplayNotifications = (requestedSessionId: string) => {
|
||||
writeJsonRpcNotification("session/update", {
|
||||
_meta: { isReplay: true },
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId: "replay-tool-1",
|
||||
title: "Replay tool",
|
||||
kind: "search",
|
||||
status: "completed",
|
||||
},
|
||||
});
|
||||
writeJsonRpcNotification("session/update", {
|
||||
_meta: { isReplay: true },
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "replayed assistant text" },
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
yield* agent.handleLoadSession((request) =>
|
||||
Effect.gen(function* () {
|
||||
const requestedSessionId = String(request.sessionId ?? sessionId);
|
||||
if (failLoadSession) {
|
||||
return yield* AcpError.AcpRequestError.internalError("Mock load session failure");
|
||||
}
|
||||
if (hangLoadSessionAfterReplay || delayLoadSessionAfterReplay) {
|
||||
emitLoadReplayNotifications(requestedSessionId);
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "user_message_chunk",
|
||||
content: { type: "text", text: "replay-tail" },
|
||||
},
|
||||
});
|
||||
yield* Effect.sleep(loadSessionDelayMs);
|
||||
return {
|
||||
modes: modeState(),
|
||||
models: modelState(),
|
||||
configOptions: configOptions(),
|
||||
};
|
||||
}
|
||||
if (emitLoadReplay) {
|
||||
emitLoadReplayNotifications(requestedSessionId);
|
||||
}
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
agent.client
|
||||
.sessionUpdate({
|
||||
sessionId: String(request.sessionId ?? sessionId),
|
||||
update: {
|
||||
sessionUpdate: "user_message_chunk",
|
||||
content: { type: "text", text: "replay" },
|
||||
},
|
||||
});
|
||||
return {
|
||||
modes: modeState(),
|
||||
models: modelState(),
|
||||
configOptions: configOptions(),
|
||||
};
|
||||
}),
|
||||
})
|
||||
.pipe(
|
||||
Effect.as({
|
||||
modes: modeState(),
|
||||
models: modelState(),
|
||||
configOptions: configOptions(),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
yield* agent.handleSetSessionModel((request) =>
|
||||
@@ -434,152 +356,19 @@ const program = Effect.gen(function* () {
|
||||
);
|
||||
|
||||
yield* agent.handleCancel(({ sessionId }) =>
|
||||
Effect.gen(function* () {
|
||||
const cancelledSessionId = String(sessionId ?? "mock-session-1");
|
||||
cancelledSessions.add(cancelledSessionId);
|
||||
if (emitLateUpdateAfterCancel) {
|
||||
yield* Effect.sleep("50 millis");
|
||||
yield* Effect.sync(() => {
|
||||
writeJsonRpcNotification("session/update", {
|
||||
sessionId: cancelledSessionId,
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "late after cancel" },
|
||||
},
|
||||
});
|
||||
});
|
||||
}
|
||||
Effect.sync(() => {
|
||||
cancelledSessions.add(String(sessionId ?? "mock-session-1"));
|
||||
}),
|
||||
);
|
||||
|
||||
yield* agent.handlePrompt((request) =>
|
||||
Effect.gen(function* () {
|
||||
const requestedSessionId = String(request.sessionId ?? sessionId);
|
||||
promptCount += 1;
|
||||
|
||||
if (Number.isFinite(promptDelayMs) && promptDelayMs > 0) {
|
||||
yield* Effect.sleep(`${promptDelayMs} millis`);
|
||||
}
|
||||
|
||||
if (failPrompt) {
|
||||
return yield* AcpError.AcpRequestError.internalError("Mock prompt failure");
|
||||
}
|
||||
|
||||
if (emitStaleXAiPromptCompleteBeforeSecondHang && promptCount === 1) {
|
||||
return {
|
||||
stopReason: "end_turn",
|
||||
_meta: {
|
||||
promptId: "mock-stale-xai-prompt-1",
|
||||
requestId: "mock-stale-xai-prompt-1",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
if (emitStaleXAiPromptCompleteBeforeSecondHang && promptCount === 2) {
|
||||
const currentPromptId = promptIdFromRequestMeta(request) ?? "mock-current-xai-prompt-2";
|
||||
writeJsonRpcNotification("_x.ai/session/prompt_complete", {
|
||||
sessionId: requestedSessionId,
|
||||
promptId: "mock-stale-xai-prompt-1",
|
||||
stopReason: "end_turn",
|
||||
agentResult: null,
|
||||
});
|
||||
|
||||
writeJsonRpcNotification("_x.ai/session/prompt_complete", {
|
||||
sessionId: requestedSessionId,
|
||||
promptId: currentPromptId,
|
||||
stopReason: "end_turn",
|
||||
agentResult: null,
|
||||
});
|
||||
|
||||
return yield* Effect.never;
|
||||
}
|
||||
|
||||
if (emitOverlappingXAiPromptCompleteOutOfOrder && promptCount === 1) {
|
||||
overlappingFirstPromptId = promptIdFromRequestMeta(request);
|
||||
return yield* Effect.never;
|
||||
}
|
||||
|
||||
if (emitOverlappingXAiPromptCompleteOutOfOrder && promptCount === 2) {
|
||||
const secondPromptId = promptIdFromRequestMeta(request);
|
||||
if (overlappingFirstPromptId !== undefined && secondPromptId !== undefined) {
|
||||
writeJsonRpcNotification("_x.ai/session/prompt_complete", {
|
||||
sessionId: requestedSessionId,
|
||||
promptId: secondPromptId,
|
||||
stopReason: "end_turn",
|
||||
agentResult: null,
|
||||
});
|
||||
writeJsonRpcNotification("_x.ai/session/prompt_complete", {
|
||||
sessionId: requestedSessionId,
|
||||
promptId: overlappingFirstPromptId,
|
||||
stopReason: "end_turn",
|
||||
agentResult: null,
|
||||
});
|
||||
}
|
||||
return yield* Effect.never;
|
||||
}
|
||||
|
||||
if (hangPromptForever || (hangFirstPromptForever && promptCount === 1)) {
|
||||
return yield* Effect.never;
|
||||
}
|
||||
|
||||
if (emitXAiPromptCompleteThenHang) {
|
||||
writeJsonRpcNotification("session/update", {
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "hello from " },
|
||||
},
|
||||
});
|
||||
|
||||
if (emitForeignSessionUpdates) {
|
||||
writeJsonRpcNotification("session/update", {
|
||||
sessionId: "mock-child-session-1",
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "child before completion" },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
writeJsonRpcNotification("_x.ai/session/prompt_complete", {
|
||||
sessionId: requestedSessionId,
|
||||
promptId: promptIdFromRequestMeta(request) ?? "mock-xai-prompt-1",
|
||||
...(omitXAiPromptCompleteStopReason ? {} : { stopReason: "end_turn" }),
|
||||
agentResult: null,
|
||||
});
|
||||
|
||||
if (emitForeignSessionUpdates) {
|
||||
writeJsonRpcNotification("session/update", {
|
||||
sessionId: "mock-child-session-1",
|
||||
update: {
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId: "child-tool-call-1",
|
||||
title: "Child-only tool",
|
||||
kind: "other",
|
||||
status: "pending",
|
||||
rawInput: {},
|
||||
},
|
||||
});
|
||||
writeJsonRpcNotification("session/update", {
|
||||
sessionId: "mock-child-session-1",
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "child after completion" },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
writeJsonRpcNotification("session/update", {
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "mock" },
|
||||
},
|
||||
});
|
||||
|
||||
return yield* Effect.never;
|
||||
}
|
||||
|
||||
if (emitInterleavedAssistantToolCalls) {
|
||||
const toolCallId = "tool-call-1";
|
||||
|
||||
@@ -810,42 +599,6 @@ const program = Effect.gen(function* () {
|
||||
return { stopReason: "end_turn" };
|
||||
}
|
||||
|
||||
if (emitForeignSessionUpdates) {
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "root before child" },
|
||||
},
|
||||
});
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: "mock-child-session-1",
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "child content" },
|
||||
},
|
||||
});
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: "mock-child-session-1",
|
||||
update: {
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId: "child-tool-call-1",
|
||||
title: "Child-only tool",
|
||||
kind: "other",
|
||||
status: "pending",
|
||||
rawInput: {},
|
||||
},
|
||||
});
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: " root after child" },
|
||||
},
|
||||
});
|
||||
return { stopReason: "end_turn" };
|
||||
}
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
|
||||
@@ -114,6 +114,16 @@ it.layer(NodeServices.layer)("EnvironmentAuth.layer", (it) => {
|
||||
.pipe(Effect.flip);
|
||||
|
||||
expect(error._tag).toBe("ServerAuthScopeNotGrantedError");
|
||||
if (error._tag === "ServerAuthScopeNotGrantedError") {
|
||||
expect(error.requestedScopes).toEqual(["orchestration:read", "access:write"]);
|
||||
expect(error.grantedScopes).toEqual([
|
||||
"orchestration:read",
|
||||
"orchestration:operate",
|
||||
"terminal:operate",
|
||||
"review:write",
|
||||
"relay:read",
|
||||
]);
|
||||
}
|
||||
}).pipe(Effect.provide(makeEnvironmentAuthLayer())),
|
||||
);
|
||||
|
||||
@@ -252,4 +262,20 @@ it.layer(NodeServices.layer)("EnvironmentAuth.layer", (it) => {
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("retains both session ids when rejecting self-revocation", () =>
|
||||
Effect.gen(function* () {
|
||||
const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
|
||||
const issued = yield* serverAuth.issueSession();
|
||||
const error = yield* serverAuth
|
||||
.revokeClientSession(issued.sessionId, issued.sessionId)
|
||||
.pipe(Effect.flip);
|
||||
|
||||
expect(error._tag).toBe("ServerAuthForbiddenOperationError");
|
||||
if (error._tag === "ServerAuthForbiddenOperationError") {
|
||||
expect(error.currentSessionId).toBe(issued.sessionId);
|
||||
expect(error.targetSessionId).toBe(issued.sessionId);
|
||||
}
|
||||
}).pipe(Effect.provide(makeEnvironmentAuthLayer())),
|
||||
);
|
||||
});
|
||||
@@ -85,44 +85,50 @@ export class ServerAuthBootstrapCredentialValidationError extends Schema.TaggedE
|
||||
export class ServerAuthSessionCredentialValidationError extends Schema.TaggedErrorClass<ServerAuthSessionCredentialValidationError>()(
|
||||
"ServerAuthSessionCredentialValidationError",
|
||||
{
|
||||
credentialKind: Schema.Literals(["session", "websocket-ticket"]),
|
||||
...serverAuthInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to validate session credential.";
|
||||
return `Failed to validate ${this.credentialKind} credential.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ServerAuthAuthenticatedSessionIssueError extends Schema.TaggedErrorClass<ServerAuthAuthenticatedSessionIssueError>()(
|
||||
"ServerAuthAuthenticatedSessionIssueError",
|
||||
{
|
||||
subject: Schema.String,
|
||||
...serverAuthInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to issue authenticated session.";
|
||||
return `Failed to issue authenticated session for ${this.subject}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ServerAuthAuthenticatedAccessTokenIssueError extends Schema.TaggedErrorClass<ServerAuthAuthenticatedAccessTokenIssueError>()(
|
||||
"ServerAuthAuthenticatedAccessTokenIssueError",
|
||||
{
|
||||
subject: Schema.String,
|
||||
scopes: Schema.Array(Schema.String),
|
||||
...serverAuthInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to issue authenticated access token.";
|
||||
return `Failed to issue authenticated access token for ${this.subject} with scopes [${this.scopes.join(", ")}].`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ServerAuthPairingLinkCreationError extends Schema.TaggedErrorClass<ServerAuthPairingLinkCreationError>()(
|
||||
"ServerAuthPairingLinkCreationError",
|
||||
{
|
||||
subject: Schema.String,
|
||||
scopes: Schema.Array(Schema.String),
|
||||
...serverAuthInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to create pairing link.";
|
||||
return `Failed to create pairing link for ${this.subject} with scopes [${this.scopes.join(", ")}].`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -140,22 +146,25 @@ export class ServerAuthPairingLinksListError extends Schema.TaggedErrorClass<Ser
|
||||
export class ServerAuthPairingLinkRevocationError extends Schema.TaggedErrorClass<ServerAuthPairingLinkRevocationError>()(
|
||||
"ServerAuthPairingLinkRevocationError",
|
||||
{
|
||||
pairingLinkId: Schema.String,
|
||||
...serverAuthInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to revoke pairing link.";
|
||||
return `Failed to revoke pairing link ${this.pairingLinkId}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ServerAuthSessionTokenIssueError extends Schema.TaggedErrorClass<ServerAuthSessionTokenIssueError>()(
|
||||
"ServerAuthSessionTokenIssueError",
|
||||
{
|
||||
subject: Schema.String,
|
||||
scopes: Schema.Array(Schema.String),
|
||||
...serverAuthInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to issue session token.";
|
||||
return `Failed to issue session token for ${this.subject} with scopes [${this.scopes.join(", ")}].`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -173,55 +182,63 @@ export class ServerAuthSessionsListError extends Schema.TaggedErrorClass<ServerA
|
||||
export class ServerAuthSessionRevocationError extends Schema.TaggedErrorClass<ServerAuthSessionRevocationError>()(
|
||||
"ServerAuthSessionRevocationError",
|
||||
{
|
||||
sessionId: Schema.String,
|
||||
...serverAuthInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to revoke session.";
|
||||
return `Failed to revoke session ${this.sessionId}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ServerAuthOtherSessionsRevocationError extends Schema.TaggedErrorClass<ServerAuthOtherSessionsRevocationError>()(
|
||||
"ServerAuthOtherSessionsRevocationError",
|
||||
{
|
||||
excludedSessionId: Schema.String,
|
||||
...serverAuthInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to revoke other sessions.";
|
||||
return `Failed to revoke sessions other than ${this.excludedSessionId}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ServerAuthWebSocketTokenIssueError extends Schema.TaggedErrorClass<ServerAuthWebSocketTokenIssueError>()(
|
||||
"ServerAuthWebSocketTokenIssueError",
|
||||
{
|
||||
sessionId: Schema.String,
|
||||
...serverAuthInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to issue websocket token.";
|
||||
return `Failed to issue websocket token for session ${this.sessionId}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ServerAuthDpopReplayStateRecordError extends Schema.TaggedErrorClass<ServerAuthDpopReplayStateRecordError>()(
|
||||
"ServerAuthDpopReplayStateRecordError",
|
||||
{
|
||||
proofKeyThumbprint: Schema.String,
|
||||
proofId: Schema.String,
|
||||
replayKey: Schema.String,
|
||||
...serverAuthInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to record DPoP proof replay state.";
|
||||
return `Failed to record replay state for DPoP proof ${this.proofId} (${this.proofKeyThumbprint}).`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ServerAuthDpopReplayKeyCalculationError extends Schema.TaggedErrorClass<ServerAuthDpopReplayKeyCalculationError>()(
|
||||
"ServerAuthDpopReplayKeyCalculationError",
|
||||
{
|
||||
proofKeyThumbprint: Schema.String,
|
||||
proofId: Schema.String,
|
||||
...serverAuthInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to calculate DPoP replay key.";
|
||||
return `Failed to calculate replay key for DPoP proof ${this.proofId} (${this.proofKeyThumbprint}).`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -360,11 +377,6 @@ export const ServerAuthCredentialError = Schema.Union([
|
||||
ServerAuthInvalidCredentialError,
|
||||
]);
|
||||
export type ServerAuthCredentialError = typeof ServerAuthCredentialError.Type;
|
||||
export const isServerAuthCredentialError = Schema.is(ServerAuthCredentialError);
|
||||
export const serverAuthCredentialReason = (
|
||||
error: ServerAuthCredentialError,
|
||||
): "missing_credential" | "invalid_credential" =>
|
||||
error._tag === "ServerAuthMissingCredentialError" ? "missing_credential" : "invalid_credential";
|
||||
|
||||
export class ServerAuthInvalidScopeError extends Schema.TaggedErrorClass<ServerAuthInvalidScopeError>()(
|
||||
"ServerAuthInvalidScopeError",
|
||||
@@ -377,10 +389,13 @@ export class ServerAuthInvalidScopeError extends Schema.TaggedErrorClass<ServerA
|
||||
|
||||
export class ServerAuthScopeNotGrantedError extends Schema.TaggedErrorClass<ServerAuthScopeNotGrantedError>()(
|
||||
"ServerAuthScopeNotGrantedError",
|
||||
{},
|
||||
{
|
||||
requestedScopes: Schema.Array(Schema.String),
|
||||
grantedScopes: Schema.Array(Schema.String),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "The requested authentication scope was not granted.";
|
||||
return `Requested scopes [${this.requestedScopes.join(", ")}] exceed granted scopes [${this.grantedScopes.join(", ")}].`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -389,28 +404,35 @@ export const ServerAuthInvalidRequestError = Schema.Union([
|
||||
ServerAuthScopeNotGrantedError,
|
||||
]);
|
||||
export type ServerAuthInvalidRequestError = typeof ServerAuthInvalidRequestError.Type;
|
||||
export const isServerAuthInvalidRequestError = Schema.is(ServerAuthInvalidRequestError);
|
||||
export const serverAuthInvalidRequestReason = (
|
||||
error: ServerAuthInvalidRequestError,
|
||||
): "invalid_scope" | "scope_not_granted" =>
|
||||
error._tag === "ServerAuthInvalidScopeError" ? "invalid_scope" : "scope_not_granted";
|
||||
|
||||
export class ServerAuthForbiddenOperationError extends Schema.TaggedErrorClass<ServerAuthForbiddenOperationError>()(
|
||||
"ServerAuthForbiddenOperationError",
|
||||
{},
|
||||
{
|
||||
currentSessionId: Schema.String,
|
||||
targetSessionId: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "The current authentication session cannot revoke itself.";
|
||||
return `Authentication session ${this.currentSessionId} cannot revoke itself.`;
|
||||
}
|
||||
}
|
||||
|
||||
export type ServerAuthAuthenticationInternalError =
|
||||
| ServerAuthSessionCredentialValidationError
|
||||
| ServerAuthDpopReplayStateRecordError
|
||||
| ServerAuthDpopReplayKeyCalculationError;
|
||||
|
||||
export type ServerAuthAuthenticationError =
|
||||
| ServerAuthCredentialError
|
||||
| ServerAuthAuthenticationInternalError;
|
||||
|
||||
export class EnvironmentAuth extends Context.Service<
|
||||
EnvironmentAuth,
|
||||
{
|
||||
readonly getDescriptor: () => Effect.Effect<ServerAuthDescriptor>;
|
||||
readonly getSessionState: (
|
||||
request: HttpServerRequest.HttpServerRequest,
|
||||
) => Effect.Effect<AuthSessionState, ServerAuthInternalError>;
|
||||
) => Effect.Effect<AuthSessionState, ServerAuthAuthenticationInternalError>;
|
||||
readonly createBrowserSession: (
|
||||
credential: string,
|
||||
requestMetadata: AuthClientMetadata,
|
||||
@@ -419,7 +441,9 @@ export class EnvironmentAuth extends Context.Service<
|
||||
readonly response: AuthBrowserSessionResult;
|
||||
readonly sessionToken: string;
|
||||
},
|
||||
ServerAuthInvalidCredentialError | ServerAuthInternalError
|
||||
| ServerAuthInvalidCredentialError
|
||||
| ServerAuthBootstrapCredentialValidationError
|
||||
| ServerAuthAuthenticatedSessionIssueError
|
||||
>;
|
||||
readonly exchangeBootstrapCredentialForAccessToken: (
|
||||
credential: string,
|
||||
@@ -430,7 +454,10 @@ export class EnvironmentAuth extends Context.Service<
|
||||
},
|
||||
) => Effect.Effect<
|
||||
AuthAccessTokenResult,
|
||||
ServerAuthInvalidCredentialError | ServerAuthInvalidRequestError | ServerAuthInternalError
|
||||
| ServerAuthInvalidCredentialError
|
||||
| ServerAuthScopeNotGrantedError
|
||||
| ServerAuthBootstrapCredentialValidationError
|
||||
| ServerAuthAuthenticatedAccessTokenIssueError
|
||||
>;
|
||||
readonly createPairingLink: (input?: {
|
||||
readonly ttl?: Duration.Duration;
|
||||
@@ -438,56 +465,61 @@ export class EnvironmentAuth extends Context.Service<
|
||||
readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;
|
||||
readonly subject?: string;
|
||||
readonly proofKeyThumbprint?: string;
|
||||
}) => Effect.Effect<IssuedPairingLink, ServerAuthInternalError>;
|
||||
}) => Effect.Effect<IssuedPairingLink, ServerAuthPairingLinkCreationError>;
|
||||
readonly issuePairingCredential: (
|
||||
input?: AuthCreatePairingCredentialInput,
|
||||
) => Effect.Effect<AuthPairingCredentialResult, ServerAuthInternalError>;
|
||||
) => Effect.Effect<AuthPairingCredentialResult, ServerAuthPairingLinkCreationError>;
|
||||
readonly issueStartupPairingCredential: () => Effect.Effect<
|
||||
AuthPairingCredentialResult,
|
||||
ServerAuthInternalError
|
||||
ServerAuthPairingLinkCreationError
|
||||
>;
|
||||
readonly listPairingLinks: (input?: {
|
||||
readonly excludeSubjects?: ReadonlyArray<string>;
|
||||
}) => Effect.Effect<ReadonlyArray<AuthPairingLink>, ServerAuthInternalError>;
|
||||
readonly revokePairingLink: (id: string) => Effect.Effect<boolean, ServerAuthInternalError>;
|
||||
}) => Effect.Effect<ReadonlyArray<AuthPairingLink>, ServerAuthPairingLinksListError>;
|
||||
readonly revokePairingLink: (
|
||||
id: string,
|
||||
) => Effect.Effect<boolean, ServerAuthPairingLinkRevocationError>;
|
||||
readonly issueSession: (input?: {
|
||||
readonly ttl?: Duration.Duration;
|
||||
readonly subject?: string;
|
||||
readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;
|
||||
readonly label?: string;
|
||||
}) => Effect.Effect<IssuedBearerSession, ServerAuthInternalError>;
|
||||
}) => Effect.Effect<IssuedBearerSession, ServerAuthSessionTokenIssueError>;
|
||||
readonly listSessions: () => Effect.Effect<
|
||||
ReadonlyArray<AuthClientSession>,
|
||||
ServerAuthInternalError
|
||||
ServerAuthSessionsListError
|
||||
>;
|
||||
readonly revokeSession: (
|
||||
sessionId: AuthSessionId,
|
||||
) => Effect.Effect<boolean, ServerAuthInternalError>;
|
||||
) => Effect.Effect<boolean, ServerAuthSessionRevocationError>;
|
||||
readonly revokeOtherSessionsExcept: (
|
||||
sessionId: AuthSessionId,
|
||||
) => Effect.Effect<number, ServerAuthInternalError>;
|
||||
) => Effect.Effect<number, ServerAuthOtherSessionsRevocationError>;
|
||||
readonly listClientSessions: (
|
||||
currentSessionId: AuthSessionId,
|
||||
) => Effect.Effect<ReadonlyArray<AuthClientSession>, ServerAuthInternalError>;
|
||||
) => Effect.Effect<ReadonlyArray<AuthClientSession>, ServerAuthSessionsListError>;
|
||||
readonly revokeClientSession: (
|
||||
currentSessionId: AuthSessionId,
|
||||
targetSessionId: AuthSessionId,
|
||||
) => Effect.Effect<boolean, ServerAuthForbiddenOperationError | ServerAuthInternalError>;
|
||||
) => Effect.Effect<
|
||||
boolean,
|
||||
ServerAuthForbiddenOperationError | ServerAuthSessionRevocationError
|
||||
>;
|
||||
readonly revokeOtherClientSessions: (
|
||||
currentSessionId: AuthSessionId,
|
||||
) => Effect.Effect<number, ServerAuthInternalError>;
|
||||
) => Effect.Effect<number, ServerAuthOtherSessionsRevocationError>;
|
||||
readonly authenticateHttpRequest: (
|
||||
request: HttpServerRequest.HttpServerRequest,
|
||||
) => Effect.Effect<AuthenticatedSession, ServerAuthCredentialError | ServerAuthInternalError>;
|
||||
) => Effect.Effect<AuthenticatedSession, ServerAuthAuthenticationError>;
|
||||
readonly authenticateWebSocketUpgrade: (
|
||||
request: HttpServerRequest.HttpServerRequest,
|
||||
) => Effect.Effect<AuthenticatedSession, ServerAuthCredentialError | ServerAuthInternalError>;
|
||||
) => Effect.Effect<AuthenticatedSession, ServerAuthAuthenticationError>;
|
||||
readonly issueWebSocketTicket: (
|
||||
session: Pick<AuthenticatedSession, "sessionId">,
|
||||
) => Effect.Effect<AuthWebSocketTicketResult, ServerAuthInternalError>;
|
||||
) => Effect.Effect<AuthWebSocketTicketResult, ServerAuthWebSocketTokenIssueError>;
|
||||
readonly issueStartupPairingUrl: (
|
||||
baseUrl: string,
|
||||
) => Effect.Effect<string, ServerAuthInternalError>;
|
||||
) => Effect.Effect<string, ServerAuthPairingLinkCreationError>;
|
||||
}
|
||||
>()("t3/auth/EnvironmentAuth") {}
|
||||
|
||||
@@ -514,7 +546,7 @@ const bySessionPriority = (left: AuthClientSession, right: AuthClientSession) =>
|
||||
|
||||
export function toBootstrapExchangeError(
|
||||
cause: PairingGrantStore.BootstrapCredentialError,
|
||||
): ServerAuthInvalidCredentialError | ServerAuthInternalError {
|
||||
): ServerAuthInvalidCredentialError | ServerAuthBootstrapCredentialValidationError {
|
||||
if (PairingGrantStore.isBootstrapCredentialInternalError(cause)) {
|
||||
return new ServerAuthBootstrapCredentialValidationError({ cause });
|
||||
}
|
||||
@@ -526,12 +558,17 @@ export function toBootstrapExchangeError(
|
||||
|
||||
const mapSessionVerificationErrors = <A, R>(
|
||||
effect: Effect.Effect<A, SessionStore.SessionCredentialError, R>,
|
||||
): Effect.Effect<A, ServerAuthInvalidCredentialError | ServerAuthInternalError, R> =>
|
||||
credentialKind: ServerAuthSessionCredentialValidationError["credentialKind"],
|
||||
): Effect.Effect<
|
||||
A,
|
||||
ServerAuthInvalidCredentialError | ServerAuthSessionCredentialValidationError,
|
||||
R
|
||||
> =>
|
||||
effect.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
SessionStore.isSessionCredentialInvalidError(cause)
|
||||
? new ServerAuthInvalidCredentialError({ cause })
|
||||
: new ServerAuthSessionCredentialValidationError({ cause }),
|
||||
: new ServerAuthSessionCredentialValidationError({ credentialKind, cause }),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -565,7 +602,7 @@ export const make = Effect.gen(function* () {
|
||||
token: string,
|
||||
): Effect.Effect<
|
||||
AuthenticatedSession,
|
||||
ServerAuthInvalidCredentialError | ServerAuthInternalError
|
||||
ServerAuthInvalidCredentialError | ServerAuthSessionCredentialValidationError
|
||||
> =>
|
||||
sessions.verify(token).pipe(
|
||||
Effect.tapError((cause) =>
|
||||
@@ -585,12 +622,12 @@ export const make = Effect.gen(function* () {
|
||||
...(session.proofKeyThumbprint ? { proofKeyThumbprint: session.proofKeyThumbprint } : {}),
|
||||
...(session.expiresAt ? { expiresAt: session.expiresAt } : {}),
|
||||
})),
|
||||
mapSessionVerificationErrors,
|
||||
(effect) => mapSessionVerificationErrors(effect, "session"),
|
||||
);
|
||||
|
||||
const authenticateRequest = (
|
||||
request: HttpServerRequest.HttpServerRequest,
|
||||
): Effect.Effect<AuthenticatedSession, ServerAuthCredentialError | ServerAuthInternalError> => {
|
||||
): Effect.Effect<AuthenticatedSession, ServerAuthAuthenticationError> => {
|
||||
const cookieToken = request.cookies[sessions.cookieName];
|
||||
const bearerToken = parseBearerToken(request);
|
||||
const dpopToken = parseDpopToken(request);
|
||||
@@ -642,12 +679,18 @@ export const make = Effect.gen(function* () {
|
||||
...(session.expiresAt ? { expiresAt: DateTime.toUtc(session.expiresAt) } : {}),
|
||||
}) satisfies AuthSessionState,
|
||||
),
|
||||
Effect.catchIf(isServerAuthCredentialError, () =>
|
||||
Effect.succeed({
|
||||
authenticated: false,
|
||||
auth: descriptor,
|
||||
} satisfies AuthSessionState),
|
||||
),
|
||||
Effect.catchTags({
|
||||
ServerAuthMissingCredentialError: () =>
|
||||
Effect.succeed({
|
||||
authenticated: false,
|
||||
auth: descriptor,
|
||||
} satisfies AuthSessionState),
|
||||
ServerAuthInvalidCredentialError: () =>
|
||||
Effect.succeed({
|
||||
authenticated: false,
|
||||
auth: descriptor,
|
||||
} satisfies AuthSessionState),
|
||||
}),
|
||||
Effect.withSpan("EnvironmentAuth.getSessionState"),
|
||||
);
|
||||
|
||||
@@ -669,7 +712,13 @@ export const make = Effect.gen(function* () {
|
||||
},
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError((cause) => new ServerAuthAuthenticatedSessionIssueError({ cause })),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ServerAuthAuthenticatedSessionIssueError({
|
||||
subject: grant.subject,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
Effect.map(
|
||||
@@ -695,7 +744,10 @@ export const make = Effect.gen(function* () {
|
||||
Effect.gen(function* () {
|
||||
const grantedScopes = requestedScopes ?? grant.scopes;
|
||||
if (!grantedScopes.every((scope) => grant.scopes.includes(scope))) {
|
||||
return yield* new ServerAuthScopeNotGrantedError({});
|
||||
return yield* new ServerAuthScopeNotGrantedError({
|
||||
requestedScopes: grantedScopes,
|
||||
grantedScopes: grant.scopes,
|
||||
});
|
||||
}
|
||||
return yield* sessions
|
||||
.issue({
|
||||
@@ -715,7 +767,12 @@ export const make = Effect.gen(function* () {
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new ServerAuthAuthenticatedAccessTokenIssueError({ cause }),
|
||||
(cause) =>
|
||||
new ServerAuthAuthenticatedAccessTokenIssueError({
|
||||
subject: grant.subject,
|
||||
scopes: grantedScopes,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}),
|
||||
@@ -765,28 +822,33 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
const createPairingLink: EnvironmentAuth["Service"]["createPairingLink"] = Effect.fn(
|
||||
"EnvironmentAuth.createPairingLink",
|
||||
)(
|
||||
function* (input) {
|
||||
const createdAt = yield* DateTime.now;
|
||||
const issued = yield* bootstrapCredentials.issueOneTimeToken({
|
||||
scopes: input?.scopes ?? AuthStandardClientScopes,
|
||||
subject: input?.subject ?? "one-time-token",
|
||||
)(function* (input) {
|
||||
const scopes = input?.scopes ?? AuthStandardClientScopes;
|
||||
const subject = input?.subject ?? "one-time-token";
|
||||
const createdAt = yield* DateTime.now;
|
||||
const issued = yield* bootstrapCredentials
|
||||
.issueOneTimeToken({
|
||||
scopes,
|
||||
subject,
|
||||
...(input?.ttl ? { ttl: input.ttl } : {}),
|
||||
...(input?.label ? { label: input.label } : {}),
|
||||
...(input?.proofKeyThumbprint ? { proofKeyThumbprint: input.proofKeyThumbprint } : {}),
|
||||
});
|
||||
return {
|
||||
id: issued.id,
|
||||
credential: issued.credential,
|
||||
scopes: input?.scopes ?? AuthStandardClientScopes,
|
||||
subject: input?.subject ?? "one-time-token",
|
||||
...(issued.label ? { label: issued.label } : {}),
|
||||
createdAt: DateTime.toUtc(createdAt),
|
||||
expiresAt: DateTime.toUtc(issued.expiresAt),
|
||||
} satisfies IssuedPairingLink;
|
||||
},
|
||||
Effect.mapError((cause) => new ServerAuthPairingLinkCreationError({ cause })),
|
||||
);
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new ServerAuthPairingLinkCreationError({ subject, scopes, cause }),
|
||||
),
|
||||
);
|
||||
return {
|
||||
id: issued.id,
|
||||
credential: issued.credential,
|
||||
scopes,
|
||||
subject,
|
||||
...(issued.label ? { label: issued.label } : {}),
|
||||
createdAt: DateTime.toUtc(createdAt),
|
||||
expiresAt: DateTime.toUtc(issued.expiresAt),
|
||||
} satisfies IssuedPairingLink;
|
||||
});
|
||||
|
||||
const listPairingLinks: EnvironmentAuth["Service"]["listPairingLinks"] = (input) =>
|
||||
bootstrapCredentials.listActive().pipe(
|
||||
@@ -806,16 +868,20 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
const revokePairingLink: EnvironmentAuth["Service"]["revokePairingLink"] = (id) =>
|
||||
bootstrapCredentials.revoke(id).pipe(
|
||||
Effect.mapError((cause) => new ServerAuthPairingLinkRevocationError({ cause })),
|
||||
Effect.mapError(
|
||||
(cause) => new ServerAuthPairingLinkRevocationError({ pairingLinkId: id, cause }),
|
||||
),
|
||||
Effect.withSpan("EnvironmentAuth.revokePairingLink"),
|
||||
);
|
||||
|
||||
const issueSession: EnvironmentAuth["Service"]["issueSession"] = (input) =>
|
||||
sessions
|
||||
const issueSession: EnvironmentAuth["Service"]["issueSession"] = (input) => {
|
||||
const subject = input?.subject ?? DEFAULT_SESSION_SUBJECT;
|
||||
const scopes = input?.scopes ?? AuthAdministrativeScopes;
|
||||
return sessions
|
||||
.issue({
|
||||
subject: input?.subject ?? DEFAULT_SESSION_SUBJECT,
|
||||
subject,
|
||||
method: "bearer-access-token",
|
||||
scopes: input?.scopes ?? AuthAdministrativeScopes,
|
||||
scopes,
|
||||
client: {
|
||||
...(input?.label ? { label: input.label } : {}),
|
||||
deviceType: "bot",
|
||||
@@ -830,14 +896,17 @@ export const make = Effect.gen(function* () {
|
||||
token: issued.token,
|
||||
method: "bearer-access-token",
|
||||
scopes: issued.scopes,
|
||||
subject: input?.subject ?? DEFAULT_SESSION_SUBJECT,
|
||||
subject,
|
||||
client: issued.client,
|
||||
expiresAt: DateTime.toUtc(issued.expiresAt),
|
||||
}) satisfies IssuedBearerSession,
|
||||
),
|
||||
Effect.mapError((cause) => new ServerAuthSessionTokenIssueError({ cause })),
|
||||
Effect.mapError(
|
||||
(cause) => new ServerAuthSessionTokenIssueError({ subject, scopes, cause }),
|
||||
),
|
||||
Effect.withSpan("EnvironmentAuth.issueSession"),
|
||||
);
|
||||
};
|
||||
|
||||
const listSessions: EnvironmentAuth["Service"]["listSessions"] = () =>
|
||||
sessions.listActive().pipe(
|
||||
@@ -848,7 +917,7 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
const revokeSession: EnvironmentAuth["Service"]["revokeSession"] = (sessionId) =>
|
||||
sessions.revoke(sessionId).pipe(
|
||||
Effect.mapError((cause) => new ServerAuthSessionRevocationError({ cause })),
|
||||
Effect.mapError((cause) => new ServerAuthSessionRevocationError({ sessionId, cause })),
|
||||
Effect.withSpan("EnvironmentAuth.revokeSession"),
|
||||
);
|
||||
|
||||
@@ -856,7 +925,10 @@ export const make = Effect.gen(function* () {
|
||||
sessionId,
|
||||
) =>
|
||||
sessions.revokeAllExcept(sessionId).pipe(
|
||||
Effect.mapError((cause) => new ServerAuthOtherSessionsRevocationError({ cause })),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ServerAuthOtherSessionsRevocationError({ excludedSessionId: sessionId, cause }),
|
||||
),
|
||||
Effect.withSpan("EnvironmentAuth.revokeOtherSessionsExcept"),
|
||||
);
|
||||
|
||||
@@ -891,7 +963,10 @@ export const make = Effect.gen(function* () {
|
||||
"EnvironmentAuth.revokeClientSession",
|
||||
)(function* (currentSessionId, targetSessionId) {
|
||||
if (currentSessionId === targetSessionId) {
|
||||
return yield* new ServerAuthForbiddenOperationError({});
|
||||
return yield* new ServerAuthForbiddenOperationError({
|
||||
currentSessionId,
|
||||
targetSessionId,
|
||||
});
|
||||
}
|
||||
return yield* revokeSession(targetSessionId);
|
||||
});
|
||||
@@ -917,7 +992,9 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
const issueWebSocketTicket: EnvironmentAuth["Service"]["issueWebSocketTicket"] = (session) =>
|
||||
sessions.issueWebSocketToken(session.sessionId).pipe(
|
||||
Effect.mapError((cause) => new ServerAuthWebSocketTokenIssueError({ cause })),
|
||||
Effect.mapError(
|
||||
(cause) => new ServerAuthWebSocketTokenIssueError({ sessionId: session.sessionId, cause }),
|
||||
),
|
||||
Effect.map(
|
||||
(issued) =>
|
||||
({
|
||||
@@ -947,7 +1024,7 @@ export const make = Effect.gen(function* () {
|
||||
scopes: session.scopes,
|
||||
...(session.expiresAt ? { expiresAt: session.expiresAt } : {}),
|
||||
})),
|
||||
mapSessionVerificationErrors,
|
||||
(effect) => mapSessionVerificationErrors(effect, "websocket-ticket"),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -45,6 +45,31 @@ const makePermissionDeniedSecretStoreLayer = () =>
|
||||
Layer.provideMerge(PermissionDeniedFileSystemLayer),
|
||||
);
|
||||
|
||||
const DirectoryCreateFailureFileSystemLayer = Layer.effect(
|
||||
FileSystem.FileSystem,
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
return {
|
||||
...fileSystem,
|
||||
makeDirectory: (path) =>
|
||||
Effect.fail(
|
||||
PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "makeDirectory",
|
||||
pathOrDescriptor: String(path),
|
||||
}),
|
||||
),
|
||||
} satisfies FileSystem.FileSystem;
|
||||
}),
|
||||
).pipe(Layer.provide(NodeServices.layer));
|
||||
|
||||
const makeDirectoryCreateFailureSecretStoreLayer = (config: ServerConfig.ServerConfig["Service"]) =>
|
||||
ServerSecretStore.layer.pipe(
|
||||
Layer.provide(Layer.succeed(ServerConfig.ServerConfig, config)),
|
||||
Layer.provideMerge(DirectoryCreateFailureFileSystemLayer),
|
||||
);
|
||||
|
||||
const RenameFailureFileSystemLayer = Layer.effect(
|
||||
FileSystem.FileSystem,
|
||||
Effect.gen(function* () {
|
||||
@@ -145,7 +170,56 @@ const makeConcurrentCreateSecretStoreLayer = () =>
|
||||
Layer.provideMerge(ConcurrentReadMissFileSystemLayer),
|
||||
);
|
||||
|
||||
const ConcurrentCreationWithoutReadableSecretFileSystemLayer = Layer.effect(
|
||||
FileSystem.FileSystem,
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
|
||||
return {
|
||||
...fileSystem,
|
||||
readFile: (path) =>
|
||||
Effect.fail(
|
||||
PlatformError.systemError({
|
||||
_tag: "NotFound",
|
||||
module: "FileSystem",
|
||||
method: "readFile",
|
||||
pathOrDescriptor: path,
|
||||
}),
|
||||
),
|
||||
open: (path) =>
|
||||
Effect.fail(
|
||||
PlatformError.systemError({
|
||||
_tag: "AlreadyExists",
|
||||
module: "FileSystem",
|
||||
method: "open",
|
||||
pathOrDescriptor: path,
|
||||
}),
|
||||
),
|
||||
} satisfies FileSystem.FileSystem;
|
||||
}),
|
||||
).pipe(Layer.provide(NodeServices.layer));
|
||||
|
||||
const makeConcurrentCreationWithoutReadableSecretStoreLayer = () =>
|
||||
ServerSecretStore.layer.pipe(
|
||||
Layer.provide(makeServerConfigLayer()),
|
||||
Layer.provideMerge(ConcurrentCreationWithoutReadableSecretFileSystemLayer),
|
||||
);
|
||||
|
||||
it.layer(NodeServices.layer)("ServerSecretStore.layer", (it) => {
|
||||
it.effect("preserves directory context when secret-store initialization fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const config = yield* ServerConfig.ServerConfig.pipe(Effect.provide(makeServerConfigLayer()));
|
||||
const error = yield* Layer.build(makeDirectoryCreateFailureSecretStoreLayer(config)).pipe(
|
||||
Effect.scoped,
|
||||
Effect.flip,
|
||||
);
|
||||
|
||||
assert.instanceOf(error, ServerSecretStore.SecretStoreDirectoryCreateError);
|
||||
assert.match(error.directoryPath, /secrets$/u);
|
||||
assert.instanceOf(error.cause, PlatformError.PlatformError);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns Option.none when a secret file does not exist", () =>
|
||||
Effect.gen(function* () {
|
||||
const secretStore = yield* ServerSecretStore.ServerSecretStore;
|
||||
@@ -186,6 +260,25 @@ it.layer(NodeServices.layer)("ServerSecretStore.layer", (it) => {
|
||||
}).pipe(Effect.provide(makeConcurrentCreateSecretStoreLayer())),
|
||||
);
|
||||
|
||||
it.effect("preserves the persist failure when a concurrent secret remains unreadable", () =>
|
||||
Effect.gen(function* () {
|
||||
const secretStore = yield* ServerSecretStore.ServerSecretStore;
|
||||
|
||||
const error = yield* Effect.flip(secretStore.getOrCreateRandom("session-signing-key", 32));
|
||||
|
||||
assert.instanceOf(error, ServerSecretStore.SecretStoreConcurrentReadError);
|
||||
assert.equal(error.secretName, "session-signing-key");
|
||||
assert.equal(
|
||||
error.message,
|
||||
"Failed to read secret session-signing-key after concurrent creation.",
|
||||
);
|
||||
assert.instanceOf(error.cause, ServerSecretStore.SecretStorePersistError);
|
||||
assert.equal(error.cause.operation, "create");
|
||||
assert.instanceOf(error.cause.cause, PlatformError.PlatformError);
|
||||
assert.equal(error.cause.cause.reason._tag, "AlreadyExists");
|
||||
}).pipe(Effect.provide(makeConcurrentCreationWithoutReadableSecretStoreLayer())),
|
||||
);
|
||||
|
||||
it.effect("uses restrictive permissions for the secret directory and files", () =>
|
||||
Effect.gen(function* () {
|
||||
const chmodCalls: Array<{ readonly path: string; readonly mode: number }> = [];
|
||||
@@ -232,7 +325,8 @@ it.layer(NodeServices.layer)("ServerSecretStore.layer", (it) => {
|
||||
const error = yield* Effect.flip(secretStore.getOrCreateRandom("session-signing-key", 32));
|
||||
|
||||
assert.instanceOf(error, ServerSecretStore.SecretStoreReadError);
|
||||
assert.include(error.message, "Failed to read secret session-signing-key.");
|
||||
assert.equal(error.secretName, "session-signing-key");
|
||||
assert.match(error.secretPath, /session-signing-key\.bin$/u);
|
||||
assert.instanceOf(error.cause, PlatformError.PlatformError);
|
||||
assert.equal((error.cause as PlatformError.PlatformError).reason._tag, "PermissionDenied");
|
||||
}).pipe(Effect.provide(makePermissionDeniedSecretStoreLayer())),
|
||||
@@ -247,7 +341,9 @@ it.layer(NodeServices.layer)("ServerSecretStore.layer", (it) => {
|
||||
);
|
||||
|
||||
assert.instanceOf(error, ServerSecretStore.SecretStorePersistError);
|
||||
assert.include(error.message, "Failed to persist secret session-signing-key.");
|
||||
assert.equal(error.operation, "set");
|
||||
assert.equal(error.secretName, "session-signing-key");
|
||||
assert.match(error.secretPath, /session-signing-key\.bin$/u);
|
||||
assert.instanceOf(error.cause, PlatformError.PlatformError);
|
||||
assert.equal((error.cause as PlatformError.PlatformError).reason._tag, "PermissionDenied");
|
||||
}).pipe(Effect.provide(makeRenameFailureSecretStoreLayer())),
|
||||
@@ -260,7 +356,8 @@ it.layer(NodeServices.layer)("ServerSecretStore.layer", (it) => {
|
||||
const error = yield* Effect.flip(secretStore.remove("session-signing-key"));
|
||||
|
||||
assert.instanceOf(error, ServerSecretStore.SecretStoreRemoveError);
|
||||
assert.include(error.message, "Failed to remove secret session-signing-key.");
|
||||
assert.equal(error.secretName, "session-signing-key");
|
||||
assert.match(error.secretPath, /session-signing-key\.bin$/u);
|
||||
assert.instanceOf(error.cause, PlatformError.PlatformError);
|
||||
assert.equal((error.cause as PlatformError.PlatformError).reason._tag, "PermissionDenied");
|
||||
}).pipe(Effect.provide(makeRemoveFailureSecretStoreLayer())),
|
||||
|
||||
@@ -11,114 +11,137 @@ import * as Schema from "effect/Schema";
|
||||
|
||||
import * as ServerConfig from "../config.ts";
|
||||
|
||||
const secretStoreErrorContext = {
|
||||
resource: Schema.String,
|
||||
const storedSecretErrorContext = {
|
||||
secretName: Schema.String,
|
||||
secretPath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
};
|
||||
|
||||
export class SecretStoreSecureError extends Schema.TaggedErrorClass<SecretStoreSecureError>()(
|
||||
"SecretStoreSecureError",
|
||||
export class SecretStoreDirectoryCreateError extends Schema.TaggedErrorClass<SecretStoreDirectoryCreateError>()(
|
||||
"SecretStoreDirectoryCreateError",
|
||||
{
|
||||
...secretStoreErrorContext,
|
||||
directoryPath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to secure ${this.resource}.`;
|
||||
return `Failed to create secret store directory ${this.directoryPath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class SecretStoreDirectorySecureError extends Schema.TaggedErrorClass<SecretStoreDirectorySecureError>()(
|
||||
"SecretStoreDirectorySecureError",
|
||||
{
|
||||
directoryPath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to secure secret store directory ${this.directoryPath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class SecretStoreReadError extends Schema.TaggedErrorClass<SecretStoreReadError>()(
|
||||
"SecretStoreReadError",
|
||||
{
|
||||
...secretStoreErrorContext,
|
||||
...storedSecretErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to read ${this.resource}.`;
|
||||
return `Failed to read secret ${this.secretName} at ${this.secretPath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class SecretStoreTemporaryPathError extends Schema.TaggedErrorClass<SecretStoreTemporaryPathError>()(
|
||||
"SecretStoreTemporaryPathError",
|
||||
export class SecretStoreTemporaryPathGenerationError extends Schema.TaggedErrorClass<SecretStoreTemporaryPathGenerationError>()(
|
||||
"SecretStoreTemporaryPathGenerationError",
|
||||
{
|
||||
...secretStoreErrorContext,
|
||||
secretName: Schema.String,
|
||||
secretPath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to create temporary path for ${this.resource}.`;
|
||||
return `Failed to generate a temporary path for secret ${this.secretName} at ${this.secretPath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class SecretStorePersistError extends Schema.TaggedErrorClass<SecretStorePersistError>()(
|
||||
"SecretStorePersistError",
|
||||
{
|
||||
...secretStoreErrorContext,
|
||||
operation: Schema.Literals(["create", "set"]),
|
||||
...storedSecretErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to persist ${this.resource}.`;
|
||||
return `Failed to ${this.operation} secret ${this.secretName} at ${this.secretPath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class SecretStoreRandomGenerationError extends Schema.TaggedErrorClass<SecretStoreRandomGenerationError>()(
|
||||
"SecretStoreRandomGenerationError",
|
||||
{
|
||||
...secretStoreErrorContext,
|
||||
secretName: Schema.String,
|
||||
byteCount: Schema.Number,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to generate random bytes for ${this.resource}.`;
|
||||
return `Failed to generate ${this.byteCount} random bytes for secret ${this.secretName}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class SecretStoreConcurrentReadError extends Schema.TaggedErrorClass<SecretStoreConcurrentReadError>()(
|
||||
"SecretStoreConcurrentReadError",
|
||||
{
|
||||
resource: Schema.String,
|
||||
secretName: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to read ${this.resource} after concurrent creation.`;
|
||||
return `Failed to read secret ${this.secretName} after concurrent creation.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class SecretStoreRemoveError extends Schema.TaggedErrorClass<SecretStoreRemoveError>()(
|
||||
"SecretStoreRemoveError",
|
||||
{
|
||||
...secretStoreErrorContext,
|
||||
...storedSecretErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to remove ${this.resource}.`;
|
||||
return `Failed to remove secret ${this.secretName} at ${this.secretPath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class SecretStoreDecodeError extends Schema.TaggedErrorClass<SecretStoreDecodeError>()(
|
||||
"SecretStoreDecodeError",
|
||||
{
|
||||
...secretStoreErrorContext,
|
||||
secretName: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to decode ${this.resource}.`;
|
||||
return `Failed to decode secret ${this.secretName}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class SecretStoreEncodeError extends Schema.TaggedErrorClass<SecretStoreEncodeError>()(
|
||||
"SecretStoreEncodeError",
|
||||
{
|
||||
...secretStoreErrorContext,
|
||||
secretName: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to encode ${this.resource}.`;
|
||||
return `Failed to encode secret ${this.secretName}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export const SecretStoreError = Schema.Union([
|
||||
SecretStoreSecureError,
|
||||
SecretStoreDirectoryCreateError,
|
||||
SecretStoreDirectorySecureError,
|
||||
SecretStoreReadError,
|
||||
SecretStoreTemporaryPathError,
|
||||
SecretStoreTemporaryPathGenerationError,
|
||||
SecretStorePersistError,
|
||||
SecretStoreRandomGenerationError,
|
||||
SecretStoreConcurrentReadError,
|
||||
@@ -138,14 +161,26 @@ export const isSecretAlreadyExistsError = (error: SecretStoreError): boolean =>
|
||||
export class ServerSecretStore extends Context.Service<
|
||||
ServerSecretStore,
|
||||
{
|
||||
readonly get: (name: string) => Effect.Effect<Option.Option<Uint8Array>, SecretStoreError>;
|
||||
readonly set: (name: string, value: Uint8Array) => Effect.Effect<void, SecretStoreError>;
|
||||
readonly create: (name: string, value: Uint8Array) => Effect.Effect<void, SecretStoreError>;
|
||||
readonly get: (name: string) => Effect.Effect<Option.Option<Uint8Array>, SecretStoreReadError>;
|
||||
readonly set: (
|
||||
name: string,
|
||||
value: Uint8Array,
|
||||
) => Effect.Effect<void, SecretStoreTemporaryPathGenerationError | SecretStorePersistError>;
|
||||
readonly create: (
|
||||
name: string,
|
||||
value: Uint8Array,
|
||||
) => Effect.Effect<void, SecretStorePersistError>;
|
||||
readonly getOrCreateRandom: (
|
||||
name: string,
|
||||
bytes: number,
|
||||
) => Effect.Effect<Uint8Array, SecretStoreError>;
|
||||
readonly remove: (name: string) => Effect.Effect<void, SecretStoreError>;
|
||||
) => Effect.Effect<
|
||||
Uint8Array,
|
||||
| SecretStoreReadError
|
||||
| SecretStoreRandomGenerationError
|
||||
| SecretStorePersistError
|
||||
| SecretStoreConcurrentReadError
|
||||
>;
|
||||
readonly remove: (name: string) => Effect.Effect<void, SecretStoreRemoveError>;
|
||||
}
|
||||
>()("t3/auth/ServerSecretStore") {}
|
||||
|
||||
@@ -155,12 +190,20 @@ export const make = Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
const serverConfig = yield* ServerConfig.ServerConfig;
|
||||
|
||||
yield* fileSystem.makeDirectory(serverConfig.secretsDir, { recursive: true });
|
||||
yield* fileSystem.makeDirectory(serverConfig.secretsDir, { recursive: true }).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new SecretStoreDirectoryCreateError({
|
||||
directoryPath: serverConfig.secretsDir,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* fileSystem.chmod(serverConfig.secretsDir, 0o700).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new SecretStoreSecureError({
|
||||
resource: `secrets directory ${serverConfig.secretsDir}`,
|
||||
new SecretStoreDirectorySecureError({
|
||||
directoryPath: serverConfig.secretsDir,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
@@ -168,29 +211,33 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
const resolveSecretPath = (name: string) => path.join(serverConfig.secretsDir, `${name}.bin`);
|
||||
|
||||
const get: ServerSecretStore["Service"]["get"] = (name) =>
|
||||
fileSystem.readFile(resolveSecretPath(name)).pipe(
|
||||
const get: ServerSecretStore["Service"]["get"] = (name) => {
|
||||
const secretPath = resolveSecretPath(name);
|
||||
return fileSystem.readFile(secretPath).pipe(
|
||||
Effect.map((bytes) => Option.some(Uint8Array.from(bytes))),
|
||||
Effect.catch((cause) =>
|
||||
cause.reason._tag === "NotFound"
|
||||
? Effect.succeed(Option.none())
|
||||
: Effect.fail(
|
||||
new SecretStoreReadError({
|
||||
resource: `secret ${name}`,
|
||||
secretName: name,
|
||||
secretPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
Effect.withSpan("ServerSecretStore.get"),
|
||||
);
|
||||
};
|
||||
|
||||
const set: ServerSecretStore["Service"]["set"] = (name, value) => {
|
||||
const secretPath = resolveSecretPath(name);
|
||||
return crypto.randomUUIDv4.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new SecretStoreTemporaryPathError({
|
||||
resource: `secret ${name}`,
|
||||
new SecretStoreTemporaryPathGenerationError({
|
||||
secretName: name,
|
||||
secretPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
@@ -208,7 +255,9 @@ export const make = Effect.gen(function* () {
|
||||
Effect.flatMap(() =>
|
||||
Effect.fail(
|
||||
new SecretStorePersistError({
|
||||
resource: `secret ${name}`,
|
||||
operation: "set",
|
||||
secretName: name,
|
||||
secretPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
@@ -237,7 +286,9 @@ export const make = Effect.gen(function* () {
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new SecretStorePersistError({
|
||||
resource: `secret ${name}`,
|
||||
operation: "create",
|
||||
secretName: name,
|
||||
secretPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
@@ -254,30 +305,33 @@ export const make = Effect.gen(function* () {
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new SecretStoreRandomGenerationError({
|
||||
resource: `secret ${name}`,
|
||||
secretName: name,
|
||||
byteCount: bytes,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.flatMap((generated) =>
|
||||
create(name, generated).pipe(
|
||||
Effect.as(Uint8Array.from(generated)),
|
||||
Effect.catchIf(isSecretStoreError, (error) =>
|
||||
isSecretAlreadyExistsError(error)
|
||||
? get(name).pipe(
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onSome: Effect.succeed,
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
new SecretStoreConcurrentReadError({
|
||||
resource: `secret ${name}`,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
),
|
||||
)
|
||||
: Effect.fail(error),
|
||||
),
|
||||
Effect.catchTags({
|
||||
SecretStorePersistError: (error) =>
|
||||
isSecretAlreadyExistsError(error)
|
||||
? get(name).pipe(
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onSome: Effect.succeed,
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
new SecretStoreConcurrentReadError({
|
||||
secretName: name,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
),
|
||||
)
|
||||
: Effect.fail(error),
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
@@ -286,20 +340,23 @@ export const make = Effect.gen(function* () {
|
||||
Effect.withSpan("ServerSecretStore.getOrCreateRandom"),
|
||||
);
|
||||
|
||||
const remove: ServerSecretStore["Service"]["remove"] = (name) =>
|
||||
fileSystem.remove(resolveSecretPath(name)).pipe(
|
||||
const remove: ServerSecretStore["Service"]["remove"] = (name) => {
|
||||
const secretPath = resolveSecretPath(name);
|
||||
return fileSystem.remove(secretPath).pipe(
|
||||
Effect.catch((cause) =>
|
||||
cause.reason._tag === "NotFound"
|
||||
? Effect.void
|
||||
: Effect.fail(
|
||||
new SecretStoreRemoveError({
|
||||
resource: `secret ${name}`,
|
||||
secretName: name,
|
||||
secretPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
Effect.withSpan("ServerSecretStore.remove"),
|
||||
);
|
||||
};
|
||||
|
||||
return ServerSecretStore.of({
|
||||
get,
|
||||
|
||||
@@ -44,8 +44,8 @@ const failingSessionLookupRepositoryLayer = Layer.succeed(AuthSessions.AuthSessi
|
||||
create: () => Effect.void,
|
||||
getById: () => Effect.fail(repositoryFailure),
|
||||
listActive: () => Effect.succeed([]),
|
||||
revoke: () => Effect.fail(repositoryFailure),
|
||||
revokeAllExcept: () => Effect.fail(repositoryFailure),
|
||||
revoke: () => Effect.succeed(false),
|
||||
revokeAllExcept: () => Effect.succeed([]),
|
||||
setLastConnectedAt: () => Effect.void,
|
||||
});
|
||||
|
||||
@@ -104,29 +104,11 @@ it.layer(NodeServices.layer)("SessionStore.layer", (it) => {
|
||||
|
||||
const sessionError = yield* Effect.flip(sessions.verify(issued.token));
|
||||
const websocketError = yield* Effect.flip(sessions.verifyWebSocketToken(websocket.token));
|
||||
const revokeError = yield* Effect.flip(sessions.revoke(issued.sessionId));
|
||||
const revokeOthersError = yield* Effect.flip(sessions.revokeAllExcept(issued.sessionId));
|
||||
|
||||
expect(sessionError._tag).toBe("SessionCredentialVerificationError");
|
||||
expect(websocketError._tag).toBe("WebSocketTokenVerificationError");
|
||||
expect(sessionError.cause).toBe(repositoryFailure);
|
||||
expect(websocketError.cause).toBe(repositoryFailure);
|
||||
if (sessionError._tag === "SessionCredentialVerificationError") {
|
||||
expect(sessionError.sessionId).toBe(issued.sessionId);
|
||||
}
|
||||
if (websocketError._tag === "WebSocketTokenVerificationError") {
|
||||
expect(websocketError.sessionId).toBe(issued.sessionId);
|
||||
}
|
||||
expect(revokeError).toMatchObject({
|
||||
_tag: "SessionRevocationError",
|
||||
sessionId: issued.sessionId,
|
||||
cause: repositoryFailure,
|
||||
});
|
||||
expect(revokeOthersError).toMatchObject({
|
||||
_tag: "OtherSessionsRevocationError",
|
||||
currentSessionId: issued.sessionId,
|
||||
cause: repositoryFailure,
|
||||
});
|
||||
}).pipe(Effect.provide(failingSessionLookupCredentialLayer)),
|
||||
);
|
||||
it.effect("verifies session tokens against the Effect clock", () =>
|
||||
@@ -163,52 +145,7 @@ it.layer(NodeServices.layer)("SessionStore.layer", (it) => {
|
||||
yield* TestClock.adjust(Duration.seconds(2));
|
||||
|
||||
const error = yield* Effect.flip(sessions.verifyWebSocketToken(websocket.token));
|
||||
expect(error._tag).toBe("WebSocketSessionExpiredError");
|
||||
if (error._tag === "WebSocketSessionExpiredError") {
|
||||
expect(error.sessionId).toBe(issued.sessionId);
|
||||
expect(error.expiresAt.epochMilliseconds).toBe(issued.expiresAt.epochMilliseconds);
|
||||
expect(error.observedAt.epochMilliseconds).toBeGreaterThan(
|
||||
error.expiresAt.epochMilliseconds,
|
||||
);
|
||||
}
|
||||
}).pipe(Effect.provide(Layer.merge(makeSessionStoreLayer(), TestClock.layer()))),
|
||||
);
|
||||
|
||||
it.effect("includes expiry context when session and websocket tokens expire", () =>
|
||||
Effect.gen(function* () {
|
||||
const sessions = yield* SessionStore.SessionStore;
|
||||
const issued = yield* sessions.issue({
|
||||
method: "bearer-access-token",
|
||||
subject: "short-lived-token",
|
||||
ttl: Duration.seconds(1),
|
||||
});
|
||||
const websocket = yield* sessions.issueWebSocketToken(issued.sessionId, {
|
||||
ttl: Duration.seconds(1),
|
||||
});
|
||||
|
||||
yield* TestClock.adjust(Duration.seconds(2));
|
||||
|
||||
const sessionError = yield* Effect.flip(sessions.verify(issued.token));
|
||||
const websocketError = yield* Effect.flip(sessions.verifyWebSocketToken(websocket.token));
|
||||
|
||||
expect(sessionError._tag).toBe("SessionTokenExpiredError");
|
||||
if (sessionError._tag === "SessionTokenExpiredError") {
|
||||
expect(sessionError.sessionId).toBe(issued.sessionId);
|
||||
expect(sessionError.expiresAt.epochMilliseconds).toBe(issued.expiresAt.epochMilliseconds);
|
||||
expect(sessionError.observedAt.epochMilliseconds).toBeGreaterThan(
|
||||
sessionError.expiresAt.epochMilliseconds,
|
||||
);
|
||||
}
|
||||
expect(websocketError._tag).toBe("WebSocketTokenExpiredError");
|
||||
if (websocketError._tag === "WebSocketTokenExpiredError") {
|
||||
expect(websocketError.sessionId).toBe(issued.sessionId);
|
||||
expect(websocketError.expiresAt.epochMilliseconds).toBe(
|
||||
websocket.expiresAt.epochMilliseconds,
|
||||
);
|
||||
expect(websocketError.observedAt.epochMilliseconds).toBeGreaterThan(
|
||||
websocketError.expiresAt.epochMilliseconds,
|
||||
);
|
||||
}
|
||||
expect(error.message).toContain("expired");
|
||||
}).pipe(Effect.provide(Layer.merge(makeSessionStoreLayer(), TestClock.layer()))),
|
||||
);
|
||||
|
||||
@@ -236,16 +173,12 @@ it.layer(NodeServices.layer)("SessionStore.layer", (it) => {
|
||||
ipAddress: "192.168.1.88",
|
||||
},
|
||||
});
|
||||
const clientWebSocket = yield* sessions.issueWebSocketToken(client.sessionId);
|
||||
|
||||
yield* sessions.markConnected(client.sessionId);
|
||||
const beforeRevoke = yield* sessions.listActive();
|
||||
const revokedCount = yield* sessions.revokeAllExcept(administrative.sessionId);
|
||||
const afterRevoke = yield* sessions.listActive();
|
||||
const revokedClient = yield* Effect.flip(sessions.verify(client.token));
|
||||
const revokedClientWebSocket = yield* Effect.flip(
|
||||
sessions.verifyWebSocketToken(clientWebSocket.token),
|
||||
);
|
||||
|
||||
expect(beforeRevoke).toHaveLength(2);
|
||||
expect(beforeRevoke.find((entry) => entry.sessionId === client.sessionId)?.connected).toBe(
|
||||
@@ -261,16 +194,7 @@ it.layer(NodeServices.layer)("SessionStore.layer", (it) => {
|
||||
expect(revokedCount).toBe(1);
|
||||
expect(afterRevoke).toHaveLength(1);
|
||||
expect(afterRevoke[0]?.sessionId).toBe(administrative.sessionId);
|
||||
expect(revokedClient._tag).toBe("SessionTokenRevokedError");
|
||||
if (revokedClient._tag === "SessionTokenRevokedError") {
|
||||
expect(revokedClient.sessionId).toBe(client.sessionId);
|
||||
expect(revokedClient.revokedAt.epochMilliseconds).toBeGreaterThanOrEqual(0);
|
||||
}
|
||||
expect(revokedClientWebSocket._tag).toBe("WebSocketSessionRevokedError");
|
||||
if (revokedClientWebSocket._tag === "WebSocketSessionRevokedError") {
|
||||
expect(revokedClientWebSocket.sessionId).toBe(client.sessionId);
|
||||
expect(revokedClientWebSocket.revokedAt.epochMilliseconds).toBeGreaterThanOrEqual(0);
|
||||
}
|
||||
expect(revokedClient.message).toContain("revoked");
|
||||
}).pipe(Effect.provide(makeSessionStoreLayer())),
|
||||
);
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
type AuthEnvironmentScope,
|
||||
type ServerAuthSessionMethod,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Clock from "effect/Clock";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
@@ -92,11 +93,7 @@ export class InvalidSessionTokenPayloadError extends Schema.TaggedErrorClass<Inv
|
||||
|
||||
export class SessionTokenExpiredError extends Schema.TaggedErrorClass<SessionTokenExpiredError>()(
|
||||
"SessionTokenExpiredError",
|
||||
{
|
||||
sessionId: AuthSessionId,
|
||||
expiresAt: Schema.DateTimeUtc,
|
||||
observedAt: Schema.DateTimeUtc,
|
||||
},
|
||||
{},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Session token expired.";
|
||||
@@ -105,9 +102,7 @@ export class SessionTokenExpiredError extends Schema.TaggedErrorClass<SessionTok
|
||||
|
||||
export class UnknownSessionTokenError extends Schema.TaggedErrorClass<UnknownSessionTokenError>()(
|
||||
"UnknownSessionTokenError",
|
||||
{
|
||||
sessionId: AuthSessionId,
|
||||
},
|
||||
{},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Unknown session token.";
|
||||
@@ -116,10 +111,7 @@ export class UnknownSessionTokenError extends Schema.TaggedErrorClass<UnknownSes
|
||||
|
||||
export class SessionTokenRevokedError extends Schema.TaggedErrorClass<SessionTokenRevokedError>()(
|
||||
"SessionTokenRevokedError",
|
||||
{
|
||||
sessionId: AuthSessionId,
|
||||
revokedAt: Schema.DateTimeUtc,
|
||||
},
|
||||
{},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Session token revoked.";
|
||||
@@ -128,10 +120,7 @@ export class SessionTokenRevokedError extends Schema.TaggedErrorClass<SessionTok
|
||||
|
||||
export class InvalidSessionExpirationClaimError extends Schema.TaggedErrorClass<InvalidSessionExpirationClaimError>()(
|
||||
"InvalidSessionExpirationClaimError",
|
||||
{
|
||||
sessionId: AuthSessionId,
|
||||
expirationClaim: Schema.Number,
|
||||
},
|
||||
{},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Invalid `exp` claim";
|
||||
@@ -169,11 +158,7 @@ export class InvalidWebSocketTokenPayloadError extends Schema.TaggedErrorClass<I
|
||||
|
||||
export class WebSocketTokenExpiredError extends Schema.TaggedErrorClass<WebSocketTokenExpiredError>()(
|
||||
"WebSocketTokenExpiredError",
|
||||
{
|
||||
sessionId: AuthSessionId,
|
||||
expiresAt: Schema.DateTimeUtc,
|
||||
observedAt: Schema.DateTimeUtc,
|
||||
},
|
||||
{},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Websocket token expired.";
|
||||
@@ -182,9 +167,7 @@ export class WebSocketTokenExpiredError extends Schema.TaggedErrorClass<WebSocke
|
||||
|
||||
export class UnknownWebSocketSessionError extends Schema.TaggedErrorClass<UnknownWebSocketSessionError>()(
|
||||
"UnknownWebSocketSessionError",
|
||||
{
|
||||
sessionId: AuthSessionId,
|
||||
},
|
||||
{},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Unknown websocket session.";
|
||||
@@ -193,11 +176,7 @@ export class UnknownWebSocketSessionError extends Schema.TaggedErrorClass<Unknow
|
||||
|
||||
export class WebSocketSessionExpiredError extends Schema.TaggedErrorClass<WebSocketSessionExpiredError>()(
|
||||
"WebSocketSessionExpiredError",
|
||||
{
|
||||
sessionId: AuthSessionId,
|
||||
expiresAt: Schema.DateTimeUtc,
|
||||
observedAt: Schema.DateTimeUtc,
|
||||
},
|
||||
{},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Websocket session expired.";
|
||||
@@ -206,10 +185,7 @@ export class WebSocketSessionExpiredError extends Schema.TaggedErrorClass<WebSoc
|
||||
|
||||
export class WebSocketSessionRevokedError extends Schema.TaggedErrorClass<WebSocketSessionRevokedError>()(
|
||||
"WebSocketSessionRevokedError",
|
||||
{
|
||||
sessionId: AuthSessionId,
|
||||
revokedAt: Schema.DateTimeUtc,
|
||||
},
|
||||
{},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Websocket session revoked.";
|
||||
@@ -242,7 +218,6 @@ const sessionCredentialInternalErrorContext = {
|
||||
export class SessionClaimsEncodingError extends Schema.TaggedErrorClass<SessionClaimsEncodingError>()(
|
||||
"SessionClaimsEncodingError",
|
||||
{
|
||||
sessionId: AuthSessionId,
|
||||
operation: Schema.Literals(["encode_session_claims", "encode_websocket_claims"]),
|
||||
...sessionCredentialInternalErrorContext,
|
||||
},
|
||||
@@ -255,7 +230,6 @@ export class SessionClaimsEncodingError extends Schema.TaggedErrorClass<SessionC
|
||||
export class SessionCredentialIssueError extends Schema.TaggedErrorClass<SessionCredentialIssueError>()(
|
||||
"SessionCredentialIssueError",
|
||||
{
|
||||
sessionId: Schema.optional(AuthSessionId),
|
||||
...sessionCredentialInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
@@ -267,7 +241,6 @@ export class SessionCredentialIssueError extends Schema.TaggedErrorClass<Session
|
||||
export class SessionCredentialVerificationError extends Schema.TaggedErrorClass<SessionCredentialVerificationError>()(
|
||||
"SessionCredentialVerificationError",
|
||||
{
|
||||
sessionId: AuthSessionId,
|
||||
...sessionCredentialInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
@@ -279,7 +252,6 @@ export class SessionCredentialVerificationError extends Schema.TaggedErrorClass<
|
||||
export class WebSocketTokenIssueError extends Schema.TaggedErrorClass<WebSocketTokenIssueError>()(
|
||||
"WebSocketTokenIssueError",
|
||||
{
|
||||
sessionId: AuthSessionId,
|
||||
...sessionCredentialInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
@@ -291,7 +263,6 @@ export class WebSocketTokenIssueError extends Schema.TaggedErrorClass<WebSocketT
|
||||
export class WebSocketTokenVerificationError extends Schema.TaggedErrorClass<WebSocketTokenVerificationError>()(
|
||||
"WebSocketTokenVerificationError",
|
||||
{
|
||||
sessionId: AuthSessionId,
|
||||
...sessionCredentialInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
@@ -314,7 +285,6 @@ export class ActiveSessionsListError extends Schema.TaggedErrorClass<ActiveSessi
|
||||
export class SessionRevocationError extends Schema.TaggedErrorClass<SessionRevocationError>()(
|
||||
"SessionRevocationError",
|
||||
{
|
||||
sessionId: AuthSessionId,
|
||||
...sessionCredentialInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
@@ -326,7 +296,6 @@ export class SessionRevocationError extends Schema.TaggedErrorClass<SessionRevoc
|
||||
export class OtherSessionsRevocationError extends Schema.TaggedErrorClass<OtherSessionsRevocationError>()(
|
||||
"OtherSessionsRevocationError",
|
||||
{
|
||||
currentSessionId: AuthSessionId,
|
||||
...sessionCredentialInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
@@ -570,11 +539,7 @@ export const make = Effect.gen(function* () {
|
||||
const encodeClaims = Schema.encodeEffect(Schema.fromJsonString(SessionClaims));
|
||||
const issue: SessionStore["Service"]["issue"] = Effect.fn("SessionStore.issue")(
|
||||
function* (input) {
|
||||
const sessionId = AuthSessionId.make(
|
||||
yield* crypto.randomUUIDv4.pipe(
|
||||
Effect.mapError((cause) => new SessionCredentialIssueError({ cause })),
|
||||
),
|
||||
);
|
||||
const sessionId = AuthSessionId.make(yield* crypto.randomUUIDv4);
|
||||
const issuedAt = yield* DateTime.now;
|
||||
const expiresAt = DateTime.add(issuedAt, {
|
||||
milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_SESSION_TTL),
|
||||
@@ -594,37 +559,27 @@ export const make = Effect.gen(function* () {
|
||||
const encodedPayload = yield* encodeClaims(claims).pipe(
|
||||
Effect.map(base64UrlEncode),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new SessionCredentialIssueError({
|
||||
sessionId,
|
||||
cause: new SessionClaimsEncodingError({
|
||||
sessionId,
|
||||
operation: "encode_session_claims",
|
||||
cause,
|
||||
}),
|
||||
}),
|
||||
(cause) => new SessionClaimsEncodingError({ operation: "encode_session_claims", cause }),
|
||||
),
|
||||
);
|
||||
const signature = signPayload(encodedPayload, signingSecret);
|
||||
const client = input?.client ?? createDefaultClientMetadata();
|
||||
yield* authSessions
|
||||
.create({
|
||||
sessionId,
|
||||
subject: claims.sub,
|
||||
scopes: claims.scopes,
|
||||
method: claims.method,
|
||||
client: {
|
||||
label: client.label ?? null,
|
||||
ipAddress: client.ipAddress ?? null,
|
||||
userAgent: client.userAgent ?? null,
|
||||
deviceType: client.deviceType,
|
||||
os: client.os ?? null,
|
||||
browser: client.browser ?? null,
|
||||
},
|
||||
issuedAt,
|
||||
expiresAt,
|
||||
})
|
||||
.pipe(Effect.mapError((cause) => new SessionCredentialIssueError({ sessionId, cause })));
|
||||
yield* authSessions.create({
|
||||
sessionId,
|
||||
subject: claims.sub,
|
||||
scopes: claims.scopes,
|
||||
method: claims.method,
|
||||
client: {
|
||||
label: client.label ?? null,
|
||||
ipAddress: client.ipAddress ?? null,
|
||||
userAgent: client.userAgent ?? null,
|
||||
deviceType: client.deviceType,
|
||||
os: client.os ?? null,
|
||||
browser: client.browser ?? null,
|
||||
},
|
||||
issuedAt,
|
||||
expiresAt,
|
||||
});
|
||||
yield* emitUpsert(
|
||||
toAuthClientSession({
|
||||
sessionId,
|
||||
@@ -649,6 +604,7 @@ export const make = Effect.gen(function* () {
|
||||
...(claims.jkt ? { proofKeyThumbprint: claims.jkt } : {}),
|
||||
} satisfies IssuedSession;
|
||||
},
|
||||
Effect.mapError((cause) => new SessionCredentialIssueError({ cause })),
|
||||
);
|
||||
|
||||
const verify: SessionStore["Service"]["verify"] = Effect.fn("SessionStore.verify")(
|
||||
@@ -667,37 +623,22 @@ export const make = Effect.gen(function* () {
|
||||
Effect.mapError((cause) => new InvalidSessionTokenPayloadError({ cause })),
|
||||
);
|
||||
|
||||
const observedAt = yield* DateTime.now;
|
||||
const expiresAt = DateTime.make(claims.exp);
|
||||
if (Option.isNone(expiresAt)) {
|
||||
return yield* new InvalidSessionExpirationClaimError({
|
||||
sessionId: claims.sid,
|
||||
expirationClaim: claims.exp,
|
||||
});
|
||||
}
|
||||
if (claims.exp <= observedAt.epochMilliseconds) {
|
||||
return yield* new SessionTokenExpiredError({
|
||||
sessionId: claims.sid,
|
||||
expiresAt: expiresAt.value,
|
||||
observedAt,
|
||||
});
|
||||
const now = yield* Clock.currentTimeMillis;
|
||||
if (claims.exp <= now) {
|
||||
return yield* new SessionTokenExpiredError({});
|
||||
}
|
||||
|
||||
const row = yield* authSessions
|
||||
.getById({ sessionId: claims.sid })
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new SessionCredentialVerificationError({ sessionId: claims.sid, cause }),
|
||||
),
|
||||
);
|
||||
const row = yield* authSessions.getById({ sessionId: claims.sid });
|
||||
if (Option.isNone(row)) {
|
||||
return yield* new UnknownSessionTokenError({ sessionId: claims.sid });
|
||||
return yield* new UnknownSessionTokenError({});
|
||||
}
|
||||
if (row.value.revokedAt !== null) {
|
||||
return yield* new SessionTokenRevokedError({
|
||||
sessionId: claims.sid,
|
||||
revokedAt: row.value.revokedAt,
|
||||
});
|
||||
return yield* new SessionTokenRevokedError({});
|
||||
}
|
||||
|
||||
const expiresAt = DateTime.make(claims.exp);
|
||||
if (Option.isNone(expiresAt)) {
|
||||
return yield* new InvalidSessionExpirationClaimError({});
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -711,111 +652,95 @@ export const make = Effect.gen(function* () {
|
||||
...(claims.jkt ? { proofKeyThumbprint: claims.jkt } : {}),
|
||||
} satisfies VerifiedSession;
|
||||
},
|
||||
Effect.mapError((cause) =>
|
||||
isSessionCredentialInvalidError(cause)
|
||||
? cause
|
||||
: new SessionCredentialVerificationError({ cause }),
|
||||
),
|
||||
);
|
||||
|
||||
const encodeWsClaims = Schema.encodeEffect(Schema.fromJsonString(WebSocketClaims));
|
||||
const issueWebSocketToken: SessionStore["Service"]["issueWebSocketToken"] = Effect.fn(
|
||||
"SessionStore.issueWebSocketToken",
|
||||
)(function* (sessionId, input) {
|
||||
const issuedAt = yield* DateTime.now;
|
||||
const expiresAt = DateTime.add(issuedAt, {
|
||||
milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_WEBSOCKET_TOKEN_TTL),
|
||||
});
|
||||
const claims: WebSocketClaims = {
|
||||
v: 1,
|
||||
kind: "websocket",
|
||||
sid: sessionId,
|
||||
iat: issuedAt.epochMilliseconds,
|
||||
exp: expiresAt.epochMilliseconds,
|
||||
};
|
||||
const encodedPayload = yield* encodeWsClaims(claims).pipe(
|
||||
Effect.map(base64UrlEncode),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new WebSocketTokenIssueError({
|
||||
sessionId,
|
||||
cause: new SessionClaimsEncodingError({
|
||||
sessionId,
|
||||
operation: "encode_websocket_claims",
|
||||
cause,
|
||||
}),
|
||||
}),
|
||||
),
|
||||
);
|
||||
const signature = signPayload(encodedPayload, signingSecret);
|
||||
return {
|
||||
token: `${encodedPayload}.${signature}`,
|
||||
expiresAt,
|
||||
};
|
||||
});
|
||||
)(
|
||||
function* (sessionId, input) {
|
||||
const issuedAt = yield* DateTime.now;
|
||||
const expiresAt = DateTime.add(issuedAt, {
|
||||
milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_WEBSOCKET_TOKEN_TTL),
|
||||
});
|
||||
const claims: WebSocketClaims = {
|
||||
v: 1,
|
||||
kind: "websocket",
|
||||
sid: sessionId,
|
||||
iat: issuedAt.epochMilliseconds,
|
||||
exp: expiresAt.epochMilliseconds,
|
||||
};
|
||||
const encodedPayload = yield* encodeWsClaims(claims).pipe(
|
||||
Effect.map(base64UrlEncode),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new SessionClaimsEncodingError({ operation: "encode_websocket_claims", cause }),
|
||||
),
|
||||
);
|
||||
const signature = signPayload(encodedPayload, signingSecret);
|
||||
return {
|
||||
token: `${encodedPayload}.${signature}`,
|
||||
expiresAt,
|
||||
};
|
||||
},
|
||||
Effect.mapError((cause) => new WebSocketTokenIssueError({ cause })),
|
||||
);
|
||||
|
||||
const verifyWebSocketToken: SessionStore["Service"]["verifyWebSocketToken"] = Effect.fn(
|
||||
"SessionStore.verifyWebSocketToken",
|
||||
)(function* (token) {
|
||||
const [encodedPayload, signature] = token.split(".");
|
||||
if (!encodedPayload || !signature) {
|
||||
return yield* new MalformedWebSocketTokenError({});
|
||||
}
|
||||
)(
|
||||
function* (token) {
|
||||
const [encodedPayload, signature] = token.split(".");
|
||||
if (!encodedPayload || !signature) {
|
||||
return yield* new MalformedWebSocketTokenError({});
|
||||
}
|
||||
|
||||
const expectedSignature = signPayload(encodedPayload, signingSecret);
|
||||
if (!timingSafeEqualBase64Url(signature, expectedSignature)) {
|
||||
return yield* new InvalidWebSocketTokenSignatureError({});
|
||||
}
|
||||
const expectedSignature = signPayload(encodedPayload, signingSecret);
|
||||
if (!timingSafeEqualBase64Url(signature, expectedSignature)) {
|
||||
return yield* new InvalidWebSocketTokenSignatureError({});
|
||||
}
|
||||
|
||||
const claims = yield* decodeWebSocketClaims(base64UrlDecodeUtf8(encodedPayload)).pipe(
|
||||
Effect.mapError((cause) => new InvalidWebSocketTokenPayloadError({ cause })),
|
||||
);
|
||||
|
||||
const observedAt = yield* DateTime.now;
|
||||
const expiresAt = DateTime.make(claims.exp);
|
||||
if (Option.isNone(expiresAt)) {
|
||||
return yield* new InvalidSessionExpirationClaimError({
|
||||
sessionId: claims.sid,
|
||||
expirationClaim: claims.exp,
|
||||
});
|
||||
}
|
||||
if (claims.exp <= observedAt.epochMilliseconds) {
|
||||
return yield* new WebSocketTokenExpiredError({
|
||||
sessionId: claims.sid,
|
||||
expiresAt: expiresAt.value,
|
||||
observedAt,
|
||||
});
|
||||
}
|
||||
|
||||
const row = yield* authSessions
|
||||
.getById({ sessionId: claims.sid })
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new WebSocketTokenVerificationError({ sessionId: claims.sid, cause }),
|
||||
),
|
||||
const claims = yield* decodeWebSocketClaims(base64UrlDecodeUtf8(encodedPayload)).pipe(
|
||||
Effect.mapError((cause) => new InvalidWebSocketTokenPayloadError({ cause })),
|
||||
);
|
||||
if (Option.isNone(row)) {
|
||||
return yield* new UnknownWebSocketSessionError({ sessionId: claims.sid });
|
||||
}
|
||||
if (row.value.expiresAt.epochMilliseconds <= observedAt.epochMilliseconds) {
|
||||
return yield* new WebSocketSessionExpiredError({
|
||||
sessionId: claims.sid,
|
||||
expiresAt: row.value.expiresAt,
|
||||
observedAt,
|
||||
});
|
||||
}
|
||||
if (row.value.revokedAt !== null) {
|
||||
return yield* new WebSocketSessionRevokedError({
|
||||
sessionId: claims.sid,
|
||||
revokedAt: row.value.revokedAt,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
sessionId: row.value.sessionId,
|
||||
token,
|
||||
method: row.value.method,
|
||||
client: toClientMetadata(row.value.client),
|
||||
expiresAt: row.value.expiresAt,
|
||||
subject: row.value.subject,
|
||||
scopes: row.value.scopes,
|
||||
} satisfies VerifiedSession;
|
||||
});
|
||||
const now = yield* Clock.currentTimeMillis;
|
||||
if (claims.exp <= now) {
|
||||
return yield* new WebSocketTokenExpiredError({});
|
||||
}
|
||||
|
||||
const row = yield* authSessions.getById({ sessionId: claims.sid });
|
||||
if (Option.isNone(row)) {
|
||||
return yield* new UnknownWebSocketSessionError({});
|
||||
}
|
||||
if (row.value.expiresAt.epochMilliseconds <= now) {
|
||||
return yield* new WebSocketSessionExpiredError({});
|
||||
}
|
||||
if (row.value.revokedAt !== null) {
|
||||
return yield* new WebSocketSessionRevokedError({});
|
||||
}
|
||||
|
||||
return {
|
||||
sessionId: row.value.sessionId,
|
||||
token,
|
||||
method: row.value.method,
|
||||
client: toClientMetadata(row.value.client),
|
||||
expiresAt: row.value.expiresAt,
|
||||
subject: row.value.subject,
|
||||
scopes: row.value.scopes,
|
||||
} satisfies VerifiedSession;
|
||||
},
|
||||
Effect.mapError((cause) =>
|
||||
isSessionCredentialInvalidError(cause)
|
||||
? cause
|
||||
: new WebSocketTokenVerificationError({ cause }),
|
||||
),
|
||||
);
|
||||
|
||||
const listActive: SessionStore["Service"]["listActive"] = Effect.fn("SessionStore.listActive")(
|
||||
function* () {
|
||||
@@ -843,12 +768,10 @@ export const make = Effect.gen(function* () {
|
||||
const revoke: SessionStore["Service"]["revoke"] = Effect.fn("SessionStore.revoke")(
|
||||
function* (sessionId) {
|
||||
const revokedAt = yield* DateTime.now;
|
||||
const revoked = yield* authSessions
|
||||
.revoke({
|
||||
sessionId,
|
||||
revokedAt,
|
||||
})
|
||||
.pipe(Effect.mapError((cause) => new SessionRevocationError({ sessionId, cause })));
|
||||
const revoked = yield* authSessions.revoke({
|
||||
sessionId,
|
||||
revokedAt,
|
||||
});
|
||||
if (revoked) {
|
||||
yield* Ref.update(connectedSessionsRef, (current) => {
|
||||
const next = new Map(current);
|
||||
@@ -859,41 +782,39 @@ export const make = Effect.gen(function* () {
|
||||
}
|
||||
return revoked;
|
||||
},
|
||||
Effect.mapError((cause) => new SessionRevocationError({ cause })),
|
||||
);
|
||||
|
||||
const revokeAllExcept: SessionStore["Service"]["revokeAllExcept"] = Effect.fn(
|
||||
"SessionStore.revokeAllExcept",
|
||||
)(function* (sessionId) {
|
||||
const revokedAt = yield* DateTime.now;
|
||||
const revokedSessionIds = yield* authSessions
|
||||
.revokeAllExcept({
|
||||
)(
|
||||
function* (sessionId) {
|
||||
const revokedAt = yield* DateTime.now;
|
||||
const revokedSessionIds = yield* authSessions.revokeAllExcept({
|
||||
currentSessionId: sessionId,
|
||||
revokedAt,
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new OtherSessionsRevocationError({ currentSessionId: sessionId, cause }),
|
||||
),
|
||||
);
|
||||
if (revokedSessionIds.length > 0) {
|
||||
yield* Ref.update(connectedSessionsRef, (current) => {
|
||||
const next = new Map(current);
|
||||
for (const revokedSessionId of revokedSessionIds) {
|
||||
next.delete(revokedSessionId);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
yield* Effect.forEach(
|
||||
revokedSessionIds,
|
||||
(revokedSessionId) => emitRemoved(revokedSessionId),
|
||||
{
|
||||
concurrency: "unbounded",
|
||||
discard: true,
|
||||
},
|
||||
);
|
||||
}
|
||||
return revokedSessionIds.length;
|
||||
});
|
||||
if (revokedSessionIds.length > 0) {
|
||||
yield* Ref.update(connectedSessionsRef, (current) => {
|
||||
const next = new Map(current);
|
||||
for (const revokedSessionId of revokedSessionIds) {
|
||||
next.delete(revokedSessionId);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
yield* Effect.forEach(
|
||||
revokedSessionIds,
|
||||
(revokedSessionId) => emitRemoved(revokedSessionId),
|
||||
{
|
||||
concurrency: "unbounded",
|
||||
discard: true,
|
||||
},
|
||||
);
|
||||
}
|
||||
return revokedSessionIds.length;
|
||||
},
|
||||
Effect.mapError((cause) => new OtherSessionsRevocationError({ cause })),
|
||||
);
|
||||
|
||||
return SessionStore.of({
|
||||
cookieName,
|
||||
|
||||
@@ -6,7 +6,9 @@ import { mapDpopReplayStoreError } from "./dpop.ts";
|
||||
|
||||
const storeFailure = (tag: "AlreadyExists" | "PermissionDenied") =>
|
||||
new SecretStorePersistError({
|
||||
resource: "DPoP proof",
|
||||
operation: "create",
|
||||
secretName: "DPoP proof",
|
||||
secretPath: "dpop-proof.bin",
|
||||
cause: PlatformError.systemError({
|
||||
_tag: tag,
|
||||
module: "FileSystem",
|
||||
@@ -15,10 +17,16 @@ const storeFailure = (tag: "AlreadyExists" | "PermissionDenied") =>
|
||||
}),
|
||||
});
|
||||
|
||||
const replayContext = {
|
||||
proofKeyThumbprint: "proof-key-thumbprint",
|
||||
proofId: "proof-id",
|
||||
replayKey: "replay-key",
|
||||
};
|
||||
|
||||
describe("mapDpopReplayStoreError", () => {
|
||||
it("reports replay conflicts as invalid credentials", () => {
|
||||
const cause = storeFailure("AlreadyExists");
|
||||
const error = mapDpopReplayStoreError(cause);
|
||||
const error = mapDpopReplayStoreError(cause, replayContext);
|
||||
|
||||
expect(error._tag).toBe("ServerAuthInvalidCredentialError");
|
||||
if (error._tag === "ServerAuthInvalidCredentialError") {
|
||||
@@ -27,11 +35,18 @@ describe("mapDpopReplayStoreError", () => {
|
||||
});
|
||||
|
||||
it("reports replay-store availability failures as internal errors", () => {
|
||||
const error = mapDpopReplayStoreError(storeFailure("PermissionDenied"));
|
||||
const cause = storeFailure("PermissionDenied");
|
||||
const error = mapDpopReplayStoreError(cause, replayContext);
|
||||
|
||||
expect(error._tag).toBe("ServerAuthDpopReplayStateRecordError");
|
||||
if (error._tag === "ServerAuthDpopReplayStateRecordError") {
|
||||
expect(error.message).toBe("Failed to record DPoP proof replay state.");
|
||||
expect(error.message).toBe(
|
||||
"Failed to record replay state for DPoP proof proof-id (proof-key-thumbprint).",
|
||||
);
|
||||
expect(error.proofKeyThumbprint).toBe(replayContext.proofKeyThumbprint);
|
||||
expect(error.proofId).toBe(replayContext.proofId);
|
||||
expect(error.replayKey).toBe(replayContext.replayKey);
|
||||
expect(error.cause).toBe(cause);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -3,26 +3,46 @@ import * as Crypto from "effect/Crypto";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Encoding from "effect/Encoding";
|
||||
import * as Option from "effect/Option";
|
||||
import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
|
||||
import type * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
|
||||
|
||||
import {
|
||||
ServerAuthDpopReplayKeyCalculationError,
|
||||
ServerAuthDpopReplayStateRecordError,
|
||||
ServerAuthInvalidCredentialError,
|
||||
type ServerAuthInternalError,
|
||||
} 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 =>
|
||||
context: {
|
||||
readonly proofKeyThumbprint: string;
|
||||
readonly proofId: string;
|
||||
readonly replayKey: string;
|
||||
},
|
||||
): ServerAuthInvalidCredentialError | ServerAuthDpopReplayStateRecordError =>
|
||||
ServerSecretStore.isSecretAlreadyExistsError(error)
|
||||
? new ServerAuthInvalidCredentialError({
|
||||
diagnostic: "DPoP proof replayed.",
|
||||
cause: error,
|
||||
})
|
||||
: new ServerAuthDpopReplayStateRecordError({
|
||||
...context,
|
||||
cause: error,
|
||||
});
|
||||
|
||||
@@ -33,17 +53,11 @@ export const verifyRequestDpopProof = (input: {
|
||||
}) =>
|
||||
Effect.gen(function* () {
|
||||
const proof = input.request.headers.dpop;
|
||||
const url = HttpServerRequest.toURL(input.request);
|
||||
if (Option.isNone(url)) {
|
||||
return yield* new ServerAuthInvalidCredentialError({
|
||||
diagnostic: "Invalid DPoP request URL.",
|
||||
});
|
||||
}
|
||||
const now = yield* DateTime.now;
|
||||
const result = verifyDpopProof({
|
||||
proof,
|
||||
method: input.request.method,
|
||||
url: url.value.href,
|
||||
url: requestAbsoluteUrl(input.request),
|
||||
nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
|
||||
...(input.expectedThumbprint ? { expectedThumbprint: input.expectedThumbprint } : {}),
|
||||
...(input.expectedAccessToken ? { expectedAccessToken: input.expectedAccessToken } : {}),
|
||||
@@ -62,6 +76,8 @@ export const verifyRequestDpopProof = (input: {
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ServerAuthDpopReplayKeyCalculationError({
|
||||
proofKeyThumbprint: result.thumbprint,
|
||||
proofId: result.jti,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
@@ -79,8 +95,12 @@ export const verifyRequestDpopProof = (input: {
|
||||
),
|
||||
)
|
||||
.pipe(
|
||||
Effect.catchIf(ServerSecretStore.isSecretStoreError, (error) =>
|
||||
Effect.fail(mapDpopReplayStoreError(error)),
|
||||
Effect.mapError((error) =>
|
||||
mapDpopReplayStoreError(error, {
|
||||
proofKeyThumbprint: result.thumbprint,
|
||||
proofId: result.jti,
|
||||
replayKey,
|
||||
}),
|
||||
),
|
||||
);
|
||||
return result.thumbprint;
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import { EnvironmentInternalError } from "@t3tools/contracts";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Logger from "effect/Logger";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
|
||||
|
||||
import * as AuthHttp from "./http.ts";
|
||||
|
||||
const encodeEnvironmentInternalError = Schema.encodeUnknownSync(EnvironmentInternalError);
|
||||
|
||||
const loggerLayer = (messages: Array<unknown>) =>
|
||||
Logger.layer(
|
||||
[
|
||||
Logger.make(({ message }) => {
|
||||
messages.push(message);
|
||||
}),
|
||||
],
|
||||
{ mergeWithExisting: false },
|
||||
);
|
||||
|
||||
describe("auth http diagnostics", () => {
|
||||
it.effect("logs and encodes bounded internal diagnostics without exposing secrets", () => {
|
||||
const messages: Array<unknown> = [];
|
||||
const cause = new Error("credential=secret-value");
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const error = yield* Effect.flip(
|
||||
AuthHttp.failEnvironmentInternal("browser_session_cookie_failed", cause),
|
||||
);
|
||||
|
||||
expect(error).toBeInstanceOf(AuthHttp.EnvironmentHttpInternalError);
|
||||
expect(error.failureTag).toBe("Error");
|
||||
expect(error.message).toBe(
|
||||
"Environment API operation failed (browser_session_cookie_failed).",
|
||||
);
|
||||
expect(encodeEnvironmentInternalError(error)).toEqual({
|
||||
_tag: "EnvironmentInternalError",
|
||||
code: "internal_error",
|
||||
reason: "browser_session_cookie_failed",
|
||||
traceId: error.traceId,
|
||||
});
|
||||
|
||||
expect(messages).toEqual([
|
||||
[
|
||||
"environment api operation failed",
|
||||
{
|
||||
reason: "browser_session_cookie_failed",
|
||||
traceId: error.traceId,
|
||||
failureTag: "Error",
|
||||
reasonCount: 1,
|
||||
failureCount: 1,
|
||||
defectCount: 0,
|
||||
interruptionCount: 0,
|
||||
},
|
||||
],
|
||||
]);
|
||||
}).pipe(Effect.provide(loggerLayer(messages)));
|
||||
});
|
||||
|
||||
it.effect("logs request failures without serializing their Error or Cause values", () => {
|
||||
const messages: Array<unknown> = [];
|
||||
const request = HttpServerRequest.fromWeb(
|
||||
new Request("https://environment.example.test/api/auth/session"),
|
||||
);
|
||||
const requestCause = Cause.combine(
|
||||
Cause.fail(new Error("credential=secret-value")),
|
||||
Cause.die(new Error("stderr=private-value")),
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const exit = yield* Effect.exit(
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
yield* AuthHttp.annotateEnvironmentRequest("auth.session");
|
||||
return yield* Effect.failCause(requestCause);
|
||||
}),
|
||||
).pipe(Effect.provideService(HttpServerRequest.HttpServerRequest, request)),
|
||||
);
|
||||
|
||||
expect(Exit.isFailure(exit)).toBe(true);
|
||||
expect(messages).toEqual([
|
||||
[
|
||||
"environment api request failed",
|
||||
{
|
||||
endpoint: "auth.session",
|
||||
traceId: "unavailable",
|
||||
failureTag: "Error",
|
||||
reasonCount: 2,
|
||||
failureCount: 1,
|
||||
defectCount: 1,
|
||||
interruptionCount: 0,
|
||||
},
|
||||
],
|
||||
]);
|
||||
}).pipe(Effect.provide(loggerLayer(messages)));
|
||||
});
|
||||
|
||||
it.effect("re-propagates nested interruption causes without logging a synthetic 500", () => {
|
||||
const messages: Array<unknown> = [];
|
||||
const interruption = Cause.interrupt();
|
||||
const cause = new Error("cancelled", { cause: interruption });
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const exit = yield* Effect.exit(AuthHttp.failEnvironmentInternal("internal_error", cause));
|
||||
|
||||
expect(Exit.isFailure(exit)).toBe(true);
|
||||
if (Exit.isFailure(exit)) {
|
||||
expect(Cause.hasInterruptsOnly(exit.cause)).toBe(true);
|
||||
expect(Option.isNone(Cause.findErrorOption(exit.cause))).toBe(true);
|
||||
}
|
||||
expect(messages).toEqual([]);
|
||||
}).pipe(Effect.provide(loggerLayer(messages)));
|
||||
});
|
||||
});
|
||||
+183
-74
@@ -23,10 +23,12 @@ import {
|
||||
import type { AuthEnvironmentScope } from "@t3tools/contracts";
|
||||
import { parseAllowedOAuthScope } from "@t3tools/shared/oauthScope";
|
||||
import { causeErrorTag } from "@t3tools/shared/observability";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import { identity } from "effect/Function";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Cookies from "effect/unstable/http/Cookies";
|
||||
import * as HttpEffect from "effect/unstable/http/HttpEffect";
|
||||
import { HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
|
||||
@@ -43,6 +45,72 @@ const CREDENTIAL_RESPONSE_HEADERS = {
|
||||
pragma: "no-cache",
|
||||
} as const;
|
||||
|
||||
const MAX_FAILURE_TAG_LENGTH = 128;
|
||||
const MAX_CAUSE_CHAIN_DEPTH = 32;
|
||||
|
||||
const EnvironmentFailureTag = Schema.String.check(
|
||||
Schema.isMinLength(1),
|
||||
Schema.isMaxLength(MAX_FAILURE_TAG_LENGTH),
|
||||
);
|
||||
|
||||
function failureLogAttributes(input: unknown) {
|
||||
const cause = Cause.isCause(input) ? input : Cause.fail(input);
|
||||
let failureCount = 0;
|
||||
let defectCount = 0;
|
||||
let interruptionCount = 0;
|
||||
for (const reason of cause.reasons) {
|
||||
switch (reason._tag) {
|
||||
case "Fail":
|
||||
failureCount += 1;
|
||||
break;
|
||||
case "Die":
|
||||
defectCount += 1;
|
||||
break;
|
||||
case "Interrupt":
|
||||
interruptionCount += 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
const unboundedFailureTag = causeErrorTag(cause).trim() || "Unknown";
|
||||
return {
|
||||
failureTag: unboundedFailureTag.slice(0, MAX_FAILURE_TAG_LENGTH),
|
||||
reasonCount: cause.reasons.length,
|
||||
failureCount,
|
||||
defectCount,
|
||||
interruptionCount,
|
||||
};
|
||||
}
|
||||
|
||||
function findInterruptCause(input: unknown): Cause.Cause<never> | undefined {
|
||||
const seen = new Set<object>();
|
||||
let current = input;
|
||||
for (let depth = 0; depth < MAX_CAUSE_CHAIN_DEPTH; depth += 1) {
|
||||
if (Cause.isCause(current)) {
|
||||
return Cause.hasInterruptsOnly(current) ? (current as Cause.Cause<never>) : undefined;
|
||||
}
|
||||
if (typeof current !== "object" || current === null || seen.has(current)) {
|
||||
return undefined;
|
||||
}
|
||||
seen.add(current);
|
||||
if (!("cause" in current)) {
|
||||
return undefined;
|
||||
}
|
||||
current = current.cause;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export class EnvironmentHttpInternalError extends EnvironmentInternalError.extend<EnvironmentHttpInternalError>(
|
||||
"EnvironmentHttpInternalError",
|
||||
)({
|
||||
failureTag: EnvironmentFailureTag,
|
||||
cause: Schema.Defect(),
|
||||
}) {
|
||||
override get message(): string {
|
||||
return `Environment API operation failed (${this.reason}).`;
|
||||
}
|
||||
}
|
||||
|
||||
const appendCredentialResponseHeaders = HttpEffect.appendPreResponseHandler((_request, response) =>
|
||||
Effect.succeed(HttpServerResponse.setHeaders(response, CREDENTIAL_RESPONSE_HEADERS)),
|
||||
);
|
||||
@@ -75,12 +143,11 @@ export function annotateEnvironmentRequest(endpoint: string) {
|
||||
const traceId = yield* currentEnvironmentTraceId;
|
||||
|
||||
yield* Effect.addFinalizer((exit) =>
|
||||
exit._tag === "Failure"
|
||||
exit._tag === "Failure" && !Cause.hasInterruptsOnly(exit.cause)
|
||||
? Effect.logWarning("environment api request failed", {
|
||||
endpoint,
|
||||
traceId,
|
||||
errorTag: causeErrorTag(exit.cause),
|
||||
cause: exit.cause,
|
||||
...failureLogAttributes(exit.cause),
|
||||
})
|
||||
: Effect.void,
|
||||
);
|
||||
@@ -137,19 +204,44 @@ function failEnvironmentOperationForbidden(reason: "current_session_revoke_not_a
|
||||
);
|
||||
}
|
||||
|
||||
export function failEnvironmentInternal(reason: EnvironmentInternalErrorReason, error?: unknown) {
|
||||
return Effect.gen(function* () {
|
||||
const traceId = yield* currentEnvironmentTraceId;
|
||||
if (error !== undefined) {
|
||||
yield* Effect.logError("environment api operation failed", {
|
||||
reason,
|
||||
traceId,
|
||||
cause: error,
|
||||
});
|
||||
export const failEnvironmentInternal = Effect.fn("environment.auth.failEnvironmentInternal")(
|
||||
function* (reason: EnvironmentInternalErrorReason, cause: unknown) {
|
||||
const interruptCause = findInterruptCause(cause);
|
||||
if (interruptCause !== undefined) {
|
||||
return yield* Effect.failCause(interruptCause);
|
||||
}
|
||||
return yield* new EnvironmentInternalError({ code: "internal_error", reason, traceId });
|
||||
});
|
||||
}
|
||||
const traceId = yield* currentEnvironmentTraceId;
|
||||
const diagnostics = failureLogAttributes(cause);
|
||||
yield* Effect.logError("environment api operation failed", {
|
||||
reason,
|
||||
traceId,
|
||||
...diagnostics,
|
||||
});
|
||||
return yield* new EnvironmentHttpInternalError({
|
||||
code: "internal_error",
|
||||
reason,
|
||||
traceId,
|
||||
failureTag: diagnostics.failureTag,
|
||||
cause,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
const failAuthenticationInternal = (error: EnvironmentAuth.ServerAuthAuthenticationInternalError) =>
|
||||
failEnvironmentInternal("internal_error", error);
|
||||
|
||||
export const catchEnvironmentAuthenticationErrors = <A, R>(
|
||||
effect: Effect.Effect<A, EnvironmentAuth.ServerAuthAuthenticationError, R>,
|
||||
) =>
|
||||
effect.pipe(
|
||||
Effect.catchTags({
|
||||
ServerAuthMissingCredentialError: () => failEnvironmentAuthInvalid("missing_credential"),
|
||||
ServerAuthInvalidCredentialError: () => failEnvironmentAuthInvalid("invalid_credential"),
|
||||
ServerAuthSessionCredentialValidationError: failAuthenticationInternal,
|
||||
ServerAuthDpopReplayStateRecordError: failAuthenticationInternal,
|
||||
ServerAuthDpopReplayKeyCalculationError: failAuthenticationInternal,
|
||||
}),
|
||||
);
|
||||
|
||||
export const requireEnvironmentScope = Effect.fn("environment.auth.requireScope")(function* (
|
||||
scope: AuthEnvironmentScope,
|
||||
@@ -168,13 +260,8 @@ export const environmentAuthenticatedAuthLayer = Layer.effect(
|
||||
return (httpEffect) =>
|
||||
Effect.gen(function* () {
|
||||
const request = yield* HttpServerRequest.HttpServerRequest;
|
||||
const session = yield* serverAuth.authenticateHttpRequest(request).pipe(
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, (error) =>
|
||||
failEnvironmentAuthInvalid(EnvironmentAuth.serverAuthCredentialReason(error)),
|
||||
),
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
|
||||
failEnvironmentInternal("internal_error", error),
|
||||
),
|
||||
const session = yield* catchEnvironmentAuthenticationErrors(
|
||||
serverAuth.authenticateHttpRequest(request),
|
||||
);
|
||||
return yield* httpEffect.pipe(
|
||||
Effect.provideService(EnvironmentAuthenticatedPrincipal, {
|
||||
@@ -183,7 +270,11 @@ export const environmentAuthenticatedAuthLayer = Layer.effect(
|
||||
}),
|
||||
session.subject === "cloud-connect" ? traceAuthenticatedRelayRequest : identity,
|
||||
);
|
||||
}).pipe(Effect.catchTag("EnvironmentAuthInvalidError", appendDpopChallengeOnUnauthorized));
|
||||
}).pipe(
|
||||
Effect.catchTags({
|
||||
EnvironmentAuthInvalidError: appendDpopChallengeOnUnauthorized,
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -203,9 +294,11 @@ export const authHttpApiLayer = HttpApiBuilder.group(
|
||||
const request = yield* HttpServerRequest.HttpServerRequest;
|
||||
return yield* serverAuth.getSessionState(request);
|
||||
},
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
|
||||
failEnvironmentInternal("internal_error", error),
|
||||
),
|
||||
Effect.catchTags({
|
||||
ServerAuthSessionCredentialValidationError: failAuthenticationInternal,
|
||||
ServerAuthDpopReplayStateRecordError: failAuthenticationInternal,
|
||||
ServerAuthDpopReplayKeyCalculationError: failAuthenticationInternal,
|
||||
}),
|
||||
),
|
||||
)
|
||||
.handle(
|
||||
@@ -225,7 +318,12 @@ export const authHttpApiLayer = HttpApiBuilder.group(
|
||||
path: "/",
|
||||
sameSite: "lax",
|
||||
}),
|
||||
).pipe(Effect.catch(() => failEnvironmentInternal("browser_session_cookie_failed")));
|
||||
).pipe(
|
||||
Effect.catchTags({
|
||||
CookieError: (cause) =>
|
||||
failEnvironmentInternal("browser_session_cookie_failed", cause),
|
||||
}),
|
||||
);
|
||||
|
||||
yield* HttpEffect.appendPreResponseHandler((_request, response) =>
|
||||
Effect.succeed(HttpServerResponse.mergeCookies(response, sessionCookies)),
|
||||
@@ -233,12 +331,14 @@ export const authHttpApiLayer = HttpApiBuilder.group(
|
||||
yield* appendCredentialResponseHeaders;
|
||||
return result.response;
|
||||
},
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, (error) =>
|
||||
failEnvironmentAuthInvalid(EnvironmentAuth.serverAuthCredentialReason(error)),
|
||||
),
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
|
||||
failEnvironmentInternal("browser_session_issuance_failed", error),
|
||||
),
|
||||
Effect.catchTags({
|
||||
ServerAuthInvalidCredentialError: () =>
|
||||
failEnvironmentAuthInvalid("invalid_credential"),
|
||||
ServerAuthBootstrapCredentialValidationError: (error) =>
|
||||
failEnvironmentInternal("browser_session_issuance_failed", error),
|
||||
ServerAuthAuthenticatedSessionIssueError: (error) =>
|
||||
failEnvironmentInternal("browser_session_issuance_failed", error),
|
||||
}),
|
||||
),
|
||||
)
|
||||
.handle(
|
||||
@@ -268,14 +368,16 @@ export const authHttpApiLayer = HttpApiBuilder.group(
|
||||
}
|
||||
const proofKeyThumbprint = args.headers.dpop
|
||||
? yield* verifyRequestDpopProof({ request }).pipe(
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, () =>
|
||||
appendDpopChallengeHeader.pipe(
|
||||
Effect.andThen(failEnvironmentAuthInvalid("invalid_credential")),
|
||||
),
|
||||
),
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
|
||||
failEnvironmentInternal("access_token_issuance_failed", error),
|
||||
),
|
||||
Effect.catchTags({
|
||||
ServerAuthInvalidCredentialError: () =>
|
||||
appendDpopChallengeHeader.pipe(
|
||||
Effect.andThen(failEnvironmentAuthInvalid("invalid_credential")),
|
||||
),
|
||||
ServerAuthDpopReplayStateRecordError: (error) =>
|
||||
failEnvironmentInternal("access_token_issuance_failed", error),
|
||||
ServerAuthDpopReplayKeyCalculationError: (error) =>
|
||||
failEnvironmentInternal("access_token_issuance_failed", error),
|
||||
}),
|
||||
)
|
||||
: undefined;
|
||||
yield* appendCredentialResponseHeaders;
|
||||
@@ -296,15 +398,16 @@ export const authHttpApiLayer = HttpApiBuilder.group(
|
||||
);
|
||||
},
|
||||
traceRelayRequest,
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, (error) =>
|
||||
failEnvironmentAuthInvalid(EnvironmentAuth.serverAuthCredentialReason(error)),
|
||||
),
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthInvalidRequestError, (error) =>
|
||||
failEnvironmentInvalidRequest(EnvironmentAuth.serverAuthInvalidRequestReason(error)),
|
||||
),
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
|
||||
failEnvironmentInternal("access_token_issuance_failed", error),
|
||||
),
|
||||
Effect.catchTags({
|
||||
ServerAuthInvalidCredentialError: () =>
|
||||
failEnvironmentAuthInvalid("invalid_credential"),
|
||||
ServerAuthScopeNotGrantedError: () =>
|
||||
failEnvironmentInvalidRequest("scope_not_granted"),
|
||||
ServerAuthBootstrapCredentialValidationError: (error) =>
|
||||
failEnvironmentInternal("access_token_issuance_failed", error),
|
||||
ServerAuthAuthenticatedAccessTokenIssueError: (error) =>
|
||||
failEnvironmentInternal("access_token_issuance_failed", error),
|
||||
}),
|
||||
),
|
||||
)
|
||||
.handle(
|
||||
@@ -316,9 +419,10 @@ export const authHttpApiLayer = HttpApiBuilder.group(
|
||||
yield* appendCredentialResponseHeaders;
|
||||
return yield* serverAuth.issueWebSocketTicket(session);
|
||||
},
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
|
||||
failEnvironmentInternal("websocket_ticket_issuance_failed", error),
|
||||
),
|
||||
Effect.catchTags({
|
||||
ServerAuthWebSocketTokenIssueError: (error) =>
|
||||
failEnvironmentInternal("websocket_ticket_issuance_failed", error),
|
||||
}),
|
||||
),
|
||||
)
|
||||
.handle(
|
||||
@@ -341,9 +445,10 @@ export const authHttpApiLayer = HttpApiBuilder.group(
|
||||
}
|
||||
return yield* serverAuth.issuePairingCredential(args.payload);
|
||||
},
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
|
||||
failEnvironmentInternal("pairing_credential_issuance_failed", error),
|
||||
),
|
||||
Effect.catchTags({
|
||||
ServerAuthPairingLinkCreationError: (error) =>
|
||||
failEnvironmentInternal("pairing_credential_issuance_failed", error),
|
||||
}),
|
||||
),
|
||||
)
|
||||
.handle(
|
||||
@@ -354,9 +459,10 @@ export const authHttpApiLayer = HttpApiBuilder.group(
|
||||
yield* requireEnvironmentScope(AuthAccessReadScope);
|
||||
return yield* serverAuth.listPairingLinks();
|
||||
},
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
|
||||
failEnvironmentInternal("pairing_links_load_failed", error),
|
||||
),
|
||||
Effect.catchTags({
|
||||
ServerAuthPairingLinksListError: (error) =>
|
||||
failEnvironmentInternal("pairing_links_load_failed", error),
|
||||
}),
|
||||
),
|
||||
)
|
||||
.handle(
|
||||
@@ -368,9 +474,10 @@ export const authHttpApiLayer = HttpApiBuilder.group(
|
||||
const revoked = yield* serverAuth.revokePairingLink(args.payload.id);
|
||||
return { revoked };
|
||||
},
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
|
||||
failEnvironmentInternal("pairing_link_revoke_failed", error),
|
||||
),
|
||||
Effect.catchTags({
|
||||
ServerAuthPairingLinkRevocationError: (error) =>
|
||||
failEnvironmentInternal("pairing_link_revoke_failed", error),
|
||||
}),
|
||||
),
|
||||
)
|
||||
.handle(
|
||||
@@ -381,9 +488,10 @@ export const authHttpApiLayer = HttpApiBuilder.group(
|
||||
const session = yield* requireEnvironmentScope(AuthAccessReadScope);
|
||||
return yield* serverAuth.listClientSessions(session.sessionId);
|
||||
},
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
|
||||
failEnvironmentInternal("client_sessions_load_failed", error),
|
||||
),
|
||||
Effect.catchTags({
|
||||
ServerAuthSessionsListError: (error) =>
|
||||
failEnvironmentInternal("client_sessions_load_failed", error),
|
||||
}),
|
||||
),
|
||||
)
|
||||
.handle(
|
||||
@@ -398,12 +506,12 @@ export const authHttpApiLayer = HttpApiBuilder.group(
|
||||
);
|
||||
return { revoked };
|
||||
},
|
||||
Effect.catchTag("ServerAuthForbiddenOperationError", () =>
|
||||
failEnvironmentOperationForbidden("current_session_revoke_not_allowed"),
|
||||
),
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
|
||||
failEnvironmentInternal("client_session_revoke_failed", error),
|
||||
),
|
||||
Effect.catchTags({
|
||||
ServerAuthForbiddenOperationError: () =>
|
||||
failEnvironmentOperationForbidden("current_session_revoke_not_allowed"),
|
||||
ServerAuthSessionRevocationError: (error) =>
|
||||
failEnvironmentInternal("client_session_revoke_failed", error),
|
||||
}),
|
||||
),
|
||||
)
|
||||
.handle(
|
||||
@@ -415,9 +523,10 @@ export const authHttpApiLayer = HttpApiBuilder.group(
|
||||
const revokedCount = yield* serverAuth.revokeOtherClientSessions(session.sessionId);
|
||||
return { revokedCount };
|
||||
},
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
|
||||
failEnvironmentInternal("client_session_revoke_failed", error),
|
||||
),
|
||||
Effect.catchTags({
|
||||
ServerAuthOtherSessionsRevocationError: (error) =>
|
||||
failEnvironmentInternal("client_session_revoke_failed", error),
|
||||
}),
|
||||
),
|
||||
);
|
||||
}),
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as HttpClient from "effect/unstable/http/HttpClient";
|
||||
|
||||
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
|
||||
import * as CliTokenManager from "./CliTokenManager.ts";
|
||||
|
||||
const unusedSecretStoreOperation = () => Effect.die("unused secret-store operation");
|
||||
|
||||
function makeSecretStore(
|
||||
overrides: Partial<ServerSecretStore.ServerSecretStore["Service"]>,
|
||||
): ServerSecretStore.ServerSecretStore["Service"] {
|
||||
return {
|
||||
get: unusedSecretStoreOperation,
|
||||
set: unusedSecretStoreOperation,
|
||||
create: unusedSecretStoreOperation,
|
||||
getOrCreateRandom: unusedSecretStoreOperation,
|
||||
remove: unusedSecretStoreOperation,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function makeTokenManager(secretStore: ServerSecretStore.ServerSecretStore["Service"]) {
|
||||
return CliTokenManager.make.pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
NodeServices.layer,
|
||||
Layer.succeed(ServerSecretStore.ServerSecretStore, secretStore),
|
||||
Layer.succeed(
|
||||
HttpClient.HttpClient,
|
||||
HttpClient.make(() => Effect.die("unused HTTP client")),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
describe("CloudCliTokenManager", () => {
|
||||
it("redacts OAuth endpoint credentials while retaining exact causes", () => {
|
||||
const tokenEndpoint =
|
||||
"https://user:[email protected]/private/token?client_secret=secret#fragment";
|
||||
const redirectUri =
|
||||
"https://callback-user:callback-password@localhost/private/callback?code=secret#fragment";
|
||||
const cause = new Error("exchange failed");
|
||||
|
||||
const refreshError = CliTokenManager.CloudCliCredentialRefreshError.fromStage({
|
||||
stage: "exchange-token",
|
||||
tokenEndpoint,
|
||||
cause,
|
||||
});
|
||||
const authorizationError = CliTokenManager.CloudCliAuthorizationError.fromStage({
|
||||
stage: "exchange-token",
|
||||
tokenEndpoint,
|
||||
redirectUri,
|
||||
cause,
|
||||
});
|
||||
const timeoutError = CliTokenManager.CloudCliAuthorizationTimeoutError.fromRedirectUri({
|
||||
redirectUri,
|
||||
timeoutMillis: 1000,
|
||||
cause,
|
||||
});
|
||||
|
||||
expect(refreshError).toMatchObject({
|
||||
tokenEndpointInputLength: tokenEndpoint.length,
|
||||
tokenEndpointProtocol: "https:",
|
||||
tokenEndpointHostname: "auth.example.test",
|
||||
cause,
|
||||
});
|
||||
expect(authorizationError).toMatchObject({
|
||||
tokenEndpointInputLength: tokenEndpoint.length,
|
||||
tokenEndpointHostname: "auth.example.test",
|
||||
redirectUriInputLength: redirectUri.length,
|
||||
redirectUriHostname: "localhost",
|
||||
cause,
|
||||
});
|
||||
expect(timeoutError).toMatchObject({
|
||||
redirectUriInputLength: redirectUri.length,
|
||||
redirectUriHostname: "localhost",
|
||||
cause,
|
||||
});
|
||||
expect(refreshError.cause).toBe(cause);
|
||||
expect(authorizationError.cause).toBe(cause);
|
||||
expect(timeoutError.cause).toBe(cause);
|
||||
for (const error of [refreshError, authorizationError, timeoutError]) {
|
||||
expect(error).not.toHaveProperty("tokenEndpoint");
|
||||
expect(error).not.toHaveProperty("redirectUri");
|
||||
const serialized = JSON.stringify(error);
|
||||
for (const secret of [
|
||||
"user:password",
|
||||
"callback-user:callback-password",
|
||||
"/private/",
|
||||
"client_secret=secret",
|
||||
"code=secret",
|
||||
"#fragment",
|
||||
]) {
|
||||
expect(error.message).not.toContain(secret);
|
||||
expect(serialized).not.toContain(secret);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it.effect("retains secret context and cause when credential removal fails", () => {
|
||||
const failure = new ServerSecretStore.SecretStoreRemoveError({
|
||||
secretName: "cloud-cli-oauth-token",
|
||||
secretPath: "/tmp/secrets/cloud-cli-oauth-token.bin",
|
||||
cause: PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "remove",
|
||||
pathOrDescriptor: "/tmp/secrets/cloud-cli-oauth-token.bin",
|
||||
}),
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const tokens = yield* makeTokenManager(
|
||||
makeSecretStore({ remove: () => Effect.fail(failure) }),
|
||||
);
|
||||
const error = yield* Effect.flip(tokens.clear);
|
||||
|
||||
expect(error).toMatchObject({
|
||||
_tag: "CloudCliCredentialRemovalError",
|
||||
secretName: "cloud-cli-oauth-token",
|
||||
cause: failure,
|
||||
});
|
||||
expect(error.message).toBe(
|
||||
"Could not remove the stored T3 Connect CLI credential cloud-cli-oauth-token.",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("classifies credential read failures without replacing the cause", () => {
|
||||
const failure = new ServerSecretStore.SecretStoreReadError({
|
||||
secretName: "cloud-cli-oauth-token",
|
||||
secretPath: "/tmp/secrets/cloud-cli-oauth-token.bin",
|
||||
cause: PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "readFile",
|
||||
pathOrDescriptor: "/tmp/secrets/cloud-cli-oauth-token.bin",
|
||||
}),
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const tokens = yield* makeTokenManager(makeSecretStore({ get: () => Effect.fail(failure) }));
|
||||
const error = yield* Effect.flip(tokens.hasCredential);
|
||||
|
||||
expect(error).toMatchObject({
|
||||
_tag: "CloudCliCredentialReadError",
|
||||
stage: "read-credential",
|
||||
secretName: "cloud-cli-oauth-token",
|
||||
cause: failure,
|
||||
});
|
||||
expect(error.message).toBe(
|
||||
"Could not inspect the stored T3 Connect CLI credential cloud-cli-oauth-token during read-credential.",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("classifies malformed persisted credentials as refresh decode failures", () =>
|
||||
Effect.gen(function* () {
|
||||
const tokens = yield* makeTokenManager(
|
||||
makeSecretStore({
|
||||
get: () =>
|
||||
Effect.succeed(Option.some(new TextEncoder().encode("not valid credential JSON"))),
|
||||
}),
|
||||
);
|
||||
const error = yield* Effect.flip(tokens.getExisting);
|
||||
|
||||
expect(error).toMatchObject({
|
||||
_tag: "CloudCliCredentialRefreshError",
|
||||
stage: "decode-credential",
|
||||
secretName: "cloud-cli-oauth-token",
|
||||
cause: { _tag: "SchemaError" },
|
||||
});
|
||||
expect(error.message).toBe(
|
||||
"Could not refresh the T3 Connect CLI credential cloud-cli-oauth-token during decode-credential.",
|
||||
);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -20,6 +20,7 @@ import * as HttpClientResponse from "effect/unstable/http/HttpClientResponse";
|
||||
import * as HttpRouter from "effect/unstable/http/HttpRouter";
|
||||
import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
|
||||
import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";
|
||||
import { getUrlDiagnostics } from "@t3tools/shared/urlDiagnostics";
|
||||
|
||||
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
|
||||
import { cloudCliOAuthConfig, type CloudCliOAuthConfig } from "./publicConfig.ts";
|
||||
@@ -27,6 +28,8 @@ import { cloudCliOAuthConfig, type CloudCliOAuthConfig } from "./publicConfig.ts
|
||||
const CLOUD_CLI_OAUTH_TOKEN_SECRET = "cloud-cli-oauth-token";
|
||||
const CLOUD_CLI_OAUTH_CALLBACK_TIMEOUT = Duration.minutes(10);
|
||||
const CLOUD_CLI_OAUTH_REFRESH_EARLY_MS = Duration.toMillis(Duration.minutes(5));
|
||||
const CLOUD_CLI_OAUTH_CALLBACK_HOST = "127.0.0.1";
|
||||
const CLOUD_CLI_OAUTH_CALLBACK_PORT = 34338;
|
||||
|
||||
const PersistedToken = Schema.Struct({
|
||||
accessToken: Schema.String,
|
||||
@@ -46,48 +49,223 @@ const OAuthTokenResponse = Schema.Struct({
|
||||
token_type: Schema.String,
|
||||
});
|
||||
|
||||
type CredentialReadFailure = ServerSecretStore.SecretStoreReadError | Schema.SchemaError;
|
||||
|
||||
type CredentialPersistFailure =
|
||||
| Schema.SchemaError
|
||||
| ServerSecretStore.SecretStoreTemporaryPathGenerationError
|
||||
| ServerSecretStore.SecretStorePersistError;
|
||||
|
||||
const CloudCliCredentialRefreshStage = Schema.Literals([
|
||||
"read-credential",
|
||||
"decode-credential",
|
||||
"load-oauth-config",
|
||||
"exchange-token",
|
||||
"encode-credential",
|
||||
"persist-credential",
|
||||
]);
|
||||
type CloudCliCredentialRefreshStage = typeof CloudCliCredentialRefreshStage.Type;
|
||||
|
||||
const CloudCliAuthorizationStage = Schema.Literals([
|
||||
"load-oauth-config",
|
||||
"prepare-pkce",
|
||||
"start-callback-server",
|
||||
"exchange-token",
|
||||
"encode-credential",
|
||||
"persist-credential",
|
||||
]);
|
||||
type CloudCliAuthorizationStage = typeof CloudCliAuthorizationStage.Type;
|
||||
|
||||
function tokenEndpointDiagnosticFields(tokenEndpoint: string | undefined) {
|
||||
if (tokenEndpoint === undefined) return {};
|
||||
const diagnostics = getUrlDiagnostics(tokenEndpoint);
|
||||
return {
|
||||
tokenEndpointInputLength: diagnostics.inputLength,
|
||||
...(diagnostics.protocol === undefined ? {} : { tokenEndpointProtocol: diagnostics.protocol }),
|
||||
...(diagnostics.hostname === undefined ? {} : { tokenEndpointHostname: diagnostics.hostname }),
|
||||
};
|
||||
}
|
||||
|
||||
function redirectUriDiagnosticFields(redirectUri: string | undefined) {
|
||||
if (redirectUri === undefined) return {};
|
||||
const diagnostics = getUrlDiagnostics(redirectUri);
|
||||
return {
|
||||
redirectUriInputLength: diagnostics.inputLength,
|
||||
...(diagnostics.protocol === undefined ? {} : { redirectUriProtocol: diagnostics.protocol }),
|
||||
...(diagnostics.hostname === undefined ? {} : { redirectUriHostname: diagnostics.hostname }),
|
||||
};
|
||||
}
|
||||
|
||||
export class CloudCliCredentialRemovalError extends Schema.TaggedErrorClass<CloudCliCredentialRemovalError>()(
|
||||
"CloudCliCredentialRemovalError",
|
||||
{ cause: Schema.Defect() },
|
||||
{
|
||||
secretName: Schema.Literal(CLOUD_CLI_OAUTH_TOKEN_SECRET),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Could not remove the stored T3 Connect CLI credential.";
|
||||
return `Could not remove the stored T3 Connect CLI credential ${this.secretName}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class CloudCliCredentialRefreshError extends Schema.TaggedErrorClass<CloudCliCredentialRefreshError>()(
|
||||
"CloudCliCredentialRefreshError",
|
||||
{ cause: Schema.Defect() },
|
||||
{
|
||||
stage: CloudCliCredentialRefreshStage,
|
||||
secretName: Schema.Literal(CLOUD_CLI_OAUTH_TOKEN_SECRET),
|
||||
tokenEndpointInputLength: Schema.optionalKey(Schema.Number),
|
||||
tokenEndpointProtocol: Schema.optionalKey(Schema.String),
|
||||
tokenEndpointHostname: Schema.optionalKey(Schema.String),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
static fromStage(input: {
|
||||
readonly stage: CloudCliCredentialRefreshStage;
|
||||
readonly cause: unknown;
|
||||
readonly tokenEndpoint?: string;
|
||||
}): CloudCliCredentialRefreshError {
|
||||
return new CloudCliCredentialRefreshError({
|
||||
stage: input.stage,
|
||||
secretName: CLOUD_CLI_OAUTH_TOKEN_SECRET,
|
||||
...tokenEndpointDiagnosticFields(input.tokenEndpoint),
|
||||
cause: input.cause,
|
||||
});
|
||||
}
|
||||
|
||||
static fromCredentialRead(cause: CredentialReadFailure): CloudCliCredentialRefreshError {
|
||||
return new CloudCliCredentialRefreshError({
|
||||
stage: cause._tag === "SecretStoreReadError" ? "read-credential" : "decode-credential",
|
||||
secretName: CLOUD_CLI_OAUTH_TOKEN_SECRET,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
|
||||
static fromCredentialPersist(cause: CredentialPersistFailure): CloudCliCredentialRefreshError {
|
||||
return new CloudCliCredentialRefreshError({
|
||||
stage: cause._tag === "SchemaError" ? "encode-credential" : "persist-credential",
|
||||
secretName: CLOUD_CLI_OAUTH_TOKEN_SECRET,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return "Could not refresh the T3 Connect CLI credential.";
|
||||
const tokenEndpoint =
|
||||
this.tokenEndpointInputLength === undefined
|
||||
? ""
|
||||
: ` using the token endpoint${this.tokenEndpointHostname ? ` at ${this.tokenEndpointHostname}` : ""} (input length ${this.tokenEndpointInputLength})`;
|
||||
return `Could not refresh the T3 Connect CLI credential ${this.secretName} during ${this.stage}${tokenEndpoint}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class CloudCliCredentialReadError extends Schema.TaggedErrorClass<CloudCliCredentialReadError>()(
|
||||
"CloudCliCredentialReadError",
|
||||
{ cause: Schema.Defect() },
|
||||
{
|
||||
stage: Schema.Literals(["read-credential", "decode-credential"]),
|
||||
secretName: Schema.Literal(CLOUD_CLI_OAUTH_TOKEN_SECRET),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
static fromCredentialRead(cause: CredentialReadFailure): CloudCliCredentialReadError {
|
||||
return new CloudCliCredentialReadError({
|
||||
stage: cause._tag === "SecretStoreReadError" ? "read-credential" : "decode-credential",
|
||||
secretName: CLOUD_CLI_OAUTH_TOKEN_SECRET,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return "Could not read the stored T3 Connect CLI credential.";
|
||||
return `Could not inspect the stored T3 Connect CLI credential ${this.secretName} during ${this.stage}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class CloudCliAuthorizationError extends Schema.TaggedErrorClass<CloudCliAuthorizationError>()(
|
||||
"CloudCliAuthorizationError",
|
||||
{ cause: Schema.Defect() },
|
||||
{
|
||||
stage: CloudCliAuthorizationStage,
|
||||
secretName: Schema.Literal(CLOUD_CLI_OAUTH_TOKEN_SECRET),
|
||||
tokenEndpointInputLength: Schema.optionalKey(Schema.Number),
|
||||
tokenEndpointProtocol: Schema.optionalKey(Schema.String),
|
||||
tokenEndpointHostname: Schema.optionalKey(Schema.String),
|
||||
redirectUriInputLength: Schema.optionalKey(Schema.Number),
|
||||
redirectUriProtocol: Schema.optionalKey(Schema.String),
|
||||
redirectUriHostname: Schema.optionalKey(Schema.String),
|
||||
callbackHost: Schema.optional(Schema.String),
|
||||
callbackPort: Schema.optional(Schema.Number),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
static fromStage(input: {
|
||||
readonly stage: CloudCliAuthorizationStage;
|
||||
readonly cause: unknown;
|
||||
readonly tokenEndpoint?: string;
|
||||
readonly redirectUri?: string;
|
||||
readonly callbackHost?: string;
|
||||
readonly callbackPort?: number;
|
||||
}): CloudCliAuthorizationError {
|
||||
return new CloudCliAuthorizationError({
|
||||
stage: input.stage,
|
||||
secretName: CLOUD_CLI_OAUTH_TOKEN_SECRET,
|
||||
...tokenEndpointDiagnosticFields(input.tokenEndpoint),
|
||||
...redirectUriDiagnosticFields(input.redirectUri),
|
||||
...(input.callbackHost === undefined ? {} : { callbackHost: input.callbackHost }),
|
||||
...(input.callbackPort === undefined ? {} : { callbackPort: input.callbackPort }),
|
||||
cause: input.cause,
|
||||
});
|
||||
}
|
||||
|
||||
static fromCredentialPersist(cause: CredentialPersistFailure): CloudCliAuthorizationError {
|
||||
return new CloudCliAuthorizationError({
|
||||
stage: cause._tag === "SchemaError" ? "encode-credential" : "persist-credential",
|
||||
secretName: CLOUD_CLI_OAUTH_TOKEN_SECRET,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return "Could not authorize the T3 Connect CLI.";
|
||||
const tokenEndpoint =
|
||||
this.tokenEndpointInputLength === undefined
|
||||
? ""
|
||||
: ` using the token endpoint${this.tokenEndpointHostname ? ` at ${this.tokenEndpointHostname}` : ""} (input length ${this.tokenEndpointInputLength})`;
|
||||
const redirectUri =
|
||||
this.redirectUriInputLength === undefined
|
||||
? ""
|
||||
: ` with a callback URI input of length ${this.redirectUriInputLength}`;
|
||||
const callbackAddress =
|
||||
this.callbackHost && this.callbackPort !== undefined
|
||||
? ` on ${this.callbackHost}:${this.callbackPort}`
|
||||
: "";
|
||||
return `Could not authorize the T3 Connect CLI credential ${this.secretName} during ${this.stage}${tokenEndpoint}${redirectUri}${callbackAddress}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class CloudCliAuthorizationTimeoutError extends Schema.TaggedErrorClass<CloudCliAuthorizationTimeoutError>()(
|
||||
"CloudCliAuthorizationTimeoutError",
|
||||
{ cause: Schema.Defect() },
|
||||
{
|
||||
redirectUriInputLength: Schema.Number,
|
||||
redirectUriProtocol: Schema.optionalKey(Schema.String),
|
||||
redirectUriHostname: Schema.optionalKey(Schema.String),
|
||||
timeoutMillis: Schema.Number,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
static fromRedirectUri(input: {
|
||||
readonly redirectUri: string;
|
||||
readonly timeoutMillis: number;
|
||||
readonly cause: unknown;
|
||||
}): CloudCliAuthorizationTimeoutError {
|
||||
const diagnostics = getUrlDiagnostics(input.redirectUri);
|
||||
return new CloudCliAuthorizationTimeoutError({
|
||||
redirectUriInputLength: diagnostics.inputLength,
|
||||
...(diagnostics.protocol === undefined ? {} : { redirectUriProtocol: diagnostics.protocol }),
|
||||
...(diagnostics.hostname === undefined ? {} : { redirectUriHostname: diagnostics.hostname }),
|
||||
timeoutMillis: input.timeoutMillis,
|
||||
cause: input.cause,
|
||||
});
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return "Timed out waiting for T3 Connect authorization.";
|
||||
const callback = this.redirectUriHostname ? ` for ${this.redirectUriHostname}` : "";
|
||||
return `Timed out after ${this.timeoutMillis}ms waiting for T3 Connect authorization${callback} (callback URI input length ${this.redirectUriInputLength}).`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -103,18 +281,21 @@ export type CloudCliTokenManagerError = typeof CloudCliTokenManagerError.Type;
|
||||
export class CloudCliTokenManager extends Context.Service<
|
||||
CloudCliTokenManager,
|
||||
{
|
||||
readonly get: Effect.Effect<PersistedToken, CloudCliTokenManagerError>;
|
||||
readonly getExisting: Effect.Effect<Option.Option<PersistedToken>, CloudCliTokenManagerError>;
|
||||
readonly hasCredential: Effect.Effect<boolean, CloudCliTokenManagerError>;
|
||||
readonly clear: Effect.Effect<void, CloudCliTokenManagerError>;
|
||||
readonly get: Effect.Effect<
|
||||
PersistedToken,
|
||||
| CloudCliCredentialRefreshError
|
||||
| CloudCliAuthorizationError
|
||||
| CloudCliAuthorizationTimeoutError
|
||||
>;
|
||||
readonly getExisting: Effect.Effect<
|
||||
Option.Option<PersistedToken>,
|
||||
CloudCliCredentialRefreshError
|
||||
>;
|
||||
readonly hasCredential: Effect.Effect<boolean, CloudCliCredentialReadError>;
|
||||
readonly clear: Effect.Effect<void, CloudCliCredentialRemovalError>;
|
||||
}
|
||||
>()("t3/cloud/CliTokenManager/CloudCliTokenManager") {}
|
||||
|
||||
const wrapError =
|
||||
<WrappedError extends CloudCliTokenManagerError>(makeError: (cause: unknown) => WrappedError) =>
|
||||
<A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, WrappedError, R> =>
|
||||
effect.pipe(Effect.mapError(makeError));
|
||||
|
||||
function stringToBytes(value: string): Uint8Array {
|
||||
return new TextEncoder().encode(value);
|
||||
}
|
||||
@@ -134,9 +315,15 @@ export const make = Effect.gen(function* () {
|
||||
return token;
|
||||
});
|
||||
|
||||
const clear = secrets
|
||||
.remove(CLOUD_CLI_OAUTH_TOKEN_SECRET)
|
||||
.pipe(wrapError((cause) => new CloudCliCredentialRemovalError({ cause })));
|
||||
const clear = secrets.remove(CLOUD_CLI_OAUTH_TOKEN_SECRET).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new CloudCliCredentialRemovalError({
|
||||
secretName: CLOUD_CLI_OAUTH_TOKEN_SECRET,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const read = Effect.fn("cloud.cli_token.read")(function* () {
|
||||
const encoded = yield* secrets.get(CLOUD_CLI_OAUTH_TOKEN_SECRET);
|
||||
@@ -162,21 +349,54 @@ export const make = Effect.gen(function* () {
|
||||
});
|
||||
|
||||
const refresh = Effect.fn("cloud.cli_token.refresh")(function* (token: PersistedToken) {
|
||||
const metadata = yield* cloudCliOAuthConfig;
|
||||
const metadata = yield* cloudCliOAuthConfig.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
CloudCliCredentialRefreshError.fromStage({
|
||||
stage: "load-oauth-config",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
return yield* exchangeToken(metadata, {
|
||||
grant_type: "refresh_token",
|
||||
refresh_token: token.refreshToken,
|
||||
client_id: metadata.clientId,
|
||||
});
|
||||
}).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
CloudCliCredentialRefreshError.fromStage({
|
||||
stage: "exchange-token",
|
||||
tokenEndpoint: metadata.tokenEndpoint,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
const login = Effect.fn("cloud.cli_token.login")(function* () {
|
||||
const metadata = yield* cloudCliOAuthConfig;
|
||||
const verifier = Encoding.encodeBase64Url(yield* crypto.randomBytes(32));
|
||||
const challenge = Encoding.encodeBase64Url(
|
||||
yield* crypto.digest("SHA-256", new TextEncoder().encode(verifier)),
|
||||
const metadata = yield* cloudCliOAuthConfig.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
CloudCliAuthorizationError.fromStage({
|
||||
stage: "load-oauth-config",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const { challenge, state, verifier } = yield* Effect.gen(function* () {
|
||||
const verifier = Encoding.encodeBase64Url(yield* crypto.randomBytes(32));
|
||||
const challenge = Encoding.encodeBase64Url(
|
||||
yield* crypto.digest("SHA-256", new TextEncoder().encode(verifier)),
|
||||
);
|
||||
const state = yield* crypto.randomUUIDv4;
|
||||
return { challenge, state, verifier };
|
||||
}).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
CloudCliAuthorizationError.fromStage({
|
||||
stage: "prepare-pkce",
|
||||
redirectUri: metadata.redirectUri,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const state = yield* crypto.randomUUIDv4;
|
||||
const callback = yield* Deferred.make<string>();
|
||||
const callbackRoute = HttpRouter.add(
|
||||
"GET",
|
||||
@@ -207,12 +427,21 @@ export const make = Effect.gen(function* () {
|
||||
}).pipe(
|
||||
Layer.provide(
|
||||
NodeHttpServer.layer(NodeHttp.createServer, {
|
||||
host: "127.0.0.1",
|
||||
port: 34338,
|
||||
host: CLOUD_CLI_OAUTH_CALLBACK_HOST,
|
||||
port: CLOUD_CLI_OAUTH_CALLBACK_PORT,
|
||||
disablePreemptiveShutdown: true,
|
||||
}),
|
||||
),
|
||||
Layer.build,
|
||||
Effect.mapError((cause) =>
|
||||
CloudCliAuthorizationError.fromStage({
|
||||
stage: "start-callback-server",
|
||||
redirectUri: metadata.redirectUri,
|
||||
callbackHost: CLOUD_CLI_OAUTH_CALLBACK_HOST,
|
||||
callbackPort: CLOUD_CLI_OAUTH_CALLBACK_PORT,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const authorizationUrl = new URL(metadata.authorizationEndpoint);
|
||||
authorizationUrl.searchParams.set("client_id", metadata.clientId);
|
||||
@@ -225,13 +454,16 @@ export const make = Effect.gen(function* () {
|
||||
yield* Console.log(`Open this URL to authorize T3 Connect:\n${authorizationUrl.toString()}\n`);
|
||||
const code = yield* Deferred.await(callback).pipe(
|
||||
Effect.timeout(CLOUD_CLI_OAUTH_CALLBACK_TIMEOUT),
|
||||
Effect.catchTag("TimeoutError", (cause) =>
|
||||
Effect.fail(
|
||||
new CloudCliAuthorizationTimeoutError({
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
Effect.catchTags({
|
||||
TimeoutError: (cause) =>
|
||||
Effect.fail(
|
||||
CloudCliAuthorizationTimeoutError.fromRedirectUri({
|
||||
redirectUri: metadata.redirectUri,
|
||||
timeoutMillis: Duration.toMillis(CLOUD_CLI_OAUTH_CALLBACK_TIMEOUT),
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
);
|
||||
return yield* exchangeToken(metadata, {
|
||||
grant_type: "authorization_code",
|
||||
@@ -239,26 +471,43 @@ export const make = Effect.gen(function* () {
|
||||
redirect_uri: metadata.redirectUri,
|
||||
client_id: metadata.clientId,
|
||||
code_verifier: verifier,
|
||||
});
|
||||
}).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
CloudCliAuthorizationError.fromStage({
|
||||
stage: "exchange-token",
|
||||
tokenEndpoint: metadata.tokenEndpoint,
|
||||
redirectUri: metadata.redirectUri,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
const getExistingNoLock = Effect.fn("cloud.cli_token.get_existing_no_lock")(function* () {
|
||||
const token = yield* read();
|
||||
const token = yield* read().pipe(
|
||||
Effect.mapError(CloudCliCredentialRefreshError.fromCredentialRead),
|
||||
);
|
||||
if (Option.isNone(token)) return token;
|
||||
const now = yield* Clock.currentTimeMillis;
|
||||
if (token.value.expiresAtEpochMs - CLOUD_CLI_OAUTH_REFRESH_EARLY_MS > now) {
|
||||
return token;
|
||||
}
|
||||
return Option.some(yield* refresh(token.value).pipe(Effect.flatMap(persist)));
|
||||
return Option.some(
|
||||
yield* refresh(token.value).pipe(
|
||||
Effect.flatMap((refreshed) =>
|
||||
persist(refreshed).pipe(
|
||||
Effect.mapError(CloudCliCredentialRefreshError.fromCredentialPersist),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
const getExisting = semaphore.withPermits(1)(
|
||||
getExistingNoLock().pipe(wrapError((cause) => new CloudCliCredentialRefreshError({ cause }))),
|
||||
);
|
||||
const getExisting = semaphore.withPermits(1)(getExistingNoLock());
|
||||
const hasCredential = semaphore.withPermits(1)(
|
||||
read().pipe(
|
||||
Effect.map(Option.isSome),
|
||||
wrapError((cause) => new CloudCliCredentialReadError({ cause })),
|
||||
Effect.mapError(CloudCliCredentialReadError.fromCredentialRead),
|
||||
),
|
||||
);
|
||||
const get = semaphore.withPermits(1)(
|
||||
@@ -266,8 +515,14 @@ export const make = Effect.gen(function* () {
|
||||
const token = yield* getExistingNoLock();
|
||||
return Option.isSome(token)
|
||||
? token.value
|
||||
: yield* Effect.scoped(login()).pipe(Effect.flatMap(persist));
|
||||
}).pipe(wrapError((cause) => new CloudCliAuthorizationError({ cause }))),
|
||||
: yield* Effect.scoped(login()).pipe(
|
||||
Effect.flatMap((authorized) =>
|
||||
persist(authorized).pipe(
|
||||
Effect.mapError(CloudCliAuthorizationError.fromCredentialPersist),
|
||||
),
|
||||
),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
return CloudCliTokenManager.of({ get, getExisting, hasCredential, clear });
|
||||
|
||||
@@ -66,7 +66,9 @@ it.layer(NodeServices.layer)("getOrCreateEnvironmentKeyPairFromSecretStore", (it
|
||||
Effect.flatMap(() =>
|
||||
Effect.fail(
|
||||
new ServerSecretStore.SecretStorePersistError({
|
||||
resource: "environment signing key pair",
|
||||
operation: "create",
|
||||
secretName: "cloud-link-ed25519-key-pair",
|
||||
secretPath: "cloud-link-ed25519-key-pair.bin",
|
||||
cause: PlatformError.systemError({
|
||||
_tag: "AlreadyExists",
|
||||
module: "FileSystem",
|
||||
@@ -87,4 +89,24 @@ it.layer(NodeServices.layer)("getOrCreateEnvironmentKeyPairFromSecretStore", (it
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("retains the secret name and decode cause for malformed keypairs", () =>
|
||||
Effect.gen(function* () {
|
||||
const secretStore = {
|
||||
get: () => Effect.succeed(Option.some(new TextEncoder().encode("not-json"))),
|
||||
set: unusedSecretStoreOperation,
|
||||
create: unusedSecretStoreOperation,
|
||||
getOrCreateRandom: unusedSecretStoreOperation,
|
||||
remove: unusedSecretStoreOperation,
|
||||
} satisfies ServerSecretStore.ServerSecretStore["Service"];
|
||||
|
||||
const error = yield* getOrCreateEnvironmentKeyPairFromSecretStore(secretStore).pipe(
|
||||
Effect.flip,
|
||||
);
|
||||
|
||||
assert.instanceOf(error, ServerSecretStore.SecretStoreDecodeError);
|
||||
assert.equal(error.secretName, "cloud-link-ed25519-key-pair");
|
||||
assert.exists(error.cause);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -27,17 +27,6 @@ function stringToBytes(value: string): Uint8Array {
|
||||
return new TextEncoder().encode(value);
|
||||
}
|
||||
|
||||
const KEY_PAIR_RESOURCE = "environment signing key pair";
|
||||
|
||||
const keyPairDecodeError = (cause: unknown): ServerSecretStore.SecretStoreDecodeError =>
|
||||
new ServerSecretStore.SecretStoreDecodeError({ resource: KEY_PAIR_RESOURCE, cause });
|
||||
|
||||
const keyPairEncodeError = (cause: unknown): ServerSecretStore.SecretStoreEncodeError =>
|
||||
new ServerSecretStore.SecretStoreEncodeError({ resource: KEY_PAIR_RESOURCE, cause });
|
||||
|
||||
const keyPairConcurrentReadError = (): ServerSecretStore.SecretStoreConcurrentReadError =>
|
||||
new ServerSecretStore.SecretStoreConcurrentReadError({ resource: KEY_PAIR_RESOURCE });
|
||||
|
||||
const readEnvironmentKeyPair = Effect.fn("readEnvironmentKeyPair")(function* (
|
||||
secrets: ServerSecretStore.ServerSecretStore["Service"],
|
||||
) {
|
||||
@@ -46,7 +35,13 @@ const readEnvironmentKeyPair = Effect.fn("readEnvironmentKeyPair")(function* (
|
||||
return Option.none<EnvironmentKeyPair>();
|
||||
}
|
||||
const decoded = yield* decodeEnvironmentKeyPair(bytesToString(encoded.value)).pipe(
|
||||
Effect.mapError(keyPairDecodeError),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ServerSecretStore.SecretStoreDecodeError({
|
||||
secretName: CLOUD_LINK_KEY_PAIR,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
return Option.some(decoded);
|
||||
});
|
||||
@@ -56,22 +51,35 @@ const persistEnvironmentKeyPair = Effect.fn("persistEnvironmentKeyPair")(functio
|
||||
keyPair: EnvironmentKeyPair,
|
||||
) {
|
||||
const encoded = yield* encodeEnvironmentKeyPair(keyPair).pipe(
|
||||
Effect.mapError(keyPairEncodeError),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ServerSecretStore.SecretStoreEncodeError({
|
||||
secretName: CLOUD_LINK_KEY_PAIR,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
return yield* secrets.create(CLOUD_LINK_KEY_PAIR, stringToBytes(encoded)).pipe(
|
||||
Effect.as(keyPair),
|
||||
Effect.catchIf(ServerSecretStore.isSecretStoreError, (error) =>
|
||||
ServerSecretStore.isSecretAlreadyExistsError(error)
|
||||
? readEnvironmentKeyPair(secrets).pipe(
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onSome: Effect.succeed,
|
||||
onNone: () => Effect.fail(keyPairConcurrentReadError()),
|
||||
}),
|
||||
),
|
||||
)
|
||||
: Effect.fail(error),
|
||||
),
|
||||
Effect.catchTags({
|
||||
SecretStorePersistError: (error) =>
|
||||
ServerSecretStore.isSecretAlreadyExistsError(error)
|
||||
? readEnvironmentKeyPair(secrets).pipe(
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onSome: Effect.succeed,
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
new ServerSecretStore.SecretStoreConcurrentReadError({
|
||||
secretName: CLOUD_LINK_KEY_PAIR,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
),
|
||||
)
|
||||
: Effect.fail(error),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@@ -1,23 +1,45 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as ConfigProvider from "effect/ConfigProvider";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Logger from "effect/Logger";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Tracer from "effect/Tracer";
|
||||
import { HttpClient, HttpServerRequest } from "effect/unstable/http";
|
||||
import * as HttpClient from "effect/unstable/http/HttpClient";
|
||||
import * as HttpClientError from "effect/unstable/http/HttpClientError";
|
||||
import * as HttpClientRequest from "effect/unstable/http/HttpClientRequest";
|
||||
import * as HttpClientResponse from "effect/unstable/http/HttpClientResponse";
|
||||
import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
|
||||
import { EnvironmentHttpInternalServerError } from "@t3tools/contracts";
|
||||
|
||||
import { RelayClientTracer } from "@t3tools/shared/relayTracing";
|
||||
import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
|
||||
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
|
||||
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
|
||||
import * as CliTokenManager from "./CliTokenManager.ts";
|
||||
import { consumeCloudReplayGuards, reconcileDesiredCloudLink } from "./http.ts";
|
||||
import {
|
||||
CloudRelayRequestError,
|
||||
consumeCloudReplayGuards,
|
||||
reconcileDesiredCloudLink,
|
||||
} from "./http.ts";
|
||||
import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts";
|
||||
import { traceAuthenticatedRelayRequest, traceRelayRequest } from "./traceRelayRequest.ts";
|
||||
|
||||
const encodeEnvironmentHttpInternalServerError = Schema.encodeUnknownSync(
|
||||
EnvironmentHttpInternalServerError,
|
||||
);
|
||||
const decodeEnvironmentHttpInternalServerError = Schema.decodeUnknownSync(
|
||||
EnvironmentHttpInternalServerError,
|
||||
);
|
||||
|
||||
const storeFailure = (tag: "AlreadyExists" | "PermissionDenied") =>
|
||||
new ServerSecretStore.SecretStorePersistError({
|
||||
resource: "cloud replay guard",
|
||||
operation: "create",
|
||||
secretName: "cloud replay guard",
|
||||
secretPath: "cloud-replay-guard.bin",
|
||||
cause: PlatformError.systemError({
|
||||
_tag: tag,
|
||||
module: "FileSystem",
|
||||
@@ -40,6 +62,56 @@ function makeSecretStore(
|
||||
};
|
||||
}
|
||||
|
||||
function reconcileWith(input: {
|
||||
readonly getExisting: CliTokenManager.CloudCliTokenManager["Service"]["getExisting"];
|
||||
readonly httpClient?: HttpClient.HttpClient;
|
||||
readonly secretStore?: ServerSecretStore.ServerSecretStore["Service"];
|
||||
readonly env?: Readonly<Record<string, string>>;
|
||||
}) {
|
||||
return reconcileDesiredCloudLink("http://127.0.0.1:3774").pipe(
|
||||
Effect.provideService(
|
||||
ServerSecretStore.ServerSecretStore,
|
||||
input.secretStore ?? makeSecretStore(unusedSecretStoreOperation),
|
||||
),
|
||||
Effect.provideService(
|
||||
ServerEnvironment.ServerEnvironment,
|
||||
ServerEnvironment.ServerEnvironment.of({
|
||||
getEnvironmentId: unusedSecretStoreOperation(),
|
||||
getDescriptor: unusedSecretStoreOperation(),
|
||||
}),
|
||||
),
|
||||
Effect.provideService(
|
||||
ManagedEndpointRuntime.CloudManagedEndpointRuntime,
|
||||
ManagedEndpointRuntime.CloudManagedEndpointRuntime.of({
|
||||
applyConfig: unusedSecretStoreOperation,
|
||||
} satisfies ManagedEndpointRuntime.CloudManagedEndpointRuntime["Service"]),
|
||||
),
|
||||
Effect.provideService(
|
||||
EnvironmentAuth.EnvironmentAuth,
|
||||
EnvironmentAuth.EnvironmentAuth.of({} as EnvironmentAuth.EnvironmentAuth["Service"]),
|
||||
),
|
||||
Effect.provideService(
|
||||
CliTokenManager.CloudCliTokenManager,
|
||||
CliTokenManager.CloudCliTokenManager.of({
|
||||
get: unusedSecretStoreOperation(),
|
||||
getExisting: input.getExisting,
|
||||
hasCredential: unusedSecretStoreOperation(),
|
||||
clear: unusedSecretStoreOperation(),
|
||||
}),
|
||||
),
|
||||
Effect.provideService(
|
||||
HttpClient.HttpClient,
|
||||
input.httpClient ?? HttpClient.make(() => unusedSecretStoreOperation()),
|
||||
),
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
NodeServices.layer,
|
||||
ConfigProvider.layer(ConfigProvider.fromEnv({ env: input.env ?? {} })),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
it("preserves messages surfaced by cloud 500 responses", () => {
|
||||
const cause = new Error("cloud operation failed");
|
||||
|
||||
@@ -93,6 +165,84 @@ describe("consumeCloudReplayGuards", () => {
|
||||
);
|
||||
});
|
||||
|
||||
describe("CloudRelayRequestError", () => {
|
||||
it("classifies response failures without deriving its message from the cause", () => {
|
||||
const requestUrl =
|
||||
"https://relay-user:[email protected]/private/environment-links?token=relay-secret#relay-fragment";
|
||||
const request = HttpClientRequest.post(requestUrl);
|
||||
const response = HttpClientResponse.fromWeb(
|
||||
request,
|
||||
new Response("sensitive upstream response", { status: 502 }),
|
||||
);
|
||||
const upstreamCause = new Error("sensitive upstream response details");
|
||||
const cause = new HttpClientError.HttpClientError({
|
||||
reason: new HttpClientError.StatusCodeError({
|
||||
request,
|
||||
response,
|
||||
cause: upstreamCause,
|
||||
}),
|
||||
});
|
||||
|
||||
const error = CloudRelayRequestError.fromClientFailure({
|
||||
operation: "create-environment-link",
|
||||
url: request.url,
|
||||
cause,
|
||||
});
|
||||
|
||||
expect(error).toMatchObject({
|
||||
operation: "create-environment-link",
|
||||
phase: "check-response-status",
|
||||
method: "POST",
|
||||
requestUrlInputLength: requestUrl.length,
|
||||
requestUrlProtocol: "https:",
|
||||
requestUrlHostname: "relay.example.test",
|
||||
responseStatus: 502,
|
||||
cause,
|
||||
});
|
||||
expect(error.cause).toBe(cause);
|
||||
expect(error).not.toHaveProperty("url");
|
||||
expect(error.message).toBe(
|
||||
"T3 Connect relay create-environment-link failed during check-response-status with response status 502.",
|
||||
);
|
||||
expect(error.message).not.toContain(upstreamCause.message);
|
||||
for (const secret of [
|
||||
"relay-user",
|
||||
"relay-password",
|
||||
"/private/environment-links",
|
||||
"relay-secret",
|
||||
"relay-fragment",
|
||||
]) {
|
||||
expect(error.message).not.toContain(secret);
|
||||
expect(Object.values(error).join(" ")).not.toContain(secret);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps internal causes out of encoded HTTP error bodies", () => {
|
||||
const cause = new Error("private upstream detail");
|
||||
const error = new EnvironmentHttpInternalServerError({
|
||||
operation: "generate_link_proof",
|
||||
cause,
|
||||
});
|
||||
|
||||
expect(error.cause).toBe(cause);
|
||||
expect(encodeEnvironmentHttpInternalServerError(error)).toEqual({
|
||||
_tag: "EnvironmentHttpInternalServerError",
|
||||
operation: "generate_link_proof",
|
||||
message: "Could not generate environment link proof.",
|
||||
});
|
||||
});
|
||||
|
||||
it("decodes legacy message-only HTTP errors during rolling deployments", () => {
|
||||
const error = decodeEnvironmentHttpInternalServerError({
|
||||
_tag: "EnvironmentHttpInternalServerError",
|
||||
message: "Legacy environment server failure.",
|
||||
});
|
||||
|
||||
expect(error.operation).toBeUndefined();
|
||||
expect(error.message).toBe("Legacy environment server failure.");
|
||||
});
|
||||
|
||||
describe("relay request tracing", () => {
|
||||
it.effect("does not accept an unauthenticated request trace parent", () =>
|
||||
Effect.gen(function* () {
|
||||
@@ -160,48 +310,127 @@ describe("relay request tracing", () => {
|
||||
describe("reconcileDesiredCloudLink", () => {
|
||||
it.effect("requires stored CLI authorization without exposing an HTTP endpoint", () =>
|
||||
Effect.gen(function* () {
|
||||
const error = yield* Effect.flip(reconcileDesiredCloudLink("http://127.0.0.1:3774"));
|
||||
const error = yield* Effect.flip(
|
||||
reconcileWith({ getExisting: Effect.succeed(Option.none()) }),
|
||||
);
|
||||
|
||||
expect(error).toMatchObject({
|
||||
_tag: "EnvironmentHttpUnauthorizedError",
|
||||
reason: "cloud_cli_authorization_required",
|
||||
message: "Run `t3 connect link` to authorize this environment.",
|
||||
});
|
||||
}).pipe(
|
||||
Effect.provideService(
|
||||
ServerSecretStore.ServerSecretStore,
|
||||
makeSecretStore(unusedSecretStoreOperation),
|
||||
),
|
||||
Effect.provideService(
|
||||
ServerEnvironment.ServerEnvironment,
|
||||
ServerEnvironment.ServerEnvironment.of({
|
||||
getEnvironmentId: unusedSecretStoreOperation(),
|
||||
getDescriptor: unusedSecretStoreOperation(),
|
||||
}),
|
||||
),
|
||||
Effect.provideService(
|
||||
ManagedEndpointRuntime.CloudManagedEndpointRuntime,
|
||||
ManagedEndpointRuntime.CloudManagedEndpointRuntime.of({
|
||||
applyConfig: unusedSecretStoreOperation,
|
||||
} satisfies ManagedEndpointRuntime.CloudManagedEndpointRuntime["Service"]),
|
||||
),
|
||||
Effect.provideService(
|
||||
EnvironmentAuth.EnvironmentAuth,
|
||||
EnvironmentAuth.EnvironmentAuth.of({} as EnvironmentAuth.EnvironmentAuth["Service"]),
|
||||
),
|
||||
Effect.provideService(
|
||||
CliTokenManager.CloudCliTokenManager,
|
||||
CliTokenManager.CloudCliTokenManager.of({
|
||||
get: unusedSecretStoreOperation(),
|
||||
getExisting: Effect.succeed(Option.none()),
|
||||
hasCredential: unusedSecretStoreOperation(),
|
||||
clear: unusedSecretStoreOperation(),
|
||||
}),
|
||||
),
|
||||
Effect.provideService(
|
||||
HttpClient.HttpClient,
|
||||
HttpClient.make(() => unusedSecretStoreOperation()),
|
||||
),
|
||||
Effect.provide(NodeServices.layer),
|
||||
),
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("attributes link-proof secret failures to proof generation", () => {
|
||||
const cause = new Error("private secret-store detail");
|
||||
const secretFailure = new ServerSecretStore.SecretStoreReadError({
|
||||
secretName: "environment-key-pair",
|
||||
secretPath: "environment-key-pair.json",
|
||||
cause,
|
||||
});
|
||||
const httpClient = HttpClient.make((request) =>
|
||||
Effect.succeed(
|
||||
HttpClientResponse.fromWeb(
|
||||
request,
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
challenge: "relay-link-challenge",
|
||||
expiresAt: "2099-01-01T00:00:00.000Z",
|
||||
}),
|
||||
{ status: 200, headers: { "content-type": "application/json" } },
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
const secretStore = makeSecretStore(unusedSecretStoreOperation);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const error = yield* Effect.flip(
|
||||
reconcileWith({
|
||||
getExisting: Effect.succeed(
|
||||
Option.some({
|
||||
accessToken: "access-token",
|
||||
refreshToken: "refresh-token",
|
||||
expiresAtEpochMs: Number.MAX_SAFE_INTEGER,
|
||||
}),
|
||||
),
|
||||
httpClient,
|
||||
secretStore: {
|
||||
...secretStore,
|
||||
get: () => Effect.fail(secretFailure),
|
||||
},
|
||||
env: { T3CODE_RELAY_URL: "https://relay.example.test" },
|
||||
}),
|
||||
);
|
||||
|
||||
expect(error).toMatchObject({
|
||||
_tag: "EnvironmentHttpInternalServerError",
|
||||
operation: "generate_link_proof",
|
||||
cause: secretFailure,
|
||||
});
|
||||
expect(error.message).toBe("Could not generate environment link proof.");
|
||||
expect(error.cause).toBe(secretFailure);
|
||||
expect(error.message).not.toContain(cause.message);
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("redacts relay transport failures behind a stable structural message", () => {
|
||||
const transportCause = new Error("upstream included a sensitive database password");
|
||||
const capturedLogs: Array<ReadonlyArray<unknown>> = [];
|
||||
const logger = Logger.make(({ message }) => {
|
||||
capturedLogs.push(Array.isArray(message) ? message : [message]);
|
||||
});
|
||||
const httpClient = HttpClient.make((request) =>
|
||||
Effect.fail(
|
||||
new HttpClientError.HttpClientError({
|
||||
reason: new HttpClientError.TransportError({ request, cause: transportCause }),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const error = yield* Effect.flip(
|
||||
reconcileWith({
|
||||
getExisting: Effect.succeed(
|
||||
Option.some({
|
||||
accessToken: "access-token",
|
||||
refreshToken: "refresh-token",
|
||||
expiresAtEpochMs: Number.MAX_SAFE_INTEGER,
|
||||
}),
|
||||
),
|
||||
httpClient,
|
||||
env: { T3CODE_RELAY_URL: "https://relay.example.test" },
|
||||
}).pipe(Effect.provide(Logger.layer([logger], { mergeWithExisting: false }))),
|
||||
);
|
||||
|
||||
expect(error).toMatchObject({
|
||||
_tag: "EnvironmentHttpInternalServerError",
|
||||
operation: "relay_request",
|
||||
relayOperation: "create-link-challenge",
|
||||
relayPhase: "send-request",
|
||||
message: "T3 Connect relay create-link-challenge failed during send-request.",
|
||||
cause: {
|
||||
_tag: "CloudRelayRequestError",
|
||||
operation: "create-link-challenge",
|
||||
phase: "send-request",
|
||||
},
|
||||
});
|
||||
expect(error.message).not.toContain(transportCause.message);
|
||||
expect(capturedLogs).toHaveLength(1);
|
||||
const logFields = capturedLogs[0]?.find(
|
||||
(value): value is Record<string, unknown> => typeof value === "object" && value !== null,
|
||||
);
|
||||
expect(logFields).toMatchObject({
|
||||
operation: "relay_request",
|
||||
relayOperation: "create-link-challenge",
|
||||
relayPhase: "send-request",
|
||||
causeTag: "CloudRelayRequestError",
|
||||
});
|
||||
expect(logFields).not.toHaveProperty("cause");
|
||||
expect(capturedLogs[0]?.filter((value) => typeof value === "string").join(" ")).not.toContain(
|
||||
transportCause.message,
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
+334
-117
@@ -9,7 +9,10 @@ import {
|
||||
EnvironmentHttpApi,
|
||||
EnvironmentHttpBadRequestError,
|
||||
EnvironmentHttpConflictError,
|
||||
type EnvironmentHttpInternalOperation,
|
||||
EnvironmentHttpInternalServerError,
|
||||
EnvironmentHttpRelayOperation,
|
||||
EnvironmentHttpRelayPhase,
|
||||
EnvironmentHttpUnauthorizedError,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
@@ -41,6 +44,7 @@ import {
|
||||
verifyRelayJwt,
|
||||
} from "@t3tools/shared/relayJwt";
|
||||
import { isSecureRelayUrl } from "@t3tools/shared/relayUrl";
|
||||
import { getUrlDiagnostics } from "@t3tools/shared/urlDiagnostics";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Duration from "effect/Duration";
|
||||
@@ -48,8 +52,13 @@ import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as HttpEffect from "effect/unstable/http/HttpEffect";
|
||||
import { HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
|
||||
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
|
||||
import * as HttpBody from "effect/unstable/http/HttpBody";
|
||||
import * as HttpClient from "effect/unstable/http/HttpClient";
|
||||
import * as HttpClientError from "effect/unstable/http/HttpClientError";
|
||||
import * as HttpClientRequest from "effect/unstable/http/HttpClientRequest";
|
||||
import * as HttpClientResponse from "effect/unstable/http/HttpClientResponse";
|
||||
import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
|
||||
import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";
|
||||
import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
|
||||
|
||||
import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
|
||||
@@ -85,26 +94,145 @@ const CLOUD_CREDENTIAL_RESPONSE_HEADERS = {
|
||||
pragma: "no-cache",
|
||||
} as const;
|
||||
|
||||
export class CloudRelayConfigurationError extends Schema.TaggedErrorClass<CloudRelayConfigurationError>()(
|
||||
"CloudRelayConfigurationError",
|
||||
{
|
||||
configKey: Schema.Literal("T3CODE_RELAY_URL"),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `${this.configKey} must be configured as a secure absolute HTTPS origin.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class CloudRelayRequestError extends Schema.TaggedErrorClass<CloudRelayRequestError>()(
|
||||
"CloudRelayRequestError",
|
||||
{
|
||||
operation: EnvironmentHttpRelayOperation,
|
||||
phase: EnvironmentHttpRelayPhase,
|
||||
method: Schema.Literal("POST"),
|
||||
requestUrlInputLength: Schema.Number,
|
||||
requestUrlProtocol: Schema.optionalKey(Schema.String),
|
||||
requestUrlHostname: Schema.optionalKey(Schema.String),
|
||||
responseStatus: Schema.optional(Schema.Number),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
static fromClientFailure(input: {
|
||||
readonly operation: CloudRelayRequestError["operation"];
|
||||
readonly url: string;
|
||||
readonly cause: HttpBody.HttpBodyError | HttpClientError.HttpClientError | Schema.SchemaError;
|
||||
readonly responseStatus?: number;
|
||||
}): CloudRelayRequestError {
|
||||
const diagnostics = getUrlDiagnostics(input.url);
|
||||
const context = {
|
||||
operation: input.operation,
|
||||
method: "POST" as const,
|
||||
requestUrlInputLength: diagnostics.inputLength,
|
||||
...(diagnostics.protocol === undefined ? {} : { requestUrlProtocol: diagnostics.protocol }),
|
||||
...(diagnostics.hostname === undefined ? {} : { requestUrlHostname: diagnostics.hostname }),
|
||||
};
|
||||
if (input.cause._tag === "SchemaError") {
|
||||
return new CloudRelayRequestError({
|
||||
...context,
|
||||
phase: "decode-response",
|
||||
...(input.responseStatus === undefined ? {} : { responseStatus: input.responseStatus }),
|
||||
cause: input.cause,
|
||||
});
|
||||
}
|
||||
|
||||
if (!HttpClientError.isHttpClientError(input.cause)) {
|
||||
return new CloudRelayRequestError({
|
||||
...context,
|
||||
phase: "encode-request",
|
||||
cause: input.cause,
|
||||
});
|
||||
}
|
||||
|
||||
const phase: CloudRelayRequestError["phase"] = (() => {
|
||||
switch (input.cause.reason._tag) {
|
||||
case "EncodeError":
|
||||
return "encode-request";
|
||||
case "TransportError":
|
||||
case "InvalidUrlError":
|
||||
return "send-request";
|
||||
case "StatusCodeError":
|
||||
return "check-response-status";
|
||||
case "DecodeError":
|
||||
case "EmptyBodyError":
|
||||
return "decode-response";
|
||||
}
|
||||
})();
|
||||
|
||||
return new CloudRelayRequestError({
|
||||
...context,
|
||||
phase,
|
||||
...(input.cause.response === undefined
|
||||
? input.responseStatus === undefined
|
||||
? {}
|
||||
: { responseStatus: input.responseStatus }
|
||||
: { responseStatus: input.cause.response.status }),
|
||||
cause: input.cause,
|
||||
});
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
const responseStatus =
|
||||
this.responseStatus === undefined ? "" : ` with response status ${this.responseStatus}`;
|
||||
return `T3 Connect relay ${this.operation} failed during ${this.phase}${responseStatus}.`;
|
||||
}
|
||||
}
|
||||
|
||||
const appendCloudCredentialResponseHeaders = HttpEffect.appendPreResponseHandler(
|
||||
(_request, response) =>
|
||||
Effect.succeed(HttpServerResponse.setHeaders(response, CLOUD_CREDENTIAL_RESPONSE_HEADERS)),
|
||||
);
|
||||
|
||||
const failEnvironmentCloudInternalError =
|
||||
(message: string) =>
|
||||
(cause: unknown): Effect.Effect<never, EnvironmentHttpInternalServerError> =>
|
||||
Effect.logError(message, { cause }).pipe(
|
||||
Effect.flatMap(() => Effect.fail(new EnvironmentHttpInternalServerError({ message }))),
|
||||
);
|
||||
function errorDiagnosticTag(cause: unknown): string {
|
||||
if (
|
||||
typeof cause === "object" &&
|
||||
cause !== null &&
|
||||
"_tag" in cause &&
|
||||
typeof cause._tag === "string"
|
||||
) {
|
||||
return cause._tag;
|
||||
}
|
||||
if (cause instanceof Error) return cause.name;
|
||||
return typeof cause;
|
||||
}
|
||||
|
||||
const failCloudCliTokenManagerError = (error: CliTokenManager.CloudCliTokenManagerError) =>
|
||||
failEnvironmentCloudInternalError(error.message)(error);
|
||||
type EnvironmentCloudInternalErrorContext =
|
||||
| Exclude<EnvironmentHttpInternalOperation, "relay_request">
|
||||
| {
|
||||
readonly operation: "relay_request";
|
||||
readonly relayOperation: CloudRelayRequestError["operation"];
|
||||
readonly relayPhase: CloudRelayRequestError["phase"];
|
||||
readonly responseStatus?: number;
|
||||
};
|
||||
|
||||
const failEnvironmentCloudInternalError =
|
||||
(context: EnvironmentCloudInternalErrorContext) =>
|
||||
(cause: unknown): Effect.Effect<never, EnvironmentHttpInternalServerError> => {
|
||||
const error =
|
||||
typeof context === "string"
|
||||
? new EnvironmentHttpInternalServerError({ operation: context, cause })
|
||||
: new EnvironmentHttpInternalServerError({ ...context, cause });
|
||||
const logContext =
|
||||
typeof context === "string"
|
||||
? { operation: context, causeTag: errorDiagnosticTag(cause) }
|
||||
: { ...context, causeTag: errorDiagnosticTag(cause) };
|
||||
return Effect.logError(error.message, logContext).pipe(
|
||||
Effect.flatMap(() => Effect.fail(error)),
|
||||
);
|
||||
};
|
||||
|
||||
const requireRelayUrl = relayUrlConfig.pipe(
|
||||
Effect.mapError(
|
||||
() =>
|
||||
new EnvironmentHttpInternalServerError({
|
||||
message: "T3CODE_RELAY_URL must be configured as a secure absolute HTTPS origin.",
|
||||
(cause) =>
|
||||
new CloudRelayConfigurationError({
|
||||
configKey: "T3CODE_RELAY_URL",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -126,11 +254,12 @@ export function consumeCloudReplayGuards(input: {
|
||||
input.names.map((name) =>
|
||||
input.secrets.create(name, input.value).pipe(
|
||||
Effect.as(true),
|
||||
Effect.catchIf(ServerSecretStore.isSecretStoreError, (error) =>
|
||||
ServerSecretStore.isSecretAlreadyExistsError(error)
|
||||
? Effect.succeed(false)
|
||||
: Effect.fail(error),
|
||||
),
|
||||
Effect.catchTags({
|
||||
SecretStorePersistError: (error) =>
|
||||
ServerSecretStore.isSecretAlreadyExistsError(error)
|
||||
? Effect.succeed(false)
|
||||
: Effect.fail(error),
|
||||
}),
|
||||
),
|
||||
),
|
||||
{ concurrency: input.names.length },
|
||||
@@ -153,9 +282,10 @@ function validateCloudMintPublicKey(
|
||||
): Effect.Effect<void, EnvironmentHttpBadRequestError> {
|
||||
return Effect.try({
|
||||
try: () => NodeCrypto.createPublicKey(publicKey.replace(/\\n/g, "\n")),
|
||||
catch: () =>
|
||||
catch: (cause) =>
|
||||
new EnvironmentHttpBadRequestError({
|
||||
message: "Cloud mint public key must be a valid Ed25519 public key.",
|
||||
reason: "invalid_cloud_mint_public_key",
|
||||
cause,
|
||||
}),
|
||||
}).pipe(
|
||||
Effect.flatMap((key) =>
|
||||
@@ -163,7 +293,7 @@ function validateCloudMintPublicKey(
|
||||
? Effect.void
|
||||
: Effect.fail(
|
||||
new EnvironmentHttpBadRequestError({
|
||||
message: "Cloud mint public key must be a valid Ed25519 public key.",
|
||||
reason: "invalid_cloud_mint_public_key",
|
||||
}),
|
||||
),
|
||||
),
|
||||
@@ -176,28 +306,28 @@ function validateRelayConfigPayload(
|
||||
if (!isSecureRelayUrl(payload.relayUrl)) {
|
||||
return Effect.fail(
|
||||
new EnvironmentHttpBadRequestError({
|
||||
message: "Relay URL must be a secure absolute HTTPS URL.",
|
||||
reason: "invalid_relay_url",
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (payload.relayIssuer !== undefined && !isSecureRelayUrl(payload.relayIssuer)) {
|
||||
return Effect.fail(
|
||||
new EnvironmentHttpBadRequestError({
|
||||
message: "Relay issuer must be a secure absolute HTTPS URL.",
|
||||
reason: "invalid_relay_issuer",
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (payload.environmentCredential.trim().length === 0) {
|
||||
return Effect.fail(
|
||||
new EnvironmentHttpBadRequestError({
|
||||
message: "Relay environment credential is required.",
|
||||
reason: "missing_relay_environment_credential",
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (payload.cloudUserId.trim().length === 0) {
|
||||
return Effect.fail(
|
||||
new EnvironmentHttpBadRequestError({
|
||||
message: "Cloud user id is required.",
|
||||
reason: "missing_cloud_user_id",
|
||||
}),
|
||||
);
|
||||
}
|
||||
@@ -207,7 +337,7 @@ function validateRelayConfigPayload(
|
||||
function validateLinkedCloudUser(input: {
|
||||
readonly secrets: ServerSecretStore.ServerSecretStore["Service"];
|
||||
readonly cloudUserId: string;
|
||||
}): Effect.Effect<void, EnvironmentAuth.ServerAuthInternalError | EnvironmentHttpConflictError> {
|
||||
}) {
|
||||
return input.secrets.get(CLOUD_LINKED_USER_ID).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
@@ -224,17 +354,14 @@ function validateLinkedCloudUser(input: {
|
||||
? Effect.void
|
||||
: Effect.fail(
|
||||
new EnvironmentHttpConflictError({
|
||||
message:
|
||||
"This environment is already linked to a different cloud account. Unlink it before switching accounts.",
|
||||
reason: "linked_to_different_cloud_account",
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
function readInstalledCloudUserId(
|
||||
secrets: ServerSecretStore.ServerSecretStore["Service"],
|
||||
): Effect.Effect<string, EnvironmentAuth.ServerAuthInternalError> {
|
||||
function readInstalledCloudUserId(secrets: ServerSecretStore.ServerSecretStore["Service"]) {
|
||||
return secrets.get(CLOUD_LINKED_USER_ID).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
@@ -359,7 +486,7 @@ const makeCloudLinkProof = Effect.fn("environment.cloud.makeLinkProof")(function
|
||||
})
|
||||
) {
|
||||
return yield* new EnvironmentHttpBadRequestError({
|
||||
message: "Invalid managed endpoint origin.",
|
||||
reason: "invalid_managed_endpoint_origin",
|
||||
});
|
||||
}
|
||||
const now = yield* DateTime.now;
|
||||
@@ -402,24 +529,23 @@ const cloudLinkProofHandler = Effect.fn("environment.cloud.linkProof")(
|
||||
const requestUrl = requestAbsoluteUrl(httpRequest);
|
||||
if (requestUrl === null || hasForwardedAuthorityHeaders(httpRequest)) {
|
||||
return yield* new EnvironmentHttpBadRequestError({
|
||||
message: "Invalid managed endpoint origin.",
|
||||
reason: "invalid_managed_endpoint_origin",
|
||||
});
|
||||
}
|
||||
const proof = yield* makeCloudLinkProof(dependencies, request, requestUrl);
|
||||
yield* appendCloudCredentialResponseHeaders;
|
||||
return proof satisfies RelayEnvironmentLinkProof;
|
||||
},
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
|
||||
failEnvironmentCloudInternalError(error.message)(error),
|
||||
),
|
||||
Effect.catchIf(
|
||||
ServerSecretStore.isSecretStoreError,
|
||||
failEnvironmentCloudInternalError("Could not generate environment link proof."),
|
||||
),
|
||||
Effect.catchTag(
|
||||
"PlatformError",
|
||||
failEnvironmentCloudInternalError("Could not generate environment link proof."),
|
||||
),
|
||||
Effect.catchTags({
|
||||
ServerAuthCloudLinkJwtSigningError: (error) =>
|
||||
failEnvironmentCloudInternalError("sign_cloud_link_jwt")(error),
|
||||
SecretStoreReadError: failEnvironmentCloudInternalError("generate_link_proof"),
|
||||
SecretStoreDecodeError: failEnvironmentCloudInternalError("generate_link_proof"),
|
||||
SecretStoreEncodeError: failEnvironmentCloudInternalError("generate_link_proof"),
|
||||
SecretStorePersistError: failEnvironmentCloudInternalError("generate_link_proof"),
|
||||
SecretStoreConcurrentReadError: failEnvironmentCloudInternalError("generate_link_proof"),
|
||||
PlatformError: failEnvironmentCloudInternalError("generate_link_proof"),
|
||||
}),
|
||||
);
|
||||
|
||||
const applyCloudRelayConfig = Effect.fn("environment.cloud.applyRelayConfig")(function* (
|
||||
@@ -439,7 +565,6 @@ const applyCloudRelayConfig = Effect.fn("environment.cloud.applyRelayConfig")(fu
|
||||
endpointRuntimeStatus.status === "disabled" || endpointRuntimeStatus.status === "running";
|
||||
if (!ok) {
|
||||
return yield* new EnvironmentCloudEndpointUnavailableError({
|
||||
message: "Managed endpoint runtime could not be started.",
|
||||
endpointRuntimeStatus,
|
||||
});
|
||||
}
|
||||
@@ -472,22 +597,22 @@ const cloudRelayConfigHandler = Effect.fn("environment.cloud.relayConfig")(
|
||||
yield* requireEnvironmentScope(AuthRelayWriteScope);
|
||||
return yield* applyCloudRelayConfig(dependencies, payload);
|
||||
},
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
|
||||
failEnvironmentCloudInternalError(error.message)(error),
|
||||
),
|
||||
Effect.catchIf(
|
||||
ServerSecretStore.isSecretStoreError,
|
||||
failEnvironmentCloudInternalError("Could not persist environment relay configuration."),
|
||||
),
|
||||
Effect.catchTag(
|
||||
"SchemaError",
|
||||
failEnvironmentCloudInternalError("Could not persist environment relay configuration."),
|
||||
),
|
||||
Effect.catchTags({
|
||||
ServerAuthLinkedCloudAccountVerificationError: (error) =>
|
||||
failEnvironmentCloudInternalError("verify_linked_cloud_account")(error),
|
||||
SecretStoreTemporaryPathGenerationError: failEnvironmentCloudInternalError(
|
||||
"persist_relay_configuration",
|
||||
),
|
||||
SecretStorePersistError: failEnvironmentCloudInternalError("persist_relay_configuration"),
|
||||
SecretStoreRemoveError: failEnvironmentCloudInternalError("persist_relay_configuration"),
|
||||
SchemaError: failEnvironmentCloudInternalError("persist_relay_configuration"),
|
||||
}),
|
||||
);
|
||||
|
||||
const relayClientRequest = <A>(
|
||||
dependencies: CloudHttpDependencies,
|
||||
input: {
|
||||
readonly operation: CloudRelayRequestError["operation"];
|
||||
readonly url: string;
|
||||
readonly token: string;
|
||||
readonly payload: unknown;
|
||||
@@ -497,14 +622,46 @@ const relayClientRequest = <A>(
|
||||
HttpClientRequest.post(input.url).pipe(
|
||||
HttpClientRequest.bearerToken(input.token),
|
||||
HttpClientRequest.bodyJson(input.payload),
|
||||
Effect.flatMap(dependencies.httpClient.execute),
|
||||
Effect.flatMap(HttpClientResponse.filterStatusOk),
|
||||
Effect.flatMap(HttpClientResponse.schemaBodyJson(input.schema)),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new EnvironmentHttpInternalServerError({
|
||||
message: `T3 Connect relay request failed: ${String(cause)}`,
|
||||
}),
|
||||
Effect.mapError((cause) =>
|
||||
CloudRelayRequestError.fromClientFailure({
|
||||
operation: input.operation,
|
||||
url: input.url,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.flatMap((request) =>
|
||||
dependencies.httpClient.execute(request).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
CloudRelayRequestError.fromClientFailure({
|
||||
operation: input.operation,
|
||||
url: input.url,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
Effect.flatMap((response) =>
|
||||
HttpClientResponse.filterStatusOk(response).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
CloudRelayRequestError.fromClientFailure({
|
||||
operation: input.operation,
|
||||
url: input.url,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
Effect.flatMap((response) =>
|
||||
HttpClientResponse.schemaBodyJson(input.schema)(response).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
CloudRelayRequestError.fromClientFailure({
|
||||
operation: input.operation,
|
||||
url: input.url,
|
||||
responseStatus: response.status,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
withRelayClientTracing,
|
||||
);
|
||||
@@ -513,14 +670,15 @@ const reconcileDesiredCloudLinkWith = Effect.fn("environment.cloud.reconcileDesi
|
||||
function* (dependencies: CloudHttpDependencies, localOrigin: string) {
|
||||
const localUrl = yield* Effect.try({
|
||||
try: () => new URL(localOrigin),
|
||||
catch: () =>
|
||||
catch: (cause) =>
|
||||
new EnvironmentHttpBadRequestError({
|
||||
message: "Could not resolve local environment origin.",
|
||||
reason: "invalid_local_environment_origin",
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
if (localUrl.origin !== localOrigin) {
|
||||
return yield* new EnvironmentHttpBadRequestError({
|
||||
message: "Could not resolve local environment origin.",
|
||||
reason: "invalid_local_environment_origin",
|
||||
});
|
||||
}
|
||||
const localWsOrigin = localOrigin.replace(/^http/u, "ws");
|
||||
@@ -530,7 +688,7 @@ const reconcileDesiredCloudLinkWith = Effect.fn("environment.cloud.reconcileDesi
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
new EnvironmentHttpUnauthorizedError({
|
||||
message: "Run `t3 connect link` to authorize this environment.",
|
||||
reason: "cloud_cli_authorization_required",
|
||||
}),
|
||||
),
|
||||
onSome: Effect.succeed,
|
||||
@@ -539,6 +697,7 @@ const reconcileDesiredCloudLinkWith = Effect.fn("environment.cloud.reconcileDesi
|
||||
);
|
||||
const relayUrl = yield* requireRelayUrl;
|
||||
const challenge = yield* relayClientRequest(dependencies, {
|
||||
operation: "create-link-challenge",
|
||||
url: `${relayUrl}/v1/client/environment-link-challenges`,
|
||||
token: token.accessToken,
|
||||
payload: {
|
||||
@@ -564,8 +723,20 @@ const reconcileDesiredCloudLinkWith = Effect.fn("environment.cloud.reconcileDesi
|
||||
},
|
||||
},
|
||||
localOrigin,
|
||||
).pipe(
|
||||
Effect.catchTags({
|
||||
ServerAuthCloudLinkJwtSigningError: (error) =>
|
||||
failEnvironmentCloudInternalError("sign_cloud_link_jwt")(error),
|
||||
SecretStoreReadError: failEnvironmentCloudInternalError("generate_link_proof"),
|
||||
SecretStoreDecodeError: failEnvironmentCloudInternalError("generate_link_proof"),
|
||||
SecretStoreEncodeError: failEnvironmentCloudInternalError("generate_link_proof"),
|
||||
SecretStorePersistError: failEnvironmentCloudInternalError("generate_link_proof"),
|
||||
SecretStoreConcurrentReadError: failEnvironmentCloudInternalError("generate_link_proof"),
|
||||
PlatformError: failEnvironmentCloudInternalError("generate_link_proof"),
|
||||
}),
|
||||
);
|
||||
const link = yield* relayClientRequest(dependencies, {
|
||||
operation: "create-environment-link",
|
||||
url: `${relayUrl}/v1/client/environment-links`,
|
||||
token: token.accessToken,
|
||||
payload: {
|
||||
@@ -576,7 +747,15 @@ const reconcileDesiredCloudLinkWith = Effect.fn("environment.cloud.reconcileDesi
|
||||
},
|
||||
schema: RelayEnvironmentLinkResponse,
|
||||
});
|
||||
yield* setCliDesiredCloudLink(true);
|
||||
yield* setCliDesiredCloudLink(true).pipe(
|
||||
Effect.catchTags({
|
||||
SecretStoreTemporaryPathGenerationError: failEnvironmentCloudInternalError(
|
||||
"persist_desired_link_state",
|
||||
),
|
||||
SecretStorePersistError: failEnvironmentCloudInternalError("persist_desired_link_state"),
|
||||
SecretStoreRemoveError: failEnvironmentCloudInternalError("persist_desired_link_state"),
|
||||
}),
|
||||
);
|
||||
return yield* applyCloudRelayConfig(dependencies, {
|
||||
relayUrl,
|
||||
relayIssuer: link.relayIssuer,
|
||||
@@ -584,18 +763,31 @@ const reconcileDesiredCloudLinkWith = Effect.fn("environment.cloud.reconcileDesi
|
||||
environmentCredential: link.environmentCredential,
|
||||
cloudMintPublicKey: link.cloudMintPublicKey,
|
||||
endpointRuntime: link.endpointRuntime,
|
||||
});
|
||||
}).pipe(
|
||||
Effect.catchTags({
|
||||
ServerAuthLinkedCloudAccountVerificationError: (error) =>
|
||||
failEnvironmentCloudInternalError("verify_linked_cloud_account")(error),
|
||||
SecretStoreTemporaryPathGenerationError: failEnvironmentCloudInternalError(
|
||||
"persist_relay_configuration",
|
||||
),
|
||||
SecretStorePersistError: failEnvironmentCloudInternalError("persist_relay_configuration"),
|
||||
SecretStoreRemoveError: failEnvironmentCloudInternalError("persist_relay_configuration"),
|
||||
SchemaError: failEnvironmentCloudInternalError("persist_relay_configuration"),
|
||||
}),
|
||||
);
|
||||
},
|
||||
Effect.catchIf(
|
||||
ServerSecretStore.isSecretStoreError,
|
||||
failEnvironmentCloudInternalError("Could not persist desired T3 Connect link state."),
|
||||
),
|
||||
Effect.catchTags({
|
||||
CloudCliCredentialRemovalError: failCloudCliTokenManagerError,
|
||||
CloudCliCredentialRefreshError: failCloudCliTokenManagerError,
|
||||
CloudCliCredentialReadError: failCloudCliTokenManagerError,
|
||||
CloudCliAuthorizationError: failCloudCliTokenManagerError,
|
||||
CloudCliAuthorizationTimeoutError: failCloudCliTokenManagerError,
|
||||
CloudRelayConfigurationError: (error) =>
|
||||
failEnvironmentCloudInternalError("read_relay_url_configuration")(error),
|
||||
CloudRelayRequestError: (error) =>
|
||||
failEnvironmentCloudInternalError({
|
||||
operation: "relay_request",
|
||||
relayOperation: error.operation,
|
||||
relayPhase: error.phase,
|
||||
...(error.responseStatus === undefined ? {} : { responseStatus: error.responseStatus }),
|
||||
})(error),
|
||||
CloudCliCredentialRefreshError: (error) =>
|
||||
failEnvironmentCloudInternalError("refresh_cloud_cli_credential")(error),
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -633,10 +825,9 @@ const cloudLinkStateHandler = Effect.fn("environment.cloud.linkState")(
|
||||
yield* requireEnvironmentScope(AuthRelayReadScope);
|
||||
return yield* readCloudLinkState(dependencies);
|
||||
},
|
||||
Effect.catchIf(
|
||||
ServerSecretStore.isSecretStoreError,
|
||||
failEnvironmentCloudInternalError("Could not read environment relay configuration."),
|
||||
),
|
||||
Effect.catchTags({
|
||||
SecretStoreReadError: failEnvironmentCloudInternalError("read_relay_configuration"),
|
||||
}),
|
||||
);
|
||||
|
||||
const cloudUnlinkHandler = Effect.fn("environment.cloud.unlink")(
|
||||
@@ -658,10 +849,13 @@ const cloudUnlinkHandler = Effect.fn("environment.cloud.unlink")(
|
||||
yield* setCliDesiredCloudLink(false);
|
||||
return { ok: true, endpointRuntimeStatus } satisfies EnvironmentCloudRelayConfigResult;
|
||||
},
|
||||
Effect.catchIf(
|
||||
ServerSecretStore.isSecretStoreError,
|
||||
failEnvironmentCloudInternalError("Could not remove environment relay configuration."),
|
||||
),
|
||||
Effect.catchTags({
|
||||
SecretStoreTemporaryPathGenerationError: failEnvironmentCloudInternalError(
|
||||
"remove_relay_configuration",
|
||||
),
|
||||
SecretStorePersistError: failEnvironmentCloudInternalError("remove_relay_configuration"),
|
||||
SecretStoreRemoveError: failEnvironmentCloudInternalError("remove_relay_configuration"),
|
||||
}),
|
||||
);
|
||||
|
||||
const cloudPreferencesHandler = Effect.fn("environment.cloud.preferences")(
|
||||
@@ -676,10 +870,13 @@ const cloudPreferencesHandler = Effect.fn("environment.cloud.preferences")(
|
||||
);
|
||||
return yield* readCloudLinkState(dependencies);
|
||||
},
|
||||
Effect.catchIf(
|
||||
ServerSecretStore.isSecretStoreError,
|
||||
failEnvironmentCloudInternalError("Could not persist environment cloud preferences."),
|
||||
),
|
||||
Effect.catchTags({
|
||||
SecretStoreReadError: failEnvironmentCloudInternalError("persist_cloud_preferences"),
|
||||
SecretStoreTemporaryPathGenerationError: failEnvironmentCloudInternalError(
|
||||
"persist_cloud_preferences",
|
||||
),
|
||||
SecretStorePersistError: failEnvironmentCloudInternalError("persist_cloud_preferences"),
|
||||
}),
|
||||
);
|
||||
|
||||
const cloudEnvironmentHealthHandler = Effect.fn("environment.cloud.health")(
|
||||
@@ -730,7 +927,7 @@ const cloudEnvironmentHealthHandler = Effect.fn("environment.cloud.health")(
|
||||
!hasExactScope({ scopes: proofOption.value.scope, expected: "environment:status" })
|
||||
) {
|
||||
return yield* new EnvironmentHttpUnauthorizedError({
|
||||
message: "Invalid cloud health request.",
|
||||
reason: "invalid_cloud_health_request",
|
||||
});
|
||||
}
|
||||
const proof = proofOption.value;
|
||||
@@ -744,7 +941,7 @@ const cloudEnvironmentHealthHandler = Effect.fn("environment.cloud.health")(
|
||||
});
|
||||
if (!consumedReplayGuards) {
|
||||
return yield* new EnvironmentHttpConflictError({
|
||||
message: "Cloud health request was already consumed.",
|
||||
reason: "cloud_health_request_replayed",
|
||||
});
|
||||
}
|
||||
|
||||
@@ -787,17 +984,26 @@ const cloudEnvironmentHealthHandler = Effect.fn("environment.cloud.health")(
|
||||
yield* appendCloudCredentialResponseHeaders;
|
||||
return response;
|
||||
},
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
|
||||
failEnvironmentCloudInternalError(error.message)(error),
|
||||
),
|
||||
Effect.catchIf(
|
||||
ServerSecretStore.isSecretStoreError,
|
||||
failEnvironmentCloudInternalError("Could not answer cloud health request."),
|
||||
),
|
||||
Effect.catchTag(
|
||||
"PlatformError",
|
||||
failEnvironmentCloudInternalError("Could not answer cloud health request."),
|
||||
),
|
||||
Effect.catchTags({
|
||||
ServerAuthLinkedCloudAccountReadError: (error) =>
|
||||
failEnvironmentCloudInternalError("read_linked_cloud_account")(error),
|
||||
ServerAuthLinkedCloudAccountMissingError: (error) =>
|
||||
failEnvironmentCloudInternalError("require_linked_cloud_account")(error),
|
||||
ServerAuthCloudMintPublicKeyMissingError: (error) =>
|
||||
failEnvironmentCloudInternalError("read_cloud_mint_public_key")(error),
|
||||
ServerAuthCloudRelayIssuerMissingError: (error) =>
|
||||
failEnvironmentCloudInternalError("read_cloud_relay_issuer")(error),
|
||||
ServerAuthCloudHealthJwtSigningError: (error) =>
|
||||
failEnvironmentCloudInternalError("sign_cloud_health_jwt")(error),
|
||||
SecretStoreReadError: failEnvironmentCloudInternalError("answer_cloud_health_request"),
|
||||
SecretStorePersistError: failEnvironmentCloudInternalError("answer_cloud_health_request"),
|
||||
SecretStoreDecodeError: failEnvironmentCloudInternalError("answer_cloud_health_request"),
|
||||
SecretStoreEncodeError: failEnvironmentCloudInternalError("answer_cloud_health_request"),
|
||||
SecretStoreConcurrentReadError: failEnvironmentCloudInternalError(
|
||||
"answer_cloud_health_request",
|
||||
),
|
||||
PlatformError: failEnvironmentCloudInternalError("answer_cloud_health_request"),
|
||||
}),
|
||||
);
|
||||
|
||||
const cloudMintCredentialHandler = Effect.fn("environment.cloud.mintCredential")(
|
||||
@@ -849,7 +1055,7 @@ const cloudMintCredentialHandler = Effect.fn("environment.cloud.mintCredential")
|
||||
!hasExactScope({ scopes: proofOption.value.scope, expected: "environment:connect" })
|
||||
) {
|
||||
return yield* new EnvironmentHttpUnauthorizedError({
|
||||
message: "Invalid cloud mint request.",
|
||||
reason: "invalid_cloud_mint_request",
|
||||
});
|
||||
}
|
||||
const proof = proofOption.value;
|
||||
@@ -863,7 +1069,7 @@ const cloudMintCredentialHandler = Effect.fn("environment.cloud.mintCredential")
|
||||
});
|
||||
if (!consumedReplayGuards) {
|
||||
return yield* new EnvironmentHttpConflictError({
|
||||
message: "Cloud mint request was already consumed.",
|
||||
reason: "cloud_mint_request_replayed",
|
||||
});
|
||||
}
|
||||
|
||||
@@ -908,17 +1114,28 @@ const cloudMintCredentialHandler = Effect.fn("environment.cloud.mintCredential")
|
||||
yield* appendCloudCredentialResponseHeaders;
|
||||
return response;
|
||||
},
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
|
||||
failEnvironmentCloudInternalError(error.message)(error),
|
||||
),
|
||||
Effect.catchIf(
|
||||
ServerSecretStore.isSecretStoreError,
|
||||
failEnvironmentCloudInternalError("Could not issue cloud connection credential."),
|
||||
),
|
||||
Effect.catchTag(
|
||||
"PlatformError",
|
||||
failEnvironmentCloudInternalError("Could not issue cloud connection credential."),
|
||||
),
|
||||
Effect.catchTags({
|
||||
ServerAuthLinkedCloudAccountReadError: (error) =>
|
||||
failEnvironmentCloudInternalError("read_linked_cloud_account")(error),
|
||||
ServerAuthLinkedCloudAccountMissingError: (error) =>
|
||||
failEnvironmentCloudInternalError("require_linked_cloud_account")(error),
|
||||
ServerAuthCloudMintPublicKeyMissingError: (error) =>
|
||||
failEnvironmentCloudInternalError("read_cloud_mint_public_key")(error),
|
||||
ServerAuthCloudRelayIssuerMissingError: (error) =>
|
||||
failEnvironmentCloudInternalError("read_cloud_relay_issuer")(error),
|
||||
ServerAuthPairingLinkCreationError: (error) =>
|
||||
failEnvironmentCloudInternalError("create_cloud_pairing_link")(error),
|
||||
ServerAuthCloudMintJwtSigningError: (error) =>
|
||||
failEnvironmentCloudInternalError("sign_cloud_mint_jwt")(error),
|
||||
SecretStoreReadError: failEnvironmentCloudInternalError("issue_cloud_connection_credential"),
|
||||
SecretStorePersistError: failEnvironmentCloudInternalError("issue_cloud_connection_credential"),
|
||||
SecretStoreDecodeError: failEnvironmentCloudInternalError("issue_cloud_connection_credential"),
|
||||
SecretStoreEncodeError: failEnvironmentCloudInternalError("issue_cloud_connection_credential"),
|
||||
SecretStoreConcurrentReadError: failEnvironmentCloudInternalError(
|
||||
"issue_cloud_connection_credential",
|
||||
),
|
||||
PlatformError: failEnvironmentCloudInternalError("issue_cloud_connection_credential"),
|
||||
}),
|
||||
);
|
||||
|
||||
export const connectHttpApiLayer = HttpApiBuilder.group(
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { isLoopbackHostname, resolveDevRedirectUrl } from "./http.ts";
|
||||
import {
|
||||
BrowserOtlpTraceCollectionError,
|
||||
BrowserOtlpTraceDecodeError,
|
||||
BrowserOtlpTraceExportError,
|
||||
isLoopbackHostname,
|
||||
resolveDevRedirectUrl,
|
||||
} from "./http.ts";
|
||||
|
||||
describe("http dev routing", () => {
|
||||
it("treats localhost and loopback addresses as local", () => {
|
||||
@@ -25,3 +31,73 @@ describe("http dev routing", () => {
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("browser OTLP diagnostics", () => {
|
||||
it("retains decode causes without retaining the trace payload", () => {
|
||||
const cause = new Error("private trace payload detail");
|
||||
const error = BrowserOtlpTraceDecodeError.fromPayload({ resourceSpans: [] }, cause);
|
||||
|
||||
expect(error).toMatchObject({
|
||||
resourceSpanCount: 0,
|
||||
cause,
|
||||
message: "Failed to decode browser OTLP payload with 0 resource spans.",
|
||||
});
|
||||
expect(error.cause).toBe(cause);
|
||||
expect(error).not.toHaveProperty("bodyJson");
|
||||
});
|
||||
|
||||
it("describes malformed trace payloads without inspecting unsafe fields", () => {
|
||||
const cause = new Error("private malformed trace payload detail");
|
||||
const error = BrowserOtlpTraceDecodeError.fromPayload(
|
||||
{ resourceSpans: "private malformed resource spans" },
|
||||
cause,
|
||||
);
|
||||
|
||||
expect(error).toMatchObject({
|
||||
resourceSpanCount: 0,
|
||||
cause,
|
||||
message: "Failed to decode browser OTLP payload with 0 resource spans.",
|
||||
});
|
||||
expect(error.cause).toBe(cause);
|
||||
expect(error).not.toHaveProperty("resourceSpans");
|
||||
});
|
||||
|
||||
it("retains local collection causes with a structural record count", () => {
|
||||
const records = [{ type: "private trace record" }];
|
||||
const cause = new Error("private local collector detail");
|
||||
const error = BrowserOtlpTraceCollectionError.fromRecords(records, cause);
|
||||
|
||||
expect(error).toMatchObject({
|
||||
recordCount: 1,
|
||||
cause,
|
||||
message: "Failed to collect 1 browser OTLP trace records locally.",
|
||||
});
|
||||
expect(error.cause).toBe(cause);
|
||||
expect(error).not.toHaveProperty("records");
|
||||
});
|
||||
|
||||
it("redacts collector URL credentials while retaining the exact cause", () => {
|
||||
const collectorUrl =
|
||||
"https://collector-user:[email protected]/private/v1/traces?access_token=collector-secret#collector-fragment";
|
||||
const cause = new Error("collector transport failed");
|
||||
const error = BrowserOtlpTraceExportError.fromCollectorUrl(collectorUrl, cause);
|
||||
|
||||
expect(error).toMatchObject({
|
||||
collectorUrlInputLength: collectorUrl.length,
|
||||
collectorUrlProtocol: "https:",
|
||||
collectorUrlHostname: "traces.example.test",
|
||||
cause,
|
||||
});
|
||||
expect(error.cause).toBe(cause);
|
||||
expect(error).not.toHaveProperty("collectorUrl");
|
||||
for (const secret of [
|
||||
"collector-user",
|
||||
"collector-password",
|
||||
"/private/v1/traces",
|
||||
"collector-secret",
|
||||
"collector-fragment",
|
||||
]) {
|
||||
expect(error.message).not.toContain(secret);
|
||||
}
|
||||
});
|
||||
});
|
||||
+134
-35
@@ -5,12 +5,13 @@ import {
|
||||
EnvironmentHttpApi,
|
||||
} from "@t3tools/contracts";
|
||||
import { decodeOtlpTraceRecords } from "@t3tools/shared/observability";
|
||||
import * as Data from "effect/Data";
|
||||
import { getUrlDiagnostics } from "@t3tools/shared/urlDiagnostics";
|
||||
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 Path from "effect/Path";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { cast } from "effect/Function";
|
||||
import {
|
||||
HttpBody,
|
||||
@@ -35,27 +36,21 @@ import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
|
||||
import { traceRelayRequest } from "./cloud/traceRelayRequest.ts";
|
||||
import {
|
||||
annotateEnvironmentRequest,
|
||||
catchEnvironmentAuthenticationErrors,
|
||||
failEnvironmentScopeRequired,
|
||||
failEnvironmentAuthInvalid,
|
||||
failEnvironmentInternal,
|
||||
} from "./auth/http.ts";
|
||||
import * as ServerEnvironment from "./environment/ServerEnvironment.ts";
|
||||
import { browserApiCorsAllowedHeaders, browserApiCorsAllowedMethods } from "./httpCors.ts";
|
||||
|
||||
const OTLP_TRACES_PROXY_PATH = "/api/observability/v1/traces";
|
||||
const LOOPBACK_HOSTNAMES = new Set(["127.0.0.1", "::1", "localhost"]);
|
||||
const DESKTOP_RENDERER_ORIGINS = ["t3code://app", "t3code-dev://app"];
|
||||
|
||||
export const browserApiCorsLayer = Layer.unwrap(
|
||||
Effect.gen(function* () {
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
const devOrigin = config.devUrl?.origin;
|
||||
// Dev uses credentialed requests from Vite or the Electron custom origin, so both must be
|
||||
// explicit. Packaged desktop omits credentials and uses Effect's default wildcard origin.
|
||||
return HttpRouter.cors({
|
||||
...(devOrigin
|
||||
? { allowedOrigins: [devOrigin, ...DESKTOP_RENDERER_ORIGINS], credentials: true }
|
||||
: {}),
|
||||
...(devOrigin ? { allowedOrigins: [devOrigin], credentials: true } : {}),
|
||||
allowedMethods: browserApiCorsAllowedMethods,
|
||||
allowedHeaders: browserApiCorsAllowedHeaders,
|
||||
maxAge: 600,
|
||||
@@ -85,13 +80,8 @@ const authenticateRawRouteWithScope = (
|
||||
Effect.gen(function* () {
|
||||
const request = yield* HttpServerRequest.HttpServerRequest;
|
||||
const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
|
||||
const session = yield* serverAuth.authenticateHttpRequest(request).pipe(
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, (error) =>
|
||||
failEnvironmentAuthInvalid(EnvironmentAuth.serverAuthCredentialReason(error)),
|
||||
),
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
|
||||
failEnvironmentInternal("internal_error", error),
|
||||
),
|
||||
const session = yield* catchEnvironmentAuthenticationErrors(
|
||||
serverAuth.authenticateHttpRequest(request),
|
||||
);
|
||||
if (!session.scopes.includes(scope)) {
|
||||
return yield* failEnvironmentScopeRequired(scope);
|
||||
@@ -113,10 +103,95 @@ export const serverEnvironmentHttpApiLayer = HttpApiBuilder.group(
|
||||
}),
|
||||
);
|
||||
|
||||
class DecodeOtlpTraceRecordsError extends Data.TaggedError("DecodeOtlpTraceRecordsError")<{
|
||||
readonly cause: unknown;
|
||||
readonly bodyJson: OtlpTracer.TraceData;
|
||||
}> {}
|
||||
function errorDiagnosticTag(cause: unknown): string {
|
||||
if (
|
||||
typeof cause === "object" &&
|
||||
cause !== null &&
|
||||
"_tag" in cause &&
|
||||
typeof cause._tag === "string"
|
||||
) {
|
||||
return cause._tag;
|
||||
}
|
||||
if (cause instanceof Error) return cause.name;
|
||||
return typeof cause;
|
||||
}
|
||||
|
||||
export class BrowserOtlpTraceDecodeError extends Schema.TaggedErrorClass<BrowserOtlpTraceDecodeError>()(
|
||||
"BrowserOtlpTraceDecodeError",
|
||||
{
|
||||
resourceSpanCount: Schema.Number,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
static fromPayload(payload: unknown, cause: unknown): BrowserOtlpTraceDecodeError {
|
||||
const resourceSpanCount =
|
||||
typeof payload === "object" &&
|
||||
payload !== null &&
|
||||
"resourceSpans" in payload &&
|
||||
Array.isArray(payload.resourceSpans)
|
||||
? payload.resourceSpans.length
|
||||
: 0;
|
||||
|
||||
return new BrowserOtlpTraceDecodeError({
|
||||
resourceSpanCount,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `Failed to decode browser OTLP payload with ${this.resourceSpanCount} resource spans.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class BrowserOtlpTraceCollectionError extends Schema.TaggedErrorClass<BrowserOtlpTraceCollectionError>()(
|
||||
"BrowserOtlpTraceCollectionError",
|
||||
{
|
||||
recordCount: Schema.Number,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
static fromRecords(
|
||||
records: ReadonlyArray<unknown>,
|
||||
cause: unknown,
|
||||
): BrowserOtlpTraceCollectionError {
|
||||
return new BrowserOtlpTraceCollectionError({
|
||||
recordCount: records.length,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `Failed to collect ${this.recordCount} browser OTLP trace records locally.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class BrowserOtlpTraceExportError extends Schema.TaggedErrorClass<BrowserOtlpTraceExportError>()(
|
||||
"BrowserOtlpTraceExportError",
|
||||
{
|
||||
collectorUrlInputLength: Schema.Number,
|
||||
collectorUrlProtocol: Schema.optionalKey(Schema.String),
|
||||
collectorUrlHostname: Schema.optionalKey(Schema.String),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
static fromCollectorUrl(collectorUrl: string, cause: unknown): BrowserOtlpTraceExportError {
|
||||
const diagnostics = getUrlDiagnostics(collectorUrl);
|
||||
return new BrowserOtlpTraceExportError({
|
||||
collectorUrlInputLength: diagnostics.inputLength,
|
||||
...(diagnostics.protocol === undefined ? {} : { collectorUrlProtocol: diagnostics.protocol }),
|
||||
...(diagnostics.hostname === undefined ? {} : { collectorUrlHostname: diagnostics.hostname }),
|
||||
cause,
|
||||
});
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
const collector =
|
||||
this.collectorUrlHostname === undefined
|
||||
? "the configured collector"
|
||||
: this.collectorUrlHostname;
|
||||
return `Failed to export browser OTLP traces to ${collector} (collector URL input length ${this.collectorUrlInputLength}).`;
|
||||
}
|
||||
}
|
||||
|
||||
export const otlpTracesProxyRouteLayer = HttpRouter.add(
|
||||
"POST",
|
||||
@@ -132,15 +207,31 @@ export const otlpTracesProxyRouteLayer = HttpRouter.add(
|
||||
|
||||
yield* Effect.try({
|
||||
try: () => decodeOtlpTraceRecords(bodyJson),
|
||||
catch: (cause) => new DecodeOtlpTraceRecordsError({ cause, bodyJson }),
|
||||
catch: (cause) => BrowserOtlpTraceDecodeError.fromPayload(bodyJson, cause),
|
||||
}).pipe(
|
||||
Effect.flatMap((records) => browserTraceCollector.record(records)),
|
||||
Effect.catch((cause) =>
|
||||
Effect.logWarning("Failed to decode browser OTLP traces", {
|
||||
cause,
|
||||
bodyJson,
|
||||
}),
|
||||
Effect.flatMap((records) =>
|
||||
browserTraceCollector
|
||||
.record(records)
|
||||
.pipe(
|
||||
Effect.catchDefect((cause) =>
|
||||
Effect.fail(BrowserOtlpTraceCollectionError.fromRecords(records, cause)),
|
||||
),
|
||||
),
|
||||
),
|
||||
Effect.catchTags({
|
||||
BrowserOtlpTraceDecodeError: (error) =>
|
||||
Effect.logWarning(error.message, {
|
||||
errorTag: error._tag,
|
||||
resourceSpanCount: error.resourceSpanCount,
|
||||
causeTag: errorDiagnosticTag(error.cause),
|
||||
}),
|
||||
BrowserOtlpTraceCollectionError: (error) =>
|
||||
Effect.logWarning(error.message, {
|
||||
errorTag: error._tag,
|
||||
recordCount: error.recordCount,
|
||||
causeTag: errorDiagnosticTag(error.cause),
|
||||
}),
|
||||
}),
|
||||
);
|
||||
|
||||
if (otlpTracesUrl === undefined) {
|
||||
@@ -154,15 +245,23 @@ export const otlpTracesProxyRouteLayer = HttpRouter.add(
|
||||
.pipe(
|
||||
Effect.flatMap(HttpClientResponse.filterStatusOk),
|
||||
Effect.as(HttpServerResponse.empty({ status: 204 })),
|
||||
Effect.tapError((cause) =>
|
||||
Effect.logWarning("Failed to export browser OTLP traces", {
|
||||
cause,
|
||||
otlpTracesUrl,
|
||||
}),
|
||||
),
|
||||
Effect.orElseSucceed(() =>
|
||||
HttpServerResponse.text("Trace export failed.", { status: 502 }),
|
||||
Effect.mapError((cause) =>
|
||||
BrowserOtlpTraceExportError.fromCollectorUrl(otlpTracesUrl, cause),
|
||||
),
|
||||
Effect.catchTags({
|
||||
BrowserOtlpTraceExportError: (error) =>
|
||||
Effect.logWarning(error.message, {
|
||||
errorTag: error._tag,
|
||||
collectorUrlInputLength: error.collectorUrlInputLength,
|
||||
...(error.collectorUrlProtocol === undefined
|
||||
? {}
|
||||
: { collectorUrlProtocol: error.collectorUrlProtocol }),
|
||||
...(error.collectorUrlHostname === undefined
|
||||
? {}
|
||||
: { collectorUrlHostname: error.collectorUrlHostname }),
|
||||
causeTag: errorDiagnosticTag(error.cause),
|
||||
}).pipe(Effect.as(HttpServerResponse.text("Trace export failed.", { status: 502 }))),
|
||||
}),
|
||||
);
|
||||
}).pipe(
|
||||
Effect.catchTags({
|
||||
|
||||
@@ -1,17 +1,16 @@
|
||||
import { KeybindingCommand, KeybindingRule, KeybindingsConfig } from "@t3tools/contracts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { assertFailure } from "@effect/vitest/utils";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Logger from "effect/Logger";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Result from "effect/Result";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as ServerConfig from "./config.ts";
|
||||
import * as Keybindings from "./keybindings.ts";
|
||||
import { KeybindingsConfigError } from "@t3tools/contracts";
|
||||
|
||||
const KeybindingsConfigJson = Schema.fromJsonString(KeybindingsConfig);
|
||||
const encodeKeybindingsConfigJson = Schema.encodeEffect(KeybindingsConfigJson);
|
||||
@@ -34,12 +33,6 @@ const makeKeybindingsLayer = () => {
|
||||
);
|
||||
};
|
||||
|
||||
const toDetailResult = <A, R>(effect: Effect.Effect<A, KeybindingsConfigError, R>) =>
|
||||
effect.pipe(
|
||||
Effect.mapError((error) => error.detail),
|
||||
Effect.result,
|
||||
);
|
||||
|
||||
const writeKeybindingsConfig = (configPath: string, rules: readonly KeybindingRule[]) =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
@@ -198,7 +191,6 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
|
||||
assert.equal(defaultsByCommand.get("thread.jump.1"), "mod+1");
|
||||
assert.equal(defaultsByCommand.get("thread.jump.9"), "mod+9");
|
||||
assert.equal(defaultsByCommand.get("modelPicker.toggle"), "mod+shift+m");
|
||||
assert.equal(defaultsByCommand.get("sidebar.toggle"), "mod+b");
|
||||
assert.equal(defaultsByCommand.get("rightPanel.toggle"), "mod+alt+b");
|
||||
assert.equal(defaultsByCommand.get("terminal.splitVertical"), "mod+shift+d");
|
||||
assert.equal(defaultsByCommand.get("modelPicker.jump.1"), "mod+1");
|
||||
@@ -224,15 +216,21 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
|
||||
assert.deepEqual(configState.issues, [
|
||||
{
|
||||
kind: "keybindings.malformed-config",
|
||||
message: configState.issues[0]?.message ?? "",
|
||||
message: "Expected the keybindings configuration to be a JSON array.",
|
||||
},
|
||||
]);
|
||||
assert.equal(yield* fs.readFileString(keybindingsConfigPath), "{ not-json");
|
||||
}).pipe(Effect.provide(makeKeybindingsLayer())),
|
||||
);
|
||||
|
||||
it.effect("ignores invalid entries in runtime and reports them as issues", () =>
|
||||
Effect.gen(function* () {
|
||||
it.effect("ignores invalid entries in runtime and reports them as issues", () => {
|
||||
const logs: ReadonlyArray<unknown>[] = [];
|
||||
const logger = Logger.make(({ message }) => {
|
||||
logs.push(Array.isArray(message) ? message : [message]);
|
||||
});
|
||||
const secret = "private-shortcut-payload";
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig;
|
||||
yield* fs.writeFileString(
|
||||
@@ -241,7 +239,7 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
|
||||
JSON.stringify([
|
||||
{ key: "mod+j", command: "terminal.toggle" },
|
||||
{ key: "mod+shift+d+o", command: "terminal.new" },
|
||||
{ key: "mod+x", command: "invalid.command" },
|
||||
{ key: "mod+x", command: secret },
|
||||
]),
|
||||
);
|
||||
|
||||
@@ -251,23 +249,55 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
|
||||
});
|
||||
|
||||
assert.isTrue(configState.keybindings.some((entry) => entry.command === "terminal.toggle"));
|
||||
assert.isFalse(
|
||||
configState.keybindings.some((entry) => String(entry.command) === "invalid.command"),
|
||||
);
|
||||
assert.isFalse(configState.keybindings.some((entry) => String(entry.command) === secret));
|
||||
assert.deepEqual(configState.issues, [
|
||||
{
|
||||
kind: "keybindings.invalid-entry",
|
||||
index: 1,
|
||||
message: configState.issues[0]?.message ?? "",
|
||||
message: "The keybinding entry contains an invalid shortcut or when expression.",
|
||||
},
|
||||
{
|
||||
kind: "keybindings.invalid-entry",
|
||||
index: 2,
|
||||
message: configState.issues[1]?.message ?? "",
|
||||
message: "Expected a keybinding entry with key, command, and optional when fields.",
|
||||
},
|
||||
]);
|
||||
}).pipe(Effect.provide(makeKeybindingsLayer())),
|
||||
);
|
||||
const invalidEntryLog = logs.find((log) => {
|
||||
const attributes = log[1];
|
||||
return (
|
||||
String(log[0]).includes("ignoring invalid keybinding entry") &&
|
||||
typeof attributes === "object" &&
|
||||
attributes !== null &&
|
||||
Reflect.get(attributes, "entryIndex") === 2
|
||||
);
|
||||
});
|
||||
if (!invalidEntryLog) {
|
||||
return assert.fail("Expected invalid keybinding warning");
|
||||
}
|
||||
const attributes = invalidEntryLog[1];
|
||||
if (typeof attributes !== "object" || attributes === null) {
|
||||
return assert.fail("Expected structured invalid keybinding attributes");
|
||||
}
|
||||
assert.equal(Reflect.get(attributes, "validationStage"), "entry-schema");
|
||||
assert.equal(Reflect.get(attributes, "validationInputKind"), "object");
|
||||
assert.equal(Reflect.get(attributes, "validationInputSize"), 2);
|
||||
assert.equal(Reflect.get(attributes, "validationHasKeyField"), true);
|
||||
assert.equal(Reflect.get(attributes, "validationHasCommandField"), true);
|
||||
assert.equal(Reflect.get(attributes, "validationHasWhenField"), false);
|
||||
assert.equal(Reflect.get(attributes, "causeReasonCount"), 1);
|
||||
assert.isFalse("entry" in attributes);
|
||||
assert.isFalse("cause" in attributes);
|
||||
assert.isFalse(String(invalidEntryLog[0]).includes(secret));
|
||||
assert.isFalse(Object.values(attributes).some((value) => String(value).includes(secret)));
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
makeKeybindingsLayer(),
|
||||
Logger.layer([logger], { mergeWithExisting: false }),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect(
|
||||
"upserts missing default keybindings on startup without overriding existing command rules",
|
||||
@@ -302,9 +332,9 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
|
||||
);
|
||||
|
||||
it.effect("skips conflicting default keybindings on startup and logs a detailed warning", () => {
|
||||
const messages: string[] = [];
|
||||
const logs: ReadonlyArray<unknown>[] = [];
|
||||
const logger = Logger.make(({ message }) => {
|
||||
messages.push(String(message));
|
||||
logs.push(Array.isArray(message) ? message : [message]);
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
@@ -322,11 +352,21 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
|
||||
assert.isFalse(persisted.some((entry) => entry.command === "terminal.toggle"));
|
||||
assert.isTrue(persisted.some((entry) => entry.command === "script.custom-action.run"));
|
||||
|
||||
assert.isTrue(
|
||||
messages.some((message) =>
|
||||
message.includes("skipping default keybinding due to shortcut conflict"),
|
||||
),
|
||||
const warning = logs.find((log) =>
|
||||
String(log[0]).includes("skipping default keybinding due to shortcut conflict"),
|
||||
);
|
||||
if (!warning) {
|
||||
return assert.fail("Expected shortcut conflict warning");
|
||||
}
|
||||
const attributes = warning[1];
|
||||
if (typeof attributes !== "object" || attributes === null) {
|
||||
return assert.fail("Expected structured shortcut conflict attributes");
|
||||
}
|
||||
assert.equal(Reflect.get(attributes, "defaultCommand"), "terminal.toggle");
|
||||
assert.equal(Reflect.get(attributes, "conflictingCommand"), "script.custom-action.run");
|
||||
assert.equal(Reflect.get(attributes, "hasWhenContext"), false);
|
||||
assert.isFalse("key" in attributes);
|
||||
assert.isFalse("when" in attributes);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
@@ -444,15 +484,24 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
|
||||
key: "mod+shift+r",
|
||||
command: "script.run-tests.run",
|
||||
});
|
||||
}).pipe(toDetailResult);
|
||||
assertFailure(result, "expected JSON array");
|
||||
}).pipe(Effect.result);
|
||||
if (Result.isSuccess(result)) {
|
||||
return assert.fail("Expected malformed config update to fail");
|
||||
}
|
||||
assert.equal(result.failure._tag, "KeybindingsConfigError");
|
||||
assert.equal(result.failure.operation, "decode");
|
||||
assert.isTrue(Schema.isSchemaError(result.failure.cause));
|
||||
assert.equal(
|
||||
result.failure.message,
|
||||
`Keybindings config operation 'decode' failed at ${keybindingsConfigPath}.`,
|
||||
);
|
||||
|
||||
const persistedRaw = yield* fs.readFileString(keybindingsConfigPath);
|
||||
assert.equal(persistedRaw, "{ not-json");
|
||||
}).pipe(Effect.provide(makeKeybindingsLayer())),
|
||||
);
|
||||
|
||||
it.effect("reports non-array config parse errors without duplicate prefix", () =>
|
||||
it.effect("returns stable structured decode errors across retries", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig;
|
||||
@@ -467,8 +516,12 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
|
||||
key: "mod+shift+r",
|
||||
command: "script.run-tests.run",
|
||||
});
|
||||
}).pipe(toDetailResult);
|
||||
assertFailure(firstResult, "expected JSON array");
|
||||
}).pipe(Effect.result);
|
||||
if (Result.isSuccess(firstResult)) {
|
||||
return assert.fail("Expected first malformed config update to fail");
|
||||
}
|
||||
assert.equal(firstResult.failure.operation, "decode");
|
||||
assert.isTrue(Schema.isSchemaError(firstResult.failure.cause));
|
||||
|
||||
const secondResult = yield* Effect.gen(function* () {
|
||||
const keybindings = yield* Keybindings.Keybindings;
|
||||
@@ -476,8 +529,13 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
|
||||
key: "mod+shift+r",
|
||||
command: "script.run-tests.run",
|
||||
});
|
||||
}).pipe(toDetailResult);
|
||||
assertFailure(secondResult, "expected JSON array");
|
||||
}).pipe(Effect.result);
|
||||
if (Result.isSuccess(secondResult)) {
|
||||
return assert.fail("Expected second malformed config update to fail");
|
||||
}
|
||||
assert.equal(secondResult.failure.operation, "decode");
|
||||
assert.isTrue(Schema.isSchemaError(secondResult.failure.cause));
|
||||
assert.equal(secondResult.failure.message, firstResult.failure.message);
|
||||
}).pipe(Effect.provide(makeKeybindingsLayer())),
|
||||
);
|
||||
|
||||
@@ -497,8 +555,11 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
|
||||
key: "mod+shift+r",
|
||||
command: "script.run-tests.run",
|
||||
});
|
||||
}).pipe(toDetailResult);
|
||||
assertFailure(result, "failed to write keybindings config");
|
||||
}).pipe(Effect.result);
|
||||
if (Result.isSuccess(result)) {
|
||||
return assert.fail("Expected update in a read-only directory to fail");
|
||||
}
|
||||
assert.equal(result.failure.operation, "write");
|
||||
|
||||
yield* fs.chmod(dirname(keybindingsConfigPath), 0o700);
|
||||
|
||||
|
||||
+139
-49
@@ -44,6 +44,7 @@ import * as Semaphore from "effect/Semaphore";
|
||||
import * as ServerConfig from "./config.ts";
|
||||
import { writeFileStringAtomically } from "./atomicWrite.ts";
|
||||
import { fromJsonStringPretty, fromLenientJson } from "@t3tools/shared/schemaJson";
|
||||
import { causeErrorTag } from "@t3tools/shared/observability";
|
||||
import {
|
||||
DEFAULT_KEYBINDINGS,
|
||||
DEFAULT_RESOLVED_KEYBINDINGS,
|
||||
@@ -186,23 +187,53 @@ export interface KeybindingsChangeEvent {
|
||||
readonly issues: readonly ServerConfigIssue[];
|
||||
}
|
||||
|
||||
function trimIssueMessage(message: string): string {
|
||||
const trimmed = message.trim();
|
||||
return trimmed.length > 0 ? trimmed : "Invalid keybindings configuration.";
|
||||
}
|
||||
const MALFORMED_KEYBINDINGS_CONFIG_MESSAGE =
|
||||
"Expected the keybindings configuration to be a JSON array.";
|
||||
const INVALID_KEYBINDING_ENTRY_MESSAGE =
|
||||
"Expected a keybinding entry with key, command, and optional when fields.";
|
||||
const INVALID_KEYBINDING_RULE_MESSAGE =
|
||||
"The keybinding entry contains an invalid shortcut or when expression.";
|
||||
|
||||
function malformedConfigIssue(detail: string): ServerConfigIssue {
|
||||
function keybindingsCauseLogAttributes(cause: Cause.Cause<unknown>) {
|
||||
return {
|
||||
kind: "keybindings.malformed-config",
|
||||
message: trimIssueMessage(detail),
|
||||
errorTag: causeErrorTag(cause),
|
||||
causeReasonCount: cause.reasons.length,
|
||||
causeFailureCount: cause.reasons.filter(Cause.isFailReason).length,
|
||||
causeDefectCount: cause.reasons.filter(Cause.isDieReason).length,
|
||||
causeInterruptionCount: cause.reasons.filter(Cause.isInterruptReason).length,
|
||||
};
|
||||
}
|
||||
|
||||
function invalidEntryIssue(index: number, detail: string): ServerConfigIssue {
|
||||
function keybindingsValidationInputLogAttributes(value: unknown) {
|
||||
if (typeof value === "string") {
|
||||
return { validationInputKind: "string", validationInputSize: value.length };
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
return { validationInputKind: "array", validationInputSize: value.length };
|
||||
}
|
||||
if (typeof value === "object" && value !== null) {
|
||||
return {
|
||||
validationInputKind: "object",
|
||||
validationInputSize: Object.keys(value).length,
|
||||
validationHasKeyField: Object.hasOwn(value, "key"),
|
||||
validationHasCommandField: Object.hasOwn(value, "command"),
|
||||
validationHasWhenField: Object.hasOwn(value, "when"),
|
||||
};
|
||||
}
|
||||
return { validationInputKind: value === null ? "null" : typeof value };
|
||||
}
|
||||
|
||||
function keybindingsValidationLogAttributes(input: {
|
||||
readonly stage: "document" | "entry-schema" | "resolved-rule";
|
||||
readonly value: unknown;
|
||||
readonly cause: Cause.Cause<unknown>;
|
||||
readonly index?: number;
|
||||
}) {
|
||||
return {
|
||||
kind: "keybindings.invalid-entry",
|
||||
index,
|
||||
message: trimIssueMessage(detail),
|
||||
validationStage: input.stage,
|
||||
...(input.index === undefined ? {} : { entryIndex: input.index }),
|
||||
...keybindingsValidationInputLogAttributes(input.value),
|
||||
...keybindingsCauseLogAttributes(input.cause),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -306,7 +337,7 @@ const make = Effect.gen(function* () {
|
||||
(cause) =>
|
||||
new KeybindingsConfigError({
|
||||
configPath: keybindingsConfigPath,
|
||||
detail: "failed to access keybindings config",
|
||||
operation: "access",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
@@ -317,7 +348,7 @@ const make = Effect.gen(function* () {
|
||||
(cause) =>
|
||||
new KeybindingsConfigError({
|
||||
configPath: keybindingsConfigPath,
|
||||
detail: "failed to read keybindings config",
|
||||
operation: "read",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
@@ -337,20 +368,24 @@ const make = Effect.gen(function* () {
|
||||
(cause) =>
|
||||
new KeybindingsConfigError({
|
||||
configPath: keybindingsConfigPath,
|
||||
detail: "expected JSON array",
|
||||
operation: "decode",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return yield* Effect.forEach(rawConfig, (entry) =>
|
||||
return yield* Effect.forEach(rawConfig, (entry, index) =>
|
||||
Effect.gen(function* () {
|
||||
const decodedRule = decodeKeybindingRuleExit(entry);
|
||||
if (decodedRule._tag === "Failure") {
|
||||
yield* Effect.logWarning("ignoring invalid keybinding entry", {
|
||||
path: keybindingsConfigPath,
|
||||
entry,
|
||||
error: Cause.pretty(decodedRule.cause),
|
||||
...keybindingsValidationLogAttributes({
|
||||
stage: "entry-schema",
|
||||
value: entry,
|
||||
cause: decodedRule.cause,
|
||||
index,
|
||||
}),
|
||||
});
|
||||
return null;
|
||||
}
|
||||
@@ -358,8 +393,12 @@ const make = Effect.gen(function* () {
|
||||
if (resolved._tag === "Failure") {
|
||||
yield* Effect.logWarning("ignoring invalid keybinding entry", {
|
||||
path: keybindingsConfigPath,
|
||||
entry,
|
||||
error: Cause.pretty(resolved.cause),
|
||||
...keybindingsValidationLogAttributes({
|
||||
stage: "resolved-rule",
|
||||
value: entry,
|
||||
cause: resolved.cause,
|
||||
index,
|
||||
}),
|
||||
});
|
||||
return null;
|
||||
}
|
||||
@@ -382,10 +421,22 @@ const make = Effect.gen(function* () {
|
||||
const rawConfig = yield* readRawConfig;
|
||||
const decodedEntries = decodeRawKeybindingsEntriesExit(rawConfig);
|
||||
if (decodedEntries._tag === "Failure") {
|
||||
const detail = `expected JSON array (${Cause.pretty(decodedEntries.cause)})`;
|
||||
yield* Effect.logWarning("ignoring malformed keybindings config", {
|
||||
path: keybindingsConfigPath,
|
||||
...keybindingsValidationLogAttributes({
|
||||
stage: "document",
|
||||
value: rawConfig,
|
||||
cause: decodedEntries.cause,
|
||||
}),
|
||||
});
|
||||
return {
|
||||
keybindings: [],
|
||||
issues: [malformedConfigIssue(detail)],
|
||||
issues: [
|
||||
{
|
||||
kind: "keybindings.malformed-config",
|
||||
message: MALFORMED_KEYBINDINGS_CONFIG_MESSAGE,
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
@@ -394,26 +445,38 @@ const make = Effect.gen(function* () {
|
||||
for (const [index, entry] of decodedEntries.value.entries()) {
|
||||
const decodedRule = decodeKeybindingRuleExit(entry);
|
||||
if (decodedRule._tag === "Failure") {
|
||||
const detail = Cause.pretty(decodedRule.cause);
|
||||
issues.push(invalidEntryIssue(index, detail));
|
||||
issues.push({
|
||||
kind: "keybindings.invalid-entry",
|
||||
index,
|
||||
message: INVALID_KEYBINDING_ENTRY_MESSAGE,
|
||||
});
|
||||
yield* Effect.logWarning("ignoring invalid keybinding entry", {
|
||||
path: keybindingsConfigPath,
|
||||
index,
|
||||
entry,
|
||||
error: detail,
|
||||
...keybindingsValidationLogAttributes({
|
||||
stage: "entry-schema",
|
||||
value: entry,
|
||||
cause: decodedRule.cause,
|
||||
index,
|
||||
}),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
const resolvedRule = decodeResolvedKeybindingFromConfigExit(decodedRule.value);
|
||||
if (resolvedRule._tag === "Failure") {
|
||||
const detail = Cause.pretty(resolvedRule.cause);
|
||||
issues.push(invalidEntryIssue(index, detail));
|
||||
issues.push({
|
||||
kind: "keybindings.invalid-entry",
|
||||
index,
|
||||
message: INVALID_KEYBINDING_RULE_MESSAGE,
|
||||
});
|
||||
yield* Effect.logWarning("ignoring invalid keybinding entry", {
|
||||
path: keybindingsConfigPath,
|
||||
index,
|
||||
entry,
|
||||
error: detail,
|
||||
...keybindingsValidationLogAttributes({
|
||||
stage: "resolved-rule",
|
||||
value: entry,
|
||||
cause: resolvedRule.cause,
|
||||
index,
|
||||
}),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
@@ -425,6 +488,14 @@ const make = Effect.gen(function* () {
|
||||
|
||||
const writeConfigAtomically = (rules: readonly KeybindingRule[]) => {
|
||||
return encodeKeybindingsConfigPrettyJson(rules).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new KeybindingsConfigError({
|
||||
configPath: keybindingsConfigPath,
|
||||
operation: "encode",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.map((encoded) => `${encoded}\n`),
|
||||
Effect.flatMap((encoded) =>
|
||||
writeFileStringAtomically({
|
||||
@@ -433,16 +504,16 @@ const make = Effect.gen(function* () {
|
||||
}).pipe(
|
||||
Effect.provideService(FileSystem.FileSystem, fs),
|
||||
Effect.provideService(Path.Path, path),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new KeybindingsConfigError({
|
||||
configPath: keybindingsConfigPath,
|
||||
operation: "write",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new KeybindingsConfigError({
|
||||
configPath: keybindingsConfigPath,
|
||||
detail: "failed to write keybindings config",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
@@ -487,7 +558,13 @@ const make = Effect.gen(function* () {
|
||||
"skipping startup keybindings default sync because config has issues",
|
||||
{
|
||||
path: keybindingsConfigPath,
|
||||
issues: runtimeConfig.issues,
|
||||
issueCount: runtimeConfig.issues.length,
|
||||
malformedConfigIssueCount: runtimeConfig.issues.filter(
|
||||
(issue) => issue.kind === "keybindings.malformed-config",
|
||||
).length,
|
||||
invalidEntryIssueCount: runtimeConfig.issues.filter(
|
||||
(issue) => issue.kind === "keybindings.invalid-entry",
|
||||
).length,
|
||||
},
|
||||
);
|
||||
yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);
|
||||
@@ -499,8 +576,7 @@ const make = Effect.gen(function* () {
|
||||
const shortcutConflictWarnings: Array<{
|
||||
defaultCommand: KeybindingRule["command"];
|
||||
conflictingCommand: KeybindingRule["command"];
|
||||
key: string;
|
||||
when: string | null;
|
||||
hasWhenContext: boolean;
|
||||
}> = [];
|
||||
for (const defaultRule of DEFAULT_KEYBINDINGS) {
|
||||
if (existingCommands.has(defaultRule.command)) {
|
||||
@@ -513,8 +589,7 @@ const make = Effect.gen(function* () {
|
||||
shortcutConflictWarnings.push({
|
||||
defaultCommand: defaultRule.command,
|
||||
conflictingCommand: conflictingEntry.command,
|
||||
key: defaultRule.key,
|
||||
when: defaultRule.when ?? null,
|
||||
hasWhenContext: defaultRule.when !== undefined,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
@@ -525,8 +600,7 @@ const make = Effect.gen(function* () {
|
||||
path: keybindingsConfigPath,
|
||||
defaultCommand: conflict.defaultCommand,
|
||||
conflictingCommand: conflict.conflictingCommand,
|
||||
key: conflict.key,
|
||||
when: conflict.when,
|
||||
hasWhenContext: conflict.hasWhenContext,
|
||||
reason: "shortcut context already used by existing rule",
|
||||
});
|
||||
}
|
||||
@@ -574,13 +648,22 @@ const make = Effect.gen(function* () {
|
||||
(cause) =>
|
||||
new KeybindingsConfigError({
|
||||
configPath: keybindingsConfigPath,
|
||||
detail: "failed to prepare keybindings config directory",
|
||||
operation: "prepare-directory",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const revalidateAndEmitSafely = revalidateAndEmit.pipe(Effect.ignoreCause({ log: true }));
|
||||
const revalidateAndEmitSafely = revalidateAndEmit.pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
Cause.hasInterruptsOnly(cause)
|
||||
? Effect.void
|
||||
: Effect.logWarning("keybindings config revalidation failed", {
|
||||
path: keybindingsConfigPath,
|
||||
...keybindingsCauseLogAttributes(cause),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
// Debounce watch events so the file is fully written before we read it.
|
||||
// Editors emit multiple events per save (truncate, write, rename) and
|
||||
@@ -597,7 +680,14 @@ const make = Effect.gen(function* () {
|
||||
);
|
||||
|
||||
yield* Stream.runForEach(debouncedKeybindingsEvents, () => revalidateAndEmitSafely).pipe(
|
||||
Effect.ignoreCause({ log: true }),
|
||||
Effect.catchCause((cause) =>
|
||||
Cause.hasInterruptsOnly(cause)
|
||||
? Effect.void
|
||||
: Effect.logWarning("keybindings config watcher failed", {
|
||||
path: keybindingsConfigPath,
|
||||
...keybindingsCauseLogAttributes(cause),
|
||||
}),
|
||||
),
|
||||
Effect.forkIn(watcherScope),
|
||||
Effect.asVoid,
|
||||
);
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import { NodeHttpServer } from "@effect/platform-node";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { EnvironmentId, PreviewTabId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
@@ -35,7 +34,7 @@ const client = McpSchema.McpServerClient.of({
|
||||
});
|
||||
const TestLayer = McpHttpServer.PreviewToolkitRegistrationLive.pipe(
|
||||
Layer.provideMerge(McpServer.McpServer.layer),
|
||||
Layer.provideMerge(PreviewAutomationBroker.layer.pipe(Layer.provide(NodeServices.layer))),
|
||||
Layer.provideMerge(PreviewAutomationBroker.layer),
|
||||
);
|
||||
|
||||
it("normalizes empty successful notification responses to accepted", () => {
|
||||
@@ -55,26 +54,36 @@ it.effect("returns bounded structural preview snapshot failures", () =>
|
||||
Effect.gen(function* () {
|
||||
const server = yield* McpServer.McpServer;
|
||||
const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
|
||||
const events = yield* broker.connect({
|
||||
const requests = yield* broker.connect({
|
||||
clientId: "mcp-failure-client",
|
||||
environmentId,
|
||||
threadId,
|
||||
tabId,
|
||||
visible: true,
|
||||
supportsAutomation: true,
|
||||
focusedAt: "2026-06-11T00:00:00.000Z",
|
||||
});
|
||||
yield* Stream.runForEach(events, (event) =>
|
||||
event.type === "connected"
|
||||
? Effect.void
|
||||
: broker.respond({
|
||||
clientId: "mcp-failure-client",
|
||||
connectionId: event.connectionId,
|
||||
requestId: event.request.requestId,
|
||||
ok: false,
|
||||
error: {
|
||||
_tag: "PreviewAutomationExecutionError",
|
||||
message: "sensitive renderer failure",
|
||||
detail: { consoleOutput: "sensitive browser output" },
|
||||
},
|
||||
}),
|
||||
yield* Stream.runForEach(requests, (request) =>
|
||||
broker.respond({
|
||||
requestId: request.requestId,
|
||||
ok: false,
|
||||
error: {
|
||||
_tag: "PreviewAutomationExecutionError",
|
||||
message: "sensitive renderer failure",
|
||||
detail: { consoleOutput: "sensitive browser output" },
|
||||
},
|
||||
}),
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
yield* broker.reportOwner({
|
||||
clientId: "mcp-failure-client",
|
||||
environmentId,
|
||||
threadId,
|
||||
tabId,
|
||||
visible: true,
|
||||
supportsAutomation: true,
|
||||
focusedAt: "2026-06-11T00:00:00.000Z",
|
||||
});
|
||||
|
||||
const snapshot = yield* server
|
||||
.callTool({ name: "preview_snapshot", arguments: {} })
|
||||
@@ -154,50 +163,60 @@ it.effect("registers annotated tools and preserves authenticated request context
|
||||
Effect.gen(function* () {
|
||||
const server = yield* McpServer.McpServer;
|
||||
const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
|
||||
const events = yield* broker.connect({
|
||||
const requests = yield* broker.connect({
|
||||
clientId: "mcp-test-client",
|
||||
environmentId,
|
||||
threadId,
|
||||
tabId,
|
||||
visible: true,
|
||||
supportsAutomation: true,
|
||||
focusedAt: "2026-06-11T00:00:00.000Z",
|
||||
});
|
||||
yield* Stream.runForEach(events, (event) =>
|
||||
event.type === "connected"
|
||||
? Effect.void
|
||||
: broker.respond({
|
||||
clientId: "mcp-test-client",
|
||||
connectionId: event.connectionId,
|
||||
requestId: event.request.requestId,
|
||||
ok: true,
|
||||
result:
|
||||
event.request.operation === "snapshot"
|
||||
? {
|
||||
url: "http://example.test/",
|
||||
title: "Example",
|
||||
loading: false,
|
||||
visibleText: "Example",
|
||||
interactiveElements: [],
|
||||
accessibilityTree: {},
|
||||
consoleEntries: [],
|
||||
networkEntries: [],
|
||||
actionTimeline: [],
|
||||
screenshot: {
|
||||
mimeType: "image/png",
|
||||
data: Buffer.from("png").toString("base64"),
|
||||
width: 10,
|
||||
height: 5,
|
||||
},
|
||||
}
|
||||
: event.request.operation === "press"
|
||||
? undefined
|
||||
: {
|
||||
available: true,
|
||||
visible: true,
|
||||
tabId,
|
||||
url: "http://example.test/",
|
||||
title: "Example",
|
||||
loading: false,
|
||||
},
|
||||
}),
|
||||
yield* Stream.runForEach(requests, (request) =>
|
||||
broker.respond({
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
result:
|
||||
request.operation === "snapshot"
|
||||
? {
|
||||
url: "http://example.test/",
|
||||
title: "Example",
|
||||
loading: false,
|
||||
visibleText: "Example",
|
||||
interactiveElements: [],
|
||||
accessibilityTree: {},
|
||||
consoleEntries: [],
|
||||
networkEntries: [],
|
||||
actionTimeline: [],
|
||||
screenshot: {
|
||||
mimeType: "image/png",
|
||||
data: Buffer.from("png").toString("base64"),
|
||||
width: 10,
|
||||
height: 5,
|
||||
},
|
||||
}
|
||||
: request.operation === "press"
|
||||
? undefined
|
||||
: {
|
||||
available: true,
|
||||
visible: true,
|
||||
tabId,
|
||||
url: "http://example.test/",
|
||||
title: "Example",
|
||||
loading: false,
|
||||
},
|
||||
}),
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
yield* broker.reportOwner({
|
||||
clientId: "mcp-test-client",
|
||||
environmentId,
|
||||
threadId,
|
||||
tabId,
|
||||
visible: true,
|
||||
supportsAutomation: true,
|
||||
focusedAt: "2026-06-11T00:00:00.000Z",
|
||||
});
|
||||
|
||||
const statusTool = server.tools.find(({ tool }) => tool.name === "preview_status");
|
||||
expect(statusTool?.tool.annotations?.readOnlyHint).toBe(true);
|
||||
|
||||
@@ -214,4 +214,7 @@ const McpTransportLive = McpServer.layerHttp({
|
||||
path: "/mcp",
|
||||
}).pipe(Layer.provide(McpAuthMiddlewareLive));
|
||||
|
||||
export const layer = PreviewToolkitRegistrationLive.pipe(Layer.provideMerge(McpTransportLive));
|
||||
export const layer = PreviewToolkitRegistrationLive.pipe(
|
||||
Layer.provideMerge(McpTransportLive),
|
||||
Layer.provide(PreviewAutomationBroker.layer),
|
||||
);
|
||||
@@ -1,28 +1,20 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import {
|
||||
EnvironmentId,
|
||||
PreviewAutomationClientDisconnectedError,
|
||||
PreviewAutomationInvalidSelectorError,
|
||||
PreviewAutomationMalformedResponseError,
|
||||
PreviewAutomationNoAvailableHostError,
|
||||
PreviewAutomationTargetNotEditableError,
|
||||
PreviewTabId,
|
||||
PreviewAutomationNoFocusedOwnerError,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
type PreviewAutomationHost,
|
||||
type PreviewAutomationRequest,
|
||||
type PreviewAutomationStreamEvent,
|
||||
type PreviewAutomationOwner,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Result from "effect/Result";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import * as PreviewAutomationBroker from "./PreviewAutomationBroker.ts";
|
||||
|
||||
const makeBroker = PreviewAutomationBroker.make.pipe(Effect.provide(NodeServices.layer));
|
||||
|
||||
const scope = {
|
||||
environmentId: EnvironmentId.make("environment-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
@@ -30,42 +22,27 @@ const scope = {
|
||||
providerInstanceId: ProviderInstanceId.make("codex"),
|
||||
capabilities: new Set(["preview"] as const),
|
||||
issuedAt: 1,
|
||||
expiresAt: Number.MAX_SAFE_INTEGER,
|
||||
expiresAt: 2,
|
||||
};
|
||||
|
||||
const makeHost = (overrides: Partial<PreviewAutomationHost> = {}): PreviewAutomationHost => ({
|
||||
const makeOwner = (overrides: Partial<PreviewAutomationOwner> = {}): PreviewAutomationOwner => ({
|
||||
clientId: "client-1",
|
||||
environmentId: scope.environmentId,
|
||||
threadId: scope.threadId,
|
||||
tabId: null,
|
||||
visible: false,
|
||||
supportsAutomation: true,
|
||||
focusedAt: "2026-06-11T00:00:00.000Z",
|
||||
...overrides,
|
||||
});
|
||||
|
||||
type RoutedRequest = PreviewAutomationRequest & {
|
||||
readonly connectionId: PreviewAutomationStreamEvent["connectionId"];
|
||||
};
|
||||
|
||||
const requestsFrom = (
|
||||
events: Stream.Stream<PreviewAutomationStreamEvent>,
|
||||
onConnected: (connectionId: PreviewAutomationStreamEvent["connectionId"]) => void = () => {},
|
||||
): Stream.Stream<RoutedRequest> =>
|
||||
events.pipe(
|
||||
Stream.filterMap((event) => {
|
||||
if (event.type === "connected") {
|
||||
onConnected(event.connectionId);
|
||||
return Result.failVoid;
|
||||
}
|
||||
return Result.succeed({ ...event.request, connectionId: event.connectionId });
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("atomically registers a connected host and correlates its response", () =>
|
||||
it.effect("atomically registers a connected owner and correlates its response", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* makeBroker;
|
||||
const requests = requestsFrom(yield* broker.connect(makeHost()));
|
||||
const broker = yield* PreviewAutomationBroker.make;
|
||||
const requests = yield* broker.connect(makeOwner());
|
||||
yield* Stream.runForEach(requests, (request) =>
|
||||
broker.respond({
|
||||
clientId: "client-1",
|
||||
connectionId: request.connectionId,
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
result: { available: true },
|
||||
@@ -84,39 +61,6 @@ it.effect("atomically registers a connected host and correlates its response", (
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("announces a live replacement stream before delivering requests", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* makeBroker;
|
||||
const events = yield* broker.connect(makeHost());
|
||||
const receivedTypes: PreviewAutomationStreamEvent["type"][] = [];
|
||||
const consumer = yield* events.pipe(
|
||||
Stream.take(2),
|
||||
Stream.runForEach((event) => {
|
||||
receivedTypes.push(event.type);
|
||||
return event.type === "connected"
|
||||
? Effect.void
|
||||
: broker.respond({
|
||||
clientId: "client-1",
|
||||
connectionId: event.connectionId,
|
||||
requestId: event.request.requestId,
|
||||
ok: true,
|
||||
result: "ready",
|
||||
});
|
||||
}),
|
||||
Effect.forkScoped,
|
||||
);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
const result = yield* broker.invoke<string>({ scope, operation: "status", input: {} });
|
||||
yield* Fiber.join(consumer);
|
||||
|
||||
expect(receivedTypes).toEqual(["connected", "request"]);
|
||||
expect(result).toBe("ready");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("preserves bounded request and remote selector diagnostics", () => {
|
||||
const locator = "role=button[name='request-secret']";
|
||||
const remoteMessage = "Unexpected token near remote-secret.";
|
||||
@@ -128,12 +72,10 @@ it.effect("preserves bounded request and remote selector diagnostics", () => {
|
||||
|
||||
return Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* makeBroker;
|
||||
const requests = requestsFrom(yield* broker.connect(makeHost()));
|
||||
const broker = yield* PreviewAutomationBroker.make;
|
||||
const requests = yield* broker.connect(makeOwner({ tabId: "tab-1" }));
|
||||
yield* Stream.runForEach(requests, (request) =>
|
||||
broker.respond({
|
||||
clientId: "client-1",
|
||||
connectionId: request.connectionId,
|
||||
requestId: request.requestId,
|
||||
ok: false,
|
||||
error: remoteError,
|
||||
@@ -146,7 +88,6 @@ it.effect("preserves bounded request and remote selector diagnostics", () => {
|
||||
scope,
|
||||
operation: "click",
|
||||
input: { locator },
|
||||
tabId: PreviewTabId.make("tab-1"),
|
||||
timeoutMs: 1_234,
|
||||
})
|
||||
.pipe(Effect.flip);
|
||||
@@ -180,61 +121,13 @@ it.effect("preserves bounded request and remote selector diagnostics", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("classifies a remote non-editable target without collapsing it to execution", () => {
|
||||
const remoteError = {
|
||||
_tag: "PreviewAutomationTargetNotEditableError",
|
||||
message: "remote target details",
|
||||
detail: { selectorKind: "focused-element" },
|
||||
} as const;
|
||||
|
||||
return Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* makeBroker;
|
||||
const requests = requestsFrom(yield* broker.connect(makeHost()));
|
||||
yield* Stream.runForEach(requests, (request) =>
|
||||
broker.respond({
|
||||
clientId: "client-1",
|
||||
connectionId: request.connectionId,
|
||||
requestId: request.requestId,
|
||||
ok: false,
|
||||
error: remoteError,
|
||||
}),
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
const error = yield* broker
|
||||
.invoke<void>({
|
||||
scope,
|
||||
operation: "type",
|
||||
input: { text: "hello" },
|
||||
tabId: PreviewTabId.make("tab-1"),
|
||||
})
|
||||
.pipe(Effect.flip);
|
||||
|
||||
expect(error).toBeInstanceOf(PreviewAutomationTargetNotEditableError);
|
||||
expect(error).toMatchObject({
|
||||
operation: "type",
|
||||
tabId: "tab-1",
|
||||
selectorKind: "focused-element",
|
||||
remoteTag: "PreviewAutomationTargetNotEditableError",
|
||||
});
|
||||
expect(error.message).toBe("Preview automation type requires an editable focused element.");
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("distinguishes malformed remote failures", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* makeBroker;
|
||||
const requests = requestsFrom(yield* broker.connect(makeHost()));
|
||||
const broker = yield* PreviewAutomationBroker.make;
|
||||
const requests = yield* broker.connect(makeOwner());
|
||||
yield* Stream.runForEach(requests, (request) =>
|
||||
broker.respond({
|
||||
clientId: "client-1",
|
||||
connectionId: request.connectionId,
|
||||
requestId: request.requestId,
|
||||
ok: false,
|
||||
}),
|
||||
broker.respond({ requestId: request.requestId, ok: false }),
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
@@ -257,14 +150,13 @@ it.effect("distinguishes malformed remote failures", () =>
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("rejects calls when no connected host exists", () =>
|
||||
it.effect("rejects calls when no focused owner exists", () =>
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* makeBroker;
|
||||
const broker = yield* PreviewAutomationBroker.make;
|
||||
const error = yield* broker
|
||||
.invoke<void>({ scope, operation: "status", input: {} })
|
||||
.pipe(Effect.flip);
|
||||
|
||||
expect(error).toBeInstanceOf(PreviewAutomationNoAvailableHostError);
|
||||
expect(error).toBeInstanceOf(PreviewAutomationNoFocusedOwnerError);
|
||||
expect(error).toMatchObject({
|
||||
operation: "status",
|
||||
environmentId: scope.environmentId,
|
||||
@@ -275,425 +167,32 @@ it.effect("rejects calls when no connected host exists", () =>
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not create host state from focus updates without a live stream", () =>
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* makeBroker;
|
||||
yield* broker.focusHost({
|
||||
clientId: "client-1",
|
||||
environmentId: scope.environmentId,
|
||||
connectionId: "connection-missing",
|
||||
focused: true,
|
||||
});
|
||||
|
||||
const error = yield* broker
|
||||
.invoke<void>({ scope, operation: "status", input: {} })
|
||||
.pipe(Effect.flip);
|
||||
expect(error).toBeInstanceOf(PreviewAutomationNoAvailableHostError);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("removes host availability when the authoritative request stream disconnects", () =>
|
||||
it.effect("routes interactive commands to a hidden durable browser host", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* makeBroker;
|
||||
const requests = requestsFrom(yield* broker.connect(makeHost()));
|
||||
const beforeAcquisition = yield* broker
|
||||
.invoke<void>({ scope, operation: "status", input: {} })
|
||||
.pipe(Effect.flip);
|
||||
expect(beforeAcquisition).toBeInstanceOf(PreviewAutomationNoAvailableHostError);
|
||||
|
||||
const consumer = yield* Stream.runDrain(requests).pipe(Effect.forkScoped);
|
||||
const broker = yield* PreviewAutomationBroker.make;
|
||||
const requests = yield* broker.connect(
|
||||
makeOwner({ clientId: "client-hidden", tabId: "tab-hidden" }),
|
||||
);
|
||||
yield* Stream.runForEach(requests, (request) =>
|
||||
broker.respond({ requestId: request.requestId, ok: true }),
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
yield* Fiber.interrupt(consumer);
|
||||
|
||||
const error = yield* broker
|
||||
.invoke<void>({ scope, operation: "status", input: {} })
|
||||
.pipe(Effect.flip);
|
||||
expect(error).toBeInstanceOf(PreviewAutomationNoAvailableHostError);
|
||||
yield* broker.invoke<void>({ scope, operation: "click", input: { x: 10, y: 10 } });
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("routes requests for background threads through an environment-level host", () =>
|
||||
it.effect("lets the browser host resolve an active tab that has not been reported yet", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* makeBroker;
|
||||
const backgroundThreadId = ThreadId.make("thread-background");
|
||||
const requests = requestsFrom(yield* broker.connect(makeHost()));
|
||||
let routedThreadId: string | undefined;
|
||||
yield* Stream.runForEach(requests, (request) => {
|
||||
routedThreadId = request.threadId;
|
||||
return broker.respond({
|
||||
clientId: "client-1",
|
||||
connectionId: request.connectionId,
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
result: "background",
|
||||
});
|
||||
}).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
const result = yield* broker.invoke<string>({
|
||||
scope: {
|
||||
...scope,
|
||||
threadId: backgroundThreadId,
|
||||
providerSessionId: "provider-session-background",
|
||||
},
|
||||
operation: "status",
|
||||
input: {},
|
||||
});
|
||||
|
||||
expect(result).toBe("background");
|
||||
expect(routedThreadId).toBe(backgroundThreadId);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("never routes a provider session to a host from another environment", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* makeBroker;
|
||||
const matchingRequests = requestsFrom(
|
||||
yield* broker.connect(makeHost({ clientId: "client-matching" })),
|
||||
);
|
||||
const foreignRequests = requestsFrom(
|
||||
yield* broker.connect(
|
||||
makeHost({
|
||||
clientId: "client-foreign",
|
||||
environmentId: EnvironmentId.make("environment-foreign"),
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* Stream.runForEach(matchingRequests, (request) =>
|
||||
broker.respond({
|
||||
clientId: "client-matching",
|
||||
connectionId: request.connectionId,
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
result: "matching",
|
||||
}),
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* Stream.runForEach(foreignRequests, (request) =>
|
||||
broker.respond({
|
||||
clientId: "client-foreign",
|
||||
connectionId: request.connectionId,
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
result: "foreign",
|
||||
}),
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
expect(yield* broker.invoke<string>({ scope, operation: "status", input: {} })).toBe(
|
||||
"matching",
|
||||
);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("pins a provider session to its initial host despite later focus changes", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* makeBroker;
|
||||
let firstConnectionId = "";
|
||||
let secondConnectionId = "";
|
||||
const firstRequests = requestsFrom(
|
||||
yield* broker.connect(makeHost({ clientId: "client-first" })),
|
||||
(connectionId) => {
|
||||
firstConnectionId = connectionId;
|
||||
},
|
||||
);
|
||||
const secondRequests = requestsFrom(
|
||||
yield* broker.connect(makeHost({ clientId: "client-second" })),
|
||||
(connectionId) => {
|
||||
secondConnectionId = connectionId;
|
||||
},
|
||||
);
|
||||
yield* Stream.runForEach(firstRequests, (request) =>
|
||||
broker.respond({
|
||||
clientId: "client-first",
|
||||
connectionId: request.connectionId,
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
result: "first",
|
||||
}),
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* Stream.runForEach(secondRequests, (request) =>
|
||||
broker.respond({
|
||||
clientId: "client-second",
|
||||
connectionId: request.connectionId,
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
result: "second",
|
||||
}),
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
yield* broker.focusHost({
|
||||
clientId: "client-first",
|
||||
environmentId: scope.environmentId,
|
||||
connectionId: "connection-stale",
|
||||
focused: true,
|
||||
});
|
||||
expect(yield* broker.invoke<string>({ scope, operation: "status", input: {} })).toBe(
|
||||
"second",
|
||||
);
|
||||
yield* broker.focusHost({
|
||||
clientId: "client-first",
|
||||
environmentId: scope.environmentId,
|
||||
connectionId: firstConnectionId,
|
||||
focused: true,
|
||||
});
|
||||
|
||||
const firstPinnedScope = {
|
||||
...scope,
|
||||
providerSessionId: "provider-session-first-pinned",
|
||||
};
|
||||
expect(
|
||||
yield* broker.invoke<string>({ scope: firstPinnedScope, operation: "status", input: {} }),
|
||||
).toBe("first");
|
||||
|
||||
yield* broker.focusHost({
|
||||
clientId: "client-second",
|
||||
environmentId: scope.environmentId,
|
||||
connectionId: secondConnectionId,
|
||||
focused: true,
|
||||
});
|
||||
|
||||
expect(
|
||||
yield* broker.invoke<string>({ scope: firstPinnedScope, operation: "status", input: {} }),
|
||||
).toBe("first");
|
||||
expect(
|
||||
yield* broker.invoke<string>({
|
||||
scope: { ...scope, providerSessionId: "provider-session-second-pinned" },
|
||||
operation: "status",
|
||||
input: {},
|
||||
}),
|
||||
).toBe("second");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("does not route new operations to legacy hosts that did not advertise support", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* makeBroker;
|
||||
const legacyEvents = yield* broker.connect(makeHost());
|
||||
yield* Stream.runDrain(legacyEvents).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
const error = yield* broker
|
||||
.invoke<void>({ scope, operation: "resize", input: { mode: "fill" } })
|
||||
.pipe(Effect.flip);
|
||||
|
||||
expect(error).toBeInstanceOf(PreviewAutomationNoAvailableHostError);
|
||||
expect(error).toMatchObject({ operation: "resize", environmentId: scope.environmentId });
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("routes resize to a capable host instead of a newer legacy connection", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* makeBroker;
|
||||
const capableRequests = requestsFrom(
|
||||
yield* broker.connect(
|
||||
makeHost({ clientId: "client-capable", supportedOperations: ["resize"] }),
|
||||
),
|
||||
);
|
||||
const legacyRequests = requestsFrom(
|
||||
yield* broker.connect(makeHost({ clientId: "client-legacy" })),
|
||||
);
|
||||
yield* Stream.runForEach(capableRequests, (request) =>
|
||||
broker.respond({
|
||||
clientId: "client-capable",
|
||||
connectionId: request.connectionId,
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
result: "capable",
|
||||
}),
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* Stream.runForEach(legacyRequests, (request) =>
|
||||
broker.respond({
|
||||
clientId: "client-legacy",
|
||||
connectionId: request.connectionId,
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
result: "legacy",
|
||||
}),
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
expect(
|
||||
yield* broker.invoke<string>({ scope, operation: "resize", input: { mode: "fill" } }),
|
||||
).toBe("capable");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("does not move a live legacy assignment to another runtime for resize", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* makeBroker;
|
||||
const legacyRequests = requestsFrom(
|
||||
yield* broker.connect(makeHost({ clientId: "client-legacy" })),
|
||||
);
|
||||
yield* Stream.runForEach(legacyRequests, (request) =>
|
||||
broker.respond({
|
||||
clientId: "client-legacy",
|
||||
connectionId: request.connectionId,
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
result: "legacy",
|
||||
}),
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
expect(yield* broker.invoke<string>({ scope, operation: "status", input: {} })).toBe(
|
||||
"legacy",
|
||||
);
|
||||
|
||||
const capableRequests = requestsFrom(
|
||||
yield* broker.connect(
|
||||
makeHost({ clientId: "client-capable", supportedOperations: ["resize"] }),
|
||||
),
|
||||
);
|
||||
yield* Stream.runForEach(capableRequests, (request) =>
|
||||
broker.respond({
|
||||
clientId: "client-capable",
|
||||
connectionId: request.connectionId,
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
result: "capable",
|
||||
}),
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
const error = yield* broker
|
||||
.invoke<void>({ scope, operation: "resize", input: { mode: "fill" } })
|
||||
.pipe(Effect.flip);
|
||||
expect(error).toBeInstanceOf(PreviewAutomationNoAvailableHostError);
|
||||
expect(yield* broker.invoke<string>({ scope, operation: "status", input: {} })).toBe(
|
||||
"legacy",
|
||||
);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("ignores stale focus updates for a different environment", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* makeBroker;
|
||||
let firstConnectionId = "";
|
||||
const firstRequests = requestsFrom(
|
||||
yield* broker.connect(makeHost({ clientId: "client-first" })),
|
||||
(connectionId) => {
|
||||
firstConnectionId = connectionId;
|
||||
},
|
||||
);
|
||||
const secondRequests = requestsFrom(
|
||||
yield* broker.connect(makeHost({ clientId: "client-second" })),
|
||||
);
|
||||
yield* Stream.runForEach(firstRequests, (request) =>
|
||||
broker.respond({
|
||||
clientId: "client-first",
|
||||
connectionId: request.connectionId,
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
result: "first",
|
||||
}),
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* Stream.runForEach(secondRequests, (request) =>
|
||||
broker.respond({
|
||||
clientId: "client-second",
|
||||
connectionId: request.connectionId,
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
result: "second",
|
||||
}),
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
yield* broker.focusHost({
|
||||
clientId: "client-first",
|
||||
environmentId: EnvironmentId.make("environment-stale"),
|
||||
connectionId: firstConnectionId,
|
||||
focused: true,
|
||||
});
|
||||
|
||||
expect(yield* broker.invoke<string>({ scope, operation: "status", input: {} })).toBe(
|
||||
"second",
|
||||
);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("fails over a pinned provider session only after its host disconnects", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* makeBroker;
|
||||
let firstConnectionId = "";
|
||||
const firstRequests = requestsFrom(
|
||||
yield* broker.connect(makeHost({ clientId: "client-first" })),
|
||||
(connectionId) => {
|
||||
firstConnectionId = connectionId;
|
||||
},
|
||||
);
|
||||
const secondRequests = requestsFrom(
|
||||
yield* broker.connect(makeHost({ clientId: "client-second" })),
|
||||
);
|
||||
const firstConsumer = yield* Stream.runForEach(firstRequests, (request) =>
|
||||
broker.respond({
|
||||
clientId: "client-first",
|
||||
connectionId: request.connectionId,
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
result: "first",
|
||||
}),
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* Stream.runForEach(secondRequests, (request) =>
|
||||
broker.respond({
|
||||
clientId: "client-second",
|
||||
connectionId: request.connectionId,
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
result: "second",
|
||||
}),
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
yield* broker.focusHost({
|
||||
clientId: "client-first",
|
||||
environmentId: scope.environmentId,
|
||||
connectionId: firstConnectionId,
|
||||
focused: true,
|
||||
});
|
||||
expect(yield* broker.invoke<string>({ scope, operation: "status", input: {} })).toBe("first");
|
||||
|
||||
yield* Fiber.interrupt(firstConsumer);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
expect(yield* broker.invoke<string>({ scope, operation: "status", input: {} })).toBe(
|
||||
"second",
|
||||
);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("lets the browser host resolve an active tab locally", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* makeBroker;
|
||||
const requests = requestsFrom(yield* broker.connect(makeHost()));
|
||||
const broker = yield* PreviewAutomationBroker.make;
|
||||
const requests = yield* broker.connect(makeOwner({ tabId: null }));
|
||||
let routedTabId: string | undefined;
|
||||
yield* Stream.runForEach(requests, (request) => {
|
||||
routedTabId = request.tabId;
|
||||
return broker.respond({
|
||||
clientId: "client-1",
|
||||
connectionId: request.connectionId,
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
});
|
||||
return broker.respond({ requestId: request.requestId, ok: true });
|
||||
}).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
@@ -704,55 +203,61 @@ it.effect("lets the browser host resolve an active tab locally", () =>
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("keeps a replacement stream authoritative when the old stream finalizes", () =>
|
||||
it.effect("preserves current owner metadata when its request stream reconnects", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* makeBroker;
|
||||
let firstConnectionId = "";
|
||||
let replacementConnectionId = "";
|
||||
const firstRequests = requestsFrom(yield* broker.connect(makeHost()), (connectionId) => {
|
||||
firstConnectionId = connectionId;
|
||||
});
|
||||
const broker = yield* PreviewAutomationBroker.make;
|
||||
const firstRequests = yield* broker.connect(makeOwner());
|
||||
yield* Stream.runDrain(firstRequests).pipe(Effect.forkScoped);
|
||||
yield* broker.reportOwner(makeOwner({ tabId: "tab-current", visible: true }));
|
||||
|
||||
const reconnectedRequests = yield* broker.connect(makeOwner());
|
||||
let routedTabId: string | undefined;
|
||||
yield* Stream.runForEach(reconnectedRequests, (request) => {
|
||||
routedTabId = request.tabId;
|
||||
return broker.respond({ requestId: request.requestId, ok: true });
|
||||
}).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
const replacementRequests = requestsFrom(
|
||||
yield* broker.connect(makeHost()),
|
||||
(connectionId) => {
|
||||
replacementConnectionId = connectionId;
|
||||
},
|
||||
);
|
||||
yield* Stream.runForEach(replacementRequests, (request) =>
|
||||
broker.respond({
|
||||
clientId: "client-1",
|
||||
connectionId: request.connectionId,
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
result: "replacement",
|
||||
}),
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
yield* broker.invoke<void>({ scope, operation: "click", input: { x: 10, y: 10 } });
|
||||
|
||||
expect(replacementConnectionId).not.toBe(firstConnectionId);
|
||||
const result = yield* broker.invoke<string>({ scope, operation: "status", input: {} });
|
||||
expect(result).toBe("replacement");
|
||||
expect(routedTabId).toBe("tab-current");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("fails requests assigned to the stream that is replaced", () =>
|
||||
it.effect("ignores stale owner cleanup after the client moves to another thread", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* makeBroker;
|
||||
const requests = requestsFrom(yield* broker.connect(makeHost()));
|
||||
yield* Stream.runDrain(requests).pipe(Effect.forkScoped);
|
||||
const broker = yield* PreviewAutomationBroker.make;
|
||||
const requests = yield* broker.connect(makeOwner());
|
||||
yield* Stream.runForEach(requests, (request) =>
|
||||
broker.respond({ requestId: request.requestId, ok: true }),
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
yield* broker.clearOwner({
|
||||
clientId: "client-1",
|
||||
environmentId: scope.environmentId,
|
||||
threadId: ThreadId.make("thread-stale"),
|
||||
});
|
||||
|
||||
yield* broker.invoke<void>({ scope, operation: "status", input: {} });
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("fails requests assigned to a browser stream when that stream reconnects", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* PreviewAutomationBroker.make;
|
||||
const _requests = yield* broker.connect(makeOwner());
|
||||
const pending = yield* broker
|
||||
.invoke<void>({ scope, operation: "status", input: {} })
|
||||
.pipe(Effect.flip, Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
const replacementRequests = requestsFrom(yield* broker.connect(makeHost()));
|
||||
yield* Stream.runDrain(replacementRequests).pipe(Effect.forkScoped);
|
||||
const _replacementRequests = yield* broker.connect(makeOwner());
|
||||
|
||||
const error = yield* Fiber.join(pending);
|
||||
expect(error).toBeInstanceOf(PreviewAutomationClientDisconnectedError);
|
||||
@@ -770,40 +275,25 @@ it.effect("fails requests assigned to the stream that is replaced", () =>
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("accepts responses only from the host that received the request", () =>
|
||||
it.effect("falls back to an older connected owner when a newer report is not connected", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* makeBroker;
|
||||
const requests = requestsFrom(yield* broker.connect(makeHost()));
|
||||
const broker = yield* PreviewAutomationBroker.make;
|
||||
const requests = yield* broker.connect(makeOwner({ clientId: "client-connected" }));
|
||||
yield* Stream.runForEach(requests, (request) =>
|
||||
Effect.gen(function* () {
|
||||
yield* broker.respond({
|
||||
clientId: "client-foreign",
|
||||
connectionId: request.connectionId,
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
result: "foreign",
|
||||
});
|
||||
yield* broker.respond({
|
||||
clientId: "client-1",
|
||||
connectionId: "connection-stale",
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
result: "stale",
|
||||
});
|
||||
yield* broker.respond({
|
||||
clientId: "client-1",
|
||||
connectionId: request.connectionId,
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
result: "owner",
|
||||
});
|
||||
}),
|
||||
broker.respond({ requestId: request.requestId, ok: true, result: "connected" }),
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
yield* broker.reportOwner(
|
||||
makeOwner({
|
||||
clientId: "client-report-only",
|
||||
focusedAt: "2026-06-11T00:00:01.000Z",
|
||||
}),
|
||||
);
|
||||
|
||||
const result = yield* broker.invoke<string>({ scope, operation: "status", input: {} });
|
||||
expect(result).toBe("owner");
|
||||
|
||||
expect(result).toBe("connected");
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -1,29 +1,26 @@
|
||||
import {
|
||||
PREVIEW_AUTOMATION_V1_OPERATIONS,
|
||||
PreviewAutomationClientDisconnectedError,
|
||||
PreviewAutomationControlInterruptedError,
|
||||
PreviewAutomationExecutionError,
|
||||
PreviewAutomationHostNotConnectedError,
|
||||
PreviewAutomationInvalidSelectorError,
|
||||
PreviewAutomationMalformedResponseError,
|
||||
PreviewAutomationNoAvailableHostError,
|
||||
PreviewAutomationNoFocusedOwnerError,
|
||||
PreviewAutomationRemoteUnavailableError,
|
||||
PreviewAutomationRequestQueueClosedError,
|
||||
PreviewAutomationResultTooLargeError,
|
||||
PreviewAutomationTabNotFoundError,
|
||||
PreviewAutomationTargetNotEditableError,
|
||||
PreviewAutomationTimeoutError,
|
||||
PreviewAutomationUnsupportedClientError,
|
||||
type PreviewAutomationError,
|
||||
type PreviewAutomationOperation,
|
||||
type PreviewAutomationHost,
|
||||
type PreviewAutomationHostFocus,
|
||||
type PreviewAutomationOwner,
|
||||
type PreviewAutomationOwnerIdentity,
|
||||
type PreviewAutomationRequest,
|
||||
type PreviewAutomationResponse,
|
||||
type PreviewAutomationStreamEvent,
|
||||
type PreviewTabId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Clock from "effect/Clock";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
@@ -46,9 +43,12 @@ export class PreviewAutomationBroker extends Context.Service<
|
||||
PreviewAutomationBroker,
|
||||
{
|
||||
readonly connect: (
|
||||
host: PreviewAutomationHost,
|
||||
) => Effect.Effect<Stream.Stream<PreviewAutomationStreamEvent>>;
|
||||
readonly focusHost: (host: PreviewAutomationHostFocus) => Effect.Effect<void>;
|
||||
owner: PreviewAutomationOwner,
|
||||
) => Effect.Effect<Stream.Stream<PreviewAutomationRequest>>;
|
||||
readonly reportOwner: (
|
||||
owner: PreviewAutomationOwner,
|
||||
) => Effect.Effect<void, PreviewAutomationError>;
|
||||
readonly clearOwner: (owner: PreviewAutomationOwnerIdentity) => Effect.Effect<void>;
|
||||
readonly respond: (
|
||||
response: PreviewAutomationResponse,
|
||||
) => Effect.Effect<void, PreviewAutomationError>;
|
||||
@@ -60,12 +60,7 @@ export class PreviewAutomationBroker extends Context.Service<
|
||||
|
||||
interface ClientConnection {
|
||||
readonly clientId: string;
|
||||
readonly connectionId: string;
|
||||
readonly environmentId: PreviewAutomationHost["environmentId"];
|
||||
readonly supportedOperations: ReadonlySet<PreviewAutomationOperation>;
|
||||
readonly focused: boolean;
|
||||
readonly focusOrder: number;
|
||||
readonly queue: Queue.Queue<PreviewAutomationStreamEvent>;
|
||||
readonly queue: Queue.Queue<PreviewAutomationRequest>;
|
||||
}
|
||||
|
||||
interface PendingRequest {
|
||||
@@ -74,13 +69,6 @@ interface PendingRequest {
|
||||
readonly context: PreviewAutomationRequestErrorContext;
|
||||
}
|
||||
|
||||
interface HostAssignment {
|
||||
readonly clientId: ClientConnection["clientId"];
|
||||
readonly connectionId: ClientConnection["connectionId"];
|
||||
readonly queue: ClientConnection["queue"];
|
||||
readonly expiresAt: number;
|
||||
}
|
||||
|
||||
interface PreviewAutomationRequestErrorContext {
|
||||
readonly operation: PreviewAutomationOperation;
|
||||
readonly environmentId: McpInvocationContext.McpInvocationScope["environmentId"];
|
||||
@@ -88,7 +76,6 @@ interface PreviewAutomationRequestErrorContext {
|
||||
readonly providerSessionId: string;
|
||||
readonly providerInstanceId: McpInvocationContext.McpInvocationScope["providerInstanceId"];
|
||||
readonly clientId: string;
|
||||
readonly connectionId: ClientConnection["connectionId"];
|
||||
readonly requestId: string;
|
||||
readonly tabId?: PreviewTabId;
|
||||
readonly timeoutMs: number;
|
||||
@@ -98,36 +85,11 @@ interface PreviewAutomationRequestErrorContext {
|
||||
|
||||
interface BrokerState {
|
||||
readonly clients: ReadonlyMap<string, ClientConnection>;
|
||||
readonly assignments: ReadonlyMap<string, HostAssignment>;
|
||||
readonly owners: ReadonlyMap<string, PreviewAutomationOwner>;
|
||||
readonly pending: ReadonlyMap<string, PendingRequest>;
|
||||
readonly requestSequence: number;
|
||||
readonly focusSequence: number;
|
||||
}
|
||||
|
||||
const removeConnectionFromState = (
|
||||
current: BrokerState,
|
||||
clientId: string,
|
||||
queue: ClientConnection["queue"],
|
||||
): { readonly state: BrokerState; readonly disconnected: ReadonlyArray<PendingRequest> } => {
|
||||
const clients = new Map(current.clients);
|
||||
const assignments = new Map(current.assignments);
|
||||
const pending = new Map(current.pending);
|
||||
const disconnected: PendingRequest[] = [];
|
||||
if (current.clients.get(clientId)?.queue === queue) clients.delete(clientId);
|
||||
for (const [assignmentKey, assignment] of assignments) {
|
||||
if (assignment.queue === queue) assignments.delete(assignmentKey);
|
||||
}
|
||||
for (const [requestId, entry] of pending) {
|
||||
if (entry.queue !== queue) continue;
|
||||
pending.delete(requestId);
|
||||
disconnected.push(entry);
|
||||
}
|
||||
return {
|
||||
state: { ...current, clients, assignments, pending },
|
||||
disconnected,
|
||||
};
|
||||
};
|
||||
|
||||
const selectorDiagnosticsFromInput = (
|
||||
input: unknown,
|
||||
): Pick<PreviewAutomationRequestErrorContext, "selectorKind" | "selectorLength"> => {
|
||||
@@ -141,14 +103,6 @@ const selectorDiagnosticsFromInput = (
|
||||
return {};
|
||||
};
|
||||
|
||||
const hostAssignmentKey = (scope: McpInvocationContext.McpInvocationScope): string =>
|
||||
`${scope.environmentId}\u0000${scope.providerSessionId}`;
|
||||
|
||||
const supportsOperation = (
|
||||
connection: ClientConnection,
|
||||
operation: PreviewAutomationOperation,
|
||||
): boolean => connection.supportedOperations.has(operation);
|
||||
|
||||
type RemoteDetailKind = "null" | "array" | "object" | "string" | "number" | "boolean";
|
||||
|
||||
function remoteDetailKind(detail: unknown): RemoteDetailKind {
|
||||
@@ -177,8 +131,8 @@ const classifyResponseError = (
|
||||
cause: error,
|
||||
};
|
||||
switch (error._tag) {
|
||||
case "PreviewAutomationNoAvailableHostError":
|
||||
return new PreviewAutomationNoAvailableHostError({
|
||||
case "PreviewAutomationNoFocusedOwnerError":
|
||||
return new PreviewAutomationNoFocusedOwnerError({
|
||||
...context,
|
||||
...remoteDiagnostics,
|
||||
});
|
||||
@@ -208,36 +162,6 @@ const classifyResponseError = (
|
||||
...remoteDiagnostics,
|
||||
});
|
||||
}
|
||||
case "PreviewAutomationTargetNotEditableError": {
|
||||
const detail =
|
||||
typeof error.detail === "object" && error.detail !== null ? error.detail : undefined;
|
||||
const remoteSelectorKind =
|
||||
detail &&
|
||||
"selectorKind" in detail &&
|
||||
(detail.selectorKind === "focused-element" ||
|
||||
detail.selectorKind === "locator" ||
|
||||
detail.selectorKind === "selector")
|
||||
? detail.selectorKind
|
||||
: undefined;
|
||||
const remoteSelectorLength =
|
||||
detail &&
|
||||
"selectorLength" in detail &&
|
||||
typeof detail.selectorLength === "number" &&
|
||||
Number.isInteger(detail.selectorLength) &&
|
||||
detail.selectorLength >= 0
|
||||
? detail.selectorLength
|
||||
: undefined;
|
||||
return new PreviewAutomationTargetNotEditableError({
|
||||
...context,
|
||||
...remoteDiagnostics,
|
||||
...(remoteSelectorKind === undefined && context.selectorKind === undefined
|
||||
? {}
|
||||
: { selectorKind: remoteSelectorKind ?? context.selectorKind }),
|
||||
...(remoteSelectorLength === undefined && context.selectorLength === undefined
|
||||
? {}
|
||||
: { selectorLength: remoteSelectorLength ?? context.selectorLength }),
|
||||
});
|
||||
}
|
||||
case "PreviewAutomationResultTooLargeError": {
|
||||
const detail =
|
||||
typeof error.detail === "object" && error.detail !== null ? error.detail : undefined;
|
||||
@@ -269,21 +193,36 @@ const classifyResponseError = (
|
||||
};
|
||||
|
||||
export const make = Effect.gen(function* PreviewAutomationBrokerMake() {
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const state = yield* SynchronizedRef.make<BrokerState>({
|
||||
clients: new Map(),
|
||||
assignments: new Map(),
|
||||
owners: new Map(),
|
||||
pending: new Map(),
|
||||
requestSequence: 0,
|
||||
focusSequence: 0,
|
||||
});
|
||||
|
||||
const closeConnection = Effect.fn("PreviewAutomationBroker.closeConnection")(function* (
|
||||
const disconnect = Effect.fn("PreviewAutomationBroker.disconnect")(function* (
|
||||
clientId: string,
|
||||
queue: ClientConnection["queue"],
|
||||
disconnected: ReadonlyArray<PendingRequest>,
|
||||
) {
|
||||
const toFail = yield* SynchronizedRef.modify(state, (current) => {
|
||||
const clients = new Map(current.clients);
|
||||
const owners = new Map(current.owners);
|
||||
const pending = new Map(current.pending);
|
||||
const disconnected: PendingRequest[] = [];
|
||||
if (current.clients.get(clientId)?.queue === queue) {
|
||||
clients.delete(clientId);
|
||||
owners.delete(clientId);
|
||||
}
|
||||
for (const [requestId, entry] of pending) {
|
||||
if (entry.queue === queue) {
|
||||
pending.delete(requestId);
|
||||
disconnected.push(entry);
|
||||
}
|
||||
}
|
||||
return [disconnected, { ...current, clients, owners, pending }] as const;
|
||||
});
|
||||
yield* Effect.forEach(
|
||||
disconnected,
|
||||
toFail,
|
||||
({ deferred, context }) =>
|
||||
Deferred.fail(deferred, new PreviewAutomationClientDisconnectedError(context)),
|
||||
{ discard: true },
|
||||
@@ -291,89 +230,54 @@ export const make = Effect.gen(function* PreviewAutomationBrokerMake() {
|
||||
yield* Queue.shutdown(queue);
|
||||
});
|
||||
|
||||
const disconnect = Effect.fn("PreviewAutomationBroker.disconnect")(function* (
|
||||
clientId: string,
|
||||
queue: ClientConnection["queue"],
|
||||
) {
|
||||
const disconnected = yield* SynchronizedRef.modify(state, (current) => {
|
||||
const removed = removeConnectionFromState(current, clientId, queue);
|
||||
return [removed.disconnected, removed.state] as const;
|
||||
});
|
||||
yield* closeConnection(queue, disconnected);
|
||||
});
|
||||
|
||||
const acquireConnection = Effect.fn("PreviewAutomationBroker.acquireConnection")(function* (
|
||||
host: PreviewAutomationHost,
|
||||
) {
|
||||
const clientId = host.clientId;
|
||||
const queue = yield* Queue.unbounded<PreviewAutomationStreamEvent>();
|
||||
const connectionId = yield* crypto.randomUUIDv4.pipe(Effect.orDie);
|
||||
yield* Queue.offer(queue, { type: "connected", connectionId });
|
||||
const connection: ClientConnection = {
|
||||
clientId,
|
||||
connectionId,
|
||||
environmentId: host.environmentId,
|
||||
supportedOperations: new Set(host.supportedOperations ?? PREVIEW_AUTOMATION_V1_OPERATIONS),
|
||||
focused: false,
|
||||
focusOrder: 0,
|
||||
queue,
|
||||
};
|
||||
const registration = yield* SynchronizedRef.modify(state, (current) => {
|
||||
const previousConnection = current.clients.get(clientId);
|
||||
const removed = previousConnection
|
||||
? removeConnectionFromState(current, clientId, previousConnection.queue)
|
||||
: { state: current, disconnected: [] };
|
||||
const clients = new Map(removed.state.clients);
|
||||
const focusSequence = removed.state.focusSequence + 1;
|
||||
const registeredConnection = { ...connection, focusOrder: focusSequence };
|
||||
clients.set(clientId, registeredConnection);
|
||||
return [
|
||||
{
|
||||
previousConnection,
|
||||
disconnected: removed.disconnected,
|
||||
registeredConnection,
|
||||
},
|
||||
{ ...removed.state, clients, focusSequence },
|
||||
] as const;
|
||||
});
|
||||
if (registration.previousConnection) {
|
||||
yield* closeConnection(registration.previousConnection.queue, registration.disconnected);
|
||||
}
|
||||
return registration.registeredConnection;
|
||||
});
|
||||
|
||||
const connect: PreviewAutomationBroker["Service"]["connect"] = Effect.fn(
|
||||
"PreviewAutomationBroker.connect",
|
||||
)((host) =>
|
||||
Effect.succeed(
|
||||
Stream.unwrap(
|
||||
Effect.acquireRelease(acquireConnection(host), (connection) =>
|
||||
disconnect(connection.clientId, connection.queue),
|
||||
).pipe(Effect.map((connection) => Stream.fromQueue(connection.queue))),
|
||||
),
|
||||
),
|
||||
);
|
||||
)(function* (owner) {
|
||||
const clientId = owner.clientId;
|
||||
const queue = yield* Queue.unbounded<import("@t3tools/contracts").PreviewAutomationRequest>();
|
||||
const previous = yield* SynchronizedRef.modify(state, (current) => {
|
||||
const clients = new Map(current.clients);
|
||||
const owners = new Map(current.owners);
|
||||
const existingOwner = current.owners.get(clientId);
|
||||
clients.set(clientId, { clientId, queue });
|
||||
owners.set(
|
||||
clientId,
|
||||
existingOwner?.environmentId === owner.environmentId &&
|
||||
existingOwner.threadId === owner.threadId
|
||||
? { ...existingOwner, supportsAutomation: owner.supportsAutomation }
|
||||
: owner,
|
||||
);
|
||||
return [current.clients.get(clientId), { ...current, clients, owners }] as const;
|
||||
});
|
||||
if (previous) yield* disconnect(clientId, previous.queue);
|
||||
return Stream.fromQueue(queue).pipe(Stream.ensuring(disconnect(clientId, queue)));
|
||||
});
|
||||
|
||||
const focusHost: PreviewAutomationBroker["Service"]["focusHost"] = Effect.fn(
|
||||
"PreviewAutomationBroker.focusHost",
|
||||
)(function* (host) {
|
||||
const reportOwner: PreviewAutomationBroker["Service"]["reportOwner"] = Effect.fn(
|
||||
"PreviewAutomationBroker.reportOwner",
|
||||
)(function* (owner) {
|
||||
yield* SynchronizedRef.update(state, (current) => {
|
||||
const currentHost = current.clients.get(host.clientId);
|
||||
const owners = new Map(current.owners);
|
||||
owners.set(owner.clientId, owner);
|
||||
return { ...current, owners };
|
||||
});
|
||||
});
|
||||
|
||||
const clearOwner: PreviewAutomationBroker["Service"]["clearOwner"] = Effect.fn(
|
||||
"PreviewAutomationBroker.clearOwner",
|
||||
)(function* (owner) {
|
||||
yield* SynchronizedRef.update(state, (current) => {
|
||||
const currentOwner = current.owners.get(owner.clientId);
|
||||
if (
|
||||
!currentHost ||
|
||||
currentHost.environmentId !== host.environmentId ||
|
||||
currentHost.connectionId !== host.connectionId
|
||||
!currentOwner ||
|
||||
currentOwner.environmentId !== owner.environmentId ||
|
||||
currentOwner.threadId !== owner.threadId
|
||||
) {
|
||||
return current;
|
||||
}
|
||||
const clients = new Map(current.clients);
|
||||
const focusSequence = host.focused ? current.focusSequence + 1 : current.focusSequence;
|
||||
clients.set(host.clientId, {
|
||||
...currentHost,
|
||||
focused: host.focused,
|
||||
focusOrder: host.focused ? focusSequence : currentHost.focusOrder,
|
||||
});
|
||||
return { ...current, clients, focusSequence };
|
||||
const owners = new Map(current.owners);
|
||||
owners.delete(owner.clientId);
|
||||
return { ...current, owners };
|
||||
});
|
||||
});
|
||||
|
||||
@@ -382,13 +286,7 @@ export const make = Effect.gen(function* PreviewAutomationBrokerMake() {
|
||||
)(function* (response) {
|
||||
const pending = yield* SynchronizedRef.modify(state, (current) => {
|
||||
const entry = current.pending.get(response.requestId);
|
||||
if (
|
||||
!entry ||
|
||||
entry.context.clientId !== response.clientId ||
|
||||
entry.context.connectionId !== response.connectionId
|
||||
) {
|
||||
return [undefined, current] as const;
|
||||
}
|
||||
if (!entry) return [undefined, current] as const;
|
||||
const next = new Map(current.pending);
|
||||
next.delete(response.requestId);
|
||||
return [entry, { ...current, pending: next }] as const;
|
||||
@@ -409,83 +307,29 @@ export const make = Effect.gen(function* PreviewAutomationBrokerMake() {
|
||||
const invoke = Effect.fn("PreviewAutomationBroker.invoke")(function* <A = unknown>(
|
||||
input: Parameters<PreviewAutomationBroker["Service"]["invoke"]>[0],
|
||||
): Effect.fn.Return<A, PreviewAutomationError> {
|
||||
const timeoutMs = input.timeoutMs ?? 15_000;
|
||||
const deferred = yield* Deferred.make<unknown, PreviewAutomationError>();
|
||||
const now = yield* Clock.currentTimeMillis;
|
||||
const route = yield* SynchronizedRef.modify(state, (current) => {
|
||||
const assignments = new Map(
|
||||
Array.from(current.assignments).filter(([, assignment]) => {
|
||||
const connection = current.clients.get(assignment.clientId);
|
||||
return (
|
||||
assignment.expiresAt > now &&
|
||||
connection?.connectionId === assignment.connectionId &&
|
||||
connection.queue === assignment.queue
|
||||
);
|
||||
}),
|
||||
);
|
||||
const assignmentKey = hostAssignmentKey(input.scope);
|
||||
const assigned = assignments.get(assignmentKey);
|
||||
const assignedConnection = assigned ? current.clients.get(assigned.clientId) : undefined;
|
||||
const hasLiveAssignment = assignedConnection?.environmentId === input.scope.environmentId;
|
||||
// Keep one provider session on one physical desktop runtime so a
|
||||
// multi-step browser interaction cannot jump between independent
|
||||
// Electron cookie/DOM state. A live assignment that predates an
|
||||
// operation is not silently moved to a newer client: the caller gets a
|
||||
// capability failure and can deliberately start a fresh provider
|
||||
// session. A dead lease is pruned above and may fail over.
|
||||
const connection =
|
||||
hasLiveAssignment && supportsOperation(assignedConnection, input.operation)
|
||||
? assignedConnection
|
||||
: hasLiveAssignment
|
||||
? undefined
|
||||
: Array.from(current.clients.values())
|
||||
.filter(
|
||||
(host) =>
|
||||
host.environmentId === input.scope.environmentId &&
|
||||
supportsOperation(host, input.operation),
|
||||
)
|
||||
.sort(
|
||||
(left, right) =>
|
||||
right.supportedOperations.size - left.supportedOperations.size ||
|
||||
Number(right.focused) - Number(left.focused) ||
|
||||
right.focusOrder - left.focusOrder,
|
||||
)[0];
|
||||
if (!connection) {
|
||||
if (!hasLiveAssignment) assignments.delete(assignmentKey);
|
||||
return [undefined, { ...current, assignments }] as const;
|
||||
const current = yield* SynchronizedRef.get(state);
|
||||
const candidates = Array.from(current.owners.values())
|
||||
.filter(
|
||||
(owner) =>
|
||||
owner.environmentId === input.scope.environmentId &&
|
||||
owner.threadId === input.scope.threadId &&
|
||||
owner.supportsAutomation,
|
||||
)
|
||||
.sort((left, right) => right.focusedAt.localeCompare(left.focusedAt));
|
||||
const owner = candidates.find((candidate) => current.clients.has(candidate.clientId));
|
||||
if (!owner) {
|
||||
const disconnectedOwner = candidates[0];
|
||||
if (disconnectedOwner) {
|
||||
return yield* new PreviewAutomationHostNotConnectedError({
|
||||
operation: input.operation,
|
||||
environmentId: input.scope.environmentId,
|
||||
threadId: input.scope.threadId,
|
||||
providerSessionId: input.scope.providerSessionId,
|
||||
providerInstanceId: input.scope.providerInstanceId,
|
||||
clientId: disconnectedOwner.clientId,
|
||||
});
|
||||
}
|
||||
assignments.set(assignmentKey, {
|
||||
clientId: connection.clientId,
|
||||
connectionId: connection.connectionId,
|
||||
queue: connection.queue,
|
||||
expiresAt: input.scope.expiresAt,
|
||||
});
|
||||
|
||||
const requestId = `preview-${current.requestSequence}`;
|
||||
const tabId = input.tabId;
|
||||
const selectorDiagnostics = selectorDiagnosticsFromInput(input.input);
|
||||
const context: PreviewAutomationRequestErrorContext = {
|
||||
operation: input.operation,
|
||||
environmentId: input.scope.environmentId,
|
||||
threadId: input.scope.threadId,
|
||||
providerSessionId: input.scope.providerSessionId,
|
||||
providerInstanceId: input.scope.providerInstanceId,
|
||||
clientId: connection.clientId,
|
||||
connectionId: connection.connectionId,
|
||||
requestId,
|
||||
...(tabId === undefined ? {} : { tabId }),
|
||||
timeoutMs,
|
||||
...selectorDiagnostics,
|
||||
};
|
||||
const pending = new Map(current.pending);
|
||||
pending.set(requestId, { queue: connection.queue, deferred, context });
|
||||
return [
|
||||
{ connection, requestId, requestContext: context },
|
||||
{ ...current, assignments, pending, requestSequence: current.requestSequence + 1 },
|
||||
] as const;
|
||||
});
|
||||
if (!route) {
|
||||
return yield* new PreviewAutomationNoAvailableHostError({
|
||||
return yield* new PreviewAutomationNoFocusedOwnerError({
|
||||
operation: input.operation,
|
||||
environmentId: input.scope.environmentId,
|
||||
threadId: input.scope.threadId,
|
||||
@@ -493,7 +337,42 @@ export const make = Effect.gen(function* PreviewAutomationBrokerMake() {
|
||||
providerInstanceId: input.scope.providerInstanceId,
|
||||
});
|
||||
}
|
||||
const { connection, requestId, requestContext } = route;
|
||||
const connection = current.clients.get(owner.clientId);
|
||||
if (!connection) {
|
||||
return yield* new PreviewAutomationHostNotConnectedError({
|
||||
operation: input.operation,
|
||||
environmentId: input.scope.environmentId,
|
||||
threadId: input.scope.threadId,
|
||||
providerSessionId: input.scope.providerSessionId,
|
||||
providerInstanceId: input.scope.providerInstanceId,
|
||||
clientId: owner.clientId,
|
||||
});
|
||||
}
|
||||
const timeoutMs = input.timeoutMs ?? 15_000;
|
||||
const deferred = yield* Deferred.make<unknown, PreviewAutomationError>();
|
||||
const [requestId, requestContext] = yield* SynchronizedRef.modify(state, (next) => {
|
||||
const requestId = `preview-${next.requestSequence}`;
|
||||
const tabId = input.tabId ?? owner.tabId ?? undefined;
|
||||
const selectorDiagnostics = selectorDiagnosticsFromInput(input.input);
|
||||
const context: PreviewAutomationRequestErrorContext = {
|
||||
operation: input.operation,
|
||||
environmentId: input.scope.environmentId,
|
||||
threadId: input.scope.threadId,
|
||||
providerSessionId: input.scope.providerSessionId,
|
||||
providerInstanceId: input.scope.providerInstanceId,
|
||||
clientId: owner.clientId,
|
||||
requestId,
|
||||
...(tabId === undefined ? {} : { tabId }),
|
||||
timeoutMs,
|
||||
...selectorDiagnostics,
|
||||
};
|
||||
const pending = new Map(next.pending);
|
||||
pending.set(requestId, { queue: connection.queue, deferred, context });
|
||||
return [
|
||||
[requestId, context] as const,
|
||||
{ ...next, pending, requestSequence: next.requestSequence + 1 },
|
||||
] as const;
|
||||
});
|
||||
const removePending = SynchronizedRef.update(state, (next) => {
|
||||
if (!next.pending.has(requestId)) return next;
|
||||
const pending = new Map(next.pending);
|
||||
@@ -502,16 +381,12 @@ export const make = Effect.gen(function* PreviewAutomationBrokerMake() {
|
||||
});
|
||||
const awaitResponse = Effect.fn("PreviewAutomationBroker.awaitResponse")(function* () {
|
||||
const offered = yield* Queue.offer(connection.queue, {
|
||||
type: "request",
|
||||
connectionId: connection.connectionId,
|
||||
request: {
|
||||
requestId,
|
||||
threadId: input.scope.threadId,
|
||||
tabId: requestContext.tabId,
|
||||
operation: input.operation,
|
||||
input: input.input,
|
||||
timeoutMs,
|
||||
},
|
||||
requestId,
|
||||
threadId: input.scope.threadId,
|
||||
tabId: requestContext.tabId,
|
||||
operation: input.operation,
|
||||
input: input.input,
|
||||
timeoutMs,
|
||||
});
|
||||
if (!offered) {
|
||||
const completion = yield* Deferred.poll(deferred);
|
||||
@@ -529,7 +404,7 @@ export const make = Effect.gen(function* PreviewAutomationBrokerMake() {
|
||||
return yield* awaitResponse().pipe(Effect.ensuring(removePending));
|
||||
});
|
||||
|
||||
return PreviewAutomationBroker.of({ connect, focusHost, respond, invoke });
|
||||
return PreviewAutomationBroker.of({ connect, reportOwner, clearOwner, respond, invoke });
|
||||
}).pipe(Effect.withSpan("PreviewAutomationBroker.make"));
|
||||
|
||||
export const layer = Layer.effect(PreviewAutomationBroker, make);
|
||||
@@ -3,7 +3,6 @@ import type {
|
||||
PreviewAutomationOperation,
|
||||
PreviewAutomationRecordingArtifact,
|
||||
PreviewAutomationRecordingStatus,
|
||||
PreviewAutomationResizeResult,
|
||||
PreviewAutomationSnapshot,
|
||||
PreviewAutomationStatus,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -40,8 +39,6 @@ const handlers = {
|
||||
reuseExistingTab: input.reuseExistingTab ?? true,
|
||||
}),
|
||||
preview_navigate: (input) => invoke<PreviewAutomationStatus>("navigate", input, input.timeoutMs),
|
||||
preview_resize: (input) =>
|
||||
invoke<PreviewAutomationResizeResult>("resize", input, input.timeoutMs),
|
||||
preview_snapshot: () => invoke<PreviewAutomationSnapshot>("snapshot", {}),
|
||||
preview_click: (input) => invoke<void>("click", input, input.timeoutMs).pipe(Effect.as(null)),
|
||||
preview_type: (input) => invoke<void>("type", input, input.timeoutMs).pipe(Effect.as(null)),
|
||||
|
||||
@@ -7,8 +7,6 @@ import {
|
||||
PreviewAutomationPressInput,
|
||||
PreviewAutomationRecordingArtifact,
|
||||
PreviewAutomationRecordingStatus,
|
||||
PreviewAutomationResizeInput,
|
||||
PreviewAutomationResizeResult,
|
||||
PreviewAutomationScrollInput,
|
||||
PreviewAutomationSnapshot,
|
||||
PreviewAutomationStatus,
|
||||
@@ -37,7 +35,7 @@ const readonlyBrowserTool = <T extends Tool.Any>(tool: T): T =>
|
||||
|
||||
export const PreviewStatusTool = Tool.make("preview_status", {
|
||||
description:
|
||||
"Report whether the scoped thread has an automation-capable desktop preview, including its active tab, URL, title, visibility, loading state, viewport mode, and measured CSS-pixel size.",
|
||||
"Report whether the scoped thread has an automation-capable desktop preview, including its active tab, URL, title, visibility, and loading state.",
|
||||
success: PreviewAutomationStatus,
|
||||
failure: PreviewAutomationError,
|
||||
dependencies,
|
||||
@@ -71,19 +69,6 @@ export const PreviewNavigateTool = safeBrowserTool(
|
||||
}).annotate(Tool.Title, "Navigate browser preview"),
|
||||
);
|
||||
|
||||
export const PreviewResizeTool = safeBrowserTool(
|
||||
Tool.make("preview_resize", {
|
||||
description:
|
||||
"Set the active collaborative browser tab to fill-panel sizing, an independently resizable freeform size, or a Chrome-standard device preset. Use {mode:'fill'}, {mode:'freeform',width:1024,height:768}, or {mode:'preset',preset:'iphone-12-pro',orientation:'portrait'}. This changes CSS layout breakpoints without changing the desktop browser user agent.",
|
||||
parameters: PreviewAutomationResizeInput,
|
||||
success: PreviewAutomationResizeResult,
|
||||
failure: PreviewAutomationError,
|
||||
dependencies,
|
||||
})
|
||||
.annotate(Tool.Title, "Resize browser viewport")
|
||||
.annotate(Tool.Idempotent, true),
|
||||
);
|
||||
|
||||
export const PreviewSnapshotTool = readonlyBrowserTool(
|
||||
Tool.make("preview_snapshot", {
|
||||
description:
|
||||
@@ -183,7 +168,6 @@ export const PreviewToolkit = Toolkit.make(
|
||||
PreviewStatusTool,
|
||||
PreviewOpenTool,
|
||||
PreviewNavigateTool,
|
||||
PreviewResizeTool,
|
||||
PreviewSnapshotTool,
|
||||
PreviewClickTool,
|
||||
PreviewTypeTool,
|
||||
@@ -199,7 +183,6 @@ export const PreviewStandardToolkit = Toolkit.make(
|
||||
PreviewStatusTool,
|
||||
PreviewOpenTool,
|
||||
PreviewNavigateTool,
|
||||
PreviewResizeTool,
|
||||
PreviewClickTool,
|
||||
PreviewTypeTool,
|
||||
PreviewPressTool,
|
||||
|
||||
@@ -151,61 +151,6 @@ it.layer(PreviewManager.layer)("PreviewManager", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("resizes a tab and preserves its viewport across navigation reports", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = freshThreadId();
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
const collector = yield* collectEvents;
|
||||
const opened = yield* manager.open({ threadId, url: "http://localhost:5173" });
|
||||
|
||||
const resized = yield* manager.resize({
|
||||
threadId,
|
||||
tabId: opened.tabId,
|
||||
viewport: { _tag: "freeform", width: 1024, height: 768 },
|
||||
});
|
||||
expect(resized.viewport).toEqual({ _tag: "freeform", width: 1024, height: 768 });
|
||||
|
||||
const navigated = yield* manager.navigate({
|
||||
threadId,
|
||||
tabId: opened.tabId,
|
||||
url: "http://localhost:5173/resized",
|
||||
});
|
||||
expect(navigated.viewport).toEqual(resized.viewport);
|
||||
|
||||
yield* manager.reportStatus({
|
||||
threadId,
|
||||
tabId: opened.tabId,
|
||||
navStatus: { _tag: "Success", url: "http://localhost:5173/resized", title: "Resized" },
|
||||
canGoBack: true,
|
||||
canGoForward: false,
|
||||
});
|
||||
const listed = yield* manager.list({ threadId });
|
||||
expect(listed.sessions[0]?.viewport).toEqual(resized.viewport);
|
||||
|
||||
const events = yield* collector.drain;
|
||||
expect(events.map((event) => event.type)).toEqual([
|
||||
"opened",
|
||||
"resized",
|
||||
"navigated",
|
||||
"navigated",
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects resize for an unknown tab", () =>
|
||||
Effect.gen(function* () {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
const error = yield* Effect.flip(
|
||||
manager.resize({
|
||||
threadId: freshThreadId(),
|
||||
tabId: "tab_missing",
|
||||
viewport: { _tag: "fill" },
|
||||
}),
|
||||
);
|
||||
expect(error._tag).toBe("PreviewSessionLookupError");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reportStatus emits failed for LoadFailed nav", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = freshThreadId();
|
||||
|
||||
@@ -20,8 +20,6 @@ import {
|
||||
type PreviewOpenInput,
|
||||
type PreviewRefreshInput,
|
||||
type PreviewReportStatusInput,
|
||||
type PreviewResizeInput,
|
||||
FILL_PREVIEW_VIEWPORT,
|
||||
PreviewSessionLookupError,
|
||||
type PreviewSessionSnapshot,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -47,9 +45,6 @@ export class PreviewManager extends Context.Service<
|
||||
input: PreviewNavigateInput,
|
||||
) => Effect.Effect<PreviewSessionSnapshot, PreviewError>;
|
||||
readonly reportStatus: (input: PreviewReportStatusInput) => Effect.Effect<void, PreviewError>;
|
||||
readonly resize: (
|
||||
input: PreviewResizeInput,
|
||||
) => Effect.Effect<PreviewSessionSnapshot, PreviewError>;
|
||||
readonly refresh: (input: PreviewRefreshInput) => Effect.Effect<void, PreviewError>;
|
||||
readonly close: (input: PreviewCloseInput) => Effect.Effect<void, PreviewError>;
|
||||
readonly list: (input: PreviewListInput) => Effect.Effect<PreviewListResult>;
|
||||
@@ -119,7 +114,6 @@ const buildLoadingSnapshot = (input: {
|
||||
navStatus: { _tag: "Loading", url: input.url, title: input.title },
|
||||
canGoBack: false,
|
||||
canGoForward: false,
|
||||
viewport: FILL_PREVIEW_VIEWPORT,
|
||||
updatedAt: input.updatedAt,
|
||||
});
|
||||
|
||||
@@ -133,7 +127,6 @@ const buildIdleSnapshot = (input: {
|
||||
navStatus: { _tag: "Idle" },
|
||||
canGoBack: false,
|
||||
canGoForward: false,
|
||||
viewport: FILL_PREVIEW_VIEWPORT,
|
||||
updatedAt: input.updatedAt,
|
||||
});
|
||||
|
||||
@@ -244,7 +237,6 @@ export const make = Effect.gen(function* PreviewManagerMake() {
|
||||
navStatus: { _tag: "Success", url, title: resolvedTitle },
|
||||
canGoBack: session.snapshot.canGoBack,
|
||||
canGoForward: session.snapshot.canGoForward,
|
||||
viewport: session.snapshot.viewport ?? FILL_PREVIEW_VIEWPORT,
|
||||
updatedAt,
|
||||
};
|
||||
return {
|
||||
@@ -277,7 +269,6 @@ export const make = Effect.gen(function* PreviewManagerMake() {
|
||||
navStatus: input.navStatus,
|
||||
canGoBack: input.canGoBack,
|
||||
canGoForward: input.canGoForward,
|
||||
viewport: session.snapshot.viewport ?? FILL_PREVIEW_VIEWPORT,
|
||||
updatedAt,
|
||||
};
|
||||
const emit: PreviewEvent =
|
||||
@@ -308,34 +299,6 @@ export const make = Effect.gen(function* PreviewManagerMake() {
|
||||
);
|
||||
});
|
||||
|
||||
const resize: PreviewManager["Service"]["resize"] = Effect.fn("PreviewManager.resize")(
|
||||
function* (input) {
|
||||
return yield* mutateExistingSession(
|
||||
input.threadId,
|
||||
input.tabId,
|
||||
Effect.fn("PreviewManager.resizeSession")(function* (session) {
|
||||
const updatedAt = yield* currentIsoTimestamp;
|
||||
const snapshot: PreviewSessionSnapshot = {
|
||||
...session.snapshot,
|
||||
viewport: input.viewport,
|
||||
updatedAt,
|
||||
};
|
||||
return {
|
||||
next: { ...session, snapshot },
|
||||
emit: {
|
||||
type: "resized",
|
||||
threadId: session.threadId,
|
||||
tabId: session.tabId,
|
||||
createdAt: snapshot.updatedAt,
|
||||
snapshot,
|
||||
},
|
||||
result: snapshot,
|
||||
};
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
const refresh: PreviewManager["Service"]["refresh"] = Effect.fn("PreviewManager.refresh")(
|
||||
function* (input) {
|
||||
// Verify the session exists; the desktop bridge handles the actual reload
|
||||
@@ -397,7 +360,6 @@ export const make = Effect.gen(function* PreviewManagerMake() {
|
||||
open,
|
||||
navigate,
|
||||
reportStatus,
|
||||
resize,
|
||||
refresh,
|
||||
close,
|
||||
list,
|
||||
|
||||
@@ -113,23 +113,6 @@ async function waitForFileContent(filePath: string, attempts = 40) {
|
||||
throw new Error(`Timed out waiting for file content at ${filePath}`);
|
||||
}
|
||||
|
||||
function waitForJsonLogMatch(
|
||||
filePath: string,
|
||||
predicate: (entry: Record<string, unknown>) => boolean,
|
||||
attempts = 40,
|
||||
) {
|
||||
return Effect.gen(function* () {
|
||||
for (let attempt = 0; attempt < attempts; attempt += 1) {
|
||||
const requests = yield* Effect.promise(() => readJsonLines(filePath));
|
||||
if (requests.some(predicate)) {
|
||||
return requests;
|
||||
}
|
||||
yield* Effect.yieldNow;
|
||||
}
|
||||
return yield* Effect.promise(() => readJsonLines(filePath));
|
||||
});
|
||||
}
|
||||
|
||||
// Tests mutate `ServerSettingsService` mid-flight (e.g. setting
|
||||
// `providers.cursor.binaryPath` to a mock ACP wrapper). The adapter
|
||||
// captures `cursorSettings` once at construction, so without a resolver
|
||||
@@ -1021,10 +1004,7 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
|
||||
assert.equal(turnCompleted.payload.stopReason, "cancelled");
|
||||
}
|
||||
|
||||
const requests = yield* waitForJsonLogMatch(
|
||||
requestLogPath,
|
||||
(entry) => entry.method === "session/cancel",
|
||||
);
|
||||
const requests = yield* Effect.promise(() => readJsonLines(requestLogPath));
|
||||
assert.isTrue(requests.some((entry) => entry.method === "session/cancel"));
|
||||
assert.isTrue(
|
||||
requests.some(
|
||||
|
||||
@@ -785,9 +785,6 @@ export function makeCursorAdapter(
|
||||
Stream.mapEffect(acp.getEvents(), (event) =>
|
||||
Effect.gen(function* () {
|
||||
switch (event._tag) {
|
||||
case "EventStreamBarrier":
|
||||
yield* Deferred.succeed(event.acknowledge, undefined);
|
||||
return;
|
||||
case "ModeChanged":
|
||||
return;
|
||||
case "AssistantItemStarted":
|
||||
|
||||
@@ -4,7 +4,6 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Path from "effect/Path";
|
||||
import type * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
import type * as EffectAcpSchema from "effect-acp/schema";
|
||||
import type { CursorSettings } from "@t3tools/contracts";
|
||||
@@ -25,11 +24,7 @@ import {
|
||||
} from "./CursorProvider.ts";
|
||||
|
||||
const runNode = <A, E>(
|
||||
effect: Effect.Effect<
|
||||
A,
|
||||
E,
|
||||
ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
|
||||
>,
|
||||
effect: Effect.Effect<A, E, FileSystem.FileSystem | Path.Path>,
|
||||
): Promise<A> => Effect.runPromise(effect.pipe(Effect.provide(NodeServices.layer)));
|
||||
|
||||
const resolveMockAgentPath = Effect.fn("resolveMockAgentPath")(function* () {
|
||||
@@ -298,18 +293,6 @@ const baseCursorSettings: CursorSettings = {
|
||||
apiEndpoint: "",
|
||||
customModels: [],
|
||||
};
|
||||
const cursorAcpDiscoveryFailedMessage = [
|
||||
"Cursor ACP model discovery failed.",
|
||||
"Cursor CLI setup may be incomplete; install or enable the Cursor CLI, restart T3 Code, and try again.",
|
||||
"See https://cursor.com/docs/cli/installation.",
|
||||
"Check server logs for ACP details.",
|
||||
].join(" ");
|
||||
const missingCursorBinaryPath = "/definitely/not/installed/t3-cursor-agent";
|
||||
const cursorCliCommandMissingMessage = [
|
||||
`Cursor CLI command \`${missingCursorBinaryPath}\` was not found.`,
|
||||
`Install or enable the Cursor CLI, make sure \`${missingCursorBinaryPath}\` is on PATH, then restart T3 Code.`,
|
||||
"See https://cursor.com/docs/cli/installation.",
|
||||
].join(" ");
|
||||
|
||||
describe("getCursorFallbackModels", () => {
|
||||
it("does not publish any built-in cursor models before ACP discovery", () => {
|
||||
@@ -355,11 +338,12 @@ describe("buildCursorProviderSnapshot", () => {
|
||||
auth: { status: "unauthenticated" },
|
||||
message: "Cursor Agent is not authenticated. Run `agent login` and try again.",
|
||||
},
|
||||
discoveryWarning: cursorAcpDiscoveryFailedMessage,
|
||||
discoveryWarning: "Cursor ACP model discovery failed. Check server logs for details.",
|
||||
}),
|
||||
).toMatchObject({
|
||||
status: "error",
|
||||
message: `Cursor Agent is not authenticated. Run \`agent login\` and try again. ${cursorAcpDiscoveryFailedMessage}`,
|
||||
message:
|
||||
"Cursor Agent is not authenticated. Run `agent login` and try again. Cursor ACP model discovery failed. Check server logs for details.",
|
||||
models: [
|
||||
{
|
||||
slug: "claude-sonnet-4-6",
|
||||
@@ -427,28 +411,10 @@ describe("buildCursorCapabilitiesFromConfigOptions", () => {
|
||||
});
|
||||
|
||||
describe("checkCursorProviderStatus", () => {
|
||||
it("reports the install docs when the Cursor CLI command is missing", async () => {
|
||||
const provider = await runNode(
|
||||
checkCursorProviderStatus({
|
||||
enabled: true,
|
||||
binaryPath: missingCursorBinaryPath,
|
||||
apiEndpoint: "",
|
||||
customModels: [],
|
||||
}),
|
||||
);
|
||||
|
||||
expect(provider).toMatchObject({
|
||||
installed: false,
|
||||
status: "error",
|
||||
auth: { status: "unknown" },
|
||||
message: cursorCliCommandMissingMessage,
|
||||
});
|
||||
});
|
||||
|
||||
it("passes the injected environment to ACP model discovery", async () => {
|
||||
const { requestLogPath, wrapperPath } = await runNode(makeProviderStatusEnvFixture());
|
||||
|
||||
const provider = await runNode(
|
||||
const provider = await Effect.runPromise(
|
||||
checkCursorProviderStatus(
|
||||
{
|
||||
enabled: true,
|
||||
@@ -460,7 +426,7 @@ describe("checkCursorProviderStatus", () => {
|
||||
...process.env,
|
||||
T3_ACP_REQUEST_LOG_PATH: requestLogPath,
|
||||
},
|
||||
),
|
||||
).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
expect(provider.models.map((model) => model.slug)).toEqual([
|
||||
@@ -477,13 +443,13 @@ describe("discoverCursorModelsViaAcp", () => {
|
||||
it("keeps the ACP probe runtime alive long enough to discover models", async () => {
|
||||
const wrapperPath = await runNode(makeMockAgentWrapper());
|
||||
|
||||
const models = await runNode(
|
||||
const models = await Effect.runPromise(
|
||||
discoverCursorModelsViaAcp({
|
||||
enabled: true,
|
||||
binaryPath: wrapperPath,
|
||||
apiEndpoint: "",
|
||||
customModels: [],
|
||||
}).pipe(Effect.scoped),
|
||||
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
|
||||
);
|
||||
|
||||
expect(models.map((model) => model.slug)).toEqual([
|
||||
@@ -499,13 +465,13 @@ describe("discoverCursorModelsViaAcp", () => {
|
||||
makeExitLogFixture("cursor-provider-exit-log-"),
|
||||
);
|
||||
|
||||
await runNode(
|
||||
await Effect.runPromise(
|
||||
discoverCursorModelsViaAcp({
|
||||
enabled: true,
|
||||
binaryPath: wrapperPath,
|
||||
apiEndpoint: "",
|
||||
customModels: [],
|
||||
}),
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
const exitLog = await runNode(waitForFileContent(exitLogPath));
|
||||
|
||||
@@ -62,13 +62,6 @@ const EMPTY_CAPABILITIES: ModelCapabilities = createModelCapabilities({
|
||||
|
||||
const CURSOR_ACP_MODEL_DISCOVERY_TIMEOUT_MS = 15_000;
|
||||
const CURSOR_PARAMETERIZED_MODEL_PICKER_MIN_VERSION_DATE = 2026_04_08;
|
||||
const CURSOR_CLI_INSTALLATION_DOCS_URL = "https://cursor.com/docs/cli/installation";
|
||||
const CURSOR_ACP_MODEL_DISCOVERY_FAILED_MESSAGE = [
|
||||
"Cursor ACP model discovery failed.",
|
||||
"Cursor CLI setup may be incomplete; install or enable the Cursor CLI, restart T3 Code, and try again.",
|
||||
`See ${CURSOR_CLI_INSTALLATION_DOCS_URL}.`,
|
||||
"Check server logs for ACP details.",
|
||||
].join(" ");
|
||||
export const CURSOR_PARAMETERIZED_MODEL_PICKER_CAPABILITIES = {
|
||||
_meta: {
|
||||
parameterizedModelPicker: true,
|
||||
@@ -615,14 +608,6 @@ function joinProviderMessages(...messages: ReadonlyArray<string | undefined>): s
|
||||
return parts.length > 0 ? parts.join(" ") : undefined;
|
||||
}
|
||||
|
||||
function buildCursorCliCommandMissingMessage(binaryPath: string): string {
|
||||
return [
|
||||
`Cursor CLI command \`${binaryPath}\` was not found.`,
|
||||
`Install or enable the Cursor CLI, make sure \`${binaryPath}\` is on PATH, then restart T3 Code.`,
|
||||
`See ${CURSOR_CLI_INSTALLATION_DOCS_URL}.`,
|
||||
].join(" ");
|
||||
}
|
||||
|
||||
export function buildCursorProviderSnapshot(input: {
|
||||
readonly checkedAt: string;
|
||||
readonly cursorSettings: CursorSettings;
|
||||
@@ -1035,7 +1020,7 @@ export const checkCursorProviderStatus = Effect.fn("checkCursorProviderStatus")(
|
||||
status: "error",
|
||||
auth: { status: "unknown" },
|
||||
message: isCommandMissingCause(error)
|
||||
? buildCursorCliCommandMissingMessage(cursorSettings.binaryPath)
|
||||
? "Cursor Agent CLI (`agent`) is not installed or not on PATH."
|
||||
: "Failed to execute Cursor Agent CLI health check.",
|
||||
},
|
||||
});
|
||||
@@ -1094,7 +1079,7 @@ export const checkCursorProviderStatus = Effect.fn("checkCursorProviderStatus")(
|
||||
yield* Effect.logWarning("Cursor ACP model discovery failed", {
|
||||
errorTag: causeErrorTag(discoveryExit.cause),
|
||||
});
|
||||
discoveryWarning = CURSOR_ACP_MODEL_DISCOVERY_FAILED_MESSAGE;
|
||||
discoveryWarning = "Cursor ACP model discovery failed. Check server logs for details.";
|
||||
} else if (Option.isNone(discoveryExit.value)) {
|
||||
discoveryWarning = `Cursor ACP model discovery timed out after ${CURSOR_ACP_MODEL_DISCOVERY_TIMEOUT_MS}ms.`;
|
||||
} else if (discoveryExit.value.value.length === 0) {
|
||||
|
||||
@@ -10,23 +10,20 @@ import * as Deferred from "effect/Deferred";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
GrokSettings,
|
||||
ProviderDriverKind,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
ProviderInstanceId,
|
||||
type ProviderRuntimeEvent,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { grokPromptSettlementBelongsToContext, makeGrokAdapter } from "./GrokAdapter.ts";
|
||||
import { makeGrokAdapter } from "./GrokAdapter.ts";
|
||||
const decodeGrokSettings = Schema.decodeSync(GrokSettings);
|
||||
|
||||
const __dirname = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url));
|
||||
@@ -48,11 +45,7 @@ exec ${JSON.stringify(mockAgentCommand)} ${JSON.stringify(mockAgentPath)} "$@"
|
||||
return wrapperPath;
|
||||
}
|
||||
|
||||
function waitForFileContent(
|
||||
filePath: string,
|
||||
attempts = 40,
|
||||
expectedContent?: string,
|
||||
): Effect.Effect<string> {
|
||||
function waitForFileContent(filePath: string, attempts = 40): Effect.Effect<string> {
|
||||
const readAttempt = (remainingAttempts: number): Effect.Effect<string> =>
|
||||
Effect.gen(function* () {
|
||||
if (remainingAttempts <= 0) {
|
||||
@@ -61,10 +54,7 @@ function waitForFileContent(
|
||||
const raw = yield* Effect.tryPromise(() => NodeFSP.readFile(filePath, "utf8")).pipe(
|
||||
Effect.orElseSucceed(() => ""),
|
||||
);
|
||||
if (
|
||||
raw.trim().length > 0 &&
|
||||
(expectedContent === undefined || raw.includes(expectedContent))
|
||||
) {
|
||||
if (raw.trim().length > 0) {
|
||||
return raw;
|
||||
}
|
||||
yield* Effect.sleep("25 millis");
|
||||
@@ -89,39 +79,6 @@ const grokAdapterTestLayer = ServerConfig.layerTest(process.cwd(), {
|
||||
const makeTestAdapter = (binaryPath: string, options?: Parameters<typeof makeGrokAdapter>[1]) =>
|
||||
makeGrokAdapter(decodeGrokSettings({ binaryPath }), options).pipe(Effect.orDie);
|
||||
|
||||
it("requires a settlement to match the live Grok turn", () => {
|
||||
const staleTurnId = TurnId.make("stale-turn");
|
||||
const replacementTurnId = TurnId.make("replacement-turn");
|
||||
|
||||
assert.isFalse(
|
||||
grokPromptSettlementBelongsToContext({
|
||||
liveAcpSessionId: "session-1",
|
||||
expectedAcpSessionId: "session-1",
|
||||
liveActiveTurnId: replacementTurnId,
|
||||
liveSessionActiveTurnId: replacementTurnId,
|
||||
turnId: staleTurnId,
|
||||
}),
|
||||
);
|
||||
assert.isFalse(
|
||||
grokPromptSettlementBelongsToContext({
|
||||
liveAcpSessionId: "replacement-session",
|
||||
expectedAcpSessionId: "stale-session",
|
||||
liveActiveTurnId: staleTurnId,
|
||||
liveSessionActiveTurnId: staleTurnId,
|
||||
turnId: staleTurnId,
|
||||
}),
|
||||
);
|
||||
assert.isTrue(
|
||||
grokPromptSettlementBelongsToContext({
|
||||
liveAcpSessionId: "session-1",
|
||||
expectedAcpSessionId: "session-1",
|
||||
liveActiveTurnId: staleTurnId,
|
||||
liveSessionActiveTurnId: staleTurnId,
|
||||
turnId: staleTurnId,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.layer(grokAdapterTestLayer)("GrokAdapterLive", (it) => {
|
||||
it.effect("starts a session and maps mock ACP prompt flow to runtime events", () =>
|
||||
Effect.gen(function* () {
|
||||
@@ -218,783 +175,6 @@ it.layer(grokAdapterTestLayer)("GrokAdapterLive", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reports a Grok session running only while the prompt is in flight", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("grok-session-ready-after-prompt");
|
||||
const wrapperPath = yield* Effect.promise(() =>
|
||||
makeMockGrokWrapper({
|
||||
T3_ACP_EMIT_TOOL_CALLS: "1",
|
||||
}),
|
||||
);
|
||||
const adapter = yield* makeTestAdapter(wrapperPath);
|
||||
const requestOpened =
|
||||
yield* Deferred.make<Extract<ProviderRuntimeEvent, { type: "request.opened" }>>();
|
||||
const eventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
|
||||
event.type === "request.opened"
|
||||
? Deferred.succeed(requestOpened, event).pipe(Effect.ignore)
|
||||
: Effect.void,
|
||||
).pipe(Effect.forkChild);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("grok"),
|
||||
cwd: process.cwd(),
|
||||
runtimeMode: "approval-required",
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok-build" },
|
||||
});
|
||||
|
||||
const sendTurnFiber = yield* adapter
|
||||
.sendTurn({ threadId, input: "check lifecycle", attachments: [] })
|
||||
.pipe(Effect.forkChild);
|
||||
const requestOpenedEvent = yield* Deferred.await(requestOpened);
|
||||
|
||||
const runningSessions = yield* adapter.listSessions();
|
||||
const runningSession = runningSessions.find((session) => session.threadId === threadId);
|
||||
assert.equal(runningSession?.status, "running");
|
||||
assert.isDefined(runningSession?.activeTurnId);
|
||||
|
||||
yield* adapter.respondToRequest(
|
||||
threadId,
|
||||
ApprovalRequestId.make(String(requestOpenedEvent.requestId)),
|
||||
"accept",
|
||||
);
|
||||
yield* Fiber.join(sendTurnFiber);
|
||||
|
||||
const readySessions = yield* adapter.listSessions();
|
||||
const readySession = readySessions.find((session) => session.threadId === threadId);
|
||||
assert.equal(readySession?.status, "ready");
|
||||
assert.isUndefined(readySession?.activeTurnId);
|
||||
|
||||
yield* Fiber.interrupt(eventsFiber);
|
||||
yield* adapter.stopSession(threadId);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("restores ready without completing an unstarted turn when preparation fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("grok-preparation-failure-while-connecting");
|
||||
const wrapperPath = yield* Effect.promise(() => makeMockGrokWrapper());
|
||||
const adapter = yield* makeTestAdapter(wrapperPath);
|
||||
|
||||
const runtimeEvents: ProviderRuntimeEvent[] = [];
|
||||
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
|
||||
Effect.sync(() => {
|
||||
runtimeEvents.push(event);
|
||||
}),
|
||||
).pipe(Effect.forkChild);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("grok"),
|
||||
cwd: process.cwd(),
|
||||
runtimeMode: "full-access",
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok-build" },
|
||||
});
|
||||
|
||||
const error = yield* Effect.flip(
|
||||
adapter.sendTurn({
|
||||
threadId,
|
||||
input: "prepare invalid attachment",
|
||||
attachments: [
|
||||
{
|
||||
type: "image",
|
||||
id: "missing-image",
|
||||
name: "missing.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 1,
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
for (let yieldAttempt = 0; yieldAttempt < 4; yieldAttempt += 1) {
|
||||
yield* Effect.yieldNow;
|
||||
}
|
||||
|
||||
const turnCompletedEvent = runtimeEvents.find(
|
||||
(event): event is Extract<ProviderRuntimeEvent, { type: "turn.completed" }> =>
|
||||
event.type === "turn.completed",
|
||||
);
|
||||
const readySessions = yield* adapter.listSessions();
|
||||
const readySession = readySessions.find((session) => session.threadId === threadId);
|
||||
|
||||
assert.equal(error._tag, "ProviderAdapterRequestError");
|
||||
assert.isUndefined(turnCompletedEvent);
|
||||
assert.equal(readySession?.status, "ready");
|
||||
assert.isUndefined(readySession?.activeTurnId);
|
||||
|
||||
yield* Fiber.interrupt(runtimeEventsFiber);
|
||||
yield* adapter.stopSession(threadId);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("completes a Grok turn from xAI prompt completion when the prompt RPC hangs", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("grok-xai-prompt-complete-fallback");
|
||||
const wrapperPath = yield* Effect.promise(() =>
|
||||
makeMockGrokWrapper({
|
||||
T3_ACP_EMIT_XAI_PROMPT_COMPLETE_THEN_HANG: "1",
|
||||
T3_ACP_EMIT_FOREIGN_SESSION_UPDATES: "1",
|
||||
}),
|
||||
);
|
||||
const adapter = yield* makeTestAdapter(wrapperPath);
|
||||
|
||||
const runtimeEvents: ProviderRuntimeEvent[] = [];
|
||||
const turnCompleted = yield* Deferred.make<void>();
|
||||
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
|
||||
Effect.sync(() => {
|
||||
runtimeEvents.push(event);
|
||||
}).pipe(
|
||||
Effect.andThen(
|
||||
event.type === "turn.completed"
|
||||
? Deferred.succeed(turnCompleted, undefined)
|
||||
: Effect.void,
|
||||
),
|
||||
),
|
||||
).pipe(Effect.forkChild);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("grok"),
|
||||
cwd: process.cwd(),
|
||||
runtimeMode: "full-access",
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok-build" },
|
||||
});
|
||||
|
||||
const sendTurnResult = yield* adapter.sendTurn({
|
||||
threadId,
|
||||
input: "exercise fallback",
|
||||
attachments: [],
|
||||
});
|
||||
|
||||
yield* Deferred.await(turnCompleted);
|
||||
for (let yieldAttempt = 0; yieldAttempt < 8; yieldAttempt += 1) {
|
||||
yield* Effect.yieldNow;
|
||||
}
|
||||
const readySessions = yield* adapter.listSessions();
|
||||
const readySession = readySessions.find((session) => session.threadId === threadId);
|
||||
const turnCompletedEvent = runtimeEvents.find(
|
||||
(event): event is Extract<ProviderRuntimeEvent, { type: "turn.completed" }> =>
|
||||
event.type === "turn.completed",
|
||||
);
|
||||
const eventTypes = runtimeEvents.map((event) => event.type);
|
||||
const content = runtimeEvents
|
||||
.filter(
|
||||
(event): event is Extract<ProviderRuntimeEvent, { type: "content.delta" }> =>
|
||||
event.type === "content.delta" && String(event.threadId) === String(threadId),
|
||||
)
|
||||
.map((event) => event.payload.delta)
|
||||
.join("");
|
||||
const terminalIndex = runtimeEvents.findIndex(
|
||||
(event) => event.type === "turn.completed" && String(event.threadId) === String(threadId),
|
||||
);
|
||||
const turnOutputTypes = new Set([
|
||||
"content.delta",
|
||||
"item.started",
|
||||
"item.updated",
|
||||
"item.completed",
|
||||
"turn.plan.updated",
|
||||
]);
|
||||
const outputAfterTerminal = runtimeEvents
|
||||
.slice(terminalIndex + 1)
|
||||
.filter(
|
||||
(event) => String(event.threadId) === String(threadId) && turnOutputTypes.has(event.type),
|
||||
);
|
||||
const toolTitles = runtimeEvents.flatMap((event) =>
|
||||
event.type === "item.updated" && event.payload.title ? [event.payload.title] : [],
|
||||
);
|
||||
|
||||
assert.equal(sendTurnResult.threadId, threadId);
|
||||
assert.include(eventTypes, "turn.completed");
|
||||
assert.equal(content, "hello from mock");
|
||||
assert.isAtLeast(terminalIndex, 0);
|
||||
assert.deepEqual(outputAfterTerminal, []);
|
||||
assert.notInclude(toolTitles, "Child-only tool");
|
||||
assert.equal(turnCompletedEvent?.payload.stopReason, "end_turn");
|
||||
assert.equal(readySession?.status, "ready");
|
||||
assert.isUndefined(readySession?.activeTurnId);
|
||||
|
||||
yield* Fiber.interrupt(runtimeEventsFiber);
|
||||
yield* adapter.stopSession(threadId);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("retains turn transcript when sendTurn is interrupted after prompt success", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("grok-send-turn-interrupt-after-prompt");
|
||||
const wrapperPath = yield* Effect.promise(() =>
|
||||
makeMockGrokWrapper({
|
||||
T3_ACP_EMIT_XAI_PROMPT_COMPLETE_THEN_HANG: "1",
|
||||
}),
|
||||
);
|
||||
const adapter = yield* makeTestAdapter(wrapperPath);
|
||||
const contentDelta = yield* Deferred.make<void>();
|
||||
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
|
||||
event.type === "content.delta" ? Deferred.succeed(contentDelta, undefined) : Effect.void,
|
||||
).pipe(Effect.forkChild);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("grok"),
|
||||
cwd: process.cwd(),
|
||||
runtimeMode: "full-access",
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok-build" },
|
||||
});
|
||||
|
||||
const sendTurnFiber = yield* adapter
|
||||
.sendTurn({
|
||||
threadId,
|
||||
input: "interrupt after prompt",
|
||||
attachments: [],
|
||||
})
|
||||
.pipe(Effect.forkChild);
|
||||
|
||||
yield* Deferred.await(contentDelta);
|
||||
for (let yieldAttempt = 0; yieldAttempt < 6; yieldAttempt += 1) {
|
||||
yield* Effect.yieldNow;
|
||||
}
|
||||
yield* Fiber.interrupt(sendTurnFiber);
|
||||
for (let yieldAttempt = 0; yieldAttempt < 4; yieldAttempt += 1) {
|
||||
yield* Effect.yieldNow;
|
||||
}
|
||||
|
||||
const snapshot = yield* adapter.readThread(threadId);
|
||||
assert.equal(snapshot.turns.length, 1);
|
||||
assert.equal(snapshot.turns[0]?.items.length, 1);
|
||||
|
||||
yield* Fiber.interrupt(runtimeEventsFiber);
|
||||
yield* adapter.stopSession(threadId);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not report a synthetic stop reason when xAI omits one", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("grok-xai-prompt-complete-missing-stop-reason");
|
||||
const wrapperPath = yield* Effect.promise(() =>
|
||||
makeMockGrokWrapper({
|
||||
T3_ACP_EMIT_XAI_PROMPT_COMPLETE_THEN_HANG: "1",
|
||||
T3_ACP_OMIT_XAI_PROMPT_COMPLETE_STOP_REASON: "1",
|
||||
}),
|
||||
);
|
||||
const adapter = yield* makeTestAdapter(wrapperPath);
|
||||
|
||||
const runtimeEvents: ProviderRuntimeEvent[] = [];
|
||||
const turnCompleted = yield* Deferred.make<void>();
|
||||
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
|
||||
Effect.sync(() => {
|
||||
runtimeEvents.push(event);
|
||||
}).pipe(
|
||||
Effect.andThen(
|
||||
event.type === "turn.completed"
|
||||
? Deferred.succeed(turnCompleted, undefined)
|
||||
: Effect.void,
|
||||
),
|
||||
),
|
||||
).pipe(Effect.forkChild);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("grok"),
|
||||
cwd: process.cwd(),
|
||||
runtimeMode: "full-access",
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok-build" },
|
||||
});
|
||||
|
||||
yield* adapter.sendTurn({
|
||||
threadId,
|
||||
input: "exercise missing stop reason",
|
||||
attachments: [],
|
||||
});
|
||||
|
||||
yield* Deferred.await(turnCompleted);
|
||||
const turnCompletedEvent = runtimeEvents.find(
|
||||
(event): event is Extract<ProviderRuntimeEvent, { type: "turn.completed" }> =>
|
||||
event.type === "turn.completed",
|
||||
);
|
||||
|
||||
assert.equal(turnCompletedEvent?.payload.state, "completed");
|
||||
assert.isNull(turnCompletedEvent?.payload.stopReason);
|
||||
|
||||
yield* Fiber.interrupt(runtimeEventsFiber);
|
||||
yield* adapter.stopSession(threadId);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("lets Stop unblock a fully silent Grok prompt and accept a follow-up turn", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("grok-stop-after-full-silence");
|
||||
const wrapperPath = yield* Effect.promise(() =>
|
||||
makeMockGrokWrapper({
|
||||
T3_ACP_HANG_FIRST_PROMPT_FOREVER: "1",
|
||||
}),
|
||||
);
|
||||
const adapter = yield* makeTestAdapter(wrapperPath);
|
||||
|
||||
const runtimeEvents: ProviderRuntimeEvent[] = [];
|
||||
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
|
||||
Effect.sync(() => {
|
||||
runtimeEvents.push(event);
|
||||
}),
|
||||
).pipe(Effect.forkChild);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("grok"),
|
||||
cwd: process.cwd(),
|
||||
runtimeMode: "full-access",
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok-build" },
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
yield* Effect.sleep("500 millis");
|
||||
yield* adapter.interruptTurn(threadId);
|
||||
}).pipe(Effect.forkChild({ startImmediately: true }));
|
||||
|
||||
yield* adapter.sendTurn({
|
||||
threadId,
|
||||
input: "hang forever",
|
||||
attachments: [],
|
||||
});
|
||||
for (let yieldAttempt = 0; yieldAttempt < 8; yieldAttempt += 1) {
|
||||
yield* Effect.yieldNow;
|
||||
}
|
||||
|
||||
const cancelledEvents = runtimeEvents.filter(
|
||||
(event): event is Extract<ProviderRuntimeEvent, { type: "turn.completed" }> =>
|
||||
event.type === "turn.completed" && String(event.threadId) === String(threadId),
|
||||
);
|
||||
const readySessions = yield* adapter.listSessions();
|
||||
const readySession = readySessions.find((session) => session.threadId === threadId);
|
||||
|
||||
assert.lengthOf(cancelledEvents, 1);
|
||||
assert.equal(cancelledEvents[0]?.payload.state, "cancelled");
|
||||
assert.equal(readySession?.status, "ready");
|
||||
assert.isUndefined(readySession?.activeTurnId);
|
||||
|
||||
const followUpEventsBefore = runtimeEvents.length;
|
||||
yield* adapter.sendTurn({
|
||||
threadId,
|
||||
input: "continue after stop",
|
||||
attachments: [],
|
||||
});
|
||||
for (let yieldAttempt = 0; yieldAttempt < 8; yieldAttempt += 1) {
|
||||
yield* Effect.yieldNow;
|
||||
}
|
||||
|
||||
const followUpCompletedEvents = runtimeEvents
|
||||
.slice(followUpEventsBefore)
|
||||
.filter(
|
||||
(event): event is Extract<ProviderRuntimeEvent, { type: "turn.completed" }> =>
|
||||
event.type === "turn.completed" && String(event.threadId) === String(threadId),
|
||||
);
|
||||
assert.lengthOf(followUpCompletedEvents, 1);
|
||||
assert.equal(followUpCompletedEvents[0]?.payload.state, "completed");
|
||||
|
||||
yield* Fiber.interrupt(runtimeEventsFiber);
|
||||
yield* adapter.stopSession(threadId);
|
||||
}).pipe(TestClock.withLive),
|
||||
);
|
||||
|
||||
it.effect("does not let a cancelled prompt settlement consume the follow-up prompt slot", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("grok-cancelled-settlement-before-follow-up");
|
||||
const tempDir = yield* Effect.promise(() =>
|
||||
NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "grok-acp-cancel-race-")),
|
||||
);
|
||||
const requestLogPath = NodePath.join(tempDir, "requests.ndjson");
|
||||
const wrapperPath = yield* Effect.promise(() =>
|
||||
makeMockGrokWrapper({
|
||||
T3_ACP_HANG_FIRST_PROMPT_FOREVER: "1",
|
||||
T3_ACP_REQUEST_LOG_PATH: requestLogPath,
|
||||
}),
|
||||
);
|
||||
const adapter = yield* makeTestAdapter(wrapperPath);
|
||||
|
||||
const runtimeEvents: ProviderRuntimeEvent[] = [];
|
||||
const firstTurnStarted = yield* Deferred.make<TurnId>();
|
||||
const twoTurnsCompleted = yield* Deferred.make<void>();
|
||||
const completedCountRef = yield* Ref.make(0);
|
||||
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
|
||||
Effect.gen(function* () {
|
||||
runtimeEvents.push(event);
|
||||
if (String(event.threadId) !== String(threadId)) {
|
||||
return;
|
||||
}
|
||||
if (event.type === "turn.started" && event.turnId !== undefined) {
|
||||
yield* Deferred.succeed(firstTurnStarted, event.turnId).pipe(Effect.ignore);
|
||||
return;
|
||||
}
|
||||
if (event.type !== "turn.completed") {
|
||||
return;
|
||||
}
|
||||
const completedCount = yield* Ref.updateAndGet(completedCountRef, (count) => count + 1);
|
||||
if (completedCount === 2) {
|
||||
yield* Deferred.succeed(twoTurnsCompleted, undefined);
|
||||
}
|
||||
}),
|
||||
).pipe(Effect.forkChild);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("grok"),
|
||||
cwd: process.cwd(),
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
const firstSendTurnFiber = yield* adapter
|
||||
.sendTurn({ threadId, input: "cancel this prompt", attachments: [] })
|
||||
.pipe(Effect.forkChild);
|
||||
const firstTurnId = yield* Deferred.await(firstTurnStarted).pipe(Effect.timeout("2 seconds"));
|
||||
yield* waitForFileContent(requestLogPath, 80, '"method":"session/prompt"');
|
||||
|
||||
yield* adapter.interruptTurn(threadId, firstTurnId).pipe(Effect.timeout("2 seconds"));
|
||||
const followUp = yield* adapter
|
||||
.sendTurn({ threadId, input: "complete the follow-up", attachments: [] })
|
||||
.pipe(Effect.timeout("2 seconds"));
|
||||
yield* Fiber.join(firstSendTurnFiber).pipe(Effect.timeout("2 seconds"));
|
||||
yield* Deferred.await(twoTurnsCompleted).pipe(Effect.timeout("2 seconds"));
|
||||
|
||||
const turnCompletedEvents = runtimeEvents.filter(
|
||||
(event): event is Extract<ProviderRuntimeEvent, { type: "turn.completed" }> =>
|
||||
event.type === "turn.completed" && String(event.threadId) === String(threadId),
|
||||
);
|
||||
const readySessions = yield* adapter.listSessions();
|
||||
const readySession = readySessions.find((session) => session.threadId === threadId);
|
||||
|
||||
assert.notEqual(String(followUp.turnId), String(firstTurnId));
|
||||
assert.deepEqual(
|
||||
turnCompletedEvents.map((event) => [String(event.turnId), event.payload.state]),
|
||||
[
|
||||
[String(firstTurnId), "cancelled"],
|
||||
[String(followUp.turnId), "completed"],
|
||||
],
|
||||
);
|
||||
assert.equal(readySession?.status, "ready");
|
||||
assert.isUndefined(readySession?.activeTurnId);
|
||||
|
||||
yield* Fiber.interrupt(runtimeEventsFiber);
|
||||
yield* adapter.stopSession(threadId);
|
||||
}).pipe(TestClock.withLive),
|
||||
);
|
||||
|
||||
it.effect("drops late ACP notifications after a turn is cancelled", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("grok-drop-late-cancelled-notifications");
|
||||
const wrapperPath = yield* Effect.promise(() =>
|
||||
makeMockGrokWrapper({
|
||||
T3_ACP_HANG_PROMPT_FOREVER: "1",
|
||||
T3_ACP_EMIT_LATE_UPDATE_AFTER_CANCEL: "1",
|
||||
}),
|
||||
);
|
||||
const lateNativeUpdate = yield* Deferred.make<void>();
|
||||
const adapter = yield* makeTestAdapter(wrapperPath, {
|
||||
nativeEventLogger: {
|
||||
filePath: "memory://grok-cancelled-native-events",
|
||||
write: (record: unknown) =>
|
||||
JSON.stringify(record).includes("late after cancel")
|
||||
? Deferred.succeed(lateNativeUpdate, undefined).pipe(Effect.asVoid)
|
||||
: Effect.void,
|
||||
close: () => Effect.void,
|
||||
},
|
||||
});
|
||||
|
||||
const runtimeEvents: ProviderRuntimeEvent[] = [];
|
||||
const turnStarted = yield* Deferred.make<TurnId>();
|
||||
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
|
||||
Effect.sync(() => {
|
||||
runtimeEvents.push(event);
|
||||
}).pipe(
|
||||
Effect.andThen(
|
||||
event.type === "turn.started" &&
|
||||
event.turnId !== undefined &&
|
||||
String(event.threadId) === String(threadId)
|
||||
? Deferred.succeed(turnStarted, event.turnId).pipe(Effect.asVoid)
|
||||
: Effect.void,
|
||||
),
|
||||
),
|
||||
).pipe(Effect.forkChild);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("grok"),
|
||||
cwd: process.cwd(),
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
const sendTurnFiber = yield* adapter
|
||||
.sendTurn({ threadId, input: "cancel before the late update", attachments: [] })
|
||||
.pipe(Effect.forkChild);
|
||||
const turnId = yield* Deferred.await(turnStarted).pipe(Effect.timeout("2 seconds"));
|
||||
yield* adapter.interruptTurn(threadId, turnId).pipe(Effect.timeout("2 seconds"));
|
||||
yield* Fiber.join(sendTurnFiber).pipe(Effect.timeout("2 seconds"));
|
||||
yield* Deferred.await(lateNativeUpdate).pipe(Effect.timeout("2 seconds"));
|
||||
for (let yieldAttempt = 0; yieldAttempt < 8; yieldAttempt += 1) {
|
||||
yield* Effect.yieldNow;
|
||||
}
|
||||
|
||||
const cancelledIndex = runtimeEvents.findIndex(
|
||||
(event) =>
|
||||
event.type === "turn.completed" &&
|
||||
String(event.threadId) === String(threadId) &&
|
||||
String(event.turnId) === String(turnId) &&
|
||||
event.payload.state === "cancelled",
|
||||
);
|
||||
const turnOutputTypes = new Set([
|
||||
"content.delta",
|
||||
"item.started",
|
||||
"item.updated",
|
||||
"item.completed",
|
||||
"turn.plan.updated",
|
||||
]);
|
||||
const outputAfterCancellation = runtimeEvents
|
||||
.slice(cancelledIndex + 1)
|
||||
.filter(
|
||||
(event) => String(event.threadId) === String(threadId) && turnOutputTypes.has(event.type),
|
||||
);
|
||||
|
||||
assert.isAtLeast(cancelledIndex, 0);
|
||||
assert.deepEqual(outputAfterCancellation, []);
|
||||
|
||||
yield* Fiber.interrupt(runtimeEventsFiber);
|
||||
yield* adapter.stopSession(threadId);
|
||||
}).pipe(TestClock.withLive),
|
||||
);
|
||||
|
||||
it.effect("lets Stop cancel during the xAI completion drain window", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("grok-stop-during-completion-drain");
|
||||
const wrapperPath = yield* Effect.promise(() =>
|
||||
makeMockGrokWrapper({
|
||||
T3_ACP_EMIT_XAI_PROMPT_COMPLETE_THEN_HANG: "1",
|
||||
}),
|
||||
);
|
||||
const adapter = yield* makeTestAdapter(wrapperPath);
|
||||
|
||||
const runtimeEvents: ProviderRuntimeEvent[] = [];
|
||||
const activeTurnIdRef = yield* Ref.make<TurnId | undefined>(undefined);
|
||||
const trailingChunkTurnId = yield* Deferred.make<TurnId>();
|
||||
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
|
||||
Effect.gen(function* () {
|
||||
runtimeEvents.push(event);
|
||||
if (String(event.threadId) !== String(threadId)) {
|
||||
return;
|
||||
}
|
||||
if (event.type === "turn.started") {
|
||||
yield* Ref.set(activeTurnIdRef, event.turnId);
|
||||
}
|
||||
if (event.type !== "content.delta" || event.payload.delta !== "mock") {
|
||||
return;
|
||||
}
|
||||
const turnId = event.turnId ?? (yield* Ref.get(activeTurnIdRef));
|
||||
if (turnId === undefined) {
|
||||
return;
|
||||
}
|
||||
yield* Deferred.succeed(trailingChunkTurnId, turnId).pipe(Effect.ignore);
|
||||
}),
|
||||
).pipe(Effect.forkChild);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("grok"),
|
||||
cwd: process.cwd(),
|
||||
runtimeMode: "full-access",
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok-build" },
|
||||
});
|
||||
|
||||
const sendTurnFiber = yield* adapter
|
||||
.sendTurn({
|
||||
threadId,
|
||||
input: "cancel during completion drain",
|
||||
attachments: [],
|
||||
})
|
||||
.pipe(Effect.forkChild);
|
||||
|
||||
const turnId = yield* Deferred.await(trailingChunkTurnId).pipe(Effect.timeout("2 seconds"));
|
||||
yield* adapter.interruptTurn(threadId, turnId).pipe(Effect.timeout("2 seconds"));
|
||||
yield* Fiber.join(sendTurnFiber).pipe(Effect.timeout("2 seconds"));
|
||||
|
||||
const turnCompletedEvents = runtimeEvents.filter(
|
||||
(event): event is Extract<ProviderRuntimeEvent, { type: "turn.completed" }> =>
|
||||
event.type === "turn.completed" && String(event.threadId) === String(threadId),
|
||||
);
|
||||
const readySessions = yield* adapter.listSessions();
|
||||
const readySession = readySessions.find((session) => session.threadId === threadId);
|
||||
|
||||
assert.lengthOf(turnCompletedEvents, 1);
|
||||
assert.equal(turnCompletedEvents[0]?.payload.state, "cancelled");
|
||||
assert.equal(readySession?.status, "ready");
|
||||
assert.isUndefined(readySession?.activeTurnId);
|
||||
|
||||
yield* Fiber.interrupt(runtimeEventsFiber);
|
||||
yield* adapter.stopSession(threadId);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("settles the in-flight prompt before emitting completion", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("grok-completion-before-next-turn");
|
||||
const wrapperPath = yield* Effect.promise(() => makeMockGrokWrapper());
|
||||
const adapter = yield* makeTestAdapter(wrapperPath);
|
||||
const completedCountRef = yield* Ref.make(0);
|
||||
const secondTurnCompleted = yield* Deferred.make<void>();
|
||||
|
||||
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) => {
|
||||
if (event.type !== "turn.completed" || String(event.threadId) !== String(threadId)) {
|
||||
return Effect.void;
|
||||
}
|
||||
|
||||
return Ref.modify(completedCountRef, (count) => {
|
||||
const nextCount = count + 1;
|
||||
return [nextCount, nextCount] as const;
|
||||
}).pipe(
|
||||
Effect.flatMap((count) => {
|
||||
if (count === 1) {
|
||||
return adapter
|
||||
.sendTurn({
|
||||
threadId,
|
||||
input: "second turn after completion",
|
||||
attachments: [],
|
||||
})
|
||||
.pipe(Effect.forkChild, Effect.asVoid);
|
||||
}
|
||||
if (count === 2) {
|
||||
return Deferred.succeed(secondTurnCompleted, undefined).pipe(Effect.asVoid);
|
||||
}
|
||||
return Effect.void;
|
||||
}),
|
||||
);
|
||||
}).pipe(Effect.forkChild);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("grok"),
|
||||
cwd: process.cwd(),
|
||||
runtimeMode: "full-access",
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok-build" },
|
||||
});
|
||||
|
||||
yield* adapter.sendTurn({
|
||||
threadId,
|
||||
input: "first turn",
|
||||
attachments: [],
|
||||
});
|
||||
yield* Deferred.await(secondTurnCompleted);
|
||||
|
||||
const completedCount = yield* Ref.get(completedCountRef);
|
||||
const readySessions = yield* adapter.listSessions();
|
||||
const readySession = readySessions.find((session) => session.threadId === threadId);
|
||||
|
||||
assert.equal(completedCount, 2);
|
||||
assert.equal(readySession?.status, "ready");
|
||||
assert.isUndefined(readySession?.activeTurnId);
|
||||
|
||||
yield* Fiber.interrupt(runtimeEventsFiber);
|
||||
yield* adapter.stopSession(threadId);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("restores a Grok session to ready when the prompt RPC fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("grok-prompt-failure-ready");
|
||||
const wrapperPath = yield* Effect.promise(() =>
|
||||
makeMockGrokWrapper({
|
||||
T3_ACP_FAIL_PROMPT: "1",
|
||||
}),
|
||||
);
|
||||
const adapter = yield* makeTestAdapter(wrapperPath);
|
||||
const runtimeEvents: ProviderRuntimeEvent[] = [];
|
||||
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
|
||||
Effect.sync(() => {
|
||||
runtimeEvents.push(event);
|
||||
}),
|
||||
).pipe(Effect.forkChild);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("grok"),
|
||||
cwd: process.cwd(),
|
||||
runtimeMode: "full-access",
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok-build" },
|
||||
});
|
||||
|
||||
const error = yield* Effect.flip(
|
||||
adapter.sendTurn({
|
||||
threadId,
|
||||
input: "fail prompt",
|
||||
attachments: [],
|
||||
}),
|
||||
);
|
||||
const readySessions = yield* adapter.listSessions();
|
||||
const readySession = readySessions.find((session) => session.threadId === threadId);
|
||||
const failedTurnCompleted = runtimeEvents.find(
|
||||
(event) => event.type === "turn.completed" && event.threadId === threadId,
|
||||
);
|
||||
|
||||
assert.equal(error._tag, "ProviderAdapterRequestError");
|
||||
assert.equal(readySession?.status, "ready");
|
||||
assert.isUndefined(readySession?.activeTurnId);
|
||||
assert.equal(failedTurnCompleted?.type, "turn.completed");
|
||||
if (failedTurnCompleted?.type === "turn.completed") {
|
||||
assert.equal(failedTurnCompleted.payload.state, "failed");
|
||||
assert.isString(failedTurnCompleted.payload.errorMessage);
|
||||
}
|
||||
|
||||
yield* Fiber.interrupt(runtimeEventsFiber);
|
||||
yield* adapter.stopSession(threadId);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("ignores replayed session/load updates when resuming a Grok session", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("grok-load-replay-filter");
|
||||
const wrapperPath = yield* Effect.promise(() =>
|
||||
makeMockGrokWrapper({
|
||||
T3_ACP_EMIT_LOAD_REPLAY: "1",
|
||||
}),
|
||||
);
|
||||
const adapter = yield* makeTestAdapter(wrapperPath);
|
||||
const runtimeEvents: ProviderRuntimeEvent[] = [];
|
||||
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
|
||||
Effect.sync(() => {
|
||||
runtimeEvents.push(event);
|
||||
}),
|
||||
).pipe(Effect.forkChild);
|
||||
|
||||
const session = yield* adapter.startSession({
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("grok"),
|
||||
cwd: process.cwd(),
|
||||
runtimeMode: "full-access",
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok-build" },
|
||||
resumeCursor: { schemaVersion: 1, sessionId: "mock-session-1" },
|
||||
});
|
||||
|
||||
yield* adapter.sendTurn({
|
||||
threadId,
|
||||
input: "after resume",
|
||||
attachments: [],
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(session.resumeCursor, {
|
||||
schemaVersion: 1,
|
||||
sessionId: "mock-session-1",
|
||||
});
|
||||
assert.isFalse(
|
||||
runtimeEvents.some(
|
||||
(event) => event.type === "item.completed" && event.payload.title === "Replay tool",
|
||||
),
|
||||
);
|
||||
assert.isFalse(
|
||||
runtimeEvents.some(
|
||||
(event) =>
|
||||
event.type === "content.delta" && event.payload.delta === "replayed assistant text",
|
||||
),
|
||||
);
|
||||
|
||||
yield* Fiber.interrupt(runtimeEventsFiber);
|
||||
yield* adapter.stopSession(threadId);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects startSession when provider mismatches", () =>
|
||||
Effect.gen(function* () {
|
||||
const wrapperPath = yield* Effect.promise(() => makeMockGrokWrapper());
|
||||
@@ -1151,7 +331,6 @@ it.layer(grokAdapterTestLayer)("GrokAdapterLive", (it) => {
|
||||
assert.deepEqual(resolvedEvent.payload.answers, {
|
||||
"Which scope should Grok use?": "Workspace",
|
||||
});
|
||||
assert.equal(String(resolvedEvent.turnId), String(requestedEvent.turnId));
|
||||
yield* Fiber.join(sendTurnFiber);
|
||||
|
||||
yield* Fiber.interrupt(eventsFiber);
|
||||
|
||||
@@ -22,7 +22,6 @@ import * as FileSystem from "effect/FileSystem";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as PubSub from "effect/PubSub";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
@@ -63,7 +62,6 @@ import {
|
||||
extractXAiAskUserQuestions,
|
||||
makeXAiAskUserQuestionCancelledResponse,
|
||||
makeXAiAskUserQuestionResponse,
|
||||
promptResponseHasMissingXAiStopReason,
|
||||
XAiAskUserQuestionRequest,
|
||||
} from "../acp/XAiAcpExtension.ts";
|
||||
import { type GrokAdapterShape } from "../Services/GrokAdapter.ts";
|
||||
@@ -110,8 +108,6 @@ interface GrokSessionContext {
|
||||
turns: Array<{ id: TurnId; items: Array<unknown> }>;
|
||||
lastPlanFingerprint: string | undefined;
|
||||
activeTurnId: TurnId | undefined;
|
||||
/** Turns already interrupted; late prompt RPCs must not resurrect them. */
|
||||
interruptedTurnIds: Set<TurnId>;
|
||||
/** Number of sendTurn prompts currently in flight or being prepared.
|
||||
* >0 means a turn is actively running, so a new sendTurn is a steer that
|
||||
* continues it, and only the last remaining prompt settles the turn. */
|
||||
@@ -140,38 +136,10 @@ function settlePendingUserInputsAsCancelled(
|
||||
);
|
||||
}
|
||||
|
||||
function appendPromptResultToTurn(
|
||||
ctx: GrokSessionContext,
|
||||
turnId: TurnId,
|
||||
promptParts: ReadonlyArray<EffectAcpSchema.ContentBlock>,
|
||||
result: EffectAcpSchema.PromptResponse,
|
||||
): void {
|
||||
const existingTurnRecord = ctx.turns.find((turn) => turn.id === turnId);
|
||||
ctx.turns = existingTurnRecord
|
||||
? ctx.turns.map((turn) =>
|
||||
turn.id === turnId
|
||||
? { ...turn, items: [...turn.items, { prompt: promptParts, result }] }
|
||||
: turn,
|
||||
)
|
||||
: [...ctx.turns, { id: turnId, items: [{ prompt: promptParts, result }] }];
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
const resolveNotificationTurnId = (ctx: GrokSessionContext): TurnId | undefined => ctx.activeTurnId;
|
||||
|
||||
const resolveCallbackTurnId = (ctx: GrokSessionContext): TurnId | undefined => ctx.activeTurnId;
|
||||
|
||||
const resolveSessionCallbackTurnId = (
|
||||
sessions: ReadonlyMap<ThreadId, GrokSessionContext>,
|
||||
threadId: ThreadId,
|
||||
): TurnId | undefined => {
|
||||
const ctx = sessions.get(threadId);
|
||||
return ctx ? resolveCallbackTurnId(ctx) : undefined;
|
||||
};
|
||||
|
||||
function parseGrokResume(raw: unknown): { sessionId: string } | undefined {
|
||||
if (!isRecord(raw)) return undefined;
|
||||
if (raw.schemaVersion !== GROK_RESUME_VERSION) return undefined;
|
||||
@@ -202,28 +170,6 @@ function selectAutoApprovedPermissionOption(
|
||||
);
|
||||
}
|
||||
|
||||
function completedStopReasonFromPromptResponse(
|
||||
response: EffectAcpSchema.PromptResponse | undefined,
|
||||
): EffectAcpSchema.StopReason | null {
|
||||
if (response === undefined || promptResponseHasMissingXAiStopReason(response)) {
|
||||
return null;
|
||||
}
|
||||
return response.stopReason;
|
||||
}
|
||||
|
||||
export function grokPromptSettlementBelongsToContext(input: {
|
||||
readonly liveAcpSessionId: string;
|
||||
readonly expectedAcpSessionId: string;
|
||||
readonly liveActiveTurnId: TurnId | undefined;
|
||||
readonly liveSessionActiveTurnId: TurnId | undefined;
|
||||
readonly turnId: TurnId;
|
||||
}): boolean {
|
||||
return (
|
||||
input.liveAcpSessionId === input.expectedAcpSessionId &&
|
||||
(input.liveActiveTurnId === input.turnId || input.liveSessionActiveTurnId === input.turnId)
|
||||
);
|
||||
}
|
||||
|
||||
export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapterLiveOptions) {
|
||||
return Effect.gen(function* () {
|
||||
const boundInstanceId = options?.instanceId ?? ProviderInstanceId.make("grok");
|
||||
@@ -294,144 +240,6 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
const withThreadLock = <A, E, R>(threadId: string, effect: Effect.Effect<A, E, R>) =>
|
||||
Effect.flatMap(getThreadSemaphore(threadId), (semaphore) => semaphore.withPermit(effect));
|
||||
|
||||
const settlePromptInFlight = (
|
||||
threadId: ThreadId,
|
||||
turnId: TurnId,
|
||||
expectedAcpSessionId: string,
|
||||
options?: {
|
||||
readonly errorMessage?: string;
|
||||
readonly completedStopReason?: EffectAcpSchema.StopReason | null;
|
||||
readonly emitTurnCompletion?: boolean;
|
||||
/** Interrupt/cancel: drop every outstanding prompt slot and settle once. */
|
||||
readonly settleAllPrompts?: boolean;
|
||||
},
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const liveCtx = sessions.get(threadId);
|
||||
if (!liveCtx) {
|
||||
return;
|
||||
}
|
||||
const settlementBelongsToLiveContext = grokPromptSettlementBelongsToContext({
|
||||
liveAcpSessionId: liveCtx.acpSessionId,
|
||||
expectedAcpSessionId,
|
||||
liveActiveTurnId: liveCtx.activeTurnId,
|
||||
liveSessionActiveTurnId: liveCtx.session.activeTurnId,
|
||||
turnId,
|
||||
});
|
||||
if (!settlementBelongsToLiveContext) {
|
||||
// interruptTurn already consumed every prompt slot for this turn. A
|
||||
// late prompt result must neither emit a second terminal event nor
|
||||
// consume a slot belonging to a newer turn on the same ACP session.
|
||||
if (
|
||||
liveCtx.acpSessionId !== expectedAcpSessionId ||
|
||||
liveCtx.interruptedTurnIds.has(turnId)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
if (options?.emitTurnCompletion !== false) {
|
||||
if (options?.errorMessage !== undefined) {
|
||||
yield* offerRuntimeEvent({
|
||||
type: "turn.completed",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: PROVIDER,
|
||||
threadId,
|
||||
turnId,
|
||||
payload: {
|
||||
state: "failed",
|
||||
errorMessage: options.errorMessage,
|
||||
},
|
||||
});
|
||||
} else if (options?.completedStopReason !== undefined) {
|
||||
yield* offerRuntimeEvent({
|
||||
type: "turn.completed",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: PROVIDER,
|
||||
threadId,
|
||||
turnId,
|
||||
payload: {
|
||||
state: options.completedStopReason === "cancelled" ? "cancelled" : "completed",
|
||||
stopReason: options.completedStopReason ?? null,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
let settleTurnId = turnId;
|
||||
if (options?.settleAllPrompts) {
|
||||
liveCtx.promptsInFlight = 0;
|
||||
if (liveCtx.activeTurnId !== turnId && liveCtx.session.activeTurnId !== turnId) {
|
||||
const fallbackTurnId = liveCtx.activeTurnId ?? liveCtx.session.activeTurnId;
|
||||
if (!fallbackTurnId) {
|
||||
if (liveCtx.session.status === "running" || liveCtx.session.status === "connecting") {
|
||||
const updatedAt = yield* nowIso;
|
||||
const { activeTurnId: _activeTurnId, ...readySession } = liveCtx.session;
|
||||
liveCtx.activeTurnId = undefined;
|
||||
liveCtx.session = {
|
||||
...readySession,
|
||||
status: "ready",
|
||||
updatedAt,
|
||||
};
|
||||
}
|
||||
return;
|
||||
}
|
||||
settleTurnId = fallbackTurnId;
|
||||
}
|
||||
} else {
|
||||
const remainingPrompts = Math.max(0, liveCtx.promptsInFlight - 1);
|
||||
if (
|
||||
remainingPrompts > 0 ||
|
||||
liveCtx.activeTurnId !== settleTurnId ||
|
||||
liveCtx.session.activeTurnId !== settleTurnId
|
||||
) {
|
||||
liveCtx.promptsInFlight = remainingPrompts;
|
||||
return;
|
||||
}
|
||||
liveCtx.promptsInFlight = remainingPrompts;
|
||||
}
|
||||
const updatedAt = yield* nowIso;
|
||||
const canEmitTurnCompletion =
|
||||
liveCtx.session.status === "running" || liveCtx.session.status === "connecting";
|
||||
const shouldEmitFailedTurn = options?.errorMessage !== undefined && canEmitTurnCompletion;
|
||||
const shouldEmitCompletedTurn =
|
||||
options?.completedStopReason !== undefined && canEmitTurnCompletion;
|
||||
const { activeTurnId: _activeTurnId, ...readySession } = liveCtx.session;
|
||||
liveCtx.activeTurnId = undefined;
|
||||
liveCtx.session = {
|
||||
...readySession,
|
||||
status: "ready",
|
||||
updatedAt,
|
||||
};
|
||||
if (options?.emitTurnCompletion === false) {
|
||||
return;
|
||||
}
|
||||
if (shouldEmitFailedTurn) {
|
||||
yield* offerRuntimeEvent({
|
||||
type: "turn.completed",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: PROVIDER,
|
||||
threadId,
|
||||
turnId: settleTurnId,
|
||||
payload: {
|
||||
state: "failed",
|
||||
errorMessage: options.errorMessage,
|
||||
},
|
||||
});
|
||||
} else if (shouldEmitCompletedTurn) {
|
||||
yield* offerRuntimeEvent({
|
||||
type: "turn.completed",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: PROVIDER,
|
||||
threadId,
|
||||
turnId: settleTurnId,
|
||||
payload: {
|
||||
state: options.completedStopReason === "cancelled" ? "cancelled" : "completed",
|
||||
stopReason: options.completedStopReason ?? null,
|
||||
},
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
const logNative = (threadId: ThreadId, method: string, payload: unknown) =>
|
||||
Effect.gen(function* () {
|
||||
if (!nativeEventLogger) return;
|
||||
@@ -463,8 +271,6 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
|
||||
const emitPlanUpdate = (
|
||||
ctx: GrokSessionContext,
|
||||
turnId: TurnId | undefined,
|
||||
stamp: { readonly eventId: EventId; readonly createdAt: string },
|
||||
payload: {
|
||||
readonly explanation?: string | null;
|
||||
readonly plan: ReadonlyArray<{
|
||||
@@ -476,17 +282,17 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
method: string,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const fingerprint = `${turnId ?? "no-turn"}:${encodeJsonStringForDiagnostics(payload) ?? "[unserializable payload]"}`;
|
||||
const fingerprint = `${ctx.activeTurnId ?? "no-turn"}:${encodeJsonStringForDiagnostics(payload) ?? "[unserializable payload]"}`;
|
||||
if (ctx.lastPlanFingerprint === fingerprint) {
|
||||
return;
|
||||
}
|
||||
ctx.lastPlanFingerprint = fingerprint;
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpPlanUpdatedEvent({
|
||||
stamp,
|
||||
stamp: yield* makeEventStamp(),
|
||||
provider: PROVIDER,
|
||||
threadId: ctx.threadId,
|
||||
turnId,
|
||||
turnId: ctx.activeTurnId,
|
||||
payload,
|
||||
source: "acp.jsonrpc",
|
||||
method,
|
||||
@@ -618,14 +424,13 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
const requestId = ApprovalRequestId.make(yield* randomUUIDv4);
|
||||
const runtimeRequestId = RuntimeRequestId.make(requestId);
|
||||
const resolution = yield* Deferred.make<PendingUserInputResolution>();
|
||||
const turnId = resolveSessionCallbackTurnId(sessions, input.threadId);
|
||||
pendingUserInputs.set(requestId, { resolution });
|
||||
yield* offerRuntimeEvent({
|
||||
type: "user-input.requested",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
turnId,
|
||||
turnId: sessions.get(input.threadId)?.activeTurnId,
|
||||
requestId: runtimeRequestId,
|
||||
payload: { questions: extractXAiAskUserQuestions(params) },
|
||||
raw: {
|
||||
@@ -642,7 +447,7 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
...(yield* makeEventStamp()),
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
turnId,
|
||||
turnId: sessions.get(input.threadId)?.activeTurnId,
|
||||
requestId: runtimeRequestId,
|
||||
payload: { answers: resolvedAnswers },
|
||||
raw: {
|
||||
@@ -681,14 +486,13 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
const requestId = ApprovalRequestId.make(yield* randomUUIDv4);
|
||||
const runtimeRequestId = RuntimeRequestId.make(requestId);
|
||||
const decision = yield* Deferred.make<ProviderApprovalDecision>();
|
||||
const turnId = resolveSessionCallbackTurnId(sessions, input.threadId);
|
||||
pendingApprovals.set(requestId, { decision });
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpRequestOpenedEvent({
|
||||
stamp: yield* makeEventStamp(),
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
turnId,
|
||||
turnId: sessions.get(input.threadId)?.activeTurnId,
|
||||
requestId: runtimeRequestId,
|
||||
permissionRequest,
|
||||
detail:
|
||||
@@ -708,7 +512,7 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
stamp: yield* makeEventStamp(),
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
turnId,
|
||||
turnId: sessions.get(input.threadId)?.activeTurnId,
|
||||
requestId: runtimeRequestId,
|
||||
permissionRequest,
|
||||
decision: resolved,
|
||||
@@ -774,7 +578,6 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
turns: [],
|
||||
lastPlanFingerprint: undefined,
|
||||
activeTurnId: undefined,
|
||||
interruptedTurnIds: new Set(),
|
||||
promptsInFlight: 0,
|
||||
currentModelId: boundModelId,
|
||||
stopped: false,
|
||||
@@ -783,39 +586,14 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
const nf = yield* Stream.runDrain(
|
||||
Stream.mapEffect(acp.getEvents(), (event) =>
|
||||
Effect.gen(function* () {
|
||||
if (event._tag === "EventStreamBarrier") {
|
||||
yield* Deferred.succeed(event.acknowledge, undefined);
|
||||
return;
|
||||
}
|
||||
if (
|
||||
event._tag === "PlanUpdated" ||
|
||||
event._tag === "ToolCallUpdated" ||
|
||||
event._tag === "ContentDelta"
|
||||
) {
|
||||
yield* logNative(ctx.threadId, "session/update", event.rawPayload);
|
||||
}
|
||||
|
||||
if (event._tag === "ModeChanged") {
|
||||
return;
|
||||
}
|
||||
|
||||
const notificationTurnId = resolveNotificationTurnId(ctx);
|
||||
if (
|
||||
notificationTurnId === undefined ||
|
||||
ctx.interruptedTurnIds.has(notificationTurnId)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const stamp = yield* makeEventStamp();
|
||||
|
||||
switch (event._tag) {
|
||||
case "AssistantItemStarted":
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpAssistantItemEvent({
|
||||
stamp,
|
||||
stamp: yield* makeEventStamp(),
|
||||
provider: PROVIDER,
|
||||
threadId: ctx.threadId,
|
||||
turnId: notificationTurnId,
|
||||
turnId: ctx.activeTurnId,
|
||||
itemId: event.itemId,
|
||||
lifecycle: "item.started",
|
||||
}),
|
||||
@@ -824,44 +602,40 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
case "AssistantItemCompleted":
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpAssistantItemEvent({
|
||||
stamp,
|
||||
stamp: yield* makeEventStamp(),
|
||||
provider: PROVIDER,
|
||||
threadId: ctx.threadId,
|
||||
turnId: notificationTurnId,
|
||||
turnId: ctx.activeTurnId,
|
||||
itemId: event.itemId,
|
||||
lifecycle: "item.completed",
|
||||
}),
|
||||
);
|
||||
return;
|
||||
case "PlanUpdated":
|
||||
yield* emitPlanUpdate(
|
||||
ctx,
|
||||
notificationTurnId,
|
||||
stamp,
|
||||
event.payload,
|
||||
event.rawPayload,
|
||||
"session/update",
|
||||
);
|
||||
yield* logNative(ctx.threadId, "session/update", event.rawPayload);
|
||||
yield* emitPlanUpdate(ctx, event.payload, event.rawPayload, "session/update");
|
||||
return;
|
||||
case "ToolCallUpdated":
|
||||
yield* logNative(ctx.threadId, "session/update", event.rawPayload);
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpToolCallEvent({
|
||||
stamp,
|
||||
stamp: yield* makeEventStamp(),
|
||||
provider: PROVIDER,
|
||||
threadId: ctx.threadId,
|
||||
turnId: notificationTurnId,
|
||||
turnId: ctx.activeTurnId,
|
||||
toolCall: event.toolCall,
|
||||
rawPayload: event.rawPayload,
|
||||
}),
|
||||
);
|
||||
return;
|
||||
case "ContentDelta":
|
||||
yield* logNative(ctx.threadId, "session/update", event.rawPayload);
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpContentDeltaEvent({
|
||||
stamp,
|
||||
stamp: yield* makeEventStamp(),
|
||||
provider: PROVIDER,
|
||||
threadId: ctx.threadId,
|
||||
turnId: notificationTurnId,
|
||||
turnId: ctx.activeTurnId,
|
||||
...(event.itemId ? { itemId: event.itemId } : {}),
|
||||
text: event.text,
|
||||
rawPayload: event.rawPayload,
|
||||
@@ -923,15 +697,6 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
// resolving from here on does not settle the turn; decremented on
|
||||
// preparation failure here, and after the prompt below otherwise.
|
||||
ctx.promptsInFlight += 1;
|
||||
// Bind the turn id before cooperative yields so interruptTurn can
|
||||
// settle this prompt even if stop arrives during preparation.
|
||||
ctx.activeTurnId = turnId;
|
||||
ctx.session = {
|
||||
...ctx.session,
|
||||
status: steeringTurnId === undefined ? "connecting" : "running",
|
||||
activeTurnId: turnId,
|
||||
updatedAt: yield* nowIso,
|
||||
};
|
||||
|
||||
return yield* Effect.gen(function* () {
|
||||
const turnModelSelection =
|
||||
@@ -1000,27 +765,12 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
const displayModel = currentModelId
|
||||
? resolveGrokAcpBaseModelId(currentModelId)
|
||||
: undefined;
|
||||
for (let yieldAttempt = 0; yieldAttempt < 8; yieldAttempt += 1) {
|
||||
yield* Effect.yieldNow;
|
||||
}
|
||||
if (ctx.interruptedTurnIds.has(turnId)) {
|
||||
yield* settlePromptInFlight(input.threadId, turnId, ctx.acpSessionId, {
|
||||
completedStopReason: "cancelled",
|
||||
emitTurnCompletion: false,
|
||||
settleAllPrompts: true,
|
||||
});
|
||||
return yield* new ProviderAdapterRequestError({
|
||||
provider: PROVIDER,
|
||||
method: "session/prompt",
|
||||
detail: "Grok prompt was interrupted during preparation.",
|
||||
});
|
||||
}
|
||||
ctx.activeTurnId = turnId;
|
||||
if (steeringTurnId === undefined) {
|
||||
ctx.lastPlanFingerprint = undefined;
|
||||
}
|
||||
ctx.session = {
|
||||
...ctx.session,
|
||||
status: "running",
|
||||
activeTurnId: turnId,
|
||||
updatedAt: yield* nowIso,
|
||||
...(displayModel ? { model: displayModel } : {}),
|
||||
@@ -1046,27 +796,13 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
};
|
||||
}).pipe(
|
||||
Effect.tapCause(() =>
|
||||
Effect.gen(function* () {
|
||||
const liveCtx = sessions.get(input.threadId);
|
||||
if (!liveCtx) {
|
||||
return;
|
||||
}
|
||||
yield* settlePromptInFlight(input.threadId, turnId, liveCtx.acpSessionId, {
|
||||
errorMessage: "Grok prompt preparation failed.",
|
||||
emitTurnCompletion: false,
|
||||
});
|
||||
Effect.sync(() => {
|
||||
ctx.promptsInFlight = Math.max(0, ctx.promptsInFlight - 1);
|
||||
}),
|
||||
),
|
||||
);
|
||||
}),
|
||||
);
|
||||
const promptSettled = yield* Ref.make(false);
|
||||
const promptRpcSucceeded = yield* Ref.make(false);
|
||||
const promptResultRef = yield* Ref.make<EffectAcpSchema.PromptResponse | undefined>(
|
||||
undefined,
|
||||
);
|
||||
|
||||
const promptFailureMessageRef = yield* Ref.make<string | undefined>(undefined);
|
||||
|
||||
return yield* Effect.gen(function* () {
|
||||
const result = yield* prepared.acp
|
||||
@@ -1074,18 +810,6 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
prompt: prepared.promptParts,
|
||||
})
|
||||
.pipe(
|
||||
Effect.tap((promptResult) =>
|
||||
Effect.all([
|
||||
Ref.set(promptRpcSucceeded, true),
|
||||
Ref.set(promptResultRef, promptResult),
|
||||
]),
|
||||
),
|
||||
Effect.tapError((error) =>
|
||||
Ref.set(
|
||||
promptFailureMessageRef,
|
||||
mapAcpToAdapterError(PROVIDER, input.threadId, "session/prompt", error).message,
|
||||
).pipe(Effect.andThen(prepared.acp.drainEvents)),
|
||||
),
|
||||
Effect.mapError((error) =>
|
||||
mapAcpToAdapterError(PROVIDER, input.threadId, "session/prompt", error),
|
||||
),
|
||||
@@ -1096,88 +820,38 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
Effect.gen(function* () {
|
||||
const ctx = yield* requireSession(input.threadId);
|
||||
if (ctx.acpSessionId !== prepared.acpSessionId) {
|
||||
yield* settlePromptInFlight(
|
||||
input.threadId,
|
||||
prepared.turnId,
|
||||
prepared.acpSessionId,
|
||||
{
|
||||
errorMessage: "Grok session changed before the turn completed.",
|
||||
settleAllPrompts: true,
|
||||
},
|
||||
);
|
||||
yield* Ref.set(promptSettled, true);
|
||||
return yield* new ProviderAdapterRequestError({
|
||||
provider: PROVIDER,
|
||||
method: "session/prompt",
|
||||
detail: "Grok session changed before the turn completed.",
|
||||
});
|
||||
}
|
||||
// Keep prompt settlement atomic with respect to Stop and steering.
|
||||
// interruptTurn marks its target before waiting for this lock, so
|
||||
// cancellation can still win while queued ACP events are drained.
|
||||
for (let yieldAttempt = 0; yieldAttempt < 8; yieldAttempt += 1) {
|
||||
yield* Effect.yieldNow;
|
||||
}
|
||||
yield* prepared.acp.drainEvents;
|
||||
if (ctx.interruptedTurnIds.has(prepared.turnId)) {
|
||||
yield* Ref.set(promptSettled, true);
|
||||
return {
|
||||
threadId: input.threadId,
|
||||
turnId: prepared.turnId,
|
||||
resumeCursor: ctx.session.resumeCursor,
|
||||
};
|
||||
}
|
||||
|
||||
if (
|
||||
ctx.promptsInFlight <= 0 ||
|
||||
ctx.activeTurnId !== prepared.turnId ||
|
||||
ctx.session.activeTurnId !== prepared.turnId
|
||||
) {
|
||||
yield* Ref.set(promptSettled, true);
|
||||
return {
|
||||
threadId: input.threadId,
|
||||
turnId: prepared.turnId,
|
||||
resumeCursor: ctx.session.resumeCursor,
|
||||
};
|
||||
}
|
||||
|
||||
appendPromptResultToTurn(ctx, prepared.turnId, prepared.promptParts, result);
|
||||
const existingTurnRecord = ctx.turns.find((turn) => turn.id === prepared.turnId);
|
||||
ctx.turns = existingTurnRecord
|
||||
? ctx.turns.map((turn) =>
|
||||
turn.id === prepared.turnId
|
||||
? {
|
||||
...turn,
|
||||
items: [...turn.items, { prompt: prepared.promptParts, result }],
|
||||
}
|
||||
: turn,
|
||||
)
|
||||
: [
|
||||
...ctx.turns,
|
||||
{ id: prepared.turnId, items: [{ prompt: prepared.promptParts, result }] },
|
||||
];
|
||||
ctx.session = {
|
||||
...ctx.session,
|
||||
status: "running",
|
||||
activeTurnId: prepared.turnId,
|
||||
updatedAt: yield* nowIso,
|
||||
...(prepared.displayModel ? { model: prepared.displayModel } : {}),
|
||||
};
|
||||
const remainingPrompts = Math.max(0, ctx.promptsInFlight - 1);
|
||||
ctx.promptsInFlight = remainingPrompts;
|
||||
|
||||
// Only the last remaining prompt settles the turn. A steer-
|
||||
// superseded prompt resolving while another is in flight or
|
||||
// pending must leave the merged turn running.
|
||||
if (
|
||||
remainingPrompts === 0 &&
|
||||
ctx.activeTurnId === prepared.turnId &&
|
||||
ctx.session.activeTurnId === prepared.turnId
|
||||
) {
|
||||
if (ctx.interruptedTurnIds.has(prepared.turnId)) {
|
||||
yield* Ref.set(promptSettled, true);
|
||||
return {
|
||||
threadId: input.threadId,
|
||||
turnId: prepared.turnId,
|
||||
resumeCursor: ctx.session.resumeCursor,
|
||||
};
|
||||
}
|
||||
const completedAt = yield* nowIso;
|
||||
const { activeTurnId: _completedTurnId, ...readySession } = ctx.session;
|
||||
ctx.activeTurnId = undefined;
|
||||
ctx.session = {
|
||||
...readySession,
|
||||
status: "ready",
|
||||
updatedAt: completedAt,
|
||||
...(prepared.displayModel ? { model: prepared.displayModel } : {}),
|
||||
};
|
||||
const completedStopReason = completedStopReasonFromPromptResponse(result);
|
||||
// Only the last remaining prompt settles the turn — a steer-
|
||||
// superseded prompt resolving (usually cancelled) while another
|
||||
// is in flight or pending must leave the merged turn running.
|
||||
if (ctx.promptsInFlight === 1) {
|
||||
yield* offerRuntimeEvent({
|
||||
type: "turn.completed",
|
||||
...(yield* makeEventStamp()),
|
||||
@@ -1186,13 +860,9 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
turnId: prepared.turnId,
|
||||
payload: {
|
||||
state: result.stopReason === "cancelled" ? "cancelled" : "completed",
|
||||
stopReason: completedStopReason,
|
||||
stopReason: result.stopReason ?? null,
|
||||
},
|
||||
});
|
||||
ctx.interruptedTurnIds.delete(prepared.turnId);
|
||||
yield* Ref.set(promptSettled, true);
|
||||
} else if (remainingPrompts > 0) {
|
||||
yield* Ref.set(promptSettled, true);
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -1204,153 +874,27 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
);
|
||||
}).pipe(
|
||||
Effect.ensuring(
|
||||
Effect.gen(function* () {
|
||||
if (yield* Ref.get(promptSettled)) {
|
||||
return;
|
||||
Effect.sync(() => {
|
||||
const liveCtx = sessions.get(input.threadId);
|
||||
if (liveCtx) {
|
||||
liveCtx.promptsInFlight = Math.max(0, liveCtx.promptsInFlight - 1);
|
||||
}
|
||||
|
||||
if (yield* Ref.get(promptRpcSucceeded)) {
|
||||
const promptResult = yield* Ref.get(promptResultRef);
|
||||
if (promptResult === undefined) {
|
||||
return;
|
||||
}
|
||||
yield* withThreadLock(
|
||||
input.threadId,
|
||||
Effect.gen(function* () {
|
||||
const ctx = yield* requireSession(input.threadId);
|
||||
if (ctx.acpSessionId !== prepared.acpSessionId) {
|
||||
yield* settlePromptInFlight(
|
||||
input.threadId,
|
||||
prepared.turnId,
|
||||
prepared.acpSessionId,
|
||||
{
|
||||
errorMessage: "Grok session changed before the turn completed.",
|
||||
settleAllPrompts: true,
|
||||
},
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (ctx.interruptedTurnIds.has(prepared.turnId)) {
|
||||
return;
|
||||
}
|
||||
if (
|
||||
ctx.promptsInFlight <= 0 ||
|
||||
ctx.activeTurnId !== prepared.turnId ||
|
||||
ctx.session.activeTurnId !== prepared.turnId
|
||||
) {
|
||||
return;
|
||||
}
|
||||
appendPromptResultToTurn(
|
||||
ctx,
|
||||
prepared.turnId,
|
||||
prepared.promptParts,
|
||||
promptResult,
|
||||
);
|
||||
yield* settlePromptInFlight(
|
||||
input.threadId,
|
||||
prepared.turnId,
|
||||
prepared.acpSessionId,
|
||||
{
|
||||
completedStopReason: completedStopReasonFromPromptResponse(promptResult),
|
||||
},
|
||||
);
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const errorMessage = yield* Ref.get(promptFailureMessageRef);
|
||||
yield* withThreadLock(
|
||||
input.threadId,
|
||||
settlePromptInFlight(input.threadId, prepared.turnId, prepared.acpSessionId, {
|
||||
errorMessage: errorMessage ?? "Grok prompt request failed.",
|
||||
}),
|
||||
);
|
||||
}).pipe(Effect.catch(() => Effect.void)),
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
const interruptTurn: GrokAdapterShape["interruptTurn"] = (threadId, turnId) =>
|
||||
const interruptTurn: GrokAdapterShape["interruptTurn"] = (threadId) =>
|
||||
Effect.gen(function* () {
|
||||
const observed = yield* Effect.sync(() => {
|
||||
const ctx = sessions.get(threadId);
|
||||
if (!ctx || ctx.stopped) {
|
||||
return {
|
||||
_tag: "Proceed" as const,
|
||||
acpSessionId: undefined,
|
||||
interruptedTurnId: turnId,
|
||||
};
|
||||
}
|
||||
const activeTurnId = ctx.activeTurnId ?? ctx.session.activeTurnId;
|
||||
if (turnId !== undefined && activeTurnId !== undefined && activeTurnId !== turnId) {
|
||||
return { _tag: "Ignore" as const };
|
||||
}
|
||||
const interruptedTurnId = turnId ?? activeTurnId;
|
||||
if (interruptedTurnId !== undefined) {
|
||||
ctx.interruptedTurnIds.add(interruptedTurnId);
|
||||
}
|
||||
return {
|
||||
_tag: "Proceed" as const,
|
||||
acpSessionId: ctx.acpSessionId,
|
||||
interruptedTurnId,
|
||||
};
|
||||
});
|
||||
if (observed._tag === "Ignore") {
|
||||
return;
|
||||
}
|
||||
|
||||
yield* withThreadLock(
|
||||
threadId,
|
||||
Effect.gen(function* () {
|
||||
const ctx = yield* requireSession(threadId);
|
||||
if (observed.acpSessionId !== undefined && ctx.acpSessionId !== observed.acpSessionId) {
|
||||
return;
|
||||
}
|
||||
const activeTurnId = ctx.activeTurnId ?? ctx.session.activeTurnId;
|
||||
if (turnId !== undefined && activeTurnId !== undefined && activeTurnId !== turnId) {
|
||||
return;
|
||||
}
|
||||
if (
|
||||
observed.interruptedTurnId !== undefined &&
|
||||
activeTurnId !== undefined &&
|
||||
activeTurnId !== observed.interruptedTurnId
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const interruptedTurnId =
|
||||
observed.interruptedTurnId ?? turnId ?? activeTurnId ?? ctx.session.activeTurnId;
|
||||
yield* settlePendingApprovalsAsCancelled(ctx.pendingApprovals);
|
||||
yield* settlePendingUserInputsAsCancelled(ctx.pendingUserInputs);
|
||||
yield* Effect.ignore(
|
||||
ctx.acp.cancel.pipe(
|
||||
Effect.mapError((error) =>
|
||||
mapAcpToAdapterError(PROVIDER, threadId, "session/cancel", error),
|
||||
),
|
||||
),
|
||||
);
|
||||
if (interruptedTurnId) {
|
||||
ctx.interruptedTurnIds.add(interruptedTurnId);
|
||||
yield* settlePromptInFlight(threadId, interruptedTurnId, ctx.acpSessionId, {
|
||||
completedStopReason: "cancelled",
|
||||
settleAllPrompts: true,
|
||||
});
|
||||
} else if (
|
||||
ctx.promptsInFlight > 0 ||
|
||||
ctx.session.status === "running" ||
|
||||
ctx.session.status === "connecting"
|
||||
) {
|
||||
const updatedAt = yield* nowIso;
|
||||
ctx.promptsInFlight = 0;
|
||||
ctx.activeTurnId = undefined;
|
||||
const { activeTurnId: _activeTurnId, ...readySession } = ctx.session;
|
||||
ctx.session = {
|
||||
...readySession,
|
||||
status: "ready",
|
||||
updatedAt,
|
||||
};
|
||||
}
|
||||
}),
|
||||
const ctx = yield* requireSession(threadId);
|
||||
yield* settlePendingApprovalsAsCancelled(ctx.pendingApprovals);
|
||||
yield* settlePendingUserInputsAsCancelled(ctx.pendingUserInputs);
|
||||
yield* Effect.ignore(
|
||||
ctx.acp.cancel.pipe(
|
||||
Effect.mapError((error) =>
|
||||
mapAcpToAdapterError(PROVIDER, threadId, "session/cancel", error),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@@ -7,9 +7,6 @@ import * as NodeFS from "node:fs";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Option from "effect/Option";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { describe, expect } from "vite-plus/test";
|
||||
|
||||
@@ -116,122 +113,6 @@ describe("AcpSessionRuntime", () => {
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("drops session updates emitted for a child ACP session", () =>
|
||||
Effect.gen(function* () {
|
||||
const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
|
||||
yield* runtime.start();
|
||||
|
||||
const promptResult = yield* runtime.prompt({
|
||||
prompt: [{ type: "text", text: "hi" }],
|
||||
});
|
||||
expect(promptResult).toMatchObject({ stopReason: "end_turn" });
|
||||
|
||||
const notes = Array.from(yield* Stream.runCollect(Stream.take(runtime.getEvents(), 4)));
|
||||
expect(notes.map((note) => note._tag)).toEqual([
|
||||
"AssistantItemStarted",
|
||||
"ContentDelta",
|
||||
"ContentDelta",
|
||||
"AssistantItemCompleted",
|
||||
]);
|
||||
expect(
|
||||
notes
|
||||
.filter((note) => note._tag === "ContentDelta")
|
||||
.map((note) => note.text)
|
||||
.join(""),
|
||||
).toBe("root before child root after child");
|
||||
expect(notes.some((note) => note._tag === "ToolCallUpdated")).toBe(false);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
AcpSessionRuntime.layer({
|
||||
spawn: {
|
||||
command: mockAgentCommand,
|
||||
args: mockAgentArgs,
|
||||
env: {
|
||||
T3_ACP_EMIT_FOREIGN_SESSION_UPDATES: "1",
|
||||
},
|
||||
},
|
||||
cwd: process.cwd(),
|
||||
clientInfo: { name: "t3-test", version: "0.0.0" },
|
||||
authMethodId: "test",
|
||||
}),
|
||||
),
|
||||
Effect.scoped,
|
||||
Effect.provide(NodeServices.layer),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("supports successive standard ACP prompts", () =>
|
||||
Effect.gen(function* () {
|
||||
const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
|
||||
yield* runtime.start();
|
||||
|
||||
const firstPromptResult = yield* runtime.prompt({
|
||||
prompt: [{ type: "text", text: "first" }],
|
||||
});
|
||||
const secondPromptResult = yield* runtime.prompt({
|
||||
prompt: [{ type: "text", text: "second" }],
|
||||
});
|
||||
|
||||
expect(firstPromptResult).toMatchObject({ stopReason: "end_turn" });
|
||||
expect(secondPromptResult).toMatchObject({ stopReason: "end_turn" });
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
AcpSessionRuntime.layer({
|
||||
spawn: {
|
||||
command: mockAgentCommand,
|
||||
args: mockAgentArgs,
|
||||
},
|
||||
cwd: process.cwd(),
|
||||
clientInfo: { name: "t3-test", version: "0.0.0" },
|
||||
authMethodId: "test",
|
||||
}),
|
||||
),
|
||||
Effect.scoped,
|
||||
Effect.provide(NodeServices.layer),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("releases a fully silent prompt when session/cancel is requested", () =>
|
||||
Effect.gen(function* () {
|
||||
const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
|
||||
yield* runtime.start();
|
||||
|
||||
const promptFiber = yield* runtime
|
||||
.prompt({
|
||||
prompt: [{ type: "text", text: "hang forever" }],
|
||||
})
|
||||
.pipe(Effect.forkChild({ startImmediately: true }));
|
||||
|
||||
yield* TestClock.adjust("500 millis");
|
||||
yield* runtime.cancel;
|
||||
|
||||
const firstPromptResult = yield* Fiber.join(promptFiber);
|
||||
expect(firstPromptResult).toMatchObject({ stopReason: "cancelled" });
|
||||
|
||||
const secondPromptResult = yield* runtime.prompt({
|
||||
prompt: [{ type: "text", text: "second" }],
|
||||
});
|
||||
expect(secondPromptResult).toMatchObject({ stopReason: "end_turn" });
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
AcpSessionRuntime.layer({
|
||||
spawn: {
|
||||
command: mockAgentCommand,
|
||||
args: mockAgentArgs,
|
||||
env: {
|
||||
T3_ACP_HANG_FIRST_PROMPT_FOREVER: "1",
|
||||
},
|
||||
},
|
||||
cwd: process.cwd(),
|
||||
clientInfo: { name: "t3-test", version: "0.0.0" },
|
||||
authMethodId: "test",
|
||||
}),
|
||||
),
|
||||
Effect.scoped,
|
||||
Effect.provide(NodeServices.layer),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("segments assistant text around ACP tool calls", () =>
|
||||
Effect.gen(function* () {
|
||||
const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
|
||||
@@ -465,109 +346,6 @@ describe("AcpSessionRuntime", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("fails session startup when session/load returns an error", () =>
|
||||
Effect.gen(function* () {
|
||||
const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
|
||||
const error = yield* runtime.start().pipe(Effect.flip);
|
||||
|
||||
expect(error._tag).toBe("AcpRequestError");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
AcpSessionRuntime.layer({
|
||||
authMethodId: "test",
|
||||
spawn: {
|
||||
command: mockAgentCommand,
|
||||
args: mockAgentArgs,
|
||||
env: {
|
||||
T3_ACP_FAIL_LOAD_SESSION: "1",
|
||||
},
|
||||
},
|
||||
cwd: process.cwd(),
|
||||
resumeSessionId: "stale-session-id",
|
||||
clientInfo: { name: "t3-test", version: "0.0.0" },
|
||||
}),
|
||||
),
|
||||
Effect.scoped,
|
||||
Effect.provide(NodeServices.layer),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("ignores session/update replay notifications during session/load", () =>
|
||||
Effect.gen(function* () {
|
||||
const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
|
||||
yield* runtime.start();
|
||||
|
||||
yield* runtime.prompt({
|
||||
prompt: [{ type: "text", text: "hi" }],
|
||||
});
|
||||
const notes = Array.from(yield* Stream.runCollect(Stream.take(runtime.getEvents(), 4)));
|
||||
expect(notes.map((note) => note._tag)).toEqual([
|
||||
"PlanUpdated",
|
||||
"AssistantItemStarted",
|
||||
"ContentDelta",
|
||||
"AssistantItemCompleted",
|
||||
]);
|
||||
expect(notes.some((note) => note._tag === "ToolCallUpdated")).toBe(false);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
AcpSessionRuntime.layer({
|
||||
authMethodId: "test",
|
||||
spawn: {
|
||||
command: mockAgentCommand,
|
||||
args: mockAgentArgs,
|
||||
env: {
|
||||
T3_ACP_EMIT_LOAD_REPLAY: "1",
|
||||
},
|
||||
},
|
||||
cwd: process.cwd(),
|
||||
resumeSessionId: "mock-session-1",
|
||||
clientInfo: { name: "t3-test", version: "0.0.0" },
|
||||
}),
|
||||
),
|
||||
Effect.scoped,
|
||||
Effect.provide(NodeServices.layer),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("completes session/load after replay becomes idle while its RPC stays pending", () =>
|
||||
Effect.gen(function* () {
|
||||
const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
|
||||
const started = yield* runtime.start().pipe(Effect.timeout("2 seconds"));
|
||||
|
||||
expect(started.sessionId).toBe("mock-session-1");
|
||||
expect(started.sessionSetupResult._meta).toMatchObject({
|
||||
t3SessionLoadReady: "replay_idle",
|
||||
});
|
||||
|
||||
const unexpectedReplayEvent = yield* Stream.runHead(runtime.getEvents()).pipe(
|
||||
Effect.timeoutOption("100 millis"),
|
||||
);
|
||||
expect(Option.isNone(unexpectedReplayEvent)).toBe(true);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
AcpSessionRuntime.layer({
|
||||
authMethodId: "test",
|
||||
spawn: {
|
||||
command: mockAgentCommand,
|
||||
args: mockAgentArgs,
|
||||
env: {
|
||||
T3_ACP_HANG_LOAD_SESSION_AFTER_REPLAY: "1",
|
||||
T3_ACP_LOAD_SESSION_DELAY_MS: "10000",
|
||||
},
|
||||
},
|
||||
cwd: process.cwd(),
|
||||
resumeSessionId: "mock-session-1",
|
||||
sessionLoadReplayIdleGap: "50 millis",
|
||||
sessionLoadTimeout: "1 second",
|
||||
clientInfo: { name: "t3-test", version: "0.0.0" },
|
||||
}),
|
||||
),
|
||||
Effect.scoped,
|
||||
Effect.provide(NodeServices.layer),
|
||||
TestClock.withLive,
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("rejects invalid config option values before sending session/set_config_option", () => {
|
||||
const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "acp-runtime-"));
|
||||
const requestLogPath = NodePath.join(tempDir, "requests.ndjson");
|
||||
|
||||
@@ -8,8 +8,6 @@ import {
|
||||
parsePermissionRequest,
|
||||
parseSessionModeState,
|
||||
parseSessionUpdateEvent,
|
||||
sessionUpdateIsReplay,
|
||||
syntheticLoadSessionResponseFromInitialize,
|
||||
} from "./AcpRuntimeModel.ts";
|
||||
|
||||
describe("AcpRuntimeModel", () => {
|
||||
@@ -61,95 +59,6 @@ describe("AcpRuntimeModel", () => {
|
||||
expect(modelConfigId).toBe("model");
|
||||
});
|
||||
|
||||
it("detects Grok session replay updates from _meta.isReplay", () => {
|
||||
expect(
|
||||
sessionUpdateIsReplay({
|
||||
_meta: { isReplay: true },
|
||||
sessionId: "session-1",
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "replayed" },
|
||||
},
|
||||
} satisfies EffectAcpSchema.SessionNotification),
|
||||
).toBe(true);
|
||||
expect(
|
||||
sessionUpdateIsReplay({
|
||||
sessionId: "session-1",
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "live" },
|
||||
},
|
||||
} satisfies EffectAcpSchema.SessionNotification),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("builds a synthetic load response from initialize model state", () => {
|
||||
const response = syntheticLoadSessionResponseFromInitialize({
|
||||
protocolVersion: 1,
|
||||
_meta: {
|
||||
modelState: {
|
||||
currentModelId: "grok-build",
|
||||
availableModels: [{ modelId: "grok-build", name: "Grok Build" }],
|
||||
},
|
||||
},
|
||||
} satisfies EffectAcpSchema.InitializeResponse);
|
||||
|
||||
expect(response.models?.currentModelId).toBe("grok-build");
|
||||
expect(response._meta).toMatchObject({ t3SessionLoadReady: "replay_idle" });
|
||||
});
|
||||
|
||||
it("accepts initialize model descriptions with null", () => {
|
||||
const response = syntheticLoadSessionResponseFromInitialize({
|
||||
protocolVersion: 1,
|
||||
_meta: {
|
||||
modelState: {
|
||||
currentModelId: "grok-build",
|
||||
availableModels: [{ modelId: "grok-build", name: "Grok Build", description: null }],
|
||||
},
|
||||
},
|
||||
} satisfies EffectAcpSchema.InitializeResponse);
|
||||
|
||||
expect(response.models?.availableModels[0]?.description).toBeNull();
|
||||
});
|
||||
|
||||
it("ignores malformed initialize model state in synthetic load responses", () => {
|
||||
const response = syntheticLoadSessionResponseFromInitialize({
|
||||
protocolVersion: 1,
|
||||
_meta: {
|
||||
modelState: {
|
||||
currentModelId: "grok-build",
|
||||
availableModels: [null],
|
||||
},
|
||||
modeState: {
|
||||
currentModeId: "code",
|
||||
availableModes: [{ id: "code", name: 12 }],
|
||||
},
|
||||
},
|
||||
} as EffectAcpSchema.InitializeResponse);
|
||||
|
||||
expect(response.models).toBeUndefined();
|
||||
expect(response.modes).toBeUndefined();
|
||||
expect(response._meta).toMatchObject({ t3SessionLoadReady: "replay_idle" });
|
||||
});
|
||||
|
||||
it("builds a synthetic load response with initialize mode state", () => {
|
||||
const response = syntheticLoadSessionResponseFromInitialize({
|
||||
protocolVersion: 1,
|
||||
_meta: {
|
||||
modeState: {
|
||||
currentModeId: "code",
|
||||
availableModes: [
|
||||
{ id: "ask", name: "Ask" },
|
||||
{ id: "code", name: "Code" },
|
||||
],
|
||||
},
|
||||
},
|
||||
} satisfies EffectAcpSchema.InitializeResponse);
|
||||
|
||||
expect(response.modes?.currentModeId).toBe("code");
|
||||
expect(response.modes?.availableModes).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("projects typed ACP tool call updates into runtime events", () => {
|
||||
const created = parseSessionUpdateEvent({
|
||||
sessionId: "session-1",
|
||||
|
||||
@@ -1,8 +1,3 @@
|
||||
import * as Clock from "effect/Clock";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
import type * as EffectAcpSchema from "effect-acp/schema";
|
||||
import { deriveToolActivityPresentation } from "@t3tools/shared/toolActivity";
|
||||
import type { ToolLifecycleItemType } from "@t3tools/contracts";
|
||||
@@ -11,40 +6,6 @@ function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function isSessionModelState(value: unknown): value is EffectAcpSchema.SessionModelState {
|
||||
if (!isRecord(value) || typeof value.currentModelId !== "string") {
|
||||
return false;
|
||||
}
|
||||
if (!Array.isArray(value.availableModels)) {
|
||||
return false;
|
||||
}
|
||||
return value.availableModels.every(
|
||||
(model) =>
|
||||
isRecord(model) &&
|
||||
typeof model.modelId === "string" &&
|
||||
typeof model.name === "string" &&
|
||||
(model.description === undefined ||
|
||||
model.description === null ||
|
||||
typeof model.description === "string"),
|
||||
);
|
||||
}
|
||||
|
||||
function isSessionModeState(value: unknown): value is EffectAcpSchema.SessionModeState {
|
||||
if (!isRecord(value) || typeof value.currentModeId !== "string") {
|
||||
return false;
|
||||
}
|
||||
if (!Array.isArray(value.availableModes)) {
|
||||
return false;
|
||||
}
|
||||
return value.availableModes.every(
|
||||
(mode) =>
|
||||
isRecord(mode) &&
|
||||
typeof mode.id === "string" &&
|
||||
typeof mode.name === "string" &&
|
||||
(mode.description === undefined || typeof mode.description === "string"),
|
||||
);
|
||||
}
|
||||
|
||||
export interface AcpSessionMode {
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
@@ -453,58 +414,6 @@ export function parsePermissionRequest(
|
||||
};
|
||||
}
|
||||
|
||||
export function sessionUpdateIsReplay(params: EffectAcpSchema.SessionNotification): boolean {
|
||||
const meta = params._meta;
|
||||
return isRecord(meta) && meta.isReplay === true;
|
||||
}
|
||||
|
||||
export interface SessionLoadGate {
|
||||
readonly active: boolean;
|
||||
readonly lastActivityAtMillis: number | undefined;
|
||||
readonly idleGap: Duration.Duration;
|
||||
readonly initializeResult: EffectAcpSchema.InitializeResponse;
|
||||
}
|
||||
|
||||
export const waitForSessionLoadReplayIdle = (input: {
|
||||
readonly gateRef: Ref.Ref<Option.Option<SessionLoadGate>>;
|
||||
}): Effect.Effect<EffectAcpSchema.LoadSessionResponse, never> =>
|
||||
Effect.gen(function* () {
|
||||
const pollInterval = Duration.millis(25);
|
||||
while (true) {
|
||||
const gate = yield* Ref.get(input.gateRef);
|
||||
if (
|
||||
Option.isSome(gate) &&
|
||||
gate.value.active &&
|
||||
gate.value.lastActivityAtMillis !== undefined
|
||||
) {
|
||||
const idleGapMillis = Duration.toMillis(gate.value.idleGap);
|
||||
const nowMillis = yield* Clock.currentTimeMillis;
|
||||
if (nowMillis - gate.value.lastActivityAtMillis >= idleGapMillis) {
|
||||
return syntheticLoadSessionResponseFromInitialize(gate.value.initializeResult);
|
||||
}
|
||||
}
|
||||
yield* Effect.sleep(pollInterval);
|
||||
}
|
||||
});
|
||||
|
||||
export function syntheticLoadSessionResponseFromInitialize(
|
||||
initializeResult: EffectAcpSchema.InitializeResponse,
|
||||
): EffectAcpSchema.LoadSessionResponse {
|
||||
const meta = initializeResult._meta;
|
||||
const modelState = isRecord(meta) ? meta.modelState : undefined;
|
||||
const modeState = isRecord(meta) ? meta.modeState : undefined;
|
||||
const models = isSessionModelState(modelState) ? modelState : undefined;
|
||||
const modes = isSessionModeState(modeState) ? modeState : undefined;
|
||||
|
||||
return {
|
||||
...(models ? { models } : {}),
|
||||
...(modes ? { modes } : {}),
|
||||
_meta: {
|
||||
t3SessionLoadReady: "replay_idle",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function parseSessionUpdateEvent(params: EffectAcpSchema.SessionNotification): {
|
||||
readonly modeId?: string;
|
||||
readonly events: ReadonlyArray<AcpParsedSessionEvent>;
|
||||
|
||||
@@ -1,16 +1,12 @@
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Clock from "effect/Clock";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Queue from "effect/Queue";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as ChildProcess from "effect/unstable/process/ChildProcess";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
@@ -27,9 +23,6 @@ import {
|
||||
mergeToolCallState,
|
||||
parseSessionModeState,
|
||||
parseSessionUpdateEvent,
|
||||
sessionUpdateIsReplay,
|
||||
waitForSessionLoadReplayIdle,
|
||||
type SessionLoadGate,
|
||||
type AcpParsedSessionEvent,
|
||||
type AcpSessionModeState,
|
||||
type AcpToolCallState,
|
||||
@@ -39,16 +32,6 @@ function formatConfigOptionValue(value: string | boolean): string {
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
|
||||
export interface AcpSessionEventStreamBarrier {
|
||||
readonly _tag: "EventStreamBarrier";
|
||||
readonly acknowledge: Deferred.Deferred<void>;
|
||||
}
|
||||
|
||||
export type AcpSessionRuntimeEvent = AcpParsedSessionEvent | AcpSessionEventStreamBarrier;
|
||||
|
||||
const defaultSessionLoadTimeout = Duration.seconds(90);
|
||||
const defaultSessionLoadReplayIdleGap = Duration.seconds(2);
|
||||
|
||||
export interface AcpSpawnInput {
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
@@ -60,8 +43,6 @@ export interface AcpSessionRuntimeOptions {
|
||||
readonly spawn: AcpSpawnInput;
|
||||
readonly cwd: string;
|
||||
readonly resumeSessionId?: string;
|
||||
readonly sessionLoadTimeout?: Duration.Input;
|
||||
readonly sessionLoadReplayIdleGap?: Duration.Input;
|
||||
readonly clientCapabilities?: EffectAcpSchema.InitializeRequest["clientCapabilities"];
|
||||
readonly clientInfo: {
|
||||
readonly name: string;
|
||||
@@ -179,9 +160,7 @@ export class AcpSessionRuntime extends Context.Service<
|
||||
*/
|
||||
readonly start: () => Effect.Effect<AcpSessionRuntimeStartResult, EffectAcpErrors.AcpError>;
|
||||
/** Stream of parsed ACP session events emitted after startup. */
|
||||
readonly getEvents: () => Stream.Stream<AcpSessionRuntimeEvent, never>;
|
||||
/** Waits until the current event consumer has processed every queued event. */
|
||||
readonly drainEvents: Effect.Effect<void>;
|
||||
readonly getEvents: () => Stream.Stream<AcpParsedSessionEvent, never>;
|
||||
/** Latest mode state observed from session setup and `session/update` notifications. */
|
||||
readonly getModeState: Effect.Effect<AcpSessionModeState | undefined>;
|
||||
/** Latest configuration options observed from session setup and configuration writes. */
|
||||
@@ -275,17 +254,12 @@ export const make = (
|
||||
Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const runtimeScope = yield* Scope.Scope;
|
||||
const eventQueue = yield* Queue.unbounded<AcpSessionRuntimeEvent>();
|
||||
const eventQueue = yield* Queue.unbounded<AcpParsedSessionEvent>();
|
||||
const modeStateRef = yield* Ref.make<AcpSessionModeState | undefined>(undefined);
|
||||
const toolCallsRef = yield* Ref.make(new Map<string, AcpToolCallState>());
|
||||
const assistantSegmentRef = yield* Ref.make<AcpAssistantSegmentState>({ nextSegmentIndex: 0 });
|
||||
const configOptionsRef = yield* Ref.make(sessionConfigOptionsFromSetup(undefined));
|
||||
const startStateRef = yield* Ref.make<AcpStartState>({ _tag: "NotStarted" });
|
||||
const promptSerializationSemaphore = yield* Semaphore.make(1);
|
||||
const activePromptFiberRef = yield* Ref.make<
|
||||
Option.Option<Fiber.Fiber<EffectAcpSchema.PromptResponse, EffectAcpErrors.AcpError>>
|
||||
>(Option.none());
|
||||
const sessionLoadGateRef = yield* Ref.make<Option.Option<SessionLoadGate>>(Option.none());
|
||||
|
||||
const logRequest = (event: AcpSessionRequestLogEvent) =>
|
||||
options.requestLogger ? options.requestLogger(event) : Effect.void;
|
||||
@@ -357,40 +331,15 @@ export const make = (
|
||||
const acp = yield* Effect.service(EffectAcpClient.AcpClient).pipe(Effect.provide(acpContext));
|
||||
|
||||
yield* acp.handleSessionUpdate((notification) =>
|
||||
Effect.gen(function* () {
|
||||
const gate = yield* Ref.get(sessionLoadGateRef);
|
||||
if (Option.isSome(gate) && gate.value.active) {
|
||||
const lastActivityAtMillis = yield* Clock.currentTimeMillis;
|
||||
yield* Ref.set(
|
||||
sessionLoadGateRef,
|
||||
Option.some({
|
||||
...gate.value,
|
||||
lastActivityAtMillis,
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (sessionUpdateIsReplay(notification)) {
|
||||
return;
|
||||
}
|
||||
const startState = yield* Ref.get(startStateRef);
|
||||
// One runtime projects one root ACP session. Child-session updates need
|
||||
// explicit lineage routing and must never be flattened into this stream.
|
||||
if (
|
||||
startState._tag !== "Started" ||
|
||||
notification.sessionId !== startState.result.sessionId
|
||||
) {
|
||||
return;
|
||||
}
|
||||
yield* handleSessionUpdate({
|
||||
queue: eventQueue,
|
||||
modeStateRef,
|
||||
toolCallsRef,
|
||||
assistantSegmentRef,
|
||||
params: notification,
|
||||
});
|
||||
handleSessionUpdate({
|
||||
queue: eventQueue,
|
||||
modeStateRef,
|
||||
toolCallsRef,
|
||||
assistantSegmentRef,
|
||||
params: notification,
|
||||
}),
|
||||
);
|
||||
|
||||
const initializeClientCapabilities = {
|
||||
fs: {
|
||||
readTextFile: false,
|
||||
@@ -550,74 +499,27 @@ export const make = (
|
||||
cwd: options.cwd,
|
||||
mcpServers: options.mcpServers ?? [],
|
||||
} satisfies EffectAcpSchema.LoadSessionRequest;
|
||||
const sessionLoadTimeout = Duration.fromInputUnsafe(
|
||||
options.sessionLoadTimeout ?? defaultSessionLoadTimeout,
|
||||
);
|
||||
const sessionLoadReplayIdleGap = Duration.fromInputUnsafe(
|
||||
options.sessionLoadReplayIdleGap ?? defaultSessionLoadReplayIdleGap,
|
||||
);
|
||||
|
||||
yield* Ref.set(
|
||||
sessionLoadGateRef,
|
||||
Option.some({
|
||||
active: true,
|
||||
lastActivityAtMillis: undefined,
|
||||
idleGap: sessionLoadReplayIdleGap,
|
||||
initializeResult,
|
||||
}),
|
||||
);
|
||||
|
||||
sessionId = options.resumeSessionId;
|
||||
sessionSetupResult = yield* Effect.gen(function* () {
|
||||
yield* logRequest({
|
||||
method: "session/load",
|
||||
payload: loadPayload,
|
||||
status: "started",
|
||||
});
|
||||
|
||||
const idleFiber = yield* waitForSessionLoadReplayIdle({
|
||||
gateRef: sessionLoadGateRef,
|
||||
}).pipe(Effect.forkIn(runtimeScope));
|
||||
const loaded = yield* Effect.raceFirst(
|
||||
acp.agent.loadSession(loadPayload),
|
||||
Fiber.join(idleFiber),
|
||||
).pipe(
|
||||
Effect.ensuring(Fiber.interrupt(idleFiber).pipe(Effect.ignore)),
|
||||
Effect.timeoutOption(sessionLoadTimeout),
|
||||
Effect.flatMap((result) =>
|
||||
Option.match(result, {
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
new EffectAcpErrors.AcpTransportError({
|
||||
operation: "call-rpc",
|
||||
method: "session/load",
|
||||
detail: "session/load timed out waiting for RPC response or replay idle gap",
|
||||
cause: undefined,
|
||||
}),
|
||||
),
|
||||
onSome: Effect.succeed,
|
||||
}),
|
||||
),
|
||||
Effect.tap((result) =>
|
||||
logRequest({
|
||||
method: "session/load",
|
||||
payload: loadPayload,
|
||||
status: "succeeded",
|
||||
result,
|
||||
}),
|
||||
),
|
||||
Effect.onError((cause) =>
|
||||
logRequest({
|
||||
method: "session/load",
|
||||
payload: loadPayload,
|
||||
status: "failed",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
const resumed = yield* runLoggedRequest(
|
||||
"session/load",
|
||||
loadPayload,
|
||||
acp.agent.loadSession(loadPayload),
|
||||
).pipe(Effect.exit);
|
||||
if (Exit.isSuccess(resumed)) {
|
||||
sessionId = options.resumeSessionId;
|
||||
sessionSetupResult = resumed.value;
|
||||
} else {
|
||||
const createPayload = {
|
||||
cwd: options.cwd,
|
||||
mcpServers: options.mcpServers ?? [],
|
||||
} satisfies EffectAcpSchema.NewSessionRequest;
|
||||
const created = yield* runLoggedRequest(
|
||||
"session/new",
|
||||
createPayload,
|
||||
acp.agent.createSession(createPayload),
|
||||
);
|
||||
|
||||
return loaded;
|
||||
}).pipe(Effect.ensuring(Ref.set(sessionLoadGateRef, Option.none())));
|
||||
sessionId = created.sessionId;
|
||||
sessionSetupResult = created;
|
||||
}
|
||||
} else {
|
||||
const createPayload = {
|
||||
cwd: options.cwd,
|
||||
@@ -694,48 +596,25 @@ export const make = (
|
||||
handleExtNotification: acp.handleExtNotification,
|
||||
start: () => start,
|
||||
getEvents: () => Stream.fromQueue(eventQueue),
|
||||
drainEvents: Effect.gen(function* () {
|
||||
const acknowledge = yield* Deferred.make<void>();
|
||||
yield* Queue.offer(eventQueue, {
|
||||
_tag: "EventStreamBarrier",
|
||||
acknowledge,
|
||||
});
|
||||
yield* Deferred.await(acknowledge);
|
||||
}),
|
||||
getModeState: Ref.get(modeStateRef),
|
||||
getConfigOptions: Ref.get(configOptionsRef),
|
||||
prompt: (payload) =>
|
||||
promptSerializationSemaphore.withPermit(
|
||||
Effect.gen(function* () {
|
||||
const started = yield* getStartedState;
|
||||
yield* closeActiveAssistantSegment({
|
||||
queue: eventQueue,
|
||||
assistantSegmentRef,
|
||||
});
|
||||
getStartedState.pipe(
|
||||
Effect.flatMap((started) => {
|
||||
const requestPayload = {
|
||||
sessionId: started.sessionId,
|
||||
...payload,
|
||||
} satisfies EffectAcpSchema.PromptRequest;
|
||||
const cancelledResponse = {
|
||||
stopReason: "cancelled",
|
||||
} satisfies EffectAcpSchema.PromptResponse;
|
||||
const promptRpcFiber = yield* runLoggedRequest(
|
||||
"session/prompt",
|
||||
requestPayload,
|
||||
acp.agent.prompt(requestPayload),
|
||||
).pipe(Effect.forkIn(runtimeScope));
|
||||
yield* Ref.set(activePromptFiberRef, Option.some(promptRpcFiber));
|
||||
return yield* Fiber.join(promptRpcFiber).pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
Cause.hasInterruptsOnly(cause)
|
||||
? Effect.succeed(cancelledResponse)
|
||||
: Effect.failCause(cause),
|
||||
),
|
||||
Effect.ensuring(
|
||||
Effect.gen(function* () {
|
||||
yield* Fiber.interrupt(promptRpcFiber).pipe(Effect.ignore);
|
||||
yield* Ref.set(activePromptFiberRef, Option.none());
|
||||
}),
|
||||
return closeActiveAssistantSegment({
|
||||
queue: eventQueue,
|
||||
assistantSegmentRef,
|
||||
}).pipe(
|
||||
Effect.andThen(
|
||||
runLoggedRequest(
|
||||
"session/prompt",
|
||||
requestPayload,
|
||||
acp.agent.prompt(requestPayload),
|
||||
),
|
||||
),
|
||||
Effect.tap(() =>
|
||||
closeActiveAssistantSegment({
|
||||
@@ -747,17 +626,7 @@ export const make = (
|
||||
}),
|
||||
),
|
||||
cancel: getStartedState.pipe(
|
||||
Effect.flatMap((started) =>
|
||||
Effect.gen(function* () {
|
||||
const activePromptFiber = yield* Ref.get(activePromptFiberRef);
|
||||
if (Option.isSome(activePromptFiber)) {
|
||||
yield* Fiber.interrupt(activePromptFiber.value).pipe(Effect.ignore);
|
||||
}
|
||||
yield* acp.agent
|
||||
.cancel({ sessionId: started.sessionId })
|
||||
.pipe(Effect.ignore, Effect.forkIn(runtimeScope));
|
||||
}),
|
||||
),
|
||||
Effect.flatMap((started) => acp.agent.cancel({ sessionId: started.sessionId })),
|
||||
),
|
||||
setMode: (modeId) =>
|
||||
Ref.get(modeStateRef).pipe(
|
||||
@@ -836,7 +705,7 @@ const handleSessionUpdate = ({
|
||||
assistantSegmentRef,
|
||||
params,
|
||||
}: {
|
||||
readonly queue: Queue.Queue<AcpSessionRuntimeEvent>;
|
||||
readonly queue: Queue.Queue<AcpParsedSessionEvent>;
|
||||
readonly modeStateRef: Ref.Ref<AcpSessionModeState | undefined>;
|
||||
readonly toolCallsRef: Ref.Ref<Map<string, AcpToolCallState>>;
|
||||
readonly assistantSegmentRef: Ref.Ref<AcpAssistantSegmentState>;
|
||||
@@ -932,7 +801,7 @@ const ensureActiveAssistantSegment = ({
|
||||
assistantSegmentRef,
|
||||
sessionId,
|
||||
}: {
|
||||
readonly queue: Queue.Queue<AcpSessionRuntimeEvent>;
|
||||
readonly queue: Queue.Queue<AcpParsedSessionEvent>;
|
||||
readonly assistantSegmentRef: Ref.Ref<AcpAssistantSegmentState>;
|
||||
readonly sessionId: string;
|
||||
}) =>
|
||||
@@ -969,7 +838,7 @@ const closeActiveAssistantSegment = ({
|
||||
queue,
|
||||
assistantSegmentRef,
|
||||
}: {
|
||||
readonly queue: Queue.Queue<AcpSessionRuntimeEvent>;
|
||||
readonly queue: Queue.Queue<AcpParsedSessionEvent>;
|
||||
readonly assistantSegmentRef: Ref.Ref<AcpAssistantSegmentState>;
|
||||
}) =>
|
||||
Ref.modify(assistantSegmentRef, (current) => {
|
||||
|
||||
@@ -8,7 +8,6 @@ import type * as EffectAcpSchema from "effect-acp/schema";
|
||||
import { normalizeModelSlug } from "@t3tools/shared/model";
|
||||
|
||||
import * as AcpSessionRuntime from "./AcpSessionRuntime.ts";
|
||||
import { makeXAiPromptCompletionRuntime } from "./XAiAcpExtension.ts";
|
||||
|
||||
const GROK_API_KEY_ENV = "XAI_API_KEY";
|
||||
const GROK_OAUTH2_REFERRER_ENV = "GROK_OAUTH2_REFERRER";
|
||||
@@ -69,10 +68,9 @@ export const makeGrokAcpRuntime = (
|
||||
),
|
||||
),
|
||||
);
|
||||
const runtime = yield* Effect.service(AcpSessionRuntime.AcpSessionRuntime).pipe(
|
||||
return yield* Effect.service(AcpSessionRuntime.AcpSessionRuntime).pipe(
|
||||
Effect.provide(acpContext),
|
||||
);
|
||||
return yield* makeXAiPromptCompletionRuntime(runtime);
|
||||
});
|
||||
|
||||
export function resolveGrokAcpBaseModelId(model: string | null | undefined): string {
|
||||
|
||||
@@ -1,39 +1,12 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off
|
||||
import * as NodePath from "node:path";
|
||||
import * as NodeURL from "node:url";
|
||||
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { describe, expect } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
extractXAiAskUserQuestions,
|
||||
makeXAiAskUserQuestionCancelledResponse,
|
||||
makeXAiAskUserQuestionResponse,
|
||||
makeXAiPromptCompletionRuntime,
|
||||
XAiAskUserQuestionRequest,
|
||||
} from "./XAiAcpExtension.ts";
|
||||
import * as AcpSessionRuntime from "./AcpSessionRuntime.ts";
|
||||
|
||||
const __dirname = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url));
|
||||
const mockAgentPath = NodePath.join(__dirname, "../../../scripts/acp-mock-agent.ts");
|
||||
|
||||
const makePromptCompletionRuntime = (env: NodeJS.ProcessEnv) =>
|
||||
Effect.gen(function* () {
|
||||
const runtime = yield* AcpSessionRuntime.make({
|
||||
spawn: {
|
||||
command: process.execPath,
|
||||
args: [mockAgentPath],
|
||||
env,
|
||||
},
|
||||
cwd: process.cwd(),
|
||||
clientInfo: { name: "t3-test", version: "0.0.0" },
|
||||
authMethodId: "test",
|
||||
});
|
||||
return yield* makeXAiPromptCompletionRuntime(runtime);
|
||||
});
|
||||
|
||||
const decodeXAiAskUserQuestionRequest = Schema.decodeUnknownSync(XAiAskUserQuestionRequest);
|
||||
|
||||
@@ -274,59 +247,4 @@ describe("XAiAcpExtension", () => {
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("resolves a hung standard prompt from xAI prompt completion", () =>
|
||||
Effect.gen(function* () {
|
||||
const runtime = yield* makePromptCompletionRuntime({
|
||||
T3_ACP_EMIT_XAI_PROMPT_COMPLETE_THEN_HANG: "1",
|
||||
});
|
||||
yield* runtime.start();
|
||||
|
||||
const promptResult = yield* runtime.prompt({
|
||||
prompt: [{ type: "text", text: "hi" }],
|
||||
});
|
||||
const promptId = promptResult._meta?.promptId;
|
||||
|
||||
expect(typeof promptId).toBe("string");
|
||||
expect(promptResult).toMatchObject({
|
||||
stopReason: "end_turn",
|
||||
_meta: {
|
||||
sessionId: "mock-session-1",
|
||||
promptId,
|
||||
requestId: promptId,
|
||||
},
|
||||
});
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("ignores stale xAI completion from an already settled prompt", () =>
|
||||
Effect.gen(function* () {
|
||||
const runtime = yield* makePromptCompletionRuntime({
|
||||
T3_ACP_EMIT_STALE_XAI_PROMPT_COMPLETE_BEFORE_SECOND_HANG: "1",
|
||||
});
|
||||
yield* runtime.start();
|
||||
|
||||
const firstPromptResult = yield* runtime.prompt({
|
||||
prompt: [{ type: "text", text: "first" }],
|
||||
});
|
||||
expect(firstPromptResult).toMatchObject({
|
||||
stopReason: "end_turn",
|
||||
_meta: { promptId: "mock-stale-xai-prompt-1" },
|
||||
});
|
||||
|
||||
const secondPromptResult = yield* runtime.prompt({
|
||||
prompt: [{ type: "text", text: "second" }],
|
||||
});
|
||||
const secondPromptId = secondPromptResult._meta?.promptId;
|
||||
expect(typeof secondPromptId).toBe("string");
|
||||
expect(secondPromptId).not.toBe("mock-stale-xai-prompt-1");
|
||||
expect(secondPromptResult).toMatchObject({
|
||||
stopReason: "end_turn",
|
||||
_meta: {
|
||||
promptId: secondPromptId,
|
||||
requestId: secondPromptId,
|
||||
},
|
||||
});
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
});
|
||||
@@ -1,29 +1,5 @@
|
||||
import type { ProviderUserInputAnswers, UserInputQuestion } from "@t3tools/contracts";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import type * as EffectAcpSchema from "effect-acp/schema";
|
||||
|
||||
import type * as AcpSessionRuntime from "./AcpSessionRuntime.ts";
|
||||
|
||||
const XAiPromptCompleteNotification = Schema.Struct({
|
||||
sessionId: Schema.String,
|
||||
promptId: Schema.optional(Schema.String),
|
||||
stopReason: Schema.optional(Schema.String),
|
||||
agentResult: Schema.optional(Schema.NullOr(Schema.Unknown)),
|
||||
});
|
||||
|
||||
type XAiPromptCompleteNotification = typeof XAiPromptCompleteNotification.Type;
|
||||
|
||||
interface PendingXAiPromptCompletion {
|
||||
readonly sessionId: string;
|
||||
readonly promptId: string;
|
||||
readonly deferred: Deferred.Deferred<EffectAcpSchema.PromptResponse>;
|
||||
}
|
||||
|
||||
const completedXAiPromptIdLimit = 128;
|
||||
const xAiStopReasonMissingMetaKey = "xAiStopReasonMissing";
|
||||
|
||||
const XAiAskUserQuestionOption = Schema.Struct({
|
||||
label: Schema.String,
|
||||
@@ -195,238 +171,3 @@ export function makeXAiAskUserQuestionResponse(
|
||||
export function makeXAiAskUserQuestionCancelledResponse(): XAiAskUserQuestionCancelledResponse {
|
||||
return { outcome: "cancelled" };
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds Grok's private prompt-completion fallback around a standards-only ACP runtime.
|
||||
* The underlying runtime remains unaware of xAI methods and metadata.
|
||||
*/
|
||||
export const makeXAiPromptCompletionRuntime = Effect.fn("makeXAiPromptCompletionRuntime")(
|
||||
function* (runtime: AcpSessionRuntime.AcpSessionRuntime["Service"]) {
|
||||
const activeSessionIdRef = yield* Ref.make<string | undefined>(undefined);
|
||||
const pendingRef = yield* Ref.make<ReadonlyArray<PendingXAiPromptCompletion>>([]);
|
||||
const completedPromptIdsRef = yield* Ref.make<ReadonlyArray<string>>([]);
|
||||
let nextPromptFallbackId = 0;
|
||||
const allocatePromptFallbackId = Effect.sync(() => {
|
||||
nextPromptFallbackId += 1;
|
||||
return `t3-xai-prompt-${nextPromptFallbackId}`;
|
||||
});
|
||||
|
||||
yield* runtime.handleExtNotification(
|
||||
"_x.ai/session/prompt_complete",
|
||||
XAiPromptCompleteNotification,
|
||||
(notification) =>
|
||||
resolveXAiPromptCompletionFallback({
|
||||
pendingRef,
|
||||
completedPromptIdsRef,
|
||||
notification,
|
||||
}),
|
||||
);
|
||||
|
||||
return {
|
||||
...runtime,
|
||||
start: () =>
|
||||
runtime
|
||||
.start()
|
||||
.pipe(Effect.tap((started) => Ref.set(activeSessionIdRef, started.sessionId))),
|
||||
prompt: (payload) =>
|
||||
Effect.gen(function* () {
|
||||
const sessionId = yield* Ref.get(activeSessionIdRef);
|
||||
if (sessionId === undefined) {
|
||||
return yield* runtime.prompt(payload);
|
||||
}
|
||||
|
||||
const promptId = yield* allocatePromptFallbackId;
|
||||
const fallback = yield* registerXAiPromptCompletionFallback(
|
||||
pendingRef,
|
||||
sessionId,
|
||||
promptId,
|
||||
);
|
||||
const requestPayload = {
|
||||
...payload,
|
||||
_meta: {
|
||||
...payload._meta,
|
||||
promptId: fallback.promptId,
|
||||
requestId: fallback.promptId,
|
||||
},
|
||||
} satisfies Omit<EffectAcpSchema.PromptRequest, "sessionId">;
|
||||
|
||||
return yield* Effect.raceFirst(
|
||||
runtime.prompt(requestPayload),
|
||||
Deferred.await(fallback.deferred),
|
||||
).pipe(
|
||||
Effect.tap((response) =>
|
||||
rememberCompletedXAiPromptId(completedPromptIdsRef, response, fallback.promptId),
|
||||
),
|
||||
Effect.ensuring(unregisterXAiPromptCompletionFallback(pendingRef, fallback.deferred)),
|
||||
);
|
||||
}),
|
||||
cancel: Ref.get(activeSessionIdRef).pipe(
|
||||
Effect.flatMap((sessionId) =>
|
||||
sessionId === undefined
|
||||
? runtime.cancel
|
||||
: abortPendingPromptCompletions(pendingRef, sessionId).pipe(
|
||||
Effect.andThen(runtime.cancel),
|
||||
),
|
||||
),
|
||||
),
|
||||
} satisfies AcpSessionRuntime.AcpSessionRuntime["Service"];
|
||||
},
|
||||
);
|
||||
|
||||
const registerXAiPromptCompletionFallback = (
|
||||
pendingRef: Ref.Ref<ReadonlyArray<PendingXAiPromptCompletion>>,
|
||||
sessionId: string,
|
||||
promptId: string,
|
||||
) =>
|
||||
Deferred.make<EffectAcpSchema.PromptResponse>().pipe(
|
||||
Effect.tap((deferred) =>
|
||||
Ref.update(pendingRef, (pending) => [...pending, { sessionId, promptId, deferred }]),
|
||||
),
|
||||
Effect.map((deferred) => ({ deferred, promptId })),
|
||||
);
|
||||
|
||||
const unregisterXAiPromptCompletionFallback = (
|
||||
pendingRef: Ref.Ref<ReadonlyArray<PendingXAiPromptCompletion>>,
|
||||
deferred: Deferred.Deferred<EffectAcpSchema.PromptResponse>,
|
||||
) => Ref.update(pendingRef, (pending) => pending.filter((entry) => entry.deferred !== deferred));
|
||||
|
||||
const abortPendingPromptCompletions = (
|
||||
pendingRef: Ref.Ref<ReadonlyArray<PendingXAiPromptCompletion>>,
|
||||
sessionId: string,
|
||||
) =>
|
||||
Ref.modify(pendingRef, (pending) => {
|
||||
const [toAbort, remaining] = pending.reduce<
|
||||
[ReadonlyArray<PendingXAiPromptCompletion>, ReadonlyArray<PendingXAiPromptCompletion>]
|
||||
>(
|
||||
([aborting, kept], entry) =>
|
||||
entry.sessionId === sessionId ? [[...aborting, entry], kept] : [aborting, [...kept, entry]],
|
||||
[[], []],
|
||||
);
|
||||
if (toAbort.length === 0) {
|
||||
return [Effect.void, pending] as const;
|
||||
}
|
||||
return [
|
||||
Effect.forEach(
|
||||
toAbort,
|
||||
(entry) =>
|
||||
Deferred.succeed(
|
||||
entry.deferred,
|
||||
promptResponseFromXAi({
|
||||
sessionId: entry.sessionId,
|
||||
promptId: entry.promptId,
|
||||
stopReason: "cancelled",
|
||||
agentResult: null,
|
||||
}),
|
||||
),
|
||||
{ concurrency: "unbounded" },
|
||||
).pipe(Effect.asVoid),
|
||||
remaining,
|
||||
] as const;
|
||||
}).pipe(Effect.flatten);
|
||||
|
||||
const resolveXAiPromptCompletionFallback = ({
|
||||
pendingRef,
|
||||
completedPromptIdsRef,
|
||||
notification,
|
||||
}: {
|
||||
readonly pendingRef: Ref.Ref<ReadonlyArray<PendingXAiPromptCompletion>>;
|
||||
readonly completedPromptIdsRef: Ref.Ref<ReadonlyArray<string>>;
|
||||
readonly notification: XAiPromptCompleteNotification;
|
||||
}) =>
|
||||
Ref.get(completedPromptIdsRef).pipe(
|
||||
Effect.flatMap((completedPromptIds) => {
|
||||
if (
|
||||
notification.promptId !== undefined &&
|
||||
completedPromptIds.includes(notification.promptId)
|
||||
) {
|
||||
return Effect.void;
|
||||
}
|
||||
return Ref.modify(pendingRef, (pending) => {
|
||||
const index =
|
||||
notification.promptId !== undefined
|
||||
? pending.findIndex(
|
||||
(entry) =>
|
||||
entry.sessionId === notification.sessionId &&
|
||||
entry.promptId === notification.promptId,
|
||||
)
|
||||
: pending.findIndex((entry) => entry.sessionId === notification.sessionId);
|
||||
if (index < 0) {
|
||||
return [Effect.void, pending] as const;
|
||||
}
|
||||
const entry = pending[index];
|
||||
if (!entry) {
|
||||
return [Effect.void, pending] as const;
|
||||
}
|
||||
return [
|
||||
Deferred.succeed(entry.deferred, promptResponseFromXAi(notification)).pipe(Effect.asVoid),
|
||||
[...pending.slice(0, index), ...pending.slice(index + 1)],
|
||||
] as const;
|
||||
}).pipe(Effect.flatten);
|
||||
}),
|
||||
);
|
||||
|
||||
const rememberCompletedXAiPromptId = (
|
||||
completedPromptIdsRef: Ref.Ref<ReadonlyArray<string>>,
|
||||
response: EffectAcpSchema.PromptResponse,
|
||||
fallbackPromptId: string,
|
||||
) => {
|
||||
const promptId = promptIdFromResponse(response) ?? fallbackPromptId;
|
||||
return Ref.update(completedPromptIdsRef, (completedPromptIds) => {
|
||||
if (completedPromptIds.includes(promptId)) {
|
||||
return completedPromptIds;
|
||||
}
|
||||
return [...completedPromptIds, promptId].slice(-completedXAiPromptIdLimit);
|
||||
});
|
||||
};
|
||||
|
||||
function promptIdFromResponse(response: EffectAcpSchema.PromptResponse): string | undefined {
|
||||
const meta = response._meta;
|
||||
if (meta === null || typeof meta !== "object") {
|
||||
return undefined;
|
||||
}
|
||||
const promptId = meta.promptId ?? meta.requestId;
|
||||
return typeof promptId === "string" && promptId.length > 0 ? promptId : undefined;
|
||||
}
|
||||
|
||||
export function promptResponseHasMissingXAiStopReason(
|
||||
response: EffectAcpSchema.PromptResponse,
|
||||
): boolean {
|
||||
const meta = response._meta;
|
||||
return meta !== null && typeof meta === "object" && meta[xAiStopReasonMissingMetaKey] === true;
|
||||
}
|
||||
|
||||
function promptResponseFromXAi(
|
||||
notification: XAiPromptCompleteNotification,
|
||||
): EffectAcpSchema.PromptResponse {
|
||||
const stopReason = normalizeXAiStopReason(notification.stopReason);
|
||||
const meta: Record<string, unknown> = {
|
||||
sessionId: notification.sessionId,
|
||||
};
|
||||
if (notification.stopReason === undefined) {
|
||||
meta[xAiStopReasonMissingMetaKey] = true;
|
||||
}
|
||||
if (notification.promptId !== undefined) {
|
||||
meta.promptId = notification.promptId;
|
||||
meta.requestId = notification.promptId;
|
||||
}
|
||||
if (notification.agentResult !== undefined) {
|
||||
meta.agentResult = notification.agentResult;
|
||||
}
|
||||
return {
|
||||
stopReason,
|
||||
_meta: meta,
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeXAiStopReason(value: string | undefined): EffectAcpSchema.StopReason {
|
||||
switch (value) {
|
||||
case "cancelled":
|
||||
case "end_turn":
|
||||
case "max_tokens":
|
||||
case "max_turn_requests":
|
||||
case "refusal":
|
||||
return value;
|
||||
default:
|
||||
return "end_turn";
|
||||
}
|
||||
}
|
||||
@@ -20,6 +20,7 @@ import { CommandId, ProviderInstanceId } from "@t3tools/contracts";
|
||||
import { RelayClientTracer } from "@t3tools/shared/relayTracing";
|
||||
import { RELAY_ACTIVITY_PUBLISH_TYP, verifyRelayJwt } from "@t3tools/shared/relayJwt";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
@@ -98,6 +99,50 @@ function makeMemorySecretStore() {
|
||||
}
|
||||
|
||||
describe.sequential("signRelayAgentActivityPublishProof", () => {
|
||||
it("redacts relay URL secrets from log attributes", () => {
|
||||
const relayUrl =
|
||||
"https://relay-user:[email protected]/private/path?token=relay-secret#fragment";
|
||||
const attributes = AgentAwarenessRelay.relayUrlLogAttributes(relayUrl);
|
||||
|
||||
expect(attributes).toEqual({
|
||||
relayUrlConfigured: true,
|
||||
relayUrlInputLength: relayUrl.length,
|
||||
relayUrlProtocol: "https:",
|
||||
relayUrlHostname: "relay.example.test",
|
||||
});
|
||||
const renderedAttributes = Object.values(attributes).join(" ");
|
||||
expect(renderedAttributes).not.toContain("relay-user");
|
||||
expect(renderedAttributes).not.toContain("relay-password");
|
||||
expect(renderedAttributes).not.toContain("private/path");
|
||||
expect(renderedAttributes).not.toContain("relay-secret");
|
||||
expect(renderedAttributes).not.toContain("fragment");
|
||||
});
|
||||
|
||||
it("summarizes publish causes without serializing nested failures or defects", () => {
|
||||
const privateFailureDetail = "private relay response body";
|
||||
const privateDefectDetail = "private relay defect detail";
|
||||
const cause = Cause.combine(
|
||||
Cause.fail({
|
||||
_tag: "RelayPublishError",
|
||||
cause: new Error(privateFailureDetail),
|
||||
detail: privateFailureDetail,
|
||||
}),
|
||||
Cause.die(new Error(privateDefectDetail)),
|
||||
);
|
||||
const attributes = AgentAwarenessRelay.relayPublishCauseLogAttributes(cause);
|
||||
|
||||
expect(attributes).toEqual({
|
||||
causeReasonCount: 2,
|
||||
causeFailureCount: 1,
|
||||
causeDefectCount: 1,
|
||||
causeInterruptionCount: 0,
|
||||
causeFailureTags: ["RelayPublishError"],
|
||||
});
|
||||
const renderedAttributes = Object.values(attributes).join(" ");
|
||||
expect(renderedAttributes).not.toContain(privateFailureDetail);
|
||||
expect(renderedAttributes).not.toContain(privateDefectDetail);
|
||||
});
|
||||
|
||||
it("distinguishes pending link credentials from disabled publication", () => {
|
||||
expect(
|
||||
AgentAwarenessRelay.resolveAgentActivityPublishingStartupState({
|
||||
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
RELAY_ACTIVITY_PUBLISH_TYP,
|
||||
signRelayJwt,
|
||||
} from "@t3tools/shared/relayJwt";
|
||||
import { getUrlDiagnostics } from "@t3tools/shared/urlDiagnostics";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
@@ -98,6 +99,44 @@ export function isAgentActivityPublishingEnabled(value: string | null): boolean
|
||||
return value === "true";
|
||||
}
|
||||
|
||||
export function relayUrlLogAttributes(relayUrl: string | undefined) {
|
||||
if (relayUrl === undefined) {
|
||||
return { relayUrlConfigured: false };
|
||||
}
|
||||
const diagnostics = getUrlDiagnostics(relayUrl);
|
||||
return {
|
||||
relayUrlConfigured: true,
|
||||
relayUrlInputLength: diagnostics.inputLength,
|
||||
...(diagnostics.protocol === undefined ? {} : { relayUrlProtocol: diagnostics.protocol }),
|
||||
...(diagnostics.hostname === undefined ? {} : { relayUrlHostname: diagnostics.hostname }),
|
||||
};
|
||||
}
|
||||
|
||||
export function relayPublishCauseLogAttributes(cause: Cause.Cause<unknown>) {
|
||||
const failureTags = cause.reasons.flatMap((reason) => {
|
||||
if (!Cause.isFailReason(reason)) {
|
||||
return [];
|
||||
}
|
||||
const error = reason.error;
|
||||
if (
|
||||
typeof error !== "object" ||
|
||||
error === null ||
|
||||
!("_tag" in error) ||
|
||||
typeof error._tag !== "string"
|
||||
) {
|
||||
return [];
|
||||
}
|
||||
return [error._tag];
|
||||
});
|
||||
return {
|
||||
causeReasonCount: cause.reasons.length,
|
||||
causeFailureCount: cause.reasons.filter(Cause.isFailReason).length,
|
||||
causeDefectCount: cause.reasons.filter(Cause.isDieReason).length,
|
||||
causeInterruptionCount: cause.reasons.filter(Cause.isInterruptReason).length,
|
||||
causeFailureTags: [...new Set(failureTags)],
|
||||
};
|
||||
}
|
||||
|
||||
export function resolveAgentActivityPublishingStartupState(input: {
|
||||
readonly relayConfigured: boolean;
|
||||
readonly publishEnabled: boolean;
|
||||
@@ -417,12 +456,12 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
const publishThread: AgentAwarenessRelay["Service"]["publishThread"] = (threadId) =>
|
||||
publishThreadUnsafe(threadId).pipe(
|
||||
Effect.catchCause((cause) => {
|
||||
return Effect.logWarning("agent activity publish failed", {
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logWarning("agent activity publish failed", {
|
||||
threadId,
|
||||
cause: Cause.pretty(cause),
|
||||
});
|
||||
}),
|
||||
...relayPublishCauseLogAttributes(cause),
|
||||
}),
|
||||
),
|
||||
Effect.withSpan("AgentAwarenessRelay.publishThread"),
|
||||
withRelayClientTracing,
|
||||
);
|
||||
@@ -467,7 +506,7 @@ export const make = Effect.gen(function* () {
|
||||
if (logEnabledWhenReady) {
|
||||
const relayConfig = yield* readRelayConfig.pipe(Effect.orElseSucceed(() => null));
|
||||
yield* Effect.logInfo("agent activity publishing enabled after link reconciliation", {
|
||||
relayUrl: relayConfig?.url,
|
||||
...relayUrlLogAttributes(relayConfig?.url),
|
||||
});
|
||||
}
|
||||
return;
|
||||
@@ -499,7 +538,7 @@ export const make = Effect.gen(function* () {
|
||||
break;
|
||||
case "enabled":
|
||||
yield* Effect.logInfo("agent activity publishing enabled", {
|
||||
relayUrl: relayConfig?.url,
|
||||
...relayUrlLogAttributes(relayConfig?.url),
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -653,7 +653,6 @@ const buildAppUnderTest = (options?: {
|
||||
Layer.mock(PreviewManager.PreviewManager)({
|
||||
open: () => Effect.die("PreviewManager not stubbed in this test"),
|
||||
navigate: () => Effect.die("PreviewManager not stubbed in this test"),
|
||||
resize: () => Effect.die("PreviewManager not stubbed in this test"),
|
||||
reportStatus: () => Effect.void,
|
||||
refresh: () => Effect.void,
|
||||
close: () => Effect.void,
|
||||
@@ -3234,32 +3233,6 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
for (const desktopOrigin of ["t3code://app", "t3code-dev://app"]) {
|
||||
it.effect(`allows credentialed preflights from ${desktopOrigin} in development`, () =>
|
||||
Effect.gen(function* () {
|
||||
yield* buildAppUnderTest({
|
||||
config: { devUrl: new URL(crossOriginClientOrigin) },
|
||||
});
|
||||
|
||||
const sessionUrl = yield* getHttpServerUrl("/api/auth/session");
|
||||
const response = yield* fetchEffect(sessionUrl, {
|
||||
method: "OPTIONS",
|
||||
headers: {
|
||||
origin: desktopOrigin,
|
||||
"access-control-request-method": "GET",
|
||||
"access-control-request-headers": "content-type",
|
||||
},
|
||||
});
|
||||
|
||||
assert.equal(response.status, 204);
|
||||
assertBrowserApiCorsPreflightHeaders(response.headers, {
|
||||
origin: desktopOrigin,
|
||||
credentials: true,
|
||||
});
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
}
|
||||
|
||||
it.effect("includes CORS headers on remote websocket-ticket auth failures", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* buildAppUnderTest();
|
||||
@@ -4054,6 +4027,31 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("continues browser OTLP requests when local trace collection defects", () =>
|
||||
Effect.gen(function* () {
|
||||
const payload = yield* makeBrowserOtlpPayload("client.test");
|
||||
|
||||
yield* buildAppUnderTest({
|
||||
layers: {
|
||||
browserTraceCollector: {
|
||||
record: () => Effect.die(new Error("private local collector failure")),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const response = yield* HttpClient.post("/api/observability/v1/traces", {
|
||||
headers: {
|
||||
cookie: yield* getAuthenticatedSessionCookieHeader(),
|
||||
"content-type": "application/json",
|
||||
},
|
||||
// @effect-diagnostics-next-line preferSchemaOverJson:off
|
||||
body: HttpBody.text(JSON.stringify(payload), "application/json"),
|
||||
});
|
||||
|
||||
assert.equal(response.status, 204);
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("routes websocket rpc server.upsertKeybinding", () =>
|
||||
Effect.gen(function* () {
|
||||
const rule: KeybindingRule = {
|
||||
@@ -4126,46 +4124,6 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("shares one preview automation broker across websocket sessions", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
yield* buildAppUnderTest();
|
||||
|
||||
const wsUrl = yield* getWsServerUrl("/ws");
|
||||
const firstConnected = yield* Deferred.make<string>();
|
||||
const firstClosed = yield* Deferred.make<void>();
|
||||
const host = {
|
||||
clientId: "shared-preview-host",
|
||||
environmentId: testEnvironmentDescriptor.environmentId,
|
||||
} as const;
|
||||
|
||||
yield* withWsRpcClient(wsUrl, (client) =>
|
||||
client[WS_METHODS.previewAutomationConnect](host).pipe(
|
||||
Stream.tap((event) =>
|
||||
event.type === "connected"
|
||||
? Deferred.succeed(firstConnected, event.connectionId)
|
||||
: Effect.void,
|
||||
),
|
||||
Stream.runDrain,
|
||||
Effect.ensuring(Deferred.succeed(firstClosed, undefined)),
|
||||
),
|
||||
).pipe(Effect.forkScoped);
|
||||
|
||||
const firstConnectionId = yield* Deferred.await(firstConnected);
|
||||
const replacementEvent = yield* withWsRpcClient(wsUrl, (client) =>
|
||||
client[WS_METHODS.previewAutomationConnect](host).pipe(Stream.runHead),
|
||||
).pipe(Effect.map(Option.getOrThrow));
|
||||
const firstStreamClosed = yield* Deferred.await(firstClosed).pipe(
|
||||
Effect.timeoutOption("2 seconds"),
|
||||
);
|
||||
|
||||
assert.equal(replacementEvent.type, "connected");
|
||||
assert.notEqual(replacementEvent.connectionId, firstConnectionId);
|
||||
assert.isTrue(Option.isSome(firstStreamClosed));
|
||||
}),
|
||||
).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("rejects websocket rpc handshake when session authentication is missing", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
|
||||
Loaded 100 of 293 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user