Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f3d8594d49 | ||
|
|
1d107bd84a | ||
|
|
65385c0281 | ||
|
|
6d2dae0627 | ||
|
|
10a8d3fbd9 | ||
|
|
0ad1e9d9e4 | ||
|
|
2f8d3baa88 | ||
|
|
6b74476322 | ||
|
|
d9e9539862 | ||
|
|
7118e43d16 | ||
|
|
4e8ee13d8f | ||
|
|
b17b6d50c5 | ||
|
|
ccf8331600 | ||
|
|
ffae12f329 | ||
|
|
01cd564557 | ||
|
|
4ee719a094 | ||
|
|
01492ebd3b | ||
|
|
93fd972108 | ||
|
|
df1540f3ac | ||
|
|
d5a72d5be1 | ||
|
|
742dd7af0d | ||
|
|
5c1ac92257 | ||
|
|
8bfdacf206 | ||
|
|
b6302784f8 |
No files matched your search
@@ -0,0 +1,74 @@
|
||||
---
|
||||
title: Effect Service Conventions
|
||||
model: claude-opus-4-8
|
||||
effort: high
|
||||
input: full_diff
|
||||
tools:
|
||||
- browse_code
|
||||
- git_tools
|
||||
- github_api_read_only
|
||||
- modify_pr
|
||||
include:
|
||||
- "apps/**/*.ts"
|
||||
- "apps/**/*.tsx"
|
||||
- "packages/**/*.ts"
|
||||
- "packages/**/*.tsx"
|
||||
- "infra/**/*.ts"
|
||||
- "infra/**/*.tsx"
|
||||
conclusion: failure
|
||||
showToolCalls: true
|
||||
---
|
||||
|
||||
# Effect service review
|
||||
|
||||
Review changed TypeScript and directly affected call sites for the conventions below. Apply them when a pull request creates, moves, refactors, or consumes an Effect service. Do not demand unrelated repository-wide cleanup. Treat these instructions as authoritative when older code differs.
|
||||
|
||||
## Imports and module namespaces
|
||||
|
||||
- Import Effect library modules from their subpaths as namespaces, for example `import * as Effect from "effect/Effect"` and `import * as Layer from "effect/Layer"`. Flag consolidated named imports from `"effect"` in touched Effect service code.
|
||||
- At a service boundary, import the local service module as a namespace and use its public module shape: `WorkspacePaths.WorkspacePaths`, `WorkspacePaths.make`, and `WorkspacePaths.layer`. Flag aliases such as `import { layer as workspacePathsLayer }` that erase the module namespace.
|
||||
- Namespace imports are not a blanket rule. Keep named imports for whole packages such as `@t3tools/contracts` and `electron`, and for modules used only for a pure helper, error, schema, config value, or standalone type. Do not request `import type * as Contracts`.
|
||||
- A package subpath that is itself a service module may use a namespace import when callers access its service/tag, `make`, or `layer` members.
|
||||
- When a barrel exposes an entire service module, prefer `export * as TokenStore from "./tokenStore.ts"` so consumers can use `TokenStore.TokenStore` and `TokenStore.layer`. Do not individually rename `make` and `layer` exports to simulate a namespace.
|
||||
|
||||
## Service definition
|
||||
|
||||
- Use the canonical single-file order: imports, error/schema declarations, the `Context.Service` tag with its inline interface, `make`, then `layer`.
|
||||
- Keep a service's schemas/errors, `Context.Service` tag, construction, and layer in one canonical module when they form one implementation.
|
||||
- Define the service interface inline in the `Context.Service` declaration. Do not retain a standalone `FooShape` or `FooServiceShape` interface/type.
|
||||
- Refer to the inferred service interface as `Foo["Service"]`, including in mechanically updated orchestration, MCP, tests, and integration harnesses.
|
||||
- Export a real `make` when the module owns construction. Do not create `make = Effect.succeed(...)` solely to force `Layer.effect`.
|
||||
- Export the canonical layer as `export const layer = Layer...`. `Layer.effect` is not required: use `Layer.succeed`, `Layer.scoped`, or another appropriate constructor when that matches the implementation.
|
||||
- In a concrete implementation module already named for the implementation, use plain `make` and `layer` (for example `BunPtyAdapter.ts` and `NodePtyAdapter.ts`).
|
||||
- Keep implementation-specific names when an abstract port module contains one of several possible implementations, for example `makeCloudflaredRelayClient` and `layerCloudflared` in `RelayClient.ts`.
|
||||
- `infra/relay/src/db.ts` is an intentional exception: an inline `Layer.succeed(RelayDb, db)` is acceptable without generic `make`/`layer` exports.
|
||||
|
||||
## Errors and predicates
|
||||
|
||||
- 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 an error. Flag error classes whose only meaningful field is `cause`, or whose `message` merely stringifies an opaque cause.
|
||||
- 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.
|
||||
- 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.
|
||||
- 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.
|
||||
- Split semantically distinct failures into separate error classes when a `reason`, `kind`, `phase`, or similar discriminator is used to choose the user-facing message or drive caller control flow. A discriminator used only for internal diagnostics may remain a field.
|
||||
- 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.
|
||||
|
||||
## File layout and migrations
|
||||
|
||||
- When combining `domain/Services/Foo.ts` and `domain/Layers/Foo.ts`, hoist the result to `domain/Foo.ts`.
|
||||
- Delete the old service/layer files. Do not leave compatibility re-export shims. Mechanically update every consumer, including orchestration, MCP, tests, and integration harnesses, to the canonical path.
|
||||
- Do not flag genuinely separate implementation/adapter modules merely because they remain in an implementation-oriented directory.
|
||||
- Avoid substantive orchestration or MCP redesign in service-cleanup PRs. Mechanical import, layer, and `Service["Service"]` updates are expected when required to remove obsolete paths or shapes.
|
||||
|
||||
## Change discipline
|
||||
|
||||
- Preserve useful comments, invariants, and specification documentation while moving code.
|
||||
- Do not add large tests solely to prove a mechanical refactor. Update existing tests and imports as needed.
|
||||
- If backend behavior changes, require focused tests. Use test implementations/layers for external services only; do not mock out core business logic.
|
||||
- Do not require `Layer.effect`, universal namespace imports, generic `make`/`layer` names for abstract-port implementations, separate error classes for diagnostic-only fields, or new tests for import-only changes.
|
||||
|
||||
## Reporting
|
||||
|
||||
Report only concrete violations introduced or retained in the pull request's changed scope. Prefer precise inline comments on the smallest relevant line range and state the expected fix. A clear convention violation may fail the check. Do not fail for optional style preferences or unrelated legacy code. If there are no findings, report exactly `All clear`.
|
||||
@@ -17,6 +17,7 @@ import * as DesktopBackendManager from "../backend/DesktopBackendManager.ts";
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
import * as DesktopLifecycle from "./DesktopLifecycle.ts";
|
||||
import * as DesktopObservability from "./DesktopObservability.ts";
|
||||
import * as DesktopShutdown from "./DesktopShutdown.ts";
|
||||
import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts";
|
||||
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
|
||||
import * as DesktopShellEnvironment from "../shell/DesktopShellEnvironment.ts";
|
||||
@@ -100,12 +101,12 @@ const handleFatalStartupError = Effect.fn("desktop.startup.handleFatalStartupErr
|
||||
): Effect.fn.Return<
|
||||
void,
|
||||
never,
|
||||
| DesktopLifecycle.DesktopShutdown
|
||||
| DesktopShutdown.DesktopShutdown
|
||||
| DesktopState.DesktopState
|
||||
| ElectronApp.ElectronApp
|
||||
| ElectronDialog.ElectronDialog
|
||||
> {
|
||||
const shutdown = yield* DesktopLifecycle.DesktopShutdown;
|
||||
const shutdown = yield* DesktopShutdown.DesktopShutdown;
|
||||
const state = yield* DesktopState.DesktopState;
|
||||
const electronApp = yield* ElectronApp.ElectronApp;
|
||||
const electronDialog = yield* ElectronDialog.ElectronDialog;
|
||||
@@ -237,7 +238,7 @@ const scopedProgram = Effect.scoped(
|
||||
yield* Effect.annotateLogsScoped({ scope: "desktop", runId });
|
||||
yield* Effect.annotateCurrentSpan({ scope: "desktop", runId });
|
||||
|
||||
const shutdown = yield* DesktopLifecycle.DesktopShutdown;
|
||||
const shutdown = yield* DesktopShutdown.DesktopShutdown;
|
||||
const backendManager = yield* DesktopBackendManager.DesktopBackendManager;
|
||||
|
||||
yield* Effect.addFinalizer(() =>
|
||||
|
||||
@@ -21,7 +21,6 @@ const textEncoder = new TextEncoder();
|
||||
const decodeConnectionCatalog = Schema.decodeEffect(
|
||||
Schema.fromJsonString(ConnectionCatalogDocument),
|
||||
);
|
||||
|
||||
function makeSafeStorageLayer(available: boolean, failDecrypt: Ref.Ref<boolean> | null = null) {
|
||||
return Layer.succeed(ElectronSafeStorage.ElectronSafeStorage, {
|
||||
isEncryptionAvailable: Effect.succeed(available),
|
||||
@@ -40,7 +39,7 @@ function makeSafeStorageLayer(available: boolean, failDecrypt: Ref.Ref<boolean>
|
||||
return decoded.slice("encrypted:".length);
|
||||
});
|
||||
},
|
||||
} satisfies ElectronSafeStorage.ElectronSafeStorageShape);
|
||||
} satisfies ElectronSafeStorage.ElectronSafeStorage["Service"]);
|
||||
}
|
||||
|
||||
function makeLayer(
|
||||
@@ -236,8 +235,11 @@ describe("DesktopConnectionCatalogStore", () => {
|
||||
const error = yield* store.get.pipe(Effect.flip);
|
||||
assert.instanceOf(
|
||||
error,
|
||||
DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreReadError,
|
||||
DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreDocumentDecodeError,
|
||||
);
|
||||
assert.equal(error.operation, "decode-catalog-document");
|
||||
assert.equal(error.catalogPath, catalogPath);
|
||||
assert.exists(error.cause);
|
||||
assert.equal(yield* fileSystem.readFileString(catalogPath), "{not-json");
|
||||
}),
|
||||
),
|
||||
@@ -253,7 +255,7 @@ describe("DesktopConnectionCatalogStore", () => {
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "readFileString",
|
||||
pathOrDescriptor: `${baseDir}/connection-catalog.json`,
|
||||
pathOrDescriptor: `${baseDir}/userdata/connection-catalog.json`,
|
||||
});
|
||||
const fileSystemLayer = Layer.succeed(
|
||||
FileSystem.FileSystem,
|
||||
@@ -270,10 +272,115 @@ describe("DesktopConnectionCatalogStore", () => {
|
||||
error,
|
||||
DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreReadError,
|
||||
);
|
||||
assert.equal(error.cause, permissionError);
|
||||
assert.equal(error.operation, "read-catalog");
|
||||
assert.equal(error.catalogPath, `${baseDir}/userdata/connection-catalog.json`);
|
||||
assert.strictEqual(error.cause, permissionError);
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Failed to read the desktop connection catalog at ${baseDir}/userdata/connection-catalog.json.`,
|
||||
);
|
||||
assert.notEqual(error.message, permissionError.message);
|
||||
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
|
||||
);
|
||||
|
||||
it.effect("reports the failed catalog write operation and path", () =>
|
||||
Effect.gen(function* () {
|
||||
const baseFileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* baseFileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-connection-catalog-test-",
|
||||
});
|
||||
const permissionError = PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "makeDirectory",
|
||||
pathOrDescriptor: `${baseDir}/userdata`,
|
||||
});
|
||||
const fileSystemLayer = Layer.succeed(
|
||||
FileSystem.FileSystem,
|
||||
FileSystem.makeNoop({
|
||||
makeDirectory: () => Effect.fail(permissionError),
|
||||
}),
|
||||
);
|
||||
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore.pipe(
|
||||
Effect.provide(makeLayer(baseDir, true, null, fileSystemLayer)),
|
||||
);
|
||||
|
||||
const error = yield* store.set("{}").pipe(Effect.flip);
|
||||
assert.instanceOf(
|
||||
error,
|
||||
DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreWriteError,
|
||||
);
|
||||
assert.equal(error.operation, "create-directory");
|
||||
assert.equal(error.path, `${baseDir}/userdata`);
|
||||
assert.strictEqual(error.cause, permissionError);
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Desktop connection catalog write failed during create-directory at ${baseDir}/userdata.`,
|
||||
);
|
||||
assert.notEqual(error.message, permissionError.message);
|
||||
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
|
||||
);
|
||||
|
||||
it.effect("reports the legacy migration stage", () =>
|
||||
withStore(
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
|
||||
yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
|
||||
yield* fileSystem.writeFileString(environment.savedEnvironmentRegistryPath, "{not-json");
|
||||
|
||||
const error = yield* store.get.pipe(Effect.flip);
|
||||
assert.instanceOf(
|
||||
error,
|
||||
DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreMigrationError,
|
||||
);
|
||||
assert.equal(error.operation, "read-legacy-registry");
|
||||
assert.equal(error.catalogPath, `${environment.stateDir}/connection-catalog.json`);
|
||||
assert.instanceOf(
|
||||
error.cause,
|
||||
DesktopSavedEnvironments.DesktopSavedEnvironmentsDocumentDecodeError,
|
||||
);
|
||||
const registryError =
|
||||
error.cause as DesktopSavedEnvironments.DesktopSavedEnvironmentsDocumentDecodeError;
|
||||
assert.exists(registryError.cause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Legacy desktop saved-environment migration failed during read-legacy-registry into ${environment.stateDir}/connection-catalog.json.`,
|
||||
);
|
||||
assert.notEqual(error.message, registryError.message);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("reports invalid encrypted catalog data without exposing it", () =>
|
||||
withStore(
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
|
||||
const catalogPath = `${environment.stateDir}/connection-catalog.json`;
|
||||
yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
|
||||
yield* fileSystem.writeFileString(catalogPath, '{"version":1,"encryptedCatalog":"%%%"}\n');
|
||||
|
||||
const error = yield* store.get.pipe(Effect.flip);
|
||||
assert.instanceOf(
|
||||
error,
|
||||
DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreDecodeError,
|
||||
);
|
||||
assert.equal(error.operation, "decode-encrypted-catalog");
|
||||
assert.equal(error.resource, "encryptedCatalog");
|
||||
assert.equal(error.catalogPath, catalogPath);
|
||||
assert.exists(error.cause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Failed to decode encryptedCatalog for the desktop connection catalog at ${catalogPath}.`,
|
||||
);
|
||||
assert.notInclude(error.message, "%%%");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("surfaces a catalog that can no longer be decrypted without deleting it", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
|
||||
@@ -14,14 +14,12 @@ import type { PersistedSavedEnvironmentRecord } from "@t3tools/contracts";
|
||||
import { fromLenientJson } from "@t3tools/shared/schemaJson";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Encoding from "effect/Encoding";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
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 * as ElectronSafeStorage from "../electron/ElectronSafeStorage.ts";
|
||||
@@ -48,76 +46,156 @@ const encodeRuntimeConnectionCatalogDocumentJson = Schema.encodeEffect(
|
||||
RuntimeConnectionCatalogDocumentJson,
|
||||
);
|
||||
|
||||
export class DesktopConnectionCatalogStoreWriteError extends Data.TaggedError(
|
||||
const DesktopConnectionCatalogStoreWriteOperation = Schema.Literals([
|
||||
"create-temporary-file-name",
|
||||
"encode-document",
|
||||
"create-directory",
|
||||
"write-temporary-file",
|
||||
"replace-catalog-file",
|
||||
]);
|
||||
type DesktopConnectionCatalogStoreWriteOperation =
|
||||
typeof DesktopConnectionCatalogStoreWriteOperation.Type;
|
||||
|
||||
const DesktopConnectionCatalogStoreMigrationOperation = Schema.Literals([
|
||||
"read-legacy-registry",
|
||||
"read-legacy-secret",
|
||||
"encode-catalog",
|
||||
"persist-catalog",
|
||||
]);
|
||||
type DesktopConnectionCatalogStoreMigrationOperation =
|
||||
typeof DesktopConnectionCatalogStoreMigrationOperation.Type;
|
||||
|
||||
export class DesktopConnectionCatalogStoreWriteError extends Schema.TaggedErrorClass<DesktopConnectionCatalogStoreWriteError>()(
|
||||
"DesktopConnectionCatalogStoreWriteError",
|
||||
)<{
|
||||
readonly cause: PlatformError.PlatformError | Schema.SchemaError;
|
||||
}> {
|
||||
override get message() {
|
||||
return `Failed to write desktop connection catalog: ${this.cause.message}`;
|
||||
{
|
||||
operation: DesktopConnectionCatalogStoreWriteOperation,
|
||||
path: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Desktop connection catalog write failed during ${this.operation} at ${this.path}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopConnectionCatalogStoreDecodeError extends Data.TaggedError(
|
||||
const writeError = (
|
||||
operation: DesktopConnectionCatalogStoreWriteOperation,
|
||||
path: string,
|
||||
cause: unknown,
|
||||
): DesktopConnectionCatalogStoreWriteError =>
|
||||
new DesktopConnectionCatalogStoreWriteError({
|
||||
operation,
|
||||
path,
|
||||
cause,
|
||||
});
|
||||
|
||||
export class DesktopConnectionCatalogStoreDecodeError extends Schema.TaggedErrorClass<DesktopConnectionCatalogStoreDecodeError>()(
|
||||
"DesktopConnectionCatalogStoreDecodeError",
|
||||
)<{
|
||||
readonly cause: Encoding.EncodingError;
|
||||
}> {
|
||||
override get message() {
|
||||
return "Failed to decode the desktop connection catalog.";
|
||||
{
|
||||
operation: Schema.Literal("decode-encrypted-catalog"),
|
||||
resource: Schema.Literal("encryptedCatalog"),
|
||||
catalogPath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to decode ${this.resource} for the desktop connection catalog at ${this.catalogPath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopConnectionCatalogStoreReadError extends Data.TaggedError(
|
||||
export class DesktopConnectionCatalogStoreReadError extends Schema.TaggedErrorClass<DesktopConnectionCatalogStoreReadError>()(
|
||||
"DesktopConnectionCatalogStoreReadError",
|
||||
)<{
|
||||
readonly cause: PlatformError.PlatformError | Schema.SchemaError;
|
||||
}> {
|
||||
override get message() {
|
||||
return `Failed to read desktop connection catalog: ${this.cause.message}`;
|
||||
{
|
||||
operation: Schema.Literal("read-catalog"),
|
||||
catalogPath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to read the desktop connection catalog at ${this.catalogPath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopConnectionCatalogStoreMigrationError extends Data.TaggedError(
|
||||
export class DesktopConnectionCatalogStoreDocumentDecodeError extends Schema.TaggedErrorClass<DesktopConnectionCatalogStoreDocumentDecodeError>()(
|
||||
"DesktopConnectionCatalogStoreDocumentDecodeError",
|
||||
{
|
||||
operation: Schema.Literal("decode-catalog-document"),
|
||||
catalogPath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to decode the desktop connection catalog document at ${this.catalogPath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopConnectionCatalogStoreMigrationError extends Schema.TaggedErrorClass<DesktopConnectionCatalogStoreMigrationError>()(
|
||||
"DesktopConnectionCatalogStoreMigrationError",
|
||||
)<{
|
||||
readonly cause: unknown;
|
||||
}> {
|
||||
override get message() {
|
||||
return "Failed to migrate legacy desktop saved environments.";
|
||||
{
|
||||
operation: DesktopConnectionCatalogStoreMigrationOperation,
|
||||
catalogPath: Schema.String,
|
||||
environmentId: Schema.optionalKey(Schema.String),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
const environment =
|
||||
this.environmentId === undefined ? "" : ` for environment ${this.environmentId}`;
|
||||
return `Legacy desktop saved-environment migration failed during ${this.operation}${environment} into ${this.catalogPath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export interface DesktopConnectionCatalogStoreShape {
|
||||
readonly get: Effect.Effect<
|
||||
Option.Option<string>,
|
||||
| DesktopConnectionCatalogStoreReadError
|
||||
| DesktopConnectionCatalogStoreDecodeError
|
||||
| DesktopConnectionCatalogStoreMigrationError
|
||||
| ElectronSafeStorage.ElectronSafeStorageAvailabilityError
|
||||
| ElectronSafeStorage.ElectronSafeStorageDecryptError
|
||||
>;
|
||||
readonly set: (
|
||||
catalog: string,
|
||||
) => Effect.Effect<
|
||||
boolean,
|
||||
| DesktopConnectionCatalogStoreWriteError
|
||||
| ElectronSafeStorage.ElectronSafeStorageAvailabilityError
|
||||
| ElectronSafeStorage.ElectronSafeStorageEncryptError
|
||||
>;
|
||||
readonly clear: Effect.Effect<void>;
|
||||
}
|
||||
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,
|
||||
DesktopConnectionCatalogStoreShape
|
||||
{
|
||||
readonly get: Effect.Effect<
|
||||
Option.Option<string>,
|
||||
| DesktopConnectionCatalogStoreReadError
|
||||
| DesktopConnectionCatalogStoreDocumentDecodeError
|
||||
| DesktopConnectionCatalogStoreDecodeError
|
||||
| DesktopConnectionCatalogStoreMigrationError
|
||||
| ElectronSafeStorage.ElectronSafeStorageAvailabilityError
|
||||
| ElectronSafeStorage.ElectronSafeStorageDecryptError
|
||||
>;
|
||||
readonly set: (
|
||||
catalog: string,
|
||||
) => Effect.Effect<
|
||||
boolean,
|
||||
| DesktopConnectionCatalogStoreWriteError
|
||||
| ElectronSafeStorage.ElectronSafeStorageAvailabilityError
|
||||
| ElectronSafeStorage.ElectronSafeStorageEncryptError
|
||||
>;
|
||||
readonly clear: Effect.Effect<void>;
|
||||
}
|
||||
>()("@t3tools/desktop/app/DesktopConnectionCatalogStore") {}
|
||||
|
||||
function decodeSecretBytes(
|
||||
catalogPath: string,
|
||||
encoded: string,
|
||||
): Effect.Effect<Uint8Array, DesktopConnectionCatalogStoreDecodeError> {
|
||||
return Effect.fromResult(Encoding.decodeBase64(encoded)).pipe(
|
||||
Effect.mapError((cause) => new DesktopConnectionCatalogStoreDecodeError({ cause })),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopConnectionCatalogStoreDecodeError({
|
||||
operation: "decode-encrypted-catalog",
|
||||
resource: "encryptedCatalog",
|
||||
catalogPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -126,16 +204,34 @@ const readDocument = (
|
||||
catalogPath: string,
|
||||
): Effect.Effect<
|
||||
Option.Option<EncryptedConnectionCatalogDocument>,
|
||||
PlatformError.PlatformError | Schema.SchemaError
|
||||
DesktopConnectionCatalogStoreReadError | DesktopConnectionCatalogStoreDocumentDecodeError
|
||||
> =>
|
||||
fileSystem.readFileString(catalogPath).pipe(
|
||||
Effect.catch((error) =>
|
||||
error.reason._tag === "NotFound" ? Effect.succeed<string | null>(null) : Effect.fail(error),
|
||||
error.reason._tag === "NotFound"
|
||||
? Effect.succeed<string | null>(null)
|
||||
: Effect.fail(
|
||||
new DesktopConnectionCatalogStoreReadError({
|
||||
operation: "read-catalog",
|
||||
catalogPath,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
),
|
||||
Effect.flatMap((raw) =>
|
||||
raw === null
|
||||
? Effect.succeed(Option.none<EncryptedConnectionCatalogDocument>())
|
||||
: decodeEncryptedConnectionCatalogDocumentJson(raw).pipe(Effect.map(Option.some)),
|
||||
: decodeEncryptedConnectionCatalogDocumentJson(raw).pipe(
|
||||
Effect.map(Option.some),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopConnectionCatalogStoreDocumentDecodeError({
|
||||
operation: "decode-catalog-document",
|
||||
catalogPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -145,14 +241,24 @@ const writeDocument = Effect.fn("desktop.connectionCatalogStore.writeDocument")(
|
||||
readonly catalogPath: string;
|
||||
readonly document: EncryptedConnectionCatalogDocument;
|
||||
readonly suffix: string;
|
||||
}): Effect.fn.Return<void, PlatformError.PlatformError | Schema.SchemaError> {
|
||||
}): Effect.fn.Return<void, DesktopConnectionCatalogStoreWriteError> {
|
||||
const directory = input.path.dirname(input.catalogPath);
|
||||
const tempPath = `${input.catalogPath}.${process.pid}.${input.suffix}.tmp`;
|
||||
const encoded = yield* encodeEncryptedConnectionCatalogDocumentJson(input.document);
|
||||
yield* input.fileSystem.makeDirectory(directory, { recursive: true });
|
||||
const encoded = yield* encodeEncryptedConnectionCatalogDocumentJson(input.document).pipe(
|
||||
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`);
|
||||
yield* input.fileSystem.rename(tempPath, input.catalogPath);
|
||||
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(
|
||||
@@ -175,10 +281,11 @@ const migrateSavedEnvironmentRecords = Effect.fn(
|
||||
"desktop.connectionCatalogStore.migrateSavedEnvironmentRecords",
|
||||
)(function* (
|
||||
records: readonly PersistedSavedEnvironmentRecord[],
|
||||
savedEnvironments: DesktopSavedEnvironments.DesktopSavedEnvironmentsShape,
|
||||
savedEnvironments: DesktopSavedEnvironments.DesktopSavedEnvironments["Service"],
|
||||
catalogPath: string,
|
||||
): Effect.fn.Return<
|
||||
RuntimeConnectionCatalogDocumentType,
|
||||
DesktopSavedEnvironments.DesktopSavedEnvironmentsGetSecretError
|
||||
DesktopConnectionCatalogStoreMigrationError
|
||||
> {
|
||||
const targets: Array<RuntimeConnectionCatalogDocumentType["targets"][number]> = [];
|
||||
const profiles: Array<RuntimeConnectionCatalogDocumentType["profiles"][number]> = [];
|
||||
@@ -232,7 +339,13 @@ const migrateSavedEnvironmentRecords = Effect.fn(
|
||||
wsBaseUrl: record.wsBaseUrl,
|
||||
}),
|
||||
);
|
||||
const token = yield* savedEnvironments.getSecret(record.environmentId);
|
||||
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,
|
||||
@@ -250,79 +363,82 @@ const migrateSavedEnvironmentRecords = Effect.fn(
|
||||
};
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(
|
||||
DesktopConnectionCatalogStore,
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const safeStorage = yield* ElectronSafeStorage.ElectronSafeStorage;
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
|
||||
const catalogPath = path.join(environment.stateDir, "connection-catalog.json");
|
||||
export const make = Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const safeStorage = yield* ElectronSafeStorage.ElectronSafeStorage;
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
|
||||
const catalogPath = path.join(environment.stateDir, "connection-catalog.json");
|
||||
|
||||
const writeCatalog = Effect.fn("desktop.connectionCatalogStore.writeCatalog")(function* (
|
||||
catalog: string,
|
||||
) {
|
||||
const encryptedCatalog = Encoding.encodeBase64(yield* safeStorage.encryptString(catalog));
|
||||
const suffix = (yield* crypto.randomUUIDv4.pipe(
|
||||
Effect.mapError((cause) => new DesktopConnectionCatalogStoreWriteError({ cause })),
|
||||
)).replace(/-/g, "");
|
||||
yield* writeDocument({
|
||||
fileSystem,
|
||||
path,
|
||||
catalogPath,
|
||||
document: { version: 1, encryptedCatalog },
|
||||
suffix,
|
||||
}).pipe(Effect.mapError((cause) => new DesktopConnectionCatalogStoreWriteError({ cause })));
|
||||
const writeCatalog = Effect.fn("desktop.connectionCatalogStore.writeCatalog")(function* (
|
||||
catalog: string,
|
||||
) {
|
||||
const encryptedCatalog = Encoding.encodeBase64(yield* safeStorage.encryptString(catalog));
|
||||
const suffix = (yield* crypto.randomUUIDv4.pipe(
|
||||
Effect.mapError((cause) => writeError("create-temporary-file-name", catalogPath, cause)),
|
||||
)).replace(/-/g, "");
|
||||
yield* writeDocument({
|
||||
fileSystem,
|
||||
path,
|
||||
catalogPath,
|
||||
document: { version: 1, encryptedCatalog },
|
||||
suffix,
|
||||
});
|
||||
});
|
||||
|
||||
const migrateLegacyCatalog = Effect.gen(function* () {
|
||||
const migrateLegacyCatalog = Effect.gen(function* () {
|
||||
if (!(yield* safeStorage.isEncryptionAvailable)) {
|
||||
return Option.none<string>();
|
||||
}
|
||||
const records = yield* savedEnvironments.getRegistry.pipe(
|
||||
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) => migrationError("encode-catalog", catalogPath, cause)),
|
||||
);
|
||||
yield* writeCatalog(encoded).pipe(
|
||||
Effect.mapError((cause) => migrationError("persist-catalog", catalogPath, cause)),
|
||||
);
|
||||
return Option.some(encoded);
|
||||
});
|
||||
|
||||
return DesktopConnectionCatalogStore.of({
|
||||
get: Effect.gen(function* () {
|
||||
const document = yield* readDocument(fileSystem, catalogPath);
|
||||
if (Option.isNone(document)) {
|
||||
return yield* migrateLegacyCatalog;
|
||||
}
|
||||
if (!(yield* safeStorage.isEncryptionAvailable)) {
|
||||
return Option.none<string>();
|
||||
}
|
||||
const records = yield* savedEnvironments.getRegistry;
|
||||
if (records.length === 0) {
|
||||
return Option.none<string>();
|
||||
const decrypted = yield* decodeSecretBytes(catalogPath, document.value.encryptedCatalog).pipe(
|
||||
Effect.flatMap(safeStorage.decryptString),
|
||||
);
|
||||
return Option.some(decrypted);
|
||||
}).pipe(Effect.withSpan("desktop.connectionCatalogStore.get")),
|
||||
set: Effect.fn("desktop.connectionCatalogStore.set")(function* (catalog) {
|
||||
if (!(yield* safeStorage.isEncryptionAvailable)) {
|
||||
return false;
|
||||
}
|
||||
const catalog = yield* migrateSavedEnvironmentRecords(records, savedEnvironments);
|
||||
const encoded = yield* encodeRuntimeConnectionCatalogDocumentJson(catalog);
|
||||
yield* writeCatalog(encoded);
|
||||
return Option.some(encoded);
|
||||
}).pipe(Effect.mapError((cause) => new DesktopConnectionCatalogStoreMigrationError({ cause })));
|
||||
|
||||
return DesktopConnectionCatalogStore.of({
|
||||
get: Effect.gen(function* () {
|
||||
const document = yield* readDocument(fileSystem, catalogPath).pipe(
|
||||
Effect.mapError((cause) => new DesktopConnectionCatalogStoreReadError({ cause })),
|
||||
);
|
||||
if (Option.isNone(document)) {
|
||||
return yield* migrateLegacyCatalog;
|
||||
}
|
||||
if (!(yield* safeStorage.isEncryptionAvailable)) {
|
||||
return Option.none<string>();
|
||||
}
|
||||
const decrypted = yield* decodeSecretBytes(document.value.encryptedCatalog).pipe(
|
||||
Effect.flatMap(safeStorage.decryptString),
|
||||
);
|
||||
return Option.some(decrypted);
|
||||
}).pipe(Effect.withSpan("desktop.connectionCatalogStore.get")),
|
||||
set: Effect.fn("desktop.connectionCatalogStore.set")(function* (catalog) {
|
||||
if (!(yield* safeStorage.isEncryptionAvailable)) {
|
||||
return false;
|
||||
}
|
||||
yield* writeCatalog(catalog);
|
||||
return true;
|
||||
}),
|
||||
clear: fileSystem.remove(catalogPath, { force: true }).pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.logWarning("Could not clear the desktop connection catalog.", {
|
||||
catalogPath,
|
||||
error,
|
||||
}),
|
||||
),
|
||||
Effect.withSpan("desktop.connectionCatalogStore.clear"),
|
||||
yield* writeCatalog(catalog);
|
||||
return true;
|
||||
}),
|
||||
clear: fileSystem.remove(catalogPath, { force: true }).pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.logWarning("Could not clear the desktop connection catalog.", {
|
||||
catalogPath,
|
||||
error,
|
||||
}),
|
||||
),
|
||||
});
|
||||
}),
|
||||
);
|
||||
Effect.withSpan("desktop.connectionCatalogStore.clear"),
|
||||
),
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(DesktopConnectionCatalogStore, make);
|
||||
@@ -9,17 +9,15 @@ import type * as Electron from "electron";
|
||||
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
import * as DesktopObservability from "./DesktopObservability.ts";
|
||||
import * as DesktopShutdownModule from "./DesktopShutdown.ts";
|
||||
import * as DesktopShutdown from "./DesktopShutdown.ts";
|
||||
import * as ElectronApp from "../electron/ElectronApp.ts";
|
||||
import * as ElectronTheme from "../electron/ElectronTheme.ts";
|
||||
import * as DesktopState from "./DesktopState.ts";
|
||||
import * as DesktopWindow from "../window/DesktopWindow.ts";
|
||||
|
||||
export { DesktopShutdown, layer as layerShutdown } from "./DesktopShutdown.ts";
|
||||
|
||||
export type DesktopLifecycleRuntimeServices =
|
||||
| DesktopEnvironment.DesktopEnvironment
|
||||
| DesktopShutdownModule.DesktopShutdown
|
||||
| DesktopShutdown.DesktopShutdown
|
||||
| DesktopState.DesktopState
|
||||
| DesktopWindow.DesktopWindow
|
||||
| ElectronApp.ElectronApp
|
||||
@@ -63,8 +61,8 @@ function addScopedListener<Args extends ReadonlyArray<unknown>>(
|
||||
}
|
||||
|
||||
const requestDesktopShutdownAndWait = Effect.fn("desktop.lifecycle.requestShutdownAndWait")(
|
||||
function* (): Effect.fn.Return<void, never, DesktopShutdownModule.DesktopShutdown> {
|
||||
const shutdown = yield* DesktopShutdownModule.DesktopShutdown;
|
||||
function* (): Effect.fn.Return<void, never, DesktopShutdown.DesktopShutdown> {
|
||||
const shutdown = yield* DesktopShutdown.DesktopShutdown;
|
||||
yield* shutdown.request;
|
||||
yield* shutdown.awaitComplete;
|
||||
},
|
||||
|
||||
@@ -34,7 +34,7 @@ const serverExposureLayer = Layer.succeed(DesktopServerExposure.DesktopServerExp
|
||||
setMode: () => Effect.die("unexpected setMode"),
|
||||
setTailscaleServeEnabled: () => Effect.die("unexpected setTailscaleServeEnabled"),
|
||||
getAdvertisedEndpoints: Effect.succeed([]),
|
||||
} satisfies DesktopServerExposure.DesktopServerExposureShape);
|
||||
} satisfies DesktopServerExposure.DesktopServerExposure["Service"]);
|
||||
|
||||
function makeEnvironmentLayer(
|
||||
baseDir: string,
|
||||
|
||||
@@ -14,16 +14,14 @@ import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import * as DesktopObservability from "../app/DesktopObservability.ts";
|
||||
import * as DesktopServerExposure from "./DesktopServerExposure.ts";
|
||||
|
||||
export interface DesktopBackendConfigurationShape {
|
||||
readonly resolve: Effect.Effect<
|
||||
DesktopBackendManager.DesktopBackendStartConfig,
|
||||
PlatformError.PlatformError
|
||||
>;
|
||||
}
|
||||
|
||||
export class DesktopBackendConfiguration extends Context.Service<
|
||||
DesktopBackendConfiguration,
|
||||
DesktopBackendConfigurationShape
|
||||
{
|
||||
readonly resolve: Effect.Effect<
|
||||
DesktopBackendManager.DesktopBackendStartConfig,
|
||||
PlatformError.PlatformError
|
||||
>;
|
||||
}
|
||||
>()("@t3tools/desktop/backend/DesktopBackendConfiguration") {}
|
||||
|
||||
interface BackendObservabilitySettings {
|
||||
@@ -130,40 +128,39 @@ const resolveBackendStartConfig = Effect.fn("desktop.backendConfiguration.resolv
|
||||
},
|
||||
);
|
||||
|
||||
export const layer = Layer.effect(
|
||||
DesktopBackendConfiguration,
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const tokenRef = yield* Ref.make(Option.none<string>());
|
||||
const getOrCreateBootstrapToken = Effect.gen(function* () {
|
||||
const existing = yield* Ref.get(tokenRef);
|
||||
if (Option.isSome(existing)) {
|
||||
return existing.value;
|
||||
}
|
||||
export const make = Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const tokenRef = yield* Ref.make(Option.none<string>());
|
||||
const getOrCreateBootstrapToken = Effect.gen(function* () {
|
||||
const existing = yield* Ref.get(tokenRef);
|
||||
if (Option.isSome(existing)) {
|
||||
return existing.value;
|
||||
}
|
||||
|
||||
const token = Encoding.encodeHex(yield* crypto.randomBytes(24));
|
||||
yield* Ref.set(tokenRef, Option.some(token));
|
||||
return token;
|
||||
});
|
||||
const token = Encoding.encodeHex(yield* crypto.randomBytes(24));
|
||||
yield* Ref.set(tokenRef, Option.some(token));
|
||||
return token;
|
||||
});
|
||||
|
||||
return DesktopBackendConfiguration.of({
|
||||
resolve: Effect.gen(function* () {
|
||||
const bootstrapToken = yield* getOrCreateBootstrapToken;
|
||||
const observabilitySettings = yield* readPersistedBackendObservabilitySettings.pipe(
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
|
||||
);
|
||||
return yield* resolveBackendStartConfig({
|
||||
bootstrapToken,
|
||||
observabilitySettings,
|
||||
}).pipe(
|
||||
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
|
||||
Effect.provideService(DesktopServerExposure.DesktopServerExposure, serverExposure),
|
||||
);
|
||||
}).pipe(Effect.withSpan("desktop.backendConfiguration.resolve")),
|
||||
});
|
||||
}),
|
||||
);
|
||||
return DesktopBackendConfiguration.of({
|
||||
resolve: Effect.gen(function* () {
|
||||
const bootstrapToken = yield* getOrCreateBootstrapToken;
|
||||
const observabilitySettings = yield* readPersistedBackendObservabilitySettings.pipe(
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
|
||||
);
|
||||
return yield* resolveBackendStartConfig({
|
||||
bootstrapToken,
|
||||
observabilitySettings,
|
||||
}).pipe(
|
||||
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
|
||||
Effect.provideService(DesktopServerExposure.DesktopServerExposure, serverExposure),
|
||||
);
|
||||
}).pipe(Effect.withSpan("desktop.backendConfiguration.resolve")),
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(DesktopBackendConfiguration, make);
|
||||
@@ -1,6 +1,5 @@
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
@@ -16,8 +15,9 @@ import * as Schema from "effect/Schema";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
import * as HttpClient from "effect/unstable/http/HttpClient";
|
||||
import * as ChildProcess from "effect/unstable/process/ChildProcess";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
|
||||
import {
|
||||
DesktopBackendBootstrap,
|
||||
@@ -59,29 +59,38 @@ interface BackendProcessExit {
|
||||
readonly result: Result.Result<ChildProcessSpawner.ExitCode, PlatformError.PlatformError>;
|
||||
}
|
||||
|
||||
export class BackendTimeoutError extends Data.TaggedError("BackendTimeoutError")<{
|
||||
readonly url: URL;
|
||||
}> {
|
||||
override get message() {
|
||||
export class BackendTimeoutError extends Schema.TaggedErrorClass<BackendTimeoutError>()(
|
||||
"BackendTimeoutError",
|
||||
{
|
||||
url: Schema.URL,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Timed out waiting for backend readiness at ${this.url.href}.`;
|
||||
}
|
||||
}
|
||||
|
||||
class BackendProcessBootstrapEncodeError extends Data.TaggedError(
|
||||
class BackendProcessBootstrapEncodeError extends Schema.TaggedErrorClass<BackendProcessBootstrapEncodeError>()(
|
||||
"BackendProcessBootstrapEncodeError",
|
||||
)<{
|
||||
readonly cause: Schema.SchemaError;
|
||||
}> {
|
||||
override get message() {
|
||||
return `Failed to encode desktop backend bootstrap payload: ${this.cause.message}`;
|
||||
{
|
||||
detail: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to encode desktop backend bootstrap payload: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
class BackendProcessSpawnError extends Data.TaggedError("BackendProcessSpawnError")<{
|
||||
readonly cause: PlatformError.PlatformError;
|
||||
}> {
|
||||
override get message() {
|
||||
return `Failed to spawn desktop backend process: ${this.cause.message}`;
|
||||
class BackendProcessSpawnError extends Schema.TaggedErrorClass<BackendProcessSpawnError>()(
|
||||
"BackendProcessSpawnError",
|
||||
{
|
||||
detail: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to spawn desktop backend process: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -106,16 +115,14 @@ export interface DesktopBackendSnapshot {
|
||||
readonly restartScheduled: boolean;
|
||||
}
|
||||
|
||||
export interface DesktopBackendManagerShape {
|
||||
readonly start: Effect.Effect<void>;
|
||||
readonly stop: (options?: { readonly timeout?: Duration.Duration }) => Effect.Effect<void>;
|
||||
readonly currentConfig: Effect.Effect<Option.Option<DesktopBackendStartConfig>>;
|
||||
readonly snapshot: Effect.Effect<DesktopBackendSnapshot>;
|
||||
}
|
||||
|
||||
export class DesktopBackendManager extends Context.Service<
|
||||
DesktopBackendManager,
|
||||
DesktopBackendManagerShape
|
||||
{
|
||||
readonly start: Effect.Effect<void>;
|
||||
readonly stop: (options?: { readonly timeout?: Duration.Duration }) => Effect.Effect<void>;
|
||||
readonly currentConfig: Effect.Effect<Option.Option<DesktopBackendStartConfig>>;
|
||||
readonly snapshot: Effect.Effect<DesktopBackendSnapshot>;
|
||||
}
|
||||
>()("@t3tools/desktop/backend/DesktopBackendManager") {}
|
||||
|
||||
const { logWarning: logBackendManagerWarning, logError: logBackendManagerError } =
|
||||
@@ -230,7 +237,13 @@ const runBackendProcess = Effect.fn("runBackendProcess")(function* (
|
||||
): Effect.fn.Return<BackendProcessExit, BackendProcessError, BackendProcessRunRequirements> {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const bootstrapJson = yield* encodeBootstrapJson(options.bootstrap).pipe(
|
||||
Effect.mapError((cause) => new BackendProcessBootstrapEncodeError({ cause })),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new BackendProcessBootstrapEncodeError({
|
||||
detail: cause.message,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const onOutput = options.onOutput ?? (() => Effect.void);
|
||||
const command = ChildProcess.make(
|
||||
@@ -256,9 +269,15 @@ const runBackendProcess = Effect.fn("runBackendProcess")(function* (
|
||||
},
|
||||
);
|
||||
|
||||
const handle = yield* spawner
|
||||
.spawn(command)
|
||||
.pipe(Effect.mapError((cause) => new BackendProcessSpawnError({ cause })));
|
||||
const handle = yield* spawner.spawn(command).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new BackendProcessSpawnError({
|
||||
detail: cause.message,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
yield* options.onStarted?.(handle.pid) ?? Effect.void;
|
||||
if (options.captureOutput) {
|
||||
@@ -277,7 +296,7 @@ const runBackendProcess = Effect.fn("runBackendProcess")(function* (
|
||||
return describeProcessExit(yield* Effect.result(handle.exitCode));
|
||||
});
|
||||
|
||||
const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(function* () {
|
||||
export const make = Effect.gen(function* () {
|
||||
const parentScope = yield* Scope.Scope;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
@@ -603,4 +622,4 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(DesktopBackendManager, makeDesktopBackendManager());
|
||||
export const layer = Layer.effect(DesktopBackendManager, make);
|
||||
@@ -3,7 +3,8 @@ 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 { HttpClient, HttpClientResponse } from "effect/unstable/http";
|
||||
import * as HttpClient from "effect/unstable/http/HttpClient";
|
||||
import * as HttpClientResponse from "effect/unstable/http/HttpClientResponse";
|
||||
|
||||
import * as DesktopBackendManager from "./DesktopBackendManager.ts";
|
||||
import * as DesktopLocalEnvironmentAuth from "./DesktopLocalEnvironmentAuth.ts";
|
||||
|
||||
@@ -1,77 +1,88 @@
|
||||
import { bootstrapRemoteBearerSession } from "@t3tools/client-runtime/authorization";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Data from "effect/Data";
|
||||
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 Schema from "effect/Schema";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import * as HttpClient from "effect/unstable/http/HttpClient";
|
||||
|
||||
import * as DesktopBackendManager from "./DesktopBackendManager.ts";
|
||||
|
||||
export interface DesktopLocalEnvironmentAuthShape {
|
||||
readonly getBearerToken: Effect.Effect<string, DesktopLocalEnvironmentAuthError>;
|
||||
export class DesktopLocalEnvironmentAuthBackendNotConfiguredError extends Schema.TaggedErrorClass<DesktopLocalEnvironmentAuthBackendNotConfiguredError>()(
|
||||
"DesktopLocalEnvironmentAuthBackendNotConfiguredError",
|
||||
{},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Local backend is not configured.";
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopLocalEnvironmentAuthError extends Data.TaggedError(
|
||||
"DesktopLocalEnvironmentAuthError",
|
||||
)<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
export class DesktopLocalEnvironmentAuthSessionBootstrapError extends Schema.TaggedErrorClass<DesktopLocalEnvironmentAuthSessionBootstrapError>()(
|
||||
"DesktopLocalEnvironmentAuthSessionBootstrapError",
|
||||
{ cause: Schema.Defect() },
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to create the local desktop bearer session.";
|
||||
}
|
||||
}
|
||||
|
||||
export const DesktopLocalEnvironmentAuthError = Schema.Union([
|
||||
DesktopLocalEnvironmentAuthBackendNotConfiguredError,
|
||||
DesktopLocalEnvironmentAuthSessionBootstrapError,
|
||||
]);
|
||||
export type DesktopLocalEnvironmentAuthError = typeof DesktopLocalEnvironmentAuthError.Type;
|
||||
|
||||
export class DesktopLocalEnvironmentAuth extends Context.Service<
|
||||
DesktopLocalEnvironmentAuth,
|
||||
DesktopLocalEnvironmentAuthShape
|
||||
{
|
||||
readonly getBearerToken: Effect.Effect<string, DesktopLocalEnvironmentAuthError>;
|
||||
}
|
||||
>()("@t3tools/desktop/backend/DesktopLocalEnvironmentAuth") {}
|
||||
|
||||
export const layer = Layer.effect(
|
||||
DesktopLocalEnvironmentAuth,
|
||||
Effect.gen(function* () {
|
||||
const backendManager = yield* DesktopBackendManager.DesktopBackendManager;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const tokenRef = yield* Ref.make(Option.none<string>());
|
||||
const mutex = yield* Semaphore.make(1);
|
||||
export const make = Effect.gen(function* () {
|
||||
const backendManager = yield* DesktopBackendManager.DesktopBackendManager;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const tokenRef = yield* Ref.make(Option.none<string>());
|
||||
const mutex = yield* Semaphore.make(1);
|
||||
|
||||
const getBearerToken = mutex
|
||||
.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
const cached = yield* Ref.get(tokenRef);
|
||||
if (Option.isSome(cached)) {
|
||||
return cached.value;
|
||||
}
|
||||
const getBearerToken = mutex
|
||||
.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
const cached = yield* Ref.get(tokenRef);
|
||||
if (Option.isSome(cached)) {
|
||||
return cached.value;
|
||||
}
|
||||
|
||||
const configOption = yield* backendManager.currentConfig;
|
||||
if (Option.isNone(configOption)) {
|
||||
return yield* new DesktopLocalEnvironmentAuthError({
|
||||
message: "Local backend is not configured.",
|
||||
});
|
||||
}
|
||||
const config = configOption.value;
|
||||
const session = yield* bootstrapRemoteBearerSession({
|
||||
httpBaseUrl: config.httpBaseUrl.href,
|
||||
credential: config.bootstrap.desktopBootstrapToken,
|
||||
clientMetadata: {
|
||||
label: "T3 Code Desktop",
|
||||
deviceType: "desktop",
|
||||
},
|
||||
}).pipe(
|
||||
Effect.provideService(HttpClient.HttpClient, httpClient),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopLocalEnvironmentAuthError({
|
||||
message: "Failed to create the local desktop bearer session.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* Ref.set(tokenRef, Option.some(session.access_token));
|
||||
return session.access_token;
|
||||
}),
|
||||
)
|
||||
.pipe(Effect.withSpan("desktop.localEnvironmentAuth.getBearerToken"));
|
||||
const configOption = yield* backendManager.currentConfig;
|
||||
if (Option.isNone(configOption)) {
|
||||
return yield* new DesktopLocalEnvironmentAuthBackendNotConfiguredError();
|
||||
}
|
||||
const config = configOption.value;
|
||||
const session = yield* bootstrapRemoteBearerSession({
|
||||
httpBaseUrl: config.httpBaseUrl.href,
|
||||
credential: config.bootstrap.desktopBootstrapToken,
|
||||
clientMetadata: {
|
||||
label: "T3 Code Desktop",
|
||||
deviceType: "desktop",
|
||||
},
|
||||
}).pipe(
|
||||
Effect.provideService(HttpClient.HttpClient, httpClient),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopLocalEnvironmentAuthSessionBootstrapError({
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* Ref.set(tokenRef, Option.some(session.access_token));
|
||||
return session.access_token;
|
||||
}),
|
||||
)
|
||||
.pipe(Effect.withSpan("desktop.localEnvironmentAuth.getBearerToken"));
|
||||
|
||||
return DesktopLocalEnvironmentAuth.of({ getBearerToken });
|
||||
}),
|
||||
);
|
||||
return DesktopLocalEnvironmentAuth.of({ getBearerToken });
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(DesktopLocalEnvironmentAuth, make);
|
||||
@@ -0,0 +1,33 @@
|
||||
import { networkInterfaces } from "node:os";
|
||||
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
|
||||
export interface DesktopNetworkInterfaceInfo {
|
||||
readonly address: string;
|
||||
readonly family: string | number;
|
||||
readonly internal: boolean;
|
||||
readonly netmask?: string;
|
||||
readonly mac?: string;
|
||||
readonly cidr?: string | null;
|
||||
readonly scopeid?: number;
|
||||
}
|
||||
|
||||
export type NetworkInterfaces = Readonly<
|
||||
Record<string, readonly DesktopNetworkInterfaceInfo[] | undefined>
|
||||
>;
|
||||
|
||||
export class DesktopNetworkInterfaces extends Context.Service<
|
||||
DesktopNetworkInterfaces,
|
||||
{
|
||||
readonly read: Effect.Effect<NetworkInterfaces>;
|
||||
}
|
||||
>()("@t3tools/desktop/backend/DesktopNetworkInterfaces") {}
|
||||
|
||||
export const make = (): DesktopNetworkInterfaces["Service"] =>
|
||||
DesktopNetworkInterfaces.of({
|
||||
read: Effect.sync(() => networkInterfaces()),
|
||||
});
|
||||
|
||||
export const layer = Layer.succeed(DesktopNetworkInterfaces, make());
|
||||
@@ -7,21 +7,18 @@ import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Sink from "effect/Sink";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
|
||||
import {
|
||||
DesktopEnvironment,
|
||||
layer as makeDesktopEnvironmentLayer,
|
||||
} from "../app/DesktopEnvironment.ts";
|
||||
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import * as DesktopConfig from "../app/DesktopConfig.ts";
|
||||
import * as DesktopNetworkInterfaces from "./DesktopNetworkInterfaces.ts";
|
||||
import * as DesktopServerExposure from "./DesktopServerExposure.ts";
|
||||
import type { DesktopNetworkInterfaces } from "./DesktopServerExposure.ts";
|
||||
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
|
||||
const emptyNetworkInterfaces: DesktopNetworkInterfaces = {};
|
||||
const lanNetworkInterfaces: DesktopNetworkInterfaces = {
|
||||
const emptyNetworkInterfaces: DesktopNetworkInterfaces.NetworkInterfaces = {};
|
||||
const lanNetworkInterfaces: DesktopNetworkInterfaces.NetworkInterfaces = {
|
||||
en0: [
|
||||
{
|
||||
address: "192.168.1.20",
|
||||
@@ -31,7 +28,7 @@ const lanNetworkInterfaces: DesktopNetworkInterfaces = {
|
||||
],
|
||||
};
|
||||
|
||||
const tailnetNetworkInterfaces: DesktopNetworkInterfaces = {
|
||||
const tailnetNetworkInterfaces: DesktopNetworkInterfaces.NetworkInterfaces = {
|
||||
tailscale0: [
|
||||
{
|
||||
address: "100.90.1.2",
|
||||
@@ -72,7 +69,7 @@ function dieOnSpawnLayer() {
|
||||
}
|
||||
|
||||
function makeEnvironmentLayer(baseDir: string, env: Record<string, string | undefined> = {}) {
|
||||
return makeDesktopEnvironmentLayer({
|
||||
return DesktopEnvironment.layer({
|
||||
dirname: "/repo/apps/desktop/src",
|
||||
homeDirectory: baseDir,
|
||||
platform: "darwin",
|
||||
@@ -91,13 +88,13 @@ function makeEnvironmentLayer(baseDir: string, env: Record<string, string | unde
|
||||
|
||||
function makeLayer(input: {
|
||||
readonly baseDir: string;
|
||||
readonly networkInterfaces?: DesktopNetworkInterfaces;
|
||||
readonly networkInterfaces?: DesktopNetworkInterfaces.NetworkInterfaces;
|
||||
readonly env?: Record<string, string | undefined>;
|
||||
readonly spawnerLayer?: Layer.Layer<ChildProcessSpawner.ChildProcessSpawner>;
|
||||
}) {
|
||||
const env = { T3CODE_HOME: input.baseDir, ...input.env };
|
||||
const environmentLayer = makeEnvironmentLayer(input.baseDir, env);
|
||||
const networkLayer = Layer.succeed(DesktopServerExposure.DesktopNetworkInterfacesService, {
|
||||
const networkLayer = Layer.succeed(DesktopNetworkInterfaces.DesktopNetworkInterfaces, {
|
||||
read: Effect.succeed(input.networkInterfaces ?? emptyNetworkInterfaces),
|
||||
});
|
||||
|
||||
@@ -113,12 +110,12 @@ function makeLayer(input: {
|
||||
}
|
||||
|
||||
const withHarness = <A, E, R>(
|
||||
networkInterfaces: DesktopNetworkInterfaces,
|
||||
networkInterfaces: DesktopNetworkInterfaces.NetworkInterfaces,
|
||||
effect: Effect.Effect<
|
||||
A,
|
||||
E,
|
||||
| R
|
||||
| DesktopEnvironment
|
||||
| DesktopEnvironment.DesktopEnvironment
|
||||
| FileSystem.FileSystem
|
||||
| DesktopServerExposure.DesktopServerExposure
|
||||
| DesktopAppSettings.DesktopAppSettings
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
import * as NodeOS from "node:os";
|
||||
|
||||
import {
|
||||
createAdvertisedEndpoint,
|
||||
type CreateAdvertisedEndpointInput,
|
||||
@@ -10,41 +8,27 @@ import type {
|
||||
DesktopServerExposureMode,
|
||||
DesktopServerExposureState,
|
||||
} from "@t3tools/contracts";
|
||||
import { readTailscaleStatus } from "@t3tools/tailscale";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Duration from "effect/Duration";
|
||||
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 { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as HttpClient from "effect/unstable/http/HttpClient";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
|
||||
import { DEFAULT_DESKTOP_SETTINGS, type DesktopSettings } from "../settings/DesktopAppSettings.ts";
|
||||
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
|
||||
import * as DesktopConfig from "../app/DesktopConfig.ts";
|
||||
import * as DesktopNetworkInterfaces from "./DesktopNetworkInterfaces.ts";
|
||||
import { resolveTailscaleAdvertisedEndpoints } from "./tailscaleEndpointProvider.ts";
|
||||
import { readTailscaleStatus } from "@t3tools/tailscale";
|
||||
import * as DesktopAppSettingsService from "../settings/DesktopAppSettings.ts";
|
||||
|
||||
const TAILSCALE_STATUS_CACHE_TTL = Duration.seconds(60);
|
||||
|
||||
export const DESKTOP_LOOPBACK_HOST = "127.0.0.1";
|
||||
const DESKTOP_LAN_BIND_HOST = "0.0.0.0";
|
||||
|
||||
export interface DesktopNetworkInterfaceInfo {
|
||||
readonly address: string;
|
||||
readonly family: string | number;
|
||||
readonly internal: boolean;
|
||||
readonly netmask?: string;
|
||||
readonly mac?: string;
|
||||
readonly cidr?: string | null;
|
||||
readonly scopeid?: number;
|
||||
}
|
||||
|
||||
export type DesktopNetworkInterfaces = Readonly<
|
||||
Record<string, readonly DesktopNetworkInterfaceInfo[] | undefined>
|
||||
>;
|
||||
|
||||
interface ResolvedDesktopServerExposure {
|
||||
readonly mode: DesktopServerExposureMode;
|
||||
readonly bindHost: string;
|
||||
@@ -91,7 +75,7 @@ const isHttpsEndpointUrl = (value: string): boolean => {
|
||||
};
|
||||
|
||||
const resolveLanAdvertisedHost = (
|
||||
networkInterfaces: DesktopNetworkInterfaces,
|
||||
networkInterfaces: DesktopNetworkInterfaces.NetworkInterfaces,
|
||||
explicitHost: string | undefined,
|
||||
): string | null => {
|
||||
const normalizedExplicitHost = normalizeOptionalHost(explicitHost);
|
||||
@@ -116,7 +100,7 @@ const resolveLanAdvertisedHost = (
|
||||
const resolveDesktopServerExposure = (input: {
|
||||
readonly mode: DesktopServerExposureMode;
|
||||
readonly port: number;
|
||||
readonly networkInterfaces: DesktopNetworkInterfaces;
|
||||
readonly networkInterfaces: DesktopNetworkInterfaces.NetworkInterfaces;
|
||||
readonly advertisedHostOverride?: string;
|
||||
}): ResolvedDesktopServerExposure => {
|
||||
const localHttpUrl = `http://${DESKTOP_LOOPBACK_HOST}:${input.port}`;
|
||||
@@ -218,25 +202,25 @@ const resolveDesktopCoreAdvertisedEndpoints = (
|
||||
return endpoints;
|
||||
};
|
||||
|
||||
type DesktopServerExposurePersistenceOperation = "server-exposure-mode" | "tailscale-serve";
|
||||
|
||||
export class DesktopServerExposureNoNetworkAddressError extends Data.TaggedError(
|
||||
export class DesktopServerExposureNoNetworkAddressError extends Schema.TaggedErrorClass<DesktopServerExposureNoNetworkAddressError>()(
|
||||
"DesktopServerExposureNoNetworkAddressError",
|
||||
)<{
|
||||
readonly port: number;
|
||||
}> {
|
||||
override get message() {
|
||||
{
|
||||
port: Schema.Number,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `No reachable network address is available for desktop network access on port ${this.port}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopServerExposurePersistenceError extends Data.TaggedError(
|
||||
export class DesktopServerExposurePersistenceError extends Schema.TaggedErrorClass<DesktopServerExposurePersistenceError>()(
|
||||
"DesktopServerExposurePersistenceError",
|
||||
)<{
|
||||
readonly operation: DesktopServerExposurePersistenceOperation;
|
||||
readonly cause: DesktopAppSettingsService.DesktopSettingsWriteError;
|
||||
}> {
|
||||
override get message() {
|
||||
{
|
||||
operation: Schema.Literals(["server-exposure-mode", "tailscale-serve"]),
|
||||
cause: Schema.instanceOf(DesktopAppSettings.DesktopSettingsWriteError),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to persist desktop ${this.operation} settings.`;
|
||||
}
|
||||
}
|
||||
@@ -260,36 +244,25 @@ export interface DesktopServerExposureChange {
|
||||
readonly requiresRelaunch: boolean;
|
||||
}
|
||||
|
||||
export interface DesktopServerExposureShape {
|
||||
readonly getState: Effect.Effect<DesktopServerExposureState>;
|
||||
readonly backendConfig: Effect.Effect<DesktopServerExposureBackendConfig>;
|
||||
readonly configureFromSettings: (input: {
|
||||
readonly port: number;
|
||||
}) => Effect.Effect<DesktopServerExposureState>;
|
||||
readonly setMode: (
|
||||
mode: DesktopServerExposureMode,
|
||||
) => Effect.Effect<DesktopServerExposureChange, DesktopServerExposureSetModeError>;
|
||||
readonly setTailscaleServeEnabled: (input: {
|
||||
readonly enabled: boolean;
|
||||
readonly port?: number;
|
||||
}) => Effect.Effect<DesktopServerExposureChange, DesktopServerExposurePersistenceError>;
|
||||
readonly getAdvertisedEndpoints: Effect.Effect<readonly AdvertisedEndpoint[]>;
|
||||
}
|
||||
|
||||
export class DesktopServerExposure extends Context.Service<
|
||||
DesktopServerExposure,
|
||||
DesktopServerExposureShape
|
||||
{
|
||||
readonly getState: Effect.Effect<DesktopServerExposureState>;
|
||||
readonly backendConfig: Effect.Effect<DesktopServerExposureBackendConfig>;
|
||||
readonly configureFromSettings: (input: {
|
||||
readonly port: number;
|
||||
}) => Effect.Effect<DesktopServerExposureState>;
|
||||
readonly setMode: (
|
||||
mode: DesktopServerExposureMode,
|
||||
) => Effect.Effect<DesktopServerExposureChange, DesktopServerExposureSetModeError>;
|
||||
readonly setTailscaleServeEnabled: (input: {
|
||||
readonly enabled: boolean;
|
||||
readonly port?: number;
|
||||
}) => Effect.Effect<DesktopServerExposureChange, DesktopServerExposurePersistenceError>;
|
||||
readonly getAdvertisedEndpoints: Effect.Effect<readonly AdvertisedEndpoint[]>;
|
||||
}
|
||||
>()("@t3tools/desktop/backend/DesktopServerExposure") {}
|
||||
|
||||
export interface DesktopNetworkInterfacesServiceShape {
|
||||
readonly read: Effect.Effect<DesktopNetworkInterfaces>;
|
||||
}
|
||||
|
||||
export class DesktopNetworkInterfacesService extends Context.Service<
|
||||
DesktopNetworkInterfacesService,
|
||||
DesktopNetworkInterfacesServiceShape
|
||||
>()("@t3tools/desktop/backend/DesktopServerExposure/DesktopNetworkInterfacesService") {}
|
||||
|
||||
interface RuntimeState {
|
||||
readonly requestedMode: DesktopServerExposureMode;
|
||||
readonly mode: DesktopServerExposureMode;
|
||||
@@ -311,10 +284,10 @@ interface ResolvedRuntimeState {
|
||||
|
||||
const initialRuntimeState = (): RuntimeState =>
|
||||
runtimeStateFromResolvedExposure({
|
||||
requestedMode: DEFAULT_DESKTOP_SETTINGS.serverExposureMode,
|
||||
settings: DEFAULT_DESKTOP_SETTINGS,
|
||||
requestedMode: DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS.serverExposureMode,
|
||||
settings: DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
|
||||
exposure: resolveDesktopServerExposure({
|
||||
mode: DEFAULT_DESKTOP_SETTINGS.serverExposureMode,
|
||||
mode: DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS.serverExposureMode,
|
||||
port: 0,
|
||||
networkInterfaces: {},
|
||||
}),
|
||||
@@ -348,7 +321,7 @@ const toResolvedExposure = (state: RuntimeState): ResolvedDesktopServerExposure
|
||||
|
||||
function runtimeStateFromResolvedExposure(input: {
|
||||
readonly requestedMode: DesktopServerExposureMode;
|
||||
readonly settings: DesktopSettings;
|
||||
readonly settings: DesktopAppSettings.DesktopSettings;
|
||||
readonly exposure: ResolvedDesktopServerExposure;
|
||||
readonly port: number;
|
||||
}): RuntimeState {
|
||||
@@ -369,9 +342,9 @@ function runtimeStateFromResolvedExposure(input: {
|
||||
|
||||
function resolveRuntimeState(input: {
|
||||
readonly requestedMode: DesktopServerExposureMode;
|
||||
readonly settings: DesktopSettings;
|
||||
readonly settings: DesktopAppSettings.DesktopSettings;
|
||||
readonly port: number;
|
||||
readonly networkInterfaces: DesktopNetworkInterfaces;
|
||||
readonly networkInterfaces: DesktopNetworkInterfaces.NetworkInterfaces;
|
||||
readonly advertisedHostOverride: Option.Option<string>;
|
||||
}): ResolvedRuntimeState {
|
||||
const advertisedHostOverride = Option.getOrUndefined(input.advertisedHostOverride);
|
||||
@@ -408,12 +381,12 @@ const requiresBackendRelaunch = (previous: RuntimeState, next: RuntimeState): bo
|
||||
previous.bindHost !== next.bindHost ||
|
||||
previous.localHttpUrl !== next.localHttpUrl;
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
export const make = Effect.gen(function* () {
|
||||
const config = yield* DesktopConfig.DesktopConfig;
|
||||
const networkInterfaces = yield* DesktopNetworkInterfacesService;
|
||||
const networkInterfaces = yield* DesktopNetworkInterfaces.DesktopNetworkInterfaces;
|
||||
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const desktopSettings = yield* DesktopAppSettingsService.DesktopAppSettings;
|
||||
const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
const stateRef = yield* Ref.make(initialRuntimeState());
|
||||
|
||||
// Cache the `tailscale status` spawn for the TTL. On macOS, the Mac App
|
||||
@@ -564,10 +537,3 @@ const make = Effect.gen(function* () {
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(DesktopServerExposure, make);
|
||||
|
||||
export const networkInterfacesLayer = Layer.succeed(
|
||||
DesktopNetworkInterfacesService,
|
||||
DesktopNetworkInterfacesService.of({
|
||||
read: Effect.sync(() => NodeOS.networkInterfaces()),
|
||||
}),
|
||||
);
|
||||
@@ -9,10 +9,10 @@ import {
|
||||
} from "@t3tools/tailscale";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import * as HttpClient from "effect/unstable/http/HttpClient";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
|
||||
import type { DesktopNetworkInterfaces } from "./DesktopServerExposure.ts";
|
||||
import type { NetworkInterfaces } from "./DesktopNetworkInterfaces.ts";
|
||||
|
||||
export { isTailscaleIpv4Address, parseTailscaleMagicDnsName } from "@t3tools/tailscale";
|
||||
|
||||
@@ -25,7 +25,7 @@ const TAILSCALE_ENDPOINT_PROVIDER: AdvertisedEndpointProvider = {
|
||||
|
||||
function resolveTailscaleIpAdvertisedEndpoints(input: {
|
||||
readonly port: number;
|
||||
readonly networkInterfaces: DesktopNetworkInterfaces;
|
||||
readonly networkInterfaces: NetworkInterfaces;
|
||||
}): readonly AdvertisedEndpoint[] {
|
||||
const seen = new Set<string>();
|
||||
const endpoints: AdvertisedEndpoint[] = [];
|
||||
@@ -103,7 +103,7 @@ export const resolveTailscaleAdvertisedEndpoints = Effect.fn("resolveTailscaleAd
|
||||
readonly port: number;
|
||||
readonly serveEnabled?: boolean;
|
||||
readonly servePort?: number;
|
||||
readonly networkInterfaces: DesktopNetworkInterfaces;
|
||||
readonly networkInterfaces: NetworkInterfaces;
|
||||
readonly statusJson?: string | null;
|
||||
readonly readMagicDnsName?: Effect.Effect<
|
||||
string | null,
|
||||
|
||||
@@ -96,7 +96,7 @@ const tabMethod = (
|
||||
channel: string,
|
||||
name: string,
|
||||
invoke: (
|
||||
manager: PreviewManager.PreviewManagerShape,
|
||||
manager: PreviewManager.PreviewManager["Service"],
|
||||
tabId: string,
|
||||
) => Effect.Effect<void, PreviewManager.PreviewManagerError>,
|
||||
) =>
|
||||
|
||||
@@ -33,8 +33,10 @@ import * as DesktopAssets from "./app/DesktopAssets.ts";
|
||||
import * as DesktopBackendConfiguration from "./backend/DesktopBackendConfiguration.ts";
|
||||
import * as DesktopBackendManager from "./backend/DesktopBackendManager.ts";
|
||||
import * as DesktopLocalEnvironmentAuth from "./backend/DesktopLocalEnvironmentAuth.ts";
|
||||
import * as DesktopNetworkInterfaces from "./backend/DesktopNetworkInterfaces.ts";
|
||||
import * as DesktopEnvironment from "./app/DesktopEnvironment.ts";
|
||||
import * as DesktopLifecycle from "./app/DesktopLifecycle.ts";
|
||||
import * as DesktopShutdown from "./app/DesktopShutdown.ts";
|
||||
import * as DesktopObservability from "./app/DesktopObservability.ts";
|
||||
import * as DesktopServerExposure from "./backend/DesktopServerExposure.ts";
|
||||
import * as DesktopClientSettings from "./settings/DesktopClientSettings.ts";
|
||||
@@ -45,7 +47,7 @@ import * as DesktopSshEnvironment from "./ssh/DesktopSshEnvironment.ts";
|
||||
import * as DesktopSshPasswordPrompts from "./ssh/DesktopSshPasswordPrompts.ts";
|
||||
import * as DesktopState from "./app/DesktopState.ts";
|
||||
import * as DesktopUpdates from "./updates/DesktopUpdates.ts";
|
||||
import * as PreviewBrowserSession from "./preview/BrowserSession.ts";
|
||||
import * as BrowserSession from "./preview/BrowserSession.ts";
|
||||
import * as PreviewManager from "./preview/Manager.ts";
|
||||
import * as DesktopWindow from "./window/DesktopWindow.ts";
|
||||
|
||||
@@ -114,7 +116,7 @@ const electronLayer = Layer.mergeAll(
|
||||
|
||||
const desktopFoundationLayer = Layer.mergeAll(
|
||||
DesktopState.layer,
|
||||
DesktopLifecycle.layerShutdown,
|
||||
DesktopShutdown.layer,
|
||||
DesktopAppSettings.layer,
|
||||
DesktopClientSettings.layer,
|
||||
DesktopConnectionCatalogStore.layer.pipe(Layer.provideMerge(DesktopSavedEnvironments.layer)),
|
||||
@@ -127,12 +129,12 @@ const desktopSshLayer = desktopSshEnvironmentLayer.pipe(
|
||||
);
|
||||
|
||||
const desktopServerExposureLayer = DesktopServerExposure.layer.pipe(
|
||||
Layer.provideMerge(DesktopServerExposure.networkInterfacesLayer),
|
||||
Layer.provideMerge(DesktopNetworkInterfaces.layer),
|
||||
Layer.provideMerge(desktopFoundationLayer),
|
||||
);
|
||||
|
||||
const desktopPreviewLayer = PreviewManager.layer.pipe(
|
||||
Layer.provideMerge(PreviewBrowserSession.layer),
|
||||
Layer.provideMerge(BrowserSession.layer),
|
||||
Layer.provideMerge(desktopFoundationLayer),
|
||||
);
|
||||
|
||||
|
||||
@@ -2,36 +2,38 @@ import type { Session } from "electron";
|
||||
import { session } from "electron";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Encoding from "effect/Encoding";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as SynchronizedRef from "effect/SynchronizedRef";
|
||||
|
||||
const PREVIEW_PARTITION_PREFIX = "persist:t3code-preview-";
|
||||
|
||||
export class BrowserSessionError extends Data.TaggedError("BrowserSessionError")<{
|
||||
readonly operation: string;
|
||||
readonly cause: unknown;
|
||||
}> {
|
||||
override get message() {
|
||||
export class BrowserSessionError extends Schema.TaggedErrorClass<BrowserSessionError>()(
|
||||
"BrowserSessionError",
|
||||
{
|
||||
operation: Schema.Literals(["getPartition", "getSession", "clearCookies", "clearCache"]),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Desktop preview browser session operation failed: ${this.operation}`;
|
||||
}
|
||||
}
|
||||
|
||||
export interface BrowserSessionShape {
|
||||
readonly getPartition: (scope?: string) => Effect.Effect<string, BrowserSessionError>;
|
||||
readonly isPartition: (partition: string) => boolean;
|
||||
readonly getSession: (scope?: string) => Effect.Effect<Session, BrowserSessionError>;
|
||||
readonly clearCookies: () => Effect.Effect<void, BrowserSessionError>;
|
||||
readonly clearCache: () => Effect.Effect<void, BrowserSessionError>;
|
||||
}
|
||||
export class BrowserSession extends Context.Service<
|
||||
BrowserSession,
|
||||
{
|
||||
readonly getPartition: (scope?: string) => Effect.Effect<string, BrowserSessionError>;
|
||||
readonly isPartition: (partition: string) => boolean;
|
||||
readonly getSession: (scope?: string) => Effect.Effect<Session, BrowserSessionError>;
|
||||
readonly clearCookies: () => Effect.Effect<void, BrowserSessionError>;
|
||||
readonly clearCache: () => Effect.Effect<void, BrowserSessionError>;
|
||||
}
|
||||
>()("@t3tools/desktop/preview/BrowserSession") {}
|
||||
|
||||
export class BrowserSession extends Context.Service<BrowserSession, BrowserSessionShape>()(
|
||||
"@t3tools/desktop/preview/BrowserSession",
|
||||
) {}
|
||||
|
||||
const make = Effect.gen(function* BrowserSessionMake() {
|
||||
export const make = Effect.gen(function* BrowserSessionMake() {
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const sessionsRef = yield* SynchronizedRef.make<ReadonlyMap<string, Session>>(new Map());
|
||||
|
||||
|
||||
+119
-116
@@ -37,7 +37,6 @@ import {
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Clock from "effect/Clock";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Data from "effect/Data";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
@@ -432,15 +431,17 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
) {
|
||||
const tabs = yield* SynchronizedRef.get(tabsRef);
|
||||
const tab = tabs.get(tabId);
|
||||
if (!tab) return yield* fail("requireWebContents", new PreviewTabNotFoundError(tabId));
|
||||
if (!tab) {
|
||||
return yield* fail("requireWebContents", new PreviewTabNotFoundError({ tabId }));
|
||||
}
|
||||
if (tab.webContentsId == null) {
|
||||
return yield* fail("requireWebContents", new PreviewWebviewNotInitializedError(tabId));
|
||||
return yield* fail("requireWebContents", new PreviewWebviewNotInitializedError({ tabId }));
|
||||
}
|
||||
const wc = webContents.fromId(tab.webContentsId);
|
||||
if (!wc) {
|
||||
return yield* fail(
|
||||
"requireWebContents",
|
||||
new PreviewWebContentsNotFoundError(tabId, tab.webContentsId),
|
||||
new PreviewWebContentsNotFoundError({ tabId, webContentsId: tab.webContentsId }),
|
||||
);
|
||||
}
|
||||
return wc;
|
||||
@@ -845,7 +846,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
});
|
||||
} else {
|
||||
const error = Option.getOrNull(Cause.findErrorOption(exit.cause));
|
||||
const underlying = error instanceof PreviewManagerError ? error.cause : error;
|
||||
const underlying = isPreviewManagerError(error) ? error.cause : error;
|
||||
const interrupted =
|
||||
underlying instanceof Error &&
|
||||
underlying.name === "PreviewAutomationControlInterruptedError";
|
||||
@@ -1161,7 +1162,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
) {
|
||||
const tab = (yield* SynchronizedRef.get(tabsRef)).get(tabId);
|
||||
if (!tab) {
|
||||
return yield* fail("registerWebview", new PreviewTabNotFoundError(tabId));
|
||||
return yield* fail("registerWebview", new PreviewTabNotFoundError({ tabId }));
|
||||
}
|
||||
const wc = webContents.fromId(webContentsId);
|
||||
const mainWindow = yield* Ref.get(mainWindowRef);
|
||||
@@ -1172,7 +1173,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
) {
|
||||
return yield* fail(
|
||||
"registerWebview",
|
||||
new PreviewWebContentsNotFoundError(tabId, webContentsId),
|
||||
new PreviewWebContentsNotFoundError({ tabId, webContentsId }),
|
||||
);
|
||||
}
|
||||
const attached = yield* Ref.get(attachedRef);
|
||||
@@ -1224,7 +1225,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
] as const;
|
||||
});
|
||||
if (Option.isNone(registration)) {
|
||||
return yield* fail("registerWebview", new PreviewTabNotFoundError(tabId));
|
||||
return yield* fail("registerWebview", new PreviewTabNotFoundError({ tabId }));
|
||||
}
|
||||
const { state: registered, pendingUrl } = registration.value;
|
||||
yield* emit(tabId, registered);
|
||||
@@ -2200,129 +2201,131 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
};
|
||||
});
|
||||
|
||||
export class PreviewTabNotFoundError extends Error {
|
||||
readonly tabId: string;
|
||||
constructor(tabId: string) {
|
||||
super(`Preview tab not found: ${tabId}`);
|
||||
this.name = "PreviewTabNotFoundError";
|
||||
this.tabId = tabId;
|
||||
export class PreviewTabNotFoundError extends Schema.TaggedErrorClass<PreviewTabNotFoundError>()(
|
||||
"PreviewTabNotFoundError",
|
||||
{ tabId: Schema.String },
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Preview tab not found: ${this.tabId}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class PreviewWebContentsNotFoundError extends Error {
|
||||
readonly tabId: string;
|
||||
readonly webContentsId: number;
|
||||
constructor(tabId: string, webContentsId: number) {
|
||||
super(`WebContents ${webContentsId} not found for preview tab ${tabId}`);
|
||||
this.name = "PreviewWebContentsNotFoundError";
|
||||
this.tabId = tabId;
|
||||
this.webContentsId = webContentsId;
|
||||
export class PreviewWebContentsNotFoundError extends Schema.TaggedErrorClass<PreviewWebContentsNotFoundError>()(
|
||||
"PreviewWebContentsNotFoundError",
|
||||
{ tabId: Schema.String, webContentsId: Schema.Number },
|
||||
) {
|
||||
override get message(): string {
|
||||
return `WebContents ${this.webContentsId} not found for preview tab ${this.tabId}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class PreviewWebviewNotInitializedError extends Error {
|
||||
readonly tabId: string;
|
||||
constructor(tabId: string) {
|
||||
super(`Preview tab "${tabId}" has no webview registered`);
|
||||
this.name = "PreviewWebviewNotInitializedError";
|
||||
this.tabId = tabId;
|
||||
export class PreviewWebviewNotInitializedError extends Schema.TaggedErrorClass<PreviewWebviewNotInitializedError>()(
|
||||
"PreviewWebviewNotInitializedError",
|
||||
{ tabId: Schema.String },
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Preview tab "${this.tabId}" has no webview registered`;
|
||||
}
|
||||
}
|
||||
|
||||
export class PreviewManagerError extends Data.TaggedError("PreviewManagerError")<{
|
||||
readonly operation: string;
|
||||
readonly cause: unknown;
|
||||
}> {
|
||||
override get message() {
|
||||
export class PreviewManagerError extends Schema.TaggedErrorClass<PreviewManagerError>()(
|
||||
"PreviewManagerError",
|
||||
{
|
||||
operation: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Desktop preview operation failed: ${this.operation}`;
|
||||
}
|
||||
}
|
||||
|
||||
export interface PreviewManagerShape {
|
||||
readonly setMainWindow: (window: BrowserWindow) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly getBrowserSession: (scope?: string) => Effect.Effect<Session, PreviewManagerError>;
|
||||
readonly isBrowserPartition: (partition: string) => boolean;
|
||||
readonly createTab: (tabId: string) => Effect.Effect<PreviewTabState, PreviewManagerError>;
|
||||
readonly closeTab: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly registerWebview: (
|
||||
tabId: string,
|
||||
webContentsId: number,
|
||||
) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly navigate: (tabId: string, url: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly goBack: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly goForward: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly refresh: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly zoomIn: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly zoomOut: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly resetZoom: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly hardReload: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly openDevTools: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly clearCookies: () => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly clearCache: () => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly getBrowserPartition: (scope?: string) => Effect.Effect<string, PreviewManagerError>;
|
||||
readonly setAnnotationTheme: (
|
||||
theme: DesktopPreviewAnnotationTheme,
|
||||
) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly pickElement: (
|
||||
tabId: string,
|
||||
) => Effect.Effect<PreviewAnnotationPayload | null, PreviewManagerError>;
|
||||
readonly cancelPickElement: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly captureScreenshot: (
|
||||
tabId: string,
|
||||
) => Effect.Effect<DesktopPreviewScreenshotArtifact, PreviewManagerError>;
|
||||
readonly revealArtifact: (path: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly copyArtifactToClipboard: (path: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly startRecording: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly stopRecording: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly saveRecording: (
|
||||
tabId: string,
|
||||
mimeType: string,
|
||||
data: Uint8Array,
|
||||
) => Effect.Effect<DesktopPreviewRecordingArtifact, PreviewManagerError>;
|
||||
readonly automationStatus: (
|
||||
tabId: string,
|
||||
) => Effect.Effect<PreviewAutomationStatus, PreviewManagerError>;
|
||||
readonly automationSnapshot: (
|
||||
tabId: string,
|
||||
) => Effect.Effect<PreviewAutomationSnapshot, PreviewManagerError>;
|
||||
readonly automationClick: (
|
||||
tabId: string,
|
||||
input: PreviewAutomationClickInput,
|
||||
) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly automationType: (
|
||||
tabId: string,
|
||||
input: PreviewAutomationTypeInput,
|
||||
) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly automationPress: (
|
||||
tabId: string,
|
||||
input: PreviewAutomationPressInput,
|
||||
) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly automationScroll: (
|
||||
tabId: string,
|
||||
input: PreviewAutomationScrollInput,
|
||||
) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly automationEvaluate: (
|
||||
tabId: string,
|
||||
input: PreviewAutomationEvaluateInput,
|
||||
) => Effect.Effect<unknown, PreviewManagerError>;
|
||||
readonly automationWaitFor: (
|
||||
tabId: string,
|
||||
input: PreviewAutomationWaitForInput,
|
||||
) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly subscribeStateChanges: (listener: Listener) => Effect.Effect<void, never, Scope.Scope>;
|
||||
readonly subscribePointerEvents: (
|
||||
listener: PointerEventListener,
|
||||
) => Effect.Effect<void, never, Scope.Scope>;
|
||||
readonly subscribeRecordingFrames: (
|
||||
listener: RecordingFrameListener,
|
||||
) => Effect.Effect<void, never, Scope.Scope>;
|
||||
}
|
||||
const isPreviewManagerError = Schema.is(PreviewManagerError);
|
||||
|
||||
export class PreviewManager extends Context.Service<PreviewManager, PreviewManagerShape>()(
|
||||
"@t3tools/desktop/preview/Manager/PreviewManager",
|
||||
) {}
|
||||
export class PreviewManager extends Context.Service<
|
||||
PreviewManager,
|
||||
{
|
||||
readonly setMainWindow: (window: BrowserWindow) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly getBrowserSession: (scope?: string) => Effect.Effect<Session, PreviewManagerError>;
|
||||
readonly isBrowserPartition: (partition: string) => boolean;
|
||||
readonly createTab: (tabId: string) => Effect.Effect<PreviewTabState, PreviewManagerError>;
|
||||
readonly closeTab: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly registerWebview: (
|
||||
tabId: string,
|
||||
webContentsId: number,
|
||||
) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly navigate: (tabId: string, url: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly goBack: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly goForward: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly refresh: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly zoomIn: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly zoomOut: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly resetZoom: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly hardReload: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly openDevTools: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly clearCookies: () => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly clearCache: () => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly getBrowserPartition: (scope?: string) => Effect.Effect<string, PreviewManagerError>;
|
||||
readonly setAnnotationTheme: (
|
||||
theme: DesktopPreviewAnnotationTheme,
|
||||
) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly pickElement: (
|
||||
tabId: string,
|
||||
) => Effect.Effect<PreviewAnnotationPayload | null, PreviewManagerError>;
|
||||
readonly cancelPickElement: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly captureScreenshot: (
|
||||
tabId: string,
|
||||
) => Effect.Effect<DesktopPreviewScreenshotArtifact, PreviewManagerError>;
|
||||
readonly revealArtifact: (path: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly copyArtifactToClipboard: (path: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly startRecording: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly stopRecording: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly saveRecording: (
|
||||
tabId: string,
|
||||
mimeType: string,
|
||||
data: Uint8Array,
|
||||
) => Effect.Effect<DesktopPreviewRecordingArtifact, PreviewManagerError>;
|
||||
readonly automationStatus: (
|
||||
tabId: string,
|
||||
) => Effect.Effect<PreviewAutomationStatus, PreviewManagerError>;
|
||||
readonly automationSnapshot: (
|
||||
tabId: string,
|
||||
) => Effect.Effect<PreviewAutomationSnapshot, PreviewManagerError>;
|
||||
readonly automationClick: (
|
||||
tabId: string,
|
||||
input: PreviewAutomationClickInput,
|
||||
) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly automationType: (
|
||||
tabId: string,
|
||||
input: PreviewAutomationTypeInput,
|
||||
) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly automationPress: (
|
||||
tabId: string,
|
||||
input: PreviewAutomationPressInput,
|
||||
) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly automationScroll: (
|
||||
tabId: string,
|
||||
input: PreviewAutomationScrollInput,
|
||||
) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly automationEvaluate: (
|
||||
tabId: string,
|
||||
input: PreviewAutomationEvaluateInput,
|
||||
) => Effect.Effect<unknown, PreviewManagerError>;
|
||||
readonly automationWaitFor: (
|
||||
tabId: string,
|
||||
input: PreviewAutomationWaitForInput,
|
||||
) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly subscribeStateChanges: (listener: Listener) => Effect.Effect<void, never, Scope.Scope>;
|
||||
readonly subscribePointerEvents: (
|
||||
listener: PointerEventListener,
|
||||
) => Effect.Effect<void, never, Scope.Scope>;
|
||||
readonly subscribeRecordingFrames: (
|
||||
listener: RecordingFrameListener,
|
||||
) => Effect.Effect<void, never, Scope.Scope>;
|
||||
}
|
||||
>()("@t3tools/desktop/preview/Manager/PreviewManager") {}
|
||||
|
||||
const make = Effect.gen(function* PreviewManagerMake() {
|
||||
export const make = Effect.gen(function* PreviewManagerMake() {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const browserSession = yield* BrowserSession.BrowserSession;
|
||||
const operations = yield* makeNativeOperations(environment.browserArtifactsDir);
|
||||
|
||||
@@ -8,11 +8,6 @@ import * as Schema from "effect/Schema";
|
||||
|
||||
import * as DesktopConfig from "../app/DesktopConfig.ts";
|
||||
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import {
|
||||
DEFAULT_DESKTOP_SETTINGS,
|
||||
resolveDefaultDesktopSettings,
|
||||
type DesktopSettings as DesktopSettingsValue,
|
||||
} from "./DesktopAppSettings.ts";
|
||||
import * as DesktopAppSettings from "./DesktopAppSettings.ts";
|
||||
|
||||
const DesktopSettingsPatch = Schema.Struct({
|
||||
@@ -82,20 +77,23 @@ describe("DesktopSettings", () => {
|
||||
withSettings(
|
||||
Effect.gen(function* () {
|
||||
const settings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
assert.deepEqual(yield* settings.load, DEFAULT_DESKTOP_SETTINGS);
|
||||
assert.deepEqual(yield* settings.get, DEFAULT_DESKTOP_SETTINGS);
|
||||
assert.deepEqual(yield* settings.load, DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS);
|
||||
assert.deepEqual(yield* settings.get, DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it("defaults packaged nightly builds to the nightly update channel", () => {
|
||||
assert.deepEqual(resolveDefaultDesktopSettings("0.0.17-nightly.20260415.1"), {
|
||||
serverExposureMode: "local-only",
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
updateChannel: "nightly",
|
||||
updateChannelConfiguredByUser: false,
|
||||
} satisfies DesktopSettingsValue);
|
||||
assert.deepEqual(
|
||||
DesktopAppSettings.resolveDefaultDesktopSettings("0.0.17-nightly.20260415.1"),
|
||||
{
|
||||
serverExposureMode: "local-only",
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
updateChannel: "nightly",
|
||||
updateChannelConfiguredByUser: false,
|
||||
} satisfies DesktopAppSettings.DesktopSettings,
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("loads persisted settings and applies semantic updates", () =>
|
||||
@@ -116,7 +114,7 @@ describe("DesktopSettings", () => {
|
||||
tailscaleServePort: 8443,
|
||||
updateChannel: "latest",
|
||||
updateChannelConfiguredByUser: true,
|
||||
} satisfies DesktopSettingsValue);
|
||||
} satisfies DesktopAppSettings.DesktopSettings);
|
||||
|
||||
const exposure = yield* settings.setServerExposureMode("local-only");
|
||||
assert.isTrue(exposure.changed);
|
||||
@@ -137,6 +135,27 @@ describe("DesktopSettings", () => {
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("reports the failed desktop settings write operation and path", () =>
|
||||
withSettings(
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const settings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
yield* fileSystem.makeDirectory(environment.desktopSettingsPath, { recursive: true });
|
||||
|
||||
const error = yield* settings.setServerExposureMode("network-accessible").pipe(Effect.flip);
|
||||
assert.instanceOf(error, DesktopAppSettings.DesktopSettingsWriteError);
|
||||
assert.equal(error.operation, "replace-settings-file");
|
||||
assert.equal(error.path, environment.desktopSettingsPath);
|
||||
assert.exists(error.cause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Desktop settings write failed during replace-settings-file at ${environment.desktopSettingsPath}.`,
|
||||
);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("does not persist no-op semantic updates", () =>
|
||||
withSettings(
|
||||
Effect.gen(function* () {
|
||||
@@ -167,7 +186,7 @@ describe("DesktopSettings", () => {
|
||||
yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
|
||||
yield* fileSystem.writeFileString(environment.desktopSettingsPath, "{not-json");
|
||||
|
||||
assert.deepEqual(yield* settings.load, DEFAULT_DESKTOP_SETTINGS);
|
||||
assert.deepEqual(yield* settings.load, DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS);
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -195,7 +214,7 @@ describe("DesktopSettings", () => {
|
||||
tailscaleServePort: 8443,
|
||||
updateChannel: "latest",
|
||||
updateChannelConfiguredByUser: false,
|
||||
} satisfies DesktopSettingsValue);
|
||||
} satisfies DesktopAppSettings.DesktopSettings);
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -234,7 +253,7 @@ describe("DesktopSettings", () => {
|
||||
tailscaleServePort: 443,
|
||||
updateChannel: "nightly",
|
||||
updateChannelConfiguredByUser: false,
|
||||
} satisfies DesktopSettingsValue);
|
||||
} satisfies DesktopAppSettings.DesktopSettings);
|
||||
}),
|
||||
{ appVersion: "0.0.17-nightly.20260415.1" },
|
||||
),
|
||||
@@ -256,7 +275,7 @@ describe("DesktopSettings", () => {
|
||||
tailscaleServePort: 443,
|
||||
updateChannel: "latest",
|
||||
updateChannelConfiguredByUser: true,
|
||||
} satisfies DesktopSettingsValue);
|
||||
} satisfies DesktopAppSettings.DesktopSettings);
|
||||
}),
|
||||
{ appVersion: "0.0.17-nightly.20260415.1" },
|
||||
),
|
||||
@@ -277,7 +296,7 @@ describe("DesktopSettings", () => {
|
||||
tailscaleServePort: 443,
|
||||
updateChannel: "latest",
|
||||
updateChannelConfiguredByUser: false,
|
||||
} satisfies DesktopSettingsValue);
|
||||
} satisfies DesktopAppSettings.DesktopSettings);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -7,13 +7,11 @@ import {
|
||||
import { fromLenientJson } from "@t3tools/shared/schemaJson";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as SynchronizedRef from "effect/SynchronizedRef";
|
||||
|
||||
@@ -63,32 +61,50 @@ const settingsChange = (settings: DesktopSettings, changed: boolean): DesktopSet
|
||||
changed,
|
||||
});
|
||||
|
||||
export class DesktopSettingsWriteError extends Data.TaggedError("DesktopSettingsWriteError")<{
|
||||
readonly cause: PlatformError.PlatformError | Schema.SchemaError;
|
||||
}> {
|
||||
override get message() {
|
||||
return `Failed to write desktop settings: ${this.cause.message}`;
|
||||
const DesktopSettingsWriteOperation = Schema.Literals([
|
||||
"create-temporary-file-name",
|
||||
"encode-document",
|
||||
"create-directory",
|
||||
"write-temporary-file",
|
||||
"replace-settings-file",
|
||||
]);
|
||||
type DesktopSettingsWriteOperation = typeof DesktopSettingsWriteOperation.Type;
|
||||
|
||||
export class DesktopSettingsWriteError extends Schema.TaggedErrorClass<DesktopSettingsWriteError>()(
|
||||
"DesktopSettingsWriteError",
|
||||
{
|
||||
operation: DesktopSettingsWriteOperation,
|
||||
path: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Desktop settings write failed during ${this.operation} at ${this.path}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export interface DesktopAppSettingsShape {
|
||||
readonly load: Effect.Effect<DesktopSettings>;
|
||||
readonly get: Effect.Effect<DesktopSettings>;
|
||||
readonly setServerExposureMode: (
|
||||
mode: DesktopServerExposureMode,
|
||||
) => Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError>;
|
||||
readonly setTailscaleServe: (input: {
|
||||
readonly enabled: boolean;
|
||||
readonly port: Option.Option<number>;
|
||||
}) => Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError>;
|
||||
readonly setUpdateChannel: (
|
||||
channel: DesktopUpdateChannel,
|
||||
) => Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError>;
|
||||
}
|
||||
const writeError = (
|
||||
operation: DesktopSettingsWriteOperation,
|
||||
path: string,
|
||||
cause: unknown,
|
||||
): DesktopSettingsWriteError => new DesktopSettingsWriteError({ operation, path, cause });
|
||||
|
||||
export class DesktopAppSettings extends Context.Service<
|
||||
DesktopAppSettings,
|
||||
DesktopAppSettingsShape
|
||||
{
|
||||
readonly load: Effect.Effect<DesktopSettings>;
|
||||
readonly get: Effect.Effect<DesktopSettings>;
|
||||
readonly setServerExposureMode: (
|
||||
mode: DesktopServerExposureMode,
|
||||
) => Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError>;
|
||||
readonly setTailscaleServe: (input: {
|
||||
readonly enabled: boolean;
|
||||
readonly port: Option.Option<number>;
|
||||
}) => Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError>;
|
||||
readonly setUpdateChannel: (
|
||||
channel: DesktopUpdateChannel,
|
||||
) => Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError>;
|
||||
}
|
||||
>()("@t3tools/desktop/settings/DesktopAppSettings") {}
|
||||
|
||||
export function resolveDefaultDesktopSettings(appVersion: string): DesktopSettings {
|
||||
@@ -223,77 +239,86 @@ const writeSettings = Effect.fn("desktop.settings.writeSettings")(function* (inp
|
||||
readonly settings: DesktopSettings;
|
||||
readonly defaultSettings: DesktopSettings;
|
||||
readonly suffix: string;
|
||||
}): Effect.fn.Return<void, PlatformError.PlatformError | Schema.SchemaError> {
|
||||
}): Effect.fn.Return<void, DesktopSettingsWriteError> {
|
||||
const directory = input.path.dirname(input.settingsPath);
|
||||
const tempPath = `${input.settingsPath}.${process.pid}.${input.suffix}.tmp`;
|
||||
const encoded = yield* encodeDesktopSettingsJson(
|
||||
toDesktopSettingsDocument(input.settings, input.defaultSettings),
|
||||
);
|
||||
yield* input.fileSystem.makeDirectory(directory, { recursive: true });
|
||||
yield* input.fileSystem.writeFileString(tempPath, `${encoded}\n`);
|
||||
yield* input.fileSystem.rename(tempPath, input.settingsPath);
|
||||
).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 layer = Layer.effect(
|
||||
DesktopAppSettings,
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const settingsRef = yield* SynchronizedRef.make(environment.defaultDesktopSettings);
|
||||
export const make = Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const settingsRef = yield* SynchronizedRef.make(environment.defaultDesktopSettings);
|
||||
|
||||
const persist = (
|
||||
update: (settings: DesktopSettings) => DesktopSettings,
|
||||
): Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError> =>
|
||||
SynchronizedRef.modifyEffect(settingsRef, (settings) => {
|
||||
const nextSettings = update(settings);
|
||||
if (nextSettings === settings) {
|
||||
return Effect.succeed([settingsChange(settings, false), settings] as const);
|
||||
}
|
||||
const persist = (
|
||||
update: (settings: DesktopSettings) => DesktopSettings,
|
||||
): Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError> =>
|
||||
SynchronizedRef.modifyEffect(settingsRef, (settings) => {
|
||||
const nextSettings = update(settings);
|
||||
if (nextSettings === settings) {
|
||||
return Effect.succeed([settingsChange(settings, false), settings] as const);
|
||||
}
|
||||
|
||||
return crypto.randomUUIDv4.pipe(
|
||||
Effect.map((uuid) => uuid.replace(/-/g, "")),
|
||||
Effect.flatMap((suffix) =>
|
||||
writeSettings({
|
||||
fileSystem,
|
||||
path,
|
||||
settingsPath: environment.desktopSettingsPath,
|
||||
settings: nextSettings,
|
||||
defaultSettings: environment.defaultDesktopSettings,
|
||||
suffix,
|
||||
}),
|
||||
),
|
||||
Effect.mapError((cause) => new DesktopSettingsWriteError({ cause })),
|
||||
Effect.as([settingsChange(nextSettings, true), nextSettings] as const),
|
||||
);
|
||||
});
|
||||
|
||||
return DesktopAppSettings.of({
|
||||
get: SynchronizedRef.get(settingsRef),
|
||||
load: Effect.gen(function* () {
|
||||
const settings = yield* readSettings(
|
||||
fileSystem,
|
||||
environment.desktopSettingsPath,
|
||||
environment.appVersion,
|
||||
);
|
||||
return yield* SynchronizedRef.setAndGet(settingsRef, settings);
|
||||
}).pipe(Effect.withSpan("desktop.settings.load")),
|
||||
setServerExposureMode: (mode) =>
|
||||
persist((settings) => setServerExposureMode(settings, mode)).pipe(
|
||||
Effect.withSpan("desktop.settings.setServerExposureMode", { attributes: { mode } }),
|
||||
return crypto.randomUUIDv4.pipe(
|
||||
Effect.map((uuid) => uuid.replace(/-/g, "")),
|
||||
Effect.mapError((cause) =>
|
||||
writeError("create-temporary-file-name", environment.desktopSettingsPath, cause),
|
||||
),
|
||||
setTailscaleServe: (input) =>
|
||||
persist((settings) => setTailscaleServe(settings, input)).pipe(
|
||||
Effect.withSpan("desktop.settings.setTailscaleServe", { attributes: input }),
|
||||
),
|
||||
setUpdateChannel: (channel) =>
|
||||
persist((settings) => setUpdateChannel(settings, channel)).pipe(
|
||||
Effect.withSpan("desktop.settings.setUpdateChannel", { attributes: { channel } }),
|
||||
Effect.flatMap((suffix) =>
|
||||
writeSettings({
|
||||
fileSystem,
|
||||
path,
|
||||
settingsPath: environment.desktopSettingsPath,
|
||||
settings: nextSettings,
|
||||
defaultSettings: environment.defaultDesktopSettings,
|
||||
suffix,
|
||||
}),
|
||||
),
|
||||
Effect.as([settingsChange(nextSettings, true), nextSettings] as const),
|
||||
);
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
return DesktopAppSettings.of({
|
||||
get: SynchronizedRef.get(settingsRef),
|
||||
load: Effect.gen(function* () {
|
||||
const settings = yield* readSettings(
|
||||
fileSystem,
|
||||
environment.desktopSettingsPath,
|
||||
environment.appVersion,
|
||||
);
|
||||
return yield* SynchronizedRef.setAndGet(settingsRef, settings);
|
||||
}).pipe(Effect.withSpan("desktop.settings.load")),
|
||||
setServerExposureMode: (mode) =>
|
||||
persist((settings) => setServerExposureMode(settings, mode)).pipe(
|
||||
Effect.withSpan("desktop.settings.setServerExposureMode", { attributes: { mode } }),
|
||||
),
|
||||
setTailscaleServe: (input) =>
|
||||
persist((settings) => setTailscaleServe(settings, input)).pipe(
|
||||
Effect.withSpan("desktop.settings.setTailscaleServe", { attributes: input }),
|
||||
),
|
||||
setUpdateChannel: (channel) =>
|
||||
persist((settings) => setUpdateChannel(settings, channel)).pipe(
|
||||
Effect.withSpan("desktop.settings.setUpdateChannel", { attributes: { channel } }),
|
||||
),
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(DesktopAppSettings, make);
|
||||
|
||||
export const layerTest = (initialSettings: DesktopSettings = DEFAULT_DESKTOP_SETTINGS) =>
|
||||
Layer.effect(
|
||||
|
||||
@@ -34,7 +34,6 @@ const decodeClientSettingsJson = Schema.decodeEffect(Schema.fromJsonString(Clien
|
||||
const decodeRecordJson = Schema.decodeEffect(
|
||||
Schema.fromJsonString(Schema.Record(Schema.String, Schema.Unknown)),
|
||||
);
|
||||
|
||||
function makeLayer(baseDir: string) {
|
||||
const environmentLayer = DesktopEnvironment.layer({
|
||||
dirname: "/repo/apps/desktop/src",
|
||||
@@ -106,6 +105,27 @@ describe("DesktopClientSettings", () => {
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("reports the failed client settings write operation and path", () =>
|
||||
withClientSettings(
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const settings = yield* DesktopClientSettings.DesktopClientSettings;
|
||||
yield* fileSystem.makeDirectory(environment.clientSettingsPath, { recursive: true });
|
||||
|
||||
const error = yield* settings.set(clientSettings).pipe(Effect.flip);
|
||||
assert.instanceOf(error, DesktopClientSettings.DesktopClientSettingsWriteError);
|
||||
assert.equal(error.operation, "replace-settings-file");
|
||||
assert.equal(error.path, environment.clientSettingsPath);
|
||||
assert.exists(error.cause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Desktop client settings write failed during replace-settings-file at ${environment.clientSettingsPath}.`,
|
||||
);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("loads lenient direct client settings documents", () =>
|
||||
withClientSettings(
|
||||
Effect.gen(function* () {
|
||||
|
||||
@@ -2,13 +2,11 @@ import { ClientSettingsSchema, type ClientSettings } from "@t3tools/contracts";
|
||||
import { fromLenientJson } from "@t3tools/shared/schemaJson";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Ref from "effect/Ref";
|
||||
|
||||
@@ -31,24 +29,43 @@ const decodeClientSettingsJson = (raw: string): Effect.Effect<ClientSettings, Sc
|
||||
);
|
||||
const encodeClientSettingsJson = Schema.encodeEffect(ClientSettingsJson);
|
||||
|
||||
export class DesktopClientSettingsWriteError extends Data.TaggedError(
|
||||
const DesktopClientSettingsWriteOperation = Schema.Literals([
|
||||
"create-temporary-file-name",
|
||||
"encode-document",
|
||||
"create-directory",
|
||||
"write-temporary-file",
|
||||
"replace-settings-file",
|
||||
]);
|
||||
type DesktopClientSettingsWriteOperation = typeof DesktopClientSettingsWriteOperation.Type;
|
||||
|
||||
export class DesktopClientSettingsWriteError extends Schema.TaggedErrorClass<DesktopClientSettingsWriteError>()(
|
||||
"DesktopClientSettingsWriteError",
|
||||
)<{
|
||||
readonly cause: PlatformError.PlatformError | Schema.SchemaError;
|
||||
}> {
|
||||
override get message() {
|
||||
return `Failed to write desktop client settings: ${this.cause.message}`;
|
||||
{
|
||||
operation: DesktopClientSettingsWriteOperation,
|
||||
path: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Desktop client settings write failed during ${this.operation} at ${this.path}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export interface DesktopClientSettingsShape {
|
||||
readonly get: Effect.Effect<Option.Option<ClientSettings>>;
|
||||
readonly set: (settings: ClientSettings) => Effect.Effect<void, DesktopClientSettingsWriteError>;
|
||||
}
|
||||
const writeError = (
|
||||
operation: DesktopClientSettingsWriteOperation,
|
||||
path: string,
|
||||
cause: unknown,
|
||||
): DesktopClientSettingsWriteError =>
|
||||
new DesktopClientSettingsWriteError({ operation, path, cause });
|
||||
|
||||
export class DesktopClientSettings extends Context.Service<
|
||||
DesktopClientSettings,
|
||||
DesktopClientSettingsShape
|
||||
{
|
||||
readonly get: Effect.Effect<Option.Option<ClientSettings>>;
|
||||
readonly set: (
|
||||
settings: ClientSettings,
|
||||
) => Effect.Effect<void, DesktopClientSettingsWriteError>;
|
||||
}
|
||||
>()("@t3tools/desktop/settings/DesktopClientSettings") {}
|
||||
|
||||
const readClientSettings = (
|
||||
@@ -75,45 +92,56 @@ const writeClientSettings = Effect.fnUntraced(function* (input: {
|
||||
readonly settingsPath: string;
|
||||
readonly settings: ClientSettings;
|
||||
readonly suffix: string;
|
||||
}): Effect.fn.Return<void, PlatformError.PlatformError | Schema.SchemaError> {
|
||||
}): Effect.fn.Return<void, DesktopClientSettingsWriteError> {
|
||||
const directory = input.path.dirname(input.settingsPath);
|
||||
const tempPath = `${input.settingsPath}.${process.pid}.${input.suffix}.tmp`;
|
||||
const encoded = yield* encodeClientSettingsJson(input.settings);
|
||||
yield* input.fileSystem.makeDirectory(directory, { recursive: true });
|
||||
yield* input.fileSystem.writeFileString(tempPath, `${encoded}\n`);
|
||||
yield* input.fileSystem.rename(tempPath, input.settingsPath);
|
||||
const encoded = yield* encodeClientSettingsJson(input.settings).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 layer = Layer.effect(
|
||||
DesktopClientSettings,
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
export const make = Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
|
||||
return DesktopClientSettings.of({
|
||||
get: readClientSettings(fileSystem, environment.clientSettingsPath).pipe(
|
||||
Effect.withSpan("desktop.clientSettings.get"),
|
||||
),
|
||||
set: (settings) =>
|
||||
crypto.randomUUIDv4.pipe(
|
||||
Effect.map((uuid) => uuid.replace(/-/g, "")),
|
||||
Effect.flatMap((suffix) =>
|
||||
writeClientSettings({
|
||||
fileSystem,
|
||||
path,
|
||||
settingsPath: environment.clientSettingsPath,
|
||||
settings,
|
||||
suffix,
|
||||
}),
|
||||
),
|
||||
Effect.mapError((cause) => new DesktopClientSettingsWriteError({ cause })),
|
||||
Effect.withSpan("desktop.clientSettings.set"),
|
||||
return DesktopClientSettings.of({
|
||||
get: readClientSettings(fileSystem, environment.clientSettingsPath).pipe(
|
||||
Effect.withSpan("desktop.clientSettings.get"),
|
||||
),
|
||||
set: (settings) =>
|
||||
crypto.randomUUIDv4.pipe(
|
||||
Effect.map((uuid) => uuid.replace(/-/g, "")),
|
||||
Effect.mapError((cause) =>
|
||||
writeError("create-temporary-file-name", environment.clientSettingsPath, cause),
|
||||
),
|
||||
});
|
||||
}),
|
||||
);
|
||||
Effect.flatMap((suffix) =>
|
||||
writeClientSettings({
|
||||
fileSystem,
|
||||
path,
|
||||
settingsPath: environment.clientSettingsPath,
|
||||
settings,
|
||||
suffix,
|
||||
}),
|
||||
),
|
||||
Effect.withSpan("desktop.clientSettings.set"),
|
||||
),
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(DesktopClientSettings, make);
|
||||
|
||||
export const layerTest = (initialSettings: Option.Option<ClientSettings> = Option.none()) =>
|
||||
Layer.effect(
|
||||
|
||||
@@ -5,6 +5,7 @@ import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as DesktopConfig from "../app/DesktopConfig.ts";
|
||||
@@ -34,10 +35,15 @@ const SavedEnvironmentRegistryDocumentProbe = Schema.Struct({
|
||||
version: Schema.Number,
|
||||
records: Schema.Array(Schema.Unknown),
|
||||
});
|
||||
const decodeSavedEnvironmentRegistryDocumentProbe = Schema.decodeEffect(
|
||||
Schema.fromJsonString(SavedEnvironmentRegistryDocumentProbe),
|
||||
const SavedEnvironmentRegistryDocumentProbeJson = Schema.fromJsonString(
|
||||
SavedEnvironmentRegistryDocumentProbe,
|
||||
);
|
||||
const decodeSavedEnvironmentRegistryDocumentProbe = Schema.decodeEffect(
|
||||
SavedEnvironmentRegistryDocumentProbeJson,
|
||||
);
|
||||
const encodeSavedEnvironmentRegistryDocumentProbe = Schema.encodeEffect(
|
||||
SavedEnvironmentRegistryDocumentProbeJson,
|
||||
);
|
||||
|
||||
function makeSafeStorageLayer(input: {
|
||||
readonly available: boolean;
|
||||
readonly availabilityError?: unknown;
|
||||
@@ -80,7 +86,7 @@ function makeSafeStorageLayer(input: {
|
||||
}
|
||||
return Effect.succeed(decoded.slice("enc:".length));
|
||||
},
|
||||
} satisfies ElectronSafeStorage.ElectronSafeStorageShape);
|
||||
} satisfies ElectronSafeStorage.ElectronSafeStorage["Service"]);
|
||||
}
|
||||
|
||||
function makeLayer(
|
||||
@@ -91,6 +97,7 @@ function makeLayer(
|
||||
readonly encryptError?: unknown;
|
||||
readonly decryptError?: unknown;
|
||||
},
|
||||
fileSystemLayer: Layer.Layer<FileSystem.FileSystem> = NodeServices.layer,
|
||||
) {
|
||||
const environmentLayer = DesktopEnvironment.layer({
|
||||
dirname: "/repo/apps/desktop/src",
|
||||
@@ -108,18 +115,20 @@ function makeLayer(
|
||||
),
|
||||
);
|
||||
|
||||
return DesktopSavedEnvironments.layer.pipe(
|
||||
Layer.provideMerge(environmentLayer),
|
||||
Layer.provideMerge(
|
||||
makeSafeStorageLayer({
|
||||
available: options?.availableSecretStorage ?? true,
|
||||
availabilityError: options?.availabilityError,
|
||||
encryptError: options?.encryptError,
|
||||
decryptError: options?.decryptError,
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
const safeStorageLayer = makeSafeStorageLayer({
|
||||
available: options?.availableSecretStorage ?? true,
|
||||
availabilityError: options?.availabilityError,
|
||||
encryptError: options?.encryptError,
|
||||
decryptError: options?.decryptError,
|
||||
});
|
||||
const dependencies = Layer.mergeAll(
|
||||
environmentLayer,
|
||||
safeStorageLayer,
|
||||
NodeServices.layer,
|
||||
fileSystemLayer,
|
||||
);
|
||||
|
||||
return DesktopSavedEnvironments.layer.pipe(Layer.provideMerge(dependencies));
|
||||
}
|
||||
|
||||
const withSavedEnvironments = <A, E, R>(
|
||||
@@ -215,6 +224,37 @@ describe("DesktopSavedEnvironments", () => {
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("reports invalid saved secret encoding without exposing the secret", () =>
|
||||
withSavedEnvironments(
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
|
||||
yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
|
||||
const encoded = yield* encodeSavedEnvironmentRegistryDocumentProbe({
|
||||
version: 1,
|
||||
records: [{ ...savedRegistryRecord, encryptedBearerToken: "%%%" }],
|
||||
});
|
||||
yield* fileSystem.writeFileString(environment.savedEnvironmentRegistryPath, `${encoded}\n`);
|
||||
|
||||
const error = yield* savedEnvironments
|
||||
.getSecret(savedRegistryRecord.environmentId)
|
||||
.pipe(Effect.flip);
|
||||
assert.instanceOf(error, DesktopSavedEnvironments.DesktopSavedEnvironmentSecretDecodeError);
|
||||
assert.equal(error.operation, "decode-secret");
|
||||
assert.equal(error.environmentId, savedRegistryRecord.environmentId);
|
||||
assert.equal(error.registryPath, environment.savedEnvironmentRegistryPath);
|
||||
assert.equal(error.field, "encryptedBearerToken");
|
||||
assert.exists(error.cause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Failed to decode encryptedBearerToken for environment ${savedRegistryRecord.environmentId} at ${environment.savedEnvironmentRegistryPath}.`,
|
||||
);
|
||||
assert.notInclude(error.message, "%%%");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("returns false when writing secrets while encryption is unavailable", () =>
|
||||
withSavedEnvironments(
|
||||
Effect.gen(function* () {
|
||||
@@ -321,16 +361,98 @@ describe("DesktopSavedEnvironments", () => {
|
||||
const registryError = yield* savedEnvironments.getRegistry.pipe(Effect.flip);
|
||||
assert.instanceOf(
|
||||
registryError,
|
||||
DesktopSavedEnvironments.DesktopSavedEnvironmentsReadError,
|
||||
DesktopSavedEnvironments.DesktopSavedEnvironmentsDocumentDecodeError,
|
||||
);
|
||||
assert.equal(registryError.operation, "decode-registry");
|
||||
assert.equal(registryError.registryPath, environment.savedEnvironmentRegistryPath);
|
||||
assert.exists(registryError.cause);
|
||||
const secretError = yield* savedEnvironments
|
||||
.getSecret(savedRegistryRecord.environmentId)
|
||||
.pipe(Effect.flip);
|
||||
assert.instanceOf(secretError, DesktopSavedEnvironments.DesktopSavedEnvironmentsReadError);
|
||||
assert.instanceOf(
|
||||
secretError,
|
||||
DesktopSavedEnvironments.DesktopSavedEnvironmentsDocumentDecodeError,
|
||||
);
|
||||
const mutationError = yield* savedEnvironments
|
||||
.setRegistry([savedRegistryRecord])
|
||||
.pipe(Effect.flip);
|
||||
assert.instanceOf(
|
||||
mutationError,
|
||||
DesktopSavedEnvironments.DesktopSavedEnvironmentsDocumentDecodeError,
|
||||
);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("reports saved environment filesystem reads separately from document decoding", () =>
|
||||
Effect.gen(function* () {
|
||||
const baseFileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* baseFileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-saved-environments-test-",
|
||||
});
|
||||
const registryPath = `${baseDir}/userdata/saved-environments.json`;
|
||||
const permissionError = PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "readFileString",
|
||||
pathOrDescriptor: registryPath,
|
||||
});
|
||||
const fileSystemLayer = Layer.succeed(
|
||||
FileSystem.FileSystem,
|
||||
FileSystem.makeNoop({
|
||||
readFileString: () => Effect.fail(permissionError),
|
||||
}),
|
||||
);
|
||||
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments.pipe(
|
||||
Effect.provide(makeLayer(baseDir, undefined, fileSystemLayer)),
|
||||
);
|
||||
|
||||
const error = yield* savedEnvironments.getRegistry.pipe(Effect.flip);
|
||||
assert.instanceOf(error, DesktopSavedEnvironments.DesktopSavedEnvironmentsReadError);
|
||||
assert.equal(error.operation, "read-registry");
|
||||
assert.equal(error.registryPath, registryPath);
|
||||
assert.strictEqual(error.cause, permissionError);
|
||||
assert.equal(error.message, `Failed to read desktop saved environments at ${registryPath}.`);
|
||||
assert.notEqual(error.message, permissionError.message);
|
||||
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
|
||||
);
|
||||
|
||||
it.effect("reports the failed saved environment write operation and path", () =>
|
||||
Effect.gen(function* () {
|
||||
const baseFileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* baseFileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-saved-environments-test-",
|
||||
});
|
||||
const permissionError = PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "makeDirectory",
|
||||
pathOrDescriptor: `${baseDir}/userdata`,
|
||||
});
|
||||
const fileSystemLayer = Layer.succeed(
|
||||
FileSystem.FileSystem,
|
||||
FileSystem.makeNoop({
|
||||
readFileString: baseFileSystem.readFileString,
|
||||
makeDirectory: () => Effect.fail(permissionError),
|
||||
}),
|
||||
);
|
||||
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments.pipe(
|
||||
Effect.provide(makeLayer(baseDir, undefined, fileSystemLayer)),
|
||||
);
|
||||
|
||||
const error = yield* savedEnvironments.setRegistry([savedRegistryRecord]).pipe(Effect.flip);
|
||||
assert.instanceOf(error, DesktopSavedEnvironments.DesktopSavedEnvironmentsWriteError);
|
||||
assert.equal(error.operation, "create-directory");
|
||||
assert.equal(error.path, `${baseDir}/userdata`);
|
||||
assert.strictEqual(error.cause, permissionError);
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Desktop saved-environment write failed during create-directory at ${baseDir}/userdata.`,
|
||||
);
|
||||
assert.notEqual(error.message, permissionError.message);
|
||||
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
|
||||
);
|
||||
|
||||
it.effect("returns false when writing a secret without metadata", () =>
|
||||
withSavedEnvironments(
|
||||
Effect.gen(function* () {
|
||||
|
||||
@@ -2,14 +2,12 @@ import { EnvironmentId, type PersistedSavedEnvironmentRecord } from "@t3tools/co
|
||||
import { fromLenientJson } from "@t3tools/shared/schemaJson";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Encoding from "effect/Encoding";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
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 * as Ref from "effect/Ref";
|
||||
|
||||
@@ -72,73 +70,123 @@ const encodeSavedEnvironmentRegistryDocumentJson = Schema.encodeEffect(
|
||||
SavedEnvironmentRegistryDocumentJson,
|
||||
);
|
||||
|
||||
export class DesktopSavedEnvironmentsWriteError extends Data.TaggedError(
|
||||
const DesktopSavedEnvironmentsWriteOperation = Schema.Literals([
|
||||
"create-temporary-file-name",
|
||||
"encode-registry",
|
||||
"create-directory",
|
||||
"write-temporary-file",
|
||||
"replace-registry-file",
|
||||
]);
|
||||
type DesktopSavedEnvironmentsWriteOperation = typeof DesktopSavedEnvironmentsWriteOperation.Type;
|
||||
|
||||
export class DesktopSavedEnvironmentsWriteError extends Schema.TaggedErrorClass<DesktopSavedEnvironmentsWriteError>()(
|
||||
"DesktopSavedEnvironmentsWriteError",
|
||||
)<{
|
||||
readonly cause: PlatformError.PlatformError | Schema.SchemaError;
|
||||
}> {
|
||||
override get message() {
|
||||
return `Failed to write desktop saved environments: ${this.cause.message}`;
|
||||
{
|
||||
operation: DesktopSavedEnvironmentsWriteOperation,
|
||||
path: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Desktop saved-environment write failed during ${this.operation} at ${this.path}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopSavedEnvironmentsReadError extends Data.TaggedError(
|
||||
const writeError = (
|
||||
operation: DesktopSavedEnvironmentsWriteOperation,
|
||||
path: string,
|
||||
cause: unknown,
|
||||
): DesktopSavedEnvironmentsWriteError =>
|
||||
new DesktopSavedEnvironmentsWriteError({
|
||||
operation,
|
||||
path,
|
||||
cause,
|
||||
});
|
||||
|
||||
export class DesktopSavedEnvironmentsReadError extends Schema.TaggedErrorClass<DesktopSavedEnvironmentsReadError>()(
|
||||
"DesktopSavedEnvironmentsReadError",
|
||||
)<{
|
||||
readonly cause: PlatformError.PlatformError | Schema.SchemaError;
|
||||
}> {
|
||||
override get message() {
|
||||
return `Failed to read desktop saved environments: ${this.cause.message}`;
|
||||
{
|
||||
operation: Schema.Literal("read-registry"),
|
||||
registryPath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to read desktop saved environments at ${this.registryPath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopSavedEnvironmentSecretDecodeError extends Data.TaggedError(
|
||||
"DesktopSavedEnvironmentSecretDecodeError",
|
||||
)<{
|
||||
readonly cause: Encoding.EncodingError;
|
||||
}> {
|
||||
override get message() {
|
||||
return "Failed to decode desktop saved environment secret.";
|
||||
export class DesktopSavedEnvironmentsDocumentDecodeError extends Schema.TaggedErrorClass<DesktopSavedEnvironmentsDocumentDecodeError>()(
|
||||
"DesktopSavedEnvironmentsDocumentDecodeError",
|
||||
{
|
||||
operation: Schema.Literal("decode-registry"),
|
||||
registryPath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to decode desktop saved environments at ${this.registryPath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopSavedEnvironmentSecretDecodeError extends Schema.TaggedErrorClass<DesktopSavedEnvironmentSecretDecodeError>()(
|
||||
"DesktopSavedEnvironmentSecretDecodeError",
|
||||
{
|
||||
operation: Schema.Literal("decode-secret"),
|
||||
environmentId: Schema.String,
|
||||
registryPath: Schema.String,
|
||||
field: Schema.Literal("encryptedBearerToken"),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to decode ${this.field} for environment ${this.environmentId} at ${this.registryPath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export type DesktopSavedEnvironmentsReadRegistryError =
|
||||
| DesktopSavedEnvironmentsReadError
|
||||
| DesktopSavedEnvironmentsDocumentDecodeError;
|
||||
|
||||
export type DesktopSavedEnvironmentsMutationError =
|
||||
| DesktopSavedEnvironmentsReadRegistryError
|
||||
| DesktopSavedEnvironmentsWriteError;
|
||||
|
||||
export type DesktopSavedEnvironmentsGetSecretError =
|
||||
| DesktopSavedEnvironmentsReadError
|
||||
| DesktopSavedEnvironmentsReadRegistryError
|
||||
| DesktopSavedEnvironmentSecretDecodeError
|
||||
| ElectronSafeStorage.ElectronSafeStorageAvailabilityError
|
||||
| ElectronSafeStorage.ElectronSafeStorageDecryptError;
|
||||
|
||||
export type DesktopSavedEnvironmentsSetSecretError =
|
||||
| DesktopSavedEnvironmentsWriteError
|
||||
| DesktopSavedEnvironmentsMutationError
|
||||
| ElectronSafeStorage.ElectronSafeStorageAvailabilityError
|
||||
| ElectronSafeStorage.ElectronSafeStorageEncryptError;
|
||||
|
||||
export interface DesktopSavedEnvironmentsShape {
|
||||
readonly getRegistry: Effect.Effect<
|
||||
readonly PersistedSavedEnvironmentRecord[],
|
||||
DesktopSavedEnvironmentsReadError
|
||||
>;
|
||||
readonly setRegistry: (
|
||||
records: readonly PersistedSavedEnvironmentRecord[],
|
||||
) => Effect.Effect<void, DesktopSavedEnvironmentsWriteError>;
|
||||
readonly removeEnvironment: (
|
||||
environmentId: string,
|
||||
) => Effect.Effect<void, DesktopSavedEnvironmentsWriteError>;
|
||||
readonly getSecret: (
|
||||
environmentId: string,
|
||||
) => Effect.Effect<Option.Option<string>, DesktopSavedEnvironmentsGetSecretError>;
|
||||
readonly setSecret: (input: {
|
||||
readonly environmentId: string;
|
||||
readonly secret: string;
|
||||
}) => Effect.Effect<boolean, DesktopSavedEnvironmentsSetSecretError>;
|
||||
readonly removeSecret: (
|
||||
environmentId: string,
|
||||
) => Effect.Effect<void, DesktopSavedEnvironmentsWriteError>;
|
||||
}
|
||||
|
||||
export class DesktopSavedEnvironments extends Context.Service<
|
||||
DesktopSavedEnvironments,
|
||||
DesktopSavedEnvironmentsShape
|
||||
{
|
||||
readonly getRegistry: Effect.Effect<
|
||||
readonly PersistedSavedEnvironmentRecord[],
|
||||
DesktopSavedEnvironmentsReadRegistryError
|
||||
>;
|
||||
readonly setRegistry: (
|
||||
records: readonly PersistedSavedEnvironmentRecord[],
|
||||
) => Effect.Effect<void, DesktopSavedEnvironmentsMutationError>;
|
||||
readonly removeEnvironment: (
|
||||
environmentId: string,
|
||||
) => Effect.Effect<void, DesktopSavedEnvironmentsMutationError>;
|
||||
readonly getSecret: (
|
||||
environmentId: string,
|
||||
) => Effect.Effect<Option.Option<string>, DesktopSavedEnvironmentsGetSecretError>;
|
||||
readonly setSecret: (input: {
|
||||
readonly environmentId: string;
|
||||
readonly secret: string;
|
||||
}) => Effect.Effect<boolean, DesktopSavedEnvironmentsSetSecretError>;
|
||||
readonly removeSecret: (
|
||||
environmentId: string,
|
||||
) => Effect.Effect<void, DesktopSavedEnvironmentsMutationError>;
|
||||
}
|
||||
>()("@t3tools/desktop/settings/DesktopSavedEnvironments") {}
|
||||
|
||||
function toPersistedSavedEnvironmentRecord(
|
||||
@@ -193,19 +241,32 @@ function normalizeSavedEnvironmentRegistryDocument(
|
||||
function readRegistryDocument(
|
||||
fileSystem: FileSystem.FileSystem,
|
||||
registryPath: string,
|
||||
): Effect.Effect<
|
||||
SavedEnvironmentRegistryDocument,
|
||||
PlatformError.PlatformError | Schema.SchemaError
|
||||
> {
|
||||
): Effect.Effect<SavedEnvironmentRegistryDocument, DesktopSavedEnvironmentsReadRegistryError> {
|
||||
return fileSystem.readFileString(registryPath).pipe(
|
||||
Effect.catch((error) =>
|
||||
error.reason._tag === "NotFound" ? Effect.succeed<string | null>(null) : Effect.fail(error),
|
||||
error.reason._tag === "NotFound"
|
||||
? Effect.succeed<string | null>(null)
|
||||
: Effect.fail(
|
||||
new DesktopSavedEnvironmentsReadError({
|
||||
operation: "read-registry",
|
||||
registryPath,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
),
|
||||
Effect.flatMap((raw) =>
|
||||
raw === null
|
||||
? Effect.succeed({ version: 1, records: [] })
|
||||
: decodeSavedEnvironmentRegistryDocumentJson(raw).pipe(
|
||||
Effect.map(normalizeSavedEnvironmentRegistryDocument),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopSavedEnvironmentsDocumentDecodeError({
|
||||
operation: "decode-registry",
|
||||
registryPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -218,13 +279,23 @@ const writeRegistryDocument = Effect.fn("desktop.savedEnvironments.writeRegistry
|
||||
readonly registryPath: string;
|
||||
readonly document: SavedEnvironmentRegistryDocument;
|
||||
readonly suffix: string;
|
||||
}): Effect.fn.Return<void, PlatformError.PlatformError | Schema.SchemaError> {
|
||||
}): Effect.fn.Return<void, DesktopSavedEnvironmentsWriteError> {
|
||||
const directory = input.path.dirname(input.registryPath);
|
||||
const tempPath = `${input.registryPath}.${process.pid}.${input.suffix}.tmp`;
|
||||
const encoded = yield* encodeSavedEnvironmentRegistryDocumentJson(input.document);
|
||||
yield* input.fileSystem.makeDirectory(directory, { recursive: true });
|
||||
yield* input.fileSystem.writeFileString(tempPath, `${encoded}\n`);
|
||||
yield* input.fileSystem.rename(tempPath, input.registryPath);
|
||||
const encoded = yield* encodeSavedEnvironmentRegistryDocumentJson(input.document).pipe(
|
||||
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)),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
@@ -250,147 +321,160 @@ function preserveExistingSecrets(
|
||||
}
|
||||
|
||||
function decodeSecretBytes(
|
||||
environmentId: string,
|
||||
registryPath: string,
|
||||
encoded: string,
|
||||
): Effect.Effect<Uint8Array, DesktopSavedEnvironmentSecretDecodeError> {
|
||||
return Effect.fromResult(Encoding.decodeBase64(encoded)).pipe(
|
||||
Effect.mapError((cause) => new DesktopSavedEnvironmentSecretDecodeError({ cause })),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopSavedEnvironmentSecretDecodeError({
|
||||
operation: "decode-secret",
|
||||
environmentId,
|
||||
registryPath,
|
||||
field: "encryptedBearerToken",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
export const layer = Layer.effect(
|
||||
DesktopSavedEnvironments,
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const safeStorage = yield* ElectronSafeStorage.ElectronSafeStorage;
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
export const make = Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const safeStorage = yield* ElectronSafeStorage.ElectronSafeStorage;
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
|
||||
const writeDocument = (document: SavedEnvironmentRegistryDocument) =>
|
||||
crypto.randomUUIDv4.pipe(
|
||||
Effect.map((uuid) => uuid.replace(/-/g, "")),
|
||||
Effect.flatMap((suffix) =>
|
||||
writeRegistryDocument({
|
||||
fileSystem,
|
||||
path,
|
||||
registryPath: environment.savedEnvironmentRegistryPath,
|
||||
document,
|
||||
suffix,
|
||||
}),
|
||||
),
|
||||
Effect.mapError((cause) => new DesktopSavedEnvironmentsWriteError({ cause })),
|
||||
const writeDocument = (document: SavedEnvironmentRegistryDocument) =>
|
||||
crypto.randomUUIDv4.pipe(
|
||||
Effect.map((uuid) => uuid.replace(/-/g, "")),
|
||||
Effect.mapError((cause) =>
|
||||
writeError("create-temporary-file-name", environment.savedEnvironmentRegistryPath, cause),
|
||||
),
|
||||
Effect.flatMap((suffix) =>
|
||||
writeRegistryDocument({
|
||||
fileSystem,
|
||||
path,
|
||||
registryPath: environment.savedEnvironmentRegistryPath,
|
||||
document,
|
||||
suffix,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return DesktopSavedEnvironments.of({
|
||||
getRegistry: readRegistryDocument(fileSystem, environment.savedEnvironmentRegistryPath).pipe(
|
||||
Effect.map((document) =>
|
||||
document.records.map((record) => toPersistedSavedEnvironmentRecord(record)),
|
||||
),
|
||||
Effect.withSpan("desktop.savedEnvironments.getRegistry"),
|
||||
),
|
||||
setRegistry: Effect.fn("desktop.savedEnvironments.setRegistry")(function* (records) {
|
||||
const currentDocument = yield* readRegistryDocument(
|
||||
fileSystem,
|
||||
environment.savedEnvironmentRegistryPath,
|
||||
);
|
||||
|
||||
return DesktopSavedEnvironments.of({
|
||||
getRegistry: readRegistryDocument(fileSystem, environment.savedEnvironmentRegistryPath).pipe(
|
||||
Effect.map((document) =>
|
||||
document.records.map((record) => toPersistedSavedEnvironmentRecord(record)),
|
||||
),
|
||||
Effect.mapError((cause) => new DesktopSavedEnvironmentsReadError({ cause })),
|
||||
Effect.withSpan("desktop.savedEnvironments.getRegistry"),
|
||||
),
|
||||
setRegistry: Effect.fn("desktop.savedEnvironments.setRegistry")(function* (records) {
|
||||
const currentDocument = yield* readRegistryDocument(
|
||||
fileSystem,
|
||||
environment.savedEnvironmentRegistryPath,
|
||||
).pipe(Effect.mapError((cause) => new DesktopSavedEnvironmentsWriteError({ cause })));
|
||||
yield* writeDocument(preserveExistingSecrets(currentDocument, records));
|
||||
}),
|
||||
removeEnvironment: Effect.fn("desktop.savedEnvironments.removeEnvironment")(
|
||||
function* (environmentId) {
|
||||
yield* Effect.annotateCurrentSpan({ environmentId });
|
||||
const document = yield* readRegistryDocument(
|
||||
fileSystem,
|
||||
environment.savedEnvironmentRegistryPath,
|
||||
).pipe(Effect.mapError((cause) => new DesktopSavedEnvironmentsWriteError({ cause })));
|
||||
if (!document.records.some((record) => record.environmentId === environmentId)) {
|
||||
return;
|
||||
}
|
||||
|
||||
yield* writeDocument({
|
||||
version: document.version,
|
||||
records: document.records.filter((record) => record.environmentId !== environmentId),
|
||||
});
|
||||
},
|
||||
),
|
||||
getSecret: Effect.fn("desktop.savedEnvironments.getSecret")(function* (environmentId) {
|
||||
yield* writeDocument(preserveExistingSecrets(currentDocument, records));
|
||||
}),
|
||||
removeEnvironment: Effect.fn("desktop.savedEnvironments.removeEnvironment")(
|
||||
function* (environmentId) {
|
||||
yield* Effect.annotateCurrentSpan({ environmentId });
|
||||
const document = yield* readRegistryDocument(
|
||||
fileSystem,
|
||||
environment.savedEnvironmentRegistryPath,
|
||||
).pipe(Effect.mapError((cause) => new DesktopSavedEnvironmentsReadError({ cause })));
|
||||
const encoded = Option.fromNullishOr(
|
||||
document.records.find((record) => record.environmentId === environmentId)
|
||||
?.encryptedBearerToken,
|
||||
);
|
||||
if (Option.isNone(encoded) || !(yield* safeStorage.isEncryptionAvailable)) {
|
||||
return Option.none<string>();
|
||||
}
|
||||
|
||||
const secretBytes = yield* decodeSecretBytes(encoded.value);
|
||||
return Option.some(yield* safeStorage.decryptString(secretBytes));
|
||||
}),
|
||||
setSecret: Effect.fn("desktop.savedEnvironments.setSecret")(function* (input) {
|
||||
const { environmentId, secret } = input;
|
||||
yield* Effect.annotateCurrentSpan({ environmentId });
|
||||
const document = yield* readRegistryDocument(
|
||||
fileSystem,
|
||||
environment.savedEnvironmentRegistryPath,
|
||||
).pipe(Effect.mapError((cause) => new DesktopSavedEnvironmentsWriteError({ cause })));
|
||||
|
||||
if (!(yield* safeStorage.isEncryptionAvailable)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const encryptedBearerToken = Encoding.encodeBase64(
|
||||
yield* safeStorage.encryptString(secret),
|
||||
);
|
||||
let found = false;
|
||||
const nextDocument: SavedEnvironmentRegistryDocument = {
|
||||
version: document.version,
|
||||
records: document.records.map((record) => {
|
||||
if (record.environmentId !== environmentId) {
|
||||
return record;
|
||||
}
|
||||
|
||||
found = true;
|
||||
return toSavedEnvironmentStorageRecord(record, Option.some(encryptedBearerToken));
|
||||
}),
|
||||
};
|
||||
|
||||
if (found) {
|
||||
yield* writeDocument(nextDocument);
|
||||
}
|
||||
return found;
|
||||
}),
|
||||
removeSecret: Effect.fn("desktop.savedEnvironments.removeSecret")(function* (environmentId) {
|
||||
yield* Effect.annotateCurrentSpan({ environmentId });
|
||||
const document = yield* readRegistryDocument(
|
||||
fileSystem,
|
||||
environment.savedEnvironmentRegistryPath,
|
||||
).pipe(Effect.mapError((cause) => new DesktopSavedEnvironmentsWriteError({ cause })));
|
||||
if (
|
||||
!document.records.some(
|
||||
(record) =>
|
||||
record.environmentId === environmentId && record.encryptedBearerToken !== undefined,
|
||||
)
|
||||
) {
|
||||
if (!document.records.some((record) => record.environmentId === environmentId)) {
|
||||
return;
|
||||
}
|
||||
|
||||
yield* writeDocument({
|
||||
version: document.version,
|
||||
records: document.records.map((record) => {
|
||||
if (record.environmentId !== environmentId) {
|
||||
return record;
|
||||
}
|
||||
return toPersistedSavedEnvironmentRecord(record);
|
||||
}),
|
||||
records: document.records.filter((record) => record.environmentId !== environmentId),
|
||||
});
|
||||
}),
|
||||
});
|
||||
}),
|
||||
);
|
||||
},
|
||||
),
|
||||
getSecret: Effect.fn("desktop.savedEnvironments.getSecret")(function* (environmentId) {
|
||||
yield* Effect.annotateCurrentSpan({ environmentId });
|
||||
const document = yield* readRegistryDocument(
|
||||
fileSystem,
|
||||
environment.savedEnvironmentRegistryPath,
|
||||
);
|
||||
const encoded = Option.fromNullishOr(
|
||||
document.records.find((record) => record.environmentId === environmentId)
|
||||
?.encryptedBearerToken,
|
||||
);
|
||||
if (Option.isNone(encoded) || !(yield* safeStorage.isEncryptionAvailable)) {
|
||||
return Option.none<string>();
|
||||
}
|
||||
|
||||
const secretBytes = yield* decodeSecretBytes(
|
||||
environmentId,
|
||||
environment.savedEnvironmentRegistryPath,
|
||||
encoded.value,
|
||||
);
|
||||
return Option.some(yield* safeStorage.decryptString(secretBytes));
|
||||
}),
|
||||
setSecret: Effect.fn("desktop.savedEnvironments.setSecret")(function* (input) {
|
||||
const { environmentId, secret } = input;
|
||||
yield* Effect.annotateCurrentSpan({ environmentId });
|
||||
const document = yield* readRegistryDocument(
|
||||
fileSystem,
|
||||
environment.savedEnvironmentRegistryPath,
|
||||
);
|
||||
|
||||
if (!(yield* safeStorage.isEncryptionAvailable)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const encryptedBearerToken = Encoding.encodeBase64(yield* safeStorage.encryptString(secret));
|
||||
let found = false;
|
||||
const nextDocument: SavedEnvironmentRegistryDocument = {
|
||||
version: document.version,
|
||||
records: document.records.map((record) => {
|
||||
if (record.environmentId !== environmentId) {
|
||||
return record;
|
||||
}
|
||||
|
||||
found = true;
|
||||
return toSavedEnvironmentStorageRecord(record, Option.some(encryptedBearerToken));
|
||||
}),
|
||||
};
|
||||
|
||||
if (found) {
|
||||
yield* writeDocument(nextDocument);
|
||||
}
|
||||
return found;
|
||||
}),
|
||||
removeSecret: Effect.fn("desktop.savedEnvironments.removeSecret")(function* (environmentId) {
|
||||
yield* Effect.annotateCurrentSpan({ environmentId });
|
||||
const document = yield* readRegistryDocument(
|
||||
fileSystem,
|
||||
environment.savedEnvironmentRegistryPath,
|
||||
);
|
||||
if (
|
||||
!document.records.some(
|
||||
(record) =>
|
||||
record.environmentId === environmentId && record.encryptedBearerToken !== undefined,
|
||||
)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
yield* writeDocument({
|
||||
version: document.version,
|
||||
records: document.records.map((record) => {
|
||||
if (record.environmentId !== environmentId) {
|
||||
return record;
|
||||
}
|
||||
return toPersistedSavedEnvironmentRecord(record);
|
||||
}),
|
||||
});
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(DesktopSavedEnvironments, make);
|
||||
|
||||
export const layerTest = (input?: {
|
||||
readonly records?: readonly PersistedSavedEnvironmentRecord[];
|
||||
|
||||
@@ -7,7 +7,6 @@ import type {
|
||||
} from "@t3tools/contracts";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Data from "effect/Data";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
@@ -60,23 +59,26 @@ const decodeDownloadProgressInfo = Schema.decodeUnknownEffect(DownloadProgressIn
|
||||
|
||||
const currentIsoTimestamp = DateTime.now.pipe(Effect.map(DateTime.formatIso));
|
||||
|
||||
export class DesktopUpdateActionInProgressError extends Data.TaggedError(
|
||||
export class DesktopUpdateActionInProgressError extends Schema.TaggedErrorClass<DesktopUpdateActionInProgressError>()(
|
||||
"DesktopUpdateActionInProgressError",
|
||||
)<{
|
||||
readonly action: "check" | "download" | "install";
|
||||
}> {
|
||||
override get message() {
|
||||
{
|
||||
action: Schema.Literals(["check", "download", "install"]),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Cannot change update tracks while an update ${this.action} action is in progress.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopUpdatePersistenceError extends Data.TaggedError(
|
||||
export class DesktopUpdatePersistenceError extends Schema.TaggedErrorClass<DesktopUpdatePersistenceError>()(
|
||||
"DesktopUpdatePersistenceError",
|
||||
)<{
|
||||
readonly cause: DesktopAppSettings.DesktopSettingsWriteError;
|
||||
}> {
|
||||
override get message() {
|
||||
return "Failed to persist desktop update settings.";
|
||||
{
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
const detail = this.cause instanceof Error ? this.cause.message : String(this.cause);
|
||||
return `Failed to persist desktop update settings: ${detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -86,22 +88,21 @@ export type DesktopUpdateSetChannelError =
|
||||
| DesktopUpdateActionInProgressError
|
||||
| DesktopUpdatePersistenceError;
|
||||
|
||||
export interface DesktopUpdatesShape {
|
||||
readonly getState: Effect.Effect<DesktopUpdateState>;
|
||||
readonly emitState: Effect.Effect<void>;
|
||||
readonly disabledReason: Effect.Effect<Option.Option<string>>;
|
||||
readonly configure: Effect.Effect<void, DesktopUpdateConfigureError, Scope.Scope>;
|
||||
readonly setChannel: (
|
||||
channel: DesktopUpdateChannel,
|
||||
) => Effect.Effect<DesktopUpdateState, DesktopUpdateSetChannelError>;
|
||||
readonly check: (reason: string) => Effect.Effect<DesktopUpdateCheckResult>;
|
||||
readonly download: Effect.Effect<DesktopUpdateActionResult>;
|
||||
readonly install: Effect.Effect<DesktopUpdateActionResult>;
|
||||
}
|
||||
|
||||
export class DesktopUpdates extends Context.Service<DesktopUpdates, DesktopUpdatesShape>()(
|
||||
"@t3tools/desktop/updates/DesktopUpdates",
|
||||
) {}
|
||||
export class DesktopUpdates extends Context.Service<
|
||||
DesktopUpdates,
|
||||
{
|
||||
readonly getState: Effect.Effect<DesktopUpdateState>;
|
||||
readonly emitState: Effect.Effect<void>;
|
||||
readonly disabledReason: Effect.Effect<Option.Option<string>>;
|
||||
readonly configure: Effect.Effect<void, DesktopUpdateConfigureError, Scope.Scope>;
|
||||
readonly setChannel: (
|
||||
channel: DesktopUpdateChannel,
|
||||
) => Effect.Effect<DesktopUpdateState, DesktopUpdateSetChannelError>;
|
||||
readonly check: (reason: string) => Effect.Effect<DesktopUpdateCheckResult>;
|
||||
readonly download: Effect.Effect<DesktopUpdateActionResult>;
|
||||
readonly install: Effect.Effect<DesktopUpdateActionResult>;
|
||||
}
|
||||
>()("@t3tools/desktop/updates/DesktopUpdates") {}
|
||||
|
||||
const {
|
||||
logInfo: logUpdaterInfo,
|
||||
@@ -185,7 +186,7 @@ function isArm64HostRunningIntelBuild(runtimeInfo: DesktopRuntimeInfo): boolean
|
||||
return runtimeInfo.hostArch === "arm64" && runtimeInfo.appArch === "x64";
|
||||
}
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
export const make = Effect.gen(function* () {
|
||||
const config = yield* DesktopConfig.DesktopConfig;
|
||||
const backendManager = yield* DesktopBackendManager.DesktopBackendManager;
|
||||
const desktopState = yield* DesktopState.DesktopState;
|
||||
|
||||
@@ -64,7 +64,7 @@ const desktopUpdatesLayer = Layer.succeed(DesktopUpdates.DesktopUpdates, {
|
||||
check: () => Effect.die("unexpected check"),
|
||||
download: Effect.die("unexpected download"),
|
||||
install: Effect.die("unexpected install"),
|
||||
} satisfies DesktopUpdates.DesktopUpdatesShape);
|
||||
} satisfies DesktopUpdates.DesktopUpdates["Service"]);
|
||||
|
||||
const makeDesktopWindowLayer = (selectedAction: Deferred.Deferred<string>) =>
|
||||
Layer.succeed(DesktopWindow.DesktopWindow, {
|
||||
@@ -76,7 +76,7 @@ const makeDesktopWindowLayer = (selectedAction: Deferred.Deferred<string>) =>
|
||||
handleBackendReady: Effect.void,
|
||||
dispatchMenuAction: (action) => Deferred.succeed(selectedAction, action).pipe(Effect.asVoid),
|
||||
syncAppearance: Effect.void,
|
||||
} satisfies DesktopWindow.DesktopWindowShape);
|
||||
} satisfies DesktopWindow.DesktopWindow["Service"]);
|
||||
|
||||
const makeElectronMenuLayer = (
|
||||
applicationMenuTemplate: Deferred.Deferred<readonly Electron.MenuItemConstructorOptions[]>,
|
||||
|
||||
@@ -14,13 +14,11 @@ import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import * as DesktopUpdates from "../updates/DesktopUpdates.ts";
|
||||
import * as DesktopWindow from "./DesktopWindow.ts";
|
||||
|
||||
export interface DesktopApplicationMenuShape {
|
||||
readonly configure: Effect.Effect<void>;
|
||||
}
|
||||
|
||||
export class DesktopApplicationMenu extends Context.Service<
|
||||
DesktopApplicationMenu,
|
||||
DesktopApplicationMenuShape
|
||||
{
|
||||
readonly configure: Effect.Effect<void>;
|
||||
}
|
||||
>()("@t3tools/desktop/window/DesktopApplicationMenu") {}
|
||||
|
||||
type DesktopApplicationMenuRuntimeServices =
|
||||
@@ -94,7 +92,7 @@ const handleCheckForUpdatesMenuClick: Effect.Effect<
|
||||
yield* checkForUpdatesFromMenu;
|
||||
}).pipe(Effect.withSpan("desktop.menu.handleCheckForUpdatesClick"));
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
export const make = Effect.gen(function* () {
|
||||
const electronApp = yield* ElectronApp.ElectronApp;
|
||||
const electronMenu = yield* ElectronMenu.ElectronMenu;
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
|
||||
@@ -42,20 +42,19 @@ export type DesktopWindowError =
|
||||
| ElectronWindow.ElectronWindowCreateError
|
||||
| PreviewManager.PreviewManagerError;
|
||||
|
||||
export interface DesktopWindowShape {
|
||||
readonly createMain: Effect.Effect<Electron.BrowserWindow, DesktopWindowError>;
|
||||
readonly ensureMain: Effect.Effect<Electron.BrowserWindow, DesktopWindowError>;
|
||||
readonly revealOrCreateMain: Effect.Effect<Electron.BrowserWindow, DesktopWindowError>;
|
||||
readonly activate: Effect.Effect<void, DesktopWindowError>;
|
||||
readonly createMainIfBackendReady: Effect.Effect<void, DesktopWindowError>;
|
||||
readonly handleBackendReady: Effect.Effect<void, DesktopWindowError>;
|
||||
readonly dispatchMenuAction: (action: string) => Effect.Effect<void, DesktopWindowError>;
|
||||
readonly syncAppearance: Effect.Effect<void>;
|
||||
}
|
||||
|
||||
export class DesktopWindow extends Context.Service<DesktopWindow, DesktopWindowShape>()(
|
||||
"@t3tools/desktop/window/DesktopWindow",
|
||||
) {}
|
||||
export class DesktopWindow extends Context.Service<
|
||||
DesktopWindow,
|
||||
{
|
||||
readonly createMain: Effect.Effect<Electron.BrowserWindow, DesktopWindowError>;
|
||||
readonly ensureMain: Effect.Effect<Electron.BrowserWindow, DesktopWindowError>;
|
||||
readonly revealOrCreateMain: Effect.Effect<Electron.BrowserWindow, DesktopWindowError>;
|
||||
readonly activate: Effect.Effect<void, DesktopWindowError>;
|
||||
readonly createMainIfBackendReady: Effect.Effect<void, DesktopWindowError>;
|
||||
readonly handleBackendReady: Effect.Effect<void, DesktopWindowError>;
|
||||
readonly dispatchMenuAction: (action: string) => Effect.Effect<void, DesktopWindowError>;
|
||||
readonly syncAppearance: Effect.Effect<void>;
|
||||
}
|
||||
>()("@t3tools/desktop/window/DesktopWindow") {}
|
||||
|
||||
const { logInfo: logWindowInfo, logWarning: logWindowWarning } =
|
||||
DesktopObservability.makeComponentLogger("desktop-window");
|
||||
@@ -143,7 +142,7 @@ function bindFirstRevealTrigger(
|
||||
}
|
||||
}
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
export const make = Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const assets = yield* DesktopAssets.DesktopAssets;
|
||||
const electronMenu = yield* ElectronMenu.ElectronMenu;
|
||||
|
||||
@@ -18,7 +18,7 @@ export const LEGACY_CONNECTIONS_KEY = "t3code.connections";
|
||||
function catalogError(operation: string, cause: unknown) {
|
||||
return new ConnectionTransientError({
|
||||
reason: "remote-unavailable",
|
||||
message: `Could not ${operation} the local connection catalog: ${String(cause)}`,
|
||||
detail: `Could not ${operation} the local connection catalog: ${String(cause)}`,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -10,8 +10,8 @@ import {
|
||||
import {
|
||||
ConnectionBlockedError,
|
||||
ConnectionTransientError,
|
||||
ConnectionWakeups,
|
||||
Connectivity,
|
||||
Wakeups,
|
||||
} from "@t3tools/client-runtime/connection";
|
||||
import { managedRelayAccountChanges, managedRelaySessionAtom } from "@t3tools/client-runtime/relay";
|
||||
import { AuthStandardClientScopes } from "@t3tools/contracts";
|
||||
@@ -41,53 +41,47 @@ function networkStatus(state: Network.NetworkState): "unknown" | "offline" | "on
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
const connectivityLayer = Layer.succeed(
|
||||
Connectivity,
|
||||
Connectivity.of({
|
||||
status: Effect.tryPromise({
|
||||
try: () => Network.getNetworkStateAsync(),
|
||||
catch: () => undefined,
|
||||
}).pipe(
|
||||
Effect.match({
|
||||
onFailure: () => "unknown" as const,
|
||||
onSuccess: networkStatus,
|
||||
}),
|
||||
),
|
||||
changes: Stream.callback((queue) =>
|
||||
const connectivityLayer = Connectivity.layer({
|
||||
status: Effect.tryPromise({
|
||||
try: () => Network.getNetworkStateAsync(),
|
||||
catch: () => undefined,
|
||||
}).pipe(
|
||||
Effect.match({
|
||||
onFailure: () => "unknown" as const,
|
||||
onSuccess: networkStatus,
|
||||
}),
|
||||
),
|
||||
changes: Stream.callback((queue) =>
|
||||
Effect.acquireRelease(
|
||||
Effect.sync(() =>
|
||||
Network.addNetworkStateListener((state) => {
|
||||
Queue.offerUnsafe(queue, networkStatus(state));
|
||||
}),
|
||||
),
|
||||
(subscription) => Effect.sync(() => subscription.remove()),
|
||||
).pipe(Effect.asVoid),
|
||||
),
|
||||
});
|
||||
|
||||
const wakeupsLayer = Wakeups.layer({
|
||||
changes: Stream.merge(
|
||||
Stream.callback<"application-active">((queue) =>
|
||||
Effect.acquireRelease(
|
||||
Effect.sync(() =>
|
||||
Network.addNetworkStateListener((state) => {
|
||||
Queue.offerUnsafe(queue, networkStatus(state));
|
||||
AppState.addEventListener("change", (state) => {
|
||||
if (state === "active") {
|
||||
Queue.offerUnsafe(queue, "application-active");
|
||||
}
|
||||
}),
|
||||
),
|
||||
(subscription) => Effect.sync(() => subscription.remove()),
|
||||
).pipe(Effect.asVoid),
|
||||
),
|
||||
}),
|
||||
);
|
||||
|
||||
const wakeupsLayer = Layer.succeed(
|
||||
ConnectionWakeups,
|
||||
ConnectionWakeups.of({
|
||||
changes: Stream.merge(
|
||||
Stream.callback<"application-active">((queue) =>
|
||||
Effect.acquireRelease(
|
||||
Effect.sync(() =>
|
||||
AppState.addEventListener("change", (state) => {
|
||||
if (state === "active") {
|
||||
Queue.offerUnsafe(queue, "application-active");
|
||||
}
|
||||
}),
|
||||
),
|
||||
(subscription) => Effect.sync(() => subscription.remove()),
|
||||
).pipe(Effect.asVoid),
|
||||
),
|
||||
managedRelayAccountChanges(appAtomRegistry).pipe(
|
||||
Stream.map(() => "credentials-changed" as const),
|
||||
),
|
||||
managedRelayAccountChanges(appAtomRegistry).pipe(
|
||||
Stream.map(() => "credentials-changed" as const),
|
||||
),
|
||||
}),
|
||||
);
|
||||
),
|
||||
});
|
||||
|
||||
const capabilitiesLayer = Layer.succeedContext(
|
||||
Context.make(
|
||||
@@ -98,7 +92,7 @@ const capabilitiesLayer = Layer.succeedContext(
|
||||
if (session === null) {
|
||||
return yield* new ConnectionBlockedError({
|
||||
reason: "authentication",
|
||||
message: "Sign in to T3 Cloud to connect this environment.",
|
||||
detail: "Sign in to T3 Cloud to connect this environment.",
|
||||
});
|
||||
}
|
||||
const token = yield* session.readClerkToken().pipe(
|
||||
@@ -106,14 +100,14 @@ const capabilitiesLayer = Layer.succeedContext(
|
||||
(error) =>
|
||||
new ConnectionTransientError({
|
||||
reason: "network",
|
||||
message: error.message,
|
||||
detail: error.message,
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (token === null) {
|
||||
return yield* new ConnectionBlockedError({
|
||||
reason: "authentication",
|
||||
message: "The T3 Cloud session is unavailable.",
|
||||
detail: "The T3 Cloud session is unavailable.",
|
||||
});
|
||||
}
|
||||
return token;
|
||||
@@ -132,7 +126,7 @@ const capabilitiesLayer = Layer.succeedContext(
|
||||
catch: (cause) =>
|
||||
new ConnectionTransientError({
|
||||
reason: "remote-unavailable",
|
||||
message: `Could not load the mobile device identity: ${String(cause)}`,
|
||||
detail: `Could not load the mobile device identity: ${String(cause)}`,
|
||||
}),
|
||||
}).pipe(Effect.map(Option.some)),
|
||||
}),
|
||||
@@ -151,14 +145,14 @@ const capabilitiesLayer = Layer.succeedContext(
|
||||
Effect.fail(
|
||||
new ConnectionBlockedError({
|
||||
reason: "unsupported",
|
||||
message: "SSH environments are only available in the desktop app.",
|
||||
detail: "SSH environments are only available in the desktop app.",
|
||||
}),
|
||||
),
|
||||
prepare: () =>
|
||||
Effect.fail(
|
||||
new ConnectionBlockedError({
|
||||
reason: "unsupported",
|
||||
message: "SSH environments are only available in the desktop app.",
|
||||
detail: "SSH environments are only available in the desktop app.",
|
||||
}),
|
||||
),
|
||||
disconnect: () => Effect.void,
|
||||
@@ -195,7 +189,19 @@ const environmentOwnedDataCleanupLayer = Layer.succeed(
|
||||
}),
|
||||
);
|
||||
|
||||
export const connectionPlatformLayer = Layer.mergeAll(
|
||||
type ConnectionPlatformLayerSource =
|
||||
| typeof connectionStorageLayer
|
||||
| typeof connectivityLayer
|
||||
| typeof wakeupsLayer
|
||||
| typeof capabilitiesLayer
|
||||
| typeof platformConnectionSourceLayer
|
||||
| typeof environmentOwnedDataCleanupLayer;
|
||||
|
||||
export const connectionPlatformLayer: Layer.Layer<
|
||||
Layer.Success<ConnectionPlatformLayerSource>,
|
||||
Layer.Error<ConnectionPlatformLayerSource>,
|
||||
Layer.Services<ConnectionPlatformLayerSource>
|
||||
> = Layer.mergeAll(
|
||||
connectionStorageLayer,
|
||||
connectivityLayer,
|
||||
wakeupsLayer,
|
||||
|
||||
@@ -1,16 +1,28 @@
|
||||
import { connectionLayer as clientConnectionLayer } from "@t3tools/client-runtime/connection";
|
||||
import { Connection } from "@t3tools/client-runtime/connection";
|
||||
import * as Layer from "effect/Layer";
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
|
||||
import { runtimeContextLayer } from "../lib/runtime";
|
||||
import { connectionPlatformLayer } from "./platform";
|
||||
|
||||
const providedConnectionPlatformLayer = connectionPlatformLayer.pipe(
|
||||
Layer.provide(runtimeContextLayer),
|
||||
);
|
||||
const providedConnectionPlatformLayer: Layer.Layer<
|
||||
Layer.Success<typeof connectionPlatformLayer>,
|
||||
Layer.Error<typeof connectionPlatformLayer>
|
||||
> = connectionPlatformLayer.pipe(Layer.provide(runtimeContextLayer));
|
||||
|
||||
export const connectionLayer = clientConnectionLayer.pipe(
|
||||
type ConnectionLayerSource =
|
||||
| typeof Connection.layer
|
||||
| typeof runtimeContextLayer
|
||||
| typeof providedConnectionPlatformLayer;
|
||||
|
||||
export const connectionLayer: Layer.Layer<
|
||||
Layer.Success<ConnectionLayerSource>,
|
||||
Layer.Error<ConnectionLayerSource>
|
||||
> = Connection.layer.pipe(
|
||||
Layer.provideMerge(Layer.mergeAll(runtimeContextLayer, providedConnectionPlatformLayer)),
|
||||
);
|
||||
|
||||
export const connectionAtomRuntime = Atom.runtime(connectionLayer);
|
||||
export const connectionAtomRuntime: Atom.AtomRuntime<
|
||||
Layer.Success<typeof connectionLayer>,
|
||||
Layer.Error<typeof connectionLayer>
|
||||
> = Atom.runtime(connectionLayer);
|
||||
@@ -8,11 +8,11 @@ import {
|
||||
removeCatalogValue,
|
||||
replaceCatalogValue,
|
||||
} from "@t3tools/client-runtime/platform";
|
||||
import { RemoteDpopAccessTokenStore } from "@t3tools/client-runtime/authorization";
|
||||
import { TokenStore } from "@t3tools/client-runtime/authorization";
|
||||
import {
|
||||
ConnectionCredentialStore,
|
||||
ConnectionProfileStore,
|
||||
ConnectionTransientError,
|
||||
CredentialStore,
|
||||
ProfileStore,
|
||||
} from "@t3tools/client-runtime/connection";
|
||||
import {
|
||||
EnvironmentId,
|
||||
@@ -58,7 +58,7 @@ const LegacyStoredShellSnapshot = Schema.Struct({
|
||||
function catalogError(operation: string, cause: unknown) {
|
||||
return new ConnectionTransientError({
|
||||
reason: "remote-unavailable",
|
||||
message: `Could not ${operation} the local connection catalog: ${String(cause)}`,
|
||||
detail: `Could not ${operation} the local connection catalog: ${String(cause)}`,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -197,7 +197,7 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
.update((document) => removeConnectionFromCatalog(document, target))
|
||||
.pipe(Effect.mapError((error) => targetPersistenceError("remove-connection", error))),
|
||||
});
|
||||
const profileStore = ConnectionProfileStore.of({
|
||||
const profileStore = ProfileStore.make({
|
||||
get: (connectionId) =>
|
||||
catalog.read.pipe(
|
||||
Effect.map((document) =>
|
||||
@@ -221,7 +221,7 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
),
|
||||
})),
|
||||
});
|
||||
const credentialStore = ConnectionCredentialStore.of({
|
||||
const credentialStore = CredentialStore.make({
|
||||
get: (connectionId) =>
|
||||
catalog.read.pipe(
|
||||
Effect.map((document) =>
|
||||
@@ -248,7 +248,7 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
),
|
||||
})),
|
||||
});
|
||||
const remoteTokenStore = RemoteDpopAccessTokenStore.of({
|
||||
const remoteTokenStore = TokenStore.make({
|
||||
get: (environmentId) =>
|
||||
catalog.read.pipe(
|
||||
Effect.map((document) =>
|
||||
@@ -423,9 +423,9 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
|
||||
return Context.make(ConnectionTargetStore, targetStore).pipe(
|
||||
Context.add(ConnectionRegistrationStore, registrationStore),
|
||||
Context.add(ConnectionProfileStore, profileStore),
|
||||
Context.add(ConnectionCredentialStore, credentialStore),
|
||||
Context.add(RemoteDpopAccessTokenStore, remoteTokenStore),
|
||||
Context.add(ProfileStore.ConnectionProfileStore, profileStore),
|
||||
Context.add(CredentialStore.ConnectionCredentialStore, credentialStore),
|
||||
Context.add(TokenStore.RemoteDpopAccessTokenStore, remoteTokenStore),
|
||||
Context.add(EnvironmentCacheStore, cacheStore),
|
||||
);
|
||||
}),
|
||||
|
||||
@@ -22,8 +22,7 @@ import * as Schema from "effect/Schema";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import { CheckpointStoreLive } from "../src/checkpointing/Layers/CheckpointStore.ts";
|
||||
import { CheckpointStore } from "../src/checkpointing/Services/CheckpointStore.ts";
|
||||
import * as CheckpointStore from "../src/checkpointing/CheckpointStore.ts";
|
||||
import { TextGeneration, type TextGenerationShape } from "../src/textGeneration/TextGeneration.ts";
|
||||
import { OrchestrationCommandReceiptRepositoryLive } from "../src/persistence/Layers/OrchestrationCommandReceipts.ts";
|
||||
import { OrchestrationEventStoreLive } from "../src/persistence/Layers/OrchestrationEventStore.ts";
|
||||
@@ -180,7 +179,7 @@ export interface OrchestrationIntegrationHarness {
|
||||
readonly engine: OrchestrationEngineShape;
|
||||
readonly snapshotQuery: ProjectionSnapshotQuery["Service"];
|
||||
readonly providerService: ProviderService["Service"];
|
||||
readonly checkpointStore: CheckpointStore["Service"];
|
||||
readonly checkpointStore: CheckpointStore.CheckpointStore["Service"];
|
||||
readonly checkpointRepository: ProjectionCheckpointRepository["Service"];
|
||||
readonly pendingApprovalRepository: ProjectionPendingApprovalRepository["Service"];
|
||||
readonly waitForThread: (
|
||||
@@ -296,7 +295,7 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
);
|
||||
const providerRegistryLayer = makeProviderRegistryLayer();
|
||||
|
||||
const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(VcsDriverRegistry.layer));
|
||||
const checkpointStoreLayer = CheckpointStore.layer.pipe(Layer.provide(VcsDriverRegistry.layer));
|
||||
const projectionSnapshotQueryLayer = OrchestrationProjectionSnapshotQueryLive;
|
||||
const runtimeServicesLayer = Layer.mergeAll(
|
||||
projectionSnapshotQueryLayer,
|
||||
@@ -399,7 +398,7 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
runtime.runPromise(Effect.service(ProviderService)),
|
||||
).pipe(Effect.orDie);
|
||||
const checkpointStore = yield* tryRuntimePromise("load CheckpointStore service", () =>
|
||||
runtime.runPromise(Effect.service(CheckpointStore)),
|
||||
runtime.runPromise(Effect.service(CheckpointStore.CheckpointStore)),
|
||||
).pipe(Effect.orDie);
|
||||
const checkpointRepository = yield* tryRuntimePromise(
|
||||
"load ProjectionCheckpointRepository service",
|
||||
|
||||
@@ -25,7 +25,7 @@ import {
|
||||
import { ServerSettingsService } from "../src/serverSettings.ts";
|
||||
import { AnalyticsService } from "../src/telemetry/Services/AnalyticsService.ts";
|
||||
import { SqlitePersistenceMemory } from "../src/persistence/Layers/Sqlite.ts";
|
||||
import { ProviderSessionRuntimeRepositoryLive } from "../src/persistence/Layers/ProviderSessionRuntime.ts";
|
||||
import * as ProviderSessionRuntime from "../src/persistence/ProviderSessionRuntime.ts";
|
||||
|
||||
import {
|
||||
makeTestProviderAdapterHarness,
|
||||
@@ -63,7 +63,7 @@ const makeIntegrationFixture = Effect.gen(function* () {
|
||||
});
|
||||
|
||||
const directoryLayer = ProviderSessionDirectoryLive.pipe(
|
||||
Layer.provide(ProviderSessionRuntimeRepositoryLive),
|
||||
Layer.provide(ProviderSessionRuntime.layer),
|
||||
);
|
||||
|
||||
const shared = Layer.mergeAll(
|
||||
|
||||
@@ -18,8 +18,7 @@ import * as Stream from "effect/Stream";
|
||||
import * as Option from "effect/Option";
|
||||
|
||||
import { ServerConfig } from "../config.ts";
|
||||
import { AuthPairingLinkRepositoryLive } from "../persistence/Layers/AuthPairingLinks.ts";
|
||||
import { AuthPairingLinkRepository } from "../persistence/Services/AuthPairingLinks.ts";
|
||||
import * as AuthPairingLinks from "../persistence/AuthPairingLinks.ts";
|
||||
|
||||
export interface BootstrapGrant {
|
||||
readonly method: ServerAuthBootstrapMethod;
|
||||
@@ -126,7 +125,7 @@ const internalBootstrapCredentialError = (message: string, cause: unknown) =>
|
||||
export const make = Effect.fn("makePairingGrantStore")(function* () {
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const config = yield* ServerConfig;
|
||||
const pairingLinks = yield* AuthPairingLinkRepository;
|
||||
const pairingLinks = yield* AuthPairingLinks.AuthPairingLinkRepository;
|
||||
const seededGrantsRef = yield* Ref.make(new Map<string, StoredBootstrapGrant>());
|
||||
const changesPubSub = yield* PubSub.unbounded<BootstrapCredentialChange>();
|
||||
const generatePairingToken = Effect.gen(function* () {
|
||||
@@ -417,5 +416,5 @@ export const make = Effect.fn("makePairingGrantStore")(function* () {
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(PairingGrantStore, make()).pipe(
|
||||
Layer.provideMerge(AuthPairingLinkRepositoryLive),
|
||||
Layer.provideMerge(AuthPairingLinks.layer),
|
||||
);
|
||||
@@ -8,7 +8,7 @@ import * as TestClock from "effect/testing/TestClock";
|
||||
import * as ServerConfig from "../config.ts";
|
||||
import { PersistenceSqlError } from "../persistence/Errors.ts";
|
||||
import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";
|
||||
import * as AuthSessions from "../persistence/Services/AuthSessions.ts";
|
||||
import * as AuthSessions from "../persistence/AuthSessions.ts";
|
||||
import * as SessionStore from "./SessionStore.ts";
|
||||
import * as ServerSecretStore from "./ServerSecretStore.ts";
|
||||
|
||||
|
||||
@@ -22,8 +22,7 @@ import * as Stream from "effect/Stream";
|
||||
import * as Option from "effect/Option";
|
||||
|
||||
import { ServerConfig } from "../config.ts";
|
||||
import { AuthSessionRepositoryLive } from "../persistence/Layers/AuthSessions.ts";
|
||||
import { AuthSessionRepository } from "../persistence/Services/AuthSessions.ts";
|
||||
import * as AuthSessions from "../persistence/AuthSessions.ts";
|
||||
import * as ServerSecretStore from "./ServerSecretStore.ts";
|
||||
import {
|
||||
base64UrlDecodeUtf8,
|
||||
@@ -195,7 +194,7 @@ export const make = Effect.fn("makeSessionStore")(function* () {
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const serverConfig = yield* ServerConfig;
|
||||
const secretStore = yield* ServerSecretStore.ServerSecretStore;
|
||||
const authSessions = yield* AuthSessionRepository;
|
||||
const authSessions = yield* AuthSessions.AuthSessionRepository;
|
||||
const signingSecret = yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32);
|
||||
const connectedSessionsRef = yield* Ref.make(new Map<string, number>());
|
||||
const changesPubSub = yield* PubSub.unbounded<SessionCredentialChange>();
|
||||
@@ -640,5 +639,5 @@ export const make = Effect.fn("makeSessionStore")(function* () {
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(SessionStore, make()).pipe(
|
||||
Layer.provideMerge(AuthSessionRepositoryLive),
|
||||
Layer.provideMerge(AuthSessions.layer),
|
||||
);
|
||||
@@ -0,0 +1,418 @@
|
||||
import { CheckpointRef, ProjectId, ThreadId, TurnId } from "@t3tools/contracts";
|
||||
import { it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import { describe, expect } from "vite-plus/test";
|
||||
|
||||
import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import { checkpointRefForThreadTurn } from "./Utils.ts";
|
||||
import * as CheckpointDiffQuery from "./CheckpointDiffQuery.ts";
|
||||
import * as CheckpointStore from "./CheckpointStore.ts";
|
||||
|
||||
function makeThreadCheckpointContext(input: {
|
||||
readonly projectId: ProjectId;
|
||||
readonly threadId: ThreadId;
|
||||
readonly workspaceRoot: string;
|
||||
readonly worktreePath: string | null;
|
||||
readonly checkpointTurnCount: number;
|
||||
readonly checkpointRef: CheckpointRef;
|
||||
}): ProjectionSnapshotQuery.ProjectionThreadCheckpointContext {
|
||||
return {
|
||||
threadId: input.threadId,
|
||||
projectId: input.projectId,
|
||||
workspaceRoot: input.workspaceRoot,
|
||||
worktreePath: input.worktreePath,
|
||||
checkpoints: [
|
||||
{
|
||||
turnId: TurnId.make("turn-1"),
|
||||
checkpointTurnCount: input.checkpointTurnCount,
|
||||
checkpointRef: input.checkpointRef,
|
||||
status: "ready",
|
||||
files: [],
|
||||
assistantMessageId: null,
|
||||
completedAt: "2026-01-01T00:00:00.000Z",
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
describe("CheckpointDiffQuery.layer", () => {
|
||||
it.effect("uses the narrow full-thread context lookup for all-turns diffs", () =>
|
||||
Effect.gen(function* () {
|
||||
const projectId = ProjectId.make("project-full-thread");
|
||||
const threadId = ThreadId.make("thread-full-thread");
|
||||
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 4);
|
||||
let getThreadCheckpointContextCalls = 0;
|
||||
let getFullThreadDiffContextCalls = 0;
|
||||
const diffCheckpointsCalls: Array<{
|
||||
readonly fromCheckpointRef: CheckpointRef;
|
||||
readonly toCheckpointRef: CheckpointRef;
|
||||
readonly cwd: string;
|
||||
readonly ignoreWhitespace: boolean;
|
||||
}> = [];
|
||||
|
||||
const checkpointStore: CheckpointStore.CheckpointStore["Service"] = {
|
||||
isGitRepository: () => Effect.succeed(true),
|
||||
captureCheckpoint: () => Effect.void,
|
||||
hasCheckpointRef: () => Effect.succeed(true),
|
||||
restoreCheckpoint: () => Effect.succeed(true),
|
||||
diffCheckpoints: ({ fromCheckpointRef, toCheckpointRef, cwd, ignoreWhitespace }) =>
|
||||
Effect.sync(() => {
|
||||
diffCheckpointsCalls.push({
|
||||
fromCheckpointRef,
|
||||
toCheckpointRef,
|
||||
cwd,
|
||||
ignoreWhitespace,
|
||||
});
|
||||
return "full thread diff patch";
|
||||
}),
|
||||
deleteCheckpointRefs: () => Effect.void,
|
||||
};
|
||||
|
||||
const layer = CheckpointDiffQuery.layer.pipe(
|
||||
Layer.provideMerge(Layer.succeed(CheckpointStore.CheckpointStore, checkpointStore)),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
|
||||
getCommandReadModel: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the command read model"),
|
||||
getSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
|
||||
getShellSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
|
||||
getArchivedShellSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request archived shell snapshots"),
|
||||
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
|
||||
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
||||
getProjectShellById: () => Effect.succeed(Option.none()),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
|
||||
getThreadCheckpointContext: () =>
|
||||
Effect.sync(() => {
|
||||
getThreadCheckpointContextCalls += 1;
|
||||
return Option.none();
|
||||
}),
|
||||
getFullThreadDiffContext: () =>
|
||||
Effect.sync(() => {
|
||||
getFullThreadDiffContextCalls += 1;
|
||||
return Option.some({
|
||||
threadId,
|
||||
projectId,
|
||||
workspaceRoot: "/tmp/workspace",
|
||||
worktreePath: "/tmp/worktree",
|
||||
latestCheckpointTurnCount: 4,
|
||||
toCheckpointRef,
|
||||
});
|
||||
}),
|
||||
getThreadShellById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailById: () => Effect.succeed(Option.none()),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const result = yield* Effect.gen(function* () {
|
||||
const query = yield* CheckpointDiffQuery.CheckpointDiffQuery;
|
||||
return yield* query.getFullThreadDiff({
|
||||
threadId,
|
||||
toTurnCount: 4,
|
||||
ignoreWhitespace: true,
|
||||
});
|
||||
}).pipe(Effect.provide(layer));
|
||||
|
||||
expect(getThreadCheckpointContextCalls).toBe(0);
|
||||
expect(getFullThreadDiffContextCalls).toBe(1);
|
||||
expect(diffCheckpointsCalls).toEqual([
|
||||
{
|
||||
cwd: "/tmp/worktree",
|
||||
fromCheckpointRef: checkpointRefForThreadTurn(threadId, 0),
|
||||
toCheckpointRef,
|
||||
ignoreWhitespace: true,
|
||||
},
|
||||
]);
|
||||
expect(result).toEqual({
|
||||
threadId,
|
||||
fromTurnCount: 0,
|
||||
toTurnCount: 4,
|
||||
diff: "full thread diff patch",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("computes diffs using canonical turn-0 checkpoint refs", () =>
|
||||
Effect.gen(function* () {
|
||||
const projectId = ProjectId.make("project-1");
|
||||
const threadId = ThreadId.make("thread-1");
|
||||
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
|
||||
const diffCheckpointsCalls: Array<{
|
||||
readonly fromCheckpointRef: CheckpointRef;
|
||||
readonly toCheckpointRef: CheckpointRef;
|
||||
readonly cwd: string;
|
||||
readonly ignoreWhitespace: boolean;
|
||||
}> = [];
|
||||
|
||||
const threadCheckpointContext = makeThreadCheckpointContext({
|
||||
projectId,
|
||||
threadId,
|
||||
workspaceRoot: "/tmp/workspace",
|
||||
worktreePath: null,
|
||||
checkpointTurnCount: 1,
|
||||
checkpointRef: toCheckpointRef,
|
||||
});
|
||||
|
||||
const checkpointStore: CheckpointStore.CheckpointStore["Service"] = {
|
||||
isGitRepository: () => Effect.succeed(true),
|
||||
captureCheckpoint: () => Effect.void,
|
||||
hasCheckpointRef: () => Effect.succeed(true),
|
||||
restoreCheckpoint: () => Effect.succeed(true),
|
||||
diffCheckpoints: ({ fromCheckpointRef, toCheckpointRef, cwd, ignoreWhitespace }) =>
|
||||
Effect.sync(() => {
|
||||
diffCheckpointsCalls.push({
|
||||
fromCheckpointRef,
|
||||
toCheckpointRef,
|
||||
cwd,
|
||||
ignoreWhitespace,
|
||||
});
|
||||
return "diff patch";
|
||||
}),
|
||||
deleteCheckpointRefs: () => Effect.void,
|
||||
};
|
||||
|
||||
const layer = CheckpointDiffQuery.layer.pipe(
|
||||
Layer.provideMerge(Layer.succeed(CheckpointStore.CheckpointStore, checkpointStore)),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
|
||||
getCommandReadModel: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the command read model"),
|
||||
getSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
|
||||
getShellSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
|
||||
getArchivedShellSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request archived shell snapshots"),
|
||||
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
|
||||
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
||||
getProjectShellById: () => Effect.succeed(Option.none()),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
|
||||
getThreadCheckpointContext: () => Effect.succeed(Option.some(threadCheckpointContext)),
|
||||
getFullThreadDiffContext: () => Effect.die("unused"),
|
||||
getThreadShellById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailById: () => Effect.succeed(Option.none()),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const result = yield* Effect.gen(function* () {
|
||||
const query = yield* CheckpointDiffQuery.CheckpointDiffQuery;
|
||||
return yield* query.getTurnDiff({
|
||||
threadId,
|
||||
fromTurnCount: 0,
|
||||
toTurnCount: 1,
|
||||
ignoreWhitespace: true,
|
||||
});
|
||||
}).pipe(Effect.provide(layer));
|
||||
|
||||
const expectedFromRef = checkpointRefForThreadTurn(threadId, 0);
|
||||
expect(diffCheckpointsCalls).toEqual([
|
||||
{
|
||||
cwd: "/tmp/workspace",
|
||||
fromCheckpointRef: expectedFromRef,
|
||||
toCheckpointRef,
|
||||
ignoreWhitespace: true,
|
||||
},
|
||||
]);
|
||||
expect(result).toEqual({
|
||||
threadId,
|
||||
fromTurnCount: 0,
|
||||
toTurnCount: 1,
|
||||
diff: "diff patch",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("defaults to hide whitespace changes", () =>
|
||||
Effect.gen(function* () {
|
||||
const projectId = ProjectId.make("project-default-whitespace");
|
||||
const threadId = ThreadId.make("thread-default-whitespace");
|
||||
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
|
||||
const diffCheckpointsCalls: Array<{ readonly ignoreWhitespace: boolean }> = [];
|
||||
|
||||
const threadCheckpointContext = makeThreadCheckpointContext({
|
||||
projectId,
|
||||
threadId,
|
||||
workspaceRoot: "/tmp/workspace",
|
||||
worktreePath: null,
|
||||
checkpointTurnCount: 1,
|
||||
checkpointRef: toCheckpointRef,
|
||||
});
|
||||
|
||||
const checkpointStore: CheckpointStore.CheckpointStore["Service"] = {
|
||||
isGitRepository: () => Effect.succeed(true),
|
||||
captureCheckpoint: () => Effect.void,
|
||||
hasCheckpointRef: () => Effect.succeed(true),
|
||||
restoreCheckpoint: () => Effect.succeed(true),
|
||||
diffCheckpoints: ({ ignoreWhitespace }) =>
|
||||
Effect.sync(() => {
|
||||
diffCheckpointsCalls.push({ ignoreWhitespace });
|
||||
return "diff patch";
|
||||
}),
|
||||
deleteCheckpointRefs: () => Effect.void,
|
||||
};
|
||||
|
||||
const layer = CheckpointDiffQuery.layer.pipe(
|
||||
Layer.provideMerge(Layer.succeed(CheckpointStore.CheckpointStore, checkpointStore)),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
|
||||
getCommandReadModel: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the command read model"),
|
||||
getSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
|
||||
getShellSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
|
||||
getArchivedShellSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request archived shell snapshots"),
|
||||
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
|
||||
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
||||
getProjectShellById: () => Effect.succeed(Option.none()),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
|
||||
getThreadCheckpointContext: () => Effect.succeed(Option.some(threadCheckpointContext)),
|
||||
getFullThreadDiffContext: () => Effect.die("unused"),
|
||||
getThreadShellById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailById: () => Effect.succeed(Option.none()),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const query = yield* CheckpointDiffQuery.CheckpointDiffQuery;
|
||||
return yield* query.getTurnDiff({
|
||||
threadId,
|
||||
fromTurnCount: 0,
|
||||
toTurnCount: 1,
|
||||
});
|
||||
}).pipe(Effect.provide(layer));
|
||||
|
||||
expect(diffCheckpointsCalls).toEqual([{ ignoreWhitespace: true }]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not preflight checkpoint refs before diffing", () =>
|
||||
Effect.gen(function* () {
|
||||
const projectId = ProjectId.make("project-no-preflight");
|
||||
const threadId = ThreadId.make("thread-no-preflight");
|
||||
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
|
||||
let hasCheckpointRefCallCount = 0;
|
||||
|
||||
const threadCheckpointContext = makeThreadCheckpointContext({
|
||||
projectId,
|
||||
threadId,
|
||||
workspaceRoot: "/tmp/workspace",
|
||||
worktreePath: null,
|
||||
checkpointTurnCount: 1,
|
||||
checkpointRef: toCheckpointRef,
|
||||
});
|
||||
|
||||
const checkpointStore: CheckpointStore.CheckpointStore["Service"] = {
|
||||
isGitRepository: () => Effect.succeed(true),
|
||||
captureCheckpoint: () => Effect.void,
|
||||
hasCheckpointRef: () =>
|
||||
Effect.sync(() => {
|
||||
hasCheckpointRefCallCount += 1;
|
||||
return true;
|
||||
}),
|
||||
restoreCheckpoint: () => Effect.succeed(true),
|
||||
diffCheckpoints: () => Effect.succeed("diff patch"),
|
||||
deleteCheckpointRefs: () => Effect.void,
|
||||
};
|
||||
|
||||
const layer = CheckpointDiffQuery.layer.pipe(
|
||||
Layer.provideMerge(Layer.succeed(CheckpointStore.CheckpointStore, checkpointStore)),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
|
||||
getCommandReadModel: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the command read model"),
|
||||
getSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
|
||||
getShellSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
|
||||
getArchivedShellSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request archived shell snapshots"),
|
||||
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
|
||||
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
||||
getProjectShellById: () => Effect.succeed(Option.none()),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
|
||||
getThreadCheckpointContext: () => Effect.succeed(Option.some(threadCheckpointContext)),
|
||||
getFullThreadDiffContext: () => Effect.die("unused"),
|
||||
getThreadShellById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailById: () => Effect.succeed(Option.none()),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const query = yield* CheckpointDiffQuery.CheckpointDiffQuery;
|
||||
return yield* query.getTurnDiff({
|
||||
threadId,
|
||||
fromTurnCount: 0,
|
||||
toTurnCount: 1,
|
||||
ignoreWhitespace: true,
|
||||
});
|
||||
}).pipe(Effect.provide(layer));
|
||||
|
||||
expect(hasCheckpointRefCallCount).toBe(0);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("fails when the thread is missing from the snapshot", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("thread-missing");
|
||||
|
||||
const checkpointStore: CheckpointStore.CheckpointStore["Service"] = {
|
||||
isGitRepository: () => Effect.succeed(true),
|
||||
captureCheckpoint: () => Effect.void,
|
||||
hasCheckpointRef: () => Effect.succeed(true),
|
||||
restoreCheckpoint: () => Effect.succeed(true),
|
||||
diffCheckpoints: () => Effect.succeed(""),
|
||||
deleteCheckpointRefs: () => Effect.void,
|
||||
};
|
||||
|
||||
const layer = CheckpointDiffQuery.layer.pipe(
|
||||
Layer.provideMerge(Layer.succeed(CheckpointStore.CheckpointStore, checkpointStore)),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
|
||||
getCommandReadModel: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the command read model"),
|
||||
getSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
|
||||
getShellSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
|
||||
getArchivedShellSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request archived shell snapshots"),
|
||||
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
|
||||
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
||||
getProjectShellById: () => Effect.succeed(Option.none()),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
|
||||
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
|
||||
getFullThreadDiffContext: () => Effect.succeed(Option.none()),
|
||||
getThreadShellById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailById: () => Effect.succeed(Option.none()),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const error = yield* Effect.gen(function* () {
|
||||
const query = yield* CheckpointDiffQuery.CheckpointDiffQuery;
|
||||
return yield* query.getTurnDiff({
|
||||
threadId,
|
||||
fromTurnCount: 0,
|
||||
toTurnCount: 1,
|
||||
});
|
||||
}).pipe(Effect.provide(layer), Effect.flip);
|
||||
|
||||
expect(error.message).toContain("Thread 'thread-missing' not found.");
|
||||
}),
|
||||
);
|
||||
});
|
||||
+48
-16
@@ -1,23 +1,55 @@
|
||||
/**
|
||||
* CheckpointDiffQuery - Query interface for computed checkpoint diffs.
|
||||
*
|
||||
* Provides read-only diff operations across checkpoint snapshots used by
|
||||
* orchestration APIs.
|
||||
*
|
||||
* @module CheckpointDiffQuery
|
||||
*/
|
||||
import {
|
||||
type CheckpointRef,
|
||||
OrchestrationGetTurnDiffResult,
|
||||
type ThreadId,
|
||||
type OrchestrationGetFullThreadDiffInput,
|
||||
type OrchestrationGetFullThreadDiffResult,
|
||||
type OrchestrationGetTurnDiffInput,
|
||||
type OrchestrationGetTurnDiffResult as OrchestrationGetTurnDiffResultType,
|
||||
type ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import { CheckpointInvariantError, CheckpointUnavailableError } from "../Errors.ts";
|
||||
import { checkpointRefForThreadTurn } from "../Utils.ts";
|
||||
import { CheckpointStore } from "../Services/CheckpointStore.ts";
|
||||
import {
|
||||
import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import { CheckpointInvariantError, CheckpointUnavailableError } from "./Errors.ts";
|
||||
import type { CheckpointServiceError } from "./Errors.ts";
|
||||
import { checkpointRefForThreadTurn } from "./Utils.ts";
|
||||
import * as CheckpointStore from "./CheckpointStore.ts";
|
||||
|
||||
/** Service tag for checkpoint diff queries. */
|
||||
export class CheckpointDiffQuery extends Context.Service<
|
||||
CheckpointDiffQuery,
|
||||
type CheckpointDiffQueryShape,
|
||||
} from "../Services/CheckpointDiffQuery.ts";
|
||||
{
|
||||
/**
|
||||
* Read the patch diff for a single turn checkpoint transition.
|
||||
*
|
||||
* Verifies checkpoint availability in both projection state and filesystem.
|
||||
*/
|
||||
readonly getTurnDiff: (
|
||||
input: OrchestrationGetTurnDiffInput,
|
||||
) => Effect.Effect<OrchestrationGetTurnDiffResultType, CheckpointServiceError>;
|
||||
|
||||
/**
|
||||
* Read the full patch diff across a thread range of checkpoints.
|
||||
*
|
||||
* Uses turn-diff semantics with `fromTurnCount = 0`.
|
||||
*/
|
||||
readonly getFullThreadDiff: (
|
||||
input: OrchestrationGetFullThreadDiffInput,
|
||||
) => Effect.Effect<OrchestrationGetFullThreadDiffResult, CheckpointServiceError>;
|
||||
}
|
||||
>()("t3/checkpointing/CheckpointDiffQuery") {}
|
||||
|
||||
const isTurnDiffResult = Schema.is(OrchestrationGetTurnDiffResult);
|
||||
|
||||
@@ -37,11 +69,11 @@ function buildTurnDiffResult(
|
||||
};
|
||||
}
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
const checkpointStore = yield* CheckpointStore;
|
||||
export const make = Effect.gen(function* () {
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
|
||||
const checkpointStore = yield* CheckpointStore.CheckpointStore;
|
||||
|
||||
const getTurnDiff: CheckpointDiffQueryShape["getTurnDiff"] = Effect.fn("getTurnDiff")(
|
||||
const getTurnDiff: CheckpointDiffQuery["Service"]["getTurnDiff"] = Effect.fn("getTurnDiff")(
|
||||
function* (input) {
|
||||
const operation = "CheckpointDiffQuery.getTurnDiff";
|
||||
const ignoreWhitespace = input.ignoreWhitespace ?? true;
|
||||
@@ -145,7 +177,7 @@ const make = Effect.gen(function* () {
|
||||
},
|
||||
);
|
||||
|
||||
const getFullThreadDiff: CheckpointDiffQueryShape["getFullThreadDiff"] = Effect.fn(
|
||||
const getFullThreadDiff: CheckpointDiffQuery["Service"]["getFullThreadDiff"] = Effect.fn(
|
||||
"CheckpointDiffQuery.getFullThreadDiff",
|
||||
)(function* (input) {
|
||||
const operation = "CheckpointDiffQuery.getFullThreadDiff";
|
||||
@@ -239,10 +271,10 @@ const make = Effect.gen(function* () {
|
||||
return turnDiff satisfies OrchestrationGetFullThreadDiffResult;
|
||||
});
|
||||
|
||||
return {
|
||||
return CheckpointDiffQuery.of({
|
||||
getTurnDiff,
|
||||
getFullThreadDiff,
|
||||
} satisfies CheckpointDiffQueryShape;
|
||||
});
|
||||
});
|
||||
|
||||
export const CheckpointDiffQueryLive = Layer.effect(CheckpointDiffQuery, make);
|
||||
export const layer = Layer.effect(CheckpointDiffQuery, make);
|
||||
+11
-13
@@ -3,6 +3,7 @@ import path from "node:path";
|
||||
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it } from "@effect/vitest";
|
||||
import { ThreadId, type VcsError } from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
@@ -10,21 +11,18 @@ import * as PlatformError from "effect/PlatformError";
|
||||
import * as Scope from "effect/Scope";
|
||||
import { describe, expect } from "vite-plus/test";
|
||||
|
||||
import { checkpointRefForThreadTurn } from "../Utils.ts";
|
||||
import { CheckpointStoreLive } from "./CheckpointStore.ts";
|
||||
import { CheckpointStore } from "../Services/CheckpointStore.ts";
|
||||
import * as VcsDriverRegistry from "../../vcs/VcsDriverRegistry.ts";
|
||||
import * as VcsProcess from "../../vcs/VcsProcess.ts";
|
||||
import type { VcsError } from "@t3tools/contracts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ThreadId } from "@t3tools/contracts";
|
||||
import { checkpointRefForThreadTurn } from "./Utils.ts";
|
||||
import * as CheckpointStore from "./CheckpointStore.ts";
|
||||
import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
|
||||
import * as VcsProcess from "../vcs/VcsProcess.ts";
|
||||
import * as ServerConfig from "../config.ts";
|
||||
|
||||
const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
|
||||
const ServerConfigLayer = ServerConfig.ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3-checkpoint-store-test-",
|
||||
});
|
||||
const VcsProcessTestLayer = VcsProcess.layer.pipe(Layer.provide(NodeServices.layer));
|
||||
const VcsDriverTestLayer = VcsDriverRegistry.layer.pipe(Layer.provide(VcsProcessTestLayer));
|
||||
const CheckpointStoreTestLayer = CheckpointStoreLive.pipe(
|
||||
const CheckpointStoreTestLayer = CheckpointStore.layer.pipe(
|
||||
Layer.provideMerge(VcsDriverTestLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
@@ -94,13 +92,13 @@ function buildLargeText(lineCount = 5_000): string {
|
||||
.concat("\n");
|
||||
}
|
||||
|
||||
it.layer(TestLayer)("CheckpointStoreLive", (it) => {
|
||||
it.layer(TestLayer)("CheckpointStore.layer", (it) => {
|
||||
describe("diffCheckpoints", () => {
|
||||
it.effect("returns full oversized checkpoint diffs without truncation", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
const checkpointStore = yield* CheckpointStore;
|
||||
const checkpointStore = yield* CheckpointStore.CheckpointStore;
|
||||
const threadId = ThreadId.make("thread-checkpoint-store");
|
||||
const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0);
|
||||
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
|
||||
@@ -132,7 +130,7 @@ it.layer(TestLayer)("CheckpointStoreLive", (it) => {
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
const checkpointStore = yield* CheckpointStore;
|
||||
const checkpointStore = yield* CheckpointStore.CheckpointStore;
|
||||
const threadId = ThreadId.make("thread-checkpoint-store-whitespace");
|
||||
const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0);
|
||||
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
|
||||
@@ -0,0 +1,171 @@
|
||||
/**
|
||||
* CheckpointStore - Repository interface for filesystem-backed workspace checkpoints.
|
||||
*
|
||||
* Owns hidden Git-ref checkpoint capture/restore and diff computation for a
|
||||
* workspace thread timeline. It does not store user-facing checkpoint metadata
|
||||
* and does not coordinate provider conversation rollback.
|
||||
*
|
||||
* The live adapter resolves the active VCS driver once per checkpoint operation
|
||||
* and delegates to the driver's optional checkpoint capability.
|
||||
*
|
||||
* Uses Effect `Context.Service` for dependency injection and exposes typed
|
||||
* domain errors for checkpoint storage operations.
|
||||
*
|
||||
* @module CheckpointStore
|
||||
*/
|
||||
import { VcsUnsupportedOperationError, type CheckpointRef } from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
|
||||
import type { CheckpointStoreError } from "./Errors.ts";
|
||||
import type { VcsCheckpointOps } from "../vcs/VcsDriver.ts";
|
||||
import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
|
||||
|
||||
export interface CaptureCheckpointInput {
|
||||
readonly cwd: string;
|
||||
readonly checkpointRef: CheckpointRef;
|
||||
}
|
||||
|
||||
export interface RestoreCheckpointInput {
|
||||
readonly cwd: string;
|
||||
readonly checkpointRef: CheckpointRef;
|
||||
readonly fallbackToHead?: boolean;
|
||||
}
|
||||
|
||||
export interface DiffCheckpointsInput {
|
||||
readonly cwd: string;
|
||||
readonly fromCheckpointRef: CheckpointRef;
|
||||
readonly toCheckpointRef: CheckpointRef;
|
||||
readonly fallbackFromToHead?: boolean;
|
||||
readonly ignoreWhitespace: boolean;
|
||||
}
|
||||
|
||||
export interface DeleteCheckpointRefsInput {
|
||||
readonly cwd: string;
|
||||
readonly checkpointRefs: ReadonlyArray<CheckpointRef>;
|
||||
}
|
||||
|
||||
/** Service tag for checkpoint persistence and restore operations. */
|
||||
export class CheckpointStore extends Context.Service<
|
||||
CheckpointStore,
|
||||
{
|
||||
/** Check whether cwd is inside a Git worktree. */
|
||||
readonly isGitRepository: (cwd: string) => Effect.Effect<boolean, CheckpointStoreError>;
|
||||
|
||||
/**
|
||||
* Capture a checkpoint commit and store it at the provided checkpoint ref.
|
||||
*
|
||||
* Uses an isolated temporary Git index and writes a hidden ref.
|
||||
*/
|
||||
readonly captureCheckpoint: (
|
||||
input: CaptureCheckpointInput,
|
||||
) => Effect.Effect<void, CheckpointStoreError>;
|
||||
|
||||
/** Check whether a checkpoint ref exists. */
|
||||
readonly hasCheckpointRef: (
|
||||
input: Omit<RestoreCheckpointInput, "fallbackToHead">,
|
||||
) => Effect.Effect<boolean, CheckpointStoreError>;
|
||||
|
||||
/**
|
||||
* Restore workspace and staging state to a checkpoint.
|
||||
*
|
||||
* Optionally falls back to current `HEAD` when the checkpoint ref is missing.
|
||||
*/
|
||||
readonly restoreCheckpoint: (
|
||||
input: RestoreCheckpointInput,
|
||||
) => Effect.Effect<boolean, CheckpointStoreError>;
|
||||
|
||||
/**
|
||||
* Compute a patch diff between two checkpoint refs.
|
||||
*
|
||||
* Can optionally treat a missing "from" ref as `HEAD`.
|
||||
*/
|
||||
readonly diffCheckpoints: (
|
||||
input: DiffCheckpointsInput,
|
||||
) => Effect.Effect<string, CheckpointStoreError>;
|
||||
|
||||
/**
|
||||
* Delete the provided checkpoint refs.
|
||||
*
|
||||
* Best-effort delete: missing refs are tolerated.
|
||||
*/
|
||||
readonly deleteCheckpointRefs: (
|
||||
input: DeleteCheckpointRefsInput,
|
||||
) => Effect.Effect<void, CheckpointStoreError>;
|
||||
}
|
||||
>()("t3/checkpointing/CheckpointStore") {}
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const vcsRegistry = yield* VcsDriverRegistry.VcsDriverRegistry;
|
||||
|
||||
const resolveCheckpoints = Effect.fn("CheckpointStore.resolveCheckpoints")(function* (
|
||||
operation: string,
|
||||
cwd: string,
|
||||
) {
|
||||
const handle = yield* vcsRegistry.resolve({ cwd });
|
||||
if (!handle.driver.checkpoints) {
|
||||
return yield* new VcsUnsupportedOperationError({
|
||||
operation,
|
||||
kind: handle.kind,
|
||||
detail: `${handle.kind} driver does not implement checkpoint operations.`,
|
||||
});
|
||||
}
|
||||
return handle.driver.checkpoints satisfies VcsCheckpointOps;
|
||||
});
|
||||
|
||||
const isGitRepository: CheckpointStore["Service"]["isGitRepository"] = (cwd) =>
|
||||
vcsRegistry.resolve({ cwd, requestedKind: "git" }).pipe(
|
||||
Effect.map(() => true),
|
||||
Effect.orElseSucceed(() => false),
|
||||
);
|
||||
|
||||
const captureCheckpoint: CheckpointStore["Service"]["captureCheckpoint"] = Effect.fn(
|
||||
"captureCheckpoint",
|
||||
)(function* (input) {
|
||||
const checkpoints = yield* resolveCheckpoints("CheckpointStore.captureCheckpoint", input.cwd);
|
||||
return yield* checkpoints.captureCheckpoint(input);
|
||||
});
|
||||
|
||||
const hasCheckpointRef: CheckpointStore["Service"]["hasCheckpointRef"] = Effect.fn(
|
||||
"hasCheckpointRef",
|
||||
)(function* (input) {
|
||||
const checkpoints = yield* resolveCheckpoints("CheckpointStore.hasCheckpointRef", input.cwd);
|
||||
return yield* checkpoints.hasCheckpointRef(input);
|
||||
});
|
||||
|
||||
const restoreCheckpoint: CheckpointStore["Service"]["restoreCheckpoint"] = Effect.fn(
|
||||
"restoreCheckpoint",
|
||||
)(function* (input) {
|
||||
const checkpoints = yield* resolveCheckpoints("CheckpointStore.restoreCheckpoint", input.cwd);
|
||||
return yield* checkpoints.restoreCheckpoint(input);
|
||||
});
|
||||
|
||||
const diffCheckpoints: CheckpointStore["Service"]["diffCheckpoints"] = Effect.fn(
|
||||
"diffCheckpoints",
|
||||
)(function* (input) {
|
||||
const checkpoints = yield* resolveCheckpoints("CheckpointStore.diffCheckpoints", input.cwd);
|
||||
return yield* checkpoints.diffCheckpoints(input);
|
||||
});
|
||||
|
||||
const deleteCheckpointRefs: CheckpointStore["Service"]["deleteCheckpointRefs"] = Effect.fn(
|
||||
"deleteCheckpointRefs",
|
||||
)(function* (input) {
|
||||
const checkpoints = yield* resolveCheckpoints(
|
||||
"CheckpointStore.deleteCheckpointRefs",
|
||||
input.cwd,
|
||||
);
|
||||
return yield* checkpoints.deleteCheckpointRefs(input);
|
||||
});
|
||||
|
||||
return CheckpointStore.of({
|
||||
isGitRepository,
|
||||
captureCheckpoint,
|
||||
hasCheckpointRef,
|
||||
restoreCheckpoint,
|
||||
diffCheckpoints,
|
||||
deleteCheckpointRefs,
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(CheckpointStore, make);
|
||||
@@ -1,421 +0,0 @@
|
||||
import { CheckpointRef, ProjectId, ThreadId, TurnId } from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
ProjectionSnapshotQuery,
|
||||
type ProjectionThreadCheckpointContext,
|
||||
} from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import { checkpointRefForThreadTurn } from "../Utils.ts";
|
||||
import { CheckpointDiffQueryLive } from "./CheckpointDiffQuery.ts";
|
||||
import { CheckpointStore, type CheckpointStoreShape } from "../Services/CheckpointStore.ts";
|
||||
import { CheckpointDiffQuery } from "../Services/CheckpointDiffQuery.ts";
|
||||
|
||||
function makeThreadCheckpointContext(input: {
|
||||
readonly projectId: ProjectId;
|
||||
readonly threadId: ThreadId;
|
||||
readonly workspaceRoot: string;
|
||||
readonly worktreePath: string | null;
|
||||
readonly checkpointTurnCount: number;
|
||||
readonly checkpointRef: CheckpointRef;
|
||||
}): ProjectionThreadCheckpointContext {
|
||||
return {
|
||||
threadId: input.threadId,
|
||||
projectId: input.projectId,
|
||||
workspaceRoot: input.workspaceRoot,
|
||||
worktreePath: input.worktreePath,
|
||||
checkpoints: [
|
||||
{
|
||||
turnId: TurnId.make("turn-1"),
|
||||
checkpointTurnCount: input.checkpointTurnCount,
|
||||
checkpointRef: input.checkpointRef,
|
||||
status: "ready",
|
||||
files: [],
|
||||
assistantMessageId: null,
|
||||
completedAt: "2026-01-01T00:00:00.000Z",
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
describe("CheckpointDiffQueryLive", () => {
|
||||
it("uses the narrow full-thread context lookup for all-turns diffs", async () => {
|
||||
const projectId = ProjectId.make("project-full-thread");
|
||||
const threadId = ThreadId.make("thread-full-thread");
|
||||
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 4);
|
||||
let getThreadCheckpointContextCalls = 0;
|
||||
let getFullThreadDiffContextCalls = 0;
|
||||
const diffCheckpointsCalls: Array<{
|
||||
readonly fromCheckpointRef: CheckpointRef;
|
||||
readonly toCheckpointRef: CheckpointRef;
|
||||
readonly cwd: string;
|
||||
readonly ignoreWhitespace: boolean;
|
||||
}> = [];
|
||||
|
||||
const checkpointStore: CheckpointStoreShape = {
|
||||
isGitRepository: () => Effect.succeed(true),
|
||||
captureCheckpoint: () => Effect.void,
|
||||
hasCheckpointRef: () => Effect.succeed(true),
|
||||
restoreCheckpoint: () => Effect.succeed(true),
|
||||
diffCheckpoints: ({ fromCheckpointRef, toCheckpointRef, cwd, ignoreWhitespace }) =>
|
||||
Effect.sync(() => {
|
||||
diffCheckpointsCalls.push({
|
||||
fromCheckpointRef,
|
||||
toCheckpointRef,
|
||||
cwd,
|
||||
ignoreWhitespace,
|
||||
});
|
||||
return "full thread diff patch";
|
||||
}),
|
||||
deleteCheckpointRefs: () => Effect.void,
|
||||
};
|
||||
|
||||
const layer = CheckpointDiffQueryLive.pipe(
|
||||
Layer.provideMerge(Layer.succeed(CheckpointStore, checkpointStore)),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(ProjectionSnapshotQuery, {
|
||||
getCommandReadModel: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the command read model"),
|
||||
getSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
|
||||
getShellSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
|
||||
getArchivedShellSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request archived shell snapshots"),
|
||||
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
|
||||
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
||||
getProjectShellById: () => Effect.succeed(Option.none()),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
|
||||
getThreadCheckpointContext: () =>
|
||||
Effect.sync(() => {
|
||||
getThreadCheckpointContextCalls += 1;
|
||||
return Option.none();
|
||||
}),
|
||||
getFullThreadDiffContext: () =>
|
||||
Effect.sync(() => {
|
||||
getFullThreadDiffContextCalls += 1;
|
||||
return Option.some({
|
||||
threadId,
|
||||
projectId,
|
||||
workspaceRoot: "/tmp/workspace",
|
||||
worktreePath: "/tmp/worktree",
|
||||
latestCheckpointTurnCount: 4,
|
||||
toCheckpointRef,
|
||||
});
|
||||
}),
|
||||
getThreadShellById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailById: () => Effect.succeed(Option.none()),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const result = await Effect.runPromise(
|
||||
Effect.gen(function* () {
|
||||
const query = yield* CheckpointDiffQuery;
|
||||
return yield* query.getFullThreadDiff({
|
||||
threadId,
|
||||
toTurnCount: 4,
|
||||
ignoreWhitespace: true,
|
||||
});
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
|
||||
expect(getThreadCheckpointContextCalls).toBe(0);
|
||||
expect(getFullThreadDiffContextCalls).toBe(1);
|
||||
expect(diffCheckpointsCalls).toEqual([
|
||||
{
|
||||
cwd: "/tmp/worktree",
|
||||
fromCheckpointRef: checkpointRefForThreadTurn(threadId, 0),
|
||||
toCheckpointRef,
|
||||
ignoreWhitespace: true,
|
||||
},
|
||||
]);
|
||||
expect(result).toEqual({
|
||||
threadId,
|
||||
fromTurnCount: 0,
|
||||
toTurnCount: 4,
|
||||
diff: "full thread diff patch",
|
||||
});
|
||||
});
|
||||
|
||||
it("computes diffs using canonical turn-0 checkpoint refs", async () => {
|
||||
const projectId = ProjectId.make("project-1");
|
||||
const threadId = ThreadId.make("thread-1");
|
||||
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
|
||||
const diffCheckpointsCalls: Array<{
|
||||
readonly fromCheckpointRef: CheckpointRef;
|
||||
readonly toCheckpointRef: CheckpointRef;
|
||||
readonly cwd: string;
|
||||
readonly ignoreWhitespace: boolean;
|
||||
}> = [];
|
||||
|
||||
const threadCheckpointContext = makeThreadCheckpointContext({
|
||||
projectId,
|
||||
threadId,
|
||||
workspaceRoot: "/tmp/workspace",
|
||||
worktreePath: null,
|
||||
checkpointTurnCount: 1,
|
||||
checkpointRef: toCheckpointRef,
|
||||
});
|
||||
|
||||
const checkpointStore: CheckpointStoreShape = {
|
||||
isGitRepository: () => Effect.succeed(true),
|
||||
captureCheckpoint: () => Effect.void,
|
||||
hasCheckpointRef: () => Effect.succeed(true),
|
||||
restoreCheckpoint: () => Effect.succeed(true),
|
||||
diffCheckpoints: ({ fromCheckpointRef, toCheckpointRef, cwd, ignoreWhitespace }) =>
|
||||
Effect.sync(() => {
|
||||
diffCheckpointsCalls.push({
|
||||
fromCheckpointRef,
|
||||
toCheckpointRef,
|
||||
cwd,
|
||||
ignoreWhitespace,
|
||||
});
|
||||
return "diff patch";
|
||||
}),
|
||||
deleteCheckpointRefs: () => Effect.void,
|
||||
};
|
||||
|
||||
const layer = CheckpointDiffQueryLive.pipe(
|
||||
Layer.provideMerge(Layer.succeed(CheckpointStore, checkpointStore)),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(ProjectionSnapshotQuery, {
|
||||
getCommandReadModel: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the command read model"),
|
||||
getSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
|
||||
getShellSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
|
||||
getArchivedShellSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request archived shell snapshots"),
|
||||
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
|
||||
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
||||
getProjectShellById: () => Effect.succeed(Option.none()),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
|
||||
getThreadCheckpointContext: () => Effect.succeed(Option.some(threadCheckpointContext)),
|
||||
getFullThreadDiffContext: () => Effect.die("unused"),
|
||||
getThreadShellById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailById: () => Effect.succeed(Option.none()),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const result = await Effect.runPromise(
|
||||
Effect.gen(function* () {
|
||||
const query = yield* CheckpointDiffQuery;
|
||||
return yield* query.getTurnDiff({
|
||||
threadId,
|
||||
fromTurnCount: 0,
|
||||
toTurnCount: 1,
|
||||
ignoreWhitespace: true,
|
||||
});
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
|
||||
const expectedFromRef = checkpointRefForThreadTurn(threadId, 0);
|
||||
expect(diffCheckpointsCalls).toEqual([
|
||||
{
|
||||
cwd: "/tmp/workspace",
|
||||
fromCheckpointRef: expectedFromRef,
|
||||
toCheckpointRef,
|
||||
ignoreWhitespace: true,
|
||||
},
|
||||
]);
|
||||
expect(result).toEqual({
|
||||
threadId,
|
||||
fromTurnCount: 0,
|
||||
toTurnCount: 1,
|
||||
diff: "diff patch",
|
||||
});
|
||||
});
|
||||
|
||||
it("defaults to hide whitespace changes", async () => {
|
||||
const projectId = ProjectId.make("project-default-whitespace");
|
||||
const threadId = ThreadId.make("thread-default-whitespace");
|
||||
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
|
||||
const diffCheckpointsCalls: Array<{ readonly ignoreWhitespace: boolean }> = [];
|
||||
|
||||
const threadCheckpointContext = makeThreadCheckpointContext({
|
||||
projectId,
|
||||
threadId,
|
||||
workspaceRoot: "/tmp/workspace",
|
||||
worktreePath: null,
|
||||
checkpointTurnCount: 1,
|
||||
checkpointRef: toCheckpointRef,
|
||||
});
|
||||
|
||||
const checkpointStore: CheckpointStoreShape = {
|
||||
isGitRepository: () => Effect.succeed(true),
|
||||
captureCheckpoint: () => Effect.void,
|
||||
hasCheckpointRef: () => Effect.succeed(true),
|
||||
restoreCheckpoint: () => Effect.succeed(true),
|
||||
diffCheckpoints: ({ ignoreWhitespace }) =>
|
||||
Effect.sync(() => {
|
||||
diffCheckpointsCalls.push({ ignoreWhitespace });
|
||||
return "diff patch";
|
||||
}),
|
||||
deleteCheckpointRefs: () => Effect.void,
|
||||
};
|
||||
|
||||
const layer = CheckpointDiffQueryLive.pipe(
|
||||
Layer.provideMerge(Layer.succeed(CheckpointStore, checkpointStore)),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(ProjectionSnapshotQuery, {
|
||||
getCommandReadModel: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the command read model"),
|
||||
getSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
|
||||
getShellSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
|
||||
getArchivedShellSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request archived shell snapshots"),
|
||||
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
|
||||
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
||||
getProjectShellById: () => Effect.succeed(Option.none()),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
|
||||
getThreadCheckpointContext: () => Effect.succeed(Option.some(threadCheckpointContext)),
|
||||
getFullThreadDiffContext: () => Effect.die("unused"),
|
||||
getThreadShellById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailById: () => Effect.succeed(Option.none()),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
await Effect.runPromise(
|
||||
Effect.gen(function* () {
|
||||
const query = yield* CheckpointDiffQuery;
|
||||
return yield* query.getTurnDiff({
|
||||
threadId,
|
||||
fromTurnCount: 0,
|
||||
toTurnCount: 1,
|
||||
});
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
|
||||
expect(diffCheckpointsCalls).toEqual([{ ignoreWhitespace: true }]);
|
||||
});
|
||||
|
||||
it("does not preflight checkpoint refs before diffing", async () => {
|
||||
const projectId = ProjectId.make("project-no-preflight");
|
||||
const threadId = ThreadId.make("thread-no-preflight");
|
||||
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
|
||||
let hasCheckpointRefCallCount = 0;
|
||||
|
||||
const threadCheckpointContext = makeThreadCheckpointContext({
|
||||
projectId,
|
||||
threadId,
|
||||
workspaceRoot: "/tmp/workspace",
|
||||
worktreePath: null,
|
||||
checkpointTurnCount: 1,
|
||||
checkpointRef: toCheckpointRef,
|
||||
});
|
||||
|
||||
const checkpointStore: CheckpointStoreShape = {
|
||||
isGitRepository: () => Effect.succeed(true),
|
||||
captureCheckpoint: () => Effect.void,
|
||||
hasCheckpointRef: () =>
|
||||
Effect.sync(() => {
|
||||
hasCheckpointRefCallCount += 1;
|
||||
return true;
|
||||
}),
|
||||
restoreCheckpoint: () => Effect.succeed(true),
|
||||
diffCheckpoints: () => Effect.succeed("diff patch"),
|
||||
deleteCheckpointRefs: () => Effect.void,
|
||||
};
|
||||
|
||||
const layer = CheckpointDiffQueryLive.pipe(
|
||||
Layer.provideMerge(Layer.succeed(CheckpointStore, checkpointStore)),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(ProjectionSnapshotQuery, {
|
||||
getCommandReadModel: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the command read model"),
|
||||
getSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
|
||||
getShellSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
|
||||
getArchivedShellSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request archived shell snapshots"),
|
||||
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
|
||||
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
||||
getProjectShellById: () => Effect.succeed(Option.none()),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
|
||||
getThreadCheckpointContext: () => Effect.succeed(Option.some(threadCheckpointContext)),
|
||||
getFullThreadDiffContext: () => Effect.die("unused"),
|
||||
getThreadShellById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailById: () => Effect.succeed(Option.none()),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
await Effect.runPromise(
|
||||
Effect.gen(function* () {
|
||||
const query = yield* CheckpointDiffQuery;
|
||||
return yield* query.getTurnDiff({
|
||||
threadId,
|
||||
fromTurnCount: 0,
|
||||
toTurnCount: 1,
|
||||
ignoreWhitespace: true,
|
||||
});
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
|
||||
expect(hasCheckpointRefCallCount).toBe(0);
|
||||
});
|
||||
|
||||
it("fails when the thread is missing from the snapshot", async () => {
|
||||
const threadId = ThreadId.make("thread-missing");
|
||||
|
||||
const checkpointStore: CheckpointStoreShape = {
|
||||
isGitRepository: () => Effect.succeed(true),
|
||||
captureCheckpoint: () => Effect.void,
|
||||
hasCheckpointRef: () => Effect.succeed(true),
|
||||
restoreCheckpoint: () => Effect.succeed(true),
|
||||
diffCheckpoints: () => Effect.succeed(""),
|
||||
deleteCheckpointRefs: () => Effect.void,
|
||||
};
|
||||
|
||||
const layer = CheckpointDiffQueryLive.pipe(
|
||||
Layer.provideMerge(Layer.succeed(CheckpointStore, checkpointStore)),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(ProjectionSnapshotQuery, {
|
||||
getCommandReadModel: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the command read model"),
|
||||
getSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
|
||||
getShellSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
|
||||
getArchivedShellSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request archived shell snapshots"),
|
||||
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
|
||||
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
||||
getProjectShellById: () => Effect.succeed(Option.none()),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
|
||||
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
|
||||
getFullThreadDiffContext: () => Effect.succeed(Option.none()),
|
||||
getThreadShellById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailById: () => Effect.succeed(Option.none()),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
await expect(
|
||||
Effect.runPromise(
|
||||
Effect.gen(function* () {
|
||||
const query = yield* CheckpointDiffQuery;
|
||||
return yield* query.getTurnDiff({
|
||||
threadId,
|
||||
fromTurnCount: 0,
|
||||
toTurnCount: 1,
|
||||
});
|
||||
}).pipe(Effect.provide(layer)),
|
||||
),
|
||||
).rejects.toThrow("Thread 'thread-missing' not found.");
|
||||
});
|
||||
});
|
||||
@@ -1,89 +0,0 @@
|
||||
/**
|
||||
* CheckpointStoreLive - Filesystem checkpoint store adapter layer.
|
||||
*
|
||||
* Resolves the active VCS driver once per checkpoint operation and delegates
|
||||
* checkpoint-specific behavior to the driver's optional checkpoint capability.
|
||||
*
|
||||
* @module CheckpointStoreLive
|
||||
*/
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
|
||||
import { CheckpointStore, type CheckpointStoreShape } from "../Services/CheckpointStore.ts";
|
||||
import { VcsUnsupportedOperationError } from "@t3tools/contracts";
|
||||
import { VcsDriverRegistry } from "../../vcs/VcsDriverRegistry.ts";
|
||||
import type { VcsCheckpointOps } from "../../vcs/VcsDriver.ts";
|
||||
|
||||
const makeCheckpointStore = Effect.gen(function* () {
|
||||
const vcsRegistry = yield* VcsDriverRegistry;
|
||||
|
||||
const resolveCheckpoints = Effect.fn("CheckpointStore.resolveCheckpoints")(function* (
|
||||
operation: string,
|
||||
cwd: string,
|
||||
) {
|
||||
const handle = yield* vcsRegistry.resolve({ cwd });
|
||||
if (!handle.driver.checkpoints) {
|
||||
return yield* new VcsUnsupportedOperationError({
|
||||
operation,
|
||||
kind: handle.kind,
|
||||
detail: `${handle.kind} driver does not implement checkpoint operations.`,
|
||||
});
|
||||
}
|
||||
return handle.driver.checkpoints satisfies VcsCheckpointOps;
|
||||
});
|
||||
|
||||
const isGitRepository: CheckpointStoreShape["isGitRepository"] = (cwd) =>
|
||||
vcsRegistry.resolve({ cwd, requestedKind: "git" }).pipe(
|
||||
Effect.map(() => true),
|
||||
Effect.orElseSucceed(() => false),
|
||||
);
|
||||
|
||||
const captureCheckpoint: CheckpointStoreShape["captureCheckpoint"] = Effect.fn(
|
||||
"captureCheckpoint",
|
||||
)(function* (input) {
|
||||
const checkpoints = yield* resolveCheckpoints("CheckpointStore.captureCheckpoint", input.cwd);
|
||||
return yield* checkpoints.captureCheckpoint(input);
|
||||
});
|
||||
|
||||
const hasCheckpointRef: CheckpointStoreShape["hasCheckpointRef"] = Effect.fn("hasCheckpointRef")(
|
||||
function* (input) {
|
||||
const checkpoints = yield* resolveCheckpoints("CheckpointStore.hasCheckpointRef", input.cwd);
|
||||
return yield* checkpoints.hasCheckpointRef(input);
|
||||
},
|
||||
);
|
||||
|
||||
const restoreCheckpoint: CheckpointStoreShape["restoreCheckpoint"] = Effect.fn(
|
||||
"restoreCheckpoint",
|
||||
)(function* (input) {
|
||||
const checkpoints = yield* resolveCheckpoints("CheckpointStore.restoreCheckpoint", input.cwd);
|
||||
return yield* checkpoints.restoreCheckpoint(input);
|
||||
});
|
||||
|
||||
const diffCheckpoints: CheckpointStoreShape["diffCheckpoints"] = Effect.fn("diffCheckpoints")(
|
||||
function* (input) {
|
||||
const checkpoints = yield* resolveCheckpoints("CheckpointStore.diffCheckpoints", input.cwd);
|
||||
return yield* checkpoints.diffCheckpoints(input);
|
||||
},
|
||||
);
|
||||
|
||||
const deleteCheckpointRefs: CheckpointStoreShape["deleteCheckpointRefs"] = Effect.fn(
|
||||
"deleteCheckpointRefs",
|
||||
)(function* (input) {
|
||||
const checkpoints = yield* resolveCheckpoints(
|
||||
"CheckpointStore.deleteCheckpointRefs",
|
||||
input.cwd,
|
||||
);
|
||||
return yield* checkpoints.deleteCheckpointRefs(input);
|
||||
});
|
||||
|
||||
return {
|
||||
isGitRepository,
|
||||
captureCheckpoint,
|
||||
hasCheckpointRef,
|
||||
restoreCheckpoint,
|
||||
diffCheckpoints,
|
||||
deleteCheckpointRefs,
|
||||
} satisfies CheckpointStoreShape;
|
||||
});
|
||||
|
||||
export const CheckpointStoreLive = Layer.effect(CheckpointStore, makeCheckpointStore);
|
||||
@@ -1,49 +0,0 @@
|
||||
/**
|
||||
* CheckpointDiffQuery - Query interface for computed checkpoint diffs.
|
||||
*
|
||||
* Provides read-only diff operations across checkpoint snapshots used by
|
||||
* orchestration APIs.
|
||||
*
|
||||
* @module CheckpointDiffQuery
|
||||
*/
|
||||
import type {
|
||||
OrchestrationGetFullThreadDiffInput,
|
||||
OrchestrationGetFullThreadDiffResult,
|
||||
OrchestrationGetTurnDiffInput,
|
||||
OrchestrationGetTurnDiffResult,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import type * as Effect from "effect/Effect";
|
||||
|
||||
import type { CheckpointServiceError } from "../Errors.ts";
|
||||
|
||||
/**
|
||||
* CheckpointDiffQueryShape - Service API for checkpoint diff queries.
|
||||
*/
|
||||
export interface CheckpointDiffQueryShape {
|
||||
/**
|
||||
* Read the patch diff for a single turn checkpoint transition.
|
||||
*
|
||||
* Verifies checkpoint availability in both projection state and filesystem.
|
||||
*/
|
||||
readonly getTurnDiff: (
|
||||
input: OrchestrationGetTurnDiffInput,
|
||||
) => Effect.Effect<OrchestrationGetTurnDiffResult, CheckpointServiceError>;
|
||||
|
||||
/**
|
||||
* Read the full patch diff across a thread range of checkpoints.
|
||||
*
|
||||
* Delegates to turn diff with `fromTurnCount = 0`.
|
||||
*/
|
||||
readonly getFullThreadDiff: (
|
||||
input: OrchestrationGetFullThreadDiffInput,
|
||||
) => Effect.Effect<OrchestrationGetFullThreadDiffResult, CheckpointServiceError>;
|
||||
}
|
||||
|
||||
/**
|
||||
* CheckpointDiffQuery - Service tag for checkpoint diff queries.
|
||||
*/
|
||||
export class CheckpointDiffQuery extends Context.Service<
|
||||
CheckpointDiffQuery,
|
||||
CheckpointDiffQueryShape
|
||||
>()("t3/checkpointing/Services/CheckpointDiffQuery") {}
|
||||
@@ -1,101 +0,0 @@
|
||||
/**
|
||||
* CheckpointStore - Repository interface for filesystem-backed workspace checkpoints.
|
||||
*
|
||||
* Owns hidden Git-ref checkpoint capture/restore and diff computation for a
|
||||
* workspace thread timeline. It does not store user-facing checkpoint metadata
|
||||
* and does not coordinate provider conversation rollback.
|
||||
*
|
||||
* Uses Effect `Context.Service` for dependency injection and exposes typed
|
||||
* domain errors for checkpoint storage operations.
|
||||
*
|
||||
* @module CheckpointStore
|
||||
*/
|
||||
import * as Context from "effect/Context";
|
||||
import type * as Effect from "effect/Effect";
|
||||
|
||||
import type { CheckpointStoreError } from "../Errors.ts";
|
||||
import { CheckpointRef } from "@t3tools/contracts";
|
||||
|
||||
export interface CaptureCheckpointInput {
|
||||
readonly cwd: string;
|
||||
readonly checkpointRef: CheckpointRef;
|
||||
}
|
||||
|
||||
export interface RestoreCheckpointInput {
|
||||
readonly cwd: string;
|
||||
readonly checkpointRef: CheckpointRef;
|
||||
readonly fallbackToHead?: boolean;
|
||||
}
|
||||
|
||||
export interface DiffCheckpointsInput {
|
||||
readonly cwd: string;
|
||||
readonly fromCheckpointRef: CheckpointRef;
|
||||
readonly toCheckpointRef: CheckpointRef;
|
||||
readonly fallbackFromToHead?: boolean;
|
||||
readonly ignoreWhitespace: boolean;
|
||||
}
|
||||
|
||||
export interface DeleteCheckpointRefsInput {
|
||||
readonly cwd: string;
|
||||
readonly checkpointRefs: ReadonlyArray<CheckpointRef>;
|
||||
}
|
||||
|
||||
/**
|
||||
* CheckpointStoreShape - Service API for checkpoint capture/restore and diff access.
|
||||
*/
|
||||
export interface CheckpointStoreShape {
|
||||
/**
|
||||
* Check whether cwd is inside a Git worktree.
|
||||
*/
|
||||
readonly isGitRepository: (cwd: string) => Effect.Effect<boolean, CheckpointStoreError>;
|
||||
|
||||
/**
|
||||
* Capture a checkpoint commit and store it at the provided checkpoint ref.
|
||||
*
|
||||
* Uses an isolated temporary Git index and writes a hidden ref.
|
||||
*/
|
||||
readonly captureCheckpoint: (
|
||||
input: CaptureCheckpointInput,
|
||||
) => Effect.Effect<void, CheckpointStoreError>;
|
||||
|
||||
/**
|
||||
* Check whether a checkpoint ref exists.
|
||||
*/
|
||||
readonly hasCheckpointRef: (
|
||||
input: Omit<RestoreCheckpointInput, "fallbackToHead">,
|
||||
) => Effect.Effect<boolean, CheckpointStoreError>;
|
||||
|
||||
/**
|
||||
* Restore workspace/staging state to a checkpoint.
|
||||
*
|
||||
* Optionally falls back to current `HEAD` when the checkpoint ref is missing.
|
||||
*/
|
||||
readonly restoreCheckpoint: (
|
||||
input: RestoreCheckpointInput,
|
||||
) => Effect.Effect<boolean, CheckpointStoreError>;
|
||||
|
||||
/**
|
||||
* Compute patch diff between two checkpoint refs.
|
||||
*
|
||||
* Can optionally treat missing "from" ref as `HEAD`.
|
||||
*/
|
||||
readonly diffCheckpoints: (
|
||||
input: DiffCheckpointsInput,
|
||||
) => Effect.Effect<string, CheckpointStoreError>;
|
||||
|
||||
/**
|
||||
* Delete the provided checkpoint refs.
|
||||
*
|
||||
* Best-effort delete: missing refs are tolerated.
|
||||
*/
|
||||
readonly deleteCheckpointRefs: (
|
||||
input: DeleteCheckpointRefsInput,
|
||||
) => Effect.Effect<void, CheckpointStoreError>;
|
||||
}
|
||||
|
||||
/**
|
||||
* CheckpointStore - Service tag for checkpoint persistence and restore operations.
|
||||
*/
|
||||
export class CheckpointStore extends Context.Service<CheckpointStore, CheckpointStoreShape>()(
|
||||
"t3/checkpointing/Services/CheckpointStore",
|
||||
) {}
|
||||
@@ -6,7 +6,6 @@ import * as Clock from "effect/Clock";
|
||||
import * as Console from "effect/Console";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
@@ -15,10 +14,12 @@ import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import * as HttpClient from "effect/unstable/http/HttpClient";
|
||||
import * as HttpClientRequest from "effect/unstable/http/HttpClientRequest";
|
||||
import * as HttpClientResponse from "effect/unstable/http/HttpClientResponse";
|
||||
import * as HttpRouter from "effect/unstable/http/HttpRouter";
|
||||
import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
|
||||
import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";
|
||||
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
|
||||
|
||||
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
|
||||
import { cloudCliOAuthConfig, type CloudCliOAuthConfig } from "./publicConfig.ts";
|
||||
@@ -45,35 +46,74 @@ const OAuthTokenResponse = Schema.Struct({
|
||||
token_type: Schema.String,
|
||||
});
|
||||
|
||||
export class CloudCliTokenManagerError extends Data.TaggedError("CloudCliTokenManagerError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
export interface CloudCliTokenManagerShape {
|
||||
readonly get: Effect.Effect<PersistedToken, CloudCliTokenManagerError>;
|
||||
readonly getExisting: Effect.Effect<Option.Option<PersistedToken>, CloudCliTokenManagerError>;
|
||||
readonly hasCredential: Effect.Effect<boolean, CloudCliTokenManagerError>;
|
||||
readonly clear: Effect.Effect<void, CloudCliTokenManagerError>;
|
||||
export class CloudCliCredentialRemovalError extends Schema.TaggedErrorClass<CloudCliCredentialRemovalError>()(
|
||||
"CloudCliCredentialRemovalError",
|
||||
{ cause: Schema.Defect() },
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Could not remove the stored T3 Connect CLI credential.";
|
||||
}
|
||||
}
|
||||
|
||||
export class CloudCliCredentialRefreshError extends Schema.TaggedErrorClass<CloudCliCredentialRefreshError>()(
|
||||
"CloudCliCredentialRefreshError",
|
||||
{ cause: Schema.Defect() },
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Could not refresh the T3 Connect CLI credential.";
|
||||
}
|
||||
}
|
||||
|
||||
export class CloudCliCredentialReadError extends Schema.TaggedErrorClass<CloudCliCredentialReadError>()(
|
||||
"CloudCliCredentialReadError",
|
||||
{ cause: Schema.Defect() },
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Could not read the stored T3 Connect CLI credential.";
|
||||
}
|
||||
}
|
||||
|
||||
export class CloudCliAuthorizationError extends Schema.TaggedErrorClass<CloudCliAuthorizationError>()(
|
||||
"CloudCliAuthorizationError",
|
||||
{ cause: Schema.Defect() },
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Could not authorize the T3 Connect CLI.";
|
||||
}
|
||||
}
|
||||
|
||||
export class CloudCliAuthorizationTimeoutError extends Schema.TaggedErrorClass<CloudCliAuthorizationTimeoutError>()(
|
||||
"CloudCliAuthorizationTimeoutError",
|
||||
{ cause: Schema.Defect() },
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Timed out waiting for T3 Connect authorization.";
|
||||
}
|
||||
}
|
||||
|
||||
export const CloudCliTokenManagerError = Schema.Union([
|
||||
CloudCliCredentialRemovalError,
|
||||
CloudCliCredentialRefreshError,
|
||||
CloudCliCredentialReadError,
|
||||
CloudCliAuthorizationError,
|
||||
CloudCliAuthorizationTimeoutError,
|
||||
]);
|
||||
export type CloudCliTokenManagerError = typeof CloudCliTokenManagerError.Type;
|
||||
|
||||
export class CloudCliTokenManager extends Context.Service<
|
||||
CloudCliTokenManager,
|
||||
CloudCliTokenManagerShape
|
||||
{
|
||||
readonly get: Effect.Effect<PersistedToken, CloudCliTokenManagerError>;
|
||||
readonly getExisting: Effect.Effect<Option.Option<PersistedToken>, CloudCliTokenManagerError>;
|
||||
readonly hasCredential: Effect.Effect<boolean, CloudCliTokenManagerError>;
|
||||
readonly clear: Effect.Effect<void, CloudCliTokenManagerError>;
|
||||
}
|
||||
>()("t3/cloud/CliTokenManager/CloudCliTokenManager") {}
|
||||
|
||||
const wrapError =
|
||||
(message: string) =>
|
||||
<A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, CloudCliTokenManagerError, R> =>
|
||||
effect.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new CloudCliTokenManagerError({
|
||||
message,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
<WrappedError extends CloudCliTokenManagerError>(makeError: (cause: unknown) => WrappedError) =>
|
||||
<A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, WrappedError, R> =>
|
||||
effect.pipe(Effect.mapError(makeError));
|
||||
|
||||
function stringToBytes(value: string): Uint8Array {
|
||||
return new TextEncoder().encode(value);
|
||||
@@ -83,7 +123,7 @@ function bytesToString(value: Uint8Array): string {
|
||||
return new TextDecoder().decode(value);
|
||||
}
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
export const make = Effect.gen(function* () {
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const httpClient = (yield* HttpClient.HttpClient).pipe(HttpClient.filterStatusOk);
|
||||
const secrets = yield* ServerSecretStore.ServerSecretStore;
|
||||
@@ -96,7 +136,7 @@ const make = Effect.gen(function* () {
|
||||
|
||||
const clear = secrets
|
||||
.remove(CLOUD_CLI_OAUTH_TOKEN_SECRET)
|
||||
.pipe(wrapError("Could not remove the stored T3 Connect CLI credential."));
|
||||
.pipe(wrapError((cause) => new CloudCliCredentialRemovalError({ cause })));
|
||||
|
||||
const read = Effect.fn("cloud.cli_token.read")(function* () {
|
||||
const encoded = yield* secrets.get(CLOUD_CLI_OAUTH_TOKEN_SECRET);
|
||||
@@ -185,10 +225,10 @@ const make = Effect.gen(function* () {
|
||||
yield* Console.log(`Open this URL to authorize T3 Connect:\n${authorizationUrl.toString()}\n`);
|
||||
const code = yield* Deferred.await(callback).pipe(
|
||||
Effect.timeout(CLOUD_CLI_OAUTH_CALLBACK_TIMEOUT),
|
||||
Effect.catchTag("TimeoutError", () =>
|
||||
Effect.catchTag("TimeoutError", (cause) =>
|
||||
Effect.fail(
|
||||
new CloudCliTokenManagerError({
|
||||
message: "Timed out waiting for T3 Connect authorization.",
|
||||
new CloudCliAuthorizationTimeoutError({
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
@@ -213,12 +253,12 @@ const make = Effect.gen(function* () {
|
||||
});
|
||||
|
||||
const getExisting = semaphore.withPermits(1)(
|
||||
getExistingNoLock().pipe(wrapError("Could not refresh the T3 Connect CLI credential.")),
|
||||
getExistingNoLock().pipe(wrapError((cause) => new CloudCliCredentialRefreshError({ cause }))),
|
||||
);
|
||||
const hasCredential = semaphore.withPermits(1)(
|
||||
read().pipe(
|
||||
Effect.map(Option.isSome),
|
||||
wrapError("Could not read the stored T3 Connect CLI credential."),
|
||||
wrapError((cause) => new CloudCliCredentialReadError({ cause })),
|
||||
),
|
||||
);
|
||||
const get = semaphore.withPermits(1)(
|
||||
@@ -227,7 +267,7 @@ const make = Effect.gen(function* () {
|
||||
return Option.isSome(token)
|
||||
? token.value
|
||||
: yield* Effect.scoped(login()).pipe(Effect.flatMap(persist));
|
||||
}).pipe(wrapError("Could not authorize the T3 Connect CLI.")),
|
||||
}).pipe(wrapError((cause) => new CloudCliAuthorizationError({ cause }))),
|
||||
);
|
||||
|
||||
return CloudCliTokenManager.of({ get, getExisting, hasCredential, clear });
|
||||
|
||||
@@ -4,16 +4,15 @@ import * as Deferred from "effect/Deferred";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Sink from "effect/Sink";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
import * as RelayClient from "@t3tools/shared/relayClient";
|
||||
|
||||
import {
|
||||
classifyRelayClientOutput,
|
||||
makeCloudManagedEndpointRuntime,
|
||||
} from "./ManagedEndpointRuntime.ts";
|
||||
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
|
||||
import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts";
|
||||
|
||||
const relayClientAvailableLayer = Layer.succeed(
|
||||
RelayClient.RelayClient,
|
||||
@@ -29,12 +28,33 @@ const relayClientAvailableLayer = Layer.succeed(
|
||||
}),
|
||||
);
|
||||
|
||||
const runtimeDependencies = (spawner: ReturnType<typeof ChildProcessSpawner.make>) =>
|
||||
const runtimeDependencies = (
|
||||
spawner: ReturnType<typeof ChildProcessSpawner.make>,
|
||||
relayClientLayer = relayClientAvailableLayer,
|
||||
) =>
|
||||
Layer.mergeAll(
|
||||
Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||
relayClientAvailableLayer,
|
||||
relayClientLayer,
|
||||
Layer.mock(ServerSecretStore.ServerSecretStore)({
|
||||
get: () => Effect.succeed(Option.none()),
|
||||
}),
|
||||
);
|
||||
|
||||
const buildCloudManagedEndpointRuntime = (
|
||||
spawner: ReturnType<typeof ChildProcessSpawner.make>,
|
||||
relayClientLayer = relayClientAvailableLayer,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const context = yield* Layer.build(
|
||||
ManagedEndpointRuntime.layer.pipe(
|
||||
Layer.provide(runtimeDependencies(spawner, relayClientLayer)),
|
||||
),
|
||||
);
|
||||
return yield* Effect.service(ManagedEndpointRuntime.CloudManagedEndpointRuntime).pipe(
|
||||
Effect.provide(context),
|
||||
);
|
||||
});
|
||||
|
||||
function makeHandle(input: {
|
||||
readonly pid: number;
|
||||
readonly onKill: () => void;
|
||||
@@ -62,16 +82,20 @@ function makeHandle(input: {
|
||||
describe("CloudManagedEndpointRuntime", () => {
|
||||
it("classifies Cloudflare connection and warning output", () => {
|
||||
expect(
|
||||
classifyRelayClientOutput(
|
||||
ManagedEndpointRuntime.classifyRelayClientOutput(
|
||||
"2026-06-17T02:00:00Z INF Registered tunnel connection connIndex=0",
|
||||
),
|
||||
).toBe("connected");
|
||||
expect(
|
||||
classifyRelayClientOutput("2026-06-17T02:00:00Z ERR Failed to serve tunnel connection"),
|
||||
ManagedEndpointRuntime.classifyRelayClientOutput(
|
||||
"2026-06-17T02:00:00Z ERR Failed to serve tunnel connection",
|
||||
),
|
||||
).toBe("warning");
|
||||
expect(classifyRelayClientOutput("2026-06-17T02:00:00Z INF Starting metrics server")).toBe(
|
||||
"debug",
|
||||
);
|
||||
expect(
|
||||
ManagedEndpointRuntime.classifyRelayClientOutput(
|
||||
"2026-06-17T02:00:00Z INF Starting metrics server",
|
||||
),
|
||||
).toBe("debug");
|
||||
});
|
||||
|
||||
it.effect("starts, deduplicates, rotates, and stops the Cloudflare connector", () =>
|
||||
@@ -97,9 +121,7 @@ describe("CloudManagedEndpointRuntime", () => {
|
||||
return handle;
|
||||
}),
|
||||
);
|
||||
const runtime = yield* makeCloudManagedEndpointRuntime.pipe(
|
||||
Effect.provide(runtimeDependencies(spawner)),
|
||||
);
|
||||
const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
|
||||
|
||||
yield* runtime.applyConfig({
|
||||
providerKind: "cloudflare_tunnel",
|
||||
@@ -154,9 +176,7 @@ describe("CloudManagedEndpointRuntime", () => {
|
||||
return handle;
|
||||
}),
|
||||
);
|
||||
const runtime = yield* makeCloudManagedEndpointRuntime.pipe(
|
||||
Effect.provide(runtimeDependencies(spawner)),
|
||||
);
|
||||
const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
|
||||
|
||||
const started = yield* runtime.applyConfig({
|
||||
providerKind: "cloudflare_tunnel",
|
||||
@@ -193,9 +213,7 @@ describe("CloudManagedEndpointRuntime", () => {
|
||||
return handle;
|
||||
}),
|
||||
);
|
||||
const runtime = yield* makeCloudManagedEndpointRuntime.pipe(
|
||||
Effect.provide(runtimeDependencies(spawner)),
|
||||
);
|
||||
const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
|
||||
const config = {
|
||||
providerKind: "cloudflare_tunnel" as const,
|
||||
connectorToken: "token",
|
||||
@@ -240,9 +258,7 @@ describe("CloudManagedEndpointRuntime", () => {
|
||||
return handle;
|
||||
}),
|
||||
);
|
||||
const runtime = yield* makeCloudManagedEndpointRuntime.pipe(
|
||||
Effect.provide(runtimeDependencies(spawner)),
|
||||
);
|
||||
const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
|
||||
|
||||
const started = yield* runtime.applyConfig({
|
||||
providerKind: "cloudflare_tunnel",
|
||||
@@ -282,9 +298,7 @@ describe("CloudManagedEndpointRuntime", () => {
|
||||
return handle;
|
||||
}),
|
||||
);
|
||||
const runtime = yield* makeCloudManagedEndpointRuntime.pipe(
|
||||
Effect.provide(runtimeDependencies(spawner)),
|
||||
);
|
||||
const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
|
||||
|
||||
const first = yield* runtime
|
||||
.applyConfig({
|
||||
@@ -322,9 +336,7 @@ describe("CloudManagedEndpointRuntime", () => {
|
||||
}),
|
||||
),
|
||||
);
|
||||
const runtime = yield* makeCloudManagedEndpointRuntime.pipe(
|
||||
Effect.provide(runtimeDependencies(spawner)),
|
||||
);
|
||||
const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
|
||||
|
||||
const status = yield* runtime.applyConfig({
|
||||
providerKind: "cloudflare_tunnel",
|
||||
@@ -344,22 +356,18 @@ describe("CloudManagedEndpointRuntime", () => {
|
||||
Effect.gen(function* () {
|
||||
const spawn = vi.fn();
|
||||
const spawner = ChildProcessSpawner.make(spawn);
|
||||
const runtime = yield* makeCloudManagedEndpointRuntime.pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||
Layer.succeed(
|
||||
RelayClient.RelayClient,
|
||||
RelayClient.RelayClient.of({
|
||||
resolve: Effect.succeed({
|
||||
status: "missing",
|
||||
version: RelayClient.CLOUDFLARED_VERSION,
|
||||
}),
|
||||
install: Effect.die("unused"),
|
||||
installWithProgress: () => Effect.die("unused"),
|
||||
}),
|
||||
),
|
||||
),
|
||||
const runtime = yield* buildCloudManagedEndpointRuntime(
|
||||
spawner,
|
||||
Layer.succeed(
|
||||
RelayClient.RelayClient,
|
||||
RelayClient.RelayClient.of({
|
||||
resolve: Effect.succeed({
|
||||
status: "missing",
|
||||
version: RelayClient.CLOUDFLARED_VERSION,
|
||||
}),
|
||||
install: Effect.die("unused"),
|
||||
installWithProgress: () => Effect.die("unused"),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
|
||||
@@ -10,7 +10,8 @@ import * as Result from "effect/Result";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
import * as ChildProcess from "effect/unstable/process/ChildProcess";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
|
||||
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
|
||||
import { CLOUD_ENDPOINT_RUNTIME_CONFIG, decodeRuntimeConfig } from "./config.ts";
|
||||
@@ -28,17 +29,6 @@ const readRuntimeConfig = Effect.gen(function* () {
|
||||
return Option.getOrNull(decodeRuntimeConfig(bytesToString(bytes.value)));
|
||||
});
|
||||
|
||||
export interface CloudManagedEndpointRuntimeShape {
|
||||
readonly applyConfig: (
|
||||
config: RelayManagedEndpointRuntimeConfig | null,
|
||||
) => Effect.Effect<CloudManagedEndpointRuntimeStatus>;
|
||||
}
|
||||
|
||||
export class CloudManagedEndpointRuntime extends Context.Service<
|
||||
CloudManagedEndpointRuntime,
|
||||
CloudManagedEndpointRuntimeShape
|
||||
>()("t3/cloud/ManagedEndpointRuntime/CloudManagedEndpointRuntime") {}
|
||||
|
||||
export type CloudManagedEndpointRuntimeStatus =
|
||||
| {
|
||||
readonly status: "disabled";
|
||||
@@ -62,6 +52,15 @@ export type CloudManagedEndpointRuntimeStatus =
|
||||
readonly providerKind: RelayManagedEndpointRuntimeConfig["providerKind"];
|
||||
};
|
||||
|
||||
export class CloudManagedEndpointRuntime extends Context.Service<
|
||||
CloudManagedEndpointRuntime,
|
||||
{
|
||||
readonly applyConfig: (
|
||||
config: RelayManagedEndpointRuntimeConfig | null,
|
||||
) => Effect.Effect<CloudManagedEndpointRuntimeStatus>;
|
||||
}
|
||||
>()("t3/cloud/ManagedEndpointRuntime/CloudManagedEndpointRuntime") {}
|
||||
|
||||
interface ActiveConnector {
|
||||
readonly child: ChildProcessSpawner.ChildProcessHandle;
|
||||
readonly scope: Scope.Closeable;
|
||||
@@ -97,13 +96,13 @@ const stopConnector = (connector: ActiveConnector | null) =>
|
||||
)
|
||||
: Effect.void;
|
||||
|
||||
export const makeCloudManagedEndpointRuntime = Effect.gen(function* () {
|
||||
export const make = Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const relayClient = yield* RelayClient.RelayClient;
|
||||
const activeRef = yield* Ref.make<ActiveConnector | null>(null);
|
||||
const desiredConfigRef = yield* Ref.make<RelayManagedEndpointRuntimeConfig | null>(null);
|
||||
const reconcileSemaphore = yield* Semaphore.make(1);
|
||||
let reconcileConfig: CloudManagedEndpointRuntimeShape["applyConfig"];
|
||||
let reconcileConfig: CloudManagedEndpointRuntime["Service"]["applyConfig"];
|
||||
|
||||
const stopActive = Effect.gen(function* () {
|
||||
const active = yield* Ref.getAndSet(activeRef, null);
|
||||
@@ -301,24 +300,20 @@ export const makeCloudManagedEndpointRuntime = Effect.gen(function* () {
|
||||
),
|
||||
);
|
||||
|
||||
return CloudManagedEndpointRuntime.of({
|
||||
const runtime = CloudManagedEndpointRuntime.of({
|
||||
applyConfig,
|
||||
});
|
||||
|
||||
const initialConfig = yield* readRuntimeConfig.pipe(
|
||||
Effect.catch((cause) =>
|
||||
Effect.logWarning("Failed to read managed endpoint runtime config", { cause }).pipe(
|
||||
Effect.as(null),
|
||||
),
|
||||
),
|
||||
);
|
||||
yield* runtime.applyConfig(initialConfig);
|
||||
yield* Effect.addFinalizer(() => runtime.applyConfig(null));
|
||||
return runtime;
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(
|
||||
CloudManagedEndpointRuntime,
|
||||
Effect.gen(function* () {
|
||||
const runtime = yield* makeCloudManagedEndpointRuntime;
|
||||
const initialConfig = yield* readRuntimeConfig.pipe(
|
||||
Effect.catch((cause) =>
|
||||
Effect.logWarning("Failed to read managed endpoint runtime config", { cause }).pipe(
|
||||
Effect.as(null),
|
||||
),
|
||||
),
|
||||
);
|
||||
yield* runtime.applyConfig(initialConfig);
|
||||
yield* Effect.addFinalizer(() => runtime.applyConfig(null));
|
||||
return runtime;
|
||||
}),
|
||||
);
|
||||
export const layer = Layer.effect(CloudManagedEndpointRuntime, make);
|
||||
@@ -9,13 +9,10 @@ import { HttpClient, HttpServerRequest } from "effect/unstable/http";
|
||||
import { RelayClientTracer } from "@t3tools/shared/relayTracing";
|
||||
import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
|
||||
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
|
||||
import { ServerEnvironment } from "../environment/Services/ServerEnvironment.ts";
|
||||
import * as ServerEnvironment from "../environment/Services/ServerEnvironment.ts";
|
||||
import * as CliTokenManager from "./CliTokenManager.ts";
|
||||
import { consumeCloudReplayGuards, reconcileDesiredCloudLink } from "./http.ts";
|
||||
import {
|
||||
CloudManagedEndpointRuntime,
|
||||
type CloudManagedEndpointRuntimeShape,
|
||||
} from "./ManagedEndpointRuntime.ts";
|
||||
import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts";
|
||||
import { traceAuthenticatedRelayRequest, traceRelayRequest } from "./traceRelayRequest.ts";
|
||||
|
||||
const storeFailure = (tag: "AlreadyExists" | "PermissionDenied") =>
|
||||
@@ -32,8 +29,8 @@ const storeFailure = (tag: "AlreadyExists" | "PermissionDenied") =>
|
||||
const unusedSecretStoreOperation = () => Effect.die("unused secret-store operation");
|
||||
|
||||
function makeSecretStore(
|
||||
create: ServerSecretStore.ServerSecretStoreShape["create"],
|
||||
): ServerSecretStore.ServerSecretStoreShape {
|
||||
create: ServerSecretStore.ServerSecretStore["Service"]["create"],
|
||||
): ServerSecretStore.ServerSecretStore["Service"] {
|
||||
return {
|
||||
get: unusedSecretStoreOperation,
|
||||
set: unusedSecretStoreOperation,
|
||||
@@ -151,21 +148,21 @@ describe("reconcileDesiredCloudLink", () => {
|
||||
makeSecretStore(unusedSecretStoreOperation),
|
||||
),
|
||||
Effect.provideService(
|
||||
ServerEnvironment,
|
||||
ServerEnvironment.of({
|
||||
ServerEnvironment.ServerEnvironment,
|
||||
ServerEnvironment.ServerEnvironment.of({
|
||||
getEnvironmentId: unusedSecretStoreOperation(),
|
||||
getDescriptor: unusedSecretStoreOperation(),
|
||||
}),
|
||||
),
|
||||
Effect.provideService(
|
||||
CloudManagedEndpointRuntime,
|
||||
CloudManagedEndpointRuntime.of({
|
||||
ManagedEndpointRuntime.CloudManagedEndpointRuntime,
|
||||
ManagedEndpointRuntime.CloudManagedEndpointRuntime.of({
|
||||
applyConfig: unusedSecretStoreOperation,
|
||||
} satisfies CloudManagedEndpointRuntimeShape),
|
||||
} satisfies ManagedEndpointRuntime.CloudManagedEndpointRuntime["Service"]),
|
||||
),
|
||||
Effect.provideService(
|
||||
EnvironmentAuth.EnvironmentAuth,
|
||||
EnvironmentAuth.EnvironmentAuth.of({} as EnvironmentAuth.EnvironmentAuthShape),
|
||||
EnvironmentAuth.EnvironmentAuth.of({} as EnvironmentAuth.EnvironmentAuth["Service"]),
|
||||
),
|
||||
Effect.provideService(
|
||||
CliTokenManager.CloudCliTokenManager,
|
||||
|
||||
@@ -55,14 +55,8 @@ import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
|
||||
import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
|
||||
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
|
||||
import { requireEnvironmentScope } from "../auth/http.ts";
|
||||
import {
|
||||
ServerEnvironment,
|
||||
type ServerEnvironmentShape,
|
||||
} from "../environment/Services/ServerEnvironment.ts";
|
||||
import {
|
||||
CloudManagedEndpointRuntime,
|
||||
type CloudManagedEndpointRuntimeShape,
|
||||
} from "./ManagedEndpointRuntime.ts";
|
||||
import * as ServerEnvironment from "../environment/Services/ServerEnvironment.ts";
|
||||
import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts";
|
||||
import {
|
||||
CLOUD_ENDPOINT_RUNTIME_CONFIG,
|
||||
CLOUD_LINKED_USER_ID,
|
||||
@@ -103,6 +97,9 @@ const failEnvironmentCloudInternalError =
|
||||
Effect.flatMap(() => Effect.fail(new EnvironmentHttpInternalServerError({ message }))),
|
||||
);
|
||||
|
||||
const failCloudCliTokenManagerError = (error: CliTokenManager.CloudCliTokenManagerError) =>
|
||||
failEnvironmentCloudInternalError(error.message)(error.cause);
|
||||
|
||||
const requireRelayUrl = relayUrlConfig.pipe(
|
||||
Effect.mapError(
|
||||
() =>
|
||||
@@ -121,7 +118,7 @@ function stringToBytes(value: string): Uint8Array {
|
||||
}
|
||||
|
||||
export function consumeCloudReplayGuards(input: {
|
||||
readonly secrets: ServerSecretStore.ServerSecretStoreShape;
|
||||
readonly secrets: ServerSecretStore.ServerSecretStore["Service"];
|
||||
readonly names: ReadonlyArray<string>;
|
||||
readonly value: Uint8Array;
|
||||
}) {
|
||||
@@ -208,7 +205,7 @@ function validateRelayConfigPayload(
|
||||
}
|
||||
|
||||
function validateLinkedCloudUser(input: {
|
||||
readonly secrets: ServerSecretStore.ServerSecretStoreShape;
|
||||
readonly secrets: ServerSecretStore.ServerSecretStore["Service"];
|
||||
readonly cloudUserId: string;
|
||||
}): Effect.Effect<void, EnvironmentAuth.ServerAuthInternalError | EnvironmentHttpConflictError> {
|
||||
return input.secrets.get(CLOUD_LINKED_USER_ID).pipe(
|
||||
@@ -237,7 +234,7 @@ function validateLinkedCloudUser(input: {
|
||||
}
|
||||
|
||||
function readInstalledCloudUserId(
|
||||
secrets: ServerSecretStore.ServerSecretStoreShape,
|
||||
secrets: ServerSecretStore.ServerSecretStore["Service"],
|
||||
): Effect.Effect<string, EnvironmentAuth.ServerAuthInternalError> {
|
||||
return secrets.get(CLOUD_LINKED_USER_ID).pipe(
|
||||
Effect.mapError(
|
||||
@@ -335,19 +332,19 @@ const decodeCloudHealthProof = Schema.decodeUnknownEffect(RelayCloudEnvironmentH
|
||||
const decodeCloudMintProof = Schema.decodeUnknownEffect(RelayCloudMintCredentialProofPayload);
|
||||
|
||||
interface CloudHttpDependencies {
|
||||
readonly secrets: ServerSecretStore.ServerSecretStoreShape;
|
||||
readonly environment: ServerEnvironmentShape;
|
||||
readonly endpointRuntime: CloudManagedEndpointRuntimeShape;
|
||||
readonly environmentAuth: EnvironmentAuth.EnvironmentAuthShape;
|
||||
readonly cliTokenManager: CliTokenManager.CloudCliTokenManagerShape;
|
||||
readonly secrets: ServerSecretStore.ServerSecretStore["Service"];
|
||||
readonly environment: ServerEnvironment.ServerEnvironment["Service"];
|
||||
readonly endpointRuntime: ManagedEndpointRuntime.CloudManagedEndpointRuntime["Service"];
|
||||
readonly environmentAuth: EnvironmentAuth.EnvironmentAuth["Service"];
|
||||
readonly cliTokenManager: CliTokenManager.CloudCliTokenManager["Service"];
|
||||
readonly httpClient: HttpClient.HttpClient;
|
||||
}
|
||||
|
||||
const cloudHttpDependencies = Effect.gen(function* () {
|
||||
return {
|
||||
secrets: yield* ServerSecretStore.ServerSecretStore,
|
||||
environment: yield* ServerEnvironment,
|
||||
endpointRuntime: yield* CloudManagedEndpointRuntime,
|
||||
environment: yield* ServerEnvironment.ServerEnvironment,
|
||||
endpointRuntime: yield* ManagedEndpointRuntime.CloudManagedEndpointRuntime,
|
||||
environmentAuth: yield* EnvironmentAuth.EnvironmentAuth,
|
||||
cliTokenManager: yield* CliTokenManager.CloudCliTokenManager,
|
||||
httpClient: yield* HttpClient.HttpClient,
|
||||
@@ -595,8 +592,11 @@ const reconcileDesiredCloudLinkWith = Effect.fn("environment.cloud.reconcileDesi
|
||||
});
|
||||
},
|
||||
Effect.catchTags({
|
||||
CloudCliTokenManagerError: (error) =>
|
||||
failEnvironmentCloudInternalError(error.message)(error.cause),
|
||||
CloudCliCredentialRemovalError: failCloudCliTokenManagerError,
|
||||
CloudCliCredentialRefreshError: failCloudCliTokenManagerError,
|
||||
CloudCliCredentialReadError: failCloudCliTokenManagerError,
|
||||
CloudCliAuthorizationError: failCloudCliTokenManagerError,
|
||||
CloudCliAuthorizationTimeoutError: failCloudCliTokenManagerError,
|
||||
SecretStoreError: failEnvironmentCloudInternalError(
|
||||
"Could not persist desired T3 Connect link state.",
|
||||
),
|
||||
|
||||
@@ -12,7 +12,8 @@ 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 { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
import * as ChildProcess from "effect/unstable/process/ChildProcess";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
|
||||
import { collectUint8StreamText } from "../stream/collectUint8StreamText.ts";
|
||||
|
||||
@@ -31,35 +32,80 @@ const PROCESS_QUERY_TIMEOUT_MS = 1_000;
|
||||
const POSIX_PROCESS_QUERY_COMMAND = "pid=,ppid=,pgid=,stat=,pcpu=,rss=,etime=,command=";
|
||||
const PROCESS_QUERY_MAX_OUTPUT_BYTES = 2 * 1024 * 1024;
|
||||
|
||||
export interface ProcessDiagnosticsShape {
|
||||
readonly read: Effect.Effect<ServerProcessDiagnosticsResult>;
|
||||
readonly signal: (input: {
|
||||
readonly pid: number;
|
||||
readonly signal: ServerProcessSignal;
|
||||
}) => Effect.Effect<ServerSignalProcessResult>;
|
||||
}
|
||||
|
||||
export class ProcessDiagnostics extends Context.Service<
|
||||
ProcessDiagnostics,
|
||||
ProcessDiagnosticsShape
|
||||
{
|
||||
readonly read: Effect.Effect<ServerProcessDiagnosticsResult>;
|
||||
readonly signal: (input: {
|
||||
readonly pid: number;
|
||||
readonly signal: ServerProcessSignal;
|
||||
}) => Effect.Effect<ServerSignalProcessResult>;
|
||||
}
|
||||
>()("t3/diagnostics/ProcessDiagnostics") {}
|
||||
|
||||
class ProcessDiagnosticsError extends Schema.TaggedErrorClass<ProcessDiagnosticsError>()(
|
||||
"ProcessDiagnosticsError",
|
||||
class ProcessDiagnosticsQueryTimeoutError extends Schema.TaggedErrorClass<ProcessDiagnosticsQueryTimeoutError>()(
|
||||
"ProcessDiagnosticsQueryTimeoutError",
|
||||
{ command: Schema.String },
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Process diagnostics query '${this.command}' timed out.`;
|
||||
}
|
||||
}
|
||||
|
||||
class ProcessDiagnosticsQueryFailedError extends Schema.TaggedErrorClass<ProcessDiagnosticsQueryFailedError>()(
|
||||
"ProcessDiagnosticsQueryFailedError",
|
||||
{
|
||||
message: Schema.String,
|
||||
command: Schema.String,
|
||||
stderr: Schema.optional(Schema.String),
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {}
|
||||
const isProcessDiagnosticsError = Schema.is(ProcessDiagnosticsError);
|
||||
|
||||
function toProcessDiagnosticsError(message: string, cause?: unknown): ProcessDiagnosticsError {
|
||||
return new ProcessDiagnosticsError({
|
||||
message,
|
||||
...(cause === undefined ? {} : { cause }),
|
||||
});
|
||||
) {
|
||||
override get message(): string {
|
||||
return this.stderr?.trim() || `Failed to query process diagnostics with '${this.command}'.`;
|
||||
}
|
||||
}
|
||||
|
||||
class ProcessDiagnosticsServerProcessSignalError extends Schema.TaggedErrorClass<ProcessDiagnosticsServerProcessSignalError>()(
|
||||
"ProcessDiagnosticsServerProcessSignalError",
|
||||
{ pid: Schema.Number },
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Refusing to signal the T3 server process.";
|
||||
}
|
||||
}
|
||||
|
||||
class ProcessDiagnosticsNotDescendantError extends Schema.TaggedErrorClass<ProcessDiagnosticsNotDescendantError>()(
|
||||
"ProcessDiagnosticsNotDescendantError",
|
||||
{ pid: Schema.Number },
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Process ${this.pid} is not a live descendant of the T3 server.`;
|
||||
}
|
||||
}
|
||||
|
||||
class ProcessDiagnosticsSignalFailedError extends Schema.TaggedErrorClass<ProcessDiagnosticsSignalFailedError>()(
|
||||
"ProcessDiagnosticsSignalFailedError",
|
||||
{
|
||||
pid: Schema.Number,
|
||||
signal: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to signal process ${this.pid} with ${this.signal}.`;
|
||||
}
|
||||
}
|
||||
|
||||
const ProcessDiagnosticsError = Schema.Union([
|
||||
ProcessDiagnosticsQueryTimeoutError,
|
||||
ProcessDiagnosticsQueryFailedError,
|
||||
ProcessDiagnosticsServerProcessSignalError,
|
||||
ProcessDiagnosticsNotDescendantError,
|
||||
ProcessDiagnosticsSignalFailedError,
|
||||
]);
|
||||
type ProcessDiagnosticsError = typeof ProcessDiagnosticsError.Type;
|
||||
const isProcessDiagnosticsError = Schema.is(ProcessDiagnosticsError);
|
||||
|
||||
function parsePositiveInt(value: string): number | null {
|
||||
const parsed = Number.parseInt(value, 10);
|
||||
return Number.isInteger(parsed) && parsed > 0 ? parsed : null;
|
||||
@@ -272,11 +318,7 @@ interface ProcessOutput {
|
||||
}
|
||||
|
||||
const runProcess = Effect.fn("runProcess")(
|
||||
function* (input: {
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly errorMessage: string;
|
||||
}) {
|
||||
function* (input: { readonly command: string; readonly args: ReadonlyArray<string> }) {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
// `ps` and `powershell.exe` are real executables; spawning through cmd.exe
|
||||
// shell mode would re-tokenize the PowerShell `-Command` payload (which
|
||||
@@ -315,14 +357,22 @@ const runProcess = Effect.fn("runProcess")(
|
||||
Effect.timeoutOption(Duration.millis(PROCESS_QUERY_TIMEOUT_MS)),
|
||||
Effect.flatMap((result) =>
|
||||
Option.match(result, {
|
||||
onNone: () => Effect.fail(toProcessDiagnosticsError(`${input.errorMessage} timed out.`)),
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
new ProcessDiagnosticsQueryTimeoutError({
|
||||
command: input.command,
|
||||
}),
|
||||
),
|
||||
onSome: Effect.succeed,
|
||||
}),
|
||||
),
|
||||
Effect.mapError((cause) =>
|
||||
isProcessDiagnosticsError(cause)
|
||||
? cause
|
||||
: toProcessDiagnosticsError(input.errorMessage, cause),
|
||||
: new ProcessDiagnosticsQueryFailedError({
|
||||
command: input.command,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -335,11 +385,15 @@ function readPosixProcessRows(): Effect.Effect<
|
||||
return runProcess({
|
||||
command: "ps",
|
||||
args: ["-axo", POSIX_PROCESS_QUERY_COMMAND],
|
||||
errorMessage: "Failed to query process diagnostics.",
|
||||
}).pipe(
|
||||
Effect.flatMap((result) =>
|
||||
result.exitCode !== 0
|
||||
? Effect.fail(toProcessDiagnosticsError(result.stderr.trim() || "ps failed."))
|
||||
? Effect.fail(
|
||||
new ProcessDiagnosticsQueryFailedError({
|
||||
command: "ps",
|
||||
stderr: result.stderr.trim() || "ps failed.",
|
||||
}),
|
||||
)
|
||||
: Effect.succeed(parsePosixProcessRows(result.stdout)),
|
||||
),
|
||||
);
|
||||
@@ -361,12 +415,14 @@ function readWindowsProcessRows(): Effect.Effect<
|
||||
return runProcess({
|
||||
command: "powershell.exe",
|
||||
args: ["-NoProfile", "-NonInteractive", "-Command", command],
|
||||
errorMessage: "Failed to query process diagnostics.",
|
||||
}).pipe(
|
||||
Effect.flatMap((result) =>
|
||||
result.exitCode !== 0
|
||||
? Effect.fail(
|
||||
toProcessDiagnosticsError(result.stderr.trim() || "PowerShell process query failed."),
|
||||
new ProcessDiagnosticsQueryFailedError({
|
||||
command: "powershell.exe",
|
||||
stderr: result.stderr.trim() || "PowerShell process query failed.",
|
||||
}),
|
||||
)
|
||||
: Effect.succeed(parseWindowsProcessRows(result.stdout)),
|
||||
),
|
||||
@@ -390,7 +446,11 @@ function assertDescendantPid(
|
||||
pid: number,
|
||||
): Effect.Effect<void, ProcessDiagnosticsError, ChildProcessSpawner.ChildProcessSpawner> {
|
||||
if (pid === process.pid) {
|
||||
return Effect.fail(toProcessDiagnosticsError("Refusing to signal the T3 server process."));
|
||||
return Effect.fail(
|
||||
new ProcessDiagnosticsServerProcessSignalError({
|
||||
pid,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return readProcessRows.pipe(
|
||||
@@ -402,16 +462,18 @@ function assertDescendantPid(
|
||||
return descendant
|
||||
? Effect.void
|
||||
: Effect.fail(
|
||||
toProcessDiagnosticsError(`Process ${pid} is not a live descendant of the T3 server.`),
|
||||
new ProcessDiagnosticsNotDescendantError({
|
||||
pid,
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export const make = Effect.fn("makeProcessDiagnostics")(function* () {
|
||||
export const make = Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
|
||||
const read: ProcessDiagnosticsShape["read"] = Effect.gen(function* () {
|
||||
const read: ProcessDiagnostics["Service"]["read"] = Effect.gen(function* () {
|
||||
const readAt = yield* DateTime.now;
|
||||
const rows = yield* readProcessRows.pipe(
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||
@@ -427,7 +489,7 @@ export const make = Effect.fn("makeProcessDiagnostics")(function* () {
|
||||
),
|
||||
);
|
||||
|
||||
const signal: ProcessDiagnosticsShape["signal"] = Effect.fn("ProcessDiagnostics.signal")(
|
||||
const signal: ProcessDiagnostics["Service"]["signal"] = Effect.fn("ProcessDiagnostics.signal")(
|
||||
function* (input) {
|
||||
return yield* assertDescendantPid(input.pid).pipe(
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||
@@ -443,10 +505,11 @@ export const make = Effect.fn("makeProcessDiagnostics")(function* () {
|
||||
};
|
||||
},
|
||||
catch: (cause) =>
|
||||
toProcessDiagnosticsError(
|
||||
`Failed to signal process ${input.pid} with ${input.signal}.`,
|
||||
new ProcessDiagnosticsSignalFailedError({
|
||||
pid: input.pid,
|
||||
signal: input.signal,
|
||||
cause,
|
||||
),
|
||||
}),
|
||||
}),
|
||||
),
|
||||
Effect.catch((error: ProcessDiagnosticsError) =>
|
||||
@@ -464,4 +527,4 @@ export const make = Effect.fn("makeProcessDiagnostics")(function* () {
|
||||
return ProcessDiagnostics.of({ read, signal });
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(ProcessDiagnostics, make());
|
||||
export const layer = Layer.effect(ProcessDiagnostics, make);
|
||||
@@ -3,16 +3,13 @@ import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
|
||||
import {
|
||||
aggregateProcessResourceHistory,
|
||||
collectMonitoredSamples,
|
||||
} from "./ProcessResourceMonitor.ts";
|
||||
import * as ProcessResourceMonitor from "./ProcessResourceMonitor.ts";
|
||||
|
||||
describe("ProcessResourceMonitor", () => {
|
||||
it.effect("samples the server root process and descendants", () =>
|
||||
Effect.sync(() => {
|
||||
const sampledAt = DateTime.makeUnsafe("2026-05-05T10:00:00.000Z");
|
||||
const samples = collectMonitoredSamples({
|
||||
const samples = ProcessResourceMonitor.collectMonitoredSamples({
|
||||
serverPid: 100,
|
||||
sampledAt,
|
||||
sampledAtMs: DateTime.toEpochMillis(sampledAt),
|
||||
@@ -72,7 +69,7 @@ describe("ProcessResourceMonitor", () => {
|
||||
const firstAt = DateTime.makeUnsafe("2026-05-05T10:00:00.000Z");
|
||||
const secondAt = DateTime.makeUnsafe("2026-05-05T10:00:05.000Z");
|
||||
const samples = [
|
||||
...collectMonitoredSamples({
|
||||
...ProcessResourceMonitor.collectMonitoredSamples({
|
||||
serverPid: 100,
|
||||
sampledAt: firstAt,
|
||||
sampledAtMs: DateTime.toEpochMillis(firstAt),
|
||||
@@ -89,7 +86,7 @@ describe("ProcessResourceMonitor", () => {
|
||||
},
|
||||
],
|
||||
}),
|
||||
...collectMonitoredSamples({
|
||||
...ProcessResourceMonitor.collectMonitoredSamples({
|
||||
serverPid: 100,
|
||||
sampledAt: secondAt,
|
||||
sampledAtMs: DateTime.toEpochMillis(secondAt),
|
||||
@@ -108,7 +105,7 @@ describe("ProcessResourceMonitor", () => {
|
||||
}),
|
||||
];
|
||||
|
||||
const result = aggregateProcessResourceHistory({
|
||||
const result = ProcessResourceMonitor.aggregateProcessResourceHistory({
|
||||
samples,
|
||||
readAt: secondAt,
|
||||
readAtMs: DateTime.toEpochMillis(secondAt),
|
||||
@@ -132,7 +129,7 @@ describe("ProcessResourceMonitor", () => {
|
||||
const firstAt = DateTime.makeUnsafe("2026-05-05T10:00:00.400Z");
|
||||
const secondAt = DateTime.makeUnsafe("2026-05-05T10:00:05.900Z");
|
||||
const samples = [
|
||||
...collectMonitoredSamples({
|
||||
...ProcessResourceMonitor.collectMonitoredSamples({
|
||||
serverPid: 100,
|
||||
sampledAt: firstAt,
|
||||
sampledAtMs: DateTime.toEpochMillis(firstAt),
|
||||
@@ -149,7 +146,7 @@ describe("ProcessResourceMonitor", () => {
|
||||
},
|
||||
],
|
||||
}),
|
||||
...collectMonitoredSamples({
|
||||
...ProcessResourceMonitor.collectMonitoredSamples({
|
||||
serverPid: 100,
|
||||
sampledAt: secondAt,
|
||||
sampledAtMs: DateTime.toEpochMillis(secondAt),
|
||||
@@ -168,7 +165,7 @@ describe("ProcessResourceMonitor", () => {
|
||||
}),
|
||||
];
|
||||
|
||||
const result = aggregateProcessResourceHistory({
|
||||
const result = ProcessResourceMonitor.aggregateProcessResourceHistory({
|
||||
samples,
|
||||
readAt: secondAt,
|
||||
readAtMs: DateTime.toEpochMillis(secondAt),
|
||||
@@ -187,7 +184,7 @@ describe("ProcessResourceMonitor", () => {
|
||||
it.effect("returns all process summaries in the selected window", () =>
|
||||
Effect.sync(() => {
|
||||
const sampledAt = DateTime.makeUnsafe("2026-05-05T10:00:00.000Z");
|
||||
const samples = collectMonitoredSamples({
|
||||
const samples = ProcessResourceMonitor.collectMonitoredSamples({
|
||||
serverPid: 100,
|
||||
sampledAt,
|
||||
sampledAtMs: DateTime.toEpochMillis(sampledAt),
|
||||
@@ -215,7 +212,7 @@ describe("ProcessResourceMonitor", () => {
|
||||
],
|
||||
});
|
||||
|
||||
const result = aggregateProcessResourceHistory({
|
||||
const result = ProcessResourceMonitor.aggregateProcessResourceHistory({
|
||||
samples,
|
||||
readAt: sampledAt,
|
||||
readAtMs: DateTime.toEpochMillis(sampledAt),
|
||||
|
||||
@@ -10,14 +10,9 @@ 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 { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
|
||||
import {
|
||||
buildDescendantEntries,
|
||||
isDiagnosticsQueryProcess,
|
||||
type ProcessRow,
|
||||
readProcessRows,
|
||||
} from "./ProcessDiagnostics.ts";
|
||||
import * as ProcessDiagnostics from "./ProcessDiagnostics.ts";
|
||||
|
||||
const SAMPLE_INTERVAL_MS = 5_000;
|
||||
const RETENTION_MS = 60 * 60_000;
|
||||
@@ -41,38 +36,41 @@ interface MonitorState {
|
||||
readonly lastError: string | null;
|
||||
}
|
||||
|
||||
export interface ProcessResourceMonitorShape {
|
||||
readonly readHistory: (
|
||||
input: ServerProcessResourceHistoryInput,
|
||||
) => Effect.Effect<ServerProcessResourceHistoryResult>;
|
||||
}
|
||||
|
||||
export class ProcessResourceMonitor extends Context.Service<
|
||||
ProcessResourceMonitor,
|
||||
ProcessResourceMonitorShape
|
||||
{
|
||||
readonly readHistory: (
|
||||
input: ServerProcessResourceHistoryInput,
|
||||
) => Effect.Effect<ServerProcessResourceHistoryResult>;
|
||||
}
|
||||
>()("t3/diagnostics/ProcessResourceMonitor") {}
|
||||
|
||||
function dateTimeFromMillis(ms: number): DateTime.Utc {
|
||||
return DateTime.makeUnsafe(ms);
|
||||
}
|
||||
|
||||
function sampleKey(row: Pick<ProcessRow, "pid" | "command">): string {
|
||||
function sampleKey(row: Pick<ProcessDiagnostics.ProcessRow, "pid" | "command">): string {
|
||||
return `${row.pid}:${row.command}`;
|
||||
}
|
||||
|
||||
function findServerRootRow(rows: ReadonlyArray<ProcessRow>, serverPid: number): ProcessRow | null {
|
||||
function findServerRootRow(
|
||||
rows: ReadonlyArray<ProcessDiagnostics.ProcessRow>,
|
||||
serverPid: number,
|
||||
): ProcessDiagnostics.ProcessRow | null {
|
||||
return rows.find((row) => row.pid === serverPid) ?? null;
|
||||
}
|
||||
|
||||
export function collectMonitoredSamples(input: {
|
||||
readonly rows: ReadonlyArray<ProcessRow>;
|
||||
readonly rows: ReadonlyArray<ProcessDiagnostics.ProcessRow>;
|
||||
readonly serverPid: number;
|
||||
readonly sampledAt: DateTime.Utc;
|
||||
readonly sampledAtMs: number;
|
||||
}): ReadonlyArray<ProcessResourceSample> {
|
||||
const rows = input.rows.filter((row) => !isDiagnosticsQueryProcess(row, input.serverPid));
|
||||
const rows = input.rows.filter(
|
||||
(row) => !ProcessDiagnostics.isDiagnosticsQueryProcess(row, input.serverPid),
|
||||
);
|
||||
const root = findServerRootRow(rows, input.serverPid);
|
||||
const descendants = buildDescendantEntries(rows, input.serverPid);
|
||||
const descendants = ProcessDiagnostics.buildDescendantEntries(rows, input.serverPid);
|
||||
const samples: ProcessResourceSample[] = [];
|
||||
|
||||
if (root) {
|
||||
@@ -245,14 +243,14 @@ export function aggregateProcessResourceHistory(input: {
|
||||
};
|
||||
}
|
||||
|
||||
export const make = Effect.fn("makeProcessResourceMonitor")(function* () {
|
||||
export const make = Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const state = yield* Ref.make<MonitorState>({ samples: [], lastError: null });
|
||||
|
||||
const sampleOnce = Effect.gen(function* () {
|
||||
const sampledAt = yield* DateTime.now;
|
||||
const sampledAtMs = DateTime.toEpochMillis(sampledAt);
|
||||
const rows = yield* readProcessRows.pipe(
|
||||
const rows = yield* ProcessDiagnostics.readProcessRows.pipe(
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||
);
|
||||
const samples = collectMonitoredSamples({
|
||||
@@ -278,7 +276,7 @@ export const make = Effect.fn("makeProcessResourceMonitor")(function* () {
|
||||
Effect.forkScoped,
|
||||
);
|
||||
|
||||
const readHistory: ProcessResourceMonitorShape["readHistory"] = (input) =>
|
||||
const readHistory: ProcessResourceMonitor["Service"]["readHistory"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const readAt = yield* DateTime.now;
|
||||
const readAtMs = DateTime.toEpochMillis(readAt);
|
||||
@@ -296,4 +294,4 @@ export const make = Effect.fn("makeProcessResourceMonitor")(function* () {
|
||||
return ProcessResourceMonitor.of({ readHistory });
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(ProcessResourceMonitor, make());
|
||||
export const layer = Layer.effect(ProcessResourceMonitor, make);
|
||||
@@ -39,13 +39,14 @@ export interface TraceDiagnosticsOptions {
|
||||
readonly readAt?: DateTime.Utc;
|
||||
}
|
||||
|
||||
export interface TraceDiagnosticsShape {
|
||||
readonly read: (options: TraceDiagnosticsOptions) => Effect.Effect<ServerTraceDiagnosticsResult>;
|
||||
}
|
||||
|
||||
export class TraceDiagnostics extends Context.Service<TraceDiagnostics, TraceDiagnosticsShape>()(
|
||||
"t3/diagnostics/TraceDiagnostics",
|
||||
) {}
|
||||
export class TraceDiagnostics extends Context.Service<
|
||||
TraceDiagnostics,
|
||||
{
|
||||
readonly read: (
|
||||
options: TraceDiagnosticsOptions,
|
||||
) => Effect.Effect<ServerTraceDiagnosticsResult>;
|
||||
}
|
||||
>()("t3/diagnostics/TraceDiagnostics") {}
|
||||
|
||||
interface TraceDiagnosticsInput {
|
||||
readonly traceFilePath: string;
|
||||
@@ -395,10 +396,10 @@ function readTraceFile(
|
||||
);
|
||||
}
|
||||
|
||||
export const make = Effect.fn("makeTraceDiagnostics")(function* () {
|
||||
export const make = Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
|
||||
const read: TraceDiagnosticsShape["read"] = Effect.fn("TraceDiagnostics.read")(
|
||||
const read: TraceDiagnostics["Service"]["read"] = Effect.fn("TraceDiagnostics.read")(
|
||||
function* (options) {
|
||||
const readAt = options.readAt ?? (yield* DateTime.now);
|
||||
const slowSpanThresholdMs = options.slowSpanThresholdMs ?? DEFAULT_SLOW_SPAN_THRESHOLD_MS;
|
||||
@@ -449,7 +450,7 @@ export const make = Effect.fn("makeTraceDiagnostics")(function* () {
|
||||
return TraceDiagnostics.of({ read });
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(TraceDiagnostics, make());
|
||||
export const layer = Layer.effect(TraceDiagnostics, make);
|
||||
|
||||
export function readTraceDiagnostics(
|
||||
options: TraceDiagnosticsOptions,
|
||||
|
||||
@@ -5,15 +5,15 @@ import * as Layer from "effect/Layer";
|
||||
import { HostProcessHostname, HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import { vi } from "vite-plus/test";
|
||||
|
||||
import { ProcessRunner, ProcessSpawnError, type ProcessRunnerShape } from "../../processRunner.ts";
|
||||
import * as ProcessRunner from "../../processRunner.ts";
|
||||
import { resolveServerEnvironmentLabel } from "./ServerEnvironmentLabel.ts";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
const runMock = vi.fn<ProcessRunnerShape["run"]>();
|
||||
const runMock = vi.fn<ProcessRunner.ProcessRunner["Service"]["run"]>();
|
||||
|
||||
const ProcessRunnerTest = Layer.succeed(
|
||||
ProcessRunner,
|
||||
ProcessRunner.of({
|
||||
ProcessRunner.ProcessRunner,
|
||||
ProcessRunner.ProcessRunner.of({
|
||||
run: (input) => runMock(input),
|
||||
}),
|
||||
);
|
||||
@@ -136,7 +136,7 @@ describe("resolveServerEnvironmentLabel", () => {
|
||||
Effect.gen(function* () {
|
||||
runMock.mockReturnValueOnce(
|
||||
Effect.fail(
|
||||
new ProcessSpawnError({
|
||||
new ProcessRunner.ProcessSpawnError({
|
||||
command: "scutil",
|
||||
args: ["--get", "ComputerName"],
|
||||
cause: new Error("spawn scutil ENOENT"),
|
||||
|
||||
@@ -20,27 +20,16 @@ import type {
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import { GitCommandError, TextGenerationError } from "@t3tools/contracts";
|
||||
import { type GitManagerShape } from "./GitManager.ts";
|
||||
import {
|
||||
GitHubCliError,
|
||||
type GitHubCliShape,
|
||||
type GitHubPullRequestSummary,
|
||||
GitHubCli,
|
||||
} from "../sourceControl/GitHubCli.ts";
|
||||
import { type TextGenerationShape, TextGeneration } from "../textGeneration/TextGeneration.ts";
|
||||
import * as GitManager from "./GitManager.ts";
|
||||
import * as GitHubCli from "../sourceControl/GitHubCli.ts";
|
||||
import * as TextGeneration from "../textGeneration/TextGeneration.ts";
|
||||
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
|
||||
import * as VcsProcess from "../vcs/VcsProcess.ts";
|
||||
import * as GitHubSourceControlProvider from "../sourceControl/GitHubSourceControlProvider.ts";
|
||||
import * as SourceControlProviderRegistry from "../sourceControl/SourceControlProviderRegistry.ts";
|
||||
import { makeGitManager } from "./GitManager.ts";
|
||||
import { ServerConfig } from "../config.ts";
|
||||
import { ServerSettingsService } from "../serverSettings.ts";
|
||||
import {
|
||||
ProjectSetupScriptRunner,
|
||||
ProjectSetupScriptRunnerError,
|
||||
type ProjectSetupScriptRunnerInput,
|
||||
type ProjectSetupScriptRunnerShape,
|
||||
} from "../project/Services/ProjectSetupScriptRunner.ts";
|
||||
import * as ServerConfig from "../config.ts";
|
||||
import * as ServerSettings from "../serverSettings.ts";
|
||||
import * as ProjectSetupScriptRunner from "../project/Services/ProjectSetupScriptRunner.ts";
|
||||
|
||||
interface FakeGhScenario {
|
||||
prListSequence?: string[];
|
||||
@@ -60,7 +49,7 @@ interface FakeGhScenario {
|
||||
headRepositoryOwnerLogin?: string | null;
|
||||
};
|
||||
repositoryCloneUrls?: Record<string, { url: string; sshUrl: string }>;
|
||||
failWith?: GitHubCliError;
|
||||
failWith?: GitHubCli.GitHubCliError;
|
||||
}
|
||||
|
||||
function fakeGhOutput(stdout: string): VcsProcess.VcsProcessOutput {
|
||||
@@ -108,7 +97,7 @@ interface FakeGitTextGeneration {
|
||||
|
||||
type FakePullRequest = NonNullable<FakeGhScenario["pullRequest"]>;
|
||||
|
||||
function normalizeFakePullRequestSummary(raw: unknown): GitHubPullRequestSummary | null {
|
||||
function normalizeFakePullRequestSummary(raw: unknown): GitHubCli.GitHubPullRequestSummary | null {
|
||||
if (!raw || typeof raw !== "object") {
|
||||
return null;
|
||||
}
|
||||
@@ -182,13 +171,13 @@ function runGitSyncForFakeGh(cwd: string, args: readonly string[]): void {
|
||||
if (result.status === 0) {
|
||||
return;
|
||||
}
|
||||
throw new GitHubCliError({
|
||||
throw new GitHubCli.GitHubCliError({
|
||||
operation: "execute",
|
||||
detail: `Failed to simulate gh checkout with git ${args.join(" ")}: ${result.stderr?.trim() || "unknown error"}`,
|
||||
});
|
||||
}
|
||||
|
||||
function isGitHubCliError(error: unknown): error is GitHubCliError {
|
||||
function isGitHubCliError(error: unknown): error is GitHubCli.GitHubCliError {
|
||||
return (
|
||||
typeof error === "object" &&
|
||||
error !== null &&
|
||||
@@ -312,7 +301,9 @@ function configureVisibleRemoteUrlWithLocalRewrite(
|
||||
});
|
||||
}
|
||||
|
||||
function createTextGeneration(overrides: Partial<FakeGitTextGeneration> = {}): TextGenerationShape {
|
||||
function createTextGeneration(
|
||||
overrides: Partial<FakeGitTextGeneration> = {},
|
||||
): TextGeneration.TextGeneration["Service"] {
|
||||
const implementation: FakeGitTextGeneration = {
|
||||
generateCommitMessage: (input) =>
|
||||
Effect.succeed({
|
||||
@@ -385,7 +376,7 @@ function createTextGeneration(overrides: Partial<FakeGitTextGeneration> = {}): T
|
||||
}
|
||||
|
||||
function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
|
||||
service: GitHubCliShape;
|
||||
service: GitHubCli.GitHubCli["Service"];
|
||||
ghCalls: string[];
|
||||
} {
|
||||
const prListQueue = [...(scenario.prListSequence ?? [])];
|
||||
@@ -397,7 +388,7 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
|
||||
);
|
||||
const ghCalls: string[] = [];
|
||||
|
||||
const execute: GitHubCliShape["execute"] = (input) => {
|
||||
const execute: GitHubCli.GitHubCli["Service"]["execute"] = (input) => {
|
||||
const args = [...input.args];
|
||||
ghCalls.push(args.join(" "));
|
||||
|
||||
@@ -487,7 +478,7 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
|
||||
catch: (error) =>
|
||||
isGitHubCliError(error)
|
||||
? error
|
||||
: new GitHubCliError({
|
||||
: new GitHubCli.GitHubCliError({
|
||||
operation: "execute",
|
||||
detail:
|
||||
error instanceof Error
|
||||
@@ -503,7 +494,7 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
|
||||
const cloneUrls = scenario.repositoryCloneUrls?.[repository];
|
||||
if (!cloneUrls) {
|
||||
return Effect.fail(
|
||||
new GitHubCliError({
|
||||
new GitHubCli.GitHubCliError({
|
||||
operation: "execute",
|
||||
detail: `Unexpected repository lookup: ${repository}`,
|
||||
}),
|
||||
@@ -523,7 +514,7 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
|
||||
}
|
||||
|
||||
return Effect.fail(
|
||||
new GitHubCliError({
|
||||
new GitHubCli.GitHubCliError({
|
||||
operation: "execute",
|
||||
detail: `Unexpected gh command: ${args.join(" ")}`,
|
||||
}),
|
||||
@@ -553,7 +544,7 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
|
||||
Effect.map((raw) =>
|
||||
raw
|
||||
.map((entry) => normalizeFakePullRequestSummary(entry))
|
||||
.filter((entry): entry is GitHubPullRequestSummary => entry !== null),
|
||||
.filter((entry): entry is GitHubCli.GitHubPullRequestSummary => entry !== null),
|
||||
),
|
||||
),
|
||||
createPullRequest: (input) =>
|
||||
@@ -592,7 +583,9 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
|
||||
"--json",
|
||||
"number,title,url,baseRefName,headRefName,state,mergedAt,isCrossRepository,headRepository,headRepositoryOwner",
|
||||
],
|
||||
}).pipe(Effect.map((result) => JSON.parse(result.stdout) as GitHubPullRequestSummary)),
|
||||
}).pipe(
|
||||
Effect.map((result) => JSON.parse(result.stdout) as GitHubCli.GitHubPullRequestSummary),
|
||||
),
|
||||
getRepositoryCloneUrls: (input) =>
|
||||
execute({
|
||||
cwd: input.cwd,
|
||||
@@ -600,7 +593,7 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
|
||||
}).pipe(Effect.map((result) => JSON.parse(result.stdout))),
|
||||
createRepository: (input) =>
|
||||
Effect.fail(
|
||||
new GitHubCliError({
|
||||
new GitHubCli.GitHubCliError({
|
||||
operation: "createRepository",
|
||||
detail: `Unexpected repository create: ${input.repository}`,
|
||||
}),
|
||||
@@ -616,7 +609,7 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
|
||||
}
|
||||
|
||||
function runStackedAction(
|
||||
manager: GitManagerShape,
|
||||
manager: GitManager.GitManager["Service"],
|
||||
input: {
|
||||
cwd: string;
|
||||
action: "commit" | "push" | "create_pr" | "commit_push" | "commit_push_pr";
|
||||
@@ -625,7 +618,7 @@ function runStackedAction(
|
||||
featureBranch?: boolean;
|
||||
filePaths?: readonly string[];
|
||||
},
|
||||
options?: Parameters<GitManagerShape["runStackedAction"]>[1],
|
||||
options?: Parameters<GitManager.GitManager["Service"]["runStackedAction"]>[1],
|
||||
) {
|
||||
return manager.runStackedAction(
|
||||
{
|
||||
@@ -636,12 +629,15 @@ function runStackedAction(
|
||||
);
|
||||
}
|
||||
|
||||
function resolvePullRequest(manager: GitManagerShape, input: { cwd: string; reference: string }) {
|
||||
function resolvePullRequest(
|
||||
manager: GitManager.GitManager["Service"],
|
||||
input: { cwd: string; reference: string },
|
||||
) {
|
||||
return manager.resolvePullRequest(input);
|
||||
}
|
||||
|
||||
function preparePullRequestThread(
|
||||
manager: GitManagerShape,
|
||||
manager: GitManager.GitManager["Service"],
|
||||
input: GitPreparePullRequestThreadInput,
|
||||
) {
|
||||
return manager.preparePullRequestThread(input);
|
||||
@@ -650,24 +646,24 @@ function preparePullRequestThread(
|
||||
function makeManager(input?: {
|
||||
ghScenario?: FakeGhScenario;
|
||||
textGeneration?: Partial<FakeGitTextGeneration>;
|
||||
setupScriptRunner?: ProjectSetupScriptRunnerShape;
|
||||
setupScriptRunner?: ProjectSetupScriptRunner.ProjectSetupScriptRunner["Service"];
|
||||
}) {
|
||||
const { service: gitHubCli, ghCalls } = createGitHubCliWithFakeGh(input?.ghScenario);
|
||||
const textGeneration = createTextGeneration(input?.textGeneration);
|
||||
const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
|
||||
const serverConfigLayer = ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3-git-manager-test-",
|
||||
});
|
||||
|
||||
const serverSettingsLayer = ServerSettingsService.layerTest();
|
||||
const serverSettingsLayer = ServerSettings.ServerSettingsService.layerTest();
|
||||
|
||||
const vcsDriverLayer = GitVcsDriver.layer.pipe(
|
||||
Layer.provideMerge(VcsProcess.layer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provideMerge(ServerConfigLayer),
|
||||
Layer.provideMerge(serverConfigLayer),
|
||||
);
|
||||
const sourceControlRegistryLayer = Layer.effect(
|
||||
SourceControlProviderRegistry.SourceControlProviderRegistry,
|
||||
GitHubSourceControlProvider.make().pipe(
|
||||
GitHubSourceControlProvider.make.pipe(
|
||||
Effect.map((provider) =>
|
||||
SourceControlProviderRegistry.SourceControlProviderRegistry.of({
|
||||
get: () => Effect.succeed(provider),
|
||||
@@ -676,14 +672,14 @@ function makeManager(input?: {
|
||||
discover: Effect.succeed([]),
|
||||
}),
|
||||
),
|
||||
Effect.provide(Layer.succeed(GitHubCli, gitHubCli)),
|
||||
Effect.provide(Layer.succeed(GitHubCli.GitHubCli, gitHubCli)),
|
||||
),
|
||||
);
|
||||
|
||||
const managerLayer = Layer.mergeAll(
|
||||
Layer.succeed(TextGeneration, textGeneration),
|
||||
Layer.succeed(TextGeneration.TextGeneration, textGeneration),
|
||||
Layer.succeed(
|
||||
ProjectSetupScriptRunner,
|
||||
ProjectSetupScriptRunner.ProjectSetupScriptRunner,
|
||||
input?.setupScriptRunner ?? {
|
||||
runForThread: () => Effect.succeed({ status: "no-script" as const }),
|
||||
},
|
||||
@@ -692,7 +688,7 @@ function makeManager(input?: {
|
||||
serverSettingsLayer,
|
||||
).pipe(Layer.provideMerge(sourceControlRegistryLayer), Layer.provideMerge(NodeServices.layer));
|
||||
|
||||
return makeGitManager().pipe(
|
||||
return GitManager.make.pipe(
|
||||
Effect.provide(managerLayer),
|
||||
Effect.map((manager) => ({ manager, ghCalls })),
|
||||
);
|
||||
@@ -1335,7 +1331,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
failWith: new GitHubCliError({
|
||||
failWith: new GitHubCli.GitHubCliError({
|
||||
operation: "execute",
|
||||
detail: "GitHub CLI (`gh`) is required but not available on PATH.",
|
||||
}),
|
||||
@@ -2417,7 +2413,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
failWith: new GitHubCliError({
|
||||
failWith: new GitHubCli.GitHubCliError({
|
||||
operation: "execute",
|
||||
detail: "GitHub CLI (`gh`) is required but not available on PATH.",
|
||||
}),
|
||||
@@ -2446,7 +2442,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
failWith: new GitHubCliError({
|
||||
failWith: new GitHubCli.GitHubCliError({
|
||||
operation: "execute",
|
||||
detail: "GitHub CLI is not authenticated. Run `gh auth login` and retry.",
|
||||
}),
|
||||
@@ -2702,7 +2698,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
yield* runGit(repoDir, ["push", "origin", "HEAD:refs/pull/177/head"]);
|
||||
yield* runGit(repoDir, ["checkout", "main"]);
|
||||
|
||||
const setupCalls: ProjectSetupScriptRunnerInput[] = [];
|
||||
const setupCalls: ProjectSetupScriptRunner.ProjectSetupScriptRunnerInput[] = [];
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
pullRequest: {
|
||||
@@ -2924,7 +2920,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
const worktreePath = path.join(repoDir, "..", `pr-existing-${path.basename(repoDir)}`);
|
||||
yield* runGit(repoDir, ["worktree", "add", worktreePath, "feature/pr-existing-worktree"]);
|
||||
|
||||
const setupCalls: ProjectSetupScriptRunnerInput[] = [];
|
||||
const setupCalls: ProjectSetupScriptRunner.ProjectSetupScriptRunnerInput[] = [];
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
pullRequest: {
|
||||
@@ -3164,7 +3160,11 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
},
|
||||
setupScriptRunner: {
|
||||
runForThread: () =>
|
||||
Effect.fail(new ProjectSetupScriptRunnerError({ message: "terminal start failed" })),
|
||||
Effect.fail(
|
||||
new ProjectSetupScriptRunner.ProjectSetupScriptRunnerError({
|
||||
message: "terminal start failed",
|
||||
}),
|
||||
),
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -42,17 +42,13 @@ import {
|
||||
} from "@t3tools/shared/sourceControl";
|
||||
|
||||
import { GitManagerError } from "@t3tools/contracts";
|
||||
import { TextGeneration } from "../textGeneration/TextGeneration.ts";
|
||||
import { ProjectSetupScriptRunner } from "../project/Services/ProjectSetupScriptRunner.ts";
|
||||
import * as TextGeneration from "../textGeneration/TextGeneration.ts";
|
||||
import * as ProjectSetupScriptRunner from "../project/Services/ProjectSetupScriptRunner.ts";
|
||||
import { extractBranchNameFromRemoteRef } from "./remoteRefs.ts";
|
||||
import { ServerSettingsService } from "../serverSettings.ts";
|
||||
import * as ServerSettings from "../serverSettings.ts";
|
||||
import type { GitManagerServiceError } from "@t3tools/contracts";
|
||||
import {
|
||||
GitVcsDriver,
|
||||
type GitRemoteStatusOptions,
|
||||
type GitStatusDetails,
|
||||
} from "../vcs/GitVcsDriver.ts";
|
||||
import { SourceControlProviderRegistry } from "../sourceControl/SourceControlProviderRegistry.ts";
|
||||
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
|
||||
import * as SourceControlProviderRegistry from "../sourceControl/SourceControlProviderRegistry.ts";
|
||||
import type { ChangeRequest } from "@t3tools/contracts";
|
||||
|
||||
export interface GitActionProgressReporter {
|
||||
@@ -64,35 +60,34 @@ export interface GitRunStackedActionOptions {
|
||||
readonly progressReporter?: GitActionProgressReporter;
|
||||
}
|
||||
|
||||
export interface GitManagerShape {
|
||||
readonly status: (
|
||||
input: VcsStatusInput,
|
||||
) => Effect.Effect<VcsStatusResult, GitManagerServiceError>;
|
||||
readonly localStatus: (
|
||||
input: VcsStatusInput,
|
||||
) => Effect.Effect<VcsStatusLocalResult, GitManagerServiceError>;
|
||||
readonly remoteStatus: (
|
||||
input: VcsStatusInput,
|
||||
options?: GitRemoteStatusOptions,
|
||||
) => Effect.Effect<VcsStatusRemoteResult | null, GitManagerServiceError>;
|
||||
readonly invalidateLocalStatus: (cwd: string) => Effect.Effect<void, never>;
|
||||
readonly invalidateRemoteStatus: (cwd: string) => Effect.Effect<void, never>;
|
||||
readonly invalidateStatus: (cwd: string) => Effect.Effect<void, never>;
|
||||
readonly resolvePullRequest: (
|
||||
input: GitPullRequestRefInput,
|
||||
) => Effect.Effect<GitResolvePullRequestResult, GitManagerServiceError>;
|
||||
readonly preparePullRequestThread: (
|
||||
input: GitPreparePullRequestThreadInput,
|
||||
) => Effect.Effect<GitPreparePullRequestThreadResult, GitManagerServiceError>;
|
||||
readonly runStackedAction: (
|
||||
input: GitRunStackedActionInput,
|
||||
options?: GitRunStackedActionOptions,
|
||||
) => Effect.Effect<GitRunStackedActionResult, GitManagerServiceError>;
|
||||
}
|
||||
|
||||
export class GitManager extends Context.Service<GitManager, GitManagerShape>()(
|
||||
"t3/git/GitManager",
|
||||
) {}
|
||||
export class GitManager extends Context.Service<
|
||||
GitManager,
|
||||
{
|
||||
readonly status: (
|
||||
input: VcsStatusInput,
|
||||
) => Effect.Effect<VcsStatusResult, GitManagerServiceError>;
|
||||
readonly localStatus: (
|
||||
input: VcsStatusInput,
|
||||
) => Effect.Effect<VcsStatusLocalResult, GitManagerServiceError>;
|
||||
readonly remoteStatus: (
|
||||
input: VcsStatusInput,
|
||||
options?: GitVcsDriver.GitRemoteStatusOptions,
|
||||
) => Effect.Effect<VcsStatusRemoteResult | null, GitManagerServiceError>;
|
||||
readonly invalidateLocalStatus: (cwd: string) => Effect.Effect<void, never>;
|
||||
readonly invalidateRemoteStatus: (cwd: string) => Effect.Effect<void, never>;
|
||||
readonly invalidateStatus: (cwd: string) => Effect.Effect<void, never>;
|
||||
readonly resolvePullRequest: (
|
||||
input: GitPullRequestRefInput,
|
||||
) => Effect.Effect<GitResolvePullRequestResult, GitManagerServiceError>;
|
||||
readonly preparePullRequestThread: (
|
||||
input: GitPreparePullRequestThreadInput,
|
||||
) => Effect.Effect<GitPreparePullRequestThreadResult, GitManagerServiceError>;
|
||||
readonly runStackedAction: (
|
||||
input: GitRunStackedActionInput,
|
||||
options?: GitRunStackedActionOptions,
|
||||
) => Effect.Effect<GitRunStackedActionResult, GitManagerServiceError>;
|
||||
}
|
||||
>()("t3/git/GitManager") {}
|
||||
|
||||
const COMMIT_TIMEOUT_MS = 10 * 60_000;
|
||||
const MAX_PROGRESS_TEXT_LENGTH = 500;
|
||||
@@ -531,15 +526,15 @@ function toPullRequestHeadRemoteInfo(pr: {
|
||||
};
|
||||
}
|
||||
|
||||
export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
const gitCore = yield* GitVcsDriver;
|
||||
const sourceControlProviders = yield* SourceControlProviderRegistry;
|
||||
const textGeneration = yield* TextGeneration;
|
||||
const projectSetupScriptRunner = yield* ProjectSetupScriptRunner;
|
||||
export const make = Effect.gen(function* () {
|
||||
const gitCore = yield* GitVcsDriver.GitVcsDriver;
|
||||
const sourceControlProviders = yield* SourceControlProviderRegistry.SourceControlProviderRegistry;
|
||||
const textGeneration = yield* TextGeneration.TextGeneration;
|
||||
const projectSetupScriptRunner = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner;
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
|
||||
const sourceControlProvider = (cwd: string) => sourceControlProviders.resolve({ cwd });
|
||||
const serverSettingsService = yield* ServerSettingsService;
|
||||
const serverSettingsService = yield* ServerSettings.ServerSettingsService;
|
||||
const randomUUIDv4 = crypto.randomUUIDv4.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
gitManagerError("randomUUIDv4", "Failed to generate Git operation identifier.", cause),
|
||||
@@ -721,7 +716,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
aheadOfDefaultCount: 0,
|
||||
} satisfies GitStatusDetails;
|
||||
} satisfies GitVcsDriver.GitStatusDetails;
|
||||
const readLocalStatus = Effect.fn("readLocalStatus")(function* (cwd: string) {
|
||||
const details = yield* gitCore
|
||||
.statusDetailsLocal(cwd)
|
||||
@@ -752,7 +747,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
);
|
||||
const readRemoteStatus = Effect.fn("readRemoteStatus")(function* (
|
||||
cwd: string,
|
||||
options?: GitRemoteStatusOptions,
|
||||
options?: GitVcsDriver.GitRemoteStatusOptions,
|
||||
) {
|
||||
const details = yield* gitCore
|
||||
.statusDetailsRemote(cwd, options)
|
||||
@@ -1303,7 +1298,19 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
phase: "pr",
|
||||
label: `Generating ${terms.shortLabel} content...`,
|
||||
});
|
||||
const rangeContext = yield* gitCore.readRangeContext(cwd, baseBranch);
|
||||
const rangeBaseRef = yield* gitCore.resolvePrimaryRemoteName(cwd).pipe(
|
||||
Effect.map((remote) =>
|
||||
baseBranch.startsWith(`${remote}/`) ? baseBranch : `${remote}/${baseBranch}`,
|
||||
),
|
||||
Effect.orElseSucceed(() => baseBranch),
|
||||
);
|
||||
const rangeContext = yield* (
|
||||
rangeBaseRef === baseBranch
|
||||
? gitCore.readRangeContext(cwd, rangeBaseRef)
|
||||
: gitCore.readRangeContext(cwd, rangeBaseRef).pipe(
|
||||
Effect.catch(() => gitCore.readRangeContext(cwd, baseBranch)),
|
||||
)
|
||||
);
|
||||
|
||||
const generated = yield* textGeneration.generatePrContent({
|
||||
cwd,
|
||||
@@ -1358,11 +1365,13 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
};
|
||||
});
|
||||
|
||||
const localStatus: GitManagerShape["localStatus"] = Effect.fn("localStatus")(function* (input) {
|
||||
const cacheKey = yield* normalizeStatusCacheKey(input.cwd);
|
||||
return yield* Cache.get(localStatusResultCache, cacheKey);
|
||||
});
|
||||
const remoteStatus: GitManagerShape["remoteStatus"] = Effect.fn("remoteStatus")(
|
||||
const localStatus: GitManager["Service"]["localStatus"] = Effect.fn("localStatus")(
|
||||
function* (input) {
|
||||
const cacheKey = yield* normalizeStatusCacheKey(input.cwd);
|
||||
return yield* Cache.get(localStatusResultCache, cacheKey);
|
||||
},
|
||||
);
|
||||
const remoteStatus: GitManager["Service"]["remoteStatus"] = Effect.fn("remoteStatus")(
|
||||
function* (input, options) {
|
||||
const cacheKey = yield* normalizeStatusCacheKey(input.cwd);
|
||||
if (options?.refreshUpstream === false) {
|
||||
@@ -1371,43 +1380,43 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
return yield* Cache.get(remoteStatusResultCache, cacheKey);
|
||||
},
|
||||
);
|
||||
const status: GitManagerShape["status"] = Effect.fn("status")(function* (input) {
|
||||
const status: GitManager["Service"]["status"] = Effect.fn("status")(function* (input) {
|
||||
const [local, remote] = yield* Effect.all([localStatus(input), remoteStatus(input)], {
|
||||
concurrency: "unbounded",
|
||||
});
|
||||
return mergeGitStatusParts(local, remote);
|
||||
});
|
||||
const invalidateLocalStatus: GitManagerShape["invalidateLocalStatus"] = Effect.fn(
|
||||
const invalidateLocalStatus: GitManager["Service"]["invalidateLocalStatus"] = Effect.fn(
|
||||
"invalidateLocalStatus",
|
||||
)(function* (cwd) {
|
||||
yield* invalidateLocalStatusResultCache(cwd);
|
||||
});
|
||||
const invalidateRemoteStatus: GitManagerShape["invalidateRemoteStatus"] = Effect.fn(
|
||||
const invalidateRemoteStatus: GitManager["Service"]["invalidateRemoteStatus"] = Effect.fn(
|
||||
"invalidateRemoteStatus",
|
||||
)(function* (cwd) {
|
||||
yield* invalidateRemoteStatusResultCache(cwd);
|
||||
});
|
||||
const invalidateStatus: GitManagerShape["invalidateStatus"] = Effect.fn("invalidateStatus")(
|
||||
const invalidateStatus: GitManager["Service"]["invalidateStatus"] = Effect.fn("invalidateStatus")(
|
||||
function* (cwd) {
|
||||
yield* invalidateLocalStatusResultCache(cwd);
|
||||
yield* invalidateRemoteStatusResultCache(cwd);
|
||||
},
|
||||
);
|
||||
|
||||
const resolvePullRequest: GitManagerShape["resolvePullRequest"] = Effect.fn("resolvePullRequest")(
|
||||
function* (input) {
|
||||
const pullRequest = yield* (yield* sourceControlProvider(input.cwd))
|
||||
.getChangeRequest({
|
||||
cwd: input.cwd,
|
||||
reference: normalizePullRequestReference(input.reference),
|
||||
})
|
||||
.pipe(Effect.map((resolved) => toResolvedPullRequest(resolved)));
|
||||
const resolvePullRequest: GitManager["Service"]["resolvePullRequest"] = Effect.fn(
|
||||
"resolvePullRequest",
|
||||
)(function* (input) {
|
||||
const pullRequest = yield* (yield* sourceControlProvider(input.cwd))
|
||||
.getChangeRequest({
|
||||
cwd: input.cwd,
|
||||
reference: normalizePullRequestReference(input.reference),
|
||||
})
|
||||
.pipe(Effect.map((resolved) => toResolvedPullRequest(resolved)));
|
||||
|
||||
return { pullRequest };
|
||||
},
|
||||
);
|
||||
return { pullRequest };
|
||||
});
|
||||
|
||||
const preparePullRequestThread: GitManagerShape["preparePullRequestThread"] = Effect.fn(
|
||||
const preparePullRequestThread: GitManager["Service"]["preparePullRequestThread"] = Effect.fn(
|
||||
"preparePullRequestThread",
|
||||
)(function* (input) {
|
||||
const maybeRunSetupScript = (worktreePath: string) => {
|
||||
@@ -1608,7 +1617,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
};
|
||||
});
|
||||
|
||||
const runStackedAction: GitManagerShape["runStackedAction"] = Effect.fn("runStackedAction")(
|
||||
const runStackedAction: GitManager["Service"]["runStackedAction"] = Effect.fn("runStackedAction")(
|
||||
function* (input, options) {
|
||||
const progress = yield* createProgressEmitter(input, options);
|
||||
const currentPhase = yield* Ref.make<Option.Option<GitActionProgressPhase>>(Option.none());
|
||||
@@ -1787,7 +1796,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
},
|
||||
);
|
||||
|
||||
return {
|
||||
return GitManager.of({
|
||||
localStatus,
|
||||
remoteStatus,
|
||||
status,
|
||||
@@ -1797,7 +1806,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
resolvePullRequest,
|
||||
preparePullRequestThread,
|
||||
runStackedAction,
|
||||
} satisfies GitManagerShape;
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(GitManager, makeGitManager());
|
||||
export const layer = Layer.effect(GitManager, make);
|
||||
@@ -7,7 +7,9 @@ import * as GitWorkflowService from "./GitWorkflowService.ts";
|
||||
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
|
||||
import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
|
||||
|
||||
function makeLayer(input: { readonly detect: VcsDriverRegistry.VcsDriverRegistryShape["detect"] }) {
|
||||
function makeLayer(input: {
|
||||
readonly detect: VcsDriverRegistry.VcsDriverRegistry["Service"]["detect"];
|
||||
}) {
|
||||
return GitWorkflowService.layer.pipe(
|
||||
Layer.provide(
|
||||
Layer.mock(VcsDriverRegistry.VcsDriverRegistry)({
|
||||
|
||||
@@ -28,68 +28,70 @@ import {
|
||||
type VcsStatusResult,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import { GitManager, type GitRunStackedActionOptions } from "./GitManager.ts";
|
||||
import { GitVcsDriver, type GitRemoteStatusOptions } from "../vcs/GitVcsDriver.ts";
|
||||
import { VcsDriverRegistry } from "../vcs/VcsDriverRegistry.ts";
|
||||
|
||||
export interface GitWorkflowServiceShape {
|
||||
readonly status: (
|
||||
input: VcsStatusInput,
|
||||
) => Effect.Effect<VcsStatusResult, GitManagerServiceError>;
|
||||
readonly localStatus: (
|
||||
input: VcsStatusInput,
|
||||
) => Effect.Effect<VcsStatusLocalResult, GitManagerServiceError>;
|
||||
readonly remoteStatus: (
|
||||
input: VcsStatusInput,
|
||||
options?: GitRemoteStatusOptions,
|
||||
) => Effect.Effect<VcsStatusRemoteResult | null, GitManagerServiceError>;
|
||||
readonly invalidateLocalStatus: (cwd: string) => Effect.Effect<void, never>;
|
||||
readonly invalidateRemoteStatus: (cwd: string) => Effect.Effect<void, never>;
|
||||
readonly invalidateStatus: (cwd: string) => Effect.Effect<void, never>;
|
||||
readonly pullCurrentBranch: (cwd: string) => Effect.Effect<VcsPullResult, GitCommandError>;
|
||||
readonly runStackedAction: (
|
||||
input: GitRunStackedActionInput,
|
||||
options?: GitRunStackedActionOptions,
|
||||
) => Effect.Effect<GitRunStackedActionResult, GitManagerServiceError>;
|
||||
readonly resolvePullRequest: (
|
||||
input: GitPullRequestRefInput,
|
||||
) => Effect.Effect<GitResolvePullRequestResult, GitManagerServiceError>;
|
||||
readonly preparePullRequestThread: (
|
||||
input: GitPreparePullRequestThreadInput,
|
||||
) => Effect.Effect<GitPreparePullRequestThreadResult, GitManagerServiceError>;
|
||||
readonly listRefs: (input: VcsListRefsInput) => Effect.Effect<VcsListRefsResult, GitCommandError>;
|
||||
readonly createWorktree: (
|
||||
input: VcsCreateWorktreeInput,
|
||||
) => Effect.Effect<VcsCreateWorktreeResult, GitCommandError>;
|
||||
readonly fetchRemote: (input: {
|
||||
readonly cwd: string;
|
||||
readonly remoteName: string;
|
||||
}) => Effect.Effect<void, GitCommandError>;
|
||||
readonly resolveRemoteTrackingCommit: (input: {
|
||||
readonly cwd: string;
|
||||
readonly refName: string;
|
||||
readonly fallbackRemoteName: string;
|
||||
}) => Effect.Effect<
|
||||
{ readonly commitSha: string; readonly remoteRefName: string },
|
||||
GitCommandError
|
||||
>;
|
||||
readonly removeWorktree: (input: VcsRemoveWorktreeInput) => Effect.Effect<void, GitCommandError>;
|
||||
readonly createRef: (
|
||||
input: VcsCreateRefInput,
|
||||
) => Effect.Effect<VcsCreateRefResult, GitCommandError>;
|
||||
readonly switchRef: (
|
||||
input: VcsSwitchRefInput,
|
||||
) => Effect.Effect<VcsSwitchRefResult, GitCommandError>;
|
||||
readonly renameBranch: (input: {
|
||||
readonly cwd: string;
|
||||
readonly oldBranch: string;
|
||||
readonly newBranch: string;
|
||||
}) => Effect.Effect<{ readonly branch: string }, GitManagerServiceError>;
|
||||
}
|
||||
import * as GitManager from "./GitManager.ts";
|
||||
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
|
||||
import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
|
||||
|
||||
export class GitWorkflowService extends Context.Service<
|
||||
GitWorkflowService,
|
||||
GitWorkflowServiceShape
|
||||
{
|
||||
readonly status: (
|
||||
input: VcsStatusInput,
|
||||
) => Effect.Effect<VcsStatusResult, GitManagerServiceError>;
|
||||
readonly localStatus: (
|
||||
input: VcsStatusInput,
|
||||
) => Effect.Effect<VcsStatusLocalResult, GitManagerServiceError>;
|
||||
readonly remoteStatus: (
|
||||
input: VcsStatusInput,
|
||||
options?: GitVcsDriver.GitRemoteStatusOptions,
|
||||
) => Effect.Effect<VcsStatusRemoteResult | null, GitManagerServiceError>;
|
||||
readonly invalidateLocalStatus: (cwd: string) => Effect.Effect<void, never>;
|
||||
readonly invalidateRemoteStatus: (cwd: string) => Effect.Effect<void, never>;
|
||||
readonly invalidateStatus: (cwd: string) => Effect.Effect<void, never>;
|
||||
readonly pullCurrentBranch: (cwd: string) => Effect.Effect<VcsPullResult, GitCommandError>;
|
||||
readonly runStackedAction: (
|
||||
input: GitRunStackedActionInput,
|
||||
options?: GitManager.GitRunStackedActionOptions,
|
||||
) => Effect.Effect<GitRunStackedActionResult, GitManagerServiceError>;
|
||||
readonly resolvePullRequest: (
|
||||
input: GitPullRequestRefInput,
|
||||
) => Effect.Effect<GitResolvePullRequestResult, GitManagerServiceError>;
|
||||
readonly preparePullRequestThread: (
|
||||
input: GitPreparePullRequestThreadInput,
|
||||
) => Effect.Effect<GitPreparePullRequestThreadResult, GitManagerServiceError>;
|
||||
readonly listRefs: (
|
||||
input: VcsListRefsInput,
|
||||
) => Effect.Effect<VcsListRefsResult, GitCommandError>;
|
||||
readonly createWorktree: (
|
||||
input: VcsCreateWorktreeInput,
|
||||
) => Effect.Effect<VcsCreateWorktreeResult, GitCommandError>;
|
||||
readonly fetchRemote: (input: {
|
||||
readonly cwd: string;
|
||||
readonly remoteName: string;
|
||||
}) => Effect.Effect<void, GitCommandError>;
|
||||
readonly resolveRemoteTrackingCommit: (input: {
|
||||
readonly cwd: string;
|
||||
readonly refName: string;
|
||||
readonly fallbackRemoteName: string;
|
||||
}) => Effect.Effect<
|
||||
{ readonly commitSha: string; readonly remoteRefName: string },
|
||||
GitCommandError
|
||||
>;
|
||||
readonly removeWorktree: (
|
||||
input: VcsRemoveWorktreeInput,
|
||||
) => Effect.Effect<void, GitCommandError>;
|
||||
readonly createRef: (
|
||||
input: VcsCreateRefInput,
|
||||
) => Effect.Effect<VcsCreateRefResult, GitCommandError>;
|
||||
readonly switchRef: (
|
||||
input: VcsSwitchRefInput,
|
||||
) => Effect.Effect<VcsSwitchRefResult, GitCommandError>;
|
||||
readonly renameBranch: (input: {
|
||||
readonly cwd: string;
|
||||
readonly oldBranch: string;
|
||||
readonly newBranch: string;
|
||||
}) => Effect.Effect<{ readonly branch: string }, GitManagerServiceError>;
|
||||
}
|
||||
>()("t3/git/GitWorkflowService") {}
|
||||
|
||||
const unsupportedGitWorkflow = (operation: string, cwd: string, detail: string) =>
|
||||
@@ -142,10 +144,10 @@ function nonRepositoryListRefs(): VcsListRefsResult {
|
||||
};
|
||||
}
|
||||
|
||||
export const make = Effect.fn("makeGitWorkflowService")(function* () {
|
||||
const registry = yield* VcsDriverRegistry;
|
||||
const git = yield* GitVcsDriver;
|
||||
const gitManager = yield* GitManager;
|
||||
export const make = Effect.gen(function* () {
|
||||
const registry = yield* VcsDriverRegistry.VcsDriverRegistry;
|
||||
const git = yield* GitVcsDriver.GitVcsDriver;
|
||||
const gitManager = yield* GitManager.GitManager;
|
||||
|
||||
const ensureGit = Effect.fn("GitWorkflowService.ensureGit")(function* (
|
||||
operation: string,
|
||||
@@ -334,4 +336,4 @@ export const make = Effect.fn("makeGitWorkflowService")(function* () {
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(GitWorkflowService, make());
|
||||
export const layer = Layer.effect(GitWorkflowService, make);
|
||||
+10
-9
@@ -24,13 +24,13 @@ import {
|
||||
import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
|
||||
import { OtlpTracer } from "effect/unstable/observability";
|
||||
|
||||
import { resolveStaticDir, ServerConfig } from "./config.ts";
|
||||
import * as ServerConfig from "./config.ts";
|
||||
import {
|
||||
ASSET_ROUTE_PREFIX,
|
||||
FALLBACK_PROJECT_FAVICON_SVG,
|
||||
resolveAsset,
|
||||
} from "./assets/AssetAccess.ts";
|
||||
import { BrowserTraceCollector } from "./observability/Services/BrowserTraceCollector.ts";
|
||||
import * as BrowserTraceCollector from "./observability/BrowserTraceCollector.ts";
|
||||
import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
|
||||
import { traceRelayRequest } from "./cloud/traceRelayRequest.ts";
|
||||
import {
|
||||
@@ -39,7 +39,7 @@ import {
|
||||
failEnvironmentAuthInvalid,
|
||||
failEnvironmentInternal,
|
||||
} from "./auth/http.ts";
|
||||
import { ServerEnvironment } from "./environment/Services/ServerEnvironment.ts";
|
||||
import * as ServerEnvironment from "./environment/Services/ServerEnvironment.ts";
|
||||
import { browserApiCorsAllowedHeaders, browserApiCorsAllowedMethods } from "./httpCors.ts";
|
||||
|
||||
const OTLP_TRACES_PROXY_PATH = "/api/observability/v1/traces";
|
||||
@@ -47,7 +47,7 @@ const LOOPBACK_HOSTNAMES = new Set(["127.0.0.1", "::1", "localhost"]);
|
||||
|
||||
export const browserApiCorsLayer = Layer.unwrap(
|
||||
Effect.gen(function* () {
|
||||
const config = yield* ServerConfig;
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
const devOrigin = config.devUrl?.origin;
|
||||
return HttpRouter.cors({
|
||||
...(devOrigin ? { allowedOrigins: [devOrigin], credentials: true } : {}),
|
||||
@@ -95,7 +95,7 @@ export const serverEnvironmentHttpApiLayer = HttpApiBuilder.group(
|
||||
EnvironmentHttpApi,
|
||||
"metadata",
|
||||
Effect.fnUntraced(function* (handlers) {
|
||||
const serverEnvironment = yield* ServerEnvironment;
|
||||
const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
|
||||
return handlers.handle(
|
||||
"descriptor",
|
||||
Effect.fn("environment.metadata.descriptor")(function* (args) {
|
||||
@@ -117,9 +117,9 @@ export const otlpTracesProxyRouteLayer = HttpRouter.add(
|
||||
Effect.gen(function* () {
|
||||
yield* authenticateRawRouteWithScope(AuthOrchestrationOperateScope);
|
||||
const request = yield* HttpServerRequest.HttpServerRequest;
|
||||
const config = yield* ServerConfig;
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
const otlpTracesUrl = config.otlpTracesUrl;
|
||||
const browserTraceCollector = yield* BrowserTraceCollector;
|
||||
const browserTraceCollector = yield* BrowserTraceCollector.BrowserTraceCollector;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const bodyJson = cast<unknown, OtlpTracer.TraceData>(yield* request.json);
|
||||
|
||||
@@ -223,14 +223,15 @@ export const staticAndDevRouteLayer = HttpRouter.add(
|
||||
return HttpServerResponse.text("Bad Request", { status: 400 });
|
||||
}
|
||||
|
||||
const config = yield* ServerConfig;
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
if (config.devUrl && isLoopbackHostname(url.value.hostname)) {
|
||||
return HttpServerResponse.redirect(resolveDevRedirectUrl(config.devUrl, url.value), {
|
||||
status: 302,
|
||||
});
|
||||
}
|
||||
|
||||
const staticDir = config.staticDir ?? (config.devUrl ? yield* resolveStaticDir() : undefined);
|
||||
const staticDir =
|
||||
config.staticDir ?? (config.devUrl ? yield* ServerConfig.resolveStaticDir() : undefined);
|
||||
if (!staticDir) {
|
||||
return HttpServerResponse.text("No static directory configured and no dev URL set.", {
|
||||
status: 503,
|
||||
|
||||
@@ -37,7 +37,7 @@ const makeOwner = (overrides: Partial<PreviewAutomationOwner> = {}): PreviewAuto
|
||||
it.effect("atomically registers a connected owner and correlates its response", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* PreviewAutomationBroker.__testing.make;
|
||||
const broker = yield* PreviewAutomationBroker.make;
|
||||
const requests = yield* broker.connect(makeOwner());
|
||||
yield* Stream.runForEach(requests, (request) =>
|
||||
broker.respond({
|
||||
@@ -61,7 +61,7 @@ it.effect("atomically registers a connected owner and correlates its response",
|
||||
|
||||
it.effect("rejects calls when no focused owner exists", () =>
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* PreviewAutomationBroker.__testing.make;
|
||||
const broker = yield* PreviewAutomationBroker.make;
|
||||
const error = yield* broker
|
||||
.invoke<void>({ scope, operation: "status", input: {} })
|
||||
.pipe(Effect.flip);
|
||||
@@ -72,7 +72,7 @@ it.effect("rejects calls when no focused owner exists", () =>
|
||||
it.effect("routes interactive commands to a hidden durable browser host", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* PreviewAutomationBroker.__testing.make;
|
||||
const broker = yield* PreviewAutomationBroker.make;
|
||||
const requests = yield* broker.connect(
|
||||
makeOwner({ clientId: "client-hidden", tabId: "tab-hidden" }),
|
||||
);
|
||||
@@ -89,7 +89,7 @@ it.effect("routes interactive commands to a hidden durable browser host", () =>
|
||||
it.effect("lets the browser host resolve an active tab that has not been reported yet", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* PreviewAutomationBroker.__testing.make;
|
||||
const broker = yield* PreviewAutomationBroker.make;
|
||||
const requests = yield* broker.connect(makeOwner({ tabId: null }));
|
||||
let routedTabId: string | undefined;
|
||||
yield* Stream.runForEach(requests, (request) => {
|
||||
@@ -108,7 +108,7 @@ it.effect("lets the browser host resolve an active tab that has not been reporte
|
||||
it.effect("preserves current owner metadata when its request stream reconnects", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* PreviewAutomationBroker.__testing.make;
|
||||
const broker = yield* PreviewAutomationBroker.make;
|
||||
const firstRequests = yield* broker.connect(makeOwner());
|
||||
yield* Stream.runDrain(firstRequests).pipe(Effect.forkScoped);
|
||||
yield* broker.reportOwner(makeOwner({ tabId: "tab-current", visible: true }));
|
||||
@@ -131,7 +131,7 @@ it.effect("preserves current owner metadata when its request stream reconnects",
|
||||
it.effect("ignores stale owner cleanup after the client moves to another thread", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* PreviewAutomationBroker.__testing.make;
|
||||
const broker = yield* PreviewAutomationBroker.make;
|
||||
const requests = yield* broker.connect(makeOwner());
|
||||
yield* Stream.runForEach(requests, (request) =>
|
||||
broker.respond({ requestId: request.requestId, ok: true }),
|
||||
@@ -152,7 +152,7 @@ it.effect("ignores stale owner cleanup after the client moves to another thread"
|
||||
it.effect("fails requests assigned to a browser stream when that stream reconnects", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* PreviewAutomationBroker.__testing.make;
|
||||
const broker = yield* PreviewAutomationBroker.make;
|
||||
const _requests = yield* broker.connect(makeOwner());
|
||||
const pending = yield* broker
|
||||
.invoke<void>({ scope, operation: "status", input: {} })
|
||||
@@ -170,7 +170,7 @@ it.effect("fails requests assigned to a browser stream when that stream reconnec
|
||||
it.effect("falls back to an older connected owner when a newer report is not connected", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* PreviewAutomationBroker.__testing.make;
|
||||
const broker = yield* PreviewAutomationBroker.make;
|
||||
const requests = yield* broker.connect(makeOwner({ clientId: "client-connected" }));
|
||||
yield* Stream.runForEach(requests, (request) =>
|
||||
broker.respond({ requestId: request.requestId, ok: true, result: "connected" }),
|
||||
|
||||
@@ -35,34 +35,28 @@ export interface PreviewAutomationInvokeInput {
|
||||
readonly timeoutMs?: number;
|
||||
}
|
||||
|
||||
export interface PreviewAutomationBrokerShape {
|
||||
readonly connect: (
|
||||
owner: PreviewAutomationOwner,
|
||||
) => Effect.Effect<Stream.Stream<PreviewAutomationRequest>>;
|
||||
readonly reportOwner: (
|
||||
owner: PreviewAutomationOwner,
|
||||
) => Effect.Effect<void, PreviewAutomationError>;
|
||||
readonly clearOwner: (owner: PreviewAutomationOwnerIdentity) => Effect.Effect<void>;
|
||||
readonly respond: (
|
||||
response: PreviewAutomationResponse,
|
||||
) => Effect.Effect<void, PreviewAutomationError>;
|
||||
readonly invoke: <A = unknown>(
|
||||
request: PreviewAutomationInvokeInput,
|
||||
) => Effect.Effect<A, PreviewAutomationError>;
|
||||
}
|
||||
|
||||
export class PreviewAutomationBroker extends Context.Service<
|
||||
PreviewAutomationBroker,
|
||||
PreviewAutomationBrokerShape
|
||||
{
|
||||
readonly connect: (
|
||||
owner: PreviewAutomationOwner,
|
||||
) => Effect.Effect<Stream.Stream<PreviewAutomationRequest>>;
|
||||
readonly reportOwner: (
|
||||
owner: PreviewAutomationOwner,
|
||||
) => Effect.Effect<void, PreviewAutomationError>;
|
||||
readonly clearOwner: (owner: PreviewAutomationOwnerIdentity) => Effect.Effect<void>;
|
||||
readonly respond: (
|
||||
response: PreviewAutomationResponse,
|
||||
) => Effect.Effect<void, PreviewAutomationError>;
|
||||
readonly invoke: <A = unknown>(
|
||||
request: PreviewAutomationInvokeInput,
|
||||
) => Effect.Effect<A, PreviewAutomationError>;
|
||||
}
|
||||
>()("t3/mcp/PreviewAutomationBroker") {}
|
||||
|
||||
interface ClientConnection {
|
||||
readonly clientId: string;
|
||||
readonly queue: Queue.Queue<
|
||||
Parameters<PreviewAutomationBrokerShape["respond"]>[0] extends never
|
||||
? never
|
||||
: import("@t3tools/contracts").PreviewAutomationRequest
|
||||
>;
|
||||
readonly queue: Queue.Queue<PreviewAutomationRequest>;
|
||||
}
|
||||
|
||||
interface PendingRequest {
|
||||
@@ -123,7 +117,7 @@ const makeResponseError = (
|
||||
}
|
||||
};
|
||||
|
||||
const make = Effect.gen(function* PreviewAutomationBrokerMake() {
|
||||
export const make = Effect.gen(function* PreviewAutomationBrokerMake() {
|
||||
const state = yield* SynchronizedRef.make<BrokerState>({
|
||||
clients: new Map(),
|
||||
owners: new Map(),
|
||||
@@ -166,7 +160,7 @@ const make = Effect.gen(function* PreviewAutomationBrokerMake() {
|
||||
yield* Queue.shutdown(queue);
|
||||
});
|
||||
|
||||
const connect: PreviewAutomationBrokerShape["connect"] = Effect.fn(
|
||||
const connect: PreviewAutomationBroker["Service"]["connect"] = Effect.fn(
|
||||
"PreviewAutomationBroker.connect",
|
||||
)(function* (owner) {
|
||||
const clientId = owner.clientId;
|
||||
@@ -189,7 +183,7 @@ const make = Effect.gen(function* PreviewAutomationBrokerMake() {
|
||||
return Stream.fromQueue(queue).pipe(Stream.ensuring(disconnect(clientId, queue)));
|
||||
});
|
||||
|
||||
const reportOwner: PreviewAutomationBrokerShape["reportOwner"] = Effect.fn(
|
||||
const reportOwner: PreviewAutomationBroker["Service"]["reportOwner"] = Effect.fn(
|
||||
"PreviewAutomationBroker.reportOwner",
|
||||
)(function* (owner) {
|
||||
yield* SynchronizedRef.update(state, (current) => {
|
||||
@@ -199,7 +193,7 @@ const make = Effect.gen(function* PreviewAutomationBrokerMake() {
|
||||
});
|
||||
});
|
||||
|
||||
const clearOwner: PreviewAutomationBrokerShape["clearOwner"] = Effect.fn(
|
||||
const clearOwner: PreviewAutomationBroker["Service"]["clearOwner"] = Effect.fn(
|
||||
"PreviewAutomationBroker.clearOwner",
|
||||
)(function* (owner) {
|
||||
yield* SynchronizedRef.update(state, (current) => {
|
||||
@@ -217,7 +211,7 @@ const make = Effect.gen(function* PreviewAutomationBrokerMake() {
|
||||
});
|
||||
});
|
||||
|
||||
const respond: PreviewAutomationBrokerShape["respond"] = Effect.fn(
|
||||
const respond: PreviewAutomationBroker["Service"]["respond"] = Effect.fn(
|
||||
"PreviewAutomationBroker.respond",
|
||||
)(function* (response) {
|
||||
const pending = yield* SynchronizedRef.modify(state, (current) => {
|
||||
@@ -243,7 +237,7 @@ const make = Effect.gen(function* PreviewAutomationBrokerMake() {
|
||||
});
|
||||
|
||||
const invoke = Effect.fn("PreviewAutomationBroker.invoke")(function* <A = unknown>(
|
||||
input: Parameters<PreviewAutomationBrokerShape["invoke"]>[0],
|
||||
input: Parameters<PreviewAutomationBroker["Service"]["invoke"]>[0],
|
||||
): Effect.fn.Return<A, PreviewAutomationError> {
|
||||
const current = yield* SynchronizedRef.get(state);
|
||||
const candidates = Array.from(current.owners.values())
|
||||
@@ -317,8 +311,3 @@ const make = Effect.gen(function* PreviewAutomationBrokerMake() {
|
||||
}).pipe(Effect.withSpan("PreviewAutomationBroker.make"));
|
||||
|
||||
export const layer = Layer.effect(PreviewAutomationBroker, make);
|
||||
|
||||
/** Exposed for tests. */
|
||||
export const __testing = {
|
||||
make,
|
||||
};
|
||||
@@ -0,0 +1,23 @@
|
||||
import type { TraceRecord, TraceSink } from "@t3tools/shared/observability";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
|
||||
export class BrowserTraceCollector extends Context.Service<
|
||||
BrowserTraceCollector,
|
||||
{
|
||||
readonly record: (records: ReadonlyArray<TraceRecord>) => Effect.Effect<void>;
|
||||
}
|
||||
>()("t3/observability/BrowserTraceCollector") {}
|
||||
|
||||
export const make = (sink: TraceSink): BrowserTraceCollector["Service"] =>
|
||||
BrowserTraceCollector.of({
|
||||
record: (records) =>
|
||||
Effect.sync(() => {
|
||||
for (const record of records) {
|
||||
sink.push(record);
|
||||
}
|
||||
}),
|
||||
});
|
||||
|
||||
export const layer = (sink: TraceSink) => Layer.succeed(BrowserTraceCollector, make(sink));
|
||||
@@ -4,17 +4,19 @@ import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as References from "effect/References";
|
||||
import * as Tracer from "effect/Tracer";
|
||||
import { OtlpMetrics, OtlpSerialization, OtlpTracer } from "effect/unstable/observability";
|
||||
import * as OtlpMetrics from "effect/unstable/observability/OtlpMetrics";
|
||||
import * as OtlpSerialization from "effect/unstable/observability/OtlpSerialization";
|
||||
import * as OtlpTracer from "effect/unstable/observability/OtlpTracer";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import * as ServerConfig from "../../config.ts";
|
||||
import { ServerLoggerLive } from "../../serverLogger.ts";
|
||||
import { BrowserTraceCollector } from "../Services/BrowserTraceCollector.ts";
|
||||
import * as BrowserTraceCollector from "../BrowserTraceCollector.ts";
|
||||
|
||||
const otlpSerializationLayer = OtlpSerialization.layerJson;
|
||||
|
||||
export const ObservabilityLive = Layer.unwrap(
|
||||
Effect.gen(function* () {
|
||||
const config = yield* ServerConfig;
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
|
||||
const traceReferencesLayer = Layer.mergeAll(
|
||||
Layer.succeed(Tracer.MinimumTraceLevel, config.traceMinLevel),
|
||||
@@ -56,14 +58,7 @@ export const ObservabilityLive = Layer.unwrap(
|
||||
|
||||
return Layer.mergeAll(
|
||||
Layer.succeed(Tracer.Tracer, tracer),
|
||||
Layer.succeed(BrowserTraceCollector, {
|
||||
record: (records) =>
|
||||
Effect.sync(() => {
|
||||
for (const record of records) {
|
||||
sink.push(record);
|
||||
}
|
||||
}),
|
||||
}),
|
||||
BrowserTraceCollector.layer(sink),
|
||||
);
|
||||
}),
|
||||
).pipe(Layer.provideMerge(otlpSerializationLayer));
|
||||
|
||||
@@ -1,12 +0,0 @@
|
||||
import type { TraceRecord } from "@t3tools/shared/observability";
|
||||
import * as Context from "effect/Context";
|
||||
import type * as Effect from "effect/Effect";
|
||||
|
||||
export interface BrowserTraceCollectorShape {
|
||||
readonly record: (records: ReadonlyArray<TraceRecord>) => Effect.Effect<void>;
|
||||
}
|
||||
|
||||
export class BrowserTraceCollector extends Context.Service<
|
||||
BrowserTraceCollector,
|
||||
BrowserTraceCollectorShape
|
||||
>()("t3/observability/Services/BrowserTraceCollector") {}
|
||||
@@ -30,8 +30,7 @@ import * as Scope from "effect/Scope";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import { CheckpointStoreLive } from "../../checkpointing/Layers/CheckpointStore.ts";
|
||||
import { CheckpointStore } from "../../checkpointing/Services/CheckpointStore.ts";
|
||||
import * as CheckpointStore from "../../checkpointing/CheckpointStore.ts";
|
||||
import * as VcsDriverRegistry from "../../vcs/VcsDriverRegistry.ts";
|
||||
import * as VcsProcess from "../../vcs/VcsProcess.ts";
|
||||
import { VcsStatusBroadcaster } from "../../vcs/VcsStatusBroadcaster.ts";
|
||||
@@ -247,7 +246,10 @@ async function waitForGitRefExists(cwd: string, ref: string, timeoutMs = 15_000)
|
||||
|
||||
describe("CheckpointReactor", () => {
|
||||
let runtime: ManagedRuntime.ManagedRuntime<
|
||||
OrchestrationEngineService | CheckpointReactor | CheckpointStore | ProjectionSnapshotQuery,
|
||||
| OrchestrationEngineService
|
||||
| CheckpointReactor
|
||||
| CheckpointStore.CheckpointStore
|
||||
| ProjectionSnapshotQuery,
|
||||
unknown
|
||||
> | null = null;
|
||||
let scope: Scope.Closeable | null = null;
|
||||
@@ -328,7 +330,7 @@ describe("CheckpointReactor", () => {
|
||||
Layer.provideMerge(RuntimeReceiptBusLive),
|
||||
Layer.provideMerge(Layer.succeed(ProviderService, provider.service)),
|
||||
Layer.provideMerge(vcsStatusBroadcasterLayer),
|
||||
Layer.provideMerge(CheckpointStoreLive.pipe(Layer.provide(VcsDriverRegistry.layer))),
|
||||
Layer.provideMerge(CheckpointStore.layer.pipe(Layer.provide(VcsDriverRegistry.layer))),
|
||||
Layer.provideMerge(
|
||||
WorkspaceEntries.layer.pipe(
|
||||
Layer.provide(WorkspacePathsLive),
|
||||
@@ -345,7 +347,9 @@ describe("CheckpointReactor", () => {
|
||||
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
|
||||
const snapshotQuery = await runtime.runPromise(Effect.service(ProjectionSnapshotQuery));
|
||||
const reactor = await runtime.runPromise(Effect.service(CheckpointReactor));
|
||||
const checkpointStore = await runtime.runPromise(Effect.service(CheckpointStore));
|
||||
const checkpointStore = await runtime.runPromise(
|
||||
Effect.service(CheckpointStore.CheckpointStore),
|
||||
);
|
||||
scope = await Effect.runPromise(Scope.make("sequential"));
|
||||
await Effect.runPromise(reactor.start().pipe(Scope.provide(scope)));
|
||||
const drain = () => Effect.runPromise(reactor.drain);
|
||||
|
||||
@@ -24,7 +24,7 @@ import {
|
||||
checkpointRefForThreadTurn,
|
||||
resolveThreadWorkspaceCwd,
|
||||
} from "../../checkpointing/Utils.ts";
|
||||
import { CheckpointStore } from "../../checkpointing/Services/CheckpointStore.ts";
|
||||
import * as CheckpointStore from "../../checkpointing/CheckpointStore.ts";
|
||||
import { ProviderService } from "../../provider/Services/ProviderService.ts";
|
||||
import { CheckpointReactor, type CheckpointReactorShape } from "../Services/CheckpointReactor.ts";
|
||||
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
|
||||
@@ -81,7 +81,7 @@ const make = Effect.gen(function* () {
|
||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
const providerService = yield* ProviderService;
|
||||
const checkpointStore = yield* CheckpointStore;
|
||||
const checkpointStore = yield* CheckpointStore.CheckpointStore;
|
||||
const receiptBus = yield* RuntimeReceiptBus;
|
||||
const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
|
||||
const vcsStatusBroadcaster = yield* VcsStatusBroadcaster;
|
||||
|
||||
@@ -59,7 +59,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import * as Clock from "effect/Clock";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { VcsStatusBroadcaster } from "../../vcs/VcsStatusBroadcaster.ts";
|
||||
import { GitWorkflowService, type GitWorkflowServiceShape } from "../../git/GitWorkflowService.ts";
|
||||
import * as GitWorkflowService from "../../git/GitWorkflowService.ts";
|
||||
|
||||
const asProjectId = (value: string): ProjectId => ProjectId.make(value);
|
||||
const asApprovalRequestId = (value: string): ApprovalRequestId => ApprovalRequestId.make(value);
|
||||
@@ -348,9 +348,9 @@ describe("ProviderCommandReactor", () => {
|
||||
Layer.provideMerge(Layer.succeed(ProviderService, service)),
|
||||
Layer.provideMerge(makeProviderRegistryLayer(providerSnapshots as never)),
|
||||
Layer.provideMerge(
|
||||
Layer.mock(GitWorkflowService)({
|
||||
Layer.mock(GitWorkflowService.GitWorkflowService)({
|
||||
renameBranch,
|
||||
} satisfies Partial<GitWorkflowServiceShape>),
|
||||
} satisfies Partial<GitWorkflowService.GitWorkflowService["Service"]>),
|
||||
),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(VcsStatusBroadcaster, {
|
||||
|
||||
@@ -6,7 +6,7 @@ import * as Layer from "effect/Layer";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import { ProviderService } from "../../provider/Services/ProviderService.ts";
|
||||
import { TerminalManager } from "../../terminal/Services/Manager.ts";
|
||||
import * as TerminalManager from "../../terminal/Manager.ts";
|
||||
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
|
||||
import {
|
||||
ThreadDeletionReactor,
|
||||
@@ -39,7 +39,7 @@ export const logCleanupCauseUnlessInterrupted = <R, E>({
|
||||
const make = Effect.gen(function* () {
|
||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||
const providerService = yield* ProviderService;
|
||||
const terminalManager = yield* TerminalManager;
|
||||
const terminalManager = yield* TerminalManager.TerminalManager;
|
||||
|
||||
const stopProviderSession = (threadId: ThreadDeletedEvent["payload"]["threadId"]) =>
|
||||
logCleanupCauseUnlessInterrupted({
|
||||
|
||||
+88
-24
@@ -1,24 +1,91 @@
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
import * as SqlSchema from "effect/unstable/sql/SqlSchema";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
import * as SqlSchema from "effect/unstable/sql/SqlSchema";
|
||||
|
||||
import { AuthEnvironmentScopes } from "@t3tools/contracts";
|
||||
|
||||
import {
|
||||
type AuthPairingLinkRepositoryError,
|
||||
toPersistenceDecodeError,
|
||||
toPersistenceSqlError,
|
||||
type AuthPairingLinkRepositoryError,
|
||||
} from "../Errors.ts";
|
||||
import {
|
||||
AuthPairingLinkRecord,
|
||||
} from "./Errors.ts";
|
||||
|
||||
export const AuthPairingLinkRecord = Schema.Struct({
|
||||
id: Schema.String,
|
||||
credential: Schema.String,
|
||||
method: Schema.Literals(["desktop-bootstrap", "one-time-token"]),
|
||||
scopes: Schema.fromJsonString(AuthEnvironmentScopes),
|
||||
subject: Schema.String,
|
||||
label: Schema.NullOr(Schema.String),
|
||||
proofKeyThumbprint: Schema.NullOr(Schema.String),
|
||||
createdAt: Schema.DateTimeUtcFromString,
|
||||
expiresAt: Schema.DateTimeUtcFromString,
|
||||
consumedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
|
||||
revokedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
|
||||
});
|
||||
export type AuthPairingLinkRecord = typeof AuthPairingLinkRecord.Type;
|
||||
|
||||
export const CreateAuthPairingLinkInput = Schema.Struct({
|
||||
id: Schema.String,
|
||||
credential: Schema.String,
|
||||
method: Schema.Literals(["desktop-bootstrap", "one-time-token"]),
|
||||
scopes: AuthEnvironmentScopes,
|
||||
subject: Schema.String,
|
||||
label: Schema.NullOr(Schema.String),
|
||||
proofKeyThumbprint: Schema.NullOr(Schema.String),
|
||||
createdAt: Schema.DateTimeUtcFromString,
|
||||
expiresAt: Schema.DateTimeUtcFromString,
|
||||
});
|
||||
export type CreateAuthPairingLinkInput = typeof CreateAuthPairingLinkInput.Type;
|
||||
|
||||
export const ConsumeAuthPairingLinkInput = Schema.Struct({
|
||||
credential: Schema.String,
|
||||
proofKeyThumbprint: Schema.NullOr(Schema.String),
|
||||
consumedAt: Schema.DateTimeUtcFromString,
|
||||
now: Schema.DateTimeUtcFromString,
|
||||
});
|
||||
export type ConsumeAuthPairingLinkInput = typeof ConsumeAuthPairingLinkInput.Type;
|
||||
|
||||
export const ListActiveAuthPairingLinksInput = Schema.Struct({
|
||||
now: Schema.DateTimeUtcFromString,
|
||||
});
|
||||
export type ListActiveAuthPairingLinksInput = typeof ListActiveAuthPairingLinksInput.Type;
|
||||
|
||||
export const RevokeAuthPairingLinkInput = Schema.Struct({
|
||||
id: Schema.String,
|
||||
revokedAt: Schema.DateTimeUtcFromString,
|
||||
});
|
||||
export type RevokeAuthPairingLinkInput = typeof RevokeAuthPairingLinkInput.Type;
|
||||
|
||||
export const GetAuthPairingLinkByCredentialInput = Schema.Struct({
|
||||
credential: Schema.String,
|
||||
});
|
||||
export type GetAuthPairingLinkByCredentialInput = typeof GetAuthPairingLinkByCredentialInput.Type;
|
||||
|
||||
export class AuthPairingLinkRepository extends Context.Service<
|
||||
AuthPairingLinkRepository,
|
||||
type AuthPairingLinkRepositoryShape,
|
||||
ConsumeAuthPairingLinkInput,
|
||||
CreateAuthPairingLinkInput,
|
||||
GetAuthPairingLinkByCredentialInput,
|
||||
ListActiveAuthPairingLinksInput,
|
||||
RevokeAuthPairingLinkInput,
|
||||
} from "../Services/AuthPairingLinks.ts";
|
||||
{
|
||||
readonly create: (
|
||||
input: CreateAuthPairingLinkInput,
|
||||
) => Effect.Effect<void, AuthPairingLinkRepositoryError>;
|
||||
readonly consumeAvailable: (
|
||||
input: ConsumeAuthPairingLinkInput,
|
||||
) => Effect.Effect<Option.Option<AuthPairingLinkRecord>, AuthPairingLinkRepositoryError>;
|
||||
readonly listActive: (
|
||||
input: ListActiveAuthPairingLinksInput,
|
||||
) => Effect.Effect<ReadonlyArray<AuthPairingLinkRecord>, AuthPairingLinkRepositoryError>;
|
||||
readonly revoke: (
|
||||
input: RevokeAuthPairingLinkInput,
|
||||
) => Effect.Effect<boolean, AuthPairingLinkRepositoryError>;
|
||||
readonly getByCredential: (
|
||||
input: GetAuthPairingLinkByCredentialInput,
|
||||
) => Effect.Effect<Option.Option<AuthPairingLinkRecord>, AuthPairingLinkRepositoryError>;
|
||||
}
|
||||
>()("t3/persistence/AuthPairingLinks/AuthPairingLinkRepository") {}
|
||||
|
||||
function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: string) {
|
||||
return (cause: unknown): AuthPairingLinkRepositoryError =>
|
||||
@@ -27,7 +94,7 @@ function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: st
|
||||
: toPersistenceSqlError(sqlOperation)(cause);
|
||||
}
|
||||
|
||||
const makeAuthPairingLinkRepository = Effect.gen(function* () {
|
||||
export const make = Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
const createPairingLinkRow = SqlSchema.void({
|
||||
@@ -154,7 +221,7 @@ const makeAuthPairingLinkRepository = Effect.gen(function* () {
|
||||
`,
|
||||
});
|
||||
|
||||
const create: AuthPairingLinkRepositoryShape["create"] = (input) =>
|
||||
const create: AuthPairingLinkRepository["Service"]["create"] = (input) =>
|
||||
createPairingLinkRow(input).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
@@ -164,7 +231,7 @@ const makeAuthPairingLinkRepository = Effect.gen(function* () {
|
||||
),
|
||||
);
|
||||
|
||||
const consumeAvailable: AuthPairingLinkRepositoryShape["consumeAvailable"] = (input) =>
|
||||
const consumeAvailable: AuthPairingLinkRepository["Service"]["consumeAvailable"] = (input) =>
|
||||
consumeAvailablePairingLinkRow(input).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
@@ -174,7 +241,7 @@ const makeAuthPairingLinkRepository = Effect.gen(function* () {
|
||||
),
|
||||
);
|
||||
|
||||
const listActive: AuthPairingLinkRepositoryShape["listActive"] = (input) =>
|
||||
const listActive: AuthPairingLinkRepository["Service"]["listActive"] = (input) =>
|
||||
listActivePairingLinkRows(input).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
@@ -184,7 +251,7 @@ const makeAuthPairingLinkRepository = Effect.gen(function* () {
|
||||
),
|
||||
);
|
||||
|
||||
const revoke: AuthPairingLinkRepositoryShape["revoke"] = (input) =>
|
||||
const revoke: AuthPairingLinkRepository["Service"]["revoke"] = (input) =>
|
||||
revokePairingLinkRow(input).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
@@ -195,7 +262,7 @@ const makeAuthPairingLinkRepository = Effect.gen(function* () {
|
||||
Effect.map((rows) => rows.length > 0),
|
||||
);
|
||||
|
||||
const getByCredential: AuthPairingLinkRepositoryShape["getByCredential"] = (input) =>
|
||||
const getByCredential: AuthPairingLinkRepository["Service"]["getByCredential"] = (input) =>
|
||||
getPairingLinkRowByCredential(input).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
@@ -211,10 +278,7 @@ const makeAuthPairingLinkRepository = Effect.gen(function* () {
|
||||
listActive,
|
||||
revoke,
|
||||
getByCredential,
|
||||
} satisfies AuthPairingLinkRepositoryShape;
|
||||
} satisfies AuthPairingLinkRepository["Service"];
|
||||
});
|
||||
|
||||
export const AuthPairingLinkRepositoryLive = Layer.effect(
|
||||
AuthPairingLinkRepository,
|
||||
makeAuthPairingLinkRepository,
|
||||
);
|
||||
export const layer = Layer.effect(AuthPairingLinkRepository, make);
|
||||
+106
-27
@@ -1,27 +1,109 @@
|
||||
import { AuthEnvironmentScopes, AuthSessionId, ServerAuthSessionMethod } from "@t3tools/contracts";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
import * as SqlSchema from "effect/unstable/sql/SqlSchema";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
import * as SqlSchema from "effect/unstable/sql/SqlSchema";
|
||||
|
||||
import {
|
||||
AuthClientMetadataDeviceType,
|
||||
AuthEnvironmentScopes,
|
||||
AuthSessionId,
|
||||
ServerAuthSessionMethod,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import {
|
||||
type AuthSessionRepositoryError,
|
||||
toPersistenceDecodeError,
|
||||
toPersistenceSqlError,
|
||||
type AuthSessionRepositoryError,
|
||||
} from "../Errors.ts";
|
||||
import {
|
||||
AuthSessionRecord,
|
||||
} from "./Errors.ts";
|
||||
|
||||
export const AuthSessionClientMetadataRecord = Schema.Struct({
|
||||
label: Schema.NullOr(Schema.String),
|
||||
ipAddress: Schema.NullOr(Schema.String),
|
||||
userAgent: Schema.NullOr(Schema.String),
|
||||
deviceType: AuthClientMetadataDeviceType,
|
||||
os: Schema.NullOr(Schema.String),
|
||||
browser: Schema.NullOr(Schema.String),
|
||||
});
|
||||
export type AuthSessionClientMetadataRecord = typeof AuthSessionClientMetadataRecord.Type;
|
||||
|
||||
export const AuthSessionRecord = Schema.Struct({
|
||||
sessionId: AuthSessionId,
|
||||
subject: Schema.String,
|
||||
scopes: AuthEnvironmentScopes,
|
||||
method: ServerAuthSessionMethod,
|
||||
client: AuthSessionClientMetadataRecord,
|
||||
issuedAt: Schema.DateTimeUtcFromString,
|
||||
expiresAt: Schema.DateTimeUtcFromString,
|
||||
lastConnectedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
|
||||
revokedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
|
||||
});
|
||||
export type AuthSessionRecord = typeof AuthSessionRecord.Type;
|
||||
|
||||
export const CreateAuthSessionInput = Schema.Struct({
|
||||
sessionId: AuthSessionId,
|
||||
subject: Schema.String,
|
||||
scopes: AuthEnvironmentScopes,
|
||||
method: ServerAuthSessionMethod,
|
||||
client: AuthSessionClientMetadataRecord,
|
||||
issuedAt: Schema.DateTimeUtcFromString,
|
||||
expiresAt: Schema.DateTimeUtcFromString,
|
||||
});
|
||||
export type CreateAuthSessionInput = typeof CreateAuthSessionInput.Type;
|
||||
|
||||
export const GetAuthSessionByIdInput = Schema.Struct({
|
||||
sessionId: AuthSessionId,
|
||||
});
|
||||
export type GetAuthSessionByIdInput = typeof GetAuthSessionByIdInput.Type;
|
||||
|
||||
export const ListActiveAuthSessionsInput = Schema.Struct({
|
||||
now: Schema.DateTimeUtcFromString,
|
||||
});
|
||||
export type ListActiveAuthSessionsInput = typeof ListActiveAuthSessionsInput.Type;
|
||||
|
||||
export const RevokeAuthSessionInput = Schema.Struct({
|
||||
sessionId: AuthSessionId,
|
||||
revokedAt: Schema.DateTimeUtcFromString,
|
||||
});
|
||||
export type RevokeAuthSessionInput = typeof RevokeAuthSessionInput.Type;
|
||||
|
||||
export const RevokeOtherAuthSessionsInput = Schema.Struct({
|
||||
currentSessionId: AuthSessionId,
|
||||
revokedAt: Schema.DateTimeUtcFromString,
|
||||
});
|
||||
export type RevokeOtherAuthSessionsInput = typeof RevokeOtherAuthSessionsInput.Type;
|
||||
|
||||
export const SetAuthSessionLastConnectedAtInput = Schema.Struct({
|
||||
sessionId: AuthSessionId,
|
||||
lastConnectedAt: Schema.DateTimeUtcFromString,
|
||||
});
|
||||
export type SetAuthSessionLastConnectedAtInput = typeof SetAuthSessionLastConnectedAtInput.Type;
|
||||
|
||||
export class AuthSessionRepository extends Context.Service<
|
||||
AuthSessionRepository,
|
||||
type AuthSessionRepositoryShape,
|
||||
CreateAuthSessionInput,
|
||||
GetAuthSessionByIdInput,
|
||||
ListActiveAuthSessionsInput,
|
||||
RevokeAuthSessionInput,
|
||||
RevokeOtherAuthSessionsInput,
|
||||
SetAuthSessionLastConnectedAtInput,
|
||||
} from "../Services/AuthSessions.ts";
|
||||
{
|
||||
readonly create: (
|
||||
input: CreateAuthSessionInput,
|
||||
) => Effect.Effect<void, AuthSessionRepositoryError>;
|
||||
readonly getById: (
|
||||
input: GetAuthSessionByIdInput,
|
||||
) => Effect.Effect<Option.Option<AuthSessionRecord>, AuthSessionRepositoryError>;
|
||||
readonly listActive: (
|
||||
input: ListActiveAuthSessionsInput,
|
||||
) => Effect.Effect<ReadonlyArray<AuthSessionRecord>, AuthSessionRepositoryError>;
|
||||
readonly revoke: (
|
||||
input: RevokeAuthSessionInput,
|
||||
) => Effect.Effect<boolean, AuthSessionRepositoryError>;
|
||||
readonly revokeAllExcept: (
|
||||
input: RevokeOtherAuthSessionsInput,
|
||||
) => Effect.Effect<ReadonlyArray<AuthSessionId>, AuthSessionRepositoryError>;
|
||||
readonly setLastConnectedAt: (
|
||||
input: SetAuthSessionLastConnectedAtInput,
|
||||
) => Effect.Effect<void, AuthSessionRepositoryError>;
|
||||
}
|
||||
>()("t3/persistence/AuthSessions/AuthSessionRepository") {}
|
||||
|
||||
const AuthSessionDbRow = Schema.Struct({
|
||||
sessionId: AuthSessionId,
|
||||
@@ -68,7 +150,7 @@ function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: st
|
||||
: toPersistenceSqlError(sqlOperation)(cause);
|
||||
}
|
||||
|
||||
const makeAuthSessionRepository = Effect.gen(function* () {
|
||||
export const make = Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
const createSessionRow = SqlSchema.void({
|
||||
@@ -197,7 +279,7 @@ const makeAuthSessionRepository = Effect.gen(function* () {
|
||||
`,
|
||||
});
|
||||
|
||||
const create: AuthSessionRepositoryShape["create"] = (input) =>
|
||||
const create: AuthSessionRepository["Service"]["create"] = (input) =>
|
||||
createSessionRow(input).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
@@ -207,7 +289,7 @@ const makeAuthSessionRepository = Effect.gen(function* () {
|
||||
),
|
||||
);
|
||||
|
||||
const getById: AuthSessionRepositoryShape["getById"] = (input) =>
|
||||
const getById: AuthSessionRepository["Service"]["getById"] = (input) =>
|
||||
getSessionRowById(input).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
@@ -223,7 +305,7 @@ const makeAuthSessionRepository = Effect.gen(function* () {
|
||||
),
|
||||
);
|
||||
|
||||
const listActive: AuthSessionRepositoryShape["listActive"] = (input) =>
|
||||
const listActive: AuthSessionRepository["Service"]["listActive"] = (input) =>
|
||||
listActiveSessionRows(input).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
@@ -234,7 +316,7 @@ const makeAuthSessionRepository = Effect.gen(function* () {
|
||||
Effect.flatMap((rows) => Effect.succeed(rows.map((row) => toAuthSessionRecord(row)))),
|
||||
);
|
||||
|
||||
const revoke: AuthSessionRepositoryShape["revoke"] = (input) =>
|
||||
const revoke: AuthSessionRepository["Service"]["revoke"] = (input) =>
|
||||
revokeSessionRows(input).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
@@ -245,7 +327,7 @@ const makeAuthSessionRepository = Effect.gen(function* () {
|
||||
Effect.map((rows) => rows.length > 0),
|
||||
);
|
||||
|
||||
const revokeAllExcept: AuthSessionRepositoryShape["revokeAllExcept"] = (input) =>
|
||||
const revokeAllExcept: AuthSessionRepository["Service"]["revokeAllExcept"] = (input) =>
|
||||
revokeOtherSessionRows(input).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
@@ -256,7 +338,7 @@ const makeAuthSessionRepository = Effect.gen(function* () {
|
||||
Effect.map((rows) => rows.map((row) => row.sessionId)),
|
||||
);
|
||||
|
||||
const setLastConnectedAt: AuthSessionRepositoryShape["setLastConnectedAt"] = (input) =>
|
||||
const setLastConnectedAt: AuthSessionRepository["Service"]["setLastConnectedAt"] = (input) =>
|
||||
setLastConnectedAtRow(input).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
@@ -273,10 +355,7 @@ const makeAuthSessionRepository = Effect.gen(function* () {
|
||||
revoke,
|
||||
revokeAllExcept,
|
||||
setLastConnectedAt,
|
||||
} satisfies AuthSessionRepositoryShape;
|
||||
} satisfies AuthSessionRepository["Service"];
|
||||
});
|
||||
|
||||
export const AuthSessionRepositoryLive = Layer.effect(
|
||||
AuthSessionRepository,
|
||||
makeAuthSessionRepository,
|
||||
);
|
||||
export const layer = Layer.effect(AuthSessionRepository, make);
|
||||
@@ -1,208 +1,2 @@
|
||||
import { ThreadId } from "@t3tools/contracts";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
import * as SqlSchema from "effect/unstable/sql/SqlSchema";
|
||||
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 Struct from "effect/Struct";
|
||||
|
||||
import {
|
||||
toPersistenceDecodeError,
|
||||
toPersistenceSqlError,
|
||||
type ProviderSessionRuntimeRepositoryError,
|
||||
} from "../Errors.ts";
|
||||
import {
|
||||
ProviderSessionRuntime,
|
||||
ProviderSessionRuntimeRepository,
|
||||
type ProviderSessionRuntimeRepositoryShape,
|
||||
} from "../Services/ProviderSessionRuntime.ts";
|
||||
|
||||
const ProviderSessionRuntimeDbRowSchema = ProviderSessionRuntime.mapFields(
|
||||
Struct.assign({
|
||||
resumeCursor: Schema.NullOr(Schema.fromJsonString(Schema.Unknown)),
|
||||
runtimePayload: Schema.NullOr(Schema.fromJsonString(Schema.Unknown)),
|
||||
}),
|
||||
);
|
||||
|
||||
const decodeRuntime = Schema.decodeUnknownEffect(ProviderSessionRuntime);
|
||||
|
||||
const GetRuntimeRequestSchema = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
});
|
||||
|
||||
const DeleteRuntimeRequestSchema = GetRuntimeRequestSchema;
|
||||
|
||||
function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: string) {
|
||||
return (cause: unknown): ProviderSessionRuntimeRepositoryError =>
|
||||
Schema.isSchemaError(cause)
|
||||
? toPersistenceDecodeError(decodeOperation)(cause)
|
||||
: toPersistenceSqlError(sqlOperation)(cause);
|
||||
}
|
||||
|
||||
const makeProviderSessionRuntimeRepository = Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
const upsertRuntimeRow = SqlSchema.void({
|
||||
Request: ProviderSessionRuntimeDbRowSchema,
|
||||
execute: (runtime) =>
|
||||
sql`
|
||||
INSERT INTO provider_session_runtime (
|
||||
thread_id,
|
||||
provider_name,
|
||||
provider_instance_id,
|
||||
adapter_key,
|
||||
runtime_mode,
|
||||
status,
|
||||
last_seen_at,
|
||||
resume_cursor_json,
|
||||
runtime_payload_json
|
||||
)
|
||||
VALUES (
|
||||
${runtime.threadId},
|
||||
${runtime.providerName},
|
||||
${runtime.providerInstanceId},
|
||||
${runtime.adapterKey},
|
||||
${runtime.runtimeMode},
|
||||
${runtime.status},
|
||||
${runtime.lastSeenAt},
|
||||
${runtime.resumeCursor},
|
||||
${runtime.runtimePayload}
|
||||
)
|
||||
ON CONFLICT (thread_id)
|
||||
DO UPDATE SET
|
||||
provider_name = excluded.provider_name,
|
||||
provider_instance_id = excluded.provider_instance_id,
|
||||
adapter_key = excluded.adapter_key,
|
||||
runtime_mode = excluded.runtime_mode,
|
||||
status = excluded.status,
|
||||
last_seen_at = excluded.last_seen_at,
|
||||
resume_cursor_json = excluded.resume_cursor_json,
|
||||
runtime_payload_json = excluded.runtime_payload_json
|
||||
`,
|
||||
});
|
||||
|
||||
const getRuntimeRowByThreadId = SqlSchema.findOneOption({
|
||||
Request: GetRuntimeRequestSchema,
|
||||
Result: ProviderSessionRuntimeDbRowSchema,
|
||||
execute: ({ threadId }) =>
|
||||
sql`
|
||||
SELECT
|
||||
thread_id AS "threadId",
|
||||
provider_name AS "providerName",
|
||||
provider_instance_id AS "providerInstanceId",
|
||||
adapter_key AS "adapterKey",
|
||||
runtime_mode AS "runtimeMode",
|
||||
status,
|
||||
last_seen_at AS "lastSeenAt",
|
||||
resume_cursor_json AS "resumeCursor",
|
||||
runtime_payload_json AS "runtimePayload"
|
||||
FROM provider_session_runtime
|
||||
WHERE thread_id = ${threadId}
|
||||
`,
|
||||
});
|
||||
|
||||
const listRuntimeRows = SqlSchema.findAll({
|
||||
Request: Schema.Void,
|
||||
Result: ProviderSessionRuntimeDbRowSchema,
|
||||
execute: () =>
|
||||
sql`
|
||||
SELECT
|
||||
thread_id AS "threadId",
|
||||
provider_name AS "providerName",
|
||||
provider_instance_id AS "providerInstanceId",
|
||||
adapter_key AS "adapterKey",
|
||||
runtime_mode AS "runtimeMode",
|
||||
status,
|
||||
last_seen_at AS "lastSeenAt",
|
||||
resume_cursor_json AS "resumeCursor",
|
||||
runtime_payload_json AS "runtimePayload"
|
||||
FROM provider_session_runtime
|
||||
ORDER BY last_seen_at ASC, thread_id ASC
|
||||
`,
|
||||
});
|
||||
|
||||
const deleteRuntimeByThreadId = SqlSchema.void({
|
||||
Request: DeleteRuntimeRequestSchema,
|
||||
execute: ({ threadId }) =>
|
||||
sql`
|
||||
DELETE FROM provider_session_runtime
|
||||
WHERE thread_id = ${threadId}
|
||||
`,
|
||||
});
|
||||
|
||||
const upsert: ProviderSessionRuntimeRepositoryShape["upsert"] = (runtime) =>
|
||||
upsertRuntimeRow(runtime).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProviderSessionRuntimeRepository.upsert:query",
|
||||
"ProviderSessionRuntimeRepository.upsert:encodeRequest",
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const getByThreadId: ProviderSessionRuntimeRepositoryShape["getByThreadId"] = (input) =>
|
||||
getRuntimeRowByThreadId(input).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProviderSessionRuntimeRepository.getByThreadId:query",
|
||||
"ProviderSessionRuntimeRepository.getByThreadId:decodeRow",
|
||||
),
|
||||
),
|
||||
Effect.flatMap((runtimeRowOption) =>
|
||||
Option.match(runtimeRowOption, {
|
||||
onNone: () => Effect.succeed(Option.none()),
|
||||
onSome: (row) =>
|
||||
decodeRuntime(row).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceDecodeError(
|
||||
"ProviderSessionRuntimeRepository.getByThreadId:rowToRuntime",
|
||||
),
|
||||
),
|
||||
Effect.map((runtime) => Option.some(runtime)),
|
||||
),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const list: ProviderSessionRuntimeRepositoryShape["list"] = () =>
|
||||
listRuntimeRows(undefined).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProviderSessionRuntimeRepository.list:query",
|
||||
"ProviderSessionRuntimeRepository.list:decodeRows",
|
||||
),
|
||||
),
|
||||
Effect.flatMap((rows) =>
|
||||
Effect.forEach(
|
||||
rows,
|
||||
(row) =>
|
||||
decodeRuntime(row).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceDecodeError("ProviderSessionRuntimeRepository.list:rowToRuntime"),
|
||||
),
|
||||
),
|
||||
{ concurrency: "unbounded" },
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const deleteByThreadId: ProviderSessionRuntimeRepositoryShape["deleteByThreadId"] = (input) =>
|
||||
deleteRuntimeByThreadId(input).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlError("ProviderSessionRuntimeRepository.deleteByThreadId:query"),
|
||||
),
|
||||
);
|
||||
|
||||
return {
|
||||
upsert,
|
||||
getByThreadId,
|
||||
list,
|
||||
deleteByThreadId,
|
||||
} satisfies ProviderSessionRuntimeRepositoryShape;
|
||||
});
|
||||
|
||||
export const ProviderSessionRuntimeRepositoryLive = Layer.effect(
|
||||
ProviderSessionRuntimeRepository,
|
||||
makeProviderSessionRuntimeRepository,
|
||||
);
|
||||
/** @deprecated Compatibility alias for the excluded orchestration integration harness. */
|
||||
export { layer as ProviderSessionRuntimeRepositoryLive } from "../ProviderSessionRuntime.ts";
|
||||
@@ -29,11 +29,6 @@ export const TypeId: TypeId = "~local/sqlite-node/SqliteClient";
|
||||
|
||||
export type TypeId = "~local/sqlite-node/SqliteClient";
|
||||
|
||||
/**
|
||||
* SqliteClient - Effect service tag for the sqlite SQL client.
|
||||
*/
|
||||
export const SqliteClient = Context.Service<Client.SqlClient>("t3/persistence/NodeSqliteClient");
|
||||
|
||||
export interface SqliteClientConfig {
|
||||
readonly filename: string;
|
||||
readonly readonly?: boolean | undefined;
|
||||
@@ -251,25 +246,12 @@ const makeMemory = (
|
||||
export const layerConfig = (
|
||||
config: Config.Wrap<SqliteClientConfig>,
|
||||
): Layer.Layer<Client.SqlClient, Config.ConfigError> =>
|
||||
Layer.effectContext(
|
||||
Config.unwrap(config).pipe(
|
||||
Effect.flatMap(make),
|
||||
Effect.map((client) =>
|
||||
Context.make(SqliteClient, client).pipe(Context.add(Client.SqlClient, client)),
|
||||
),
|
||||
),
|
||||
).pipe(Layer.provide(Reactivity.layer));
|
||||
Layer.effect(Client.SqlClient, Config.unwrap(config).pipe(Effect.flatMap(make))).pipe(
|
||||
Layer.provide(Reactivity.layer),
|
||||
);
|
||||
|
||||
export const layer = (config: SqliteClientConfig): Layer.Layer<Client.SqlClient> =>
|
||||
Layer.effectContext(
|
||||
Effect.map(make(config), (client) =>
|
||||
Context.make(SqliteClient, client).pipe(Context.add(Client.SqlClient, client)),
|
||||
),
|
||||
).pipe(Layer.provide(Reactivity.layer));
|
||||
Layer.effect(Client.SqlClient, make(config)).pipe(Layer.provide(Reactivity.layer));
|
||||
|
||||
export const layerMemory = (config: SqliteMemoryClientConfig = {}): Layer.Layer<Client.SqlClient> =>
|
||||
Layer.effectContext(
|
||||
Effect.map(makeMemory(config), (client) =>
|
||||
Context.make(SqliteClient, client).pipe(Context.add(Client.SqlClient, client)),
|
||||
),
|
||||
).pipe(Layer.provide(Reactivity.layer));
|
||||
Layer.effect(Client.SqlClient, makeMemory(config)).pipe(Layer.provide(Reactivity.layer));
|
||||
@@ -0,0 +1,288 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Struct from "effect/Struct";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
import * as SqlSchema from "effect/unstable/sql/SqlSchema";
|
||||
|
||||
import {
|
||||
IsoDateTime,
|
||||
ProviderInstanceId,
|
||||
ProviderSessionRuntimeStatus,
|
||||
RuntimeMode,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import {
|
||||
type ProviderSessionRuntimeRepositoryError,
|
||||
toPersistenceDecodeError,
|
||||
toPersistenceSqlError,
|
||||
} from "./Errors.ts";
|
||||
|
||||
/**
|
||||
* ProviderSessionRuntimeRepository - Repository interface for provider runtime sessions.
|
||||
*
|
||||
* Owns persistence operations for provider runtime metadata and resume cursors.
|
||||
*
|
||||
* @module ProviderSessionRuntimeRepository
|
||||
*/
|
||||
|
||||
export const ProviderSessionRuntime = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
providerName: Schema.String,
|
||||
/**
|
||||
* User-defined routing key for the configured provider instance that
|
||||
* owns this session. Nullable only at the storage/migration boundary:
|
||||
* rows persisted before the driver/instance split carry only
|
||||
* `providerName`. Repository consumers must materialize a concrete
|
||||
* instance id before routing.
|
||||
*/
|
||||
providerInstanceId: Schema.NullOr(ProviderInstanceId),
|
||||
adapterKey: Schema.String,
|
||||
runtimeMode: RuntimeMode,
|
||||
status: ProviderSessionRuntimeStatus,
|
||||
lastSeenAt: IsoDateTime,
|
||||
resumeCursor: Schema.NullOr(Schema.Unknown),
|
||||
runtimePayload: Schema.NullOr(Schema.Unknown),
|
||||
});
|
||||
export type ProviderSessionRuntime = typeof ProviderSessionRuntime.Type;
|
||||
|
||||
export const GetProviderSessionRuntimeInput = Schema.Struct({ threadId: ThreadId });
|
||||
export type GetProviderSessionRuntimeInput = typeof GetProviderSessionRuntimeInput.Type;
|
||||
|
||||
export const DeleteProviderSessionRuntimeInput = Schema.Struct({ threadId: ThreadId });
|
||||
export type DeleteProviderSessionRuntimeInput = typeof DeleteProviderSessionRuntimeInput.Type;
|
||||
|
||||
/**
|
||||
* ProviderSessionRuntimeRepository - Service tag for provider runtime persistence.
|
||||
*/
|
||||
export class ProviderSessionRuntimeRepository extends Context.Service<
|
||||
ProviderSessionRuntimeRepository,
|
||||
{
|
||||
/**
|
||||
* Insert or replace a provider runtime row.
|
||||
*
|
||||
* Upserts by canonical `threadId`, including JSON payload/cursor fields.
|
||||
*/
|
||||
readonly upsert: (
|
||||
runtime: ProviderSessionRuntime,
|
||||
) => Effect.Effect<void, ProviderSessionRuntimeRepositoryError>;
|
||||
|
||||
/**
|
||||
* Read provider runtime state by canonical thread id.
|
||||
*/
|
||||
readonly getByThreadId: (
|
||||
input: GetProviderSessionRuntimeInput,
|
||||
) => Effect.Effect<
|
||||
Option.Option<ProviderSessionRuntime>,
|
||||
ProviderSessionRuntimeRepositoryError
|
||||
>;
|
||||
|
||||
/**
|
||||
* List all provider runtime rows.
|
||||
*
|
||||
* Returned in ascending last-seen order.
|
||||
*/
|
||||
readonly list: () => Effect.Effect<
|
||||
ReadonlyArray<ProviderSessionRuntime>,
|
||||
ProviderSessionRuntimeRepositoryError
|
||||
>;
|
||||
|
||||
/**
|
||||
* Delete provider runtime state by canonical thread id.
|
||||
*/
|
||||
readonly deleteByThreadId: (
|
||||
input: DeleteProviderSessionRuntimeInput,
|
||||
) => Effect.Effect<void, ProviderSessionRuntimeRepositoryError>;
|
||||
}
|
||||
>()("t3/persistence/ProviderSessionRuntime/ProviderSessionRuntimeRepository") {}
|
||||
|
||||
const ProviderSessionRuntimeDbRowSchema = ProviderSessionRuntime.mapFields(
|
||||
Struct.assign({
|
||||
resumeCursor: Schema.NullOr(Schema.fromJsonString(Schema.Unknown)),
|
||||
runtimePayload: Schema.NullOr(Schema.fromJsonString(Schema.Unknown)),
|
||||
}),
|
||||
);
|
||||
|
||||
const decodeRuntime = Schema.decodeUnknownEffect(ProviderSessionRuntime);
|
||||
|
||||
const GetRuntimeRequestSchema = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
});
|
||||
|
||||
const DeleteRuntimeRequestSchema = GetRuntimeRequestSchema;
|
||||
|
||||
function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: string) {
|
||||
return (cause: unknown): ProviderSessionRuntimeRepositoryError =>
|
||||
Schema.isSchemaError(cause)
|
||||
? toPersistenceDecodeError(decodeOperation)(cause)
|
||||
: toPersistenceSqlError(sqlOperation)(cause);
|
||||
}
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
const upsertRuntimeRow = SqlSchema.void({
|
||||
Request: ProviderSessionRuntimeDbRowSchema,
|
||||
execute: (runtime) =>
|
||||
sql`
|
||||
INSERT INTO provider_session_runtime (
|
||||
thread_id,
|
||||
provider_name,
|
||||
provider_instance_id,
|
||||
adapter_key,
|
||||
runtime_mode,
|
||||
status,
|
||||
last_seen_at,
|
||||
resume_cursor_json,
|
||||
runtime_payload_json
|
||||
)
|
||||
VALUES (
|
||||
${runtime.threadId},
|
||||
${runtime.providerName},
|
||||
${runtime.providerInstanceId},
|
||||
${runtime.adapterKey},
|
||||
${runtime.runtimeMode},
|
||||
${runtime.status},
|
||||
${runtime.lastSeenAt},
|
||||
${runtime.resumeCursor},
|
||||
${runtime.runtimePayload}
|
||||
)
|
||||
ON CONFLICT (thread_id)
|
||||
DO UPDATE SET
|
||||
provider_name = excluded.provider_name,
|
||||
provider_instance_id = excluded.provider_instance_id,
|
||||
adapter_key = excluded.adapter_key,
|
||||
runtime_mode = excluded.runtime_mode,
|
||||
status = excluded.status,
|
||||
last_seen_at = excluded.last_seen_at,
|
||||
resume_cursor_json = excluded.resume_cursor_json,
|
||||
runtime_payload_json = excluded.runtime_payload_json
|
||||
`,
|
||||
});
|
||||
|
||||
const getRuntimeRowByThreadId = SqlSchema.findOneOption({
|
||||
Request: GetRuntimeRequestSchema,
|
||||
Result: ProviderSessionRuntimeDbRowSchema,
|
||||
execute: ({ threadId }) =>
|
||||
sql`
|
||||
SELECT
|
||||
thread_id AS "threadId",
|
||||
provider_name AS "providerName",
|
||||
provider_instance_id AS "providerInstanceId",
|
||||
adapter_key AS "adapterKey",
|
||||
runtime_mode AS "runtimeMode",
|
||||
status,
|
||||
last_seen_at AS "lastSeenAt",
|
||||
resume_cursor_json AS "resumeCursor",
|
||||
runtime_payload_json AS "runtimePayload"
|
||||
FROM provider_session_runtime
|
||||
WHERE thread_id = ${threadId}
|
||||
`,
|
||||
});
|
||||
|
||||
const listRuntimeRows = SqlSchema.findAll({
|
||||
Request: Schema.Void,
|
||||
Result: ProviderSessionRuntimeDbRowSchema,
|
||||
execute: () =>
|
||||
sql`
|
||||
SELECT
|
||||
thread_id AS "threadId",
|
||||
provider_name AS "providerName",
|
||||
provider_instance_id AS "providerInstanceId",
|
||||
adapter_key AS "adapterKey",
|
||||
runtime_mode AS "runtimeMode",
|
||||
status,
|
||||
last_seen_at AS "lastSeenAt",
|
||||
resume_cursor_json AS "resumeCursor",
|
||||
runtime_payload_json AS "runtimePayload"
|
||||
FROM provider_session_runtime
|
||||
ORDER BY last_seen_at ASC, thread_id ASC
|
||||
`,
|
||||
});
|
||||
|
||||
const deleteRuntimeByThreadId = SqlSchema.void({
|
||||
Request: DeleteRuntimeRequestSchema,
|
||||
execute: ({ threadId }) =>
|
||||
sql`
|
||||
DELETE FROM provider_session_runtime
|
||||
WHERE thread_id = ${threadId}
|
||||
`,
|
||||
});
|
||||
|
||||
const upsert: ProviderSessionRuntimeRepository["Service"]["upsert"] = (runtime) =>
|
||||
upsertRuntimeRow(runtime).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProviderSessionRuntimeRepository.upsert:query",
|
||||
"ProviderSessionRuntimeRepository.upsert:encodeRequest",
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const getByThreadId: ProviderSessionRuntimeRepository["Service"]["getByThreadId"] = (input) =>
|
||||
getRuntimeRowByThreadId(input).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProviderSessionRuntimeRepository.getByThreadId:query",
|
||||
"ProviderSessionRuntimeRepository.getByThreadId:decodeRow",
|
||||
),
|
||||
),
|
||||
Effect.flatMap((runtimeRowOption) =>
|
||||
Option.match(runtimeRowOption, {
|
||||
onNone: () => Effect.succeed(Option.none()),
|
||||
onSome: (row) =>
|
||||
decodeRuntime(row).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceDecodeError(
|
||||
"ProviderSessionRuntimeRepository.getByThreadId:rowToRuntime",
|
||||
),
|
||||
),
|
||||
Effect.map((runtime) => Option.some(runtime)),
|
||||
),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const list: ProviderSessionRuntimeRepository["Service"]["list"] = () =>
|
||||
listRuntimeRows(undefined).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProviderSessionRuntimeRepository.list:query",
|
||||
"ProviderSessionRuntimeRepository.list:decodeRows",
|
||||
),
|
||||
),
|
||||
Effect.flatMap((rows) =>
|
||||
Effect.forEach(
|
||||
rows,
|
||||
(row) =>
|
||||
decodeRuntime(row).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceDecodeError("ProviderSessionRuntimeRepository.list:rowToRuntime"),
|
||||
),
|
||||
),
|
||||
{ concurrency: "unbounded" },
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const deleteByThreadId: ProviderSessionRuntimeRepository["Service"]["deleteByThreadId"] = (
|
||||
input,
|
||||
) =>
|
||||
deleteRuntimeByThreadId(input).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlError("ProviderSessionRuntimeRepository.deleteByThreadId:query"),
|
||||
),
|
||||
);
|
||||
|
||||
return {
|
||||
upsert,
|
||||
getByThreadId,
|
||||
list,
|
||||
deleteByThreadId,
|
||||
} satisfies ProviderSessionRuntimeRepository["Service"];
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(ProviderSessionRuntimeRepository, make);
|
||||
@@ -1,82 +0,0 @@
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Context from "effect/Context";
|
||||
import type * as Effect from "effect/Effect";
|
||||
import { AuthEnvironmentScopes } from "@t3tools/contracts";
|
||||
|
||||
import type { AuthPairingLinkRepositoryError } from "../Errors.ts";
|
||||
|
||||
export const AuthPairingLinkRecord = Schema.Struct({
|
||||
id: Schema.String,
|
||||
credential: Schema.String,
|
||||
method: Schema.Literals(["desktop-bootstrap", "one-time-token"]),
|
||||
scopes: Schema.fromJsonString(AuthEnvironmentScopes),
|
||||
subject: Schema.String,
|
||||
label: Schema.NullOr(Schema.String),
|
||||
proofKeyThumbprint: Schema.NullOr(Schema.String),
|
||||
createdAt: Schema.DateTimeUtcFromString,
|
||||
expiresAt: Schema.DateTimeUtcFromString,
|
||||
consumedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
|
||||
revokedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
|
||||
});
|
||||
export type AuthPairingLinkRecord = typeof AuthPairingLinkRecord.Type;
|
||||
|
||||
export const CreateAuthPairingLinkInput = Schema.Struct({
|
||||
id: Schema.String,
|
||||
credential: Schema.String,
|
||||
method: Schema.Literals(["desktop-bootstrap", "one-time-token"]),
|
||||
scopes: AuthEnvironmentScopes,
|
||||
subject: Schema.String,
|
||||
label: Schema.NullOr(Schema.String),
|
||||
proofKeyThumbprint: Schema.NullOr(Schema.String),
|
||||
createdAt: Schema.DateTimeUtcFromString,
|
||||
expiresAt: Schema.DateTimeUtcFromString,
|
||||
});
|
||||
export type CreateAuthPairingLinkInput = typeof CreateAuthPairingLinkInput.Type;
|
||||
|
||||
export const ConsumeAuthPairingLinkInput = Schema.Struct({
|
||||
credential: Schema.String,
|
||||
proofKeyThumbprint: Schema.NullOr(Schema.String),
|
||||
consumedAt: Schema.DateTimeUtcFromString,
|
||||
now: Schema.DateTimeUtcFromString,
|
||||
});
|
||||
export type ConsumeAuthPairingLinkInput = typeof ConsumeAuthPairingLinkInput.Type;
|
||||
|
||||
export const ListActiveAuthPairingLinksInput = Schema.Struct({
|
||||
now: Schema.DateTimeUtcFromString,
|
||||
});
|
||||
export type ListActiveAuthPairingLinksInput = typeof ListActiveAuthPairingLinksInput.Type;
|
||||
|
||||
export const RevokeAuthPairingLinkInput = Schema.Struct({
|
||||
id: Schema.String,
|
||||
revokedAt: Schema.DateTimeUtcFromString,
|
||||
});
|
||||
export type RevokeAuthPairingLinkInput = typeof RevokeAuthPairingLinkInput.Type;
|
||||
|
||||
export const GetAuthPairingLinkByCredentialInput = Schema.Struct({
|
||||
credential: Schema.String,
|
||||
});
|
||||
export type GetAuthPairingLinkByCredentialInput = typeof GetAuthPairingLinkByCredentialInput.Type;
|
||||
|
||||
export interface AuthPairingLinkRepositoryShape {
|
||||
readonly create: (
|
||||
input: CreateAuthPairingLinkInput,
|
||||
) => Effect.Effect<void, AuthPairingLinkRepositoryError>;
|
||||
readonly consumeAvailable: (
|
||||
input: ConsumeAuthPairingLinkInput,
|
||||
) => Effect.Effect<Option.Option<AuthPairingLinkRecord>, AuthPairingLinkRepositoryError>;
|
||||
readonly listActive: (
|
||||
input: ListActiveAuthPairingLinksInput,
|
||||
) => Effect.Effect<ReadonlyArray<AuthPairingLinkRecord>, AuthPairingLinkRepositoryError>;
|
||||
readonly revoke: (
|
||||
input: RevokeAuthPairingLinkInput,
|
||||
) => Effect.Effect<boolean, AuthPairingLinkRepositoryError>;
|
||||
readonly getByCredential: (
|
||||
input: GetAuthPairingLinkByCredentialInput,
|
||||
) => Effect.Effect<Option.Option<AuthPairingLinkRecord>, AuthPairingLinkRepositoryError>;
|
||||
}
|
||||
|
||||
export class AuthPairingLinkRepository extends Context.Service<
|
||||
AuthPairingLinkRepository,
|
||||
AuthPairingLinkRepositoryShape
|
||||
>()("t3/persistence/Services/AuthPairingLinks/AuthPairingLinkRepository") {}
|
||||
@@ -1,100 +0,0 @@
|
||||
import {
|
||||
AuthClientMetadataDeviceType,
|
||||
AuthEnvironmentScopes,
|
||||
AuthSessionId,
|
||||
ServerAuthSessionMethod,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Context from "effect/Context";
|
||||
import type * as Effect from "effect/Effect";
|
||||
|
||||
import type { AuthSessionRepositoryError } from "../Errors.ts";
|
||||
|
||||
export const AuthSessionClientMetadataRecord = Schema.Struct({
|
||||
label: Schema.NullOr(Schema.String),
|
||||
ipAddress: Schema.NullOr(Schema.String),
|
||||
userAgent: Schema.NullOr(Schema.String),
|
||||
deviceType: AuthClientMetadataDeviceType,
|
||||
os: Schema.NullOr(Schema.String),
|
||||
browser: Schema.NullOr(Schema.String),
|
||||
});
|
||||
export type AuthSessionClientMetadataRecord = typeof AuthSessionClientMetadataRecord.Type;
|
||||
|
||||
export const AuthSessionRecord = Schema.Struct({
|
||||
sessionId: AuthSessionId,
|
||||
subject: Schema.String,
|
||||
scopes: AuthEnvironmentScopes,
|
||||
method: ServerAuthSessionMethod,
|
||||
client: AuthSessionClientMetadataRecord,
|
||||
issuedAt: Schema.DateTimeUtcFromString,
|
||||
expiresAt: Schema.DateTimeUtcFromString,
|
||||
lastConnectedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
|
||||
revokedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
|
||||
});
|
||||
export type AuthSessionRecord = typeof AuthSessionRecord.Type;
|
||||
|
||||
export const CreateAuthSessionInput = Schema.Struct({
|
||||
sessionId: AuthSessionId,
|
||||
subject: Schema.String,
|
||||
scopes: AuthEnvironmentScopes,
|
||||
method: ServerAuthSessionMethod,
|
||||
client: AuthSessionClientMetadataRecord,
|
||||
issuedAt: Schema.DateTimeUtcFromString,
|
||||
expiresAt: Schema.DateTimeUtcFromString,
|
||||
});
|
||||
export type CreateAuthSessionInput = typeof CreateAuthSessionInput.Type;
|
||||
|
||||
export const GetAuthSessionByIdInput = Schema.Struct({
|
||||
sessionId: AuthSessionId,
|
||||
});
|
||||
export type GetAuthSessionByIdInput = typeof GetAuthSessionByIdInput.Type;
|
||||
|
||||
export const ListActiveAuthSessionsInput = Schema.Struct({
|
||||
now: Schema.DateTimeUtcFromString,
|
||||
});
|
||||
export type ListActiveAuthSessionsInput = typeof ListActiveAuthSessionsInput.Type;
|
||||
|
||||
export const RevokeAuthSessionInput = Schema.Struct({
|
||||
sessionId: AuthSessionId,
|
||||
revokedAt: Schema.DateTimeUtcFromString,
|
||||
});
|
||||
export type RevokeAuthSessionInput = typeof RevokeAuthSessionInput.Type;
|
||||
|
||||
export const RevokeOtherAuthSessionsInput = Schema.Struct({
|
||||
currentSessionId: AuthSessionId,
|
||||
revokedAt: Schema.DateTimeUtcFromString,
|
||||
});
|
||||
export type RevokeOtherAuthSessionsInput = typeof RevokeOtherAuthSessionsInput.Type;
|
||||
|
||||
export const SetAuthSessionLastConnectedAtInput = Schema.Struct({
|
||||
sessionId: AuthSessionId,
|
||||
lastConnectedAt: Schema.DateTimeUtcFromString,
|
||||
});
|
||||
export type SetAuthSessionLastConnectedAtInput = typeof SetAuthSessionLastConnectedAtInput.Type;
|
||||
|
||||
export interface AuthSessionRepositoryShape {
|
||||
readonly create: (
|
||||
input: CreateAuthSessionInput,
|
||||
) => Effect.Effect<void, AuthSessionRepositoryError>;
|
||||
readonly getById: (
|
||||
input: GetAuthSessionByIdInput,
|
||||
) => Effect.Effect<Option.Option<AuthSessionRecord>, AuthSessionRepositoryError>;
|
||||
readonly listActive: (
|
||||
input: ListActiveAuthSessionsInput,
|
||||
) => Effect.Effect<ReadonlyArray<AuthSessionRecord>, AuthSessionRepositoryError>;
|
||||
readonly revoke: (
|
||||
input: RevokeAuthSessionInput,
|
||||
) => Effect.Effect<boolean, AuthSessionRepositoryError>;
|
||||
readonly revokeAllExcept: (
|
||||
input: RevokeOtherAuthSessionsInput,
|
||||
) => Effect.Effect<ReadonlyArray<AuthSessionId>, AuthSessionRepositoryError>;
|
||||
readonly setLastConnectedAt: (
|
||||
input: SetAuthSessionLastConnectedAtInput,
|
||||
) => Effect.Effect<void, AuthSessionRepositoryError>;
|
||||
}
|
||||
|
||||
export class AuthSessionRepository extends Context.Service<
|
||||
AuthSessionRepository,
|
||||
AuthSessionRepositoryShape
|
||||
>()("t3/persistence/Services/AuthSessions/AuthSessionRepository") {}
|
||||
@@ -1,92 +0,0 @@
|
||||
/**
|
||||
* ProviderSessionRuntimeRepository - Repository interface for provider runtime sessions.
|
||||
*
|
||||
* Owns persistence operations for provider runtime metadata and resume cursors.
|
||||
*
|
||||
* @module ProviderSessionRuntimeRepository
|
||||
*/
|
||||
import {
|
||||
IsoDateTime,
|
||||
ProviderInstanceId,
|
||||
ProviderSessionRuntimeStatus,
|
||||
RuntimeMode,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Context from "effect/Context";
|
||||
import type * as Effect from "effect/Effect";
|
||||
|
||||
import type { ProviderSessionRuntimeRepositoryError } from "../Errors.ts";
|
||||
|
||||
export const ProviderSessionRuntime = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
providerName: Schema.String,
|
||||
/**
|
||||
* User-defined routing key for the configured provider instance that
|
||||
* owns this session. Nullable only at the storage/migration boundary:
|
||||
* rows persisted before the driver/instance split carry only
|
||||
* `providerName`. Repository consumers must materialize a concrete
|
||||
* instance id before routing.
|
||||
*/
|
||||
providerInstanceId: Schema.NullOr(ProviderInstanceId),
|
||||
adapterKey: Schema.String,
|
||||
runtimeMode: RuntimeMode,
|
||||
status: ProviderSessionRuntimeStatus,
|
||||
lastSeenAt: IsoDateTime,
|
||||
resumeCursor: Schema.NullOr(Schema.Unknown),
|
||||
runtimePayload: Schema.NullOr(Schema.Unknown),
|
||||
});
|
||||
export type ProviderSessionRuntime = typeof ProviderSessionRuntime.Type;
|
||||
|
||||
export const GetProviderSessionRuntimeInput = Schema.Struct({ threadId: ThreadId });
|
||||
export type GetProviderSessionRuntimeInput = typeof GetProviderSessionRuntimeInput.Type;
|
||||
|
||||
export const DeleteProviderSessionRuntimeInput = Schema.Struct({ threadId: ThreadId });
|
||||
export type DeleteProviderSessionRuntimeInput = typeof DeleteProviderSessionRuntimeInput.Type;
|
||||
|
||||
/**
|
||||
* ProviderSessionRuntimeRepositoryShape - Service API for provider runtime records.
|
||||
*/
|
||||
export interface ProviderSessionRuntimeRepositoryShape {
|
||||
/**
|
||||
* Insert or replace a provider runtime row.
|
||||
*
|
||||
* Upserts by canonical `threadId`, including JSON payload/cursor fields.
|
||||
*/
|
||||
readonly upsert: (
|
||||
runtime: ProviderSessionRuntime,
|
||||
) => Effect.Effect<void, ProviderSessionRuntimeRepositoryError>;
|
||||
|
||||
/**
|
||||
* Read provider runtime state by canonical thread id.
|
||||
*/
|
||||
readonly getByThreadId: (
|
||||
input: GetProviderSessionRuntimeInput,
|
||||
) => Effect.Effect<Option.Option<ProviderSessionRuntime>, ProviderSessionRuntimeRepositoryError>;
|
||||
|
||||
/**
|
||||
* List all provider runtime rows.
|
||||
*
|
||||
* Returned in ascending last-seen order.
|
||||
*/
|
||||
readonly list: () => Effect.Effect<
|
||||
ReadonlyArray<ProviderSessionRuntime>,
|
||||
ProviderSessionRuntimeRepositoryError
|
||||
>;
|
||||
|
||||
/**
|
||||
* Delete provider runtime state by canonical thread id.
|
||||
*/
|
||||
readonly deleteByThreadId: (
|
||||
input: DeleteProviderSessionRuntimeInput,
|
||||
) => Effect.Effect<void, ProviderSessionRuntimeRepositoryError>;
|
||||
}
|
||||
|
||||
/**
|
||||
* ProviderSessionRuntimeRepository - Service tag for provider runtime persistence.
|
||||
*/
|
||||
export class ProviderSessionRuntimeRepository extends Context.Service<
|
||||
ProviderSessionRuntimeRepository,
|
||||
ProviderSessionRuntimeRepositoryShape
|
||||
>()("t3/persistence/Services/ProviderSessionRuntime/ProviderSessionRuntimeRepository") {}
|
||||
@@ -28,33 +28,30 @@ import {
|
||||
normalizePreviewUrl,
|
||||
PreviewUrlNormalizationError,
|
||||
} from "@t3tools/shared/preview";
|
||||
import {
|
||||
Context,
|
||||
DateTime,
|
||||
Effect,
|
||||
Layer,
|
||||
PubSub,
|
||||
type Scope,
|
||||
Stream,
|
||||
SynchronizedRef,
|
||||
} from "effect";
|
||||
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 PubSub from "effect/PubSub";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as SynchronizedRef from "effect/SynchronizedRef";
|
||||
|
||||
export interface PreviewManagerShape {
|
||||
readonly open: (input: PreviewOpenInput) => Effect.Effect<PreviewSessionSnapshot, PreviewError>;
|
||||
readonly navigate: (
|
||||
input: PreviewNavigateInput,
|
||||
) => Effect.Effect<PreviewSessionSnapshot, PreviewError>;
|
||||
readonly reportStatus: (input: PreviewReportStatusInput) => Effect.Effect<void, PreviewError>;
|
||||
readonly refresh: (input: PreviewRefreshInput) => Effect.Effect<void, PreviewError>;
|
||||
readonly close: (input: PreviewCloseInput) => Effect.Effect<void, PreviewError>;
|
||||
readonly list: (input: PreviewListInput) => Effect.Effect<PreviewListResult>;
|
||||
readonly events: Stream.Stream<PreviewEvent>;
|
||||
readonly subscribeEvents: Effect.Effect<PubSub.Subscription<PreviewEvent>, never, Scope.Scope>;
|
||||
}
|
||||
|
||||
export class PreviewManager extends Context.Service<PreviewManager, PreviewManagerShape>()(
|
||||
"t3/preview/Manager/PreviewManager",
|
||||
) {}
|
||||
export class PreviewManager extends Context.Service<
|
||||
PreviewManager,
|
||||
{
|
||||
readonly open: (input: PreviewOpenInput) => Effect.Effect<PreviewSessionSnapshot, PreviewError>;
|
||||
readonly navigate: (
|
||||
input: PreviewNavigateInput,
|
||||
) => Effect.Effect<PreviewSessionSnapshot, PreviewError>;
|
||||
readonly reportStatus: (input: PreviewReportStatusInput) => Effect.Effect<void, PreviewError>;
|
||||
readonly refresh: (input: PreviewRefreshInput) => Effect.Effect<void, PreviewError>;
|
||||
readonly close: (input: PreviewCloseInput) => Effect.Effect<void, PreviewError>;
|
||||
readonly list: (input: PreviewListInput) => Effect.Effect<PreviewListResult>;
|
||||
readonly events: Stream.Stream<PreviewEvent>;
|
||||
readonly subscribeEvents: Effect.Effect<PubSub.Subscription<PreviewEvent>, never, Scope.Scope>;
|
||||
}
|
||||
>()("t3/preview/Manager/PreviewManager") {}
|
||||
|
||||
interface PreviewSessionState {
|
||||
readonly threadId: string;
|
||||
@@ -127,7 +124,7 @@ const buildIdleSnapshot = (input: {
|
||||
updatedAt: input.updatedAt,
|
||||
});
|
||||
|
||||
const make = Effect.gen(function* PreviewManagerMake() {
|
||||
export const make = Effect.gen(function* PreviewManagerMake() {
|
||||
const stateRef = yield* SynchronizedRef.make<ManagerState>(initialState);
|
||||
// Unbounded PubSub is fine here — events are tiny and we don't want to
|
||||
// block publishers if a subscriber is slow. WS clients backpressure on
|
||||
@@ -184,38 +181,40 @@ const make = Effect.gen(function* PreviewManagerMake() {
|
||||
);
|
||||
};
|
||||
|
||||
const open: PreviewManagerShape["open"] = Effect.fn("PreviewManager.open")(function* (input) {
|
||||
const tabId = newPreviewTabId();
|
||||
const updatedAt = yield* currentIsoTimestamp;
|
||||
const snapshot = input.url
|
||||
? buildLoadingSnapshot({
|
||||
const open: PreviewManager["Service"]["open"] = Effect.fn("PreviewManager.open")(
|
||||
function* (input) {
|
||||
const tabId = newPreviewTabId();
|
||||
const updatedAt = yield* currentIsoTimestamp;
|
||||
const snapshot = input.url
|
||||
? buildLoadingSnapshot({
|
||||
threadId: input.threadId,
|
||||
tabId,
|
||||
url: yield* normalizeUrl(input.url),
|
||||
title: "",
|
||||
updatedAt,
|
||||
})
|
||||
: buildIdleSnapshot({ threadId: input.threadId, tabId, updatedAt });
|
||||
yield* SynchronizedRef.update(stateRef, (state) => {
|
||||
const sessions = new Map(state.sessions);
|
||||
sessions.set(compositeKey(input.threadId, tabId), {
|
||||
threadId: input.threadId,
|
||||
tabId,
|
||||
url: yield* normalizeUrl(input.url),
|
||||
title: "",
|
||||
updatedAt,
|
||||
})
|
||||
: buildIdleSnapshot({ threadId: input.threadId, tabId, updatedAt });
|
||||
yield* SynchronizedRef.update(stateRef, (state) => {
|
||||
const sessions = new Map(state.sessions);
|
||||
sessions.set(compositeKey(input.threadId, tabId), {
|
||||
snapshot,
|
||||
});
|
||||
return { sessions };
|
||||
});
|
||||
yield* PubSub.publish(eventsPubSub, {
|
||||
type: "opened",
|
||||
threadId: input.threadId,
|
||||
tabId,
|
||||
createdAt: snapshot.updatedAt,
|
||||
snapshot,
|
||||
});
|
||||
return { sessions };
|
||||
});
|
||||
yield* PubSub.publish(eventsPubSub, {
|
||||
type: "opened",
|
||||
threadId: input.threadId,
|
||||
tabId,
|
||||
createdAt: snapshot.updatedAt,
|
||||
snapshot,
|
||||
});
|
||||
return snapshot;
|
||||
});
|
||||
return snapshot;
|
||||
},
|
||||
);
|
||||
|
||||
const navigate: PreviewManagerShape["navigate"] = Effect.fn("PreviewManager.navigate")(
|
||||
const navigate: PreviewManager["Service"]["navigate"] = Effect.fn("PreviewManager.navigate")(
|
||||
function* (input) {
|
||||
const url = yield* normalizeUrl(input.url);
|
||||
return yield* mutateExistingSession(
|
||||
@@ -250,7 +249,7 @@ const make = Effect.gen(function* PreviewManagerMake() {
|
||||
},
|
||||
);
|
||||
|
||||
const reportStatus: PreviewManagerShape["reportStatus"] = Effect.fn(
|
||||
const reportStatus: PreviewManager["Service"]["reportStatus"] = Effect.fn(
|
||||
"PreviewManager.reportStatus",
|
||||
)(function* (input) {
|
||||
yield* mutateExistingSession(
|
||||
@@ -294,7 +293,7 @@ const make = Effect.gen(function* PreviewManagerMake() {
|
||||
);
|
||||
});
|
||||
|
||||
const refresh: PreviewManagerShape["refresh"] = Effect.fn("PreviewManager.refresh")(
|
||||
const refresh: PreviewManager["Service"]["refresh"] = Effect.fn("PreviewManager.refresh")(
|
||||
function* (input) {
|
||||
// Verify the session exists; the desktop bridge handles the actual reload
|
||||
// and will report progress back via `reportStatus`. No event emitted.
|
||||
@@ -304,50 +303,54 @@ const make = Effect.gen(function* PreviewManagerMake() {
|
||||
},
|
||||
);
|
||||
|
||||
const close: PreviewManagerShape["close"] = Effect.fn("PreviewManager.close")(function* (input) {
|
||||
const createdAt = yield* currentIsoTimestamp;
|
||||
const events = yield* SynchronizedRef.modify(stateRef, (state) => {
|
||||
const eventsToEmit: PreviewEvent[] = [];
|
||||
const sessions = new Map(state.sessions);
|
||||
const targets = input.tabId
|
||||
? [state.sessions.get(compositeKey(input.threadId, input.tabId))].filter(
|
||||
(entry): entry is PreviewSessionState => entry !== undefined,
|
||||
)
|
||||
: sessionsForThread(state, input.threadId);
|
||||
for (const target of targets) {
|
||||
sessions.delete(compositeKey(target.threadId, target.tabId));
|
||||
eventsToEmit.push({
|
||||
type: "closed",
|
||||
threadId: target.threadId,
|
||||
tabId: target.tabId,
|
||||
createdAt,
|
||||
const close: PreviewManager["Service"]["close"] = Effect.fn("PreviewManager.close")(
|
||||
function* (input) {
|
||||
const createdAt = yield* currentIsoTimestamp;
|
||||
const events = yield* SynchronizedRef.modify(stateRef, (state) => {
|
||||
const eventsToEmit: PreviewEvent[] = [];
|
||||
const sessions = new Map(state.sessions);
|
||||
const targets = input.tabId
|
||||
? [state.sessions.get(compositeKey(input.threadId, input.tabId))].filter(
|
||||
(entry): entry is PreviewSessionState => entry !== undefined,
|
||||
)
|
||||
: sessionsForThread(state, input.threadId);
|
||||
for (const target of targets) {
|
||||
sessions.delete(compositeKey(target.threadId, target.tabId));
|
||||
eventsToEmit.push({
|
||||
type: "closed",
|
||||
threadId: target.threadId,
|
||||
tabId: target.tabId,
|
||||
createdAt,
|
||||
});
|
||||
}
|
||||
if (eventsToEmit.length === 0) {
|
||||
return [eventsToEmit, state] as const;
|
||||
}
|
||||
return [eventsToEmit, { sessions }] as const;
|
||||
});
|
||||
if (events.length > 0) {
|
||||
yield* Effect.forEach(events, (event) => PubSub.publish(eventsPubSub, event), {
|
||||
discard: true,
|
||||
});
|
||||
}
|
||||
if (eventsToEmit.length === 0) {
|
||||
return [eventsToEmit, state] as const;
|
||||
}
|
||||
return [eventsToEmit, { sessions }] as const;
|
||||
});
|
||||
if (events.length > 0) {
|
||||
yield* Effect.forEach(events, (event) => PubSub.publish(eventsPubSub, event), {
|
||||
discard: true,
|
||||
});
|
||||
}
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
const list: PreviewManagerShape["list"] = Effect.fn("PreviewManager.list")(function* (input) {
|
||||
return yield* SynchronizedRef.get(stateRef).pipe(
|
||||
Effect.map(
|
||||
(state): PreviewListResult => ({
|
||||
sessions: sessionsForThread(state, input.threadId)
|
||||
.map((s) => s.snapshot)
|
||||
.toSorted((a, b) => a.updatedAt.localeCompare(b.updatedAt)),
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
const list: PreviewManager["Service"]["list"] = Effect.fn("PreviewManager.list")(
|
||||
function* (input) {
|
||||
return yield* SynchronizedRef.get(stateRef).pipe(
|
||||
Effect.map(
|
||||
(state): PreviewListResult => ({
|
||||
sessions: sessionsForThread(state, input.threadId)
|
||||
.map((s) => s.snapshot)
|
||||
.toSorted((a, b) => a.updatedAt.localeCompare(b.updatedAt)),
|
||||
}),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
return {
|
||||
return PreviewManager.of({
|
||||
open,
|
||||
navigate,
|
||||
reportStatus,
|
||||
@@ -356,7 +359,7 @@ const make = Effect.gen(function* PreviewManagerMake() {
|
||||
list,
|
||||
events,
|
||||
subscribeEvents: PubSub.subscribe(eventsPubSub),
|
||||
} satisfies PreviewManagerShape;
|
||||
});
|
||||
}).pipe(Effect.withSpan("PreviewManager.make"));
|
||||
|
||||
export const layer = Layer.effect(PreviewManager, make);
|
||||
@@ -6,9 +6,9 @@ import * as Net from "@t3tools/shared/Net";
|
||||
import { Effect, Layer } from "effect";
|
||||
import { expect } from "vite-plus/test";
|
||||
|
||||
import { ProcessRunner } from "../processRunner.ts";
|
||||
import * as ProcessRunner from "../processRunner.ts";
|
||||
import * as PortScanner from "./PortScanner.ts";
|
||||
const TestProcessRunner = Layer.succeed(ProcessRunner, {
|
||||
const TestProcessRunner = Layer.succeed(ProcessRunner.ProcessRunner, {
|
||||
run: () => Effect.die("ProcessRunner should not be used by Windows TCP probe tests"),
|
||||
});
|
||||
const TestPortDiscoveryLive = PortScanner.layer.pipe(
|
||||
|
||||
@@ -15,30 +15,36 @@ import { ThreadId, type DiscoveredLocalServer } from "@t3tools/contracts";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import * as Net from "@t3tools/shared/Net";
|
||||
import { LSOF_LOCAL_HOST_TOKENS } from "@t3tools/shared/preview";
|
||||
import { Cause, Context, Duration, Effect, Layer, Ref, Schedule, Scope } from "effect";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schedule from "effect/Schedule";
|
||||
import * as Scope from "effect/Scope";
|
||||
|
||||
import { ProcessRunner } from "../processRunner.ts";
|
||||
import * as ProcessRunner from "../processRunner.ts";
|
||||
|
||||
export interface PortDiscoveryShape {
|
||||
readonly scan: () => Effect.Effect<ReadonlyArray<DiscoveredLocalServer>>;
|
||||
readonly subscribe: (
|
||||
listener: (servers: ReadonlyArray<DiscoveredLocalServer>) => Effect.Effect<void>,
|
||||
) => Effect.Effect<void, never, Scope.Scope>;
|
||||
readonly retain: Effect.Effect<void, never, Scope.Scope>;
|
||||
readonly registerTerminalProcesses: (input: {
|
||||
readonly threadId: string;
|
||||
readonly terminalId: string;
|
||||
readonly processIds: ReadonlyArray<number>;
|
||||
}) => Effect.Effect<void>;
|
||||
readonly unregisterTerminal: (input: {
|
||||
readonly threadId: string;
|
||||
readonly terminalId: string;
|
||||
}) => Effect.Effect<void>;
|
||||
}
|
||||
|
||||
export class PortDiscovery extends Context.Service<PortDiscovery, PortDiscoveryShape>()(
|
||||
"t3/preview/PortScanner/PortDiscovery",
|
||||
) {}
|
||||
export class PortDiscovery extends Context.Service<
|
||||
PortDiscovery,
|
||||
{
|
||||
readonly scan: () => Effect.Effect<ReadonlyArray<DiscoveredLocalServer>>;
|
||||
readonly subscribe: (
|
||||
listener: (servers: ReadonlyArray<DiscoveredLocalServer>) => Effect.Effect<void>,
|
||||
) => Effect.Effect<void, never, Scope.Scope>;
|
||||
readonly retain: Effect.Effect<void, never, Scope.Scope>;
|
||||
readonly registerTerminalProcesses: (input: {
|
||||
readonly threadId: string;
|
||||
readonly terminalId: string;
|
||||
readonly processIds: ReadonlyArray<number>;
|
||||
}) => Effect.Effect<void>;
|
||||
readonly unregisterTerminal: (input: {
|
||||
readonly threadId: string;
|
||||
readonly terminalId: string;
|
||||
}) => Effect.Effect<void>;
|
||||
}
|
||||
>()("t3/preview/PortScanner/PortDiscovery") {}
|
||||
|
||||
export const COMMON_DEV_PORTS: ReadonlyArray<number> = Object.freeze([
|
||||
3000, 3001, 3333, 4173, 4200, 4321, 5000, 5173, 5174, 5175, 5500, 8000, 8080, 8081, 8888, 9000,
|
||||
@@ -180,9 +186,9 @@ const serversEqual = (
|
||||
return true;
|
||||
};
|
||||
|
||||
const make = Effect.gen(function* PortDiscoveryMake() {
|
||||
export const make = Effect.gen(function* PortDiscoveryMake() {
|
||||
const net = yield* Net.NetService;
|
||||
const processRunner = yield* ProcessRunner;
|
||||
const processRunner = yield* ProcessRunner.ProcessRunner;
|
||||
const hostPlatform = yield* HostProcessPlatform;
|
||||
const stateRef = yield* Ref.make<ScannerState>({
|
||||
lastSnapshot: [],
|
||||
@@ -296,14 +302,14 @@ const make = Effect.gen(function* PortDiscoveryMake() {
|
||||
}
|
||||
});
|
||||
|
||||
const retain: PortDiscoveryShape["retain"] = Effect.acquireRelease(acquireRetention(), () =>
|
||||
const retain: PortDiscovery["Service"]["retain"] = Effect.acquireRelease(acquireRetention(), () =>
|
||||
Ref.update(stateRef, (state) => ({
|
||||
...state,
|
||||
retainCount: Math.max(0, state.retainCount - 1),
|
||||
})),
|
||||
);
|
||||
|
||||
const subscribe: PortDiscoveryShape["subscribe"] = Effect.fn("PortDiscovery.subscribe")(
|
||||
const subscribe: PortDiscovery["Service"]["subscribe"] = Effect.fn("PortDiscovery.subscribe")(
|
||||
(listener) =>
|
||||
Effect.acquireRelease(
|
||||
Ref.update(stateRef, (state) => ({
|
||||
@@ -319,29 +325,28 @@ const make = Effect.gen(function* PortDiscoveryMake() {
|
||||
),
|
||||
);
|
||||
|
||||
const registerTerminalProcesses: PortDiscoveryShape["registerTerminalProcesses"] = Effect.fn(
|
||||
"PortDiscovery.registerTerminalProcesses",
|
||||
)(function* (input) {
|
||||
const owner = {
|
||||
threadId: ThreadId.make(input.threadId),
|
||||
terminalId: input.terminalId,
|
||||
};
|
||||
const processIds = new Set(
|
||||
input.processIds.filter((processId) => Number.isInteger(processId) && processId > 0),
|
||||
);
|
||||
yield* Ref.update(stateRef, (state) => {
|
||||
const terminalProcesses = new Map(state.terminalProcesses);
|
||||
const key = terminalOwnerKey(owner);
|
||||
if (processIds.size === 0) {
|
||||
terminalProcesses.delete(key);
|
||||
} else {
|
||||
terminalProcesses.set(key, { owner, processIds });
|
||||
}
|
||||
return { ...state, terminalProcesses };
|
||||
const registerTerminalProcesses: PortDiscovery["Service"]["registerTerminalProcesses"] =
|
||||
Effect.fn("PortDiscovery.registerTerminalProcesses")(function* (input) {
|
||||
const owner = {
|
||||
threadId: ThreadId.make(input.threadId),
|
||||
terminalId: input.terminalId,
|
||||
};
|
||||
const processIds = new Set(
|
||||
input.processIds.filter((processId) => Number.isInteger(processId) && processId > 0),
|
||||
);
|
||||
yield* Ref.update(stateRef, (state) => {
|
||||
const terminalProcesses = new Map(state.terminalProcesses);
|
||||
const key = terminalOwnerKey(owner);
|
||||
if (processIds.size === 0) {
|
||||
terminalProcesses.delete(key);
|
||||
} else {
|
||||
terminalProcesses.set(key, { owner, processIds });
|
||||
}
|
||||
return { ...state, terminalProcesses };
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
const unregisterTerminal: PortDiscoveryShape["unregisterTerminal"] = Effect.fn(
|
||||
const unregisterTerminal: PortDiscovery["Service"]["unregisterTerminal"] = Effect.fn(
|
||||
"PortDiscovery.unregisterTerminal",
|
||||
)(function* (input) {
|
||||
yield* Ref.update(stateRef, (state) => {
|
||||
@@ -351,13 +356,13 @@ const make = Effect.gen(function* PortDiscoveryMake() {
|
||||
});
|
||||
});
|
||||
|
||||
return {
|
||||
return PortDiscovery.of({
|
||||
scan: scanOnce,
|
||||
subscribe,
|
||||
retain,
|
||||
registerTerminalProcesses,
|
||||
unregisterTerminal,
|
||||
} satisfies PortDiscoveryShape;
|
||||
});
|
||||
}).pipe(Effect.withSpan("PortDiscovery.make"));
|
||||
|
||||
export const layer = Layer.effect(PortDiscovery, make);
|
||||
@@ -11,7 +11,7 @@ import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import { SpawnExecutableResolution } from "@t3tools/shared/shell";
|
||||
import { ExternalLauncher, layer as ExternalLauncherLive } from "./externalLauncher.ts";
|
||||
import * as ExternalLauncher from "./externalLauncher.ts";
|
||||
|
||||
function makeMockDetachedHandle(onUnref: () => void = () => undefined) {
|
||||
return ChildProcessSpawner.makeHandle({
|
||||
@@ -54,7 +54,7 @@ const testLayer = (input: {
|
||||
);
|
||||
|
||||
return Layer.mergeAll(
|
||||
ExternalLauncherLive.pipe(Layer.provide(Layer.merge(NodeServices.layer, spawnerLayer))),
|
||||
ExternalLauncher.layer.pipe(Layer.provide(Layer.merge(NodeServices.layer, spawnerLayer))),
|
||||
Layer.succeed(HostProcessPlatform, input.platform),
|
||||
Layer.succeed(
|
||||
SpawnExecutableResolution,
|
||||
@@ -68,7 +68,7 @@ it.effect("launches the default browser through the platform command", () => {
|
||||
let spawned: ChildProcess.StandardCommand | undefined;
|
||||
let didUnref = false;
|
||||
return Effect.gen(function* () {
|
||||
const launcher = yield* ExternalLauncher;
|
||||
const launcher = yield* ExternalLauncher.ExternalLauncher;
|
||||
|
||||
yield* launcher.launchBrowser("https://example.com/some path");
|
||||
|
||||
@@ -101,7 +101,7 @@ it.effect("launches an installed editor with platform-safe arguments", () =>
|
||||
|
||||
let spawned: ChildProcess.StandardCommand | undefined;
|
||||
yield* Effect.gen(function* () {
|
||||
const launcher = yield* ExternalLauncher;
|
||||
const launcher = yield* ExternalLauncher.ExternalLauncher;
|
||||
yield* launcher.launchEditor({
|
||||
editor: "vscode",
|
||||
cwd: "C:\\workspace with spaces\\src\\index.ts:12:4",
|
||||
@@ -139,7 +139,7 @@ it.effect("discovers editors through the service API", () =>
|
||||
yield* fileSystem.writeFileString(path.join(binDir, "explorer.CMD"), "@echo off\r\n");
|
||||
|
||||
const editors = yield* Effect.gen(function* () {
|
||||
const launcher = yield* ExternalLauncher;
|
||||
const launcher = yield* ExternalLauncher.ExternalLauncher;
|
||||
return yield* launcher.resolveAvailableEditors();
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
@@ -157,10 +157,12 @@ it.effect("discovers editors through the service API", () =>
|
||||
|
||||
it.effect("rejects unknown editors through the service API", () =>
|
||||
Effect.gen(function* () {
|
||||
const launcher = yield* ExternalLauncher;
|
||||
const result = yield* launcher
|
||||
const launcher = yield* ExternalLauncher.ExternalLauncher;
|
||||
const error = yield* launcher
|
||||
.launchEditor({ editor: "missing-editor" as never, cwd: "/tmp/workspace" })
|
||||
.pipe(Effect.result);
|
||||
assert.equal(result._tag, "Failure");
|
||||
.pipe(Effect.flip);
|
||||
assert.instanceOf(error, ExternalLauncher.ExternalLauncherUnknownEditorError);
|
||||
assert.equal(error.editor, "missing-editor");
|
||||
assert.equal(error.message, "Unknown editor: missing-editor");
|
||||
}).pipe(Effect.provide(testLayer({ platform: "linux", env: { PATH: "" } }))),
|
||||
);
|
||||
@@ -9,6 +9,11 @@
|
||||
import {
|
||||
EDITORS,
|
||||
ExternalLauncherError,
|
||||
ExternalLauncherBrowserSpawnError,
|
||||
ExternalLauncherCommandNotFoundError,
|
||||
ExternalLauncherEditorSpawnError,
|
||||
ExternalLauncherUnknownEditorError,
|
||||
ExternalLauncherUnsupportedEditorError,
|
||||
type EditorId,
|
||||
type LaunchEditorInput,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -22,15 +27,26 @@ import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
import * as ChildProcess from "effect/unstable/process/ChildProcess";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
|
||||
// ==============================
|
||||
// Definitions
|
||||
// ==============================
|
||||
|
||||
export { ExternalLauncherError };
|
||||
export {
|
||||
ExternalLauncherError,
|
||||
ExternalLauncherBrowserSpawnError,
|
||||
ExternalLauncherCommandNotFoundError,
|
||||
ExternalLauncherEditorSpawnError,
|
||||
ExternalLauncherUnknownEditorError,
|
||||
ExternalLauncherUnsupportedEditorError,
|
||||
isExternalLauncherError,
|
||||
} from "@t3tools/contracts";
|
||||
export type { LaunchEditorInput };
|
||||
interface EditorLaunch {
|
||||
readonly editor: EditorId;
|
||||
readonly target: string;
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
}
|
||||
@@ -282,30 +298,23 @@ const resolveAvailableEditors = Effect.fn("externalLauncher.resolveAvailableEdit
|
||||
return yield* buildAvailableEditors(platform, env);
|
||||
});
|
||||
|
||||
/**
|
||||
* ExternalLauncherShape - Service API for browser and editor launch actions.
|
||||
*/
|
||||
export interface ExternalLauncherShape {
|
||||
readonly resolveAvailableEditors: () => Effect.Effect<ReadonlyArray<EditorId>>;
|
||||
/**
|
||||
* Launch a URL target in the default browser.
|
||||
*/
|
||||
readonly launchBrowser: (target: string) => Effect.Effect<void, ExternalLauncherError>;
|
||||
|
||||
/**
|
||||
* Launch a workspace path in a selected editor integration.
|
||||
*
|
||||
* Launches the editor as a detached process so server startup is not blocked.
|
||||
*/
|
||||
readonly launchEditor: (input: LaunchEditorInput) => Effect.Effect<void, ExternalLauncherError>;
|
||||
}
|
||||
|
||||
/**
|
||||
* ExternalLauncher - Service tag for browser/editor launch operations.
|
||||
*/
|
||||
export class ExternalLauncher extends Context.Service<ExternalLauncher, ExternalLauncherShape>()(
|
||||
"t3/process/externalLauncher",
|
||||
) {}
|
||||
export class ExternalLauncher extends Context.Service<
|
||||
ExternalLauncher,
|
||||
{
|
||||
readonly resolveAvailableEditors: () => Effect.Effect<ReadonlyArray<EditorId>>;
|
||||
/** Launch a URL target in the default browser. */
|
||||
readonly launchBrowser: (target: string) => Effect.Effect<void, ExternalLauncherError>;
|
||||
/**
|
||||
* Launch a workspace path in a selected editor integration.
|
||||
*
|
||||
* Launches the editor as a detached process so server startup is not blocked.
|
||||
*/
|
||||
readonly launchEditor: (input: LaunchEditorInput) => Effect.Effect<void, ExternalLauncherError>;
|
||||
}
|
||||
>()("t3/process/externalLauncher") {}
|
||||
|
||||
// ==============================
|
||||
// Implementations
|
||||
@@ -323,7 +332,7 @@ const resolveEditorLaunch = Effect.fn("resolveEditorLaunch")(function* (
|
||||
});
|
||||
const editorDef = EDITORS.find((editor) => editor.id === input.editor);
|
||||
if (!editorDef) {
|
||||
return yield* new ExternalLauncherError({ message: `Unknown editor: ${input.editor}` });
|
||||
return yield* new ExternalLauncherUnknownEditorError({ editor: input.editor });
|
||||
}
|
||||
|
||||
if (editorDef.commands) {
|
||||
@@ -332,21 +341,28 @@ const resolveEditorLaunch = Effect.fn("resolveEditorLaunch")(function* (
|
||||
() => editorDef.commands[0],
|
||||
);
|
||||
return {
|
||||
editor: editorDef.id,
|
||||
target: input.cwd,
|
||||
command,
|
||||
args: resolveEditorArgs(editorDef, input.cwd),
|
||||
};
|
||||
}
|
||||
|
||||
if (editorDef.id !== "file-manager") {
|
||||
return yield* new ExternalLauncherError({ message: `Unsupported editor: ${input.editor}` });
|
||||
return yield* new ExternalLauncherUnsupportedEditorError({ editor: input.editor });
|
||||
}
|
||||
|
||||
return { command: fileManagerCommandForPlatform(platform), args: [input.cwd] };
|
||||
return {
|
||||
editor: editorDef.id,
|
||||
target: input.cwd,
|
||||
command: fileManagerCommandForPlatform(platform),
|
||||
args: [input.cwd],
|
||||
};
|
||||
});
|
||||
|
||||
const launchAndUnref = Effect.fn("externalLauncher.launchAndUnref")(function* (
|
||||
launch: ProcessLaunch,
|
||||
errorMessage: string,
|
||||
onError: (cause: unknown) => ExternalLauncherError,
|
||||
): Effect.fn.Return<void, ExternalLauncherError, ChildProcessSpawner.ChildProcessSpawner> {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const command = ChildProcess.make(launch.command, launch.args, launch.options);
|
||||
@@ -355,7 +371,7 @@ const launchAndUnref = Effect.fn("externalLauncher.launchAndUnref")(function* (
|
||||
Effect.flatMap((handle) => handle.unref),
|
||||
Effect.asVoid,
|
||||
Effect.scoped,
|
||||
Effect.mapError((cause) => new ExternalLauncherError({ message: errorMessage, cause })),
|
||||
Effect.mapError(onError),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -363,7 +379,16 @@ const launchBrowser = Effect.fn("externalLauncher.launchBrowser")(function* (
|
||||
target: string,
|
||||
): Effect.fn.Return<void, ExternalLauncherError, ChildProcessSpawner.ChildProcessSpawner> {
|
||||
const launch = yield* resolveBrowserLaunch(target);
|
||||
return yield* launchAndUnref(launch, "Browser auto-open failed");
|
||||
return yield* launchAndUnref(
|
||||
launch,
|
||||
(cause) =>
|
||||
new ExternalLauncherBrowserSpawnError({
|
||||
target,
|
||||
command: launch.command,
|
||||
args: launch.args,
|
||||
cause,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
const launchEditorProcess = Effect.fn("externalLauncher.launchEditorProcess")(function* (
|
||||
@@ -375,8 +400,9 @@ const launchEditorProcess = Effect.fn("externalLauncher.launchEditorProcess")(fu
|
||||
> {
|
||||
const env = yield* readCommandLookupEnv;
|
||||
if (!(yield* isCommandAvailable(launch.command, { env }))) {
|
||||
return yield* new ExternalLauncherError({
|
||||
message: `Editor command not found: ${launch.command}`,
|
||||
return yield* new ExternalLauncherCommandNotFoundError({
|
||||
editor: launch.editor,
|
||||
command: launch.command,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -393,11 +419,18 @@ const launchEditorProcess = Effect.fn("externalLauncher.launchEditorProcess")(fu
|
||||
stderr: "ignore",
|
||||
},
|
||||
},
|
||||
"failed to spawn detached process",
|
||||
(cause) =>
|
||||
new ExternalLauncherEditorSpawnError({
|
||||
editor: launch.editor,
|
||||
target: launch.target,
|
||||
command: spawnCommand.command,
|
||||
args: spawnCommand.args,
|
||||
cause,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
export const make = Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
@@ -410,7 +443,7 @@ const make = Effect.gen(function* () {
|
||||
Effect.provideService(Path.Path, path),
|
||||
);
|
||||
|
||||
return {
|
||||
return ExternalLauncher.of({
|
||||
resolveAvailableEditors: () => provideCommandResolutionServices(resolveAvailableEditors()),
|
||||
launchBrowser: (target) =>
|
||||
launchBrowser(target).pipe(
|
||||
@@ -424,7 +457,7 @@ const make = Effect.gen(function* () {
|
||||
),
|
||||
),
|
||||
),
|
||||
} satisfies ExternalLauncherShape;
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(ExternalLauncher, make);
|
||||
@@ -11,14 +11,7 @@ import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { HostProcessEnvironment, HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import { SpawnExecutableResolution } from "@t3tools/shared/shell";
|
||||
|
||||
import {
|
||||
isWindowsCommandNotFound,
|
||||
ProcessOutputLimitError,
|
||||
ProcessRunner,
|
||||
ProcessTimeoutError,
|
||||
layer as ProcessRunnerLive,
|
||||
type ProcessRunInput,
|
||||
} from "./processRunner.ts";
|
||||
import * as ProcessRunner from "./processRunner.ts";
|
||||
|
||||
type ChildProcessCommand = {
|
||||
readonly command: string;
|
||||
@@ -68,15 +61,16 @@ function makeSpawner(
|
||||
}
|
||||
|
||||
const runWith =
|
||||
(spawner: ChildProcessSpawner.ChildProcessSpawner["Service"]) => (input: ProcessRunInput) =>
|
||||
Effect.service(ProcessRunner).pipe(
|
||||
(spawner: ChildProcessSpawner.ChildProcessSpawner["Service"]) =>
|
||||
(input: ProcessRunner.ProcessRunInput) =>
|
||||
Effect.service(ProcessRunner.ProcessRunner).pipe(
|
||||
Effect.flatMap((runner) =>
|
||||
runner.run({
|
||||
...input,
|
||||
}),
|
||||
),
|
||||
Effect.provide(
|
||||
ProcessRunnerLive.pipe(
|
||||
ProcessRunner.layer.pipe(
|
||||
Layer.provide(Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner)),
|
||||
),
|
||||
),
|
||||
@@ -112,12 +106,12 @@ describe("runProcess", () => {
|
||||
return makeHandle({ stdout: "service ok" });
|
||||
}),
|
||||
);
|
||||
const layer = ProcessRunnerLive.pipe(
|
||||
const layer = ProcessRunner.layer.pipe(
|
||||
Layer.provide(Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner)),
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const runner = yield* ProcessRunner;
|
||||
const runner = yield* ProcessRunner.ProcessRunner;
|
||||
const result = yield* runner.run({
|
||||
command: "fake",
|
||||
args: ["--service"],
|
||||
@@ -175,7 +169,7 @@ describe("runProcess", () => {
|
||||
maxOutputBytes: 128,
|
||||
}).pipe(Effect.flip);
|
||||
|
||||
expect(error).toBeInstanceOf(ProcessOutputLimitError);
|
||||
expect(error).toBeInstanceOf(ProcessRunner.ProcessOutputLimitError);
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -200,7 +194,7 @@ describe("runProcess", () => {
|
||||
timeout: "2 seconds",
|
||||
}).pipe(Effect.flip);
|
||||
|
||||
expect(error).toBeInstanceOf(ProcessOutputLimitError);
|
||||
expect(error).toBeInstanceOf(ProcessRunner.ProcessOutputLimitError);
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -285,7 +279,7 @@ describe("runProcess", () => {
|
||||
yield* TestClock.adjust(Duration.millis(50));
|
||||
const error = yield* Fiber.join(errorFiber);
|
||||
|
||||
expect(error).toBeInstanceOf(ProcessTimeoutError);
|
||||
expect(error).toBeInstanceOf(ProcessRunner.ProcessTimeoutError);
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -324,7 +318,7 @@ describe("runProcess", () => {
|
||||
describe("isWindowsCommandNotFound", () => {
|
||||
it.effect("matches the localized German cmd.exe error text", () =>
|
||||
Effect.gen(function* () {
|
||||
const isCommandNotFound = yield* isWindowsCommandNotFound(
|
||||
const isCommandNotFound = yield* ProcessRunner.isWindowsCommandNotFound(
|
||||
1,
|
||||
"wird nicht als interner oder externer Befehl, betriebsfahiges Programm oder Batch-Datei erkannt",
|
||||
).pipe(Effect.provideService(HostProcessPlatform, "win32"));
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
import * as Data from "effect/Data";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
import * as ChildProcess from "effect/unstable/process/ChildProcess";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import { resolveSpawnCommand } from "@t3tools/shared/shell";
|
||||
import {
|
||||
@@ -42,42 +43,82 @@ export interface ProcessRunOutput {
|
||||
readonly stderrTruncated: boolean;
|
||||
}
|
||||
|
||||
export class ProcessSpawnError extends Data.TaggedError("ProcessSpawnError")<{
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly cwd?: string | undefined;
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
const ProcessInvocationFields = {
|
||||
command: Schema.String,
|
||||
args: Schema.Array(Schema.String),
|
||||
cwd: Schema.optional(Schema.String),
|
||||
};
|
||||
|
||||
export class ProcessStdinError extends Data.TaggedError("ProcessStdinError")<{
|
||||
const formatProcessInvocation = (input: {
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly cwd?: string | undefined;
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
}): string => {
|
||||
const command = [input.command, ...input.args].join(" ");
|
||||
return input.cwd === undefined ? `'${command}'` : `'${command}' in '${input.cwd}'`;
|
||||
};
|
||||
|
||||
export class ProcessOutputLimitError extends Data.TaggedError("ProcessOutputLimitError")<{
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly cwd?: string | undefined;
|
||||
readonly stream: "stdout" | "stderr";
|
||||
readonly maxBytes: number;
|
||||
}> {}
|
||||
export class ProcessSpawnError extends Schema.TaggedErrorClass<ProcessSpawnError>()(
|
||||
"ProcessSpawnError",
|
||||
{
|
||||
...ProcessInvocationFields,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to spawn process ${formatProcessInvocation(this)}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ProcessReadError extends Data.TaggedError("ProcessReadError")<{
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly cwd?: string | undefined;
|
||||
readonly stream: "stdout" | "stderr" | "exitCode";
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
export class ProcessStdinError extends Schema.TaggedErrorClass<ProcessStdinError>()(
|
||||
"ProcessStdinError",
|
||||
{
|
||||
...ProcessInvocationFields,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to write stdin for process ${formatProcessInvocation(this)}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ProcessTimeoutError extends Data.TaggedError("ProcessTimeoutError")<{
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly cwd?: string | undefined;
|
||||
readonly timeoutMs: number;
|
||||
}> {}
|
||||
export class ProcessOutputLimitError extends Schema.TaggedErrorClass<ProcessOutputLimitError>()(
|
||||
"ProcessOutputLimitError",
|
||||
{
|
||||
...ProcessInvocationFields,
|
||||
stream: Schema.Literals(["stdout", "stderr"]),
|
||||
maxBytes: Schema.Number,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Process ${formatProcessInvocation(this)} ${this.stream} exceeded ${this.maxBytes} bytes`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ProcessReadError extends Schema.TaggedErrorClass<ProcessReadError>()(
|
||||
"ProcessReadError",
|
||||
{
|
||||
...ProcessInvocationFields,
|
||||
stream: Schema.Literals(["stdout", "stderr", "exitCode"]),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to read ${this.stream} for process ${formatProcessInvocation(this)}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ProcessTimeoutError extends Schema.TaggedErrorClass<ProcessTimeoutError>()(
|
||||
"ProcessTimeoutError",
|
||||
{
|
||||
...ProcessInvocationFields,
|
||||
timeoutMs: Schema.Number,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Process ${formatProcessInvocation(this)} timed out after ${this.timeoutMs}ms`;
|
||||
}
|
||||
}
|
||||
|
||||
export type ProcessRunError =
|
||||
| ProcessSpawnError
|
||||
@@ -86,13 +127,12 @@ export type ProcessRunError =
|
||||
| ProcessReadError
|
||||
| ProcessTimeoutError;
|
||||
|
||||
export interface ProcessRunnerShape {
|
||||
readonly run: (input: ProcessRunInput) => Effect.Effect<ProcessRunOutput, ProcessRunError>;
|
||||
}
|
||||
|
||||
export class ProcessRunner extends Context.Service<ProcessRunner, ProcessRunnerShape>()(
|
||||
"t3/processRunner",
|
||||
) {}
|
||||
export class ProcessRunner extends Context.Service<
|
||||
ProcessRunner,
|
||||
{
|
||||
readonly run: (input: ProcessRunInput) => Effect.Effect<ProcessRunOutput, ProcessRunError>;
|
||||
}
|
||||
>()("t3/processRunner") {}
|
||||
|
||||
const DEFAULT_TIMEOUT = "60 seconds";
|
||||
const DEFAULT_MAX_OUTPUT_BYTES = 8 * 1024 * 1024;
|
||||
@@ -332,10 +372,10 @@ const runProcessCore = Effect.fn("processRunner.runProcessCore")(function* (
|
||||
} satisfies ProcessRunOutput;
|
||||
});
|
||||
|
||||
export const make = Effect.fn("makeProcessRunner")(function* () {
|
||||
export const make = Effect.fn("ProcessRunner.make")(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
|
||||
const run: ProcessRunnerShape["run"] = (input) =>
|
||||
const run: ProcessRunner["Service"]["run"] = (input) =>
|
||||
finalizeRunProcess(runProcessCore(spawner, input), input);
|
||||
|
||||
return ProcessRunner.of({
|
||||
|
||||
@@ -5,7 +5,7 @@ import * as Option from "effect/Option";
|
||||
import { describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import { TerminalManager } from "../../terminal/Services/Manager.ts";
|
||||
import * as TerminalManager from "../../terminal/Manager.ts";
|
||||
import { ProjectSetupScriptRunner } from "../Services/ProjectSetupScriptRunner.ts";
|
||||
import { ProjectSetupScriptRunnerLive } from "./ProjectSetupScriptRunner.ts";
|
||||
|
||||
@@ -52,7 +52,7 @@ describe("ProjectSetupScriptRunner", () => {
|
||||
ProjectSetupScriptRunnerLive.pipe(
|
||||
Layer.provideMerge(makeProjectionSnapshotQueryLayer(project)),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(TerminalManager, {
|
||||
Layer.succeed(TerminalManager.TerminalManager, {
|
||||
open,
|
||||
attachStream: () => Effect.die(new Error("unused")),
|
||||
write,
|
||||
@@ -114,7 +114,7 @@ describe("ProjectSetupScriptRunner", () => {
|
||||
ProjectSetupScriptRunnerLive.pipe(
|
||||
Layer.provideMerge(makeProjectionSnapshotQueryLayer(project)),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(TerminalManager, {
|
||||
Layer.succeed(TerminalManager.TerminalManager, {
|
||||
open,
|
||||
attachStream: () => Effect.die(new Error("unused")),
|
||||
write,
|
||||
|
||||
@@ -5,7 +5,7 @@ import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
|
||||
import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import { TerminalManager } from "../../terminal/Services/Manager.ts";
|
||||
import * as TerminalManager from "../../terminal/Manager.ts";
|
||||
import {
|
||||
type ProjectSetupScriptRunnerShape,
|
||||
ProjectSetupScriptRunner,
|
||||
@@ -14,7 +14,7 @@ import {
|
||||
|
||||
const makeProjectSetupScriptRunner = Effect.gen(function* () {
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
const terminalManager = yield* TerminalManager;
|
||||
const terminalManager = yield* TerminalManager.TerminalManager;
|
||||
|
||||
const runForThread: ProjectSetupScriptRunnerShape["runForThread"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
|
||||
@@ -7,7 +7,8 @@ import * as Result from "effect/Result";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Types from "effect/Types";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
import * as ChildProcess from "effect/unstable/process/ChildProcess";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
import * as CodexClient from "effect-codex-app-server/client";
|
||||
import * as CodexSchema from "effect-codex-app-server/schema";
|
||||
import * as CodexErrors from "effect-codex-app-server/errors";
|
||||
@@ -253,7 +254,7 @@ function parseCodexSkillsListResponse(
|
||||
}
|
||||
|
||||
const requestAllCodexModels = Effect.fn("requestAllCodexModels")(function* (
|
||||
client: CodexClient.CodexAppServerClientShape,
|
||||
client: CodexClient.CodexAppServerClient["Service"],
|
||||
) {
|
||||
const models: ServerProviderModel[] = [];
|
||||
let cursor: string | null | undefined = undefined;
|
||||
|
||||
@@ -36,7 +36,7 @@ import * as Scope from "effect/Scope";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as SynchronizedRef from "effect/SynchronizedRef";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
import * as EffectAcpErrors from "effect-acp/errors";
|
||||
import type * as EffectAcpSchema from "effect-acp/schema";
|
||||
|
||||
@@ -50,7 +50,7 @@ import {
|
||||
ProviderAdapterValidationError,
|
||||
} from "../Errors.ts";
|
||||
import { acpPermissionOutcome, mapAcpToAdapterError } from "../acp/AcpAdapterSupport.ts";
|
||||
import { type AcpSessionRuntimeShape } from "../acp/AcpSessionRuntime.ts";
|
||||
import type * as AcpSessionRuntime from "../acp/AcpSessionRuntime.ts";
|
||||
import {
|
||||
makeAcpAssistantItemEvent,
|
||||
makeAcpContentDeltaEvent,
|
||||
@@ -126,7 +126,7 @@ interface CursorSessionContext {
|
||||
readonly threadId: ThreadId;
|
||||
session: ProviderSession;
|
||||
readonly scope: Scope.Closeable;
|
||||
readonly acp: AcpSessionRuntimeShape;
|
||||
readonly acp: AcpSessionRuntime.AcpSessionRuntime["Service"];
|
||||
notificationFiber: Fiber.Fiber<void, never> | undefined;
|
||||
readonly pendingApprovals: Map<ApprovalRequestId, PendingApproval>;
|
||||
readonly pendingUserInputs: Map<ApprovalRequestId, PendingUserInput>;
|
||||
@@ -246,7 +246,7 @@ function resolveRequestedModeId(input: {
|
||||
}
|
||||
|
||||
function applyRequestedSessionConfiguration<E>(input: {
|
||||
readonly runtime: AcpSessionRuntimeShape;
|
||||
readonly runtime: AcpSessionRuntime.AcpSessionRuntime["Service"];
|
||||
readonly runtimeMode: RuntimeMode;
|
||||
readonly interactionMode: ProviderInteractionMode | undefined;
|
||||
readonly modelSelection:
|
||||
|
||||
@@ -21,7 +21,8 @@ import * as Path from "effect/Path";
|
||||
import * as Result from "effect/Result";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
import * as ChildProcess from "effect/unstable/process/ChildProcess";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
import {
|
||||
createModelCapabilities,
|
||||
getProviderOptionBooleanSelectionValue,
|
||||
@@ -43,7 +44,7 @@ import {
|
||||
enrichProviderSnapshotWithVersionAdvisory,
|
||||
type ProviderMaintenanceCapabilities,
|
||||
} from "../providerMaintenance.ts";
|
||||
import { AcpSessionRuntime } from "../acp/AcpSessionRuntime.ts";
|
||||
import * as AcpSessionRuntime from "../acp/AcpSessionRuntime.ts";
|
||||
import { CursorListAvailableModelsResponse } from "../acp/CursorAcpExtension.ts";
|
||||
|
||||
const decodeCursorListAvailableModelsResponse = Schema.decodeUnknownEffect(
|
||||
@@ -416,12 +417,14 @@ const makeCursorAcpProbeRuntime = (
|
||||
clientCapabilities: CURSOR_PARAMETERIZED_MODEL_PICKER_CAPABILITIES,
|
||||
}).pipe(Layer.provide(Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner))),
|
||||
);
|
||||
return yield* Effect.service(AcpSessionRuntime).pipe(Effect.provide(acpContext));
|
||||
return yield* Effect.service(AcpSessionRuntime.AcpSessionRuntime).pipe(
|
||||
Effect.provide(acpContext),
|
||||
);
|
||||
});
|
||||
|
||||
const withCursorAcpProbeRuntime = <A, E, R>(
|
||||
cursorSettings: CursorSettings,
|
||||
useRuntime: (acp: AcpSessionRuntime["Service"]) => Effect.Effect<A, E, R>,
|
||||
useRuntime: (acp: AcpSessionRuntime.AcpSessionRuntime["Service"]) => Effect.Effect<A, E, R>,
|
||||
environment?: NodeJS.ProcessEnv,
|
||||
) =>
|
||||
makeCursorAcpProbeRuntime(cursorSettings, environment).pipe(
|
||||
|
||||
@@ -27,7 +27,7 @@ import * as Scope from "effect/Scope";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as SynchronizedRef from "effect/SynchronizedRef";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
import * as EffectAcpErrors from "effect-acp/errors";
|
||||
import type * as EffectAcpSchema from "effect-acp/schema";
|
||||
|
||||
@@ -41,7 +41,7 @@ import {
|
||||
ProviderAdapterValidationError,
|
||||
} from "../Errors.ts";
|
||||
import { mapAcpToAdapterError } from "../acp/AcpAdapterSupport.ts";
|
||||
import { type AcpSessionRuntimeShape } from "../acp/AcpSessionRuntime.ts";
|
||||
import type * as AcpSessionRuntime from "../acp/AcpSessionRuntime.ts";
|
||||
import {
|
||||
makeAcpAssistantItemEvent,
|
||||
makeAcpContentDeltaEvent,
|
||||
@@ -101,7 +101,7 @@ interface GrokSessionContext {
|
||||
readonly acpSessionId: string;
|
||||
session: ProviderSession;
|
||||
readonly scope: Scope.Closeable;
|
||||
readonly acp: AcpSessionRuntimeShape;
|
||||
readonly acp: AcpSessionRuntime.AcpSessionRuntime["Service"];
|
||||
notificationFiber: Fiber.Fiber<void, never> | undefined;
|
||||
readonly pendingApprovals: Map<ApprovalRequestId, PendingApproval>;
|
||||
readonly pendingUserInputs: Map<ApprovalRequestId, PendingUserInput>;
|
||||
|
||||
@@ -10,16 +10,16 @@ import * as Layer from "effect/Layer";
|
||||
import * as PubSub from "effect/PubSub";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import type { ClaudeAdapterShape } from "../Services/ClaudeAdapter.ts";
|
||||
import type { CodexAdapterShape } from "../Services/CodexAdapter.ts";
|
||||
import type { CursorAdapterShape } from "../Services/CursorAdapter.ts";
|
||||
import type { OpenCodeAdapterShape } from "../Services/OpenCodeAdapter.ts";
|
||||
import { ProviderAdapterRegistry } from "../Services/ProviderAdapterRegistry.ts";
|
||||
import { ProviderInstanceRegistry } from "../Services/ProviderInstanceRegistry.ts";
|
||||
import type * as ClaudeAdapter from "../Services/ClaudeAdapter.ts";
|
||||
import type * as CodexAdapter from "../Services/CodexAdapter.ts";
|
||||
import type * as CursorAdapter from "../Services/CursorAdapter.ts";
|
||||
import type * as OpenCodeAdapter from "../Services/OpenCodeAdapter.ts";
|
||||
import * as ProviderAdapterRegistry from "../Services/ProviderAdapterRegistry.ts";
|
||||
import * as ProviderInstanceRegistry from "../Services/ProviderInstanceRegistry.ts";
|
||||
import type { ProviderInstance } from "../ProviderDriver.ts";
|
||||
import { makeManualOnlyProviderMaintenanceCapabilities } from "../providerMaintenance.ts";
|
||||
import type { TextGenerationShape } from "../../textGeneration/TextGeneration.ts";
|
||||
import { ProviderAdapterRegistryLive } from "./ProviderAdapterRegistry.ts";
|
||||
import type * as TextGeneration from "../../textGeneration/TextGeneration.ts";
|
||||
import * as ProviderAdapterRegistryLayer from "./ProviderAdapterRegistry.ts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
|
||||
const CODEX_DRIVER = ProviderDriverKind.make("codex");
|
||||
@@ -27,7 +27,7 @@ const CLAUDE_AGENT_DRIVER = ProviderDriverKind.make("claudeAgent");
|
||||
const OPENCODE_DRIVER = ProviderDriverKind.make("opencode");
|
||||
const CURSOR_DRIVER = ProviderDriverKind.make("cursor");
|
||||
|
||||
const fakeCodexAdapter: CodexAdapterShape = {
|
||||
const fakeCodexAdapter: CodexAdapter.CodexAdapterShape = {
|
||||
provider: CODEX_DRIVER,
|
||||
capabilities: { sessionModelSwitch: "in-session" },
|
||||
startSession: vi.fn(),
|
||||
@@ -44,7 +44,7 @@ const fakeCodexAdapter: CodexAdapterShape = {
|
||||
streamEvents: Stream.empty,
|
||||
};
|
||||
|
||||
const fakeClaudeAdapter: ClaudeAdapterShape = {
|
||||
const fakeClaudeAdapter: ClaudeAdapter.ClaudeAdapterShape = {
|
||||
provider: CLAUDE_AGENT_DRIVER,
|
||||
capabilities: { sessionModelSwitch: "in-session" },
|
||||
startSession: vi.fn(),
|
||||
@@ -61,7 +61,7 @@ const fakeClaudeAdapter: ClaudeAdapterShape = {
|
||||
streamEvents: Stream.empty,
|
||||
};
|
||||
|
||||
const fakeOpenCodeAdapter: OpenCodeAdapterShape = {
|
||||
const fakeOpenCodeAdapter: OpenCodeAdapter.OpenCodeAdapterShape = {
|
||||
provider: OPENCODE_DRIVER,
|
||||
capabilities: { sessionModelSwitch: "in-session" },
|
||||
startSession: vi.fn(),
|
||||
@@ -78,7 +78,7 @@ const fakeOpenCodeAdapter: OpenCodeAdapterShape = {
|
||||
streamEvents: Stream.empty,
|
||||
};
|
||||
|
||||
const fakeCursorAdapter: CursorAdapterShape = {
|
||||
const fakeCursorAdapter: CursorAdapter.CursorAdapterShape = {
|
||||
provider: CURSOR_DRIVER,
|
||||
capabilities: { sessionModelSwitch: "in-session" },
|
||||
startSession: vi.fn(),
|
||||
@@ -124,7 +124,7 @@ const makeFakeInstance = (
|
||||
streamChanges: Stream.empty,
|
||||
},
|
||||
adapter,
|
||||
textGeneration: {} as unknown as TextGenerationShape,
|
||||
textGeneration: {} as unknown as TextGeneration.TextGeneration["Service"],
|
||||
};
|
||||
};
|
||||
|
||||
@@ -135,7 +135,7 @@ const fakeInstances: ReadonlyArray<ProviderInstance> = [
|
||||
makeFakeInstance("cursor", fakeCursorAdapter),
|
||||
];
|
||||
|
||||
const fakeInstanceRegistryLayer = Layer.succeed(ProviderInstanceRegistry, {
|
||||
const fakeInstanceRegistryLayer = Layer.succeed(ProviderInstanceRegistry.ProviderInstanceRegistry, {
|
||||
getInstance: (instanceId) =>
|
||||
Effect.succeed(fakeInstances.find((instance) => instance.instanceId === instanceId)),
|
||||
listInstances: Effect.succeed(fakeInstances),
|
||||
@@ -147,14 +147,17 @@ const fakeInstanceRegistryLayer = Layer.succeed(ProviderInstanceRegistry, {
|
||||
});
|
||||
|
||||
const layer = Layer.mergeAll(
|
||||
Layer.provide(ProviderAdapterRegistryLive, fakeInstanceRegistryLayer),
|
||||
Layer.provide(
|
||||
ProviderAdapterRegistryLayer.ProviderAdapterRegistryLive,
|
||||
fakeInstanceRegistryLayer,
|
||||
),
|
||||
NodeServices.layer,
|
||||
);
|
||||
|
||||
it.layer(layer)("ProviderAdapterRegistryLive", (it) => {
|
||||
it("resolves adapters and routing metadata from provider instances", () =>
|
||||
Effect.gen(function* () {
|
||||
const registry = yield* ProviderAdapterRegistry;
|
||||
const registry = yield* ProviderAdapterRegistry.ProviderAdapterRegistry;
|
||||
const claudeInstanceId = defaultInstanceIdForDriver(CLAUDE_AGENT_DRIVER);
|
||||
|
||||
const adapter = yield* registry.getByInstance(claudeInstanceId);
|
||||
|
||||
@@ -43,27 +43,23 @@ import {
|
||||
type ProviderAdapterError,
|
||||
} from "../Errors.ts";
|
||||
import type { ProviderAdapterShape } from "../Services/ProviderAdapter.ts";
|
||||
import {
|
||||
ProviderAdapterRegistry,
|
||||
type ProviderAdapterRegistryShape,
|
||||
} from "../Services/ProviderAdapterRegistry.ts";
|
||||
import { ProviderService } from "../Services/ProviderService.ts";
|
||||
import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts";
|
||||
import * as ProviderAdapterRegistry from "../Services/ProviderAdapterRegistry.ts";
|
||||
import * as ProviderService from "../Services/ProviderService.ts";
|
||||
import * as ProviderSessionDirectory from "../Services/ProviderSessionDirectory.ts";
|
||||
import { makeProviderServiceLive } from "./ProviderService.ts";
|
||||
import { NoOpProviderEventLoggers, ProviderEventLoggers } from "./ProviderEventLoggers.ts";
|
||||
import * as ProviderEventLoggers from "./ProviderEventLoggers.ts";
|
||||
import { ProviderSessionDirectoryLive } from "./ProviderSessionDirectory.ts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { ProviderSessionRuntimeRepositoryLive } from "../../persistence/Layers/ProviderSessionRuntime.ts";
|
||||
import { ProviderSessionRuntimeRepository } from "../../persistence/Services/ProviderSessionRuntime.ts";
|
||||
import * as ProviderSessionRuntime from "../../persistence/ProviderSessionRuntime.ts";
|
||||
import {
|
||||
makeSqlitePersistenceLive,
|
||||
SqlitePersistenceMemory,
|
||||
} from "../../persistence/Layers/Sqlite.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { AnalyticsService } from "../../telemetry/Services/AnalyticsService.ts";
|
||||
import * as ServerSettings from "../../serverSettings.ts";
|
||||
import * as AnalyticsService from "../../telemetry/AnalyticsService.ts";
|
||||
import { makeAdapterRegistryMock } from "../testUtils/providerAdapterRegistryMock.ts";
|
||||
|
||||
const defaultServerSettingsLayer = ServerSettingsService.layerTest();
|
||||
const defaultServerSettingsLayer = ServerSettings.ServerSettingsService.layerTest();
|
||||
|
||||
const asRequestId = (value: string): ApprovalRequestId => ApprovalRequestId.make(value);
|
||||
const asEventId = (value: string): EventId => EventId.make(value);
|
||||
@@ -281,8 +277,11 @@ function makeProviderServiceLayer() {
|
||||
[ProviderDriverKind.make("cursor")]: cursor.adapter,
|
||||
});
|
||||
|
||||
const providerAdapterLayer = Layer.succeed(ProviderAdapterRegistry, registry);
|
||||
const runtimeRepositoryLayer = ProviderSessionRuntimeRepositoryLive.pipe(
|
||||
const providerAdapterLayer = Layer.succeed(
|
||||
ProviderAdapterRegistry.ProviderAdapterRegistry,
|
||||
registry,
|
||||
);
|
||||
const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe(
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
);
|
||||
const directoryLayer = ProviderSessionDirectoryLive.pipe(Layer.provide(runtimeRepositoryLayer));
|
||||
@@ -294,7 +293,12 @@ function makeProviderServiceLayer() {
|
||||
Layer.provide(directoryLayer),
|
||||
Layer.provide(defaultServerSettingsLayer),
|
||||
Layer.provideMerge(AnalyticsService.layerTest),
|
||||
Layer.provide(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
|
||||
Layer.provide(
|
||||
Layer.succeed(
|
||||
ProviderEventLoggers.ProviderEventLoggers,
|
||||
ProviderEventLoggers.NoOpProviderEventLoggers,
|
||||
),
|
||||
),
|
||||
),
|
||||
directoryLayer,
|
||||
|
||||
@@ -326,8 +330,11 @@ it.effect("ProviderServiceLive catches stopAll failures during shutdown", () =>
|
||||
const registry = makeAdapterRegistryMock({
|
||||
[CODEX_DRIVER]: codex.adapter,
|
||||
});
|
||||
const providerAdapterLayer = Layer.succeed(ProviderAdapterRegistry, registry);
|
||||
const runtimeRepositoryLayer = ProviderSessionRuntimeRepositoryLive.pipe(
|
||||
const providerAdapterLayer = Layer.succeed(
|
||||
ProviderAdapterRegistry.ProviderAdapterRegistry,
|
||||
registry,
|
||||
);
|
||||
const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe(
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
);
|
||||
const directoryLayer = ProviderSessionDirectoryLive.pipe(Layer.provide(runtimeRepositoryLayer));
|
||||
@@ -337,7 +344,12 @@ it.effect("ProviderServiceLive catches stopAll failures during shutdown", () =>
|
||||
Layer.provide(directoryLayer),
|
||||
Layer.provide(defaultServerSettingsLayer),
|
||||
Layer.provideMerge(AnalyticsService.layerTest),
|
||||
Layer.provide(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
|
||||
Layer.provide(
|
||||
Layer.succeed(
|
||||
ProviderEventLoggers.ProviderEventLoggers,
|
||||
ProviderEventLoggers.NoOpProviderEventLoggers,
|
||||
),
|
||||
),
|
||||
),
|
||||
directoryLayer,
|
||||
runtimeRepositoryLayer,
|
||||
@@ -346,7 +358,7 @@ it.effect("ProviderServiceLive catches stopAll failures during shutdown", () =>
|
||||
const scope = yield* Scope.make();
|
||||
const runtimeServices = yield* Layer.build(providerLayer).pipe(Scope.provide(scope));
|
||||
|
||||
yield* ProviderService.pipe(Effect.provide(runtimeServices));
|
||||
yield* ProviderService.ProviderService.pipe(Effect.provide(runtimeServices));
|
||||
const closeExit = yield* Scope.close(scope, Exit.void).pipe(Effect.exit);
|
||||
|
||||
assert.equal(Exit.isSuccess(closeExit), true);
|
||||
@@ -362,7 +374,7 @@ it.effect("ProviderServiceLive rejects new sessions for disabled providers", ()
|
||||
[CODEX_DRIVER]: codex.adapter,
|
||||
[CLAUDE_AGENT_DRIVER]: claude.adapter,
|
||||
});
|
||||
const registry: ProviderAdapterRegistryShape = {
|
||||
const registry: ProviderAdapterRegistry.ProviderAdapterRegistry["Service"] = {
|
||||
...registryBase,
|
||||
getInstanceInfo: (instanceId) =>
|
||||
instanceId === claudeAgentInstanceId
|
||||
@@ -378,8 +390,11 @@ it.effect("ProviderServiceLive rejects new sessions for disabled providers", ()
|
||||
})
|
||||
: registryBase.getInstanceInfo(instanceId),
|
||||
};
|
||||
const providerAdapterLayer = Layer.succeed(ProviderAdapterRegistry, registry);
|
||||
const runtimeRepositoryLayer = ProviderSessionRuntimeRepositoryLive.pipe(
|
||||
const providerAdapterLayer = Layer.succeed(
|
||||
ProviderAdapterRegistry.ProviderAdapterRegistry,
|
||||
registry,
|
||||
);
|
||||
const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe(
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
);
|
||||
const directoryLayer = ProviderSessionDirectoryLive.pipe(Layer.provide(runtimeRepositoryLayer));
|
||||
@@ -388,12 +403,17 @@ it.effect("ProviderServiceLive rejects new sessions for disabled providers", ()
|
||||
Layer.provide(directoryLayer),
|
||||
Layer.provide(defaultServerSettingsLayer),
|
||||
Layer.provide(AnalyticsService.layerTest),
|
||||
Layer.provide(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
|
||||
Layer.provide(
|
||||
Layer.succeed(
|
||||
ProviderEventLoggers.ProviderEventLoggers,
|
||||
ProviderEventLoggers.NoOpProviderEventLoggers,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const failure = yield* Effect.flip(
|
||||
Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
const provider = yield* ProviderService.ProviderService;
|
||||
return yield* provider.startSession(asThreadId("thread-disabled"), {
|
||||
provider: ProviderDriverKind.make("claudeAgent"),
|
||||
providerInstanceId: claudeAgentInstanceId,
|
||||
@@ -420,7 +440,7 @@ it.effect(
|
||||
new ProviderUnsupportedError({
|
||||
provider: driverKind,
|
||||
});
|
||||
const registry: ProviderAdapterRegistryShape = {
|
||||
const registry: ProviderAdapterRegistry.ProviderAdapterRegistry["Service"] = {
|
||||
getByInstance: (requestedInstanceId) =>
|
||||
requestedInstanceId === instanceId
|
||||
? Effect.succeed(codex.adapter)
|
||||
@@ -445,15 +465,18 @@ it.effect(
|
||||
PubSub.subscribe(pubsub),
|
||||
),
|
||||
};
|
||||
const providerAdapterLayer = Layer.succeed(ProviderAdapterRegistry, registry);
|
||||
const serverSettingsLayer = ServerSettingsService.layerTest({
|
||||
const providerAdapterLayer = Layer.succeed(
|
||||
ProviderAdapterRegistry.ProviderAdapterRegistry,
|
||||
registry,
|
||||
);
|
||||
const serverSettingsLayer = ServerSettings.ServerSettingsService.layerTest({
|
||||
providers: {
|
||||
codex: {
|
||||
enabled: false,
|
||||
},
|
||||
},
|
||||
});
|
||||
const runtimeRepositoryLayer = ProviderSessionRuntimeRepositoryLive.pipe(
|
||||
const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe(
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
);
|
||||
const directoryLayer = ProviderSessionDirectoryLive.pipe(
|
||||
@@ -464,11 +487,16 @@ it.effect(
|
||||
Layer.provide(directoryLayer),
|
||||
Layer.provide(serverSettingsLayer),
|
||||
Layer.provide(AnalyticsService.layerTest),
|
||||
Layer.provide(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
|
||||
Layer.provide(
|
||||
Layer.succeed(
|
||||
ProviderEventLoggers.ProviderEventLoggers,
|
||||
ProviderEventLoggers.NoOpProviderEventLoggers,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const session = yield* Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
const provider = yield* ProviderService.ProviderService;
|
||||
return yield* provider.startSession(asThreadId("thread-enabled-custom"), {
|
||||
provider: driverKind,
|
||||
providerInstanceId: instanceId,
|
||||
@@ -491,7 +519,7 @@ it.effect("ProviderServiceLive rejects new sessions for disabled custom instance
|
||||
new ProviderUnsupportedError({
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
});
|
||||
const registry: ProviderAdapterRegistryShape = {
|
||||
const registry: ProviderAdapterRegistry.ProviderAdapterRegistry["Service"] = {
|
||||
getByInstance: (requestedInstanceId) =>
|
||||
requestedInstanceId === instanceId
|
||||
? Effect.succeed(codex.adapter)
|
||||
@@ -516,8 +544,11 @@ it.effect("ProviderServiceLive rejects new sessions for disabled custom instance
|
||||
PubSub.subscribe(pubsub),
|
||||
),
|
||||
};
|
||||
const providerAdapterLayer = Layer.succeed(ProviderAdapterRegistry, registry);
|
||||
const runtimeRepositoryLayer = ProviderSessionRuntimeRepositoryLive.pipe(
|
||||
const providerAdapterLayer = Layer.succeed(
|
||||
ProviderAdapterRegistry.ProviderAdapterRegistry,
|
||||
registry,
|
||||
);
|
||||
const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe(
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
);
|
||||
const directoryLayer = ProviderSessionDirectoryLive.pipe(Layer.provide(runtimeRepositoryLayer));
|
||||
@@ -526,12 +557,17 @@ it.effect("ProviderServiceLive rejects new sessions for disabled custom instance
|
||||
Layer.provide(directoryLayer),
|
||||
Layer.provide(defaultServerSettingsLayer),
|
||||
Layer.provide(AnalyticsService.layerTest),
|
||||
Layer.provide(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
|
||||
Layer.provide(
|
||||
Layer.succeed(
|
||||
ProviderEventLoggers.ProviderEventLoggers,
|
||||
ProviderEventLoggers.NoOpProviderEventLoggers,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const failure = yield* Effect.flip(
|
||||
Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
const provider = yield* ProviderService.ProviderService;
|
||||
return yield* provider.startSession(asThreadId("thread-disabled-instance"), {
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
providerInstanceId: instanceId,
|
||||
@@ -557,7 +593,7 @@ it.effect("ProviderServiceLive writes canonical events to the emitting thread se
|
||||
const registry = makeAdapterRegistryMock({
|
||||
[ProviderDriverKind.make("codex")]: codex.adapter,
|
||||
});
|
||||
const runtimeRepositoryLayer = ProviderSessionRuntimeRepositoryLive.pipe(
|
||||
const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe(
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
);
|
||||
const directoryLayer = ProviderSessionDirectoryLive.pipe(Layer.provide(runtimeRepositoryLayer));
|
||||
@@ -572,15 +608,20 @@ it.effect("ProviderServiceLive writes canonical events to the emitting thread se
|
||||
close: () => Effect.void,
|
||||
},
|
||||
}).pipe(
|
||||
Layer.provide(Layer.succeed(ProviderAdapterRegistry, registry)),
|
||||
Layer.provide(Layer.succeed(ProviderAdapterRegistry.ProviderAdapterRegistry, registry)),
|
||||
Layer.provide(directoryLayer),
|
||||
Layer.provide(defaultServerSettingsLayer),
|
||||
Layer.provide(AnalyticsService.layerTest),
|
||||
Layer.provide(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
|
||||
Layer.provide(
|
||||
Layer.succeed(
|
||||
ProviderEventLoggers.ProviderEventLoggers,
|
||||
ProviderEventLoggers.NoOpProviderEventLoggers,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
yield* ProviderService;
|
||||
yield* ProviderService.ProviderService;
|
||||
yield* advanceTestClock(10);
|
||||
codex.emit({
|
||||
eventId: asEventId("evt-canonical-thread-segment"),
|
||||
@@ -612,13 +653,13 @@ it.effect("ProviderServiceLive keeps persisted resumable sessions on startup", (
|
||||
});
|
||||
|
||||
const persistenceLayer = makeSqlitePersistenceLive(dbPath);
|
||||
const runtimeRepositoryLayer = ProviderSessionRuntimeRepositoryLive.pipe(
|
||||
const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe(
|
||||
Layer.provide(persistenceLayer),
|
||||
);
|
||||
const directoryLayer = ProviderSessionDirectoryLive.pipe(Layer.provide(runtimeRepositoryLayer));
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const directory = yield* ProviderSessionDirectory;
|
||||
const directory = yield* ProviderSessionDirectory.ProviderSessionDirectory;
|
||||
yield* directory.upsert({
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
providerInstanceId: codexInstanceId,
|
||||
@@ -627,23 +668,28 @@ it.effect("ProviderServiceLive keeps persisted resumable sessions on startup", (
|
||||
}).pipe(Effect.provide(directoryLayer));
|
||||
|
||||
const providerLayer = makeProviderServiceLive().pipe(
|
||||
Layer.provide(Layer.succeed(ProviderAdapterRegistry, registry)),
|
||||
Layer.provide(Layer.succeed(ProviderAdapterRegistry.ProviderAdapterRegistry, registry)),
|
||||
Layer.provide(directoryLayer),
|
||||
Layer.provide(defaultServerSettingsLayer),
|
||||
Layer.provide(AnalyticsService.layerTest),
|
||||
Layer.provide(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
|
||||
Layer.provide(
|
||||
Layer.succeed(
|
||||
ProviderEventLoggers.ProviderEventLoggers,
|
||||
ProviderEventLoggers.NoOpProviderEventLoggers,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
yield* ProviderService.pipe(Effect.provide(providerLayer));
|
||||
yield* ProviderService.ProviderService.pipe(Effect.provide(providerLayer));
|
||||
|
||||
const persistedProvider = yield* Effect.gen(function* () {
|
||||
const directory = yield* ProviderSessionDirectory;
|
||||
const directory = yield* ProviderSessionDirectory.ProviderSessionDirectory;
|
||||
return yield* directory.getProvider(asThreadId("thread-stale"));
|
||||
}).pipe(Effect.provide(directoryLayer));
|
||||
assert.equal(persistedProvider, "codex");
|
||||
|
||||
const runtime = yield* Effect.gen(function* () {
|
||||
const repository = yield* ProviderSessionRuntimeRepository;
|
||||
const repository = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
|
||||
return yield* repository.getByThreadId({
|
||||
threadId: asThreadId("thread-stale"),
|
||||
});
|
||||
@@ -671,7 +717,7 @@ it.effect(
|
||||
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-provider-service-restart-"));
|
||||
const dbPath = path.join(tempDir, "orchestration.sqlite");
|
||||
const persistenceLayer = makeSqlitePersistenceLive(dbPath);
|
||||
const runtimeRepositoryLayer = ProviderSessionRuntimeRepositoryLive.pipe(
|
||||
const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe(
|
||||
Layer.provide(persistenceLayer),
|
||||
);
|
||||
|
||||
@@ -684,11 +730,18 @@ it.effect(
|
||||
Layer.provide(runtimeRepositoryLayer),
|
||||
);
|
||||
const firstProviderLayer = makeProviderServiceLive().pipe(
|
||||
Layer.provide(Layer.succeed(ProviderAdapterRegistry, firstRegistry)),
|
||||
Layer.provide(
|
||||
Layer.succeed(ProviderAdapterRegistry.ProviderAdapterRegistry, firstRegistry),
|
||||
),
|
||||
Layer.provide(firstDirectoryLayer),
|
||||
Layer.provide(defaultServerSettingsLayer),
|
||||
Layer.provide(AnalyticsService.layerTest),
|
||||
Layer.provide(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
|
||||
Layer.provide(
|
||||
Layer.succeed(
|
||||
ProviderEventLoggers.ProviderEventLoggers,
|
||||
ProviderEventLoggers.NoOpProviderEventLoggers,
|
||||
),
|
||||
),
|
||||
);
|
||||
const updatedResumeCursor = {
|
||||
threadId: asThreadId("thread-1"),
|
||||
@@ -698,7 +751,7 @@ it.effect(
|
||||
};
|
||||
|
||||
const startedSession = yield* Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
const provider = yield* ProviderService.ProviderService;
|
||||
const threadId = asThreadId("thread-1");
|
||||
const session = yield* provider.startSession(threadId, {
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
@@ -717,7 +770,7 @@ it.effect(
|
||||
}).pipe(Effect.provide(firstProviderLayer));
|
||||
|
||||
const persistedAfterStopAll = yield* Effect.gen(function* () {
|
||||
const repository = yield* ProviderSessionRuntimeRepository;
|
||||
const repository = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
|
||||
return yield* repository.getByThreadId({
|
||||
threadId: startedSession.threadId,
|
||||
});
|
||||
@@ -736,18 +789,25 @@ it.effect(
|
||||
Layer.provide(runtimeRepositoryLayer),
|
||||
);
|
||||
const secondProviderLayer = makeProviderServiceLive().pipe(
|
||||
Layer.provide(Layer.succeed(ProviderAdapterRegistry, secondRegistry)),
|
||||
Layer.provide(
|
||||
Layer.succeed(ProviderAdapterRegistry.ProviderAdapterRegistry, secondRegistry),
|
||||
),
|
||||
Layer.provide(secondDirectoryLayer),
|
||||
Layer.provide(defaultServerSettingsLayer),
|
||||
Layer.provide(AnalyticsService.layerTest),
|
||||
Layer.provide(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
|
||||
Layer.provide(
|
||||
Layer.succeed(
|
||||
ProviderEventLoggers.ProviderEventLoggers,
|
||||
ProviderEventLoggers.NoOpProviderEventLoggers,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
secondCodex.startSession.mockClear();
|
||||
secondCodex.rollbackThread.mockClear();
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
const provider = yield* ProviderService.ProviderService;
|
||||
yield* provider.rollbackConversation({
|
||||
threadId: startedSession.threadId,
|
||||
numTurns: 1,
|
||||
@@ -781,7 +841,7 @@ it.effect(
|
||||
routing.layer("ProviderServiceLive routing", (it) => {
|
||||
it.effect("routes provider operations and rollback conversation", () =>
|
||||
Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
const provider = yield* ProviderService.ProviderService;
|
||||
|
||||
const session = yield* provider.startSession(asThreadId("thread-1"), {
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
@@ -867,7 +927,7 @@ routing.layer("ProviderServiceLive routing", (it) => {
|
||||
|
||||
it.effect("recovers stale persisted sessions for rollback by resuming thread identity", () =>
|
||||
Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
const provider = yield* ProviderService.ProviderService;
|
||||
|
||||
const initial = yield* provider.startSession(asThreadId("thread-1"), {
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
@@ -908,8 +968,8 @@ routing.layer("ProviderServiceLive routing", (it) => {
|
||||
|
||||
it.effect("preserves the persisted binding when stopping a session", () =>
|
||||
Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
const runtimeRepository = yield* ProviderSessionRuntimeRepository;
|
||||
const provider = yield* ProviderService.ProviderService;
|
||||
const runtimeRepository = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
|
||||
|
||||
const initial = yield* provider.startSession(asThreadId("thread-reap-preserve"), {
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
@@ -960,7 +1020,7 @@ routing.layer("ProviderServiceLive routing", (it) => {
|
||||
|
||||
it.effect("routes explicit claudeAgent provider session starts to the claude adapter", () =>
|
||||
Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
const provider = yield* ProviderService.ProviderService;
|
||||
|
||||
const session = yield* provider.startSession(asThreadId("thread-claude"), {
|
||||
provider: ProviderDriverKind.make("claudeAgent"),
|
||||
@@ -989,8 +1049,8 @@ routing.layer("ProviderServiceLive routing", (it) => {
|
||||
|
||||
it.effect("dies when an active session conflicts with its persisted binding", () =>
|
||||
Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
const directory = yield* ProviderSessionDirectory;
|
||||
const provider = yield* ProviderService.ProviderService;
|
||||
const directory = yield* ProviderSessionDirectory.ProviderSessionDirectory;
|
||||
const threadId = asThreadId("thread-binding-mismatch");
|
||||
|
||||
yield* provider.startSession(threadId, {
|
||||
@@ -1020,7 +1080,7 @@ routing.layer("ProviderServiceLive routing", (it) => {
|
||||
|
||||
it.effect("stops stale sessions in other providers after a successful replacement start", () =>
|
||||
Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
const provider = yield* ProviderService.ProviderService;
|
||||
const threadId = asThreadId("thread-provider-replacement");
|
||||
|
||||
const codexSession = yield* provider.startSession(threadId, {
|
||||
@@ -1059,7 +1119,7 @@ routing.layer("ProviderServiceLive routing", (it) => {
|
||||
|
||||
it.effect("recovers stale sessions for sendTurn using persisted cwd", () =>
|
||||
Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
const provider = yield* ProviderService.ProviderService;
|
||||
|
||||
const initial = yield* provider.startSession(asThreadId("thread-1"), {
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
@@ -1100,7 +1160,7 @@ routing.layer("ProviderServiceLive routing", (it) => {
|
||||
|
||||
it.effect("recovers stale claudeAgent sessions for sendTurn using persisted cwd", () =>
|
||||
Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
const provider = yield* ProviderService.ProviderService;
|
||||
|
||||
const initial = yield* provider.startSession(asThreadId("thread-claude-send-turn"), {
|
||||
provider: ProviderDriverKind.make("claudeAgent"),
|
||||
@@ -1153,7 +1213,7 @@ routing.layer("ProviderServiceLive routing", (it) => {
|
||||
|
||||
it.effect("lists no sessions after adapter runtime clears", () =>
|
||||
Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
const provider = yield* ProviderService.ProviderService;
|
||||
|
||||
yield* provider.startSession(asThreadId("thread-1"), {
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
@@ -1178,8 +1238,8 @@ routing.layer("ProviderServiceLive routing", (it) => {
|
||||
|
||||
it.effect("persists runtime status transitions in provider_session_runtime", () =>
|
||||
Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
const runtimeRepository = yield* ProviderSessionRuntimeRepository;
|
||||
const provider = yield* ProviderService.ProviderService;
|
||||
const runtimeRepository = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
|
||||
|
||||
const threadId = asThreadId("thread-runtime-status");
|
||||
const session = yield* provider.startSession(threadId, {
|
||||
@@ -1226,7 +1286,7 @@ routing.layer("ProviderServiceLive routing", (it) => {
|
||||
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-provider-service-start-"));
|
||||
const dbPath = path.join(tempDir, "orchestration.sqlite");
|
||||
const persistenceLayer = makeSqlitePersistenceLive(dbPath);
|
||||
const runtimeRepositoryLayer = ProviderSessionRuntimeRepositoryLive.pipe(
|
||||
const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe(
|
||||
Layer.provide(persistenceLayer),
|
||||
);
|
||||
|
||||
@@ -1238,15 +1298,22 @@ routing.layer("ProviderServiceLive routing", (it) => {
|
||||
Layer.provide(runtimeRepositoryLayer),
|
||||
);
|
||||
const firstProviderLayer = makeProviderServiceLive().pipe(
|
||||
Layer.provide(Layer.succeed(ProviderAdapterRegistry, firstRegistry)),
|
||||
Layer.provide(
|
||||
Layer.succeed(ProviderAdapterRegistry.ProviderAdapterRegistry, firstRegistry),
|
||||
),
|
||||
Layer.provide(firstDirectoryLayer),
|
||||
Layer.provide(defaultServerSettingsLayer),
|
||||
Layer.provide(AnalyticsService.layerTest),
|
||||
Layer.provide(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
|
||||
Layer.provide(
|
||||
Layer.succeed(
|
||||
ProviderEventLoggers.ProviderEventLoggers,
|
||||
ProviderEventLoggers.NoOpProviderEventLoggers,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const initial = yield* Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
const provider = yield* ProviderService.ProviderService;
|
||||
return yield* provider.startSession(asThreadId("thread-claude-start"), {
|
||||
provider: ProviderDriverKind.make("claudeAgent"),
|
||||
providerInstanceId: claudeAgentInstanceId,
|
||||
@@ -1257,7 +1324,7 @@ routing.layer("ProviderServiceLive routing", (it) => {
|
||||
}).pipe(Effect.provide(firstProviderLayer));
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
const provider = yield* ProviderService.ProviderService;
|
||||
yield* provider.listSessions();
|
||||
}).pipe(Effect.provide(firstProviderLayer));
|
||||
|
||||
@@ -1269,17 +1336,24 @@ routing.layer("ProviderServiceLive routing", (it) => {
|
||||
Layer.provide(runtimeRepositoryLayer),
|
||||
);
|
||||
const secondProviderLayer = makeProviderServiceLive().pipe(
|
||||
Layer.provide(Layer.succeed(ProviderAdapterRegistry, secondRegistry)),
|
||||
Layer.provide(
|
||||
Layer.succeed(ProviderAdapterRegistry.ProviderAdapterRegistry, secondRegistry),
|
||||
),
|
||||
Layer.provide(secondDirectoryLayer),
|
||||
Layer.provide(defaultServerSettingsLayer),
|
||||
Layer.provide(AnalyticsService.layerTest),
|
||||
Layer.provide(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
|
||||
Layer.provide(
|
||||
Layer.succeed(
|
||||
ProviderEventLoggers.ProviderEventLoggers,
|
||||
ProviderEventLoggers.NoOpProviderEventLoggers,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
secondClaude.startSession.mockClear();
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
const provider = yield* ProviderService.ProviderService;
|
||||
yield* provider.startSession(initial.threadId, {
|
||||
provider: ProviderDriverKind.make("claudeAgent"),
|
||||
providerInstanceId: claudeAgentInstanceId,
|
||||
@@ -1316,7 +1390,7 @@ routing.layer("ProviderServiceLive routing", (it) => {
|
||||
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-provider-service-cwd-"));
|
||||
const dbPath = path.join(tempDir, "orchestration.sqlite");
|
||||
const persistenceLayer = makeSqlitePersistenceLive(dbPath);
|
||||
const runtimeRepositoryLayer = ProviderSessionRuntimeRepositoryLive.pipe(
|
||||
const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe(
|
||||
Layer.provide(persistenceLayer),
|
||||
);
|
||||
|
||||
@@ -1328,15 +1402,22 @@ routing.layer("ProviderServiceLive routing", (it) => {
|
||||
Layer.provide(runtimeRepositoryLayer),
|
||||
);
|
||||
const firstProviderLayer = makeProviderServiceLive().pipe(
|
||||
Layer.provide(Layer.succeed(ProviderAdapterRegistry, firstRegistry)),
|
||||
Layer.provide(
|
||||
Layer.succeed(ProviderAdapterRegistry.ProviderAdapterRegistry, firstRegistry),
|
||||
),
|
||||
Layer.provide(firstDirectoryLayer),
|
||||
Layer.provide(defaultServerSettingsLayer),
|
||||
Layer.provide(AnalyticsService.layerTest),
|
||||
Layer.provide(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
|
||||
Layer.provide(
|
||||
Layer.succeed(
|
||||
ProviderEventLoggers.ProviderEventLoggers,
|
||||
ProviderEventLoggers.NoOpProviderEventLoggers,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const initial = yield* Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
const provider = yield* ProviderService.ProviderService;
|
||||
return yield* provider.startSession(asThreadId("thread-claude-cwd"), {
|
||||
provider: ProviderDriverKind.make("claudeAgent"),
|
||||
providerInstanceId: claudeAgentInstanceId,
|
||||
@@ -1354,17 +1435,24 @@ routing.layer("ProviderServiceLive routing", (it) => {
|
||||
Layer.provide(runtimeRepositoryLayer),
|
||||
);
|
||||
const secondProviderLayer = makeProviderServiceLive().pipe(
|
||||
Layer.provide(Layer.succeed(ProviderAdapterRegistry, secondRegistry)),
|
||||
Layer.provide(
|
||||
Layer.succeed(ProviderAdapterRegistry.ProviderAdapterRegistry, secondRegistry),
|
||||
),
|
||||
Layer.provide(secondDirectoryLayer),
|
||||
Layer.provide(defaultServerSettingsLayer),
|
||||
Layer.provide(AnalyticsService.layerTest),
|
||||
Layer.provide(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
|
||||
Layer.provide(
|
||||
Layer.succeed(
|
||||
ProviderEventLoggers.ProviderEventLoggers,
|
||||
ProviderEventLoggers.NoOpProviderEventLoggers,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
secondClaude.startSession.mockClear();
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
const provider = yield* ProviderService.ProviderService;
|
||||
yield* provider.startSession(initial.threadId, {
|
||||
provider: ProviderDriverKind.make("claudeAgent"),
|
||||
providerInstanceId: claudeAgentInstanceId,
|
||||
@@ -1398,7 +1486,7 @@ const fanout = makeProviderServiceLayer();
|
||||
fanout.layer("ProviderServiceLive fanout", (it) => {
|
||||
it.effect("fans out adapter turn completion events", () =>
|
||||
Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
const provider = yield* ProviderService.ProviderService;
|
||||
const session = yield* provider.startSession(asThreadId("thread-1"), {
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
providerInstanceId: codexInstanceId,
|
||||
@@ -1444,7 +1532,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
|
||||
|
||||
it.effect("fans out canonical runtime events in emission order", () =>
|
||||
Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
const provider = yield* ProviderService.ProviderService;
|
||||
const session = yield* provider.startSession(asThreadId("thread-seq"), {
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
providerInstanceId: codexInstanceId,
|
||||
@@ -1500,7 +1588,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
|
||||
|
||||
it.effect("keeps subscriber delivery ordered and isolates failing subscribers", () =>
|
||||
Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
const provider = yield* ProviderService.ProviderService;
|
||||
const session = yield* provider.startSession(asThreadId("thread-1"), {
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
providerInstanceId: codexInstanceId,
|
||||
@@ -1572,7 +1660,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
|
||||
|
||||
it.effect("records provider metrics with the routed provider label", () =>
|
||||
Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
const provider = yield* ProviderService.ProviderService;
|
||||
|
||||
const session = yield* provider.startSession(asThreadId("thread-metrics"), {
|
||||
provider: ProviderDriverKind.make("claudeAgent"),
|
||||
@@ -1650,7 +1738,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
|
||||
"records sendTurn metrics with the resolved provider when modelSelection is omitted",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
const provider = yield* ProviderService.ProviderService;
|
||||
|
||||
const session = yield* provider.startSession(asThreadId("thread-send-metrics"), {
|
||||
provider: ProviderDriverKind.make("claudeAgent"),
|
||||
@@ -1691,7 +1779,7 @@ const validation = makeProviderServiceLayer();
|
||||
validation.layer("ProviderServiceLive validation", (it) => {
|
||||
it.effect("rejects session starts without an explicit provider instance id", () =>
|
||||
Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
const provider = yield* ProviderService.ProviderService;
|
||||
|
||||
validation.codex.startSession.mockClear();
|
||||
const failure = yield* Effect.flip(
|
||||
@@ -1710,7 +1798,7 @@ validation.layer("ProviderServiceLive validation", (it) => {
|
||||
|
||||
it.effect("rejects mismatched provider kind and provider instance id", () =>
|
||||
Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
const provider = yield* ProviderService.ProviderService;
|
||||
|
||||
validation.codex.startSession.mockClear();
|
||||
validation.claude.startSession.mockClear();
|
||||
@@ -1735,7 +1823,7 @@ validation.layer("ProviderServiceLive validation", (it) => {
|
||||
|
||||
it.effect("returns ProviderValidationError for invalid input payloads", () =>
|
||||
Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
const provider = yield* ProviderService.ProviderService;
|
||||
|
||||
const failure = yield* Effect.result(
|
||||
provider.startSession(asThreadId("thread-validation"), {
|
||||
@@ -1760,8 +1848,8 @@ validation.layer("ProviderServiceLive validation", (it) => {
|
||||
|
||||
it.effect("accepts startSession when adapter has not emitted provider thread id yet", () =>
|
||||
Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
const runtimeRepository = yield* ProviderSessionRuntimeRepository;
|
||||
const provider = yield* ProviderService.ProviderService;
|
||||
const runtimeRepository = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
|
||||
|
||||
validation.codex.startSession.mockImplementationOnce((input: ProviderSessionStartInput) =>
|
||||
Effect.sync(() => {
|
||||
|
||||
@@ -47,15 +47,12 @@ import {
|
||||
} from "../../observability/Metrics.ts";
|
||||
import { type ProviderAdapterError, ProviderValidationError } from "../Errors.ts";
|
||||
import type { ProviderAdapterShape } from "../Services/ProviderAdapter.ts";
|
||||
import { ProviderAdapterRegistry } from "../Services/ProviderAdapterRegistry.ts";
|
||||
import { ProviderService, type ProviderServiceShape } from "../Services/ProviderService.ts";
|
||||
import {
|
||||
ProviderSessionDirectory,
|
||||
type ProviderRuntimeBinding,
|
||||
} from "../Services/ProviderSessionDirectory.ts";
|
||||
import * as ProviderAdapterRegistry from "../Services/ProviderAdapterRegistry.ts";
|
||||
import * as ProviderService from "../Services/ProviderService.ts";
|
||||
import * as ProviderSessionDirectory from "../Services/ProviderSessionDirectory.ts";
|
||||
import { type EventNdjsonLogger } from "./EventNdjsonLogger.ts";
|
||||
import { ProviderEventLoggers } from "./ProviderEventLoggers.ts";
|
||||
import { AnalyticsService } from "../../telemetry/Services/AnalyticsService.ts";
|
||||
import * as ProviderEventLoggers from "./ProviderEventLoggers.ts";
|
||||
import * as AnalyticsService from "../../telemetry/AnalyticsService.ts";
|
||||
import * as McpProviderSession from "../../mcp/McpProviderSession.ts";
|
||||
import * as McpSessionRegistry from "../../mcp/McpSessionRegistry.ts";
|
||||
const isModelSelection = Schema.is(ModelSelection);
|
||||
@@ -69,6 +66,9 @@ export interface ProviderServiceLiveOptions {
|
||||
readonly canonicalEventLogger?: EventNdjsonLogger;
|
||||
}
|
||||
|
||||
type ProviderServiceMethod<Name extends keyof ProviderService.ProviderService["Service"]> =
|
||||
ProviderService.ProviderService["Service"][Name];
|
||||
|
||||
const ProviderRollbackConversationInput = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
numTurns: NonNegativeInt,
|
||||
@@ -141,7 +141,7 @@ function toRuntimePayloadFromSession(
|
||||
}
|
||||
|
||||
function readPersistedModelSelection(
|
||||
runtimePayload: ProviderRuntimeBinding["runtimePayload"],
|
||||
runtimePayload: ProviderSessionDirectory.ProviderRuntimeBinding["runtimePayload"],
|
||||
): ModelSelection | undefined {
|
||||
if (!runtimePayload || typeof runtimePayload !== "object" || Array.isArray(runtimePayload)) {
|
||||
return undefined;
|
||||
@@ -151,7 +151,7 @@ function readPersistedModelSelection(
|
||||
}
|
||||
|
||||
function readPersistedCwd(
|
||||
runtimePayload: ProviderRuntimeBinding["runtimePayload"],
|
||||
runtimePayload: ProviderSessionDirectory.ProviderRuntimeBinding["runtimePayload"],
|
||||
): string | undefined {
|
||||
if (!runtimePayload || typeof runtimePayload !== "object" || Array.isArray(runtimePayload)) {
|
||||
return undefined;
|
||||
@@ -202,16 +202,16 @@ const correlateRuntimeEventWithInstance = (
|
||||
const makeProviderService = Effect.fn("makeProviderService")(function* (
|
||||
options?: ProviderServiceLiveOptions,
|
||||
) {
|
||||
const analytics = yield* Effect.service(AnalyticsService);
|
||||
const eventLoggers = yield* ProviderEventLoggers;
|
||||
const analytics = yield* Effect.service(AnalyticsService.AnalyticsService);
|
||||
const eventLoggers = yield* ProviderEventLoggers.ProviderEventLoggers;
|
||||
// Options-provided logger wins (test overrides); otherwise we take whatever
|
||||
// the `ProviderEventLoggers` tag exposes — `undefined` means "no canonical
|
||||
// log writer is attached", which downstream code already handles as a
|
||||
// no-op.
|
||||
const canonicalEventLogger = options?.canonicalEventLogger ?? eventLoggers.canonical;
|
||||
|
||||
const registry = yield* ProviderAdapterRegistry;
|
||||
const directory = yield* ProviderSessionDirectory;
|
||||
const registry = yield* ProviderAdapterRegistry.ProviderAdapterRegistry;
|
||||
const directory = yield* ProviderSessionDirectory.ProviderSessionDirectory;
|
||||
const runtimeEventPubSub = yield* PubSub.unbounded<ProviderRuntimeEvent>();
|
||||
const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
|
||||
const prepareMcpSession = (threadId: ThreadId, providerInstanceId: ProviderInstanceId) =>
|
||||
@@ -353,7 +353,7 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
|
||||
).pipe(Effect.forkScoped);
|
||||
|
||||
const recoverSessionForThread = Effect.fn("recoverSessionForThread")(function* (input: {
|
||||
readonly binding: ProviderRuntimeBinding;
|
||||
readonly binding: ProviderSessionDirectory.ProviderRuntimeBinding;
|
||||
readonly operation: string;
|
||||
}) {
|
||||
const bindingInstanceId = yield* requireBindingInstanceId(input.operation, input.binding);
|
||||
@@ -519,7 +519,7 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
|
||||
);
|
||||
});
|
||||
|
||||
const startSession: ProviderServiceShape["startSession"] = Effect.fn("startSession")(
|
||||
const startSession: ProviderServiceMethod<"startSession"> = Effect.fn("startSession")(
|
||||
function* (threadId, rawInput) {
|
||||
const parsed = yield* decodeInputOrValidationError({
|
||||
operation: "ProviderService.startSession",
|
||||
@@ -642,7 +642,7 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
|
||||
},
|
||||
);
|
||||
|
||||
const sendTurn: ProviderServiceShape["sendTurn"] = Effect.fn("sendTurn")(function* (rawInput) {
|
||||
const sendTurn: ProviderServiceMethod<"sendTurn"> = Effect.fn("sendTurn")(function* (rawInput) {
|
||||
const parsed = yield* decodeInputOrValidationError({
|
||||
operation: "ProviderService.sendTurn",
|
||||
schema: ProviderSendTurnInput,
|
||||
@@ -717,7 +717,7 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
|
||||
);
|
||||
});
|
||||
|
||||
const interruptTurn: ProviderServiceShape["interruptTurn"] = Effect.fn("interruptTurn")(
|
||||
const interruptTurn: ProviderServiceMethod<"interruptTurn"> = Effect.fn("interruptTurn")(
|
||||
function* (rawInput) {
|
||||
const input = yield* decodeInputOrValidationError({
|
||||
operation: "ProviderService.interruptTurn",
|
||||
@@ -754,7 +754,7 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
|
||||
},
|
||||
);
|
||||
|
||||
const respondToRequest: ProviderServiceShape["respondToRequest"] = Effect.fn("respondToRequest")(
|
||||
const respondToRequest: ProviderServiceMethod<"respondToRequest"> = Effect.fn("respondToRequest")(
|
||||
function* (rawInput) {
|
||||
const input = yield* decodeInputOrValidationError({
|
||||
operation: "ProviderService.respondToRequest",
|
||||
@@ -792,7 +792,7 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
|
||||
},
|
||||
);
|
||||
|
||||
const respondToUserInput: ProviderServiceShape["respondToUserInput"] = Effect.fn(
|
||||
const respondToUserInput: ProviderServiceMethod<"respondToUserInput"> = Effect.fn(
|
||||
"respondToUserInput",
|
||||
)(function* (rawInput) {
|
||||
const input = yield* decodeInputOrValidationError({
|
||||
@@ -826,7 +826,7 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
|
||||
);
|
||||
});
|
||||
|
||||
const stopSession: ProviderServiceShape["stopSession"] = Effect.fn("stopSession")(
|
||||
const stopSession: ProviderServiceMethod<"stopSession"> = Effect.fn("stopSession")(
|
||||
function* (rawInput) {
|
||||
const input = yield* decodeInputOrValidationError({
|
||||
operation: "ProviderService.stopSession",
|
||||
@@ -874,7 +874,7 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
|
||||
},
|
||||
);
|
||||
|
||||
const listSessions: ProviderServiceShape["listSessions"] = Effect.fn("listSessions")(
|
||||
const listSessions: ProviderServiceMethod<"listSessions"> = Effect.fn("listSessions")(
|
||||
function* () {
|
||||
const currentAdapters = yield* getAdapterEntries;
|
||||
const sessionsByProvider = yield* Effect.forEach(currentAdapters, ([instanceId, adapter]) =>
|
||||
@@ -895,13 +895,22 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
|
||||
(threadId) =>
|
||||
directory
|
||||
.getBinding(threadId)
|
||||
.pipe(Effect.orElseSucceed(() => Option.none<ProviderRuntimeBinding>())),
|
||||
.pipe(
|
||||
Effect.orElseSucceed(() =>
|
||||
Option.none<ProviderSessionDirectory.ProviderRuntimeBinding>(),
|
||||
),
|
||||
),
|
||||
{ concurrency: "unbounded" },
|
||||
),
|
||||
),
|
||||
Effect.orElseSucceed(() => [] as Array<Option.Option<ProviderRuntimeBinding>>),
|
||||
Effect.orElseSucceed(
|
||||
() => [] as Array<Option.Option<ProviderSessionDirectory.ProviderRuntimeBinding>>,
|
||||
),
|
||||
);
|
||||
const bindingsByThreadId = new Map<ThreadId, ProviderRuntimeBinding>();
|
||||
const bindingsByThreadId = new Map<
|
||||
ThreadId,
|
||||
ProviderSessionDirectory.ProviderRuntimeBinding
|
||||
>();
|
||||
for (const bindingOption of persistedBindings) {
|
||||
const binding = Option.getOrUndefined(bindingOption);
|
||||
if (binding) {
|
||||
@@ -952,13 +961,13 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
|
||||
},
|
||||
);
|
||||
|
||||
const getCapabilities: ProviderServiceShape["getCapabilities"] = (instanceId) =>
|
||||
const getCapabilities: ProviderServiceMethod<"getCapabilities"> = (instanceId) =>
|
||||
registry.getByInstance(instanceId).pipe(Effect.map((adapter) => adapter.capabilities));
|
||||
|
||||
const getInstanceInfo: ProviderServiceShape["getInstanceInfo"] = (instanceId) =>
|
||||
const getInstanceInfo: ProviderServiceMethod<"getInstanceInfo"> = (instanceId) =>
|
||||
registry.getInstanceInfo(instanceId);
|
||||
|
||||
const rollbackConversation: ProviderServiceShape["rollbackConversation"] = Effect.fn(
|
||||
const rollbackConversation: ProviderServiceMethod<"rollbackConversation"> = Effect.fn(
|
||||
"rollbackConversation",
|
||||
)(function* (rawInput) {
|
||||
const input = yield* decodeInputOrValidationError({
|
||||
@@ -1071,14 +1080,17 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
|
||||
// Each access creates a fresh PubSub subscription so that multiple
|
||||
// consumers (ProviderRuntimeIngestion, CheckpointReactor, etc.) each
|
||||
// independently receive all runtime events.
|
||||
get streamEvents(): ProviderServiceShape["streamEvents"] {
|
||||
get streamEvents(): ProviderServiceMethod<"streamEvents"> {
|
||||
return Stream.fromPubSub(runtimeEventPubSub);
|
||||
},
|
||||
} satisfies ProviderServiceShape;
|
||||
} satisfies ProviderService.ProviderService["Service"];
|
||||
});
|
||||
|
||||
export const ProviderServiceLive = Layer.effect(ProviderService, makeProviderService());
|
||||
export const ProviderServiceLive = Layer.effect(
|
||||
ProviderService.ProviderService,
|
||||
makeProviderService(),
|
||||
);
|
||||
|
||||
export function makeProviderServiceLive(options?: ProviderServiceLiveOptions) {
|
||||
return Layer.effect(ProviderService, makeProviderService(options));
|
||||
return Layer.effect(ProviderService.ProviderService, makeProviderService(options));
|
||||
}
|
||||
@@ -16,15 +16,12 @@ import {
|
||||
makeSqlitePersistenceLive,
|
||||
SqlitePersistenceMemory,
|
||||
} from "../../persistence/Layers/Sqlite.ts";
|
||||
import { ProviderSessionRuntimeRepositoryLive } from "../../persistence/Layers/ProviderSessionRuntime.ts";
|
||||
import { ProviderSessionRuntimeRepository } from "../../persistence/Services/ProviderSessionRuntime.ts";
|
||||
import * as ProviderSessionRuntime from "../../persistence/ProviderSessionRuntime.ts";
|
||||
import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts";
|
||||
import { ProviderSessionDirectoryLive } from "./ProviderSessionDirectory.ts";
|
||||
|
||||
function makeDirectoryLayer<E, R>(persistenceLayer: Layer.Layer<SqlClient.SqlClient, E, R>) {
|
||||
const runtimeRepositoryLayer = ProviderSessionRuntimeRepositoryLive.pipe(
|
||||
Layer.provide(persistenceLayer),
|
||||
);
|
||||
const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe(Layer.provide(persistenceLayer));
|
||||
return Layer.mergeAll(
|
||||
runtimeRepositoryLayer,
|
||||
ProviderSessionDirectoryLive.pipe(Layer.provide(runtimeRepositoryLayer)),
|
||||
@@ -36,7 +33,7 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
|
||||
it("upserts and reads thread bindings", () =>
|
||||
Effect.gen(function* () {
|
||||
const directory = yield* ProviderSessionDirectory;
|
||||
const runtimeRepository = yield* ProviderSessionRuntimeRepository;
|
||||
const runtimeRepository = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
|
||||
|
||||
const initialThreadId = ThreadId.make("thread-1");
|
||||
|
||||
@@ -83,7 +80,7 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
|
||||
it("persists runtime fields and merges payload updates", () =>
|
||||
Effect.gen(function* () {
|
||||
const directory = yield* ProviderSessionDirectory;
|
||||
const runtimeRepository = yield* ProviderSessionRuntimeRepository;
|
||||
const runtimeRepository = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
|
||||
|
||||
const threadId = ThreadId.make("thread-runtime");
|
||||
|
||||
@@ -128,7 +125,7 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
|
||||
it("lists persisted bindings with metadata in oldest-first order", () =>
|
||||
Effect.gen(function* () {
|
||||
const directory = yield* ProviderSessionDirectory;
|
||||
const runtimeRepository = yield* ProviderSessionRuntimeRepository;
|
||||
const runtimeRepository = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
|
||||
|
||||
const olderThreadId = ThreadId.make("thread-runtime-older");
|
||||
const newerThreadId = ThreadId.make("thread-runtime-newer");
|
||||
@@ -202,7 +199,7 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
|
||||
it("resets adapterKey to the new provider when provider changes without an explicit adapter key", () =>
|
||||
Effect.gen(function* () {
|
||||
const directory = yield* ProviderSessionDirectory;
|
||||
const runtimeRepository = yield* ProviderSessionRuntimeRepository;
|
||||
const runtimeRepository = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
|
||||
const threadId = ThreadId.make("thread-provider-change");
|
||||
|
||||
yield* runtimeRepository.upsert({
|
||||
|
||||
@@ -5,8 +5,7 @@ import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import type { ProviderSessionRuntime } from "../../persistence/Services/ProviderSessionRuntime.ts";
|
||||
import { ProviderSessionRuntimeRepository } from "../../persistence/Services/ProviderSessionRuntime.ts";
|
||||
import * as ProviderSessionRuntime from "../../persistence/ProviderSessionRuntime.ts";
|
||||
import { ProviderSessionDirectoryPersistenceError, ProviderValidationError } from "../Errors.ts";
|
||||
import {
|
||||
ProviderSessionDirectory,
|
||||
@@ -59,7 +58,7 @@ function mergeRuntimePayload(
|
||||
}
|
||||
|
||||
function toRuntimeBinding(
|
||||
runtime: ProviderSessionRuntime,
|
||||
runtime: ProviderSessionRuntime.ProviderSessionRuntime,
|
||||
operation: string,
|
||||
): Effect.Effect<ProviderRuntimeBindingWithMetadata, ProviderSessionDirectoryPersistenceError> {
|
||||
return decodeProviderDriverKind(runtime.providerName, operation).pipe(
|
||||
@@ -85,7 +84,7 @@ function toRuntimeBinding(
|
||||
}
|
||||
|
||||
const makeProviderSessionDirectory = Effect.gen(function* () {
|
||||
const repository = yield* ProviderSessionRuntimeRepository;
|
||||
const repository = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
|
||||
|
||||
const getBinding = (threadId: ThreadId) =>
|
||||
repository.getByThreadId({ threadId }).pipe(
|
||||
|
||||
@@ -19,8 +19,7 @@ import { afterEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
|
||||
import { ProviderSessionRuntimeRepositoryLive } from "../../persistence/Layers/ProviderSessionRuntime.ts";
|
||||
import { ProviderSessionRuntimeRepository } from "../../persistence/Services/ProviderSessionRuntime.ts";
|
||||
import * as ProviderSessionRuntime from "../../persistence/ProviderSessionRuntime.ts";
|
||||
import { ProviderValidationError } from "../Errors.ts";
|
||||
import { ProviderSessionReaper } from "../Services/ProviderSessionReaper.ts";
|
||||
import { ProviderService, type ProviderServiceShape } from "../Services/ProviderService.ts";
|
||||
@@ -118,7 +117,7 @@ function makeReadModel(
|
||||
|
||||
describe("ProviderSessionReaper", () => {
|
||||
let runtime: ManagedRuntime.ManagedRuntime<
|
||||
ProviderSessionReaper | ProviderSessionRuntimeRepository,
|
||||
ProviderSessionReaper | ProviderSessionRuntime.ProviderSessionRuntimeRepository,
|
||||
unknown
|
||||
> | null = null;
|
||||
let scope: Scope.Closeable | null = null;
|
||||
@@ -176,7 +175,7 @@ describe("ProviderSessionReaper", () => {
|
||||
streamEvents: Stream.empty,
|
||||
};
|
||||
|
||||
const runtimeRepositoryLayer = ProviderSessionRuntimeRepositoryLive.pipe(
|
||||
const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe(
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
);
|
||||
const providerSessionDirectoryLayer = ProviderSessionDirectoryLive.pipe(
|
||||
@@ -238,7 +237,9 @@ describe("ProviderSessionReaper", () => {
|
||||
},
|
||||
]),
|
||||
});
|
||||
const repository = await runtime!.runPromise(Effect.service(ProviderSessionRuntimeRepository));
|
||||
const repository = await runtime!.runPromise(
|
||||
Effect.service(ProviderSessionRuntime.ProviderSessionRuntimeRepository),
|
||||
);
|
||||
|
||||
await runtime!.runPromise(
|
||||
repository.upsert({
|
||||
@@ -286,7 +287,9 @@ describe("ProviderSessionReaper", () => {
|
||||
},
|
||||
]),
|
||||
});
|
||||
const repository = await runtime!.runPromise(Effect.service(ProviderSessionRuntimeRepository));
|
||||
const repository = await runtime!.runPromise(
|
||||
Effect.service(ProviderSessionRuntime.ProviderSessionRuntimeRepository),
|
||||
);
|
||||
|
||||
await runtime!.runPromise(
|
||||
repository.upsert({
|
||||
@@ -333,7 +336,9 @@ describe("ProviderSessionReaper", () => {
|
||||
},
|
||||
]),
|
||||
});
|
||||
const repository = await runtime!.runPromise(Effect.service(ProviderSessionRuntimeRepository));
|
||||
const repository = await runtime!.runPromise(
|
||||
Effect.service(ProviderSessionRuntime.ProviderSessionRuntimeRepository),
|
||||
);
|
||||
|
||||
await runtime!.runPromise(
|
||||
repository.upsert({
|
||||
@@ -380,7 +385,9 @@ describe("ProviderSessionReaper", () => {
|
||||
},
|
||||
]),
|
||||
});
|
||||
const repository = await runtime!.runPromise(Effect.service(ProviderSessionRuntimeRepository));
|
||||
const repository = await runtime!.runPromise(
|
||||
Effect.service(ProviderSessionRuntime.ProviderSessionRuntimeRepository),
|
||||
);
|
||||
|
||||
await runtime!.runPromise(
|
||||
repository.upsert({
|
||||
@@ -449,7 +456,9 @@ describe("ProviderSessionReaper", () => {
|
||||
)
|
||||
: Effect.void,
|
||||
});
|
||||
const repository = await runtime!.runPromise(Effect.service(ProviderSessionRuntimeRepository));
|
||||
const repository = await runtime!.runPromise(
|
||||
Effect.service(ProviderSessionRuntime.ProviderSessionRuntimeRepository),
|
||||
);
|
||||
|
||||
await runtime!.runPromise(
|
||||
repository.upsert({
|
||||
@@ -530,7 +539,9 @@ describe("ProviderSessionReaper", () => {
|
||||
? Effect.die(new Error("simulated stop defect"))
|
||||
: Effect.void,
|
||||
});
|
||||
const repository = await runtime!.runPromise(Effect.service(ProviderSessionRuntimeRepository));
|
||||
const repository = await runtime!.runPromise(
|
||||
Effect.service(ProviderSessionRuntime.ProviderSessionRuntimeRepository),
|
||||
);
|
||||
|
||||
await runtime!.runPromise(
|
||||
repository.upsert({
|
||||
|
||||
@@ -30,7 +30,7 @@ import type * as Effect from "effect/Effect";
|
||||
import type * as Schema from "effect/Schema";
|
||||
import type * as Scope from "effect/Scope";
|
||||
|
||||
import type { TextGenerationShape } from "../textGeneration/TextGeneration.ts";
|
||||
import type * as TextGeneration from "../textGeneration/TextGeneration.ts";
|
||||
import type { ProviderAdapterError, ProviderDriverError } from "./Errors.ts";
|
||||
import type { ProviderAdapterShape } from "./Services/ProviderAdapter.ts";
|
||||
import type { ServerProviderShape } from "./Services/ServerProvider.ts";
|
||||
@@ -70,7 +70,7 @@ export interface ProviderInstance {
|
||||
readonly enabled: boolean;
|
||||
readonly snapshot: ServerProviderShape;
|
||||
readonly adapter: ProviderAdapterShape<ProviderAdapterError>;
|
||||
readonly textGeneration: TextGenerationShape;
|
||||
readonly textGeneration: TextGeneration.TextGeneration["Service"];
|
||||
}
|
||||
|
||||
export interface ProviderContinuationIdentity {
|
||||
|
||||
@@ -10,7 +10,7 @@ import * as Effect from "effect/Effect";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { describe, expect } from "vite-plus/test";
|
||||
|
||||
import { AcpSessionRuntime, type AcpSessionRequestLogEvent } from "./AcpSessionRuntime.ts";
|
||||
import * as AcpSessionRuntime from "./AcpSessionRuntime.ts";
|
||||
import type * as EffectAcpProtocol from "effect-acp/protocol";
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
@@ -20,9 +20,9 @@ const mockAgentArgs = [mockAgentPath];
|
||||
|
||||
describe("AcpSessionRuntime", () => {
|
||||
it.effect("merges custom initialize client capabilities into the ACP handshake", () => {
|
||||
const requestEvents: Array<AcpSessionRequestLogEvent> = [];
|
||||
const requestEvents: Array<AcpSessionRuntime.AcpSessionRequestLogEvent> = [];
|
||||
return Effect.gen(function* () {
|
||||
const runtime = yield* AcpSessionRuntime;
|
||||
const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
|
||||
yield* runtime.start();
|
||||
|
||||
const initializeStarted = requestEvents.find(
|
||||
@@ -64,7 +64,7 @@ describe("AcpSessionRuntime", () => {
|
||||
|
||||
it.effect("starts a session, prompts, and emits normalized events against the mock agent", () =>
|
||||
Effect.gen(function* () {
|
||||
const runtime = yield* AcpSessionRuntime;
|
||||
const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
|
||||
const started = yield* runtime.start();
|
||||
|
||||
expect(started.initializeResult).toMatchObject({ protocolVersion: 1 });
|
||||
@@ -115,7 +115,7 @@ describe("AcpSessionRuntime", () => {
|
||||
|
||||
it.effect("segments assistant text around ACP tool calls", () =>
|
||||
Effect.gen(function* () {
|
||||
const runtime = yield* AcpSessionRuntime;
|
||||
const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
|
||||
yield* runtime.start();
|
||||
|
||||
const promptResult = yield* runtime.prompt({
|
||||
@@ -176,7 +176,7 @@ describe("AcpSessionRuntime", () => {
|
||||
|
||||
it.effect("suppresses generic placeholder tool updates until completion", () =>
|
||||
Effect.gen(function* () {
|
||||
const runtime = yield* AcpSessionRuntime;
|
||||
const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
|
||||
yield* runtime.start();
|
||||
|
||||
const promptResult = yield* runtime.prompt({
|
||||
@@ -213,9 +213,9 @@ describe("AcpSessionRuntime", () => {
|
||||
);
|
||||
|
||||
it.effect("logs ACP requests from the shared runtime", () => {
|
||||
const requestEvents: Array<AcpSessionRequestLogEvent> = [];
|
||||
const requestEvents: Array<AcpSessionRuntime.AcpSessionRequestLogEvent> = [];
|
||||
return Effect.gen(function* () {
|
||||
const runtime = yield* AcpSessionRuntime;
|
||||
const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
|
||||
yield* runtime.start();
|
||||
|
||||
yield* runtime.setModel("composer-2");
|
||||
@@ -265,9 +265,9 @@ describe("AcpSessionRuntime", () => {
|
||||
});
|
||||
|
||||
it.effect("skips no-op session config writes when the requested value is already active", () => {
|
||||
const requestEvents: Array<AcpSessionRequestLogEvent> = [];
|
||||
const requestEvents: Array<AcpSessionRuntime.AcpSessionRequestLogEvent> = [];
|
||||
return Effect.gen(function* () {
|
||||
const runtime = yield* AcpSessionRuntime;
|
||||
const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
|
||||
yield* runtime.start();
|
||||
|
||||
yield* runtime.setConfigOption("model", "default");
|
||||
@@ -302,7 +302,7 @@ describe("AcpSessionRuntime", () => {
|
||||
it.effect("emits low-level ACP protocol logs for raw and decoded messages", () => {
|
||||
const protocolEvents: Array<EffectAcpProtocol.AcpProtocolLogEvent> = [];
|
||||
return Effect.gen(function* () {
|
||||
const runtime = yield* AcpSessionRuntime;
|
||||
const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
|
||||
yield* runtime.start();
|
||||
|
||||
yield* runtime.prompt({
|
||||
@@ -350,7 +350,7 @@ describe("AcpSessionRuntime", () => {
|
||||
const tempDir = mkdtempSync(path.join(os.tmpdir(), "acp-runtime-"));
|
||||
const requestLogPath = path.join(tempDir, "requests.ndjson");
|
||||
return Effect.gen(function* () {
|
||||
const runtime = yield* AcpSessionRuntime;
|
||||
const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
|
||||
yield* runtime.start();
|
||||
|
||||
const error = yield* runtime.setModel("composer-2[fast=false]").pipe(Effect.flip);
|
||||
|
||||
@@ -6,9 +6,9 @@ import * as Effect from "effect/Effect";
|
||||
import type * as EffectAcpProtocol from "effect-acp/protocol";
|
||||
|
||||
import type { EventNdjsonLogger } from "../Layers/EventNdjsonLogger.ts";
|
||||
import type { AcpSessionRequestLogEvent, AcpSessionRuntimeOptions } from "./AcpSessionRuntime.ts";
|
||||
import type * as AcpSessionRuntime from "./AcpSessionRuntime.ts";
|
||||
|
||||
function formatRequestLogPayload(event: AcpSessionRequestLogEvent) {
|
||||
function formatRequestLogPayload(event: AcpSessionRuntime.AcpSessionRequestLogEvent) {
|
||||
return {
|
||||
method: event.method,
|
||||
status: event.status,
|
||||
@@ -24,7 +24,7 @@ export const makeAcpNativeLoggerFactory = Effect.fn("makeAcpNativeLoggerFactory"
|
||||
readonly nativeEventLogger: EventNdjsonLogger | undefined;
|
||||
readonly provider: ProviderDriverKind;
|
||||
readonly threadId: ThreadId;
|
||||
}): Pick<AcpSessionRuntimeOptions, "requestLogger" | "protocolLogging"> => {
|
||||
}): Pick<AcpSessionRuntime.AcpSessionRuntimeOptions, "requestLogger" | "protocolLogging"> => {
|
||||
const writeNativeAcpLog = (logInput: {
|
||||
readonly kind: "request" | "protocol";
|
||||
readonly payload: unknown;
|
||||
@@ -57,7 +57,7 @@ export const makeAcpNativeLoggerFactory = Effect.fn("makeAcpNativeLoggerFactory"
|
||||
);
|
||||
|
||||
return {
|
||||
requestLogger: (event: AcpSessionRequestLogEvent) =>
|
||||
requestLogger: (event: AcpSessionRuntime.AcpSessionRequestLogEvent) =>
|
||||
writeNativeAcpLog({
|
||||
kind: "request",
|
||||
payload: formatRequestLogPayload(event),
|
||||
@@ -72,7 +72,7 @@ export const makeAcpNativeLoggerFactory = Effect.fn("makeAcpNativeLoggerFactory"
|
||||
kind: "protocol",
|
||||
payload: event,
|
||||
}),
|
||||
} satisfies NonNullable<AcpSessionRuntimeOptions["protocolLogging"]>,
|
||||
} satisfies NonNullable<AcpSessionRuntime.AcpSessionRuntimeOptions["protocolLogging"]>,
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
@@ -6,9 +7,9 @@ import * as Layer from "effect/Layer";
|
||||
import * as Queue from "effect/Queue";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
import * as ChildProcess from "effect/unstable/process/ChildProcess";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
import * as EffectAcpClient from "effect-acp/client";
|
||||
import * as EffectAcpErrors from "effect-acp/errors";
|
||||
import type * as EffectAcpSchema from "effect-acp/schema";
|
||||
@@ -75,50 +76,153 @@ export interface AcpSessionRuntimeStartResult {
|
||||
readonly modelConfigId: string | undefined;
|
||||
}
|
||||
|
||||
export interface AcpSessionRuntimeShape {
|
||||
readonly handleRequestPermission: EffectAcpClient.AcpClientShape["handleRequestPermission"];
|
||||
readonly handleElicitation: EffectAcpClient.AcpClientShape["handleElicitation"];
|
||||
readonly handleReadTextFile: EffectAcpClient.AcpClientShape["handleReadTextFile"];
|
||||
readonly handleWriteTextFile: EffectAcpClient.AcpClientShape["handleWriteTextFile"];
|
||||
readonly handleCreateTerminal: EffectAcpClient.AcpClientShape["handleCreateTerminal"];
|
||||
readonly handleTerminalOutput: EffectAcpClient.AcpClientShape["handleTerminalOutput"];
|
||||
readonly handleTerminalWaitForExit: EffectAcpClient.AcpClientShape["handleTerminalWaitForExit"];
|
||||
readonly handleTerminalKill: EffectAcpClient.AcpClientShape["handleTerminalKill"];
|
||||
readonly handleTerminalRelease: EffectAcpClient.AcpClientShape["handleTerminalRelease"];
|
||||
readonly handleSessionUpdate: EffectAcpClient.AcpClientShape["handleSessionUpdate"];
|
||||
readonly handleElicitationComplete: EffectAcpClient.AcpClientShape["handleElicitationComplete"];
|
||||
readonly handleUnknownExtRequest: EffectAcpClient.AcpClientShape["handleUnknownExtRequest"];
|
||||
readonly handleUnknownExtNotification: EffectAcpClient.AcpClientShape["handleUnknownExtNotification"];
|
||||
readonly handleExtRequest: EffectAcpClient.AcpClientShape["handleExtRequest"];
|
||||
readonly handleExtNotification: EffectAcpClient.AcpClientShape["handleExtNotification"];
|
||||
readonly start: () => Effect.Effect<AcpSessionRuntimeStartResult, EffectAcpErrors.AcpError>;
|
||||
readonly getEvents: () => Stream.Stream<AcpParsedSessionEvent, never>;
|
||||
readonly getModeState: Effect.Effect<AcpSessionModeState | undefined>;
|
||||
readonly getConfigOptions: Effect.Effect<ReadonlyArray<EffectAcpSchema.SessionConfigOption>>;
|
||||
readonly prompt: (
|
||||
payload: Omit<EffectAcpSchema.PromptRequest, "sessionId">,
|
||||
) => Effect.Effect<EffectAcpSchema.PromptResponse, EffectAcpErrors.AcpError>;
|
||||
readonly cancel: Effect.Effect<void, EffectAcpErrors.AcpError>;
|
||||
readonly setMode: (
|
||||
modeId: string,
|
||||
) => Effect.Effect<EffectAcpSchema.SetSessionModeResponse, EffectAcpErrors.AcpError>;
|
||||
readonly setConfigOption: (
|
||||
configId: string,
|
||||
value: string | boolean,
|
||||
) => Effect.Effect<EffectAcpSchema.SetSessionConfigOptionResponse, EffectAcpErrors.AcpError>;
|
||||
readonly setModel: (model: string) => Effect.Effect<void, EffectAcpErrors.AcpError>;
|
||||
readonly setSessionModel: (
|
||||
modelId: string,
|
||||
) => Effect.Effect<EffectAcpSchema.SetSessionModelResponse, EffectAcpErrors.AcpError>;
|
||||
readonly request: (
|
||||
method: string,
|
||||
payload: unknown,
|
||||
) => Effect.Effect<unknown, EffectAcpErrors.AcpError>;
|
||||
readonly notify: (
|
||||
method: string,
|
||||
payload: unknown,
|
||||
) => Effect.Effect<void, EffectAcpErrors.AcpError>;
|
||||
}
|
||||
export class AcpSessionRuntime extends Context.Service<
|
||||
AcpSessionRuntime,
|
||||
{
|
||||
/**
|
||||
* Registers a handler for `session/request_permission`.
|
||||
* @see https://agentclientprotocol.com/protocol/schema#session/request_permission
|
||||
*/
|
||||
readonly handleRequestPermission: EffectAcpClient.AcpClient["Service"]["handleRequestPermission"];
|
||||
/**
|
||||
* Registers a handler for `session/elicitation`.
|
||||
* @see https://agentclientprotocol.com/protocol/schema#session/elicitation
|
||||
*/
|
||||
readonly handleElicitation: EffectAcpClient.AcpClient["Service"]["handleElicitation"];
|
||||
/**
|
||||
* Registers a handler for `fs/read_text_file`.
|
||||
* @see https://agentclientprotocol.com/protocol/schema#fs/read_text_file
|
||||
*/
|
||||
readonly handleReadTextFile: EffectAcpClient.AcpClient["Service"]["handleReadTextFile"];
|
||||
/**
|
||||
* Registers a handler for `fs/write_text_file`.
|
||||
* @see https://agentclientprotocol.com/protocol/schema#fs/write_text_file
|
||||
*/
|
||||
readonly handleWriteTextFile: EffectAcpClient.AcpClient["Service"]["handleWriteTextFile"];
|
||||
/**
|
||||
* Registers a handler for `terminal/create`.
|
||||
* @see https://agentclientprotocol.com/protocol/schema#terminal/create
|
||||
*/
|
||||
readonly handleCreateTerminal: EffectAcpClient.AcpClient["Service"]["handleCreateTerminal"];
|
||||
/**
|
||||
* Registers a handler for `terminal/output`.
|
||||
* @see https://agentclientprotocol.com/protocol/schema#terminal/output
|
||||
*/
|
||||
readonly handleTerminalOutput: EffectAcpClient.AcpClient["Service"]["handleTerminalOutput"];
|
||||
/**
|
||||
* Registers a handler for `terminal/wait_for_exit`.
|
||||
* @see https://agentclientprotocol.com/protocol/schema#terminal/wait_for_exit
|
||||
*/
|
||||
readonly handleTerminalWaitForExit: EffectAcpClient.AcpClient["Service"]["handleTerminalWaitForExit"];
|
||||
/**
|
||||
* Registers a handler for `terminal/kill`.
|
||||
* @see https://agentclientprotocol.com/protocol/schema#terminal/kill
|
||||
*/
|
||||
readonly handleTerminalKill: EffectAcpClient.AcpClient["Service"]["handleTerminalKill"];
|
||||
/**
|
||||
* Registers a handler for `terminal/release`.
|
||||
* @see https://agentclientprotocol.com/protocol/schema#terminal/release
|
||||
*/
|
||||
readonly handleTerminalRelease: EffectAcpClient.AcpClient["Service"]["handleTerminalRelease"];
|
||||
/**
|
||||
* Registers a handler for `session/update`.
|
||||
* @see https://agentclientprotocol.com/protocol/schema#session/update
|
||||
*/
|
||||
readonly handleSessionUpdate: EffectAcpClient.AcpClient["Service"]["handleSessionUpdate"];
|
||||
/**
|
||||
* Registers a handler for `session/elicitation/complete`.
|
||||
* @see https://agentclientprotocol.com/protocol/schema#session/elicitation/complete
|
||||
*/
|
||||
readonly handleElicitationComplete: EffectAcpClient.AcpClient["Service"]["handleElicitationComplete"];
|
||||
/**
|
||||
* Registers a fallback extension request handler.
|
||||
* @see https://agentclientprotocol.com/protocol/extensibility
|
||||
*/
|
||||
readonly handleUnknownExtRequest: EffectAcpClient.AcpClient["Service"]["handleUnknownExtRequest"];
|
||||
/**
|
||||
* Registers a fallback extension notification handler.
|
||||
* @see https://agentclientprotocol.com/protocol/extensibility
|
||||
*/
|
||||
readonly handleUnknownExtNotification: EffectAcpClient.AcpClient["Service"]["handleUnknownExtNotification"];
|
||||
/**
|
||||
* Registers a typed extension request handler.
|
||||
* @see https://agentclientprotocol.com/protocol/extensibility
|
||||
*/
|
||||
readonly handleExtRequest: EffectAcpClient.AcpClient["Service"]["handleExtRequest"];
|
||||
/**
|
||||
* Registers a typed extension notification handler.
|
||||
* @see https://agentclientprotocol.com/protocol/extensibility
|
||||
*/
|
||||
readonly handleExtNotification: EffectAcpClient.AcpClient["Service"]["handleExtNotification"];
|
||||
/**
|
||||
* Initializes the ACP connection, authenticates, and loads, resumes, or creates the session.
|
||||
* Concurrent calls share the same in-flight startup and a failed startup may be retried.
|
||||
*/
|
||||
readonly start: () => Effect.Effect<AcpSessionRuntimeStartResult, EffectAcpErrors.AcpError>;
|
||||
/** Stream of parsed ACP session events emitted after startup. */
|
||||
readonly getEvents: () => Stream.Stream<AcpParsedSessionEvent, never>;
|
||||
/** Latest mode state observed from session setup and `session/update` notifications. */
|
||||
readonly getModeState: Effect.Effect<AcpSessionModeState | undefined>;
|
||||
/** Latest configuration options observed from session setup and configuration writes. */
|
||||
readonly getConfigOptions: Effect.Effect<ReadonlyArray<EffectAcpSchema.SessionConfigOption>>;
|
||||
/**
|
||||
* Sends a prompt turn to the active session.
|
||||
* @see https://agentclientprotocol.com/protocol/schema#session/prompt
|
||||
*/
|
||||
readonly prompt: (
|
||||
payload: Omit<EffectAcpSchema.PromptRequest, "sessionId">,
|
||||
) => Effect.Effect<EffectAcpSchema.PromptResponse, EffectAcpErrors.AcpError>;
|
||||
/**
|
||||
* Sends a real ACP `session/cancel` notification for the active session.
|
||||
* @see https://agentclientprotocol.com/protocol/schema#session/cancel
|
||||
*/
|
||||
readonly cancel: Effect.Effect<void, EffectAcpErrors.AcpError>;
|
||||
/**
|
||||
* Selects the active mode through the negotiated `mode` configuration option.
|
||||
* This is a no-op when the requested mode is already active.
|
||||
* @see https://agentclientprotocol.com/protocol/schema#session/set_config_option
|
||||
*/
|
||||
readonly setMode: (
|
||||
modeId: string,
|
||||
) => Effect.Effect<EffectAcpSchema.SetSessionModeResponse, EffectAcpErrors.AcpError>;
|
||||
/**
|
||||
* Updates a session configuration option and the runtime configuration snapshot.
|
||||
* @see https://agentclientprotocol.com/protocol/schema#session/set_config_option
|
||||
*/
|
||||
readonly setConfigOption: (
|
||||
configId: string,
|
||||
value: string | boolean,
|
||||
) => Effect.Effect<EffectAcpSchema.SetSessionConfigOptionResponse, EffectAcpErrors.AcpError>;
|
||||
/**
|
||||
* Selects the base model through the negotiated model configuration option.
|
||||
* @see https://agentclientprotocol.com/protocol/schema#session/set_config_option
|
||||
*/
|
||||
readonly setModel: (model: string) => Effect.Effect<void, EffectAcpErrors.AcpError>;
|
||||
/**
|
||||
* Selects the active model through the unstable ACP `session/set_model` capability.
|
||||
* @see https://agentclientprotocol.com/protocol/schema#session/set_model
|
||||
*/
|
||||
readonly setSessionModel: (
|
||||
modelId: string,
|
||||
) => Effect.Effect<EffectAcpSchema.SetSessionModelResponse, EffectAcpErrors.AcpError>;
|
||||
/**
|
||||
* Sends a generic ACP extension request and records it through the request logger.
|
||||
* @see https://agentclientprotocol.com/protocol/extensibility
|
||||
*/
|
||||
readonly request: (
|
||||
method: string,
|
||||
payload: unknown,
|
||||
) => Effect.Effect<unknown, EffectAcpErrors.AcpError>;
|
||||
/**
|
||||
* Sends a generic ACP extension notification.
|
||||
* @see https://agentclientprotocol.com/protocol/extensibility
|
||||
*/
|
||||
readonly notify: (
|
||||
method: string,
|
||||
payload: unknown,
|
||||
) => Effect.Effect<void, EffectAcpErrors.AcpError>;
|
||||
}
|
||||
>()("t3/provider/acp/AcpSessionRuntime") {}
|
||||
|
||||
interface AcpStartedState extends AcpSessionRuntimeStartResult {}
|
||||
|
||||
@@ -140,24 +244,10 @@ interface EnsureActiveAssistantSegmentResult {
|
||||
readonly startedEvent?: Extract<AcpParsedSessionEvent, { readonly _tag: "AssistantItemStarted" }>;
|
||||
}
|
||||
|
||||
export class AcpSessionRuntime extends Context.Service<AcpSessionRuntime, AcpSessionRuntimeShape>()(
|
||||
"t3/provider/acp/AcpSessionRuntime",
|
||||
) {
|
||||
static layer(
|
||||
options: AcpSessionRuntimeOptions,
|
||||
): Layer.Layer<
|
||||
AcpSessionRuntime,
|
||||
EffectAcpErrors.AcpError,
|
||||
ChildProcessSpawner.ChildProcessSpawner
|
||||
> {
|
||||
return Layer.effect(AcpSessionRuntime, makeAcpSessionRuntime(options));
|
||||
}
|
||||
}
|
||||
|
||||
const makeAcpSessionRuntime = (
|
||||
export const make = (
|
||||
options: AcpSessionRuntimeOptions,
|
||||
): Effect.Effect<
|
||||
AcpSessionRuntimeShape,
|
||||
AcpSessionRuntime["Service"],
|
||||
EffectAcpErrors.AcpError,
|
||||
ChildProcessSpawner.ChildProcessSpawner | Scope.Scope
|
||||
> =>
|
||||
@@ -573,9 +663,17 @@ const makeAcpSessionRuntime = (
|
||||
request: (method, payload) =>
|
||||
runLoggedRequest(method, payload, acp.raw.request(method, payload)),
|
||||
notify: acp.raw.notify,
|
||||
} satisfies AcpSessionRuntimeShape;
|
||||
} satisfies AcpSessionRuntime["Service"];
|
||||
});
|
||||
|
||||
export const layer = (
|
||||
options: AcpSessionRuntimeOptions,
|
||||
): Layer.Layer<
|
||||
AcpSessionRuntime,
|
||||
EffectAcpErrors.AcpError,
|
||||
ChildProcessSpawner.ChildProcessSpawner
|
||||
> => Layer.effect(AcpSessionRuntime, make(options));
|
||||
|
||||
function sessionConfigOptionsFromSetup(
|
||||
response:
|
||||
| {
|
||||
|
||||
Loaded 100 of 236 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user