Compare commits

...
Author SHA1 Message Date
Cursor AgentandJulius Marminge 7e514b697c Merge telemetry test clock layer
Co-authored-by: Julius Marminge <[email protected]>
2026-06-24 16:09:50 +00:00
Cursor AgentandJulius Marminge bed379a80b Assert platform realPath failure details
Co-authored-by: Julius Marminge <[email protected]>
2026-06-24 16:08:12 +00:00
Cursor AgentandJulius Marminge 2ba8472afb Use idiomatic Effect filesystem and duration APIs
Co-authored-by: Julius Marminge <[email protected]>
2026-06-24 16:06:42 +00:00
Wout StiensandCodex a4964b3b36 [codex] fix: show standalone element-pick context (#3527)
Co-authored-by: Codex <[email protected]>
2026-06-23 13:04:20 -07:00
c6c64918f8 Reduce ChatMarkdown settings rerenders (#3536)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-06-23 11:47:26 -07:00
Wout StiensandCodex 4abf8b46c5 [codex] fix: ignore stale shell reducer events (#3517)
Co-authored-by: Codex <[email protected]>
2026-06-22 22:33:23 -07:00
Wout StiensandCodex 3083d712ee [codex] fix: clarify Cursor CLI setup error (#3519)
Co-authored-by: Codex <[email protected]>
2026-06-22 22:33:01 -07:00
Julius Marminge 6672a1d210 Bump Clerk packages and refresh lockfile (#3511) 2026-06-22 16:59:56 -07:00
92e54fb96c [codex] fix: guard DPoP fallback URL construction (#3503)
Co-authored-by: Codex <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-06-22 16:21:06 -07:00
Julius MarmingeandJulius Marminge 8cc9a6fa6b [codex] Restore T3 Connect account controls (#3492)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-22 15:58:54 -07:00
b2d17b7108 Add main sidebar toggle (#3497)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-06-22 14:00:30 -07:00
Abdul AzeezandJulius Marminge fb1034546f feat: add persistent word-wrap setting for chat code blocks and tables (#3480)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-22 13:14:24 -07:00
f5f98cf0ae Stabilize composer provider state while typing (#3507)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-06-22 12:52:13 -07:00
Julius Marmingeandcodex 37ac970e28 Persist mobile composer selectors across drafts (#3496)
Co-authored-by: codex <[email protected]>
2026-06-22 12:37:31 -07:00
Wout StiensandCodex 8919ae7c53 [codex] Reject unsupported remote pairing protocols (#3498)
Co-authored-by: Codex <[email protected]>
2026-06-22 10:15:43 -07:00
Wout StiensandCodex c1e2408e1f [codex] fix: preserve localhost preview hosts (#3499)
Co-authored-by: Codex <[email protected]>
2026-06-22 10:14:16 -07:00
Wout StiensandCodex 8b993bc9ff [codex] fix: restore pending input keyboard activation (#3501)
Co-authored-by: Codex <[email protected]>
2026-06-22 10:10:47 -07:00
Wout StiensandCodex ea52bb1dbd [codex] fix: guard trace ID clipboard copy (#3505)
Co-authored-by: Codex <[email protected]>
2026-06-22 09:46:15 -07:00
Illia Panasenko 28107e89c2 chore: remove AnnotatableFileDiff leftovers, rename file (#3488) 2026-06-21 20:31:26 -07:00
Julius Marminge 82a9bcc7f4 [codex] add session context to credential errors (#3349) 2026-06-20 20:45:17 -07:00
Julius Marminge 61f8d46fa2 [codex] Enforce Effect error handling conventions (#3380) 2026-06-20 20:43:41 -07:00
Julius Marminge 0debebafbb [codex] Structure thread archive blocked error (#3451) 2026-06-20 20:41:58 -07:00
Julius Marmingeandcodex 2a29de7502 [codex] Structure primary auth validation failures (#3471)
Co-authored-by: codex <[email protected]>
2026-06-20 20:20:12 -07:00
Julius Marmingeandcodex 8c1605b383 [codex] Structure OpenCode text generation failures (#3472)
Co-authored-by: codex <[email protected]>
2026-06-20 20:20:09 -07:00
Julius Marmingeandcodex 90074e359f [codex] Preserve desktop update state causes (#3473)
Co-authored-by: codex <[email protected]>
2026-06-20 20:20:07 -07:00
Julius Marmingeandcodex 6155f5cf64 [codex] Preserve VCS project config error causes (#3474)
Co-authored-by: codex <[email protected]>
2026-06-20 20:20:04 -07:00
Julius Marmingeandcodex e3970e755b [codex] Preserve APNs delivery failure context (#3475)
Co-authored-by: codex <[email protected]>
2026-06-20 20:20:01 -07:00
Julius Marmingeandcodex 3c246f56b4 [codex] Structure VCS process boundary errors (#3476)
Co-authored-by: codex <[email protected]>
2026-06-20 20:19:59 -07:00
Julius Marmingeandcodex cebbe6ff19 [codex] Preserve child process termination context (#3469)
Co-authored-by: codex <[email protected]>
2026-06-20 19:20:04 -07:00
Julius Marmingeandcodex e4a84a348e [codex] Structure release output failures (#3470)
Co-authored-by: codex <[email protected]>
2026-06-20 19:20:01 -07:00
Julius Marmingeandcodex 61e6d89d69 [codex] Structure GitHub CLI failures (#3456)
Co-authored-by: codex <[email protected]>
2026-06-20 19:14:35 -07:00
Julius Marmingeandcodex 1b2f39d018 [codex] Structure theme synchronization failures (#3466)
Co-authored-by: codex <[email protected]>
2026-06-20 19:09:05 -07:00
Julius Marmingeandcodex 8c2d33abde [codex] Structure release package updater failures (#3468)
Co-authored-by: codex <[email protected]>
2026-06-20 19:09:02 -07:00
Julius Marmingeandcodex 60dc4af916 [codex] Structure desktop build script failures (#3452)
Co-authored-by: codex <[email protected]>
2026-06-20 18:58:22 -07:00
Julius Marmingeandcodex d389cfd4e3 [codex] Structure Azure DevOps CLI failures (#3460)
Co-authored-by: codex <[email protected]>
2026-06-20 18:58:19 -07:00
Julius Marmingeandcodex 6fc79737c3 [codex] Structure mobile native static-check failures (#3464)
Co-authored-by: codex <[email protected]>
2026-06-20 18:58:16 -07:00
Julius Marmingeandcodex cdd03591ef [codex] Structure release metadata failures (#3467)
Co-authored-by: codex <[email protected]>
2026-06-20 18:58:13 -07:00
Julius Marmingeandcodex 2fbb0565d7 [codex] Structure workspace search cleanup failures (#3465)
Co-authored-by: codex <[email protected]>
2026-06-20 18:58:08 -07:00
Julius Marmingeandcodex a3dadc04bf [codex] Structure Bitbucket API errors (#3457)
Co-authored-by: codex <[email protected]>
2026-06-20 18:47:12 -07:00
Julius Marmingeandcodex 1a59277dc8 [codex] Structure GitLab CLI failures (#3458)
Co-authored-by: codex <[email protected]>
2026-06-20 18:41:25 -07:00
Julius Marmingeandcodex 6424197a19 [codex] Structure unroutable app-server messages (#3463)
Co-authored-by: codex <[email protected]>
2026-06-20 18:30:19 -07:00
Julius Marmingeandcodex 8d4a8b4f31 [codex] Structure preview capability errors (#3454)
Co-authored-by: codex <[email protected]>
2026-06-20 18:19:12 -07:00
Julius Marmingeandcodex 23ab75e84a [codex] Split project command failures (#3459)
Co-authored-by: codex <[email protected]>
2026-06-20 18:19:07 -07:00
Julius Marmingeandcodex 0488e47d9c [codex] Structure checkpoint diff failures (#3453)
Co-authored-by: codex <[email protected]>
2026-06-20 18:07:22 -07:00
Julius Marmingeandcodex 0eba548282 [codex] Model asset access failures with distinct errors (#3448)
Co-authored-by: codex <[email protected]>
2026-06-20 17:35:07 -07:00
Julius Marmingeandcodex 68c0dd3b70 [codex] Structure server CLI failures (#3450)
Co-authored-by: codex <[email protected]>
2026-06-20 17:35:02 -07:00
Julius Marmingeandcodex 4cd958445f [codex] Migrate desktop app errors to Schema (#3449)
Co-authored-by: codex <[email protected]>
2026-06-20 17:25:27 -07:00
Julius Marmingeandcodex 9f7861aadd [codex] Structure desktop update persistence errors (#3261)
Co-authored-by: codex <[email protected]>
2026-06-20 17:09:17 -07:00
Julius Marmingeandcodex 9243ead1c3 [codex] Preserve Linux icon resize fallback failures (#3447)
Co-authored-by: codex <[email protected]>
2026-06-20 17:09:11 -07:00
Julius Marmingeandcodex 803c2b7738 [codex] Preserve desktop backend output read failures (#3444)
Co-authored-by: codex <[email protected]>
2026-06-20 16:58:21 -07:00
Julius Marmingeandcodex 28e7c9ae17 [codex] Structure mobile waitlist enrollment failures (#3446)
Co-authored-by: codex <[email protected]>
2026-06-20 16:58:15 -07:00
Julius Marmingeandcodex a9460bb772 [codex] Structure pull request link failures (#3445)
Co-authored-by: codex <[email protected]>
2026-06-20 16:44:22 -07:00
Julius Marmingeandcodex 5edf7c56ba [codex] Preserve PR materialization failure chains (#3443)
Co-authored-by: codex <[email protected]>
2026-06-20 16:38:56 -07:00
Julius Marmingeandcodex 90dc76b11e Preserve asset access failure causes (#3342)
Co-authored-by: codex <[email protected]>
2026-06-20 16:15:22 -07:00
Julius Marmingeandcodex 57d25c934b [codex] Structure persistence error correlation (#3439)
Co-authored-by: codex <[email protected]>
2026-06-20 16:15:16 -07:00
Julius Marmingeandcodex a26f0dc89f [codex] structure source-control repository failures (#3336)
Co-authored-by: codex <[email protected]>
2026-06-20 15:56:46 -07:00
Julius Marmingeandcodex 6ff6c13fc8 [codex] structure desktop backend process errors (#3254)
Co-authored-by: codex <[email protected]>
2026-06-20 15:55:50 -07:00
Julius Marmingeandcodex 60c9ca0e33 [codex] Preserve checkpoint repository detection failures (#3360)
Co-authored-by: codex <[email protected]>
2026-06-20 15:55:44 -07:00
Julius Marmingeandcodex ad2cb1dd57 [codex] Diagnose desktop client settings read failures (#3432)
Co-authored-by: codex <[email protected]>
2026-06-20 15:55:38 -07:00
Julius Marmingeandcodex 674590e009 [codex] Fix terminal cwd error test construction (#3440)
Co-authored-by: codex <[email protected]>
2026-06-20 15:47:58 -07:00
Julius Marmingeandcodex f2cb14e774 [codex] Structure mobile relay token-store failures (#3309)
Co-authored-by: codex <[email protected]>
2026-06-20 15:31:33 -07:00
Julius Marmingeandcodex e042c25f56 [codex] Structure rotating log sink errors (#3279)
Co-authored-by: codex <[email protected]>
2026-06-20 15:24:38 -07:00
Julius Marmingeandcodex 90f1936fad [codex] Structure server runtime-state failures (#3319)
Co-authored-by: codex <[email protected]>
2026-06-20 15:15:05 -07:00
Julius Marmingeandcodex 42ff43915a [codex] Preserve mobile review highlighter failures (#3337)
Co-authored-by: codex <[email protected]>
2026-06-20 15:15:00 -07:00
Julius Marmingeandcodex 834e5db458 [codex] structure project CLI failures (#3339)
Co-authored-by: codex <[email protected]>
2026-06-20 15:14:55 -07:00
Julius Marmingeandcodex 8ce627ba91 [codex] Structure mobile thread outbox failures (#3341)
Co-authored-by: codex <[email protected]>
2026-06-20 15:14:51 -07:00
Julius Marmingeandcodex 9a78c6f2ba [codex] Structure web local storage failures (#3350)
Co-authored-by: codex <[email protected]>
2026-06-20 15:14:46 -07:00
Julius Marmingeandcodex aab72f10c1 [codex] Report markdown interaction failures (#3355)
Co-authored-by: codex <[email protected]>
2026-06-20 15:14:41 -07:00
Julius Marmingeandcodex a76b7bbfb5 Preserve PortScanner probe defects (#3282)
Co-authored-by: codex <[email protected]>
2026-06-20 15:14:02 -07:00
Julius Marmingeandcodex a51691a9b0 [codex] Structure server environment-label probe failures (#3321)
Co-authored-by: codex <[email protected]>
2026-06-20 15:13:53 -07:00
Julius Marmingeandcodex 97de7d7e15 [codex] Structure agent awareness registration errors (#3328)
Co-authored-by: codex <[email protected]>
2026-06-20 15:13:48 -07:00
Julius Marmingeandcodex d7718e81e0 [codex] Structure mobile notification navigation failures (#3359)
Co-authored-by: codex <[email protected]>
2026-06-20 15:13:04 -07:00
Julius Marmingeandcodex b88873508e [codex] Structure cross-client clipboard failures (#3361)
Co-authored-by: codex <[email protected]>
2026-06-20 15:12:59 -07:00
Julius Marmingeandcodex 58053d146b [codex] Structure terminal PTY operation failures (#3364)
Co-authored-by: codex <[email protected]>
2026-06-20 15:12:54 -07:00
Julius Marmingeandcodex 50767683b3 [codex] Preserve terminal preview link failure context (#3367)
Co-authored-by: codex <[email protected]>
2026-06-20 15:12:50 -07:00
Julius Marmingeandcodex d1339f3846 [codex] Structure client state key errors (#3374)
Co-authored-by: codex <[email protected]>
2026-06-20 15:12:45 -07:00
Julius Marmingeandcodex faccdd4ca9 [codex] Preserve desktop backend log failures (#3375)
Co-authored-by: codex <[email protected]>
2026-06-20 15:12:40 -07:00
Julius Marmingeandcodex dd48bfd98c [codex] Structure server settings failures (#3376)
Co-authored-by: codex <[email protected]>
2026-06-20 15:12:36 -07:00
Julius Marmingeandcodex 6d8d995621 [codex] Correlate protocol request failures (#3433)
Co-authored-by: codex <[email protected]>
2026-06-20 15:12:31 -07:00
Julius Marmingeandcodex b6c590af38 [codex] Fix desktop preview event delivery errors (#3435)
Co-authored-by: codex <[email protected]>
2026-06-20 15:12:27 -07:00
Julius Marmingeandcodex b51aef10c4 [codex] Preserve cloud disconnect diagnostics (#3437)
Co-authored-by: codex <[email protected]>
2026-06-20 15:12:22 -07:00
Julius Marmingeandcodex fc2cdeceb9 [codex] Structure preview automation boundary failures (#3436)
Co-authored-by: codex <[email protected]>
2026-06-20 13:50:19 -07:00
Julius Marmingeandcodex c637dfc454 [codex] enrich Git workflow errors (#3241)
Co-authored-by: codex <[email protected]>
2026-06-20 13:16:32 -07:00
Julius Marmingeandcodex 6e9b43cb84 Preserve trace file read causes (#3300)
Co-authored-by: codex <[email protected]>
2026-06-20 13:11:52 -07:00
241 changed files with 13967 additions and 3371 deletions

No files matched your search

@@ -48,7 +48,9 @@ Review changed TypeScript and directly affected call sites for the conventions b
- Define service failures with `Schema.TaggedErrorClass` and structured attributes. Derive `message` from those attributes rather than storing an unstructured message as the only data.
- `Schema.Defect()` is not a substitute for modeling a generic error: its tag, fields, or both must identify the failure structurally, and its `message` must not merely stringify an opaque cause. A semantically precise error tag may preserve a real `cause` without inventing a redundant singleton field when no additional variable context exists; still retain any real path, resource, request, or entity context available at the wrapping site.
- Capture stable, serializable domain context such as the operation or stage, resource/path or entity identifier, and normalized category/status. Map failures where that context is known instead of wrapping an entire multi-step pipeline in one generic error. Do not add a `detail` field that merely copies `cause.message` and then use it to construct the wrapper message.
- Keep direct error attributes and log annotations safe and bounded. Do not copy raw wire payloads, command arguments or output, signed URLs, credentials, query strings, fragments, selectors, or arbitrary defect text into `detail`, `reason`, `message`, or a parallel log payload. Preserve the exact underlying value only as `cause`; expose normalized categories plus lengths/counts and safe URL protocol/hostname diagnostics where useful. Logging a sanitized error must not reintroduce a removed legacy `detail` or serialized `cause` field beside it.
- When translating or wrapping a real failure, preserve the immediate underlying error itself as `cause` alongside the structural fields so the complete error chain and stack remain available. If every construction wraps a failure, `cause` should be required; make it optional only when the same error can legitimately originate without an underlying failure.
- At a translation boundary, pass through an already structured domain error when it is part of the declared target error channel. Wrap only unknown or genuinely lower-level failures. A static factory or mapper may perform this classification when it is reused and keeps the policy next to the target error type.
- Derive the wrapper's `message` exclusively from its stable structural attributes, never from `cause`, `cause.message`, or a stringified defect. Do not replace the immediate error with only `error.cause`, erase a structured upstream error into a string, or manufacture an `Error` merely to populate `cause`. Pure validation/domain errors created without an underlying failure do not need a cause.
- Do not encode the same distinction twice with both a specific error tag and a single-value `operation`, `reason`, `kind`, or `phase` literal. Choose one coherent model: use distinct error classes and omit the redundant discriminator when callers or messages treat the failures as genuinely different, or use one service-level error with a multi-value operation discriminator and a generic message derived from that operation when the failures share the same semantics.
- Treat an error message exposed through an HTTP/RPC response, persisted state, UI, or another caller-visible boundary as behavior. Preserve those messages during a structural refactor. Existing distinct caller-visible messages are evidence that the failures should normally remain distinct error tags without redundant singleton discriminators, rather than being collapsed into a generic operation error.
@@ -56,6 +58,9 @@ Review changed TypeScript and directly affected call sites for the conventions b
- Use `Schema.Union` of error classes when a shared schema, predicate, or helper type is useful.
- Export direct schema predicates such as `export const isFoo = Schema.is(Foo)`. Flag a private `Schema.is` constant wrapped by a redundant function with the same signature.
- Do not introduce a large `switch` or lookup table in an error's `message` getter to model failures that deserve separate error classes.
- Catch statically known tagged failures with `Effect.catchTags({ ... })`, including when handling only one tag. Do not use `catchIf` with a schema predicate merely to recover one or more known `_tag` variants, and do not use `catchTag`. `Effect.catch` is appropriate when the entire error channel is intentionally handled; `catchIf` remains appropriate for genuinely structural predicates such as inspecting an underlying platform error code.
- Do not add a helper whose only behavior is `(...args) => new SomeError({ ...args })`, including curried aliases used once with `mapError`. Construct the error at the failure boundary so its attributes and cause remain visible. Keep a mapper only when it performs real normalization, passes through existing domain errors, or adds reusable context/control flow.
- When a reusable error-to-error translation clearly belongs to the target error type, prefer a descriptive static factory on that error class over a detached production-side switch. Do not force a static method for one-off inline mappings.
## File layout and migrations
@@ -73,4 +78,6 @@ Review changed TypeScript and directly affected call sites for the conventions b
## Reporting
Report only concrete violations introduced or retained in the pull request's changed scope. Prefer precise inline comments on the smallest relevant line range and state the expected fix. A clear convention violation may fail the check. Do not fail for optional style preferences or unrelated legacy code. If there are no findings, report exactly `All clear`.
Report only concrete violations introduced or retained in the pull request's changed scope. Prefer precise inline comments on the smallest relevant line range and state the expected fix. A clear convention violation may fail the check. Do not fail for optional style preferences or unrelated legacy code.
This check defaults to failure. When there are no findings, stop immediately and make the entire final response exactly `All clear` on one line. Do not add a title, explanation, punctuation, Markdown, JSON, or trailing analysis, and do not continue reasoning after deciding the review is clean.
+13 -11
View File
@@ -1,8 +1,8 @@
import * as Cause from "effect/Cause";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as NetService from "@t3tools/shared/Net";
import * as Crypto from "effect/Crypto";
@@ -33,22 +33,24 @@ const makeDesktopRunId = Crypto.Crypto.pipe(
Effect.map((value) => value.replaceAll("-", "").slice(0, 12)),
);
class DesktopBackendPortUnavailableError extends Data.TaggedError(
export class DesktopBackendPortUnavailableError extends Schema.TaggedErrorClass<DesktopBackendPortUnavailableError>()(
"DesktopBackendPortUnavailableError",
)<{
readonly startPort: number;
readonly maxPort: number;
readonly hosts: readonly string[];
}> {
override get message() {
{
startPort: Schema.Int,
maxPort: Schema.Int,
hosts: Schema.Array(Schema.String),
},
) {
override get message(): string {
return `No desktop backend port is available on hosts ${this.hosts.join(", ")} between ${this.startPort} and ${this.maxPort}.`;
}
}
class DesktopDevelopmentBackendPortRequiredError extends Data.TaggedError(
export class DesktopDevelopmentBackendPortRequiredError extends Schema.TaggedErrorClass<DesktopDevelopmentBackendPortRequiredError>()(
"DesktopDevelopmentBackendPortRequiredError",
)<{}> {
override get message() {
{},
) {
override get message(): string {
return "T3CODE_PORT is required in desktop development.";
}
}
@@ -0,0 +1,30 @@
import { assert, describe, it } from "@effect/vitest";
import {
DesktopBackendPortUnavailableError,
DesktopDevelopmentBackendPortRequiredError,
} from "./DesktopApp.ts";
describe("DesktopApp errors", () => {
it("preserves unavailable backend port context", () => {
const error = new DesktopBackendPortUnavailableError({
startPort: 3_773,
maxPort: 65_535,
hosts: ["127.0.0.1", "0.0.0.0", "::"],
});
assert.equal(error.startPort, 3_773);
assert.equal(error.maxPort, 65_535);
assert.deepEqual(error.hosts, ["127.0.0.1", "0.0.0.0", "::"]);
assert.equal(
error.message,
"No desktop backend port is available on hosts 127.0.0.1, 0.0.0.0, :: between 3773 and 65535.",
);
});
it("reports the required development port", () => {
const error = new DesktopDevelopmentBackendPortRequiredError();
assert.equal(error.message, "T3CODE_PORT is required in desktop development.");
});
});
@@ -0,0 +1,122 @@
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Logger from "effect/Logger";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as DesktopBackendOutputLog from "./DesktopBackendOutputLog.ts";
import * as DesktopConfig from "./DesktopConfig.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
const LOG_FILE_PATH = "/Users/alice/.t3/userdata/logs/server-child.log";
const environmentLayer = DesktopEnvironment.layer({
dirname: "/repo/apps/desktop/dist-electron",
homeDirectory: "/Users/alice",
platform: "darwin",
processArch: "arm64",
appVersion: "1.2.3",
appPath: "/Applications/T3 Code.app/Contents/Resources/app.asar",
isPackaged: true,
resourcesPath: "/Applications/T3 Code.app/Contents/Resources",
runningUnderArm64Translation: false,
}).pipe(Layer.provide(Layer.merge(Path.layer, DesktopConfig.layerTest({}))));
const withOutputLog = <A, E, R>(
effect: Effect.Effect<A, E, R | DesktopBackendOutputLog.DesktopBackendOutputLog>,
fileSystemLayer: Layer.Layer<FileSystem.FileSystem>,
messages: Array<ReadonlyArray<unknown>>,
) => {
const logger = Logger.make(({ message }) => {
messages.push(Array.isArray(message) ? message : [message]);
});
const outputLogLayer = DesktopBackendOutputLog.layer.pipe(
Layer.provide(Layer.mergeAll(fileSystemLayer, Path.layer, environmentLayer)),
Layer.provideMerge(Logger.layer([logger], { mergeWithExisting: false })),
);
return effect.pipe(Effect.provide(outputLogLayer));
};
const loggedError = (messages: ReadonlyArray<ReadonlyArray<unknown>>): unknown =>
messages.flat().find((value) => typeof value === "object" && value !== null && "error" in value)
?.error;
describe("DesktopBackendOutputLog", () => {
it.effect("logs setup failures with the log path and exact cause", () => {
const messages: Array<ReadonlyArray<unknown>> = [];
const cause = PlatformError.systemError({
_tag: "PermissionDenied",
module: "FileSystem",
method: "makeDirectory",
pathOrDescriptor: "/Users/alice/.t3/userdata/logs",
description: "private setup diagnostic",
});
const fileSystemLayer = FileSystem.layerNoop({
makeDirectory: () => Effect.fail(cause),
});
return withOutputLog(
Effect.gen(function* () {
const outputLog = yield* DesktopBackendOutputLog.DesktopBackendOutputLog;
yield* outputLog.writeSessionBoundary({ phase: "START", details: "test" });
const error = loggedError(messages);
assert.instanceOf(error, DesktopBackendOutputLog.DesktopBackendOutputLogSetupError);
assert.equal(error.logFilePath, LOG_FILE_PATH);
assert.strictEqual(error.cause, cause);
assert.equal(
error.message,
`Failed to initialize the desktop backend output log at ${LOG_FILE_PATH}.`,
);
assert.notInclude(error.message, "private setup diagnostic");
}),
fileSystemLayer,
messages,
);
});
it.effect("logs record write failures with the operation and exact cause", () => {
const messages: Array<ReadonlyArray<unknown>> = [];
const missingCause = PlatformError.systemError({
_tag: "NotFound",
module: "FileSystem",
method: "stat",
pathOrDescriptor: LOG_FILE_PATH,
});
const writeCause = PlatformError.systemError({
_tag: "PermissionDenied",
module: "FileSystem",
method: "writeFile",
pathOrDescriptor: LOG_FILE_PATH,
description: "private write diagnostic",
});
const fileSystemLayer = FileSystem.layerNoop({
makeDirectory: () => Effect.void,
stat: () => Effect.fail(missingCause),
readDirectory: () => Effect.succeed([]),
writeFile: () => Effect.fail(writeCause),
});
return withOutputLog(
Effect.gen(function* () {
const outputLog = yield* DesktopBackendOutputLog.DesktopBackendOutputLog;
yield* outputLog.writeSessionBoundary({ phase: "START", details: "test" });
const error = loggedError(messages);
assert.instanceOf(error, DesktopBackendOutputLog.DesktopBackendOutputLogWriteError);
assert.equal(error.operation, "write-record");
assert.equal(error.logFilePath, LOG_FILE_PATH);
assert.strictEqual(error.cause, writeCause);
assert.equal(
error.message,
`Desktop backend output log operation "write-record" failed at ${LOG_FILE_PATH}.`,
);
assert.notInclude(error.message, "private write diagnostic");
}),
fileSystemLayer,
messages,
);
});
});
+151 -46
View File
@@ -19,8 +19,75 @@ export const DESKTOP_LOG_FILE_MAX_FILES = 10;
const DESKTOP_BACKEND_CHILD_LOG_FIBER_ID = "#backend-child";
interface RotatingLogFileWriter {
readonly writeBytes: (chunk: Uint8Array) => Effect.Effect<void>;
readonly writeText: (chunk: string) => Effect.Effect<void>;
readonly filePath: string;
readonly writeBytes: (
chunk: Uint8Array,
) => Effect.Effect<void, PlatformError.PlatformError | DesktopLogFileWriterRecoveryError>;
readonly writeText: (
chunk: string,
) => Effect.Effect<void, PlatformError.PlatformError | DesktopLogFileWriterRecoveryError>;
}
class DesktopLogFileWriterConfigurationError extends Schema.TaggedErrorClass<DesktopLogFileWriterConfigurationError>()(
"DesktopLogFileWriterConfigurationError",
{
option: Schema.Literals(["maxBytes", "maxFiles"]),
value: Schema.Number,
},
) {
override get message(): string {
return `${this.option} must be >= 1 (received ${this.value})`;
}
}
class DesktopLogFileWriterRecoveryError extends Schema.TaggedErrorClass<DesktopLogFileWriterRecoveryError>()(
"DesktopLogFileWriterRecoveryError",
{
logFilePath: Schema.String,
cause: Schema.Defect(),
recoveryCause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to refresh desktop backend output log size after a write failure at ${this.logFilePath}.`;
}
}
export class DesktopBackendOutputLogSetupError extends Schema.TaggedErrorClass<DesktopBackendOutputLogSetupError>()(
"DesktopBackendOutputLogSetupError",
{
logFilePath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to initialize the desktop backend output log at ${this.logFilePath}.`;
}
}
export class DesktopBackendOutputLogWriteError extends Schema.TaggedErrorClass<DesktopBackendOutputLogWriteError>()(
"DesktopBackendOutputLogWriteError",
{
operation: Schema.Literals(["encode-record", "write-record"]),
logFilePath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Desktop backend output log operation "${this.operation}" failed at ${this.logFilePath}.`;
}
}
export class DesktopBackendConsoleWriteError extends Schema.TaggedErrorClass<DesktopBackendConsoleWriteError>()(
"DesktopBackendConsoleWriteError",
{
streamName: Schema.Literals(["stdout", "stderr"]),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to mirror desktop backend output to ${this.streamName}.`;
}
}
export class DesktopBackendOutputLog extends Context.Service<
@@ -37,18 +104,6 @@ export class DesktopBackendOutputLog extends Context.Service<
}
>()("@t3tools/desktop/app/DesktopBackendOutputLog") {}
class DesktopLogFileWriterConfigurationError extends Schema.TaggedErrorClass<DesktopLogFileWriterConfigurationError>()(
"DesktopLogFileWriterConfigurationError",
{
option: Schema.Literals(["maxBytes", "maxFiles"]),
value: Schema.Number,
},
) {
override get message(): string {
return `${this.option} must be >= 1 (received ${this.value})`;
}
}
type DesktopLogFileWriterError =
| DesktopLogFileWriterConfigurationError
| PlatformError.PlatformError;
@@ -85,10 +140,13 @@ const sanitizeLogValue = (value: string): string => value.replace(/\s+/g, " ").t
const refreshFileSize = (
fileSystem: FileSystem.FileSystem,
filePath: string,
): Effect.Effect<number, never> =>
): Effect.Effect<number, PlatformError.PlatformError> =>
fileSystem.stat(filePath).pipe(
Effect.map((stat) => Number(stat.size)),
Effect.orElseSucceed(() => 0),
Effect.catchTags({
PlatformError: (error) =>
error.reason._tag === "NotFound" ? Effect.succeed(0) : Effect.fail(error),
}),
);
const makeRotatingLogFileWriter = Effect.fn("makeRotatingLogFileWriter")(function* (input: {
@@ -126,41 +184,52 @@ const makeRotatingLogFileWriter = Effect.fn("makeRotatingLogFileWriter")(functio
const currentSize = yield* Ref.make(yield* refreshFileSize(fileSystem, input.filePath));
const mutex = yield* Semaphore.make(1);
const recoverCurrentSize = (
cause: PlatformError.PlatformError,
): Effect.Effect<never, PlatformError.PlatformError | DesktopLogFileWriterRecoveryError> =>
refreshFileSize(fileSystem, input.filePath).pipe(
Effect.matchEffect({
onFailure: (recoveryCause) =>
Effect.fail(
new DesktopLogFileWriterRecoveryError({
logFilePath: input.filePath,
cause,
recoveryCause,
}),
),
onSuccess: (size) => Ref.set(currentSize, size).pipe(Effect.andThen(Effect.fail(cause))),
}),
);
const pruneOverflowBackups = Effect.gen(function* () {
const entries = yield* fileSystem.readDirectory(directory).pipe(Effect.orElseSucceed(() => []));
const entries = yield* fileSystem.readDirectory(directory);
for (const entry of entries) {
if (!entry.startsWith(`${baseName}.`)) continue;
const suffix = Number(entry.slice(baseName.length + 1));
if (!Number.isInteger(suffix) || suffix <= maxFiles) continue;
yield* fileSystem.remove(path.join(directory, entry), { force: true }).pipe(Effect.ignore);
yield* fileSystem.remove(path.join(directory, entry), { force: true });
}
});
const rotate = Effect.gen(function* () {
yield* fileSystem.remove(withSuffix(maxFiles), { force: true }).pipe(Effect.ignore);
yield* fileSystem.remove(withSuffix(maxFiles), { force: true });
for (let index = maxFiles - 1; index >= 1; index -= 1) {
const source = withSuffix(index);
const sourceExists = yield* fileSystem.exists(source).pipe(Effect.orElseSucceed(() => false));
const sourceExists = yield* fileSystem.exists(source);
if (sourceExists) {
yield* fileSystem.rename(source, withSuffix(index + 1));
}
}
const currentExists = yield* fileSystem
.exists(input.filePath)
.pipe(Effect.orElseSucceed(() => false));
const currentExists = yield* fileSystem.exists(input.filePath);
if (currentExists) {
yield* fileSystem.rename(input.filePath, withSuffix(1));
}
yield* Ref.set(currentSize, 0);
}).pipe(
Effect.catch(() =>
refreshFileSize(fileSystem, input.filePath).pipe(
Effect.flatMap((size) => Ref.set(currentSize, size)),
),
),
);
});
const writeBytes = (chunk: Uint8Array): Effect.Effect<void> => {
const writeBytes = (
chunk: Uint8Array,
): Effect.Effect<void, PlatformError.PlatformError | DesktopLogFileWriterRecoveryError> => {
if (chunk.byteLength === 0) return Effect.void;
return mutex.withPermits(1)(
@@ -178,11 +247,9 @@ const makeRotatingLogFileWriter = Effect.fn("makeRotatingLogFileWriter")(functio
yield* rotate;
}
}).pipe(
Effect.catch(() =>
refreshFileSize(fileSystem, input.filePath).pipe(
Effect.flatMap((size) => Ref.set(currentSize, size)),
),
),
Effect.catchTags({
PlatformError: recoverCurrentSize,
}),
),
);
};
@@ -190,6 +257,7 @@ const makeRotatingLogFileWriter = Effect.fn("makeRotatingLogFileWriter")(functio
yield* pruneOverflowBackups;
return {
filePath: input.filePath,
writeBytes,
writeText: (chunk) => writeBytes(textEncoder.encode(chunk)),
} satisfies RotatingLogFileWriter;
@@ -199,10 +267,17 @@ const writeDevelopmentConsoleOutput = (
streamName: "stdout" | "stderr",
chunk: Uint8Array,
): Effect.Effect<void> =>
Effect.sync(() => {
const output = streamName === "stderr" ? process.stderr : process.stdout;
output.write(chunk);
}).pipe(Effect.ignore);
Effect.try({
try: () => {
const output = streamName === "stderr" ? process.stderr : process.stdout;
output.write(chunk);
},
catch: (cause) => new DesktopBackendConsoleWriteError({ streamName, cause }),
}).pipe(
Effect.catchTags({
DesktopBackendConsoleWriteError: (error) => Effect.logError(error.message, { error }),
}),
);
const writeBackendChildLogRecord = Effect.fn("desktop.observability.writeBackendChildLogRecord")(
function* (
@@ -222,17 +297,47 @@ const writeBackendChildLogRecord = Effect.fn("desktop.observability.writeBackend
annotations: input.annotations,
spans: {},
fiberId: DESKTOP_BACKEND_CHILD_LOG_FIBER_ID,
});
yield* logFile.writeText(`${encoded}\n`);
}).pipe(Effect.ignore({ log: true }));
}).pipe(
Effect.mapError(
(cause) =>
new DesktopBackendOutputLogWriteError({
operation: "encode-record",
logFilePath: logFile.filePath,
cause,
}),
),
);
yield* logFile.writeText(`${encoded}\n`).pipe(
Effect.mapError(
(cause) =>
new DesktopBackendOutputLogWriteError({
operation: "write-record",
logFilePath: logFile.filePath,
cause,
}),
),
);
}).pipe(
Effect.catchTags({
DesktopBackendOutputLogWriteError: (error) => Effect.logError(error.message, { error }),
}),
);
},
);
const make = Effect.gen(function* () {
export const make = Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const logFilePath = environment.path.join(environment.logDir, "server-child.log");
const writer = yield* makeRotatingLogFileWriter({
filePath: environment.path.join(environment.logDir, "server-child.log"),
}).pipe(Effect.option);
filePath: logFilePath,
}).pipe(
Effect.mapError((cause) => new DesktopBackendOutputLogSetupError({ logFilePath, cause })),
Effect.map(Option.some),
Effect.catchTags({
DesktopBackendOutputLogSetupError: (error) =>
Effect.logError(error.message, { error }).pipe(Effect.as(Option.none())),
}),
);
const service = Option.match(writer, {
onNone: () => DesktopBackendOutputLogNoop,
@@ -3,12 +3,15 @@ import {
type DesktopBackendBootstrap as DesktopBackendBootstrapValue,
} from "@t3tools/contracts";
import { assert, describe, it } from "@effect/vitest";
import * as Cause from "effect/Cause";
import * as Deferred from "effect/Deferred";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError";
import * as Queue from "effect/Queue";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
@@ -28,6 +31,7 @@ import * as DesktopWindow from "../window/DesktopWindow.ts";
const decodeDesktopBackendBootstrap = Schema.decodeEffect(
Schema.fromJsonString(DesktopBackendBootstrap),
);
const isBackendProcessError = Schema.is(DesktopBackendManager.BackendProcessError);
const baseConfig: DesktopBackendManager.DesktopBackendStartConfig = {
executablePath: "/electron",
@@ -55,9 +59,9 @@ const configWithObservability: DesktopBackendBootstrapValue = {
};
function makeProcess(options?: {
readonly stdout?: Stream.Stream<Uint8Array>;
readonly stderr?: Stream.Stream<Uint8Array>;
readonly exitCode?: Effect.Effect<ChildProcessSpawner.ExitCode>;
readonly stdout?: Stream.Stream<Uint8Array, PlatformError.PlatformError>;
readonly stderr?: Stream.Stream<Uint8Array, PlatformError.PlatformError>;
readonly exitCode?: Effect.Effect<ChildProcessSpawner.ExitCode, PlatformError.PlatformError>;
readonly kill?: ChildProcessSpawner.ChildProcessHandle["kill"];
}): ChildProcessSpawner.ChildProcessHandle {
return ChildProcessSpawner.makeHandle({
@@ -145,6 +149,23 @@ function makeManagerLayer(input: {
}
describe("DesktopBackendManager", () => {
it("preserves the complete restart cause and schedule context", () => {
const cause = Cause.combine(
Cause.fail(new Error("start failed")),
Cause.die(new Error("restart defect")),
);
const error = new DesktopBackendManager.DesktopBackendRestartError({
reason: "backend exited with code 1",
delayMs: 500,
cause,
});
assert.strictEqual(error.cause, cause);
assert.equal(error.reason, "backend exited with code 1");
assert.equal(error.delayMs, 500);
assert.equal(error.message, "Desktop backend restart failed after a scheduled 500ms delay.");
});
it.effect("spawns the backend with fd3 bootstrap JSON and reports HTTP readiness", () =>
Effect.gen(function* () {
let spawnedCommand: ChildProcess.Command | undefined;
@@ -218,6 +239,243 @@ describe("DesktopBackendManager", () => {
}),
);
it.effect("preserves the readiness timeout cause and process context", () =>
Effect.gen(function* () {
const requested = yield* Deferred.make<HttpClientRequest.HttpClientRequest>();
const layer = Layer.merge(
TestClock.layer(),
httpClientLayer((request) =>
Deferred.succeed(requested, request).pipe(Effect.andThen(Effect.never)),
),
);
yield* Effect.gen(function* () {
const readiness = yield* DesktopBackendManager.waitForHttpReady({
executablePath: baseConfig.executablePath,
entryPath: baseConfig.entryPath,
cwd: baseConfig.cwd,
httpBaseUrl: baseConfig.httpBaseUrl,
timeout: Duration.millis(50),
}).pipe(Effect.flip, Effect.forkChild);
const request = yield* Deferred.await(requested);
assert.equal(request.url, "http://127.0.0.1:3773/.well-known/t3/environment");
yield* TestClock.adjust(Duration.millis(50));
const error = yield* Fiber.join(readiness);
assert.instanceOf(error, DesktopBackendManager.BackendReadinessTimeoutError);
assert.equal(error.executablePath, "/electron");
assert.equal(error.entryPath, "/server/bin.mjs");
assert.equal(error.cwd, "/server");
assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/");
assert.equal(error.readinessUrl.href, "http://127.0.0.1:3773/.well-known/t3/environment");
assert.equal(error.timeoutMs, 50);
assert.isTrue(Cause.isTimeoutError(error.cause));
assert.equal(
error.message,
"Timed out after 50ms waiting for desktop backend readiness at http://127.0.0.1:3773/.well-known/t3/environment.",
);
}).pipe(Effect.provide(layer));
}),
);
it.effect("reports bootstrap encoding failures with stable process context", () =>
Effect.gen(function* () {
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() => Effect.die("unexpected backend spawn")),
);
const error = yield* DesktopBackendManager.runBackendProcess({
...baseConfig,
bootstrap: {
...baseConfig.bootstrap,
port: 0,
},
}).pipe(
Effect.flip,
Effect.scoped,
Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)),
);
if (error._tag !== "BackendProcessBootstrapEncodeError") {
return assert.fail(`Expected bootstrap encode error, received ${error._tag}`);
}
assert.equal(error.executablePath, "/electron");
assert.equal(error.entryPath, "/server/bin.mjs");
assert.equal(error.cwd, "/server");
assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/");
assert.isDefined(error.cause);
assert.equal(
error.message,
"Failed to encode the desktop backend bootstrap payload for /server/bin.mjs.",
);
assert.isTrue(isBackendProcessError(error));
}),
);
it.effect("preserves spawn failures without deriving their message from the cause", () =>
Effect.gen(function* () {
const spawnCause = PlatformError.systemError({
_tag: "PermissionDenied",
module: "ChildProcessSpawner",
method: "spawn",
pathOrDescriptor: baseConfig.executablePath,
description: "low-level detail that must not become the public message",
});
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() => Effect.fail(spawnCause)),
);
const error = yield* DesktopBackendManager.runBackendProcess(baseConfig).pipe(
Effect.flip,
Effect.scoped,
Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)),
);
if (error._tag !== "BackendProcessSpawnError") {
return assert.fail(`Expected backend spawn error, received ${error._tag}`);
}
assert.equal(error.executablePath, "/electron");
assert.equal(error.entryPath, "/server/bin.mjs");
assert.equal(error.cwd, "/server");
assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/");
assert.strictEqual(error.cause, spawnCause);
assert.equal(
error.message,
"Failed to spawn desktop backend entry /server/bin.mjs with /electron.",
);
assert.notInclude(error.message, spawnCause.message);
assert.isTrue(isBackendProcessError(error));
}),
);
it.effect("preserves exit-status failures without copying their detail into the message", () =>
Effect.gen(function* () {
const exitCause = PlatformError.systemError({
_tag: "PermissionDenied",
module: "ChildProcess",
method: "exitCode",
description: "exit-status-secret-sentinel",
});
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.succeed(
makeProcess({
exitCode: Effect.fail(exitCause),
}),
),
),
);
const error = yield* DesktopBackendManager.runBackendProcess(baseConfig).pipe(
Effect.flip,
Effect.scoped,
Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)),
);
if (error._tag !== "BackendProcessExitStatusError") {
return assert.fail(`Expected backend exit-status error, received ${error._tag}`);
}
assert.equal(error.pid, 123);
assert.equal(error.executablePath, "/electron");
assert.equal(error.entryPath, "/server/bin.mjs");
assert.equal(error.cwd, "/server");
assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/");
assert.strictEqual(error.cause, exitCause);
assert.equal(error.message, "Failed to read the exit status of desktop backend process 123.");
assert.notInclude(error.message, "exit-status-secret-sentinel");
assert.isTrue(isBackendProcessError(error));
}),
);
it.effect("reports output stream failures with process and stream context", () =>
Effect.gen(function* () {
const outputCause = PlatformError.systemError({
_tag: "BadResource",
module: "ChildProcess",
method: "stdout",
description: "output-stream-secret-sentinel",
});
const reported = yield* Deferred.make<DesktopBackendManager.BackendProcessOutputError>();
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.succeed(
makeProcess({
stdout: Stream.fail(outputCause),
exitCode: Deferred.await(reported).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
}),
),
),
);
const exit = yield* DesktopBackendManager.runBackendProcess({
...baseConfig,
onOutputFailure: (error) => Deferred.succeed(reported, error).pipe(Effect.asVoid),
}).pipe(Effect.scoped, Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)));
const error = yield* Deferred.await(reported);
assert.equal(exit.code.pipe(Option.getOrUndefined), 0);
if (error._tag !== "BackendProcessOutputReadError") {
return assert.fail(`Expected output read error, received ${error._tag}`);
}
assert.equal(error.executablePath, "/electron");
assert.equal(error.entryPath, "/server/bin.mjs");
assert.equal(error.cwd, "/server");
assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/");
assert.equal(error.pid, 123);
assert.equal(error.streamName, "stdout");
assert.strictEqual(error.cause, outputCause);
assert.equal(error.message, "Failed to read stdout from desktop backend process 123.");
assert.notInclude(error.message, "output-stream-secret-sentinel");
}),
);
it.effect("reports output handler failures separately from stream read failures", () =>
Effect.gen(function* () {
const chunk = new TextEncoder().encode("backend output");
const outputCause = new Error("output-handler-secret-sentinel");
const reported = yield* Deferred.make<DesktopBackendManager.BackendProcessOutputError>();
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.succeed(
makeProcess({
stdout: Stream.make(chunk),
exitCode: Deferred.await(reported).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
}),
),
),
);
const exit = yield* DesktopBackendManager.runBackendProcess({
...baseConfig,
onOutput: () => Effect.fail(outputCause),
onOutputFailure: (error) => Deferred.succeed(reported, error).pipe(Effect.asVoid),
}).pipe(Effect.scoped, Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)));
const error = yield* Deferred.await(reported);
assert.equal(exit.code.pipe(Option.getOrUndefined), 0);
if (error._tag !== "BackendProcessOutputHandlingError") {
return assert.fail(`Expected output handling error, received ${error._tag}`);
}
assert.equal(error.executablePath, "/electron");
assert.equal(error.entryPath, "/server/bin.mjs");
assert.equal(error.cwd, "/server");
assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/");
assert.equal(error.pid, 123);
assert.equal(error.streamName, "stdout");
assert.equal(error.chunkByteLength, chunk.byteLength);
assert.strictEqual(error.cause, outputCause);
assert.equal(
error.message,
`Failed to handle ${chunk.byteLength} bytes from stdout of desktop backend process 123.`,
);
assert.notInclude(error.message, "output-handler-secret-sentinel");
}),
);
it.effect("retries HTTP readiness before reporting the backend ready", () =>
Effect.gen(function* () {
const requestUrls: Array<string> = [];
+218 -65
View File
@@ -9,7 +9,6 @@ import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError";
import * as Ref from "effect/Ref";
import * as Result from "effect/Result";
import * as Schedule from "effect/Schedule";
import * as Schema from "effect/Schema";
import * as Semaphore from "effect/Semaphore";
@@ -43,68 +42,145 @@ type BackendProcessRunRequirements = BackendProcessLayerServices | Scope.Scope;
export type BackendProcessOutputStream = "stdout" | "stderr";
export interface DesktopBackendStartConfig {
export interface BackendProcessContext {
readonly executablePath: string;
readonly entryPath: string;
readonly cwd: string;
readonly httpBaseUrl: URL;
}
export interface DesktopBackendStartConfig extends BackendProcessContext {
readonly env: Record<string, string | undefined>;
readonly bootstrap: DesktopBackendBootstrapValue;
readonly httpBaseUrl: URL;
readonly captureOutput: boolean;
}
interface BackendProcessExit {
readonly code: Option.Option<number>;
readonly reason: string;
readonly result: Result.Result<ChildProcessSpawner.ExitCode, PlatformError.PlatformError>;
}
export class BackendTimeoutError extends Schema.TaggedErrorClass<BackendTimeoutError>()(
"BackendTimeoutError",
const backendProcessContextSchema = {
executablePath: Schema.String,
entryPath: Schema.String,
cwd: Schema.String,
httpBaseUrl: Schema.URL,
};
export class BackendReadinessTimeoutError extends Schema.TaggedErrorClass<BackendReadinessTimeoutError>()(
"BackendReadinessTimeoutError",
{
url: Schema.URL,
...backendProcessContextSchema,
readinessUrl: Schema.URL,
timeoutMs: Schema.Number,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Timed out waiting for backend readiness at ${this.url.href}.`;
return `Timed out after ${this.timeoutMs}ms waiting for desktop backend readiness at ${this.readinessUrl.href}.`;
}
}
class BackendProcessBootstrapEncodeError extends Schema.TaggedErrorClass<BackendProcessBootstrapEncodeError>()(
export class BackendProcessBootstrapEncodeError extends Schema.TaggedErrorClass<BackendProcessBootstrapEncodeError>()(
"BackendProcessBootstrapEncodeError",
{
detail: Schema.String,
...backendProcessContextSchema,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to encode desktop backend bootstrap payload: ${this.detail}`;
return `Failed to encode the desktop backend bootstrap payload for ${this.entryPath}.`;
}
}
class BackendProcessSpawnError extends Schema.TaggedErrorClass<BackendProcessSpawnError>()(
export class BackendProcessSpawnError extends Schema.TaggedErrorClass<BackendProcessSpawnError>()(
"BackendProcessSpawnError",
{
detail: Schema.String,
...backendProcessContextSchema,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to spawn desktop backend process: ${this.detail}`;
return `Failed to spawn desktop backend entry ${this.entryPath} with ${this.executablePath}.`;
}
}
type BackendProcessError = BackendProcessBootstrapEncodeError | BackendProcessSpawnError;
export class BackendProcessOutputReadError extends Schema.TaggedErrorClass<BackendProcessOutputReadError>()(
"BackendProcessOutputReadError",
{
...backendProcessContextSchema,
pid: Schema.Number,
streamName: Schema.Literals(["stdout", "stderr"]),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to read ${this.streamName} from desktop backend process ${this.pid}.`;
}
}
export class BackendProcessOutputHandlingError extends Schema.TaggedErrorClass<BackendProcessOutputHandlingError>()(
"BackendProcessOutputHandlingError",
{
...backendProcessContextSchema,
pid: Schema.Number,
streamName: Schema.Literals(["stdout", "stderr"]),
chunkByteLength: Schema.Number,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to handle ${this.chunkByteLength} bytes from ${this.streamName} of desktop backend process ${this.pid}.`;
}
}
export type BackendProcessOutputError =
| BackendProcessOutputReadError
| BackendProcessOutputHandlingError;
export class BackendProcessExitStatusError extends Schema.TaggedErrorClass<BackendProcessExitStatusError>()(
"BackendProcessExitStatusError",
{
...backendProcessContextSchema,
pid: Schema.Number,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to read the exit status of desktop backend process ${this.pid}.`;
}
}
export class DesktopBackendRestartError extends Schema.TaggedErrorClass<DesktopBackendRestartError>()(
"DesktopBackendRestartError",
{
reason: Schema.String,
delayMs: Schema.Number,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Desktop backend restart failed after a scheduled ${this.delayMs}ms delay.`;
}
}
export const BackendProcessError = Schema.Union([
BackendProcessBootstrapEncodeError,
BackendProcessSpawnError,
BackendProcessExitStatusError,
]);
export type BackendProcessError = typeof BackendProcessError.Type;
interface RunBackendProcessOptions extends DesktopBackendStartConfig {
readonly readinessTimeout?: Duration.Duration;
readonly onStarted?: (pid: number) => Effect.Effect<void>;
readonly onReady?: () => Effect.Effect<void>;
readonly onReadinessFailure?: (error: BackendTimeoutError) => Effect.Effect<void>;
readonly onReadinessFailure?: (error: BackendReadinessTimeoutError) => Effect.Effect<void>;
readonly onOutput?: (
streamName: BackendProcessOutputStream,
chunk: Uint8Array,
) => Effect.Effect<void>;
) => Effect.Effect<void, Error>;
readonly onOutputFailure?: (error: BackendProcessOutputError) => Effect.Effect<void>;
}
export interface DesktopBackendSnapshot {
@@ -183,11 +259,10 @@ const closeRun = (
).pipe(Effect.ignore);
};
const waitForHttpReady = Effect.fn("desktop.backendManager.waitForHttpReady")(function* (
baseUrl: URL,
timeout: Duration.Duration,
): Effect.fn.Return<void, BackendTimeoutError, HttpClient.HttpClient> {
const readinessUrl = new URL(BACKEND_READINESS_PATH, baseUrl);
export const waitForHttpReady = Effect.fn("desktop.backendManager.waitForHttpReady")(function* (
options: BackendProcessContext & { readonly timeout: Duration.Duration },
): Effect.fn.Return<void, BackendReadinessTimeoutError, HttpClient.HttpClient> {
const readinessUrl = new URL(BACKEND_READINESS_PATH, options.httpBaseUrl);
const client = (yield* HttpClient.HttpClient).pipe(
HttpClient.filterStatusOk,
HttpClient.transformResponse(Effect.timeout(DEFAULT_BACKEND_READINESS_REQUEST_TIMEOUT)),
@@ -196,43 +271,64 @@ const waitForHttpReady = Effect.fn("desktop.backendManager.waitForHttpReady")(fu
yield* client.get(readinessUrl).pipe(
Effect.asVoid,
Effect.timeout(timeout),
Effect.mapError(() => new BackendTimeoutError({ url: readinessUrl })),
Effect.timeout(options.timeout),
Effect.mapError(
(cause) =>
new BackendReadinessTimeoutError({
executablePath: options.executablePath,
entryPath: options.entryPath,
cwd: options.cwd,
httpBaseUrl: options.httpBaseUrl,
readinessUrl,
timeoutMs: Duration.toMillis(options.timeout),
cause,
}),
),
);
});
function describeProcessExit(
result: Result.Result<ChildProcessSpawner.ExitCode, PlatformError.PlatformError>,
): BackendProcessExit {
if (Result.isSuccess(result)) {
return {
code: Option.some(result.success),
reason: `code=${result.success}`,
result,
};
}
return {
code: Option.none(),
reason: result.failure.message,
result,
};
}
function drainBackendOutput(
context: BackendProcessContext & { readonly pid: number },
streamName: BackendProcessOutputStream,
stream: Stream.Stream<Uint8Array, PlatformError.PlatformError>,
onOutput: (streamName: BackendProcessOutputStream, chunk: Uint8Array) => Effect.Effect<void>,
onOutput: (
streamName: BackendProcessOutputStream,
chunk: Uint8Array,
) => Effect.Effect<void, Error>,
onOutputFailure: (error: BackendProcessOutputError) => Effect.Effect<void>,
): Effect.Effect<void> {
return stream.pipe(
Stream.runForEach((chunk) => onOutput(streamName, chunk)),
Effect.ignore,
Stream.mapError(
(cause) =>
new BackendProcessOutputReadError({
...context,
streamName,
cause,
}),
),
Stream.runForEach((chunk) =>
onOutput(streamName, chunk).pipe(
Effect.mapError(
(cause) =>
new BackendProcessOutputHandlingError({
...context,
streamName,
chunkByteLength: chunk.byteLength,
cause,
}),
),
),
),
Effect.catchTags({
BackendProcessOutputReadError: onOutputFailure,
BackendProcessOutputHandlingError: onOutputFailure,
}),
);
}
const encodeBootstrapJson = Schema.encodeEffect(Schema.fromJsonString(DesktopBackendBootstrap));
const runBackendProcess = Effect.fn("runBackendProcess")(function* (
export const runBackendProcess = Effect.fn("runBackendProcess")(function* (
options: RunBackendProcessOptions,
): Effect.fn.Return<BackendProcessExit, BackendProcessError, BackendProcessRunRequirements> {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
@@ -240,7 +336,10 @@ const runBackendProcess = Effect.fn("runBackendProcess")(function* (
Effect.mapError(
(cause) =>
new BackendProcessBootstrapEncodeError({
detail: cause.message,
executablePath: options.executablePath,
entryPath: options.entryPath,
cwd: options.cwd,
httpBaseUrl: options.httpBaseUrl,
cause,
}),
),
@@ -273,7 +372,10 @@ const runBackendProcess = Effect.fn("runBackendProcess")(function* (
Effect.mapError(
(cause) =>
new BackendProcessSpawnError({
detail: cause.message,
executablePath: options.executablePath,
entryPath: options.entryPath,
cwd: options.cwd,
httpBaseUrl: options.httpBaseUrl,
cause,
}),
),
@@ -281,19 +383,60 @@ const runBackendProcess = Effect.fn("runBackendProcess")(function* (
yield* options.onStarted?.(handle.pid) ?? Effect.void;
if (options.captureOutput) {
yield* drainBackendOutput("stdout", handle.stdout, onOutput).pipe(Effect.forkScoped);
yield* drainBackendOutput("stderr", handle.stderr, onOutput).pipe(Effect.forkScoped);
const outputContext = {
executablePath: options.executablePath,
entryPath: options.entryPath,
cwd: options.cwd,
httpBaseUrl: options.httpBaseUrl,
pid: Number(handle.pid),
};
const onOutputFailure = options.onOutputFailure ?? (() => Effect.void);
yield* drainBackendOutput(
outputContext,
"stdout",
handle.stdout,
onOutput,
onOutputFailure,
).pipe(Effect.forkScoped);
yield* drainBackendOutput(
outputContext,
"stderr",
handle.stderr,
onOutput,
onOutputFailure,
).pipe(Effect.forkScoped);
}
yield* waitForHttpReady(
options.httpBaseUrl,
options.readinessTimeout ?? DEFAULT_BACKEND_READINESS_TIMEOUT,
).pipe(
yield* waitForHttpReady({
executablePath: options.executablePath,
entryPath: options.entryPath,
cwd: options.cwd,
httpBaseUrl: options.httpBaseUrl,
timeout: options.readinessTimeout ?? DEFAULT_BACKEND_READINESS_TIMEOUT,
}).pipe(
Effect.tap(() => options.onReady?.() ?? Effect.void),
Effect.catch((error) => options.onReadinessFailure?.(error) ?? Effect.void),
Effect.catchTags({
BackendReadinessTimeoutError: (error) => options.onReadinessFailure?.(error) ?? Effect.void,
}),
Effect.forkScoped,
);
return describeProcessExit(yield* Effect.result(handle.exitCode));
const exitCode = yield* handle.exitCode.pipe(
Effect.mapError(
(cause) =>
new BackendProcessExitStatusError({
executablePath: options.executablePath,
entryPath: options.entryPath,
cwd: options.cwd,
httpBaseUrl: options.httpBaseUrl,
pid: Number(handle.pid),
cause,
}),
),
);
return {
code: Option.some(exitCode),
reason: `code=${exitCode}`,
} satisfies BackendProcessExit;
});
export const make = Effect.gen(function* () {
@@ -351,7 +494,7 @@ export const make = Effect.gen(function* () {
const config = yield* configuration.resolve.pipe(
Effect.tapError((error) =>
logBackendManagerError("failed to generate desktop backend configuration", {
cause: error.message,
cause: error,
}),
),
Effect.option,
@@ -489,22 +632,26 @@ export const make = Effect.gen(function* () {
yield* desktopWindow.handleBackendReady.pipe(
Effect.catch((error) =>
logBackendManagerError("failed to open main window after backend readiness", {
message: error.message,
cause: error,
}),
),
);
}),
onReadinessFailure: (error) =>
logBackendManagerWarning("backend readiness check failed during bootstrap", {
error: error.message,
error,
}),
onOutput: (streamName, chunk) => backendOutputLog.writeOutputChunk(streamName, chunk),
onOutputFailure: (error) => logBackendManagerError(error.message, { error }),
}).pipe(
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
Effect.provideService(HttpClient.HttpClient, httpClient),
Scope.provide(runScope),
Effect.matchEffect({
onFailure: (error) => finalizeRun(error.message),
onFailure: (error) =>
logBackendManagerError(error.message, { error }).pipe(
Effect.andThen(finalizeRun(error.message)),
),
onSuccess: (exit) => finalizeRun(exit.reason),
}),
Effect.ensuring(Scope.close(runScope, Exit.void).pipe(Effect.ignore)),
@@ -559,11 +706,17 @@ export const make = Effect.gen(function* () {
}),
),
Effect.flatMap((shouldRestart) => (shouldRestart ? start : Effect.void)),
Effect.catchCause((cause) =>
logBackendManagerError("desktop backend restart fiber failed", {
cause: Cause.pretty(cause),
}),
),
Effect.catchCause((cause) => {
if (Cause.hasInterruptsOnly(cause)) {
return Effect.void;
}
const error = new DesktopBackendRestartError({
reason,
delayMs: Duration.toMillis(delay),
cause,
});
return logBackendManagerError(error.message, { error });
}),
),
parentScope,
);
+11 -18
View File
@@ -19,37 +19,30 @@ import {
PreviewAutomationSnapshot,
PreviewAutomationStatus,
} from "@t3tools/contracts";
import { BrowserWindow } from "electron";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import * as NodeURL from "node:url";
import * as ElectronWindow from "../../electron/ElectronWindow.ts";
import * as PreviewManager from "../../preview/Manager.ts";
import { PREVIEW_WEBVIEW_PREFERENCES } from "../../preview/WebviewPreferences.ts";
import * as IpcChannels from "../channels.ts";
import * as DesktopIpc from "../DesktopIpc.ts";
const broadcast = (channel: string, ...args: ReadonlyArray<unknown>): void => {
for (const window of BrowserWindow.getAllWindows()) {
if (!window.isDestroyed()) {
window.webContents.send(channel, ...args);
}
}
};
export const installPreviewEventForwarding = Effect.fn(
"desktop.ipc.preview.installEventForwarding",
)(function* () {
const electronWindow = yield* ElectronWindow.ElectronWindow;
const manager = yield* PreviewManager.PreviewManager;
yield* manager.subscribeStateChanges((tabId, state) => {
broadcast(IpcChannels.PREVIEW_STATE_CHANGE_CHANNEL, tabId, state);
});
yield* manager.subscribeRecordingFrames((frame) => {
broadcast(IpcChannels.PREVIEW_RECORDING_FRAME_CHANNEL, frame);
});
yield* manager.subscribePointerEvents((event) => {
broadcast(IpcChannels.PREVIEW_POINTER_EVENT_CHANNEL, event);
});
yield* manager.subscribeStateChanges((tabId, state) =>
electronWindow.sendAll(IpcChannels.PREVIEW_STATE_CHANGE_CHANNEL, tabId, state),
);
yield* manager.subscribeRecordingFrames((frame) =>
electronWindow.sendAll(IpcChannels.PREVIEW_RECORDING_FRAME_CHANNEL, frame),
);
yield* manager.subscribePointerEvents((event) =>
electronWindow.sendAll(IpcChannels.PREVIEW_POINTER_EVENT_CHANNEL, event),
);
});
export const createTab = DesktopIpc.makeIpcMethod({
+73 -1
View File
@@ -5,6 +5,7 @@ import * as Exit from "effect/Exit";
import * as FileSystem from "effect/FileSystem";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Logger from "effect/Logger";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
@@ -13,6 +14,7 @@ import { TestClock } from "effect/testing";
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import * as ElectronWindow from "../electron/ElectronWindow.ts";
import * as BrowserSession from "./BrowserSession.ts";
import * as PreviewManager from "./Manager.ts";
@@ -130,6 +132,72 @@ describe("PreviewManager", () => {
),
);
effectIt.effect("isolates failed state listeners and continues delivery", () => {
const loggedErrors: Array<unknown> = [];
const logger = Logger.make(({ message }) => {
for (const value of Array.isArray(message) ? message : [message]) {
if (typeof value === "object" && value !== null && "cause" in value) {
loggedErrors.push(Cause.squash(value.cause as Cause.Cause<never>));
}
}
});
const deliveryError = new ElectronWindow.ElectronWindowOperationError({
operation: "send-window-message",
platform: "darwin",
windowId: 42,
channel: "preview:state-change",
cause: new Error("renderer unavailable"),
});
const delivered = vi.fn();
return withManager((manager) =>
Effect.gen(function* () {
yield* manager.subscribeStateChanges(() => Effect.die(deliveryError));
yield* manager.subscribeStateChanges((tabId, state) =>
Effect.sync(() => {
delivered(tabId, state);
}),
);
const state = yield* manager.createTab("tab_listener_failure");
expect(delivered).toHaveBeenCalledOnce();
expect(delivered).toHaveBeenCalledWith("tab_listener_failure", state);
expect(loggedErrors).toHaveLength(1);
expect(loggedErrors[0]).toBeInstanceOf(ElectronWindow.ElectronWindowOperationError);
expect(loggedErrors[0]).toMatchObject({
operation: "send-window-message",
windowId: 42,
channel: "preview:state-change",
});
}),
).pipe(
Effect.provide(
Logger.layer([logger], {
mergeWithExisting: false,
}),
),
);
});
effectIt.effect("does not swallow state listener interruption", () =>
withManager((manager) =>
Effect.gen(function* () {
const exit = yield* Effect.scoped(
Effect.gen(function* () {
yield* manager.subscribeStateChanges(() => Effect.interrupt);
return yield* Effect.exit(manager.createTab("tab_interrupted_listener"));
}),
);
expect(Exit.isFailure(exit)).toBe(true);
if (Exit.isFailure(exit)) {
expect(Cause.hasInterrupts(exit.cause)).toBe(true);
}
}),
),
);
effectIt.effect("queues navigation until the webview registers", () =>
withManager((manager) =>
Effect.gen(function* () {
@@ -411,7 +479,11 @@ describe("PreviewManager", () => {
},
} as never);
yield* manager.subscribePointerEvents((event) => activity.push(event.phase));
yield* manager.subscribePointerEvents((event) =>
Effect.sync(() => {
activity.push(event.phase);
}),
);
yield* manager.createTab("tab_1");
yield* manager.registerWebview("tab_1", 42);
const click = yield* manager
+24 -6
View File
@@ -281,8 +281,8 @@ const nextZoomLevel = (current: number, direction: "in" | "out"): number => {
return ZOOM_LEVELS[Math.max(step - 1, 0)] ?? current;
};
type Listener = (tabId: string, state: PreviewTabState) => void;
type RecordingFrameListener = (frame: DesktopPreviewRecordingFrame) => void;
type Listener = (tabId: string, state: PreviewTabState) => Effect.Effect<void>;
type RecordingFrameListener = (frame: DesktopPreviewRecordingFrame) => Effect.Effect<void>;
type PreviewInputSignal =
| { readonly kind: "pointer"; readonly x: number; readonly y: number; readonly button: number }
@@ -313,7 +313,7 @@ interface BrowserDiagnostics {
readonly requests: ReadonlyMap<string, { url: string; method: string }>;
}
type PointerEventListener = (event: DesktopPreviewPointerEvent) => void;
type PointerEventListener = (event: DesktopPreviewPointerEvent) => Effect.Effect<void>;
interface ExpectedAgentInput {
readonly signal: PreviewInputSignal;
@@ -442,11 +442,28 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
return copy;
};
const deliverEvent = (
eventKind: "state-change" | "recording-frame" | "pointer-event",
tabId: string,
delivery: () => Effect.Effect<void>,
) =>
Effect.suspend(delivery).pipe(
Effect.catchCause((cause) =>
Cause.hasInterrupts(cause)
? Effect.failCause(cause)
: Effect.logWarning("Desktop preview event listener failed.", {
eventKind,
tabId,
cause,
}),
),
);
const emit = Effect.fn("PreviewManager.emit")(function* (tabId: string, state: PreviewTabState) {
const listeners = yield* Ref.get(listenersRef);
yield* Effect.forEach(
listeners,
(listener) => Effect.sync(() => listener(tabId, state)).pipe(Effect.ignore),
(listener) => deliverEvent("state-change", tabId, () => listener(tabId, state)),
{ discard: true },
);
});
@@ -739,7 +756,8 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
};
yield* Effect.forEach(
listeners,
(listener) => Effect.sync(() => listener(frame)).pipe(Effect.ignore),
(listener) =>
deliverEvent("recording-frame", frame.tabId, () => listener(frame)),
{ discard: true },
);
}
@@ -1918,7 +1936,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
const listeners = yield* Ref.get(pointerEventListenersRef);
yield* Effect.forEach(
listeners,
(listener) => Effect.sync(() => listener(event)).pipe(Effect.ignore),
(listener) => deliverEvent("pointer-event", event.tabId, () => listener(event)),
{ discard: true },
);
});
+47 -20
View File
@@ -83,12 +83,6 @@ export class DesktopSettingsWriteError extends Schema.TaggedErrorClass<DesktopSe
}
}
const writeError = (
operation: DesktopSettingsWriteOperation,
path: string,
cause: unknown,
): DesktopSettingsWriteError => new DesktopSettingsWriteError({ operation, path, cause });
export class DesktopAppSettings extends Context.Service<
DesktopAppSettings,
{
@@ -244,18 +238,46 @@ const writeSettings = Effect.fn("desktop.settings.writeSettings")(function* (inp
const tempPath = `${input.settingsPath}.${process.pid}.${input.suffix}.tmp`;
const encoded = yield* encodeDesktopSettingsJson(
toDesktopSettingsDocument(input.settings, input.defaultSettings),
).pipe(Effect.mapError((cause) => 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)),
);
).pipe(
Effect.mapError(
(cause) =>
new DesktopSettingsWriteError({
operation: "encode-document",
path: input.settingsPath,
cause,
}),
),
);
yield* input.fileSystem.makeDirectory(directory, { recursive: true }).pipe(
Effect.mapError(
(cause) =>
new DesktopSettingsWriteError({
operation: "create-directory",
path: directory,
cause,
}),
),
);
yield* input.fileSystem.writeFileString(tempPath, `${encoded}\n`).pipe(
Effect.mapError(
(cause) =>
new DesktopSettingsWriteError({
operation: "write-temporary-file",
path: tempPath,
cause,
}),
),
);
yield* input.fileSystem.rename(tempPath, input.settingsPath).pipe(
Effect.mapError(
(cause) =>
new DesktopSettingsWriteError({
operation: "replace-settings-file",
path: input.settingsPath,
cause,
}),
),
);
});
export const make = Effect.gen(function* () {
@@ -276,8 +298,13 @@ export const make = Effect.gen(function* () {
return crypto.randomUUIDv4.pipe(
Effect.map((uuid) => uuid.replace(/-/g, "")),
Effect.mapError((cause) =>
writeError("create-temporary-file-name", environment.desktopSettingsPath, cause),
Effect.mapError(
(cause) =>
new DesktopSettingsWriteError({
operation: "create-temporary-file-name",
path: environment.desktopSettingsPath,
cause,
}),
),
Effect.flatMap((suffix) =>
writeSettings({
@@ -0,0 +1,129 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Logger from "effect/Logger";
import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError";
import * as References from "effect/References";
import * as DesktopConfig from "../app/DesktopConfig.ts";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import * as DesktopClientSettings from "./DesktopClientSettings.ts";
interface LogRecord {
readonly message: unknown;
readonly annotations: Readonly<Record<string, unknown>>;
}
const baseDir = "/virtual-home";
function makeLayer(fileSystemLayer: Layer.Layer<FileSystem.FileSystem>) {
const environmentLayer = DesktopEnvironment.layer({
dirname: "/repo/apps/desktop/src",
homeDirectory: baseDir,
platform: "darwin",
processArch: "x64",
appVersion: "1.2.3",
appPath: "/repo",
isPackaged: true,
resourcesPath: "/missing/resources",
runningUnderArm64Translation: false,
}).pipe(
Layer.provide(
Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({ T3CODE_HOME: baseDir })),
),
);
return DesktopClientSettings.layer.pipe(
Layer.provideMerge(Layer.mergeAll(environmentLayer, NodeServices.layer, fileSystemLayer)),
);
}
const readWithLogs = (fileSystemLayer: Layer.Layer<FileSystem.FileSystem>) => {
const records: Array<LogRecord> = [];
const logger = Logger.make(({ fiber, message }) => {
records.push({
message,
annotations: { ...fiber.getRef(References.CurrentLogAnnotations) },
});
});
return Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const settings = yield* DesktopClientSettings.DesktopClientSettings;
return {
result: yield* settings.get,
settingsPath: environment.clientSettingsPath,
records,
};
}).pipe(
Effect.provide(
Layer.mergeAll(
makeLayer(fileSystemLayer),
Logger.layer([logger], { mergeWithExisting: false }),
),
),
);
};
describe("DesktopClientSettings diagnostics", () => {
it.effect("treats a missing settings file as expected without warning", () =>
Effect.gen(function* () {
const result = yield* readWithLogs(FileSystem.layerNoop({}));
assert.isTrue(Option.isNone(result.result));
assert.deepEqual(result.records, []);
}),
);
it.effect("logs non-missing filesystem failures with the settings path", () => {
const permissionError = PlatformError.systemError({
_tag: "PermissionDenied",
module: "FileSystem",
method: "readFileString",
pathOrDescriptor: `${baseDir}/userdata/client-settings.json`,
});
return Effect.gen(function* () {
const result = yield* readWithLogs(
FileSystem.layerNoop({
readFileString: () => Effect.fail(permissionError),
}),
);
assert.isTrue(Option.isNone(result.result));
assert.equal(result.records.length, 1);
assert.deepEqual(result.records[0]?.message, [
"Could not read desktop client settings.",
permissionError,
]);
assert.equal(result.records[0]?.annotations.settingsPath, result.settingsPath);
});
});
it.effect("logs malformed settings documents with the settings path", () =>
Effect.gen(function* () {
const result = yield* readWithLogs(
FileSystem.layerNoop({
readFileString: () => Effect.succeed("{not-json"),
}),
);
assert.isTrue(Option.isNone(result.result));
assert.equal(result.records.length, 1);
const message = result.records[0]?.message;
if (!Array.isArray(message)) {
return assert.fail("expected structured warning arguments");
}
assert.equal(message[0], "Could not decode desktop client settings.");
const schemaError = message[1];
if (schemaError === null || typeof schemaError !== "object") {
return assert.fail("expected the schema error in the warning");
}
assert.equal("_tag" in schemaError ? schemaError._tag : undefined, "SchemaError");
assert.equal(result.records[0]?.annotations.settingsPath, result.settingsPath);
}),
);
});
@@ -18,7 +18,6 @@ const clientSettings: ClientSettings = {
confirmThreadDelete: false,
dismissedProviderUpdateNotificationKeys: [],
diffIgnoreWhitespace: true,
diffWordWrap: true,
favorites: [],
providerModelPreferences: {},
sidebarProjectGroupingMode: "repository_path",
@@ -29,6 +28,7 @@ const clientSettings: ClientSettings = {
sidebarThreadSortOrder: "created_at",
sidebarThreadPreviewCount: 6,
timestampFormat: "24-hour",
wordWrap: true,
};
const decodeClientSettingsJson = Schema.decodeEffect(Schema.fromJsonString(ClientSettingsSchema));
@@ -67,14 +67,29 @@ const readClientSettings = (
settingsPath: string,
): Effect.Effect<Option.Option<ClientSettings>> =>
fileSystem.readFileString(settingsPath).pipe(
Effect.option,
Effect.map(Option.some),
Effect.catchTags({
PlatformError: (cause) =>
cause.reason._tag === "NotFound"
? Effect.succeed(Option.none<string>())
: Effect.logWarning("Could not read desktop client settings.", cause).pipe(
Effect.annotateLogs({ settingsPath }),
Effect.as(Option.none<string>()),
),
}),
Effect.flatMap(
Option.match({
onNone: () => Effect.succeed(Option.none<ClientSettings>()),
onSome: (raw) =>
decodeClientSettingsJson(raw).pipe(
Effect.map((settings) => Option.some(settings)),
Effect.orElseSucceed(() => Option.none<ClientSettings>()),
Effect.catchTags({
SchemaError: (cause) =>
Effect.logWarning("Could not decode desktop client settings.", cause).pipe(
Effect.annotateLogs({ settingsPath }),
Effect.as(Option.none<ClientSettings>()),
),
}),
),
}),
),
+259 -3
View File
@@ -7,7 +7,10 @@ import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Logger from "effect/Logger";
import * as Option from "effect/Option";
import * as References from "effect/References";
import * as Ref from "effect/Ref";
import * as TestClock from "effect/testing/TestClock";
import * as DesktopBackendManager from "../backend/DesktopBackendManager.ts";
@@ -24,6 +27,9 @@ interface UpdatesHarnessOptions {
void,
ElectronUpdater.ElectronUpdaterCheckForUpdatesError
>;
readonly setUpdateChannelError?: DesktopAppSettings.DesktopSettingsWriteError;
readonly setDisableDifferentialDownload?: Effect.Effect<void>;
readonly stopBackend?: Effect.Effect<void>;
readonly env?: Record<string, string | undefined>;
}
@@ -67,7 +73,7 @@ function makeHarness(options: UpdatesHarnessOptions = {}) {
Effect.sync(() => {
allowDowngrade = value;
}),
setDisableDifferentialDownload: () => Effect.void,
setDisableDifferentialDownload: () => options.setDisableDifferentialDownload ?? Effect.void,
checkForUpdates: Effect.sync(() => {
checkCount += 1;
}).pipe(Effect.andThen(options.checkForUpdates ?? Effect.void)),
@@ -103,7 +109,7 @@ function makeHarness(options: UpdatesHarnessOptions = {}) {
const backendLayer = Layer.succeed(DesktopBackendManager.DesktopBackendManager, {
start: Effect.void,
stop: () => Effect.void,
stop: () => options.stopBackend ?? Effect.void,
currentConfig: Effect.succeed(Option.none()),
snapshot: Effect.succeed({
desiredRunning: false,
@@ -138,12 +144,23 @@ function makeHarness(options: UpdatesHarnessOptions = {}) {
),
);
const setUpdateChannelError = options.setUpdateChannelError;
const settingsLayer = setUpdateChannelError
? Layer.succeed(DesktopAppSettings.DesktopAppSettings, {
get: Effect.succeed(DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS),
load: Effect.succeed(DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS),
setServerExposureMode: () => Effect.die("unexpected server exposure update"),
setTailscaleServe: () => Effect.die("unexpected Tailscale Serve update"),
setUpdateChannel: () => Effect.fail(setUpdateChannelError),
} satisfies DesktopAppSettings.DesktopAppSettings["Service"])
: DesktopAppSettings.layer;
const layer = DesktopUpdates.layer.pipe(
Layer.provideMerge(updaterLayer),
Layer.provideMerge(windowLayer),
Layer.provideMerge(backendLayer),
Layer.provideMerge(DesktopState.layer),
Layer.provideMerge(DesktopAppSettings.layer),
Layer.provideMerge(settingsLayer),
Layer.provideMerge(
DesktopConfig.layerTest({
T3CODE_HOME: `/tmp/t3-desktop-updates-test-${process.pid}`,
@@ -175,6 +192,45 @@ function makeHarness(options: UpdatesHarnessOptions = {}) {
}
describe("DesktopUpdates", () => {
it("preserves complete causes for update poller and event failures", () => {
const cause = Cause.combine(
Cause.fail(new Error("updater failed")),
Cause.die(new Error("updater defect")),
);
const pollerError = new DesktopUpdates.DesktopUpdatePollerError({
poller: "startup",
cause,
});
const eventError = new DesktopUpdates.DesktopUpdateEventHandlingError({
event: "download-progress",
cause,
});
const reportedError = new DesktopUpdates.DesktopUpdaterReportedError({
operation: "download",
cause,
});
const unexpectedActionError = new DesktopUpdates.DesktopUpdateUnexpectedActionError({
action: "install",
cause,
});
assert.strictEqual(pollerError.cause, cause);
assert.equal(pollerError.poller, "startup");
assert.equal(pollerError.message, "Desktop update startup poller failed.");
assert.strictEqual(eventError.cause, cause);
assert.equal(eventError.event, "download-progress");
assert.equal(eventError.message, "Failed to handle desktop update download-progress event.");
assert.strictEqual(reportedError.cause, cause);
assert.equal(reportedError.operation, "download");
assert.equal(reportedError.message, "Desktop updater download operation reported an error.");
assert.strictEqual(unexpectedActionError.cause, cause);
assert.equal(unexpectedActionError.action, "install");
assert.equal(
unexpectedActionError.message,
"Desktop update install action failed unexpectedly.",
);
});
it.effect("configures the updater and runs startup checks on the test clock", () => {
const harness = makeHarness();
@@ -222,6 +278,178 @@ describe("DesktopUpdates", () => {
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
});
it.effect("keeps raw updater event failures out of update state", () => {
const harness = makeHarness();
const cause = new Error(
"request failed for https://user:[email protected]/update?token=secret",
);
return Effect.scoped(
Effect.gen(function* () {
const updates = yield* DesktopUpdates.DesktopUpdates;
yield* updates.configure;
harness.emit("error", cause);
yield* flushCallbacks;
const state = yield* updates.getState;
assert.equal(state.status, "error");
assert.equal(state.message, "Desktop updater background operation reported an error.");
assert.notInclude(state.message ?? "", "secret");
}),
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
});
it.effect("logs bounded updater failure context without exposing the cause", () => {
const cause = new Error(
"request failed for https://user:[email protected]/update?token=secret",
);
const updaterError = new ElectronUpdater.ElectronUpdaterCheckForUpdatesError({
channel: null,
cause,
});
const harness = makeHarness({ checkForUpdates: Effect.fail(updaterError) });
const loggedAnnotations: Array<Record<string, unknown>> = [];
const logger = Logger.make(({ fiber }) => {
const annotations = fiber.getRef(References.CurrentLogAnnotations);
if (annotations.errorTag === "ElectronUpdaterCheckForUpdatesError") {
loggedAnnotations.push(annotations);
}
});
return Effect.scoped(
Effect.gen(function* () {
const updates = yield* DesktopUpdates.DesktopUpdates;
yield* updates.configure;
yield* updates.check("manual");
const state = yield* updates.getState;
const loggedAnnotation = loggedAnnotations.at(-1);
assert.isDefined(loggedAnnotation);
assert.equal(loggedAnnotation.errorTag, "ElectronUpdaterCheckForUpdatesError");
assert.isNull(loggedAnnotation.channel);
assert.notProperty(loggedAnnotation, "error");
assert.notInclude(Object.values(loggedAnnotation).map(String).join(" "), "secret");
assert.equal(
state.message,
"Electron updater failed to check for updates on channel default.",
);
assert.notInclude(state.message ?? "", "secret");
}),
).pipe(
Effect.provide(
Layer.mergeAll(
TestClock.layer(),
harness.layer,
Logger.layer([logger], { mergeWithExisting: false }),
),
),
);
});
it.effect("recovers download state after an unexpected setup failure", () => {
let disableDifferentialCalls = 0;
const harness = makeHarness({
setDisableDifferentialDownload: Effect.suspend(() => {
disableDifferentialCalls += 1;
return disableDifferentialCalls === 1
? Effect.void
: Effect.die(new Error("download setup failed"));
}),
});
return Effect.scoped(
Effect.gen(function* () {
const updates = yield* DesktopUpdates.DesktopUpdates;
yield* updates.configure;
harness.emit("update-available", { version: "1.2.4" });
yield* flushCallbacks;
const result = yield* updates.download;
assert.isTrue(result.accepted);
assert.isFalse(result.completed);
const failedState = yield* updates.getState;
assert.equal(failedState.status, "available");
assert.equal(failedState.errorContext, "download");
assert.equal(failedState.message, "Desktop update download action failed unexpectedly.");
const changedState = yield* updates.setChannel("nightly");
assert.equal(changedState.channel, "nightly");
}),
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
});
it.effect("restores download state and permits retry after interruption", () =>
Effect.gen(function* () {
const actionStarted = yield* Deferred.make<void>();
let disableDifferentialCalls = 0;
const harness = makeHarness({
setDisableDifferentialDownload: Effect.suspend(() => {
disableDifferentialCalls += 1;
if (disableDifferentialCalls === 1) {
return Effect.void;
}
if (disableDifferentialCalls === 2) {
return Deferred.succeed(actionStarted, undefined).pipe(Effect.andThen(Effect.never));
}
return Effect.void;
}),
});
yield* Effect.scoped(
Effect.gen(function* () {
const updates = yield* DesktopUpdates.DesktopUpdates;
yield* updates.configure;
harness.emit("update-available", { version: "1.2.4" });
yield* flushCallbacks;
const downloadFiber = yield* updates.download.pipe(Effect.forkScoped);
yield* Deferred.await(actionStarted);
yield* Fiber.interrupt(downloadFiber);
const interruptedState = yield* updates.getState;
assert.equal(interruptedState.status, "available");
assert.isNull(interruptedState.message);
const retry = yield* updates.download;
assert.isTrue(retry.accepted);
assert.isTrue(retry.completed);
}),
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
}),
);
it.effect("clears quitting state after an unexpected install setup failure", () => {
const harness = makeHarness({
stopBackend: Effect.die(new Error("backend stop failed")),
});
return Effect.scoped(
Effect.gen(function* () {
const desktopState = yield* DesktopState.DesktopState;
const updates = yield* DesktopUpdates.DesktopUpdates;
yield* updates.configure;
harness.emit("update-downloaded", { version: "1.2.4" });
yield* flushCallbacks;
const result = yield* updates.install;
assert.isTrue(result.accepted);
assert.isFalse(result.completed);
assert.isFalse(yield* Ref.get(desktopState.quitting));
const failedState = yield* updates.getState;
assert.equal(failedState.status, "downloaded");
assert.equal(failedState.errorContext, "install");
assert.equal(failedState.message, "Desktop update install action failed unexpectedly.");
const changedState = yield* updates.setChannel("nightly");
assert.equal(changedState.channel, "nightly");
}),
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
});
it.effect("persists channel changes through the settings service", () => {
const harness = makeHarness();
@@ -284,6 +512,7 @@ describe("DesktopUpdates", () => {
const error = Cause.squash(exit.cause);
assert.instanceOf(error, DesktopUpdates.DesktopUpdateActionInProgressError);
assert.equal(error.action, "check");
assert.equal(error.requestedChannel, "nightly");
}
yield* Deferred.succeed(releaseCheck, undefined);
@@ -292,4 +521,31 @@ describe("DesktopUpdates", () => {
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
}),
);
it.effect("preserves settings failure context when an update channel cannot be persisted", () => {
const diskFailure = new Error("disk exploded");
const settingsFailure = new DesktopAppSettings.DesktopSettingsWriteError({
operation: "replace-settings-file",
path: "/tmp/settings.json",
cause: diskFailure,
});
const harness = makeHarness({ setUpdateChannelError: settingsFailure });
return Effect.scoped(
Effect.gen(function* () {
const updates = yield* DesktopUpdates.DesktopUpdates;
yield* updates.configure;
const error = yield* updates.setChannel("nightly").pipe(Effect.flip);
assert.instanceOf(error, DesktopUpdates.DesktopUpdateChannelPersistenceError);
assert.isTrue(DesktopUpdates.isDesktopUpdateSetChannelError(error));
assert.equal(error.channel, "nightly");
assert.strictEqual(error.cause, settingsFailure);
assert.strictEqual(error.cause.cause, diskFailure);
assert.equal(error.message, "Failed to persist the nightly desktop update channel.");
assert.notInclude(error.message, diskFailure.message);
}),
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
});
});
+218 -57
View File
@@ -1,9 +1,10 @@
import type {
DesktopRuntimeInfo,
DesktopUpdateActionResult,
DesktopUpdateChannel,
DesktopUpdateCheckResult,
DesktopUpdateState,
import {
DesktopUpdateChannelSchema,
type DesktopRuntimeInfo,
type DesktopUpdateActionResult,
type DesktopUpdateChannel,
type DesktopUpdateCheckResult,
type DesktopUpdateState,
} from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import * as Context from "effect/Context";
@@ -63,30 +64,82 @@ export class DesktopUpdateActionInProgressError extends Schema.TaggedErrorClass<
"DesktopUpdateActionInProgressError",
{
action: Schema.Literals(["check", "download", "install"]),
requestedChannel: DesktopUpdateChannelSchema,
},
) {
override get message(): string {
return `Cannot change update tracks while an update ${this.action} action is in progress.`;
return `Cannot change the desktop update channel to ${this.requestedChannel} while an update ${this.action} action is in progress.`;
}
}
export class DesktopUpdatePersistenceError extends Schema.TaggedErrorClass<DesktopUpdatePersistenceError>()(
"DesktopUpdatePersistenceError",
export class DesktopUpdateChannelPersistenceError extends Schema.TaggedErrorClass<DesktopUpdateChannelPersistenceError>()(
"DesktopUpdateChannelPersistenceError",
{
channel: DesktopUpdateChannelSchema,
cause: Schema.instanceOf(DesktopAppSettings.DesktopSettingsWriteError),
},
) {
override get message(): string {
return `Failed to persist the ${this.channel} desktop update channel.`;
}
}
export class DesktopUpdatePollerError extends Schema.TaggedErrorClass<DesktopUpdatePollerError>()(
"DesktopUpdatePollerError",
{
poller: Schema.Literals(["startup", "poll"]),
cause: Schema.Defect(),
},
) {
override get message(): string {
const detail = this.cause instanceof Error ? this.cause.message : String(this.cause);
return `Failed to persist desktop update settings: ${detail}`;
return `Desktop update ${this.poller} poller failed.`;
}
}
export class DesktopUpdateEventHandlingError extends Schema.TaggedErrorClass<DesktopUpdateEventHandlingError>()(
"DesktopUpdateEventHandlingError",
{
event: Schema.Literals(["update-available", "download-progress", "update-downloaded"]),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to handle desktop update ${this.event} event.`;
}
}
export class DesktopUpdaterReportedError extends Schema.TaggedErrorClass<DesktopUpdaterReportedError>()(
"DesktopUpdaterReportedError",
{
operation: Schema.Literals(["check", "download", "install", "background"]),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Desktop updater ${this.operation} operation reported an error.`;
}
}
export class DesktopUpdateUnexpectedActionError extends Schema.TaggedErrorClass<DesktopUpdateUnexpectedActionError>()(
"DesktopUpdateUnexpectedActionError",
{
action: Schema.Literals(["download", "install"]),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Desktop update ${this.action} action failed unexpectedly.`;
}
}
export type DesktopUpdateConfigureError = never;
export type DesktopUpdateSetChannelError =
| DesktopUpdateActionInProgressError
| DesktopUpdatePersistenceError;
export const DesktopUpdateSetChannelError = Schema.Union([
DesktopUpdateActionInProgressError,
DesktopUpdateChannelPersistenceError,
]);
export type DesktopUpdateSetChannelError = typeof DesktopUpdateSetChannelError.Type;
export const isDesktopUpdateSetChannelError = Schema.is(DesktopUpdateSetChannelError);
export class DesktopUpdates extends Context.Service<
DesktopUpdates,
@@ -308,16 +361,21 @@ export const make = Effect.gen(function* () {
return yield* electronUpdater.checkForUpdates.pipe(
Effect.as(true),
Effect.catch(
Effect.fn("desktop.updates.handleCheckForUpdatesFailure")(function* (error) {
Effect.catchTags({
ElectronUpdaterCheckForUpdatesError: Effect.fn(
"desktop.updates.handleCheckForUpdatesFailure",
)(function* (error) {
const failedAt = yield* currentIsoTimestamp;
yield* updateState((current) =>
reduceDesktopUpdateStateOnCheckFailure(current, error.message, failedAt),
);
yield* logUpdaterError("failed to check for updates", { message: error.message });
yield* logUpdaterError(error.message, {
errorTag: error._tag,
channel: error.channel,
});
return true;
}),
),
}),
Effect.ensuring(Ref.set(updateCheckInFlightRef, false)),
);
});
@@ -342,19 +400,50 @@ export const make = Effect.gen(function* () {
yield* electronUpdater.downloadUpdate;
return { accepted: true, completed: true };
}).pipe(
Effect.catch(
Effect.fn("desktop.updates.handleDownloadFailure")(function* (error) {
Effect.catchTags({
ElectronUpdaterDownloadUpdateError: Effect.fn("desktop.updates.handleDownloadFailure")(
function* (error) {
yield* updateState((current) =>
reduceDesktopUpdateStateOnDownloadFailure(current, error.message),
);
yield* logUpdaterError(error.message, {
errorTag: error._tag,
channel: error.channel,
});
return { accepted: true, completed: false };
},
),
}),
Effect.onInterrupt(() =>
updateState((current) => (current.status === "downloading" ? state : current)).pipe(
Effect.asVoid,
),
),
Effect.catchCause((cause) => {
if (Cause.hasInterruptsOnly(cause)) {
return Effect.failCause(cause);
}
const error = new DesktopUpdateUnexpectedActionError({ action: "download", cause });
return Effect.gen(function* () {
yield* updateState((current) =>
reduceDesktopUpdateStateOnDownloadFailure(current, error.message),
);
yield* logUpdaterError("failed to download update", { message: error.message });
yield* logUpdaterError(error.message, {
errorTag: error._tag,
action: error.action,
});
return { accepted: true, completed: false };
}),
),
});
}),
Effect.ensuring(Ref.set(updateDownloadInFlightRef, false)),
);
}).pipe(Effect.withSpan("desktop.updates.downloadAvailableUpdate"));
const resetInstallAction = Effect.all(
[Ref.set(updateInstallInFlightRef, false), Ref.set(desktopState.quitting, false)],
{ discard: true },
);
const installDownloadedUpdate = Effect.gen(function* () {
const state = yield* Ref.get(updateStateRef);
if (
@@ -377,14 +466,38 @@ export const make = Effect.gen(function* () {
});
return { accepted: true, completed: false };
}).pipe(
Effect.catch(
Effect.fn("desktop.updates.handleInstallFailure")(function* (error) {
yield* Ref.set(updateInstallInFlightRef, false);
Effect.catchTags({
ElectronUpdaterQuitAndInstallError: Effect.fn("desktop.updates.handleInstallFailure")(
function* (error) {
yield* resetInstallAction;
yield* updateState((current) =>
reduceDesktopUpdateStateOnInstallFailure(current, error.message),
);
yield* logUpdaterError(error.message, {
errorTag: error._tag,
channel: error.channel,
isSilent: error.isSilent,
isForceRunAfter: error.isForceRunAfter,
});
return { accepted: true, completed: false };
},
),
}),
Effect.onInterrupt(() => resetInstallAction),
Effect.catchCause((cause) =>
Effect.gen(function* () {
if (Cause.hasInterruptsOnly(cause)) {
return yield* Effect.failCause(cause);
}
yield* resetInstallAction;
const error = new DesktopUpdateUnexpectedActionError({ action: "install", cause });
yield* updateState((current) =>
reduceDesktopUpdateStateOnInstallFailure(current, error.message),
);
yield* Ref.set(desktopState.quitting, false);
yield* logUpdaterError("failed to install update", { message: error.message });
yield* logUpdaterError(error.message, {
errorTag: error._tag,
action: error.action,
});
return { accepted: true, completed: false };
}),
),
@@ -394,17 +507,31 @@ export const make = Effect.gen(function* () {
const startUpdatePollers: Effect.Effect<void, never, Scope.Scope> = Effect.gen(function* () {
yield* Effect.sleep(AUTO_UPDATE_STARTUP_DELAY).pipe(
Effect.andThen(checkForUpdates("startup")),
Effect.catchCause((cause) =>
logUpdaterError("startup update check failed", { cause: Cause.pretty(cause) }),
),
Effect.catchCause((cause) => {
if (Cause.hasInterruptsOnly(cause)) {
return Effect.void;
}
const error = new DesktopUpdatePollerError({ poller: "startup", cause });
return logUpdaterError(error.message, {
errorTag: error._tag,
poller: error.poller,
});
}),
Effect.forkScoped,
);
yield* Effect.sleep(AUTO_UPDATE_POLL_INTERVAL).pipe(
Effect.andThen(checkForUpdates("poll")),
Effect.forever,
Effect.catchCause((cause) =>
logUpdaterError("poll update check failed", { cause: Cause.pretty(cause) }),
),
Effect.catchCause((cause) => {
if (Cause.hasInterruptsOnly(cause)) {
return Effect.void;
}
const error = new DesktopUpdatePollerError({ poller: "poll", cause });
return logUpdaterError(error.message, {
errorTag: error._tag,
poller: error.poller,
});
}),
Effect.forkScoped,
);
}).pipe(Effect.withSpan("desktop.updates.startPollers"));
@@ -435,11 +562,16 @@ export const make = Effect.gen(function* () {
yield* logUpdaterInfo("update available", { version: info.version });
}),
),
Effect.catchCause((cause) =>
logUpdaterWarning("ignored malformed update-available event", {
cause: Cause.pretty(cause),
}),
),
Effect.catchCause((cause) => {
if (Cause.hasInterruptsOnly(cause)) {
return Effect.void;
}
const error = new DesktopUpdateEventHandlingError({ event: "update-available", cause });
return logUpdaterWarning(error.message, {
errorTag: error._tag,
event: error.event,
});
}),
);
});
@@ -452,14 +584,23 @@ export const make = Effect.gen(function* () {
}).pipe(Effect.withSpan("desktop.updates.handleUpdateNotAvailable"));
const handleUpdaterError = Effect.fn("desktop.updates.handleUpdaterError")(function* (
error: unknown,
cause: unknown,
) {
const message = error instanceof Error ? error.message : String(error);
const activeAction = yield* activeUpdateAction;
const error = new DesktopUpdaterReportedError({
operation: Option.getOrElse(activeAction, () => "background" as const),
cause,
});
if (yield* Ref.get(updateInstallInFlightRef)) {
yield* Ref.set(updateInstallInFlightRef, false);
yield* Ref.set(desktopState.quitting, false);
yield* updateState((current) => reduceDesktopUpdateStateOnInstallFailure(current, message));
yield* logUpdaterError("updater error", { message });
yield* updateState((current) =>
reduceDesktopUpdateStateOnInstallFailure(current, error.message),
);
yield* logUpdaterError(error.message, {
errorTag: error._tag,
operation: error.operation,
});
return;
}
@@ -469,7 +610,7 @@ export const make = Effect.gen(function* () {
yield* updateState((current) => ({
...current,
status: "error",
message,
message: error.message,
checkedAt,
downloadPercent: null,
errorContext,
@@ -477,7 +618,10 @@ export const make = Effect.gen(function* () {
}));
}
yield* logUpdaterError("updater error", { message });
yield* logUpdaterError(error.message, {
errorTag: error._tag,
operation: error.operation,
});
});
const handleDownloadProgress = Effect.fn("desktop.updates.handleDownloadProgress")(function* (
@@ -499,11 +643,16 @@ export const make = Effect.gen(function* () {
}
}),
),
Effect.catchCause((cause) =>
logUpdaterWarning("ignored malformed download-progress event", {
cause: Cause.pretty(cause),
}),
),
Effect.catchCause((cause) => {
if (Cause.hasInterruptsOnly(cause)) {
return Effect.void;
}
const error = new DesktopUpdateEventHandlingError({ event: "download-progress", cause });
return logUpdaterWarning(error.message, {
errorTag: error._tag,
event: error.event,
});
}),
);
});
@@ -518,11 +667,16 @@ export const make = Effect.gen(function* () {
yield* logUpdaterInfo("update downloaded", { version: info.version });
}),
),
Effect.catchCause((cause) =>
logUpdaterWarning("ignored malformed update-downloaded event", {
cause: Cause.pretty(cause),
}),
),
Effect.catchCause((cause) => {
if (Cause.hasInterruptsOnly(cause)) {
return Effect.void;
}
const error = new DesktopUpdateEventHandlingError({ event: "update-downloaded", cause });
return logUpdaterWarning(error.message, {
errorTag: error._tag,
event: error.event,
});
}),
);
});
@@ -598,7 +752,10 @@ export const make = Effect.gen(function* () {
yield* Effect.annotateCurrentSpan({ channel: nextChannel });
const activeAction = yield* activeUpdateAction;
if (Option.isSome(activeAction)) {
return yield* new DesktopUpdateActionInProgressError({ action: activeAction.value });
return yield* new DesktopUpdateActionInProgressError({
action: activeAction.value,
requestedChannel: nextChannel,
});
}
const state = yield* Ref.get(updateStateRef);
@@ -608,7 +765,11 @@ export const make = Effect.gen(function* () {
yield* desktopSettings
.setUpdateChannel(nextChannel)
.pipe(Effect.mapError((cause) => new DesktopUpdatePersistenceError({ cause })));
.pipe(
Effect.mapError(
(cause) => new DesktopUpdateChannelPersistenceError({ channel: nextChannel, cause }),
),
);
const enabled = yield* shouldEnableAutoUpdates;
yield* setState(createBaseUpdateState(nextChannel, enabled, environment));
@@ -397,7 +397,7 @@ function CloudEnvironmentRowShell(props: {
className={cn("text-xs leading-[16px] underline", statusClassName)}
onLongPress={(event) => {
event.stopPropagation();
copyTextWithHaptic(errorTraceId);
copyTextWithHaptic(errorTraceId, { target: "connection-trace-id" });
}}
onPress={(event) => {
event.stopPropagation();
@@ -441,7 +441,7 @@ function CopyTraceIdButton(props: { readonly traceId: string }) {
<Pressable
accessibilityRole="button"
onPress={() => {
copyTextWithHaptic(props.traceId);
copyTextWithHaptic(props.traceId, { target: "connection-trace-id" });
}}
className="self-start flex-row items-center gap-1.5 rounded-full bg-subtle px-3 py-2 active:opacity-70"
>
@@ -1,4 +1,7 @@
import { describe, expect, it } from "vite-plus/test";
import type { NotificationResponse } from "expo-notifications";
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
import { consumeLastAgentNotificationResponse } from "./notificationResponseConsumer";
import {
extractAgentNotificationDeepLink,
@@ -18,6 +21,76 @@ function responseWithData(data: Record<string, unknown>, identifier = "notificat
};
}
afterEach(() => {
vi.restoreAllMocks();
});
describe("consumeLastAgentNotificationResponse", () => {
it("reports which initial-response operation failed", async () => {
const cause = new Error("notification lookup unavailable");
const consoleError = vi.spyOn(console, "error").mockImplementation(() => undefined);
await consumeLastAgentNotificationResponse({
getLastResponse: () => Promise.reject(cause),
clearLastResponse: () => Promise.resolve(),
handleResponse: vi.fn(),
});
expect(consoleError).toHaveBeenCalledWith(
expect.objectContaining({
_tag: "NotificationNavigationError",
operation: "read",
}),
);
});
it("routes a response before reporting a clear failure", async () => {
const cause = new Error("notification clear unavailable");
const consoleError = vi.spyOn(console, "error").mockImplementation(() => undefined);
const response = responseWithData({}, "notification-clear") as NotificationResponse;
const handleResponse = vi.fn();
await consumeLastAgentNotificationResponse({
getLastResponse: () => Promise.resolve(response),
clearLastResponse: () => Promise.reject(cause),
handleResponse,
});
expect(handleResponse).toHaveBeenCalledWith(response);
expect(consoleError).toHaveBeenCalledWith(
expect.objectContaining({
_tag: "NotificationNavigationError",
operation: "clear",
notificationId: "notification-clear",
}),
);
});
it("reports routing failures before clearing the response", async () => {
const cause = new Error("notification routing unavailable");
const consoleError = vi.spyOn(console, "error").mockImplementation(() => undefined);
const response = responseWithData({}, "notification-route") as NotificationResponse;
const clearLastResponse = vi.fn(() => Promise.resolve());
await consumeLastAgentNotificationResponse({
getLastResponse: () => Promise.resolve(response),
clearLastResponse,
handleResponse: () => {
throw cause;
},
});
expect(clearLastResponse).not.toHaveBeenCalled();
expect(consoleError).toHaveBeenCalledWith(
expect.objectContaining({
_tag: "NotificationNavigationError",
operation: "route",
notificationId: "notification-route",
}),
);
});
});
describe("extractAgentNotificationDeepLink", () => {
it("uses explicit deep links from APNs payload data", () => {
expect(
@@ -3,6 +3,7 @@ import * as Notifications from "expo-notifications";
import { useRouter } from "expo-router";
import { routeAgentNotificationResponseOnce } from "./notificationPayload";
import { consumeLastAgentNotificationResponse } from "./notificationResponseConsumer";
export function useAgentNotificationNavigation(): void {
const router = useRouter();
@@ -18,15 +19,11 @@ export function useAgentNotificationNavigation(): void {
};
const subscription = Notifications.addNotificationResponseReceivedListener(handleResponse);
void Notifications.getLastNotificationResponseAsync()
.then((response) => {
if (response) {
handleResponse(response);
return Notifications.clearLastNotificationResponseAsync();
}
return undefined;
})
.catch(() => undefined);
void consumeLastAgentNotificationResponse({
getLastResponse: () => Notifications.getLastNotificationResponseAsync(),
clearLastResponse: () => Notifications.clearLastNotificationResponseAsync(),
handleResponse,
});
return () => {
subscription.remove();
@@ -0,0 +1,58 @@
import type { NotificationResponse } from "expo-notifications";
import * as Schema from "effect/Schema";
export class NotificationNavigationError extends Schema.TaggedErrorClass<NotificationNavigationError>()(
"NotificationNavigationError",
{
operation: Schema.Literals(["read", "route", "clear"]),
notificationId: Schema.optional(Schema.String),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to ${this.operation} the last notification response.`;
}
}
export async function consumeLastAgentNotificationResponse(input: {
readonly getLastResponse: () => Promise<NotificationResponse | null>;
readonly clearLastResponse: () => Promise<void>;
readonly handleResponse: (response: NotificationResponse) => void;
}): Promise<void> {
let response: NotificationResponse | null;
try {
response = await input.getLastResponse();
} catch (cause) {
console.error(new NotificationNavigationError({ operation: "read", cause }));
return;
}
if (!response) {
return;
}
try {
input.handleResponse(response);
} catch (cause) {
console.error(
new NotificationNavigationError({
operation: "route",
notificationId: response.notification.request.identifier,
cause,
}),
);
return;
}
try {
await input.clearLastResponse();
} catch (cause) {
console.error(
new NotificationNavigationError({
operation: "clear",
notificationId: response.notification.request.identifier,
cause,
}),
);
}
}
@@ -18,6 +18,7 @@ import { cryptoLayer } from "../cloud/dpop";
import { managedRelayClientLayer } from "../cloud/managedRelayLayer";
import { makeRelayDeviceRegistrationRequest } from "./registrationPayload";
import {
AgentAwarenessOperationError,
__resetAgentAwarenessRemoteRegistrationForTest,
refreshActiveLiveActivityRemoteRegistration,
refreshAgentAwarenessRegistration,
@@ -267,6 +268,28 @@ describe("makeRelayDeviceRegistrationRequest", () => {
}).pipe(Effect.provide(relayTestLayer));
});
it.effect("preserves Live Activity push-token lookup failures", () => {
const cause = new Error("native token lookup failed");
const activity = {
getPushToken: vi.fn(() => Promise.reject(cause)),
addPushTokenListener: vi.fn(),
};
return Effect.gen(function* () {
const error = yield* Effect.flip(
registerLiveActivityPushToken({ activity: activity as never }),
);
expect(error).toBeInstanceOf(AgentAwarenessOperationError);
expect(error).toMatchObject({
_tag: "AgentAwarenessOperationError",
operation: "read-live-activity-push-token",
cause,
message: "Agent awareness operation read-live-activity-push-token failed.",
});
}).pipe(Effect.provide(relayTestLayer));
});
it.effect(
"reports Live Activity token registration as skipped when relay auth is unavailable",
() => {
@@ -2,6 +2,7 @@ import { addPushToStartTokenListener, type LiveActivity } from "expo-widgets";
import Constants from "expo-constants";
import * as Notifications from "expo-notifications";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import { Platform } from "react-native";
import type { EnvironmentId } from "@t3tools/contracts";
import {
@@ -28,6 +29,33 @@ import { resolveCloudPublicConfig } from "../cloud/publicConfig";
import { makeRelayDeviceRegistrationRequest } from "./registrationPayload";
const REMOTE_ACTIVITY_REGISTRATION_RETRY_MS = 15_000;
const AgentAwarenessOperation = Schema.Literals([
"read-notification-permissions",
"read-native-push-token",
"read-device-registration-relay-token",
"read-device-unregistration-relay-token",
"read-live-activity-registration-relay-token",
"load-device-registration-identifier",
"load-device-registration-preferences",
"load-device-unregistration-identifier",
"read-live-activity-push-token",
"load-live-activity-registration-identifier",
"list-active-live-activities",
]);
export class AgentAwarenessOperationError extends Schema.TaggedErrorClass<AgentAwarenessOperationError>()(
"AgentAwarenessOperationError",
{
operation: AgentAwarenessOperation,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Agent awareness operation ${this.operation} failed.`;
}
}
const environmentConnections = new Map<EnvironmentId, SavedRemoteConnection>();
const activityPushTokenListeners = new WeakSet<LiveActivity<AgentActivityProps>>();
let pushToStartSubscription: { remove: () => void } | null = null;
@@ -137,14 +165,22 @@ function nativePushTokenRegistration(observedPushToken?: string) {
}
const permissions = yield* Effect.tryPromise({
try: () => Notifications.getPermissionsAsync(),
catch: (error) => error,
catch: (cause) =>
new AgentAwarenessOperationError({
operation: "read-notification-permissions",
cause,
}),
});
if (!permissions.granted) {
return { notificationsEnabled: false, pushToken: null };
}
const token = yield* Effect.tryPromise({
try: () => Notifications.getDevicePushTokenAsync(),
catch: (error) => error,
catch: (cause) =>
new AgentAwarenessOperationError({
operation: "read-native-push-token",
cause,
}),
}).pipe(
Effect.tapError((error) =>
Effect.sync(() => {
@@ -161,16 +197,19 @@ function nativePushTokenRegistration(observedPushToken?: string) {
});
}
const relayToken = Effect.gen(function* () {
const provider = relayTokenProvider;
if (!provider) {
return null;
}
return yield* Effect.tryPromise({
try: provider,
catch: (error) => error,
const relayToken = (
operation: "read-device-registration-relay-token" | "read-live-activity-registration-relay-token",
) =>
Effect.gen(function* () {
const provider = relayTokenProvider;
if (!provider) {
return null;
}
return yield* Effect.tryPromise({
try: provider,
catch: (cause) => new AgentAwarenessOperationError({ operation, cause }),
});
});
});
function registerDeviceWithRelay(
body: RelayDeviceRegistrationRequest,
@@ -185,7 +224,7 @@ function registerDeviceWithRelay(
return;
}
if (!readRelayConfig()) return;
const token = yield* relayToken;
const token = yield* relayToken("read-device-registration-relay-token");
if (expectedGeneration !== deviceRegistrationGeneration) {
logRegistrationDebug("device registration cancelled after auth lookup", {
expectedGeneration,
@@ -220,7 +259,11 @@ function unregisterDeviceWithRelay(input: {
if (!readRelayConfig()) return;
const token = yield* Effect.tryPromise({
try: input.tokenProvider,
catch: (error) => error,
catch: (cause) =>
new AgentAwarenessOperationError({
operation: "read-device-unregistration-relay-token",
cause,
}),
});
if (!token) {
logRegistrationDebug("relay device unregistration skipped; user is not signed in");
@@ -240,7 +283,7 @@ function registerLiveActivityWithRelay(
): Effect.Effect<boolean, unknown, ManagedRelay.ManagedRelayClient> {
return Effect.gen(function* () {
if (!readRelayConfig()) return false;
const token = yield* relayToken;
const token = yield* relayToken("read-live-activity-registration-relay-token");
if (!token) {
logRegistrationDebug("relay live activity registration skipped; user is not signed in");
return false;
@@ -381,11 +424,19 @@ function registerDevice(
const [deviceId, preferences] = yield* Effect.all([
Effect.tryPromise({
try: () => loadOrCreateAgentAwarenessDeviceId(),
catch: (error) => error,
catch: (cause) =>
new AgentAwarenessOperationError({
operation: "load-device-registration-identifier",
cause,
}),
}),
Effect.tryPromise({
try: () => loadPreferences(),
catch: (error) => error,
catch: (cause) =>
new AgentAwarenessOperationError({
operation: "load-device-registration-preferences",
cause,
}),
}),
]);
const pushTokenRegistration = yield* nativePushTokenRegistration(input?.observedPushToken);
@@ -519,7 +570,11 @@ export function unregisterAgentAwarenessDeviceForCurrentUser(
return Effect.gen(function* () {
const deviceId = yield* Effect.tryPromise({
try: () => loadAgentAwarenessDeviceId(),
catch: (error) => error,
catch: (cause) =>
new AgentAwarenessOperationError({
operation: "load-device-unregistration-identifier",
cause,
}),
});
if (!deviceId) {
return;
@@ -544,7 +599,11 @@ export function registerLiveActivityPushToken(input: {
const activityPushToken = yield* Effect.tryPromise({
try: () => input.activity.getPushToken(),
catch: (error) => error,
catch: (cause) =>
new AgentAwarenessOperationError({
operation: "read-live-activity-push-token",
cause,
}),
});
if (!activityPushToken) {
if (activityPushTokenListeners.has(input.activity)) {
@@ -592,7 +651,11 @@ function registerLiveActivityPushTokenValue(input: {
return Effect.gen(function* () {
const deviceId = yield* Effect.tryPromise({
try: () => loadOrCreateAgentAwarenessDeviceId(),
catch: (error) => error,
catch: (cause) =>
new AgentAwarenessOperationError({
operation: "load-live-activity-registration-identifier",
cause,
}),
});
const registered = yield* registerLiveActivityWithRelay({
deviceId,
@@ -633,7 +696,11 @@ export function refreshActiveLiveActivityRemoteRegistration(): Effect.Effect<
const activities = yield* Effect.try({
try: () => AgentActivity.getInstances(),
catch: (error) => error,
catch: (cause) =>
new AgentAwarenessOperationError({
operation: "list-active-live-activities",
cause,
}),
}).pipe(
Effect.catch((error) =>
Effect.sync(() => {
@@ -4,6 +4,7 @@ import { useState } from "react";
import { MOBILE_TYPOGRAPHY } from "../../lib/typography";
import { useThemeColor } from "../../lib/useThemeColor";
import { CloudWaitlistJoinRejectedError, joinCloudWaitlist } from "./cloudWaitlistJoin";
export function CloudWaitlistEnrollment(props: { readonly onSignIn: () => void }) {
const { errors, fetchStatus, waitlist } = useWaitlist();
@@ -21,12 +22,14 @@ export function CloudWaitlistEnrollment(props: { readonly onSignIn: () => void }
setRequestError(null);
try {
const { error } = await waitlist.join({ emailAddress: normalizedEmailAddress });
if (error) {
setRequestError("Could not join the waitlist. Check your email address and try again.");
}
} catch {
setRequestError("Could not join the waitlist. Check your connection and try again.");
await joinCloudWaitlist(waitlist, normalizedEmailAddress);
} catch (error) {
console.error(error);
setRequestError(
error instanceof CloudWaitlistJoinRejectedError
? "Could not join the waitlist. Check your email address and try again."
: "Could not join the waitlist. Check your connection and try again.",
);
}
};
@@ -0,0 +1,48 @@
import { describe, expect, it, vi } from "vite-plus/test";
import {
CloudWaitlistJoinRejectedError,
CloudWaitlistJoinRequestError,
joinCloudWaitlist,
} from "./cloudWaitlistJoin";
describe("joinCloudWaitlist", () => {
it("submits the provided email address", async () => {
const join = vi.fn().mockResolvedValue({ error: null });
await joinCloudWaitlist({ join }, "[email protected]");
expect(join).toHaveBeenCalledExactlyOnceWith({ emailAddress: "[email protected]" });
});
it("preserves Clerk rejection details without exposing the email address", async () => {
const cause = Object.assign(new Error("The enrollment was rejected."), {
code: "form_identifier_invalid",
});
const join = vi.fn().mockResolvedValue({ error: cause });
const failure = await joinCloudWaitlist({ join }, "[email protected]").catch(
(error: unknown) => error,
);
expect(failure).toBeInstanceOf(CloudWaitlistJoinRejectedError);
expect(failure).toMatchObject({
code: "form_identifier_invalid",
cause,
});
expect(String(failure)).not.toContain("[email protected]");
});
it("distinguishes request failures from rejected enrollments", async () => {
const cause = new Error("network unavailable");
const join = vi.fn().mockRejectedValue(cause);
const failure = await joinCloudWaitlist({ join }, "[email protected]").catch(
(error: unknown) => error,
);
expect(failure).toBeInstanceOf(CloudWaitlistJoinRequestError);
expect(failure).toMatchObject({ cause });
expect(failure).not.toBeInstanceOf(CloudWaitlistJoinRejectedError);
});
});
@@ -0,0 +1,46 @@
import * as Schema from "effect/Schema";
interface CloudWaitlistJoiner {
readonly join: (input: { emailAddress: string }) => Promise<{
readonly error: { readonly code: string } | null;
}>;
}
export class CloudWaitlistJoinRejectedError extends Schema.TaggedErrorClass<CloudWaitlistJoinRejectedError>()(
"CloudWaitlistJoinRejectedError",
{
code: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Cloud waitlist enrollment was rejected with code "${this.code}".`;
}
}
export class CloudWaitlistJoinRequestError extends Schema.TaggedErrorClass<CloudWaitlistJoinRequestError>()(
"CloudWaitlistJoinRequestError",
{
cause: Schema.Defect(),
},
) {
override get message(): string {
return "Cloud waitlist enrollment request failed.";
}
}
export async function joinCloudWaitlist(
waitlist: CloudWaitlistJoiner,
emailAddress: string,
): Promise<void> {
const result = await waitlist.join({ emailAddress }).catch((cause) => {
throw new CloudWaitlistJoinRequestError({ cause });
});
if (result.error) {
throw new CloudWaitlistJoinRejectedError({
code: result.error.code,
cause: result.error,
});
}
}
@@ -1,5 +1,7 @@
import { expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Logger from "effect/Logger";
import * as SecureStore from "expo-secure-store";
import { vi } from "vite-plus/test";
const secureStore = vi.hoisted(() => new Map<string, string>());
@@ -16,7 +18,10 @@ vi.mock("expo-secure-store", () => ({
}),
}));
import { managedRelayAccessTokenStore } from "./managedRelayTokenStore";
import {
ManagedRelayTokenStoreError,
managedRelayAccessTokenStore,
} from "./managedRelayTokenStore";
it.effect("round-trips and clears persisted managed relay access tokens", () =>
Effect.gen(function* () {
@@ -49,3 +54,32 @@ it.effect("falls back to an empty cache when persisted data is invalid", () =>
expect(yield* managedRelayAccessTokenStore.load).toEqual([]);
}),
);
it.effect("logs structured storage failures before falling back to an empty cache", () => {
const messages: Array<unknown> = [];
const logger = Logger.make(({ message }) => {
messages.push(message);
});
const cause = new Error("secure store unavailable");
vi.mocked(SecureStore.getItemAsync).mockRejectedValueOnce(cause);
return Effect.gen(function* () {
expect(yield* managedRelayAccessTokenStore.load).toEqual([]);
const message = messages.find(
(candidate) =>
Array.isArray(candidate) && candidate[0] === "Managed relay token store operation failed.",
);
expect(message).toBeDefined();
const context = (message as ReadonlyArray<unknown>)[1] as {
readonly cause: ManagedRelayTokenStoreError;
};
expect(context.cause).toBeInstanceOf(ManagedRelayTokenStoreError);
expect(context.cause).toMatchObject({
operation: "read",
storageKey: "t3code.cloud.relay-access-tokens",
cause,
});
expect(context.cause.message).not.toContain(cause.message);
}).pipe(Effect.provide(Logger.layer([logger], { mergeWithExisting: false })));
});
@@ -1,5 +1,4 @@
import { ManagedRelay } from "@t3tools/client-runtime/relay";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import * as SecureStore from "expo-secure-store";
@@ -31,36 +30,50 @@ const decodeManagedRelayAccessTokenCache = Schema.decodeUnknownEffect(
);
const encodeManagedRelayAccessTokenCache = Schema.encodeEffect(ManagedRelayAccessTokenCacheSchema);
export class ManagedRelayTokenStoreError extends Data.TaggedError("ManagedRelayTokenStoreError")<{
readonly message: string;
readonly cause: unknown;
}> {}
export class ManagedRelayTokenStoreError extends Schema.TaggedErrorClass<ManagedRelayTokenStoreError>()(
"ManagedRelayTokenStoreError",
{
operation: Schema.Literals(["read", "decode", "encode", "write", "clear"]),
storageKey: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Managed relay token store operation "${this.operation}" failed for key "${this.storageKey}".`;
}
}
const storeError =
(message: string) =>
(cause: unknown): ManagedRelayTokenStoreError =>
new ManagedRelayTokenStoreError({ message, cause });
function logStoreFailure(operation: string) {
return (error: ManagedRelayTokenStoreError) =>
Effect.logWarning(`Managed relay token store ${operation} failed.`).pipe(
Effect.annotateLogs({
errorTag: error._tag,
message: error.message,
}),
);
function logStoreFailure(error: ManagedRelayTokenStoreError) {
return Effect.logWarning("Managed relay token store operation failed.", {
errorTag: error._tag,
operation: error.operation,
storageKey: error.storageKey,
cause: error,
});
}
const loadManagedRelayAccessTokens = Effect.tryPromise({
try: () => SecureStore.getItemAsync(MANAGED_RELAY_TOKEN_CACHE_KEY),
catch: storeError("Could not read persisted relay access tokens."),
catch: (cause) =>
new ManagedRelayTokenStoreError({
operation: "read",
storageKey: MANAGED_RELAY_TOKEN_CACHE_KEY,
cause,
}),
}).pipe(
Effect.flatMap((encoded) =>
encoded === null
? Effect.succeed<ReadonlyArray<ManagedRelay.ManagedRelayAccessTokenCacheEntry>>([])
: decodeManagedRelayAccessTokenCache(encoded).pipe(
Effect.map((cache) => cache.entries),
Effect.mapError(storeError("Persisted relay access tokens are invalid.")),
Effect.mapError(
(cause) =>
new ManagedRelayTokenStoreError({
operation: "decode",
storageKey: MANAGED_RELAY_TOKEN_CACHE_KEY,
cause,
}),
),
),
),
);
@@ -72,34 +85,48 @@ const saveManagedRelayAccessTokens = (
version: MANAGED_RELAY_TOKEN_CACHE_VERSION,
entries,
}).pipe(
Effect.mapError(storeError("Could not encode relay access tokens.")),
Effect.mapError(
(cause) =>
new ManagedRelayTokenStoreError({
operation: "encode",
storageKey: MANAGED_RELAY_TOKEN_CACHE_KEY,
cause,
}),
),
Effect.flatMap((encoded) =>
Effect.tryPromise({
try: () => SecureStore.setItemAsync(MANAGED_RELAY_TOKEN_CACHE_KEY, encoded),
catch: storeError("Could not persist relay access tokens."),
catch: (cause) =>
new ManagedRelayTokenStoreError({
operation: "write",
storageKey: MANAGED_RELAY_TOKEN_CACHE_KEY,
cause,
}),
}),
),
);
const clearManagedRelayAccessTokens = Effect.tryPromise({
try: () => SecureStore.deleteItemAsync(MANAGED_RELAY_TOKEN_CACHE_KEY),
catch: storeError("Could not clear persisted relay access tokens."),
catch: (cause) =>
new ManagedRelayTokenStoreError({
operation: "clear",
storageKey: MANAGED_RELAY_TOKEN_CACHE_KEY,
cause,
}),
});
export const managedRelayAccessTokenStore: ManagedRelay.ManagedRelayAccessTokenStore = {
load: loadManagedRelayAccessTokens.pipe(
Effect.tapError(logStoreFailure("load")),
Effect.tapError(logStoreFailure),
Effect.orElseSucceed(() => []),
Effect.withSpan("mobile.managedRelayTokenStore.load"),
),
save: Effect.fn("mobile.managedRelayTokenStore.save")((entries) =>
saveManagedRelayAccessTokens(entries).pipe(
Effect.tapError(logStoreFailure("save")),
Effect.ignore,
),
saveManagedRelayAccessTokens(entries).pipe(Effect.tapError(logStoreFailure), Effect.ignore),
),
clear: clearManagedRelayAccessTokens.pipe(
Effect.tapError(logStoreFailure("clear")),
Effect.tapError(logStoreFailure),
Effect.ignore,
Effect.withSpan("mobile.managedRelayTokenStore.clear"),
),
@@ -101,7 +101,7 @@ export function ConnectionEnvironmentRow(props: {
className="underline"
onLongPress={(event) => {
event.stopPropagation();
copyTextWithHaptic(statusTraceId);
copyTextWithHaptic(statusTraceId, { target: "connection-trace-id" });
}}
onPress={(event) => {
event.stopPropagation();
@@ -85,7 +85,11 @@ export function EnvironmentConnectionNotice(props: {
accessibilityHint="Copies the trace ID"
accessibilityRole="button"
className="underline decoration-dotted"
onPress={() => copyTextWithHaptic(props.connection.traceId!)}
onPress={() =>
copyTextWithHaptic(props.connection.traceId!, {
target: "connection-trace-id",
})
}
>
{props.connection.traceId}
</Text>
@@ -8,6 +8,7 @@ import jsxLanguage from "@shikijs/langs/jsx";
import tsxLanguage from "@shikijs/langs/tsx";
import typescriptLanguage from "@shikijs/langs/typescript";
import yamlLanguage from "@shikijs/langs/yaml";
import * as Schema from "effect/Schema";
import type { NativeReviewDiffFile, NativeReviewDiffLanguage } from "./nativeReviewDiffTypes";
import type { NativeReviewDiffRow, NativeReviewDiffToken } from "./nativeReviewDiffSurface";
@@ -15,6 +16,32 @@ import type { NativeReviewDiffRow, NativeReviewDiffToken } from "./nativeReviewD
export type NativeReviewDiffHighlightScheme = "light" | "dark";
export type NativeReviewDiffHighlightEngine = "native" | "javascript";
export class NativeReviewDiffHighlighterUnavailableError extends Schema.TaggedErrorClass<NativeReviewDiffHighlighterUnavailableError>()(
"NativeReviewDiffHighlighterUnavailableError",
{},
) {
override get message(): string {
return "The native review diff highlighter is unavailable in this build.";
}
}
export const isNativeReviewDiffHighlighterUnavailableError = Schema.is(
NativeReviewDiffHighlighterUnavailableError,
);
export class NativeReviewDiffHighlighterInitializationError extends Schema.TaggedErrorClass<NativeReviewDiffHighlighterInitializationError>()(
"NativeReviewDiffHighlighterInitializationError",
{
requestedEngine: Schema.Literals(["native", "javascript"]),
attemptedEngine: Schema.Literals(["native", "javascript"]),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to initialize the ${this.attemptedEngine} review diff highlighter requested as ${this.requestedEngine}.`;
}
}
export interface NativeReviewDiffHighlighterHandle {
readonly engine: NativeReviewDiffHighlightEngine;
readonly tokenize: (
@@ -197,7 +224,7 @@ function normalizeTokens(
async function createNativeReviewDiffHighlighter(): Promise<NativeReviewDiffHighlighterHandle> {
const nativeEngineModule = await import("react-native-shiki-engine");
if (!nativeEngineModule.isNativeEngineAvailable()) {
throw new Error("Native Shiki engine is not available in this build.");
throw new NativeReviewDiffHighlighterUnavailableError();
}
const highlighter = await createHighlighterCore({
@@ -229,18 +256,52 @@ export async function getNativeReviewDiffHighlighter(
engine: NativeReviewDiffHighlightEngine = "native",
): Promise<NativeReviewDiffHighlighterHandle> {
if (engine === "javascript") {
javascriptHighlighterPromise ??= createJavascriptReviewDiffHighlighter();
return javascriptHighlighterPromise;
try {
javascriptHighlighterPromise ??= createJavascriptReviewDiffHighlighter();
return await javascriptHighlighterPromise;
} catch (cause) {
javascriptHighlighterPromise = null;
throw new NativeReviewDiffHighlighterInitializationError({
requestedEngine: engine,
attemptedEngine: "javascript",
cause,
});
}
}
nativeHighlighterPromise ??= createNativeReviewDiffHighlighter().catch((error: unknown) => {
console.warn("[debug-native-diff] native highlighter unavailable", {
error: error instanceof Error ? error.message : String(error),
nativeHighlighterPromise ??= createNativeReviewDiffHighlighter()
.catch(async (cause: unknown) => {
const nativeError = isNativeReviewDiffHighlighterUnavailableError(cause)
? cause
: new NativeReviewDiffHighlighterInitializationError({
requestedEngine: engine,
attemptedEngine: "native",
cause,
});
console.warn("[debug-native-diff] native highlighter unavailable", {
error: nativeError,
});
try {
javascriptHighlighterPromise ??= createJavascriptReviewDiffHighlighter();
return await javascriptHighlighterPromise;
} catch (fallbackCause) {
javascriptHighlighterPromise = null;
throw new NativeReviewDiffHighlighterInitializationError({
requestedEngine: engine,
attemptedEngine: "javascript",
cause: new AggregateError(
[nativeError, fallbackCause],
"Native and JavaScript review diff highlighter initialization failed.",
{ cause: nativeError },
),
});
}
})
.catch((error) => {
nativeHighlighterPromise = null;
throw error;
});
javascriptHighlighterPromise ??= createJavascriptReviewDiffHighlighter();
return javascriptHighlighterPromise;
});
return nativeHighlighterPromise;
return await nativeHighlighterPromise;
}
function isHighlightableLineRow(row: NativeReviewDiffRow): row is NativeReviewDiffLineRow {
@@ -53,11 +53,12 @@ it("initializes review highlighter state once", async () => {
});
it("stores initialization failures in atom state", async () => {
const cause = new Error("load failed");
const manager = createReviewHighlighterManager({
getRegistry: () => registry,
loader: {
prepare: async () => {
throw new Error("load failed");
throw cause;
},
prepareLanguages: async () => undefined,
getEngine: async () => "javascript",
@@ -67,9 +68,23 @@ it("stores initialization failures in atom state", async () => {
void manager.initialize();
await flushAsyncWork();
assert.deepStrictEqual(manager.getSnapshot(), {
engine: null,
error: "load failed",
status: "error",
});
const snapshot = manager.getSnapshot();
assert.strictEqual(snapshot.engine, null);
assert.strictEqual(snapshot.status, "error");
assert.strictEqual(snapshot.error?._tag, "ReviewHighlighterManagerError");
assert.strictEqual(snapshot.error?.operation, "prepare");
assert.deepStrictEqual(snapshot.error?.languages, [
"typescript",
"tsx",
"javascript",
"jsx",
"json",
"yaml",
"bash",
]);
assert.strictEqual(snapshot.error?.cause, cause);
assert.strictEqual(
snapshot.error?.message,
"Review highlighter operation prepare failed for languages typescript, tsx, javascript, jsx, json, yaml, bash.",
);
});
@@ -1,4 +1,5 @@
import { useAtomValue } from "@effect/atom-react";
import * as Schema from "effect/Schema";
import { Atom, type AtomRegistry } from "effect/unstable/reactivity";
import { useEffect } from "react";
@@ -12,9 +13,22 @@ import {
export type ReviewHighlighterStatus = "idle" | "initializing" | "ready" | "error";
export class ReviewHighlighterManagerError extends Schema.TaggedErrorClass<ReviewHighlighterManagerError>()(
"ReviewHighlighterManagerError",
{
operation: Schema.Literals(["prepare", "prepare-languages", "resolve-engine"]),
languages: Schema.Array(Schema.String),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Review highlighter operation ${this.operation} failed for languages ${this.languages.join(", ")}.`;
}
}
export interface ReviewHighlighterState {
readonly engine: ReviewHighlighterEngine | null;
readonly error: string | null;
readonly error: ReviewHighlighterManagerError | null;
readonly status: ReviewHighlighterStatus;
}
@@ -101,24 +115,35 @@ export function createReviewHighlighterManager(config: {
inFlight = (async () => {
const startedAt = performance.now();
const languages = config.languages ?? REVIEW_INITIAL_LANGUAGES;
let operation: ReviewHighlighterManagerError["operation"] = "prepare";
let engine: ReviewHighlighterEngine;
try {
await config.loader.prepare();
await config.loader.prepareLanguages(config.languages ?? REVIEW_INITIAL_LANGUAGES);
const engine = await config.loader.getEngine();
const durationMs = Math.round(performance.now() - startedAt);
logReviewHighlighterProviderDiagnostic("initialized", {
durationMs,
engine,
operation = "prepare-languages";
await config.loader.prepareLanguages(languages);
operation = "resolve-engine";
engine = await config.loader.getEngine();
} catch (cause) {
const error = new ReviewHighlighterManagerError({
operation,
languages,
cause,
});
setState({ engine, error: null, status: "ready" });
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
logReviewHighlighterProviderDiagnostic("initialization failed", { error: message });
setState({ engine: null, error: message, status: "error" });
} finally {
inFlight = null;
logReviewHighlighterProviderDiagnostic("initialization failed", { error });
setState({ engine: null, error, status: "error" });
return;
}
})();
const durationMs = Math.round(performance.now() - startedAt);
logReviewHighlighterProviderDiagnostic("initialized", {
durationMs,
engine,
});
setState({ engine, error: null, status: "ready" });
})().finally(() => {
inFlight = null;
});
return inFlight;
}
@@ -10,6 +10,7 @@ import yamlLanguage from "@shikijs/langs/yaml";
import githubDarkDefault from "@shikijs/themes/github-dark-default";
import githubLightDefault from "@shikijs/themes/github-light-default";
import { getFiletypeFromFileName } from "@pierre/diffs/utils/getFiletypeFromFileName";
import * as Schema from "effect/Schema";
import {
resolveReviewHighlighterEngine,
@@ -22,6 +23,19 @@ import { applyDiffRangesToTokens, computeWordAltDiffRanges } from "./reviewWordD
export type ReviewDiffTheme = "light" | "dark";
export type { ReviewHighlighterEngine };
export class ReviewHighlighterEngineInitializationError extends Schema.TaggedErrorClass<ReviewHighlighterEngineInitializationError>()(
"ReviewHighlighterEngineInitializationError",
{
preferredEngine: Schema.Literals(["native", "javascript"]),
attemptedEngine: Schema.Literals(["native", "javascript"]),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to initialize the ${this.attemptedEngine} review highlighter with ${this.preferredEngine} preferred.`;
}
}
export interface ReviewHighlightedToken {
content: string;
readonly color: string | null;
@@ -227,16 +241,6 @@ function logReviewHighlighterDiagnosticError(message: string, error: unknown): v
if (!isReviewHighlighterDebugLoggingEnabled()) {
return;
}
if (error instanceof Error) {
console.error(`[review-highlighter] ${message}`, {
name: error.name,
message: error.message,
stack: error.stack,
});
return;
}
console.error(`[review-highlighter] ${message}`, error);
}
@@ -258,6 +262,7 @@ async function getHighlighter(): Promise<HighlighterCore> {
if (!highlighterPromise) {
const configuredHighlighterPromise = (async () => {
let nativeEngineAvailable = false;
let nativeInitializationError: ReviewHighlighterEngineInitializationError | undefined;
logReviewHighlighterDiagnostic("initializing", {
configuredPreference: REVIEW_HIGHLIGHTER_ENGINE_ENV_VALUE,
@@ -289,9 +294,14 @@ async function getHighlighter(): Promise<HighlighterCore> {
};
}
} catch (error) {
nativeInitializationError = new ReviewHighlighterEngineInitializationError({
preferredEngine: REVIEW_HIGHLIGHTER_ENGINE_PREFERENCE,
attemptedEngine: "native",
cause: error,
});
logReviewHighlighterDiagnosticError(
"native engine initialization failed; falling back to javascript",
error,
nativeInitializationError,
);
nativeEngineAvailable = false;
}
@@ -305,11 +315,30 @@ async function getHighlighter(): Promise<HighlighterCore> {
REVIEW_HIGHLIGHTER_ENGINE_PREFERENCE,
nativeEngineAvailable,
);
const highlighter = await createHighlighterCore({
themes,
langs: REVIEW_INITIAL_LANGUAGE_MODULES,
engine: createJavaScriptRegexEngine(),
});
let highlighter: HighlighterCore;
try {
highlighter = await createHighlighterCore({
themes,
langs: REVIEW_INITIAL_LANGUAGE_MODULES,
engine: createJavaScriptRegexEngine(),
});
} catch (cause) {
const javascriptError = new ReviewHighlighterEngineInitializationError({
preferredEngine: REVIEW_HIGHLIGHTER_ENGINE_PREFERENCE,
attemptedEngine: "javascript",
cause,
});
if (!nativeInitializationError) throw javascriptError;
throw new ReviewHighlighterEngineInitializationError({
preferredEngine: REVIEW_HIGHLIGHTER_ENGINE_PREFERENCE,
attemptedEngine: "javascript",
cause: new AggregateError(
[nativeInitializationError, javascriptError],
"Native and JavaScript review highlighter initialization failed.",
{ cause: nativeInitializationError },
),
});
}
logReviewHighlighterDiagnostic("using javascript engine", {
resolvedEngine: engine,
});
@@ -108,7 +108,11 @@ export function useNativeReviewDiffHighlighting(input: {
} catch (error) {
if (!abortController.signal.aborted) {
logReviewDiffDiagnostic("native visible highlight failed", {
error: error instanceof Error ? error.message : String(error),
error,
resetKey,
scheme,
firstRowIndex: requestRange.firstRowIndex,
lastRowIndex: requestRange.lastRowIndex,
});
}
}
@@ -30,7 +30,9 @@ import {
resolveProviderOptionDescriptors,
} from "../../lib/providerOptions";
import { buildThreadRoutePath } from "../../lib/routes";
import { scopedProjectKey } from "../../lib/scopedEntities";
import { MOBILE_TYPOGRAPHY } from "../../lib/typography";
import { getComposerDraftSnapshot } from "../../state/use-composer-drafts";
import { useProjects } from "../../state/entities";
import { branchBadgeLabel, useNewTaskFlow } from "./new-task-flow-provider";
import { useCreateProjectThread } from "./use-project-actions";
@@ -63,6 +65,7 @@ export function NewTaskDraftScreen(props: {
const controlsBottomPadding = isKeyboardVisible ? 8 : Math.max(insets.bottom, 10);
const { logicalProjects, selectedProject, setProject } = flow;
const promptInputRef = useRef<ComposerEditorHandle>(null);
const loadedBranchesProjectKeyRef = useRef<string | null>(null);
const borderColor = useThemeColor("--color-border");
const sheetFadeOpaque = colorScheme === "dark" ? "rgba(14,14,14,0.98)" : "rgba(242,242,247,0.98)";
@@ -78,6 +81,12 @@ export function NewTaskDraftScreen(props: {
) ?? null;
if (directProject) {
if (
selectedProject?.environmentId === directProject.environmentId &&
selectedProject.id === directProject.id
) {
return;
}
setProject(directProject);
return;
}
@@ -105,10 +114,16 @@ export function NewTaskDraftScreen(props: {
useEffect(() => {
if (!selectedProject) {
loadedBranchesProjectKeyRef.current = null;
return;
}
const projectKey = `${selectedProject.environmentId}:${selectedProject.id}`;
if (loadedBranchesProjectKeyRef.current === projectKey) {
return;
}
loadedBranchesProjectKeyRef.current = projectKey;
void flow.loadBranches();
}, [flow, selectedProject]);
}, [flow.loadBranches, selectedProject]);
useEffect(() => {
if (!selectedProject) {
@@ -292,11 +307,7 @@ export function NewTaskDraftScreen(props: {
if (!event.startsWith("model:")) {
return;
}
// Defer state update so the native menu dismiss animation completes
// before re-rendering the menu actions (prevents submenu jump).
setTimeout(() => {
flow.setSelectedModelKey(event.slice("model:".length));
}, 150);
flow.setSelectedModelKey(event.slice("model:".length));
}
function handleEnvironmentMenuAction(event: string) {
@@ -366,27 +377,42 @@ export function NewTaskDraftScreen(props: {
);
async function handleStart(): Promise<void> {
const selectedProject = flow.selectedProject;
if (!selectedProject) {
return;
}
const draft = getComposerDraftSnapshot(
`new-task:${scopedProjectKey(selectedProject.environmentId, selectedProject.id)}`,
);
const modelSelection = draft.modelSelection ?? flow.selectedModel;
const workspaceMode = draft.workspaceSelection?.mode ?? flow.workspaceMode;
const selectedBranchName = draft.workspaceSelection?.branch ?? flow.selectedBranchName;
const selectedWorktreePath =
draft.workspaceSelection?.worktreePath ?? flow.selectedWorktreePath;
const runtimeMode = draft.runtimeMode ?? flow.runtimeMode;
const interactionMode = draft.interactionMode ?? flow.interactionMode;
const initialMessageText = draft.text.trim();
if (
!flow.selectedProject ||
!flow.selectedModel ||
flow.prompt.trim().length === 0 ||
!modelSelection ||
initialMessageText.length === 0 ||
flow.submitting ||
(flow.workspaceMode === "worktree" && !flow.selectedBranchName)
(workspaceMode === "worktree" && !selectedBranchName)
) {
return;
}
flow.setSubmitting(true);
const result = await createProjectThread({
project: flow.selectedProject,
modelSelection: flow.selectedModel,
envMode: flow.workspaceMode,
branch: flow.selectedBranchName,
worktreePath: flow.workspaceMode === "worktree" ? null : flow.selectedWorktreePath,
runtimeMode: flow.runtimeMode,
interactionMode: flow.interactionMode,
initialMessageText: flow.prompt.trim(),
initialAttachments: flow.attachments,
project: selectedProject,
modelSelection,
envMode: workspaceMode,
branch: selectedBranchName,
worktreePath: workspaceMode === "worktree" ? null : selectedWorktreePath,
runtimeMode,
interactionMode,
initialMessageText,
initialAttachments: draft.attachments,
});
flow.setSubmitting(false);
@@ -1,4 +1,3 @@
import * as Clipboard from "expo-clipboard";
import * as Haptics from "expo-haptics";
import { KeyboardAvoidingLegendList } from "@legendapp/list/keyboard";
import { type LegendListRef } from "@legendapp/list/react-native";
@@ -31,6 +30,7 @@ import { TouchableOpacity } from "react-native-gesture-handler";
import ImageViewing from "react-native-image-viewing";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useThemeColor } from "../../lib/useThemeColor";
import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
import {
hasNativeSelectableMarkdownText,
SelectableMarkdownText,
@@ -1321,8 +1321,10 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
}, []);
const onCopyWorkRow = useCallback((rowId: string, value: string) => {
void Clipboard.setStringAsync(value);
void Haptics.selectionAsync();
copyTextWithHaptic(value, {
target: "thread-work-row",
feedback: "selection",
});
setInteractionState((current) => ({ ...current, copiedRowId: rowId }));
if (copyFeedbackTimeoutRef.current) {
clearTimeout(copyFeedbackTimeoutRef.current);
@@ -1,13 +1,7 @@
import { Stack, useLocalSearchParams, useRouter } from "expo-router";
import { useCallback, useMemo, useState } from "react";
import * as Option from "effect/Option";
import {
EnvironmentId,
type ModelSelection,
type ProjectScript,
type ProviderInteractionMode,
type RuntimeMode,
} from "@t3tools/contracts";
import { EnvironmentId, type ProjectScript } from "@t3tools/contracts";
import { projectScriptCwd, projectScriptRuntimeEnv } from "@t3tools/shared/projectScripts";
import { Pressable, ScrollView, Text as RNText, View } from "react-native";
import { useWorkspaceState } from "../../state/workspace";
@@ -79,18 +73,6 @@ export function ThreadRouteScreen() {
const gitState = useSelectedThreadGitState();
const gitActions = useSelectedThreadGitActions();
const requests = useSelectedThreadRequests();
const updateThreadMetadata = useAtomCommand(
threadEnvironment.updateMetadata,
"thread metadata update",
);
const setThreadRuntimeMode = useAtomCommand(
threadEnvironment.setRuntimeMode,
"thread runtime mode",
);
const setThreadInteractionMode = useAtomCommand(
threadEnvironment.setInteractionMode,
"thread interaction mode",
);
const interruptThreadTurn = useAtomCommand(threadEnvironment.interruptTurn, "thread interrupt");
const router = useRouter();
const params = useLocalSearchParams<{
@@ -105,6 +87,18 @@ export function ThreadRouteScreen() {
const routeConnectionState =
routeEnvironmentRuntime?.connectionState ?? (environmentId ? "available" : connectionState);
const routeConnectionError = routeEnvironmentRuntime?.connectionError ?? null;
const selectedThreadWithDraftSettings = useMemo(
() =>
selectedThread
? {
...selectedThread,
modelSelection: composer.modelSelection ?? selectedThread.modelSelection,
runtimeMode: composer.runtimeMode ?? selectedThread.runtimeMode,
interactionMode: composer.interactionMode ?? selectedThread.interactionMode,
}
: null,
[composer.interactionMode, composer.modelSelection, composer.runtimeMode, selectedThread],
);
/* ─── Native header theming ──────────────────────────────────────── */
const iconColor = String(useThemeColor("--color-icon"));
@@ -157,51 +151,6 @@ export function ThreadRouteScreen() {
const handleOpenConnectionEditor = useCallback(() => {
void router.push("/connections");
}, [router]);
const handleUpdateThreadModelSelection = useCallback(
(modelSelection: ModelSelection) => {
if (!selectedThread) {
return;
}
return updateThreadMetadata({
environmentId: selectedThread.environmentId,
input: {
threadId: selectedThread.id,
modelSelection,
},
});
},
[selectedThread, updateThreadMetadata],
);
const handleUpdateThreadRuntimeMode = useCallback(
(runtimeMode: RuntimeMode) => {
if (!selectedThread) {
return;
}
return setThreadRuntimeMode({
environmentId: selectedThread.environmentId,
input: {
threadId: selectedThread.id,
runtimeMode,
},
});
},
[selectedThread, setThreadRuntimeMode],
);
const handleUpdateThreadInteractionMode = useCallback(
(interactionMode: ProviderInteractionMode) => {
if (!selectedThread) {
return;
}
return setThreadInteractionMode({
environmentId: selectedThread.environmentId,
input: {
threadId: selectedThread.id,
interactionMode,
},
});
},
[selectedThread, setThreadInteractionMode],
);
const handleStopThread = useCallback(() => {
if (
!selectedThread ||
@@ -435,7 +384,7 @@ export function ThreadRouteScreen() {
<View className="flex-1 bg-screen">
<ThreadDetailScreen
selectedThread={selectedThread}
selectedThread={selectedThreadWithDraftSettings ?? selectedThread}
contentPresentation={contentPresentation}
screenTone={connectionTone(routeConnectionState)}
connectionError={routeConnectionError}
@@ -466,9 +415,9 @@ export function ThreadRouteScreen() {
onStopThread={handleStopThread}
onSendMessage={composer.onSendMessage}
onReconnectEnvironment={handleReconnectEnvironment}
onUpdateThreadModelSelection={handleUpdateThreadModelSelection}
onUpdateThreadRuntimeMode={handleUpdateThreadRuntimeMode}
onUpdateThreadInteractionMode={handleUpdateThreadInteractionMode}
onUpdateThreadModelSelection={composer.onUpdateModelSelection}
onUpdateThreadRuntimeMode={composer.onUpdateRuntimeMode}
onUpdateThreadInteractionMode={composer.onUpdateInteractionMode}
onRespondToApproval={requests.onRespondToApproval}
onSelectUserInputOption={requests.onSelectUserInputOption}
onChangeUserInputCustomAnswer={requests.onChangeUserInputCustomAnswer}
@@ -1,4 +1,4 @@
import React, { useCallback, useMemo, useRef, useState } from "react";
import React, { useCallback, useEffect, useMemo, useState } from "react";
import type {
EnvironmentId,
@@ -23,6 +23,7 @@ import {
removeComposerDraftAttachment,
replaceComposerDraftAttachments,
setComposerDraftText,
updateComposerDraftSettings,
useComposerDraft,
} from "../../state/use-composer-drafts";
import { useBranches } from "../../state/queries";
@@ -158,34 +159,15 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
? selectedEnvironmentIdOverride
: (projects[0]?.environmentId ?? null);
const [selectedProjectKey, setSelectedProjectKey] = useState<string | null>(null);
const [selectedModelKey, setSelectedModelKey] = useState<string | null>(null);
const [workspaceMode, setWorkspaceMode] = useState<WorkspaceMode>("local");
const [selectedBranchName, setSelectedBranchName] = useState<string | null>(null);
const [selectedWorktreePath, setSelectedWorktreePath] = useState<string | null>(null);
const branchLoadVersionRef = useRef(0);
const [submitting, setSubmitting] = useState(false);
const [branchQuery, setBranchQuery] = useState("");
const [runtimeMode, setRuntimeMode] = useState<RuntimeMode>(DEFAULT_RUNTIME_MODE);
const [interactionMode, setInteractionMode] = useState<ProviderInteractionMode>(
DEFAULT_PROVIDER_INTERACTION_MODE,
);
const [modelSelectionOverrides, setModelSelectionOverrides] = useState<
Record<string, ModelSelection>
>({});
const [expandedProvider, setExpandedProvider] = useState<string | null>(null);
const reset = useCallback(() => {
setSelectedEnvironmentId(null);
setSelectedProjectKey(null);
setSelectedModelKey(null);
setWorkspaceMode("local");
setSelectedBranchName(null);
setSelectedWorktreePath(null);
setSubmitting(false);
setBranchQuery("");
setRuntimeMode(DEFAULT_RUNTIME_MODE);
setInteractionMode(DEFAULT_PROVIDER_INTERACTION_MODE);
setModelSelectionOverrides({});
setExpandedProvider(null);
}, []);
@@ -247,33 +229,33 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
const selectedProjectDraft = useComposerDraft(selectedProjectDraftKey);
const prompt = selectedProjectDraft.text;
const attachments = selectedProjectDraft.attachments;
const workspaceMode = selectedProjectDraft.workspaceSelection?.mode ?? "local";
const selectedBranchName = selectedProjectDraft.workspaceSelection?.branch ?? null;
const selectedWorktreePath = selectedProjectDraft.workspaceSelection?.worktreePath ?? null;
const runtimeMode = selectedProjectDraft.runtimeMode ?? DEFAULT_RUNTIME_MODE;
const interactionMode = selectedProjectDraft.interactionMode ?? DEFAULT_PROVIDER_INTERACTION_MODE;
const modelOptions = useMemo(
() =>
buildModelOptions(
selectedEnvironmentServerConfig,
selectedProject?.defaultModelSelection ?? null,
selectedProjectDraft.modelSelection ?? selectedProject?.defaultModelSelection ?? null,
),
[selectedEnvironmentServerConfig, selectedProject?.defaultModelSelection],
[
selectedEnvironmentServerConfig,
selectedProject?.defaultModelSelection,
selectedProjectDraft.modelSelection,
],
);
const defaultModelKey = selectedProject?.defaultModelSelection
? `${selectedProject.defaultModelSelection.instanceId}:${selectedProject.defaultModelSelection.model}`
: null;
const baseSelectedModel =
modelOptions.find((option) => option.key === selectedModelKey)?.selection ??
(defaultModelKey
? modelOptions.find((option) => option.key === defaultModelKey)?.selection
: null) ??
const selectedModel =
selectedProjectDraft.modelSelection ??
selectedProject?.defaultModelSelection ??
modelOptions[0]?.selection ??
null;
const selectedModelIdentity = baseSelectedModel
? `${baseSelectedModel.instanceId}:${baseSelectedModel.model}`
const selectedModelKey = selectedModel
? `${selectedModel.instanceId}:${selectedModel.model}`
: null;
const selectedModel =
(selectedModelIdentity ? modelSelectionOverrides[selectedModelIdentity] : null) ??
baseSelectedModel;
const selectedModelOption =
modelOptions.find(
@@ -282,13 +264,31 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
option.selection.instanceId === selectedModel.instanceId &&
option.selection.model === selectedModel.model,
) ?? null;
const selectedProviderSkills =
selectedEnvironmentServerConfig?.providers.find(
(provider) => provider.instanceId === selectedModel?.instanceId,
)?.skills ?? [];
const selectedProviderSkills = useMemo(
() =>
selectedEnvironmentServerConfig?.providers.find(
(provider) => provider.instanceId === selectedModel?.instanceId,
)?.skills ?? [],
[selectedEnvironmentServerConfig, selectedModel?.instanceId],
);
const setSelectedModelKey = useCallback(
(key: string | null) => {
if (!key || !selectedProjectDraftKey) {
return;
}
const option = modelOptions.find((candidate) => candidate.key === key);
if (!option) {
return;
}
updateComposerDraftSettings(selectedProjectDraftKey, {
modelSelection: option.selection,
});
},
[modelOptions, selectedProjectDraftKey],
);
const setSelectedModelOptions = useCallback(
(options: ReadonlyArray<ProviderOptionSelection> | undefined) => {
if (!selectedModel || !selectedModelIdentity) {
if (!selectedModel || !selectedProjectDraftKey) {
return;
}
const nextSelection: ModelSelection = options
@@ -297,12 +297,11 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
instanceId: selectedModel.instanceId,
model: selectedModel.model,
};
setModelSelectionOverrides((current) => ({
...current,
[selectedModelIdentity]: nextSelection,
}));
updateComposerDraftSettings(selectedProjectDraftKey, {
modelSelection: nextSelection,
});
},
[selectedModel, selectedModelIdentity],
[selectedModel, selectedProjectDraftKey],
);
const providerGroups = useMemo(() => groupByProvider(modelOptions), [modelOptions]);
@@ -381,62 +380,85 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
const setProject = useCallback((project: EnvironmentProject) => {
const nextProjectKey = scopedProjectKey(project.environmentId, project.id);
branchLoadVersionRef.current += 1;
setSelectedEnvironmentId(project.environmentId);
setSelectedProjectKey(nextProjectKey);
setSelectedBranchName(null);
setSelectedWorktreePath(null);
setModelSelectionOverrides({});
}, []);
const selectEnvironment = useCallback((environmentId: EnvironmentId) => {
branchLoadVersionRef.current += 1;
setSelectedEnvironmentId(environmentId);
setSelectedProjectKey(null);
setSelectedBranchName(null);
setSelectedWorktreePath(null);
setModelSelectionOverrides({});
}, []);
const setWorkspaceMode = useCallback(
(mode: WorkspaceMode) => {
if (!selectedProjectDraftKey) {
return;
}
updateComposerDraftSettings(selectedProjectDraftKey, {
workspaceSelection: {
mode,
branch: selectedBranchName,
worktreePath: selectedWorktreePath,
},
});
},
[selectedBranchName, selectedProjectDraftKey, selectedWorktreePath],
);
const selectBranch = useCallback(
(branch: VcsRef) => {
setSelectedBranchName(branch.name);
setSelectedWorktreePath(
selectedProject ? normalizeSelectedWorktreePath(selectedProject, branch) : null,
);
if (!selectedProject || !selectedProjectDraftKey) {
return;
}
updateComposerDraftSettings(selectedProjectDraftKey, {
workspaceSelection: {
mode: workspaceMode,
branch: branch.name,
worktreePath: normalizeSelectedWorktreePath(selectedProject, branch),
},
});
},
[selectedProject],
[selectedProject, selectedProjectDraftKey, workspaceMode],
);
const refreshBranches = branchState.refresh;
const loadBranches = useCallback(async () => {
if (!selectedProject) {
return;
}
setPendingConnectionError(null);
refreshBranches();
}, [refreshBranches, selectedProject]);
const loadVersion = ++branchLoadVersionRef.current;
const projectKey = scopedProjectKey(selectedProject.environmentId, selectedProject.id);
branchState.refresh();
if (loadVersion !== branchLoadVersionRef.current || selectedProjectKey !== projectKey) {
useEffect(() => {
if (workspaceMode !== "worktree" || selectedBranchName !== null) {
return;
}
setPendingConnectionError(null);
if (workspaceMode === "worktree" && !selectedBranchName) {
const preferredBranch =
availableBranches.find((branch) => branch.current)?.name ??
availableBranches.find((branch) => branch.isDefault)?.name ??
null;
if (preferredBranch) {
setSelectedBranchName(preferredBranch);
}
const preferredBranch =
availableBranches.find((branch) => branch.current) ??
availableBranches.find((branch) => branch.isDefault) ??
null;
if (preferredBranch) {
selectBranch(preferredBranch);
}
}, [
availableBranches,
branchState,
selectedBranchName,
selectedProject,
selectedProjectKey,
workspaceMode,
]);
}, [availableBranches, selectBranch, selectedBranchName, workspaceMode]);
const setRuntimeMode = useCallback(
(value: RuntimeMode) => {
if (selectedProjectDraftKey) {
updateComposerDraftSettings(selectedProjectDraftKey, { runtimeMode: value });
}
},
[selectedProjectDraftKey],
);
const setInteractionMode = useCallback(
(value: ProviderInteractionMode) => {
if (selectedProjectDraftKey) {
updateComposerDraftSettings(selectedProjectDraftKey, { interactionMode: value });
}
},
[selectedProjectDraftKey],
);
const value = useMemo<NewTaskFlowContextValue>(
() => ({
@@ -513,6 +535,11 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
setProject,
selectBranch,
selectEnvironment,
setInteractionMode,
setPrompt,
setRuntimeMode,
setSelectedModelKey,
setWorkspaceMode,
submitting,
workspaceMode,
appendAttachments,
@@ -0,0 +1,11 @@
import * as Schema from "effect/Schema";
export const DraftComposerImageAttachmentSchema = Schema.Struct({
id: Schema.String,
previewUri: Schema.String,
type: Schema.Literal("image"),
name: Schema.String,
mimeType: Schema.String,
sizeBytes: Schema.Number,
dataUrl: Schema.String,
});
+58 -2
View File
@@ -1,7 +1,8 @@
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
const mocks = vi.hoisted(() => ({
impactAsync: vi.fn(),
selectionAsync: vi.fn(),
setStringAsync: vi.fn(),
}));
@@ -14,15 +15,25 @@ vi.mock("expo-haptics", () => ({
Light: "light",
},
impactAsync: mocks.impactAsync,
selectionAsync: mocks.selectionAsync,
}));
import { copyTextWithHaptic } from "./copyTextWithHaptic";
import {
CopyTextClipboardWriteError,
CopyTextHapticFeedbackError,
copyTextWithHaptic,
} from "./copyTextWithHaptic";
describe("copyTextWithHaptic", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.setStringAsync.mockReturnValue(new Promise<void>(() => undefined));
mocks.impactAsync.mockResolvedValue(undefined);
mocks.selectionAsync.mockResolvedValue(undefined);
});
afterEach(() => {
vi.restoreAllMocks();
});
it("triggers haptic feedback without waiting for the clipboard promise", () => {
@@ -31,4 +42,49 @@ describe("copyTextWithHaptic", () => {
expect(mocks.setStringAsync).toHaveBeenCalledWith("trace-123");
expect(mocks.impactAsync).toHaveBeenCalledWith("light");
});
it("preserves selection feedback for thread work rows", () => {
copyTextWithHaptic("work output", {
target: "thread-work-row",
feedback: "selection",
});
expect(mocks.setStringAsync).toHaveBeenCalledWith("work output");
expect(mocks.selectionAsync).toHaveBeenCalledOnce();
expect(mocks.impactAsync).not.toHaveBeenCalled();
});
it("reports structured failures without including clipboard contents", async () => {
const clipboardCause = new Error("native clipboard failure");
const hapticCause = new Error("native haptic failure");
const consoleError = vi.spyOn(console, "error").mockImplementation(() => undefined);
mocks.setStringAsync.mockRejectedValueOnce(clipboardCause);
mocks.impactAsync.mockRejectedValueOnce(hapticCause);
copyTextWithHaptic("secret clipboard contents", { target: "connection-trace-id" });
await vi.waitFor(() => {
expect(consoleError).toHaveBeenCalledTimes(2);
});
const failures = consoleError.mock.calls.map(([failure]) => failure);
const clipboardError = failures.find(
(failure) => failure instanceof CopyTextClipboardWriteError,
);
expect(clipboardError).toBeInstanceOf(CopyTextClipboardWriteError);
expect(clipboardError).toMatchObject({
target: "connection-trace-id",
cause: clipboardCause,
});
expect((clipboardError as Error).message).not.toContain("secret clipboard contents");
const hapticError = failures.find((failure) => failure instanceof CopyTextHapticFeedbackError);
expect(hapticError).toBeInstanceOf(CopyTextHapticFeedbackError);
expect(hapticError).toMatchObject({
target: "connection-trace-id",
feedback: "light-impact",
cause: hapticCause,
});
expect((hapticError as Error).message).not.toContain("secret clipboard contents");
});
});
+66 -3
View File
@@ -1,7 +1,70 @@
import * as Schema from "effect/Schema";
import * as Clipboard from "expo-clipboard";
import * as Haptics from "expo-haptics";
export function copyTextWithHaptic(value: string): void {
void Clipboard.setStringAsync(value);
void Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light);
export class CopyTextClipboardWriteError extends Schema.TaggedErrorClass<CopyTextClipboardWriteError>()(
"CopyTextClipboardWriteError",
{
target: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to copy ${this.target} to the clipboard.`;
}
}
export class CopyTextHapticFeedbackError extends Schema.TaggedErrorClass<CopyTextHapticFeedbackError>()(
"CopyTextHapticFeedbackError",
{
target: Schema.String,
feedback: Schema.Literals(["light-impact", "selection"]),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to trigger ${this.feedback} haptic feedback after copying ${this.target}.`;
}
}
export function copyTextWithHaptic(
value: string,
options: {
readonly target?: string;
readonly feedback?: "light-impact" | "selection";
} = {},
): void {
const target = options.target ?? "text";
const feedback = options.feedback ?? "light-impact";
void (async () => {
try {
await Clipboard.setStringAsync(value);
} catch (cause) {
console.error(
new CopyTextClipboardWriteError({
target,
cause,
}),
);
}
})();
void (async () => {
try {
if (feedback === "selection") {
await Haptics.selectionAsync();
} else {
await Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light);
}
} catch (cause) {
console.error(
new CopyTextHapticFeedbackError({
target,
feedback,
cause,
}),
);
}
})();
}
+78 -9
View File
@@ -1,4 +1,5 @@
import type { EnvironmentId, MessageId } from "@t3tools/contracts";
import { EnvironmentId, MessageId, ThreadId } from "@t3tools/contracts";
import * as Schema from "effect/Schema";
import { Atom, type AtomRegistry } from "effect/unstable/reactivity";
import {
@@ -8,6 +9,27 @@ import {
} from "./thread-outbox-model";
import type { ThreadOutboxStorage } from "./thread-outbox-storage";
export class ThreadOutboxManagerError extends Schema.TaggedErrorClass<ThreadOutboxManagerError>()(
"ThreadOutboxManagerError",
{
operation: Schema.Literals([
"load",
"enqueue",
"remove",
"clear-environment-load",
"clear-environment-remove",
]),
environmentId: Schema.NullOr(EnvironmentId),
threadId: Schema.NullOr(ThreadId),
messageId: Schema.NullOr(MessageId),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Thread outbox operation ${this.operation} failed for environment ${this.environmentId ?? "unknown"}, thread ${this.threadId ?? "unknown"}, message ${this.messageId ?? "unknown"}.`;
}
}
export interface ThreadOutboxManagerOptions {
readonly registry: AtomRegistry.AtomRegistry;
readonly storage: ThreadOutboxStorage;
@@ -49,22 +71,51 @@ export function createThreadOutboxManager(options: ThreadOutboxManagerOptions) {
loadPromise = serialize(async () => {
const persistedMessages = await options.storage.load();
setMessages([...persistedMessages, ...currentMessages()]);
}).catch((error) => {
}).catch((cause) => {
loadPromise = null;
warn("[thread-outbox] failed to load persisted messages", error);
warn(
"[thread-outbox] failed to load persisted messages",
new ThreadOutboxManagerError({
operation: "load",
environmentId: null,
threadId: null,
messageId: null,
cause,
}),
);
});
return loadPromise;
};
const enqueue = (message: QueuedThreadMessage): Promise<void> =>
serialize(async () => {
await options.storage.write(message);
try {
await options.storage.write(message);
} catch (cause) {
throw new ThreadOutboxManagerError({
operation: "enqueue",
environmentId: message.environmentId,
threadId: message.threadId,
messageId: message.messageId,
cause,
});
}
setMessages([...currentMessages(), message]);
});
const remove = (message: QueuedThreadMessage): Promise<void> =>
serialize(async () => {
await options.storage.remove(message);
try {
await options.storage.remove(message);
} catch (cause) {
throw new ThreadOutboxManagerError({
operation: "remove",
environmentId: message.environmentId,
threadId: message.threadId,
messageId: message.messageId,
cause,
});
}
setMessages(
currentMessages().filter((candidate) => candidate.messageId !== message.messageId),
);
@@ -72,8 +123,17 @@ export function createThreadOutboxManager(options: ThreadOutboxManagerOptions) {
const clearEnvironment = (environmentId: EnvironmentId): Promise<void> =>
serialize(async () => {
const persisted = await options.storage.load().catch((error) => {
warn("[thread-outbox] failed to load messages while clearing environment", error);
const persisted = await options.storage.load().catch((cause) => {
warn(
"[thread-outbox] failed to load messages while clearing environment",
new ThreadOutboxManagerError({
operation: "clear-environment-load",
environmentId,
threadId: null,
messageId: null,
cause,
}),
);
return [];
});
const allMessages = flattenQueuedThreadMessages(
@@ -88,8 +148,17 @@ export function createThreadOutboxManager(options: ThreadOutboxManagerOptions) {
try {
await options.storage.remove(message);
removedMessageIds.add(message.messageId);
} catch (error) {
warn("[thread-outbox] failed to clear persisted message", error);
} catch (cause) {
warn(
"[thread-outbox] failed to clear persisted message",
new ThreadOutboxManagerError({
operation: "clear-environment-remove",
environmentId: message.environmentId,
threadId: message.threadId,
messageId: message.messageId,
cause,
}),
);
}
}),
);
+65 -13
View File
@@ -1,32 +1,38 @@
import { isTransportConnectionErrorMessage } from "@t3tools/client-runtime/errors";
import type { EnvironmentShellStatus } from "@t3tools/client-runtime/state/shell";
import { CommandId, EnvironmentId, IsoDateTime, MessageId, ThreadId } from "@t3tools/contracts";
import {
CommandId,
EnvironmentId,
IsoDateTime,
MessageId,
ModelSelection,
ProviderInteractionMode,
RuntimeMode,
ThreadId,
type ModelSelection as ModelSelectionType,
type ProviderInteractionMode as ProviderInteractionModeType,
type RuntimeMode as RuntimeModeType,
} from "@t3tools/contracts";
import * as Schema from "effect/Schema";
import { DraftComposerImageAttachmentSchema } from "../lib/composer-image-schema";
import type { DraftComposerImageAttachment } from "../lib/composerImages";
import { scopedThreadKey } from "../lib/scopedEntities";
const THREAD_OUTBOX_SCHEMA_VERSION = 1;
const THREAD_OUTBOX_SCHEMA_VERSION = 2;
const THREAD_OUTBOX_MAX_RETRY_DELAY_MS = 16_000;
const DraftComposerImageAttachmentSchema = Schema.Struct({
id: Schema.String,
previewUri: Schema.String,
type: Schema.Literal("image"),
name: Schema.String,
mimeType: Schema.String,
sizeBytes: Schema.Number,
dataUrl: Schema.String,
});
export const QueuedThreadMessageSchema = Schema.Struct({
schemaVersion: Schema.Literal(THREAD_OUTBOX_SCHEMA_VERSION),
schemaVersion: Schema.Literals([1, THREAD_OUTBOX_SCHEMA_VERSION]),
environmentId: EnvironmentId,
threadId: ThreadId,
messageId: MessageId,
commandId: CommandId,
text: Schema.String,
attachments: Schema.Array(DraftComposerImageAttachmentSchema),
modelSelection: Schema.optional(ModelSelection),
runtimeMode: Schema.optional(RuntimeMode),
interactionMode: Schema.optional(ProviderInteractionMode),
createdAt: IsoDateTime,
});
@@ -40,9 +46,37 @@ export interface QueuedThreadMessage {
readonly commandId: CommandId;
readonly text: string;
readonly attachments: ReadonlyArray<DraftComposerImageAttachment>;
readonly modelSelection?: ModelSelectionType;
readonly runtimeMode?: RuntimeModeType;
readonly interactionMode?: ProviderInteractionModeType;
readonly createdAt: string;
}
export interface ThreadSettingsSnapshot {
readonly modelSelection: ModelSelectionType;
readonly runtimeMode: RuntimeModeType;
readonly interactionMode: ProviderInteractionModeType;
}
export function resolveQueuedThreadSettings(
message: QueuedThreadMessage,
thread: ThreadSettingsSnapshot,
): ThreadSettingsSnapshot {
return {
modelSelection: message.modelSelection ?? thread.modelSelection,
runtimeMode: message.runtimeMode ?? thread.runtimeMode,
interactionMode: message.interactionMode ?? thread.interactionMode,
};
}
export function modelSelectionsEqual(left: ModelSelectionType, right: ModelSelectionType): boolean {
return (
left.instanceId === right.instanceId &&
left.model === right.model &&
JSON.stringify(left.options ?? null) === JSON.stringify(right.options ?? null)
);
}
export function encodeQueuedThreadMessage(message: QueuedThreadMessage): unknown {
return encodeStoredQueuedThreadMessage({
schemaVersion: THREAD_OUTBOX_SCHEMA_VERSION,
@@ -119,3 +153,21 @@ export function shouldRetryThreadOutboxDelivery(error: unknown): boolean {
}
return isTransportConnectionErrorMessage(errorMessage(error));
}
export type ThreadOutboxCommandStage = "settings-sync" | "start-turn";
export type ThreadOutboxFailureAction = "retry" | "discard";
export function resolveThreadOutboxFailureAction(input: {
readonly stage: ThreadOutboxCommandStage;
readonly error: unknown;
readonly interrupted: boolean;
}): ThreadOutboxFailureAction {
if (
input.stage === "settings-sync" ||
input.interrupted ||
shouldRetryThreadOutboxDelivery(input.error)
) {
return "retry";
}
return "discard";
}
+80 -18
View File
@@ -1,4 +1,5 @@
import type { MessageId } from "@t3tools/contracts";
import { EnvironmentId, MessageId, ThreadId } from "@t3tools/contracts";
import * as Schema from "effect/Schema";
import {
decodeQueuedThreadMessage,
@@ -8,6 +9,22 @@ import {
const THREAD_OUTBOX_DIRECTORY = "thread-outbox";
export class ThreadOutboxStorageError extends Schema.TaggedErrorClass<ThreadOutboxStorageError>()(
"ThreadOutboxStorageError",
{
operation: Schema.Literals(["load", "read-message", "write", "remove"]),
environmentId: Schema.NullOr(EnvironmentId),
threadId: Schema.NullOr(ThreadId),
messageId: Schema.NullOr(MessageId),
fileName: Schema.NullOr(Schema.String),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Thread outbox storage operation ${this.operation} failed for environment ${this.environmentId ?? "unknown"}, thread ${this.threadId ?? "unknown"}, message ${this.messageId ?? "unknown"}, file ${this.fileName ?? "unknown"}.`;
}
}
export interface ThreadOutboxStorage {
readonly load: () => Promise<ReadonlyArray<QueuedThreadMessage>>;
readonly write: (message: QueuedThreadMessage) => Promise<void>;
@@ -32,33 +49,78 @@ async function getMessageFile(messageId: MessageId) {
export const expoThreadOutboxStorage: ThreadOutboxStorage = {
load: async () => {
const { File } = await import("expo-file-system");
const directory = await getOutboxDirectory();
const messages: QueuedThreadMessage[] = [];
try {
const { File } = await import("expo-file-system");
const directory = await getOutboxDirectory();
for (const entry of directory.list()) {
if (!(entry instanceof File) || !entry.name.endsWith(".json")) {
continue;
}
try {
messages.push(decodeQueuedThreadMessage(JSON.parse(await entry.text()) as unknown));
} catch (error) {
console.warn("[thread-outbox] ignored invalid persisted message", entry.name, error);
for (const entry of directory.list()) {
if (!(entry instanceof File) || !entry.name.endsWith(".json")) {
continue;
}
try {
messages.push(decodeQueuedThreadMessage(JSON.parse(await entry.text()) as unknown));
} catch (cause) {
console.warn(
"[thread-outbox] ignored invalid persisted message",
new ThreadOutboxStorageError({
operation: "read-message",
environmentId: null,
threadId: null,
messageId: null,
fileName: entry.name,
cause,
}),
);
}
}
} catch (cause) {
throw new ThreadOutboxStorageError({
operation: "load",
environmentId: null,
threadId: null,
messageId: null,
fileName: null,
cause,
});
}
return messages;
},
write: async (message) => {
const file = await getMessageFile(message.messageId);
if (!file.exists) {
file.create({ intermediates: true, overwrite: true });
const fileName = messageFileName(message.messageId);
try {
const file = await getMessageFile(message.messageId);
if (!file.exists) {
file.create({ intermediates: true, overwrite: true });
}
file.write(JSON.stringify(encodeQueuedThreadMessage(message)));
} catch (cause) {
throw new ThreadOutboxStorageError({
operation: "write",
environmentId: message.environmentId,
threadId: message.threadId,
messageId: message.messageId,
fileName,
cause,
});
}
file.write(JSON.stringify(encodeQueuedThreadMessage(message)));
},
remove: async (message) => {
const file = await getMessageFile(message.messageId);
if (file.exists) {
file.delete();
const fileName = messageFileName(message.messageId);
try {
const file = await getMessageFile(message.messageId);
if (file.exists) {
file.delete();
}
} catch (cause) {
throw new ThreadOutboxStorageError({
operation: "remove",
environmentId: message.environmentId,
threadId: message.threadId,
messageId: message.messageId,
fileName,
cause,
});
}
},
};
+128 -4
View File
@@ -1,16 +1,26 @@
import { describe, expect, it } from "@effect/vitest";
import { CommandId, EnvironmentId, MessageId, ThreadId } from "@t3tools/contracts";
import {
CommandId,
EnvironmentId,
MessageId,
ProviderInstanceId,
ThreadId,
} from "@t3tools/contracts";
import { AtomRegistry } from "effect/unstable/reactivity";
import {
decodeQueuedThreadMessage,
encodeQueuedThreadMessage,
groupQueuedThreadMessages,
modelSelectionsEqual,
resolveThreadOutboxDeliveryAction,
resolveThreadOutboxFailureAction,
resolveQueuedThreadSettings,
shouldRetryThreadOutboxDelivery,
threadOutboxRetryDelayMs,
type QueuedThreadMessage,
} from "./thread-outbox-model";
import { createThreadOutboxManager } from "./thread-outbox-manager";
import { createThreadOutboxManager, ThreadOutboxManagerError } from "./thread-outbox-manager";
import type { ThreadOutboxStorage } from "./thread-outbox-storage";
function queuedMessage(input: {
@@ -66,6 +76,54 @@ describe("thread outbox", () => {
).toThrow();
});
it("persists the exact selector snapshot while remaining compatible with v1 messages", () => {
const legacyMessage = queuedMessage({
messageId: "message-1",
createdAt: "2026-06-08T10:00:01.000Z",
});
const selectedMessage = {
...legacyMessage,
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5.4",
options: [{ id: "reasoningEffort", value: "xhigh" }],
},
runtimeMode: "approval-required",
interactionMode: "plan",
} satisfies QueuedThreadMessage;
expect(decodeQueuedThreadMessage(encodeQueuedThreadMessage(selectedMessage))).toEqual(
selectedMessage,
);
expect(
resolveQueuedThreadSettings(legacyMessage, {
modelSelection: selectedMessage.modelSelection,
runtimeMode: selectedMessage.runtimeMode,
interactionMode: selectedMessage.interactionMode,
}),
).toEqual({
modelSelection: selectedMessage.modelSelection,
runtimeMode: selectedMessage.runtimeMode,
interactionMode: selectedMessage.interactionMode,
});
});
it("compares model options as part of the queued settings change", () => {
const base = {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5.4",
options: [{ id: "reasoningEffort", value: "medium" }],
} as const;
expect(modelSelectionsEqual(base, base)).toBe(true);
expect(
modelSelectionsEqual(base, {
...base,
options: [{ id: "reasoningEffort", value: "xhigh" }],
}),
).toBe(false);
});
it("backs off queued delivery retries and caps them at sixteen seconds", () => {
expect([1, 2, 3, 4, 5, 6].map(threadOutboxRetryDelayMs)).toEqual([
1_000, 2_000, 4_000, 8_000, 16_000, 16_000,
@@ -149,9 +207,48 @@ describe("thread outbox", () => {
registry.dispose();
});
it("reports structured load failures and permits a retry", async () => {
const registry = AtomRegistry.make();
const loadCause = new Error("storage unavailable");
const warnings: Array<{ message: string; error: unknown }> = [];
let loadCalls = 0;
const manager = createThreadOutboxManager({
registry,
storage: {
load: async () => {
loadCalls += 1;
if (loadCalls === 1) throw loadCause;
return [];
},
write: async () => undefined,
remove: async () => undefined,
},
warn: (message, error) => warnings.push({ message, error }),
});
await manager.load();
expect(warnings).toEqual([
{
message: "[thread-outbox] failed to load persisted messages",
error: new ThreadOutboxManagerError({
operation: "load",
environmentId: null,
threadId: null,
messageId: null,
cause: loadCause,
}),
},
]);
await manager.load();
expect(loadCalls).toBe(2);
registry.dispose();
});
it("keeps atom state aligned with durable writes and removals", async () => {
const registry = AtomRegistry.make();
const stored = new Map<MessageId, QueuedThreadMessage>();
const removalCause = new Error("remove failed");
let failRemoval = true;
const storage: ThreadOutboxStorage = {
load: async () => [...stored.values()],
@@ -160,7 +257,7 @@ describe("thread outbox", () => {
},
remove: async (message) => {
if (failRemoval) {
throw new Error("remove failed");
throw removalCause;
}
stored.delete(message.messageId);
},
@@ -176,7 +273,15 @@ describe("thread outbox", () => {
"environment-1:thread-1": [message],
});
await expect(manager.remove(message)).rejects.toThrow("remove failed");
await expect(manager.remove(message)).rejects.toEqual(
new ThreadOutboxManagerError({
operation: "remove",
environmentId: message.environmentId,
threadId: message.threadId,
messageId: message.messageId,
cause: removalCause,
}),
);
expect(registry.get(manager.queuedMessagesByThreadKeyAtom)).toEqual({
"environment-1:thread-1": [message],
});
@@ -224,4 +329,23 @@ describe("thread outbox", () => {
).toBe(true);
expect(shouldRetryThreadOutboxDelivery(new Error("Thread no longer exists"))).toBe(false);
});
it("retains queued messages when settings synchronization fails before startTurn", () => {
const deterministicFailure = new Error("Thread no longer exists");
expect(
resolveThreadOutboxFailureAction({
stage: "settings-sync",
error: deterministicFailure,
interrupted: false,
}),
).toBe("retry");
expect(
resolveThreadOutboxFailureAction({
stage: "start-turn",
error: deterministicFailure,
interrupted: false,
}),
).toBe("discard");
});
});
@@ -1,14 +1,136 @@
import { describe, expect, it } from "@effect/vitest";
import { EnvironmentId } from "@t3tools/contracts";
import { afterEach, describe, expect, it } from "@effect/vitest";
import { EnvironmentId, ProviderInstanceId } from "@t3tools/contracts";
import { type ComposerDraft, removeComposerDraftsForEnvironment } from "./use-composer-drafts";
import { appAtomRegistry } from "./atom-registry";
import {
clearComposerDraftContentState,
composerDraftsAtom,
decodePersistedComposerDrafts,
type ComposerDraft,
getComposerDraftSnapshot,
removeComposerDraftsForEnvironment,
} from "./use-composer-drafts";
const DRAFT: ComposerDraft = {
text: "hello",
attachments: [],
};
afterEach(() => {
appAtomRegistry.set(composerDraftsAtom, {});
});
describe("mobile composer drafts", () => {
it("hydrates selector state even when the message content is empty", () => {
expect(
decodePersistedComposerDrafts({
schemaVersion: 1,
drafts: {
"new-task:environment-1:project-1": {
text: "",
attachments: [],
modelSelection: {
instanceId: "codex",
model: "gpt-5.4",
options: [{ id: "reasoningEffort", value: "xhigh" }],
},
runtimeMode: "approval-required",
interactionMode: "plan",
workspaceSelection: {
mode: "worktree",
branch: "main",
worktreePath: null,
},
},
},
}),
).toEqual({
"new-task:environment-1:project-1": {
text: "",
attachments: [],
modelSelection: {
instanceId: "codex",
model: "gpt-5.4",
options: [{ id: "reasoningEffort", value: "xhigh" }],
},
runtimeMode: "approval-required",
interactionMode: "plan",
workspaceSelection: {
mode: "worktree",
branch: "main",
worktreePath: null,
},
},
});
});
it("keeps legacy content-only drafts and rejects invalid selector state", () => {
expect(
decodePersistedComposerDrafts({
schemaVersion: 1,
drafts: {
"environment-1:thread-1": DRAFT,
},
}),
).toEqual({
"environment-1:thread-1": DRAFT,
});
expect(() =>
decodePersistedComposerDrafts({
schemaVersion: 1,
drafts: {
"environment-1:thread-1": {
...DRAFT,
runtimeMode: "sometimes-safe",
},
},
}),
).toThrow();
});
it("clears sent content without clearing the selected model or workspace", () => {
const draftKey = "environment-1:thread-1";
const draft: ComposerDraft = {
text: "send this",
attachments: [],
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5.4",
options: [{ id: "reasoningEffort", value: "xhigh" }],
},
workspaceSelection: {
mode: "worktree",
branch: "main",
worktreePath: null,
},
};
expect(clearComposerDraftContentState({ [draftKey]: draft }, draftKey)).toEqual({
[draftKey]: {
...draft,
text: "",
attachments: [],
},
});
});
it("reads the latest selector state synchronously for send", () => {
const draftKey = "environment-1:thread-1";
const selectedDraft: ComposerDraft = {
text: "send this",
attachments: [],
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5.4",
options: [{ id: "reasoningEffort", value: "xhigh" }],
},
};
appAtomRegistry.set(composerDraftsAtom, { [draftKey]: selectedDraft });
expect(getComposerDraftSnapshot(draftKey)).toEqual(selectedDraft);
});
it("removes only drafts owned by the selected environment", () => {
const environmentId = EnvironmentId.make("environment-cloud");
const retainedEnvironmentId = EnvironmentId.make("environment-local");
@@ -17,12 +139,15 @@ describe("mobile composer drafts", () => {
removeComposerDraftsForEnvironment(
{
[`${environmentId}:thread-cloud`]: DRAFT,
[`new-task:${environmentId}:project-cloud`]: DRAFT,
[`${retainedEnvironmentId}:thread-local`]: DRAFT,
[`new-task:${retainedEnvironmentId}:project-local`]: DRAFT,
},
environmentId,
),
).toEqual({
[`${retainedEnvironmentId}:thread-local`]: DRAFT,
[`new-task:${retainedEnvironmentId}:project-local`]: DRAFT,
});
});
});
+124 -22
View File
@@ -1,9 +1,18 @@
import { useAtomValue } from "@effect/atom-react";
import type { EnvironmentId } from "@t3tools/contracts";
import {
ModelSelection as ModelSelectionSchema,
ProviderInteractionMode as ProviderInteractionModeSchema,
RuntimeMode as RuntimeModeSchema,
type EnvironmentId,
type ModelSelection,
type ProviderInteractionMode,
type RuntimeMode,
} from "@t3tools/contracts";
import * as Schema from "effect/Schema";
import { useEffect } from "react";
import { Atom } from "effect/unstable/reactivity";
import { DraftComposerImageAttachmentSchema } from "../lib/composer-image-schema";
import type { DraftComposerImageAttachment } from "../lib/composerImages";
import { appAtomRegistry } from "./atom-registry";
@@ -29,13 +38,47 @@ export class ComposerDraftPersistenceError extends Schema.TaggedErrorClass<Compo
export interface ComposerDraft {
readonly text: string;
readonly attachments: ReadonlyArray<DraftComposerImageAttachment>;
readonly modelSelection?: ModelSelection;
readonly runtimeMode?: RuntimeMode;
readonly interactionMode?: ProviderInteractionMode;
readonly workspaceSelection?: ComposerDraftWorkspaceSelection;
}
interface PersistedComposerDrafts {
readonly schemaVersion: typeof COMPOSER_DRAFTS_SCHEMA_VERSION;
readonly drafts: Record<string, ComposerDraft>;
export interface ComposerDraftWorkspaceSelection {
readonly mode: "local" | "worktree";
readonly branch: string | null;
readonly worktreePath: string | null;
}
export type ComposerDraftSettingsUpdate = Pick<
ComposerDraft,
"modelSelection" | "runtimeMode" | "interactionMode" | "workspaceSelection"
>;
const ComposerDraftWorkspaceSelectionSchema = Schema.Struct({
mode: Schema.Literals(["local", "worktree"]),
branch: Schema.NullOr(Schema.String),
worktreePath: Schema.NullOr(Schema.String),
});
const ComposerDraftSchema = Schema.Struct({
text: Schema.String,
attachments: Schema.Array(DraftComposerImageAttachmentSchema),
modelSelection: Schema.optional(ModelSelectionSchema),
runtimeMode: Schema.optional(RuntimeModeSchema),
interactionMode: Schema.optional(ProviderInteractionModeSchema),
workspaceSelection: Schema.optional(ComposerDraftWorkspaceSelectionSchema),
});
const PersistedComposerDraftsSchema = Schema.Struct({
schemaVersion: Schema.Literal(COMPOSER_DRAFTS_SCHEMA_VERSION),
drafts: Schema.Record(Schema.String, ComposerDraftSchema),
});
const decodePersistedComposerDraftsDocument = Schema.decodeUnknownSync(
PersistedComposerDraftsSchema,
);
const EMPTY_DRAFT: ComposerDraft = {
text: "",
attachments: [],
@@ -54,13 +97,32 @@ function normalizeDraft(draft: ComposerDraft | undefined): ComposerDraft {
return EMPTY_DRAFT;
}
return {
...draft,
text: draft.text,
attachments: draft.attachments,
};
}
export function getComposerDraftSnapshot(draftKey: string): ComposerDraft {
return normalizeDraft(appAtomRegistry.get(composerDraftsAtom)[draftKey]);
}
function isEmptyDraft(draft: ComposerDraft): boolean {
return draft.text.length === 0 && draft.attachments.length === 0;
return (
draft.text.length === 0 &&
draft.attachments.length === 0 &&
draft.modelSelection === undefined &&
draft.runtimeMode === undefined &&
draft.interactionMode === undefined &&
draft.workspaceSelection === undefined
);
}
export function decodePersistedComposerDrafts(value: unknown): Record<string, ComposerDraft> {
const parsed = decodePersistedComposerDraftsDocument(value);
return Object.fromEntries(
Object.entries(parsed.drafts).filter(([, draft]) => !isEmptyDraft(draft)),
);
}
async function getComposerDraftsFile() {
@@ -80,20 +142,7 @@ async function loadPersistedComposerDrafts(): Promise<Record<string, ComposerDra
operation = "read";
const raw = await file.text();
operation = "decode";
const parsed = JSON.parse(raw) as Partial<PersistedComposerDrafts>;
if (parsed.schemaVersion !== COMPOSER_DRAFTS_SCHEMA_VERSION || !parsed.drafts) {
return {};
}
return Object.fromEntries(
Object.entries(parsed.drafts).filter((entry): entry is [string, ComposerDraft] => {
const draft = entry[1];
return (
typeof draft?.text === "string" &&
Array.isArray(draft.attachments) &&
!isEmptyDraft(draft)
);
}),
);
return decodePersistedComposerDrafts(JSON.parse(raw) as unknown);
} catch (cause) {
console.warn(
"[composer-drafts] ignored persisted draft failure",
@@ -116,10 +165,10 @@ async function writePersistedComposerDrafts(drafts: Record<string, ComposerDraft
const nonEmptyDrafts = Object.fromEntries(
Object.entries(drafts).filter(([, draft]) => !isEmptyDraft(draft)),
);
const document: PersistedComposerDrafts = {
const document = {
schemaVersion: COMPOSER_DRAFTS_SCHEMA_VERSION,
drafts: nonEmptyDrafts,
};
} as const;
const encoded = JSON.stringify(document);
operation = "write";
if (!file.exists) {
@@ -282,6 +331,55 @@ export function removeComposerDraftAttachment(draftKey: string, imageId: string)
});
}
export function updateComposerDraftSettings(
draftKey: string,
settings: Partial<ComposerDraftSettingsUpdate>,
): void {
updateComposerDrafts((current) => {
const draft = {
...normalizeDraft(current[draftKey]),
...settings,
};
if (isEmptyDraft(draft)) {
const next = { ...current };
delete next[draftKey];
return next;
}
return {
...current,
[draftKey]: draft,
};
});
}
export function clearComposerDraftContentState(
current: Record<string, ComposerDraft>,
draftKey: string,
): Record<string, ComposerDraft> {
const existing = current[draftKey];
if (!existing) {
return current;
}
const draft = {
...existing,
text: "",
attachments: [],
};
if (isEmptyDraft(draft)) {
const next = { ...current };
delete next[draftKey];
return next;
}
return {
...current,
[draftKey]: draft,
};
}
export function clearComposerDraftContent(draftKey: string): void {
updateComposerDrafts((current) => clearComposerDraftContentState(current, draftKey));
}
export function clearComposerDraft(draftKey: string): void {
updateComposerDrafts((current) => {
if (!current[draftKey]) {
@@ -298,8 +396,12 @@ export function removeComposerDraftsForEnvironment(
environmentId: EnvironmentId,
): Record<string, ComposerDraft> {
const environmentPrefix = `${environmentId}:`;
const newTaskPrefix = `new-task:${environmentId}:`;
return Object.fromEntries(
Object.entries(drafts).filter(([draftKey]) => !draftKey.startsWith(environmentPrefix)),
Object.entries(drafts).filter(
([draftKey]) =>
!draftKey.startsWith(environmentPrefix) && !draftKey.startsWith(newTaskPrefix),
),
);
}
@@ -1,7 +1,15 @@
import { useAtomValue } from "@effect/atom-react";
import { useCallback, useEffect, useMemo } from "react";
import { CommandId, MessageId, type EnvironmentId, type ThreadId } from "@t3tools/contracts";
import {
CommandId,
MessageId,
type EnvironmentId,
type ModelSelection,
type ProviderInteractionMode,
type RuntimeMode,
type ThreadId,
} from "@t3tools/contracts";
import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors";
import { deriveActiveWorkStartedAt } from "@t3tools/shared/orchestrationTiming";
@@ -18,11 +26,13 @@ import { appAtomRegistry } from "../state/atom-registry";
import {
appendComposerDraftAttachments,
appendComposerDraftText,
clearComposerDraft,
clearComposerDraftContent,
composerDraftsAtom,
ensureComposerDraftsLoaded,
getComposerDraftSnapshot,
removeComposerDraftAttachment,
setComposerDraftText,
updateComposerDraftSettings,
useComposerDraft,
} from "./use-composer-drafts";
import { setPendingConnectionError } from "../state/use-remote-environment-registry";
@@ -98,6 +108,10 @@ export function useThreadComposerState() {
const draftMessage = selectedDraft?.text ?? "";
const draftAttachments = selectedDraft?.attachments ?? [];
const selectedThreadQueueCount = selectedThreadQueuedMessages.length;
const selectedThread = selectedThreadDetail ?? selectedThreadShell;
const modelSelection = selectedDraft?.modelSelection ?? selectedThread?.modelSelection ?? null;
const runtimeMode = selectedDraft?.runtimeMode ?? selectedThread?.runtimeMode ?? null;
const interactionMode = selectedDraft?.interactionMode ?? selectedThread?.interactionMode ?? null;
const selectedThreadSessionActivity = useMemo(() => {
const selectedThread = selectedThreadDetail ?? selectedThreadShell;
@@ -130,7 +144,6 @@ export function useThreadComposerState() {
selectedThreadShell,
]);
const selectedThread = selectedThreadDetail ?? selectedThreadShell;
const activeThreadBusy =
!!selectedThread &&
(selectedThread.session?.status === "running" || selectedThread.session?.status === "starting");
@@ -141,9 +154,10 @@ export function useThreadComposerState() {
}
const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
const draft = composerDrafts[threadKey];
const text = (draft?.text ?? "").trim();
const attachments = draft?.attachments ?? [];
const draft = getComposerDraftSnapshot(threadKey);
const thread = selectedThreadDetail ?? selectedThreadShell;
const text = draft.text.trim();
const attachments = draft.attachments;
if (text.length === 0 && attachments.length === 0) {
return;
}
@@ -157,15 +171,18 @@ export function useThreadComposerState() {
commandId: CommandId.make(metadata.commandId),
text,
attachments,
modelSelection: draft.modelSelection ?? thread.modelSelection,
runtimeMode: draft.runtimeMode ?? thread.runtimeMode,
interactionMode: draft.interactionMode ?? thread.interactionMode,
createdAt: metadata.createdAt,
});
clearComposerDraft(threadKey);
clearComposerDraftContent(threadKey);
} catch (error) {
setPendingConnectionError(
error instanceof Error ? error.message : "Failed to save the queued message.",
);
}
}, [composerDrafts, selectedThreadShell]);
}, [selectedThreadDetail, selectedThreadShell]);
const onChangeDraftMessage = useCallback(
(value: string) => {
@@ -255,12 +272,45 @@ export function useThreadComposerState() {
[selectedThreadShell],
);
const onUpdateModelSelection = useCallback(
(value: ModelSelection) => {
if (!selectedThreadKey) {
return;
}
updateComposerDraftSettings(selectedThreadKey, { modelSelection: value });
},
[selectedThreadKey],
);
const onUpdateRuntimeMode = useCallback(
(value: RuntimeMode) => {
if (!selectedThreadKey) {
return;
}
updateComposerDraftSettings(selectedThreadKey, { runtimeMode: value });
},
[selectedThreadKey],
);
const onUpdateInteractionMode = useCallback(
(value: ProviderInteractionMode) => {
if (!selectedThreadKey) {
return;
}
updateComposerDraftSettings(selectedThreadKey, { interactionMode: value });
},
[selectedThreadKey],
);
return {
selectedThreadFeed,
selectedThreadQueueCount,
activeWorkStartedAt,
draftMessage,
draftAttachments,
modelSelection,
runtimeMode,
interactionMode,
activeThreadBusy,
onChangeDraftMessage,
onPickDraftImages,
@@ -268,5 +318,8 @@ export function useThreadComposerState() {
onNativePasteImages,
onRemoveDraftImage,
onSendMessage,
onUpdateModelSelection,
onUpdateRuntimeMode,
onUpdateInteractionMode,
};
}
+116 -33
View File
@@ -1,6 +1,7 @@
import { useAtomValue } from "@effect/atom-react";
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
import { type MessageId } from "@t3tools/contracts";
import type { AtomCommandResult } from "@t3tools/client-runtime/state/runtime";
import { CommandId, type MessageId } from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import { AsyncResult, Atom } from "effect/unstable/reactivity";
import { useCallback, useEffect, useRef, useState } from "react";
@@ -10,10 +11,13 @@ import { appAtomRegistry } from "./atom-registry";
import { useThreadShells } from "./entities";
import { ensureThreadOutboxLoaded, removeThreadOutboxMessage } from "./thread-outbox";
import {
modelSelectionsEqual,
resolveThreadOutboxDeliveryAction,
shouldRetryThreadOutboxDelivery,
resolveThreadOutboxFailureAction,
resolveQueuedThreadSettings,
threadOutboxRetryDelayMs,
type QueuedThreadMessage,
type ThreadOutboxCommandStage,
} from "./thread-outbox-model";
import { threadEnvironment } from "./threads";
import { useAtomCommand } from "./use-atom-command";
@@ -44,8 +48,21 @@ function findThread(
);
}
function settingsCommandId(message: QueuedThreadMessage, setting: string): CommandId {
return CommandId.make(`${message.commandId}:${setting}`);
}
export function useThreadOutboxDrain(): void {
const startTurn = useAtomCommand(threadEnvironment.startTurn, { reportFailure: false });
const updateThreadMetadata = useAtomCommand(threadEnvironment.updateMetadata, {
reportFailure: false,
});
const setThreadRuntimeMode = useAtomCommand(threadEnvironment.setRuntimeMode, {
reportFailure: false,
});
const setThreadInteractionMode = useAtomCommand(threadEnvironment.setInteractionMode, {
reportFailure: false,
});
const dispatchingQueuedMessageId = useAtomValue(dispatchingQueuedMessageIdAtom);
const queuedMessagesByThreadKey = useThreadOutboxMessages();
const shellStatuses = useThreadOutboxShellStatuses();
@@ -68,6 +85,98 @@ export function useThreadOutboxDrain(): void {
const sendQueuedMessage = useCallback(
async (queuedMessage: QueuedThreadMessage, thread: EnvironmentThreadShell) => {
const settings = resolveQueuedThreadSettings(queuedMessage, thread);
const reportFailure = (
commandResult: AtomCommandResult<unknown, unknown>,
stage: ThreadOutboxCommandStage,
): boolean => {
if (!AsyncResult.isFailure(commandResult)) {
return false;
}
const action = resolveThreadOutboxFailureAction({
stage,
error: Cause.squash(commandResult.cause),
interrupted: Cause.hasInterruptsOnly(commandResult.cause),
});
const retry = action === "retry";
console.warn("[thread-outbox] queued message delivery failed", {
environmentId: queuedMessage.environmentId,
threadId: queuedMessage.threadId,
messageId: queuedMessage.messageId,
stage,
cause: commandResult.cause,
retry,
});
return retry;
};
const completeDelivery = async (
deliveryResult: AtomCommandResult<unknown, unknown>,
): Promise<boolean> => {
if (reportFailure(deliveryResult, "start-turn")) {
return false;
}
try {
await removeThreadOutboxMessage(queuedMessage);
return true;
} catch (error) {
console.warn("[thread-outbox] failed to remove delivered queued message", {
environmentId: queuedMessage.environmentId,
threadId: queuedMessage.threadId,
messageId: queuedMessage.messageId,
error,
});
return false;
}
};
if (!modelSelectionsEqual(settings.modelSelection, thread.modelSelection)) {
const updateResult = await updateThreadMetadata({
environmentId: queuedMessage.environmentId,
input: {
commandId: settingsCommandId(queuedMessage, "model-selection"),
threadId: queuedMessage.threadId,
modelSelection: settings.modelSelection,
},
});
if (AsyncResult.isFailure(updateResult)) {
reportFailure(updateResult, "settings-sync");
return false;
}
}
if (settings.runtimeMode !== thread.runtimeMode) {
const runtimeResult = await setThreadRuntimeMode({
environmentId: queuedMessage.environmentId,
input: {
commandId: settingsCommandId(queuedMessage, "runtime-mode"),
threadId: queuedMessage.threadId,
runtimeMode: settings.runtimeMode,
createdAt: queuedMessage.createdAt,
},
});
if (AsyncResult.isFailure(runtimeResult)) {
reportFailure(runtimeResult, "settings-sync");
return false;
}
}
if (settings.interactionMode !== thread.interactionMode) {
const interactionResult = await setThreadInteractionMode({
environmentId: queuedMessage.environmentId,
input: {
commandId: settingsCommandId(queuedMessage, "interaction-mode"),
threadId: queuedMessage.threadId,
interactionMode: settings.interactionMode,
createdAt: queuedMessage.createdAt,
},
});
if (AsyncResult.isFailure(interactionResult)) {
reportFailure(interactionResult, "settings-sync");
return false;
}
}
const deliveryResult = await startTurn({
environmentId: queuedMessage.environmentId,
input: {
@@ -79,41 +188,15 @@ export function useThreadOutboxDrain(): void {
text: queuedMessage.text,
attachments: queuedMessage.attachments,
},
runtimeMode: thread.runtimeMode,
interactionMode: thread.interactionMode,
modelSelection: settings.modelSelection,
runtimeMode: settings.runtimeMode,
interactionMode: settings.interactionMode,
createdAt: queuedMessage.createdAt,
},
});
if (AsyncResult.isFailure(deliveryResult)) {
const error = Cause.squash(deliveryResult.cause);
const retry =
Cause.hasInterruptsOnly(deliveryResult.cause) || shouldRetryThreadOutboxDelivery(error);
console.warn("[thread-outbox] queued message delivery failed", {
environmentId: queuedMessage.environmentId,
threadId: queuedMessage.threadId,
messageId: queuedMessage.messageId,
cause: deliveryResult.cause,
retry,
});
if (retry) {
return false;
}
}
try {
await removeThreadOutboxMessage(queuedMessage);
return true;
} catch (error) {
console.warn("[thread-outbox] failed to remove delivered queued message", {
environmentId: queuedMessage.environmentId,
threadId: queuedMessage.threadId,
messageId: queuedMessage.messageId,
error,
});
return false;
}
return completeDelivery(deliveryResult);
},
[startTurn],
[setThreadInteractionMode, setThreadRuntimeMode, startTurn, updateThreadMetadata],
);
useEffect(() => {
+19 -24
View File
@@ -1,7 +1,6 @@
#!/usr/bin/env node
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Logger from "effect/Logger";
@@ -20,6 +19,14 @@ import { fromJsonStringPretty } from "@t3tools/shared/schemaJson";
import { fromYaml } from "@t3tools/shared/schemaYaml";
import { resolveSpawnCommand } from "@t3tools/shared/shell";
import serverPackageJson from "../package.json" with { type: "json" };
import {
ServerCliBuildAssetMissingError,
ServerCliCommandExitError,
ServerCliDevelopmentIconSourceMissingError,
ServerCliDevelopmentIconTargetMissingError,
ServerCliPublishIconSourceMissingError,
ServerCliPublishIconTargetMissingError,
} from "./cliErrors.ts";
interface PackageJson {
name: string;
@@ -47,11 +54,6 @@ const WorkspaceConfig = Schema.Struct({
type WorkspaceConfig = typeof WorkspaceConfig.Type;
const decodeWorkspaceConfig = Schema.decodeEffect(fromYaml(WorkspaceConfig));
class CliError extends Data.TaggedError("CliError")<{
readonly message: string;
readonly cause?: unknown;
}> {}
const RepoRoot = Effect.service(Path.Path).pipe(
Effect.flatMap((path) => path.fromFileUrl(new URL("../../..", import.meta.url))),
);
@@ -64,14 +66,17 @@ const readWorkspaceConfig = Effect.fn("readWorkspaceConfig")(function* () {
return yield* decodeWorkspaceConfig(workspaceYaml);
});
const runCommand = Effect.fn("runCommand")(function* (command: ChildProcess.Command) {
const runCommand = Effect.fn("runCommand")(function* (command: ChildProcess.StandardCommand) {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const child = yield* spawner.spawn(command);
const exitCode = yield* child.exitCode;
if (exitCode !== 0) {
return yield* new CliError({
message: `Command exited with non-zero exit code (${exitCode})`,
return yield* new ServerCliCommandExitError({
command: command.command,
args: command.args,
cwd: command.options.cwd,
exitCode,
});
}
});
@@ -95,14 +100,10 @@ const applyPublishIconOverrides = Effect.fn("applyPublishIconOverrides")(functio
const backupPath = `${targetPath}.publish-bak`;
if (!(yield* fs.exists(sourcePath))) {
return yield* new CliError({
message: `Missing publish icon source: ${sourcePath}`,
});
return yield* new ServerCliPublishIconSourceMissingError({ sourcePath });
}
if (!(yield* fs.exists(targetPath))) {
return yield* new CliError({
message: `Missing publish icon target: ${targetPath}. Run the build subcommand first.`,
});
return yield* new ServerCliPublishIconTargetMissingError({ targetPath });
}
yield* fs.copyFile(targetPath, backupPath);
@@ -138,14 +139,10 @@ const applyDevelopmentIconOverrides = Effect.fn("applyDevelopmentIconOverrides")
const targetPath = path.join(serverDir, override.targetRelativePath);
if (!(yield* fs.exists(sourcePath))) {
return yield* new CliError({
message: `Missing development icon source: ${sourcePath}`,
});
return yield* new ServerCliDevelopmentIconSourceMissingError({ sourcePath });
}
if (!(yield* fs.exists(targetPath))) {
return yield* new CliError({
message: `Missing development icon target: ${targetPath}. Build web first.`,
});
return yield* new ServerCliDevelopmentIconTargetMissingError({ targetPath });
}
yield* fs.copyFile(sourcePath, targetPath);
@@ -245,9 +242,7 @@ const publishCmd = Command.make(
for (const relPath of ["dist/bin.mjs", "dist/client/index.html"]) {
const abs = path.join(serverDir, relPath);
if (!(yield* fs.exists(abs))) {
return yield* new CliError({
message: `Missing build asset: ${abs}. Run the build subcommand first.`,
});
return yield* new ServerCliBuildAssetMissingError({ assetPath: abs });
}
}
+31
View File
@@ -0,0 +1,31 @@
import { assert, describe, it } from "@effect/vitest";
import { ServerCliBuildAssetMissingError, ServerCliCommandExitError } from "./cliErrors.ts";
describe("server CLI errors", () => {
it("preserves failed command context without changing its message", () => {
const error = new ServerCliCommandExitError({
command: "vp",
args: ["pm", "publish"],
cwd: "/repo",
exitCode: 17,
});
assert.equal(error._tag, "ServerCliCommandExitError");
assert.equal(error.command, "vp");
assert.deepEqual(error.args, ["pm", "publish"]);
assert.equal(error.cwd, "/repo");
assert.equal(error.exitCode, 17);
assert.equal(error.message, "Command exited with non-zero exit code (17)");
});
it("preserves a representative missing asset path", () => {
const error = new ServerCliBuildAssetMissingError({ assetPath: "/repo/server.mjs" });
assert.equal(error.assetPath, "/repo/server.mjs");
assert.equal(
error.message,
"Missing build asset: /repo/server.mjs. Run the build subcommand first.",
);
});
});
+70
View File
@@ -0,0 +1,70 @@
import * as Schema from "effect/Schema";
export class ServerCliCommandExitError extends Schema.TaggedErrorClass<ServerCliCommandExitError>()(
"ServerCliCommandExitError",
{
command: Schema.String,
args: Schema.Array(Schema.String),
cwd: Schema.optional(Schema.String),
exitCode: Schema.Int,
},
) {
override get message(): string {
return `Command exited with non-zero exit code (${this.exitCode})`;
}
}
export class ServerCliPublishIconSourceMissingError extends Schema.TaggedErrorClass<ServerCliPublishIconSourceMissingError>()(
"ServerCliPublishIconSourceMissingError",
{
sourcePath: Schema.String,
},
) {
override get message(): string {
return `Missing publish icon source: ${this.sourcePath}`;
}
}
export class ServerCliPublishIconTargetMissingError extends Schema.TaggedErrorClass<ServerCliPublishIconTargetMissingError>()(
"ServerCliPublishIconTargetMissingError",
{
targetPath: Schema.String,
},
) {
override get message(): string {
return `Missing publish icon target: ${this.targetPath}. Run the build subcommand first.`;
}
}
export class ServerCliDevelopmentIconSourceMissingError extends Schema.TaggedErrorClass<ServerCliDevelopmentIconSourceMissingError>()(
"ServerCliDevelopmentIconSourceMissingError",
{
sourcePath: Schema.String,
},
) {
override get message(): string {
return `Missing development icon source: ${this.sourcePath}`;
}
}
export class ServerCliDevelopmentIconTargetMissingError extends Schema.TaggedErrorClass<ServerCliDevelopmentIconTargetMissingError>()(
"ServerCliDevelopmentIconTargetMissingError",
{
targetPath: Schema.String,
},
) {
override get message(): string {
return `Missing development icon target: ${this.targetPath}. Build web first.`;
}
}
export class ServerCliBuildAssetMissingError extends Schema.TaggedErrorClass<ServerCliBuildAssetMissingError>()(
"ServerCliBuildAssetMissingError",
{
assetPath: Schema.String,
},
) {
override get message(): string {
return `Missing build asset: ${this.assetPath}. Run the build subcommand first.`;
}
}
+87 -1
View File
@@ -5,6 +5,7 @@ import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import * as ServerConfig from "../config.ts";
@@ -85,7 +86,58 @@ describe("AssetAccess", () => {
},
workspaceRoot: root,
}).pipe(Effect.flip);
expect(error.message).toContain("relative to the project root");
expect(error.message).toBe("Workspace file path must be relative to the project root.");
expect(error).toMatchObject({
_tag: "AssetWorkspacePathValidationError",
resource: {
_tag: "workspace-file",
threadId: "thread-1",
path: htmlPath,
},
});
expect(error.cause).toBeInstanceOf(WorkspacePaths.WorkspacePathOutsideRootError);
}).pipe(Effect.provide(testLayer)),
);
it.effect("preserves non-missing canonical path failures when issuing asset URLs", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const root = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-asset-permission-root-",
});
const htmlPath = path.join(root, "report.html");
yield* fileSystem.writeFileString(htmlPath, "<p>report</p>");
const cause = PlatformError.systemError({
_tag: "PermissionDenied",
module: "FileSystem",
method: "realPath",
pathOrDescriptor: htmlPath,
});
const failingFileSystem = FileSystem.FileSystem.of({
...fileSystem,
realPath: () => Effect.fail(cause),
});
const error = yield* issueAssetUrl({
resource: {
_tag: "workspace-file",
threadId: ThreadId.make("thread-1"),
path: htmlPath,
},
workspaceRoot: root,
}).pipe(Effect.provideService(FileSystem.FileSystem, failingFileSystem), Effect.flip);
expect(error.message).toBe("Failed to inspect the workspace asset.");
expect(error).toMatchObject({
_tag: "AssetWorkspaceAssetInspectionError",
resource: {
_tag: "workspace-file",
threadId: "thread-1",
path: htmlPath,
},
});
expect(error.cause).toBe(cause);
}).pipe(Effect.provide(testLayer)),
);
@@ -186,4 +238,38 @@ describe("AssetAccess", () => {
).toEqual({ kind: "project-favicon-fallback" });
}).pipe(Effect.provide(testLayer)),
);
it.effect("preserves structured project favicon resolution causes", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const root = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-asset-favicon-error-",
});
const platformCause = PlatformError.systemError({
_tag: "PermissionDenied",
module: "FileSystem",
method: "stat",
});
const resolutionCause = new ProjectFaviconResolver.ProjectFaviconResolutionError({
operation: "stat-candidate",
workspaceRoot: root,
relativePath: "favicon.svg",
cause: platformCause,
});
const resolver = ProjectFaviconResolver.ProjectFaviconResolver.of({
resolvePath: () => Effect.fail(resolutionCause),
});
const error = yield* issueAssetUrl({
resource: { _tag: "project-favicon", cwd: root },
}).pipe(
Effect.provideService(ProjectFaviconResolver.ProjectFaviconResolver, resolver),
Effect.flip,
);
expect(error.message).toBe("Failed to resolve project favicon.");
expect(error._tag).toBe("AssetProjectFaviconResolutionError");
expect(error.cause).toBe(resolutionCause);
}).pipe(Effect.provide(testLayer)),
);
});
+167 -45
View File
@@ -1,5 +1,18 @@
import type { AssetResource } from "@t3tools/contracts";
import { AssetAccessError } from "@t3tools/contracts";
import {
AssetAttachmentNotFoundError,
AssetPreviewTypeValidationError,
AssetProjectFaviconInspectionError,
AssetProjectFaviconNotFoundError,
AssetProjectFaviconResolutionError,
AssetSigningKeyLoadError,
AssetWorkspaceAssetInspectionError,
AssetWorkspaceAssetNotFoundError,
AssetWorkspaceContextNotFoundError,
AssetWorkspacePathValidationError,
AssetWorkspaceResolutionError,
AssetWorkspaceRootNormalizationError,
} from "@t3tools/contracts";
import {
isWorkspaceImagePreviewPath,
isWorkspacePreviewEntryPath,
@@ -11,6 +24,7 @@ import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as Schema from "effect/Schema";
import {
@@ -97,33 +111,59 @@ function decodeRelativePath(value: string): string | null {
}
}
const failAccess = (message: string, cause?: unknown) =>
new AssetAccessError({ message, ...(cause === undefined ? {} : { cause }) });
const optionOnNotFound = <A, R>(
effect: Effect.Effect<A, PlatformError.PlatformError, R>,
): Effect.Effect<Option.Option<A>, PlatformError.PlatformError, R> =>
effect.pipe(
Effect.map(Option.some),
Effect.catchTags({
PlatformError: (error) =>
error.reason._tag === "NotFound" ? Effect.succeed(Option.none<A>()) : Effect.fail(error),
}),
);
const resolveCanonicalWorkspaceFile = Effect.fn("AssetAccess.resolveCanonicalWorkspaceFile")(
function* (input: { readonly workspaceRoot: string; readonly relativePath: string }) {
const fileSystem = yield* FileSystem.FileSystem;
const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
const resolved = yield* workspacePaths
.resolveRelativePathWithinRoot(input)
.pipe(Effect.orElseSucceed(() => null));
if (!resolved) return null;
const resolved = yield* workspacePaths.resolveRelativePathWithinRoot(input).pipe(
Effect.map(Option.some),
Effect.catchTags({
WorkspacePathOutsideRootError: () => Effect.succeed(Option.none()),
}),
);
if (Option.isNone(resolved)) return null;
const [canonicalRoot, canonicalFile] = yield* Effect.all([
fileSystem.realPath(input.workspaceRoot).pipe(Effect.orElseSucceed(() => null)),
fileSystem.realPath(resolved.absolutePath).pipe(Effect.orElseSucceed(() => null)),
optionOnNotFound(fileSystem.realPath(input.workspaceRoot)),
optionOnNotFound(fileSystem.realPath(resolved.value.absolutePath)),
]);
if (!canonicalRoot || !canonicalFile) return null;
if (Option.isNone(canonicalRoot) || Option.isNone(canonicalFile)) return null;
const path = yield* Path.Path;
const relative = path.relative(canonicalRoot, canonicalFile);
const relative = path.relative(canonicalRoot.value, canonicalFile.value);
if (relative === "" || relative.startsWith("..") || path.isAbsolute(relative)) return null;
const info = yield* fileSystem.stat(canonicalFile).pipe(Effect.orElseSucceed(() => null));
return info?.type === "File" ? canonicalFile : null;
const info = yield* optionOnNotFound(fileSystem.stat(canonicalFile.value));
return Option.isSome(info) && info.value.type === "File" ? canonicalFile.value : null;
},
);
const resolveCanonicalWorkspaceFileForRequest = (input: {
readonly workspaceRoot: string;
readonly relativePath: string;
}) =>
resolveCanonicalWorkspaceFile(input).pipe(
Effect.tapError((cause) =>
Effect.logError("Failed to resolve canonical asset path.", {
workspaceRoot: input.workspaceRoot,
relativePath: input.relativePath,
cause,
}),
),
Effect.orElseSucceed(() => null),
);
export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (input: {
readonly resource: AssetResource;
readonly workspaceRoot?: string;
@@ -138,30 +178,64 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
switch (input.resource._tag) {
case "workspace-file": {
if (!input.workspaceRoot) {
return yield* failAccess("Workspace context was not found.");
return yield* new AssetWorkspaceContextNotFoundError({
resource: input.resource,
});
}
const workspaceRoot = yield* workspacePaths
.normalizeWorkspaceRoot(input.workspaceRoot)
.pipe(Effect.mapError((cause) => failAccess(cause.message, cause)));
const workspaceRoot = yield* workspacePaths.normalizeWorkspaceRoot(input.workspaceRoot).pipe(
Effect.mapError(
(cause) =>
new AssetWorkspaceRootNormalizationError({
resource: input.resource,
cause,
}),
),
);
const relativePath = path.isAbsolute(input.resource.path)
? path.relative(workspaceRoot, input.resource.path)
: input.resource.path;
const resolved = yield* workspacePaths
.resolveRelativePathWithinRoot({ workspaceRoot, relativePath })
.pipe(Effect.mapError((cause) => failAccess(cause.message, cause)));
.pipe(
Effect.mapError(
(cause) =>
new AssetWorkspacePathValidationError({
resource: input.resource,
cause,
}),
),
);
if (!isWorkspacePreviewEntryPath(resolved.relativePath)) {
return yield* failAccess("Only browser documents and images can be previewed.");
return yield* new AssetPreviewTypeValidationError({
resource: input.resource,
});
}
const canonicalFile = yield* resolveCanonicalWorkspaceFile({
workspaceRoot,
relativePath: resolved.relativePath,
});
}).pipe(
Effect.mapError(
(cause) =>
new AssetWorkspaceAssetInspectionError({
resource: input.resource,
cause,
}),
),
);
if (!canonicalFile) {
return yield* failAccess("Workspace asset was not found.");
return yield* new AssetWorkspaceAssetNotFoundError({
resource: input.resource,
});
}
const canonicalWorkspaceRoot = yield* fileSystem
.realPath(workspaceRoot)
.pipe(Effect.mapError((cause) => failAccess("Failed to resolve workspace.", cause)));
const canonicalWorkspaceRoot = yield* fileSystem.realPath(workspaceRoot).pipe(
Effect.mapError(
(cause) =>
new AssetWorkspaceResolutionError({
resource: input.resource,
cause,
}),
),
);
claims = isWorkspaceImagePreviewPath(resolved.relativePath)
? {
version: 1,
@@ -187,7 +261,9 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
attachmentId: input.resource.attachmentId,
});
if (!attachmentPath) {
return yield* failAccess("Attachment was not found.");
return yield* new AssetAttachmentNotFoundError({
resource: input.resource,
});
}
claims = {
version: 1,
@@ -199,24 +275,54 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
break;
}
case "project-favicon": {
const workspaceRoot = yield* workspacePaths
.normalizeWorkspaceRoot(input.resource.cwd)
.pipe(Effect.mapError((cause) => failAccess(cause.message, cause)));
const workspaceRoot = yield* workspacePaths.normalizeWorkspaceRoot(input.resource.cwd).pipe(
Effect.mapError(
(cause) =>
new AssetWorkspaceRootNormalizationError({
resource: input.resource,
cause,
}),
),
);
const faviconResolver = yield* ProjectFaviconResolver.ProjectFaviconResolver;
const faviconPath = yield* faviconResolver.resolvePath(workspaceRoot);
const faviconPath = yield* faviconResolver.resolvePath(workspaceRoot).pipe(
Effect.mapError(
(cause) =>
new AssetProjectFaviconResolutionError({
resource: input.resource,
cause,
}),
),
);
const relativePath = faviconPath ? path.relative(workspaceRoot, faviconPath) : null;
if (
relativePath &&
!(yield* resolveCanonicalWorkspaceFile({ workspaceRoot, relativePath }))
!(yield* resolveCanonicalWorkspaceFile({ workspaceRoot, relativePath }).pipe(
Effect.mapError(
(cause) =>
new AssetProjectFaviconInspectionError({
resource: input.resource,
cause,
}),
),
))
) {
return yield* failAccess("Project favicon was not found.");
return yield* new AssetProjectFaviconNotFoundError({
resource: input.resource,
});
}
claims = {
version: 1,
kind: "project-favicon",
workspaceRoot: yield* fileSystem
.realPath(workspaceRoot)
.pipe(Effect.mapError((cause) => failAccess("Failed to resolve workspace.", cause))),
workspaceRoot: yield* fileSystem.realPath(workspaceRoot).pipe(
Effect.mapError(
(cause) =>
new AssetWorkspaceResolutionError({
resource: input.resource,
cause,
}),
),
),
relativePath,
expiresAt,
};
@@ -226,9 +332,15 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
}
const secretStore = yield* ServerSecretStore.ServerSecretStore;
const signingSecret = yield* secretStore
.getOrCreateRandom(SIGNING_SECRET_NAME, 32)
.pipe(Effect.mapError((cause) => failAccess(cause.message, cause)));
const signingSecret = yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32).pipe(
Effect.mapError(
(cause) =>
new AssetSigningKeyLoadError({
resource: input.resource,
cause,
}),
),
);
const encodedPayload = base64UrlEncode(encodeAssetClaims(claims));
const token = `${encodedPayload}.${signPayload(encodedPayload, signingSecret)}`;
return {
@@ -245,9 +357,10 @@ export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (
if (!encodedPayload || !signature) return null;
const secretStore = yield* ServerSecretStore.ServerSecretStore;
const signingSecret = yield* secretStore
.getOrCreateRandom(SIGNING_SECRET_NAME, 32)
.pipe(Effect.orElseSucceed(() => null));
const signingSecret = yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32).pipe(
Effect.tapError((cause) => Effect.logError("Failed to load the asset signing key.", { cause })),
Effect.orElseSucceed(() => null),
);
if (!signingSecret) return null;
if (!timingSafeEqualBase64Url(signature, signPayload(encodedPayload, signingSecret))) return null;
@@ -262,8 +375,17 @@ export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (
});
if (!attachmentPath) return null;
const fileSystem = yield* FileSystem.FileSystem;
const info = yield* fileSystem.stat(attachmentPath).pipe(Effect.orElseSucceed(() => null));
return info?.type === "File"
const info = yield* optionOnNotFound(fileSystem.stat(attachmentPath)).pipe(
Effect.tapError((cause) =>
Effect.logError("Failed to inspect attachment asset.", {
attachmentId: claims.attachmentId,
path: attachmentPath,
cause,
}),
),
Effect.orElseSucceed(() => Option.none()),
);
return Option.isSome(info) && info.value.type === "File"
? ({ kind: "file", path: attachmentPath } satisfies ResolvedAsset)
: null;
}
@@ -272,7 +394,7 @@ export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (
if (claims.relativePath === null) {
return { kind: "project-favicon-fallback" } satisfies ResolvedAsset;
}
const faviconPath = yield* resolveCanonicalWorkspaceFile({
const faviconPath = yield* resolveCanonicalWorkspaceFileForRequest({
workspaceRoot: claims.workspaceRoot,
relativePath: claims.relativePath,
});
@@ -284,7 +406,7 @@ export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (
const path = yield* Path.Path;
if (claims.kind === "workspace-file-exact") {
if (decodedPath !== path.basename(claims.relativePath)) return null;
const exactWorkspaceFile = yield* resolveCanonicalWorkspaceFile({
const exactWorkspaceFile = yield* resolveCanonicalWorkspaceFileForRequest({
workspaceRoot: claims.workspaceRoot,
relativePath: claims.relativePath,
});
@@ -303,7 +425,7 @@ export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (
}
const joinedRelativePath =
claims.baseRelativePath === "." ? decodedPath : path.join(claims.baseRelativePath, decodedPath);
const workspaceFile = yield* resolveCanonicalWorkspaceFile({
const workspaceFile = yield* resolveCanonicalWorkspaceFileForRequest({
workspaceRoot: claims.workspaceRoot,
relativePath: joinedRelativePath,
});
+80 -4
View File
@@ -44,8 +44,8 @@ const failingSessionLookupRepositoryLayer = Layer.succeed(AuthSessions.AuthSessi
create: () => Effect.void,
getById: () => Effect.fail(repositoryFailure),
listActive: () => Effect.succeed([]),
revoke: () => Effect.succeed(false),
revokeAllExcept: () => Effect.succeed([]),
revoke: () => Effect.fail(repositoryFailure),
revokeAllExcept: () => Effect.fail(repositoryFailure),
setLastConnectedAt: () => Effect.void,
});
@@ -104,11 +104,29 @@ it.layer(NodeServices.layer)("SessionStore.layer", (it) => {
const sessionError = yield* Effect.flip(sessions.verify(issued.token));
const websocketError = yield* Effect.flip(sessions.verifyWebSocketToken(websocket.token));
const revokeError = yield* Effect.flip(sessions.revoke(issued.sessionId));
const revokeOthersError = yield* Effect.flip(sessions.revokeAllExcept(issued.sessionId));
expect(sessionError._tag).toBe("SessionCredentialVerificationError");
expect(websocketError._tag).toBe("WebSocketTokenVerificationError");
expect(sessionError.cause).toBe(repositoryFailure);
expect(websocketError.cause).toBe(repositoryFailure);
if (sessionError._tag === "SessionCredentialVerificationError") {
expect(sessionError.sessionId).toBe(issued.sessionId);
}
if (websocketError._tag === "WebSocketTokenVerificationError") {
expect(websocketError.sessionId).toBe(issued.sessionId);
}
expect(revokeError).toMatchObject({
_tag: "SessionRevocationError",
sessionId: issued.sessionId,
cause: repositoryFailure,
});
expect(revokeOthersError).toMatchObject({
_tag: "OtherSessionsRevocationError",
currentSessionId: issued.sessionId,
cause: repositoryFailure,
});
}).pipe(Effect.provide(failingSessionLookupCredentialLayer)),
);
it.effect("verifies session tokens against the Effect clock", () =>
@@ -145,7 +163,52 @@ it.layer(NodeServices.layer)("SessionStore.layer", (it) => {
yield* TestClock.adjust(Duration.seconds(2));
const error = yield* Effect.flip(sessions.verifyWebSocketToken(websocket.token));
expect(error.message).toContain("expired");
expect(error._tag).toBe("WebSocketSessionExpiredError");
if (error._tag === "WebSocketSessionExpiredError") {
expect(error.sessionId).toBe(issued.sessionId);
expect(error.expiresAt.epochMilliseconds).toBe(issued.expiresAt.epochMilliseconds);
expect(error.observedAt.epochMilliseconds).toBeGreaterThan(
error.expiresAt.epochMilliseconds,
);
}
}).pipe(Effect.provide(Layer.merge(makeSessionStoreLayer(), TestClock.layer()))),
);
it.effect("includes expiry context when session and websocket tokens expire", () =>
Effect.gen(function* () {
const sessions = yield* SessionStore.SessionStore;
const issued = yield* sessions.issue({
method: "bearer-access-token",
subject: "short-lived-token",
ttl: Duration.seconds(1),
});
const websocket = yield* sessions.issueWebSocketToken(issued.sessionId, {
ttl: Duration.seconds(1),
});
yield* TestClock.adjust(Duration.seconds(2));
const sessionError = yield* Effect.flip(sessions.verify(issued.token));
const websocketError = yield* Effect.flip(sessions.verifyWebSocketToken(websocket.token));
expect(sessionError._tag).toBe("SessionTokenExpiredError");
if (sessionError._tag === "SessionTokenExpiredError") {
expect(sessionError.sessionId).toBe(issued.sessionId);
expect(sessionError.expiresAt.epochMilliseconds).toBe(issued.expiresAt.epochMilliseconds);
expect(sessionError.observedAt.epochMilliseconds).toBeGreaterThan(
sessionError.expiresAt.epochMilliseconds,
);
}
expect(websocketError._tag).toBe("WebSocketTokenExpiredError");
if (websocketError._tag === "WebSocketTokenExpiredError") {
expect(websocketError.sessionId).toBe(issued.sessionId);
expect(websocketError.expiresAt.epochMilliseconds).toBe(
websocket.expiresAt.epochMilliseconds,
);
expect(websocketError.observedAt.epochMilliseconds).toBeGreaterThan(
websocketError.expiresAt.epochMilliseconds,
);
}
}).pipe(Effect.provide(Layer.merge(makeSessionStoreLayer(), TestClock.layer()))),
);
@@ -173,12 +236,16 @@ it.layer(NodeServices.layer)("SessionStore.layer", (it) => {
ipAddress: "192.168.1.88",
},
});
const clientWebSocket = yield* sessions.issueWebSocketToken(client.sessionId);
yield* sessions.markConnected(client.sessionId);
const beforeRevoke = yield* sessions.listActive();
const revokedCount = yield* sessions.revokeAllExcept(administrative.sessionId);
const afterRevoke = yield* sessions.listActive();
const revokedClient = yield* Effect.flip(sessions.verify(client.token));
const revokedClientWebSocket = yield* Effect.flip(
sessions.verifyWebSocketToken(clientWebSocket.token),
);
expect(beforeRevoke).toHaveLength(2);
expect(beforeRevoke.find((entry) => entry.sessionId === client.sessionId)?.connected).toBe(
@@ -194,7 +261,16 @@ it.layer(NodeServices.layer)("SessionStore.layer", (it) => {
expect(revokedCount).toBe(1);
expect(afterRevoke).toHaveLength(1);
expect(afterRevoke[0]?.sessionId).toBe(administrative.sessionId);
expect(revokedClient.message).toContain("revoked");
expect(revokedClient._tag).toBe("SessionTokenRevokedError");
if (revokedClient._tag === "SessionTokenRevokedError") {
expect(revokedClient.sessionId).toBe(client.sessionId);
expect(revokedClient.revokedAt.epochMilliseconds).toBeGreaterThanOrEqual(0);
}
expect(revokedClientWebSocket._tag).toBe("WebSocketSessionRevokedError");
if (revokedClientWebSocket._tag === "WebSocketSessionRevokedError") {
expect(revokedClientWebSocket.sessionId).toBe(client.sessionId);
expect(revokedClientWebSocket.revokedAt.epochMilliseconds).toBeGreaterThanOrEqual(0);
}
}).pipe(Effect.provide(makeSessionStoreLayer())),
);
+228 -149
View File
@@ -7,7 +7,6 @@ import {
type AuthEnvironmentScope,
type ServerAuthSessionMethod,
} from "@t3tools/contracts";
import * as Clock from "effect/Clock";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as DateTime from "effect/DateTime";
@@ -93,7 +92,11 @@ export class InvalidSessionTokenPayloadError extends Schema.TaggedErrorClass<Inv
export class SessionTokenExpiredError extends Schema.TaggedErrorClass<SessionTokenExpiredError>()(
"SessionTokenExpiredError",
{},
{
sessionId: AuthSessionId,
expiresAt: Schema.DateTimeUtc,
observedAt: Schema.DateTimeUtc,
},
) {
override get message(): string {
return "Session token expired.";
@@ -102,7 +105,9 @@ export class SessionTokenExpiredError extends Schema.TaggedErrorClass<SessionTok
export class UnknownSessionTokenError extends Schema.TaggedErrorClass<UnknownSessionTokenError>()(
"UnknownSessionTokenError",
{},
{
sessionId: AuthSessionId,
},
) {
override get message(): string {
return "Unknown session token.";
@@ -111,7 +116,10 @@ export class UnknownSessionTokenError extends Schema.TaggedErrorClass<UnknownSes
export class SessionTokenRevokedError extends Schema.TaggedErrorClass<SessionTokenRevokedError>()(
"SessionTokenRevokedError",
{},
{
sessionId: AuthSessionId,
revokedAt: Schema.DateTimeUtc,
},
) {
override get message(): string {
return "Session token revoked.";
@@ -120,7 +128,10 @@ export class SessionTokenRevokedError extends Schema.TaggedErrorClass<SessionTok
export class InvalidSessionExpirationClaimError extends Schema.TaggedErrorClass<InvalidSessionExpirationClaimError>()(
"InvalidSessionExpirationClaimError",
{},
{
sessionId: AuthSessionId,
expirationClaim: Schema.Number,
},
) {
override get message(): string {
return "Invalid `exp` claim";
@@ -158,7 +169,11 @@ export class InvalidWebSocketTokenPayloadError extends Schema.TaggedErrorClass<I
export class WebSocketTokenExpiredError extends Schema.TaggedErrorClass<WebSocketTokenExpiredError>()(
"WebSocketTokenExpiredError",
{},
{
sessionId: AuthSessionId,
expiresAt: Schema.DateTimeUtc,
observedAt: Schema.DateTimeUtc,
},
) {
override get message(): string {
return "Websocket token expired.";
@@ -167,7 +182,9 @@ export class WebSocketTokenExpiredError extends Schema.TaggedErrorClass<WebSocke
export class UnknownWebSocketSessionError extends Schema.TaggedErrorClass<UnknownWebSocketSessionError>()(
"UnknownWebSocketSessionError",
{},
{
sessionId: AuthSessionId,
},
) {
override get message(): string {
return "Unknown websocket session.";
@@ -176,7 +193,11 @@ export class UnknownWebSocketSessionError extends Schema.TaggedErrorClass<Unknow
export class WebSocketSessionExpiredError extends Schema.TaggedErrorClass<WebSocketSessionExpiredError>()(
"WebSocketSessionExpiredError",
{},
{
sessionId: AuthSessionId,
expiresAt: Schema.DateTimeUtc,
observedAt: Schema.DateTimeUtc,
},
) {
override get message(): string {
return "Websocket session expired.";
@@ -185,7 +206,10 @@ export class WebSocketSessionExpiredError extends Schema.TaggedErrorClass<WebSoc
export class WebSocketSessionRevokedError extends Schema.TaggedErrorClass<WebSocketSessionRevokedError>()(
"WebSocketSessionRevokedError",
{},
{
sessionId: AuthSessionId,
revokedAt: Schema.DateTimeUtc,
},
) {
override get message(): string {
return "Websocket session revoked.";
@@ -218,6 +242,7 @@ const sessionCredentialInternalErrorContext = {
export class SessionClaimsEncodingError extends Schema.TaggedErrorClass<SessionClaimsEncodingError>()(
"SessionClaimsEncodingError",
{
sessionId: AuthSessionId,
operation: Schema.Literals(["encode_session_claims", "encode_websocket_claims"]),
...sessionCredentialInternalErrorContext,
},
@@ -230,6 +255,7 @@ export class SessionClaimsEncodingError extends Schema.TaggedErrorClass<SessionC
export class SessionCredentialIssueError extends Schema.TaggedErrorClass<SessionCredentialIssueError>()(
"SessionCredentialIssueError",
{
sessionId: Schema.optional(AuthSessionId),
...sessionCredentialInternalErrorContext,
},
) {
@@ -241,6 +267,7 @@ export class SessionCredentialIssueError extends Schema.TaggedErrorClass<Session
export class SessionCredentialVerificationError extends Schema.TaggedErrorClass<SessionCredentialVerificationError>()(
"SessionCredentialVerificationError",
{
sessionId: AuthSessionId,
...sessionCredentialInternalErrorContext,
},
) {
@@ -252,6 +279,7 @@ export class SessionCredentialVerificationError extends Schema.TaggedErrorClass<
export class WebSocketTokenIssueError extends Schema.TaggedErrorClass<WebSocketTokenIssueError>()(
"WebSocketTokenIssueError",
{
sessionId: AuthSessionId,
...sessionCredentialInternalErrorContext,
},
) {
@@ -263,6 +291,7 @@ export class WebSocketTokenIssueError extends Schema.TaggedErrorClass<WebSocketT
export class WebSocketTokenVerificationError extends Schema.TaggedErrorClass<WebSocketTokenVerificationError>()(
"WebSocketTokenVerificationError",
{
sessionId: AuthSessionId,
...sessionCredentialInternalErrorContext,
},
) {
@@ -285,6 +314,7 @@ export class ActiveSessionsListError extends Schema.TaggedErrorClass<ActiveSessi
export class SessionRevocationError extends Schema.TaggedErrorClass<SessionRevocationError>()(
"SessionRevocationError",
{
sessionId: AuthSessionId,
...sessionCredentialInternalErrorContext,
},
) {
@@ -296,6 +326,7 @@ export class SessionRevocationError extends Schema.TaggedErrorClass<SessionRevoc
export class OtherSessionsRevocationError extends Schema.TaggedErrorClass<OtherSessionsRevocationError>()(
"OtherSessionsRevocationError",
{
currentSessionId: AuthSessionId,
...sessionCredentialInternalErrorContext,
},
) {
@@ -539,7 +570,11 @@ export const make = Effect.gen(function* () {
const encodeClaims = Schema.encodeEffect(Schema.fromJsonString(SessionClaims));
const issue: SessionStore["Service"]["issue"] = Effect.fn("SessionStore.issue")(
function* (input) {
const sessionId = AuthSessionId.make(yield* crypto.randomUUIDv4);
const sessionId = AuthSessionId.make(
yield* crypto.randomUUIDv4.pipe(
Effect.mapError((cause) => new SessionCredentialIssueError({ cause })),
),
);
const issuedAt = yield* DateTime.now;
const expiresAt = DateTime.add(issuedAt, {
milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_SESSION_TTL),
@@ -559,27 +594,37 @@ export const make = Effect.gen(function* () {
const encodedPayload = yield* encodeClaims(claims).pipe(
Effect.map(base64UrlEncode),
Effect.mapError(
(cause) => new SessionClaimsEncodingError({ operation: "encode_session_claims", cause }),
(cause) =>
new SessionCredentialIssueError({
sessionId,
cause: new SessionClaimsEncodingError({
sessionId,
operation: "encode_session_claims",
cause,
}),
}),
),
);
const signature = signPayload(encodedPayload, signingSecret);
const client = input?.client ?? createDefaultClientMetadata();
yield* authSessions.create({
sessionId,
subject: claims.sub,
scopes: claims.scopes,
method: claims.method,
client: {
label: client.label ?? null,
ipAddress: client.ipAddress ?? null,
userAgent: client.userAgent ?? null,
deviceType: client.deviceType,
os: client.os ?? null,
browser: client.browser ?? null,
},
issuedAt,
expiresAt,
});
yield* authSessions
.create({
sessionId,
subject: claims.sub,
scopes: claims.scopes,
method: claims.method,
client: {
label: client.label ?? null,
ipAddress: client.ipAddress ?? null,
userAgent: client.userAgent ?? null,
deviceType: client.deviceType,
os: client.os ?? null,
browser: client.browser ?? null,
},
issuedAt,
expiresAt,
})
.pipe(Effect.mapError((cause) => new SessionCredentialIssueError({ sessionId, cause })));
yield* emitUpsert(
toAuthClientSession({
sessionId,
@@ -604,7 +649,6 @@ export const make = Effect.gen(function* () {
...(claims.jkt ? { proofKeyThumbprint: claims.jkt } : {}),
} satisfies IssuedSession;
},
Effect.mapError((cause) => new SessionCredentialIssueError({ cause })),
);
const verify: SessionStore["Service"]["verify"] = Effect.fn("SessionStore.verify")(
@@ -623,22 +667,37 @@ export const make = Effect.gen(function* () {
Effect.mapError((cause) => new InvalidSessionTokenPayloadError({ cause })),
);
const now = yield* Clock.currentTimeMillis;
if (claims.exp <= now) {
return yield* new SessionTokenExpiredError({});
}
const row = yield* authSessions.getById({ sessionId: claims.sid });
if (Option.isNone(row)) {
return yield* new UnknownSessionTokenError({});
}
if (row.value.revokedAt !== null) {
return yield* new SessionTokenRevokedError({});
}
const observedAt = yield* DateTime.now;
const expiresAt = DateTime.make(claims.exp);
if (Option.isNone(expiresAt)) {
return yield* new InvalidSessionExpirationClaimError({});
return yield* new InvalidSessionExpirationClaimError({
sessionId: claims.sid,
expirationClaim: claims.exp,
});
}
if (claims.exp <= observedAt.epochMilliseconds) {
return yield* new SessionTokenExpiredError({
sessionId: claims.sid,
expiresAt: expiresAt.value,
observedAt,
});
}
const row = yield* authSessions
.getById({ sessionId: claims.sid })
.pipe(
Effect.mapError(
(cause) => new SessionCredentialVerificationError({ sessionId: claims.sid, cause }),
),
);
if (Option.isNone(row)) {
return yield* new UnknownSessionTokenError({ sessionId: claims.sid });
}
if (row.value.revokedAt !== null) {
return yield* new SessionTokenRevokedError({
sessionId: claims.sid,
revokedAt: row.value.revokedAt,
});
}
return {
@@ -652,95 +711,111 @@ export const make = Effect.gen(function* () {
...(claims.jkt ? { proofKeyThumbprint: claims.jkt } : {}),
} satisfies VerifiedSession;
},
Effect.mapError((cause) =>
isSessionCredentialInvalidError(cause)
? cause
: new SessionCredentialVerificationError({ cause }),
),
);
const encodeWsClaims = Schema.encodeEffect(Schema.fromJsonString(WebSocketClaims));
const issueWebSocketToken: SessionStore["Service"]["issueWebSocketToken"] = Effect.fn(
"SessionStore.issueWebSocketToken",
)(
function* (sessionId, input) {
const issuedAt = yield* DateTime.now;
const expiresAt = DateTime.add(issuedAt, {
milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_WEBSOCKET_TOKEN_TTL),
});
const claims: WebSocketClaims = {
v: 1,
kind: "websocket",
sid: sessionId,
iat: issuedAt.epochMilliseconds,
exp: expiresAt.epochMilliseconds,
};
const encodedPayload = yield* encodeWsClaims(claims).pipe(
Effect.map(base64UrlEncode),
Effect.mapError(
(cause) =>
new SessionClaimsEncodingError({ operation: "encode_websocket_claims", cause }),
),
);
const signature = signPayload(encodedPayload, signingSecret);
return {
token: `${encodedPayload}.${signature}`,
expiresAt,
};
},
Effect.mapError((cause) => new WebSocketTokenIssueError({ cause })),
);
)(function* (sessionId, input) {
const issuedAt = yield* DateTime.now;
const expiresAt = DateTime.add(issuedAt, {
milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_WEBSOCKET_TOKEN_TTL),
});
const claims: WebSocketClaims = {
v: 1,
kind: "websocket",
sid: sessionId,
iat: issuedAt.epochMilliseconds,
exp: expiresAt.epochMilliseconds,
};
const encodedPayload = yield* encodeWsClaims(claims).pipe(
Effect.map(base64UrlEncode),
Effect.mapError(
(cause) =>
new WebSocketTokenIssueError({
sessionId,
cause: new SessionClaimsEncodingError({
sessionId,
operation: "encode_websocket_claims",
cause,
}),
}),
),
);
const signature = signPayload(encodedPayload, signingSecret);
return {
token: `${encodedPayload}.${signature}`,
expiresAt,
};
});
const verifyWebSocketToken: SessionStore["Service"]["verifyWebSocketToken"] = Effect.fn(
"SessionStore.verifyWebSocketToken",
)(
function* (token) {
const [encodedPayload, signature] = token.split(".");
if (!encodedPayload || !signature) {
return yield* new MalformedWebSocketTokenError({});
}
)(function* (token) {
const [encodedPayload, signature] = token.split(".");
if (!encodedPayload || !signature) {
return yield* new MalformedWebSocketTokenError({});
}
const expectedSignature = signPayload(encodedPayload, signingSecret);
if (!timingSafeEqualBase64Url(signature, expectedSignature)) {
return yield* new InvalidWebSocketTokenSignatureError({});
}
const expectedSignature = signPayload(encodedPayload, signingSecret);
if (!timingSafeEqualBase64Url(signature, expectedSignature)) {
return yield* new InvalidWebSocketTokenSignatureError({});
}
const claims = yield* decodeWebSocketClaims(base64UrlDecodeUtf8(encodedPayload)).pipe(
Effect.mapError((cause) => new InvalidWebSocketTokenPayloadError({ cause })),
const claims = yield* decodeWebSocketClaims(base64UrlDecodeUtf8(encodedPayload)).pipe(
Effect.mapError((cause) => new InvalidWebSocketTokenPayloadError({ cause })),
);
const observedAt = yield* DateTime.now;
const expiresAt = DateTime.make(claims.exp);
if (Option.isNone(expiresAt)) {
return yield* new InvalidSessionExpirationClaimError({
sessionId: claims.sid,
expirationClaim: claims.exp,
});
}
if (claims.exp <= observedAt.epochMilliseconds) {
return yield* new WebSocketTokenExpiredError({
sessionId: claims.sid,
expiresAt: expiresAt.value,
observedAt,
});
}
const row = yield* authSessions
.getById({ sessionId: claims.sid })
.pipe(
Effect.mapError(
(cause) => new WebSocketTokenVerificationError({ sessionId: claims.sid, cause }),
),
);
const now = yield* Clock.currentTimeMillis;
if (claims.exp <= now) {
return yield* new WebSocketTokenExpiredError({});
}
const row = yield* authSessions.getById({ sessionId: claims.sid });
if (Option.isNone(row)) {
return yield* new UnknownWebSocketSessionError({});
}
if (row.value.expiresAt.epochMilliseconds <= now) {
return yield* new WebSocketSessionExpiredError({});
}
if (row.value.revokedAt !== null) {
return yield* new WebSocketSessionRevokedError({});
}
return {
sessionId: row.value.sessionId,
token,
method: row.value.method,
client: toClientMetadata(row.value.client),
if (Option.isNone(row)) {
return yield* new UnknownWebSocketSessionError({ sessionId: claims.sid });
}
if (row.value.expiresAt.epochMilliseconds <= observedAt.epochMilliseconds) {
return yield* new WebSocketSessionExpiredError({
sessionId: claims.sid,
expiresAt: row.value.expiresAt,
subject: row.value.subject,
scopes: row.value.scopes,
} satisfies VerifiedSession;
},
Effect.mapError((cause) =>
isSessionCredentialInvalidError(cause)
? cause
: new WebSocketTokenVerificationError({ cause }),
),
);
observedAt,
});
}
if (row.value.revokedAt !== null) {
return yield* new WebSocketSessionRevokedError({
sessionId: claims.sid,
revokedAt: row.value.revokedAt,
});
}
return {
sessionId: row.value.sessionId,
token,
method: row.value.method,
client: toClientMetadata(row.value.client),
expiresAt: row.value.expiresAt,
subject: row.value.subject,
scopes: row.value.scopes,
} satisfies VerifiedSession;
});
const listActive: SessionStore["Service"]["listActive"] = Effect.fn("SessionStore.listActive")(
function* () {
@@ -768,10 +843,12 @@ export const make = Effect.gen(function* () {
const revoke: SessionStore["Service"]["revoke"] = Effect.fn("SessionStore.revoke")(
function* (sessionId) {
const revokedAt = yield* DateTime.now;
const revoked = yield* authSessions.revoke({
sessionId,
revokedAt,
});
const revoked = yield* authSessions
.revoke({
sessionId,
revokedAt,
})
.pipe(Effect.mapError((cause) => new SessionRevocationError({ sessionId, cause })));
if (revoked) {
yield* Ref.update(connectedSessionsRef, (current) => {
const next = new Map(current);
@@ -782,39 +859,41 @@ export const make = Effect.gen(function* () {
}
return revoked;
},
Effect.mapError((cause) => new SessionRevocationError({ cause })),
);
const revokeAllExcept: SessionStore["Service"]["revokeAllExcept"] = Effect.fn(
"SessionStore.revokeAllExcept",
)(
function* (sessionId) {
const revokedAt = yield* DateTime.now;
const revokedSessionIds = yield* authSessions.revokeAllExcept({
)(function* (sessionId) {
const revokedAt = yield* DateTime.now;
const revokedSessionIds = yield* authSessions
.revokeAllExcept({
currentSessionId: sessionId,
revokedAt,
})
.pipe(
Effect.mapError(
(cause) => new OtherSessionsRevocationError({ currentSessionId: sessionId, cause }),
),
);
if (revokedSessionIds.length > 0) {
yield* Ref.update(connectedSessionsRef, (current) => {
const next = new Map(current);
for (const revokedSessionId of revokedSessionIds) {
next.delete(revokedSessionId);
}
return next;
});
if (revokedSessionIds.length > 0) {
yield* Ref.update(connectedSessionsRef, (current) => {
const next = new Map(current);
for (const revokedSessionId of revokedSessionIds) {
next.delete(revokedSessionId);
}
return next;
});
yield* Effect.forEach(
revokedSessionIds,
(revokedSessionId) => emitRemoved(revokedSessionId),
{
concurrency: "unbounded",
discard: true,
},
);
}
return revokedSessionIds.length;
},
Effect.mapError((cause) => new OtherSessionsRevocationError({ cause })),
);
yield* Effect.forEach(
revokedSessionIds,
(revokedSessionId) => emitRemoved(revokedSessionId),
{
concurrency: "unbounded",
discard: true,
},
);
}
return revokedSessionIds.length;
});
return SessionStore.of({
cookieName,
+9 -18
View File
@@ -3,7 +3,8 @@ import * as Crypto from "effect/Crypto";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Encoding from "effect/Encoding";
import type * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
import * as Option from "effect/Option";
import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
import {
ServerAuthDpopReplayKeyCalculationError,
@@ -13,22 +14,6 @@ import {
} from "./EnvironmentAuth.ts";
import * as ServerSecretStore from "./ServerSecretStore.ts";
function firstHeaderValue(value: string | undefined): string | undefined {
const first = value?.split(",")[0]?.trim();
return first && first.length > 0 ? first : undefined;
}
export function requestAbsoluteUrl(request: HttpServerRequest.HttpServerRequest): string {
try {
return new URL(request.originalUrl).href;
} catch {
const host = firstHeaderValue(request.headers.host) ?? "127.0.0.1";
const forwardedProto = firstHeaderValue(request.headers["x-forwarded-proto"]);
const proto = forwardedProto === "https" || forwardedProto === "http" ? forwardedProto : "http";
return new URL(request.originalUrl, `${proto}://${host}`).href;
}
}
export const mapDpopReplayStoreError = (
error: ServerSecretStore.SecretStoreError,
): ServerAuthInvalidCredentialError | ServerAuthInternalError =>
@@ -48,11 +33,17 @@ export const verifyRequestDpopProof = (input: {
}) =>
Effect.gen(function* () {
const proof = input.request.headers.dpop;
const url = HttpServerRequest.toURL(input.request);
if (Option.isNone(url)) {
return yield* new ServerAuthInvalidCredentialError({
diagnostic: "Invalid DPoP request URL.",
});
}
const now = yield* DateTime.now;
const result = verifyDpopProof({
proof,
method: input.request.method,
url: requestAbsoluteUrl(input.request),
url: url.value.href,
nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
...(input.expectedThumbprint ? { expectedThumbprint: input.expectedThumbprint } : {}),
...(input.expectedAccessToken ? { expectedAccessToken: input.expectedAccessToken } : {}),
@@ -9,6 +9,7 @@ import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSn
import { checkpointRefForThreadTurn } from "./Utils.ts";
import * as CheckpointDiffQuery from "./CheckpointDiffQuery.ts";
import * as CheckpointStore from "./CheckpointStore.ts";
import { CheckpointThreadNotFoundError } from "./Errors.ts";
function makeThreadCheckpointContext(input: {
readonly projectId: ProjectId;
@@ -412,7 +413,14 @@ describe("CheckpointDiffQuery.layer", () => {
});
}).pipe(Effect.provide(layer), Effect.flip);
expect(error.message).toContain("Thread 'thread-missing' not found.");
expect(error).toBeInstanceOf(CheckpointThreadNotFoundError);
expect(error).toMatchObject({
operation: "CheckpointDiffQuery.getTurnDiff",
threadId,
});
expect(error.message).toBe(
"Checkpoint invariant violation in CheckpointDiffQuery.getTurnDiff: Thread 'thread-missing' not found.",
);
}),
);
});
@@ -22,7 +22,13 @@ import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts";
import { CheckpointInvariantError, CheckpointUnavailableError } from "./Errors.ts";
import {
CheckpointDiffResultInvalidError,
CheckpointRefUnavailableError,
CheckpointThreadNotFoundError,
CheckpointTurnRangeUnavailableError,
CheckpointWorkspacePathMissingError,
} from "./Errors.ts";
import type { CheckpointServiceError } from "./Errors.ts";
import { checkpointRefForThreadTurn } from "./Utils.ts";
import * as CheckpointStore from "./CheckpointStore.ts";
@@ -92,9 +98,9 @@ export const make = Effect.gen(function* () {
diff: "",
};
if (!isTurnDiffResult(emptyDiff)) {
return yield* new CheckpointInvariantError({
return yield* new CheckpointDiffResultInvalidError({
operation,
detail: "Computed turn diff result does not satisfy contract schema.",
threadId: input.threadId,
});
}
return emptyDiff;
@@ -104,9 +110,9 @@ export const make = Effect.gen(function* () {
.getThreadCheckpointContext(input.threadId)
.pipe(Effect.withSpan("checkpoint.turnDiff.lookupContext"));
if (Option.isNone(threadContext)) {
return yield* new CheckpointInvariantError({
return yield* new CheckpointThreadNotFoundError({
operation,
detail: `Thread '${input.threadId}' not found.`,
threadId: input.threadId,
});
}
@@ -115,18 +121,19 @@ export const make = Effect.gen(function* () {
0,
);
if (input.toTurnCount > maxTurnCount) {
return yield* new CheckpointUnavailableError({
return yield* new CheckpointTurnRangeUnavailableError({
operation,
threadId: input.threadId,
turnCount: input.toTurnCount,
detail: `Turn diff range exceeds current turn count: requested ${input.toTurnCount}, current ${maxTurnCount}.`,
requestedTurnCount: input.toTurnCount,
availableTurnCount: maxTurnCount,
});
}
const workspaceCwd = threadContext.value.worktreePath ?? threadContext.value.workspaceRoot;
if (!workspaceCwd) {
return yield* new CheckpointInvariantError({
return yield* new CheckpointWorkspacePathMissingError({
operation,
detail: `Workspace path missing for thread '${input.threadId}' when computing turn diff.`,
threadId: input.threadId,
});
}
@@ -137,10 +144,11 @@ export const make = Effect.gen(function* () {
(checkpoint) => checkpoint.checkpointTurnCount === input.fromTurnCount,
)?.checkpointRef;
if (!fromCheckpointRef) {
return yield* new CheckpointUnavailableError({
return yield* new CheckpointRefUnavailableError({
operation,
threadId: input.threadId,
turnCount: input.fromTurnCount,
detail: `Checkpoint ref is unavailable for turn ${input.fromTurnCount}.`,
checkpoint: "from",
});
}
@@ -148,10 +156,11 @@ export const make = Effect.gen(function* () {
(checkpoint) => checkpoint.checkpointTurnCount === input.toTurnCount,
)?.checkpointRef;
if (!toCheckpointRef) {
return yield* new CheckpointUnavailableError({
return yield* new CheckpointRefUnavailableError({
operation,
threadId: input.threadId,
turnCount: input.toTurnCount,
detail: `Checkpoint ref is unavailable for turn ${input.toTurnCount}.`,
checkpoint: "to",
});
}
@@ -167,9 +176,9 @@ export const make = Effect.gen(function* () {
const turnDiff = buildTurnDiffResult(input, diff);
if (!isTurnDiffResult(turnDiff)) {
return yield* new CheckpointInvariantError({
return yield* new CheckpointDiffResultInvalidError({
operation,
detail: "Computed turn diff result does not satisfy contract schema.",
threadId: input.threadId,
});
}
@@ -200,9 +209,9 @@ export const make = Effect.gen(function* () {
"",
);
if (!isTurnDiffResult(emptyDiff)) {
return yield* new CheckpointInvariantError({
return yield* new CheckpointDiffResultInvalidError({
operation,
detail: "Computed full thread diff result does not satisfy contract schema.",
threadId: input.threadId,
});
}
return emptyDiff satisfies OrchestrationGetFullThreadDiffResult;
@@ -213,33 +222,35 @@ export const make = Effect.gen(function* () {
.pipe(Effect.withSpan("checkpoint.fullThread.lookupContext"));
if (Option.isNone(threadContext)) {
return yield* new CheckpointInvariantError({
return yield* new CheckpointThreadNotFoundError({
operation,
detail: `Thread '${input.threadId}' not found.`,
threadId: input.threadId,
});
}
if (input.toTurnCount > threadContext.value.latestCheckpointTurnCount) {
return yield* new CheckpointUnavailableError({
return yield* new CheckpointTurnRangeUnavailableError({
operation,
threadId: input.threadId,
turnCount: input.toTurnCount,
detail: `Turn diff range exceeds current turn count: requested ${input.toTurnCount}, current ${threadContext.value.latestCheckpointTurnCount}.`,
requestedTurnCount: input.toTurnCount,
availableTurnCount: threadContext.value.latestCheckpointTurnCount,
});
}
const workspaceCwd = threadContext.value.worktreePath ?? threadContext.value.workspaceRoot;
if (!workspaceCwd) {
return yield* new CheckpointInvariantError({
return yield* new CheckpointWorkspacePathMissingError({
operation,
detail: `Workspace path missing for thread '${input.threadId}' when computing full thread diff.`,
threadId: input.threadId,
});
}
if (!threadContext.value.toCheckpointRef) {
return yield* new CheckpointUnavailableError({
return yield* new CheckpointRefUnavailableError({
operation,
threadId: input.threadId,
turnCount: input.toTurnCount,
detail: `Checkpoint ref is unavailable for turn ${input.toTurnCount}.`,
checkpoint: "to",
});
}
@@ -262,9 +273,9 @@ export const make = Effect.gen(function* () {
diff,
);
if (!isTurnDiffResult(turnDiff)) {
return yield* new CheckpointInvariantError({
return yield* new CheckpointDiffResultInvalidError({
operation,
detail: "Computed full thread diff result does not satisfy contract schema.",
threadId: input.threadId,
});
}
@@ -93,6 +93,27 @@ function buildLargeText(lineCount = 5_000): string {
}
it.layer(TestLayer)("CheckpointStore.layer", (it) => {
describe("isGitRepository", () => {
it.effect("returns false when no Git repository is detected", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
const checkpointStore = yield* CheckpointStore.CheckpointStore;
expect(yield* checkpointStore.isGitRepository(tmp)).toBe(false);
}),
);
it.effect("returns true when a Git repository is detected", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
const checkpointStore = yield* CheckpointStore.CheckpointStore;
expect(yield* checkpointStore.isGitRepository(tmp)).toBe(true);
}),
);
});
describe("diffCheckpoints", () => {
it.effect("returns full oversized checkpoint diffs without truncation", () =>
Effect.gen(function* () {
@@ -115,10 +115,9 @@ export const make = Effect.gen(function* () {
});
const isGitRepository: CheckpointStore["Service"]["isGitRepository"] = (cwd) =>
vcsRegistry.resolve({ cwd, requestedKind: "git" }).pipe(
Effect.map(() => true),
Effect.orElseSucceed(() => false),
);
vcsRegistry
.detect({ cwd, requestedKind: "git" })
.pipe(Effect.map((repository) => repository !== null));
const captureCheckpoint: CheckpointStore["Service"]["captureCheckpoint"] = Effect.fn(
"captureCheckpoint",
@@ -0,0 +1,39 @@
import { expect, it } from "@effect/vitest";
import { ThreadId } from "@t3tools/contracts";
import {
CheckpointRefUnavailableError,
CheckpointTurnRangeUnavailableError,
CheckpointWorkspacePathMissingError,
} from "./Errors.ts";
const threadId = ThreadId.make("thread-1");
it("derives checkpoint messages from structured context", () => {
const range = new CheckpointTurnRangeUnavailableError({
operation: "CheckpointDiffQuery.getTurnDiff",
threadId,
requestedTurnCount: 4,
availableTurnCount: 2,
});
const checkpoint = new CheckpointRefUnavailableError({
operation: "CheckpointDiffQuery.getTurnDiff",
threadId,
turnCount: 2,
checkpoint: "to",
});
const workspace = new CheckpointWorkspacePathMissingError({
operation: "CheckpointDiffQuery.getFullThreadDiff",
threadId,
});
expect(range.message).toBe(
"Checkpoint unavailable for thread thread-1 turn 4: Turn diff range exceeds current turn count: requested 4, current 2.",
);
expect(checkpoint.message).toBe(
"Checkpoint unavailable for thread thread-1 turn 2: Checkpoint ref is unavailable for turn 2.",
);
expect(workspace.message).toBe(
"Checkpoint invariant violation in CheckpointDiffQuery.getFullThreadDiff: Workspace path missing for thread 'thread-1' when computing full thread diff.",
);
});
+76 -22
View File
@@ -1,40 +1,94 @@
import { NonNegativeInt, ThreadId, type VcsError } from "@t3tools/contracts";
import * as Schema from "effect/Schema";
import type { ProjectionRepositoryError } from "../persistence/Errors.ts";
import type { VcsError } from "@t3tools/contracts";
/**
* CheckpointUnavailableError - Expected checkpoint does not exist.
*/
export class CheckpointUnavailableError extends Schema.TaggedErrorClass<CheckpointUnavailableError>()(
"CheckpointUnavailableError",
export const CheckpointDiffOperation = Schema.Literals([
"CheckpointDiffQuery.getTurnDiff",
"CheckpointDiffQuery.getFullThreadDiff",
]);
export type CheckpointDiffOperation = typeof CheckpointDiffOperation.Type;
/** The computed result does not satisfy the checkpoint RPC contract. */
export class CheckpointDiffResultInvalidError extends Schema.TaggedErrorClass<CheckpointDiffResultInvalidError>()(
"CheckpointDiffResultInvalidError",
{
threadId: Schema.String,
turnCount: Schema.Number,
detail: Schema.String,
cause: Schema.optional(Schema.Defect()),
operation: CheckpointDiffOperation,
threadId: ThreadId,
},
) {
override get message(): string {
return `Checkpoint unavailable for thread ${this.threadId} turn ${this.turnCount}: ${this.detail}`;
const result =
this.operation === "CheckpointDiffQuery.getTurnDiff" ? "turn diff" : "full thread diff";
return `Checkpoint invariant violation in ${this.operation}: Computed ${result} result does not satisfy contract schema.`;
}
}
/**
* CheckpointInvariantError - Inconsistent provider/filesystem/catalog state.
*/
export class CheckpointInvariantError extends Schema.TaggedErrorClass<CheckpointInvariantError>()(
"CheckpointInvariantError",
/** Projection state no longer contains the requested checkpoint thread. */
export class CheckpointThreadNotFoundError extends Schema.TaggedErrorClass<CheckpointThreadNotFoundError>()(
"CheckpointThreadNotFoundError",
{
operation: Schema.String,
detail: Schema.String,
cause: Schema.optional(Schema.Defect()),
operation: CheckpointDiffOperation,
threadId: ThreadId,
},
) {
override get message(): string {
return `Checkpoint invariant violation in ${this.operation}: ${this.detail}`;
return `Checkpoint invariant violation in ${this.operation}: Thread '${this.threadId}' not found.`;
}
}
export type CheckpointStoreError = VcsError | CheckpointInvariantError | CheckpointUnavailableError;
/** The checkpoint thread has no workspace path from which to compute a diff. */
export class CheckpointWorkspacePathMissingError extends Schema.TaggedErrorClass<CheckpointWorkspacePathMissingError>()(
"CheckpointWorkspacePathMissingError",
{
operation: CheckpointDiffOperation,
threadId: ThreadId,
},
) {
override get message(): string {
const diff =
this.operation === "CheckpointDiffQuery.getTurnDiff" ? "turn diff" : "full thread diff";
return `Checkpoint invariant violation in ${this.operation}: Workspace path missing for thread '${this.threadId}' when computing ${diff}.`;
}
}
export type CheckpointServiceError = CheckpointStoreError | ProjectionRepositoryError;
/** The requested turn lies beyond the latest available checkpoint. */
export class CheckpointTurnRangeUnavailableError extends Schema.TaggedErrorClass<CheckpointTurnRangeUnavailableError>()(
"CheckpointTurnRangeUnavailableError",
{
operation: CheckpointDiffOperation,
threadId: ThreadId,
requestedTurnCount: NonNegativeInt,
availableTurnCount: NonNegativeInt,
},
) {
override get message(): string {
return `Checkpoint unavailable for thread ${this.threadId} turn ${this.requestedTurnCount}: Turn diff range exceeds current turn count: requested ${this.requestedTurnCount}, current ${this.availableTurnCount}.`;
}
}
/** Expected checkpoint metadata does not contain the requested Git ref. */
export class CheckpointRefUnavailableError extends Schema.TaggedErrorClass<CheckpointRefUnavailableError>()(
"CheckpointRefUnavailableError",
{
operation: CheckpointDiffOperation,
threadId: ThreadId,
turnCount: NonNegativeInt,
checkpoint: Schema.Literals(["from", "to"]),
},
) {
override get message(): string {
return `Checkpoint unavailable for thread ${this.threadId} turn ${this.turnCount}: Checkpoint ref is unavailable for turn ${this.turnCount}.`;
}
}
export type CheckpointStoreError = VcsError;
export type CheckpointServiceError =
| CheckpointStoreError
| ProjectionRepositoryError
| CheckpointDiffResultInvalidError
| CheckpointThreadNotFoundError
| CheckpointWorkspacePathMissingError
| CheckpointTurnRangeUnavailableError
| CheckpointRefUnavailableError;
+54 -1
View File
@@ -1,9 +1,14 @@
import * as RelayClient from "@t3tools/shared/relayClient";
import { assert, it } from "@effect/vitest";
import * as Cause from "effect/Cause";
import * as Console from "effect/Console";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Logger from "effect/Logger";
import * as Option from "effect/Option";
import * as References from "effect/References";
import { acquireRelayClientForLink } from "./connect.ts";
import { acquireRelayClientForLink, reportCloudDisconnectResults } from "./connect.ts";
const managedExecutable = {
status: "available",
@@ -100,3 +105,51 @@ it.effect("reuses an available relay client executable without prompting", () =>
assert.equal(promptCalls, 0);
}),
);
it.effect("keeps disconnect causes in structured logs and out of console warnings", () => {
const warnings: ReadonlyArray<unknown>[] = [];
const logs: Readonly<Record<string, unknown>>[] = [];
const testConsole = {
...globalThis.console,
warn: (...args: ReadonlyArray<unknown>) => {
warnings.push(args);
},
} satisfies Console.Console;
const logger = Logger.make(({ fiber }) => {
logs.push(fiber.getRef(References.CurrentLogAnnotations));
});
const liveFailure = "live unlink private diagnostic";
const relayFailure = "relay revoke private diagnostic";
return reportCloudDisconnectResults({
clearAuthorization: true,
liveResult: {
status: "failed",
cause: Cause.fail(new Error(liveFailure)),
},
relayResult: Exit.failCause(Cause.die(new Error(relayFailure))),
}).pipe(
Effect.provideService(Console.Console, testConsole),
Effect.provide(Logger.layer([logger], { mergeWithExisting: false })),
Effect.tap(() =>
Effect.sync(() => {
assert.lengthOf(warnings, 2);
const warningText = warnings.flat().map(String).join("\n");
assert.include(warningText, "running server could not stop its tunnel");
assert.include(warningText, "Could not revoke the relay-side environment record");
assert.notInclude(warningText, liveFailure);
assert.notInclude(warningText, relayFailure);
assert.deepEqual(
logs.map(({ operation, clearAuthorization }) => ({ operation, clearAuthorization })),
[
{ operation: "live-server-unlink", clearAuthorization: true },
{ operation: "relay-environment-unlink", clearAuthorization: true },
],
);
const loggedCauses = logs.map((log) => String(log.cause)).join("\n");
assert.include(loggedCauses, liveFailure);
assert.include(loggedCauses, relayFailure);
}),
),
);
});
+58 -18
View File
@@ -7,6 +7,7 @@ import {
import { RelayOkResponse } from "@t3tools/contracts/relay";
import * as RelayClient from "@t3tools/shared/relayClient";
import { withRelayClientTracing } from "@t3tools/shared/relayTracing";
import * as Cause from "effect/Cause";
import * as Console from "effect/Console";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
@@ -179,7 +180,7 @@ const withCloudCliSessionToken = <A, E, R>(
type LiveCloudActionResult =
| { readonly status: "not-running" }
| { readonly status: "succeeded" }
| { readonly status: "failed"; readonly cause: unknown };
| { readonly status: "failed"; readonly cause: Cause.Cause<unknown> };
const runLiveCloudUnlink = Effect.fn("cloud.cli.run_live_unlink")(function* () {
const config = yield* ServerConfig.ServerConfig;
@@ -211,6 +212,21 @@ type RelayUnlinkResult =
| { readonly status: "revoked" }
| { readonly status: "not-linked" };
type CloudDisconnectOperation = "live-server-unlink" | "relay-environment-unlink";
const logCloudDisconnectFailure = (
operation: CloudDisconnectOperation,
clearAuthorization: boolean,
cause: Cause.Cause<unknown>,
) =>
Effect.logWarning("T3 Connect disconnect operation failed.").pipe(
Effect.annotateLogs({
operation,
clearAuthorization,
cause: Cause.pretty(cause),
}),
);
const unlinkRelayEnvironment = Effect.fn("cloud.cli.unlink_relay_environment")(function* () {
const tokens = yield* CliTokenManager.CloudCliTokenManager;
const token = yield* tokens.getExisting;
@@ -236,6 +252,42 @@ const unlinkRelayEnvironment = Effect.fn("cloud.cli.unlink_relay_environment")(f
: ({ status: "not-linked" } satisfies RelayUnlinkResult);
});
export const reportCloudDisconnectResults = Effect.fn("cloud.cli.report_disconnect_results")(
function* (input: {
readonly clearAuthorization: boolean;
readonly liveResult: LiveCloudActionResult;
readonly relayResult: Exit.Exit<RelayUnlinkResult, unknown>;
}) {
if (input.liveResult.status === "failed") {
yield* logCloudDisconnectFailure(
"live-server-unlink",
input.clearAuthorization,
input.liveResult.cause,
);
yield* Console.warn(
"T3 Connect is disabled, but the running server could not stop its tunnel.\nRestart that server to stop the connector.",
);
} else {
yield* Console.log("T3 Connect is disabled locally.");
}
if (Exit.isFailure(input.relayResult)) {
yield* logCloudDisconnectFailure(
"relay-environment-unlink",
input.clearAuthorization,
input.relayResult.cause,
);
yield* Console.warn(
input.clearAuthorization
? "Could not revoke the relay-side environment record before signing out.\nThe stored CLI authorization was still removed locally."
: "Could not revoke the relay-side environment record yet.\nRun `t3 connect unlink` again when the relay is reachable.",
);
} else if (input.relayResult.value.status === "revoked") {
yield* Console.log("Revoked the relay-side environment record.");
}
},
);
const disconnectCloud = Effect.fn("cloud.cli.disconnect")(function* (options: {
readonly clearAuthorization: boolean;
}) {
@@ -249,23 +301,11 @@ const disconnectCloud = Effect.fn("cloud.cli.disconnect")(function* (options: {
yield* tokens.clear;
}
if (liveResult.status === "failed") {
yield* Console.warn(
`T3 Connect is disabled, but the running server could not stop its tunnel: ${String(liveResult.cause)}\nRestart that server to stop the connector.`,
);
} else {
yield* Console.log("T3 Connect is disabled locally.");
}
if (Exit.isFailure(relayResult)) {
yield* Console.warn(
options.clearAuthorization
? `Could not revoke the relay-side environment record before signing out: ${String(relayResult.cause)}\nThe stored CLI authorization was still removed locally.`
: `Could not revoke the relay-side environment record yet: ${String(relayResult.cause)}\nRun \`t3 connect unlink\` again when the relay is reachable.`,
);
} else if (relayResult.value.status === "revoked") {
yield* Console.log("Revoked the relay-side environment record.");
}
yield* reportCloudDisconnectResults({
clearAuthorization: options.clearAuthorization,
liveResult,
relayResult,
});
if (options.clearAuthorization) {
yield* Console.log("Signed out of T3 Connect locally.");
+37
View File
@@ -0,0 +1,37 @@
import { assert, it } from "@effect/vitest";
import { EnvironmentInternalError } from "@t3tools/contracts";
import {
ProjectLiveServerDeclaredResponseError,
ProjectLiveServerRequestError,
projectCommandErrorFromLiveServerRequest,
} from "./project.ts";
it("maps declared server failures into structural project command errors", () => {
const cause = new EnvironmentInternalError({
code: "internal_error",
reason: "orchestration_snapshot_failed",
traceId: "trace-123",
});
const error = projectCommandErrorFromLiveServerRequest(cause);
assert.instanceOf(error, ProjectLiveServerDeclaredResponseError);
assert.strictEqual(error.operation, "callLiveServer");
assert.strictEqual(error.code, "internal_error");
assert.strictEqual(error.traceId, "trace-123");
assert.strictEqual(error.message, "Server request failed (internal_error, trace trace-123).");
assert.strictEqual(error.cause, cause);
});
it("preserves unexpected server failures without deriving the message from them", () => {
const cause = new Error("credential abc123 was rejected");
const error = projectCommandErrorFromLiveServerRequest(cause);
assert.instanceOf(error, ProjectLiveServerRequestError);
assert.strictEqual(error.operation, "callLiveServer");
assert.strictEqual(error.message, "Failed to call the running server.");
assert.strictEqual(error.cause, cause);
});
+178 -46
View File
@@ -9,11 +9,9 @@ import {
} from "@t3tools/contracts";
import * as Console from "effect/Console";
import * as Crypto from "effect/Crypto";
import * as Data from "effect/Data";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
@@ -52,16 +50,150 @@ type ProjectCliDispatchCommand = Extract<
{ type: "project.create" | "project.meta.update" | "project.delete" }
>;
class ProjectCommandError extends Data.TaggedError("ProjectCommandError")<{
readonly message: string;
}> {}
const isEnvironmentHttpCommonError = Schema.is(EnvironmentHttpCommonError);
export class ProjectCommandIdGenerationError extends Schema.TaggedErrorClass<ProjectCommandIdGenerationError>()(
"ProjectCommandIdGenerationError",
{
operation: Schema.Literal("generateProjectCommandId"),
cause: Schema.Defect(),
},
) {
override get message(): string {
return "Failed to generate a project command identifier.";
}
}
export class ProjectLiveServerDeclaredResponseError extends Schema.TaggedErrorClass<ProjectLiveServerDeclaredResponseError>()(
"ProjectLiveServerDeclaredResponseError",
{
operation: Schema.Literal("callLiveServer"),
code: Schema.String,
traceId: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Server request failed (${this.code}, trace ${this.traceId}).`;
}
}
export class ProjectLiveServerUndeclaredStatusError extends Schema.TaggedErrorClass<ProjectLiveServerUndeclaredStatusError>()(
"ProjectLiveServerUndeclaredStatusError",
{
operation: Schema.Literal("callLiveServer"),
status: Schema.Int,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Server request failed with undeclared status ${this.status}.`;
}
}
export class ProjectLiveServerRequestError extends Schema.TaggedErrorClass<ProjectLiveServerRequestError>()(
"ProjectLiveServerRequestError",
{
operation: Schema.Literal("callLiveServer"),
cause: Schema.Defect(),
},
) {
override get message(): string {
return "Failed to call the running server.";
}
}
export class ProjectTitleEmptyError extends Schema.TaggedErrorClass<ProjectTitleEmptyError>()(
"ProjectTitleEmptyError",
{
operation: Schema.Literal("validateProjectTitle"),
title: Schema.String,
},
) {
override get message(): string {
return "Project title cannot be empty.";
}
}
export class ProjectIdentifierEmptyError extends Schema.TaggedErrorClass<ProjectIdentifierEmptyError>()(
"ProjectIdentifierEmptyError",
{
operation: Schema.Literal("resolveProjectTarget"),
identifier: Schema.String,
},
) {
override get message(): string {
return "Project identifier cannot be empty.";
}
}
export class ProjectNotFoundError extends Schema.TaggedErrorClass<ProjectNotFoundError>()(
"ProjectNotFoundError",
{
operation: Schema.Literal("resolveProjectTarget"),
identifier: Schema.String,
normalizedWorkspaceRoot: Schema.optional(Schema.String),
activeProjectCount: Schema.Number,
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
return `No active project found for '${this.identifier}'.`;
}
}
export class ProjectAlreadyExistsError extends Schema.TaggedErrorClass<ProjectAlreadyExistsError>()(
"ProjectAlreadyExistsError",
{
operation: Schema.Literal("addProject"),
projectId: ProjectId,
workspaceRoot: Schema.String,
},
) {
override get message(): string {
return `An active project already exists for '${this.workspaceRoot}'.`;
}
}
export const ProjectCommandError = Schema.Union([
ProjectCommandIdGenerationError,
ProjectLiveServerDeclaredResponseError,
ProjectLiveServerUndeclaredStatusError,
ProjectLiveServerRequestError,
ProjectTitleEmptyError,
ProjectIdentifierEmptyError,
ProjectNotFoundError,
ProjectAlreadyExistsError,
]);
export type ProjectCommandError = typeof ProjectCommandError.Type;
export function projectCommandErrorFromLiveServerRequest(cause: unknown): ProjectCommandError {
if (isEnvironmentHttpCommonError(cause)) {
return new ProjectLiveServerDeclaredResponseError({
operation: "callLiveServer",
code: cause.code,
traceId: cause.traceId,
cause,
});
}
if (HttpClientError.isHttpClientError(cause) && cause.response !== undefined) {
return new ProjectLiveServerUndeclaredStatusError({
operation: "callLiveServer",
status: cause.response.status,
cause,
});
}
return new ProjectLiveServerRequestError({ operation: "callLiveServer", cause });
}
const projectCommandUuid = Crypto.Crypto.pipe(
Effect.flatMap((crypto) => crypto.randomUUIDv4),
Effect.mapError(
() =>
new ProjectCommandError({
message: "Failed to generate a project command identifier.",
(cause) =>
new ProjectCommandIdGenerationError({
operation: "generateProjectCommandId",
cause,
}),
),
);
@@ -75,7 +207,6 @@ const ProjectCliRuntimeLive = Layer.mergeAll(
);
const PROJECT_CLI_LIVE_SERVER_TIMEOUT = Duration.seconds(1);
const isEnvironmentHttpCommonError = Schema.is(EnvironmentHttpCommonError);
const withProjectCliSessionToken = <A, E, R>(
environmentAuth: EnvironmentAuth.EnvironmentAuth["Service"],
run: (token: string) => Effect.Effect<A, E, R>,
@@ -92,28 +223,6 @@ const withProjectCliSessionToken = <A, E, R>(
const withProjectCliLiveServerTimeout = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
effect.pipe(Effect.timeout(PROJECT_CLI_LIVE_SERVER_TIMEOUT));
const failLiveServerRequest = (cause: unknown) => {
if (isEnvironmentHttpCommonError(cause)) {
return Effect.fail(
new ProjectCommandError({
message: `Server request failed (${cause.code}, trace ${cause.traceId}).`,
}),
);
}
if (HttpClientError.isHttpClientError(cause) && cause.response !== undefined) {
return Effect.fail(
new ProjectCommandError({
message: `Server request failed with undeclared status ${cause.response.status}.`,
}),
);
}
return Effect.fail(
new ProjectCommandError({
message: `Failed to call running server: ${String(cause)}.`,
}),
);
};
const makeLiveServerClient = (origin: string) =>
HttpApiClient.make(EnvironmentHttpApi, {
baseUrl: origin,
@@ -135,7 +244,10 @@ const resolveProjectTitle = Effect.fn("resolveProjectTitle")(function* (
if (trimmed.length > 0) {
return trimmed;
}
return yield* new ProjectCommandError({ message: "Project title cannot be empty." });
return yield* new ProjectTitleEmptyError({
operation: "validateProjectTitle",
title: explicitTitle,
});
}
const path = yield* Path.Path;
@@ -149,7 +261,10 @@ const findActiveProjectTarget = Effect.fn("findActiveProjectTarget")(function* (
}) {
const trimmedIdentifier = input.identifier.trim();
if (trimmedIdentifier.length === 0) {
return yield* new ProjectCommandError({ message: "Project identifier cannot be empty." });
return yield* new ProjectIdentifierEmptyError({
operation: "resolveProjectTarget",
identifier: input.identifier,
});
}
const activeProjects = input.snapshot.projects.filter((project) => project.deletedAt === null);
@@ -162,12 +277,11 @@ const findActiveProjectTarget = Effect.fn("findActiveProjectTarget")(function* (
} satisfies ProjectMutationTarget;
}
const normalizedWorkspaceRootResult = yield* Effect.exit(
const normalizedWorkspaceRootResult = yield* Effect.result(
normalizeWorkspaceRootForProjectCommand(trimmedIdentifier),
);
const normalizedWorkspaceRoot = Exit.isSuccess(normalizedWorkspaceRootResult)
? normalizedWorkspaceRootResult.value
: null;
const normalizedWorkspaceRoot =
normalizedWorkspaceRootResult._tag === "Success" ? normalizedWorkspaceRootResult.success : null;
const exactWorkspaceMatch =
normalizedWorkspaceRoot === null
@@ -176,8 +290,14 @@ const findActiveProjectTarget = Effect.fn("findActiveProjectTarget")(function* (
const resolved = exactWorkspaceMatch;
if (!resolved) {
return yield* new ProjectCommandError({
message: `No active project found for '${trimmedIdentifier}'.`,
return yield* new ProjectNotFoundError({
operation: "resolveProjectTarget",
identifier: trimmedIdentifier,
activeProjectCount: activeProjects.length,
...(normalizedWorkspaceRoot === null ? {} : { normalizedWorkspaceRoot }),
...(normalizedWorkspaceRootResult._tag === "Failure"
? { cause: normalizedWorkspaceRootResult.failure }
: {}),
});
}
@@ -194,7 +314,10 @@ const fetchLiveOrchestrationSnapshot = (origin: string, bearerToken: string) =>
return yield* client.orchestration.snapshot({
headers: { authorization: `Bearer ${bearerToken}` },
});
}).pipe(withProjectCliLiveServerTimeout, Effect.catch(failLiveServerRequest));
}).pipe(
withProjectCliLiveServerTimeout,
Effect.mapError(projectCommandErrorFromLiveServerRequest),
);
const dispatchLiveOrchestrationCommand = (
origin: string,
@@ -207,7 +330,10 @@ const dispatchLiveOrchestrationCommand = (
headers: { authorization: `Bearer ${bearerToken}` },
payload: command,
} as Parameters<typeof client.orchestration.dispatch>[0]);
}).pipe(withProjectCliLiveServerTimeout, Effect.catch(failLiveServerRequest));
}).pipe(
withProjectCliLiveServerTimeout,
Effect.mapError(projectCommandErrorFromLiveServerRequest),
);
const getOfflineSnapshot = Effect.fn("getOfflineSnapshot")(function* () {
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
@@ -232,11 +358,15 @@ const tryResolveLiveProjectExecutionMode = Effect.fn("tryResolveLiveProjectExecu
),
);
const attempted = yield* Effect.exit(attempt);
if (Exit.isSuccess(attempted)) {
return Option.some(attempted.value);
const attempted = yield* Effect.result(attempt);
if (attempted._tag === "Success") {
return Option.some(attempted.success);
}
yield* Effect.logDebug("Failed to connect to the persisted project CLI server.", {
origin: runtimeState.value.origin,
cause: attempted.failure,
});
yield* clearPersistedServerRuntimeState(config.serverRuntimeStatePath);
return Option.none<{ readonly origin: string }>();
},
@@ -334,8 +464,10 @@ const projectAddCommand = Command.make("add", {
(project) => project.deletedAt === null && project.workspaceRoot === workspaceRoot,
);
if (existingProject) {
return yield* new ProjectCommandError({
message: `An active project already exists for '${workspaceRoot}'.`,
return yield* new ProjectAlreadyExistsError({
operation: "addProject",
projectId: existingProject.id,
workspaceRoot,
});
}
@@ -3,8 +3,10 @@ import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Logger from "effect/Logger";
import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError";
import * as References from "effect/References";
import * as TraceDiagnostics from "./TraceDiagnostics.ts";
@@ -187,18 +189,17 @@ describe("TraceDiagnostics", () => {
it.effect("keeps loaded trace data when one rotated trace file fails to read", () =>
Effect.gen(function* () {
const traceFilePath = "/tmp/server.trace.ndjson";
const readFailure = PlatformError.systemError({
_tag: "PermissionDenied",
module: "FileSystem",
method: "readFileString",
description: "permission denied",
pathOrDescriptor: `${traceFilePath}.1`,
});
const fileSystemLayer = FileSystem.layerNoop({
readFileString: (path) =>
path === `${traceFilePath}.1`
? Effect.fail(
PlatformError.systemError({
_tag: "PermissionDenied",
module: "FileSystem",
method: "readFileString",
description: "permission denied",
pathOrDescriptor: path,
}),
)
? Effect.fail(readFailure)
: Effect.succeed(
record({
name: "server.getConfig",
@@ -209,20 +210,44 @@ describe("TraceDiagnostics", () => {
}),
),
});
const logAnnotations: Array<Record<string, unknown>> = [];
const logger = Logger.make<unknown, void>((options) => {
logAnnotations.push({ ...options.fiber.getRef(References.CurrentLogAnnotations) });
});
const diagnostics = yield* TraceDiagnostics.readTraceDiagnostics({
traceFilePath,
maxFiles: 1,
readAt: DateTime.makeUnsafe("2026-05-05T10:00:00.000Z"),
}).pipe(Effect.provide(TraceDiagnostics.layer.pipe(Layer.provide(fileSystemLayer))));
}).pipe(
Effect.provide(
Layer.mergeAll(
TraceDiagnostics.layer.pipe(Layer.provide(fileSystemLayer)),
Logger.layer([logger], { mergeWithExisting: false }),
),
),
);
assert.equal(diagnostics.recordCount, 1);
assert.equal(
Option.getOrElse(diagnostics.partialFailure, () => false),
true,
);
assert.equal(Option.getOrUndefined(diagnostics.error)?.kind, "trace-file-read-failed");
assert.deepStrictEqual(Option.getOrUndefined(diagnostics.error), {
kind: "trace-file-read-failed",
message: `Failed to read local trace file '${traceFilePath}.1'.`,
});
assert.deepStrictEqual(diagnostics.scannedFilePaths, [`${traceFilePath}.1`, traceFilePath]);
const failureLog = logAnnotations.find(
(annotations) => annotations.traceFilePath === `${traceFilePath}.1`,
);
assert.exists(failureLog);
assert.deepStrictEqual(failureLog, {
traceFilePath: `${traceFilePath}.1`,
errorTag: "TraceFileReadError",
causeTag: "PermissionDenied",
});
}),
);
+49 -19
View File
@@ -14,6 +14,8 @@ 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 Result from "effect/Result";
import * as Schema from "effect/Schema";
interface TraceRecordLike {
readonly name?: unknown;
@@ -39,6 +41,19 @@ export interface TraceDiagnosticsOptions {
readonly readAt?: DateTime.Utc;
}
export class TraceFileReadError extends Schema.TaggedErrorClass<TraceFileReadError>()(
"TraceFileReadError",
{
traceFilePath: Schema.String,
causeTag: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to read local trace file '${this.traceFilePath}'.`;
}
}
export class TraceDiagnostics extends Context.Service<
TraceDiagnostics,
{
@@ -153,10 +168,6 @@ function isNotFoundError(error: PlatformError.PlatformError): boolean {
return error.reason._tag === "NotFound";
}
function platformErrorMessage(error: PlatformError.PlatformError): string {
return error.message || String(error);
}
function insertBoundedSlowestSpan(
slowestSpans: ServerTraceDiagnosticsSpanOccurrence[],
span: ServerTraceDiagnosticsSpanOccurrence,
@@ -377,22 +388,26 @@ export function aggregateTraceDiagnostics(
type TraceFileReadResult =
| { readonly _tag: "Loaded"; readonly path: string; readonly text: string }
| { readonly _tag: "Missing"; readonly path: string }
| { readonly _tag: "Failed"; readonly path: string; readonly message: string };
| { readonly _tag: "Missing"; readonly path: string };
function readTraceFile(
fileSystem: FileSystem.FileSystem,
path: string,
): Effect.Effect<TraceFileReadResult> {
): Effect.Effect<TraceFileReadResult, TraceFileReadError> {
return fileSystem.readFileString(path).pipe(
Effect.map((text) => ({ _tag: "Loaded" as const, path, text })),
Effect.catch((error: PlatformError.PlatformError) =>
Effect.succeed(
isNotFoundError(error)
? { _tag: "Missing" as const, path }
: { _tag: "Failed" as const, path, message: platformErrorMessage(error) },
),
),
Effect.map((text): TraceFileReadResult => ({ _tag: "Loaded", path, text })),
Effect.catchTags({
PlatformError: (cause) =>
isNotFoundError(cause)
? Effect.succeed<TraceFileReadResult>({ _tag: "Missing", path })
: Effect.fail(
new TraceFileReadError({
traceFilePath: path,
causeTag: cause.reason._tag,
cause,
}),
),
}),
);
}
@@ -405,19 +420,34 @@ export const make = Effect.gen(function* () {
const slowSpanThresholdMs = options.slowSpanThresholdMs ?? DEFAULT_SLOW_SPAN_THRESHOLD_MS;
const paths = toRotatedTracePaths(options.traceFilePath, options.maxFiles);
const results = yield* Effect.all(
paths.map((path) => readTraceFile(fileSystem, path)),
paths.map((path) =>
readTraceFile(fileSystem, path).pipe(
Effect.tapError((cause) =>
Effect.logWarning("Failed to read local trace file.").pipe(
Effect.annotateLogs({
traceFilePath: cause.traceFilePath,
errorTag: cause._tag,
causeTag: cause.causeTag,
}),
),
),
Effect.result,
),
),
{
concurrency: 1,
},
);
const files = results.flatMap((result) =>
result._tag === "Loaded" ? [{ path: result.path, text: result.text }] : [],
Result.isSuccess(result) && result.success._tag === "Loaded"
? [{ path: result.success.path, text: result.success.text }]
: [],
);
const readFailure = results.find((result) => result._tag === "Failed");
const readFailure = results.find(Result.isFailure);
const readFailureError = readFailure
? ({
kind: "trace-file-read-failed",
message: readFailure.message.trim() || `Failed to read ${readFailure.path}.`,
message: readFailure.failure.message,
} satisfies TraceDiagnosticsErrorSummary)
: undefined;
@@ -2,12 +2,28 @@ import { afterEach, describe, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Logger from "effect/Logger";
import * as PlatformError from "effect/PlatformError";
import * as References from "effect/References";
import * as Schema from "effect/Schema";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
import { HostProcessHostname, HostProcessPlatform } from "@t3tools/shared/hostProcess";
import { vi } from "vite-plus/test";
import * as ProcessRunner from "../processRunner.ts";
import { resolveServerEnvironmentLabel } from "./ServerEnvironmentLabel.ts";
import * as ServerEnvironmentLabel from "./ServerEnvironmentLabel.ts";
const isServerEnvironmentLabelFileError = Schema.is(
ServerEnvironmentLabel.ServerEnvironmentLabelFileError,
);
const isServerEnvironmentLabelCommandError = Schema.is(
ServerEnvironmentLabel.ServerEnvironmentLabelCommandError,
);
interface CapturedLog {
readonly message: unknown;
readonly annotations: Readonly<Record<string, unknown>>;
}
const runMock = vi.fn<ProcessRunner.ProcessRunner["Service"]["run"]>();
@@ -47,7 +63,7 @@ afterEach(() => {
describe("resolveServerEnvironmentLabel", () => {
it.effect("uses hostname fallback regardless of launch mode", () =>
Effect.gen(function* () {
const result = yield* resolveServerEnvironmentLabel({
const result = yield* ServerEnvironmentLabel.resolveServerEnvironmentLabel({
cwdBaseName: "t3code",
}).pipe(Effect.provide(withHostPlatform(TestLayer, "win32", "macbook-pro")));
@@ -68,7 +84,7 @@ describe("resolveServerEnvironmentLabel", () => {
}),
);
const result = yield* resolveServerEnvironmentLabel({
const result = yield* ServerEnvironmentLabel.resolveServerEnvironmentLabel({
cwdBaseName: "t3code",
}).pipe(Effect.provide(withHostPlatform(TestLayer, "darwin", "macbook-pro")));
@@ -85,7 +101,7 @@ describe("resolveServerEnvironmentLabel", () => {
it.effect("prefers Linux PRETTY_HOSTNAME from machine-info", () =>
Effect.gen(function* () {
const result = yield* resolveServerEnvironmentLabel({
const result = yield* ServerEnvironmentLabel.resolveServerEnvironmentLabel({
cwdBaseName: "t3code",
}).pipe(Effect.provide(withHostPlatform(LinuxMachineInfoLayer, "linux", "buildbox")));
@@ -107,7 +123,7 @@ describe("resolveServerEnvironmentLabel", () => {
}),
);
const result = yield* resolveServerEnvironmentLabel({
const result = yield* ServerEnvironmentLabel.resolveServerEnvironmentLabel({
cwdBaseName: "t3code",
}).pipe(Effect.provide(withHostPlatform(TestLayer, "linux", "runner-01")));
@@ -124,7 +140,7 @@ describe("resolveServerEnvironmentLabel", () => {
it.effect("falls back to the hostname when friendly labels are unavailable", () =>
Effect.gen(function* () {
const result = yield* resolveServerEnvironmentLabel({
const result = yield* ServerEnvironmentLabel.resolveServerEnvironmentLabel({
cwdBaseName: "t3code",
}).pipe(Effect.provide(withHostPlatform(TestLayer, "win32", "JULIUS-LAPTOP")));
@@ -132,25 +148,111 @@ describe("resolveServerEnvironmentLabel", () => {
}),
);
it.effect("falls back to the hostname when the friendly-label command is missing", () =>
Effect.gen(function* () {
runMock.mockReturnValueOnce(
Effect.fail(
new ProcessRunner.ProcessSpawnError({
command: "scutil",
argumentCount: 2,
cause: new Error("spawn scutil ENOENT"),
}),
),
);
it.effect("falls back to the hostname when the friendly-label command is missing", () => {
const logs: CapturedLog[] = [];
const logger = Logger.make(({ fiber, message }) => {
logs.push({
message,
annotations: fiber.getRef(References.CurrentLogAnnotations),
});
});
const spawnCause = new Error("spawn scutil ENOENT");
const processError = new ProcessRunner.ProcessSpawnError({
command: "scutil",
argumentCount: 2,
cause: spawnCause,
});
runMock.mockReturnValueOnce(Effect.fail(processError));
const result = yield* resolveServerEnvironmentLabel({
return Effect.gen(function* () {
const result = yield* ServerEnvironmentLabel.resolveServerEnvironmentLabel({
cwdBaseName: "t3code",
}).pipe(Effect.provide(withHostPlatform(TestLayer, "darwin", "macbook-pro")));
});
expect(result).toBe("macbook-pro");
}),
);
expect(logs[0]?.message).toEqual([
"Failed to run environment-label probe 'macos-computer-name' with scutil.",
]);
const error = logs[0]?.annotations.cause;
expect(isServerEnvironmentLabelCommandError(error)).toBe(true);
if (isServerEnvironmentLabelCommandError(error)) {
expect(error.probe).toBe("macos-computer-name");
expect(error.executable).toBe("scutil");
expect(error.argumentCount).toBe(2);
expect(error).not.toHaveProperty("args");
expect(error.message).not.toContain("--get");
expect(error.message).not.toContain("ComputerName");
expect(error.cause).toBe(processError);
expect(processError.cause).toBe(spawnCause);
}
}).pipe(
Effect.provide(
Layer.mergeAll(
withHostPlatform(TestLayer, "darwin", "macbook-pro"),
Logger.layer([logger], { mergeWithExisting: false }),
Layer.succeed(References.MinimumLogLevel, "Debug"),
),
),
);
});
it.effect("continues to hostnamectl after a machine-info inspect failure", () => {
const logs: CapturedLog[] = [];
const logger = Logger.make(({ fiber, message }) => {
logs.push({
message,
annotations: fiber.getRef(References.CurrentLogAnnotations),
});
});
const fileCause = new Error("permission denied");
const platformError = PlatformError.systemError({
_tag: "PermissionDenied",
module: "FileSystem",
method: "exists",
pathOrDescriptor: "/etc/machine-info",
cause: fileCause,
});
const fileSystemLayer = FileSystem.layerNoop({
exists: () => Effect.fail(platformError),
});
runMock.mockReturnValueOnce(
Effect.succeed({
stdout: "CI Runner\n",
stderr: "",
code: ChildProcessSpawner.ExitCode(0),
timedOut: false,
stdoutTruncated: false,
stderrTruncated: false,
}),
);
return Effect.gen(function* () {
const result = yield* ServerEnvironmentLabel.resolveServerEnvironmentLabel({
cwdBaseName: "t3code",
});
expect(result).toBe("CI Runner");
expect(logs[0]?.message).toEqual([
"Failed to inspect environment-label file at /etc/machine-info.",
]);
const error = logs[0]?.annotations.cause;
expect(isServerEnvironmentLabelFileError(error)).toBe(true);
if (isServerEnvironmentLabelFileError(error)) {
expect(error.operation).toBe("inspect");
expect(error.path).toBe("/etc/machine-info");
expect(error.cause).toBe(platformError);
expect(platformError.cause).toBe(fileCause);
}
}).pipe(
Effect.provide(
Layer.mergeAll(
withHostPlatform(Layer.merge(ProcessRunnerTest, fileSystemLayer), "linux", "buildbox"),
Logger.layer([logger], { mergeWithExisting: false }),
Layer.succeed(References.MinimumLogLevel, "Debug"),
),
),
);
});
it.effect("falls back to the cwd basename when the hostname is blank", () =>
Effect.gen(function* () {
@@ -165,7 +267,7 @@ describe("resolveServerEnvironmentLabel", () => {
}),
);
const result = yield* resolveServerEnvironmentLabel({
const result = yield* ServerEnvironmentLabel.resolveServerEnvironmentLabel({
cwdBaseName: "t3code",
}).pipe(Effect.provide(withHostPlatform(TestLayer, "linux", " ")));
@@ -2,6 +2,7 @@ import { HostProcessHostname, HostProcessPlatform } from "@t3tools/shared/hostPr
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as ProcessRunner from "../processRunner.ts";
@@ -9,6 +10,39 @@ interface ResolveServerEnvironmentLabelInput {
readonly cwdBaseName: string;
}
const ServerEnvironmentLabelCommandProbe = Schema.Literals([
"macos-computer-name",
"linux-pretty-hostname",
]);
type ServerEnvironmentLabelCommandProbe = typeof ServerEnvironmentLabelCommandProbe.Type;
export class ServerEnvironmentLabelFileError extends Schema.TaggedErrorClass<ServerEnvironmentLabelFileError>()(
"ServerEnvironmentLabelFileError",
{
operation: Schema.Literals(["inspect", "read"]),
path: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to ${this.operation} environment-label file at ${this.path}.`;
}
}
export class ServerEnvironmentLabelCommandError extends Schema.TaggedErrorClass<ServerEnvironmentLabelCommandError>()(
"ServerEnvironmentLabelCommandError",
{
probe: ServerEnvironmentLabelCommandProbe,
executable: Schema.String,
argumentCount: Schema.Number,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to run environment-label probe '${this.probe}' with ${this.executable}.`;
}
}
function normalizeLabel(value: string | null | undefined): string | null {
const trimmed = value?.trim();
return trimmed && trimmed.length > 0 ? trimmed : null;
@@ -34,30 +68,80 @@ function parseMachineInfoValue(raw: string, key: string): string | null {
const readLinuxMachineInfo = Effect.fn("readLinuxMachineInfo")(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const exists = yield* fileSystem
.exists("/etc/machine-info")
.pipe(Effect.orElseSucceed(() => false));
if (!exists) {
return null;
}
return yield* fileSystem
.readFileString("/etc/machine-info")
.pipe(Effect.orElseSucceed(() => null));
const machineInfoPath = "/etc/machine-info";
return yield* fileSystem.exists(machineInfoPath).pipe(
Effect.mapError(
(cause) =>
new ServerEnvironmentLabelFileError({
operation: "inspect",
path: machineInfoPath,
cause,
}),
),
Effect.flatMap((exists) =>
exists
? fileSystem.readFileString(machineInfoPath).pipe(
Effect.mapError(
(cause) =>
new ServerEnvironmentLabelFileError({
operation: "read",
path: machineInfoPath,
cause,
}),
),
)
: Effect.succeed(null),
),
Effect.catchTags({
ServerEnvironmentLabelFileError: (error) =>
Effect.logDebug(error.message).pipe(
Effect.annotateLogs({
operation: error.operation,
path: error.path,
cause: error,
}),
Effect.as(null),
),
}),
);
});
const runFriendlyLabelCommand = Effect.fn("runFriendlyLabelCommand")(function* (
command: string,
args: readonly string[],
) {
const runFriendlyLabelCommand = Effect.fn("runFriendlyLabelCommand")(function* (input: {
readonly probe: ServerEnvironmentLabelCommandProbe;
readonly command: string;
readonly args: readonly string[];
}) {
const processRunner = yield* ProcessRunner.ProcessRunner;
const result = yield* processRunner
.run({
command,
args,
command: input.command,
args: input.args,
timeoutBehavior: "timedOutResult",
})
.pipe(Effect.option);
.pipe(
Effect.mapError(
(cause) =>
new ServerEnvironmentLabelCommandError({
probe: input.probe,
executable: input.command,
argumentCount: input.args.length,
cause,
}),
),
Effect.map(Option.some),
Effect.catchTags({
ServerEnvironmentLabelCommandError: (error) =>
Effect.logDebug(error.message).pipe(
Effect.annotateLogs({
probe: error.probe,
executable: error.executable,
argumentCount: error.argumentCount,
cause: error,
}),
Effect.as(Option.none()),
),
}),
);
if (Option.isNone(result) || result.value.code !== 0) {
return null;
@@ -69,7 +153,11 @@ const runFriendlyLabelCommand = Effect.fn("runFriendlyLabelCommand")(function* (
const resolveFriendlyHostLabel = Effect.fn("resolveFriendlyHostLabel")(function* () {
const platform = yield* HostProcessPlatform;
if (platform === "darwin") {
return yield* runFriendlyLabelCommand("scutil", ["--get", "ComputerName"]);
return yield* runFriendlyLabelCommand({
probe: "macos-computer-name",
command: "scutil",
args: ["--get", "ComputerName"],
});
}
if (platform === "linux") {
@@ -81,7 +169,11 @@ const resolveFriendlyHostLabel = Effect.fn("resolveFriendlyHostLabel")(function*
}
}
return yield* runFriendlyLabelCommand("hostnamectl", ["--pretty"]);
return yield* runFriendlyLabelCommand({
probe: "linux-pretty-hostname",
command: "hostnamectl",
args: ["--pretty"],
});
}
return null;
+84 -45
View File
@@ -171,20 +171,8 @@ function runGitSyncForFakeGh(cwd: string, args: readonly string[]): void {
if (result.status === 0) {
return;
}
throw new GitHubCli.GitHubCliError({
operation: "execute",
command: "gh",
cwd,
detail: `Failed to simulate gh checkout with git ${args.join(" ")}: ${result.stderr?.trim() || "unknown error"}`,
});
}
function isGitHubCliError(error: unknown): error is GitHubCli.GitHubCliError {
return (
typeof error === "object" &&
error !== null &&
"_tag" in error &&
(error as { _tag?: unknown })._tag === "GitHubCliError"
throw new Error(
`Failed to simulate gh checkout with git ${args.join(" ")}: ${result.stderr?.trim() || "unknown error"}`,
);
}
@@ -478,16 +466,12 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
return fakeGhOutput("");
},
catch: (error) =>
isGitHubCliError(error)
GitHubCli.isGitHubCliError(error)
? error
: new GitHubCli.GitHubCliError({
operation: "execute",
: new GitHubCli.GitHubCliCommandError({
command: "gh",
cwd: input.cwd,
detail:
error instanceof Error
? `Failed to simulate gh checkout: ${error.message}`
: "Failed to simulate gh checkout.",
cause: error,
}),
});
}
@@ -498,11 +482,10 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
const cloneUrls = scenario.repositoryCloneUrls?.[repository];
if (!cloneUrls) {
return Effect.fail(
new GitHubCli.GitHubCliError({
operation: "execute",
new GitHubCli.GitHubCliCommandError({
command: "gh",
cwd: input.cwd,
detail: `Unexpected repository lookup: ${repository}`,
cause: new Error(`Unexpected repository lookup: ${repository}`),
}),
);
}
@@ -520,11 +503,10 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
}
return Effect.fail(
new GitHubCli.GitHubCliError({
operation: "execute",
new GitHubCli.GitHubCliCommandError({
command: "gh",
cwd: input.cwd,
detail: `Unexpected gh command: ${args.join(" ")}`,
cause: new Error(`Unexpected gh command: ${args.join(" ")}`),
}),
);
};
@@ -601,11 +583,10 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
}).pipe(Effect.map((result) => JSON.parse(result.stdout))),
createRepository: (input) =>
Effect.fail(
new GitHubCli.GitHubCliError({
operation: "createRepository",
new GitHubCli.GitHubCliCommandError({
command: "gh",
cwd: input.cwd,
detail: `Unexpected repository create: ${input.repository}`,
cause: new Error(`Unexpected repository create: ${input.repository}`),
}),
),
checkoutPullRequest: (input) =>
@@ -1341,11 +1322,10 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
const { manager } = yield* makeManager({
ghScenario: {
failWith: new GitHubCli.GitHubCliError({
operation: "execute",
failWith: new GitHubCli.GitHubCliUnavailableError({
command: "gh",
cwd: repoDir,
detail: "GitHub CLI (`gh`) is required but not available on PATH.",
cause: new Error("gh is not available on PATH"),
}),
},
});
@@ -1589,16 +1569,18 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
yield* initRepo(repoDir);
const { manager } = yield* makeManager();
const errorMessage = yield* runStackedAction(manager, {
const error = yield* runStackedAction(manager, {
cwd: repoDir,
action: "commit",
featureBranch: true,
}).pipe(
Effect.flip,
Effect.map((error) => error.message),
);
}).pipe(Effect.flip);
expect(errorMessage).toContain("no changes to commit");
expect(error).toMatchObject({
_tag: "GitManagerError",
operation: "runFeatureBranchStep",
cwd: repoDir,
});
expect(error.message).toContain("no changes to commit");
}),
);
@@ -2481,11 +2463,10 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
const { manager } = yield* makeManager({
ghScenario: {
failWith: new GitHubCli.GitHubCliError({
operation: "execute",
failWith: new GitHubCli.GitHubCliUnavailableError({
command: "gh",
cwd: repoDir,
detail: "GitHub CLI (`gh`) is required but not available on PATH.",
cause: new Error("gh is not available on PATH"),
}),
},
});
@@ -2512,11 +2493,10 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
const { manager } = yield* makeManager({
ghScenario: {
failWith: new GitHubCli.GitHubCliError({
operation: "execute",
failWith: new GitHubCli.GitHubCliAuthenticationError({
command: "gh",
cwd: repoDir,
detail: "GitHub CLI is not authenticated. Run `gh auth login` and retry.",
cause: new Error("gh is not authenticated"),
}),
},
});
@@ -2755,6 +2735,65 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);
it.effect("preserves both branch materialization failures when the fallback also fails", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
const originDir = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "origin", originDir]);
yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
const missingForkDir = NodePath.join(repoDir, "missing-fork.git");
const { manager } = yield* makeManager({
ghScenario: {
pullRequest: {
number: 93,
title: "Missing fork branch",
url: "https://github.com/pingdotgg/codething-mvp/pull/93",
baseRefName: "main",
headRefName: "feature/missing-fork-branch",
state: "open",
isCrossRepository: true,
headRepositoryNameWithOwner: "octocat/codething-mvp",
headRepositoryOwnerLogin: "octocat",
},
repositoryCloneUrls: {
"octocat/codething-mvp": {
url: missingForkDir,
sshUrl: missingForkDir,
},
},
},
});
const error = yield* preparePullRequestThread(manager, {
cwd: repoDir,
reference: "93",
mode: "worktree",
}).pipe(Effect.flip);
if (error._tag !== "GitPullRequestMaterializationError") {
return yield* Effect.die(error);
}
expect(error).toMatchObject({
cwd: repoDir,
pullRequestNumber: 93,
headRepository: "octocat/codething-mvp",
headBranch: "feature/missing-fork-branch",
localBranch: "t3code/pr-93/feature/missing-fork-branch",
});
if (!(error.cause instanceof AggregateError)) {
return yield* Effect.die(error.cause);
}
expect(error.cause.errors).toHaveLength(2);
expect(error.cause.errors).toEqual([
expect.objectContaining({ _tag: "GitCommandError" }),
expect.objectContaining({ _tag: "GitCommandError" }),
]);
expect(error.cause.cause).toBe(error.cause.errors[0]);
}),
);
it.effect("launches setup only when creating a new PR worktree", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
+122 -70
View File
@@ -41,7 +41,7 @@ import {
type ChangeRequestTerminology,
} from "@t3tools/shared/sourceControl";
import { GitManagerError } from "@t3tools/contracts";
import { GitManagerError, GitPullRequestMaterializationError } from "@t3tools/contracts";
import * as TextGeneration from "../textGeneration/TextGeneration.ts";
import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts";
import { extractBranchNameFromRemoteRef } from "./remoteRefs.ts";
@@ -320,14 +320,6 @@ function toPullRequestInfo(summary: ChangeRequest): PullRequestInfo {
};
}
function gitManagerError(operation: string, detail: string, cause?: unknown): GitManagerError {
return new GitManagerError({
operation,
detail,
...(cause !== undefined ? { cause } : {}),
});
}
function limitContext(value: string, maxChars: number): string {
if (value.length <= maxChars) return value;
return `${value.slice(0, maxChars)}\n\n[truncated]`;
@@ -535,17 +527,27 @@ export const make = Effect.gen(function* () {
const sourceControlProvider = (cwd: string) => sourceControlProviders.resolve({ cwd });
const serverSettingsService = yield* ServerSettings.ServerSettingsService;
const randomUUIDv4 = crypto.randomUUIDv4.pipe(
Effect.mapError((cause) =>
gitManagerError("randomUUIDv4", "Failed to generate Git operation identifier.", cause),
),
);
const randomUUIDv4 = (cwd: string) =>
crypto.randomUUIDv4.pipe(
Effect.mapError(
(cause) =>
new GitManagerError({
operation: "randomUUIDv4",
cwd,
detail: "Failed to generate Git operation identifier.",
cause,
}),
),
);
const createProgressEmitter = (
input: { cwd: string; action: GitStackedAction },
options?: GitRunStackedActionOptions,
) =>
(options?.actionId === undefined ? randomUUIDv4 : Effect.succeed(options.actionId)).pipe(
(options?.actionId === undefined
? randomUUIDv4(input.cwd)
: Effect.succeed(options.actionId)
).pipe(
Effect.map((actionId) => {
const reporter = options?.progressReporter;
const emit = (event: GitActionProgressPayload) =>
@@ -629,9 +631,12 @@ export const make = Effect.gen(function* () {
) =>
configurePullRequestHeadUpstreamBase(cwd, pullRequest, localBranch).pipe(
Effect.catch((error) =>
Effect.logWarning(
`GitManager.configurePullRequestHeadUpstream: failed to configure upstream for ${localBranch} -> ${pullRequest.headBranch} in ${cwd}: ${error.message}`,
).pipe(Effect.asVoid),
Effect.logWarning("GitManager.configurePullRequestHeadUpstream failed", {
cwd,
localBranch,
headBranch: pullRequest.headBranch,
cause: error,
}).pipe(Effect.asVoid),
),
);
@@ -689,12 +694,30 @@ export const make = Effect.gen(function* () {
localBranch = pullRequest.headBranch,
) =>
materializePullRequestHeadBranchBase(cwd, pullRequest, localBranch).pipe(
Effect.catch(() =>
gitCore.fetchPullRequestBranch({
cwd,
prNumber: pullRequest.number,
branch: localBranch,
}),
Effect.catch((primaryCause) =>
gitCore
.fetchPullRequestBranch({
cwd,
prNumber: pullRequest.number,
branch: localBranch,
})
.pipe(
Effect.mapError(
(fallbackCause) =>
new GitPullRequestMaterializationError({
cwd,
pullRequestNumber: pullRequest.number,
headRepository: resolveHeadRepositoryNameWithOwner(pullRequest),
headBranch: pullRequest.headBranch,
localBranch,
cause: new AggregateError(
[primaryCause, fallbackCause],
`Repository-head and pull-request-ref fetches both failed for pull request #${pullRequest.number}.`,
{ cause: primaryCause },
),
}),
),
),
),
);
const fileSystem = yield* FileSystem.FileSystem;
@@ -1284,16 +1307,18 @@ export const make = Effect.gen(function* () {
const details = yield* gitCore.statusDetails(cwd);
const branch = details.branch ?? fallbackBranch;
if (!branch) {
return yield* gitManagerError(
"runPrStep",
"Cannot create a pull request from detached HEAD.",
);
return yield* new GitManagerError({
operation: "runPrStep",
cwd,
detail: "Cannot create a pull request from detached HEAD.",
});
}
if (!details.hasUpstream) {
return yield* gitManagerError(
"runPrStep",
"Current branch has not been pushed. Push before creating a PR.",
);
return yield* new GitManagerError({
operation: "runPrStep",
cwd,
detail: "Current branch has not been pushed. Push before creating a PR.",
});
}
const headContext = yield* resolveBranchHeadContext(cwd, {
@@ -1332,14 +1357,21 @@ export const make = Effect.gen(function* () {
modelSelection,
});
const bodyFile = path.join(tempDir, `t3code-pr-body-${process.pid}-${yield* randomUUIDv4}.md`);
yield* fileSystem
.writeFileString(bodyFile, generated.body)
.pipe(
Effect.mapError((cause) =>
gitManagerError("runPrStep", "Failed to write pull request body temp file.", cause),
),
);
const bodyFile = path.join(
tempDir,
`t3code-pr-body-${process.pid}-${yield* randomUUIDv4(cwd)}.md`,
);
yield* fileSystem.writeFileString(bodyFile, generated.body).pipe(
Effect.mapError(
(cause) =>
new GitManagerError({
operation: "runPrStep",
cwd,
detail: "Failed to write pull request body temp file.",
cause,
}),
),
);
yield* emit({
kind: "phase_started",
phase: "pr",
@@ -1441,9 +1473,11 @@ export const make = Effect.gen(function* () {
})
.pipe(
Effect.catch((error) =>
Effect.logWarning(
`GitManager.preparePullRequestThread: failed to launch worktree setup script for thread ${input.threadId} in ${worktreePath}: ${error.message}`,
).pipe(Effect.asVoid),
Effect.logWarning("GitManager.preparePullRequestThread setup script failed", {
threadId: input.threadId,
worktreePath,
cause: error,
}).pipe(Effect.asVoid),
),
);
};
@@ -1541,10 +1575,12 @@ export const make = Effect.gen(function* () {
};
}
if (existingBranchBeforeFetchPath === rootWorktreePath) {
return yield* gitManagerError(
"preparePullRequestThread",
"This PR branch is already checked out in the main repo. Use Local, or switch the main repo off that branch before creating a worktree thread.",
);
return yield* new GitManagerError({
operation: "preparePullRequestThread",
cwd: input.cwd,
detail:
"This PR branch is already checked out in the main repo. Use Local, or switch the main repo off that branch before creating a worktree thread.",
});
}
yield* materializePullRequestHeadBranch(
@@ -1569,10 +1605,12 @@ export const make = Effect.gen(function* () {
};
}
if (existingBranchAfterFetchPath === rootWorktreePath) {
return yield* gitManagerError(
"preparePullRequestThread",
"This PR branch is already checked out in the main repo. Use Local, or switch the main repo off that branch before creating a worktree thread.",
);
return yield* new GitManagerError({
operation: "preparePullRequestThread",
cwd: input.cwd,
detail:
"This PR branch is already checked out in the main repo. Use Local, or switch the main repo off that branch before creating a worktree thread.",
});
}
const worktree = yield* gitCore.createWorktree({
@@ -1607,10 +1645,11 @@ export const make = Effect.gen(function* () {
modelSelection,
});
if (!suggestion) {
return yield* gitManagerError(
"runFeatureBranchStep",
"Cannot create a feature branch because there are no changes to commit.",
);
return yield* new GitManagerError({
operation: "runFeatureBranchStep",
cwd,
detail: "Cannot create a feature branch because there are no changes to commit.",
});
}
const preferredBranch = suggestion.branch ?? sanitizeFeatureBranchName(suggestion.subject);
@@ -1647,16 +1686,18 @@ export const make = Effect.gen(function* () {
const wantsPr = input.action === "create_pr" || input.action === "commit_push_pr";
if (input.featureBranch && !wantsCommit) {
return yield* gitManagerError(
"runStackedAction",
"Feature-branch checkout is only supported for commit actions.",
);
return yield* new GitManagerError({
operation: "runStackedAction",
cwd: input.cwd,
detail: "Feature-branch checkout is only supported for commit actions.",
});
}
if (input.action === "create_pr" && initialStatus.hasWorkingTreeChanges) {
return yield* gitManagerError(
"runStackedAction",
"Commit local changes before creating a PR.",
);
return yield* new GitManagerError({
operation: "runStackedAction",
cwd: input.cwd,
detail: "Commit local changes before creating a PR.",
});
}
const phases: GitActionProgressPhase[] = [
@@ -1672,13 +1713,18 @@ export const make = Effect.gen(function* () {
});
if (!input.featureBranch && wantsPush && !initialStatus.branch) {
return yield* gitManagerError("runStackedAction", "Cannot push from detached HEAD.");
return yield* new GitManagerError({
operation: "runStackedAction",
cwd: input.cwd,
detail: "Cannot push from detached HEAD.",
});
}
if (!input.featureBranch && wantsPr && !initialStatus.branch) {
return yield* gitManagerError(
"runStackedAction",
"Cannot create a pull request from detached HEAD.",
);
return yield* new GitManagerError({
operation: "runStackedAction",
cwd: input.cwd,
detail: "Cannot create a pull request from detached HEAD.",
});
}
let branchStep: { status: "created" | "skipped_not_requested"; name?: string };
@@ -1687,8 +1733,14 @@ export const make = Effect.gen(function* () {
const modelSelection = yield* serverSettingsService.getSettings.pipe(
Effect.map((settings) => settings.textGenerationModelSelection),
Effect.mapError((cause) =>
gitManagerError("runStackedAction", "Failed to get server settings.", cause),
Effect.mapError(
(cause) =>
new GitManagerError({
operation: "runStackedAction",
cwd: input.cwd,
detail: "Failed to get server settings.",
cause,
}),
),
);
+58 -1
View File
@@ -1,7 +1,9 @@
import { assert, describe, it, vi } from "@effect/vitest";
import { assert, describe, expect, it, vi } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { VcsRepositoryDetectionError } from "@t3tools/contracts";
import * as GitManager from "./GitManager.ts";
import * as GitWorkflowService from "./GitWorkflowService.ts";
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
@@ -132,4 +134,59 @@ describe("GitWorkflowService", () => {
),
),
);
it.effect("structures workflow detection failures without exposing upstream details", () => {
const cause = new VcsRepositoryDetectionError({
operation: "VcsDriverRegistry.detect",
cwd: "/repo",
detail: "upstream detail must stay in the cause chain",
});
return Effect.gen(function* () {
const workflow = yield* GitWorkflowService.GitWorkflowService;
const error = yield* workflow.status({ cwd: "/repo" }).pipe(Effect.flip);
expect(error).toMatchObject({
_tag: "GitManagerError",
operation: "GitWorkflowService.status",
cwd: "/repo",
detail: "Failed to detect a VCS repository for this Git workflow.",
});
expect(error.message).not.toContain(cause.detail);
}).pipe(
Effect.provide(
makeLayer({
detect: () => Effect.fail(cause),
}),
),
);
});
it.effect("structures command detection failures without exposing upstream details", () => {
const cause = new VcsRepositoryDetectionError({
operation: "VcsDriverRegistry.detect",
cwd: "/repo",
detail: "upstream command detail must stay in the cause chain",
});
return Effect.gen(function* () {
const workflow = yield* GitWorkflowService.GitWorkflowService;
const error = yield* workflow.listRefs({ cwd: "/repo" }).pipe(Effect.flip);
expect(error).toMatchObject({
_tag: "GitCommandError",
operation: "GitWorkflowService.listRefs",
command: "vcs-route",
cwd: "/repo",
detail: "Failed to detect a VCS repository for this Git command.",
});
expect(error.message).not.toContain(cause.detail);
}).pipe(
Effect.provide(
makeLayer({
detect: () => Effect.fail(cause),
}),
),
);
});
});
+52 -62
View File
@@ -94,20 +94,6 @@ export class GitWorkflowService extends Context.Service<
}
>()("t3/git/GitWorkflowService") {}
const unsupportedGitWorkflow = (operation: string, cwd: string, detail: string) =>
new GitManagerError({
operation,
detail: `${detail} (${cwd})`,
});
const unsupportedGitCommand = (operation: string, cwd: string, detail: string) =>
new GitCommandError({
operation,
command: "vcs-route",
cwd,
detail,
});
function nonRepositoryLocalStatus(): VcsStatusLocalResult {
return {
isRepo: false,
@@ -153,23 +139,23 @@ export const make = Effect.gen(function* () {
operation: string,
cwd: string,
) {
const handle = yield* registry
.resolve({ cwd })
.pipe(
Effect.mapError((error) =>
unsupportedGitWorkflow(
const handle = yield* registry.resolve({ cwd }).pipe(
Effect.mapError(
(cause) =>
new GitManagerError({
operation,
cwd,
error instanceof Error ? error.message : String(error),
),
),
);
detail: "Failed to resolve the VCS driver for this Git workflow.",
cause,
}),
),
);
if (handle.kind !== "git") {
return yield* unsupportedGitWorkflow(
return yield* new GitManagerError({
operation,
cwd,
`The ${operation} workflow currently supports Git repositories only; detected ${handle.kind}.`,
);
detail: `The ${operation} workflow currently supports Git repositories only; detected ${handle.kind}. (${cwd})`,
});
}
});
@@ -177,48 +163,50 @@ export const make = Effect.gen(function* () {
operation: string,
cwd: string,
) {
const handle = yield* registry
.resolve({ cwd })
.pipe(
Effect.mapError((error) =>
unsupportedGitCommand(
const handle = yield* registry.resolve({ cwd }).pipe(
Effect.mapError(
(cause) =>
new GitCommandError({
operation,
command: "vcs-route",
cwd,
error instanceof Error ? error.message : String(error),
),
),
);
detail: "Failed to resolve the VCS driver for this Git command.",
cause,
}),
),
);
if (handle.kind !== "git") {
return yield* unsupportedGitCommand(
return yield* new GitCommandError({
operation,
command: "vcs-route",
cwd,
`The ${operation} command currently supports Git repositories only; detected ${handle.kind}.`,
);
detail: `The ${operation} command currently supports Git repositories only; detected ${handle.kind}.`,
});
}
});
const detectGitRepositoryForStatus = Effect.fn("GitWorkflowService.detectGitRepositoryForStatus")(
function* (operation: string, cwd: string) {
const handle = yield* registry
.detect({ cwd })
.pipe(
Effect.mapError((error) =>
unsupportedGitWorkflow(
const handle = yield* registry.detect({ cwd }).pipe(
Effect.mapError(
(cause) =>
new GitManagerError({
operation,
cwd,
error instanceof Error ? error.message : String(error),
),
),
);
detail: "Failed to detect a VCS repository for this Git workflow.",
cause,
}),
),
);
if (!handle) {
return false;
}
if (handle.kind !== "git") {
return yield* unsupportedGitWorkflow(
return yield* new GitManagerError({
operation,
cwd,
`The ${operation} workflow currently supports Git repositories only; detected ${handle.kind}.`,
);
detail: `The ${operation} workflow currently supports Git repositories only; detected ${handle.kind}. (${cwd})`,
});
}
return true;
},
@@ -227,26 +215,28 @@ export const make = Effect.gen(function* () {
const detectGitRepositoryForCommand = Effect.fn(
"GitWorkflowService.detectGitRepositoryForCommand",
)(function* (operation: string, cwd: string) {
const handle = yield* registry
.detect({ cwd })
.pipe(
Effect.mapError((error) =>
unsupportedGitCommand(
const handle = yield* registry.detect({ cwd }).pipe(
Effect.mapError(
(cause) =>
new GitCommandError({
operation,
command: "vcs-route",
cwd,
error instanceof Error ? error.message : String(error),
),
),
);
detail: "Failed to detect a VCS repository for this Git command.",
cause,
}),
),
);
if (!handle) {
return false;
}
if (handle.kind !== "git") {
return yield* unsupportedGitCommand(
return yield* new GitCommandError({
operation,
command: "vcs-route",
cwd,
`The ${operation} command currently supports Git repositories only; detected ${handle.kind}.`,
);
detail: `The ${operation} command currently supports Git repositories only; detected ${handle.kind}.`,
});
}
return true;
});
+1
View File
@@ -198,6 +198,7 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
assert.equal(defaultsByCommand.get("thread.jump.1"), "mod+1");
assert.equal(defaultsByCommand.get("thread.jump.9"), "mod+9");
assert.equal(defaultsByCommand.get("modelPicker.toggle"), "mod+shift+m");
assert.equal(defaultsByCommand.get("sidebar.toggle"), "mod+b");
assert.equal(defaultsByCommand.get("rightPanel.toggle"), "mod+alt+b");
assert.equal(defaultsByCommand.get("terminal.splitVertical"), "mod+shift+d");
assert.equal(defaultsByCommand.get("modelPicker.jump.1"), "mod+1");
@@ -0,0 +1,39 @@
import { expect, it } from "@effect/vitest";
import {
EnvironmentId,
PreviewAutomationUnavailableError,
ProviderInstanceId,
ThreadId,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as McpInvocationContext from "./McpInvocationContext.ts";
it.effect("reports the scoped credential context when preview capability is unavailable", () => {
const invocation: McpInvocationContext.McpInvocationScope = {
environmentId: EnvironmentId.make("environment-1"),
threadId: ThreadId.make("thread-1"),
providerSessionId: "provider-session-1",
providerInstanceId: ProviderInstanceId.make("codex"),
capabilities: new Set(),
issuedAt: 1,
expiresAt: 2,
};
return Effect.gen(function* () {
const error = yield* McpInvocationContext.requireMcpCapability("preview").pipe(
Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
Effect.flip,
);
expect(error).toBeInstanceOf(PreviewAutomationUnavailableError);
expect(error).toMatchObject({
capability: "preview",
environmentId: invocation.environmentId,
threadId: invocation.threadId,
providerSessionId: invocation.providerSessionId,
providerInstanceId: invocation.providerInstanceId,
});
expect(error.message).toBe("MCP credential does not grant the preview capability.");
});
});
+11 -3
View File
@@ -1,5 +1,9 @@
import type { EnvironmentId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
import { PreviewAutomationUnavailableError } from "@t3tools/contracts";
import {
type EnvironmentId,
PreviewAutomationUnavailableError,
type ProviderInstanceId,
type ThreadId,
} from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
@@ -26,7 +30,11 @@ export const requireMcpCapability = Effect.fn("mcp.requireCapability")(function*
const invocation = yield* McpInvocationContext;
if (!invocation.capabilities.has(capability)) {
return yield* new PreviewAutomationUnavailableError({
message: `MCP credential does not grant the ${capability} capability.`,
capability,
environmentId: invocation.environmentId,
threadId: invocation.threadId,
providerSessionId: invocation.providerSessionId,
providerInstanceId: invocation.providerInstanceId,
});
}
return invocation;
@@ -11,6 +11,7 @@ import { AuthEnvironmentScopes } from "@t3tools/contracts";
import {
type AuthPairingLinkRepositoryError,
PersistenceDecodeError,
type PersistenceErrorCorrelation,
PersistenceSqlError,
} from "./Errors.ts";
@@ -66,6 +67,22 @@ export const GetAuthPairingLinkByCredentialInput = Schema.Struct({
});
export type GetAuthPairingLinkByCredentialInput = typeof GetAuthPairingLinkByCredentialInput.Type;
const AuthPairingLinkRawDbRow = Schema.Struct({
id: Schema.String,
credential: Schema.Unknown,
method: Schema.Unknown,
scopes: Schema.Unknown,
subject: Schema.Unknown,
label: Schema.Unknown,
proofKeyThumbprint: Schema.Unknown,
createdAt: Schema.Unknown,
expiresAt: Schema.Unknown,
consumedAt: Schema.Unknown,
revokedAt: Schema.Unknown,
});
const decodeAuthPairingLinkDbRow = Schema.decodeUnknownEffect(AuthPairingLinkRecord);
export class AuthPairingLinkRepository extends Context.Service<
AuthPairingLinkRepository,
{
@@ -87,11 +104,19 @@ export class AuthPairingLinkRepository extends Context.Service<
}
>()("t3/persistence/AuthPairingLinks/AuthPairingLinkRepository") {}
function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: string) {
function toPersistenceSqlOrDecodeError(
sqlOperation: string,
decodeOperation: string,
correlation?: PersistenceErrorCorrelation,
) {
return (cause: unknown): AuthPairingLinkRepositoryError =>
Schema.isSchemaError(cause)
? PersistenceDecodeError.fromSchemaError(decodeOperation, cause)
: new PersistenceSqlError({ operation: sqlOperation, cause });
? PersistenceDecodeError.fromSchemaError(decodeOperation, cause, correlation)
: new PersistenceSqlError({
operation: sqlOperation,
...(correlation === undefined ? {} : { correlation }),
cause,
});
}
export const make = Effect.gen(function* () {
@@ -132,7 +157,7 @@ export const make = Effect.gen(function* () {
const consumeAvailablePairingLinkRow = SqlSchema.findOneOption({
Request: ConsumeAuthPairingLinkInput,
Result: AuthPairingLinkRecord,
Result: AuthPairingLinkRawDbRow,
execute: ({ credential, proofKeyThumbprint, consumedAt, now }) =>
sql`
UPDATE auth_pairing_links
@@ -162,7 +187,7 @@ export const make = Effect.gen(function* () {
const listActivePairingLinkRows = SqlSchema.findAll({
Request: ListActiveAuthPairingLinksInput,
Result: AuthPairingLinkRecord,
Result: AuthPairingLinkRawDbRow,
execute: ({ now }) =>
sql`
SELECT
@@ -201,7 +226,7 @@ export const make = Effect.gen(function* () {
const getPairingLinkRowByCredential = SqlSchema.findOneOption({
Request: GetAuthPairingLinkByCredentialInput,
Result: AuthPairingLinkRecord,
Result: AuthPairingLinkRawDbRow,
execute: ({ credential }) =>
sql`
SELECT
@@ -227,6 +252,7 @@ export const make = Effect.gen(function* () {
toPersistenceSqlOrDecodeError(
"AuthPairingLinkRepository.create:query",
"AuthPairingLinkRepository.create:encodeRequest",
{ pairingLinkId: input.id },
),
),
);
@@ -239,6 +265,22 @@ export const make = Effect.gen(function* () {
"AuthPairingLinkRepository.consumeAvailable:decodeRow",
),
),
Effect.flatMap((rowOption) =>
Option.match(rowOption, {
onNone: () => Effect.succeed(Option.none()),
onSome: (row) =>
decodeAuthPairingLinkDbRow(row).pipe(
Effect.mapError((cause) =>
PersistenceDecodeError.fromSchemaError(
"AuthPairingLinkRepository.consumeAvailable:decodeRow",
cause,
{ pairingLinkId: row.id },
),
),
Effect.map(Option.some),
),
}),
),
);
const listActive: AuthPairingLinkRepository["Service"]["listActive"] = (input) =>
@@ -249,6 +291,19 @@ export const make = Effect.gen(function* () {
"AuthPairingLinkRepository.listActive:decodeRows",
),
),
Effect.flatMap((rows) =>
Effect.forEach(rows, (row) =>
decodeAuthPairingLinkDbRow(row).pipe(
Effect.mapError((cause) =>
PersistenceDecodeError.fromSchemaError(
"AuthPairingLinkRepository.listActive:decodeRows",
cause,
{ pairingLinkId: row.id },
),
),
),
),
),
);
const revoke: AuthPairingLinkRepository["Service"]["revoke"] = (input) =>
@@ -257,6 +312,7 @@ export const make = Effect.gen(function* () {
toPersistenceSqlOrDecodeError(
"AuthPairingLinkRepository.revoke:query",
"AuthPairingLinkRepository.revoke:decodeRows",
{ pairingLinkId: input.id },
),
),
Effect.map((rows) => rows.length > 0),
@@ -270,6 +326,22 @@ export const make = Effect.gen(function* () {
"AuthPairingLinkRepository.getByCredential:decodeRow",
),
),
Effect.flatMap((rowOption) =>
Option.match(rowOption, {
onNone: () => Effect.succeed(Option.none()),
onSome: (row) =>
decodeAuthPairingLinkDbRow(row).pipe(
Effect.mapError((cause) =>
PersistenceDecodeError.fromSchemaError(
"AuthPairingLinkRepository.getByCredential:decodeRow",
cause,
{ pairingLinkId: row.id },
),
),
Effect.map(Option.some),
),
}),
),
);
return {
+63 -7
View File
@@ -16,6 +16,7 @@ import {
import {
type AuthSessionRepositoryError,
PersistenceDecodeError,
type PersistenceErrorCorrelation,
PersistenceSqlError,
} from "./Errors.ts";
@@ -122,6 +123,25 @@ const AuthSessionDbRow = Schema.Struct({
revokedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
});
const AuthSessionRawDbRow = Schema.Struct({
sessionId: Schema.String,
subject: Schema.Unknown,
scopes: Schema.Unknown,
method: Schema.Unknown,
clientLabel: Schema.Unknown,
clientIpAddress: Schema.Unknown,
clientUserAgent: Schema.Unknown,
clientDeviceType: Schema.Unknown,
clientOs: Schema.Unknown,
clientBrowser: Schema.Unknown,
issuedAt: Schema.Unknown,
expiresAt: Schema.Unknown,
lastConnectedAt: Schema.Unknown,
revokedAt: Schema.Unknown,
});
const decodeAuthSessionDbRow = Schema.decodeUnknownEffect(AuthSessionDbRow);
function toAuthSessionRecord(row: typeof AuthSessionDbRow.Type): AuthSessionRecord {
return {
sessionId: row.sessionId,
@@ -143,11 +163,19 @@ function toAuthSessionRecord(row: typeof AuthSessionDbRow.Type): AuthSessionReco
};
}
function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: string) {
function toPersistenceSqlOrDecodeError(
sqlOperation: string,
decodeOperation: string,
correlation?: PersistenceErrorCorrelation,
) {
return (cause: unknown): AuthSessionRepositoryError =>
Schema.isSchemaError(cause)
? PersistenceDecodeError.fromSchemaError(decodeOperation, cause)
: new PersistenceSqlError({ operation: sqlOperation, cause });
? PersistenceDecodeError.fromSchemaError(decodeOperation, cause, correlation)
: new PersistenceSqlError({
operation: sqlOperation,
...(correlation === undefined ? {} : { correlation }),
cause,
});
}
export const make = Effect.gen(function* () {
@@ -192,7 +220,7 @@ export const make = Effect.gen(function* () {
const getSessionRowById = SqlSchema.findOneOption({
Request: GetAuthSessionByIdInput,
Result: AuthSessionDbRow,
Result: AuthSessionRawDbRow,
execute: ({ sessionId }) =>
sql`
SELECT
@@ -217,7 +245,7 @@ export const make = Effect.gen(function* () {
const listActiveSessionRows = SqlSchema.findAll({
Request: ListActiveAuthSessionsInput,
Result: AuthSessionDbRow,
Result: AuthSessionRawDbRow,
execute: ({ now }) =>
sql`
SELECT
@@ -285,6 +313,7 @@ export const make = Effect.gen(function* () {
toPersistenceSqlOrDecodeError(
"AuthSessionRepository.create:query",
"AuthSessionRepository.create:encodeRequest",
{ sessionId: input.sessionId },
),
),
);
@@ -295,12 +324,23 @@ export const make = Effect.gen(function* () {
toPersistenceSqlOrDecodeError(
"AuthSessionRepository.getById:query",
"AuthSessionRepository.getById:decodeRow",
{ sessionId: input.sessionId },
),
),
Effect.flatMap((rowOption) =>
Option.match(rowOption, {
onNone: () => Effect.succeed(Option.none()),
onSome: (row) => Effect.succeed(Option.some(toAuthSessionRecord(row))),
onSome: (row) =>
decodeAuthSessionDbRow(row).pipe(
Effect.mapError((cause) =>
PersistenceDecodeError.fromSchemaError(
"AuthSessionRepository.getById:decodeRow",
cause,
{ sessionId: input.sessionId },
),
),
Effect.map((decodedRow) => Option.some(toAuthSessionRecord(decodedRow))),
),
}),
),
);
@@ -313,7 +353,20 @@ export const make = Effect.gen(function* () {
"AuthSessionRepository.listActive:decodeRows",
),
),
Effect.flatMap((rows) => Effect.succeed(rows.map((row) => toAuthSessionRecord(row)))),
Effect.flatMap((rows) =>
Effect.forEach(rows, (row) =>
decodeAuthSessionDbRow(row).pipe(
Effect.mapError((cause) =>
PersistenceDecodeError.fromSchemaError(
"AuthSessionRepository.listActive:decodeRows",
cause,
{ sessionId: row.sessionId },
),
),
Effect.map(toAuthSessionRecord),
),
),
),
);
const revoke: AuthSessionRepository["Service"]["revoke"] = (input) =>
@@ -322,6 +375,7 @@ export const make = Effect.gen(function* () {
toPersistenceSqlOrDecodeError(
"AuthSessionRepository.revoke:query",
"AuthSessionRepository.revoke:decodeRows",
{ sessionId: input.sessionId },
),
),
Effect.map((rows) => rows.length > 0),
@@ -333,6 +387,7 @@ export const make = Effect.gen(function* () {
toPersistenceSqlOrDecodeError(
"AuthSessionRepository.revokeAllExcept:query",
"AuthSessionRepository.revokeAllExcept:decodeRows",
{ currentSessionId: input.currentSessionId },
),
),
Effect.map((rows) => rows.map((row) => row.sessionId)),
@@ -344,6 +399,7 @@ export const make = Effect.gen(function* () {
toPersistenceSqlOrDecodeError(
"AuthSessionRepository.setLastConnectedAt:query",
"AuthSessionRepository.setLastConnectedAt:encodeRequest",
{ sessionId: input.sessionId },
),
),
);
+16 -1
View File
@@ -19,11 +19,20 @@ function summarizeSchemaIssue(issue: SchemaIssue.Issue): string {
// Core Persistence Errors
// ===============================
export const PersistenceErrorCorrelation = Schema.Union([
Schema.Struct({ sessionId: Schema.String }),
Schema.Struct({ currentSessionId: Schema.String }),
Schema.Struct({ pairingLinkId: Schema.String }),
Schema.Struct({ threadId: Schema.String }),
]);
export type PersistenceErrorCorrelation = typeof PersistenceErrorCorrelation.Type;
export class PersistenceSqlError extends Schema.TaggedErrorClass<PersistenceSqlError>()(
"PersistenceSqlError",
{
operation: Schema.String,
detail: Schema.optional(Schema.String),
correlation: Schema.optional(PersistenceErrorCorrelation),
cause: Schema.optional(Schema.Defect()),
},
) {
@@ -39,13 +48,19 @@ export class PersistenceDecodeError extends Schema.TaggedErrorClass<PersistenceD
{
operation: Schema.String,
issue: Schema.String,
correlation: Schema.optional(PersistenceErrorCorrelation),
cause: Schema.optional(Schema.Defect()),
},
) {
static fromSchemaError(operation: string, cause: Schema.SchemaError): PersistenceDecodeError {
static fromSchemaError(
operation: string,
cause: Schema.SchemaError,
correlation?: PersistenceErrorCorrelation,
): PersistenceDecodeError {
return new PersistenceDecodeError({
operation,
issue: summarizeSchemaIssue(cause.issue),
...(correlation === undefined ? {} : { correlation }),
cause,
});
}
@@ -17,6 +17,7 @@ import {
import {
PersistenceDecodeError,
type PersistenceErrorCorrelation,
PersistenceSqlError,
type ProviderSessionRuntimeRepositoryError,
} from "./Errors.ts";
@@ -106,7 +107,19 @@ const ProviderSessionRuntimeDbRowSchema = ProviderSessionRuntime.mapFields(
}),
);
const decodeRuntime = Schema.decodeUnknownEffect(ProviderSessionRuntime);
const ProviderSessionRuntimeRawDbRowSchema = Schema.Struct({
threadId: Schema.String,
providerName: Schema.Unknown,
providerInstanceId: Schema.Unknown,
adapterKey: Schema.Unknown,
runtimeMode: Schema.Unknown,
status: Schema.Unknown,
lastSeenAt: Schema.Unknown,
resumeCursor: Schema.Unknown,
runtimePayload: Schema.Unknown,
});
const decodeRuntimeRow = Schema.decodeUnknownEffect(ProviderSessionRuntimeDbRowSchema);
const GetRuntimeRequestSchema = Schema.Struct({
threadId: ThreadId,
@@ -114,11 +127,19 @@ const GetRuntimeRequestSchema = Schema.Struct({
const DeleteRuntimeRequestSchema = GetRuntimeRequestSchema;
function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: string) {
function toPersistenceSqlOrDecodeError(
sqlOperation: string,
decodeOperation: string,
correlation?: PersistenceErrorCorrelation,
) {
return (cause: unknown): ProviderSessionRuntimeRepositoryError =>
Schema.isSchemaError(cause)
? PersistenceDecodeError.fromSchemaError(decodeOperation, cause)
: new PersistenceSqlError({ operation: sqlOperation, cause });
? PersistenceDecodeError.fromSchemaError(decodeOperation, cause, correlation)
: new PersistenceSqlError({
operation: sqlOperation,
...(correlation === undefined ? {} : { correlation }),
cause,
});
}
export const make = Effect.gen(function* () {
@@ -165,7 +186,7 @@ export const make = Effect.gen(function* () {
const getRuntimeRowByThreadId = SqlSchema.findOneOption({
Request: GetRuntimeRequestSchema,
Result: ProviderSessionRuntimeDbRowSchema,
Result: ProviderSessionRuntimeRawDbRowSchema,
execute: ({ threadId }) =>
sql`
SELECT
@@ -185,7 +206,7 @@ export const make = Effect.gen(function* () {
const listRuntimeRows = SqlSchema.findAll({
Request: Schema.Void,
Result: ProviderSessionRuntimeDbRowSchema,
Result: ProviderSessionRuntimeRawDbRowSchema,
execute: () =>
sql`
SELECT
@@ -218,6 +239,7 @@ export const make = Effect.gen(function* () {
toPersistenceSqlOrDecodeError(
"ProviderSessionRuntimeRepository.upsert:query",
"ProviderSessionRuntimeRepository.upsert:encodeRequest",
{ threadId: runtime.threadId },
),
),
);
@@ -228,17 +250,19 @@ export const make = Effect.gen(function* () {
toPersistenceSqlOrDecodeError(
"ProviderSessionRuntimeRepository.getByThreadId:query",
"ProviderSessionRuntimeRepository.getByThreadId:decodeRow",
{ threadId: input.threadId },
),
),
Effect.flatMap((runtimeRowOption) =>
Option.match(runtimeRowOption, {
onNone: () => Effect.succeed(Option.none()),
onSome: (row) =>
decodeRuntime(row).pipe(
decodeRuntimeRow(row).pipe(
Effect.mapError((cause) =>
PersistenceDecodeError.fromSchemaError(
"ProviderSessionRuntimeRepository.getByThreadId:rowToRuntime",
"ProviderSessionRuntimeRepository.getByThreadId:decodeRow",
cause,
{ threadId: input.threadId },
),
),
Effect.map((runtime) => Option.some(runtime)),
@@ -256,18 +280,16 @@ export const make = Effect.gen(function* () {
),
),
Effect.flatMap((rows) =>
Effect.forEach(
rows,
(row) =>
decodeRuntime(row).pipe(
Effect.mapError((cause) =>
PersistenceDecodeError.fromSchemaError(
"ProviderSessionRuntimeRepository.list:rowToRuntime",
cause,
),
Effect.forEach(rows, (row) =>
decodeRuntimeRow(row).pipe(
Effect.mapError((cause) =>
PersistenceDecodeError.fromSchemaError(
"ProviderSessionRuntimeRepository.list:decodeRows",
cause,
{ threadId: row.threadId },
),
),
{ concurrency: "unbounded" },
),
),
),
);
@@ -280,6 +302,7 @@ export const make = Effect.gen(function* () {
(cause) =>
new PersistenceSqlError({
operation: "ProviderSessionRuntimeRepository.deleteByThreadId:query",
correlation: { threadId: input.threadId },
cause,
}),
),
@@ -0,0 +1,253 @@
import { AuthSessionId, ThreadId, type AuthEnvironmentScope } from "@t3tools/contracts";
import { assert, describe, it } from "@effect/vitest";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import * as AuthPairingLinks from "./AuthPairingLinks.ts";
import * as AuthSessions from "./AuthSessions.ts";
import * as PersistenceErrors from "./Errors.ts";
import { SqlitePersistenceMemory } from "./Layers/Sqlite.ts";
import * as ProviderSessionRuntime from "./ProviderSessionRuntime.ts";
const issuedAt = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z");
const expiresAt = DateTime.makeUnsafe("2027-06-20T00:00:00.000Z");
const now = DateTime.makeUnsafe("2026-06-21T00:00:00.000Z");
const scopes: ReadonlyArray<AuthEnvironmentScope> = ["access:read"];
const authSessionLayer = AuthSessions.layer.pipe(Layer.provideMerge(SqlitePersistenceMemory));
const authPairingLinkLayer = AuthPairingLinks.layer.pipe(
Layer.provideMerge(SqlitePersistenceMemory),
);
const providerSessionRuntimeLayer = ProviderSessionRuntime.layer.pipe(
Layer.provideMerge(SqlitePersistenceMemory),
);
describe("persistence error correlation", () => {
it.effect("correlates auth session SQL and row-decode failures without sensitive fields", () =>
Effect.gen(function* () {
const sessions = yield* AuthSessions.AuthSessionRepository;
const sql = yield* SqlClient.SqlClient;
const sessionId = AuthSessionId.make("session-correlation");
const currentSessionId = AuthSessionId.make("current-session-correlation");
const subject = "session-subject-secret-sentinel";
yield* sessions.create({
sessionId,
subject,
scopes,
method: "browser-session-cookie",
client: {
label: null,
ipAddress: null,
userAgent: null,
deviceType: "desktop",
os: null,
browser: null,
},
issuedAt,
expiresAt,
});
yield* sql`
UPDATE auth_sessions
SET scopes = ${"session-scopes-secret-sentinel"}
WHERE session_id = ${sessionId}
`;
const decodeError = yield* Effect.flip(sessions.listActive({ now }));
assert.instanceOf(decodeError, PersistenceErrors.PersistenceDecodeError);
assert.deepStrictEqual(decodeError.correlation, { sessionId });
assert.equal(
decodeError.message,
`Decode error in AuthSessionRepository.listActive:decodeRows: ${decodeError.issue}`,
);
assert.notInclude(decodeError.issue, subject);
assert.notInclude(decodeError.issue, "session-scopes-secret-sentinel");
assert.notInclude(decodeError.message, subject);
yield* sql`DROP TABLE auth_sessions`;
const createError = yield* Effect.flip(
sessions.create({
sessionId,
subject,
scopes,
method: "browser-session-cookie",
client: {
label: null,
ipAddress: null,
userAgent: null,
deviceType: "desktop",
os: null,
browser: null,
},
issuedAt,
expiresAt,
}),
);
assert.instanceOf(createError, PersistenceErrors.PersistenceSqlError);
assert.deepStrictEqual(createError.correlation, { sessionId });
assert.equal(createError.message, "SQL error in AuthSessionRepository.create:query");
assert.notInclude(createError.message, subject);
assert.notInclude(createError.message, DateTime.formatIso(issuedAt));
const revokeOtherError = yield* Effect.flip(
sessions.revokeAllExcept({ currentSessionId, revokedAt: now }),
);
assert.instanceOf(revokeOtherError, PersistenceErrors.PersistenceSqlError);
assert.deepStrictEqual(revokeOtherError.correlation, { currentSessionId });
assert.equal(
revokeOtherError.message,
"SQL error in AuthSessionRepository.revokeAllExcept:query",
);
assert.notInclude(revokeOtherError.message, DateTime.formatIso(now));
}).pipe(Effect.provide(authSessionLayer)),
);
it.effect("correlates pairing-link create and revoke failures by id only", () =>
Effect.gen(function* () {
const pairingLinks = yield* AuthPairingLinks.AuthPairingLinkRepository;
const sql = yield* SqlClient.SqlClient;
const id = "pairing-link-correlation";
const credential = "pairing-credential-secret-sentinel";
const subject = "pairing-subject-secret-sentinel";
const scopesPayload = "pairing-scopes-secret-sentinel";
yield* sql`
INSERT INTO auth_pairing_links (
id,
credential,
method,
scopes,
subject,
label,
proof_key_thumbprint,
created_at,
expires_at,
consumed_at,
revoked_at
)
VALUES (
${id},
${credential},
${"one-time-token"},
${scopesPayload},
${subject},
NULL,
NULL,
${DateTime.formatIso(issuedAt)},
${DateTime.formatIso(expiresAt)},
NULL,
NULL
)
`;
const decodeError = yield* Effect.flip(pairingLinks.getByCredential({ credential }));
assert.instanceOf(decodeError, PersistenceErrors.PersistenceDecodeError);
assert.deepStrictEqual(decodeError.correlation, { pairingLinkId: id });
assert.equal(
decodeError.message,
`Decode error in AuthPairingLinkRepository.getByCredential:decodeRow: ${decodeError.issue}`,
);
assert.notInclude(decodeError.issue, credential);
assert.notInclude(decodeError.issue, subject);
assert.notInclude(decodeError.issue, scopesPayload);
assert.notInclude(decodeError.message, DateTime.formatIso(issuedAt));
yield* sql`DROP TABLE auth_pairing_links`;
const createError = yield* Effect.flip(
pairingLinks.create({
id,
credential,
method: "one-time-token",
scopes,
subject,
label: null,
proofKeyThumbprint: null,
createdAt: issuedAt,
expiresAt,
}),
);
assert.instanceOf(createError, PersistenceErrors.PersistenceSqlError);
assert.deepStrictEqual(createError.correlation, { pairingLinkId: id });
assert.notInclude(createError.message, credential);
assert.notInclude(createError.message, subject);
assert.notInclude(createError.message, DateTime.formatIso(issuedAt));
const revokeError = yield* Effect.flip(pairingLinks.revoke({ id, revokedAt: now }));
assert.instanceOf(revokeError, PersistenceErrors.PersistenceSqlError);
assert.deepStrictEqual(revokeError.correlation, { pairingLinkId: id });
assert.notInclude(revokeError.message, credential);
assert.notInclude(revokeError.message, DateTime.formatIso(now));
}).pipe(Effect.provide(authPairingLinkLayer)),
);
it.effect("correlates provider runtime SQL and per-row decode failures by thread", () =>
Effect.gen(function* () {
const runtimes = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
const sql = yield* SqlClient.SqlClient;
const threadId = ThreadId.make("thread-correlation");
const runtimePayload = "runtime-payload-secret-sentinel";
const lastSeenAt = "2026-06-20T00:00:00.000Z";
yield* 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 (
${threadId},
${"codex"},
NULL,
${"codex"},
${"invalid-runtime-mode"},
${"running"},
${lastSeenAt},
NULL,
${`{"secret":"${runtimePayload}"}`}
)
`;
const decodeError = yield* Effect.flip(runtimes.list());
assert.instanceOf(decodeError, PersistenceErrors.PersistenceDecodeError);
assert.deepStrictEqual(decodeError.correlation, { threadId });
assert.equal(
decodeError.message,
`Decode error in ProviderSessionRuntimeRepository.list:decodeRows: ${decodeError.issue}`,
);
assert.notInclude(decodeError.issue, runtimePayload);
assert.notInclude(decodeError.message, runtimePayload);
assert.notInclude(decodeError.message, lastSeenAt);
yield* sql`DROP TABLE provider_session_runtime`;
const sqlFailure = yield* Effect.flip(
runtimes.upsert({
threadId,
providerName: "codex",
providerInstanceId: null,
adapterKey: "codex",
runtimeMode: "full-access",
status: "running",
lastSeenAt,
resumeCursor: null,
runtimePayload: { secret: runtimePayload },
}),
);
assert.instanceOf(sqlFailure, PersistenceErrors.PersistenceSqlError);
assert.deepStrictEqual(sqlFailure.correlation, { threadId });
assert.equal(
sqlFailure.message,
"SQL error in ProviderSessionRuntimeRepository.upsert:query",
);
assert.notInclude(sqlFailure.message, runtimePayload);
assert.notInclude(sqlFailure.message, lastSeenAt);
}).pipe(Effect.provide(providerSessionRuntimeLayer)),
);
});
+70 -2
View File
@@ -3,14 +3,48 @@ import * as NodeNet from "node:net";
import { it as effectIt } from "@effect/vitest";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as Net from "@t3tools/shared/Net";
import { Effect, Layer } from "effect";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Layer from "effect/Layer";
import * as PlatformError from "effect/PlatformError";
import { expect } from "vite-plus/test";
import * as ProcessRunner from "../processRunner.ts";
import * as PortScanner from "./PortScanner.ts";
const TestProcessRunner = Layer.succeed(ProcessRunner.ProcessRunner, {
run: () => Effect.die("ProcessRunner should not be used by Windows TCP probe tests"),
run: (input) =>
Effect.fail(
new ProcessRunner.ProcessSpawnError({
command: input.command,
argumentCount: input.args.length,
cwd: input.cwd,
cause: PlatformError.systemError({
_tag: "NotFound",
module: "ChildProcess",
method: "spawn",
description: "PowerShell is not installed in the test environment",
}),
}),
),
});
const makeProbeFailureLayer = (run: ProcessRunner.ProcessRunner["Service"]["run"]) =>
PortScanner.layer.pipe(
Layer.provide(
Layer.mergeAll(
Layer.succeed(ProcessRunner.ProcessRunner, { run }),
Layer.succeed(Net.NetService, {
canListenOnHost: () => Effect.succeed(true),
isPortAvailableOnLoopback: () => Effect.succeed(true),
reserveLoopbackPort: () => Effect.succeed(40_000),
findAvailablePort: (preferred) => Effect.succeed(preferred),
}),
Layer.succeed(HostProcessPlatform, "linux"),
),
),
);
const TestPortDiscoveryLive = PortScanner.layer.pipe(
Layer.provide(
Layer.mergeAll(TestProcessRunner, Net.layer, Layer.succeed(HostProcessPlatform, "win32")),
@@ -87,3 +121,37 @@ effectIt.layer(TestPortDiscoveryLive)("PortDiscovery integration (TCP probe fall
}),
);
});
effectIt("does not swallow process probe defects", () =>
Effect.gen(function* () {
const defect = new Error("unexpected process probe defect");
const layer = makeProbeFailureLayer(() => Effect.die(defect));
const exit = yield* Effect.flatMap(PortScanner.PortDiscovery, (scanner) => scanner.scan()).pipe(
Effect.provide(layer),
Effect.exit,
);
expect(Exit.isFailure(exit)).toBe(true);
if (Exit.isFailure(exit)) {
expect(Cause.hasDies(exit.cause)).toBe(true);
expect(Cause.squash(exit.cause)).toBe(defect);
}
}),
);
effectIt("does not swallow process probe interruption", () =>
Effect.gen(function* () {
const layer = makeProbeFailureLayer(() => Effect.interrupt);
const exit = yield* Effect.flatMap(PortScanner.PortDiscovery, (scanner) => scanner.scan()).pipe(
Effect.provide(layer),
Effect.exit,
);
expect(Exit.isFailure(exit)).toBe(true);
if (Exit.isFailure(exit)) {
expect(Cause.hasInterruptsOnly(exit.cause)).toBe(true);
}
}),
);
+24 -2
View File
@@ -221,6 +221,14 @@ export const make = Effect.gen(function* PortDiscoveryMake() {
}));
});
const recoverProcessProbeFailure =
(probe: "lsof" | "windows-listeners") => (error: ProcessRunner.ProcessRunError) =>
Effect.logDebug("preview port process probe failed; falling back to common-port probes", {
cause: error,
probe,
platform: hostPlatform,
}).pipe(Effect.as(null));
const scanOnce = Effect.fn("PortDiscovery.scan")(function* () {
const state = yield* Ref.get(stateRef);
const terminalByProcessId = new Map<number, TerminalProcessOwner>();
@@ -230,6 +238,7 @@ export const make = Effect.gen(function* PortDiscoveryMake() {
}
}
if (hostPlatform === "win32") {
const recoverWindowsProbeFailure = recoverProcessProbeFailure("windows-listeners");
const command =
'Get-NetTCPConnection -State Listen -ErrorAction Stop | ForEach-Object { $processName = (Get-Process -Id $_.OwningProcess -ErrorAction SilentlyContinue).ProcessName; Write-Output "$($_.LocalAddress)|$($_.LocalPort)|$($_.OwningProcess)|$processName" }';
const listeners = yield* processRunner
@@ -242,11 +251,18 @@ export const make = Effect.gen(function* PortDiscoveryMake() {
})
.pipe(
Effect.map((result) => parseWindowsListenerOutput(result.stdout, terminalByProcessId)),
Effect.catchCause(() => Effect.succeed(null)),
Effect.catchTags({
ProcessSpawnError: recoverWindowsProbeFailure,
ProcessStdinError: recoverWindowsProbeFailure,
ProcessOutputLimitError: recoverWindowsProbeFailure,
ProcessReadError: recoverWindowsProbeFailure,
ProcessTimeoutError: recoverWindowsProbeFailure,
}),
);
if (listeners !== null) return listeners;
return yield* probeCommonPorts();
}
const recoverLsofProbeFailure = recoverProcessProbeFailure("lsof");
const lsofResult = yield* processRunner
.run({
command: "lsof",
@@ -257,7 +273,13 @@ export const make = Effect.gen(function* PortDiscoveryMake() {
})
.pipe(
Effect.map((result) => parseLsofOutput(result.stdout, terminalByProcessId)),
Effect.catchCause(() => Effect.succeed(null)),
Effect.catchTags({
ProcessSpawnError: recoverLsofProbeFailure,
ProcessStdinError: recoverLsofProbeFailure,
ProcessOutputLimitError: recoverLsofProbeFailure,
ProcessReadError: recoverLsofProbeFailure,
ProcessTimeoutError: recoverLsofProbeFailure,
}),
);
if (lsofResult !== null) return lsofResult;
return yield* probeCommonPorts();
@@ -4,6 +4,7 @@ import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
import * as ProjectFaviconResolver from "./ProjectFaviconResolver.ts";
@@ -34,6 +35,12 @@ const writeTextFile = Effect.fn("writeTextFile")(function* (
yield* fileSystem.writeFileString(absolutePath, contents).pipe(Effect.orDie);
});
const makeResolverWithFileSystem = (fileSystem: FileSystem.FileSystem) =>
ProjectFaviconResolver.make.pipe(
Effect.provide(WorkspacePaths.layer),
Effect.provideService(FileSystem.FileSystem, fileSystem),
);
it.layer(TestLayer)("ProjectFaviconResolverLive", (it) => {
describe("resolvePath", () => {
it.effect("prefers well-known favicon files", () =>
@@ -73,5 +80,118 @@ it.layer(TestLayer)("ProjectFaviconResolverLive", (it) => {
expect(resolved).toBeNull();
}),
);
it.effect("preserves workspace normalization context", () =>
Effect.gen(function* () {
const resolver = yield* ProjectFaviconResolver.ProjectFaviconResolver;
const cwd = yield* makeTempDir;
const missingCwd = `${cwd}/missing`;
const error = yield* resolver.resolvePath(missingCwd).pipe(Effect.flip);
expect(error).toMatchObject({
_tag: "ProjectFaviconResolutionError",
operation: "normalize-workspace",
workspaceRoot: missingCwd,
});
expect(error.cause).toBeInstanceOf(WorkspacePaths.WorkspaceRootNotExistsError);
}),
);
it.effect("preserves non-missing candidate stat failures", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const cwd = yield* makeTempDir;
const faviconPath = path.join(cwd, "favicon.svg");
const cause = PlatformError.systemError({
_tag: "PermissionDenied",
module: "FileSystem",
method: "stat",
pathOrDescriptor: faviconPath,
});
const resolver = yield* makeResolverWithFileSystem(
FileSystem.FileSystem.of({
...fileSystem,
stat: (filePath) =>
filePath === faviconPath ? Effect.fail(cause) : fileSystem.stat(filePath),
}),
);
const error = yield* resolver.resolvePath(cwd).pipe(Effect.flip);
expect(error).toMatchObject({
_tag: "ProjectFaviconResolutionError",
operation: "stat-candidate",
workspaceRoot: cwd,
relativePath: "favicon.svg",
absolutePath: faviconPath,
});
expect(error.cause).toBe(cause);
}),
);
it.effect("preserves icon source read failures", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const cwd = yield* makeTempDir;
const sourcePath = path.join(cwd, "index.html");
yield* writeTextFile(cwd, "index.html", '<link rel="icon" href="/favicon.svg">');
const cause = PlatformError.systemError({
_tag: "PermissionDenied",
module: "FileSystem",
method: "readFileString",
pathOrDescriptor: sourcePath,
});
const resolver = yield* makeResolverWithFileSystem(
FileSystem.FileSystem.of({
...fileSystem,
readFileString: (filePath, options) =>
filePath === sourcePath
? Effect.fail(cause)
: fileSystem.readFileString(filePath, options),
}),
);
const error = yield* resolver.resolvePath(cwd).pipe(Effect.flip);
expect(error).toMatchObject({
_tag: "ProjectFaviconResolutionError",
operation: "read-source",
workspaceRoot: cwd,
relativePath: "index.html",
absolutePath: sourcePath,
});
expect(error.cause).toBe(cause);
}),
);
it.effect("skips icon metadata paths outside the workspace", () =>
Effect.gen(function* () {
const resolver = yield* ProjectFaviconResolver.ProjectFaviconResolver;
const cwd = yield* makeTempDir;
yield* writeTextFile(cwd, "index.html", '<link rel="icon" href="../../secret.svg">');
const resolved = yield* resolver.resolvePath(cwd);
expect(resolved).toBeNull();
}),
);
it.effect("continues to later sources after an outside-root icon href", () =>
Effect.gen(function* () {
const resolver = yield* ProjectFaviconResolver.ProjectFaviconResolver;
const cwd = yield* makeTempDir;
yield* writeTextFile(cwd, "index.html", '<link rel="icon" href="../../secret.svg">');
yield* writeTextFile(cwd, "public/index.html", '<link rel="icon" href="/brand/logo.svg">');
yield* writeTextFile(cwd, "public/brand/logo.svg", "<svg>brand</svg>");
const resolved = yield* resolver.resolvePath(cwd);
expect(resolved).not.toBeNull();
expect(resolved).toContain("public/brand/logo.svg");
}),
);
});
});
@@ -10,7 +10,10 @@ import * as Context from "effect/Context";
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 WorkspacePaths from "../workspace/WorkspacePaths.ts";
@@ -56,6 +59,26 @@ const LINK_ICON_HTML_RE =
const LINK_ICON_OBJ_RE =
/(?=[^}]*\brel\s*:\s*["'](?:icon|shortcut icon)["'])(?=[^}]*\bhref\s*:\s*["']([^"'?]+))[^}]*/i;
export class ProjectFaviconResolutionError extends Schema.TaggedErrorClass<ProjectFaviconResolutionError>()(
"ProjectFaviconResolutionError",
{
operation: Schema.Literals([
"normalize-workspace",
"resolve-path",
"stat-candidate",
"read-source",
]),
workspaceRoot: Schema.String,
relativePath: Schema.optional(Schema.String),
absolutePath: Schema.optional(Schema.String),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to resolve project favicon during ${this.operation} for workspace ${this.workspaceRoot}.`;
}
}
/** Service tag for project favicon resolution. */
export class ProjectFaviconResolver extends Context.Service<
ProjectFaviconResolver,
@@ -65,7 +88,9 @@ export class ProjectFaviconResolver extends Context.Service<
*
* Returns `null` when no candidate icon file can be found.
*/
readonly resolvePath: (cwd: string) => Effect.Effect<string | null>;
readonly resolvePath: (
cwd: string,
) => Effect.Effect<string | null, ProjectFaviconResolutionError>;
}
>()("t3/project/ProjectFaviconResolver") {}
@@ -77,6 +102,17 @@ function extractIconHref(source: string): string | null {
return null;
}
const optionOnNotFound = <A, R>(
effect: Effect.Effect<A, PlatformError.PlatformError, R>,
): Effect.Effect<Option.Option<A>, PlatformError.PlatformError, R> =>
effect.pipe(
Effect.map(Option.some),
Effect.catchTags({
PlatformError: (error) =>
error.reason._tag === "NotFound" ? Effect.succeed(Option.none<A>()) : Effect.fail(error),
}),
);
export const make = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
@@ -90,22 +126,39 @@ export const make = Effect.gen(function* () {
const findExistingFile = Effect.fn("ProjectFaviconResolver.findExistingFile")(function* (
projectCwd: string,
relativeCandidates: ReadonlyArray<string>,
): Effect.fn.Return<string | null> {
): Effect.fn.Return<string | null, ProjectFaviconResolutionError> {
for (const relativePath of relativeCandidates) {
const candidate = yield* workspacePaths
.resolveRelativePathWithinRoot({
workspaceRoot: projectCwd,
relativePath,
})
.pipe(Effect.orElseSucceed(() => null));
if (!candidate) {
.pipe(
Effect.map(Option.some),
Effect.catchTags({
WorkspacePathOutsideRootError: () =>
Effect.succeed(
Option.none<{ readonly absolutePath: string; readonly relativePath: string }>(),
),
}),
);
if (Option.isNone(candidate)) {
continue;
}
const stats = yield* fileSystem
.stat(candidate.absolutePath)
.pipe(Effect.orElseSucceed(() => null));
if (stats?.type === "File") {
return candidate.absolutePath;
const stats = yield* optionOnNotFound(fileSystem.stat(candidate.value.absolutePath)).pipe(
Effect.mapError(
(cause) =>
new ProjectFaviconResolutionError({
operation: "stat-candidate",
workspaceRoot: projectCwd,
relativePath,
absolutePath: candidate.value.absolutePath,
cause,
}),
),
);
if (Option.isSome(stats) && stats.value.type === "File") {
return candidate.value.absolutePath;
}
}
return null;
@@ -114,12 +167,16 @@ export const make = Effect.gen(function* () {
const resolvePath: ProjectFaviconResolver["Service"]["resolvePath"] = Effect.fn(
"ProjectFaviconResolver.resolvePath",
)(function* (cwd) {
const projectCwd = yield* workspacePaths
.normalizeWorkspaceRoot(cwd)
.pipe(Effect.orElseSucceed(() => null));
if (!projectCwd) {
return null;
}
const projectCwd = yield* workspacePaths.normalizeWorkspaceRoot(cwd).pipe(
Effect.mapError(
(cause) =>
new ProjectFaviconResolutionError({
operation: "normalize-workspace",
workspaceRoot: cwd,
cause,
}),
),
);
for (const candidate of FAVICON_CANDIDATES) {
const existing = yield* findExistingFile(projectCwd, [candidate]);
if (existing) {
@@ -133,17 +190,35 @@ export const make = Effect.gen(function* () {
workspaceRoot: projectCwd,
relativePath: sourceFile,
})
.pipe(Effect.orElseSucceed(() => null));
if (!sourcePath) {
.pipe(
Effect.mapError(
(cause) =>
new ProjectFaviconResolutionError({
operation: "resolve-path",
workspaceRoot: projectCwd,
relativePath: sourceFile,
cause,
}),
),
);
const source = yield* optionOnNotFound(
fileSystem.readFileString(sourcePath.absolutePath),
).pipe(
Effect.mapError(
(cause) =>
new ProjectFaviconResolutionError({
operation: "read-source",
workspaceRoot: projectCwd,
relativePath: sourceFile,
absolutePath: sourcePath.absolutePath,
cause,
}),
),
);
if (Option.isNone(source)) {
continue;
}
const source = yield* fileSystem
.readFileString(sourcePath.absolutePath)
.pipe(Effect.orElseSucceed(() => null));
if (!source) {
continue;
}
const href = extractIconHref(source);
const href = extractIconHref(source.value);
if (!href) {
continue;
}
@@ -153,9 +153,8 @@ describe("ProjectSetupScriptRunner", () => {
it.effect("keeps terminal failures as the exact cause of a structured operation error", () => {
const rootCause = new Error("stat failed");
const terminalError = new TerminalManager.TerminalCwdError({
const terminalError = new TerminalManager.TerminalCwdStatError({
cwd: "/repo/worktrees/a",
reason: "statFailed",
cause: rootCause,
});
const project = makeProject([
@@ -4,6 +4,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import type * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
import { describe, expect, it } from "vite-plus/test";
import type * as EffectAcpSchema from "effect-acp/schema";
import type { CursorSettings } from "@t3tools/contracts";
@@ -24,7 +25,11 @@ import {
} from "./CursorProvider.ts";
const runNode = <A, E>(
effect: Effect.Effect<A, E, FileSystem.FileSystem | Path.Path>,
effect: Effect.Effect<
A,
E,
ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
>,
): Promise<A> => Effect.runPromise(effect.pipe(Effect.provide(NodeServices.layer)));
const resolveMockAgentPath = Effect.fn("resolveMockAgentPath")(function* () {
@@ -293,6 +298,18 @@ const baseCursorSettings: CursorSettings = {
apiEndpoint: "",
customModels: [],
};
const cursorAcpDiscoveryFailedMessage = [
"Cursor ACP model discovery failed.",
"Cursor CLI setup may be incomplete; install or enable the Cursor CLI, restart T3 Code, and try again.",
"See https://cursor.com/docs/cli/installation.",
"Check server logs for ACP details.",
].join(" ");
const missingCursorBinaryPath = "/definitely/not/installed/t3-cursor-agent";
const cursorCliCommandMissingMessage = [
`Cursor CLI command \`${missingCursorBinaryPath}\` was not found.`,
`Install or enable the Cursor CLI, make sure \`${missingCursorBinaryPath}\` is on PATH, then restart T3 Code.`,
"See https://cursor.com/docs/cli/installation.",
].join(" ");
describe("getCursorFallbackModels", () => {
it("does not publish any built-in cursor models before ACP discovery", () => {
@@ -338,12 +355,11 @@ describe("buildCursorProviderSnapshot", () => {
auth: { status: "unauthenticated" },
message: "Cursor Agent is not authenticated. Run `agent login` and try again.",
},
discoveryWarning: "Cursor ACP model discovery failed. Check server logs for details.",
discoveryWarning: cursorAcpDiscoveryFailedMessage,
}),
).toMatchObject({
status: "error",
message:
"Cursor Agent is not authenticated. Run `agent login` and try again. Cursor ACP model discovery failed. Check server logs for details.",
message: `Cursor Agent is not authenticated. Run \`agent login\` and try again. ${cursorAcpDiscoveryFailedMessage}`,
models: [
{
slug: "claude-sonnet-4-6",
@@ -411,10 +427,28 @@ describe("buildCursorCapabilitiesFromConfigOptions", () => {
});
describe("checkCursorProviderStatus", () => {
it("reports the install docs when the Cursor CLI command is missing", async () => {
const provider = await runNode(
checkCursorProviderStatus({
enabled: true,
binaryPath: missingCursorBinaryPath,
apiEndpoint: "",
customModels: [],
}),
);
expect(provider).toMatchObject({
installed: false,
status: "error",
auth: { status: "unknown" },
message: cursorCliCommandMissingMessage,
});
});
it("passes the injected environment to ACP model discovery", async () => {
const { requestLogPath, wrapperPath } = await runNode(makeProviderStatusEnvFixture());
const provider = await Effect.runPromise(
const provider = await runNode(
checkCursorProviderStatus(
{
enabled: true,
@@ -426,7 +460,7 @@ describe("checkCursorProviderStatus", () => {
...process.env,
T3_ACP_REQUEST_LOG_PATH: requestLogPath,
},
).pipe(Effect.provide(NodeServices.layer)),
),
);
expect(provider.models.map((model) => model.slug)).toEqual([
@@ -443,13 +477,13 @@ describe("discoverCursorModelsViaAcp", () => {
it("keeps the ACP probe runtime alive long enough to discover models", async () => {
const wrapperPath = await runNode(makeMockAgentWrapper());
const models = await Effect.runPromise(
const models = await runNode(
discoverCursorModelsViaAcp({
enabled: true,
binaryPath: wrapperPath,
apiEndpoint: "",
customModels: [],
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
}).pipe(Effect.scoped),
);
expect(models.map((model) => model.slug)).toEqual([
@@ -465,13 +499,13 @@ describe("discoverCursorModelsViaAcp", () => {
makeExitLogFixture("cursor-provider-exit-log-"),
);
await Effect.runPromise(
await runNode(
discoverCursorModelsViaAcp({
enabled: true,
binaryPath: wrapperPath,
apiEndpoint: "",
customModels: [],
}).pipe(Effect.provide(NodeServices.layer)),
}),
);
const exitLog = await runNode(waitForFileContent(exitLogPath));
@@ -62,6 +62,13 @@ const EMPTY_CAPABILITIES: ModelCapabilities = createModelCapabilities({
const CURSOR_ACP_MODEL_DISCOVERY_TIMEOUT_MS = 15_000;
const CURSOR_PARAMETERIZED_MODEL_PICKER_MIN_VERSION_DATE = 2026_04_08;
const CURSOR_CLI_INSTALLATION_DOCS_URL = "https://cursor.com/docs/cli/installation";
const CURSOR_ACP_MODEL_DISCOVERY_FAILED_MESSAGE = [
"Cursor ACP model discovery failed.",
"Cursor CLI setup may be incomplete; install or enable the Cursor CLI, restart T3 Code, and try again.",
`See ${CURSOR_CLI_INSTALLATION_DOCS_URL}.`,
"Check server logs for ACP details.",
].join(" ");
export const CURSOR_PARAMETERIZED_MODEL_PICKER_CAPABILITIES = {
_meta: {
parameterizedModelPicker: true,
@@ -608,6 +615,14 @@ function joinProviderMessages(...messages: ReadonlyArray<string | undefined>): s
return parts.length > 0 ? parts.join(" ") : undefined;
}
function buildCursorCliCommandMissingMessage(binaryPath: string): string {
return [
`Cursor CLI command \`${binaryPath}\` was not found.`,
`Install or enable the Cursor CLI, make sure \`${binaryPath}\` is on PATH, then restart T3 Code.`,
`See ${CURSOR_CLI_INSTALLATION_DOCS_URL}.`,
].join(" ");
}
export function buildCursorProviderSnapshot(input: {
readonly checkedAt: string;
readonly cursorSettings: CursorSettings;
@@ -1020,7 +1035,7 @@ export const checkCursorProviderStatus = Effect.fn("checkCursorProviderStatus")(
status: "error",
auth: { status: "unknown" },
message: isCommandMissingCause(error)
? "Cursor Agent CLI (`agent`) is not installed or not on PATH."
? buildCursorCliCommandMissingMessage(cursorSettings.binaryPath)
: "Failed to execute Cursor Agent CLI health check.",
},
});
@@ -1079,7 +1094,7 @@ export const checkCursorProviderStatus = Effect.fn("checkCursorProviderStatus")(
yield* Effect.logWarning("Cursor ACP model discovery failed", {
errorTag: causeErrorTag(discoveryExit.cause),
});
discoveryWarning = "Cursor ACP model discovery failed. Check server logs for details.";
discoveryWarning = CURSOR_ACP_MODEL_DISCOVERY_FAILED_MESSAGE;
} else if (Option.isNone(discoveryExit.value)) {
discoveryWarning = `Cursor ACP model discovery timed out after ${CURSOR_ACP_MODEL_DISCOVERY_TIMEOUT_MS}ms.`;
} else if (discoveryExit.value.value.length === 0) {
+3 -1
View File
@@ -327,7 +327,9 @@ export const make = Effect.gen(function* () {
Effect.catch((error) =>
Effect.logWarning("failed to start server settings runtime", {
path: error.settingsPath,
detail: error.detail,
operation: error.operation,
providerInstanceId: error.providerInstanceId,
environmentVariable: error.environmentVariable,
cause: error.cause,
}),
),
+167
View File
@@ -0,0 +1,167 @@
import { assert, describe, it } from "@effect/vitest";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Logger from "effect/Logger";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as References from "effect/References";
import * as Schema from "effect/Schema";
import * as ServerRuntimeState from "./serverRuntimeState.ts";
const isServerRuntimeStateError = Schema.is(ServerRuntimeState.ServerRuntimeStateError);
interface CapturedLog {
readonly message: unknown;
readonly annotations: Readonly<Record<string, unknown>>;
}
describe("serverRuntimeState", () => {
it.effect("persists and reads the runtime state", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const root = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-server-runtime-state-test-",
});
const statePath = path.join(root, "runtime", "server.json");
const state: ServerRuntimeState.PersistedServerRuntimeState = {
version: 1,
pid: 123,
host: "127.0.0.1",
port: 4_971,
origin: "http://127.0.0.1:4971",
startedAt: "2026-06-20T00:00:00.000Z",
};
yield* ServerRuntimeState.persistServerRuntimeState({ path: statePath, state });
const restored = yield* ServerRuntimeState.readPersistedServerRuntimeState(statePath);
assert.deepEqual(Option.getOrThrow(restored), state);
}).pipe(Effect.provide(NodeServices.layer)),
);
it.effect("treats a missing runtime state file as absent", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const root = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-server-runtime-state-test-",
});
const restored = yield* ServerRuntimeState.readPersistedServerRuntimeState(
path.join(root, "missing.json"),
);
assert.isTrue(Option.isNone(restored));
}).pipe(Effect.provide(NodeServices.layer)),
);
it.effect("preserves malformed state decode failures", () => {
const logs: CapturedLog[] = [];
const logger = Logger.make(({ fiber, message }) => {
logs.push({
message,
annotations: fiber.getRef(References.CurrentLogAnnotations),
});
});
return Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const root = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-server-runtime-state-test-",
});
const statePath = path.join(root, "server.json");
yield* fileSystem.writeFileString(statePath, "{not json");
const restored = yield* ServerRuntimeState.readPersistedServerRuntimeState(statePath);
assert.isTrue(Option.isNone(restored));
assert.equal(logs[0]?.message, `Failed to decode server runtime state at ${statePath}.`);
const error = logs[0]?.annotations.cause;
assert.isTrue(isServerRuntimeStateError(error));
if (isServerRuntimeStateError(error)) {
assert.equal(error.operation, "decode");
assert.equal(error.statePath, statePath);
assert.equal(error.message, `Failed to decode server runtime state at ${statePath}.`);
assert.deepInclude(error.cause, { _tag: "SchemaError" });
}
}).pipe(
Effect.provide(
Layer.merge(NodeServices.layer, Logger.layer([logger], { mergeWithExisting: false })),
),
);
});
it.effect("preserves runtime state read failures", () => {
const logs: CapturedLog[] = [];
const logger = Logger.make(({ fiber, message }) => {
logs.push({
message,
annotations: fiber.getRef(References.CurrentLogAnnotations),
});
});
return Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const root = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-server-runtime-state-test-",
});
const statePath = path.join(root, "server.json");
yield* fileSystem.makeDirectory(statePath);
const restored = yield* ServerRuntimeState.readPersistedServerRuntimeState(statePath);
assert.isTrue(Option.isNone(restored));
assert.equal(logs[0]?.message, `Failed to read server runtime state at ${statePath}.`);
const error = logs[0]?.annotations.cause;
assert.isTrue(isServerRuntimeStateError(error));
if (isServerRuntimeStateError(error)) {
assert.equal(error.operation, "read");
assert.equal(error.statePath, statePath);
assert.equal(error.message, `Failed to read server runtime state at ${statePath}.`);
assert.deepInclude(error.cause, { _tag: "PlatformError" });
}
}).pipe(
Effect.provide(
Layer.merge(NodeServices.layer, Logger.layer([logger], { mergeWithExisting: false })),
),
);
});
it.effect("preserves runtime state persistence failures", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const root = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-server-runtime-state-test-",
});
const blockedDirectory = path.join(root, "not-a-directory");
const statePath = path.join(blockedDirectory, "server.json");
yield* fileSystem.writeFileString(blockedDirectory, "blocked");
const error = yield* ServerRuntimeState.persistServerRuntimeState({
path: statePath,
state: {
version: 1,
pid: 123,
port: 4_971,
origin: "http://127.0.0.1:4971",
startedAt: "2026-06-20T00:00:00.000Z",
},
}).pipe(Effect.flip);
assert.isTrue(isServerRuntimeStateError(error));
if (isServerRuntimeStateError(error)) {
assert.equal(error.operation, "persist");
assert.equal(error.statePath, statePath);
assert.equal(error.message, `Failed to persist server runtime state at ${statePath}.`);
assert.deepInclude(error.cause, { _tag: "PlatformError" });
}
}).pipe(Effect.provide(NodeServices.layer)),
);
});
+84 -8
View File
@@ -18,6 +18,19 @@ export const PersistedServerRuntimeState = Schema.Struct({
});
export type PersistedServerRuntimeState = typeof PersistedServerRuntimeState.Type;
export class ServerRuntimeStateError extends Schema.TaggedErrorClass<ServerRuntimeStateError>()(
"ServerRuntimeStateError",
{
operation: Schema.Literals(["persist", "read", "decode", "clear"]),
statePath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to ${this.operation} server runtime state at ${this.statePath}.`;
}
}
const decodePersistedServerRuntimeState = Schema.decodeUnknownEffect(
Schema.fromJsonString(PersistedServerRuntimeState),
);
@@ -51,27 +64,90 @@ export const persistServerRuntimeState = (input: {
writeFileStringAtomically({
filePath: input.path,
contents: `${JSON.stringify(input.state)}\n`,
});
}).pipe(
Effect.mapError(
(cause) =>
new ServerRuntimeStateError({
operation: "persist",
statePath: input.path,
cause,
}),
),
);
export const clearPersistedServerRuntimeState = (path: string) =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
yield* fs.remove(path, { force: true }).pipe(Effect.ignore({ log: true }));
yield* fs.remove(path, { force: true }).pipe(
Effect.mapError(
(cause) =>
new ServerRuntimeStateError({
operation: "clear",
statePath: path,
cause,
}),
),
Effect.catchTags({
ServerRuntimeStateError: (error) =>
Effect.logWarning(error.message).pipe(
Effect.annotateLogs({
operation: error.operation,
statePath: error.statePath,
cause: error,
}),
),
}),
);
});
export const readPersistedServerRuntimeState = (path: string) =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const exists = yield* fs.exists(path).pipe(Effect.orElseSucceed(() => false));
if (!exists) {
const raw = yield* fs.readFileString(path).pipe(
Effect.matchEffect({
onFailure: (cause) =>
cause.reason._tag === "NotFound"
? Effect.succeed(Option.none<string>())
: Effect.fail(
new ServerRuntimeStateError({
operation: "read",
statePath: path,
cause,
}),
),
onSuccess: (contents) => Effect.succeed(Option.some(contents)),
}),
);
if (Option.isNone(raw)) {
return Option.none<PersistedServerRuntimeState>();
}
const raw = yield* fs.readFileString(path).pipe(Effect.orElseSucceed(() => ""));
const trimmed = raw.trim();
const trimmed = raw.value.trim();
if (trimmed.length === 0) {
return Option.none<PersistedServerRuntimeState>();
}
return yield* decodePersistedServerRuntimeState(trimmed).pipe(Effect.option);
});
return yield* decodePersistedServerRuntimeState(trimmed).pipe(
Effect.map(Option.some),
Effect.mapError(
(cause) =>
new ServerRuntimeStateError({
operation: "decode",
statePath: path,
cause,
}),
),
);
}).pipe(
Effect.catchTags({
ServerRuntimeStateError: (error) =>
Effect.logWarning(error.message).pipe(
Effect.annotateLogs({
operation: error.operation,
statePath: error.statePath,
cause: error,
}),
Effect.as(Option.none<PersistedServerRuntimeState>()),
),
}),
);
+57
View File
@@ -12,6 +12,7 @@ import * as Effect from "effect/Effect";
import * as Duration from "effect/Duration";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as PlatformError from "effect/PlatformError";
import * as Schema from "effect/Schema";
import * as ServerSecretStore from "./auth/ServerSecretStore.ts";
import * as ServerConfig from "./config.ts";
@@ -32,7 +33,63 @@ const makeServerSettingsLayer = () =>
),
);
const makeFailingSecretStoreLayer = (cause: ServerSecretStore.SecretStoreError) =>
Layer.succeed(
ServerSecretStore.ServerSecretStore,
ServerSecretStore.ServerSecretStore.of({
get: () => Effect.fail(cause),
set: () => Effect.void,
create: () => Effect.void,
getOrCreateRandom: () => Effect.succeed(new Uint8Array()),
remove: () => Effect.void,
}),
);
it.layer(NodeServices.layer)("server settings", (it) => {
it.effect("preserves context when reading a provider environment secret fails", () => {
const platformCause = PlatformError.systemError({
_tag: "PermissionDenied",
module: "FileSystem",
method: "readFile",
pathOrDescriptor: "provider environment secret",
description: "Secret backend unavailable.",
});
const cause = new ServerSecretStore.SecretStoreReadError({
resource: "provider environment secret",
cause: platformCause,
});
const configLayer = Layer.fresh(
ServerConfig.layerTest(process.cwd(), {
prefix: "t3code-server-settings-secret-failure-test-",
}),
);
const settingsLayer = ServerSettingsModule.layer.pipe(
Layer.provide(makeFailingSecretStoreLayer(cause)),
Layer.provideMerge(configLayer),
);
return Effect.gen(function* () {
const serverConfig = yield* ServerConfig.ServerConfig;
const fileSystem = yield* FileSystem.FileSystem;
const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
yield* fileSystem.writeFileString(
serverConfig.settingsPath,
'{"providerInstances":{"codex_personal":{"driver":"codex","environment":[{"name":"OPENROUTER_API_KEY","value":"","sensitive":true,"valueRedacted":true}],"config":{}}}}',
);
const error = yield* Effect.flip(serverSettings.getSettings);
assert.deepInclude(error, {
_tag: "ServerSettingsError",
operation: "read-secret",
providerInstanceId: "codex_personal",
environmentVariable: "OPENROUTER_API_KEY",
});
assert.strictEqual(error.cause, cause);
assert.notInclude(error.message, cause.message);
}).pipe(Effect.provide(settingsLayer));
});
it.effect("decodes nested settings patches", () =>
Effect.gen(function* () {
assert.deepEqual(
+66 -49
View File
@@ -40,7 +40,6 @@ import * as Path from "effect/Path";
import * as PubSub from "effect/PubSub";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as SchemaIssue from "effect/SchemaIssue";
import * as Semaphore from "effect/Semaphore";
import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
@@ -67,7 +66,7 @@ const normalizeServerSettings = (
(cause) =>
new ServerSettingsError({
settingsPath: "<memory>",
detail: `failed to normalize server settings: ${SchemaIssue.makeFormatterDefault()(cause.issue)}`,
operation: "normalize",
cause,
}),
),
@@ -277,7 +276,7 @@ const make = Effect.gen(function* () {
(cause) =>
new ServerSettingsError({
settingsPath,
detail: "failed to check settings file existence",
operation: "check-exists",
cause,
}),
),
@@ -288,7 +287,7 @@ const make = Effect.gen(function* () {
(cause) =>
new ServerSettingsError({
settingsPath,
detail: "failed to read settings file",
operation: "read-file",
cause,
}),
),
@@ -305,6 +304,7 @@ const make = Effect.gen(function* () {
yield* Effect.logWarning("failed to parse settings.json, using defaults", {
path: settingsPath,
issues: Cause.pretty(decoded.cause),
cause: decoded.cause,
});
return DEFAULT_SERVER_SETTINGS;
}
@@ -318,13 +318,6 @@ const make = Effect.gen(function* () {
const getSettingsFromCache = Cache.get(settingsCache, cacheKey);
const toSettingsError = (detail: string, cause: unknown) =>
new ServerSettingsError({
settingsPath,
detail,
cause,
});
const materializeProviderEnvironmentSecrets = (
settings: ServerSettings,
): Effect.Effect<ServerSettings, ServerSettingsError> =>
@@ -343,11 +336,15 @@ const make = Effect.gen(function* () {
const secret = yield* secretStore
.get(providerEnvironmentSecretName({ instanceId, name: variable.name }))
.pipe(
Effect.mapError((cause) =>
toSettingsError(
`failed to read sensitive environment variable ${variable.name}`,
cause,
),
Effect.mapError(
(cause) =>
new ServerSettingsError({
settingsPath,
operation: "read-secret",
providerInstanceId: instanceId,
environmentVariable: variable.name,
cause,
}),
),
);
environment.push({
@@ -382,13 +379,18 @@ const make = Effect.gen(function* () {
for (const variable of instance.environment) {
const secretName = providerEnvironmentSecretName({ instanceId, name: variable.name });
if (!variable.sensitive) {
yield* secretStore
.remove(secretName)
.pipe(
Effect.mapError((cause) =>
toSettingsError(`failed to remove environment secret ${variable.name}`, cause),
),
);
yield* secretStore.remove(secretName).pipe(
Effect.mapError(
(cause) =>
new ServerSettingsError({
settingsPath,
operation: "remove-secret",
providerInstanceId: instanceId,
environmentVariable: variable.name,
cause,
}),
),
);
environment.push(redactProviderEnvironmentVariable(variable));
continue;
}
@@ -396,22 +398,32 @@ const make = Effect.gen(function* () {
nextSecretKeys.add(secretName);
if (!variable.valueRedacted) {
if (variable.value.length > 0) {
yield* secretStore
.set(secretName, textEncoder.encode(variable.value))
.pipe(
Effect.mapError((cause) =>
toSettingsError(`failed to persist environment secret ${variable.name}`, cause),
),
);
yield* secretStore.set(secretName, textEncoder.encode(variable.value)).pipe(
Effect.mapError(
(cause) =>
new ServerSettingsError({
settingsPath,
operation: "write-secret",
providerInstanceId: instanceId,
environmentVariable: variable.name,
cause,
}),
),
);
environment.push({ ...variable, value: "", valueRedacted: true });
} else {
yield* secretStore
.remove(secretName)
.pipe(
Effect.mapError((cause) =>
toSettingsError(`failed to remove environment secret ${variable.name}`, cause),
),
);
yield* secretStore.remove(secretName).pipe(
Effect.mapError(
(cause) =>
new ServerSettingsError({
settingsPath,
operation: "remove-secret",
providerInstanceId: instanceId,
environmentVariable: variable.name,
cause,
}),
),
);
const { valueRedacted: _omit, ...rest } = variable;
environment.push(rest);
}
@@ -431,16 +443,18 @@ const make = Effect.gen(function* () {
if (!variable.sensitive) continue;
const secretName = providerEnvironmentSecretName({ instanceId, name: variable.name });
if (nextSecretKeys.has(secretName)) continue;
yield* secretStore
.remove(secretName)
.pipe(
Effect.mapError((cause) =>
toSettingsError(
`failed to remove stale environment secret ${variable.name}`,
yield* secretStore.remove(secretName).pipe(
Effect.mapError(
(cause) =>
new ServerSettingsError({
settingsPath,
operation: "remove-stale-secret",
providerInstanceId: instanceId,
environmentVariable: variable.name,
cause,
),
),
);
}),
),
);
}
}
@@ -468,7 +482,7 @@ const make = Effect.gen(function* () {
(cause) =>
new ServerSettingsError({
settingsPath,
detail: "failed to write settings file",
operation: "write-file",
cause,
}),
),
@@ -492,7 +506,7 @@ const make = Effect.gen(function* () {
(cause) =>
new ServerSettingsError({
settingsPath,
detail: "failed to prepare settings directory",
operation: "prepare-directory",
cause,
}),
),
@@ -571,7 +585,10 @@ const make = Effect.gen(function* () {
materializeProviderEnvironmentSecrets(settings).pipe(
Effect.catch((error: ServerSettingsError) =>
Effect.logWarning("failed to materialize provider environment secrets", {
detail: error.detail,
operation: error.operation,
providerInstanceId: error.providerInstanceId,
environmentVariable: error.environmentVariable,
cause: error.cause,
}).pipe(Effect.as(settings)),
),
),
@@ -4,8 +4,9 @@ import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError";
import { ChildProcessSpawner } from "effect/unstable/process";
import { VcsProcessExitError } from "@t3tools/contracts";
import { VcsProcessExitError, VcsProcessSpawnError } from "@t3tools/contracts";
import * as VcsProcess from "../vcs/VcsProcess.ts";
import * as AzureDevOpsCli from "./AzureDevOpsCli.ts";
@@ -345,11 +346,63 @@ describe("AzureDevOpsCli.layer", () => {
const az = yield* AzureDevOpsCli.AzureDevOpsCli;
const error = yield* az.execute({ cwd: "/repo", args: ["repos", "list"] }).pipe(Effect.flip);
assert.instanceOf(error, AzureDevOpsCli.AzureDevOpsCommandFailedError);
assert.strictEqual(error.operation, "execute");
assert.strictEqual(error.command, "az");
assert.strictEqual(error.cwd, "/repo");
assert.strictEqual(error.argumentCount, 2);
assert.strictEqual(error.detail, "Azure DevOps CLI command failed.");
assert.strictEqual(error.cause, cause);
assert.equal(error.message.includes("sensitive-upstream-detail"), false);
}).pipe(Effect.provide(layer)),
);
it.effect("does not report a missing working directory as a missing Azure CLI", () =>
Effect.gen(function* () {
const cwd = "/missing/repo";
const platformCause = PlatformError.systemError({
_tag: "NotFound",
module: "ChildProcess",
method: "spawn",
syscall: "chdir",
pathOrDescriptor: cwd,
});
const cause = new VcsProcessSpawnError({
operation: "AzureDevOpsCli.execute",
command: "az",
cwd,
argumentCount: 2,
cause: platformCause,
});
mockRun.mockReturnValueOnce(Effect.fail(cause));
const az = yield* AzureDevOpsCli.AzureDevOpsCli;
const error = yield* az.execute({ cwd, args: ["repos", "list"] }).pipe(Effect.flip);
assert.instanceOf(error, AzureDevOpsCli.AzureDevOpsCommandFailedError);
assert.strictEqual(error.cwd, cwd);
assert.strictEqual(error.cause, cause);
}).pipe(Effect.provide(layer)),
);
it.effect("keeps invalid pull request output diagnostics structured", () =>
Effect.gen(function* () {
mockRun.mockReturnValueOnce(Effect.succeed(processOutput("not-json")));
const az = yield* AzureDevOpsCli.AzureDevOpsCli;
const error = yield* az.getPullRequest({ cwd: "/repo", reference: "42" }).pipe(Effect.flip);
assert.instanceOf(error, AzureDevOpsCli.AzureDevOpsPullRequestDecodeError);
assert.strictEqual(error.operation, "getPullRequest");
assert.strictEqual(error.command, "az");
assert.strictEqual(error.cwd, "/repo");
assert.strictEqual(error.outputLength, 8);
assert.strictEqual(error.detail, "Azure DevOps CLI returned invalid pull request JSON.");
assert.exists(error.cause);
assert.strictEqual(
error.message,
"Azure DevOps CLI failed in getPullRequest: Azure DevOps CLI returned invalid pull request JSON.",
);
}).pipe(Effect.provide(layer)),
);
});
+166 -83
View File
@@ -1,9 +1,11 @@
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as PlatformError from "effect/PlatformError";
import * as Result from "effect/Result";
import * as Schema from "effect/Schema";
import {
NonNegativeInt,
TrimmedNonEmptyString,
type SourceControlRepositoryVisibility,
type VcsError,
@@ -19,16 +21,61 @@ import * as SourceControlProvider from "./SourceControlProvider.ts";
const DEFAULT_TIMEOUT_MS = 30_000;
export class AzureDevOpsCliError extends Schema.TaggedErrorClass<AzureDevOpsCliError>()(
"AzureDevOpsCliError",
{
operation: Schema.String,
command: Schema.String,
cwd: Schema.String,
detail: Schema.String,
cause: Schema.optional(Schema.Defect()),
},
const azureDevOpsCommandErrorFields = {
operation: Schema.Literal("execute"),
command: Schema.Literal("az"),
cwd: Schema.String,
argumentCount: NonNegativeInt,
cause: Schema.Defect(),
};
export class AzureDevOpsCliUnavailableError extends Schema.TaggedErrorClass<AzureDevOpsCliUnavailableError>()(
"AzureDevOpsCliUnavailableError",
azureDevOpsCommandErrorFields,
) {
get detail(): string {
return "Azure CLI (`az`) with the Azure DevOps extension is required but not available on PATH.";
}
override get message(): string {
return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;
}
}
export class AzureDevOpsCliAuthenticationError extends Schema.TaggedErrorClass<AzureDevOpsCliAuthenticationError>()(
"AzureDevOpsCliAuthenticationError",
azureDevOpsCommandErrorFields,
) {
get detail(): string {
return "Azure DevOps CLI is not authenticated. Run `az devops login` and retry.";
}
override get message(): string {
return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;
}
}
export class AzureDevOpsPullRequestNotFoundError extends Schema.TaggedErrorClass<AzureDevOpsPullRequestNotFoundError>()(
"AzureDevOpsPullRequestNotFoundError",
azureDevOpsCommandErrorFields,
) {
get detail(): string {
return "Pull request not found. Check the PR number or URL and try again.";
}
override get message(): string {
return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;
}
}
export class AzureDevOpsCommandFailedError extends Schema.TaggedErrorClass<AzureDevOpsCommandFailedError>()(
"AzureDevOpsCommandFailedError",
azureDevOpsCommandErrorFields,
) {
get detail(): string {
return "Azure DevOps CLI command failed.";
}
override get message(): string {
return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;
}
@@ -38,53 +85,109 @@ export class AzureDevOpsCliError extends Schema.TaggedErrorClass<AzureDevOpsCliE
readonly operation: "execute";
readonly command: "az";
readonly cwd: string;
readonly argumentCount: number;
},
error: VcsError | unknown,
cause: VcsError,
): AzureDevOpsCliError {
const lower = errorText(error).toLowerCase();
if (lower.includes("command not found: az") || lower.includes("enoent")) {
return new AzureDevOpsCliError({
...context,
detail:
"Azure CLI (`az`) with the Azure DevOps extension is required but not available on PATH.",
cause: error,
});
}
const fields = { ...context, cause };
if (
lower.includes("az devops login") ||
lower.includes("please run az login") ||
lower.includes("not logged in") ||
lower.includes("authentication failed") ||
lower.includes("unauthorized")
cause._tag === "VcsProcessSpawnError" &&
cause.cause instanceof PlatformError.PlatformError &&
cause.cause.reason._tag === "NotFound" &&
cause.cause.reason.pathOrDescriptor !== context.cwd &&
cause.cause.reason.syscall !== "chdir"
) {
return new AzureDevOpsCliError({
...context,
detail: "Azure DevOps CLI is not authenticated. Run `az devops login` and retry.",
cause: error,
});
return new AzureDevOpsCliUnavailableError(fields);
}
if (
lower.includes("pull request") &&
(lower.includes("not found") || lower.includes("does not exist"))
) {
return new AzureDevOpsCliError({
...context,
detail: "Pull request not found. Check the PR number or URL and try again.",
cause: error,
});
if (cause._tag === "VcsProcessExitError") {
if (cause.failureKind === "authentication") {
return new AzureDevOpsCliAuthenticationError(fields);
}
if (cause.failureKind === "not-found") {
return new AzureDevOpsPullRequestNotFoundError(fields);
}
}
return new AzureDevOpsCliError({
...context,
detail: "Azure DevOps CLI command failed.",
cause: error,
});
return new AzureDevOpsCommandFailedError(fields);
}
}
const azureDevOpsDecodeErrorFields = {
command: Schema.Literal("az"),
cwd: Schema.String,
outputLength: NonNegativeInt,
cause: Schema.Defect(),
};
export class AzureDevOpsPullRequestListDecodeError extends Schema.TaggedErrorClass<AzureDevOpsPullRequestListDecodeError>()(
"AzureDevOpsPullRequestListDecodeError",
{
operation: Schema.Literal("listPullRequests"),
...azureDevOpsDecodeErrorFields,
},
) {
get detail(): string {
return "Azure DevOps CLI returned invalid PR list JSON.";
}
override get message(): string {
return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;
}
}
export class AzureDevOpsPullRequestDecodeError extends Schema.TaggedErrorClass<AzureDevOpsPullRequestDecodeError>()(
"AzureDevOpsPullRequestDecodeError",
{
operation: Schema.Literal("getPullRequest"),
...azureDevOpsDecodeErrorFields,
},
) {
get detail(): string {
return "Azure DevOps CLI returned invalid pull request JSON.";
}
override get message(): string {
return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;
}
}
const AzureDevOpsRepositoryDecodeOperation = Schema.Literals([
"getRepositoryCloneUrls",
"getDefaultBranch",
"createRepository",
]);
export class AzureDevOpsRepositoryDecodeError extends Schema.TaggedErrorClass<AzureDevOpsRepositoryDecodeError>()(
"AzureDevOpsRepositoryDecodeError",
{
operation: AzureDevOpsRepositoryDecodeOperation,
...azureDevOpsDecodeErrorFields,
},
) {
get detail(): string {
return "Azure DevOps CLI returned invalid repository JSON.";
}
override get message(): string {
return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;
}
}
export const AzureDevOpsCliError = Schema.Union([
AzureDevOpsCliUnavailableError,
AzureDevOpsCliAuthenticationError,
AzureDevOpsPullRequestNotFoundError,
AzureDevOpsCommandFailedError,
AzureDevOpsPullRequestListDecodeError,
AzureDevOpsPullRequestDecodeError,
AzureDevOpsRepositoryDecodeError,
]);
export type AzureDevOpsCliError = typeof AzureDevOpsCliError.Type;
export const isAzureDevOpsCliError = Schema.is(AzureDevOpsCliError);
export interface AzureDevOpsRepositoryCloneUrls {
readonly nameWithOwner: string;
readonly url: string;
@@ -146,17 +249,6 @@ export class AzureDevOpsCli extends Context.Service<
}
>()("t3/sourceControl/AzureDevOpsCli") {}
function errorText(error: VcsError | unknown): string {
if (typeof error === "object" && error !== null) {
const tag = "_tag" in error && typeof error._tag === "string" ? error._tag : "";
const detail = "detail" in error && typeof error.detail === "string" ? error.detail : "";
const message = "message" in error && typeof error.message === "string" ? error.message : "";
return [tag, detail, message].filter(Boolean).join("\n");
}
return String(error);
}
function normalizeChangeRequestId(reference: string): string {
const trimmed = reference.trim().replace(/^#/, "");
const urlMatch = /(?:pullrequest|pull-request|pull|_pulls?)\/(\d+)(?:\D.*)?$/i.exec(trimmed);
@@ -225,19 +317,18 @@ function parseRepositorySpecifier(repository: string): {
function decodeAzureDevOpsJson<S extends Schema.Top>(
raw: string,
schema: S,
operation: "getRepositoryCloneUrls" | "getDefaultBranch" | "createRepository",
invalidDetail: string,
operation: typeof AzureDevOpsRepositoryDecodeOperation.Type,
cwd: string,
): Effect.Effect<S["Type"], AzureDevOpsCliError, S["DecodingServices"]> {
): Effect.Effect<S["Type"], AzureDevOpsRepositoryDecodeError, S["DecodingServices"]> {
return Schema.decodeEffect(Schema.fromJsonString(schema))(raw).pipe(
Effect.mapError(
(error) =>
new AzureDevOpsCliError({
(cause) =>
new AzureDevOpsRepositoryDecodeError({
operation,
command: "az",
cwd,
detail: invalidDetail,
cause: error,
outputLength: raw.length,
cause,
}),
),
);
@@ -257,8 +348,13 @@ export const make = Effect.gen(function* () {
})
.pipe(
Effect.mapError((error) =>
AzureDevOpsCliError.fromVcsError(
{ operation: "execute", command: "az", cwd: input.cwd },
AzureDevOpsCommandFailedError.fromVcsError(
{
operation: "execute",
command: "az",
cwd: input.cwd,
argumentCount: input.args.length,
},
error,
),
),
@@ -297,11 +393,11 @@ export const make = Effect.gen(function* () {
Effect.flatMap((decoded) => {
if (!Result.isSuccess(decoded)) {
return Effect.fail(
new AzureDevOpsCliError({
new AzureDevOpsPullRequestListDecodeError({
operation: "listPullRequests",
command: "az",
cwd: input.cwd,
detail: "Azure DevOps CLI returned invalid PR list JSON.",
outputLength: raw.length,
cause: decoded.failure,
}),
);
@@ -331,11 +427,11 @@ export const make = Effect.gen(function* () {
Effect.flatMap((decoded) => {
if (!Result.isSuccess(decoded)) {
return Effect.fail(
new AzureDevOpsCliError({
new AzureDevOpsPullRequestDecodeError({
operation: "getPullRequest",
command: "az",
cwd: input.cwd,
detail: "Azure DevOps CLI returned invalid pull request JSON.",
outputLength: raw.length,
cause: decoded.failure,
}),
);
@@ -357,7 +453,6 @@ export const make = Effect.gen(function* () {
raw,
RawAzureDevOpsRepositorySchema,
"getRepositoryCloneUrls",
"Azure DevOps CLI returned invalid repository JSON.",
input.cwd,
),
),
@@ -383,13 +478,7 @@ export const make = Effect.gen(function* () {
}).pipe(
Effect.map((result) => result.stdout.trim()),
Effect.flatMap((raw) =>
decodeAzureDevOpsJson(
raw,
RawAzureDevOpsRepositorySchema,
"createRepository",
"Azure DevOps CLI returned invalid repository JSON.",
input.cwd,
),
decodeAzureDevOpsJson(raw, RawAzureDevOpsRepositorySchema, "createRepository", input.cwd),
),
Effect.map(normalizeRepositoryCloneUrls),
);
@@ -421,13 +510,7 @@ export const make = Effect.gen(function* () {
}).pipe(
Effect.map((result) => result.stdout.trim()),
Effect.flatMap((raw) =>
decodeAzureDevOpsJson(
raw,
RawAzureDevOpsRepositorySchema,
"getDefaultBranch",
"Azure DevOps CLI returned invalid repository JSON.",
input.cwd,
),
decodeAzureDevOpsJson(raw, RawAzureDevOpsRepositorySchema, "getDefaultBranch", input.cwd),
),
Effect.map((repo) => normalizeDefaultBranch(repo.defaultBranch)),
),
@@ -48,11 +48,11 @@ it.effect("maps Azure DevOps PR summaries into provider-neutral change requests"
it.effect("adds change-request context while retaining Azure CLI causes", () =>
Effect.gen(function* () {
const cause = new AzureDevOpsCli.AzureDevOpsCliError({
const cause = new AzureDevOpsCli.AzureDevOpsCommandFailedError({
operation: "execute",
command: "az",
cwd: "/repo",
detail: "Azure DevOps CLI command failed.",
argumentCount: 2,
cause: new Error("raw upstream detail that should remain in the cause"),
});
const provider = yield* makeProvider({
@@ -533,8 +533,8 @@ it.effect("preserves the HTTP client failure without deriving the domain message
}),
);
assert.instanceOf(error, BitbucketApi.BitbucketRequestError);
assert.strictEqual(error.operation, "getPullRequest");
assert.strictEqual(error.detail, "Failed to send the Bitbucket request.");
assert.strictEqual(
error.message,
"Bitbucket API failed in getPullRequest: Failed to send the Bitbucket request.",
@@ -544,6 +544,61 @@ it.effect("preserves the HTTP client failure without deriving the domain message
}).pipe(Effect.provide(layer));
});
it.effect("keeps Bitbucket response bodies out of checkout diagnostics", () => {
const responseBody = '{"error":{"message":"credential=secret-value"}}';
const { layer } = makeLayer({
response: () => new Response(responseBody, { status: 403 }),
});
return Effect.gen(function* () {
const bitbucket = yield* BitbucketApi.BitbucketApi;
const error = yield* bitbucket
.checkoutPullRequest({ cwd: "/repo", reference: "42" })
.pipe(Effect.flip);
assert.instanceOf(error, BitbucketApi.BitbucketResponseError);
assert.strictEqual(error.operation, "getPullRequest");
assert.strictEqual(error.status, 403);
assert.strictEqual(error.responseBodyLength, responseBody.length);
assert.notProperty(error, "responseBody");
assert.strictEqual(
error.message,
"Bitbucket API failed in getPullRequest: Bitbucket returned HTTP 403.",
);
assert.notInclude(error.message, "secret-value");
}).pipe(Effect.provide(layer));
});
it.effect("preserves Bitbucket response body read failures as their immediate cause", () => {
const cause = new Error("response stream failed");
const { layer } = makeLayer({
response: () =>
new Response(
new ReadableStream<Uint8Array>({
start: (controller) => controller.error(cause),
}),
{ status: 502 },
),
});
return Effect.gen(function* () {
const bitbucket = yield* BitbucketApi.BitbucketApi;
const error = yield* bitbucket
.getPullRequest({ cwd: "/repo", reference: "42" })
.pipe(Effect.flip);
assert.instanceOf(error, BitbucketApi.BitbucketResponseBodyReadError);
assert.strictEqual(error.operation, "getPullRequest");
assert.strictEqual(error.status, 502);
assert.instanceOf(error.cause, HttpClientError.HttpClientError);
assert.strictEqual(error.cause.cause, cause);
assert.strictEqual(
error.message,
"Bitbucket API failed in getPullRequest: Bitbucket returned HTTP 502.",
);
}).pipe(Effect.provide(layer));
});
it.effect("checks out same-repository pull requests with the existing Bitbucket remote", () => {
const { git, layer } = makeLayer({
response: () =>
@@ -630,8 +685,9 @@ it.effect("preserves Git checkout failures without deriving the domain message f
}),
);
assert.strictEqual(error.operation, "checkoutPullRequest");
assert.strictEqual(error.detail, "Failed to check out the Bitbucket pull request.");
assert.instanceOf(error, BitbucketApi.BitbucketCheckoutError);
assert.strictEqual(error.cwd, "/repo");
assert.strictEqual(error.reference, "42");
assert.strictEqual(
error.message,
"Bitbucket API failed in checkoutPullRequest: Failed to check out the Bitbucket pull request.",
+178 -43
View File
@@ -6,6 +6,7 @@ import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import {
NonNegativeInt,
TrimmedNonEmptyString,
type SourceControlProviderAuth,
type SourceControlRepositoryCloneUrls,
@@ -36,20 +37,156 @@ const BitbucketApiEnvConfig = Config.all({
apiToken: Config.string("T3CODE_BITBUCKET_API_TOKEN").pipe(Config.option),
});
export class BitbucketApiError extends Schema.TaggedErrorClass<BitbucketApiError>()(
"BitbucketApiError",
const BitbucketApiOperation = Schema.Literals([
"resolveRepository",
"getRepository",
"getBranchingModel",
"getPullRequest",
"listPullRequests",
"createRepository",
"createPullRequest",
"probeAuth",
"checkoutPullRequest",
]);
type BitbucketApiOperation = typeof BitbucketApiOperation.Type;
export class BitbucketRepositoryLocatorError extends Schema.TaggedErrorClass<BitbucketRepositoryLocatorError>()(
"BitbucketRepositoryLocatorError",
{
operation: Schema.String,
detail: Schema.String,
status: Schema.optional(Schema.Number),
cause: Schema.optional(Schema.Defect()),
repository: Schema.String,
},
) {
override get message(): string {
return `Bitbucket API failed in ${this.operation}: ${this.detail}`;
return "Bitbucket API failed in createRepository: Bitbucket repositories must be specified as workspace/repository.";
}
}
const isBitbucketApiError = Schema.is(BitbucketApiError);
export class BitbucketRequestError extends Schema.TaggedErrorClass<BitbucketRequestError>()(
"BitbucketRequestError",
{
operation: BitbucketApiOperation,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Bitbucket API failed in ${this.operation}: Failed to send the Bitbucket request.`;
}
}
export class BitbucketResponseError extends Schema.TaggedErrorClass<BitbucketResponseError>()(
"BitbucketResponseError",
{
operation: BitbucketApiOperation,
status: Schema.Int,
responseBodyLength: NonNegativeInt,
},
) {
override get message(): string {
return `Bitbucket API failed in ${this.operation}: Bitbucket returned HTTP ${this.status}.`;
}
}
export class BitbucketResponseBodyReadError extends Schema.TaggedErrorClass<BitbucketResponseBodyReadError>()(
"BitbucketResponseBodyReadError",
{
operation: BitbucketApiOperation,
status: Schema.Int,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Bitbucket API failed in ${this.operation}: Bitbucket returned HTTP ${this.status}.`;
}
}
export class BitbucketResponseDecodeError extends Schema.TaggedErrorClass<BitbucketResponseDecodeError>()(
"BitbucketResponseDecodeError",
{
operation: BitbucketApiOperation,
status: Schema.Int,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Bitbucket API failed in ${this.operation}: Bitbucket returned invalid JSON for the requested resource.`;
}
}
export class BitbucketRepositoryVcsResolveError extends Schema.TaggedErrorClass<BitbucketRepositoryVcsResolveError>()(
"BitbucketRepositoryVcsResolveError",
{
cwd: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Bitbucket API failed in resolveRepository: Failed to resolve VCS repository for ${this.cwd}.`;
}
}
export class BitbucketRepositoryRemotesListError extends Schema.TaggedErrorClass<BitbucketRepositoryRemotesListError>()(
"BitbucketRepositoryRemotesListError",
{
cwd: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Bitbucket API failed in resolveRepository: Failed to list remotes for ${this.cwd}.`;
}
}
export class BitbucketRepositoryRemoteNotFoundError extends Schema.TaggedErrorClass<BitbucketRepositoryRemoteNotFoundError>()(
"BitbucketRepositoryRemoteNotFoundError",
{
cwd: Schema.String,
},
) {
override get message(): string {
return `Bitbucket API failed in resolveRepository: No Bitbucket repository remote was detected for ${this.cwd}.`;
}
}
export class BitbucketPullRequestBodyReadError extends Schema.TaggedErrorClass<BitbucketPullRequestBodyReadError>()(
"BitbucketPullRequestBodyReadError",
{
cwd: Schema.String,
bodyFile: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Bitbucket API failed in createPullRequest: Failed to read pull request body file ${this.bodyFile}.`;
}
}
export class BitbucketCheckoutError extends Schema.TaggedErrorClass<BitbucketCheckoutError>()(
"BitbucketCheckoutError",
{
cwd: Schema.String,
reference: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return "Bitbucket API failed in checkoutPullRequest: Failed to check out the Bitbucket pull request.";
}
}
export const BitbucketApiError = Schema.Union([
BitbucketRepositoryLocatorError,
BitbucketRequestError,
BitbucketResponseError,
BitbucketResponseBodyReadError,
BitbucketResponseDecodeError,
BitbucketRepositoryVcsResolveError,
BitbucketRepositoryRemotesListError,
BitbucketRepositoryRemoteNotFoundError,
BitbucketPullRequestBodyReadError,
BitbucketCheckoutError,
]);
export type BitbucketApiError = typeof BitbucketApiError.Type;
export const isBitbucketApiError = Schema.is(BitbucketApiError);
const RawBitbucketRepositorySchema = Schema.Struct({
full_name: TrimmedNonEmptyString,
@@ -209,16 +346,14 @@ function parseBitbucketRepositorySlug(value: string): BitbucketRepositoryLocator
}
function requireRepositoryLocator(
operation: string,
repository: string,
): Effect.Effect<BitbucketRepositoryLocator, BitbucketApiError> {
const locator = parseBitbucketRepositorySlug(repository);
return locator
? Effect.succeed(locator)
: Effect.fail(
new BitbucketApiError({
operation,
detail: "Bitbucket repositories must be specified as workspace/repository.",
new BitbucketRepositoryLocatorError({
repository,
}),
);
}
@@ -339,20 +474,24 @@ function authFromConfig(
}
function responseError(
operation: string,
operation: BitbucketApiOperation,
response: HttpClientResponse.HttpClientResponse,
): Effect.Effect<never, BitbucketApiError> {
return response.text.pipe(
Effect.orElseSucceed(() => ""),
Effect.flatMap((body) =>
Effect.fail(
new BitbucketApiError({
Effect.mapError(
(cause) =>
new BitbucketResponseBodyReadError({
operation,
status: response.status,
detail:
body.trim().length > 0
? `Bitbucket returned HTTP ${response.status}: ${body.trim()}`
: `Bitbucket returned HTTP ${response.status}.`,
cause,
}),
),
Effect.flatMap((body) =>
Effect.fail(
new BitbucketResponseError({
operation,
status: response.status,
responseBodyLength: body.length,
}),
),
),
@@ -379,7 +518,7 @@ export const make = Effect.gen(function* () {
};
const decodeResponse = <S extends Schema.Top>(
operation: string,
operation: BitbucketApiOperation,
schema: S,
response: HttpClientResponse.HttpClientResponse,
): Effect.Effect<S["Type"], BitbucketApiError, S["DecodingServices"]> =>
@@ -388,9 +527,9 @@ export const make = Effect.gen(function* () {
HttpClientResponse.schemaBodyJson(schema)(success).pipe(
Effect.mapError(
(cause) =>
new BitbucketApiError({
new BitbucketResponseDecodeError({
operation,
detail: "Bitbucket returned invalid JSON for the requested resource.",
status: success.status,
cause,
}),
),
@@ -399,16 +538,15 @@ export const make = Effect.gen(function* () {
})(response);
const executeJson = <S extends Schema.Top>(
operation: string,
operation: BitbucketApiOperation,
request: HttpClientRequest.HttpClientRequest,
schema: S,
): Effect.Effect<S["Type"], BitbucketApiError, S["DecodingServices"]> =>
httpClient.execute(withAuth(request.pipe(HttpClientRequest.acceptJson))).pipe(
Effect.mapError(
(cause) =>
new BitbucketApiError({
new BitbucketRequestError({
operation,
detail: "Failed to send the Bitbucket request.",
cause,
}),
),
@@ -433,9 +571,8 @@ export const make = Effect.gen(function* () {
const handle = yield* vcsRegistry.resolve({ cwd: input.cwd }).pipe(
Effect.mapError(
(cause) =>
new BitbucketApiError({
operation: "resolveRepository",
detail: `Failed to resolve VCS repository for ${input.cwd}.`,
new BitbucketRepositoryVcsResolveError({
cwd: input.cwd,
cause,
}),
),
@@ -443,9 +580,8 @@ export const make = Effect.gen(function* () {
const remotes = yield* handle.driver.listRemotes(input.cwd).pipe(
Effect.mapError(
(cause) =>
new BitbucketApiError({
operation: "resolveRepository",
detail: `Failed to list remotes for ${input.cwd}.`,
new BitbucketRepositoryRemotesListError({
cwd: input.cwd,
cause,
}),
),
@@ -457,9 +593,8 @@ export const make = Effect.gen(function* () {
if (parsed) return parsed;
}
return yield* new BitbucketApiError({
operation: "resolveRepository",
detail: `No Bitbucket repository remote was detected for ${input.cwd}.`,
return yield* new BitbucketRepositoryRemoteNotFoundError({
cwd: input.cwd,
});
});
@@ -600,7 +735,7 @@ export const make = Effect.gen(function* () {
getRepositoryCloneUrls: (input) =>
getRepository(input).pipe(Effect.map(normalizeRepositoryCloneUrls)),
createRepository: (input) =>
requireRepositoryLocator("createRepository", input.repository).pipe(
requireRepositoryLocator(input.repository).pipe(
Effect.flatMap((repository) =>
executeJson(
"createRepository",
@@ -625,9 +760,9 @@ export const make = Effect.gen(function* () {
const description = yield* fileSystem.readFileString(input.bodyFile).pipe(
Effect.mapError(
(cause) =>
new BitbucketApiError({
operation: "createPullRequest",
detail: `Failed to read pull request body file ${input.bodyFile}.`,
new BitbucketPullRequestBodyReadError({
cwd: input.cwd,
bodyFile: input.bodyFile,
cause,
}),
),
@@ -743,9 +878,9 @@ export const make = Effect.gen(function* () {
Effect.mapError((cause) =>
isBitbucketApiError(cause)
? cause
: new BitbucketApiError({
operation: "checkoutPullRequest",
detail: "Failed to check out the Bitbucket pull request.",
: new BitbucketCheckoutError({
cwd: input.cwd,
reference: input.reference,
cause,
}),
),
Loaded 100 of 241 files, more files were not shown because too many files have changed in this diff. Show more