Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d0debd7905 |
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' \"$@\"",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,8 +1,8 @@
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as NetService from "@t3tools/shared/Net";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
@@ -33,24 +33,22 @@ const makeDesktopRunId = Crypto.Crypto.pipe(
|
||||
Effect.map((value) => value.replaceAll("-", "").slice(0, 12)),
|
||||
);
|
||||
|
||||
export class DesktopBackendPortUnavailableError extends Schema.TaggedErrorClass<DesktopBackendPortUnavailableError>()(
|
||||
class DesktopBackendPortUnavailableError extends Data.TaggedError(
|
||||
"DesktopBackendPortUnavailableError",
|
||||
{
|
||||
startPort: Schema.Int,
|
||||
maxPort: Schema.Int,
|
||||
hosts: Schema.Array(Schema.String),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
)<{
|
||||
readonly startPort: number;
|
||||
readonly maxPort: number;
|
||||
readonly hosts: readonly string[];
|
||||
}> {
|
||||
override get message() {
|
||||
return `No desktop backend port is available on hosts ${this.hosts.join(", ")} between ${this.startPort} and ${this.maxPort}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopDevelopmentBackendPortRequiredError extends Schema.TaggedErrorClass<DesktopDevelopmentBackendPortRequiredError>()(
|
||||
class DesktopDevelopmentBackendPortRequiredError extends Data.TaggedError(
|
||||
"DesktopDevelopmentBackendPortRequiredError",
|
||||
{},
|
||||
) {
|
||||
override get message(): string {
|
||||
)<{}> {
|
||||
override get message() {
|
||||
return "T3CODE_PORT is required in desktop development.";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,30 +0,0 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
|
||||
import {
|
||||
DesktopBackendPortUnavailableError,
|
||||
DesktopDevelopmentBackendPortRequiredError,
|
||||
} from "./DesktopApp.ts";
|
||||
|
||||
describe("DesktopApp errors", () => {
|
||||
it("preserves unavailable backend port context", () => {
|
||||
const error = new DesktopBackendPortUnavailableError({
|
||||
startPort: 3_773,
|
||||
maxPort: 65_535,
|
||||
hosts: ["127.0.0.1", "0.0.0.0", "::"],
|
||||
});
|
||||
|
||||
assert.equal(error.startPort, 3_773);
|
||||
assert.equal(error.maxPort, 65_535);
|
||||
assert.deepEqual(error.hosts, ["127.0.0.1", "0.0.0.0", "::"]);
|
||||
assert.equal(
|
||||
error.message,
|
||||
"No desktop backend port is available on hosts 127.0.0.1, 0.0.0.0, :: between 3773 and 65535.",
|
||||
);
|
||||
});
|
||||
|
||||
it("reports the required development port", () => {
|
||||
const error = new DesktopDevelopmentBackendPortRequiredError();
|
||||
|
||||
assert.equal(error.message, "T3CODE_PORT is required in desktop development.");
|
||||
});
|
||||
});
|
||||
@@ -1,122 +0,0 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
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 PlatformError from "effect/PlatformError";
|
||||
|
||||
import * as DesktopBackendOutputLog from "./DesktopBackendOutputLog.ts";
|
||||
import * as DesktopConfig from "./DesktopConfig.ts";
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
|
||||
const LOG_FILE_PATH = "/Users/alice/.t3/userdata/logs/server-child.log";
|
||||
|
||||
const environmentLayer = DesktopEnvironment.layer({
|
||||
dirname: "/repo/apps/desktop/dist-electron",
|
||||
homeDirectory: "/Users/alice",
|
||||
platform: "darwin",
|
||||
processArch: "arm64",
|
||||
appVersion: "1.2.3",
|
||||
appPath: "/Applications/T3 Code.app/Contents/Resources/app.asar",
|
||||
isPackaged: true,
|
||||
resourcesPath: "/Applications/T3 Code.app/Contents/Resources",
|
||||
runningUnderArm64Translation: false,
|
||||
}).pipe(Layer.provide(Layer.merge(Path.layer, DesktopConfig.layerTest({}))));
|
||||
|
||||
const withOutputLog = <A, E, R>(
|
||||
effect: Effect.Effect<A, E, R | DesktopBackendOutputLog.DesktopBackendOutputLog>,
|
||||
fileSystemLayer: Layer.Layer<FileSystem.FileSystem>,
|
||||
messages: Array<ReadonlyArray<unknown>>,
|
||||
) => {
|
||||
const logger = Logger.make(({ message }) => {
|
||||
messages.push(Array.isArray(message) ? message : [message]);
|
||||
});
|
||||
const outputLogLayer = DesktopBackendOutputLog.layer.pipe(
|
||||
Layer.provide(Layer.mergeAll(fileSystemLayer, Path.layer, environmentLayer)),
|
||||
Layer.provideMerge(Logger.layer([logger], { mergeWithExisting: false })),
|
||||
);
|
||||
return effect.pipe(Effect.provide(outputLogLayer));
|
||||
};
|
||||
|
||||
const loggedError = (messages: ReadonlyArray<ReadonlyArray<unknown>>): unknown =>
|
||||
messages.flat().find((value) => typeof value === "object" && value !== null && "error" in value)
|
||||
?.error;
|
||||
|
||||
describe("DesktopBackendOutputLog", () => {
|
||||
it.effect("logs setup failures with the log path and exact cause", () => {
|
||||
const messages: Array<ReadonlyArray<unknown>> = [];
|
||||
const cause = PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "makeDirectory",
|
||||
pathOrDescriptor: "/Users/alice/.t3/userdata/logs",
|
||||
description: "private setup diagnostic",
|
||||
});
|
||||
const fileSystemLayer = FileSystem.layerNoop({
|
||||
makeDirectory: () => Effect.fail(cause),
|
||||
});
|
||||
|
||||
return withOutputLog(
|
||||
Effect.gen(function* () {
|
||||
const outputLog = yield* DesktopBackendOutputLog.DesktopBackendOutputLog;
|
||||
yield* outputLog.writeSessionBoundary({ phase: "START", details: "test" });
|
||||
|
||||
const error = loggedError(messages);
|
||||
assert.instanceOf(error, DesktopBackendOutputLog.DesktopBackendOutputLogSetupError);
|
||||
assert.equal(error.logFilePath, LOG_FILE_PATH);
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Failed to initialize the desktop backend output log at ${LOG_FILE_PATH}.`,
|
||||
);
|
||||
assert.notInclude(error.message, "private setup diagnostic");
|
||||
}),
|
||||
fileSystemLayer,
|
||||
messages,
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("logs record write failures with the operation and exact cause", () => {
|
||||
const messages: Array<ReadonlyArray<unknown>> = [];
|
||||
const missingCause = PlatformError.systemError({
|
||||
_tag: "NotFound",
|
||||
module: "FileSystem",
|
||||
method: "stat",
|
||||
pathOrDescriptor: LOG_FILE_PATH,
|
||||
});
|
||||
const writeCause = PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "writeFile",
|
||||
pathOrDescriptor: LOG_FILE_PATH,
|
||||
description: "private write diagnostic",
|
||||
});
|
||||
const fileSystemLayer = FileSystem.layerNoop({
|
||||
makeDirectory: () => Effect.void,
|
||||
stat: () => Effect.fail(missingCause),
|
||||
readDirectory: () => Effect.succeed([]),
|
||||
writeFile: () => Effect.fail(writeCause),
|
||||
});
|
||||
|
||||
return withOutputLog(
|
||||
Effect.gen(function* () {
|
||||
const outputLog = yield* DesktopBackendOutputLog.DesktopBackendOutputLog;
|
||||
yield* outputLog.writeSessionBoundary({ phase: "START", details: "test" });
|
||||
|
||||
const error = loggedError(messages);
|
||||
assert.instanceOf(error, DesktopBackendOutputLog.DesktopBackendOutputLogWriteError);
|
||||
assert.equal(error.operation, "write-record");
|
||||
assert.equal(error.logFilePath, LOG_FILE_PATH);
|
||||
assert.strictEqual(error.cause, writeCause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Desktop backend output log operation "write-record" failed at ${LOG_FILE_PATH}.`,
|
||||
);
|
||||
assert.notInclude(error.message, "private write diagnostic");
|
||||
}),
|
||||
fileSystemLayer,
|
||||
messages,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -19,75 +19,8 @@ export const DESKTOP_LOG_FILE_MAX_FILES = 10;
|
||||
const DESKTOP_BACKEND_CHILD_LOG_FIBER_ID = "#backend-child";
|
||||
|
||||
interface RotatingLogFileWriter {
|
||||
readonly filePath: string;
|
||||
readonly writeBytes: (
|
||||
chunk: Uint8Array,
|
||||
) => Effect.Effect<void, PlatformError.PlatformError | DesktopLogFileWriterRecoveryError>;
|
||||
readonly writeText: (
|
||||
chunk: string,
|
||||
) => Effect.Effect<void, PlatformError.PlatformError | DesktopLogFileWriterRecoveryError>;
|
||||
}
|
||||
|
||||
class DesktopLogFileWriterConfigurationError extends Schema.TaggedErrorClass<DesktopLogFileWriterConfigurationError>()(
|
||||
"DesktopLogFileWriterConfigurationError",
|
||||
{
|
||||
option: Schema.Literals(["maxBytes", "maxFiles"]),
|
||||
value: Schema.Number,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `${this.option} must be >= 1 (received ${this.value})`;
|
||||
}
|
||||
}
|
||||
|
||||
class DesktopLogFileWriterRecoveryError extends Schema.TaggedErrorClass<DesktopLogFileWriterRecoveryError>()(
|
||||
"DesktopLogFileWriterRecoveryError",
|
||||
{
|
||||
logFilePath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
recoveryCause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to refresh desktop backend output log size after a write failure at ${this.logFilePath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopBackendOutputLogSetupError extends Schema.TaggedErrorClass<DesktopBackendOutputLogSetupError>()(
|
||||
"DesktopBackendOutputLogSetupError",
|
||||
{
|
||||
logFilePath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to initialize the desktop backend output log at ${this.logFilePath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopBackendOutputLogWriteError extends Schema.TaggedErrorClass<DesktopBackendOutputLogWriteError>()(
|
||||
"DesktopBackendOutputLogWriteError",
|
||||
{
|
||||
operation: Schema.Literals(["encode-record", "write-record"]),
|
||||
logFilePath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Desktop backend output log operation "${this.operation}" failed at ${this.logFilePath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopBackendConsoleWriteError extends Schema.TaggedErrorClass<DesktopBackendConsoleWriteError>()(
|
||||
"DesktopBackendConsoleWriteError",
|
||||
{
|
||||
streamName: Schema.Literals(["stdout", "stderr"]),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to mirror desktop backend output to ${this.streamName}.`;
|
||||
}
|
||||
readonly writeBytes: (chunk: Uint8Array) => Effect.Effect<void>;
|
||||
readonly writeText: (chunk: string) => Effect.Effect<void>;
|
||||
}
|
||||
|
||||
export class DesktopBackendOutputLog extends Context.Service<
|
||||
@@ -104,6 +37,18 @@ export class DesktopBackendOutputLog extends Context.Service<
|
||||
}
|
||||
>()("@t3tools/desktop/app/DesktopBackendOutputLog") {}
|
||||
|
||||
class DesktopLogFileWriterConfigurationError extends Schema.TaggedErrorClass<DesktopLogFileWriterConfigurationError>()(
|
||||
"DesktopLogFileWriterConfigurationError",
|
||||
{
|
||||
option: Schema.Literals(["maxBytes", "maxFiles"]),
|
||||
value: Schema.Number,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `${this.option} must be >= 1 (received ${this.value})`;
|
||||
}
|
||||
}
|
||||
|
||||
type DesktopLogFileWriterError =
|
||||
| DesktopLogFileWriterConfigurationError
|
||||
| PlatformError.PlatformError;
|
||||
@@ -140,13 +85,10 @@ const sanitizeLogValue = (value: string): string => value.replace(/\s+/g, " ").t
|
||||
const refreshFileSize = (
|
||||
fileSystem: FileSystem.FileSystem,
|
||||
filePath: string,
|
||||
): Effect.Effect<number, PlatformError.PlatformError> =>
|
||||
): Effect.Effect<number, never> =>
|
||||
fileSystem.stat(filePath).pipe(
|
||||
Effect.map((stat) => Number(stat.size)),
|
||||
Effect.catchTags({
|
||||
PlatformError: (error) =>
|
||||
error.reason._tag === "NotFound" ? Effect.succeed(0) : Effect.fail(error),
|
||||
}),
|
||||
Effect.orElseSucceed(() => 0),
|
||||
);
|
||||
|
||||
const makeRotatingLogFileWriter = Effect.fn("makeRotatingLogFileWriter")(function* (input: {
|
||||
@@ -184,52 +126,41 @@ const makeRotatingLogFileWriter = Effect.fn("makeRotatingLogFileWriter")(functio
|
||||
const currentSize = yield* Ref.make(yield* refreshFileSize(fileSystem, input.filePath));
|
||||
const mutex = yield* Semaphore.make(1);
|
||||
|
||||
const recoverCurrentSize = (
|
||||
cause: PlatformError.PlatformError,
|
||||
): Effect.Effect<never, PlatformError.PlatformError | DesktopLogFileWriterRecoveryError> =>
|
||||
refreshFileSize(fileSystem, input.filePath).pipe(
|
||||
Effect.matchEffect({
|
||||
onFailure: (recoveryCause) =>
|
||||
Effect.fail(
|
||||
new DesktopLogFileWriterRecoveryError({
|
||||
logFilePath: input.filePath,
|
||||
cause,
|
||||
recoveryCause,
|
||||
}),
|
||||
),
|
||||
onSuccess: (size) => Ref.set(currentSize, size).pipe(Effect.andThen(Effect.fail(cause))),
|
||||
}),
|
||||
);
|
||||
|
||||
const pruneOverflowBackups = Effect.gen(function* () {
|
||||
const entries = yield* fileSystem.readDirectory(directory);
|
||||
const entries = yield* fileSystem.readDirectory(directory).pipe(Effect.orElseSucceed(() => []));
|
||||
for (const entry of entries) {
|
||||
if (!entry.startsWith(`${baseName}.`)) continue;
|
||||
const suffix = Number(entry.slice(baseName.length + 1));
|
||||
if (!Number.isInteger(suffix) || suffix <= maxFiles) continue;
|
||||
yield* fileSystem.remove(path.join(directory, entry), { force: true });
|
||||
yield* fileSystem.remove(path.join(directory, entry), { force: true }).pipe(Effect.ignore);
|
||||
}
|
||||
});
|
||||
|
||||
const rotate = Effect.gen(function* () {
|
||||
yield* fileSystem.remove(withSuffix(maxFiles), { force: true });
|
||||
yield* fileSystem.remove(withSuffix(maxFiles), { force: true }).pipe(Effect.ignore);
|
||||
for (let index = maxFiles - 1; index >= 1; index -= 1) {
|
||||
const source = withSuffix(index);
|
||||
const sourceExists = yield* fileSystem.exists(source);
|
||||
const sourceExists = yield* fileSystem.exists(source).pipe(Effect.orElseSucceed(() => false));
|
||||
if (sourceExists) {
|
||||
yield* fileSystem.rename(source, withSuffix(index + 1));
|
||||
}
|
||||
}
|
||||
const currentExists = yield* fileSystem.exists(input.filePath);
|
||||
const currentExists = yield* fileSystem
|
||||
.exists(input.filePath)
|
||||
.pipe(Effect.orElseSucceed(() => false));
|
||||
if (currentExists) {
|
||||
yield* fileSystem.rename(input.filePath, withSuffix(1));
|
||||
}
|
||||
yield* Ref.set(currentSize, 0);
|
||||
});
|
||||
}).pipe(
|
||||
Effect.catch(() =>
|
||||
refreshFileSize(fileSystem, input.filePath).pipe(
|
||||
Effect.flatMap((size) => Ref.set(currentSize, size)),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const writeBytes = (
|
||||
chunk: Uint8Array,
|
||||
): Effect.Effect<void, PlatformError.PlatformError | DesktopLogFileWriterRecoveryError> => {
|
||||
const writeBytes = (chunk: Uint8Array): Effect.Effect<void> => {
|
||||
if (chunk.byteLength === 0) return Effect.void;
|
||||
|
||||
return mutex.withPermits(1)(
|
||||
@@ -247,9 +178,11 @@ const makeRotatingLogFileWriter = Effect.fn("makeRotatingLogFileWriter")(functio
|
||||
yield* rotate;
|
||||
}
|
||||
}).pipe(
|
||||
Effect.catchTags({
|
||||
PlatformError: recoverCurrentSize,
|
||||
}),
|
||||
Effect.catch(() =>
|
||||
refreshFileSize(fileSystem, input.filePath).pipe(
|
||||
Effect.flatMap((size) => Ref.set(currentSize, size)),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
};
|
||||
@@ -257,7 +190,6 @@ const makeRotatingLogFileWriter = Effect.fn("makeRotatingLogFileWriter")(functio
|
||||
yield* pruneOverflowBackups;
|
||||
|
||||
return {
|
||||
filePath: input.filePath,
|
||||
writeBytes,
|
||||
writeText: (chunk) => writeBytes(textEncoder.encode(chunk)),
|
||||
} satisfies RotatingLogFileWriter;
|
||||
@@ -267,17 +199,10 @@ const writeDevelopmentConsoleOutput = (
|
||||
streamName: "stdout" | "stderr",
|
||||
chunk: Uint8Array,
|
||||
): Effect.Effect<void> =>
|
||||
Effect.try({
|
||||
try: () => {
|
||||
const output = streamName === "stderr" ? process.stderr : process.stdout;
|
||||
output.write(chunk);
|
||||
},
|
||||
catch: (cause) => new DesktopBackendConsoleWriteError({ streamName, cause }),
|
||||
}).pipe(
|
||||
Effect.catchTags({
|
||||
DesktopBackendConsoleWriteError: (error) => Effect.logError(error.message, { error }),
|
||||
}),
|
||||
);
|
||||
Effect.sync(() => {
|
||||
const output = streamName === "stderr" ? process.stderr : process.stdout;
|
||||
output.write(chunk);
|
||||
}).pipe(Effect.ignore);
|
||||
|
||||
const writeBackendChildLogRecord = Effect.fn("desktop.observability.writeBackendChildLogRecord")(
|
||||
function* (
|
||||
@@ -297,47 +222,17 @@ const writeBackendChildLogRecord = Effect.fn("desktop.observability.writeBackend
|
||||
annotations: input.annotations,
|
||||
spans: {},
|
||||
fiberId: DESKTOP_BACKEND_CHILD_LOG_FIBER_ID,
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopBackendOutputLogWriteError({
|
||||
operation: "encode-record",
|
||||
logFilePath: logFile.filePath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* logFile.writeText(`${encoded}\n`).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopBackendOutputLogWriteError({
|
||||
operation: "write-record",
|
||||
logFilePath: logFile.filePath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}).pipe(
|
||||
Effect.catchTags({
|
||||
DesktopBackendOutputLogWriteError: (error) => Effect.logError(error.message, { error }),
|
||||
}),
|
||||
);
|
||||
});
|
||||
yield* logFile.writeText(`${encoded}\n`);
|
||||
}).pipe(Effect.ignore({ log: true }));
|
||||
},
|
||||
);
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const make = Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const logFilePath = environment.path.join(environment.logDir, "server-child.log");
|
||||
const writer = yield* makeRotatingLogFileWriter({
|
||||
filePath: logFilePath,
|
||||
}).pipe(
|
||||
Effect.mapError((cause) => new DesktopBackendOutputLogSetupError({ logFilePath, cause })),
|
||||
Effect.map(Option.some),
|
||||
Effect.catchTags({
|
||||
DesktopBackendOutputLogSetupError: (error) =>
|
||||
Effect.logError(error.message, { error }).pipe(Effect.as(Option.none())),
|
||||
}),
|
||||
);
|
||||
filePath: environment.path.join(environment.logDir, "server-child.log"),
|
||||
}).pipe(Effect.option);
|
||||
|
||||
const service = Option.match(writer, {
|
||||
onNone: () => DesktopBackendOutputLogNoop,
|
||||
|
||||
@@ -393,21 +393,7 @@ describe("DesktopConnectionCatalogStore", () => {
|
||||
assert.isTrue(yield* store.set('{"schemaVersion":1,"targets":[]}'));
|
||||
yield* Ref.set(failDecrypt, true);
|
||||
const error = yield* store.get.pipe(Effect.flip);
|
||||
assert.instanceOf(
|
||||
error,
|
||||
DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreProtectionError,
|
||||
);
|
||||
assert.equal(error.operation, "decrypt-catalog");
|
||||
assert.equal(error.catalogPath, `${baseDir}/userdata/connection-catalog.json`);
|
||||
assert.instanceOf(error.cause, ElectronSafeStorage.ElectronSafeStorageDecryptError);
|
||||
const decryptError = error.cause as ElectronSafeStorage.ElectronSafeStorageDecryptError;
|
||||
assert.instanceOf(decryptError.cause, Error);
|
||||
assert.equal(decryptError.cause.message, "invalid encrypted catalog");
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Desktop connection catalog protection failed during decrypt-catalog at ${baseDir}/userdata/connection-catalog.json.`,
|
||||
);
|
||||
assert.notEqual(error.message, decryptError.message);
|
||||
assert.instanceOf(error, ElectronSafeStorage.ElectronSafeStorageDecryptError);
|
||||
yield* Ref.set(failDecrypt, false);
|
||||
assert.deepStrictEqual(yield* store.get, Option.some('{"schemaVersion":1,"targets":[]}'));
|
||||
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
|
||||
|
||||
@@ -53,6 +53,8 @@ const DesktopConnectionCatalogStoreWriteOperation = Schema.Literals([
|
||||
"write-temporary-file",
|
||||
"replace-catalog-file",
|
||||
]);
|
||||
type DesktopConnectionCatalogStoreWriteOperation =
|
||||
typeof DesktopConnectionCatalogStoreWriteOperation.Type;
|
||||
|
||||
const DesktopConnectionCatalogStoreMigrationOperation = Schema.Literals([
|
||||
"read-legacy-registry",
|
||||
@@ -60,12 +62,8 @@ const DesktopConnectionCatalogStoreMigrationOperation = Schema.Literals([
|
||||
"encode-catalog",
|
||||
"persist-catalog",
|
||||
]);
|
||||
|
||||
const DesktopConnectionCatalogStoreProtectionOperation = Schema.Literals([
|
||||
"check-encryption-availability",
|
||||
"encrypt-catalog",
|
||||
"decrypt-catalog",
|
||||
]);
|
||||
type DesktopConnectionCatalogStoreMigrationOperation =
|
||||
typeof DesktopConnectionCatalogStoreMigrationOperation.Type;
|
||||
|
||||
export class DesktopConnectionCatalogStoreWriteError extends Schema.TaggedErrorClass<DesktopConnectionCatalogStoreWriteError>()(
|
||||
"DesktopConnectionCatalogStoreWriteError",
|
||||
@@ -80,6 +78,17 @@ export class DesktopConnectionCatalogStoreWriteError extends Schema.TaggedErrorC
|
||||
}
|
||||
}
|
||||
|
||||
const writeError = (
|
||||
operation: DesktopConnectionCatalogStoreWriteOperation,
|
||||
path: string,
|
||||
cause: unknown,
|
||||
): DesktopConnectionCatalogStoreWriteError =>
|
||||
new DesktopConnectionCatalogStoreWriteError({
|
||||
operation,
|
||||
path,
|
||||
cause,
|
||||
});
|
||||
|
||||
export class DesktopConnectionCatalogStoreDecodeError extends Schema.TaggedErrorClass<DesktopConnectionCatalogStoreDecodeError>()(
|
||||
"DesktopConnectionCatalogStoreDecodeError",
|
||||
{
|
||||
@@ -133,18 +142,18 @@ export class DesktopConnectionCatalogStoreMigrationError extends Schema.TaggedEr
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopConnectionCatalogStoreProtectionError extends Schema.TaggedErrorClass<DesktopConnectionCatalogStoreProtectionError>()(
|
||||
"DesktopConnectionCatalogStoreProtectionError",
|
||||
{
|
||||
operation: DesktopConnectionCatalogStoreProtectionOperation,
|
||||
catalogPath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Desktop connection catalog protection failed during ${this.operation} at ${this.catalogPath}.`;
|
||||
}
|
||||
}
|
||||
const migrationError = (
|
||||
operation: DesktopConnectionCatalogStoreMigrationOperation,
|
||||
catalogPath: string,
|
||||
cause: unknown,
|
||||
environmentId?: string,
|
||||
): DesktopConnectionCatalogStoreMigrationError =>
|
||||
new DesktopConnectionCatalogStoreMigrationError({
|
||||
operation,
|
||||
catalogPath,
|
||||
...(environmentId === undefined ? {} : { environmentId }),
|
||||
cause,
|
||||
});
|
||||
|
||||
export class DesktopConnectionCatalogStore extends Context.Service<
|
||||
DesktopConnectionCatalogStore,
|
||||
@@ -155,13 +164,13 @@ export class DesktopConnectionCatalogStore extends Context.Service<
|
||||
| DesktopConnectionCatalogStoreDocumentDecodeError
|
||||
| DesktopConnectionCatalogStoreDecodeError
|
||||
| DesktopConnectionCatalogStoreMigrationError
|
||||
| DesktopConnectionCatalogStoreProtectionError
|
||||
| ElectronSafeStorage.ElectronSafeStorageError
|
||||
>;
|
||||
readonly set: (
|
||||
catalog: string,
|
||||
) => Effect.Effect<
|
||||
boolean,
|
||||
DesktopConnectionCatalogStoreWriteError | DesktopConnectionCatalogStoreProtectionError
|
||||
DesktopConnectionCatalogStoreWriteError | ElectronSafeStorage.ElectronSafeStorageError
|
||||
>;
|
||||
readonly clear: Effect.Effect<void>;
|
||||
}
|
||||
@@ -227,46 +236,20 @@ const writeDocument = Effect.fn("desktop.connectionCatalogStore.writeDocument")(
|
||||
const directory = input.path.dirname(input.catalogPath);
|
||||
const tempPath = `${input.catalogPath}.${process.pid}.${input.suffix}.tmp`;
|
||||
const encoded = yield* encodeEncryptedConnectionCatalogDocumentJson(input.document).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopConnectionCatalogStoreWriteError({
|
||||
operation: "encode-document",
|
||||
path: input.catalogPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* input.fileSystem.makeDirectory(directory, { recursive: true }).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopConnectionCatalogStoreWriteError({
|
||||
operation: "create-directory",
|
||||
path: directory,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.mapError((cause) => writeError("encode-document", input.catalogPath, cause)),
|
||||
);
|
||||
yield* input.fileSystem
|
||||
.makeDirectory(directory, { recursive: true })
|
||||
.pipe(Effect.mapError((cause) => writeError("create-directory", directory, cause)));
|
||||
yield* Effect.gen(function* () {
|
||||
yield* input.fileSystem.writeFileString(tempPath, `${encoded}\n`).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopConnectionCatalogStoreWriteError({
|
||||
operation: "write-temporary-file",
|
||||
path: tempPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* input.fileSystem.rename(tempPath, input.catalogPath).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopConnectionCatalogStoreWriteError({
|
||||
operation: "replace-catalog-file",
|
||||
path: input.catalogPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* input.fileSystem
|
||||
.writeFileString(tempPath, `${encoded}\n`)
|
||||
.pipe(Effect.mapError((cause) => writeError("write-temporary-file", tempPath, cause)));
|
||||
yield* input.fileSystem
|
||||
.rename(tempPath, input.catalogPath)
|
||||
.pipe(
|
||||
Effect.mapError((cause) => writeError("replace-catalog-file", input.catalogPath, cause)),
|
||||
);
|
||||
}).pipe(
|
||||
Effect.ensuring(
|
||||
input.fileSystem.remove(tempPath, { force: true }).pipe(
|
||||
@@ -347,17 +330,13 @@ const migrateSavedEnvironmentRecords = Effect.fn(
|
||||
wsBaseUrl: record.wsBaseUrl,
|
||||
}),
|
||||
);
|
||||
const token = yield* savedEnvironments.getSecret(record.environmentId).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopConnectionCatalogStoreMigrationError({
|
||||
operation: "read-legacy-secret",
|
||||
catalogPath,
|
||||
environmentId: record.environmentId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const token = yield* savedEnvironments
|
||||
.getSecret(record.environmentId)
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
migrationError("read-legacy-secret", catalogPath, cause, record.environmentId),
|
||||
),
|
||||
);
|
||||
if (Option.isSome(token)) {
|
||||
credentials.push({
|
||||
connectionId: id,
|
||||
@@ -383,41 +362,13 @@ export const make = Effect.gen(function* () {
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
|
||||
const catalogPath = path.join(environment.stateDir, "connection-catalog.json");
|
||||
const encryptionAvailable = safeStorage.isEncryptionAvailable.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopConnectionCatalogStoreProtectionError({
|
||||
operation: "check-encryption-availability",
|
||||
catalogPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const writeCatalog = Effect.fn("desktop.connectionCatalogStore.writeCatalog")(function* (
|
||||
catalog: string,
|
||||
) {
|
||||
const encryptedCatalog = Encoding.encodeBase64(
|
||||
yield* safeStorage.encryptString(catalog).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopConnectionCatalogStoreProtectionError({
|
||||
operation: "encrypt-catalog",
|
||||
catalogPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
const encryptedCatalog = Encoding.encodeBase64(yield* safeStorage.encryptString(catalog));
|
||||
const suffix = (yield* crypto.randomUUIDv4.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopConnectionCatalogStoreWriteError({
|
||||
operation: "create-temporary-file-name",
|
||||
path: catalogPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.mapError((cause) => writeError("create-temporary-file-name", catalogPath, cause)),
|
||||
)).replace(/-/g, "");
|
||||
yield* writeDocument({
|
||||
fileSystem,
|
||||
@@ -429,42 +380,21 @@ export const make = Effect.gen(function* () {
|
||||
});
|
||||
|
||||
const migrateLegacyCatalog = Effect.gen(function* () {
|
||||
if (!(yield* encryptionAvailable)) {
|
||||
if (!(yield* safeStorage.isEncryptionAvailable)) {
|
||||
return Option.none<string>();
|
||||
}
|
||||
const records = yield* savedEnvironments.getRegistry.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopConnectionCatalogStoreMigrationError({
|
||||
operation: "read-legacy-registry",
|
||||
catalogPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.mapError((cause) => migrationError("read-legacy-registry", catalogPath, cause)),
|
||||
);
|
||||
if (records.length === 0) {
|
||||
return Option.none<string>();
|
||||
}
|
||||
const catalog = yield* migrateSavedEnvironmentRecords(records, savedEnvironments, catalogPath);
|
||||
const encoded = yield* encodeRuntimeConnectionCatalogDocumentJson(catalog).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopConnectionCatalogStoreMigrationError({
|
||||
operation: "encode-catalog",
|
||||
catalogPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.mapError((cause) => migrationError("encode-catalog", catalogPath, cause)),
|
||||
);
|
||||
yield* writeCatalog(encoded).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopConnectionCatalogStoreMigrationError({
|
||||
operation: "persist-catalog",
|
||||
catalogPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.mapError((cause) => migrationError("persist-catalog", catalogPath, cause)),
|
||||
);
|
||||
return Option.some(encoded);
|
||||
});
|
||||
@@ -475,27 +405,16 @@ export const make = Effect.gen(function* () {
|
||||
if (Option.isNone(document)) {
|
||||
return yield* migrateLegacyCatalog;
|
||||
}
|
||||
if (!(yield* encryptionAvailable)) {
|
||||
if (!(yield* safeStorage.isEncryptionAvailable)) {
|
||||
return Option.none<string>();
|
||||
}
|
||||
const decrypted = yield* decodeSecretBytes(catalogPath, document.value.encryptedCatalog).pipe(
|
||||
Effect.flatMap((encryptedCatalog) =>
|
||||
safeStorage.decryptString(encryptedCatalog).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopConnectionCatalogStoreProtectionError({
|
||||
operation: "decrypt-catalog",
|
||||
catalogPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
Effect.flatMap(safeStorage.decryptString),
|
||||
);
|
||||
return Option.some(decrypted);
|
||||
}).pipe(Effect.withSpan("desktop.connectionCatalogStore.get")),
|
||||
set: Effect.fn("desktop.connectionCatalogStore.set")(function* (catalog) {
|
||||
if (!(yield* encryptionAvailable)) {
|
||||
if (!(yield* safeStorage.isEncryptionAvailable)) {
|
||||
return false;
|
||||
}
|
||||
yield* writeCatalog(catalog);
|
||||
|
||||
@@ -3,15 +3,12 @@ import {
|
||||
type DesktopBackendBootstrap as DesktopBackendBootstrapValue,
|
||||
} from "@t3tools/contracts";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Queue from "effect/Queue";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
@@ -31,7 +28,6 @@ import * as DesktopWindow from "../window/DesktopWindow.ts";
|
||||
const decodeDesktopBackendBootstrap = Schema.decodeEffect(
|
||||
Schema.fromJsonString(DesktopBackendBootstrap),
|
||||
);
|
||||
const isBackendProcessError = Schema.is(DesktopBackendManager.BackendProcessError);
|
||||
|
||||
const baseConfig: DesktopBackendManager.DesktopBackendStartConfig = {
|
||||
executablePath: "/electron",
|
||||
@@ -59,9 +55,9 @@ const configWithObservability: DesktopBackendBootstrapValue = {
|
||||
};
|
||||
|
||||
function makeProcess(options?: {
|
||||
readonly stdout?: Stream.Stream<Uint8Array, PlatformError.PlatformError>;
|
||||
readonly stderr?: Stream.Stream<Uint8Array, PlatformError.PlatformError>;
|
||||
readonly exitCode?: Effect.Effect<ChildProcessSpawner.ExitCode, PlatformError.PlatformError>;
|
||||
readonly stdout?: Stream.Stream<Uint8Array>;
|
||||
readonly stderr?: Stream.Stream<Uint8Array>;
|
||||
readonly exitCode?: Effect.Effect<ChildProcessSpawner.ExitCode>;
|
||||
readonly kill?: ChildProcessSpawner.ChildProcessHandle["kill"];
|
||||
}): ChildProcessSpawner.ChildProcessHandle {
|
||||
return ChildProcessSpawner.makeHandle({
|
||||
@@ -149,23 +145,6 @@ function makeManagerLayer(input: {
|
||||
}
|
||||
|
||||
describe("DesktopBackendManager", () => {
|
||||
it("preserves the complete restart cause and schedule context", () => {
|
||||
const cause = Cause.combine(
|
||||
Cause.fail(new Error("start failed")),
|
||||
Cause.die(new Error("restart defect")),
|
||||
);
|
||||
const error = new DesktopBackendManager.DesktopBackendRestartError({
|
||||
reason: "backend exited with code 1",
|
||||
delayMs: 500,
|
||||
cause,
|
||||
});
|
||||
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.equal(error.reason, "backend exited with code 1");
|
||||
assert.equal(error.delayMs, 500);
|
||||
assert.equal(error.message, "Desktop backend restart failed after a scheduled 500ms delay.");
|
||||
});
|
||||
|
||||
it.effect("spawns the backend with fd3 bootstrap JSON and reports HTTP readiness", () =>
|
||||
Effect.gen(function* () {
|
||||
let spawnedCommand: ChildProcess.Command | undefined;
|
||||
@@ -239,243 +218,6 @@ describe("DesktopBackendManager", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves the readiness timeout cause and process context", () =>
|
||||
Effect.gen(function* () {
|
||||
const requested = yield* Deferred.make<HttpClientRequest.HttpClientRequest>();
|
||||
const layer = Layer.merge(
|
||||
TestClock.layer(),
|
||||
httpClientLayer((request) =>
|
||||
Deferred.succeed(requested, request).pipe(Effect.andThen(Effect.never)),
|
||||
),
|
||||
);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const readiness = yield* DesktopBackendManager.waitForHttpReady({
|
||||
executablePath: baseConfig.executablePath,
|
||||
entryPath: baseConfig.entryPath,
|
||||
cwd: baseConfig.cwd,
|
||||
httpBaseUrl: baseConfig.httpBaseUrl,
|
||||
timeout: Duration.millis(50),
|
||||
}).pipe(Effect.flip, Effect.forkChild);
|
||||
|
||||
const request = yield* Deferred.await(requested);
|
||||
assert.equal(request.url, "http://127.0.0.1:3773/.well-known/t3/environment");
|
||||
|
||||
yield* TestClock.adjust(Duration.millis(50));
|
||||
const error = yield* Fiber.join(readiness);
|
||||
|
||||
assert.instanceOf(error, DesktopBackendManager.BackendReadinessTimeoutError);
|
||||
assert.equal(error.executablePath, "/electron");
|
||||
assert.equal(error.entryPath, "/server/bin.mjs");
|
||||
assert.equal(error.cwd, "/server");
|
||||
assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/");
|
||||
assert.equal(error.readinessUrl.href, "http://127.0.0.1:3773/.well-known/t3/environment");
|
||||
assert.equal(error.timeoutMs, 50);
|
||||
assert.isTrue(Cause.isTimeoutError(error.cause));
|
||||
assert.equal(
|
||||
error.message,
|
||||
"Timed out after 50ms waiting for desktop backend readiness at http://127.0.0.1:3773/.well-known/t3/environment.",
|
||||
);
|
||||
}).pipe(Effect.provide(layer));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reports bootstrap encoding failures with stable process context", () =>
|
||||
Effect.gen(function* () {
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() => Effect.die("unexpected backend spawn")),
|
||||
);
|
||||
const error = yield* DesktopBackendManager.runBackendProcess({
|
||||
...baseConfig,
|
||||
bootstrap: {
|
||||
...baseConfig.bootstrap,
|
||||
port: 0,
|
||||
},
|
||||
}).pipe(
|
||||
Effect.flip,
|
||||
Effect.scoped,
|
||||
Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)),
|
||||
);
|
||||
|
||||
if (error._tag !== "BackendProcessBootstrapEncodeError") {
|
||||
return assert.fail(`Expected bootstrap encode error, received ${error._tag}`);
|
||||
}
|
||||
assert.equal(error.executablePath, "/electron");
|
||||
assert.equal(error.entryPath, "/server/bin.mjs");
|
||||
assert.equal(error.cwd, "/server");
|
||||
assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/");
|
||||
assert.isDefined(error.cause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
"Failed to encode the desktop backend bootstrap payload for /server/bin.mjs.",
|
||||
);
|
||||
assert.isTrue(isBackendProcessError(error));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves spawn failures without deriving their message from the cause", () =>
|
||||
Effect.gen(function* () {
|
||||
const spawnCause = PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "ChildProcessSpawner",
|
||||
method: "spawn",
|
||||
pathOrDescriptor: baseConfig.executablePath,
|
||||
description: "low-level detail that must not become the public message",
|
||||
});
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() => Effect.fail(spawnCause)),
|
||||
);
|
||||
const error = yield* DesktopBackendManager.runBackendProcess(baseConfig).pipe(
|
||||
Effect.flip,
|
||||
Effect.scoped,
|
||||
Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)),
|
||||
);
|
||||
|
||||
if (error._tag !== "BackendProcessSpawnError") {
|
||||
return assert.fail(`Expected backend spawn error, received ${error._tag}`);
|
||||
}
|
||||
assert.equal(error.executablePath, "/electron");
|
||||
assert.equal(error.entryPath, "/server/bin.mjs");
|
||||
assert.equal(error.cwd, "/server");
|
||||
assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/");
|
||||
assert.strictEqual(error.cause, spawnCause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
"Failed to spawn desktop backend entry /server/bin.mjs with /electron.",
|
||||
);
|
||||
assert.notInclude(error.message, spawnCause.message);
|
||||
assert.isTrue(isBackendProcessError(error));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves exit-status failures without copying their detail into the message", () =>
|
||||
Effect.gen(function* () {
|
||||
const exitCause = PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "ChildProcess",
|
||||
method: "exitCode",
|
||||
description: "exit-status-secret-sentinel",
|
||||
});
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() =>
|
||||
Effect.succeed(
|
||||
makeProcess({
|
||||
exitCode: Effect.fail(exitCause),
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
const error = yield* DesktopBackendManager.runBackendProcess(baseConfig).pipe(
|
||||
Effect.flip,
|
||||
Effect.scoped,
|
||||
Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)),
|
||||
);
|
||||
|
||||
if (error._tag !== "BackendProcessExitStatusError") {
|
||||
return assert.fail(`Expected backend exit-status error, received ${error._tag}`);
|
||||
}
|
||||
assert.equal(error.pid, 123);
|
||||
assert.equal(error.executablePath, "/electron");
|
||||
assert.equal(error.entryPath, "/server/bin.mjs");
|
||||
assert.equal(error.cwd, "/server");
|
||||
assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/");
|
||||
assert.strictEqual(error.cause, exitCause);
|
||||
assert.equal(error.message, "Failed to read the exit status of desktop backend process 123.");
|
||||
assert.notInclude(error.message, "exit-status-secret-sentinel");
|
||||
assert.isTrue(isBackendProcessError(error));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reports output stream failures with process and stream context", () =>
|
||||
Effect.gen(function* () {
|
||||
const outputCause = PlatformError.systemError({
|
||||
_tag: "BadResource",
|
||||
module: "ChildProcess",
|
||||
method: "stdout",
|
||||
description: "output-stream-secret-sentinel",
|
||||
});
|
||||
const reported = yield* Deferred.make<DesktopBackendManager.BackendProcessOutputError>();
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() =>
|
||||
Effect.succeed(
|
||||
makeProcess({
|
||||
stdout: Stream.fail(outputCause),
|
||||
exitCode: Deferred.await(reported).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const exit = yield* DesktopBackendManager.runBackendProcess({
|
||||
...baseConfig,
|
||||
onOutputFailure: (error) => Deferred.succeed(reported, error).pipe(Effect.asVoid),
|
||||
}).pipe(Effect.scoped, Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)));
|
||||
const error = yield* Deferred.await(reported);
|
||||
|
||||
assert.equal(exit.code.pipe(Option.getOrUndefined), 0);
|
||||
if (error._tag !== "BackendProcessOutputReadError") {
|
||||
return assert.fail(`Expected output read error, received ${error._tag}`);
|
||||
}
|
||||
assert.equal(error.executablePath, "/electron");
|
||||
assert.equal(error.entryPath, "/server/bin.mjs");
|
||||
assert.equal(error.cwd, "/server");
|
||||
assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/");
|
||||
assert.equal(error.pid, 123);
|
||||
assert.equal(error.streamName, "stdout");
|
||||
assert.strictEqual(error.cause, outputCause);
|
||||
assert.equal(error.message, "Failed to read stdout from desktop backend process 123.");
|
||||
assert.notInclude(error.message, "output-stream-secret-sentinel");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reports output handler failures separately from stream read failures", () =>
|
||||
Effect.gen(function* () {
|
||||
const chunk = new TextEncoder().encode("backend output");
|
||||
const outputCause = new Error("output-handler-secret-sentinel");
|
||||
const reported = yield* Deferred.make<DesktopBackendManager.BackendProcessOutputError>();
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() =>
|
||||
Effect.succeed(
|
||||
makeProcess({
|
||||
stdout: Stream.make(chunk),
|
||||
exitCode: Deferred.await(reported).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const exit = yield* DesktopBackendManager.runBackendProcess({
|
||||
...baseConfig,
|
||||
onOutput: () => Effect.fail(outputCause),
|
||||
onOutputFailure: (error) => Deferred.succeed(reported, error).pipe(Effect.asVoid),
|
||||
}).pipe(Effect.scoped, Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)));
|
||||
const error = yield* Deferred.await(reported);
|
||||
|
||||
assert.equal(exit.code.pipe(Option.getOrUndefined), 0);
|
||||
if (error._tag !== "BackendProcessOutputHandlingError") {
|
||||
return assert.fail(`Expected output handling error, received ${error._tag}`);
|
||||
}
|
||||
assert.equal(error.executablePath, "/electron");
|
||||
assert.equal(error.entryPath, "/server/bin.mjs");
|
||||
assert.equal(error.cwd, "/server");
|
||||
assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/");
|
||||
assert.equal(error.pid, 123);
|
||||
assert.equal(error.streamName, "stdout");
|
||||
assert.equal(error.chunkByteLength, chunk.byteLength);
|
||||
assert.strictEqual(error.cause, outputCause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Failed to handle ${chunk.byteLength} bytes from stdout of desktop backend process 123.`,
|
||||
);
|
||||
assert.notInclude(error.message, "output-handler-secret-sentinel");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("retries HTTP readiness before reporting the backend ready", () =>
|
||||
Effect.gen(function* () {
|
||||
const requestUrls: Array<string> = [];
|
||||
|
||||
@@ -9,6 +9,7 @@ import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Result from "effect/Result";
|
||||
import * as Schedule from "effect/Schedule";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
@@ -42,145 +43,68 @@ type BackendProcessRunRequirements = BackendProcessLayerServices | Scope.Scope;
|
||||
|
||||
export type BackendProcessOutputStream = "stdout" | "stderr";
|
||||
|
||||
export interface BackendProcessContext {
|
||||
export interface DesktopBackendStartConfig {
|
||||
readonly executablePath: string;
|
||||
readonly entryPath: string;
|
||||
readonly cwd: string;
|
||||
readonly httpBaseUrl: URL;
|
||||
}
|
||||
|
||||
export interface DesktopBackendStartConfig extends BackendProcessContext {
|
||||
readonly env: Record<string, string | undefined>;
|
||||
readonly bootstrap: DesktopBackendBootstrapValue;
|
||||
readonly httpBaseUrl: URL;
|
||||
readonly captureOutput: boolean;
|
||||
}
|
||||
|
||||
interface BackendProcessExit {
|
||||
readonly code: Option.Option<number>;
|
||||
readonly reason: string;
|
||||
readonly result: Result.Result<ChildProcessSpawner.ExitCode, PlatformError.PlatformError>;
|
||||
}
|
||||
|
||||
const backendProcessContextSchema = {
|
||||
executablePath: Schema.String,
|
||||
entryPath: Schema.String,
|
||||
cwd: Schema.String,
|
||||
httpBaseUrl: Schema.URL,
|
||||
};
|
||||
|
||||
export class BackendReadinessTimeoutError extends Schema.TaggedErrorClass<BackendReadinessTimeoutError>()(
|
||||
"BackendReadinessTimeoutError",
|
||||
export class BackendTimeoutError extends Schema.TaggedErrorClass<BackendTimeoutError>()(
|
||||
"BackendTimeoutError",
|
||||
{
|
||||
...backendProcessContextSchema,
|
||||
readinessUrl: Schema.URL,
|
||||
timeoutMs: Schema.Number,
|
||||
cause: Schema.Defect(),
|
||||
url: Schema.URL,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Timed out after ${this.timeoutMs}ms waiting for desktop backend readiness at ${this.readinessUrl.href}.`;
|
||||
return `Timed out waiting for backend readiness at ${this.url.href}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class BackendProcessBootstrapEncodeError extends Schema.TaggedErrorClass<BackendProcessBootstrapEncodeError>()(
|
||||
class BackendProcessBootstrapEncodeError extends Schema.TaggedErrorClass<BackendProcessBootstrapEncodeError>()(
|
||||
"BackendProcessBootstrapEncodeError",
|
||||
{
|
||||
...backendProcessContextSchema,
|
||||
detail: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to encode the desktop backend bootstrap payload for ${this.entryPath}.`;
|
||||
return `Failed to encode desktop backend bootstrap payload: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class BackendProcessSpawnError extends Schema.TaggedErrorClass<BackendProcessSpawnError>()(
|
||||
class BackendProcessSpawnError extends Schema.TaggedErrorClass<BackendProcessSpawnError>()(
|
||||
"BackendProcessSpawnError",
|
||||
{
|
||||
...backendProcessContextSchema,
|
||||
detail: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to spawn desktop backend entry ${this.entryPath} with ${this.executablePath}.`;
|
||||
return `Failed to spawn desktop backend process: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class BackendProcessOutputReadError extends Schema.TaggedErrorClass<BackendProcessOutputReadError>()(
|
||||
"BackendProcessOutputReadError",
|
||||
{
|
||||
...backendProcessContextSchema,
|
||||
pid: Schema.Number,
|
||||
streamName: Schema.Literals(["stdout", "stderr"]),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to read ${this.streamName} from desktop backend process ${this.pid}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class BackendProcessOutputHandlingError extends Schema.TaggedErrorClass<BackendProcessOutputHandlingError>()(
|
||||
"BackendProcessOutputHandlingError",
|
||||
{
|
||||
...backendProcessContextSchema,
|
||||
pid: Schema.Number,
|
||||
streamName: Schema.Literals(["stdout", "stderr"]),
|
||||
chunkByteLength: Schema.Number,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to handle ${this.chunkByteLength} bytes from ${this.streamName} of desktop backend process ${this.pid}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export type BackendProcessOutputError =
|
||||
| BackendProcessOutputReadError
|
||||
| BackendProcessOutputHandlingError;
|
||||
|
||||
export class BackendProcessExitStatusError extends Schema.TaggedErrorClass<BackendProcessExitStatusError>()(
|
||||
"BackendProcessExitStatusError",
|
||||
{
|
||||
...backendProcessContextSchema,
|
||||
pid: Schema.Number,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to read the exit status of desktop backend process ${this.pid}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopBackendRestartError extends Schema.TaggedErrorClass<DesktopBackendRestartError>()(
|
||||
"DesktopBackendRestartError",
|
||||
{
|
||||
reason: Schema.String,
|
||||
delayMs: Schema.Number,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Desktop backend restart failed after a scheduled ${this.delayMs}ms delay.`;
|
||||
}
|
||||
}
|
||||
|
||||
export const BackendProcessError = Schema.Union([
|
||||
BackendProcessBootstrapEncodeError,
|
||||
BackendProcessSpawnError,
|
||||
BackendProcessExitStatusError,
|
||||
]);
|
||||
export type BackendProcessError = typeof BackendProcessError.Type;
|
||||
type BackendProcessError = BackendProcessBootstrapEncodeError | BackendProcessSpawnError;
|
||||
|
||||
interface RunBackendProcessOptions extends DesktopBackendStartConfig {
|
||||
readonly readinessTimeout?: Duration.Duration;
|
||||
readonly onStarted?: (pid: number) => Effect.Effect<void>;
|
||||
readonly onReady?: () => Effect.Effect<void>;
|
||||
readonly onReadinessFailure?: (error: BackendReadinessTimeoutError) => Effect.Effect<void>;
|
||||
readonly onReadinessFailure?: (error: BackendTimeoutError) => Effect.Effect<void>;
|
||||
readonly onOutput?: (
|
||||
streamName: BackendProcessOutputStream,
|
||||
chunk: Uint8Array,
|
||||
) => Effect.Effect<void, Error>;
|
||||
readonly onOutputFailure?: (error: BackendProcessOutputError) => Effect.Effect<void>;
|
||||
) => Effect.Effect<void>;
|
||||
}
|
||||
|
||||
export interface DesktopBackendSnapshot {
|
||||
@@ -259,10 +183,11 @@ const closeRun = (
|
||||
).pipe(Effect.ignore);
|
||||
};
|
||||
|
||||
export const waitForHttpReady = Effect.fn("desktop.backendManager.waitForHttpReady")(function* (
|
||||
options: BackendProcessContext & { readonly timeout: Duration.Duration },
|
||||
): Effect.fn.Return<void, BackendReadinessTimeoutError, HttpClient.HttpClient> {
|
||||
const readinessUrl = new URL(BACKEND_READINESS_PATH, options.httpBaseUrl);
|
||||
const waitForHttpReady = Effect.fn("desktop.backendManager.waitForHttpReady")(function* (
|
||||
baseUrl: URL,
|
||||
timeout: Duration.Duration,
|
||||
): Effect.fn.Return<void, BackendTimeoutError, HttpClient.HttpClient> {
|
||||
const readinessUrl = new URL(BACKEND_READINESS_PATH, baseUrl);
|
||||
const client = (yield* HttpClient.HttpClient).pipe(
|
||||
HttpClient.filterStatusOk,
|
||||
HttpClient.transformResponse(Effect.timeout(DEFAULT_BACKEND_READINESS_REQUEST_TIMEOUT)),
|
||||
@@ -271,64 +196,43 @@ export const waitForHttpReady = Effect.fn("desktop.backendManager.waitForHttpRea
|
||||
|
||||
yield* client.get(readinessUrl).pipe(
|
||||
Effect.asVoid,
|
||||
Effect.timeout(options.timeout),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new BackendReadinessTimeoutError({
|
||||
executablePath: options.executablePath,
|
||||
entryPath: options.entryPath,
|
||||
cwd: options.cwd,
|
||||
httpBaseUrl: options.httpBaseUrl,
|
||||
readinessUrl,
|
||||
timeoutMs: Duration.toMillis(options.timeout),
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.timeout(timeout),
|
||||
Effect.mapError(() => new BackendTimeoutError({ url: readinessUrl })),
|
||||
);
|
||||
});
|
||||
|
||||
function describeProcessExit(
|
||||
result: Result.Result<ChildProcessSpawner.ExitCode, PlatformError.PlatformError>,
|
||||
): BackendProcessExit {
|
||||
if (Result.isSuccess(result)) {
|
||||
return {
|
||||
code: Option.some(result.success),
|
||||
reason: `code=${result.success}`,
|
||||
result,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
code: Option.none(),
|
||||
reason: result.failure.message,
|
||||
result,
|
||||
};
|
||||
}
|
||||
|
||||
function drainBackendOutput(
|
||||
context: BackendProcessContext & { readonly pid: number },
|
||||
streamName: BackendProcessOutputStream,
|
||||
stream: Stream.Stream<Uint8Array, PlatformError.PlatformError>,
|
||||
onOutput: (
|
||||
streamName: BackendProcessOutputStream,
|
||||
chunk: Uint8Array,
|
||||
) => Effect.Effect<void, Error>,
|
||||
onOutputFailure: (error: BackendProcessOutputError) => Effect.Effect<void>,
|
||||
onOutput: (streamName: BackendProcessOutputStream, chunk: Uint8Array) => Effect.Effect<void>,
|
||||
): Effect.Effect<void> {
|
||||
return stream.pipe(
|
||||
Stream.mapError(
|
||||
(cause) =>
|
||||
new BackendProcessOutputReadError({
|
||||
...context,
|
||||
streamName,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Stream.runForEach((chunk) =>
|
||||
onOutput(streamName, chunk).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new BackendProcessOutputHandlingError({
|
||||
...context,
|
||||
streamName,
|
||||
chunkByteLength: chunk.byteLength,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
Effect.catchTags({
|
||||
BackendProcessOutputReadError: onOutputFailure,
|
||||
BackendProcessOutputHandlingError: onOutputFailure,
|
||||
}),
|
||||
Stream.runForEach((chunk) => onOutput(streamName, chunk)),
|
||||
Effect.ignore,
|
||||
);
|
||||
}
|
||||
|
||||
const encodeBootstrapJson = Schema.encodeEffect(Schema.fromJsonString(DesktopBackendBootstrap));
|
||||
|
||||
export const runBackendProcess = Effect.fn("runBackendProcess")(function* (
|
||||
const runBackendProcess = Effect.fn("runBackendProcess")(function* (
|
||||
options: RunBackendProcessOptions,
|
||||
): Effect.fn.Return<BackendProcessExit, BackendProcessError, BackendProcessRunRequirements> {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
@@ -336,10 +240,7 @@ export const runBackendProcess = Effect.fn("runBackendProcess")(function* (
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new BackendProcessBootstrapEncodeError({
|
||||
executablePath: options.executablePath,
|
||||
entryPath: options.entryPath,
|
||||
cwd: options.cwd,
|
||||
httpBaseUrl: options.httpBaseUrl,
|
||||
detail: cause.message,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
@@ -372,10 +273,7 @@ export const runBackendProcess = Effect.fn("runBackendProcess")(function* (
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new BackendProcessSpawnError({
|
||||
executablePath: options.executablePath,
|
||||
entryPath: options.entryPath,
|
||||
cwd: options.cwd,
|
||||
httpBaseUrl: options.httpBaseUrl,
|
||||
detail: cause.message,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
@@ -383,60 +281,19 @@ export const runBackendProcess = Effect.fn("runBackendProcess")(function* (
|
||||
|
||||
yield* options.onStarted?.(handle.pid) ?? Effect.void;
|
||||
if (options.captureOutput) {
|
||||
const outputContext = {
|
||||
executablePath: options.executablePath,
|
||||
entryPath: options.entryPath,
|
||||
cwd: options.cwd,
|
||||
httpBaseUrl: options.httpBaseUrl,
|
||||
pid: Number(handle.pid),
|
||||
};
|
||||
const onOutputFailure = options.onOutputFailure ?? (() => Effect.void);
|
||||
yield* drainBackendOutput(
|
||||
outputContext,
|
||||
"stdout",
|
||||
handle.stdout,
|
||||
onOutput,
|
||||
onOutputFailure,
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* drainBackendOutput(
|
||||
outputContext,
|
||||
"stderr",
|
||||
handle.stderr,
|
||||
onOutput,
|
||||
onOutputFailure,
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* drainBackendOutput("stdout", handle.stdout, onOutput).pipe(Effect.forkScoped);
|
||||
yield* drainBackendOutput("stderr", handle.stderr, onOutput).pipe(Effect.forkScoped);
|
||||
}
|
||||
yield* waitForHttpReady({
|
||||
executablePath: options.executablePath,
|
||||
entryPath: options.entryPath,
|
||||
cwd: options.cwd,
|
||||
httpBaseUrl: options.httpBaseUrl,
|
||||
timeout: options.readinessTimeout ?? DEFAULT_BACKEND_READINESS_TIMEOUT,
|
||||
}).pipe(
|
||||
yield* waitForHttpReady(
|
||||
options.httpBaseUrl,
|
||||
options.readinessTimeout ?? DEFAULT_BACKEND_READINESS_TIMEOUT,
|
||||
).pipe(
|
||||
Effect.tap(() => options.onReady?.() ?? Effect.void),
|
||||
Effect.catchTags({
|
||||
BackendReadinessTimeoutError: (error) => options.onReadinessFailure?.(error) ?? Effect.void,
|
||||
}),
|
||||
Effect.catch((error) => options.onReadinessFailure?.(error) ?? Effect.void),
|
||||
Effect.forkScoped,
|
||||
);
|
||||
|
||||
const exitCode = yield* handle.exitCode.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new BackendProcessExitStatusError({
|
||||
executablePath: options.executablePath,
|
||||
entryPath: options.entryPath,
|
||||
cwd: options.cwd,
|
||||
httpBaseUrl: options.httpBaseUrl,
|
||||
pid: Number(handle.pid),
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
return {
|
||||
code: Option.some(exitCode),
|
||||
reason: `code=${exitCode}`,
|
||||
} satisfies BackendProcessExit;
|
||||
return describeProcessExit(yield* Effect.result(handle.exitCode));
|
||||
});
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
@@ -494,7 +351,7 @@ export const make = Effect.gen(function* () {
|
||||
const config = yield* configuration.resolve.pipe(
|
||||
Effect.tapError((error) =>
|
||||
logBackendManagerError("failed to generate desktop backend configuration", {
|
||||
cause: error,
|
||||
cause: error.message,
|
||||
}),
|
||||
),
|
||||
Effect.option,
|
||||
@@ -632,26 +489,22 @@ export const make = Effect.gen(function* () {
|
||||
yield* desktopWindow.handleBackendReady.pipe(
|
||||
Effect.catch((error) =>
|
||||
logBackendManagerError("failed to open main window after backend readiness", {
|
||||
cause: error,
|
||||
message: error.message,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}),
|
||||
onReadinessFailure: (error) =>
|
||||
logBackendManagerWarning("backend readiness check failed during bootstrap", {
|
||||
error,
|
||||
error: error.message,
|
||||
}),
|
||||
onOutput: (streamName, chunk) => backendOutputLog.writeOutputChunk(streamName, chunk),
|
||||
onOutputFailure: (error) => logBackendManagerError(error.message, { error }),
|
||||
}).pipe(
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||
Effect.provideService(HttpClient.HttpClient, httpClient),
|
||||
Scope.provide(runScope),
|
||||
Effect.matchEffect({
|
||||
onFailure: (error) =>
|
||||
logBackendManagerError(error.message, { error }).pipe(
|
||||
Effect.andThen(finalizeRun(error.message)),
|
||||
),
|
||||
onFailure: (error) => finalizeRun(error.message),
|
||||
onSuccess: (exit) => finalizeRun(exit.reason),
|
||||
}),
|
||||
Effect.ensuring(Scope.close(runScope, Exit.void).pipe(Effect.ignore)),
|
||||
@@ -706,17 +559,11 @@ export const make = Effect.gen(function* () {
|
||||
}),
|
||||
),
|
||||
Effect.flatMap((shouldRestart) => (shouldRestart ? start : Effect.void)),
|
||||
Effect.catchCause((cause) => {
|
||||
if (Cause.hasInterruptsOnly(cause)) {
|
||||
return Effect.void;
|
||||
}
|
||||
const error = new DesktopBackendRestartError({
|
||||
reason,
|
||||
delayMs: Duration.toMillis(delay),
|
||||
cause,
|
||||
});
|
||||
return logBackendManagerError(error.message, { error });
|
||||
}),
|
||||
Effect.catchCause((cause) =>
|
||||
logBackendManagerError("desktop backend restart fiber failed", {
|
||||
cause: Cause.pretty(cause),
|
||||
}),
|
||||
),
|
||||
),
|
||||
parentScope,
|
||||
);
|
||||
|
||||
@@ -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);
|
||||
|
||||
|
||||
@@ -1,39 +1,26 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import type * as Electron from "electron";
|
||||
import { beforeEach, vi } from "vite-plus/test";
|
||||
|
||||
const { appFocusMock, browserWindowMock, getAllWindowsMock, getFocusedWindowMock } = vi.hoisted(
|
||||
() => ({
|
||||
appFocusMock: vi.fn(),
|
||||
browserWindowMock: vi.fn(function BrowserWindowMock() {}),
|
||||
getAllWindowsMock: vi.fn(),
|
||||
getFocusedWindowMock: vi.fn(),
|
||||
}),
|
||||
);
|
||||
const { appFocusMock, getAllWindowsMock } = vi.hoisted(() => ({
|
||||
appFocusMock: vi.fn(),
|
||||
getAllWindowsMock: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("electron", () => ({
|
||||
app: {
|
||||
focus: appFocusMock,
|
||||
},
|
||||
BrowserWindow: Object.assign(browserWindowMock, {
|
||||
BrowserWindow: {
|
||||
getAllWindows: getAllWindowsMock,
|
||||
getFocusedWindow: getFocusedWindowMock,
|
||||
}),
|
||||
},
|
||||
}));
|
||||
|
||||
import * as ElectronWindow from "./ElectronWindow.ts";
|
||||
|
||||
const TestLayer = ElectronWindow.layer.pipe(
|
||||
Layer.provide(Layer.succeed(HostProcessPlatform, "linux")),
|
||||
);
|
||||
|
||||
function makeBrowserWindow(input: { readonly id: number; readonly destroyed: boolean }) {
|
||||
function makeBrowserWindow(input: { readonly destroyed: boolean }) {
|
||||
return {
|
||||
id: input.id,
|
||||
isDestroyed: vi.fn(() => input.destroyed),
|
||||
} as unknown as Electron.BrowserWindow;
|
||||
}
|
||||
@@ -41,78 +28,13 @@ function makeBrowserWindow(input: { readonly id: number; readonly destroyed: boo
|
||||
describe("ElectronWindow", () => {
|
||||
beforeEach(() => {
|
||||
appFocusMock.mockReset();
|
||||
browserWindowMock.mockReset();
|
||||
getAllWindowsMock.mockReset();
|
||||
getFocusedWindowMock.mockReset();
|
||||
});
|
||||
|
||||
it.effect("preserves schema-safe creation context and the Electron cause", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("native BrowserWindow construction failed");
|
||||
browserWindowMock.mockImplementationOnce(function BrowserWindowFailure() {
|
||||
throw cause;
|
||||
});
|
||||
const options = {
|
||||
title: "T3 Code",
|
||||
width: 1100,
|
||||
height: 780,
|
||||
minWidth: 840,
|
||||
minHeight: 620,
|
||||
show: false,
|
||||
modal: false,
|
||||
frame: true,
|
||||
transparent: false,
|
||||
backgroundColor: "#101010",
|
||||
icon: {} as Electron.NativeImage,
|
||||
webPreferences: {
|
||||
preload: "/tmp/preload.js",
|
||||
partition: "persist:t3code-preview-test",
|
||||
sandbox: true,
|
||||
contextIsolation: true,
|
||||
nodeIntegration: false,
|
||||
webviewTag: true,
|
||||
spellcheck: true,
|
||||
},
|
||||
} satisfies Electron.BrowserWindowConstructorOptions;
|
||||
const electronWindow = yield* ElectronWindow.ElectronWindow;
|
||||
|
||||
const error = yield* electronWindow.create(options).pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, ElectronWindow.ElectronWindowCreateError);
|
||||
assert.isTrue(ElectronWindow.isElectronWindowCreateError(error));
|
||||
assert.deepEqual(error.options, {
|
||||
title: "T3 Code",
|
||||
width: 1100,
|
||||
height: 780,
|
||||
minWidth: 840,
|
||||
minHeight: 620,
|
||||
show: false,
|
||||
modal: false,
|
||||
frame: true,
|
||||
transparent: false,
|
||||
backgroundColor: "#101010",
|
||||
webPreferences: {
|
||||
preload: "/tmp/preload.js",
|
||||
partition: "persist:t3code-preview-test",
|
||||
sandbox: true,
|
||||
contextIsolation: true,
|
||||
nodeIntegration: false,
|
||||
webviewTag: true,
|
||||
},
|
||||
});
|
||||
assert.isFalse("icon" in error.options);
|
||||
assert.isFalse("spellcheck" in error.options.webPreferences);
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.equal(error.message, 'Failed to create Electron BrowserWindow "T3 Code" (1100x780).');
|
||||
assert.notInclude(error.message, cause.message);
|
||||
assert.deepEqual(browserWindowMock.mock.calls, [[options]]);
|
||||
}).pipe(Effect.provide(TestLayer)),
|
||||
);
|
||||
|
||||
it.effect("skips windows destroyed before appearance sync runs", () =>
|
||||
Effect.gen(function* () {
|
||||
const liveWindow = makeBrowserWindow({ id: 1, destroyed: false });
|
||||
const destroyedWindow = makeBrowserWindow({ id: 2, destroyed: true });
|
||||
const liveWindow = makeBrowserWindow({ destroyed: false });
|
||||
const destroyedWindow = makeBrowserWindow({ destroyed: true });
|
||||
getAllWindowsMock.mockReturnValue([destroyedWindow, liveWindow]);
|
||||
|
||||
const syncedWindows: Electron.BrowserWindow[] = [];
|
||||
@@ -124,112 +46,6 @@ describe("ElectronWindow", () => {
|
||||
);
|
||||
|
||||
assert.deepEqual(syncedWindows, [liveWindow]);
|
||||
}).pipe(Effect.provide(TestLayer)),
|
||||
);
|
||||
|
||||
it.effect("preserves window enumeration failures as structured defects", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("window enumeration failed");
|
||||
getAllWindowsMock.mockImplementationOnce(() => {
|
||||
throw cause;
|
||||
});
|
||||
|
||||
const electronWindow = yield* ElectronWindow.ElectronWindow;
|
||||
const exit = yield* Effect.exit(electronWindow.currentMainOrFirst);
|
||||
|
||||
assert.equal(exit._tag, "Failure");
|
||||
if (exit._tag === "Failure") {
|
||||
const error = Cause.squash(exit.cause);
|
||||
assert.instanceOf(error, ElectronWindow.ElectronWindowOperationError);
|
||||
assert.equal(error.operation, "list-windows");
|
||||
assert.equal(error.platform, "linux");
|
||||
assert.isNull(error.windowId);
|
||||
assert.isNull(error.channel);
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.notInclude(error.message, cause.message);
|
||||
}
|
||||
}).pipe(Effect.provide(TestLayer)),
|
||||
);
|
||||
|
||||
it.effect("preserves reveal failures with the target window", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("window restore failed");
|
||||
const window = {
|
||||
id: 41,
|
||||
isDestroyed: vi.fn(() => false),
|
||||
isMinimized: vi.fn(() => true),
|
||||
restore: vi.fn(() => {
|
||||
throw cause;
|
||||
}),
|
||||
} as unknown as Electron.BrowserWindow;
|
||||
|
||||
const electronWindow = yield* ElectronWindow.ElectronWindow;
|
||||
const exit = yield* Effect.exit(electronWindow.reveal(window));
|
||||
|
||||
assert.equal(exit._tag, "Failure");
|
||||
if (exit._tag === "Failure") {
|
||||
const error = Cause.squash(exit.cause);
|
||||
assert.instanceOf(error, ElectronWindow.ElectronWindowOperationError);
|
||||
assert.equal(error.operation, "reveal-window");
|
||||
assert.equal(error.windowId, 41);
|
||||
assert.isNull(error.channel);
|
||||
assert.strictEqual(error.cause, cause);
|
||||
}
|
||||
}).pipe(Effect.provide(TestLayer)),
|
||||
);
|
||||
|
||||
it.effect("preserves message delivery failures with window and channel context", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("renderer send failed");
|
||||
const window = {
|
||||
id: 42,
|
||||
isDestroyed: vi.fn(() => false),
|
||||
webContents: {
|
||||
send: vi.fn(() => {
|
||||
throw cause;
|
||||
}),
|
||||
},
|
||||
} as unknown as Electron.BrowserWindow;
|
||||
getAllWindowsMock.mockReturnValueOnce([window]);
|
||||
|
||||
const electronWindow = yield* ElectronWindow.ElectronWindow;
|
||||
const exit = yield* Effect.exit(electronWindow.sendAll("desktop:update", { ready: true }));
|
||||
|
||||
assert.equal(exit._tag, "Failure");
|
||||
if (exit._tag === "Failure") {
|
||||
const error = Cause.squash(exit.cause);
|
||||
assert.instanceOf(error, ElectronWindow.ElectronWindowOperationError);
|
||||
assert.equal(error.operation, "send-window-message");
|
||||
assert.equal(error.windowId, 42);
|
||||
assert.equal(error.channel, "desktop:update");
|
||||
assert.strictEqual(error.cause, cause);
|
||||
}
|
||||
}).pipe(Effect.provide(TestLayer)),
|
||||
);
|
||||
|
||||
it.effect("preserves destroy failures with the target window", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("window destroy failed");
|
||||
const window = {
|
||||
id: 43,
|
||||
destroy: vi.fn(() => {
|
||||
throw cause;
|
||||
}),
|
||||
} as unknown as Electron.BrowserWindow;
|
||||
getAllWindowsMock.mockReturnValueOnce([window]);
|
||||
|
||||
const electronWindow = yield* ElectronWindow.ElectronWindow;
|
||||
const exit = yield* Effect.exit(electronWindow.destroyAll);
|
||||
|
||||
assert.equal(exit._tag, "Failure");
|
||||
if (exit._tag === "Failure") {
|
||||
const error = Cause.squash(exit.cause);
|
||||
assert.instanceOf(error, ElectronWindow.ElectronWindowOperationError);
|
||||
assert.equal(error.operation, "destroy-window");
|
||||
assert.equal(error.windowId, 43);
|
||||
assert.isNull(error.channel);
|
||||
assert.strictEqual(error.cause, cause);
|
||||
}
|
||||
}).pipe(Effect.provide(TestLayer)),
|
||||
}).pipe(Effect.provide(ElectronWindow.layer)),
|
||||
);
|
||||
});
|
||||
@@ -8,69 +8,14 @@ import * as Schema from "effect/Schema";
|
||||
|
||||
import * as Electron from "electron";
|
||||
|
||||
const ElectronWindowCreateOptions = Schema.Struct({
|
||||
title: Schema.NullOr(Schema.String),
|
||||
width: Schema.NullOr(Schema.Number),
|
||||
height: Schema.NullOr(Schema.Number),
|
||||
minWidth: Schema.NullOr(Schema.Number),
|
||||
minHeight: Schema.NullOr(Schema.Number),
|
||||
show: Schema.NullOr(Schema.Boolean),
|
||||
modal: Schema.NullOr(Schema.Boolean),
|
||||
frame: Schema.NullOr(Schema.Boolean),
|
||||
transparent: Schema.NullOr(Schema.Boolean),
|
||||
backgroundColor: Schema.NullOr(Schema.String),
|
||||
webPreferences: Schema.Struct({
|
||||
preload: Schema.NullOr(Schema.String),
|
||||
partition: Schema.NullOr(Schema.String),
|
||||
sandbox: Schema.NullOr(Schema.Boolean),
|
||||
contextIsolation: Schema.NullOr(Schema.Boolean),
|
||||
nodeIntegration: Schema.NullOr(Schema.Boolean),
|
||||
webviewTag: Schema.NullOr(Schema.Boolean),
|
||||
}),
|
||||
});
|
||||
|
||||
const ElectronWindowOperation = Schema.Literals([
|
||||
"list-windows",
|
||||
"get-focused-window",
|
||||
"inspect-window",
|
||||
"reveal-window",
|
||||
"send-window-message",
|
||||
"destroy-window",
|
||||
]);
|
||||
|
||||
export class ElectronWindowCreateError extends Schema.TaggedErrorClass<ElectronWindowCreateError>()(
|
||||
"ElectronWindowCreateError",
|
||||
{
|
||||
options: ElectronWindowCreateOptions,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
const title = this.options.title === null ? "" : ` "${this.options.title}"`;
|
||||
const dimensions =
|
||||
this.options.width === null || this.options.height === null
|
||||
? ""
|
||||
: ` (${this.options.width}x${this.options.height})`;
|
||||
return `Failed to create Electron BrowserWindow${title}${dimensions}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export const isElectronWindowCreateError = Schema.is(ElectronWindowCreateError);
|
||||
|
||||
export class ElectronWindowOperationError extends Schema.TaggedErrorClass<ElectronWindowOperationError>()(
|
||||
"ElectronWindowOperationError",
|
||||
{
|
||||
operation: ElectronWindowOperation,
|
||||
platform: Schema.String,
|
||||
windowId: Schema.NullOr(Schema.Number),
|
||||
channel: Schema.NullOr(Schema.String),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
const window = this.windowId === null ? "" : ` for window ${this.windowId}`;
|
||||
const channel = this.channel === null ? "" : ` on channel ${JSON.stringify(this.channel)}`;
|
||||
return `Electron window operation ${JSON.stringify(this.operation)} failed${window}${channel} on ${this.platform}.`;
|
||||
return "Failed to create Electron BrowserWindow.";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -98,38 +43,9 @@ export const make = Effect.gen(function* () {
|
||||
const platform = yield* HostProcessPlatform;
|
||||
const mainWindowRef = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
|
||||
|
||||
const listWindows = Effect.try({
|
||||
try: () => Electron.BrowserWindow.getAllWindows(),
|
||||
catch: (cause) =>
|
||||
new ElectronWindowOperationError({
|
||||
operation: "list-windows",
|
||||
platform,
|
||||
windowId: null,
|
||||
channel: null,
|
||||
cause,
|
||||
}),
|
||||
}).pipe(Effect.orDie);
|
||||
|
||||
const isWindowDestroyed = (window: Electron.BrowserWindow) =>
|
||||
Effect.try({
|
||||
try: () => window.isDestroyed(),
|
||||
catch: (cause) =>
|
||||
new ElectronWindowOperationError({
|
||||
operation: "inspect-window",
|
||||
platform,
|
||||
windowId: window.id,
|
||||
channel: null,
|
||||
cause,
|
||||
}),
|
||||
}).pipe(Effect.orDie);
|
||||
|
||||
const liveMain = Effect.gen(function* () {
|
||||
const main = yield* Ref.get(mainWindowRef);
|
||||
if (Option.isNone(main) || (yield* isWindowDestroyed(main.value))) {
|
||||
return Option.none<Electron.BrowserWindow>();
|
||||
}
|
||||
return main;
|
||||
});
|
||||
const liveMain = Ref.get(mainWindowRef).pipe(
|
||||
Effect.map(Option.filter((value) => !value.isDestroyed())),
|
||||
);
|
||||
|
||||
const currentMainOrFirst = Effect.gen(function* () {
|
||||
const main = yield* liveMain;
|
||||
@@ -137,60 +53,27 @@ export const make = Effect.gen(function* () {
|
||||
return main;
|
||||
}
|
||||
|
||||
const first = Option.fromNullishOr((yield* listWindows)[0] ?? null);
|
||||
if (Option.isNone(first) || (yield* isWindowDestroyed(first.value))) {
|
||||
return Option.none<Electron.BrowserWindow>();
|
||||
}
|
||||
return first;
|
||||
return Option.fromNullishOr(Electron.BrowserWindow.getAllWindows()[0] ?? null).pipe(
|
||||
Option.filter((window) => !window.isDestroyed()),
|
||||
);
|
||||
});
|
||||
|
||||
const focusedMainOrFirst = Effect.gen(function* () {
|
||||
const focused = yield* Effect.try({
|
||||
try: () => Option.fromNullishOr(Electron.BrowserWindow.getFocusedWindow() ?? null),
|
||||
catch: (cause) =>
|
||||
new ElectronWindowOperationError({
|
||||
operation: "get-focused-window",
|
||||
platform,
|
||||
windowId: null,
|
||||
channel: null,
|
||||
cause,
|
||||
}),
|
||||
}).pipe(Effect.orDie);
|
||||
if (Option.isSome(focused) && !(yield* isWindowDestroyed(focused.value))) {
|
||||
return focused;
|
||||
}
|
||||
return yield* currentMainOrFirst;
|
||||
});
|
||||
const focusedMainOrFirst = Effect.sync(() =>
|
||||
Option.fromNullishOr(Electron.BrowserWindow.getFocusedWindow() ?? null).pipe(
|
||||
Option.filter((window) => !window.isDestroyed()),
|
||||
),
|
||||
).pipe(
|
||||
Effect.flatMap((focused) =>
|
||||
Option.isSome(focused) ? Effect.succeed(focused) : currentMainOrFirst,
|
||||
),
|
||||
);
|
||||
|
||||
return ElectronWindow.of({
|
||||
create: (options) => {
|
||||
const webPreferences = options.webPreferences;
|
||||
const diagnosticOptions = {
|
||||
title: options.title ?? null,
|
||||
width: options.width ?? null,
|
||||
height: options.height ?? null,
|
||||
minWidth: options.minWidth ?? null,
|
||||
minHeight: options.minHeight ?? null,
|
||||
show: options.show ?? null,
|
||||
modal: options.modal ?? null,
|
||||
frame: options.frame ?? null,
|
||||
transparent: options.transparent ?? null,
|
||||
backgroundColor: options.backgroundColor ?? null,
|
||||
webPreferences: {
|
||||
preload: webPreferences?.preload ?? null,
|
||||
partition: webPreferences?.partition ?? null,
|
||||
sandbox: webPreferences?.sandbox ?? null,
|
||||
contextIsolation: webPreferences?.contextIsolation ?? null,
|
||||
nodeIntegration: webPreferences?.nodeIntegration ?? null,
|
||||
webviewTag: webPreferences?.webviewTag ?? null,
|
||||
},
|
||||
} satisfies typeof ElectronWindowCreateOptions.Type;
|
||||
|
||||
return Effect.try({
|
||||
create: (options) =>
|
||||
Effect.try({
|
||||
try: () => new Electron.BrowserWindow(options),
|
||||
catch: (cause) => new ElectronWindowCreateError({ options: diagnosticOptions, cause }),
|
||||
});
|
||||
},
|
||||
catch: (cause) => new ElectronWindowCreateError({ cause }),
|
||||
}),
|
||||
main: liveMain,
|
||||
currentMainOrFirst,
|
||||
focusedMainOrFirst,
|
||||
@@ -206,75 +89,45 @@ export const make = Effect.gen(function* () {
|
||||
return Option.none();
|
||||
}),
|
||||
reveal: (window) =>
|
||||
Effect.try({
|
||||
try: () => {
|
||||
if (window.isDestroyed()) {
|
||||
return;
|
||||
}
|
||||
Effect.sync(() => {
|
||||
if (window.isDestroyed()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (window.isMinimized()) {
|
||||
window.restore();
|
||||
}
|
||||
if (window.isMinimized()) {
|
||||
window.restore();
|
||||
}
|
||||
|
||||
if (!window.isVisible()) {
|
||||
window.show();
|
||||
}
|
||||
if (!window.isVisible()) {
|
||||
window.show();
|
||||
}
|
||||
|
||||
if (platform === "darwin") {
|
||||
Electron.app.focus({ steal: true });
|
||||
}
|
||||
if (platform === "darwin") {
|
||||
Electron.app.focus({ steal: true });
|
||||
}
|
||||
|
||||
window.focus();
|
||||
},
|
||||
catch: (cause) =>
|
||||
new ElectronWindowOperationError({
|
||||
operation: "reveal-window",
|
||||
platform,
|
||||
windowId: window.id,
|
||||
channel: null,
|
||||
cause,
|
||||
}),
|
||||
}).pipe(Effect.orDie),
|
||||
window.focus();
|
||||
}),
|
||||
sendAll: (channel, ...args) =>
|
||||
Effect.gen(function* () {
|
||||
for (const window of yield* listWindows) {
|
||||
if (yield* isWindowDestroyed(window)) {
|
||||
Effect.sync(() => {
|
||||
for (const window of Electron.BrowserWindow.getAllWindows()) {
|
||||
if (window.isDestroyed()) {
|
||||
continue;
|
||||
}
|
||||
yield* Effect.try({
|
||||
try: () => window.webContents.send(channel, ...args),
|
||||
catch: (cause) =>
|
||||
new ElectronWindowOperationError({
|
||||
operation: "send-window-message",
|
||||
platform,
|
||||
windowId: window.id,
|
||||
channel,
|
||||
cause,
|
||||
}),
|
||||
}).pipe(Effect.orDie);
|
||||
window.webContents.send(channel, ...args);
|
||||
}
|
||||
}),
|
||||
destroyAll: Effect.gen(function* () {
|
||||
for (const window of yield* listWindows) {
|
||||
yield* Effect.try({
|
||||
try: () => window.destroy(),
|
||||
catch: (cause) =>
|
||||
new ElectronWindowOperationError({
|
||||
operation: "destroy-window",
|
||||
platform,
|
||||
windowId: window.id,
|
||||
channel: null,
|
||||
cause,
|
||||
}),
|
||||
}).pipe(Effect.orDie);
|
||||
destroyAll: Effect.sync(() => {
|
||||
for (const window of Electron.BrowserWindow.getAllWindows()) {
|
||||
window.destroy();
|
||||
}
|
||||
}),
|
||||
syncAllAppearance: Effect.fn("desktop.electron.window.syncAllAppearance")(function* <E, R>(
|
||||
sync: (window: Electron.BrowserWindow) => Effect.Effect<void, E, R>,
|
||||
) {
|
||||
const windows = yield* listWindows;
|
||||
const windows = Electron.BrowserWindow.getAllWindows();
|
||||
for (const window of windows) {
|
||||
if (yield* isWindowDestroyed(window)) {
|
||||
if (window.isDestroyed()) {
|
||||
continue;
|
||||
}
|
||||
yield* sync(window);
|
||||
|
||||
@@ -19,30 +19,37 @@ import {
|
||||
PreviewAutomationSnapshot,
|
||||
PreviewAutomationStatus,
|
||||
} from "@t3tools/contracts";
|
||||
import { BrowserWindow } from "electron";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as NodeURL from "node:url";
|
||||
|
||||
import * as ElectronWindow from "../../electron/ElectronWindow.ts";
|
||||
import * as PreviewManager from "../../preview/Manager.ts";
|
||||
import { PREVIEW_WEBVIEW_PREFERENCES } from "../../preview/WebviewPreferences.ts";
|
||||
import * as IpcChannels from "../channels.ts";
|
||||
import * as DesktopIpc from "../DesktopIpc.ts";
|
||||
|
||||
const broadcast = (channel: string, ...args: ReadonlyArray<unknown>): void => {
|
||||
for (const window of BrowserWindow.getAllWindows()) {
|
||||
if (!window.isDestroyed()) {
|
||||
window.webContents.send(channel, ...args);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
export const installPreviewEventForwarding = Effect.fn(
|
||||
"desktop.ipc.preview.installEventForwarding",
|
||||
)(function* () {
|
||||
const electronWindow = yield* ElectronWindow.ElectronWindow;
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* manager.subscribeStateChanges((tabId, state) =>
|
||||
electronWindow.sendAll(IpcChannels.PREVIEW_STATE_CHANGE_CHANNEL, tabId, state),
|
||||
);
|
||||
yield* manager.subscribeRecordingFrames((frame) =>
|
||||
electronWindow.sendAll(IpcChannels.PREVIEW_RECORDING_FRAME_CHANNEL, frame),
|
||||
);
|
||||
yield* manager.subscribePointerEvents((event) =>
|
||||
electronWindow.sendAll(IpcChannels.PREVIEW_POINTER_EVENT_CHANNEL, event),
|
||||
);
|
||||
yield* manager.subscribeStateChanges((tabId, state) => {
|
||||
broadcast(IpcChannels.PREVIEW_STATE_CHANGE_CHANNEL, tabId, state);
|
||||
});
|
||||
yield* manager.subscribeRecordingFrames((frame) => {
|
||||
broadcast(IpcChannels.PREVIEW_RECORDING_FRAME_CHANNEL, frame);
|
||||
});
|
||||
yield* manager.subscribePointerEvents((event) => {
|
||||
broadcast(IpcChannels.PREVIEW_POINTER_EVENT_CHANNEL, event);
|
||||
});
|
||||
});
|
||||
|
||||
export const createTab = DesktopIpc.makeIpcMethod({
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import { beforeEach, vi } from "vite-plus/test";
|
||||
|
||||
const { fromPartition, sessions } = vi.hoisted(() => ({
|
||||
@@ -61,64 +59,6 @@ describe("BrowserSession", () => {
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
|
||||
it.effect("preserves partition scope and the platform failure chain", () => {
|
||||
const nativeCause = new Error("native digest failed");
|
||||
const platformCause = PlatformError.systemError({
|
||||
_tag: "Unknown",
|
||||
module: "Crypto",
|
||||
method: "digest",
|
||||
cause: nativeCause,
|
||||
});
|
||||
const failingCryptoLayer = Layer.succeed(
|
||||
Crypto.Crypto,
|
||||
Crypto.make({
|
||||
randomBytes: (size) => new Uint8Array(size),
|
||||
digest: () => Effect.fail(platformCause),
|
||||
}),
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const browserSessions = yield* BrowserSession.BrowserSession;
|
||||
const error = yield* browserSessions.getPartition("environment-a").pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, BrowserSession.BrowserSessionPartitionDerivationError);
|
||||
assert.isTrue(BrowserSession.isBrowserSessionGetSessionError(error));
|
||||
assert.isTrue(BrowserSession.isBrowserSessionError(error));
|
||||
assert.equal(error.scope, "environment-a");
|
||||
assert.strictEqual(error.cause, platformCause);
|
||||
assert.strictEqual(error.cause.reason.cause, nativeCause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
"Failed to derive a desktop preview browser partition for scope environment-a.",
|
||||
);
|
||||
assert.notInclude(error.message, nativeCause.message);
|
||||
}).pipe(Effect.provide(BrowserSession.layer.pipe(Layer.provide(failingCryptoLayer))));
|
||||
});
|
||||
|
||||
it.effect("preserves session scope, partition, and the Electron failure", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("Electron session failed");
|
||||
fromPartition.mockImplementationOnce(() => {
|
||||
throw cause;
|
||||
});
|
||||
const browserSessions = yield* BrowserSession.BrowserSession;
|
||||
const partition = yield* browserSessions.getPartition("environment-b");
|
||||
const error = yield* browserSessions.getSession("environment-b").pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, BrowserSession.BrowserSessionCreationError);
|
||||
assert.isTrue(BrowserSession.isBrowserSessionGetSessionError(error));
|
||||
assert.isTrue(BrowserSession.isBrowserSessionError(error));
|
||||
assert.equal(error.scope, "environment-b");
|
||||
assert.equal(error.partition, partition);
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Failed to create a desktop preview browser session for scope environment-b (partition ${partition}).`,
|
||||
);
|
||||
assert.notInclude(error.message, cause.message);
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
|
||||
it.effect("clears storage and cache for every created session", () =>
|
||||
Effect.gen(function* () {
|
||||
const browserSessions = yield* BrowserSession.BrowserSession;
|
||||
@@ -140,52 +80,4 @@ describe("BrowserSession", () => {
|
||||
}
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
|
||||
it.effect("correlates clear failures while still attempting every session", () =>
|
||||
Effect.gen(function* () {
|
||||
const browserSessions = yield* BrowserSession.BrowserSession;
|
||||
yield* browserSessions.getSession("scope-a");
|
||||
yield* browserSessions.getSession("scope-b");
|
||||
const firstPartition = yield* browserSessions.getPartition("scope-a");
|
||||
const secondPartition = yield* browserSessions.getPartition("scope-b");
|
||||
const firstSession = sessions.get(firstPartition);
|
||||
const secondSession = sessions.get(secondPartition);
|
||||
assert.isDefined(firstSession);
|
||||
assert.isDefined(secondSession);
|
||||
|
||||
const storageCause = new Error("storage clear failed");
|
||||
secondSession.clearStorageData.mockImplementationOnce(() => Promise.reject(storageCause));
|
||||
const storageError = yield* browserSessions.clearCookies().pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(storageError, BrowserSession.BrowserSessionStorageClearError);
|
||||
assert.isTrue(BrowserSession.isBrowserSessionError(storageError));
|
||||
assert.equal(storageError.partition, secondPartition);
|
||||
assert.strictEqual(storageError.cause, storageCause);
|
||||
assert.equal(
|
||||
storageError.message,
|
||||
`Failed to clear desktop preview browser storage for partition ${secondPartition}.`,
|
||||
);
|
||||
assert.notInclude(storageError.message, storageCause.message);
|
||||
for (const browserSession of sessions.values()) {
|
||||
assert.strictEqual(browserSession.clearStorageData.mock.calls.length, 1);
|
||||
}
|
||||
|
||||
const cacheCause = new Error("cache clear failed");
|
||||
firstSession.clearCache.mockImplementationOnce(() => Promise.reject(cacheCause));
|
||||
const cacheError = yield* browserSessions.clearCache().pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(cacheError, BrowserSession.BrowserSessionCacheClearError);
|
||||
assert.isTrue(BrowserSession.isBrowserSessionError(cacheError));
|
||||
assert.equal(cacheError.partition, firstPartition);
|
||||
assert.strictEqual(cacheError.cause, cacheCause);
|
||||
assert.equal(
|
||||
cacheError.message,
|
||||
`Failed to clear the desktop preview browser cache for partition ${firstPartition}.`,
|
||||
);
|
||||
assert.notInclude(cacheError.message, cacheCause.message);
|
||||
for (const browserSession of sessions.values()) {
|
||||
assert.strictEqual(browserSession.clearCache.mock.calls.length, 1);
|
||||
}
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
});
|
||||
@@ -5,87 +5,31 @@ import * as Crypto from "effect/Crypto";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Encoding from "effect/Encoding";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as SynchronizedRef from "effect/SynchronizedRef";
|
||||
|
||||
const PREVIEW_PARTITION_PREFIX = "persist:t3code-preview-";
|
||||
|
||||
export class BrowserSessionPartitionDerivationError extends Schema.TaggedErrorClass<BrowserSessionPartitionDerivationError>()(
|
||||
"BrowserSessionPartitionDerivationError",
|
||||
export class BrowserSessionError extends Schema.TaggedErrorClass<BrowserSessionError>()(
|
||||
"BrowserSessionError",
|
||||
{
|
||||
scope: Schema.String,
|
||||
cause: Schema.instanceOf(PlatformError.PlatformError),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to derive a desktop preview browser partition for scope ${this.scope}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class BrowserSessionCreationError extends Schema.TaggedErrorClass<BrowserSessionCreationError>()(
|
||||
"BrowserSessionCreationError",
|
||||
{
|
||||
scope: Schema.String,
|
||||
partition: Schema.String,
|
||||
operation: Schema.Literals(["getPartition", "getSession", "clearCookies", "clearCache"]),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to create a desktop preview browser session for scope ${this.scope} (partition ${this.partition}).`;
|
||||
return `Desktop preview browser session operation failed: ${this.operation}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class BrowserSessionStorageClearError extends Schema.TaggedErrorClass<BrowserSessionStorageClearError>()(
|
||||
"BrowserSessionStorageClearError",
|
||||
{
|
||||
partition: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to clear desktop preview browser storage for partition ${this.partition}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class BrowserSessionCacheClearError extends Schema.TaggedErrorClass<BrowserSessionCacheClearError>()(
|
||||
"BrowserSessionCacheClearError",
|
||||
{
|
||||
partition: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to clear the desktop preview browser cache for partition ${this.partition}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export const BrowserSessionGetSessionError = Schema.Union([
|
||||
BrowserSessionPartitionDerivationError,
|
||||
BrowserSessionCreationError,
|
||||
]);
|
||||
export type BrowserSessionGetSessionError = typeof BrowserSessionGetSessionError.Type;
|
||||
export const isBrowserSessionGetSessionError = Schema.is(BrowserSessionGetSessionError);
|
||||
|
||||
export const BrowserSessionError = Schema.Union([
|
||||
BrowserSessionPartitionDerivationError,
|
||||
BrowserSessionCreationError,
|
||||
BrowserSessionStorageClearError,
|
||||
BrowserSessionCacheClearError,
|
||||
]);
|
||||
export type BrowserSessionError = typeof BrowserSessionError.Type;
|
||||
export const isBrowserSessionError = Schema.is(BrowserSessionError);
|
||||
|
||||
export class BrowserSession extends Context.Service<
|
||||
BrowserSession,
|
||||
{
|
||||
readonly getPartition: (
|
||||
scope?: string,
|
||||
) => Effect.Effect<string, BrowserSessionPartitionDerivationError>;
|
||||
readonly getPartition: (scope?: string) => Effect.Effect<string, BrowserSessionError>;
|
||||
readonly isPartition: (partition: string) => boolean;
|
||||
readonly getSession: (scope?: string) => Effect.Effect<Session, BrowserSessionGetSessionError>;
|
||||
readonly clearCookies: () => Effect.Effect<void, BrowserSessionStorageClearError>;
|
||||
readonly clearCache: () => Effect.Effect<void, BrowserSessionCacheClearError>;
|
||||
readonly getSession: (scope?: string) => Effect.Effect<Session, BrowserSessionError>;
|
||||
readonly clearCookies: () => Effect.Effect<void, BrowserSessionError>;
|
||||
readonly clearCache: () => Effect.Effect<void, BrowserSessionError>;
|
||||
}
|
||||
>()("@t3tools/desktop/preview/BrowserSession") {}
|
||||
|
||||
@@ -94,15 +38,11 @@ export const make = Effect.gen(function* BrowserSessionMake() {
|
||||
const sessionsRef = yield* SynchronizedRef.make<ReadonlyMap<string, Session>>(new Map());
|
||||
|
||||
const getPartition = Effect.fn("BrowserSession.getPartition")(function* (scope = "shared") {
|
||||
const digest = yield* crypto.digest("SHA-256", new TextEncoder().encode(scope)).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new BrowserSessionPartitionDerivationError({
|
||||
scope,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const digest = yield* crypto
|
||||
.digest("SHA-256", new TextEncoder().encode(scope))
|
||||
.pipe(
|
||||
Effect.mapError((cause) => new BrowserSessionError({ operation: "getPartition", cause })),
|
||||
);
|
||||
return `${PREVIEW_PARTITION_PREFIX}${Encoding.encodeHex(digest).slice(0, 20)}`;
|
||||
});
|
||||
|
||||
@@ -127,12 +67,7 @@ export const make = Effect.gen(function* BrowserSessionMake() {
|
||||
next.set(partition, browserSession);
|
||||
return [browserSession, next] as const;
|
||||
},
|
||||
catch: (cause) =>
|
||||
new BrowserSessionCreationError({
|
||||
scope,
|
||||
partition,
|
||||
cause,
|
||||
}),
|
||||
catch: (cause) => new BrowserSessionError({ operation: "getSession", cause }),
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -144,17 +79,13 @@ export const make = Effect.gen(function* BrowserSessionMake() {
|
||||
clearCookies: Effect.fn("BrowserSession.clearCookies")(function* () {
|
||||
const sessions = yield* SynchronizedRef.get(sessionsRef);
|
||||
yield* Effect.all(
|
||||
[...sessions.entries()].map(([partition, browserSession]) =>
|
||||
[...sessions.values()].map((browserSession) =>
|
||||
Effect.tryPromise({
|
||||
try: () =>
|
||||
browserSession.clearStorageData({
|
||||
storages: ["cookies", "localstorage", "indexdb", "websql", "serviceworkers"],
|
||||
}),
|
||||
catch: (cause) =>
|
||||
new BrowserSessionStorageClearError({
|
||||
partition,
|
||||
cause,
|
||||
}),
|
||||
catch: (cause) => new BrowserSessionError({ operation: "clearCookies", cause }),
|
||||
}),
|
||||
),
|
||||
{ concurrency: "unbounded", discard: true },
|
||||
@@ -163,14 +94,10 @@ export const make = Effect.gen(function* BrowserSessionMake() {
|
||||
clearCache: Effect.fn("BrowserSession.clearCache")(function* () {
|
||||
const sessions = yield* SynchronizedRef.get(sessionsRef);
|
||||
yield* Effect.all(
|
||||
[...sessions.entries()].map(([partition, browserSession]) =>
|
||||
[...sessions.values()].map((browserSession) =>
|
||||
Effect.tryPromise({
|
||||
try: () => browserSession.clearCache(),
|
||||
catch: (cause) =>
|
||||
new BrowserSessionCacheClearError({
|
||||
partition,
|
||||
cause,
|
||||
}),
|
||||
catch: (cause) => new BrowserSessionError({ operation: "clearCache", cause }),
|
||||
}),
|
||||
),
|
||||
{ concurrency: "unbounded", discard: true },
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
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";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Logger from "effect/Logger";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Schema from "effect/Schema";
|
||||
@@ -15,29 +13,19 @@ import { TestClock } from "effect/testing";
|
||||
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
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 +42,6 @@ vi.mock("electron", () => ({
|
||||
},
|
||||
webContents: {
|
||||
fromId,
|
||||
getFocusedWebContents,
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -92,7 +79,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 +95,6 @@ const withManager = <A>(
|
||||
describe("PreviewManager", () => {
|
||||
beforeEach(() => {
|
||||
fromId.mockClear();
|
||||
getFocusedWebContents.mockReset();
|
||||
getFocusedWebContents.mockReturnValue(null);
|
||||
mkdir.mockClear();
|
||||
writeFile.mockClear();
|
||||
showItemInFolder.mockClear();
|
||||
@@ -146,72 +130,6 @@ describe("PreviewManager", () => {
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("isolates failed state listeners and continues delivery", () => {
|
||||
const loggedErrors: Array<unknown> = [];
|
||||
const logger = Logger.make(({ message }) => {
|
||||
for (const value of Array.isArray(message) ? message : [message]) {
|
||||
if (typeof value === "object" && value !== null && "cause" in value) {
|
||||
loggedErrors.push(Cause.squash(value.cause as Cause.Cause<never>));
|
||||
}
|
||||
}
|
||||
});
|
||||
const deliveryError = new ElectronWindow.ElectronWindowOperationError({
|
||||
operation: "send-window-message",
|
||||
platform: "darwin",
|
||||
windowId: 42,
|
||||
channel: "preview:state-change",
|
||||
cause: new Error("renderer unavailable"),
|
||||
});
|
||||
const delivered = vi.fn();
|
||||
|
||||
return withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
yield* manager.subscribeStateChanges(() => Effect.die(deliveryError));
|
||||
yield* manager.subscribeStateChanges((tabId, state) =>
|
||||
Effect.sync(() => {
|
||||
delivered(tabId, state);
|
||||
}),
|
||||
);
|
||||
|
||||
const state = yield* manager.createTab("tab_listener_failure");
|
||||
|
||||
expect(delivered).toHaveBeenCalledOnce();
|
||||
expect(delivered).toHaveBeenCalledWith("tab_listener_failure", state);
|
||||
expect(loggedErrors).toHaveLength(1);
|
||||
expect(loggedErrors[0]).toBeInstanceOf(ElectronWindow.ElectronWindowOperationError);
|
||||
expect(loggedErrors[0]).toMatchObject({
|
||||
operation: "send-window-message",
|
||||
windowId: 42,
|
||||
channel: "preview:state-change",
|
||||
});
|
||||
}),
|
||||
).pipe(
|
||||
Effect.provide(
|
||||
Logger.layer([logger], {
|
||||
mergeWithExisting: false,
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
effectIt.effect("does not swallow state listener interruption", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
const exit = yield* Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
yield* manager.subscribeStateChanges(() => Effect.interrupt);
|
||||
return yield* Effect.exit(manager.createTab("tab_interrupted_listener"));
|
||||
}),
|
||||
);
|
||||
|
||||
expect(Exit.isFailure(exit)).toBe(true);
|
||||
if (Exit.isFailure(exit)) {
|
||||
expect(Cause.hasInterrupts(exit.cause)).toBe(true);
|
||||
}
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("queues navigation until the webview registers", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
@@ -264,197 +182,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* () {
|
||||
@@ -684,11 +411,7 @@ describe("PreviewManager", () => {
|
||||
},
|
||||
} as never);
|
||||
|
||||
yield* manager.subscribePointerEvents((event) =>
|
||||
Effect.sync(() => {
|
||||
activity.push(event.phase);
|
||||
}),
|
||||
);
|
||||
yield* manager.subscribePointerEvents((event) => activity.push(event.phase));
|
||||
yield* manager.createTab("tab_1");
|
||||
yield* manager.registerWebview("tab_1", 42);
|
||||
const click = yield* manager
|
||||
@@ -716,178 +439,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" }
|
||||
@@ -283,8 +281,8 @@ const nextZoomLevel = (current: number, direction: "in" | "out"): number => {
|
||||
return ZOOM_LEVELS[Math.max(step - 1, 0)] ?? current;
|
||||
};
|
||||
|
||||
type Listener = (tabId: string, state: PreviewTabState) => Effect.Effect<void>;
|
||||
type RecordingFrameListener = (frame: DesktopPreviewRecordingFrame) => Effect.Effect<void>;
|
||||
type Listener = (tabId: string, state: PreviewTabState) => void;
|
||||
type RecordingFrameListener = (frame: DesktopPreviewRecordingFrame) => void;
|
||||
|
||||
type PreviewInputSignal =
|
||||
| { readonly kind: "pointer"; readonly x: number; readonly y: number; readonly button: number }
|
||||
@@ -315,7 +313,7 @@ interface BrowserDiagnostics {
|
||||
readonly requests: ReadonlyMap<string, { url: string; method: string }>;
|
||||
}
|
||||
|
||||
type PointerEventListener = (event: DesktopPreviewPointerEvent) => Effect.Effect<void>;
|
||||
type PointerEventListener = (event: DesktopPreviewPointerEvent) => void;
|
||||
|
||||
interface ExpectedAgentInput {
|
||||
readonly signal: PreviewInputSignal;
|
||||
@@ -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>();
|
||||
@@ -445,28 +442,11 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
return copy;
|
||||
};
|
||||
|
||||
const deliverEvent = (
|
||||
eventKind: "state-change" | "recording-frame" | "pointer-event",
|
||||
tabId: string,
|
||||
delivery: () => Effect.Effect<void>,
|
||||
) =>
|
||||
Effect.suspend(delivery).pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
Cause.hasInterrupts(cause)
|
||||
? Effect.failCause(cause)
|
||||
: Effect.logWarning("Desktop preview event listener failed.", {
|
||||
eventKind,
|
||||
tabId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const emit = Effect.fn("PreviewManager.emit")(function* (tabId: string, state: PreviewTabState) {
|
||||
const listeners = yield* Ref.get(listenersRef);
|
||||
yield* Effect.forEach(
|
||||
listeners,
|
||||
(listener) => deliverEvent("state-change", tabId, () => listener(tabId, state)),
|
||||
(listener) => Effect.sync(() => listener(tabId, state)).pipe(Effect.ignore),
|
||||
{ discard: true },
|
||||
);
|
||||
});
|
||||
@@ -759,8 +739,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
};
|
||||
yield* Effect.forEach(
|
||||
listeners,
|
||||
(listener) =>
|
||||
deliverEvent("recording-frame", frame.tabId, () => listener(frame)),
|
||||
(listener) => Effect.sync(() => listener(frame)).pipe(Effect.ignore),
|
||||
{ discard: true },
|
||||
);
|
||||
}
|
||||
@@ -857,24 +836,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 +881,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 +1073,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 +1143,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 +1155,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 +1262,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 +1295,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 +1312,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),
|
||||
);
|
||||
@@ -2022,7 +1918,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
const listeners = yield* Ref.get(pointerEventListenersRef);
|
||||
yield* Effect.forEach(
|
||||
listeners,
|
||||
(listener) => deliverEvent("pointer-event", event.tabId, () => listener(event)),
|
||||
(listener) => Effect.sync(() => listener(event)).pipe(Effect.ignore),
|
||||
{ discard: true },
|
||||
);
|
||||
});
|
||||
@@ -2032,7 +1928,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 +1993,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 +2003,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 +2012,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 +2041,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 +2048,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 +2079,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 +2112,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 +2511,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 +2613,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 },
|
||||
};
|
||||
}
|
||||
@@ -83,6 +83,12 @@ export class DesktopSettingsWriteError extends Schema.TaggedErrorClass<DesktopSe
|
||||
}
|
||||
}
|
||||
|
||||
const writeError = (
|
||||
operation: DesktopSettingsWriteOperation,
|
||||
path: string,
|
||||
cause: unknown,
|
||||
): DesktopSettingsWriteError => new DesktopSettingsWriteError({ operation, path, cause });
|
||||
|
||||
export class DesktopAppSettings extends Context.Service<
|
||||
DesktopAppSettings,
|
||||
{
|
||||
@@ -238,46 +244,18 @@ const writeSettings = Effect.fn("desktop.settings.writeSettings")(function* (inp
|
||||
const tempPath = `${input.settingsPath}.${process.pid}.${input.suffix}.tmp`;
|
||||
const encoded = yield* encodeDesktopSettingsJson(
|
||||
toDesktopSettingsDocument(input.settings, input.defaultSettings),
|
||||
).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopSettingsWriteError({
|
||||
operation: "encode-document",
|
||||
path: input.settingsPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* input.fileSystem.makeDirectory(directory, { recursive: true }).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopSettingsWriteError({
|
||||
operation: "create-directory",
|
||||
path: directory,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* input.fileSystem.writeFileString(tempPath, `${encoded}\n`).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopSettingsWriteError({
|
||||
operation: "write-temporary-file",
|
||||
path: tempPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* input.fileSystem.rename(tempPath, input.settingsPath).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopSettingsWriteError({
|
||||
operation: "replace-settings-file",
|
||||
path: input.settingsPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
).pipe(Effect.mapError((cause) => writeError("encode-document", input.settingsPath, cause)));
|
||||
yield* input.fileSystem
|
||||
.makeDirectory(directory, { recursive: true })
|
||||
.pipe(Effect.mapError((cause) => writeError("create-directory", directory, cause)));
|
||||
yield* input.fileSystem
|
||||
.writeFileString(tempPath, `${encoded}\n`)
|
||||
.pipe(Effect.mapError((cause) => writeError("write-temporary-file", tempPath, cause)));
|
||||
yield* input.fileSystem
|
||||
.rename(tempPath, input.settingsPath)
|
||||
.pipe(
|
||||
Effect.mapError((cause) => writeError("replace-settings-file", input.settingsPath, cause)),
|
||||
);
|
||||
});
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
@@ -298,13 +276,8 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
return crypto.randomUUIDv4.pipe(
|
||||
Effect.map((uuid) => uuid.replace(/-/g, "")),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopSettingsWriteError({
|
||||
operation: "create-temporary-file-name",
|
||||
path: environment.desktopSettingsPath,
|
||||
cause,
|
||||
}),
|
||||
Effect.mapError((cause) =>
|
||||
writeError("create-temporary-file-name", environment.desktopSettingsPath, cause),
|
||||
),
|
||||
Effect.flatMap((suffix) =>
|
||||
writeSettings({
|
||||
|
||||
@@ -1,129 +0,0 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
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 Option from "effect/Option";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as References from "effect/References";
|
||||
|
||||
import * as DesktopConfig from "../app/DesktopConfig.ts";
|
||||
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import * as DesktopClientSettings from "./DesktopClientSettings.ts";
|
||||
|
||||
interface LogRecord {
|
||||
readonly message: unknown;
|
||||
readonly annotations: Readonly<Record<string, unknown>>;
|
||||
}
|
||||
|
||||
const baseDir = "/virtual-home";
|
||||
|
||||
function makeLayer(fileSystemLayer: Layer.Layer<FileSystem.FileSystem>) {
|
||||
const environmentLayer = DesktopEnvironment.layer({
|
||||
dirname: "/repo/apps/desktop/src",
|
||||
homeDirectory: baseDir,
|
||||
platform: "darwin",
|
||||
processArch: "x64",
|
||||
appVersion: "1.2.3",
|
||||
appPath: "/repo",
|
||||
isPackaged: true,
|
||||
resourcesPath: "/missing/resources",
|
||||
runningUnderArm64Translation: false,
|
||||
}).pipe(
|
||||
Layer.provide(
|
||||
Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({ T3CODE_HOME: baseDir })),
|
||||
),
|
||||
);
|
||||
|
||||
return DesktopClientSettings.layer.pipe(
|
||||
Layer.provideMerge(Layer.mergeAll(environmentLayer, NodeServices.layer, fileSystemLayer)),
|
||||
);
|
||||
}
|
||||
|
||||
const readWithLogs = (fileSystemLayer: Layer.Layer<FileSystem.FileSystem>) => {
|
||||
const records: Array<LogRecord> = [];
|
||||
const logger = Logger.make(({ fiber, message }) => {
|
||||
records.push({
|
||||
message,
|
||||
annotations: { ...fiber.getRef(References.CurrentLogAnnotations) },
|
||||
});
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const settings = yield* DesktopClientSettings.DesktopClientSettings;
|
||||
return {
|
||||
result: yield* settings.get,
|
||||
settingsPath: environment.clientSettingsPath,
|
||||
records,
|
||||
};
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
makeLayer(fileSystemLayer),
|
||||
Logger.layer([logger], { mergeWithExisting: false }),
|
||||
),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
describe("DesktopClientSettings diagnostics", () => {
|
||||
it.effect("treats a missing settings file as expected without warning", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* readWithLogs(FileSystem.layerNoop({}));
|
||||
|
||||
assert.isTrue(Option.isNone(result.result));
|
||||
assert.deepEqual(result.records, []);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("logs non-missing filesystem failures with the settings path", () => {
|
||||
const permissionError = PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "readFileString",
|
||||
pathOrDescriptor: `${baseDir}/userdata/client-settings.json`,
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const result = yield* readWithLogs(
|
||||
FileSystem.layerNoop({
|
||||
readFileString: () => Effect.fail(permissionError),
|
||||
}),
|
||||
);
|
||||
|
||||
assert.isTrue(Option.isNone(result.result));
|
||||
assert.equal(result.records.length, 1);
|
||||
assert.deepEqual(result.records[0]?.message, [
|
||||
"Could not read desktop client settings.",
|
||||
permissionError,
|
||||
]);
|
||||
assert.equal(result.records[0]?.annotations.settingsPath, result.settingsPath);
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("logs malformed settings documents with the settings path", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* readWithLogs(
|
||||
FileSystem.layerNoop({
|
||||
readFileString: () => Effect.succeed("{not-json"),
|
||||
}),
|
||||
);
|
||||
|
||||
assert.isTrue(Option.isNone(result.result));
|
||||
assert.equal(result.records.length, 1);
|
||||
const message = result.records[0]?.message;
|
||||
if (!Array.isArray(message)) {
|
||||
return assert.fail("expected structured warning arguments");
|
||||
}
|
||||
assert.equal(message[0], "Could not decode desktop client settings.");
|
||||
const schemaError = message[1];
|
||||
if (schemaError === null || typeof schemaError !== "object") {
|
||||
return assert.fail("expected the schema error in the warning");
|
||||
}
|
||||
assert.equal("_tag" in schemaError ? schemaError._tag : undefined, "SchemaError");
|
||||
assert.equal(result.records[0]?.annotations.settingsPath, result.settingsPath);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -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));
|
||||
|
||||
@@ -67,29 +67,14 @@ const readClientSettings = (
|
||||
settingsPath: string,
|
||||
): Effect.Effect<Option.Option<ClientSettings>> =>
|
||||
fileSystem.readFileString(settingsPath).pipe(
|
||||
Effect.map(Option.some),
|
||||
Effect.catchTags({
|
||||
PlatformError: (cause) =>
|
||||
cause.reason._tag === "NotFound"
|
||||
? Effect.succeed(Option.none<string>())
|
||||
: Effect.logWarning("Could not read desktop client settings.", cause).pipe(
|
||||
Effect.annotateLogs({ settingsPath }),
|
||||
Effect.as(Option.none<string>()),
|
||||
),
|
||||
}),
|
||||
Effect.option,
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onNone: () => Effect.succeed(Option.none<ClientSettings>()),
|
||||
onSome: (raw) =>
|
||||
decodeClientSettingsJson(raw).pipe(
|
||||
Effect.map((settings) => Option.some(settings)),
|
||||
Effect.catchTags({
|
||||
SchemaError: (cause) =>
|
||||
Effect.logWarning("Could not decode desktop client settings.", cause).pipe(
|
||||
Effect.annotateLogs({ settingsPath }),
|
||||
Effect.as(Option.none<ClientSettings>()),
|
||||
),
|
||||
}),
|
||||
Effect.orElseSucceed(() => Option.none<ClientSettings>()),
|
||||
),
|
||||
}),
|
||||
),
|
||||
|
||||
@@ -271,11 +271,10 @@ describe("DesktopSavedEnvironments", () => {
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("adds saved-environment context to safe storage availability failures", () => {
|
||||
it.effect("surfaces typed safe storage availability failures", () => {
|
||||
const cause = new Error("safe storage unavailable");
|
||||
return withSavedEnvironments(
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
|
||||
yield* savedEnvironments.setRegistry([savedRegistryRecord]);
|
||||
|
||||
@@ -286,22 +285,8 @@ describe("DesktopSavedEnvironments", () => {
|
||||
})
|
||||
.pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(
|
||||
error,
|
||||
DesktopSavedEnvironments.DesktopSavedEnvironmentSecretProtectionError,
|
||||
);
|
||||
assert.equal(error.operation, "check-encryption-availability");
|
||||
assert.equal(error.environmentId, savedRegistryRecord.environmentId);
|
||||
assert.equal(error.registryPath, environment.savedEnvironmentRegistryPath);
|
||||
assert.instanceOf(error.cause, ElectronSafeStorage.ElectronSafeStorageAvailabilityError);
|
||||
const availabilityError =
|
||||
error.cause as ElectronSafeStorage.ElectronSafeStorageAvailabilityError;
|
||||
assert.strictEqual(availabilityError.cause, cause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Desktop saved-environment secret protection failed during check-encryption-availability for environment ${savedRegistryRecord.environmentId} at ${environment.savedEnvironmentRegistryPath}.`,
|
||||
);
|
||||
assert.notEqual(error.message, availabilityError.message);
|
||||
assert.instanceOf(error, ElectronSafeStorage.ElectronSafeStorageAvailabilityError);
|
||||
assert.equal(error.cause, cause);
|
||||
}),
|
||||
{ availabilityError: cause },
|
||||
);
|
||||
|
||||
@@ -77,12 +77,7 @@ const DesktopSavedEnvironmentsWriteOperation = Schema.Literals([
|
||||
"write-temporary-file",
|
||||
"replace-registry-file",
|
||||
]);
|
||||
|
||||
const DesktopSavedEnvironmentSecretProtectionOperation = Schema.Literals([
|
||||
"check-encryption-availability",
|
||||
"encrypt-secret",
|
||||
"decrypt-secret",
|
||||
]);
|
||||
type DesktopSavedEnvironmentsWriteOperation = typeof DesktopSavedEnvironmentsWriteOperation.Type;
|
||||
|
||||
export class DesktopSavedEnvironmentsWriteError extends Schema.TaggedErrorClass<DesktopSavedEnvironmentsWriteError>()(
|
||||
"DesktopSavedEnvironmentsWriteError",
|
||||
@@ -97,6 +92,17 @@ export class DesktopSavedEnvironmentsWriteError extends Schema.TaggedErrorClass<
|
||||
}
|
||||
}
|
||||
|
||||
const writeError = (
|
||||
operation: DesktopSavedEnvironmentsWriteOperation,
|
||||
path: string,
|
||||
cause: unknown,
|
||||
): DesktopSavedEnvironmentsWriteError =>
|
||||
new DesktopSavedEnvironmentsWriteError({
|
||||
operation,
|
||||
path,
|
||||
cause,
|
||||
});
|
||||
|
||||
export class DesktopSavedEnvironmentsReadError extends Schema.TaggedErrorClass<DesktopSavedEnvironmentsReadError>()(
|
||||
"DesktopSavedEnvironmentsReadError",
|
||||
{
|
||||
@@ -135,20 +141,6 @@ export class DesktopSavedEnvironmentSecretDecodeError extends Schema.TaggedError
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopSavedEnvironmentSecretProtectionError extends Schema.TaggedErrorClass<DesktopSavedEnvironmentSecretProtectionError>()(
|
||||
"DesktopSavedEnvironmentSecretProtectionError",
|
||||
{
|
||||
operation: DesktopSavedEnvironmentSecretProtectionOperation,
|
||||
environmentId: Schema.String,
|
||||
registryPath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Desktop saved-environment secret protection failed during ${this.operation} for environment ${this.environmentId} at ${this.registryPath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export type DesktopSavedEnvironmentsReadRegistryError =
|
||||
| DesktopSavedEnvironmentsReadError
|
||||
| DesktopSavedEnvironmentsDocumentDecodeError;
|
||||
@@ -160,11 +152,11 @@ export type DesktopSavedEnvironmentsMutationError =
|
||||
export type DesktopSavedEnvironmentsGetSecretError =
|
||||
| DesktopSavedEnvironmentsReadRegistryError
|
||||
| DesktopSavedEnvironmentSecretDecodeError
|
||||
| DesktopSavedEnvironmentSecretProtectionError;
|
||||
| ElectronSafeStorage.ElectronSafeStorageError;
|
||||
|
||||
export type DesktopSavedEnvironmentsSetSecretError =
|
||||
| DesktopSavedEnvironmentsMutationError
|
||||
| DesktopSavedEnvironmentSecretProtectionError;
|
||||
| ElectronSafeStorage.ElectronSafeStorageError;
|
||||
|
||||
export class DesktopSavedEnvironments extends Context.Service<
|
||||
DesktopSavedEnvironments,
|
||||
@@ -284,45 +276,19 @@ const writeRegistryDocument = Effect.fn("desktop.savedEnvironments.writeRegistry
|
||||
const directory = input.path.dirname(input.registryPath);
|
||||
const tempPath = `${input.registryPath}.${process.pid}.${input.suffix}.tmp`;
|
||||
const encoded = yield* encodeSavedEnvironmentRegistryDocumentJson(input.document).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopSavedEnvironmentsWriteError({
|
||||
operation: "encode-registry",
|
||||
path: input.registryPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* input.fileSystem.makeDirectory(directory, { recursive: true }).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopSavedEnvironmentsWriteError({
|
||||
operation: "create-directory",
|
||||
path: directory,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* input.fileSystem.writeFileString(tempPath, `${encoded}\n`).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopSavedEnvironmentsWriteError({
|
||||
operation: "write-temporary-file",
|
||||
path: tempPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* input.fileSystem.rename(tempPath, input.registryPath).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopSavedEnvironmentsWriteError({
|
||||
operation: "replace-registry-file",
|
||||
path: input.registryPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.mapError((cause) => writeError("encode-registry", input.registryPath, cause)),
|
||||
);
|
||||
yield* input.fileSystem
|
||||
.makeDirectory(directory, { recursive: true })
|
||||
.pipe(Effect.mapError((cause) => writeError("create-directory", directory, cause)));
|
||||
yield* input.fileSystem
|
||||
.writeFileString(tempPath, `${encoded}\n`)
|
||||
.pipe(Effect.mapError((cause) => writeError("write-temporary-file", tempPath, cause)));
|
||||
yield* input.fileSystem
|
||||
.rename(tempPath, input.registryPath)
|
||||
.pipe(
|
||||
Effect.mapError((cause) => writeError("replace-registry-file", input.registryPath, cause)),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
@@ -375,13 +341,8 @@ export const make = Effect.gen(function* () {
|
||||
const writeDocument = (document: SavedEnvironmentRegistryDocument) =>
|
||||
crypto.randomUUIDv4.pipe(
|
||||
Effect.map((uuid) => uuid.replace(/-/g, "")),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopSavedEnvironmentsWriteError({
|
||||
operation: "create-temporary-file-name",
|
||||
path: environment.savedEnvironmentRegistryPath,
|
||||
cause,
|
||||
}),
|
||||
Effect.mapError((cause) =>
|
||||
writeError("create-temporary-file-name", environment.savedEnvironmentRegistryPath, cause),
|
||||
),
|
||||
Effect.flatMap((suffix) =>
|
||||
writeRegistryDocument({
|
||||
@@ -435,21 +396,7 @@ export const make = Effect.gen(function* () {
|
||||
document.records.find((record) => record.environmentId === environmentId)
|
||||
?.encryptedBearerToken,
|
||||
);
|
||||
if (Option.isNone(encoded)) {
|
||||
return Option.none<string>();
|
||||
}
|
||||
const encryptionAvailable = yield* safeStorage.isEncryptionAvailable.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopSavedEnvironmentSecretProtectionError({
|
||||
operation: "check-encryption-availability",
|
||||
environmentId,
|
||||
registryPath: environment.savedEnvironmentRegistryPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (!encryptionAvailable) {
|
||||
if (Option.isNone(encoded) || !(yield* safeStorage.isEncryptionAvailable)) {
|
||||
return Option.none<string>();
|
||||
}
|
||||
|
||||
@@ -458,19 +405,7 @@ export const make = Effect.gen(function* () {
|
||||
environment.savedEnvironmentRegistryPath,
|
||||
encoded.value,
|
||||
);
|
||||
return Option.some(
|
||||
yield* safeStorage.decryptString(secretBytes).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopSavedEnvironmentSecretProtectionError({
|
||||
operation: "decrypt-secret",
|
||||
environmentId,
|
||||
registryPath: environment.savedEnvironmentRegistryPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
return Option.some(yield* safeStorage.decryptString(secretBytes));
|
||||
}),
|
||||
setSecret: Effect.fn("desktop.savedEnvironments.setSecret")(function* (input) {
|
||||
const { environmentId, secret } = input;
|
||||
@@ -480,34 +415,11 @@ export const make = Effect.gen(function* () {
|
||||
environment.savedEnvironmentRegistryPath,
|
||||
);
|
||||
|
||||
const encryptionAvailable = yield* safeStorage.isEncryptionAvailable.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopSavedEnvironmentSecretProtectionError({
|
||||
operation: "check-encryption-availability",
|
||||
environmentId,
|
||||
registryPath: environment.savedEnvironmentRegistryPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (!encryptionAvailable) {
|
||||
if (!(yield* safeStorage.isEncryptionAvailable)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const encryptedBearerToken = Encoding.encodeBase64(
|
||||
yield* safeStorage.encryptString(secret).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopSavedEnvironmentSecretProtectionError({
|
||||
operation: "encrypt-secret",
|
||||
environmentId,
|
||||
registryPath: environment.savedEnvironmentRegistryPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
const encryptedBearerToken = Encoding.encodeBase64(yield* safeStorage.encryptString(secret));
|
||||
let found = false;
|
||||
const nextDocument: SavedEnvironmentRegistryDocument = {
|
||||
version: document.version,
|
||||
|
||||
@@ -23,7 +23,6 @@ describe("sshEnvironment", () => {
|
||||
const cause = new DesktopSshPasswordPrompts.DesktopSshPromptPresentationError({
|
||||
requestId: "prompt-1",
|
||||
destination: "devbox",
|
||||
operation: "send-prompt-request",
|
||||
cause: new Error("renderer send failed"),
|
||||
});
|
||||
|
||||
|
||||
@@ -17,13 +17,7 @@ interface SentMessage {
|
||||
readonly args: readonly unknown[];
|
||||
}
|
||||
|
||||
function makeTestWindow(
|
||||
options: {
|
||||
readonly isDestroyedError?: unknown;
|
||||
readonly isMinimizedError?: unknown;
|
||||
readonly sendError?: unknown;
|
||||
} = {},
|
||||
) {
|
||||
function makeTestWindow() {
|
||||
const listeners = new Map<string, Set<() => void>>();
|
||||
const sentMessages: SentMessage[] = [];
|
||||
let destroyed = false;
|
||||
@@ -32,18 +26,8 @@ function makeTestWindow(
|
||||
let focused = false;
|
||||
|
||||
const window = {
|
||||
isDestroyed: () => {
|
||||
if (options.isDestroyedError !== undefined) {
|
||||
throw options.isDestroyedError;
|
||||
}
|
||||
return destroyed;
|
||||
},
|
||||
isMinimized: () => {
|
||||
if (options.isMinimizedError !== undefined) {
|
||||
throw options.isMinimizedError;
|
||||
}
|
||||
return minimized;
|
||||
},
|
||||
isDestroyed: () => destroyed,
|
||||
isMinimized: () => minimized,
|
||||
restore: () => {
|
||||
restored = true;
|
||||
minimized = false;
|
||||
@@ -61,11 +45,7 @@ function makeTestWindow(
|
||||
},
|
||||
webContents: {
|
||||
send: (channel: string, ...args: readonly unknown[]) => {
|
||||
const message = { channel, args };
|
||||
sentMessages.push(message);
|
||||
if (options.sendError !== undefined) {
|
||||
throw options.sendError;
|
||||
}
|
||||
sentMessages.push({ channel, args });
|
||||
},
|
||||
},
|
||||
};
|
||||
@@ -75,7 +55,6 @@ function makeTestWindow(
|
||||
sentMessages,
|
||||
isRestored: () => restored,
|
||||
isFocused: () => focused,
|
||||
closedListenerCount: () => listeners.get("closed")?.size ?? 0,
|
||||
close: () => {
|
||||
destroyed = true;
|
||||
const closedListeners = [...(listeners.get("closed") ?? [])];
|
||||
@@ -128,7 +107,6 @@ describe("DesktopSshPasswordPrompts", () => {
|
||||
})
|
||||
.pipe(Effect.forkScoped);
|
||||
|
||||
yield* Effect.yieldNow;
|
||||
yield* Effect.yieldNow;
|
||||
assert.equal(testWindow.sentMessages.length, 1);
|
||||
const sent = testWindow.sentMessages[0];
|
||||
@@ -165,85 +143,4 @@ describe("DesktopSshPasswordPrompts", () => {
|
||||
assert.equal(error.destination, "devbox");
|
||||
}).pipe(Effect.provide(makeLayer(testWindow.window)), Effect.scoped);
|
||||
});
|
||||
|
||||
it.effect("cleans up a prompt that fails during renderer delivery", () => {
|
||||
const cause = new Error("renderer unavailable");
|
||||
const testWindow = makeTestWindow({ sendError: cause });
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const prompts = yield* DesktopSshPasswordPrompts.DesktopSshPasswordPrompts;
|
||||
const error = yield* prompts
|
||||
.request({
|
||||
destination: "devbox",
|
||||
username: "julius",
|
||||
prompt: "Enter the SSH password.",
|
||||
attempt: 1,
|
||||
})
|
||||
.pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, DesktopSshPasswordPrompts.DesktopSshPromptPresentationError);
|
||||
assert.equal(error.operation, "send-prompt-request");
|
||||
assert.equal(error.destination, "devbox");
|
||||
const requestId = error.requestId;
|
||||
if (requestId === null) {
|
||||
assert.fail("renderer delivery failures must retain their request id");
|
||||
}
|
||||
assert.equal(testWindow.closedListenerCount(), 0);
|
||||
|
||||
const resolveError = yield* prompts
|
||||
.resolve({ requestId, password: "secret" })
|
||||
.pipe(Effect.flip);
|
||||
assert.instanceOf(resolveError, DesktopSshPasswordPrompts.DesktopSshPromptExpiredError);
|
||||
}).pipe(Effect.provide(makeLayer(testWindow.window)), Effect.scoped);
|
||||
});
|
||||
|
||||
it.effect("keeps a submitted password when a later presentation step fails", () => {
|
||||
const testWindow = makeTestWindow({
|
||||
isMinimizedError: new Error("failed to read minimized state"),
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const prompts = yield* DesktopSshPasswordPrompts.DesktopSshPasswordPrompts;
|
||||
const requestFiber = yield* prompts
|
||||
.request({
|
||||
destination: "devbox",
|
||||
username: "julius",
|
||||
prompt: "Enter the SSH password.",
|
||||
attempt: 1,
|
||||
})
|
||||
.pipe(Effect.forkScoped);
|
||||
|
||||
yield* Effect.yieldNow;
|
||||
const sent = testWindow.sentMessages[0];
|
||||
assert.ok(sent);
|
||||
const request = sent.args[0] as { readonly requestId: string };
|
||||
yield* prompts.resolve({ requestId: request.requestId, password: "secret" });
|
||||
const password = yield* Fiber.join(requestFiber);
|
||||
|
||||
assert.equal(password, "secret");
|
||||
assert.equal(testWindow.isFocused(), false);
|
||||
assert.equal(testWindow.closedListenerCount(), 0);
|
||||
}).pipe(Effect.provide(makeLayer(testWindow.window)), Effect.scoped);
|
||||
});
|
||||
|
||||
it.effect("classifies a failed initial window availability check", () => {
|
||||
const testWindow = makeTestWindow({ isDestroyedError: new Error("window unavailable") });
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const prompts = yield* DesktopSshPasswordPrompts.DesktopSshPasswordPrompts;
|
||||
const error = yield* prompts
|
||||
.request({
|
||||
destination: "devbox",
|
||||
username: "julius",
|
||||
prompt: "Enter the SSH password.",
|
||||
attempt: 1,
|
||||
})
|
||||
.pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, DesktopSshPasswordPrompts.DesktopSshPromptPresentationError);
|
||||
assert.equal(error.operation, "check-window-before-request");
|
||||
assert.equal(error.requestId, null);
|
||||
assert.deepEqual(testWindow.sentMessages, []);
|
||||
}).pipe(Effect.provide(makeLayer(testWindow.window)), Effect.scoped);
|
||||
});
|
||||
});
|
||||
@@ -20,26 +20,7 @@ const DEFAULT_SSH_PASSWORD_PROMPT_TIMEOUT_MS = 3 * 60 * 1000;
|
||||
type DesktopSshPasswordPromptResolutionInput =
|
||||
typeof DesktopSshPasswordPromptResolutionInputSchema.Type;
|
||||
|
||||
const DesktopSshPromptWindowAvailabilityStage = Schema.Literals([
|
||||
"before-request",
|
||||
"before-presentation",
|
||||
"after-send",
|
||||
"after-restore",
|
||||
]);
|
||||
|
||||
const DesktopSshPromptPresentationOperation = Schema.Literals([
|
||||
"check-window-before-request",
|
||||
"check-window-before-presentation",
|
||||
"register-window-close-listener",
|
||||
"send-prompt-request",
|
||||
"check-window-after-send",
|
||||
"check-window-minimized",
|
||||
"restore-window",
|
||||
"check-window-after-restore",
|
||||
"focus-window",
|
||||
"remove-window-close-listener",
|
||||
]);
|
||||
type DesktopSshPromptPresentationOperation = typeof DesktopSshPromptPresentationOperation.Type;
|
||||
const WINDOW_UNAVAILABLE_MESSAGE = "T3 Code window is not available for SSH authentication.";
|
||||
|
||||
export class DesktopSshPromptRequestIdGenerationError extends Schema.TaggedErrorClass<DesktopSshPromptRequestIdGenerationError>()(
|
||||
"DesktopSshPromptRequestIdGenerationError",
|
||||
@@ -57,22 +38,20 @@ export class DesktopSshPromptWindowUnavailableError extends Schema.TaggedErrorCl
|
||||
"DesktopSshPromptWindowUnavailableError",
|
||||
{
|
||||
destination: Schema.String,
|
||||
requestId: Schema.NullOr(Schema.String),
|
||||
stage: DesktopSshPromptWindowAvailabilityStage,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
const request = this.requestId === null ? "before a request id was assigned" : this.requestId;
|
||||
return `T3 Code window is unavailable during ${this.stage} for SSH authentication to ${this.destination} (request: ${request}).`;
|
||||
return WINDOW_UNAVAILABLE_MESSAGE;
|
||||
}
|
||||
}
|
||||
|
||||
const isDesktopSshPromptWindowUnavailableError = Schema.is(DesktopSshPromptWindowUnavailableError);
|
||||
|
||||
export class DesktopSshPromptPresentationError extends Schema.TaggedErrorClass<DesktopSshPromptPresentationError>()(
|
||||
"DesktopSshPromptPresentationError",
|
||||
{
|
||||
requestId: Schema.NullOr(Schema.String),
|
||||
requestId: Schema.String,
|
||||
destination: Schema.String,
|
||||
operation: DesktopSshPromptPresentationOperation,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
@@ -284,29 +263,9 @@ export const make = Effect.fn("desktop.sshPasswordPrompts.make")(function* (
|
||||
"desktop.sshPasswordPrompts.request",
|
||||
)(function* (input) {
|
||||
const window = yield* electronWindow.main;
|
||||
if (Option.isNone(window)) {
|
||||
if (Option.isNone(window) || window.value.isDestroyed()) {
|
||||
return yield* new DesktopSshPromptWindowUnavailableError({
|
||||
destination: input.destination,
|
||||
requestId: null,
|
||||
stage: "before-request",
|
||||
});
|
||||
}
|
||||
|
||||
const unavailableBeforeRequest = yield* Effect.try({
|
||||
try: () => window.value.isDestroyed(),
|
||||
catch: (cause) =>
|
||||
new DesktopSshPromptPresentationError({
|
||||
requestId: null,
|
||||
destination: input.destination,
|
||||
operation: "check-window-before-request",
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
if (unavailableBeforeRequest) {
|
||||
return yield* new DesktopSshPromptWindowUnavailableError({
|
||||
destination: input.destination,
|
||||
requestId: null,
|
||||
stage: "before-request",
|
||||
});
|
||||
}
|
||||
|
||||
@@ -360,25 +319,11 @@ export const make = Effect.fn("desktop.sshPasswordPrompts.make")(function* (
|
||||
),
|
||||
);
|
||||
};
|
||||
const runPresentationOperation = <A>(
|
||||
operation: DesktopSshPromptPresentationOperation,
|
||||
evaluate: () => A,
|
||||
) =>
|
||||
Effect.try({
|
||||
try: evaluate,
|
||||
catch: (cause) =>
|
||||
new DesktopSshPromptPresentationError({
|
||||
requestId,
|
||||
destination: input.destination,
|
||||
operation,
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
const cleanup = runPresentationOperation("remove-window-close-listener", () => {
|
||||
const cleanup = Effect.sync(() => {
|
||||
if (!window.value.isDestroyed()) {
|
||||
window.value.removeListener("closed", cancelOnWindowClosed);
|
||||
}
|
||||
}).pipe(Effect.orDie, Effect.ensuring(removePending(pendingRef, requestId)), Effect.asVoid);
|
||||
}).pipe(Effect.andThen(removePending(pendingRef, requestId)), Effect.asVoid);
|
||||
const waitForPassword = Deferred.await(deferred).pipe(
|
||||
Effect.timeoutOption(Duration.millis(passwordPromptTimeoutMs)),
|
||||
Effect.flatMap(
|
||||
@@ -394,73 +339,40 @@ export const make = Effect.fn("desktop.sshPasswordPrompts.make")(function* (
|
||||
}),
|
||||
),
|
||||
);
|
||||
const preferSubmittedPassword = (error: DesktopSshPasswordPromptRequestError) =>
|
||||
Deferred.poll(deferred).pipe(
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onSome: (completion) => completion,
|
||||
onNone: () =>
|
||||
Ref.get(pendingRef).pipe(
|
||||
Effect.flatMap((entries) =>
|
||||
entries.has(requestId) ? Effect.fail(error) : Deferred.await(deferred),
|
||||
),
|
||||
),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return yield* Effect.gen(function* () {
|
||||
const unavailableBeforePresentation = yield* runPresentationOperation(
|
||||
"check-window-before-presentation",
|
||||
() => window.value.isDestroyed(),
|
||||
);
|
||||
if (unavailableBeforePresentation) {
|
||||
return yield* new DesktopSshPromptWindowUnavailableError({
|
||||
destination: input.destination,
|
||||
requestId,
|
||||
stage: "before-presentation",
|
||||
});
|
||||
}
|
||||
yield* runPresentationOperation("register-window-close-listener", () =>
|
||||
window.value.once("closed", cancelOnWindowClosed),
|
||||
);
|
||||
return yield* Effect.gen(function* () {
|
||||
yield* runPresentationOperation("send-prompt-request", () =>
|
||||
window.value.webContents.send(SSH_PASSWORD_PROMPT_CHANNEL, promptRequest),
|
||||
);
|
||||
yield* Effect.yieldNow;
|
||||
const unavailableAfterSend = yield* runPresentationOperation(
|
||||
"check-window-after-send",
|
||||
() => window.value.isDestroyed(),
|
||||
);
|
||||
if (unavailableAfterSend) {
|
||||
return yield* new DesktopSshPromptWindowUnavailableError({
|
||||
return yield* Effect.try({
|
||||
try: () => {
|
||||
if (window.value.isDestroyed()) {
|
||||
throw new DesktopSshPromptWindowUnavailableError({
|
||||
destination: input.destination,
|
||||
requestId,
|
||||
stage: "after-send",
|
||||
});
|
||||
}
|
||||
const minimized = yield* runPresentationOperation("check-window-minimized", () =>
|
||||
window.value.isMinimized(),
|
||||
);
|
||||
if (minimized) {
|
||||
yield* runPresentationOperation("restore-window", () => window.value.restore());
|
||||
}
|
||||
const unavailableAfterRestore = yield* runPresentationOperation(
|
||||
"check-window-after-restore",
|
||||
() => window.value.isDestroyed(),
|
||||
);
|
||||
if (unavailableAfterRestore) {
|
||||
return yield* new DesktopSshPromptWindowUnavailableError({
|
||||
window.value.once("closed", cancelOnWindowClosed);
|
||||
window.value.webContents.send(SSH_PASSWORD_PROMPT_CHANNEL, promptRequest);
|
||||
if (window.value.isDestroyed()) {
|
||||
throw new DesktopSshPromptWindowUnavailableError({
|
||||
destination: input.destination,
|
||||
requestId,
|
||||
stage: "after-restore",
|
||||
});
|
||||
}
|
||||
yield* runPresentationOperation("focus-window", () => window.value.focus());
|
||||
return yield* waitForPassword;
|
||||
}).pipe(Effect.catch(preferSubmittedPassword));
|
||||
}).pipe(Effect.ensuring(cleanup));
|
||||
if (window.value.isMinimized()) {
|
||||
window.value.restore();
|
||||
}
|
||||
if (window.value.isDestroyed()) {
|
||||
throw new DesktopSshPromptWindowUnavailableError({
|
||||
destination: input.destination,
|
||||
});
|
||||
}
|
||||
window.value.focus();
|
||||
},
|
||||
catch: (cause) =>
|
||||
isDesktopSshPromptWindowUnavailableError(cause)
|
||||
? cause
|
||||
: new DesktopSshPromptPresentationError({
|
||||
requestId,
|
||||
destination: input.destination,
|
||||
cause,
|
||||
}),
|
||||
}).pipe(Effect.andThen(waitForPassword), Effect.ensuring(cleanup));
|
||||
});
|
||||
|
||||
return DesktopSshPasswordPrompts.of({
|
||||
|
||||
@@ -7,10 +7,7 @@ import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Logger from "effect/Logger";
|
||||
import * as Option from "effect/Option";
|
||||
import * as References from "effect/References";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
|
||||
import * as DesktopBackendManager from "../backend/DesktopBackendManager.ts";
|
||||
@@ -27,9 +24,6 @@ interface UpdatesHarnessOptions {
|
||||
void,
|
||||
ElectronUpdater.ElectronUpdaterCheckForUpdatesError
|
||||
>;
|
||||
readonly setUpdateChannelError?: DesktopAppSettings.DesktopSettingsWriteError;
|
||||
readonly setDisableDifferentialDownload?: Effect.Effect<void>;
|
||||
readonly stopBackend?: Effect.Effect<void>;
|
||||
readonly env?: Record<string, string | undefined>;
|
||||
}
|
||||
|
||||
@@ -73,7 +67,7 @@ function makeHarness(options: UpdatesHarnessOptions = {}) {
|
||||
Effect.sync(() => {
|
||||
allowDowngrade = value;
|
||||
}),
|
||||
setDisableDifferentialDownload: () => options.setDisableDifferentialDownload ?? Effect.void,
|
||||
setDisableDifferentialDownload: () => Effect.void,
|
||||
checkForUpdates: Effect.sync(() => {
|
||||
checkCount += 1;
|
||||
}).pipe(Effect.andThen(options.checkForUpdates ?? Effect.void)),
|
||||
@@ -109,7 +103,7 @@ function makeHarness(options: UpdatesHarnessOptions = {}) {
|
||||
|
||||
const backendLayer = Layer.succeed(DesktopBackendManager.DesktopBackendManager, {
|
||||
start: Effect.void,
|
||||
stop: () => options.stopBackend ?? Effect.void,
|
||||
stop: () => Effect.void,
|
||||
currentConfig: Effect.succeed(Option.none()),
|
||||
snapshot: Effect.succeed({
|
||||
desiredRunning: false,
|
||||
@@ -144,23 +138,12 @@ function makeHarness(options: UpdatesHarnessOptions = {}) {
|
||||
),
|
||||
);
|
||||
|
||||
const setUpdateChannelError = options.setUpdateChannelError;
|
||||
const settingsLayer = setUpdateChannelError
|
||||
? Layer.succeed(DesktopAppSettings.DesktopAppSettings, {
|
||||
get: Effect.succeed(DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS),
|
||||
load: Effect.succeed(DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS),
|
||||
setServerExposureMode: () => Effect.die("unexpected server exposure update"),
|
||||
setTailscaleServe: () => Effect.die("unexpected Tailscale Serve update"),
|
||||
setUpdateChannel: () => Effect.fail(setUpdateChannelError),
|
||||
} satisfies DesktopAppSettings.DesktopAppSettings["Service"])
|
||||
: DesktopAppSettings.layer;
|
||||
|
||||
const layer = DesktopUpdates.layer.pipe(
|
||||
Layer.provideMerge(updaterLayer),
|
||||
Layer.provideMerge(windowLayer),
|
||||
Layer.provideMerge(backendLayer),
|
||||
Layer.provideMerge(DesktopState.layer),
|
||||
Layer.provideMerge(settingsLayer),
|
||||
Layer.provideMerge(DesktopAppSettings.layer),
|
||||
Layer.provideMerge(
|
||||
DesktopConfig.layerTest({
|
||||
T3CODE_HOME: `/tmp/t3-desktop-updates-test-${process.pid}`,
|
||||
@@ -192,45 +175,6 @@ function makeHarness(options: UpdatesHarnessOptions = {}) {
|
||||
}
|
||||
|
||||
describe("DesktopUpdates", () => {
|
||||
it("preserves complete causes for update poller and event failures", () => {
|
||||
const cause = Cause.combine(
|
||||
Cause.fail(new Error("updater failed")),
|
||||
Cause.die(new Error("updater defect")),
|
||||
);
|
||||
const pollerError = new DesktopUpdates.DesktopUpdatePollerError({
|
||||
poller: "startup",
|
||||
cause,
|
||||
});
|
||||
const eventError = new DesktopUpdates.DesktopUpdateEventHandlingError({
|
||||
event: "download-progress",
|
||||
cause,
|
||||
});
|
||||
const reportedError = new DesktopUpdates.DesktopUpdaterReportedError({
|
||||
operation: "download",
|
||||
cause,
|
||||
});
|
||||
const unexpectedActionError = new DesktopUpdates.DesktopUpdateUnexpectedActionError({
|
||||
action: "install",
|
||||
cause,
|
||||
});
|
||||
|
||||
assert.strictEqual(pollerError.cause, cause);
|
||||
assert.equal(pollerError.poller, "startup");
|
||||
assert.equal(pollerError.message, "Desktop update startup poller failed.");
|
||||
assert.strictEqual(eventError.cause, cause);
|
||||
assert.equal(eventError.event, "download-progress");
|
||||
assert.equal(eventError.message, "Failed to handle desktop update download-progress event.");
|
||||
assert.strictEqual(reportedError.cause, cause);
|
||||
assert.equal(reportedError.operation, "download");
|
||||
assert.equal(reportedError.message, "Desktop updater download operation reported an error.");
|
||||
assert.strictEqual(unexpectedActionError.cause, cause);
|
||||
assert.equal(unexpectedActionError.action, "install");
|
||||
assert.equal(
|
||||
unexpectedActionError.message,
|
||||
"Desktop update install action failed unexpectedly.",
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("configures the updater and runs startup checks on the test clock", () => {
|
||||
const harness = makeHarness();
|
||||
|
||||
@@ -278,178 +222,6 @@ describe("DesktopUpdates", () => {
|
||||
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
|
||||
});
|
||||
|
||||
it.effect("keeps raw updater event failures out of update state", () => {
|
||||
const harness = makeHarness();
|
||||
const cause = new Error(
|
||||
"request failed for https://user:[email protected]/update?token=secret",
|
||||
);
|
||||
|
||||
return Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const updates = yield* DesktopUpdates.DesktopUpdates;
|
||||
yield* updates.configure;
|
||||
|
||||
harness.emit("error", cause);
|
||||
yield* flushCallbacks;
|
||||
|
||||
const state = yield* updates.getState;
|
||||
assert.equal(state.status, "error");
|
||||
assert.equal(state.message, "Desktop updater background operation reported an error.");
|
||||
assert.notInclude(state.message ?? "", "secret");
|
||||
}),
|
||||
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
|
||||
});
|
||||
|
||||
it.effect("logs bounded updater failure context without exposing the cause", () => {
|
||||
const cause = new Error(
|
||||
"request failed for https://user:[email protected]/update?token=secret",
|
||||
);
|
||||
const updaterError = new ElectronUpdater.ElectronUpdaterCheckForUpdatesError({
|
||||
channel: null,
|
||||
cause,
|
||||
});
|
||||
const harness = makeHarness({ checkForUpdates: Effect.fail(updaterError) });
|
||||
const loggedAnnotations: Array<Record<string, unknown>> = [];
|
||||
const logger = Logger.make(({ fiber }) => {
|
||||
const annotations = fiber.getRef(References.CurrentLogAnnotations);
|
||||
if (annotations.errorTag === "ElectronUpdaterCheckForUpdatesError") {
|
||||
loggedAnnotations.push(annotations);
|
||||
}
|
||||
});
|
||||
|
||||
return Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const updates = yield* DesktopUpdates.DesktopUpdates;
|
||||
yield* updates.configure;
|
||||
|
||||
yield* updates.check("manual");
|
||||
|
||||
const state = yield* updates.getState;
|
||||
const loggedAnnotation = loggedAnnotations.at(-1);
|
||||
assert.isDefined(loggedAnnotation);
|
||||
assert.equal(loggedAnnotation.errorTag, "ElectronUpdaterCheckForUpdatesError");
|
||||
assert.isNull(loggedAnnotation.channel);
|
||||
assert.notProperty(loggedAnnotation, "error");
|
||||
assert.notInclude(Object.values(loggedAnnotation).map(String).join(" "), "secret");
|
||||
assert.equal(
|
||||
state.message,
|
||||
"Electron updater failed to check for updates on channel default.",
|
||||
);
|
||||
assert.notInclude(state.message ?? "", "secret");
|
||||
}),
|
||||
).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
TestClock.layer(),
|
||||
harness.layer,
|
||||
Logger.layer([logger], { mergeWithExisting: false }),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("recovers download state after an unexpected setup failure", () => {
|
||||
let disableDifferentialCalls = 0;
|
||||
const harness = makeHarness({
|
||||
setDisableDifferentialDownload: Effect.suspend(() => {
|
||||
disableDifferentialCalls += 1;
|
||||
return disableDifferentialCalls === 1
|
||||
? Effect.void
|
||||
: Effect.die(new Error("download setup failed"));
|
||||
}),
|
||||
});
|
||||
|
||||
return Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const updates = yield* DesktopUpdates.DesktopUpdates;
|
||||
yield* updates.configure;
|
||||
harness.emit("update-available", { version: "1.2.4" });
|
||||
yield* flushCallbacks;
|
||||
|
||||
const result = yield* updates.download;
|
||||
assert.isTrue(result.accepted);
|
||||
assert.isFalse(result.completed);
|
||||
|
||||
const failedState = yield* updates.getState;
|
||||
assert.equal(failedState.status, "available");
|
||||
assert.equal(failedState.errorContext, "download");
|
||||
assert.equal(failedState.message, "Desktop update download action failed unexpectedly.");
|
||||
|
||||
const changedState = yield* updates.setChannel("nightly");
|
||||
assert.equal(changedState.channel, "nightly");
|
||||
}),
|
||||
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
|
||||
});
|
||||
|
||||
it.effect("restores download state and permits retry after interruption", () =>
|
||||
Effect.gen(function* () {
|
||||
const actionStarted = yield* Deferred.make<void>();
|
||||
let disableDifferentialCalls = 0;
|
||||
const harness = makeHarness({
|
||||
setDisableDifferentialDownload: Effect.suspend(() => {
|
||||
disableDifferentialCalls += 1;
|
||||
if (disableDifferentialCalls === 1) {
|
||||
return Effect.void;
|
||||
}
|
||||
if (disableDifferentialCalls === 2) {
|
||||
return Deferred.succeed(actionStarted, undefined).pipe(Effect.andThen(Effect.never));
|
||||
}
|
||||
return Effect.void;
|
||||
}),
|
||||
});
|
||||
|
||||
yield* Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const updates = yield* DesktopUpdates.DesktopUpdates;
|
||||
yield* updates.configure;
|
||||
harness.emit("update-available", { version: "1.2.4" });
|
||||
yield* flushCallbacks;
|
||||
|
||||
const downloadFiber = yield* updates.download.pipe(Effect.forkScoped);
|
||||
yield* Deferred.await(actionStarted);
|
||||
yield* Fiber.interrupt(downloadFiber);
|
||||
|
||||
const interruptedState = yield* updates.getState;
|
||||
assert.equal(interruptedState.status, "available");
|
||||
assert.isNull(interruptedState.message);
|
||||
|
||||
const retry = yield* updates.download;
|
||||
assert.isTrue(retry.accepted);
|
||||
assert.isTrue(retry.completed);
|
||||
}),
|
||||
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("clears quitting state after an unexpected install setup failure", () => {
|
||||
const harness = makeHarness({
|
||||
stopBackend: Effect.die(new Error("backend stop failed")),
|
||||
});
|
||||
|
||||
return Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const desktopState = yield* DesktopState.DesktopState;
|
||||
const updates = yield* DesktopUpdates.DesktopUpdates;
|
||||
yield* updates.configure;
|
||||
harness.emit("update-downloaded", { version: "1.2.4" });
|
||||
yield* flushCallbacks;
|
||||
|
||||
const result = yield* updates.install;
|
||||
assert.isTrue(result.accepted);
|
||||
assert.isFalse(result.completed);
|
||||
assert.isFalse(yield* Ref.get(desktopState.quitting));
|
||||
|
||||
const failedState = yield* updates.getState;
|
||||
assert.equal(failedState.status, "downloaded");
|
||||
assert.equal(failedState.errorContext, "install");
|
||||
assert.equal(failedState.message, "Desktop update install action failed unexpectedly.");
|
||||
|
||||
const changedState = yield* updates.setChannel("nightly");
|
||||
assert.equal(changedState.channel, "nightly");
|
||||
}),
|
||||
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
|
||||
});
|
||||
|
||||
it.effect("persists channel changes through the settings service", () => {
|
||||
const harness = makeHarness();
|
||||
|
||||
@@ -512,7 +284,6 @@ describe("DesktopUpdates", () => {
|
||||
const error = Cause.squash(exit.cause);
|
||||
assert.instanceOf(error, DesktopUpdates.DesktopUpdateActionInProgressError);
|
||||
assert.equal(error.action, "check");
|
||||
assert.equal(error.requestedChannel, "nightly");
|
||||
}
|
||||
|
||||
yield* Deferred.succeed(releaseCheck, undefined);
|
||||
@@ -521,31 +292,4 @@ describe("DesktopUpdates", () => {
|
||||
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves settings failure context when an update channel cannot be persisted", () => {
|
||||
const diskFailure = new Error("disk exploded");
|
||||
const settingsFailure = new DesktopAppSettings.DesktopSettingsWriteError({
|
||||
operation: "replace-settings-file",
|
||||
path: "/tmp/settings.json",
|
||||
cause: diskFailure,
|
||||
});
|
||||
const harness = makeHarness({ setUpdateChannelError: settingsFailure });
|
||||
|
||||
return Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const updates = yield* DesktopUpdates.DesktopUpdates;
|
||||
yield* updates.configure;
|
||||
|
||||
const error = yield* updates.setChannel("nightly").pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, DesktopUpdates.DesktopUpdateChannelPersistenceError);
|
||||
assert.isTrue(DesktopUpdates.isDesktopUpdateSetChannelError(error));
|
||||
assert.equal(error.channel, "nightly");
|
||||
assert.strictEqual(error.cause, settingsFailure);
|
||||
assert.strictEqual(error.cause.cause, diskFailure);
|
||||
assert.equal(error.message, "Failed to persist the nightly desktop update channel.");
|
||||
assert.notInclude(error.message, diskFailure.message);
|
||||
}),
|
||||
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
|
||||
});
|
||||
});
|
||||
@@ -1,10 +1,9 @@
|
||||
import {
|
||||
DesktopUpdateChannelSchema,
|
||||
type DesktopRuntimeInfo,
|
||||
type DesktopUpdateActionResult,
|
||||
type DesktopUpdateChannel,
|
||||
type DesktopUpdateCheckResult,
|
||||
type DesktopUpdateState,
|
||||
import type {
|
||||
DesktopRuntimeInfo,
|
||||
DesktopUpdateActionResult,
|
||||
DesktopUpdateChannel,
|
||||
DesktopUpdateCheckResult,
|
||||
DesktopUpdateState,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Context from "effect/Context";
|
||||
@@ -64,82 +63,30 @@ export class DesktopUpdateActionInProgressError extends Schema.TaggedErrorClass<
|
||||
"DesktopUpdateActionInProgressError",
|
||||
{
|
||||
action: Schema.Literals(["check", "download", "install"]),
|
||||
requestedChannel: DesktopUpdateChannelSchema,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Cannot change the desktop update channel to ${this.requestedChannel} while an update ${this.action} action is in progress.`;
|
||||
return `Cannot change update tracks while an update ${this.action} action is in progress.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopUpdateChannelPersistenceError extends Schema.TaggedErrorClass<DesktopUpdateChannelPersistenceError>()(
|
||||
"DesktopUpdateChannelPersistenceError",
|
||||
export class DesktopUpdatePersistenceError extends Schema.TaggedErrorClass<DesktopUpdatePersistenceError>()(
|
||||
"DesktopUpdatePersistenceError",
|
||||
{
|
||||
channel: DesktopUpdateChannelSchema,
|
||||
cause: Schema.instanceOf(DesktopAppSettings.DesktopSettingsWriteError),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to persist the ${this.channel} desktop update channel.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopUpdatePollerError extends Schema.TaggedErrorClass<DesktopUpdatePollerError>()(
|
||||
"DesktopUpdatePollerError",
|
||||
{
|
||||
poller: Schema.Literals(["startup", "poll"]),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Desktop update ${this.poller} poller failed.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopUpdateEventHandlingError extends Schema.TaggedErrorClass<DesktopUpdateEventHandlingError>()(
|
||||
"DesktopUpdateEventHandlingError",
|
||||
{
|
||||
event: Schema.Literals(["update-available", "download-progress", "update-downloaded"]),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to handle desktop update ${this.event} event.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopUpdaterReportedError extends Schema.TaggedErrorClass<DesktopUpdaterReportedError>()(
|
||||
"DesktopUpdaterReportedError",
|
||||
{
|
||||
operation: Schema.Literals(["check", "download", "install", "background"]),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Desktop updater ${this.operation} operation reported an error.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopUpdateUnexpectedActionError extends Schema.TaggedErrorClass<DesktopUpdateUnexpectedActionError>()(
|
||||
"DesktopUpdateUnexpectedActionError",
|
||||
{
|
||||
action: Schema.Literals(["download", "install"]),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Desktop update ${this.action} action failed unexpectedly.`;
|
||||
const detail = this.cause instanceof Error ? this.cause.message : String(this.cause);
|
||||
return `Failed to persist desktop update settings: ${detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export type DesktopUpdateConfigureError = never;
|
||||
|
||||
export const DesktopUpdateSetChannelError = Schema.Union([
|
||||
DesktopUpdateActionInProgressError,
|
||||
DesktopUpdateChannelPersistenceError,
|
||||
]);
|
||||
export type DesktopUpdateSetChannelError = typeof DesktopUpdateSetChannelError.Type;
|
||||
export const isDesktopUpdateSetChannelError = Schema.is(DesktopUpdateSetChannelError);
|
||||
export type DesktopUpdateSetChannelError =
|
||||
| DesktopUpdateActionInProgressError
|
||||
| DesktopUpdatePersistenceError;
|
||||
|
||||
export class DesktopUpdates extends Context.Service<
|
||||
DesktopUpdates,
|
||||
@@ -361,21 +308,16 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
return yield* electronUpdater.checkForUpdates.pipe(
|
||||
Effect.as(true),
|
||||
Effect.catchTags({
|
||||
ElectronUpdaterCheckForUpdatesError: Effect.fn(
|
||||
"desktop.updates.handleCheckForUpdatesFailure",
|
||||
)(function* (error) {
|
||||
Effect.catch(
|
||||
Effect.fn("desktop.updates.handleCheckForUpdatesFailure")(function* (error) {
|
||||
const failedAt = yield* currentIsoTimestamp;
|
||||
yield* updateState((current) =>
|
||||
reduceDesktopUpdateStateOnCheckFailure(current, error.message, failedAt),
|
||||
);
|
||||
yield* logUpdaterError(error.message, {
|
||||
errorTag: error._tag,
|
||||
channel: error.channel,
|
||||
});
|
||||
yield* logUpdaterError("failed to check for updates", { message: error.message });
|
||||
return true;
|
||||
}),
|
||||
}),
|
||||
),
|
||||
Effect.ensuring(Ref.set(updateCheckInFlightRef, false)),
|
||||
);
|
||||
});
|
||||
@@ -400,50 +342,19 @@ export const make = Effect.gen(function* () {
|
||||
yield* electronUpdater.downloadUpdate;
|
||||
return { accepted: true, completed: true };
|
||||
}).pipe(
|
||||
Effect.catchTags({
|
||||
ElectronUpdaterDownloadUpdateError: Effect.fn("desktop.updates.handleDownloadFailure")(
|
||||
function* (error) {
|
||||
yield* updateState((current) =>
|
||||
reduceDesktopUpdateStateOnDownloadFailure(current, error.message),
|
||||
);
|
||||
yield* logUpdaterError(error.message, {
|
||||
errorTag: error._tag,
|
||||
channel: error.channel,
|
||||
});
|
||||
return { accepted: true, completed: false };
|
||||
},
|
||||
),
|
||||
}),
|
||||
Effect.onInterrupt(() =>
|
||||
updateState((current) => (current.status === "downloading" ? state : current)).pipe(
|
||||
Effect.asVoid,
|
||||
),
|
||||
),
|
||||
Effect.catchCause((cause) => {
|
||||
if (Cause.hasInterruptsOnly(cause)) {
|
||||
return Effect.failCause(cause);
|
||||
}
|
||||
const error = new DesktopUpdateUnexpectedActionError({ action: "download", cause });
|
||||
return Effect.gen(function* () {
|
||||
Effect.catch(
|
||||
Effect.fn("desktop.updates.handleDownloadFailure")(function* (error) {
|
||||
yield* updateState((current) =>
|
||||
reduceDesktopUpdateStateOnDownloadFailure(current, error.message),
|
||||
);
|
||||
yield* logUpdaterError(error.message, {
|
||||
errorTag: error._tag,
|
||||
action: error.action,
|
||||
});
|
||||
yield* logUpdaterError("failed to download update", { message: error.message });
|
||||
return { accepted: true, completed: false };
|
||||
});
|
||||
}),
|
||||
}),
|
||||
),
|
||||
Effect.ensuring(Ref.set(updateDownloadInFlightRef, false)),
|
||||
);
|
||||
}).pipe(Effect.withSpan("desktop.updates.downloadAvailableUpdate"));
|
||||
|
||||
const resetInstallAction = Effect.all(
|
||||
[Ref.set(updateInstallInFlightRef, false), Ref.set(desktopState.quitting, false)],
|
||||
{ discard: true },
|
||||
);
|
||||
|
||||
const installDownloadedUpdate = Effect.gen(function* () {
|
||||
const state = yield* Ref.get(updateStateRef);
|
||||
if (
|
||||
@@ -466,38 +377,14 @@ export const make = Effect.gen(function* () {
|
||||
});
|
||||
return { accepted: true, completed: false };
|
||||
}).pipe(
|
||||
Effect.catchTags({
|
||||
ElectronUpdaterQuitAndInstallError: Effect.fn("desktop.updates.handleInstallFailure")(
|
||||
function* (error) {
|
||||
yield* resetInstallAction;
|
||||
yield* updateState((current) =>
|
||||
reduceDesktopUpdateStateOnInstallFailure(current, error.message),
|
||||
);
|
||||
yield* logUpdaterError(error.message, {
|
||||
errorTag: error._tag,
|
||||
channel: error.channel,
|
||||
isSilent: error.isSilent,
|
||||
isForceRunAfter: error.isForceRunAfter,
|
||||
});
|
||||
return { accepted: true, completed: false };
|
||||
},
|
||||
),
|
||||
}),
|
||||
Effect.onInterrupt(() => resetInstallAction),
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.gen(function* () {
|
||||
if (Cause.hasInterruptsOnly(cause)) {
|
||||
return yield* Effect.failCause(cause);
|
||||
}
|
||||
yield* resetInstallAction;
|
||||
const error = new DesktopUpdateUnexpectedActionError({ action: "install", cause });
|
||||
Effect.catch(
|
||||
Effect.fn("desktop.updates.handleInstallFailure")(function* (error) {
|
||||
yield* Ref.set(updateInstallInFlightRef, false);
|
||||
yield* updateState((current) =>
|
||||
reduceDesktopUpdateStateOnInstallFailure(current, error.message),
|
||||
);
|
||||
yield* logUpdaterError(error.message, {
|
||||
errorTag: error._tag,
|
||||
action: error.action,
|
||||
});
|
||||
yield* Ref.set(desktopState.quitting, false);
|
||||
yield* logUpdaterError("failed to install update", { message: error.message });
|
||||
return { accepted: true, completed: false };
|
||||
}),
|
||||
),
|
||||
@@ -507,31 +394,17 @@ export const make = Effect.gen(function* () {
|
||||
const startUpdatePollers: Effect.Effect<void, never, Scope.Scope> = Effect.gen(function* () {
|
||||
yield* Effect.sleep(AUTO_UPDATE_STARTUP_DELAY).pipe(
|
||||
Effect.andThen(checkForUpdates("startup")),
|
||||
Effect.catchCause((cause) => {
|
||||
if (Cause.hasInterruptsOnly(cause)) {
|
||||
return Effect.void;
|
||||
}
|
||||
const error = new DesktopUpdatePollerError({ poller: "startup", cause });
|
||||
return logUpdaterError(error.message, {
|
||||
errorTag: error._tag,
|
||||
poller: error.poller,
|
||||
});
|
||||
}),
|
||||
Effect.catchCause((cause) =>
|
||||
logUpdaterError("startup update check failed", { cause: Cause.pretty(cause) }),
|
||||
),
|
||||
Effect.forkScoped,
|
||||
);
|
||||
yield* Effect.sleep(AUTO_UPDATE_POLL_INTERVAL).pipe(
|
||||
Effect.andThen(checkForUpdates("poll")),
|
||||
Effect.forever,
|
||||
Effect.catchCause((cause) => {
|
||||
if (Cause.hasInterruptsOnly(cause)) {
|
||||
return Effect.void;
|
||||
}
|
||||
const error = new DesktopUpdatePollerError({ poller: "poll", cause });
|
||||
return logUpdaterError(error.message, {
|
||||
errorTag: error._tag,
|
||||
poller: error.poller,
|
||||
});
|
||||
}),
|
||||
Effect.catchCause((cause) =>
|
||||
logUpdaterError("poll update check failed", { cause: Cause.pretty(cause) }),
|
||||
),
|
||||
Effect.forkScoped,
|
||||
);
|
||||
}).pipe(Effect.withSpan("desktop.updates.startPollers"));
|
||||
@@ -562,16 +435,11 @@ export const make = Effect.gen(function* () {
|
||||
yield* logUpdaterInfo("update available", { version: info.version });
|
||||
}),
|
||||
),
|
||||
Effect.catchCause((cause) => {
|
||||
if (Cause.hasInterruptsOnly(cause)) {
|
||||
return Effect.void;
|
||||
}
|
||||
const error = new DesktopUpdateEventHandlingError({ event: "update-available", cause });
|
||||
return logUpdaterWarning(error.message, {
|
||||
errorTag: error._tag,
|
||||
event: error.event,
|
||||
});
|
||||
}),
|
||||
Effect.catchCause((cause) =>
|
||||
logUpdaterWarning("ignored malformed update-available event", {
|
||||
cause: Cause.pretty(cause),
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -584,23 +452,14 @@ export const make = Effect.gen(function* () {
|
||||
}).pipe(Effect.withSpan("desktop.updates.handleUpdateNotAvailable"));
|
||||
|
||||
const handleUpdaterError = Effect.fn("desktop.updates.handleUpdaterError")(function* (
|
||||
cause: unknown,
|
||||
error: unknown,
|
||||
) {
|
||||
const activeAction = yield* activeUpdateAction;
|
||||
const error = new DesktopUpdaterReportedError({
|
||||
operation: Option.getOrElse(activeAction, () => "background" as const),
|
||||
cause,
|
||||
});
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
if (yield* Ref.get(updateInstallInFlightRef)) {
|
||||
yield* Ref.set(updateInstallInFlightRef, false);
|
||||
yield* Ref.set(desktopState.quitting, false);
|
||||
yield* updateState((current) =>
|
||||
reduceDesktopUpdateStateOnInstallFailure(current, error.message),
|
||||
);
|
||||
yield* logUpdaterError(error.message, {
|
||||
errorTag: error._tag,
|
||||
operation: error.operation,
|
||||
});
|
||||
yield* updateState((current) => reduceDesktopUpdateStateOnInstallFailure(current, message));
|
||||
yield* logUpdaterError("updater error", { message });
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -610,7 +469,7 @@ export const make = Effect.gen(function* () {
|
||||
yield* updateState((current) => ({
|
||||
...current,
|
||||
status: "error",
|
||||
message: error.message,
|
||||
message,
|
||||
checkedAt,
|
||||
downloadPercent: null,
|
||||
errorContext,
|
||||
@@ -618,10 +477,7 @@ export const make = Effect.gen(function* () {
|
||||
}));
|
||||
}
|
||||
|
||||
yield* logUpdaterError(error.message, {
|
||||
errorTag: error._tag,
|
||||
operation: error.operation,
|
||||
});
|
||||
yield* logUpdaterError("updater error", { message });
|
||||
});
|
||||
|
||||
const handleDownloadProgress = Effect.fn("desktop.updates.handleDownloadProgress")(function* (
|
||||
@@ -643,16 +499,11 @@ export const make = Effect.gen(function* () {
|
||||
}
|
||||
}),
|
||||
),
|
||||
Effect.catchCause((cause) => {
|
||||
if (Cause.hasInterruptsOnly(cause)) {
|
||||
return Effect.void;
|
||||
}
|
||||
const error = new DesktopUpdateEventHandlingError({ event: "download-progress", cause });
|
||||
return logUpdaterWarning(error.message, {
|
||||
errorTag: error._tag,
|
||||
event: error.event,
|
||||
});
|
||||
}),
|
||||
Effect.catchCause((cause) =>
|
||||
logUpdaterWarning("ignored malformed download-progress event", {
|
||||
cause: Cause.pretty(cause),
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -667,16 +518,11 @@ export const make = Effect.gen(function* () {
|
||||
yield* logUpdaterInfo("update downloaded", { version: info.version });
|
||||
}),
|
||||
),
|
||||
Effect.catchCause((cause) => {
|
||||
if (Cause.hasInterruptsOnly(cause)) {
|
||||
return Effect.void;
|
||||
}
|
||||
const error = new DesktopUpdateEventHandlingError({ event: "update-downloaded", cause });
|
||||
return logUpdaterWarning(error.message, {
|
||||
errorTag: error._tag,
|
||||
event: error.event,
|
||||
});
|
||||
}),
|
||||
Effect.catchCause((cause) =>
|
||||
logUpdaterWarning("ignored malformed update-downloaded event", {
|
||||
cause: Cause.pretty(cause),
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -752,10 +598,7 @@ export const make = Effect.gen(function* () {
|
||||
yield* Effect.annotateCurrentSpan({ channel: nextChannel });
|
||||
const activeAction = yield* activeUpdateAction;
|
||||
if (Option.isSome(activeAction)) {
|
||||
return yield* new DesktopUpdateActionInProgressError({
|
||||
action: activeAction.value,
|
||||
requestedChannel: nextChannel,
|
||||
});
|
||||
return yield* new DesktopUpdateActionInProgressError({ action: activeAction.value });
|
||||
}
|
||||
|
||||
const state = yield* Ref.get(updateStateRef);
|
||||
@@ -765,11 +608,7 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
yield* desktopSettings
|
||||
.setUpdateChannel(nextChannel)
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new DesktopUpdateChannelPersistenceError({ channel: nextChannel, cause }),
|
||||
),
|
||||
);
|
||||
.pipe(Effect.mapError((cause) => new DesktopUpdatePersistenceError({ cause })));
|
||||
|
||||
const enabled = yield* shouldEnableAutoUpdates;
|
||||
yield* setState(createBaseUpdateState(nextChannel, enabled, environment));
|
||||
|
||||
@@ -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<
|
||||
@@ -305,61 +277,7 @@ export const make = Effect.gen(function* () {
|
||||
event.preventDefault();
|
||||
window.setTitle(environment.displayName);
|
||||
});
|
||||
|
||||
let developmentLoadRetryIndex = 0;
|
||||
let developmentLoadRetryFiber: Fiber.Fiber<void, never> | undefined;
|
||||
const clearDevelopmentLoadRetry = () => {
|
||||
if (developmentLoadRetryFiber === undefined) {
|
||||
return;
|
||||
}
|
||||
const retryFiber = developmentLoadRetryFiber;
|
||||
developmentLoadRetryFiber = undefined;
|
||||
runFork(Fiber.interrupt(retryFiber));
|
||||
};
|
||||
const loadApplication = () => {
|
||||
if (window.isDestroyed()) {
|
||||
return;
|
||||
}
|
||||
void window.loadURL(applicationUrl).catch(() => undefined);
|
||||
};
|
||||
const scheduleDevelopmentLoadRetry = () => {
|
||||
if (developmentLoadRetryFiber !== undefined || window.isDestroyed()) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const retryIndex = Math.min(
|
||||
developmentLoadRetryIndex,
|
||||
DEVELOPMENT_LOAD_RETRY_DELAYS_MS.length - 1,
|
||||
);
|
||||
const retryInMs = DEVELOPMENT_LOAD_RETRY_DELAYS_MS[retryIndex] ?? 2_000;
|
||||
developmentLoadRetryIndex += 1;
|
||||
developmentLoadRetryFiber = runFork(
|
||||
Effect.sleep(retryInMs).pipe(
|
||||
Effect.andThen(
|
||||
Effect.sync(() => {
|
||||
developmentLoadRetryFiber = undefined;
|
||||
if (!window.isDestroyed()) {
|
||||
loadApplication();
|
||||
}
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
return retryInMs;
|
||||
};
|
||||
|
||||
window.webContents.on("did-finish-load", () => {
|
||||
if (
|
||||
environment.isDevelopment &&
|
||||
!isSameOriginRendererNavigation({
|
||||
applicationUrl,
|
||||
navigationUrl: window.webContents.getURL(),
|
||||
})
|
||||
) {
|
||||
return;
|
||||
}
|
||||
clearDevelopmentLoadRetry();
|
||||
developmentLoadRetryIndex = 0;
|
||||
window.setTitle(environment.displayName);
|
||||
});
|
||||
window.webContents.on(
|
||||
@@ -368,22 +286,11 @@ export const make = Effect.gen(function* () {
|
||||
if (!isMainFrame) {
|
||||
return;
|
||||
}
|
||||
const retryInMs =
|
||||
environment.isDevelopment &&
|
||||
isRetryableDevelopmentRendererLoadFailure({
|
||||
applicationUrl,
|
||||
errorCode,
|
||||
isMainFrame,
|
||||
validatedUrl: validatedURL,
|
||||
})
|
||||
? scheduleDevelopmentLoadRetry()
|
||||
: undefined;
|
||||
void runPromise(
|
||||
logWindowWarning("main window failed to load", {
|
||||
errorCode,
|
||||
errorDescription,
|
||||
url: validatedURL,
|
||||
...(retryInMs === undefined ? {} : { retryInMs }),
|
||||
}),
|
||||
);
|
||||
},
|
||||
@@ -405,13 +312,14 @@ export const make = Effect.gen(function* () {
|
||||
void runPromise(electronWindow.reveal(window));
|
||||
});
|
||||
|
||||
loadApplication();
|
||||
if (environment.isDevelopment) {
|
||||
void window.loadURL(applicationUrl);
|
||||
window.webContents.openDevTools({ mode: "detach" });
|
||||
} else {
|
||||
void window.loadURL(applicationUrl);
|
||||
}
|
||||
|
||||
window.on("closed", () => {
|
||||
clearDevelopmentLoadRetry();
|
||||
void runPromise(electronWindow.clearMain(Option.some(window)));
|
||||
});
|
||||
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -397,7 +397,7 @@ function CloudEnvironmentRowShell(props: {
|
||||
className={cn("text-xs leading-[16px] underline", statusClassName)}
|
||||
onLongPress={(event) => {
|
||||
event.stopPropagation();
|
||||
copyTextWithHaptic(errorTraceId, { target: "connection-trace-id" });
|
||||
copyTextWithHaptic(errorTraceId);
|
||||
}}
|
||||
onPress={(event) => {
|
||||
event.stopPropagation();
|
||||
@@ -441,7 +441,7 @@ function CopyTraceIdButton(props: { readonly traceId: string }) {
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
onPress={() => {
|
||||
copyTextWithHaptic(props.traceId, { target: "connection-trace-id" });
|
||||
copyTextWithHaptic(props.traceId);
|
||||
}}
|
||||
className="self-start flex-row items-center gap-1.5 rounded-full bg-subtle px-3 py-2 active:opacity-70"
|
||||
>
|
||||
|
||||
@@ -1,7 +1,4 @@
|
||||
import type { NotificationResponse } from "expo-notifications";
|
||||
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import { consumeLastAgentNotificationResponse } from "./notificationResponseConsumer";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
extractAgentNotificationDeepLink,
|
||||
@@ -21,76 +18,6 @@ function responseWithData(data: Record<string, unknown>, identifier = "notificat
|
||||
};
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe("consumeLastAgentNotificationResponse", () => {
|
||||
it("reports which initial-response operation failed", async () => {
|
||||
const cause = new Error("notification lookup unavailable");
|
||||
const consoleError = vi.spyOn(console, "error").mockImplementation(() => undefined);
|
||||
|
||||
await consumeLastAgentNotificationResponse({
|
||||
getLastResponse: () => Promise.reject(cause),
|
||||
clearLastResponse: () => Promise.resolve(),
|
||||
handleResponse: vi.fn(),
|
||||
});
|
||||
|
||||
expect(consoleError).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
_tag: "NotificationNavigationError",
|
||||
operation: "read",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("routes a response before reporting a clear failure", async () => {
|
||||
const cause = new Error("notification clear unavailable");
|
||||
const consoleError = vi.spyOn(console, "error").mockImplementation(() => undefined);
|
||||
const response = responseWithData({}, "notification-clear") as NotificationResponse;
|
||||
const handleResponse = vi.fn();
|
||||
|
||||
await consumeLastAgentNotificationResponse({
|
||||
getLastResponse: () => Promise.resolve(response),
|
||||
clearLastResponse: () => Promise.reject(cause),
|
||||
handleResponse,
|
||||
});
|
||||
|
||||
expect(handleResponse).toHaveBeenCalledWith(response);
|
||||
expect(consoleError).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
_tag: "NotificationNavigationError",
|
||||
operation: "clear",
|
||||
notificationId: "notification-clear",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("reports routing failures before clearing the response", async () => {
|
||||
const cause = new Error("notification routing unavailable");
|
||||
const consoleError = vi.spyOn(console, "error").mockImplementation(() => undefined);
|
||||
const response = responseWithData({}, "notification-route") as NotificationResponse;
|
||||
const clearLastResponse = vi.fn(() => Promise.resolve());
|
||||
|
||||
await consumeLastAgentNotificationResponse({
|
||||
getLastResponse: () => Promise.resolve(response),
|
||||
clearLastResponse,
|
||||
handleResponse: () => {
|
||||
throw cause;
|
||||
},
|
||||
});
|
||||
|
||||
expect(clearLastResponse).not.toHaveBeenCalled();
|
||||
expect(consoleError).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
_tag: "NotificationNavigationError",
|
||||
operation: "route",
|
||||
notificationId: "notification-route",
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("extractAgentNotificationDeepLink", () => {
|
||||
it("uses explicit deep links from APNs payload data", () => {
|
||||
expect(
|
||||
|
||||
@@ -3,7 +3,6 @@ import * as Notifications from "expo-notifications";
|
||||
import { useRouter } from "expo-router";
|
||||
|
||||
import { routeAgentNotificationResponseOnce } from "./notificationPayload";
|
||||
import { consumeLastAgentNotificationResponse } from "./notificationResponseConsumer";
|
||||
|
||||
export function useAgentNotificationNavigation(): void {
|
||||
const router = useRouter();
|
||||
@@ -19,11 +18,15 @@ export function useAgentNotificationNavigation(): void {
|
||||
};
|
||||
|
||||
const subscription = Notifications.addNotificationResponseReceivedListener(handleResponse);
|
||||
void consumeLastAgentNotificationResponse({
|
||||
getLastResponse: () => Notifications.getLastNotificationResponseAsync(),
|
||||
clearLastResponse: () => Notifications.clearLastNotificationResponseAsync(),
|
||||
handleResponse,
|
||||
});
|
||||
void Notifications.getLastNotificationResponseAsync()
|
||||
.then((response) => {
|
||||
if (response) {
|
||||
handleResponse(response);
|
||||
return Notifications.clearLastNotificationResponseAsync();
|
||||
}
|
||||
return undefined;
|
||||
})
|
||||
.catch(() => undefined);
|
||||
|
||||
return () => {
|
||||
subscription.remove();
|
||||
|
||||
@@ -1,58 +0,0 @@
|
||||
import type { NotificationResponse } from "expo-notifications";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
export class NotificationNavigationError extends Schema.TaggedErrorClass<NotificationNavigationError>()(
|
||||
"NotificationNavigationError",
|
||||
{
|
||||
operation: Schema.Literals(["read", "route", "clear"]),
|
||||
notificationId: Schema.optional(Schema.String),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to ${this.operation} the last notification response.`;
|
||||
}
|
||||
}
|
||||
|
||||
export async function consumeLastAgentNotificationResponse(input: {
|
||||
readonly getLastResponse: () => Promise<NotificationResponse | null>;
|
||||
readonly clearLastResponse: () => Promise<void>;
|
||||
readonly handleResponse: (response: NotificationResponse) => void;
|
||||
}): Promise<void> {
|
||||
let response: NotificationResponse | null;
|
||||
try {
|
||||
response = await input.getLastResponse();
|
||||
} catch (cause) {
|
||||
console.error(new NotificationNavigationError({ operation: "read", cause }));
|
||||
return;
|
||||
}
|
||||
|
||||
if (!response) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
input.handleResponse(response);
|
||||
} catch (cause) {
|
||||
console.error(
|
||||
new NotificationNavigationError({
|
||||
operation: "route",
|
||||
notificationId: response.notification.request.identifier,
|
||||
cause,
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await input.clearLastResponse();
|
||||
} catch (cause) {
|
||||
console.error(
|
||||
new NotificationNavigationError({
|
||||
operation: "clear",
|
||||
notificationId: response.notification.request.identifier,
|
||||
cause,
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -18,7 +18,6 @@ import { cryptoLayer } from "../cloud/dpop";
|
||||
import { managedRelayClientLayer } from "../cloud/managedRelayLayer";
|
||||
import { makeRelayDeviceRegistrationRequest } from "./registrationPayload";
|
||||
import {
|
||||
AgentAwarenessOperationError,
|
||||
__resetAgentAwarenessRemoteRegistrationForTest,
|
||||
refreshActiveLiveActivityRemoteRegistration,
|
||||
refreshAgentAwarenessRegistration,
|
||||
@@ -268,28 +267,6 @@ describe("makeRelayDeviceRegistrationRequest", () => {
|
||||
}).pipe(Effect.provide(relayTestLayer));
|
||||
});
|
||||
|
||||
it.effect("preserves Live Activity push-token lookup failures", () => {
|
||||
const cause = new Error("native token lookup failed");
|
||||
const activity = {
|
||||
getPushToken: vi.fn(() => Promise.reject(cause)),
|
||||
addPushTokenListener: vi.fn(),
|
||||
};
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const error = yield* Effect.flip(
|
||||
registerLiveActivityPushToken({ activity: activity as never }),
|
||||
);
|
||||
|
||||
expect(error).toBeInstanceOf(AgentAwarenessOperationError);
|
||||
expect(error).toMatchObject({
|
||||
_tag: "AgentAwarenessOperationError",
|
||||
operation: "read-live-activity-push-token",
|
||||
cause,
|
||||
message: "Agent awareness operation read-live-activity-push-token failed.",
|
||||
});
|
||||
}).pipe(Effect.provide(relayTestLayer));
|
||||
});
|
||||
|
||||
it.effect(
|
||||
"reports Live Activity token registration as skipped when relay auth is unavailable",
|
||||
() => {
|
||||
|
||||
@@ -2,7 +2,6 @@ import { addPushToStartTokenListener, type LiveActivity } from "expo-widgets";
|
||||
import Constants from "expo-constants";
|
||||
import * as Notifications from "expo-notifications";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { Platform } from "react-native";
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import {
|
||||
@@ -29,33 +28,6 @@ import { resolveCloudPublicConfig } from "../cloud/publicConfig";
|
||||
import { makeRelayDeviceRegistrationRequest } from "./registrationPayload";
|
||||
|
||||
const REMOTE_ACTIVITY_REGISTRATION_RETRY_MS = 15_000;
|
||||
|
||||
const AgentAwarenessOperation = Schema.Literals([
|
||||
"read-notification-permissions",
|
||||
"read-native-push-token",
|
||||
"read-device-registration-relay-token",
|
||||
"read-device-unregistration-relay-token",
|
||||
"read-live-activity-registration-relay-token",
|
||||
"load-device-registration-identifier",
|
||||
"load-device-registration-preferences",
|
||||
"load-device-unregistration-identifier",
|
||||
"read-live-activity-push-token",
|
||||
"load-live-activity-registration-identifier",
|
||||
"list-active-live-activities",
|
||||
]);
|
||||
|
||||
export class AgentAwarenessOperationError extends Schema.TaggedErrorClass<AgentAwarenessOperationError>()(
|
||||
"AgentAwarenessOperationError",
|
||||
{
|
||||
operation: AgentAwarenessOperation,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Agent awareness operation ${this.operation} failed.`;
|
||||
}
|
||||
}
|
||||
|
||||
const environmentConnections = new Map<EnvironmentId, SavedRemoteConnection>();
|
||||
const activityPushTokenListeners = new WeakSet<LiveActivity<AgentActivityProps>>();
|
||||
let pushToStartSubscription: { remove: () => void } | null = null;
|
||||
@@ -165,22 +137,14 @@ function nativePushTokenRegistration(observedPushToken?: string) {
|
||||
}
|
||||
const permissions = yield* Effect.tryPromise({
|
||||
try: () => Notifications.getPermissionsAsync(),
|
||||
catch: (cause) =>
|
||||
new AgentAwarenessOperationError({
|
||||
operation: "read-notification-permissions",
|
||||
cause,
|
||||
}),
|
||||
catch: (error) => error,
|
||||
});
|
||||
if (!permissions.granted) {
|
||||
return { notificationsEnabled: false, pushToken: null };
|
||||
}
|
||||
const token = yield* Effect.tryPromise({
|
||||
try: () => Notifications.getDevicePushTokenAsync(),
|
||||
catch: (cause) =>
|
||||
new AgentAwarenessOperationError({
|
||||
operation: "read-native-push-token",
|
||||
cause,
|
||||
}),
|
||||
catch: (error) => error,
|
||||
}).pipe(
|
||||
Effect.tapError((error) =>
|
||||
Effect.sync(() => {
|
||||
@@ -197,19 +161,16 @@ function nativePushTokenRegistration(observedPushToken?: string) {
|
||||
});
|
||||
}
|
||||
|
||||
const relayToken = (
|
||||
operation: "read-device-registration-relay-token" | "read-live-activity-registration-relay-token",
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const provider = relayTokenProvider;
|
||||
if (!provider) {
|
||||
return null;
|
||||
}
|
||||
return yield* Effect.tryPromise({
|
||||
try: provider,
|
||||
catch: (cause) => new AgentAwarenessOperationError({ operation, cause }),
|
||||
});
|
||||
const relayToken = Effect.gen(function* () {
|
||||
const provider = relayTokenProvider;
|
||||
if (!provider) {
|
||||
return null;
|
||||
}
|
||||
return yield* Effect.tryPromise({
|
||||
try: provider,
|
||||
catch: (error) => error,
|
||||
});
|
||||
});
|
||||
|
||||
function registerDeviceWithRelay(
|
||||
body: RelayDeviceRegistrationRequest,
|
||||
@@ -224,7 +185,7 @@ function registerDeviceWithRelay(
|
||||
return;
|
||||
}
|
||||
if (!readRelayConfig()) return;
|
||||
const token = yield* relayToken("read-device-registration-relay-token");
|
||||
const token = yield* relayToken;
|
||||
if (expectedGeneration !== deviceRegistrationGeneration) {
|
||||
logRegistrationDebug("device registration cancelled after auth lookup", {
|
||||
expectedGeneration,
|
||||
@@ -259,11 +220,7 @@ function unregisterDeviceWithRelay(input: {
|
||||
if (!readRelayConfig()) return;
|
||||
const token = yield* Effect.tryPromise({
|
||||
try: input.tokenProvider,
|
||||
catch: (cause) =>
|
||||
new AgentAwarenessOperationError({
|
||||
operation: "read-device-unregistration-relay-token",
|
||||
cause,
|
||||
}),
|
||||
catch: (error) => error,
|
||||
});
|
||||
if (!token) {
|
||||
logRegistrationDebug("relay device unregistration skipped; user is not signed in");
|
||||
@@ -283,7 +240,7 @@ function registerLiveActivityWithRelay(
|
||||
): Effect.Effect<boolean, unknown, ManagedRelay.ManagedRelayClient> {
|
||||
return Effect.gen(function* () {
|
||||
if (!readRelayConfig()) return false;
|
||||
const token = yield* relayToken("read-live-activity-registration-relay-token");
|
||||
const token = yield* relayToken;
|
||||
if (!token) {
|
||||
logRegistrationDebug("relay live activity registration skipped; user is not signed in");
|
||||
return false;
|
||||
@@ -424,19 +381,11 @@ function registerDevice(
|
||||
const [deviceId, preferences] = yield* Effect.all([
|
||||
Effect.tryPromise({
|
||||
try: () => loadOrCreateAgentAwarenessDeviceId(),
|
||||
catch: (cause) =>
|
||||
new AgentAwarenessOperationError({
|
||||
operation: "load-device-registration-identifier",
|
||||
cause,
|
||||
}),
|
||||
catch: (error) => error,
|
||||
}),
|
||||
Effect.tryPromise({
|
||||
try: () => loadPreferences(),
|
||||
catch: (cause) =>
|
||||
new AgentAwarenessOperationError({
|
||||
operation: "load-device-registration-preferences",
|
||||
cause,
|
||||
}),
|
||||
catch: (error) => error,
|
||||
}),
|
||||
]);
|
||||
const pushTokenRegistration = yield* nativePushTokenRegistration(input?.observedPushToken);
|
||||
@@ -570,11 +519,7 @@ export function unregisterAgentAwarenessDeviceForCurrentUser(
|
||||
return Effect.gen(function* () {
|
||||
const deviceId = yield* Effect.tryPromise({
|
||||
try: () => loadAgentAwarenessDeviceId(),
|
||||
catch: (cause) =>
|
||||
new AgentAwarenessOperationError({
|
||||
operation: "load-device-unregistration-identifier",
|
||||
cause,
|
||||
}),
|
||||
catch: (error) => error,
|
||||
});
|
||||
if (!deviceId) {
|
||||
return;
|
||||
@@ -599,11 +544,7 @@ export function registerLiveActivityPushToken(input: {
|
||||
|
||||
const activityPushToken = yield* Effect.tryPromise({
|
||||
try: () => input.activity.getPushToken(),
|
||||
catch: (cause) =>
|
||||
new AgentAwarenessOperationError({
|
||||
operation: "read-live-activity-push-token",
|
||||
cause,
|
||||
}),
|
||||
catch: (error) => error,
|
||||
});
|
||||
if (!activityPushToken) {
|
||||
if (activityPushTokenListeners.has(input.activity)) {
|
||||
@@ -651,11 +592,7 @@ function registerLiveActivityPushTokenValue(input: {
|
||||
return Effect.gen(function* () {
|
||||
const deviceId = yield* Effect.tryPromise({
|
||||
try: () => loadOrCreateAgentAwarenessDeviceId(),
|
||||
catch: (cause) =>
|
||||
new AgentAwarenessOperationError({
|
||||
operation: "load-live-activity-registration-identifier",
|
||||
cause,
|
||||
}),
|
||||
catch: (error) => error,
|
||||
});
|
||||
const registered = yield* registerLiveActivityWithRelay({
|
||||
deviceId,
|
||||
@@ -696,11 +633,7 @@ export function refreshActiveLiveActivityRemoteRegistration(): Effect.Effect<
|
||||
|
||||
const activities = yield* Effect.try({
|
||||
try: () => AgentActivity.getInstances(),
|
||||
catch: (cause) =>
|
||||
new AgentAwarenessOperationError({
|
||||
operation: "list-active-live-activities",
|
||||
cause,
|
||||
}),
|
||||
catch: (error) => error,
|
||||
}).pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.sync(() => {
|
||||
|
||||
@@ -4,7 +4,6 @@ import { useState } from "react";
|
||||
|
||||
import { MOBILE_TYPOGRAPHY } from "../../lib/typography";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { CloudWaitlistJoinRejectedError, joinCloudWaitlist } from "./cloudWaitlistJoin";
|
||||
|
||||
export function CloudWaitlistEnrollment(props: { readonly onSignIn: () => void }) {
|
||||
const { errors, fetchStatus, waitlist } = useWaitlist();
|
||||
@@ -22,14 +21,12 @@ export function CloudWaitlistEnrollment(props: { readonly onSignIn: () => void }
|
||||
|
||||
setRequestError(null);
|
||||
try {
|
||||
await joinCloudWaitlist(waitlist, normalizedEmailAddress);
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
setRequestError(
|
||||
error instanceof CloudWaitlistJoinRejectedError
|
||||
? "Could not join the waitlist. Check your email address and try again."
|
||||
: "Could not join the waitlist. Check your connection and try again.",
|
||||
);
|
||||
const { error } = await waitlist.join({ emailAddress: normalizedEmailAddress });
|
||||
if (error) {
|
||||
setRequestError("Could not join the waitlist. Check your email address and try again.");
|
||||
}
|
||||
} catch {
|
||||
setRequestError("Could not join the waitlist. Check your connection and try again.");
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -1,48 +0,0 @@
|
||||
import { describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
CloudWaitlistJoinRejectedError,
|
||||
CloudWaitlistJoinRequestError,
|
||||
joinCloudWaitlist,
|
||||
} from "./cloudWaitlistJoin";
|
||||
|
||||
describe("joinCloudWaitlist", () => {
|
||||
it("submits the provided email address", async () => {
|
||||
const join = vi.fn().mockResolvedValue({ error: null });
|
||||
|
||||
await joinCloudWaitlist({ join }, "[email protected]");
|
||||
|
||||
expect(join).toHaveBeenCalledExactlyOnceWith({ emailAddress: "[email protected]" });
|
||||
});
|
||||
|
||||
it("preserves Clerk rejection details without exposing the email address", async () => {
|
||||
const cause = Object.assign(new Error("The enrollment was rejected."), {
|
||||
code: "form_identifier_invalid",
|
||||
});
|
||||
const join = vi.fn().mockResolvedValue({ error: cause });
|
||||
|
||||
const failure = await joinCloudWaitlist({ join }, "[email protected]").catch(
|
||||
(error: unknown) => error,
|
||||
);
|
||||
|
||||
expect(failure).toBeInstanceOf(CloudWaitlistJoinRejectedError);
|
||||
expect(failure).toMatchObject({
|
||||
code: "form_identifier_invalid",
|
||||
cause,
|
||||
});
|
||||
expect(String(failure)).not.toContain("[email protected]");
|
||||
});
|
||||
|
||||
it("distinguishes request failures from rejected enrollments", async () => {
|
||||
const cause = new Error("network unavailable");
|
||||
const join = vi.fn().mockRejectedValue(cause);
|
||||
|
||||
const failure = await joinCloudWaitlist({ join }, "[email protected]").catch(
|
||||
(error: unknown) => error,
|
||||
);
|
||||
|
||||
expect(failure).toBeInstanceOf(CloudWaitlistJoinRequestError);
|
||||
expect(failure).toMatchObject({ cause });
|
||||
expect(failure).not.toBeInstanceOf(CloudWaitlistJoinRejectedError);
|
||||
});
|
||||
});
|
||||
@@ -1,46 +0,0 @@
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
interface CloudWaitlistJoiner {
|
||||
readonly join: (input: { emailAddress: string }) => Promise<{
|
||||
readonly error: { readonly code: string } | null;
|
||||
}>;
|
||||
}
|
||||
|
||||
export class CloudWaitlistJoinRejectedError extends Schema.TaggedErrorClass<CloudWaitlistJoinRejectedError>()(
|
||||
"CloudWaitlistJoinRejectedError",
|
||||
{
|
||||
code: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Cloud waitlist enrollment was rejected with code "${this.code}".`;
|
||||
}
|
||||
}
|
||||
|
||||
export class CloudWaitlistJoinRequestError extends Schema.TaggedErrorClass<CloudWaitlistJoinRequestError>()(
|
||||
"CloudWaitlistJoinRequestError",
|
||||
{
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Cloud waitlist enrollment request failed.";
|
||||
}
|
||||
}
|
||||
|
||||
export async function joinCloudWaitlist(
|
||||
waitlist: CloudWaitlistJoiner,
|
||||
emailAddress: string,
|
||||
): Promise<void> {
|
||||
const result = await waitlist.join({ emailAddress }).catch((cause) => {
|
||||
throw new CloudWaitlistJoinRequestError({ cause });
|
||||
});
|
||||
|
||||
if (result.error) {
|
||||
throw new CloudWaitlistJoinRejectedError({
|
||||
code: result.error.code,
|
||||
cause: result.error,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -835,7 +835,7 @@ describe("mobile cloud link environment client", () => {
|
||||
// @effect-diagnostics-next-line preferSchemaOverJson:off
|
||||
expect(JSON.parse(connectRequestBody)).toMatchObject({
|
||||
deviceId: "device-1",
|
||||
clientProofKeyThumbprint: "client-proof-key-thumbprint",
|
||||
clientKeyThumbprint: "client-proof-key-thumbprint",
|
||||
});
|
||||
expect(createProofMock).toHaveBeenCalledWith({
|
||||
method: "POST",
|
||||
|
||||
@@ -484,7 +484,6 @@ const connectRelayManagedEnvironment = Effect.fn("mobile.cloud.connectRelayManag
|
||||
scopes: [RelayEnvironmentConnectScope],
|
||||
environmentId: input.environmentId,
|
||||
deviceId,
|
||||
client: authClientMetadata(),
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
@@ -498,30 +497,21 @@ const connectRelayManagedEnvironment = Effect.fn("mobile.cloud.connectRelayManag
|
||||
message: "Relay returned credentials for a different environment.",
|
||||
});
|
||||
}
|
||||
if (!("credential" in connect)) {
|
||||
return yield* new CloudEnvironmentLinkError({
|
||||
message:
|
||||
connect.approvalStatus === "rejected"
|
||||
? "This device was rejected by the environment. Approve it in the environment settings to connect."
|
||||
: "Waiting for this device to be approved in the environment settings.",
|
||||
});
|
||||
}
|
||||
const authorizedConnect = connect;
|
||||
if (input.expectedEnvironment) {
|
||||
yield* ensureConnectEndpointMatchesEnvironment({
|
||||
environment: input.expectedEnvironment,
|
||||
connect: authorizedConnect,
|
||||
connect,
|
||||
});
|
||||
}
|
||||
|
||||
const descriptor = yield* fetchRemoteEnvironmentDescriptor({
|
||||
httpBaseUrl: authorizedConnect.endpoint.httpBaseUrl,
|
||||
httpBaseUrl: connect.endpoint.httpBaseUrl,
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
cloudEnvironmentLinkError("Could not fetch the connected environment descriptor."),
|
||||
),
|
||||
);
|
||||
if (descriptor.environmentId !== authorizedConnect.environmentId) {
|
||||
if (descriptor.environmentId !== connect.environmentId) {
|
||||
return yield* new CloudEnvironmentLinkError({
|
||||
message: "Connected endpoint descriptor does not match the selected environment.",
|
||||
});
|
||||
@@ -530,12 +520,12 @@ const connectRelayManagedEnvironment = Effect.fn("mobile.cloud.connectRelayManag
|
||||
const bootstrapDpop = yield* signer
|
||||
.createProof({
|
||||
method: "POST",
|
||||
url: new URL("/oauth/token", authorizedConnect.endpoint.httpBaseUrl).toString(),
|
||||
url: new URL("/oauth/token", connect.endpoint.httpBaseUrl).toString(),
|
||||
})
|
||||
.pipe(Effect.mapError(cloudEnvironmentLinkError("Could not create bootstrap DPoP proof.")));
|
||||
const bootstrap = yield* exchangeRemoteDpopAccessToken({
|
||||
httpBaseUrl: authorizedConnect.endpoint.httpBaseUrl,
|
||||
credential: authorizedConnect.credential,
|
||||
httpBaseUrl: connect.endpoint.httpBaseUrl,
|
||||
credential: connect.credential,
|
||||
dpopProof: bootstrapDpop,
|
||||
clientMetadata: authClientMetadata(),
|
||||
}).pipe(
|
||||
@@ -543,16 +533,16 @@ const connectRelayManagedEnvironment = Effect.fn("mobile.cloud.connectRelayManag
|
||||
cloudEnvironmentLinkError("Could not exchange a managed endpoint DPoP access token."),
|
||||
),
|
||||
);
|
||||
const pairingUrl = new URL(authorizedConnect.endpoint.httpBaseUrl);
|
||||
pairingUrl.hash = new URLSearchParams([["token", authorizedConnect.credential]]).toString();
|
||||
const pairingUrl = new URL(connect.endpoint.httpBaseUrl);
|
||||
pairingUrl.hash = new URLSearchParams([["token", connect.credential]]).toString();
|
||||
|
||||
return {
|
||||
environmentId: descriptor.environmentId,
|
||||
environmentLabel: descriptor.label,
|
||||
pairingUrl: stripPairingTokenFromUrl(pairingUrl).toString(),
|
||||
displayUrl: authorizedConnect.endpoint.httpBaseUrl,
|
||||
httpBaseUrl: authorizedConnect.endpoint.httpBaseUrl,
|
||||
wsBaseUrl: authorizedConnect.endpoint.wsBaseUrl,
|
||||
displayUrl: connect.endpoint.httpBaseUrl,
|
||||
httpBaseUrl: connect.endpoint.httpBaseUrl,
|
||||
wsBaseUrl: connect.endpoint.wsBaseUrl,
|
||||
bearerToken: null,
|
||||
authenticationMethod: "dpop",
|
||||
dpopAccessToken: bootstrap.access_token,
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Logger from "effect/Logger";
|
||||
import * as SecureStore from "expo-secure-store";
|
||||
import { vi } from "vite-plus/test";
|
||||
|
||||
const secureStore = vi.hoisted(() => new Map<string, string>());
|
||||
@@ -18,10 +16,7 @@ vi.mock("expo-secure-store", () => ({
|
||||
}),
|
||||
}));
|
||||
|
||||
import {
|
||||
ManagedRelayTokenStoreError,
|
||||
managedRelayAccessTokenStore,
|
||||
} from "./managedRelayTokenStore";
|
||||
import { managedRelayAccessTokenStore } from "./managedRelayTokenStore";
|
||||
|
||||
it.effect("round-trips and clears persisted managed relay access tokens", () =>
|
||||
Effect.gen(function* () {
|
||||
@@ -54,32 +49,3 @@ it.effect("falls back to an empty cache when persisted data is invalid", () =>
|
||||
expect(yield* managedRelayAccessTokenStore.load).toEqual([]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("logs structured storage failures before falling back to an empty cache", () => {
|
||||
const messages: Array<unknown> = [];
|
||||
const logger = Logger.make(({ message }) => {
|
||||
messages.push(message);
|
||||
});
|
||||
const cause = new Error("secure store unavailable");
|
||||
vi.mocked(SecureStore.getItemAsync).mockRejectedValueOnce(cause);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
expect(yield* managedRelayAccessTokenStore.load).toEqual([]);
|
||||
|
||||
const message = messages.find(
|
||||
(candidate) =>
|
||||
Array.isArray(candidate) && candidate[0] === "Managed relay token store operation failed.",
|
||||
);
|
||||
expect(message).toBeDefined();
|
||||
const context = (message as ReadonlyArray<unknown>)[1] as {
|
||||
readonly cause: ManagedRelayTokenStoreError;
|
||||
};
|
||||
expect(context.cause).toBeInstanceOf(ManagedRelayTokenStoreError);
|
||||
expect(context.cause).toMatchObject({
|
||||
operation: "read",
|
||||
storageKey: "t3code.cloud.relay-access-tokens",
|
||||
cause,
|
||||
});
|
||||
expect(context.cause.message).not.toContain(cause.message);
|
||||
}).pipe(Effect.provide(Logger.layer([logger], { mergeWithExisting: false })));
|
||||
});
|
||||
@@ -1,4 +1,5 @@
|
||||
import { ManagedRelay } from "@t3tools/client-runtime/relay";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as SecureStore from "expo-secure-store";
|
||||
@@ -30,50 +31,36 @@ const decodeManagedRelayAccessTokenCache = Schema.decodeUnknownEffect(
|
||||
);
|
||||
const encodeManagedRelayAccessTokenCache = Schema.encodeEffect(ManagedRelayAccessTokenCacheSchema);
|
||||
|
||||
export class ManagedRelayTokenStoreError extends Schema.TaggedErrorClass<ManagedRelayTokenStoreError>()(
|
||||
"ManagedRelayTokenStoreError",
|
||||
{
|
||||
operation: Schema.Literals(["read", "decode", "encode", "write", "clear"]),
|
||||
storageKey: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Managed relay token store operation "${this.operation}" failed for key "${this.storageKey}".`;
|
||||
}
|
||||
}
|
||||
export class ManagedRelayTokenStoreError extends Data.TaggedError("ManagedRelayTokenStoreError")<{
|
||||
readonly message: string;
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
|
||||
function logStoreFailure(error: ManagedRelayTokenStoreError) {
|
||||
return Effect.logWarning("Managed relay token store operation failed.", {
|
||||
errorTag: error._tag,
|
||||
operation: error.operation,
|
||||
storageKey: error.storageKey,
|
||||
cause: error,
|
||||
});
|
||||
const storeError =
|
||||
(message: string) =>
|
||||
(cause: unknown): ManagedRelayTokenStoreError =>
|
||||
new ManagedRelayTokenStoreError({ message, cause });
|
||||
|
||||
function logStoreFailure(operation: string) {
|
||||
return (error: ManagedRelayTokenStoreError) =>
|
||||
Effect.logWarning(`Managed relay token store ${operation} failed.`).pipe(
|
||||
Effect.annotateLogs({
|
||||
errorTag: error._tag,
|
||||
message: error.message,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const loadManagedRelayAccessTokens = Effect.tryPromise({
|
||||
try: () => SecureStore.getItemAsync(MANAGED_RELAY_TOKEN_CACHE_KEY),
|
||||
catch: (cause) =>
|
||||
new ManagedRelayTokenStoreError({
|
||||
operation: "read",
|
||||
storageKey: MANAGED_RELAY_TOKEN_CACHE_KEY,
|
||||
cause,
|
||||
}),
|
||||
catch: storeError("Could not read persisted relay access tokens."),
|
||||
}).pipe(
|
||||
Effect.flatMap((encoded) =>
|
||||
encoded === null
|
||||
? Effect.succeed<ReadonlyArray<ManagedRelay.ManagedRelayAccessTokenCacheEntry>>([])
|
||||
: decodeManagedRelayAccessTokenCache(encoded).pipe(
|
||||
Effect.map((cache) => cache.entries),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ManagedRelayTokenStoreError({
|
||||
operation: "decode",
|
||||
storageKey: MANAGED_RELAY_TOKEN_CACHE_KEY,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.mapError(storeError("Persisted relay access tokens are invalid.")),
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -85,48 +72,34 @@ const saveManagedRelayAccessTokens = (
|
||||
version: MANAGED_RELAY_TOKEN_CACHE_VERSION,
|
||||
entries,
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ManagedRelayTokenStoreError({
|
||||
operation: "encode",
|
||||
storageKey: MANAGED_RELAY_TOKEN_CACHE_KEY,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.mapError(storeError("Could not encode relay access tokens.")),
|
||||
Effect.flatMap((encoded) =>
|
||||
Effect.tryPromise({
|
||||
try: () => SecureStore.setItemAsync(MANAGED_RELAY_TOKEN_CACHE_KEY, encoded),
|
||||
catch: (cause) =>
|
||||
new ManagedRelayTokenStoreError({
|
||||
operation: "write",
|
||||
storageKey: MANAGED_RELAY_TOKEN_CACHE_KEY,
|
||||
cause,
|
||||
}),
|
||||
catch: storeError("Could not persist relay access tokens."),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const clearManagedRelayAccessTokens = Effect.tryPromise({
|
||||
try: () => SecureStore.deleteItemAsync(MANAGED_RELAY_TOKEN_CACHE_KEY),
|
||||
catch: (cause) =>
|
||||
new ManagedRelayTokenStoreError({
|
||||
operation: "clear",
|
||||
storageKey: MANAGED_RELAY_TOKEN_CACHE_KEY,
|
||||
cause,
|
||||
}),
|
||||
catch: storeError("Could not clear persisted relay access tokens."),
|
||||
});
|
||||
|
||||
export const managedRelayAccessTokenStore: ManagedRelay.ManagedRelayAccessTokenStore = {
|
||||
load: loadManagedRelayAccessTokens.pipe(
|
||||
Effect.tapError(logStoreFailure),
|
||||
Effect.tapError(logStoreFailure("load")),
|
||||
Effect.orElseSucceed(() => []),
|
||||
Effect.withSpan("mobile.managedRelayTokenStore.load"),
|
||||
),
|
||||
save: Effect.fn("mobile.managedRelayTokenStore.save")((entries) =>
|
||||
saveManagedRelayAccessTokens(entries).pipe(Effect.tapError(logStoreFailure), Effect.ignore),
|
||||
saveManagedRelayAccessTokens(entries).pipe(
|
||||
Effect.tapError(logStoreFailure("save")),
|
||||
Effect.ignore,
|
||||
),
|
||||
),
|
||||
clear: clearManagedRelayAccessTokens.pipe(
|
||||
Effect.tapError(logStoreFailure),
|
||||
Effect.tapError(logStoreFailure("clear")),
|
||||
Effect.ignore,
|
||||
Effect.withSpan("mobile.managedRelayTokenStore.clear"),
|
||||
),
|
||||
|
||||
@@ -101,7 +101,7 @@ export function ConnectionEnvironmentRow(props: {
|
||||
className="underline"
|
||||
onLongPress={(event) => {
|
||||
event.stopPropagation();
|
||||
copyTextWithHaptic(statusTraceId, { target: "connection-trace-id" });
|
||||
copyTextWithHaptic(statusTraceId);
|
||||
}}
|
||||
onPress={(event) => {
|
||||
event.stopPropagation();
|
||||
|
||||
@@ -85,11 +85,7 @@ export function EnvironmentConnectionNotice(props: {
|
||||
accessibilityHint="Copies the trace ID"
|
||||
accessibilityRole="button"
|
||||
className="underline decoration-dotted"
|
||||
onPress={() =>
|
||||
copyTextWithHaptic(props.connection.traceId!, {
|
||||
target: "connection-trace-id",
|
||||
})
|
||||
}
|
||||
onPress={() => copyTextWithHaptic(props.connection.traceId!)}
|
||||
>
|
||||
{props.connection.traceId}
|
||||
</Text>
|
||||
|
||||
@@ -8,7 +8,6 @@ import jsxLanguage from "@shikijs/langs/jsx";
|
||||
import tsxLanguage from "@shikijs/langs/tsx";
|
||||
import typescriptLanguage from "@shikijs/langs/typescript";
|
||||
import yamlLanguage from "@shikijs/langs/yaml";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import type { NativeReviewDiffFile, NativeReviewDiffLanguage } from "./nativeReviewDiffTypes";
|
||||
import type { NativeReviewDiffRow, NativeReviewDiffToken } from "./nativeReviewDiffSurface";
|
||||
@@ -16,32 +15,6 @@ import type { NativeReviewDiffRow, NativeReviewDiffToken } from "./nativeReviewD
|
||||
export type NativeReviewDiffHighlightScheme = "light" | "dark";
|
||||
export type NativeReviewDiffHighlightEngine = "native" | "javascript";
|
||||
|
||||
export class NativeReviewDiffHighlighterUnavailableError extends Schema.TaggedErrorClass<NativeReviewDiffHighlighterUnavailableError>()(
|
||||
"NativeReviewDiffHighlighterUnavailableError",
|
||||
{},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "The native review diff highlighter is unavailable in this build.";
|
||||
}
|
||||
}
|
||||
|
||||
export const isNativeReviewDiffHighlighterUnavailableError = Schema.is(
|
||||
NativeReviewDiffHighlighterUnavailableError,
|
||||
);
|
||||
|
||||
export class NativeReviewDiffHighlighterInitializationError extends Schema.TaggedErrorClass<NativeReviewDiffHighlighterInitializationError>()(
|
||||
"NativeReviewDiffHighlighterInitializationError",
|
||||
{
|
||||
requestedEngine: Schema.Literals(["native", "javascript"]),
|
||||
attemptedEngine: Schema.Literals(["native", "javascript"]),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to initialize the ${this.attemptedEngine} review diff highlighter requested as ${this.requestedEngine}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export interface NativeReviewDiffHighlighterHandle {
|
||||
readonly engine: NativeReviewDiffHighlightEngine;
|
||||
readonly tokenize: (
|
||||
@@ -224,7 +197,7 @@ function normalizeTokens(
|
||||
async function createNativeReviewDiffHighlighter(): Promise<NativeReviewDiffHighlighterHandle> {
|
||||
const nativeEngineModule = await import("react-native-shiki-engine");
|
||||
if (!nativeEngineModule.isNativeEngineAvailable()) {
|
||||
throw new NativeReviewDiffHighlighterUnavailableError();
|
||||
throw new Error("Native Shiki engine is not available in this build.");
|
||||
}
|
||||
|
||||
const highlighter = await createHighlighterCore({
|
||||
@@ -256,52 +229,18 @@ export async function getNativeReviewDiffHighlighter(
|
||||
engine: NativeReviewDiffHighlightEngine = "native",
|
||||
): Promise<NativeReviewDiffHighlighterHandle> {
|
||||
if (engine === "javascript") {
|
||||
try {
|
||||
javascriptHighlighterPromise ??= createJavascriptReviewDiffHighlighter();
|
||||
return await javascriptHighlighterPromise;
|
||||
} catch (cause) {
|
||||
javascriptHighlighterPromise = null;
|
||||
throw new NativeReviewDiffHighlighterInitializationError({
|
||||
requestedEngine: engine,
|
||||
attemptedEngine: "javascript",
|
||||
cause,
|
||||
});
|
||||
}
|
||||
javascriptHighlighterPromise ??= createJavascriptReviewDiffHighlighter();
|
||||
return javascriptHighlighterPromise;
|
||||
}
|
||||
|
||||
nativeHighlighterPromise ??= createNativeReviewDiffHighlighter()
|
||||
.catch(async (cause: unknown) => {
|
||||
const nativeError = isNativeReviewDiffHighlighterUnavailableError(cause)
|
||||
? cause
|
||||
: new NativeReviewDiffHighlighterInitializationError({
|
||||
requestedEngine: engine,
|
||||
attemptedEngine: "native",
|
||||
cause,
|
||||
});
|
||||
console.warn("[debug-native-diff] native highlighter unavailable", {
|
||||
error: nativeError,
|
||||
});
|
||||
try {
|
||||
javascriptHighlighterPromise ??= createJavascriptReviewDiffHighlighter();
|
||||
return await javascriptHighlighterPromise;
|
||||
} catch (fallbackCause) {
|
||||
javascriptHighlighterPromise = null;
|
||||
throw new NativeReviewDiffHighlighterInitializationError({
|
||||
requestedEngine: engine,
|
||||
attemptedEngine: "javascript",
|
||||
cause: new AggregateError(
|
||||
[nativeError, fallbackCause],
|
||||
"Native and JavaScript review diff highlighter initialization failed.",
|
||||
{ cause: nativeError },
|
||||
),
|
||||
});
|
||||
}
|
||||
})
|
||||
.catch((error) => {
|
||||
nativeHighlighterPromise = null;
|
||||
throw error;
|
||||
nativeHighlighterPromise ??= createNativeReviewDiffHighlighter().catch((error: unknown) => {
|
||||
console.warn("[debug-native-diff] native highlighter unavailable", {
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
return await nativeHighlighterPromise;
|
||||
javascriptHighlighterPromise ??= createJavascriptReviewDiffHighlighter();
|
||||
return javascriptHighlighterPromise;
|
||||
});
|
||||
return nativeHighlighterPromise;
|
||||
}
|
||||
|
||||
function isHighlightableLineRow(row: NativeReviewDiffRow): row is NativeReviewDiffLineRow {
|
||||
|
||||
@@ -53,12 +53,11 @@ it("initializes review highlighter state once", async () => {
|
||||
});
|
||||
|
||||
it("stores initialization failures in atom state", async () => {
|
||||
const cause = new Error("load failed");
|
||||
const manager = createReviewHighlighterManager({
|
||||
getRegistry: () => registry,
|
||||
loader: {
|
||||
prepare: async () => {
|
||||
throw cause;
|
||||
throw new Error("load failed");
|
||||
},
|
||||
prepareLanguages: async () => undefined,
|
||||
getEngine: async () => "javascript",
|
||||
@@ -68,23 +67,9 @@ it("stores initialization failures in atom state", async () => {
|
||||
void manager.initialize();
|
||||
await flushAsyncWork();
|
||||
|
||||
const snapshot = manager.getSnapshot();
|
||||
assert.strictEqual(snapshot.engine, null);
|
||||
assert.strictEqual(snapshot.status, "error");
|
||||
assert.strictEqual(snapshot.error?._tag, "ReviewHighlighterManagerError");
|
||||
assert.strictEqual(snapshot.error?.operation, "prepare");
|
||||
assert.deepStrictEqual(snapshot.error?.languages, [
|
||||
"typescript",
|
||||
"tsx",
|
||||
"javascript",
|
||||
"jsx",
|
||||
"json",
|
||||
"yaml",
|
||||
"bash",
|
||||
]);
|
||||
assert.strictEqual(snapshot.error?.cause, cause);
|
||||
assert.strictEqual(
|
||||
snapshot.error?.message,
|
||||
"Review highlighter operation prepare failed for languages typescript, tsx, javascript, jsx, json, yaml, bash.",
|
||||
);
|
||||
assert.deepStrictEqual(manager.getSnapshot(), {
|
||||
engine: null,
|
||||
error: "load failed",
|
||||
status: "error",
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,4 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { Atom, type AtomRegistry } from "effect/unstable/reactivity";
|
||||
import { useEffect } from "react";
|
||||
|
||||
@@ -13,22 +12,9 @@ import {
|
||||
|
||||
export type ReviewHighlighterStatus = "idle" | "initializing" | "ready" | "error";
|
||||
|
||||
export class ReviewHighlighterManagerError extends Schema.TaggedErrorClass<ReviewHighlighterManagerError>()(
|
||||
"ReviewHighlighterManagerError",
|
||||
{
|
||||
operation: Schema.Literals(["prepare", "prepare-languages", "resolve-engine"]),
|
||||
languages: Schema.Array(Schema.String),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Review highlighter operation ${this.operation} failed for languages ${this.languages.join(", ")}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export interface ReviewHighlighterState {
|
||||
readonly engine: ReviewHighlighterEngine | null;
|
||||
readonly error: ReviewHighlighterManagerError | null;
|
||||
readonly error: string | null;
|
||||
readonly status: ReviewHighlighterStatus;
|
||||
}
|
||||
|
||||
@@ -115,35 +101,24 @@ export function createReviewHighlighterManager(config: {
|
||||
|
||||
inFlight = (async () => {
|
||||
const startedAt = performance.now();
|
||||
const languages = config.languages ?? REVIEW_INITIAL_LANGUAGES;
|
||||
let operation: ReviewHighlighterManagerError["operation"] = "prepare";
|
||||
let engine: ReviewHighlighterEngine;
|
||||
try {
|
||||
await config.loader.prepare();
|
||||
operation = "prepare-languages";
|
||||
await config.loader.prepareLanguages(languages);
|
||||
operation = "resolve-engine";
|
||||
engine = await config.loader.getEngine();
|
||||
} catch (cause) {
|
||||
const error = new ReviewHighlighterManagerError({
|
||||
operation,
|
||||
languages,
|
||||
cause,
|
||||
await config.loader.prepareLanguages(config.languages ?? REVIEW_INITIAL_LANGUAGES);
|
||||
const engine = await config.loader.getEngine();
|
||||
const durationMs = Math.round(performance.now() - startedAt);
|
||||
logReviewHighlighterProviderDiagnostic("initialized", {
|
||||
durationMs,
|
||||
engine,
|
||||
});
|
||||
logReviewHighlighterProviderDiagnostic("initialization failed", { error });
|
||||
setState({ engine: null, error, status: "error" });
|
||||
return;
|
||||
setState({ engine, error: null, status: "ready" });
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
logReviewHighlighterProviderDiagnostic("initialization failed", { error: message });
|
||||
setState({ engine: null, error: message, status: "error" });
|
||||
} finally {
|
||||
inFlight = null;
|
||||
}
|
||||
|
||||
const durationMs = Math.round(performance.now() - startedAt);
|
||||
logReviewHighlighterProviderDiagnostic("initialized", {
|
||||
durationMs,
|
||||
engine,
|
||||
});
|
||||
setState({ engine, error: null, status: "ready" });
|
||||
})().finally(() => {
|
||||
inFlight = null;
|
||||
});
|
||||
})();
|
||||
|
||||
return inFlight;
|
||||
}
|
||||
|
||||
@@ -10,7 +10,6 @@ import yamlLanguage from "@shikijs/langs/yaml";
|
||||
import githubDarkDefault from "@shikijs/themes/github-dark-default";
|
||||
import githubLightDefault from "@shikijs/themes/github-light-default";
|
||||
import { getFiletypeFromFileName } from "@pierre/diffs/utils/getFiletypeFromFileName";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import {
|
||||
resolveReviewHighlighterEngine,
|
||||
@@ -23,19 +22,6 @@ import { applyDiffRangesToTokens, computeWordAltDiffRanges } from "./reviewWordD
|
||||
export type ReviewDiffTheme = "light" | "dark";
|
||||
export type { ReviewHighlighterEngine };
|
||||
|
||||
export class ReviewHighlighterEngineInitializationError extends Schema.TaggedErrorClass<ReviewHighlighterEngineInitializationError>()(
|
||||
"ReviewHighlighterEngineInitializationError",
|
||||
{
|
||||
preferredEngine: Schema.Literals(["native", "javascript"]),
|
||||
attemptedEngine: Schema.Literals(["native", "javascript"]),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to initialize the ${this.attemptedEngine} review highlighter with ${this.preferredEngine} preferred.`;
|
||||
}
|
||||
}
|
||||
|
||||
export interface ReviewHighlightedToken {
|
||||
content: string;
|
||||
readonly color: string | null;
|
||||
@@ -241,6 +227,16 @@ function logReviewHighlighterDiagnosticError(message: string, error: unknown): v
|
||||
if (!isReviewHighlighterDebugLoggingEnabled()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (error instanceof Error) {
|
||||
console.error(`[review-highlighter] ${message}`, {
|
||||
name: error.name,
|
||||
message: error.message,
|
||||
stack: error.stack,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
console.error(`[review-highlighter] ${message}`, error);
|
||||
}
|
||||
|
||||
@@ -262,7 +258,6 @@ async function getHighlighter(): Promise<HighlighterCore> {
|
||||
if (!highlighterPromise) {
|
||||
const configuredHighlighterPromise = (async () => {
|
||||
let nativeEngineAvailable = false;
|
||||
let nativeInitializationError: ReviewHighlighterEngineInitializationError | undefined;
|
||||
|
||||
logReviewHighlighterDiagnostic("initializing", {
|
||||
configuredPreference: REVIEW_HIGHLIGHTER_ENGINE_ENV_VALUE,
|
||||
@@ -294,14 +289,9 @@ async function getHighlighter(): Promise<HighlighterCore> {
|
||||
};
|
||||
}
|
||||
} catch (error) {
|
||||
nativeInitializationError = new ReviewHighlighterEngineInitializationError({
|
||||
preferredEngine: REVIEW_HIGHLIGHTER_ENGINE_PREFERENCE,
|
||||
attemptedEngine: "native",
|
||||
cause: error,
|
||||
});
|
||||
logReviewHighlighterDiagnosticError(
|
||||
"native engine initialization failed; falling back to javascript",
|
||||
nativeInitializationError,
|
||||
error,
|
||||
);
|
||||
nativeEngineAvailable = false;
|
||||
}
|
||||
@@ -315,30 +305,11 @@ async function getHighlighter(): Promise<HighlighterCore> {
|
||||
REVIEW_HIGHLIGHTER_ENGINE_PREFERENCE,
|
||||
nativeEngineAvailable,
|
||||
);
|
||||
let highlighter: HighlighterCore;
|
||||
try {
|
||||
highlighter = await createHighlighterCore({
|
||||
themes,
|
||||
langs: REVIEW_INITIAL_LANGUAGE_MODULES,
|
||||
engine: createJavaScriptRegexEngine(),
|
||||
});
|
||||
} catch (cause) {
|
||||
const javascriptError = new ReviewHighlighterEngineInitializationError({
|
||||
preferredEngine: REVIEW_HIGHLIGHTER_ENGINE_PREFERENCE,
|
||||
attemptedEngine: "javascript",
|
||||
cause,
|
||||
});
|
||||
if (!nativeInitializationError) throw javascriptError;
|
||||
throw new ReviewHighlighterEngineInitializationError({
|
||||
preferredEngine: REVIEW_HIGHLIGHTER_ENGINE_PREFERENCE,
|
||||
attemptedEngine: "javascript",
|
||||
cause: new AggregateError(
|
||||
[nativeInitializationError, javascriptError],
|
||||
"Native and JavaScript review highlighter initialization failed.",
|
||||
{ cause: nativeInitializationError },
|
||||
),
|
||||
});
|
||||
}
|
||||
const highlighter = await createHighlighterCore({
|
||||
themes,
|
||||
langs: REVIEW_INITIAL_LANGUAGE_MODULES,
|
||||
engine: createJavaScriptRegexEngine(),
|
||||
});
|
||||
logReviewHighlighterDiagnostic("using javascript engine", {
|
||||
resolvedEngine: engine,
|
||||
});
|
||||
|
||||
@@ -108,11 +108,7 @@ export function useNativeReviewDiffHighlighting(input: {
|
||||
} catch (error) {
|
||||
if (!abortController.signal.aborted) {
|
||||
logReviewDiffDiagnostic("native visible highlight failed", {
|
||||
error,
|
||||
resetKey,
|
||||
scheme,
|
||||
firstRowIndex: requestRange.firstRowIndex,
|
||||
lastRowIndex: requestRange.lastRowIndex,
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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,11 @@
|
||||
import * as Clipboard from "expo-clipboard";
|
||||
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 +16,8 @@ import {
|
||||
ActivityIndicator,
|
||||
Image,
|
||||
Linking,
|
||||
type NativeScrollEvent,
|
||||
type NativeSyntheticEvent,
|
||||
Pressable,
|
||||
ScrollView,
|
||||
StyleSheet,
|
||||
@@ -37,9 +30,7 @@ import {
|
||||
import { TouchableOpacity } from "react-native-gesture-handler";
|
||||
import ImageViewing from "react-native-image-viewing";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import type { SharedValue } from "react-native-reanimated";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
|
||||
import {
|
||||
hasNativeSelectableMarkdownText,
|
||||
SelectableMarkdownText,
|
||||
@@ -73,11 +64,14 @@ import {
|
||||
type ThreadFeedEntry,
|
||||
type ThreadFeedLatestTurn,
|
||||
} from "../../lib/threadActivity";
|
||||
import { isThreadFeedNearEnd } from "../../lib/threadFeedLayout";
|
||||
import { relativeTime } from "../../lib/time";
|
||||
import type { ThreadContentPresentation } from "./threadContentPresentation";
|
||||
import { ThreadWorkGroupToggle, ThreadWorkLog } from "./thread-work-log";
|
||||
import { ThreadWorkLog } from "./thread-work-log";
|
||||
import { useAssetUrl } from "../../state/assets";
|
||||
import { resolveWorkspaceRelativeFilePath } from "../files/filePath";
|
||||
|
||||
const THREAD_FEED_END_THRESHOLD = 80;
|
||||
const MESSAGE_TIME_FORMATTER = new Intl.DateTimeFormat(undefined, {
|
||||
hour: "numeric",
|
||||
minute: "2-digit",
|
||||
@@ -99,13 +93,10 @@ export interface ThreadFeedProps {
|
||||
readonly contentPresentation: ThreadContentPresentation;
|
||||
readonly agentLabel: string;
|
||||
readonly latestTurn: ThreadFeedLatestTurn | null;
|
||||
readonly listRef: RefObject<LegendListRef | null>;
|
||||
readonly freeze: SharedValue<boolean>;
|
||||
readonly anchorMessageId: MessageId | null;
|
||||
readonly contentInsetEndAdjustment: SharedValue<number>;
|
||||
readonly contentTopInset?: number;
|
||||
readonly contentBottomInset?: number;
|
||||
readonly layoutVariant?: LayoutVariant;
|
||||
readonly composerExpanded?: boolean;
|
||||
readonly skills?: ReadonlyArray<SelectableMarkdownSkill>;
|
||||
}
|
||||
|
||||
@@ -655,6 +646,7 @@ function renderFeedEntry(
|
||||
info: { item: ThreadFeedEntry; index: number },
|
||||
props: Pick<ThreadFeedProps, "environmentId" | "skills"> & {
|
||||
readonly copiedRowId: string | null;
|
||||
readonly expandedWorkGroups: Record<string, boolean>;
|
||||
readonly expandedWorkRows: Record<string, boolean>;
|
||||
readonly terminalAssistantMessageIds: ReadonlySet<string>;
|
||||
readonly unsettledTurnId: TurnId | null;
|
||||
@@ -697,18 +689,6 @@ function renderFeedEntry(
|
||||
);
|
||||
}
|
||||
|
||||
if (entry.type === "work-toggle") {
|
||||
return (
|
||||
<ThreadWorkGroupToggle
|
||||
expanded={entry.expanded}
|
||||
hiddenCount={entry.hiddenCount}
|
||||
iconSubtleColor={iconSubtleColor}
|
||||
onlyToolActivities={entry.onlyToolActivities}
|
||||
onToggle={() => props.onToggleWorkGroup(entry.groupId)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (entry.type === "message") {
|
||||
const { message } = entry;
|
||||
const isUser = message.role === "user";
|
||||
@@ -832,13 +812,39 @@ function renderFeedEntry(
|
||||
);
|
||||
}
|
||||
|
||||
if (entry.type === "queued-message") {
|
||||
return (
|
||||
<View className="mb-5 items-end">
|
||||
<View
|
||||
className="max-w-[85%] gap-2 rounded-[22px] rounded-br-[6px] px-3.5 py-2.5 opacity-60"
|
||||
style={{ backgroundColor: userBubbleColor }}
|
||||
>
|
||||
<Text className="font-sans text-base leading-[22px] text-white">
|
||||
{entry.queuedMessage.text}
|
||||
</Text>
|
||||
{entry.queuedMessage.attachments.length > 0 ? (
|
||||
<Text className="font-t3-medium text-xs text-white/75">
|
||||
{entry.queuedMessage.attachments.length} image
|
||||
{entry.queuedMessage.attachments.length === 1 ? "" : "s"} attached
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
<Text className="mt-1.5 px-1 text-right font-t3-medium text-xs text-neutral-600 dark:text-neutral-400">
|
||||
{entry.sending ? "dispatching" : `${relativeTime(entry.createdAt)} • pending`}
|
||||
</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<ThreadWorkLog
|
||||
activities={entry.activities}
|
||||
copiedRowId={props.copiedRowId}
|
||||
expanded={props.expandedWorkGroups[entry.id] ?? false}
|
||||
expandedRows={props.expandedWorkRows}
|
||||
iconSubtleColor={iconSubtleColor}
|
||||
onCopyRow={props.onCopyWorkRow}
|
||||
onToggleGroup={() => props.onToggleWorkGroup(entry.id)}
|
||||
onToggleRow={props.onToggleWorkRow}
|
||||
/>
|
||||
);
|
||||
@@ -1116,13 +1122,17 @@ function ThreadFeedPlaceholder(props: {
|
||||
|
||||
export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
const router = useRouter();
|
||||
const listRef = useRef<LegendListRef>(null);
|
||||
const copyFeedbackTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const scrollFrameRef = useRef<number | null>(null);
|
||||
const foldSettleFrameRef = useRef<number | null>(null);
|
||||
const foldSettleSecondFrameRef = useRef<number | null>(null);
|
||||
const disclosureAnchorKeyRef = useRef<string | null>(null);
|
||||
const suppressAutoFollowRef = useRef(false);
|
||||
const previousLatestTurnRef = useRef(props.latestTurn);
|
||||
const isNearEndRef = useRef(true);
|
||||
const initialScrollReadyRef = useRef(false);
|
||||
const lastContentHeightRef = useRef(0);
|
||||
const { width: viewportWidth } = useWindowDimensions();
|
||||
const [disclosureToggleSettling, setDisclosureToggleSettling] = useState(false);
|
||||
const [interactionState, setInteractionState] = useState<{
|
||||
readonly copiedRowId: string | null;
|
||||
readonly expandedWorkGroups: Record<string, boolean>;
|
||||
@@ -1183,6 +1193,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
const listAppearanceData = useMemo(
|
||||
() => ({
|
||||
copiedRowId,
|
||||
expandedWorkGroups,
|
||||
expandedWorkRows,
|
||||
iconSubtleColor,
|
||||
markdownStyles,
|
||||
@@ -1191,6 +1202,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
}),
|
||||
[
|
||||
copiedRowId,
|
||||
expandedWorkGroups,
|
||||
expandedWorkRows,
|
||||
iconSubtleColor,
|
||||
markdownStyles,
|
||||
@@ -1198,34 +1210,9 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
userBubbleColor,
|
||||
],
|
||||
);
|
||||
const expandedWorkGroupIds = useMemo(() => {
|
||||
const ids = new Set<string>();
|
||||
for (const [groupId, expanded] of Object.entries(expandedWorkGroups)) {
|
||||
if (expanded) {
|
||||
ids.add(groupId);
|
||||
}
|
||||
}
|
||||
return ids;
|
||||
}, [expandedWorkGroups]);
|
||||
const presentedFeed = useMemo(
|
||||
() =>
|
||||
deriveThreadFeedPresentation(
|
||||
props.feed,
|
||||
props.latestTurn,
|
||||
expandedTurnIds,
|
||||
expandedWorkGroupIds,
|
||||
),
|
||||
[expandedTurnIds, expandedWorkGroupIds, props.feed, props.latestTurn],
|
||||
);
|
||||
const anchoredEndSpace = useMemo(
|
||||
() =>
|
||||
resolveChatListAnchoredEndSpace(
|
||||
presentedFeed,
|
||||
props.anchorMessageId,
|
||||
(entry) => (entry.type === "message" ? entry.id : null),
|
||||
{ anchorOffset: topContentInset + CHAT_LIST_ANCHOR_OFFSET },
|
||||
),
|
||||
[presentedFeed, props.anchorMessageId, topContentInset],
|
||||
() => deriveThreadFeedPresentation(props.feed, props.latestTurn, expandedTurnIds),
|
||||
[expandedTurnIds, props.feed, props.latestTurn],
|
||||
);
|
||||
const terminalAssistantMessageIds = useMemo(() => {
|
||||
const terminalIdsByTurn = new Map<TurnId, string>();
|
||||
@@ -1242,6 +1229,54 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
? props.latestTurn.turnId
|
||||
: null;
|
||||
|
||||
const scrollToEnd = useCallback(() => {
|
||||
if (scrollFrameRef.current !== null) {
|
||||
return;
|
||||
}
|
||||
scrollFrameRef.current = requestAnimationFrame(() => {
|
||||
scrollFrameRef.current = null;
|
||||
listRef.current?.scrollToEnd({ animated: false });
|
||||
});
|
||||
}, []);
|
||||
|
||||
const onListScroll = useCallback(
|
||||
(event: NativeSyntheticEvent<NativeScrollEvent> | NativeScrollEvent) => {
|
||||
const scrollEvent = "nativeEvent" in event ? event.nativeEvent : event;
|
||||
const { contentInset, contentOffset, contentSize, layoutMeasurement } = scrollEvent;
|
||||
isNearEndRef.current = isThreadFeedNearEnd(
|
||||
{
|
||||
contentHeight: contentSize.height,
|
||||
viewportHeight: layoutMeasurement.height,
|
||||
offsetY: contentOffset.y,
|
||||
bottomInset: contentInset.bottom,
|
||||
},
|
||||
THREAD_FEED_END_THRESHOLD,
|
||||
);
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const onListContentSizeChange = useCallback(
|
||||
(_width: number, height: number) => {
|
||||
const contentGrew = height > lastContentHeightRef.current + 0.5;
|
||||
lastContentHeightRef.current = height;
|
||||
|
||||
if (
|
||||
initialScrollReadyRef.current &&
|
||||
contentGrew &&
|
||||
isNearEndRef.current &&
|
||||
!suppressAutoFollowRef.current
|
||||
) {
|
||||
scrollToEnd();
|
||||
}
|
||||
},
|
||||
[scrollToEnd],
|
||||
);
|
||||
|
||||
const onListLoad = useCallback(() => {
|
||||
initialScrollReadyRef.current = true;
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const previous = previousLatestTurnRef.current;
|
||||
previousLatestTurnRef.current = props.latestTurn;
|
||||
@@ -1273,6 +1308,9 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
if (copyFeedbackTimeoutRef.current) {
|
||||
clearTimeout(copyFeedbackTimeoutRef.current);
|
||||
}
|
||||
if (scrollFrameRef.current !== null) {
|
||||
cancelAnimationFrame(scrollFrameRef.current);
|
||||
}
|
||||
if (foldSettleFrameRef.current !== null) {
|
||||
cancelAnimationFrame(foldSettleFrameRef.current);
|
||||
}
|
||||
@@ -1282,44 +1320,9 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
};
|
||||
}, []);
|
||||
|
||||
const suspendEndScrollMaintenanceForDisclosure = useCallback((anchorKey: string | null) => {
|
||||
disclosureAnchorKeyRef.current = anchorKey;
|
||||
setDisclosureToggleSettling(true);
|
||||
if (foldSettleFrameRef.current !== null) {
|
||||
cancelAnimationFrame(foldSettleFrameRef.current);
|
||||
}
|
||||
if (foldSettleSecondFrameRef.current !== null) {
|
||||
cancelAnimationFrame(foldSettleSecondFrameRef.current);
|
||||
}
|
||||
foldSettleFrameRef.current = requestAnimationFrame(() => {
|
||||
foldSettleSecondFrameRef.current = requestAnimationFrame(() => {
|
||||
disclosureAnchorKeyRef.current = null;
|
||||
setDisclosureToggleSettling(false);
|
||||
foldSettleFrameRef.current = null;
|
||||
foldSettleSecondFrameRef.current = null;
|
||||
});
|
||||
});
|
||||
}, []);
|
||||
|
||||
const shouldRestoreVisibleContentPosition = useCallback((entry: ThreadFeedEntry) => {
|
||||
const disclosureAnchorKey = disclosureAnchorKeyRef.current;
|
||||
return disclosureAnchorKey === null || entry.id === disclosureAnchorKey;
|
||||
}, []);
|
||||
|
||||
const maintainVisibleContentPosition = useMemo(
|
||||
() => ({
|
||||
data: true,
|
||||
size: true,
|
||||
shouldRestorePosition: shouldRestoreVisibleContentPosition,
|
||||
}),
|
||||
[shouldRestoreVisibleContentPosition],
|
||||
);
|
||||
|
||||
const onCopyWorkRow = useCallback((rowId: string, value: string) => {
|
||||
copyTextWithHaptic(value, {
|
||||
target: "thread-work-row",
|
||||
feedback: "selection",
|
||||
});
|
||||
void Clipboard.setStringAsync(value);
|
||||
void Haptics.selectionAsync();
|
||||
setInteractionState((current) => ({ ...current, copiedRowId: rowId }));
|
||||
if (copyFeedbackTimeoutRef.current) {
|
||||
clearTimeout(copyFeedbackTimeoutRef.current);
|
||||
@@ -1332,49 +1335,51 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
}, 1200);
|
||||
}, []);
|
||||
|
||||
const onToggleWorkGroup = useCallback(
|
||||
(groupId: string) => {
|
||||
suspendEndScrollMaintenanceForDisclosure(`work-toggle:${groupId}`);
|
||||
setInteractionState((current) => ({
|
||||
...current,
|
||||
expandedWorkGroups: {
|
||||
...current.expandedWorkGroups,
|
||||
[groupId]: !(current.expandedWorkGroups[groupId] ?? false),
|
||||
},
|
||||
}));
|
||||
},
|
||||
[suspendEndScrollMaintenanceForDisclosure],
|
||||
);
|
||||
const onToggleWorkGroup = useCallback((groupId: string) => {
|
||||
setInteractionState((current) => ({
|
||||
...current,
|
||||
expandedWorkGroups: {
|
||||
...current.expandedWorkGroups,
|
||||
[groupId]: !(current.expandedWorkGroups[groupId] ?? false),
|
||||
},
|
||||
}));
|
||||
}, []);
|
||||
|
||||
const onToggleWorkRow = useCallback(
|
||||
(rowId: string) => {
|
||||
suspendEndScrollMaintenanceForDisclosure(rowId);
|
||||
setInteractionState((current) => ({
|
||||
...current,
|
||||
expandedWorkRows: {
|
||||
...current.expandedWorkRows,
|
||||
[rowId]: !(current.expandedWorkRows[rowId] ?? false),
|
||||
},
|
||||
}));
|
||||
},
|
||||
[suspendEndScrollMaintenanceForDisclosure],
|
||||
);
|
||||
const onToggleWorkRow = useCallback((rowId: string) => {
|
||||
setInteractionState((current) => ({
|
||||
...current,
|
||||
expandedWorkRows: {
|
||||
...current.expandedWorkRows,
|
||||
[rowId]: !(current.expandedWorkRows[rowId] ?? false),
|
||||
},
|
||||
}));
|
||||
}, []);
|
||||
|
||||
const onToggleTurnFold = useCallback(
|
||||
(turnId: TurnId) => {
|
||||
suspendEndScrollMaintenanceForDisclosure(`turn-fold:${turnId}`);
|
||||
setInteractionState((current) => {
|
||||
const next = new Set(current.expandedTurnIds);
|
||||
if (next.has(turnId)) {
|
||||
next.delete(turnId);
|
||||
} else {
|
||||
next.add(turnId);
|
||||
}
|
||||
return { ...current, expandedTurnIds: next };
|
||||
const onToggleTurnFold = useCallback((turnId: TurnId) => {
|
||||
suppressAutoFollowRef.current = true;
|
||||
if (foldSettleFrameRef.current !== null) {
|
||||
cancelAnimationFrame(foldSettleFrameRef.current);
|
||||
}
|
||||
if (foldSettleSecondFrameRef.current !== null) {
|
||||
cancelAnimationFrame(foldSettleSecondFrameRef.current);
|
||||
}
|
||||
setInteractionState((current) => {
|
||||
const next = new Set(current.expandedTurnIds);
|
||||
if (next.has(turnId)) {
|
||||
next.delete(turnId);
|
||||
} else {
|
||||
next.add(turnId);
|
||||
}
|
||||
return { ...current, expandedTurnIds: next };
|
||||
});
|
||||
foldSettleFrameRef.current = requestAnimationFrame(() => {
|
||||
foldSettleSecondFrameRef.current = requestAnimationFrame(() => {
|
||||
suppressAutoFollowRef.current = false;
|
||||
foldSettleFrameRef.current = null;
|
||||
foldSettleSecondFrameRef.current = null;
|
||||
});
|
||||
},
|
||||
[suspendEndScrollMaintenanceForDisclosure],
|
||||
);
|
||||
});
|
||||
}, []);
|
||||
|
||||
const onPressImage = useCallback((uri: string, headers?: Record<string, string>) => {
|
||||
setExpandedImage({ uri, headers });
|
||||
@@ -1385,6 +1390,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
renderFeedEntry(info, {
|
||||
environmentId: props.environmentId,
|
||||
copiedRowId,
|
||||
expandedWorkGroups,
|
||||
expandedWorkRows,
|
||||
terminalAssistantMessageIds,
|
||||
unsettledTurnId,
|
||||
@@ -1404,6 +1410,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
}),
|
||||
[
|
||||
copiedRowId,
|
||||
expandedWorkGroups,
|
||||
expandedWorkRows,
|
||||
terminalAssistantMessageIds,
|
||||
unsettledTurnId,
|
||||
@@ -1449,60 +1456,59 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
);
|
||||
}
|
||||
|
||||
if (props.feed.length === 0) {
|
||||
return (
|
||||
<ThreadFeedPlaceholder
|
||||
title="No conversation yet"
|
||||
detail="Ask the agent to inspect the repo, run a command, or continue the active thread."
|
||||
topInset={topContentInset}
|
||||
bottomInset={bottomContentInset}
|
||||
horizontalPadding={horizontalPadding}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<View style={{ flex: 1 }}>
|
||||
<KeyboardAwareLegendList
|
||||
ref={props.listRef}
|
||||
<KeyboardAvoidingLegendList
|
||||
ref={listRef}
|
||||
key={props.threadId}
|
||||
style={{ flex: 1 }}
|
||||
automaticallyAdjustsScrollIndicatorInsets={false}
|
||||
contentInset={{ top: 0, bottom: 0 }}
|
||||
scrollIndicatorInsets={{ top: topContentInset, bottom: 0 }}
|
||||
{...(anchoredEndSpace ? { anchoredEndSpace } : {})}
|
||||
contentInsetEndAdjustment={props.contentInsetEndAdjustment}
|
||||
freeze={props.freeze}
|
||||
maintainScrollAtEnd={
|
||||
disclosureToggleSettling
|
||||
? false
|
||||
: {
|
||||
animated: false,
|
||||
on: {
|
||||
dataChange: true,
|
||||
itemLayout: true,
|
||||
layout: true,
|
||||
},
|
||||
}
|
||||
}
|
||||
maintainVisibleContentPosition={maintainVisibleContentPosition}
|
||||
alignItemsAtEnd
|
||||
maintainScrollAtEnd={{
|
||||
animated: false,
|
||||
on: {
|
||||
dataChange: true,
|
||||
itemLayout: true,
|
||||
layout: true,
|
||||
},
|
||||
}}
|
||||
data={presentedFeed}
|
||||
extraData={listAppearanceData}
|
||||
renderItem={renderItem}
|
||||
keyExtractor={(entry) => entry.id}
|
||||
keyExtractor={(entry) => `${entry.type}:${entry.id}`}
|
||||
getItemType={(entry) =>
|
||||
entry.type === "message" ? `message:${entry.message.role}` : entry.type
|
||||
}
|
||||
keyboardShouldPersistTaps="always"
|
||||
keyboardDismissMode="none"
|
||||
keyboardLiftBehavior="whenAtEnd"
|
||||
estimatedItemSize={180}
|
||||
initialScrollAtEnd
|
||||
onContentSizeChange={onListContentSizeChange}
|
||||
onLoad={onListLoad}
|
||||
onScroll={onListScroll}
|
||||
scrollEventThrottle={16}
|
||||
ListHeaderComponent={<View style={{ height: topContentInset }} />}
|
||||
contentContainerStyle={{
|
||||
paddingTop: 12,
|
||||
paddingBottom: bottomContentInset,
|
||||
paddingHorizontal: horizontalPadding,
|
||||
}}
|
||||
/>
|
||||
{props.feed.length === 0 ? (
|
||||
<View pointerEvents="none" style={StyleSheet.absoluteFill}>
|
||||
<ThreadFeedPlaceholder
|
||||
title="No conversation yet"
|
||||
detail="Ask the agent to inspect the repo, run a command, or continue the active thread."
|
||||
topInset={topContentInset}
|
||||
bottomInset={bottomContentInset}
|
||||
horizontalPadding={horizontalPadding}
|
||||
/>
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
|
||||
<ImageViewing
|
||||
|
||||
@@ -1,7 +1,13 @@
|
||||
import { Stack, useLocalSearchParams, useRouter } from "expo-router";
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
import * as Option from "effect/Option";
|
||||
import { EnvironmentId, type ProjectScript } from "@t3tools/contracts";
|
||||
import {
|
||||
EnvironmentId,
|
||||
type ModelSelection,
|
||||
type ProjectScript,
|
||||
type ProviderInteractionMode,
|
||||
type RuntimeMode,
|
||||
} from "@t3tools/contracts";
|
||||
import { projectScriptCwd, projectScriptRuntimeEnv } from "@t3tools/shared/projectScripts";
|
||||
import { Pressable, ScrollView, Text as RNText, View } from "react-native";
|
||||
import { useWorkspaceState } from "../../state/workspace";
|
||||
@@ -73,6 +79,18 @@ export function ThreadRouteScreen() {
|
||||
const gitState = useSelectedThreadGitState();
|
||||
const gitActions = useSelectedThreadGitActions();
|
||||
const requests = useSelectedThreadRequests();
|
||||
const updateThreadMetadata = useAtomCommand(
|
||||
threadEnvironment.updateMetadata,
|
||||
"thread metadata update",
|
||||
);
|
||||
const setThreadRuntimeMode = useAtomCommand(
|
||||
threadEnvironment.setRuntimeMode,
|
||||
"thread runtime mode",
|
||||
);
|
||||
const setThreadInteractionMode = useAtomCommand(
|
||||
threadEnvironment.setInteractionMode,
|
||||
"thread interaction mode",
|
||||
);
|
||||
const interruptThreadTurn = useAtomCommand(threadEnvironment.interruptTurn, "thread interrupt");
|
||||
const router = useRouter();
|
||||
const params = useLocalSearchParams<{
|
||||
@@ -87,18 +105,6 @@ export function ThreadRouteScreen() {
|
||||
const routeConnectionState =
|
||||
routeEnvironmentRuntime?.connectionState ?? (environmentId ? "available" : connectionState);
|
||||
const routeConnectionError = routeEnvironmentRuntime?.connectionError ?? null;
|
||||
const selectedThreadWithDraftSettings = useMemo(
|
||||
() =>
|
||||
selectedThread
|
||||
? {
|
||||
...selectedThread,
|
||||
modelSelection: composer.modelSelection ?? selectedThread.modelSelection,
|
||||
runtimeMode: composer.runtimeMode ?? selectedThread.runtimeMode,
|
||||
interactionMode: composer.interactionMode ?? selectedThread.interactionMode,
|
||||
}
|
||||
: null,
|
||||
[composer.interactionMode, composer.modelSelection, composer.runtimeMode, selectedThread],
|
||||
);
|
||||
|
||||
/* ─── Native header theming ──────────────────────────────────────── */
|
||||
const iconColor = String(useThemeColor("--color-icon"));
|
||||
@@ -151,6 +157,51 @@ export function ThreadRouteScreen() {
|
||||
const handleOpenConnectionEditor = useCallback(() => {
|
||||
void router.push("/connections");
|
||||
}, [router]);
|
||||
const handleUpdateThreadModelSelection = useCallback(
|
||||
(modelSelection: ModelSelection) => {
|
||||
if (!selectedThread) {
|
||||
return;
|
||||
}
|
||||
return updateThreadMetadata({
|
||||
environmentId: selectedThread.environmentId,
|
||||
input: {
|
||||
threadId: selectedThread.id,
|
||||
modelSelection,
|
||||
},
|
||||
});
|
||||
},
|
||||
[selectedThread, updateThreadMetadata],
|
||||
);
|
||||
const handleUpdateThreadRuntimeMode = useCallback(
|
||||
(runtimeMode: RuntimeMode) => {
|
||||
if (!selectedThread) {
|
||||
return;
|
||||
}
|
||||
return setThreadRuntimeMode({
|
||||
environmentId: selectedThread.environmentId,
|
||||
input: {
|
||||
threadId: selectedThread.id,
|
||||
runtimeMode,
|
||||
},
|
||||
});
|
||||
},
|
||||
[selectedThread, setThreadRuntimeMode],
|
||||
);
|
||||
const handleUpdateThreadInteractionMode = useCallback(
|
||||
(interactionMode: ProviderInteractionMode) => {
|
||||
if (!selectedThread) {
|
||||
return;
|
||||
}
|
||||
return setThreadInteractionMode({
|
||||
environmentId: selectedThread.environmentId,
|
||||
input: {
|
||||
threadId: selectedThread.id,
|
||||
interactionMode,
|
||||
},
|
||||
});
|
||||
},
|
||||
[selectedThread, setThreadInteractionMode],
|
||||
);
|
||||
const handleStopThread = useCallback(() => {
|
||||
if (
|
||||
!selectedThread ||
|
||||
@@ -384,7 +435,7 @@ export function ThreadRouteScreen() {
|
||||
|
||||
<View className="flex-1 bg-screen">
|
||||
<ThreadDetailScreen
|
||||
selectedThread={selectedThreadWithDraftSettings ?? selectedThread}
|
||||
selectedThread={selectedThread}
|
||||
contentPresentation={contentPresentation}
|
||||
screenTone={connectionTone(routeConnectionState)}
|
||||
connectionError={routeConnectionError}
|
||||
@@ -415,9 +466,9 @@ export function ThreadRouteScreen() {
|
||||
onStopThread={handleStopThread}
|
||||
onSendMessage={composer.onSendMessage}
|
||||
onReconnectEnvironment={handleReconnectEnvironment}
|
||||
onUpdateThreadModelSelection={composer.onUpdateModelSelection}
|
||||
onUpdateThreadRuntimeMode={composer.onUpdateRuntimeMode}
|
||||
onUpdateThreadInteractionMode={composer.onUpdateInteractionMode}
|
||||
onUpdateThreadModelSelection={handleUpdateThreadModelSelection}
|
||||
onUpdateThreadRuntimeMode={handleUpdateThreadRuntimeMode}
|
||||
onUpdateThreadInteractionMode={handleUpdateThreadInteractionMode}
|
||||
onRespondToApproval={requests.onRespondToApproval}
|
||||
onSelectUserInputOption={requests.onSelectUserInputOption}
|
||||
onChangeUserInputCustomAnswer={requests.onChangeUserInputCustomAnswer}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import React, { useCallback, useMemo, useRef, useState } from "react";
|
||||
|
||||
import type {
|
||||
EnvironmentId,
|
||||
@@ -23,7 +23,6 @@ import {
|
||||
removeComposerDraftAttachment,
|
||||
replaceComposerDraftAttachments,
|
||||
setComposerDraftText,
|
||||
updateComposerDraftSettings,
|
||||
useComposerDraft,
|
||||
} from "../../state/use-composer-drafts";
|
||||
import { useBranches } from "../../state/queries";
|
||||
@@ -159,15 +158,34 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
? selectedEnvironmentIdOverride
|
||||
: (projects[0]?.environmentId ?? null);
|
||||
const [selectedProjectKey, setSelectedProjectKey] = useState<string | null>(null);
|
||||
const [selectedModelKey, setSelectedModelKey] = useState<string | null>(null);
|
||||
const [workspaceMode, setWorkspaceMode] = useState<WorkspaceMode>("local");
|
||||
const [selectedBranchName, setSelectedBranchName] = useState<string | null>(null);
|
||||
const [selectedWorktreePath, setSelectedWorktreePath] = useState<string | null>(null);
|
||||
const branchLoadVersionRef = useRef(0);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [branchQuery, setBranchQuery] = useState("");
|
||||
const [runtimeMode, setRuntimeMode] = useState<RuntimeMode>(DEFAULT_RUNTIME_MODE);
|
||||
const [interactionMode, setInteractionMode] = useState<ProviderInteractionMode>(
|
||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
);
|
||||
const [modelSelectionOverrides, setModelSelectionOverrides] = useState<
|
||||
Record<string, ModelSelection>
|
||||
>({});
|
||||
const [expandedProvider, setExpandedProvider] = useState<string | null>(null);
|
||||
|
||||
const reset = useCallback(() => {
|
||||
setSelectedEnvironmentId(null);
|
||||
setSelectedProjectKey(null);
|
||||
setSelectedModelKey(null);
|
||||
setWorkspaceMode("local");
|
||||
setSelectedBranchName(null);
|
||||
setSelectedWorktreePath(null);
|
||||
setSubmitting(false);
|
||||
setBranchQuery("");
|
||||
setRuntimeMode(DEFAULT_RUNTIME_MODE);
|
||||
setInteractionMode(DEFAULT_PROVIDER_INTERACTION_MODE);
|
||||
setModelSelectionOverrides({});
|
||||
setExpandedProvider(null);
|
||||
}, []);
|
||||
|
||||
@@ -229,33 +247,33 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
const selectedProjectDraft = useComposerDraft(selectedProjectDraftKey);
|
||||
const prompt = selectedProjectDraft.text;
|
||||
const attachments = selectedProjectDraft.attachments;
|
||||
const workspaceMode = selectedProjectDraft.workspaceSelection?.mode ?? "local";
|
||||
const selectedBranchName = selectedProjectDraft.workspaceSelection?.branch ?? null;
|
||||
const selectedWorktreePath = selectedProjectDraft.workspaceSelection?.worktreePath ?? null;
|
||||
const runtimeMode = selectedProjectDraft.runtimeMode ?? DEFAULT_RUNTIME_MODE;
|
||||
const interactionMode = selectedProjectDraft.interactionMode ?? DEFAULT_PROVIDER_INTERACTION_MODE;
|
||||
|
||||
const modelOptions = useMemo(
|
||||
() =>
|
||||
buildModelOptions(
|
||||
selectedEnvironmentServerConfig,
|
||||
selectedProjectDraft.modelSelection ?? selectedProject?.defaultModelSelection ?? null,
|
||||
selectedProject?.defaultModelSelection ?? null,
|
||||
),
|
||||
[
|
||||
selectedEnvironmentServerConfig,
|
||||
selectedProject?.defaultModelSelection,
|
||||
selectedProjectDraft.modelSelection,
|
||||
],
|
||||
[selectedEnvironmentServerConfig, selectedProject?.defaultModelSelection],
|
||||
);
|
||||
|
||||
const selectedModel =
|
||||
selectedProjectDraft.modelSelection ??
|
||||
const defaultModelKey = selectedProject?.defaultModelSelection
|
||||
? `${selectedProject.defaultModelSelection.instanceId}:${selectedProject.defaultModelSelection.model}`
|
||||
: null;
|
||||
const baseSelectedModel =
|
||||
modelOptions.find((option) => option.key === selectedModelKey)?.selection ??
|
||||
(defaultModelKey
|
||||
? modelOptions.find((option) => option.key === defaultModelKey)?.selection
|
||||
: null) ??
|
||||
selectedProject?.defaultModelSelection ??
|
||||
modelOptions[0]?.selection ??
|
||||
null;
|
||||
const selectedModelKey = selectedModel
|
||||
? `${selectedModel.instanceId}:${selectedModel.model}`
|
||||
const selectedModelIdentity = baseSelectedModel
|
||||
? `${baseSelectedModel.instanceId}:${baseSelectedModel.model}`
|
||||
: null;
|
||||
const selectedModel =
|
||||
(selectedModelIdentity ? modelSelectionOverrides[selectedModelIdentity] : null) ??
|
||||
baseSelectedModel;
|
||||
|
||||
const selectedModelOption =
|
||||
modelOptions.find(
|
||||
@@ -264,31 +282,13 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
option.selection.instanceId === selectedModel.instanceId &&
|
||||
option.selection.model === selectedModel.model,
|
||||
) ?? null;
|
||||
const selectedProviderSkills = useMemo(
|
||||
() =>
|
||||
selectedEnvironmentServerConfig?.providers.find(
|
||||
(provider) => provider.instanceId === selectedModel?.instanceId,
|
||||
)?.skills ?? [],
|
||||
[selectedEnvironmentServerConfig, selectedModel?.instanceId],
|
||||
);
|
||||
const setSelectedModelKey = useCallback(
|
||||
(key: string | null) => {
|
||||
if (!key || !selectedProjectDraftKey) {
|
||||
return;
|
||||
}
|
||||
const option = modelOptions.find((candidate) => candidate.key === key);
|
||||
if (!option) {
|
||||
return;
|
||||
}
|
||||
updateComposerDraftSettings(selectedProjectDraftKey, {
|
||||
modelSelection: option.selection,
|
||||
});
|
||||
},
|
||||
[modelOptions, selectedProjectDraftKey],
|
||||
);
|
||||
const selectedProviderSkills =
|
||||
selectedEnvironmentServerConfig?.providers.find(
|
||||
(provider) => provider.instanceId === selectedModel?.instanceId,
|
||||
)?.skills ?? [];
|
||||
const setSelectedModelOptions = useCallback(
|
||||
(options: ReadonlyArray<ProviderOptionSelection> | undefined) => {
|
||||
if (!selectedModel || !selectedProjectDraftKey) {
|
||||
if (!selectedModel || !selectedModelIdentity) {
|
||||
return;
|
||||
}
|
||||
const nextSelection: ModelSelection = options
|
||||
@@ -297,11 +297,12 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
instanceId: selectedModel.instanceId,
|
||||
model: selectedModel.model,
|
||||
};
|
||||
updateComposerDraftSettings(selectedProjectDraftKey, {
|
||||
modelSelection: nextSelection,
|
||||
});
|
||||
setModelSelectionOverrides((current) => ({
|
||||
...current,
|
||||
[selectedModelIdentity]: nextSelection,
|
||||
}));
|
||||
},
|
||||
[selectedModel, selectedProjectDraftKey],
|
||||
[selectedModel, selectedModelIdentity],
|
||||
);
|
||||
|
||||
const providerGroups = useMemo(() => groupByProvider(modelOptions), [modelOptions]);
|
||||
@@ -380,85 +381,62 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
|
||||
const setProject = useCallback((project: EnvironmentProject) => {
|
||||
const nextProjectKey = scopedProjectKey(project.environmentId, project.id);
|
||||
branchLoadVersionRef.current += 1;
|
||||
setSelectedEnvironmentId(project.environmentId);
|
||||
setSelectedProjectKey(nextProjectKey);
|
||||
setSelectedBranchName(null);
|
||||
setSelectedWorktreePath(null);
|
||||
setModelSelectionOverrides({});
|
||||
}, []);
|
||||
|
||||
const selectEnvironment = useCallback((environmentId: EnvironmentId) => {
|
||||
branchLoadVersionRef.current += 1;
|
||||
setSelectedEnvironmentId(environmentId);
|
||||
setSelectedProjectKey(null);
|
||||
setSelectedBranchName(null);
|
||||
setSelectedWorktreePath(null);
|
||||
setModelSelectionOverrides({});
|
||||
}, []);
|
||||
|
||||
const setWorkspaceMode = useCallback(
|
||||
(mode: WorkspaceMode) => {
|
||||
if (!selectedProjectDraftKey) {
|
||||
return;
|
||||
}
|
||||
updateComposerDraftSettings(selectedProjectDraftKey, {
|
||||
workspaceSelection: {
|
||||
mode,
|
||||
branch: selectedBranchName,
|
||||
worktreePath: selectedWorktreePath,
|
||||
},
|
||||
});
|
||||
},
|
||||
[selectedBranchName, selectedProjectDraftKey, selectedWorktreePath],
|
||||
);
|
||||
|
||||
const selectBranch = useCallback(
|
||||
(branch: VcsRef) => {
|
||||
if (!selectedProject || !selectedProjectDraftKey) {
|
||||
return;
|
||||
}
|
||||
updateComposerDraftSettings(selectedProjectDraftKey, {
|
||||
workspaceSelection: {
|
||||
mode: workspaceMode,
|
||||
branch: branch.name,
|
||||
worktreePath: normalizeSelectedWorktreePath(selectedProject, branch),
|
||||
},
|
||||
});
|
||||
setSelectedBranchName(branch.name);
|
||||
setSelectedWorktreePath(
|
||||
selectedProject ? normalizeSelectedWorktreePath(selectedProject, branch) : null,
|
||||
);
|
||||
},
|
||||
[selectedProject, selectedProjectDraftKey, workspaceMode],
|
||||
[selectedProject],
|
||||
);
|
||||
|
||||
const refreshBranches = branchState.refresh;
|
||||
const loadBranches = useCallback(async () => {
|
||||
if (!selectedProject) {
|
||||
return;
|
||||
}
|
||||
setPendingConnectionError(null);
|
||||
refreshBranches();
|
||||
}, [refreshBranches, selectedProject]);
|
||||
|
||||
useEffect(() => {
|
||||
if (workspaceMode !== "worktree" || selectedBranchName !== null) {
|
||||
const loadVersion = ++branchLoadVersionRef.current;
|
||||
const projectKey = scopedProjectKey(selectedProject.environmentId, selectedProject.id);
|
||||
branchState.refresh();
|
||||
if (loadVersion !== branchLoadVersionRef.current || selectedProjectKey !== projectKey) {
|
||||
return;
|
||||
}
|
||||
const preferredBranch =
|
||||
availableBranches.find((branch) => branch.current) ??
|
||||
availableBranches.find((branch) => branch.isDefault) ??
|
||||
null;
|
||||
if (preferredBranch) {
|
||||
selectBranch(preferredBranch);
|
||||
setPendingConnectionError(null);
|
||||
if (workspaceMode === "worktree" && !selectedBranchName) {
|
||||
const preferredBranch =
|
||||
availableBranches.find((branch) => branch.current)?.name ??
|
||||
availableBranches.find((branch) => branch.isDefault)?.name ??
|
||||
null;
|
||||
if (preferredBranch) {
|
||||
setSelectedBranchName(preferredBranch);
|
||||
}
|
||||
}
|
||||
}, [availableBranches, selectBranch, selectedBranchName, workspaceMode]);
|
||||
|
||||
const setRuntimeMode = useCallback(
|
||||
(value: RuntimeMode) => {
|
||||
if (selectedProjectDraftKey) {
|
||||
updateComposerDraftSettings(selectedProjectDraftKey, { runtimeMode: value });
|
||||
}
|
||||
},
|
||||
[selectedProjectDraftKey],
|
||||
);
|
||||
const setInteractionMode = useCallback(
|
||||
(value: ProviderInteractionMode) => {
|
||||
if (selectedProjectDraftKey) {
|
||||
updateComposerDraftSettings(selectedProjectDraftKey, { interactionMode: value });
|
||||
}
|
||||
},
|
||||
[selectedProjectDraftKey],
|
||||
);
|
||||
}, [
|
||||
availableBranches,
|
||||
branchState,
|
||||
selectedBranchName,
|
||||
selectedProject,
|
||||
selectedProjectKey,
|
||||
workspaceMode,
|
||||
]);
|
||||
|
||||
const value = useMemo<NewTaskFlowContextValue>(
|
||||
() => ({
|
||||
@@ -535,11 +513,6 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
setProject,
|
||||
selectBranch,
|
||||
selectEnvironment,
|
||||
setInteractionMode,
|
||||
setPrompt,
|
||||
setRuntimeMode,
|
||||
setSelectedModelKey,
|
||||
setWorkspaceMode,
|
||||
submitting,
|
||||
workspaceMode,
|
||||
appendAttachments,
|
||||
|
||||
@@ -6,6 +6,7 @@ import { AppText as Text } from "../../components/AppText";
|
||||
import { cn } from "../../lib/cn";
|
||||
import type { ThreadFeedActivity } from "../../lib/threadActivity";
|
||||
|
||||
const MAX_VISIBLE_WORK_LOG_ENTRIES = 1;
|
||||
const WORK_LOG_LAYOUT_ANIMATION = {
|
||||
duration: 180,
|
||||
create: {
|
||||
@@ -71,9 +72,11 @@ function workRowSymbolName(icon: ThreadFeedActivity["icon"]): SFSymbol {
|
||||
export function ThreadWorkLog(props: {
|
||||
readonly activities: ReadonlyArray<ThreadFeedActivity>;
|
||||
readonly copiedRowId: string | null;
|
||||
readonly expanded: boolean;
|
||||
readonly expandedRows: Readonly<Record<string, boolean>>;
|
||||
readonly iconSubtleColor: import("react-native").ColorValue;
|
||||
readonly onCopyRow: (rowId: string, value: string) => void;
|
||||
readonly onToggleGroup: () => void;
|
||||
readonly onToggleRow: (rowId: string) => void;
|
||||
}) {
|
||||
const colorScheme = useColorScheme();
|
||||
@@ -86,10 +89,14 @@ export function ThreadWorkLog(props: {
|
||||
return null;
|
||||
}
|
||||
|
||||
const hasOverflow = rows.length > MAX_VISIBLE_WORK_LOG_ENTRIES;
|
||||
const visibleRows =
|
||||
hasOverflow && !props.expanded ? rows.slice(-MAX_VISIBLE_WORK_LOG_ENTRIES) : rows;
|
||||
const hiddenCount = rows.length - visibleRows.length;
|
||||
const onlyToolRows = rows.every((row) => row.toolLike);
|
||||
|
||||
return (
|
||||
<View className="-mx-1 mb-1 px-1 py-0">
|
||||
<View className="-mx-1 mb-3 px-1 py-0.5">
|
||||
{!onlyToolRows ? (
|
||||
<Text className="px-0.5 pb-0.5 font-t3-medium text-2xs text-foreground-muted opacity-60">
|
||||
work log
|
||||
@@ -97,7 +104,7 @@ export function ThreadWorkLog(props: {
|
||||
) : null}
|
||||
|
||||
<View className="gap-px">
|
||||
{rows.map((row) => {
|
||||
{visibleRows.map((row) => {
|
||||
const expanded = props.expandedRows[row.id] ?? false;
|
||||
const canExpand = row.fullDetail !== null;
|
||||
const displayText = row.detail ? `${row.summary} ${row.detail}` : row.summary;
|
||||
@@ -125,13 +132,13 @@ export function ThreadWorkLog(props: {
|
||||
style={({ pressed }) => ({
|
||||
backgroundColor: pressed ? pressedBackground : "transparent",
|
||||
})}
|
||||
className="rounded-md px-0.5 py-0"
|
||||
className="rounded-md px-0.5 py-0.5"
|
||||
>
|
||||
<View className="min-h-8 flex-row items-center gap-1.5">
|
||||
<View className="h-[18px] w-5 shrink-0 items-center justify-center">
|
||||
<View className="min-h-9 flex-row items-center gap-1.5">
|
||||
<View className="h-5 w-5 shrink-0 items-center justify-center">
|
||||
<SymbolView
|
||||
name={workRowSymbolName(row.icon)}
|
||||
size={13}
|
||||
size={14}
|
||||
weight="medium"
|
||||
tintColor={iconIsDestructive ? "#e11d48" : props.iconSubtleColor}
|
||||
type="monochrome"
|
||||
@@ -139,7 +146,7 @@ export function ThreadWorkLog(props: {
|
||||
</View>
|
||||
|
||||
<Text
|
||||
className="min-w-0 flex-1 text-xs leading-4 text-foreground"
|
||||
className="min-w-0 flex-1 text-xs leading-5 text-foreground"
|
||||
numberOfLines={1}
|
||||
>
|
||||
<Text
|
||||
@@ -192,7 +199,7 @@ export function ThreadWorkLog(props: {
|
||||
</Pressable>
|
||||
|
||||
{expanded && row.fullDetail ? (
|
||||
<View className="ml-7 border-l border-neutral-300/60 pb-1 pl-3 pt-0.5 dark:border-white/[0.12]">
|
||||
<View className="ml-7 border-l border-neutral-300/60 pb-1.5 pl-3 pt-0.5 dark:border-white/[0.12]">
|
||||
<ScrollView
|
||||
nestedScrollEnabled
|
||||
directionalLockEnabled
|
||||
@@ -214,59 +221,41 @@ export function ThreadWorkLog(props: {
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
export function ThreadWorkGroupToggle(props: {
|
||||
readonly expanded: boolean;
|
||||
readonly hiddenCount: number;
|
||||
readonly iconSubtleColor: import("react-native").ColorValue;
|
||||
readonly onlyToolActivities: boolean;
|
||||
readonly onToggle: () => void;
|
||||
}) {
|
||||
const colorScheme = useColorScheme();
|
||||
const pressedBackground = colorScheme === "dark" ? "rgba(255,255,255,0.05)" : "rgba(0,0,0,0.035)";
|
||||
const noun = props.onlyToolActivities
|
||||
? props.hiddenCount === 1
|
||||
? "tool call"
|
||||
: "tool calls"
|
||||
: props.hiddenCount === 1
|
||||
? "log entry"
|
||||
: "log entries";
|
||||
const collapsedLabel = `Show ${props.hiddenCount} previous ${noun}`;
|
||||
const expandedLabel = props.onlyToolActivities
|
||||
? "Show fewer tool calls"
|
||||
: "Show fewer log entries";
|
||||
|
||||
return (
|
||||
<View className="-mx-1 mb-1 px-1 py-0">
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityState={{ expanded: props.expanded }}
|
||||
accessibilityLabel={props.expanded ? expandedLabel : collapsedLabel}
|
||||
hitSlop={4}
|
||||
onPress={() => {
|
||||
void Haptics.selectionAsync();
|
||||
props.onToggle();
|
||||
}}
|
||||
style={({ pressed }) => ({
|
||||
backgroundColor: pressed ? pressedBackground : "transparent",
|
||||
})}
|
||||
className="min-h-8 flex-row items-center gap-1.5 rounded-md px-0.5 py-0"
|
||||
>
|
||||
<View className="h-[18px] w-5 items-center justify-center">
|
||||
<SymbolView
|
||||
name={props.expanded ? "chevron.up" : "chevron.down"}
|
||||
size={12}
|
||||
tintColor={props.iconSubtleColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
</View>
|
||||
<Text className="font-t3-medium text-xs text-foreground opacity-80">
|
||||
{props.expanded ? expandedLabel : `+${props.hiddenCount} previous ${noun}`}
|
||||
</Text>
|
||||
</Pressable>
|
||||
|
||||
{hasOverflow ? (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityState={{ expanded: props.expanded }}
|
||||
accessibilityLabel={
|
||||
props.expanded
|
||||
? "Show fewer tool calls"
|
||||
: `Show ${hiddenCount} previous tool ${hiddenCount === 1 ? "call" : "calls"}`
|
||||
}
|
||||
hitSlop={4}
|
||||
onPress={() => {
|
||||
triggerDisclosureFeedback();
|
||||
props.onToggleGroup();
|
||||
}}
|
||||
style={({ pressed }) => ({
|
||||
backgroundColor: pressed ? pressedBackground : "transparent",
|
||||
})}
|
||||
className="min-h-9 flex-row items-center gap-1.5 rounded-md px-0.5 py-0.5"
|
||||
>
|
||||
<View className="h-5 w-5 items-center justify-center">
|
||||
<SymbolView
|
||||
name={props.expanded ? "chevron.up" : "chevron.down"}
|
||||
size={13}
|
||||
tintColor={props.iconSubtleColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
</View>
|
||||
<Text className="font-t3-medium text-xs text-foreground opacity-80">
|
||||
{props.expanded
|
||||
? "Show fewer tool calls"
|
||||
: `+${hiddenCount} previous tool ${hiddenCount === 1 ? "call" : "calls"}`}
|
||||
</Text>
|
||||
</Pressable>
|
||||
) : null}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
export const DraftComposerImageAttachmentSchema = Schema.Struct({
|
||||
id: Schema.String,
|
||||
previewUri: Schema.String,
|
||||
type: Schema.Literal("image"),
|
||||
name: Schema.String,
|
||||
mimeType: Schema.String,
|
||||
sizeBytes: Schema.Number,
|
||||
dataUrl: Schema.String,
|
||||
});
|
||||
@@ -1,8 +1,7 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
impactAsync: vi.fn(),
|
||||
selectionAsync: vi.fn(),
|
||||
setStringAsync: vi.fn(),
|
||||
}));
|
||||
|
||||
@@ -15,25 +14,15 @@ vi.mock("expo-haptics", () => ({
|
||||
Light: "light",
|
||||
},
|
||||
impactAsync: mocks.impactAsync,
|
||||
selectionAsync: mocks.selectionAsync,
|
||||
}));
|
||||
|
||||
import {
|
||||
CopyTextClipboardWriteError,
|
||||
CopyTextHapticFeedbackError,
|
||||
copyTextWithHaptic,
|
||||
} from "./copyTextWithHaptic";
|
||||
import { copyTextWithHaptic } from "./copyTextWithHaptic";
|
||||
|
||||
describe("copyTextWithHaptic", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.setStringAsync.mockReturnValue(new Promise<void>(() => undefined));
|
||||
mocks.impactAsync.mockResolvedValue(undefined);
|
||||
mocks.selectionAsync.mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it("triggers haptic feedback without waiting for the clipboard promise", () => {
|
||||
@@ -42,49 +31,4 @@ describe("copyTextWithHaptic", () => {
|
||||
expect(mocks.setStringAsync).toHaveBeenCalledWith("trace-123");
|
||||
expect(mocks.impactAsync).toHaveBeenCalledWith("light");
|
||||
});
|
||||
|
||||
it("preserves selection feedback for thread work rows", () => {
|
||||
copyTextWithHaptic("work output", {
|
||||
target: "thread-work-row",
|
||||
feedback: "selection",
|
||||
});
|
||||
|
||||
expect(mocks.setStringAsync).toHaveBeenCalledWith("work output");
|
||||
expect(mocks.selectionAsync).toHaveBeenCalledOnce();
|
||||
expect(mocks.impactAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("reports structured failures without including clipboard contents", async () => {
|
||||
const clipboardCause = new Error("native clipboard failure");
|
||||
const hapticCause = new Error("native haptic failure");
|
||||
const consoleError = vi.spyOn(console, "error").mockImplementation(() => undefined);
|
||||
mocks.setStringAsync.mockRejectedValueOnce(clipboardCause);
|
||||
mocks.impactAsync.mockRejectedValueOnce(hapticCause);
|
||||
|
||||
copyTextWithHaptic("secret clipboard contents", { target: "connection-trace-id" });
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(consoleError).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
const failures = consoleError.mock.calls.map(([failure]) => failure);
|
||||
const clipboardError = failures.find(
|
||||
(failure) => failure instanceof CopyTextClipboardWriteError,
|
||||
);
|
||||
expect(clipboardError).toBeInstanceOf(CopyTextClipboardWriteError);
|
||||
expect(clipboardError).toMatchObject({
|
||||
target: "connection-trace-id",
|
||||
cause: clipboardCause,
|
||||
});
|
||||
expect((clipboardError as Error).message).not.toContain("secret clipboard contents");
|
||||
|
||||
const hapticError = failures.find((failure) => failure instanceof CopyTextHapticFeedbackError);
|
||||
expect(hapticError).toBeInstanceOf(CopyTextHapticFeedbackError);
|
||||
expect(hapticError).toMatchObject({
|
||||
target: "connection-trace-id",
|
||||
feedback: "light-impact",
|
||||
cause: hapticCause,
|
||||
});
|
||||
expect((hapticError as Error).message).not.toContain("secret clipboard contents");
|
||||
});
|
||||
});
|
||||
@@ -1,70 +1,7 @@
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Clipboard from "expo-clipboard";
|
||||
import * as Haptics from "expo-haptics";
|
||||
|
||||
export class CopyTextClipboardWriteError extends Schema.TaggedErrorClass<CopyTextClipboardWriteError>()(
|
||||
"CopyTextClipboardWriteError",
|
||||
{
|
||||
target: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to copy ${this.target} to the clipboard.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class CopyTextHapticFeedbackError extends Schema.TaggedErrorClass<CopyTextHapticFeedbackError>()(
|
||||
"CopyTextHapticFeedbackError",
|
||||
{
|
||||
target: Schema.String,
|
||||
feedback: Schema.Literals(["light-impact", "selection"]),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to trigger ${this.feedback} haptic feedback after copying ${this.target}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export function copyTextWithHaptic(
|
||||
value: string,
|
||||
options: {
|
||||
readonly target?: string;
|
||||
readonly feedback?: "light-impact" | "selection";
|
||||
} = {},
|
||||
): void {
|
||||
const target = options.target ?? "text";
|
||||
const feedback = options.feedback ?? "light-impact";
|
||||
|
||||
void (async () => {
|
||||
try {
|
||||
await Clipboard.setStringAsync(value);
|
||||
} catch (cause) {
|
||||
console.error(
|
||||
new CopyTextClipboardWriteError({
|
||||
target,
|
||||
cause,
|
||||
}),
|
||||
);
|
||||
}
|
||||
})();
|
||||
|
||||
void (async () => {
|
||||
try {
|
||||
if (feedback === "selection") {
|
||||
await Haptics.selectionAsync();
|
||||
} else {
|
||||
await Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light);
|
||||
}
|
||||
} catch (cause) {
|
||||
console.error(
|
||||
new CopyTextHapticFeedbackError({
|
||||
target,
|
||||
feedback,
|
||||
cause,
|
||||
}),
|
||||
);
|
||||
}
|
||||
})();
|
||||
export function copyTextWithHaptic(value: string): void {
|
||||
void Clipboard.setStringAsync(value);
|
||||
void Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light);
|
||||
}
|
||||
@@ -11,12 +11,7 @@ import {
|
||||
type OrchestrationThreadActivity,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import {
|
||||
buildThreadFeed,
|
||||
deriveThreadFeedPresentation,
|
||||
type ThreadFeedActivity,
|
||||
type ThreadFeedEntry,
|
||||
} from "./threadActivity";
|
||||
import { buildThreadFeed, deriveThreadFeedPresentation } from "./threadActivity";
|
||||
|
||||
function makeActivity(
|
||||
input: Partial<OrchestrationThreadActivity> &
|
||||
@@ -91,7 +86,7 @@ describe("buildThreadFeed", () => {
|
||||
],
|
||||
});
|
||||
|
||||
const feed = buildThreadFeed(thread);
|
||||
const feed = buildThreadFeed(thread, [], null);
|
||||
expect(feed).toMatchObject([
|
||||
{
|
||||
type: "activity-group",
|
||||
@@ -149,7 +144,7 @@ describe("buildThreadFeed", () => {
|
||||
],
|
||||
});
|
||||
|
||||
const feed = buildThreadFeed(thread);
|
||||
const feed = buildThreadFeed(thread, [], null);
|
||||
const group = feed[0];
|
||||
|
||||
expect(group).toMatchObject({
|
||||
@@ -214,7 +209,7 @@ describe("buildThreadFeed", () => {
|
||||
],
|
||||
});
|
||||
|
||||
const group = buildThreadFeed(thread)[0];
|
||||
const group = buildThreadFeed(thread, [], null)[0];
|
||||
expect(group).toMatchObject({ type: "activity-group" });
|
||||
if (!group || group.type !== "activity-group") {
|
||||
return;
|
||||
@@ -276,7 +271,7 @@ describe("buildThreadFeed", () => {
|
||||
],
|
||||
});
|
||||
|
||||
const feed = buildThreadFeed(thread);
|
||||
const feed = buildThreadFeed(thread, [], null);
|
||||
const collapsed = deriveThreadFeedPresentation(feed, thread.latestTurn, new Set());
|
||||
expect(collapsed.map((entry) => entry.id)).toEqual(["turn-fold:turn-1", "assistant-final"]);
|
||||
expect(collapsed[0]).toMatchObject({
|
||||
@@ -364,7 +359,7 @@ describe("buildThreadFeed", () => {
|
||||
],
|
||||
});
|
||||
|
||||
const feed = buildThreadFeed(thread);
|
||||
const feed = buildThreadFeed(thread, [], null);
|
||||
const collapsed = deriveThreadFeedPresentation(feed, thread.latestTurn, new Set());
|
||||
expect(collapsed.find((entry) => entry.type === "turn-fold")).toMatchObject({
|
||||
turnId: firstTurnId,
|
||||
@@ -404,65 +399,11 @@ describe("buildThreadFeed", () => {
|
||||
],
|
||||
});
|
||||
|
||||
const feed = buildThreadFeed(thread);
|
||||
const feed = buildThreadFeed(thread, [], null);
|
||||
expect(deriveThreadFeedPresentation(feed, thread.latestTurn, new Set())).toEqual(feed);
|
||||
expect(feed[0]).toMatchObject({
|
||||
type: "activity-group",
|
||||
activities: [{ status: "failure" }],
|
||||
});
|
||||
});
|
||||
|
||||
it("models work-log overflow as list rows", () => {
|
||||
const activity = (
|
||||
id: string,
|
||||
createdAt: string,
|
||||
status: ThreadFeedActivity["status"] = "success",
|
||||
): ThreadFeedActivity => ({
|
||||
id,
|
||||
createdAt,
|
||||
turnId: null,
|
||||
summary: `Tool ${id}`,
|
||||
detail: null,
|
||||
fullDetail: null,
|
||||
copyText: id,
|
||||
icon: "command",
|
||||
toolLike: true,
|
||||
status,
|
||||
});
|
||||
const feed: ThreadFeedEntry[] = [
|
||||
{
|
||||
type: "activity-group",
|
||||
id: "work-group-1",
|
||||
createdAt: "2026-04-01T00:00:01.000Z",
|
||||
turnId: null,
|
||||
activities: [
|
||||
activity("activity-1", "2026-04-01T00:00:01.000Z"),
|
||||
activity("activity-neutral", "2026-04-01T00:00:02.000Z", "neutral"),
|
||||
activity("activity-2", "2026-04-01T00:00:03.000Z"),
|
||||
activity("activity-3", "2026-04-01T00:00:04.000Z"),
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
const collapsed = deriveThreadFeedPresentation(feed, null, new Set());
|
||||
expect(collapsed.map((entry) => entry.id)).toEqual(["activity-3", "work-toggle:work-group-1"]);
|
||||
expect(collapsed[1]).toMatchObject({
|
||||
type: "work-toggle",
|
||||
groupId: "work-group-1",
|
||||
hiddenCount: 2,
|
||||
expanded: false,
|
||||
});
|
||||
|
||||
const expanded = deriveThreadFeedPresentation(feed, null, new Set(), new Set(["work-group-1"]));
|
||||
expect(expanded.map((entry) => entry.id)).toEqual([
|
||||
"activity-1",
|
||||
"activity-2",
|
||||
"activity-3",
|
||||
"work-toggle:work-group-1",
|
||||
]);
|
||||
expect(expanded.at(-1)).toMatchObject({
|
||||
type: "work-toggle",
|
||||
expanded: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,6 @@
|
||||
import { ApprovalRequestId, isToolLifecycleItemType } from "@t3tools/contracts";
|
||||
import type {
|
||||
MessageId,
|
||||
OrchestrationLatestTurn,
|
||||
OrchestrationThread,
|
||||
OrchestrationThreadActivity,
|
||||
@@ -9,6 +10,7 @@ import type {
|
||||
} from "@t3tools/contracts";
|
||||
import { formatDuration } from "@t3tools/shared/orchestrationTiming";
|
||||
|
||||
import type { QueuedThreadMessage } from "../state/thread-outbox-model";
|
||||
import * as Arr from "effect/Array";
|
||||
import * as Order from "effect/Order";
|
||||
|
||||
@@ -55,8 +57,6 @@ export interface ThreadFeedActivity {
|
||||
readonly status: "success" | "failure" | "neutral" | null;
|
||||
}
|
||||
|
||||
const MAX_VISIBLE_WORK_LOG_ENTRIES = 1;
|
||||
|
||||
type WorkLogToolLifecycleStatus = "inProgress" | "completed" | "failed" | "declined" | "stopped";
|
||||
|
||||
interface WorkLogEntry {
|
||||
@@ -88,6 +88,13 @@ type RawThreadFeedEntry =
|
||||
readonly createdAt: string;
|
||||
readonly message: OrchestrationThread["messages"][number];
|
||||
}
|
||||
| {
|
||||
readonly type: "queued-message";
|
||||
readonly id: string;
|
||||
readonly createdAt: string;
|
||||
readonly queuedMessage: QueuedThreadMessage;
|
||||
readonly sending: boolean;
|
||||
}
|
||||
| {
|
||||
readonly type: "activity";
|
||||
readonly id: string;
|
||||
@@ -97,7 +104,7 @@ type RawThreadFeedEntry =
|
||||
};
|
||||
|
||||
export type ThreadFeedEntry =
|
||||
| Extract<RawThreadFeedEntry, { type: "message" }>
|
||||
| Extract<RawThreadFeedEntry, { type: "message" | "queued-message" }>
|
||||
| {
|
||||
readonly type: "activity-group";
|
||||
readonly id: string;
|
||||
@@ -105,16 +112,6 @@ export type ThreadFeedEntry =
|
||||
readonly turnId: TurnId | null;
|
||||
readonly activities: ReadonlyArray<ThreadFeedActivity>;
|
||||
}
|
||||
| {
|
||||
readonly type: "work-toggle";
|
||||
readonly id: string;
|
||||
readonly createdAt: string;
|
||||
readonly turnId: TurnId | null;
|
||||
readonly groupId: string;
|
||||
readonly hiddenCount: number;
|
||||
readonly expanded: boolean;
|
||||
readonly onlyToolActivities: boolean;
|
||||
}
|
||||
| {
|
||||
readonly type: "turn-fold";
|
||||
readonly id: string;
|
||||
@@ -1104,11 +1101,8 @@ export function deriveThreadFeedPresentation(
|
||||
feed: ReadonlyArray<ThreadFeedEntry>,
|
||||
latestTurn: ThreadFeedLatestTurn | null,
|
||||
expandedTurnIds: ReadonlySet<TurnId>,
|
||||
expandedWorkGroupIds: ReadonlySet<string> = new Set(),
|
||||
): ThreadFeedEntry[] {
|
||||
const sourceFeed = feed.filter(
|
||||
(entry) => entry.type !== "turn-fold" && entry.type !== "work-toggle",
|
||||
);
|
||||
const sourceFeed = feed.filter((entry) => entry.type !== "turn-fold");
|
||||
const foldsByAnchorId = deriveThreadFeedTurnFolds(sourceFeed, latestTurn);
|
||||
const collapsedEntryIds = new Set<string>();
|
||||
for (const fold of foldsByAnchorId.values()) {
|
||||
@@ -1133,62 +1127,12 @@ export function deriveThreadFeedPresentation(
|
||||
});
|
||||
}
|
||||
if (!collapsedEntryIds.has(entry.id)) {
|
||||
appendPresentedFeedEntry(result, entry, expandedWorkGroupIds);
|
||||
result.push(entry);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function appendPresentedFeedEntry(
|
||||
result: ThreadFeedEntry[],
|
||||
entry: Exclude<ThreadFeedEntry, { readonly type: "turn-fold" | "work-toggle" }>,
|
||||
expandedWorkGroupIds: ReadonlySet<string>,
|
||||
): void {
|
||||
if (entry.type !== "activity-group") {
|
||||
result.push(entry);
|
||||
return;
|
||||
}
|
||||
|
||||
const activities = entry.activities.filter(
|
||||
(activity) => !(activity.toolLike && activity.status === "neutral"),
|
||||
);
|
||||
if (activities.length === 0) {
|
||||
return;
|
||||
}
|
||||
if (activities.length <= MAX_VISIBLE_WORK_LOG_ENTRIES) {
|
||||
result.push({
|
||||
...entry,
|
||||
activities,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const groupId = entry.id;
|
||||
const expanded = expandedWorkGroupIds.has(groupId);
|
||||
const hiddenCount = activities.length - MAX_VISIBLE_WORK_LOG_ENTRIES;
|
||||
const visibleActivities = expanded ? activities : activities.slice(-MAX_VISIBLE_WORK_LOG_ENTRIES);
|
||||
|
||||
for (const activity of visibleActivities) {
|
||||
result.push({
|
||||
type: "activity-group",
|
||||
id: activity.id,
|
||||
createdAt: activity.createdAt,
|
||||
turnId: activity.turnId,
|
||||
activities: [activity],
|
||||
});
|
||||
}
|
||||
result.push({
|
||||
type: "work-toggle",
|
||||
id: `work-toggle:${groupId}`,
|
||||
createdAt: entry.createdAt,
|
||||
turnId: entry.turnId,
|
||||
groupId,
|
||||
hiddenCount,
|
||||
expanded,
|
||||
onlyToolActivities: activities.every((activity) => activity.toolLike),
|
||||
});
|
||||
}
|
||||
|
||||
export function derivePendingApprovals(
|
||||
activities: ReadonlyArray<OrchestrationThreadActivity>,
|
||||
): PendingApproval[] {
|
||||
@@ -1311,6 +1255,8 @@ export function buildPendingUserInputAnswers(
|
||||
|
||||
export function buildThreadFeed(
|
||||
thread: OrchestrationThread,
|
||||
queuedMessages: ReadonlyArray<QueuedThreadMessage>,
|
||||
dispatchingQueuedMessageId: MessageId | null,
|
||||
options?: {
|
||||
readonly loadedMessages?: ReadonlyArray<OrchestrationThread["messages"][number]>;
|
||||
},
|
||||
@@ -1327,6 +1273,13 @@ export function buildThreadFeed(
|
||||
createdAt: message.createdAt,
|
||||
message,
|
||||
})),
|
||||
...queuedMessages.map<RawThreadFeedEntry>((queuedMessage) => ({
|
||||
type: "queued-message",
|
||||
id: queuedMessage.messageId,
|
||||
createdAt: queuedMessage.createdAt,
|
||||
queuedMessage,
|
||||
sending: queuedMessage.messageId === dispatchingQueuedMessageId,
|
||||
})),
|
||||
...workLogEntries
|
||||
.filter((entry) => {
|
||||
if (options?.loadedMessages === undefined) {
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
isThreadFeedNearEnd,
|
||||
resolveThreadFeedBottomInset,
|
||||
threadFeedDistanceFromEnd,
|
||||
} from "./threadFeedLayout";
|
||||
|
||||
describe("thread feed layout", () => {
|
||||
it("accounts for the bottom inset when measuring distance from the end", () => {
|
||||
const metrics = {
|
||||
contentHeight: 900,
|
||||
viewportHeight: 600,
|
||||
offsetY: 380,
|
||||
bottomInset: 100,
|
||||
};
|
||||
|
||||
expect(threadFeedDistanceFromEnd(metrics)).toBe(20);
|
||||
expect(isThreadFeedNearEnd(metrics, 50)).toBe(true);
|
||||
expect(isThreadFeedNearEnd(metrics, 10)).toBe(false);
|
||||
});
|
||||
|
||||
it("does not double count chrome already included in the measured composer overlay", () => {
|
||||
expect(
|
||||
resolveThreadFeedBottomInset({
|
||||
estimatedOverlayHeight: 162,
|
||||
measuredOverlayHeight: 182,
|
||||
gap: 8,
|
||||
}),
|
||||
).toBe(190);
|
||||
});
|
||||
});
|
||||
@@ -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,5 +1,4 @@
|
||||
import { EnvironmentId, MessageId, ThreadId } from "@t3tools/contracts";
|
||||
import * as Schema from "effect/Schema";
|
||||
import type { EnvironmentId, MessageId } from "@t3tools/contracts";
|
||||
import { Atom, type AtomRegistry } from "effect/unstable/reactivity";
|
||||
|
||||
import {
|
||||
@@ -9,27 +8,6 @@ import {
|
||||
} from "./thread-outbox-model";
|
||||
import type { ThreadOutboxStorage } from "./thread-outbox-storage";
|
||||
|
||||
export class ThreadOutboxManagerError extends Schema.TaggedErrorClass<ThreadOutboxManagerError>()(
|
||||
"ThreadOutboxManagerError",
|
||||
{
|
||||
operation: Schema.Literals([
|
||||
"load",
|
||||
"enqueue",
|
||||
"remove",
|
||||
"clear-environment-load",
|
||||
"clear-environment-remove",
|
||||
]),
|
||||
environmentId: Schema.NullOr(EnvironmentId),
|
||||
threadId: Schema.NullOr(ThreadId),
|
||||
messageId: Schema.NullOr(MessageId),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Thread outbox operation ${this.operation} failed for environment ${this.environmentId ?? "unknown"}, thread ${this.threadId ?? "unknown"}, message ${this.messageId ?? "unknown"}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export interface ThreadOutboxManagerOptions {
|
||||
readonly registry: AtomRegistry.AtomRegistry;
|
||||
readonly storage: ThreadOutboxStorage;
|
||||
@@ -71,51 +49,22 @@ export function createThreadOutboxManager(options: ThreadOutboxManagerOptions) {
|
||||
loadPromise = serialize(async () => {
|
||||
const persistedMessages = await options.storage.load();
|
||||
setMessages([...persistedMessages, ...currentMessages()]);
|
||||
}).catch((cause) => {
|
||||
}).catch((error) => {
|
||||
loadPromise = null;
|
||||
warn(
|
||||
"[thread-outbox] failed to load persisted messages",
|
||||
new ThreadOutboxManagerError({
|
||||
operation: "load",
|
||||
environmentId: null,
|
||||
threadId: null,
|
||||
messageId: null,
|
||||
cause,
|
||||
}),
|
||||
);
|
||||
warn("[thread-outbox] failed to load persisted messages", error);
|
||||
});
|
||||
return loadPromise;
|
||||
};
|
||||
|
||||
const enqueue = (message: QueuedThreadMessage): Promise<void> =>
|
||||
serialize(async () => {
|
||||
try {
|
||||
await options.storage.write(message);
|
||||
} catch (cause) {
|
||||
throw new ThreadOutboxManagerError({
|
||||
operation: "enqueue",
|
||||
environmentId: message.environmentId,
|
||||
threadId: message.threadId,
|
||||
messageId: message.messageId,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
await options.storage.write(message);
|
||||
setMessages([...currentMessages(), message]);
|
||||
});
|
||||
|
||||
const remove = (message: QueuedThreadMessage): Promise<void> =>
|
||||
serialize(async () => {
|
||||
try {
|
||||
await options.storage.remove(message);
|
||||
} catch (cause) {
|
||||
throw new ThreadOutboxManagerError({
|
||||
operation: "remove",
|
||||
environmentId: message.environmentId,
|
||||
threadId: message.threadId,
|
||||
messageId: message.messageId,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
await options.storage.remove(message);
|
||||
setMessages(
|
||||
currentMessages().filter((candidate) => candidate.messageId !== message.messageId),
|
||||
);
|
||||
@@ -123,17 +72,8 @@ export function createThreadOutboxManager(options: ThreadOutboxManagerOptions) {
|
||||
|
||||
const clearEnvironment = (environmentId: EnvironmentId): Promise<void> =>
|
||||
serialize(async () => {
|
||||
const persisted = await options.storage.load().catch((cause) => {
|
||||
warn(
|
||||
"[thread-outbox] failed to load messages while clearing environment",
|
||||
new ThreadOutboxManagerError({
|
||||
operation: "clear-environment-load",
|
||||
environmentId,
|
||||
threadId: null,
|
||||
messageId: null,
|
||||
cause,
|
||||
}),
|
||||
);
|
||||
const persisted = await options.storage.load().catch((error) => {
|
||||
warn("[thread-outbox] failed to load messages while clearing environment", error);
|
||||
return [];
|
||||
});
|
||||
const allMessages = flattenQueuedThreadMessages(
|
||||
@@ -148,17 +88,8 @@ export function createThreadOutboxManager(options: ThreadOutboxManagerOptions) {
|
||||
try {
|
||||
await options.storage.remove(message);
|
||||
removedMessageIds.add(message.messageId);
|
||||
} catch (cause) {
|
||||
warn(
|
||||
"[thread-outbox] failed to clear persisted message",
|
||||
new ThreadOutboxManagerError({
|
||||
operation: "clear-environment-remove",
|
||||
environmentId: message.environmentId,
|
||||
threadId: message.threadId,
|
||||
messageId: message.messageId,
|
||||
cause,
|
||||
}),
|
||||
);
|
||||
} catch (error) {
|
||||
warn("[thread-outbox] failed to clear persisted message", error);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -1,38 +1,32 @@
|
||||
import { isTransportConnectionErrorMessage } from "@t3tools/client-runtime/errors";
|
||||
import type { EnvironmentShellStatus } from "@t3tools/client-runtime/state/shell";
|
||||
import {
|
||||
CommandId,
|
||||
EnvironmentId,
|
||||
IsoDateTime,
|
||||
MessageId,
|
||||
ModelSelection,
|
||||
ProviderInteractionMode,
|
||||
RuntimeMode,
|
||||
ThreadId,
|
||||
type ModelSelection as ModelSelectionType,
|
||||
type ProviderInteractionMode as ProviderInteractionModeType,
|
||||
type RuntimeMode as RuntimeModeType,
|
||||
} from "@t3tools/contracts";
|
||||
import { CommandId, EnvironmentId, IsoDateTime, MessageId, ThreadId } from "@t3tools/contracts";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import { DraftComposerImageAttachmentSchema } from "../lib/composer-image-schema";
|
||||
import type { DraftComposerImageAttachment } from "../lib/composerImages";
|
||||
import { scopedThreadKey } from "../lib/scopedEntities";
|
||||
|
||||
const THREAD_OUTBOX_SCHEMA_VERSION = 2;
|
||||
const THREAD_OUTBOX_SCHEMA_VERSION = 1;
|
||||
const THREAD_OUTBOX_MAX_RETRY_DELAY_MS = 16_000;
|
||||
|
||||
const DraftComposerImageAttachmentSchema = Schema.Struct({
|
||||
id: Schema.String,
|
||||
previewUri: Schema.String,
|
||||
type: Schema.Literal("image"),
|
||||
name: Schema.String,
|
||||
mimeType: Schema.String,
|
||||
sizeBytes: Schema.Number,
|
||||
dataUrl: Schema.String,
|
||||
});
|
||||
|
||||
export const QueuedThreadMessageSchema = Schema.Struct({
|
||||
schemaVersion: Schema.Literals([1, THREAD_OUTBOX_SCHEMA_VERSION]),
|
||||
schemaVersion: Schema.Literal(THREAD_OUTBOX_SCHEMA_VERSION),
|
||||
environmentId: EnvironmentId,
|
||||
threadId: ThreadId,
|
||||
messageId: MessageId,
|
||||
commandId: CommandId,
|
||||
text: Schema.String,
|
||||
attachments: Schema.Array(DraftComposerImageAttachmentSchema),
|
||||
modelSelection: Schema.optional(ModelSelection),
|
||||
runtimeMode: Schema.optional(RuntimeMode),
|
||||
interactionMode: Schema.optional(ProviderInteractionMode),
|
||||
createdAt: IsoDateTime,
|
||||
});
|
||||
|
||||
@@ -46,37 +40,9 @@ export interface QueuedThreadMessage {
|
||||
readonly commandId: CommandId;
|
||||
readonly text: string;
|
||||
readonly attachments: ReadonlyArray<DraftComposerImageAttachment>;
|
||||
readonly modelSelection?: ModelSelectionType;
|
||||
readonly runtimeMode?: RuntimeModeType;
|
||||
readonly interactionMode?: ProviderInteractionModeType;
|
||||
readonly createdAt: string;
|
||||
}
|
||||
|
||||
export interface ThreadSettingsSnapshot {
|
||||
readonly modelSelection: ModelSelectionType;
|
||||
readonly runtimeMode: RuntimeModeType;
|
||||
readonly interactionMode: ProviderInteractionModeType;
|
||||
}
|
||||
|
||||
export function resolveQueuedThreadSettings(
|
||||
message: QueuedThreadMessage,
|
||||
thread: ThreadSettingsSnapshot,
|
||||
): ThreadSettingsSnapshot {
|
||||
return {
|
||||
modelSelection: message.modelSelection ?? thread.modelSelection,
|
||||
runtimeMode: message.runtimeMode ?? thread.runtimeMode,
|
||||
interactionMode: message.interactionMode ?? thread.interactionMode,
|
||||
};
|
||||
}
|
||||
|
||||
export function modelSelectionsEqual(left: ModelSelectionType, right: ModelSelectionType): boolean {
|
||||
return (
|
||||
left.instanceId === right.instanceId &&
|
||||
left.model === right.model &&
|
||||
JSON.stringify(left.options ?? null) === JSON.stringify(right.options ?? null)
|
||||
);
|
||||
}
|
||||
|
||||
export function encodeQueuedThreadMessage(message: QueuedThreadMessage): unknown {
|
||||
return encodeStoredQueuedThreadMessage({
|
||||
schemaVersion: THREAD_OUTBOX_SCHEMA_VERSION,
|
||||
@@ -153,21 +119,3 @@ export function shouldRetryThreadOutboxDelivery(error: unknown): boolean {
|
||||
}
|
||||
return isTransportConnectionErrorMessage(errorMessage(error));
|
||||
}
|
||||
|
||||
export type ThreadOutboxCommandStage = "settings-sync" | "start-turn";
|
||||
export type ThreadOutboxFailureAction = "retry" | "discard";
|
||||
|
||||
export function resolveThreadOutboxFailureAction(input: {
|
||||
readonly stage: ThreadOutboxCommandStage;
|
||||
readonly error: unknown;
|
||||
readonly interrupted: boolean;
|
||||
}): ThreadOutboxFailureAction {
|
||||
if (
|
||||
input.stage === "settings-sync" ||
|
||||
input.interrupted ||
|
||||
shouldRetryThreadOutboxDelivery(input.error)
|
||||
) {
|
||||
return "retry";
|
||||
}
|
||||
return "discard";
|
||||
}
|
||||
@@ -1,5 +1,4 @@
|
||||
import { EnvironmentId, MessageId, ThreadId } from "@t3tools/contracts";
|
||||
import * as Schema from "effect/Schema";
|
||||
import type { MessageId } from "@t3tools/contracts";
|
||||
|
||||
import {
|
||||
decodeQueuedThreadMessage,
|
||||
@@ -9,22 +8,6 @@ import {
|
||||
|
||||
const THREAD_OUTBOX_DIRECTORY = "thread-outbox";
|
||||
|
||||
export class ThreadOutboxStorageError extends Schema.TaggedErrorClass<ThreadOutboxStorageError>()(
|
||||
"ThreadOutboxStorageError",
|
||||
{
|
||||
operation: Schema.Literals(["load", "read-message", "write", "remove"]),
|
||||
environmentId: Schema.NullOr(EnvironmentId),
|
||||
threadId: Schema.NullOr(ThreadId),
|
||||
messageId: Schema.NullOr(MessageId),
|
||||
fileName: Schema.NullOr(Schema.String),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Thread outbox storage operation ${this.operation} failed for environment ${this.environmentId ?? "unknown"}, thread ${this.threadId ?? "unknown"}, message ${this.messageId ?? "unknown"}, file ${this.fileName ?? "unknown"}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export interface ThreadOutboxStorage {
|
||||
readonly load: () => Promise<ReadonlyArray<QueuedThreadMessage>>;
|
||||
readonly write: (message: QueuedThreadMessage) => Promise<void>;
|
||||
@@ -49,78 +32,33 @@ async function getMessageFile(messageId: MessageId) {
|
||||
|
||||
export const expoThreadOutboxStorage: ThreadOutboxStorage = {
|
||||
load: async () => {
|
||||
const { File } = await import("expo-file-system");
|
||||
const directory = await getOutboxDirectory();
|
||||
const messages: QueuedThreadMessage[] = [];
|
||||
try {
|
||||
const { File } = await import("expo-file-system");
|
||||
const directory = await getOutboxDirectory();
|
||||
|
||||
for (const entry of directory.list()) {
|
||||
if (!(entry instanceof File) || !entry.name.endsWith(".json")) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
messages.push(decodeQueuedThreadMessage(JSON.parse(await entry.text()) as unknown));
|
||||
} catch (cause) {
|
||||
console.warn(
|
||||
"[thread-outbox] ignored invalid persisted message",
|
||||
new ThreadOutboxStorageError({
|
||||
operation: "read-message",
|
||||
environmentId: null,
|
||||
threadId: null,
|
||||
messageId: null,
|
||||
fileName: entry.name,
|
||||
cause,
|
||||
}),
|
||||
);
|
||||
}
|
||||
for (const entry of directory.list()) {
|
||||
if (!(entry instanceof File) || !entry.name.endsWith(".json")) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
messages.push(decodeQueuedThreadMessage(JSON.parse(await entry.text()) as unknown));
|
||||
} catch (error) {
|
||||
console.warn("[thread-outbox] ignored invalid persisted message", entry.name, error);
|
||||
}
|
||||
} catch (cause) {
|
||||
throw new ThreadOutboxStorageError({
|
||||
operation: "load",
|
||||
environmentId: null,
|
||||
threadId: null,
|
||||
messageId: null,
|
||||
fileName: null,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
return messages;
|
||||
},
|
||||
write: async (message) => {
|
||||
const fileName = messageFileName(message.messageId);
|
||||
try {
|
||||
const file = await getMessageFile(message.messageId);
|
||||
if (!file.exists) {
|
||||
file.create({ intermediates: true, overwrite: true });
|
||||
}
|
||||
file.write(JSON.stringify(encodeQueuedThreadMessage(message)));
|
||||
} catch (cause) {
|
||||
throw new ThreadOutboxStorageError({
|
||||
operation: "write",
|
||||
environmentId: message.environmentId,
|
||||
threadId: message.threadId,
|
||||
messageId: message.messageId,
|
||||
fileName,
|
||||
cause,
|
||||
});
|
||||
const file = await getMessageFile(message.messageId);
|
||||
if (!file.exists) {
|
||||
file.create({ intermediates: true, overwrite: true });
|
||||
}
|
||||
file.write(JSON.stringify(encodeQueuedThreadMessage(message)));
|
||||
},
|
||||
remove: async (message) => {
|
||||
const fileName = messageFileName(message.messageId);
|
||||
try {
|
||||
const file = await getMessageFile(message.messageId);
|
||||
if (file.exists) {
|
||||
file.delete();
|
||||
}
|
||||
} catch (cause) {
|
||||
throw new ThreadOutboxStorageError({
|
||||
operation: "remove",
|
||||
environmentId: message.environmentId,
|
||||
threadId: message.threadId,
|
||||
messageId: message.messageId,
|
||||
fileName,
|
||||
cause,
|
||||
});
|
||||
const file = await getMessageFile(message.messageId);
|
||||
if (file.exists) {
|
||||
file.delete();
|
||||
}
|
||||
},
|
||||
};
|
||||
@@ -1,26 +1,16 @@
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import {
|
||||
CommandId,
|
||||
EnvironmentId,
|
||||
MessageId,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { CommandId, EnvironmentId, MessageId, ThreadId } from "@t3tools/contracts";
|
||||
import { AtomRegistry } from "effect/unstable/reactivity";
|
||||
|
||||
import {
|
||||
decodeQueuedThreadMessage,
|
||||
encodeQueuedThreadMessage,
|
||||
groupQueuedThreadMessages,
|
||||
modelSelectionsEqual,
|
||||
resolveThreadOutboxDeliveryAction,
|
||||
resolveThreadOutboxFailureAction,
|
||||
resolveQueuedThreadSettings,
|
||||
shouldRetryThreadOutboxDelivery,
|
||||
threadOutboxRetryDelayMs,
|
||||
type QueuedThreadMessage,
|
||||
} from "./thread-outbox-model";
|
||||
import { createThreadOutboxManager, ThreadOutboxManagerError } from "./thread-outbox-manager";
|
||||
import { createThreadOutboxManager } from "./thread-outbox-manager";
|
||||
import type { ThreadOutboxStorage } from "./thread-outbox-storage";
|
||||
|
||||
function queuedMessage(input: {
|
||||
@@ -76,54 +66,6 @@ describe("thread outbox", () => {
|
||||
).toThrow();
|
||||
});
|
||||
|
||||
it("persists the exact selector snapshot while remaining compatible with v1 messages", () => {
|
||||
const legacyMessage = queuedMessage({
|
||||
messageId: "message-1",
|
||||
createdAt: "2026-06-08T10:00:01.000Z",
|
||||
});
|
||||
const selectedMessage = {
|
||||
...legacyMessage,
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5.4",
|
||||
options: [{ id: "reasoningEffort", value: "xhigh" }],
|
||||
},
|
||||
runtimeMode: "approval-required",
|
||||
interactionMode: "plan",
|
||||
} satisfies QueuedThreadMessage;
|
||||
|
||||
expect(decodeQueuedThreadMessage(encodeQueuedThreadMessage(selectedMessage))).toEqual(
|
||||
selectedMessage,
|
||||
);
|
||||
expect(
|
||||
resolveQueuedThreadSettings(legacyMessage, {
|
||||
modelSelection: selectedMessage.modelSelection,
|
||||
runtimeMode: selectedMessage.runtimeMode,
|
||||
interactionMode: selectedMessage.interactionMode,
|
||||
}),
|
||||
).toEqual({
|
||||
modelSelection: selectedMessage.modelSelection,
|
||||
runtimeMode: selectedMessage.runtimeMode,
|
||||
interactionMode: selectedMessage.interactionMode,
|
||||
});
|
||||
});
|
||||
|
||||
it("compares model options as part of the queued settings change", () => {
|
||||
const base = {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5.4",
|
||||
options: [{ id: "reasoningEffort", value: "medium" }],
|
||||
} as const;
|
||||
|
||||
expect(modelSelectionsEqual(base, base)).toBe(true);
|
||||
expect(
|
||||
modelSelectionsEqual(base, {
|
||||
...base,
|
||||
options: [{ id: "reasoningEffort", value: "xhigh" }],
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("backs off queued delivery retries and caps them at sixteen seconds", () => {
|
||||
expect([1, 2, 3, 4, 5, 6].map(threadOutboxRetryDelayMs)).toEqual([
|
||||
1_000, 2_000, 4_000, 8_000, 16_000, 16_000,
|
||||
@@ -207,48 +149,9 @@ describe("thread outbox", () => {
|
||||
registry.dispose();
|
||||
});
|
||||
|
||||
it("reports structured load failures and permits a retry", async () => {
|
||||
const registry = AtomRegistry.make();
|
||||
const loadCause = new Error("storage unavailable");
|
||||
const warnings: Array<{ message: string; error: unknown }> = [];
|
||||
let loadCalls = 0;
|
||||
const manager = createThreadOutboxManager({
|
||||
registry,
|
||||
storage: {
|
||||
load: async () => {
|
||||
loadCalls += 1;
|
||||
if (loadCalls === 1) throw loadCause;
|
||||
return [];
|
||||
},
|
||||
write: async () => undefined,
|
||||
remove: async () => undefined,
|
||||
},
|
||||
warn: (message, error) => warnings.push({ message, error }),
|
||||
});
|
||||
|
||||
await manager.load();
|
||||
expect(warnings).toEqual([
|
||||
{
|
||||
message: "[thread-outbox] failed to load persisted messages",
|
||||
error: new ThreadOutboxManagerError({
|
||||
operation: "load",
|
||||
environmentId: null,
|
||||
threadId: null,
|
||||
messageId: null,
|
||||
cause: loadCause,
|
||||
}),
|
||||
},
|
||||
]);
|
||||
|
||||
await manager.load();
|
||||
expect(loadCalls).toBe(2);
|
||||
registry.dispose();
|
||||
});
|
||||
|
||||
it("keeps atom state aligned with durable writes and removals", async () => {
|
||||
const registry = AtomRegistry.make();
|
||||
const stored = new Map<MessageId, QueuedThreadMessage>();
|
||||
const removalCause = new Error("remove failed");
|
||||
let failRemoval = true;
|
||||
const storage: ThreadOutboxStorage = {
|
||||
load: async () => [...stored.values()],
|
||||
@@ -257,7 +160,7 @@ describe("thread outbox", () => {
|
||||
},
|
||||
remove: async (message) => {
|
||||
if (failRemoval) {
|
||||
throw removalCause;
|
||||
throw new Error("remove failed");
|
||||
}
|
||||
stored.delete(message.messageId);
|
||||
},
|
||||
@@ -273,15 +176,7 @@ describe("thread outbox", () => {
|
||||
"environment-1:thread-1": [message],
|
||||
});
|
||||
|
||||
await expect(manager.remove(message)).rejects.toEqual(
|
||||
new ThreadOutboxManagerError({
|
||||
operation: "remove",
|
||||
environmentId: message.environmentId,
|
||||
threadId: message.threadId,
|
||||
messageId: message.messageId,
|
||||
cause: removalCause,
|
||||
}),
|
||||
);
|
||||
await expect(manager.remove(message)).rejects.toThrow("remove failed");
|
||||
expect(registry.get(manager.queuedMessagesByThreadKeyAtom)).toEqual({
|
||||
"environment-1:thread-1": [message],
|
||||
});
|
||||
@@ -329,23 +224,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: {
|
||||
|
||||
+24
-19
@@ -1,6 +1,7 @@
|
||||
#!/usr/bin/env node
|
||||
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Logger from "effect/Logger";
|
||||
@@ -19,14 +20,6 @@ import { fromJsonStringPretty } from "@t3tools/shared/schemaJson";
|
||||
import { fromYaml } from "@t3tools/shared/schemaYaml";
|
||||
import { resolveSpawnCommand } from "@t3tools/shared/shell";
|
||||
import serverPackageJson from "../package.json" with { type: "json" };
|
||||
import {
|
||||
ServerCliBuildAssetMissingError,
|
||||
ServerCliCommandExitError,
|
||||
ServerCliDevelopmentIconSourceMissingError,
|
||||
ServerCliDevelopmentIconTargetMissingError,
|
||||
ServerCliPublishIconSourceMissingError,
|
||||
ServerCliPublishIconTargetMissingError,
|
||||
} from "./cliErrors.ts";
|
||||
|
||||
interface PackageJson {
|
||||
name: string;
|
||||
@@ -54,6 +47,11 @@ const WorkspaceConfig = Schema.Struct({
|
||||
type WorkspaceConfig = typeof WorkspaceConfig.Type;
|
||||
const decodeWorkspaceConfig = Schema.decodeEffect(fromYaml(WorkspaceConfig));
|
||||
|
||||
class CliError extends Data.TaggedError("CliError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
const RepoRoot = Effect.service(Path.Path).pipe(
|
||||
Effect.flatMap((path) => path.fromFileUrl(new URL("../../..", import.meta.url))),
|
||||
);
|
||||
@@ -66,17 +64,14 @@ const readWorkspaceConfig = Effect.fn("readWorkspaceConfig")(function* () {
|
||||
return yield* decodeWorkspaceConfig(workspaceYaml);
|
||||
});
|
||||
|
||||
const runCommand = Effect.fn("runCommand")(function* (command: ChildProcess.StandardCommand) {
|
||||
const runCommand = Effect.fn("runCommand")(function* (command: ChildProcess.Command) {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const child = yield* spawner.spawn(command);
|
||||
const exitCode = yield* child.exitCode;
|
||||
|
||||
if (exitCode !== 0) {
|
||||
return yield* new ServerCliCommandExitError({
|
||||
command: command.command,
|
||||
args: command.args,
|
||||
cwd: command.options.cwd,
|
||||
exitCode,
|
||||
return yield* new CliError({
|
||||
message: `Command exited with non-zero exit code (${exitCode})`,
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -100,10 +95,14 @@ const applyPublishIconOverrides = Effect.fn("applyPublishIconOverrides")(functio
|
||||
const backupPath = `${targetPath}.publish-bak`;
|
||||
|
||||
if (!(yield* fs.exists(sourcePath))) {
|
||||
return yield* new ServerCliPublishIconSourceMissingError({ sourcePath });
|
||||
return yield* new CliError({
|
||||
message: `Missing publish icon source: ${sourcePath}`,
|
||||
});
|
||||
}
|
||||
if (!(yield* fs.exists(targetPath))) {
|
||||
return yield* new ServerCliPublishIconTargetMissingError({ targetPath });
|
||||
return yield* new CliError({
|
||||
message: `Missing publish icon target: ${targetPath}. Run the build subcommand first.`,
|
||||
});
|
||||
}
|
||||
|
||||
yield* fs.copyFile(targetPath, backupPath);
|
||||
@@ -139,10 +138,14 @@ const applyDevelopmentIconOverrides = Effect.fn("applyDevelopmentIconOverrides")
|
||||
const targetPath = path.join(serverDir, override.targetRelativePath);
|
||||
|
||||
if (!(yield* fs.exists(sourcePath))) {
|
||||
return yield* new ServerCliDevelopmentIconSourceMissingError({ sourcePath });
|
||||
return yield* new CliError({
|
||||
message: `Missing development icon source: ${sourcePath}`,
|
||||
});
|
||||
}
|
||||
if (!(yield* fs.exists(targetPath))) {
|
||||
return yield* new ServerCliDevelopmentIconTargetMissingError({ targetPath });
|
||||
return yield* new CliError({
|
||||
message: `Missing development icon target: ${targetPath}. Build web first.`,
|
||||
});
|
||||
}
|
||||
|
||||
yield* fs.copyFile(sourcePath, targetPath);
|
||||
@@ -242,7 +245,9 @@ const publishCmd = Command.make(
|
||||
for (const relPath of ["dist/bin.mjs", "dist/client/index.html"]) {
|
||||
const abs = path.join(serverDir, relPath);
|
||||
if (!(yield* fs.exists(abs))) {
|
||||
return yield* new ServerCliBuildAssetMissingError({ assetPath: abs });
|
||||
return yield* new CliError({
|
||||
message: `Missing build asset: ${abs}. Run the build subcommand first.`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,31 +0,0 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
|
||||
import { ServerCliBuildAssetMissingError, ServerCliCommandExitError } from "./cliErrors.ts";
|
||||
|
||||
describe("server CLI errors", () => {
|
||||
it("preserves failed command context without changing its message", () => {
|
||||
const error = new ServerCliCommandExitError({
|
||||
command: "vp",
|
||||
args: ["pm", "publish"],
|
||||
cwd: "/repo",
|
||||
exitCode: 17,
|
||||
});
|
||||
|
||||
assert.equal(error._tag, "ServerCliCommandExitError");
|
||||
assert.equal(error.command, "vp");
|
||||
assert.deepEqual(error.args, ["pm", "publish"]);
|
||||
assert.equal(error.cwd, "/repo");
|
||||
assert.equal(error.exitCode, 17);
|
||||
assert.equal(error.message, "Command exited with non-zero exit code (17)");
|
||||
});
|
||||
|
||||
it("preserves a representative missing asset path", () => {
|
||||
const error = new ServerCliBuildAssetMissingError({ assetPath: "/repo/server.mjs" });
|
||||
|
||||
assert.equal(error.assetPath, "/repo/server.mjs");
|
||||
assert.equal(
|
||||
error.message,
|
||||
"Missing build asset: /repo/server.mjs. Run the build subcommand first.",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,70 +0,0 @@
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
export class ServerCliCommandExitError extends Schema.TaggedErrorClass<ServerCliCommandExitError>()(
|
||||
"ServerCliCommandExitError",
|
||||
{
|
||||
command: Schema.String,
|
||||
args: Schema.Array(Schema.String),
|
||||
cwd: Schema.optional(Schema.String),
|
||||
exitCode: Schema.Int,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Command exited with non-zero exit code (${this.exitCode})`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ServerCliPublishIconSourceMissingError extends Schema.TaggedErrorClass<ServerCliPublishIconSourceMissingError>()(
|
||||
"ServerCliPublishIconSourceMissingError",
|
||||
{
|
||||
sourcePath: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Missing publish icon source: ${this.sourcePath}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ServerCliPublishIconTargetMissingError extends Schema.TaggedErrorClass<ServerCliPublishIconTargetMissingError>()(
|
||||
"ServerCliPublishIconTargetMissingError",
|
||||
{
|
||||
targetPath: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Missing publish icon target: ${this.targetPath}. Run the build subcommand first.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ServerCliDevelopmentIconSourceMissingError extends Schema.TaggedErrorClass<ServerCliDevelopmentIconSourceMissingError>()(
|
||||
"ServerCliDevelopmentIconSourceMissingError",
|
||||
{
|
||||
sourcePath: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Missing development icon source: ${this.sourcePath}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ServerCliDevelopmentIconTargetMissingError extends Schema.TaggedErrorClass<ServerCliDevelopmentIconTargetMissingError>()(
|
||||
"ServerCliDevelopmentIconTargetMissingError",
|
||||
{
|
||||
targetPath: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Missing development icon target: ${this.targetPath}. Build web first.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ServerCliBuildAssetMissingError extends Schema.TaggedErrorClass<ServerCliBuildAssetMissingError>()(
|
||||
"ServerCliBuildAssetMissingError",
|
||||
{
|
||||
assetPath: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Missing build asset: ${this.assetPath}. Run the build subcommand first.`;
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,6 @@ import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Path from "effect/Path";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
|
||||
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
|
||||
import * as ServerConfig from "../config.ts";
|
||||
@@ -86,58 +85,7 @@ describe("AssetAccess", () => {
|
||||
},
|
||||
workspaceRoot: root,
|
||||
}).pipe(Effect.flip);
|
||||
expect(error.message).toBe("Workspace file path must be relative to the project root.");
|
||||
expect(error).toMatchObject({
|
||||
_tag: "AssetWorkspacePathValidationError",
|
||||
resource: {
|
||||
_tag: "workspace-file",
|
||||
threadId: "thread-1",
|
||||
path: htmlPath,
|
||||
},
|
||||
});
|
||||
expect(error.cause).toBeInstanceOf(WorkspacePaths.WorkspacePathOutsideRootError);
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
it.effect("preserves non-missing canonical path failures when issuing asset URLs", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const root = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-asset-permission-root-",
|
||||
});
|
||||
const htmlPath = path.join(root, "report.html");
|
||||
yield* fileSystem.writeFileString(htmlPath, "<p>report</p>");
|
||||
const cause = PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "realPath",
|
||||
pathOrDescriptor: htmlPath,
|
||||
});
|
||||
const failingFileSystem = FileSystem.FileSystem.of({
|
||||
...fileSystem,
|
||||
realPath: () => Effect.fail(cause),
|
||||
});
|
||||
|
||||
const error = yield* issueAssetUrl({
|
||||
resource: {
|
||||
_tag: "workspace-file",
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
path: htmlPath,
|
||||
},
|
||||
workspaceRoot: root,
|
||||
}).pipe(Effect.provideService(FileSystem.FileSystem, failingFileSystem), Effect.flip);
|
||||
|
||||
expect(error.message).toBe("Failed to inspect the workspace asset.");
|
||||
expect(error).toMatchObject({
|
||||
_tag: "AssetWorkspaceAssetInspectionError",
|
||||
resource: {
|
||||
_tag: "workspace-file",
|
||||
threadId: "thread-1",
|
||||
path: htmlPath,
|
||||
},
|
||||
});
|
||||
expect(error.cause).toBe(cause);
|
||||
expect(error.message).toContain("relative to the project root");
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
@@ -238,38 +186,4 @@ describe("AssetAccess", () => {
|
||||
).toEqual({ kind: "project-favicon-fallback" });
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
it.effect("preserves structured project favicon resolution causes", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const root = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-asset-favicon-error-",
|
||||
});
|
||||
const platformCause = PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "stat",
|
||||
});
|
||||
const resolutionCause = new ProjectFaviconResolver.ProjectFaviconResolutionError({
|
||||
operation: "stat-candidate",
|
||||
workspaceRoot: root,
|
||||
relativePath: "favicon.svg",
|
||||
cause: platformCause,
|
||||
});
|
||||
const resolver = ProjectFaviconResolver.ProjectFaviconResolver.of({
|
||||
resolvePath: () => Effect.fail(resolutionCause),
|
||||
});
|
||||
|
||||
const error = yield* issueAssetUrl({
|
||||
resource: { _tag: "project-favicon", cwd: root },
|
||||
}).pipe(
|
||||
Effect.provideService(ProjectFaviconResolver.ProjectFaviconResolver, resolver),
|
||||
Effect.flip,
|
||||
);
|
||||
|
||||
expect(error.message).toBe("Failed to resolve project favicon.");
|
||||
expect(error._tag).toBe("AssetProjectFaviconResolutionError");
|
||||
expect(error.cause).toBe(resolutionCause);
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
});
|
||||
@@ -1,18 +1,5 @@
|
||||
import type { AssetResource } from "@t3tools/contracts";
|
||||
import {
|
||||
AssetAttachmentNotFoundError,
|
||||
AssetPreviewTypeValidationError,
|
||||
AssetProjectFaviconInspectionError,
|
||||
AssetProjectFaviconNotFoundError,
|
||||
AssetProjectFaviconResolutionError,
|
||||
AssetSigningKeyLoadError,
|
||||
AssetWorkspaceAssetInspectionError,
|
||||
AssetWorkspaceAssetNotFoundError,
|
||||
AssetWorkspaceContextNotFoundError,
|
||||
AssetWorkspacePathValidationError,
|
||||
AssetWorkspaceResolutionError,
|
||||
AssetWorkspaceRootNormalizationError,
|
||||
} from "@t3tools/contracts";
|
||||
import { AssetAccessError } from "@t3tools/contracts";
|
||||
import {
|
||||
isWorkspaceImagePreviewPath,
|
||||
isWorkspacePreviewEntryPath,
|
||||
@@ -24,7 +11,6 @@ import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import {
|
||||
@@ -111,59 +97,33 @@ function decodeRelativePath(value: string): string | null {
|
||||
}
|
||||
}
|
||||
|
||||
const optionOnNotFound = <A, R>(
|
||||
effect: Effect.Effect<A, PlatformError.PlatformError, R>,
|
||||
): Effect.Effect<Option.Option<A>, PlatformError.PlatformError, R> =>
|
||||
effect.pipe(
|
||||
Effect.map(Option.some),
|
||||
Effect.catchTags({
|
||||
PlatformError: (error) =>
|
||||
error.reason._tag === "NotFound" ? Effect.succeed(Option.none<A>()) : Effect.fail(error),
|
||||
}),
|
||||
);
|
||||
const failAccess = (message: string, cause?: unknown) =>
|
||||
new AssetAccessError({ message, ...(cause === undefined ? {} : { cause }) });
|
||||
|
||||
const resolveCanonicalWorkspaceFile = Effect.fn("AssetAccess.resolveCanonicalWorkspaceFile")(
|
||||
function* (input: { readonly workspaceRoot: string; readonly relativePath: string }) {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
|
||||
const resolved = yield* workspacePaths.resolveRelativePathWithinRoot(input).pipe(
|
||||
Effect.map(Option.some),
|
||||
Effect.catchTags({
|
||||
WorkspacePathOutsideRootError: () => Effect.succeed(Option.none()),
|
||||
}),
|
||||
);
|
||||
if (Option.isNone(resolved)) return null;
|
||||
const resolved = yield* workspacePaths
|
||||
.resolveRelativePathWithinRoot(input)
|
||||
.pipe(Effect.orElseSucceed(() => null));
|
||||
if (!resolved) return null;
|
||||
|
||||
const [canonicalRoot, canonicalFile] = yield* Effect.all([
|
||||
optionOnNotFound(fileSystem.realPath(input.workspaceRoot)),
|
||||
optionOnNotFound(fileSystem.realPath(resolved.value.absolutePath)),
|
||||
fileSystem.realPath(input.workspaceRoot).pipe(Effect.orElseSucceed(() => null)),
|
||||
fileSystem.realPath(resolved.absolutePath).pipe(Effect.orElseSucceed(() => null)),
|
||||
]);
|
||||
if (Option.isNone(canonicalRoot) || Option.isNone(canonicalFile)) return null;
|
||||
if (!canonicalRoot || !canonicalFile) return null;
|
||||
|
||||
const path = yield* Path.Path;
|
||||
const relative = path.relative(canonicalRoot.value, canonicalFile.value);
|
||||
const relative = path.relative(canonicalRoot, canonicalFile);
|
||||
if (relative === "" || relative.startsWith("..") || path.isAbsolute(relative)) return null;
|
||||
|
||||
const info = yield* optionOnNotFound(fileSystem.stat(canonicalFile.value));
|
||||
return Option.isSome(info) && info.value.type === "File" ? canonicalFile.value : null;
|
||||
const info = yield* fileSystem.stat(canonicalFile).pipe(Effect.orElseSucceed(() => null));
|
||||
return info?.type === "File" ? canonicalFile : null;
|
||||
},
|
||||
);
|
||||
|
||||
const resolveCanonicalWorkspaceFileForRequest = (input: {
|
||||
readonly workspaceRoot: string;
|
||||
readonly relativePath: string;
|
||||
}) =>
|
||||
resolveCanonicalWorkspaceFile(input).pipe(
|
||||
Effect.tapError((cause) =>
|
||||
Effect.logError("Failed to resolve canonical asset path.", {
|
||||
workspaceRoot: input.workspaceRoot,
|
||||
relativePath: input.relativePath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.orElseSucceed(() => null),
|
||||
);
|
||||
|
||||
export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (input: {
|
||||
readonly resource: AssetResource;
|
||||
readonly workspaceRoot?: string;
|
||||
@@ -178,64 +138,30 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
|
||||
switch (input.resource._tag) {
|
||||
case "workspace-file": {
|
||||
if (!input.workspaceRoot) {
|
||||
return yield* new AssetWorkspaceContextNotFoundError({
|
||||
resource: input.resource,
|
||||
});
|
||||
return yield* failAccess("Workspace context was not found.");
|
||||
}
|
||||
const workspaceRoot = yield* workspacePaths.normalizeWorkspaceRoot(input.workspaceRoot).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AssetWorkspaceRootNormalizationError({
|
||||
resource: input.resource,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const workspaceRoot = yield* workspacePaths
|
||||
.normalizeWorkspaceRoot(input.workspaceRoot)
|
||||
.pipe(Effect.mapError((cause) => failAccess(cause.message, cause)));
|
||||
const relativePath = path.isAbsolute(input.resource.path)
|
||||
? path.relative(workspaceRoot, input.resource.path)
|
||||
: input.resource.path;
|
||||
const resolved = yield* workspacePaths
|
||||
.resolveRelativePathWithinRoot({ workspaceRoot, relativePath })
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AssetWorkspacePathValidationError({
|
||||
resource: input.resource,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
.pipe(Effect.mapError((cause) => failAccess(cause.message, cause)));
|
||||
if (!isWorkspacePreviewEntryPath(resolved.relativePath)) {
|
||||
return yield* new AssetPreviewTypeValidationError({
|
||||
resource: input.resource,
|
||||
});
|
||||
return yield* failAccess("Only browser documents and images can be previewed.");
|
||||
}
|
||||
const canonicalFile = yield* resolveCanonicalWorkspaceFile({
|
||||
workspaceRoot,
|
||||
relativePath: resolved.relativePath,
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AssetWorkspaceAssetInspectionError({
|
||||
resource: input.resource,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
if (!canonicalFile) {
|
||||
return yield* new AssetWorkspaceAssetNotFoundError({
|
||||
resource: input.resource,
|
||||
});
|
||||
return yield* failAccess("Workspace asset was not found.");
|
||||
}
|
||||
const canonicalWorkspaceRoot = yield* fileSystem.realPath(workspaceRoot).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AssetWorkspaceResolutionError({
|
||||
resource: input.resource,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const canonicalWorkspaceRoot = yield* fileSystem
|
||||
.realPath(workspaceRoot)
|
||||
.pipe(Effect.mapError((cause) => failAccess("Failed to resolve workspace.", cause)));
|
||||
claims = isWorkspaceImagePreviewPath(resolved.relativePath)
|
||||
? {
|
||||
version: 1,
|
||||
@@ -261,9 +187,7 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
|
||||
attachmentId: input.resource.attachmentId,
|
||||
});
|
||||
if (!attachmentPath) {
|
||||
return yield* new AssetAttachmentNotFoundError({
|
||||
resource: input.resource,
|
||||
});
|
||||
return yield* failAccess("Attachment was not found.");
|
||||
}
|
||||
claims = {
|
||||
version: 1,
|
||||
@@ -275,54 +199,24 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
|
||||
break;
|
||||
}
|
||||
case "project-favicon": {
|
||||
const workspaceRoot = yield* workspacePaths.normalizeWorkspaceRoot(input.resource.cwd).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AssetWorkspaceRootNormalizationError({
|
||||
resource: input.resource,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const workspaceRoot = yield* workspacePaths
|
||||
.normalizeWorkspaceRoot(input.resource.cwd)
|
||||
.pipe(Effect.mapError((cause) => failAccess(cause.message, cause)));
|
||||
const faviconResolver = yield* ProjectFaviconResolver.ProjectFaviconResolver;
|
||||
const faviconPath = yield* faviconResolver.resolvePath(workspaceRoot).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AssetProjectFaviconResolutionError({
|
||||
resource: input.resource,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const faviconPath = yield* faviconResolver.resolvePath(workspaceRoot);
|
||||
const relativePath = faviconPath ? path.relative(workspaceRoot, faviconPath) : null;
|
||||
if (
|
||||
relativePath &&
|
||||
!(yield* resolveCanonicalWorkspaceFile({ workspaceRoot, relativePath }).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AssetProjectFaviconInspectionError({
|
||||
resource: input.resource,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
))
|
||||
!(yield* resolveCanonicalWorkspaceFile({ workspaceRoot, relativePath }))
|
||||
) {
|
||||
return yield* new AssetProjectFaviconNotFoundError({
|
||||
resource: input.resource,
|
||||
});
|
||||
return yield* failAccess("Project favicon was not found.");
|
||||
}
|
||||
claims = {
|
||||
version: 1,
|
||||
kind: "project-favicon",
|
||||
workspaceRoot: yield* fileSystem.realPath(workspaceRoot).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AssetWorkspaceResolutionError({
|
||||
resource: input.resource,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
workspaceRoot: yield* fileSystem
|
||||
.realPath(workspaceRoot)
|
||||
.pipe(Effect.mapError((cause) => failAccess("Failed to resolve workspace.", cause))),
|
||||
relativePath,
|
||||
expiresAt,
|
||||
};
|
||||
@@ -332,15 +226,9 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
|
||||
}
|
||||
|
||||
const secretStore = yield* ServerSecretStore.ServerSecretStore;
|
||||
const signingSecret = yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AssetSigningKeyLoadError({
|
||||
resource: input.resource,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const signingSecret = yield* secretStore
|
||||
.getOrCreateRandom(SIGNING_SECRET_NAME, 32)
|
||||
.pipe(Effect.mapError((cause) => failAccess(cause.message, cause)));
|
||||
const encodedPayload = base64UrlEncode(encodeAssetClaims(claims));
|
||||
const token = `${encodedPayload}.${signPayload(encodedPayload, signingSecret)}`;
|
||||
return {
|
||||
@@ -357,10 +245,9 @@ export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (
|
||||
if (!encodedPayload || !signature) return null;
|
||||
|
||||
const secretStore = yield* ServerSecretStore.ServerSecretStore;
|
||||
const signingSecret = yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32).pipe(
|
||||
Effect.tapError((cause) => Effect.logError("Failed to load the asset signing key.", { cause })),
|
||||
Effect.orElseSucceed(() => null),
|
||||
);
|
||||
const signingSecret = yield* secretStore
|
||||
.getOrCreateRandom(SIGNING_SECRET_NAME, 32)
|
||||
.pipe(Effect.orElseSucceed(() => null));
|
||||
if (!signingSecret) return null;
|
||||
if (!timingSafeEqualBase64Url(signature, signPayload(encodedPayload, signingSecret))) return null;
|
||||
|
||||
@@ -375,17 +262,8 @@ export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (
|
||||
});
|
||||
if (!attachmentPath) return null;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const info = yield* optionOnNotFound(fileSystem.stat(attachmentPath)).pipe(
|
||||
Effect.tapError((cause) =>
|
||||
Effect.logError("Failed to inspect attachment asset.", {
|
||||
attachmentId: claims.attachmentId,
|
||||
path: attachmentPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.orElseSucceed(() => Option.none()),
|
||||
);
|
||||
return Option.isSome(info) && info.value.type === "File"
|
||||
const info = yield* fileSystem.stat(attachmentPath).pipe(Effect.orElseSucceed(() => null));
|
||||
return info?.type === "File"
|
||||
? ({ kind: "file", path: attachmentPath } satisfies ResolvedAsset)
|
||||
: null;
|
||||
}
|
||||
@@ -394,7 +272,7 @@ export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (
|
||||
if (claims.relativePath === null) {
|
||||
return { kind: "project-favicon-fallback" } satisfies ResolvedAsset;
|
||||
}
|
||||
const faviconPath = yield* resolveCanonicalWorkspaceFileForRequest({
|
||||
const faviconPath = yield* resolveCanonicalWorkspaceFile({
|
||||
workspaceRoot: claims.workspaceRoot,
|
||||
relativePath: claims.relativePath,
|
||||
});
|
||||
@@ -406,7 +284,7 @@ export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (
|
||||
const path = yield* Path.Path;
|
||||
if (claims.kind === "workspace-file-exact") {
|
||||
if (decodedPath !== path.basename(claims.relativePath)) return null;
|
||||
const exactWorkspaceFile = yield* resolveCanonicalWorkspaceFileForRequest({
|
||||
const exactWorkspaceFile = yield* resolveCanonicalWorkspaceFile({
|
||||
workspaceRoot: claims.workspaceRoot,
|
||||
relativePath: claims.relativePath,
|
||||
});
|
||||
@@ -425,7 +303,7 @@ export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (
|
||||
}
|
||||
const joinedRelativePath =
|
||||
claims.baseRelativePath === "." ? decodedPath : path.join(claims.baseRelativePath, decodedPath);
|
||||
const workspaceFile = yield* resolveCanonicalWorkspaceFileForRequest({
|
||||
const workspaceFile = yield* resolveCanonicalWorkspaceFile({
|
||||
workspaceRoot: claims.workspaceRoot,
|
||||
relativePath: joinedRelativePath,
|
||||
});
|
||||
|
||||
@@ -1,146 +0,0 @@
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
|
||||
import * as AuthConnectClients from "../persistence/AuthConnectClients.ts";
|
||||
import * as ServerSecretStore from "./ServerSecretStore.ts";
|
||||
import * as ConnectClientStore from "./ConnectClientStore.ts";
|
||||
|
||||
const textEncoder = new TextEncoder();
|
||||
const requestedAt = DateTime.makeUnsafe("2026-06-27T12:00:00.000Z");
|
||||
const approvedAt = DateTime.makeUnsafe("2026-06-27T12:05:00.000Z");
|
||||
const rejectedAt = DateTime.makeUnsafe("2026-06-27T12:06:00.000Z");
|
||||
|
||||
const approvedRecord: AuthConnectClients.AuthConnectClientRecord = {
|
||||
clientProofKeyThumbprint: "client-thumbprint",
|
||||
cloudUserId: "cloud-user",
|
||||
deviceId: "device-1",
|
||||
status: "approved",
|
||||
client: {
|
||||
label: "Client",
|
||||
ipAddress: null,
|
||||
userAgent: null,
|
||||
deviceType: "desktop",
|
||||
os: "macOS",
|
||||
browser: null,
|
||||
},
|
||||
requestedAt,
|
||||
updatedAt: approvedAt,
|
||||
approvedAt,
|
||||
rejectedAt: null,
|
||||
revokedAt: null,
|
||||
lastSeenAt: null,
|
||||
};
|
||||
|
||||
const makeSecretStoreLayer = (mode: string) =>
|
||||
Layer.succeed(
|
||||
ServerSecretStore.ServerSecretStore,
|
||||
ServerSecretStore.ServerSecretStore.of({
|
||||
get: () => Effect.succeed(Option.some(textEncoder.encode(mode))),
|
||||
set: () => Effect.void,
|
||||
create: () => Effect.void,
|
||||
getOrCreateRandom: () => Effect.succeed(new Uint8Array()),
|
||||
remove: () => Effect.void,
|
||||
}),
|
||||
);
|
||||
|
||||
const secretStoreLayer = makeSecretStoreLayer("client-approval");
|
||||
|
||||
const makeStoreOnlyLayer = (mode: string) =>
|
||||
Layer.effect(ConnectClientStore.ConnectClientStore, ConnectClientStore.make).pipe(
|
||||
Layer.provide(makeSecretStoreLayer(mode)),
|
||||
Layer.provide(
|
||||
Layer.succeed(
|
||||
AuthConnectClients.AuthConnectClientRepository,
|
||||
AuthConnectClients.AuthConnectClientRepository.of({
|
||||
upsertRequest: () => Effect.succeed(approvedRecord),
|
||||
updateStatus: () => Effect.succeed(Option.none()),
|
||||
revoke: () => Effect.succeed(false),
|
||||
markSeen: () => Effect.succeed(Option.some(approvedRecord)),
|
||||
listActive: () => Effect.succeed([]),
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const makeStoreLayer = (
|
||||
overrides: Partial<AuthConnectClients.AuthConnectClientRepository["Service"]>,
|
||||
) =>
|
||||
Layer.effect(ConnectClientStore.ConnectClientStore, ConnectClientStore.make).pipe(
|
||||
Layer.provide(secretStoreLayer),
|
||||
Layer.provide(
|
||||
Layer.succeed(
|
||||
AuthConnectClients.AuthConnectClientRepository,
|
||||
AuthConnectClients.AuthConnectClientRepository.of({
|
||||
upsertRequest: () => Effect.succeed(approvedRecord),
|
||||
updateStatus: () => Effect.succeed(Option.none()),
|
||||
revoke: () => Effect.succeed(false),
|
||||
markSeen: () => Effect.succeed(Option.some(approvedRecord)),
|
||||
listActive: () => Effect.succeed([]),
|
||||
...overrides,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("fails closed when persisted security mode is invalid", () =>
|
||||
Effect.gen(function* () {
|
||||
const store = yield* ConnectClientStore.ConnectClientStore;
|
||||
const error = yield* Effect.flip(store.getSecurityMode());
|
||||
|
||||
expect(error._tag).toBe("ConnectSecurityModeLoadError");
|
||||
}).pipe(Effect.provide(makeStoreOnlyLayer("invalid-mode"))),
|
||||
);
|
||||
|
||||
it.effect("returns rejected when an approved client is rejected before last-seen update", () =>
|
||||
Effect.gen(function* () {
|
||||
const store = yield* ConnectClientStore.ConnectClientStore;
|
||||
const authorization = yield* store.requestClient({
|
||||
cloudUserId: "cloud-user",
|
||||
clientProofKeyThumbprint: "client-thumbprint",
|
||||
});
|
||||
|
||||
expect(authorization.mode).toBe("client-approval");
|
||||
expect(authorization.status).toBe("rejected");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeStoreLayer({
|
||||
markSeen: () =>
|
||||
Effect.succeed(
|
||||
Option.some({
|
||||
...approvedRecord,
|
||||
status: "rejected",
|
||||
updatedAt: rejectedAt,
|
||||
rejectedAt,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("returns pending when an approved client is revoked before last-seen update", () =>
|
||||
Effect.gen(function* () {
|
||||
const store = yield* ConnectClientStore.ConnectClientStore;
|
||||
const authorization = yield* store.requestClient({
|
||||
cloudUserId: "cloud-user",
|
||||
clientProofKeyThumbprint: "client-thumbprint",
|
||||
});
|
||||
|
||||
expect(authorization.mode).toBe("client-approval");
|
||||
expect(authorization.status).toBe("pending");
|
||||
if (authorization.mode === "client-approval") {
|
||||
expect(authorization.client.status).toBe("pending");
|
||||
expect(authorization.client.approvedAt).toBeNull();
|
||||
expect(authorization.client.lastSeenAt).toBeNull();
|
||||
}
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeStoreLayer({
|
||||
markSeen: () => Effect.succeed(Option.none()),
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -1,424 +0,0 @@
|
||||
import {
|
||||
AuthConnectSecurityMode,
|
||||
type AuthClientMetadata,
|
||||
type AuthClientPresentationMetadata,
|
||||
type AuthConnectClient,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PubSub from "effect/PubSub";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import * as AuthConnectClients from "../persistence/AuthConnectClients.ts";
|
||||
import type { AuthConnectClientRepositoryError } from "../persistence/Errors.ts";
|
||||
import * as ServerSecretStore from "./ServerSecretStore.ts";
|
||||
|
||||
const CONNECT_SECURITY_MODE_SECRET = "connect-security-mode";
|
||||
const textEncoder = new TextEncoder();
|
||||
const textDecoder = new TextDecoder();
|
||||
|
||||
const connectClientInternalErrorContext = {
|
||||
cause: Schema.Defect(),
|
||||
};
|
||||
|
||||
export class ConnectSecurityModeLoadError extends Schema.TaggedErrorClass<ConnectSecurityModeLoadError>()(
|
||||
"ConnectSecurityModeLoadError",
|
||||
{
|
||||
...connectClientInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to load Connect security mode.";
|
||||
}
|
||||
}
|
||||
|
||||
export class ConnectSecurityModeUpdateError extends Schema.TaggedErrorClass<ConnectSecurityModeUpdateError>()(
|
||||
"ConnectSecurityModeUpdateError",
|
||||
{
|
||||
...connectClientInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to update Connect security mode.";
|
||||
}
|
||||
}
|
||||
|
||||
export class ConnectClientsLoadError extends Schema.TaggedErrorClass<ConnectClientsLoadError>()(
|
||||
"ConnectClientsLoadError",
|
||||
{
|
||||
...connectClientInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to load Connect clients.";
|
||||
}
|
||||
}
|
||||
|
||||
export class ConnectClientRequestError extends Schema.TaggedErrorClass<ConnectClientRequestError>()(
|
||||
"ConnectClientRequestError",
|
||||
{
|
||||
clientProofKeyThumbprint: Schema.String,
|
||||
...connectClientInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to record Connect client '${this.clientProofKeyThumbprint}'.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ConnectClientApprovalError extends Schema.TaggedErrorClass<ConnectClientApprovalError>()(
|
||||
"ConnectClientApprovalError",
|
||||
{
|
||||
clientProofKeyThumbprint: Schema.String,
|
||||
...connectClientInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to approve Connect client '${this.clientProofKeyThumbprint}'.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ConnectClientRejectionError extends Schema.TaggedErrorClass<ConnectClientRejectionError>()(
|
||||
"ConnectClientRejectionError",
|
||||
{
|
||||
clientProofKeyThumbprint: Schema.String,
|
||||
...connectClientInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to reject Connect client '${this.clientProofKeyThumbprint}'.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ConnectClientRevocationError extends Schema.TaggedErrorClass<ConnectClientRevocationError>()(
|
||||
"ConnectClientRevocationError",
|
||||
{
|
||||
clientProofKeyThumbprint: Schema.String,
|
||||
...connectClientInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to revoke Connect client '${this.clientProofKeyThumbprint}'.`;
|
||||
}
|
||||
}
|
||||
|
||||
export const ConnectClientStoreError = Schema.Union([
|
||||
ConnectSecurityModeLoadError,
|
||||
ConnectSecurityModeUpdateError,
|
||||
ConnectClientsLoadError,
|
||||
ConnectClientRequestError,
|
||||
ConnectClientApprovalError,
|
||||
ConnectClientRejectionError,
|
||||
ConnectClientRevocationError,
|
||||
]);
|
||||
export type ConnectClientStoreError = typeof ConnectClientStoreError.Type;
|
||||
export const isConnectClientStoreError = Schema.is(ConnectClientStoreError);
|
||||
|
||||
export type ConnectClientChange =
|
||||
| {
|
||||
readonly type: "connectSecurityModeUpdated";
|
||||
readonly mode: AuthConnectSecurityMode;
|
||||
}
|
||||
| {
|
||||
readonly type: "connectClientUpserted";
|
||||
readonly client: AuthConnectClient;
|
||||
}
|
||||
| {
|
||||
readonly type: "connectClientRemoved";
|
||||
readonly clientProofKeyThumbprint: string;
|
||||
};
|
||||
|
||||
export type ConnectClientAuthorization =
|
||||
| {
|
||||
readonly mode: "account";
|
||||
readonly status: "approved";
|
||||
}
|
||||
| {
|
||||
readonly mode: "client-approval";
|
||||
readonly status: "pending" | "approved" | "rejected";
|
||||
readonly client: AuthConnectClient;
|
||||
};
|
||||
|
||||
export class ConnectClientStore extends Context.Service<
|
||||
ConnectClientStore,
|
||||
{
|
||||
readonly getSecurityMode: () => Effect.Effect<
|
||||
AuthConnectSecurityMode,
|
||||
ConnectSecurityModeLoadError
|
||||
>;
|
||||
readonly setSecurityMode: (
|
||||
mode: AuthConnectSecurityMode,
|
||||
) => Effect.Effect<AuthConnectSecurityMode, ConnectSecurityModeUpdateError>;
|
||||
readonly listClients: () => Effect.Effect<
|
||||
ReadonlyArray<AuthConnectClient>,
|
||||
ConnectClientsLoadError
|
||||
>;
|
||||
readonly requestClient: (input: {
|
||||
readonly cloudUserId: string;
|
||||
readonly clientProofKeyThumbprint: string;
|
||||
readonly deviceId?: string;
|
||||
readonly client?: AuthClientPresentationMetadata;
|
||||
}) => Effect.Effect<
|
||||
ConnectClientAuthorization,
|
||||
ConnectClientRequestError | ConnectSecurityModeLoadError
|
||||
>;
|
||||
readonly approve: (
|
||||
clientProofKeyThumbprint: string,
|
||||
) => Effect.Effect<Option.Option<AuthConnectClient>, ConnectClientApprovalError>;
|
||||
readonly reject: (
|
||||
clientProofKeyThumbprint: string,
|
||||
) => Effect.Effect<Option.Option<AuthConnectClient>, ConnectClientRejectionError>;
|
||||
readonly revoke: (
|
||||
clientProofKeyThumbprint: string,
|
||||
) => Effect.Effect<boolean, ConnectClientRevocationError>;
|
||||
readonly streamChanges: Stream.Stream<ConnectClientChange>;
|
||||
}
|
||||
>()("t3/auth/ConnectClientStore") {}
|
||||
|
||||
function toAuthClientMetadata(
|
||||
record: AuthConnectClients.AuthConnectClientMetadataRecord,
|
||||
): AuthClientMetadata {
|
||||
return {
|
||||
...(record.label ? { label: record.label } : {}),
|
||||
...(record.ipAddress ? { ipAddress: record.ipAddress } : {}),
|
||||
...(record.userAgent ? { userAgent: record.userAgent } : {}),
|
||||
deviceType: record.deviceType,
|
||||
...(record.os ? { os: record.os } : {}),
|
||||
...(record.browser ? { browser: record.browser } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function toAuthConnectClient(
|
||||
record: AuthConnectClients.AuthConnectClientRecord,
|
||||
): AuthConnectClient {
|
||||
return {
|
||||
clientProofKeyThumbprint: record.clientProofKeyThumbprint,
|
||||
cloudUserId: record.cloudUserId,
|
||||
...(record.deviceId ? { deviceId: record.deviceId } : {}),
|
||||
status: record.status,
|
||||
client: toAuthClientMetadata(record.client),
|
||||
requestedAt: DateTime.toUtc(record.requestedAt),
|
||||
updatedAt: DateTime.toUtc(record.updatedAt),
|
||||
approvedAt: record.approvedAt === null ? null : DateTime.toUtc(record.approvedAt),
|
||||
rejectedAt: record.rejectedAt === null ? null : DateTime.toUtc(record.rejectedAt),
|
||||
lastSeenAt: record.lastSeenAt === null ? null : DateTime.toUtc(record.lastSeenAt),
|
||||
};
|
||||
}
|
||||
|
||||
function fromPresentationMetadata(
|
||||
client: AuthClientPresentationMetadata | undefined,
|
||||
): AuthConnectClients.AuthConnectClientMetadataRecord {
|
||||
return {
|
||||
label: client?.label ?? null,
|
||||
ipAddress: null,
|
||||
userAgent: null,
|
||||
deviceType: client?.deviceType ?? "unknown",
|
||||
os: client?.os ?? null,
|
||||
browser: null,
|
||||
};
|
||||
}
|
||||
|
||||
function decodeSecurityMode(bytes: Uint8Array): AuthConnectSecurityMode {
|
||||
const value = textDecoder.decode(bytes).trim();
|
||||
return value === "account" || value === "client-approval" ? value : "account";
|
||||
}
|
||||
|
||||
function encodeSecurityMode(mode: AuthConnectSecurityMode): Uint8Array {
|
||||
return textEncoder.encode(mode);
|
||||
}
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const secrets = yield* ServerSecretStore.ServerSecretStore;
|
||||
const repository = yield* AuthConnectClients.AuthConnectClientRepository;
|
||||
const changesPubSub = yield* PubSub.unbounded<ConnectClientChange>();
|
||||
|
||||
const emitMode = (mode: AuthConnectSecurityMode) =>
|
||||
PubSub.publish(changesPubSub, {
|
||||
type: "connectSecurityModeUpdated",
|
||||
mode,
|
||||
}).pipe(Effect.asVoid);
|
||||
|
||||
const emitUpsert = (client: AuthConnectClient) =>
|
||||
PubSub.publish(changesPubSub, {
|
||||
type: "connectClientUpserted",
|
||||
client,
|
||||
}).pipe(Effect.asVoid);
|
||||
|
||||
const emitRemoved = (clientProofKeyThumbprint: string) =>
|
||||
PubSub.publish(changesPubSub, {
|
||||
type: "connectClientRemoved",
|
||||
clientProofKeyThumbprint,
|
||||
}).pipe(Effect.asVoid);
|
||||
|
||||
const getSecurityMode: ConnectClientStore["Service"]["getSecurityMode"] = () =>
|
||||
secrets.get(CONNECT_SECURITY_MODE_SECRET).pipe(
|
||||
Effect.map((mode) =>
|
||||
Option.isSome(mode) ? decodeSecurityMode(mode.value) : ("account" as const),
|
||||
),
|
||||
Effect.mapError((cause) => new ConnectSecurityModeLoadError({ cause })),
|
||||
Effect.withSpan("ConnectClientStore.getSecurityMode"),
|
||||
);
|
||||
|
||||
const setSecurityMode: ConnectClientStore["Service"]["setSecurityMode"] = (mode) =>
|
||||
secrets.set(CONNECT_SECURITY_MODE_SECRET, encodeSecurityMode(mode)).pipe(
|
||||
Effect.as(mode),
|
||||
Effect.tap(emitMode),
|
||||
Effect.mapError((cause) => new ConnectSecurityModeUpdateError({ cause })),
|
||||
Effect.withSpan("ConnectClientStore.setSecurityMode"),
|
||||
);
|
||||
|
||||
const listClients: ConnectClientStore["Service"]["listClients"] = () =>
|
||||
repository.listActive().pipe(
|
||||
Effect.map((clients) => clients.map(toAuthConnectClient)),
|
||||
Effect.mapError((cause) => new ConnectClientsLoadError({ cause })),
|
||||
Effect.withSpan("ConnectClientStore.listClients"),
|
||||
);
|
||||
|
||||
const requestClient: ConnectClientStore["Service"]["requestClient"] = Effect.fn(
|
||||
"ConnectClientStore.requestClient",
|
||||
)(function* (input) {
|
||||
const mode = yield* getSecurityMode();
|
||||
if (mode === "account") {
|
||||
return { mode, status: "approved" as const };
|
||||
}
|
||||
|
||||
const requestedAt = yield* DateTime.now;
|
||||
const record = yield* repository
|
||||
.upsertRequest({
|
||||
clientProofKeyThumbprint: input.clientProofKeyThumbprint,
|
||||
cloudUserId: input.cloudUserId,
|
||||
deviceId: input.deviceId ?? null,
|
||||
client: fromPresentationMetadata(input.client),
|
||||
requestedAt,
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ConnectClientRequestError({
|
||||
clientProofKeyThumbprint: input.clientProofKeyThumbprint,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const visibleClient = toAuthConnectClient(record);
|
||||
yield* emitUpsert(visibleClient);
|
||||
|
||||
if (record.status !== "approved") {
|
||||
return { mode, status: record.status, client: visibleClient };
|
||||
}
|
||||
|
||||
const seenAt = yield* DateTime.now;
|
||||
const seen = yield* repository
|
||||
.markSeen({
|
||||
clientProofKeyThumbprint: input.clientProofKeyThumbprint,
|
||||
seenAt,
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ConnectClientRequestError({
|
||||
clientProofKeyThumbprint: input.clientProofKeyThumbprint,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (Option.isSome(seen)) {
|
||||
const seenClient = toAuthConnectClient(seen.value);
|
||||
yield* emitUpsert(seenClient);
|
||||
return { mode, status: seen.value.status, client: seenClient };
|
||||
}
|
||||
|
||||
return {
|
||||
mode,
|
||||
status: "pending" as const,
|
||||
client: {
|
||||
...visibleClient,
|
||||
status: "pending" as const,
|
||||
updatedAt: DateTime.toUtc(seenAt),
|
||||
approvedAt: null,
|
||||
lastSeenAt: null,
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
const updateDecision = <E extends ConnectClientApprovalError | ConnectClientRejectionError>(
|
||||
clientProofKeyThumbprint: string,
|
||||
status: "approved" | "rejected",
|
||||
toError: (cause: AuthConnectClientRepositoryError) => E,
|
||||
): Effect.Effect<Option.Option<AuthConnectClient>, E> =>
|
||||
DateTime.now.pipe(
|
||||
Effect.flatMap((decidedAt) =>
|
||||
repository.updateStatus({
|
||||
clientProofKeyThumbprint,
|
||||
status,
|
||||
decidedAt,
|
||||
}),
|
||||
),
|
||||
Effect.mapError(toError),
|
||||
Effect.map((updated) => Option.map(updated, toAuthConnectClient)),
|
||||
Effect.tap((updated) => (Option.isSome(updated) ? emitUpsert(updated.value) : Effect.void)),
|
||||
);
|
||||
|
||||
const approve: ConnectClientStore["Service"]["approve"] = (clientProofKeyThumbprint) =>
|
||||
updateDecision(
|
||||
clientProofKeyThumbprint,
|
||||
"approved",
|
||||
(cause) =>
|
||||
new ConnectClientApprovalError({
|
||||
clientProofKeyThumbprint,
|
||||
cause,
|
||||
}),
|
||||
).pipe(Effect.withSpan("ConnectClientStore.approve"));
|
||||
|
||||
const reject: ConnectClientStore["Service"]["reject"] = (clientProofKeyThumbprint) =>
|
||||
updateDecision(
|
||||
clientProofKeyThumbprint,
|
||||
"rejected",
|
||||
(cause) =>
|
||||
new ConnectClientRejectionError({
|
||||
clientProofKeyThumbprint,
|
||||
cause,
|
||||
}),
|
||||
).pipe(Effect.withSpan("ConnectClientStore.reject"));
|
||||
|
||||
const revoke: ConnectClientStore["Service"]["revoke"] = (clientProofKeyThumbprint) =>
|
||||
DateTime.now.pipe(
|
||||
Effect.flatMap((revokedAt) =>
|
||||
repository.revoke({
|
||||
clientProofKeyThumbprint,
|
||||
revokedAt,
|
||||
}),
|
||||
),
|
||||
Effect.tap((revoked) => (revoked ? emitRemoved(clientProofKeyThumbprint) : Effect.void)),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ConnectClientRevocationError({
|
||||
clientProofKeyThumbprint,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.withSpan("ConnectClientStore.revoke"),
|
||||
);
|
||||
|
||||
return ConnectClientStore.of({
|
||||
getSecurityMode,
|
||||
setSecurityMode,
|
||||
listClients,
|
||||
requestClient,
|
||||
approve,
|
||||
reject,
|
||||
revoke,
|
||||
get streamChanges() {
|
||||
return Stream.fromPubSub(changesPubSub);
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(ConnectClientStore, make).pipe(
|
||||
Layer.provideMerge(AuthConnectClients.layer),
|
||||
);
|
||||
@@ -3,9 +3,6 @@ import {
|
||||
AuthAccessWriteScope,
|
||||
AuthAdministrativeScopes,
|
||||
AuthStandardClientScopes,
|
||||
type AuthClientPresentationMetadata,
|
||||
type AuthConnectClient,
|
||||
type AuthConnectSecurityMode,
|
||||
type AuthAccessTokenResult,
|
||||
type AuthBrowserSessionResult,
|
||||
type AuthClientMetadata,
|
||||
@@ -29,11 +26,9 @@ import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
|
||||
|
||||
import * as EnvironmentAuthPolicy from "./EnvironmentAuthPolicy.ts";
|
||||
import * as ConnectClientStore from "./ConnectClientStore.ts";
|
||||
import * as PairingGrantStore from "./PairingGrantStore.ts";
|
||||
import * as ServerSecretStore from "./ServerSecretStore.ts";
|
||||
import * as SessionStore from "./SessionStore.ts";
|
||||
@@ -312,83 +307,6 @@ export class ServerAuthCloudMintJwtSigningError extends Schema.TaggedErrorClass<
|
||||
}
|
||||
}
|
||||
|
||||
export class ServerAuthConnectSecurityModeReadError extends Schema.TaggedErrorClass<ServerAuthConnectSecurityModeReadError>()(
|
||||
"ServerAuthConnectSecurityModeReadError",
|
||||
{
|
||||
...serverAuthInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to read Connect security mode.";
|
||||
}
|
||||
}
|
||||
|
||||
export class ServerAuthConnectSecurityModeUpdateError extends Schema.TaggedErrorClass<ServerAuthConnectSecurityModeUpdateError>()(
|
||||
"ServerAuthConnectSecurityModeUpdateError",
|
||||
{
|
||||
...serverAuthInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to update Connect security mode.";
|
||||
}
|
||||
}
|
||||
|
||||
export class ServerAuthConnectClientsListError extends Schema.TaggedErrorClass<ServerAuthConnectClientsListError>()(
|
||||
"ServerAuthConnectClientsListError",
|
||||
{
|
||||
...serverAuthInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to list Connect clients.";
|
||||
}
|
||||
}
|
||||
|
||||
export class ServerAuthConnectClientRequestError extends Schema.TaggedErrorClass<ServerAuthConnectClientRequestError>()(
|
||||
"ServerAuthConnectClientRequestError",
|
||||
{
|
||||
...serverAuthInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to authorize Connect client request.";
|
||||
}
|
||||
}
|
||||
|
||||
export class ServerAuthConnectClientApprovalError extends Schema.TaggedErrorClass<ServerAuthConnectClientApprovalError>()(
|
||||
"ServerAuthConnectClientApprovalError",
|
||||
{
|
||||
...serverAuthInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to approve Connect client.";
|
||||
}
|
||||
}
|
||||
|
||||
export class ServerAuthConnectClientRejectionError extends Schema.TaggedErrorClass<ServerAuthConnectClientRejectionError>()(
|
||||
"ServerAuthConnectClientRejectionError",
|
||||
{
|
||||
...serverAuthInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to reject Connect client.";
|
||||
}
|
||||
}
|
||||
|
||||
export class ServerAuthConnectClientRevocationError extends Schema.TaggedErrorClass<ServerAuthConnectClientRevocationError>()(
|
||||
"ServerAuthConnectClientRevocationError",
|
||||
{
|
||||
...serverAuthInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to revoke Connect client.";
|
||||
}
|
||||
}
|
||||
|
||||
export const ServerAuthInternalError = Schema.Union([
|
||||
ServerAuthBootstrapCredentialValidationError,
|
||||
ServerAuthSessionCredentialValidationError,
|
||||
@@ -412,13 +330,6 @@ export const ServerAuthInternalError = Schema.Union([
|
||||
ServerAuthCloudRelayIssuerMissingError,
|
||||
ServerAuthCloudHealthJwtSigningError,
|
||||
ServerAuthCloudMintJwtSigningError,
|
||||
ServerAuthConnectSecurityModeReadError,
|
||||
ServerAuthConnectSecurityModeUpdateError,
|
||||
ServerAuthConnectClientsListError,
|
||||
ServerAuthConnectClientRequestError,
|
||||
ServerAuthConnectClientApprovalError,
|
||||
ServerAuthConnectClientRejectionError,
|
||||
ServerAuthConnectClientRevocationError,
|
||||
]);
|
||||
export type ServerAuthInternalError = typeof ServerAuthInternalError.Type;
|
||||
export const isServerAuthInternalError = Schema.is(ServerAuthInternalError);
|
||||
@@ -565,33 +476,6 @@ export class EnvironmentAuth extends Context.Service<
|
||||
readonly revokeOtherClientSessions: (
|
||||
currentSessionId: AuthSessionId,
|
||||
) => Effect.Effect<number, ServerAuthInternalError>;
|
||||
readonly getConnectSecurityMode: () => Effect.Effect<
|
||||
AuthConnectSecurityMode,
|
||||
ServerAuthInternalError
|
||||
>;
|
||||
readonly setConnectSecurityMode: (
|
||||
mode: AuthConnectSecurityMode,
|
||||
) => Effect.Effect<AuthConnectSecurityMode, ServerAuthInternalError>;
|
||||
readonly listConnectClients: () => Effect.Effect<
|
||||
ReadonlyArray<AuthConnectClient>,
|
||||
ServerAuthInternalError
|
||||
>;
|
||||
readonly authorizeConnectClientRequest: (input: {
|
||||
readonly cloudUserId: string;
|
||||
readonly clientProofKeyThumbprint: string;
|
||||
readonly deviceId?: string;
|
||||
readonly client?: AuthClientPresentationMetadata;
|
||||
}) => Effect.Effect<ConnectClientStore.ConnectClientAuthorization, ServerAuthInternalError>;
|
||||
readonly approveConnectClient: (
|
||||
clientProofKeyThumbprint: string,
|
||||
) => Effect.Effect<Option.Option<AuthConnectClient>, ServerAuthInternalError>;
|
||||
readonly rejectConnectClient: (
|
||||
clientProofKeyThumbprint: string,
|
||||
) => Effect.Effect<Option.Option<AuthConnectClient>, ServerAuthInternalError>;
|
||||
readonly revokeConnectClient: (
|
||||
clientProofKeyThumbprint: string,
|
||||
) => Effect.Effect<boolean, ServerAuthInternalError>;
|
||||
readonly streamConnectClientChanges: Stream.Stream<ConnectClientStore.ConnectClientChange>;
|
||||
readonly authenticateHttpRequest: (
|
||||
request: HttpServerRequest.HttpServerRequest,
|
||||
) => Effect.Effect<AuthenticatedSession, ServerAuthCredentialError | ServerAuthInternalError>;
|
||||
@@ -673,7 +557,6 @@ export const make = Effect.gen(function* () {
|
||||
const policy = yield* EnvironmentAuthPolicy.EnvironmentAuthPolicy;
|
||||
const bootstrapCredentials = yield* PairingGrantStore.PairingGrantStore;
|
||||
const sessions = yield* SessionStore.SessionStore;
|
||||
const connectClients = yield* ConnectClientStore.ConnectClientStore;
|
||||
const secretStore = yield* ServerSecretStore.ServerSecretStore;
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const descriptor = yield* policy.getDescriptor();
|
||||
@@ -1020,59 +903,6 @@ export const make = Effect.gen(function* () {
|
||||
Effect.withSpan("EnvironmentAuth.revokeOtherClientSessions"),
|
||||
);
|
||||
|
||||
const getConnectSecurityMode: EnvironmentAuth["Service"]["getConnectSecurityMode"] = () =>
|
||||
connectClients.getSecurityMode().pipe(
|
||||
Effect.mapError((cause) => new ServerAuthConnectSecurityModeReadError({ cause })),
|
||||
Effect.withSpan("EnvironmentAuth.getConnectSecurityMode"),
|
||||
);
|
||||
|
||||
const setConnectSecurityMode: EnvironmentAuth["Service"]["setConnectSecurityMode"] = (mode) =>
|
||||
connectClients.setSecurityMode(mode).pipe(
|
||||
Effect.mapError((cause) => new ServerAuthConnectSecurityModeUpdateError({ cause })),
|
||||
Effect.withSpan("EnvironmentAuth.setConnectSecurityMode"),
|
||||
);
|
||||
|
||||
const listConnectClients: EnvironmentAuth["Service"]["listConnectClients"] = () =>
|
||||
connectClients.listClients().pipe(
|
||||
Effect.mapError((cause) => new ServerAuthConnectClientsListError({ cause })),
|
||||
Effect.withSpan("EnvironmentAuth.listConnectClients"),
|
||||
);
|
||||
|
||||
const authorizeConnectClientRequest: EnvironmentAuth["Service"]["authorizeConnectClientRequest"] =
|
||||
(input) =>
|
||||
connectClients.requestClient(input).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
cause._tag === "ConnectSecurityModeLoadError"
|
||||
? new ServerAuthConnectSecurityModeReadError({ cause })
|
||||
: new ServerAuthConnectClientRequestError({ cause }),
|
||||
),
|
||||
Effect.withSpan("EnvironmentAuth.authorizeConnectClientRequest"),
|
||||
);
|
||||
|
||||
const approveConnectClient: EnvironmentAuth["Service"]["approveConnectClient"] = (
|
||||
clientProofKeyThumbprint,
|
||||
) =>
|
||||
connectClients.approve(clientProofKeyThumbprint).pipe(
|
||||
Effect.mapError((cause) => new ServerAuthConnectClientApprovalError({ cause })),
|
||||
Effect.withSpan("EnvironmentAuth.approveConnectClient"),
|
||||
);
|
||||
|
||||
const rejectConnectClient: EnvironmentAuth["Service"]["rejectConnectClient"] = (
|
||||
clientProofKeyThumbprint,
|
||||
) =>
|
||||
connectClients.reject(clientProofKeyThumbprint).pipe(
|
||||
Effect.mapError((cause) => new ServerAuthConnectClientRejectionError({ cause })),
|
||||
Effect.withSpan("EnvironmentAuth.rejectConnectClient"),
|
||||
);
|
||||
|
||||
const revokeConnectClient: EnvironmentAuth["Service"]["revokeConnectClient"] = (
|
||||
clientProofKeyThumbprint,
|
||||
) =>
|
||||
connectClients.revoke(clientProofKeyThumbprint).pipe(
|
||||
Effect.mapError((cause) => new ServerAuthConnectClientRevocationError({ cause })),
|
||||
Effect.withSpan("EnvironmentAuth.revokeConnectClient"),
|
||||
);
|
||||
|
||||
const issueStartupPairingUrl: EnvironmentAuth["Service"]["issueStartupPairingUrl"] = (baseUrl) =>
|
||||
issueStartupPairingCredential().pipe(
|
||||
Effect.map((issued) => {
|
||||
@@ -1143,14 +973,6 @@ export const make = Effect.gen(function* () {
|
||||
listClientSessions,
|
||||
revokeClientSession,
|
||||
revokeOtherClientSessions,
|
||||
getConnectSecurityMode,
|
||||
setConnectSecurityMode,
|
||||
listConnectClients,
|
||||
authorizeConnectClientRequest,
|
||||
approveConnectClient,
|
||||
rejectConnectClient,
|
||||
revokeConnectClient,
|
||||
streamConnectClientChanges: connectClients.streamChanges,
|
||||
authenticateHttpRequest,
|
||||
authenticateWebSocketUpgrade,
|
||||
issueWebSocketTicket,
|
||||
@@ -1161,7 +983,6 @@ export const make = Effect.gen(function* () {
|
||||
export const layer = Layer.effect(EnvironmentAuth, make).pipe(
|
||||
Layer.provideMerge(PairingGrantStore.layer),
|
||||
Layer.provideMerge(SessionStore.layer),
|
||||
Layer.provideMerge(ConnectClientStore.layer),
|
||||
Layer.provideMerge(EnvironmentAuthPolicy.layer),
|
||||
);
|
||||
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -3,8 +3,7 @@ import * as Crypto from "effect/Crypto";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Encoding from "effect/Encoding";
|
||||
import * as Option from "effect/Option";
|
||||
import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
|
||||
import type * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
|
||||
|
||||
import {
|
||||
ServerAuthDpopReplayKeyCalculationError,
|
||||
@@ -14,6 +13,22 @@ import {
|
||||
} from "./EnvironmentAuth.ts";
|
||||
import * as ServerSecretStore from "./ServerSecretStore.ts";
|
||||
|
||||
function firstHeaderValue(value: string | undefined): string | undefined {
|
||||
const first = value?.split(",")[0]?.trim();
|
||||
return first && first.length > 0 ? first : undefined;
|
||||
}
|
||||
|
||||
export function requestAbsoluteUrl(request: HttpServerRequest.HttpServerRequest): string {
|
||||
try {
|
||||
return new URL(request.originalUrl).href;
|
||||
} catch {
|
||||
const host = firstHeaderValue(request.headers.host) ?? "127.0.0.1";
|
||||
const forwardedProto = firstHeaderValue(request.headers["x-forwarded-proto"]);
|
||||
const proto = forwardedProto === "https" || forwardedProto === "http" ? forwardedProto : "http";
|
||||
return new URL(request.originalUrl, `${proto}://${host}`).href;
|
||||
}
|
||||
}
|
||||
|
||||
export const mapDpopReplayStoreError = (
|
||||
error: ServerSecretStore.SecretStoreError,
|
||||
): ServerAuthInvalidCredentialError | ServerAuthInternalError =>
|
||||
@@ -33,17 +48,11 @@ export const verifyRequestDpopProof = (input: {
|
||||
}) =>
|
||||
Effect.gen(function* () {
|
||||
const proof = input.request.headers.dpop;
|
||||
const url = HttpServerRequest.toURL(input.request);
|
||||
if (Option.isNone(url)) {
|
||||
return yield* new ServerAuthInvalidCredentialError({
|
||||
diagnostic: "Invalid DPoP request URL.",
|
||||
});
|
||||
}
|
||||
const now = yield* DateTime.now;
|
||||
const result = verifyDpopProof({
|
||||
proof,
|
||||
method: input.request.method,
|
||||
url: url.value.href,
|
||||
url: requestAbsoluteUrl(input.request),
|
||||
nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
|
||||
...(input.expectedThumbprint ? { expectedThumbprint: input.expectedThumbprint } : {}),
|
||||
...(input.expectedAccessToken ? { expectedAccessToken: input.expectedAccessToken } : {}),
|
||||
|
||||
@@ -27,7 +27,6 @@ import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import { identity } from "effect/Function";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Cookies from "effect/unstable/http/Cookies";
|
||||
import * as HttpEffect from "effect/unstable/http/HttpEffect";
|
||||
import { HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
|
||||
@@ -420,81 +419,6 @@ export const authHttpApiLayer = HttpApiBuilder.group(
|
||||
failEnvironmentInternal("client_session_revoke_failed", error),
|
||||
),
|
||||
),
|
||||
)
|
||||
.handle(
|
||||
"connectSecurityMode",
|
||||
Effect.fn("environment.auth.connectSecurityMode")(
|
||||
function* (args) {
|
||||
yield* annotateEnvironmentRequest(args.endpoint.name);
|
||||
yield* requireEnvironmentScope(AuthAccessWriteScope);
|
||||
const mode = yield* serverAuth.setConnectSecurityMode(args.payload.mode);
|
||||
return { mode };
|
||||
},
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
|
||||
failEnvironmentInternal("connect_security_mode_update_failed", error),
|
||||
),
|
||||
),
|
||||
)
|
||||
.handle(
|
||||
"connectClients",
|
||||
Effect.fn("environment.auth.connectClients")(
|
||||
function* (args) {
|
||||
yield* annotateEnvironmentRequest(args.endpoint.name);
|
||||
yield* requireEnvironmentScope(AuthAccessReadScope);
|
||||
return yield* serverAuth.listConnectClients();
|
||||
},
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
|
||||
failEnvironmentInternal("connect_clients_load_failed", error),
|
||||
),
|
||||
),
|
||||
)
|
||||
.handle(
|
||||
"approveConnectClient",
|
||||
Effect.fn("environment.auth.approveConnectClient")(
|
||||
function* (args) {
|
||||
yield* annotateEnvironmentRequest(args.endpoint.name);
|
||||
yield* requireEnvironmentScope(AuthAccessWriteScope);
|
||||
const client = yield* serverAuth.approveConnectClient(
|
||||
args.payload.clientProofKeyThumbprint,
|
||||
);
|
||||
return { client: Option.getOrNull(client) };
|
||||
},
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
|
||||
failEnvironmentInternal("connect_client_approval_failed", error),
|
||||
),
|
||||
),
|
||||
)
|
||||
.handle(
|
||||
"rejectConnectClient",
|
||||
Effect.fn("environment.auth.rejectConnectClient")(
|
||||
function* (args) {
|
||||
yield* annotateEnvironmentRequest(args.endpoint.name);
|
||||
yield* requireEnvironmentScope(AuthAccessWriteScope);
|
||||
const client = yield* serverAuth.rejectConnectClient(
|
||||
args.payload.clientProofKeyThumbprint,
|
||||
);
|
||||
return { client: Option.getOrNull(client) };
|
||||
},
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
|
||||
failEnvironmentInternal("connect_client_rejection_failed", error),
|
||||
),
|
||||
),
|
||||
)
|
||||
.handle(
|
||||
"revokeConnectClient",
|
||||
Effect.fn("environment.auth.revokeConnectClient")(
|
||||
function* (args) {
|
||||
yield* annotateEnvironmentRequest(args.endpoint.name);
|
||||
yield* requireEnvironmentScope(AuthAccessWriteScope);
|
||||
const revoked = yield* serverAuth.revokeConnectClient(
|
||||
args.payload.clientProofKeyThumbprint,
|
||||
);
|
||||
return { revoked };
|
||||
},
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
|
||||
failEnvironmentInternal("connect_client_revoke_failed", error),
|
||||
),
|
||||
),
|
||||
);
|
||||
}),
|
||||
);
|
||||
@@ -9,7 +9,6 @@ import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSn
|
||||
import { checkpointRefForThreadTurn } from "./Utils.ts";
|
||||
import * as CheckpointDiffQuery from "./CheckpointDiffQuery.ts";
|
||||
import * as CheckpointStore from "./CheckpointStore.ts";
|
||||
import { CheckpointThreadNotFoundError } from "./Errors.ts";
|
||||
|
||||
function makeThreadCheckpointContext(input: {
|
||||
readonly projectId: ProjectId;
|
||||
@@ -413,14 +412,7 @@ describe("CheckpointDiffQuery.layer", () => {
|
||||
});
|
||||
}).pipe(Effect.provide(layer), Effect.flip);
|
||||
|
||||
expect(error).toBeInstanceOf(CheckpointThreadNotFoundError);
|
||||
expect(error).toMatchObject({
|
||||
operation: "CheckpointDiffQuery.getTurnDiff",
|
||||
threadId,
|
||||
});
|
||||
expect(error.message).toBe(
|
||||
"Checkpoint invariant violation in CheckpointDiffQuery.getTurnDiff: Thread 'thread-missing' not found.",
|
||||
);
|
||||
expect(error.message).toContain("Thread 'thread-missing' not found.");
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -22,13 +22,7 @@ import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import {
|
||||
CheckpointDiffResultInvalidError,
|
||||
CheckpointRefUnavailableError,
|
||||
CheckpointThreadNotFoundError,
|
||||
CheckpointTurnRangeUnavailableError,
|
||||
CheckpointWorkspacePathMissingError,
|
||||
} from "./Errors.ts";
|
||||
import { CheckpointInvariantError, CheckpointUnavailableError } from "./Errors.ts";
|
||||
import type { CheckpointServiceError } from "./Errors.ts";
|
||||
import { checkpointRefForThreadTurn } from "./Utils.ts";
|
||||
import * as CheckpointStore from "./CheckpointStore.ts";
|
||||
@@ -98,9 +92,9 @@ export const make = Effect.gen(function* () {
|
||||
diff: "",
|
||||
};
|
||||
if (!isTurnDiffResult(emptyDiff)) {
|
||||
return yield* new CheckpointDiffResultInvalidError({
|
||||
return yield* new CheckpointInvariantError({
|
||||
operation,
|
||||
threadId: input.threadId,
|
||||
detail: "Computed turn diff result does not satisfy contract schema.",
|
||||
});
|
||||
}
|
||||
return emptyDiff;
|
||||
@@ -110,9 +104,9 @@ export const make = Effect.gen(function* () {
|
||||
.getThreadCheckpointContext(input.threadId)
|
||||
.pipe(Effect.withSpan("checkpoint.turnDiff.lookupContext"));
|
||||
if (Option.isNone(threadContext)) {
|
||||
return yield* new CheckpointThreadNotFoundError({
|
||||
return yield* new CheckpointInvariantError({
|
||||
operation,
|
||||
threadId: input.threadId,
|
||||
detail: `Thread '${input.threadId}' not found.`,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -121,19 +115,18 @@ export const make = Effect.gen(function* () {
|
||||
0,
|
||||
);
|
||||
if (input.toTurnCount > maxTurnCount) {
|
||||
return yield* new CheckpointTurnRangeUnavailableError({
|
||||
operation,
|
||||
return yield* new CheckpointUnavailableError({
|
||||
threadId: input.threadId,
|
||||
requestedTurnCount: input.toTurnCount,
|
||||
availableTurnCount: maxTurnCount,
|
||||
turnCount: input.toTurnCount,
|
||||
detail: `Turn diff range exceeds current turn count: requested ${input.toTurnCount}, current ${maxTurnCount}.`,
|
||||
});
|
||||
}
|
||||
|
||||
const workspaceCwd = threadContext.value.worktreePath ?? threadContext.value.workspaceRoot;
|
||||
if (!workspaceCwd) {
|
||||
return yield* new CheckpointWorkspacePathMissingError({
|
||||
return yield* new CheckpointInvariantError({
|
||||
operation,
|
||||
threadId: input.threadId,
|
||||
detail: `Workspace path missing for thread '${input.threadId}' when computing turn diff.`,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -144,11 +137,10 @@ export const make = Effect.gen(function* () {
|
||||
(checkpoint) => checkpoint.checkpointTurnCount === input.fromTurnCount,
|
||||
)?.checkpointRef;
|
||||
if (!fromCheckpointRef) {
|
||||
return yield* new CheckpointRefUnavailableError({
|
||||
operation,
|
||||
return yield* new CheckpointUnavailableError({
|
||||
threadId: input.threadId,
|
||||
turnCount: input.fromTurnCount,
|
||||
checkpoint: "from",
|
||||
detail: `Checkpoint ref is unavailable for turn ${input.fromTurnCount}.`,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -156,11 +148,10 @@ export const make = Effect.gen(function* () {
|
||||
(checkpoint) => checkpoint.checkpointTurnCount === input.toTurnCount,
|
||||
)?.checkpointRef;
|
||||
if (!toCheckpointRef) {
|
||||
return yield* new CheckpointRefUnavailableError({
|
||||
operation,
|
||||
return yield* new CheckpointUnavailableError({
|
||||
threadId: input.threadId,
|
||||
turnCount: input.toTurnCount,
|
||||
checkpoint: "to",
|
||||
detail: `Checkpoint ref is unavailable for turn ${input.toTurnCount}.`,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -176,9 +167,9 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
const turnDiff = buildTurnDiffResult(input, diff);
|
||||
if (!isTurnDiffResult(turnDiff)) {
|
||||
return yield* new CheckpointDiffResultInvalidError({
|
||||
return yield* new CheckpointInvariantError({
|
||||
operation,
|
||||
threadId: input.threadId,
|
||||
detail: "Computed turn diff result does not satisfy contract schema.",
|
||||
});
|
||||
}
|
||||
|
||||
@@ -209,9 +200,9 @@ export const make = Effect.gen(function* () {
|
||||
"",
|
||||
);
|
||||
if (!isTurnDiffResult(emptyDiff)) {
|
||||
return yield* new CheckpointDiffResultInvalidError({
|
||||
return yield* new CheckpointInvariantError({
|
||||
operation,
|
||||
threadId: input.threadId,
|
||||
detail: "Computed full thread diff result does not satisfy contract schema.",
|
||||
});
|
||||
}
|
||||
return emptyDiff satisfies OrchestrationGetFullThreadDiffResult;
|
||||
@@ -222,35 +213,33 @@ export const make = Effect.gen(function* () {
|
||||
.pipe(Effect.withSpan("checkpoint.fullThread.lookupContext"));
|
||||
|
||||
if (Option.isNone(threadContext)) {
|
||||
return yield* new CheckpointThreadNotFoundError({
|
||||
return yield* new CheckpointInvariantError({
|
||||
operation,
|
||||
threadId: input.threadId,
|
||||
detail: `Thread '${input.threadId}' not found.`,
|
||||
});
|
||||
}
|
||||
|
||||
if (input.toTurnCount > threadContext.value.latestCheckpointTurnCount) {
|
||||
return yield* new CheckpointTurnRangeUnavailableError({
|
||||
operation,
|
||||
return yield* new CheckpointUnavailableError({
|
||||
threadId: input.threadId,
|
||||
requestedTurnCount: input.toTurnCount,
|
||||
availableTurnCount: threadContext.value.latestCheckpointTurnCount,
|
||||
turnCount: input.toTurnCount,
|
||||
detail: `Turn diff range exceeds current turn count: requested ${input.toTurnCount}, current ${threadContext.value.latestCheckpointTurnCount}.`,
|
||||
});
|
||||
}
|
||||
|
||||
const workspaceCwd = threadContext.value.worktreePath ?? threadContext.value.workspaceRoot;
|
||||
if (!workspaceCwd) {
|
||||
return yield* new CheckpointWorkspacePathMissingError({
|
||||
return yield* new CheckpointInvariantError({
|
||||
operation,
|
||||
threadId: input.threadId,
|
||||
detail: `Workspace path missing for thread '${input.threadId}' when computing full thread diff.`,
|
||||
});
|
||||
}
|
||||
|
||||
if (!threadContext.value.toCheckpointRef) {
|
||||
return yield* new CheckpointRefUnavailableError({
|
||||
operation,
|
||||
return yield* new CheckpointUnavailableError({
|
||||
threadId: input.threadId,
|
||||
turnCount: input.toTurnCount,
|
||||
checkpoint: "to",
|
||||
detail: `Checkpoint ref is unavailable for turn ${input.toTurnCount}.`,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -273,9 +262,9 @@ export const make = Effect.gen(function* () {
|
||||
diff,
|
||||
);
|
||||
if (!isTurnDiffResult(turnDiff)) {
|
||||
return yield* new CheckpointDiffResultInvalidError({
|
||||
return yield* new CheckpointInvariantError({
|
||||
operation,
|
||||
threadId: input.threadId,
|
||||
detail: "Computed full thread diff result does not satisfy contract schema.",
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -93,27 +93,6 @@ function buildLargeText(lineCount = 5_000): string {
|
||||
}
|
||||
|
||||
it.layer(TestLayer)("CheckpointStore.layer", (it) => {
|
||||
describe("isGitRepository", () => {
|
||||
it.effect("returns false when no Git repository is detected", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
const checkpointStore = yield* CheckpointStore.CheckpointStore;
|
||||
|
||||
expect(yield* checkpointStore.isGitRepository(tmp)).toBe(false);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns true when a Git repository is detected", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
const checkpointStore = yield* CheckpointStore.CheckpointStore;
|
||||
|
||||
expect(yield* checkpointStore.isGitRepository(tmp)).toBe(true);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
describe("diffCheckpoints", () => {
|
||||
it.effect("returns full oversized checkpoint diffs without truncation", () =>
|
||||
Effect.gen(function* () {
|
||||
|
||||
@@ -115,9 +115,10 @@ export const make = Effect.gen(function* () {
|
||||
});
|
||||
|
||||
const isGitRepository: CheckpointStore["Service"]["isGitRepository"] = (cwd) =>
|
||||
vcsRegistry
|
||||
.detect({ cwd, requestedKind: "git" })
|
||||
.pipe(Effect.map((repository) => repository !== null));
|
||||
vcsRegistry.resolve({ cwd, requestedKind: "git" }).pipe(
|
||||
Effect.map(() => true),
|
||||
Effect.orElseSucceed(() => false),
|
||||
);
|
||||
|
||||
const captureCheckpoint: CheckpointStore["Service"]["captureCheckpoint"] = Effect.fn(
|
||||
"captureCheckpoint",
|
||||
|
||||
@@ -1,39 +0,0 @@
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import { ThreadId } from "@t3tools/contracts";
|
||||
|
||||
import {
|
||||
CheckpointRefUnavailableError,
|
||||
CheckpointTurnRangeUnavailableError,
|
||||
CheckpointWorkspacePathMissingError,
|
||||
} from "./Errors.ts";
|
||||
|
||||
const threadId = ThreadId.make("thread-1");
|
||||
|
||||
it("derives checkpoint messages from structured context", () => {
|
||||
const range = new CheckpointTurnRangeUnavailableError({
|
||||
operation: "CheckpointDiffQuery.getTurnDiff",
|
||||
threadId,
|
||||
requestedTurnCount: 4,
|
||||
availableTurnCount: 2,
|
||||
});
|
||||
const checkpoint = new CheckpointRefUnavailableError({
|
||||
operation: "CheckpointDiffQuery.getTurnDiff",
|
||||
threadId,
|
||||
turnCount: 2,
|
||||
checkpoint: "to",
|
||||
});
|
||||
const workspace = new CheckpointWorkspacePathMissingError({
|
||||
operation: "CheckpointDiffQuery.getFullThreadDiff",
|
||||
threadId,
|
||||
});
|
||||
|
||||
expect(range.message).toBe(
|
||||
"Checkpoint unavailable for thread thread-1 turn 4: Turn diff range exceeds current turn count: requested 4, current 2.",
|
||||
);
|
||||
expect(checkpoint.message).toBe(
|
||||
"Checkpoint unavailable for thread thread-1 turn 2: Checkpoint ref is unavailable for turn 2.",
|
||||
);
|
||||
expect(workspace.message).toBe(
|
||||
"Checkpoint invariant violation in CheckpointDiffQuery.getFullThreadDiff: Workspace path missing for thread 'thread-1' when computing full thread diff.",
|
||||
);
|
||||
});
|
||||
@@ -1,94 +1,40 @@
|
||||
import { NonNegativeInt, ThreadId, type VcsError } from "@t3tools/contracts";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import type { ProjectionRepositoryError } from "../persistence/Errors.ts";
|
||||
import type { VcsError } from "@t3tools/contracts";
|
||||
|
||||
export const CheckpointDiffOperation = Schema.Literals([
|
||||
"CheckpointDiffQuery.getTurnDiff",
|
||||
"CheckpointDiffQuery.getFullThreadDiff",
|
||||
]);
|
||||
export type CheckpointDiffOperation = typeof CheckpointDiffOperation.Type;
|
||||
|
||||
/** The computed result does not satisfy the checkpoint RPC contract. */
|
||||
export class CheckpointDiffResultInvalidError extends Schema.TaggedErrorClass<CheckpointDiffResultInvalidError>()(
|
||||
"CheckpointDiffResultInvalidError",
|
||||
/**
|
||||
* CheckpointUnavailableError - Expected checkpoint does not exist.
|
||||
*/
|
||||
export class CheckpointUnavailableError extends Schema.TaggedErrorClass<CheckpointUnavailableError>()(
|
||||
"CheckpointUnavailableError",
|
||||
{
|
||||
operation: CheckpointDiffOperation,
|
||||
threadId: ThreadId,
|
||||
threadId: Schema.String,
|
||||
turnCount: Schema.Number,
|
||||
detail: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
const result =
|
||||
this.operation === "CheckpointDiffQuery.getTurnDiff" ? "turn diff" : "full thread diff";
|
||||
return `Checkpoint invariant violation in ${this.operation}: Computed ${result} result does not satisfy contract schema.`;
|
||||
return `Checkpoint unavailable for thread ${this.threadId} turn ${this.turnCount}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
/** Projection state no longer contains the requested checkpoint thread. */
|
||||
export class CheckpointThreadNotFoundError extends Schema.TaggedErrorClass<CheckpointThreadNotFoundError>()(
|
||||
"CheckpointThreadNotFoundError",
|
||||
/**
|
||||
* CheckpointInvariantError - Inconsistent provider/filesystem/catalog state.
|
||||
*/
|
||||
export class CheckpointInvariantError extends Schema.TaggedErrorClass<CheckpointInvariantError>()(
|
||||
"CheckpointInvariantError",
|
||||
{
|
||||
operation: CheckpointDiffOperation,
|
||||
threadId: ThreadId,
|
||||
operation: Schema.String,
|
||||
detail: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Checkpoint invariant violation in ${this.operation}: Thread '${this.threadId}' not found.`;
|
||||
return `Checkpoint invariant violation in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
/** The checkpoint thread has no workspace path from which to compute a diff. */
|
||||
export class CheckpointWorkspacePathMissingError extends Schema.TaggedErrorClass<CheckpointWorkspacePathMissingError>()(
|
||||
"CheckpointWorkspacePathMissingError",
|
||||
{
|
||||
operation: CheckpointDiffOperation,
|
||||
threadId: ThreadId,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
const diff =
|
||||
this.operation === "CheckpointDiffQuery.getTurnDiff" ? "turn diff" : "full thread diff";
|
||||
return `Checkpoint invariant violation in ${this.operation}: Workspace path missing for thread '${this.threadId}' when computing ${diff}.`;
|
||||
}
|
||||
}
|
||||
export type CheckpointStoreError = VcsError | CheckpointInvariantError | CheckpointUnavailableError;
|
||||
|
||||
/** The requested turn lies beyond the latest available checkpoint. */
|
||||
export class CheckpointTurnRangeUnavailableError extends Schema.TaggedErrorClass<CheckpointTurnRangeUnavailableError>()(
|
||||
"CheckpointTurnRangeUnavailableError",
|
||||
{
|
||||
operation: CheckpointDiffOperation,
|
||||
threadId: ThreadId,
|
||||
requestedTurnCount: NonNegativeInt,
|
||||
availableTurnCount: NonNegativeInt,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Checkpoint unavailable for thread ${this.threadId} turn ${this.requestedTurnCount}: Turn diff range exceeds current turn count: requested ${this.requestedTurnCount}, current ${this.availableTurnCount}.`;
|
||||
}
|
||||
}
|
||||
|
||||
/** Expected checkpoint metadata does not contain the requested Git ref. */
|
||||
export class CheckpointRefUnavailableError extends Schema.TaggedErrorClass<CheckpointRefUnavailableError>()(
|
||||
"CheckpointRefUnavailableError",
|
||||
{
|
||||
operation: CheckpointDiffOperation,
|
||||
threadId: ThreadId,
|
||||
turnCount: NonNegativeInt,
|
||||
checkpoint: Schema.Literals(["from", "to"]),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Checkpoint unavailable for thread ${this.threadId} turn ${this.turnCount}: Checkpoint ref is unavailable for turn ${this.turnCount}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export type CheckpointStoreError = VcsError;
|
||||
|
||||
export type CheckpointServiceError =
|
||||
| CheckpointStoreError
|
||||
| ProjectionRepositoryError
|
||||
| CheckpointDiffResultInvalidError
|
||||
| CheckpointThreadNotFoundError
|
||||
| CheckpointWorkspacePathMissingError
|
||||
| CheckpointTurnRangeUnavailableError
|
||||
| CheckpointRefUnavailableError;
|
||||
export type CheckpointServiceError = CheckpointStoreError | ProjectionRepositoryError;
|
||||
@@ -1,14 +1,9 @@
|
||||
import * as RelayClient from "@t3tools/shared/relayClient";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Console from "effect/Console";
|
||||
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 References from "effect/References";
|
||||
|
||||
import { acquireRelayClientForLink, reportCloudDisconnectResults } from "./connect.ts";
|
||||
import { acquireRelayClientForLink } from "./connect.ts";
|
||||
|
||||
const managedExecutable = {
|
||||
status: "available",
|
||||
@@ -105,51 +100,3 @@ it.effect("reuses an available relay client executable without prompting", () =>
|
||||
assert.equal(promptCalls, 0);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps disconnect causes in structured logs and out of console warnings", () => {
|
||||
const warnings: ReadonlyArray<unknown>[] = [];
|
||||
const logs: Readonly<Record<string, unknown>>[] = [];
|
||||
const testConsole = {
|
||||
...globalThis.console,
|
||||
warn: (...args: ReadonlyArray<unknown>) => {
|
||||
warnings.push(args);
|
||||
},
|
||||
} satisfies Console.Console;
|
||||
const logger = Logger.make(({ fiber }) => {
|
||||
logs.push(fiber.getRef(References.CurrentLogAnnotations));
|
||||
});
|
||||
const liveFailure = "live unlink private diagnostic";
|
||||
const relayFailure = "relay revoke private diagnostic";
|
||||
|
||||
return reportCloudDisconnectResults({
|
||||
clearAuthorization: true,
|
||||
liveResult: {
|
||||
status: "failed",
|
||||
cause: Cause.fail(new Error(liveFailure)),
|
||||
},
|
||||
relayResult: Exit.failCause(Cause.die(new Error(relayFailure))),
|
||||
}).pipe(
|
||||
Effect.provideService(Console.Console, testConsole),
|
||||
Effect.provide(Logger.layer([logger], { mergeWithExisting: false })),
|
||||
Effect.tap(() =>
|
||||
Effect.sync(() => {
|
||||
assert.lengthOf(warnings, 2);
|
||||
const warningText = warnings.flat().map(String).join("\n");
|
||||
assert.include(warningText, "running server could not stop its tunnel");
|
||||
assert.include(warningText, "Could not revoke the relay-side environment record");
|
||||
assert.notInclude(warningText, liveFailure);
|
||||
assert.notInclude(warningText, relayFailure);
|
||||
assert.deepEqual(
|
||||
logs.map(({ operation, clearAuthorization }) => ({ operation, clearAuthorization })),
|
||||
[
|
||||
{ operation: "live-server-unlink", clearAuthorization: true },
|
||||
{ operation: "relay-environment-unlink", clearAuthorization: true },
|
||||
],
|
||||
);
|
||||
const loggedCauses = logs.map((log) => String(log.cause)).join("\n");
|
||||
assert.include(loggedCauses, liveFailure);
|
||||
assert.include(loggedCauses, relayFailure);
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
+29
-311
@@ -1,19 +1,13 @@
|
||||
import {
|
||||
AuthConnectClient,
|
||||
AuthConnectSecurityMode,
|
||||
AuthRelayWriteScope,
|
||||
EnvironmentHttpApi,
|
||||
type AuthConnectClient as AuthConnectClientType,
|
||||
type RelayClientInstallProgressEvent,
|
||||
type RelayClientInstallProgressStage,
|
||||
} from "@t3tools/contracts";
|
||||
import { RelayOkResponse } from "@t3tools/contracts/relay";
|
||||
import * as RelayClient from "@t3tools/shared/relayClient";
|
||||
import { withRelayClientTracing } from "@t3tools/shared/relayTracing";
|
||||
import { fromJsonStringPretty } from "@t3tools/shared/schemaJson";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Console from "effect/Console";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
@@ -21,8 +15,7 @@ import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as References from "effect/References";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { Argument, Command, Flag, GlobalFlag, Prompt } from "effect/unstable/cli";
|
||||
import { Command, Flag, GlobalFlag, Prompt } from "effect/unstable/cli";
|
||||
import {
|
||||
FetchHttpClient,
|
||||
HttpClient,
|
||||
@@ -58,69 +51,9 @@ interface CloudCliStatus {
|
||||
readonly linked: boolean;
|
||||
readonly cloudUserId: string | null;
|
||||
readonly relayUrl: string | null;
|
||||
readonly connectSecurityMode: AuthConnectSecurityMode;
|
||||
readonly relayClient: RelayClient.RelayClientStatus;
|
||||
}
|
||||
|
||||
const ConnectSecurityModeOutput = Schema.Struct({
|
||||
mode: AuthConnectSecurityMode,
|
||||
});
|
||||
const encodeConnectSecurityModeOutputJson = Schema.encodeUnknownEffect(
|
||||
fromJsonStringPretty(ConnectSecurityModeOutput),
|
||||
);
|
||||
const ConnectSecurityClientsOutput = Schema.Struct({
|
||||
clients: Schema.Array(AuthConnectClient),
|
||||
});
|
||||
const ConnectSecurityClientDecisionOutput = Schema.Struct({
|
||||
client: Schema.NullOr(AuthConnectClient),
|
||||
});
|
||||
const ConnectSecurityClientRevokeOutput = Schema.Struct({
|
||||
revoked: Schema.Boolean,
|
||||
});
|
||||
const encodeConnectSecurityClientsOutputJson = Schema.encodeUnknownEffect(
|
||||
fromJsonStringPretty(ConnectSecurityClientsOutput),
|
||||
);
|
||||
const encodeConnectSecurityClientDecisionOutputJson = Schema.encodeUnknownEffect(
|
||||
fromJsonStringPretty(ConnectSecurityClientDecisionOutput),
|
||||
);
|
||||
const encodeConnectSecurityClientRevokeOutputJson = Schema.encodeUnknownEffect(
|
||||
fromJsonStringPretty(ConnectSecurityClientRevokeOutput),
|
||||
);
|
||||
|
||||
function formatConnectClientLabel(client: AuthConnectClientType): string {
|
||||
return (
|
||||
client.client.label ??
|
||||
client.client.os ??
|
||||
`client ${client.clientProofKeyThumbprint.slice(0, 12)}`
|
||||
);
|
||||
}
|
||||
|
||||
function formatConnectClientDetails(client: AuthConnectClientType): string {
|
||||
const details = [
|
||||
client.client.deviceType !== "unknown" ? client.client.deviceType : null,
|
||||
client.client.os ?? null,
|
||||
client.deviceId ? `device ${client.deviceId}` : null,
|
||||
client.lastSeenAt ? `last seen ${DateTime.formatIso(client.lastSeenAt)}` : null,
|
||||
`requested ${DateTime.formatIso(client.requestedAt)}`,
|
||||
].filter((value): value is string => value !== null);
|
||||
return details.join(", ");
|
||||
}
|
||||
|
||||
function formatConnectClientList(clients: ReadonlyArray<AuthConnectClientType>): string {
|
||||
if (clients.length === 0) {
|
||||
return "No T3 Connect clients are registered.";
|
||||
}
|
||||
return [
|
||||
"T3 Connect clients",
|
||||
...clients.map(
|
||||
(client) =>
|
||||
` ${client.clientProofKeyThumbprint} ${client.status} ${formatConnectClientLabel(
|
||||
client,
|
||||
)} (${formatConnectClientDetails(client)})`,
|
||||
),
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
function formatRelayClientStatus(executable: RelayClient.RelayClientStatus): ReadonlyArray<string> {
|
||||
switch (executable.status) {
|
||||
case "available": {
|
||||
@@ -169,9 +102,6 @@ function formatCloudStatus(status: CloudCliStatus, options?: { readonly json?: b
|
||||
` Exposure: ${status.desired ? "enabled" : "disabled"}`,
|
||||
` Authorization: ${status.authenticated ? "stored credential" : "missing"}`,
|
||||
` Environment link: ${provisioned}`,
|
||||
` Client approval: ${
|
||||
status.connectSecurityMode === "client-approval" ? "required" : "account-wide"
|
||||
}`,
|
||||
` Relay: ${status.relayUrl ?? "not provisioned"}`,
|
||||
...formatRelayClientStatus(status.relayClient),
|
||||
...(nextStep ? ["", `Next: ${nextStep}`] : []),
|
||||
@@ -249,7 +179,7 @@ const withCloudCliSessionToken = <A, E, R>(
|
||||
type LiveCloudActionResult =
|
||||
| { readonly status: "not-running" }
|
||||
| { readonly status: "succeeded" }
|
||||
| { readonly status: "failed"; readonly cause: Cause.Cause<unknown> };
|
||||
| { readonly status: "failed"; readonly cause: unknown };
|
||||
|
||||
const runLiveCloudUnlink = Effect.fn("cloud.cli.run_live_unlink")(function* () {
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
@@ -281,21 +211,6 @@ type RelayUnlinkResult =
|
||||
| { readonly status: "revoked" }
|
||||
| { readonly status: "not-linked" };
|
||||
|
||||
type CloudDisconnectOperation = "live-server-unlink" | "relay-environment-unlink";
|
||||
|
||||
const logCloudDisconnectFailure = (
|
||||
operation: CloudDisconnectOperation,
|
||||
clearAuthorization: boolean,
|
||||
cause: Cause.Cause<unknown>,
|
||||
) =>
|
||||
Effect.logWarning("T3 Connect disconnect operation failed.").pipe(
|
||||
Effect.annotateLogs({
|
||||
operation,
|
||||
clearAuthorization,
|
||||
cause: Cause.pretty(cause),
|
||||
}),
|
||||
);
|
||||
|
||||
const unlinkRelayEnvironment = Effect.fn("cloud.cli.unlink_relay_environment")(function* () {
|
||||
const tokens = yield* CliTokenManager.CloudCliTokenManager;
|
||||
const token = yield* tokens.getExisting;
|
||||
@@ -321,42 +236,6 @@ const unlinkRelayEnvironment = Effect.fn("cloud.cli.unlink_relay_environment")(f
|
||||
: ({ status: "not-linked" } satisfies RelayUnlinkResult);
|
||||
});
|
||||
|
||||
export const reportCloudDisconnectResults = Effect.fn("cloud.cli.report_disconnect_results")(
|
||||
function* (input: {
|
||||
readonly clearAuthorization: boolean;
|
||||
readonly liveResult: LiveCloudActionResult;
|
||||
readonly relayResult: Exit.Exit<RelayUnlinkResult, unknown>;
|
||||
}) {
|
||||
if (input.liveResult.status === "failed") {
|
||||
yield* logCloudDisconnectFailure(
|
||||
"live-server-unlink",
|
||||
input.clearAuthorization,
|
||||
input.liveResult.cause,
|
||||
);
|
||||
yield* Console.warn(
|
||||
"T3 Connect is disabled, but the running server could not stop its tunnel.\nRestart that server to stop the connector.",
|
||||
);
|
||||
} else {
|
||||
yield* Console.log("T3 Connect is disabled locally.");
|
||||
}
|
||||
|
||||
if (Exit.isFailure(input.relayResult)) {
|
||||
yield* logCloudDisconnectFailure(
|
||||
"relay-environment-unlink",
|
||||
input.clearAuthorization,
|
||||
input.relayResult.cause,
|
||||
);
|
||||
yield* Console.warn(
|
||||
input.clearAuthorization
|
||||
? "Could not revoke the relay-side environment record before signing out.\nThe stored CLI authorization was still removed locally."
|
||||
: "Could not revoke the relay-side environment record yet.\nRun `t3 connect unlink` again when the relay is reachable.",
|
||||
);
|
||||
} else if (input.relayResult.value.status === "revoked") {
|
||||
yield* Console.log("Revoked the relay-side environment record.");
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
const disconnectCloud = Effect.fn("cloud.cli.disconnect")(function* (options: {
|
||||
readonly clearAuthorization: boolean;
|
||||
}) {
|
||||
@@ -370,11 +249,23 @@ const disconnectCloud = Effect.fn("cloud.cli.disconnect")(function* (options: {
|
||||
yield* tokens.clear;
|
||||
}
|
||||
|
||||
yield* reportCloudDisconnectResults({
|
||||
clearAuthorization: options.clearAuthorization,
|
||||
liveResult,
|
||||
relayResult,
|
||||
});
|
||||
if (liveResult.status === "failed") {
|
||||
yield* Console.warn(
|
||||
`T3 Connect is disabled, but the running server could not stop its tunnel: ${String(liveResult.cause)}\nRestart that server to stop the connector.`,
|
||||
);
|
||||
} else {
|
||||
yield* Console.log("T3 Connect is disabled locally.");
|
||||
}
|
||||
|
||||
if (Exit.isFailure(relayResult)) {
|
||||
yield* Console.warn(
|
||||
options.clearAuthorization
|
||||
? `Could not revoke the relay-side environment record before signing out: ${String(relayResult.cause)}\nThe stored CLI authorization was still removed locally.`
|
||||
: `Could not revoke the relay-side environment record yet: ${String(relayResult.cause)}\nRun \`t3 connect unlink\` again when the relay is reachable.`,
|
||||
);
|
||||
} else if (relayResult.value.status === "revoked") {
|
||||
yield* Console.log("Revoked the relay-side environment record.");
|
||||
}
|
||||
|
||||
if (options.clearAuthorization) {
|
||||
yield* Console.log("Signed out of T3 Connect locally.");
|
||||
@@ -480,26 +371,22 @@ const connectStatusCommand = Command.make("status", {
|
||||
const secrets = yield* ServerSecretStore.ServerSecretStore;
|
||||
const relayClient = yield* RelayClient.RelayClient;
|
||||
const tokens = yield* CliTokenManager.CloudCliTokenManager;
|
||||
const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
|
||||
const [desired, authenticated, cloudUserId, relayUrl, connectSecurityMode, executable] =
|
||||
yield* Effect.all(
|
||||
[
|
||||
CliState.readCliDesiredCloudLink,
|
||||
tokens.hasCredential,
|
||||
secrets.get(CLOUD_LINKED_USER_ID),
|
||||
secrets.get(RELAY_URL_SECRET),
|
||||
environmentAuth.getConnectSecurityMode(),
|
||||
relayClient.resolve,
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
const [desired, authenticated, cloudUserId, relayUrl, executable] = yield* Effect.all(
|
||||
[
|
||||
CliState.readCliDesiredCloudLink,
|
||||
tokens.hasCredential,
|
||||
secrets.get(CLOUD_LINKED_USER_ID),
|
||||
secrets.get(RELAY_URL_SECRET),
|
||||
relayClient.resolve,
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
const status: CloudCliStatus = {
|
||||
desired,
|
||||
authenticated,
|
||||
linked: Option.isSome(cloudUserId),
|
||||
cloudUserId: Option.isSome(cloudUserId) ? bytesToString(cloudUserId.value) : null,
|
||||
relayUrl: Option.isSome(relayUrl) ? bytesToString(relayUrl.value) : null,
|
||||
connectSecurityMode,
|
||||
relayClient: executable,
|
||||
};
|
||||
yield* Console.log(formatCloudStatus(status, { json: flags.json }));
|
||||
@@ -511,174 +398,6 @@ const connectStatusCommand = Command.make("status", {
|
||||
),
|
||||
);
|
||||
|
||||
const connectSecurityModeFlag = Flag.choice("mode", ["account", "client-approval"] as const).pipe(
|
||||
Flag.withDescription("Connect security mode."),
|
||||
Flag.optional,
|
||||
);
|
||||
|
||||
const connectClientThumbprintArgument = Argument.string("client-proof-key-thumbprint").pipe(
|
||||
Argument.withDescription("T3 Connect client proof key thumbprint."),
|
||||
);
|
||||
|
||||
const connectSecurityClientsCommand = Command.make("clients", {
|
||||
...projectLocationFlags,
|
||||
json: jsonFlag,
|
||||
}).pipe(
|
||||
Command.withDescription("List T3 Connect clients registered for approval."),
|
||||
Command.withHandler((flags) =>
|
||||
runCloudCommand(
|
||||
flags,
|
||||
Effect.gen(function* () {
|
||||
const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
|
||||
const clients = yield* environmentAuth.listConnectClients();
|
||||
if (flags.json) {
|
||||
const output = yield* encodeConnectSecurityClientsOutputJson({ clients });
|
||||
yield* Console.log(output);
|
||||
return;
|
||||
}
|
||||
yield* Console.log(formatConnectClientList(clients));
|
||||
}),
|
||||
{
|
||||
quietLogs: flags.json,
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const connectSecurityApproveCommand = Command.make("approve", {
|
||||
...projectLocationFlags,
|
||||
clientProofKeyThumbprint: connectClientThumbprintArgument,
|
||||
json: jsonFlag,
|
||||
}).pipe(
|
||||
Command.withDescription("Approve a T3 Connect client."),
|
||||
Command.withHandler((flags) =>
|
||||
runCloudCommand(
|
||||
flags,
|
||||
Effect.gen(function* () {
|
||||
const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
|
||||
const client = yield* environmentAuth.approveConnectClient(flags.clientProofKeyThumbprint);
|
||||
const clientOrNull = Option.getOrNull(client);
|
||||
if (flags.json) {
|
||||
const output = yield* encodeConnectSecurityClientDecisionOutputJson({
|
||||
client: clientOrNull,
|
||||
});
|
||||
yield* Console.log(output);
|
||||
return;
|
||||
}
|
||||
yield* Console.log(
|
||||
clientOrNull
|
||||
? `Approved T3 Connect client ${flags.clientProofKeyThumbprint}.`
|
||||
: `No active T3 Connect client found for ${flags.clientProofKeyThumbprint}.`,
|
||||
);
|
||||
}),
|
||||
{
|
||||
quietLogs: flags.json,
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const connectSecurityRejectCommand = Command.make("reject", {
|
||||
...projectLocationFlags,
|
||||
clientProofKeyThumbprint: connectClientThumbprintArgument,
|
||||
json: jsonFlag,
|
||||
}).pipe(
|
||||
Command.withDescription("Reject a T3 Connect client."),
|
||||
Command.withHandler((flags) =>
|
||||
runCloudCommand(
|
||||
flags,
|
||||
Effect.gen(function* () {
|
||||
const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
|
||||
const client = yield* environmentAuth.rejectConnectClient(flags.clientProofKeyThumbprint);
|
||||
const clientOrNull = Option.getOrNull(client);
|
||||
if (flags.json) {
|
||||
const output = yield* encodeConnectSecurityClientDecisionOutputJson({
|
||||
client: clientOrNull,
|
||||
});
|
||||
yield* Console.log(output);
|
||||
return;
|
||||
}
|
||||
yield* Console.log(
|
||||
clientOrNull
|
||||
? `Rejected T3 Connect client ${flags.clientProofKeyThumbprint}.`
|
||||
: `No active T3 Connect client found for ${flags.clientProofKeyThumbprint}.`,
|
||||
);
|
||||
}),
|
||||
{
|
||||
quietLogs: flags.json,
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const connectSecurityRevokeCommand = Command.make("revoke", {
|
||||
...projectLocationFlags,
|
||||
clientProofKeyThumbprint: connectClientThumbprintArgument,
|
||||
json: jsonFlag,
|
||||
}).pipe(
|
||||
Command.withDescription("Revoke a T3 Connect client approval record."),
|
||||
Command.withHandler((flags) =>
|
||||
runCloudCommand(
|
||||
flags,
|
||||
Effect.gen(function* () {
|
||||
const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
|
||||
const revoked = yield* environmentAuth.revokeConnectClient(flags.clientProofKeyThumbprint);
|
||||
if (flags.json) {
|
||||
const output = yield* encodeConnectSecurityClientRevokeOutputJson({ revoked });
|
||||
yield* Console.log(output);
|
||||
return;
|
||||
}
|
||||
yield* Console.log(
|
||||
revoked
|
||||
? `Revoked T3 Connect client ${flags.clientProofKeyThumbprint}.`
|
||||
: `No active T3 Connect client found for ${flags.clientProofKeyThumbprint}.`,
|
||||
);
|
||||
}),
|
||||
{
|
||||
quietLogs: flags.json,
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const connectSecurityCommand = Command.make("security", {
|
||||
...projectLocationFlags,
|
||||
mode: connectSecurityModeFlag,
|
||||
json: jsonFlag,
|
||||
}).pipe(
|
||||
Command.withDescription("Read or update T3 Connect client-approval mode."),
|
||||
Command.withHandler((flags) =>
|
||||
runCloudCommand(
|
||||
flags,
|
||||
Effect.gen(function* () {
|
||||
const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
|
||||
const mode = Option.isSome(flags.mode)
|
||||
? yield* environmentAuth.setConnectSecurityMode(flags.mode.value)
|
||||
: yield* environmentAuth.getConnectSecurityMode();
|
||||
if (flags.json) {
|
||||
const output = yield* encodeConnectSecurityModeOutputJson({ mode });
|
||||
yield* Console.log(output);
|
||||
return;
|
||||
}
|
||||
yield* Console.log(
|
||||
mode === "client-approval"
|
||||
? "T3 Connect client approval is required."
|
||||
: "T3 Connect uses account-wide access.",
|
||||
);
|
||||
}),
|
||||
{
|
||||
quietLogs: flags.json,
|
||||
},
|
||||
),
|
||||
),
|
||||
Command.withSubcommands([
|
||||
connectSecurityClientsCommand,
|
||||
connectSecurityApproveCommand,
|
||||
connectSecurityRejectCommand,
|
||||
connectSecurityRevokeCommand,
|
||||
]),
|
||||
);
|
||||
|
||||
const connectUnlinkCommand = Command.make("unlink", {
|
||||
...projectLocationFlags,
|
||||
}).pipe(
|
||||
@@ -703,7 +422,6 @@ export const connectCommand = Command.make("connect").pipe(
|
||||
connectLoginCommand,
|
||||
connectLinkCommand,
|
||||
connectStatusCommand,
|
||||
connectSecurityCommand,
|
||||
connectUnlinkCommand,
|
||||
connectLogoutCommand,
|
||||
]),
|
||||
|
||||
Loaded 100 of 405 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user