Compare commits

...
Author SHA1 Message Date
Julius Marmingeandcodex c4945aad27 Use structural Git status semantics
Co-authored-by: codex <[email protected]>
2026-06-20 19:21:50 -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
20 changed files with 1090 additions and 234 deletions

No files matched your search

+49 -44
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) =>
@@ -657,6 +638,7 @@ function makeManager(input?: {
ghScenario?: FakeGhScenario;
textGeneration?: Partial<FakeGitTextGeneration>;
setupScriptRunner?: ProjectSetupScriptRunner.ProjectSetupScriptRunner["Service"];
vcsDriverLayer?: Layer.Layer<GitVcsDriver.GitVcsDriver>;
}) {
const { service: gitHubCli, ghCalls } = createGitHubCliWithFakeGh(input?.ghScenario);
const textGeneration = createTextGeneration(input?.textGeneration);
@@ -666,11 +648,13 @@ function makeManager(input?: {
const serverSettingsLayer = ServerSettings.ServerSettingsService.layerTest();
const vcsDriverLayer = GitVcsDriver.layer.pipe(
Layer.provideMerge(VcsProcess.layer),
Layer.provideMerge(NodeServices.layer),
Layer.provideMerge(serverConfigLayer),
);
const vcsDriverLayer =
input?.vcsDriverLayer ??
GitVcsDriver.layer.pipe(
Layer.provideMerge(VcsProcess.layer),
Layer.provideMerge(NodeServices.layer),
Layer.provideMerge(serverConfigLayer),
);
const sourceControlRegistryLayer = Layer.effect(
SourceControlProviderRegistry.SourceControlProviderRegistry,
GitHubSourceControlProvider.make.pipe(
@@ -953,6 +937,30 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);
it.effect("does not classify Git command failures from message text", () =>
Effect.gen(function* () {
const cwd = "/workspace";
const cause = new Error("spawn failed");
const commandError = new GitCommandError({
operation: "GitVcsDriver.statusDetails.status",
command: "git",
cwd,
detail: "not a git repository",
cause,
});
const { manager } = yield* makeManager({
vcsDriverLayer: Layer.mock(GitVcsDriver.GitVcsDriver)({
statusDetailsLocal: () => Effect.fail(commandError),
}),
});
const error = yield* manager.localStatus({ cwd }).pipe(Effect.flip);
expect(error).toBe(commandError);
expect(error.cause).toBe(cause);
}),
);
it.effect("status briefly caches repeated lookups for the same cwd", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
@@ -1341,11 +1349,10 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
const { manager } = yield* makeManager({
ghScenario: {
failWith: new GitHubCli.GitHubCliError({
operation: "execute",
failWith: new GitHubCli.GitHubCliUnavailableError({
command: "gh",
cwd: repoDir,
detail: "GitHub CLI (`gh`) is required but not available on PATH.",
cause: new Error("gh is not available on PATH"),
}),
},
});
@@ -2483,11 +2490,10 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
const { manager } = yield* makeManager({
ghScenario: {
failWith: new GitHubCli.GitHubCliError({
operation: "execute",
failWith: new GitHubCli.GitHubCliUnavailableError({
command: "gh",
cwd: repoDir,
detail: "GitHub CLI (`gh`) is required but not available on PATH.",
cause: new Error("gh is not available on PATH"),
}),
},
});
@@ -2514,11 +2520,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"),
}),
},
});
+2 -26
View File
@@ -15,7 +15,6 @@ import * as Ref from "effect/Ref";
import {
GitActionProgressEvent,
GitActionProgressPhase,
GitCommandError,
GitPreparePullRequestThreadInput,
GitPreparePullRequestThreadResult,
GitPullRequestRefInput,
@@ -99,10 +98,6 @@ type StripProgressContext<T> = T extends any ? Omit<T, "actionId" | "cwd" | "act
type GitActionProgressPayload = StripProgressContext<GitActionProgressEvent>;
type GitActionProgressEmitter = (event: GitActionProgressPayload) => Effect.Effect<void, never>;
function isNotGitRepositoryError(error: GitCommandError): boolean {
return error.message.toLowerCase().includes("not a git repository");
}
interface OpenPrInfo {
number: number;
title: string;
@@ -727,25 +722,8 @@ export const make = Effect.gen(function* () {
const canonicalizeExistingPath = (value: string) =>
fileSystem.realPath(value).pipe(Effect.orElseSucceed(() => value));
const normalizeStatusCacheKey = canonicalizeExistingPath;
const nonRepositoryStatusDetails = {
isRepo: false,
hasOriginRemote: false,
isDefaultBranch: false,
branch: null,
upstreamRef: null,
hasWorkingTreeChanges: false,
workingTree: { files: [], insertions: 0, deletions: 0 },
hasUpstream: false,
aheadCount: 0,
behindCount: 0,
aheadOfDefaultCount: 0,
} satisfies GitVcsDriver.GitStatusDetails;
const readLocalStatus = Effect.fn("readLocalStatus")(function* (cwd: string) {
const details = yield* gitCore
.statusDetailsLocal(cwd)
.pipe(
Effect.catchIf(isNotGitRepositoryError, () => Effect.succeed(nonRepositoryStatusDetails)),
);
const details = yield* gitCore.statusDetailsLocal(cwd);
const hostingProvider = details.isRepo
? yield* resolveHostingProvider(cwd, details.branch)
: null;
@@ -772,9 +750,7 @@ export const make = Effect.gen(function* () {
cwd: string,
options?: GitVcsDriver.GitRemoteStatusOptions,
) {
const details = yield* gitCore
.statusDetailsRemote(cwd, options)
.pipe(Effect.catchIf(isNotGitRepositoryError, () => Effect.succeed(null)));
const details = yield* gitCore.statusDetailsRemote(cwd, options);
if (details === null || !details.isRepo) {
return null;
}
@@ -1,8 +1,9 @@
import { assert, it, afterEach, describe, expect, vi } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as PlatformError from "effect/PlatformError";
import { ChildProcessSpawner } from "effect/unstable/process";
import { VcsProcessExitError } from "@t3tools/contracts";
import { VcsProcessExitError, VcsProcessSpawnError } from "@t3tools/contracts";
import * as VcsProcess from "../vcs/VcsProcess.ts";
import * as GitHubCli from "./GitHubCli.ts";
@@ -30,6 +31,27 @@ afterEach(() => {
});
describe("GitHubCli.layer", () => {
it("does not classify a missing cwd as an unavailable gh executable", () => {
const context = { command: "gh", cwd: "/repo" } as const;
const missingCwd = new VcsProcessSpawnError({
operation: "GitHubCli.execute",
command: "gh",
cwd: context.cwd,
cause: PlatformError.systemError({
_tag: "NotFound",
module: "FileSystem",
method: "access",
pathOrDescriptor: context.cwd,
}),
});
const commandFailure = GitHubCli.fromVcsError(context, missingCwd);
assert.equal(commandFailure._tag, "GitHubCliCommandError");
assert.strictEqual(commandFailure.cause, missingCwd);
assert.notProperty(commandFailure, "operation");
});
it.effect("parses pull request view output", () =>
Effect.gen(function* () {
mockRun.mockReturnValueOnce(
@@ -274,6 +296,7 @@ describe("GitHubCli.layer", () => {
command: "gh pr view",
cwd: "/repo",
exitCode: 1,
failureKind: "not-found",
detail:
"GraphQL: Could not resolve to a PullRequest with the number of 4888. (repository.pullRequest)",
});
@@ -288,6 +311,7 @@ describe("GitHubCli.layer", () => {
.pipe(Effect.flip);
assert.equal(error.message.includes("Pull request not found"), true);
assert.strictEqual(error._tag, "GitHubPullRequestNotFoundError");
assert.strictEqual(error.command, "gh");
assert.strictEqual(error.cwd, "/repo");
assert.strictEqual(error.cause, cause);
+168 -108
View File
@@ -1,6 +1,7 @@
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as PlatformError from "effect/PlatformError";
import * as Result from "effect/Result";
import * as Schema from "effect/Schema";
@@ -18,69 +19,165 @@ import {
const DEFAULT_TIMEOUT_MS = 30_000;
export class GitHubCliError extends Schema.TaggedErrorClass<GitHubCliError>()("GitHubCliError", {
operation: Schema.String,
command: Schema.String,
const gitHubCliFailureFields = {
command: Schema.Literal("gh"),
cwd: Schema.String,
detail: Schema.String,
cause: Schema.optional(Schema.Defect()),
}) {
cause: Schema.Defect(),
} as const;
export class GitHubCliUnavailableError extends Schema.TaggedErrorClass<GitHubCliUnavailableError>()(
"GitHubCliUnavailableError",
gitHubCliFailureFields,
) {
get detail(): string {
return "GitHub CLI (`gh`) is required but not available on PATH.";
}
override get message(): string {
return `GitHub CLI failed in ${this.operation}: ${this.detail}`;
return `GitHub CLI failed in execute: ${this.detail}`;
}
}
export class GitHubCliAuthenticationError extends Schema.TaggedErrorClass<GitHubCliAuthenticationError>()(
"GitHubCliAuthenticationError",
gitHubCliFailureFields,
) {
get detail(): string {
return "GitHub CLI is not authenticated. Run `gh auth login` and retry.";
}
static fromVcsError(
context: {
readonly operation: "execute";
readonly command: "gh";
readonly cwd: string;
},
error: VcsError | unknown,
): GitHubCliError {
const lower = errorText(error).toLowerCase();
if (lower.includes("command not found: gh") || lower.includes("enoent")) {
return new GitHubCliError({
...context,
detail: "GitHub CLI (`gh`) is required but not available on PATH.",
cause: error,
});
}
if (
lower.includes("authentication failed") ||
lower.includes("not logged in") ||
lower.includes("gh auth login") ||
lower.includes("no oauth token")
) {
return new GitHubCliError({
...context,
detail: "GitHub CLI is not authenticated. Run `gh auth login` and retry.",
cause: error,
});
}
if (
lower.includes("could not resolve to a pullrequest") ||
lower.includes("repository.pullrequest") ||
lower.includes("no pull requests found for branch") ||
lower.includes("pull request not found")
) {
return new GitHubCliError({
...context,
detail: "Pull request not found. Check the PR number or URL and try again.",
cause: error,
});
}
return new GitHubCliError({
...context,
detail: "GitHub CLI command failed.",
cause: error,
});
override get message(): string {
return `GitHub CLI failed in execute: ${this.detail}`;
}
}
export class GitHubPullRequestNotFoundError extends Schema.TaggedErrorClass<GitHubPullRequestNotFoundError>()(
"GitHubPullRequestNotFoundError",
gitHubCliFailureFields,
) {
get detail(): string {
return "Pull request not found. Check the PR number or URL and try again.";
}
override get message(): string {
return `GitHub CLI failed in execute: ${this.detail}`;
}
}
export class GitHubCliCommandError extends Schema.TaggedErrorClass<GitHubCliCommandError>()(
"GitHubCliCommandError",
gitHubCliFailureFields,
) {
get detail(): string {
return "GitHub CLI command failed.";
}
override get message(): string {
return `GitHub CLI failed in execute: ${this.detail}`;
}
}
const gitHubCliDecodeFields = {
command: Schema.Literal("gh"),
cwd: Schema.String,
cause: Schema.Defect(),
} as const;
export class GitHubPullRequestListDecodeError extends Schema.TaggedErrorClass<GitHubPullRequestListDecodeError>()(
"GitHubPullRequestListDecodeError",
gitHubCliDecodeFields,
) {
get detail(): string {
return "GitHub CLI returned invalid PR list JSON.";
}
override get message(): string {
return `GitHub CLI failed in listOpenPullRequests: ${this.detail}`;
}
}
export class GitHubChangeRequestListDecodeError extends Schema.TaggedErrorClass<GitHubChangeRequestListDecodeError>()(
"GitHubChangeRequestListDecodeError",
gitHubCliDecodeFields,
) {
get detail(): string {
return "GitHub CLI returned invalid change request JSON.";
}
override get message(): string {
return `GitHub CLI failed in listChangeRequests: ${this.detail}`;
}
}
export class GitHubPullRequestDecodeError extends Schema.TaggedErrorClass<GitHubPullRequestDecodeError>()(
"GitHubPullRequestDecodeError",
gitHubCliDecodeFields,
) {
get detail(): string {
return "GitHub CLI returned invalid pull request JSON.";
}
override get message(): string {
return `GitHub CLI failed in getPullRequest: ${this.detail}`;
}
}
export class GitHubRepositoryDecodeError extends Schema.TaggedErrorClass<GitHubRepositoryDecodeError>()(
"GitHubRepositoryDecodeError",
gitHubCliDecodeFields,
) {
get detail(): string {
return "GitHub CLI returned invalid repository JSON.";
}
override get message(): string {
return `GitHub CLI failed in getRepositoryCloneUrls: ${this.detail}`;
}
}
export const GitHubCliError = Schema.Union([
GitHubCliUnavailableError,
GitHubCliAuthenticationError,
GitHubPullRequestNotFoundError,
GitHubCliCommandError,
GitHubPullRequestListDecodeError,
GitHubChangeRequestListDecodeError,
GitHubPullRequestDecodeError,
GitHubRepositoryDecodeError,
]);
export type GitHubCliError = typeof GitHubCliError.Type;
export const isGitHubCliError = Schema.is(GitHubCliError);
export function fromVcsError(
context: {
readonly command: "gh";
readonly cwd: string;
},
error: VcsError,
): GitHubCliError {
if (
error._tag === "VcsProcessSpawnError" &&
error.cause instanceof PlatformError.PlatformError &&
error.cause.reason._tag === "NotFound" &&
error.cause.reason.module === "ChildProcess" &&
error.cause.reason.method === "spawn"
) {
return new GitHubCliUnavailableError({ ...context, cause: error });
}
if (error._tag === "VcsProcessExitError") {
if (error.failureKind === "authentication") {
return new GitHubCliAuthenticationError({ ...context, cause: error });
}
if (error.failureKind === "not-found") {
return new GitHubPullRequestNotFoundError({ ...context, cause: error });
}
}
return new GitHubCliCommandError({ ...context, cause: error });
}
export interface GitHubPullRequestSummary {
readonly number: number;
readonly title: string;
@@ -150,22 +247,14 @@ export class GitHubCli extends Context.Service<
}
>()("t3/sourceControl/GitHubCli") {}
function errorText(error: VcsError | unknown): string {
if (typeof error === "object" && error !== null) {
const tag = "_tag" in error && typeof error._tag === "string" ? error._tag : "";
const detail = "detail" in error && typeof error.detail === "string" ? error.detail : "";
const message = "message" in error && typeof error.message === "string" ? error.message : "";
return [tag, detail, message].filter(Boolean).join("\n");
}
return String(error);
}
const RawGitHubRepositoryCloneUrlsSchema = Schema.Struct({
nameWithOwner: TrimmedNonEmptyString,
url: TrimmedNonEmptyString,
sshUrl: TrimmedNonEmptyString,
});
const decodeRawGitHubRepositoryCloneUrls = Schema.decodeEffect(
Schema.fromJsonString(RawGitHubRepositoryCloneUrlsSchema),
);
function normalizeRepositoryCloneUrls(
raw: Schema.Schema.Type<typeof RawGitHubRepositoryCloneUrlsSchema>,
@@ -214,27 +303,6 @@ function deriveRepositoryCloneUrlsFromCreateOutput(
};
}
function decodeGitHubJson<S extends Schema.Top>(
raw: string,
schema: S,
operation: "listOpenPullRequests" | "getPullRequest" | "getRepositoryCloneUrls",
invalidDetail: string,
cwd: string,
): Effect.Effect<S["Type"], GitHubCliError, S["DecodingServices"]> {
return Schema.decodeEffect(Schema.fromJsonString(schema))(raw).pipe(
Effect.mapError(
(error) =>
new GitHubCliError({
operation,
command: "gh",
cwd,
detail: invalidDetail,
cause: error,
}),
),
);
}
export const make = Effect.gen(function* () {
const process = yield* VcsProcess.VcsProcess;
@@ -247,14 +315,7 @@ export const make = Effect.gen(function* () {
cwd: input.cwd,
timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
})
.pipe(
Effect.mapError((error) =>
GitHubCliError.fromVcsError(
{ operation: "execute", command: "gh", cwd: input.cwd },
error,
),
),
);
.pipe(Effect.mapError((error) => fromVcsError({ command: "gh", cwd: input.cwd }, error)));
return GitHubCli.of({
execute,
@@ -282,11 +343,9 @@ export const make = Effect.gen(function* () {
Effect.flatMap((decoded) => {
if (!Result.isSuccess(decoded)) {
return Effect.fail(
new GitHubCliError({
operation: "listOpenPullRequests",
new GitHubPullRequestListDecodeError({
command: "gh",
cwd: input.cwd,
detail: "GitHub CLI returned invalid PR list JSON.",
cause: decoded.failure,
}),
);
@@ -316,11 +375,9 @@ export const make = Effect.gen(function* () {
Effect.flatMap((decoded) => {
if (!Result.isSuccess(decoded)) {
return Effect.fail(
new GitHubCliError({
operation: "getPullRequest",
new GitHubPullRequestDecodeError({
command: "gh",
cwd: input.cwd,
detail: "GitHub CLI returned invalid pull request JSON.",
cause: decoded.failure,
}),
);
@@ -340,12 +397,15 @@ export const make = Effect.gen(function* () {
}).pipe(
Effect.map((result) => result.stdout.trim()),
Effect.flatMap((raw) =>
decodeGitHubJson(
raw,
RawGitHubRepositoryCloneUrlsSchema,
"getRepositoryCloneUrls",
"GitHub CLI returned invalid repository JSON.",
input.cwd,
decodeRawGitHubRepositoryCloneUrls(raw).pipe(
Effect.mapError(
(cause) =>
new GitHubRepositoryDecodeError({
command: "gh",
cwd: input.cwd,
cause,
}),
),
),
),
Effect.map(normalizeRepositoryCloneUrls),
@@ -70,11 +70,9 @@ it.effect("maps GitHub PR summaries into provider-neutral change requests", () =
it.effect("adds safe request context while retaining GitHub CLI causes", () =>
Effect.gen(function* () {
const cause = new GitHubCli.GitHubCliError({
operation: "execute",
const cause = new GitHubCli.GitHubPullRequestNotFoundError({
command: "gh",
cwd: "/repo",
detail: "Pull request not found. Check the PR number or URL and try again.",
cause: new Error("raw upstream detail that should remain in the cause"),
});
const provider = yield* makeProvider({
@@ -158,23 +158,17 @@ export const make = Effect.gen(function* () {
})),
)
: Effect.fail(
new SourceControlProviderError({
provider: "github",
operation: "listChangeRequests",
new GitHubCli.GitHubChangeRequestListDecodeError({
command: "gh",
cwd: input.cwd,
reference: SourceControlProvider.transportSafeSourceControlErrorValue(
input.headSelector,
),
detail: "GitHub CLI returned invalid change request JSON.",
cause: decoded.failure,
}),
),
),
);
}),
Effect.catchTags({
GitHubCliError: (error) =>
Effect.mapError(
(error) =>
new SourceControlProviderError({
provider: "github",
operation: "listChangeRequests",
@@ -186,7 +180,7 @@ export const make = Effect.gen(function* () {
detail: error.detail,
cause: error,
}),
}),
),
);
};
+193
View File
@@ -0,0 +1,193 @@
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
function createStorage(overrides: Partial<Storage> = {}): Storage {
const store = new Map<string, string>();
return {
clear: () => store.clear(),
getItem: (key) => store.get(key) ?? null,
key: (index) => [...store.keys()][index] ?? null,
get length() {
return store.size;
},
removeItem: (key) => {
store.delete(key);
},
setItem: (key, value) => {
store.set(key, value);
},
...overrides,
};
}
afterEach(() => {
vi.doUnmock("react");
vi.resetModules();
vi.restoreAllMocks();
vi.unstubAllGlobals();
});
describe("theme failure handling", () => {
it("preserves exact storage causes and operation context", async () => {
const readCause = new Error("storage read blocked");
const writeCause = new Error("storage quota exceeded");
vi.stubGlobal("window", {
localStorage: createStorage({
getItem: () => {
throw readCause;
},
setItem: () => {
throw writeCause;
},
}),
});
const { readThemePreference, ThemeStorageError, writeThemePreference } =
await import("./useTheme");
try {
readThemePreference();
expect.unreachable("expected the theme read to fail");
} catch (error) {
expect(error).toBeInstanceOf(ThemeStorageError);
expect(error).toMatchObject({
operation: "read",
storageKey: "t3code:theme",
cause: readCause,
});
}
try {
writeThemePreference("dark");
expect.unreachable("expected the theme write to fail");
} catch (error) {
expect(error).toBeInstanceOf(ThemeStorageError);
expect(error).toMatchObject({
operation: "write",
storageKey: "t3code:theme",
theme: "dark",
cause: writeCause,
});
}
});
it("falls back during initial theme application and logs only safe attributes", async () => {
const cause = new Error("private browsing storage failure");
const errorLog = vi.spyOn(console, "error").mockImplementation(() => {});
vi.stubGlobal("window", {
localStorage: createStorage({
getItem: () => {
throw cause;
},
}),
matchMedia: () => ({ matches: false }),
});
vi.stubGlobal("document", {
documentElement: {
classList: { toggle: vi.fn() },
},
});
await expect(import("./useTheme")).resolves.toBeDefined();
expect(errorLog).toHaveBeenCalledWith(
"Failed to read theme preference for t3code:theme.",
expect.objectContaining({
operation: "read",
storageKey: "t3code:theme",
errorTag: "ThemeStorageError",
}),
);
const attributes = errorLog.mock.calls[0]?.[1];
expect(attributes).not.toHaveProperty("cause");
expect(JSON.stringify(attributes)).not.toContain(cause.message);
});
it("retries a failed storage read only after a relevant storage event", async () => {
const cause = new Error("persistent storage failure");
const getItem = vi.fn(() => {
throw cause;
});
const errorLog = vi.spyOn(console, "error").mockImplementation(() => {});
let readSnapshot: (() => unknown) | undefined;
let subscribeToTheme: ((listener: () => void) => () => void) | undefined;
let storageHandler: ((event: StorageEvent) => void) | undefined;
vi.doMock("react", () => ({
useCallback: <A>(callback: A) => callback,
useEffect: () => undefined,
useSyncExternalStore: (
subscribe: (listener: () => void) => () => void,
getSnapshot: () => unknown,
) => {
subscribeToTheme = subscribe;
readSnapshot = getSnapshot;
return getSnapshot();
},
}));
vi.stubGlobal("window", {
addEventListener: (type: string, listener: (event: StorageEvent) => void) => {
if (type === "storage") storageHandler = listener;
},
localStorage: createStorage({ getItem }),
matchMedia: () => ({
matches: false,
addEventListener: () => undefined,
removeEventListener: () => undefined,
}),
removeEventListener: () => undefined,
});
const { useTheme } = await import("./useTheme");
useTheme();
readSnapshot?.();
readSnapshot?.();
expect(getItem).toHaveBeenCalledTimes(1);
expect(errorLog).toHaveBeenCalledTimes(1);
const unsubscribe = subscribeToTheme?.(() => undefined);
storageHandler?.({ key: "t3code:theme" } as StorageEvent);
readSnapshot?.();
expect(getItem).toHaveBeenCalledTimes(2);
expect(errorLog).toHaveBeenCalledTimes(2);
unsubscribe?.();
});
it("preserves desktop sync causes and retries after a failed cosmetic sync", async () => {
const cause = new Error("desktop IPC unavailable");
const errorLog = vi.spyOn(console, "error").mockImplementation(() => {});
const setTheme = vi.fn().mockRejectedValue(cause);
vi.stubGlobal("window", { desktopBridge: { setTheme } });
const { DesktopThemeSyncError, syncDesktopTheme, syncDesktopThemePreference } =
await import("./useTheme");
const error = await syncDesktopThemePreference({ setTheme }, "dark").then(
() => undefined,
(failure: unknown) => failure,
);
expect(error).toBeInstanceOf(DesktopThemeSyncError);
expect(error).toMatchObject({ theme: "dark", cause });
setTheme.mockClear();
syncDesktopTheme("dark");
await Promise.resolve();
await Promise.resolve();
syncDesktopTheme("dark");
await Promise.resolve();
await Promise.resolve();
expect(setTheme).toHaveBeenCalledTimes(2);
expect(errorLog).toHaveBeenCalledWith(
"Failed to sync the dark theme to the desktop shell.",
expect.objectContaining({
theme: "dark",
errorTag: "DesktopThemeSyncError",
}),
);
for (const [, attributes] of errorLog.mock.calls) {
expect(attributes).not.toHaveProperty("cause");
expect(JSON.stringify(attributes)).not.toContain(cause.message);
}
});
});
+132 -14
View File
@@ -1,11 +1,17 @@
import type { DesktopBridge } from "@t3tools/contracts";
import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors";
import * as Schema from "effect/Schema";
import { useCallback, useEffect, useSyncExternalStore } from "react";
type Theme = "light" | "dark" | "system";
const ThemePreference = Schema.Literals(["light", "dark", "system"]);
type Theme = typeof ThemePreference.Type;
type ThemeSnapshot = {
theme: Theme;
systemDark: boolean;
};
type DesktopThemeBridge = Pick<DesktopBridge, "setTheme">;
const STORAGE_KEY = "t3code:theme";
const MEDIA_QUERY = "(prefers-color-scheme: dark)";
const DEFAULT_THEME_SNAPSHOT: ThemeSnapshot = {
@@ -15,19 +21,46 @@ const DEFAULT_THEME_SNAPSHOT: ThemeSnapshot = {
const THEME_COLOR_META_NAME = "theme-color";
const DYNAMIC_THEME_COLOR_SELECTOR = `meta[name="${THEME_COLOR_META_NAME}"][data-dynamic-theme-color="true"]`;
export class ThemeStorageError extends Schema.TaggedErrorClass<ThemeStorageError>()(
"ThemeStorageError",
{
operation: Schema.Literals(["read", "write"]),
storageKey: Schema.String,
theme: Schema.optional(ThemePreference),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to ${this.operation} theme preference for ${this.storageKey}.`;
}
}
export const isThemeStorageError = Schema.is(ThemeStorageError);
export class DesktopThemeSyncError extends Schema.TaggedErrorClass<DesktopThemeSyncError>()(
"DesktopThemeSyncError",
{
theme: ThemePreference,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to sync the ${this.theme} theme to the desktop shell.`;
}
}
export const isDesktopThemeSyncError = Schema.is(DesktopThemeSyncError);
let listeners: Array<() => void> = [];
let lastSnapshot: ThemeSnapshot | null = null;
let lastDesktopTheme: Theme | null = null;
let lastAppliedTheme: ThemeSnapshot | null = null;
let themeStorageReadFailure: ThemeStorageError | null = null;
function emitChange() {
for (const listener of listeners) listener();
}
function hasThemeStorage() {
return typeof window !== "undefined" && typeof localStorage !== "undefined";
}
function getSystemDark() {
return (
typeof window !== "undefined" &&
@@ -36,13 +69,61 @@ function getSystemDark() {
);
}
function getStored(): Theme {
if (!hasThemeStorage()) return DEFAULT_THEME_SNAPSHOT.theme;
const raw = localStorage.getItem(STORAGE_KEY);
export function readThemePreference(): Theme {
if (typeof window === "undefined") return DEFAULT_THEME_SNAPSHOT.theme;
let raw: string | null;
try {
raw = window.localStorage.getItem(STORAGE_KEY);
} catch (cause) {
throw new ThemeStorageError({
operation: "read",
storageKey: STORAGE_KEY,
cause,
});
}
if (raw === "light" || raw === "dark" || raw === "system") return raw;
return DEFAULT_THEME_SNAPSHOT.theme;
}
export function writeThemePreference(theme: Theme): void {
if (typeof window === "undefined") return;
try {
window.localStorage.setItem(STORAGE_KEY, theme);
themeStorageReadFailure = null;
} catch (cause) {
throw new ThemeStorageError({
operation: "write",
storageKey: STORAGE_KEY,
theme,
cause,
});
}
}
function getStored(): Theme {
if (themeStorageReadFailure !== null) {
return DEFAULT_THEME_SNAPSHOT.theme;
}
try {
return readThemePreference();
} catch (cause) {
const error = isThemeStorageError(cause)
? cause
: new ThemeStorageError({
operation: "read",
storageKey: STORAGE_KEY,
cause,
});
themeStorageReadFailure = error;
console.error(error.message, {
operation: error.operation,
storageKey: error.storageKey,
...safeErrorLogAttributes(error),
});
return DEFAULT_THEME_SNAPSHOT.theme;
}
}
function ensureThemeColorMetaTag(): HTMLMetaElement {
let element = document.querySelector<HTMLMetaElement>(DYNAMIC_THEME_COLOR_SELECTOR);
if (element) {
@@ -118,7 +199,18 @@ function applyTheme(theme: Theme, suppressTransitions = false) {
}
}
function syncDesktopTheme(theme: Theme) {
export async function syncDesktopThemePreference(
bridge: DesktopThemeBridge,
theme: Theme,
): Promise<void> {
try {
await bridge.setTheme(theme);
} catch (cause) {
throw new DesktopThemeSyncError({ theme, cause });
}
}
export function syncDesktopTheme(theme: Theme) {
if (typeof window === "undefined") return;
const bridge = window.desktopBridge;
if (!bridge || typeof bridge.setTheme !== "function" || lastDesktopTheme === theme) {
@@ -126,7 +218,14 @@ function syncDesktopTheme(theme: Theme) {
}
lastDesktopTheme = theme;
void bridge.setTheme(theme).catch(() => {
void syncDesktopThemePreference(bridge, theme).catch((cause: unknown) => {
const error = isDesktopThemeSyncError(cause)
? cause
: new DesktopThemeSyncError({ theme, cause });
console.error(error.message, {
theme: error.theme,
...safeErrorLogAttributes(error),
});
if (lastDesktopTheme === theme) {
lastDesktopTheme = null;
}
@@ -134,12 +233,12 @@ function syncDesktopTheme(theme: Theme) {
}
// Apply immediately on module load to prevent flash
if (typeof document !== "undefined" && hasThemeStorage()) {
if (typeof document !== "undefined" && typeof window !== "undefined") {
applyTheme(getStored());
}
function getSnapshot(): ThemeSnapshot {
if (!hasThemeStorage()) return DEFAULT_THEME_SNAPSHOT;
if (typeof window === "undefined") return DEFAULT_THEME_SNAPSHOT;
const theme = getStored();
const systemDark = theme === "system" ? getSystemDark() : false;
@@ -170,6 +269,7 @@ function subscribe(listener: () => void): () => void {
// Listen for storage changes from other tabs
const handleStorage = (e: StorageEvent) => {
if (e.key === STORAGE_KEY) {
themeStorageReadFailure = null;
applyTheme(getStored(), true);
emitChange();
}
@@ -191,8 +291,26 @@ export function useTheme() {
theme === "system" ? (snapshot.systemDark ? "dark" : "light") : theme;
const setTheme = useCallback((next: Theme) => {
if (!hasThemeStorage()) return;
localStorage.setItem(STORAGE_KEY, next);
if (typeof window === "undefined") return;
try {
writeThemePreference(next);
} catch (cause) {
const error = isThemeStorageError(cause)
? cause
: new ThemeStorageError({
operation: "write",
storageKey: STORAGE_KEY,
theme: next,
cause,
});
console.error(error.message, {
operation: error.operation,
storageKey: error.storageKey,
theme: next,
...safeErrorLogAttributes(error),
});
return;
}
applyTheme(next, true);
emitChange();
}, []);
@@ -0,0 +1,45 @@
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as PlatformError from "effect/PlatformError";
import { ChildProcessSpawner } from "effect/unstable/process";
import * as AcpError from "../errors.ts";
import { makeTerminationError } from "./stdio.ts";
describe("ACP child process termination", () => {
it.effect("retains the process identifier with the exit code", () =>
Effect.gen(function* () {
const error = yield* makeTerminationError({
pid: ChildProcessSpawner.ProcessId(41),
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(7)),
});
assert.instanceOf(error, AcpError.AcpProcessExitedError);
assert.equal(error.pid, 41);
assert.equal(error.code, 7);
assert.equal(error.message, "ACP process exited with code 7");
}),
);
it.effect("retains the process identifier and exact exit-status cause", () =>
Effect.gen(function* () {
const rootCause = new Error("private process diagnostics");
const cause = PlatformError.systemError({
_tag: "Unknown",
module: "ChildProcess",
method: "exitCode",
cause: rootCause,
});
const error = yield* makeTerminationError({
pid: ChildProcessSpawner.ProcessId(42),
exitCode: Effect.fail(cause),
});
assert.instanceOf(error, AcpError.AcpTransportError);
assert.equal(error.pid, 42);
assert.strictEqual(error.cause, cause);
assert.equal(error.message, "ACP transport operation read-process-exit-status failed.");
assert.notInclude(error.message, rootCause.message);
}),
);
});
+8 -2
View File
@@ -44,14 +44,20 @@ export const makeInMemoryStdio = Effect.fn("makeInMemoryStdio")(function* () {
};
});
type ChildProcessTerminationHandle = Pick<
ChildProcessSpawner.ChildProcessHandle,
"exitCode" | "pid"
>;
export const makeTerminationError = (
handle: ChildProcessSpawner.ChildProcessHandle,
handle: ChildProcessTerminationHandle,
): Effect.Effect<AcpError.AcpError> =>
Effect.match(handle.exitCode, {
onFailure: (cause) =>
new AcpError.AcpTransportError({
operation: "read-process-exit-status",
pid: handle.pid,
cause,
}),
onSuccess: (code) => new AcpError.AcpProcessExitedError({ code }),
onSuccess: (code) => new AcpError.AcpProcessExitedError({ code, pid: handle.pid }),
});
+2
View File
@@ -91,6 +91,7 @@ export class AcpProcessExitedError extends Schema.TaggedErrorClass<AcpProcessExi
"AcpProcessExitedError",
{
code: Schema.optional(Schema.Number),
pid: Schema.optionalKey(Schema.Int),
cause: Schema.optional(Schema.Defect()),
},
) {
@@ -160,6 +161,7 @@ export class AcpTransportError extends Schema.TaggedErrorClass<AcpTransportError
),
method: Schema.optional(Schema.String),
detail: Schema.optional(Schema.String),
pid: Schema.optionalKey(Schema.Int),
cause: Schema.Defect(),
},
) {
@@ -0,0 +1,48 @@
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as PlatformError from "effect/PlatformError";
import { ChildProcessSpawner } from "effect/unstable/process";
import * as CodexError from "../errors.ts";
import { makeTerminationError } from "./stdio.ts";
describe("Codex App Server child process termination", () => {
it.effect("retains the process identifier with the exit code", () =>
Effect.gen(function* () {
const error = yield* makeTerminationError({
pid: ChildProcessSpawner.ProcessId(51),
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(9)),
});
assert.instanceOf(error, CodexError.CodexAppServerProcessExitedError);
assert.equal(error.pid, 51);
assert.equal(error.code, 9);
assert.equal(error.message, "Codex App Server process exited with code 9");
}),
);
it.effect("retains the process identifier and exact exit-status cause", () =>
Effect.gen(function* () {
const rootCause = new Error("private process diagnostics");
const cause = PlatformError.systemError({
_tag: "Unknown",
module: "ChildProcess",
method: "exitCode",
cause: rootCause,
});
const error = yield* makeTerminationError({
pid: ChildProcessSpawner.ProcessId(52),
exitCode: Effect.fail(cause),
});
assert.instanceOf(error, CodexError.CodexAppServerTransportError);
assert.equal(error.pid, 52);
assert.strictEqual(error.cause, cause);
assert.equal(
error.message,
"Codex App Server transport operation 'read-process-exit-status' failed.",
);
assert.notInclude(error.message, rootCause.message);
}),
);
});
@@ -44,14 +44,20 @@ export const makeInMemoryStdio = Effect.fn("makeInMemoryStdio")(function* () {
};
});
type ChildProcessTerminationHandle = Pick<
ChildProcessSpawner.ChildProcessHandle,
"exitCode" | "pid"
>;
export const makeTerminationError = (
handle: ChildProcessSpawner.ChildProcessHandle,
handle: ChildProcessTerminationHandle,
): Effect.Effect<CodexError.CodexAppServerError> =>
Effect.match(handle.exitCode, {
onFailure: (cause) =>
new CodexError.CodexAppServerTransportError({
operation: "read-process-exit-status",
pid: handle.pid,
cause,
}),
onSuccess: (code) => new CodexError.CodexAppServerProcessExitedError({ code }),
onSuccess: (code) => new CodexError.CodexAppServerProcessExitedError({ code, pid: handle.pid }),
});
@@ -146,6 +146,7 @@ export class CodexAppServerProcessExitedError extends Schema.TaggedErrorClass<Co
"CodexAppServerProcessExitedError",
{
code: Schema.optional(Schema.Number),
pid: Schema.optionalKey(Schema.Int),
cause: Schema.optional(Schema.Defect()),
},
) {
@@ -233,6 +234,7 @@ export class CodexAppServerTransportError extends Schema.TaggedErrorClass<CodexA
"CodexAppServerTransportError",
{
operation: CodexAppServerTransportOperation,
pid: Schema.optionalKey(Schema.Int),
cause: Schema.Defect(),
},
) {
+26
View File
@@ -1,5 +1,7 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import * as Config from "effect/Config";
import * as ConfigProvider from "effect/ConfigProvider";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
@@ -10,6 +12,7 @@ import {
resolveNightlyBaseVersion,
resolveNightlyReleaseMetadata,
resolveNightlyTargetVersion,
writeNightlyReleaseOutput,
} from "./resolve-nightly-release.ts";
it("strips prerelease and build metadata when deriving the nightly base version", () => {
@@ -49,6 +52,29 @@ it("derives nightly metadata including the short commit sha in the release name"
);
});
it.effect("preserves the GITHUB_OUTPUT configuration cause", () => {
const metadata = resolveNightlyReleaseMetadata("1.2.4", "20260620", 42, "abcdef1234567890");
const configCause = new ConfigProvider.SourceError({ message: "environment unavailable" });
return Effect.gen(function* () {
const configError = yield* writeNightlyReleaseOutput(metadata, true).pipe(
Effect.provideService(FileSystem.FileSystem, FileSystem.makeNoop({})),
Effect.provideService(
ConfigProvider.ConfigProvider,
ConfigProvider.make(() => Effect.fail(configCause)),
),
Effect.flip,
);
if (configError._tag !== "NightlyReleaseGitHubOutputConfigError") {
return assert.fail(`Unexpected error: ${configError._tag}`);
}
assert.instanceOf(configError.cause, Config.ConfigError);
assert.strictEqual(configError.cause.cause, configCause);
assert.notInclude(configError.message, configCause.message);
});
});
it.layer(NodeServices.layer)("readDesktopBaseVersion", (it) => {
it.effect("preserves desktop package read context and its platform cause", () =>
Effect.gen(function* () {
+43 -5
View File
@@ -11,7 +11,7 @@ import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import { Command, Flag } from "effect/unstable/cli";
interface NightlyReleaseMetadata {
export interface NightlyReleaseMetadata {
readonly baseVersion: string;
readonly version: string;
readonly tag: string;
@@ -53,6 +53,29 @@ export class NightlyReleaseDesktopPackageError extends Schema.TaggedErrorClass<N
}
}
export class NightlyReleaseGitHubOutputConfigError extends Schema.TaggedErrorClass<NightlyReleaseGitHubOutputConfigError>()(
"NightlyReleaseGitHubOutputConfigError",
{
cause: Schema.Defect(),
},
) {
override get message(): string {
return "Failed to resolve the GITHUB_OUTPUT path for nightly release metadata.";
}
}
export class NightlyReleaseGitHubOutputAppendError extends Schema.TaggedErrorClass<NightlyReleaseGitHubOutputAppendError>()(
"NightlyReleaseGitHubOutputAppendError",
{
outputPath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to append nightly release metadata to ${this.outputPath}.`;
}
}
const RepoRoot = Effect.service(Path.Path).pipe(
Effect.flatMap((path) => path.fromFileUrl(new URL("..", import.meta.url))),
);
@@ -120,7 +143,7 @@ export const readDesktopBaseVersion = Effect.fn("readDesktopBaseVersion")(functi
return yield* resolveNightlyTargetVersion(packageJson.version);
});
const writeOutput = Effect.fn("writeOutput")(function* (
export const writeNightlyReleaseOutput = Effect.fn("writeNightlyReleaseOutput")(function* (
metadata: NightlyReleaseMetadata,
writeGithubOutput: boolean,
) {
@@ -135,9 +158,24 @@ const writeOutput = Effect.fn("writeOutput")(function* (
] as const;
if (writeGithubOutput) {
const githubOutputPath = yield* Config.nonEmptyString("GITHUB_OUTPUT");
const githubOutputPath = yield* Config.nonEmptyString("GITHUB_OUTPUT").pipe(
Effect.mapError(
(cause) =>
new NightlyReleaseGitHubOutputConfigError({
cause,
}),
),
);
const serialized = entries.map(([key, value]) => `${key}=${value}\n`).join("");
yield* fs.writeFileString(githubOutputPath, serialized, { flag: "a" });
yield* fs.writeFileString(githubOutputPath, serialized, { flag: "a" }).pipe(
Effect.mapError(
(cause) =>
new NightlyReleaseGitHubOutputAppendError({
outputPath: githubOutputPath,
cause,
}),
),
);
} else {
for (const [key, value] of entries) {
yield* Console.log(`${key}=${value}`);
@@ -172,7 +210,7 @@ const command = Command.make(
({ date, runNumber, sha, githubOutput, root }) =>
readDesktopBaseVersion(Option.getOrUndefined(root)).pipe(
Effect.map((baseVersion) => resolveNightlyReleaseMetadata(baseVersion, date, runNumber, sha)),
Effect.flatMap((metadata) => writeOutput(metadata, githubOutput)),
Effect.flatMap((metadata) => writeNightlyReleaseOutput(metadata, githubOutput)),
),
).pipe(Command.withDescription("Resolve nightly release version metadata."));
+86 -3
View File
@@ -1,11 +1,17 @@
import { assert, it } from "@effect/vitest";
import * as ConfigProvider from "effect/ConfigProvider";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as PlatformError from "effect/PlatformError";
import * as Sink from "effect/Sink";
import * as Stream from "effect/Stream";
import { ChildProcessSpawner } from "effect/unstable/process";
import { listGitTags, resolvePreviousReleaseTag } from "./resolve-previous-release-tag.ts";
import {
listGitTags,
resolvePreviousReleaseTag,
writePreviousReleaseTagOutput,
} from "./resolve-previous-release-tag.ts";
const encoder = new TextEncoder();
@@ -13,6 +19,8 @@ function mockHandle(options: {
readonly exitCode: number;
readonly stdout?: string;
readonly stderr?: string;
readonly stdoutError?: PlatformError.PlatformError;
readonly stderrError?: PlatformError.PlatformError;
}) {
return ChildProcessSpawner.makeHandle({
pid: ChildProcessSpawner.ProcessId(1),
@@ -21,8 +29,12 @@ function mockHandle(options: {
kill: () => Effect.void,
unref: Effect.succeed(Effect.void),
stdin: Sink.drain,
stdout: Stream.make(encoder.encode(options.stdout ?? "")),
stderr: Stream.make(encoder.encode(options.stderr ?? "")),
stdout: options.stdoutError
? Stream.fail(options.stdoutError)
: Stream.make(encoder.encode(options.stdout ?? "")),
stderr: options.stderrError
? Stream.fail(options.stderrError)
: Stream.make(encoder.encode(options.stderr ?? "")),
all: Stream.empty,
getInputFd: () => Sink.drain,
getOutputFd: () => Stream.empty,
@@ -95,6 +107,43 @@ it.effect("preserves git tag spawn context and the exact platform cause", () =>
});
});
it.effect("distinguishes stdout and stderr read failures", () =>
Effect.gen(function* () {
for (const [stream, operation] of [
["stdout", "read-stdout"],
["stderr", "read-stderr"],
] as const) {
const cause = PlatformError.systemError({
_tag: "Unknown",
module: "ChildProcess",
method: stream,
description: `${stream} unavailable`,
});
const error = yield* listGitTags("/repo").pipe(
Effect.scoped,
Effect.provideService(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.succeed(
mockHandle({
exitCode: 0,
...(stream === "stdout" ? { stdoutError: cause } : { stderrError: cause }),
}),
),
),
),
Effect.flip,
);
if (error._tag !== "ReleaseTagListProcessError") {
return assert.fail(`Unexpected error: ${error._tag}`);
}
assert.equal(error.operation, operation);
assert.strictEqual(error.cause, cause);
}
}),
);
it.effect("reports git tag non-zero exits without manufacturing a cause", () =>
Effect.gen(function* () {
const error = yield* listGitTags("/repo").pipe(
@@ -128,3 +177,37 @@ it.effect("reports git tag non-zero exits without manufacturing a cause", () =>
assert.notProperty(error, "stderr");
}),
);
it.effect("preserves the GITHUB_OUTPUT append path and exact cause", () => {
const outputPath = "/tmp/previous-tag-github-output";
const appendCause = PlatformError.systemError({
_tag: "PermissionDenied",
module: "FileSystem",
method: "writeFileString",
pathOrDescriptor: outputPath,
});
return Effect.gen(function* () {
const appendError = yield* writePreviousReleaseTagOutput("v1.2.3", true).pipe(
Effect.provideService(
FileSystem.FileSystem,
FileSystem.makeNoop({
writeFileString: () => Effect.fail(appendCause),
}),
),
Effect.provideService(
ConfigProvider.ConfigProvider,
ConfigProvider.fromEnv({ env: { GITHUB_OUTPUT: outputPath } }),
),
Effect.flip,
);
if (appendError._tag !== "PreviousReleaseTagGitHubOutputAppendError") {
return assert.fail(`Unexpected error: ${appendError._tag}`);
}
assert.equal(appendError.outputPath, outputPath);
assert.strictEqual(appendError.cause, appendCause);
assert.notProperty(appendError, "contents");
assert.notInclude(appendError.message, appendCause.message);
});
});
+50 -10
View File
@@ -26,9 +26,11 @@ export class InvalidReleaseTagError extends Schema.TaggedErrorClass<InvalidRelea
}
}
const NonNegativeInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));
const releaseTagListProcessContext = {
executable: Schema.Literal("git"),
argumentCount: Schema.Number,
argumentCount: NonNegativeInt,
cwd: Schema.String,
};
@@ -36,7 +38,7 @@ export class ReleaseTagListProcessError extends Schema.TaggedErrorClass<ReleaseT
"ReleaseTagListProcessError",
{
...releaseTagListProcessContext,
operation: Schema.Literals(["spawn", "communicate", "wait-for-exit"]),
operation: Schema.Literals(["spawn", "read-stdout", "read-stderr", "wait-for-exit"]),
cause: Schema.Defect(),
},
) {
@@ -50,8 +52,8 @@ export class ReleaseTagListProcessExitError extends Schema.TaggedErrorClass<Rele
{
...releaseTagListProcessContext,
exitCode: Schema.Number,
stdoutLength: Schema.Number,
stderrLength: Schema.Number,
stdoutLength: NonNegativeInt,
stderrLength: NonNegativeInt,
},
) {
override get message(): string {
@@ -59,6 +61,29 @@ export class ReleaseTagListProcessExitError extends Schema.TaggedErrorClass<Rele
}
}
export class PreviousReleaseTagGitHubOutputConfigError extends Schema.TaggedErrorClass<PreviousReleaseTagGitHubOutputConfigError>()(
"PreviousReleaseTagGitHubOutputConfigError",
{
cause: Schema.Defect(),
},
) {
override get message(): string {
return "Failed to resolve the GITHUB_OUTPUT path for the previous release tag.";
}
}
export class PreviousReleaseTagGitHubOutputAppendError extends Schema.TaggedErrorClass<PreviousReleaseTagGitHubOutputAppendError>()(
"PreviousReleaseTagGitHubOutputAppendError",
{
outputPath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to append the previous release tag to ${this.outputPath}.`;
}
}
interface StableVersion {
readonly major: number;
readonly minor: number;
@@ -238,7 +263,7 @@ export const listGitTags = Effect.fn("listGitTags")(function* (cwd = process.cwd
(cause) =>
new ReleaseTagListProcessError({
...context,
operation: "communicate",
operation: "read-stdout",
cause,
}),
),
@@ -248,7 +273,7 @@ export const listGitTags = Effect.fn("listGitTags")(function* (cwd = process.cwd
(cause) =>
new ReleaseTagListProcessError({
...context,
operation: "communicate",
operation: "read-stderr",
cause,
}),
),
@@ -280,7 +305,7 @@ export const listGitTags = Effect.fn("listGitTags")(function* (cwd = process.cwd
return stdout.split(/\r?\n/).map(String.trim).filter(String.isNonEmpty);
});
const writeOutput = Effect.fn("writeOutput")(function* (
export const writePreviousReleaseTagOutput = Effect.fn("writePreviousReleaseTagOutput")(function* (
previousTag: string | undefined,
writeGithubOutput: boolean,
) {
@@ -288,8 +313,23 @@ const writeOutput = Effect.fn("writeOutput")(function* (
if (writeGithubOutput) {
const fs = yield* FileSystem.FileSystem;
const githubOutputPath = yield* Config.nonEmptyString("GITHUB_OUTPUT");
yield* fs.writeFileString(githubOutputPath, entry, { flag: "a" });
const githubOutputPath = yield* Config.nonEmptyString("GITHUB_OUTPUT").pipe(
Effect.mapError(
(cause) =>
new PreviousReleaseTagGitHubOutputConfigError({
cause,
}),
),
);
yield* fs.writeFileString(githubOutputPath, entry, { flag: "a" }).pipe(
Effect.mapError(
(cause) =>
new PreviousReleaseTagGitHubOutputAppendError({
outputPath: githubOutputPath,
cause,
}),
),
);
return;
}
@@ -313,7 +353,7 @@ const command = Command.make(
({ channel, currentTag, githubOutput }) =>
listGitTags().pipe(
Effect.flatMap((tags) => resolvePreviousReleaseTag(channel, currentTag, tags)),
Effect.flatMap((previousTag) => writeOutput(previousTag, githubOutput)),
Effect.flatMap((previousTag) => writePreviousReleaseTagOutput(previousTag, githubOutput)),
),
).pipe(Command.withDescription("Resolve the previous release tag for a stable or nightly series."));
+107 -1
View File
@@ -1,16 +1,21 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import * as Config from "effect/Config";
import * as ConfigProvider from "effect/ConfigProvider";
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 Schema from "effect/Schema";
import { Command, CliError } from "effect/unstable/cli";
import * as TestConsole from "effect/testing/TestConsole";
import { fromJsonStringPretty } from "@t3tools/shared/schemaJson";
import {
ReleaseGitHubOutputConfigurationError,
ReleaseGitHubOutputWriteError,
ReleasePackageManifestError,
releasePackageFiles,
updateReleasePackageVersions,
updateReleasePackageVersionsCommand,
@@ -103,6 +108,73 @@ it.layer(ScriptTestLayer)("update-release-package-versions", (it) => {
}),
);
it.effect("preserves manifest read context and the filesystem cause", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const baseDir = yield* fs.makeTempDirectoryScoped({
prefix: "update-release-package-versions-read-error-",
});
const filePath = path.join(baseDir, releasePackageFiles[0]);
const error = yield* updateReleasePackageVersions("1.2.3", {
rootDir: baseDir,
}).pipe(Effect.flip);
assert.instanceOf(error, ReleasePackageManifestError);
assert.equal(error.operation, "read");
assert.equal(error.filePath, filePath);
assert.instanceOf(error.cause, PlatformError.PlatformError);
assert.equal(error.message, `Failed to read release package manifest '${filePath}'.`);
}),
);
it.effect("preserves manifest decode context and the schema cause", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const baseDir = yield* fs.makeTempDirectoryScoped({
prefix: "update-release-package-versions-decode-error-",
});
const filePath = path.join(baseDir, releasePackageFiles[0]);
yield* writePackageJsonFixtures(baseDir, "0.0.1");
yield* fs.writeFileString(filePath, "not json");
const error = yield* updateReleasePackageVersions("1.2.3", {
rootDir: baseDir,
}).pipe(Effect.flip);
assert.equal(error.operation, "decode");
assert.equal(error.filePath, filePath);
assert.isTrue(Schema.isSchemaError(error.cause));
assert.equal(error.message, `Failed to decode release package manifest '${filePath}'.`);
}),
);
it.effect("preserves manifest write context and the filesystem cause", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const baseDir = yield* fs.makeTempDirectoryScoped({
prefix: "update-release-package-versions-write-error-",
});
const filePath = path.join(baseDir, releasePackageFiles[0]);
yield* writePackageJsonFixtures(baseDir, "0.0.1");
yield* fs.chmod(filePath, 0o400);
const error = yield* updateReleasePackageVersions("1.2.3", {
rootDir: baseDir,
}).pipe(Effect.flip, Effect.ensuring(fs.chmod(filePath, 0o600).pipe(Effect.orDie)));
assert.equal(error.operation, "write");
assert.equal(error.filePath, filePath);
assert.instanceOf(error.cause, PlatformError.PlatformError);
assert.equal(error.message, `Failed to write release package manifest '${filePath}'.`);
}),
);
it.effect("accepts flags before the version positional and appends changed output", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
@@ -164,9 +236,43 @@ it.layer(ScriptTestLayer)("update-release-package-versions", (it) => {
Effect.flip,
);
assert.instanceOf(error, ReleaseGitHubOutputConfigurationError);
assert.instanceOf(error.cause, Config.ConfigError);
assert.equal(
error.message,
'SchemaError(Expected string, got undefined\n at ["GITHUB_OUTPUT"])',
"Failed to resolve GITHUB_OUTPUT for release package version output.",
);
}),
);
it.effect("preserves GITHUB_OUTPUT write context and the filesystem cause", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const baseDir = yield* fs.makeTempDirectoryScoped({
prefix: "update-release-package-versions-cli-output-error-",
});
yield* writePackageJsonFixtures(baseDir, "0.0.1");
const error = yield* runCli(["4.0.0", "--root", baseDir, "--github-output"]).pipe(
Effect.provide(
ConfigProvider.layer(
ConfigProvider.fromEnv({
env: {
GITHUB_OUTPUT: baseDir,
},
}),
),
),
Effect.flip,
);
assert.instanceOf(error, ReleaseGitHubOutputWriteError);
assert.equal(error.filePath, baseDir);
assert.instanceOf(error.cause, PlatformError.PlatformError);
assert.equal(
error.message,
`Failed to append release package version output to '${baseDir}'.`,
);
}),
);
+91 -5
View File
@@ -12,6 +12,40 @@ import * as Schema from "effect/Schema";
import { Argument, Command, Flag } from "effect/unstable/cli";
import { fromJsonStringPretty } from "@t3tools/shared/schemaJson";
export class ReleasePackageManifestError extends Schema.TaggedErrorClass<ReleasePackageManifestError>()(
"ReleasePackageManifestError",
{
operation: Schema.Literals(["read", "decode", "encode", "write"]),
filePath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to ${this.operation} release package manifest '${this.filePath}'.`;
}
}
export class ReleaseGitHubOutputConfigurationError extends Schema.TaggedErrorClass<ReleaseGitHubOutputConfigurationError>()(
"ReleaseGitHubOutputConfigurationError",
{ cause: Schema.Defect() },
) {
override get message(): string {
return "Failed to resolve GITHUB_OUTPUT for release package version output.";
}
}
export class ReleaseGitHubOutputWriteError extends Schema.TaggedErrorClass<ReleaseGitHubOutputWriteError>()(
"ReleaseGitHubOutputWriteError",
{
filePath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to append release package version output to '${this.filePath}'.`;
}
}
export const releasePackageFiles = [
"apps/server/package.json",
"apps/desktop/package.json",
@@ -39,13 +73,50 @@ export const updateReleasePackageVersions = Effect.fn("updateReleasePackageVersi
for (const relativePath of releasePackageFiles) {
const filePath = path.join(rootDir, relativePath);
const packageJson = yield* fs.readFileString(filePath).pipe(Effect.flatMap(decodePackageJson));
const packageJsonText = yield* fs.readFileString(filePath).pipe(
Effect.mapError(
(cause) =>
new ReleasePackageManifestError({
operation: "read",
filePath,
cause,
}),
),
);
const packageJson = yield* decodePackageJson(packageJsonText).pipe(
Effect.mapError(
(cause) =>
new ReleasePackageManifestError({
operation: "decode",
filePath,
cause,
}),
),
);
if (packageJson.version === version) {
continue;
}
const packageJsonString = yield* encodePackageJson({ ...packageJson, version });
yield* fs.writeFileString(filePath, `${packageJsonString}\n`);
const packageJsonString = yield* encodePackageJson({ ...packageJson, version }).pipe(
Effect.mapError(
(cause) =>
new ReleasePackageManifestError({
operation: "encode",
filePath,
cause,
}),
),
);
yield* fs.writeFileString(filePath, `${packageJsonString}\n`).pipe(
Effect.mapError(
(cause) =>
new ReleasePackageManifestError({
operation: "write",
filePath,
cause,
}),
),
);
changed = true;
}
@@ -54,8 +125,23 @@ export const updateReleasePackageVersions = Effect.fn("updateReleasePackageVersi
const writeGithubOutput = Effect.fn("writeGithubOutput")(function* (changed: boolean) {
const fs = yield* FileSystem.FileSystem;
const githubOutputPath = yield* Config.nonEmptyString("GITHUB_OUTPUT");
yield* fs.writeFileString(githubOutputPath, `changed=${changed}\n`, { flag: "a" });
const githubOutputPath = yield* Config.nonEmptyString("GITHUB_OUTPUT").pipe(
Effect.mapError(
(cause) =>
new ReleaseGitHubOutputConfigurationError({
cause,
}),
),
);
yield* fs.writeFileString(githubOutputPath, `changed=${changed}\n`, { flag: "a" }).pipe(
Effect.mapError(
(cause) =>
new ReleaseGitHubOutputWriteError({
filePath: githubOutputPath,
cause,
}),
),
);
});
export const updateReleasePackageVersionsCommand = Command.make(