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
26 changed files with 1190 additions and 730 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,
}),
}),
),
);
};
@@ -1,117 +0,0 @@
import type { AtomCommandResult } from "@t3tools/client-runtime/state/runtime";
import type { PreviewSessionSnapshot, ScopedThreadRef } from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import { AsyncResult } from "effect/unstable/reactivity";
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
import { readThreadPreviewState, resetPreviewStateForTests } from "~/previewStateStore";
import { selectThreadRightPanelState, useRightPanelStore } from "~/rightPanelStore";
import {
BrowserPreviewUnavailableError,
isBrowserPreviewAssetUrlInvalidError,
type OpenPreviewMutation,
openFileInPreview,
openUrlInPreview,
} from "./openFileInPreview";
const threadRef = {
environmentId: "environment-1" as ScopedThreadRef["environmentId"],
threadId: "thread-1" as ScopedThreadRef["threadId"],
};
const snapshot = (tabId: string, url: string): PreviewSessionSnapshot => ({
threadId: threadRef.threadId,
tabId,
navStatus: { _tag: "Success", url, title: "" },
canGoBack: false,
canGoForward: false,
updatedAt: "2026-06-21T00:00:00.000Z",
});
beforeEach(() => {
resetPreviewStateForTests();
useRightPanelStore.setState({ byThreadKey: {} });
});
afterEach(() => vi.unstubAllGlobals());
describe("openFileInPreview", () => {
it("uses the fixed unavailable-runtime message", () => {
expect(new BrowserPreviewUnavailableError().message).toBe(
"The integrated browser is unavailable in this runtime.",
);
});
it("reports invalid asset URLs with safe context and the exact parser cause", async () => {
vi.stubGlobal("window", { desktopBridge: { preview: {} } });
const parserCause = new TypeError("invalid URL");
const InvalidUrl = vi.fn(function InvalidUrl() {
throw parserCause;
});
vi.stubGlobal("URL", InvalidUrl);
const openPreview = vi.fn();
const httpBaseUrl = "not a URL";
const relativeUrl = "/api/assets/signed-secret-token/docs/report.pdf";
const expiresAt = Date.now();
const result = await openFileInPreview({
threadRef,
filePath: "docs/report.pdf",
httpBaseUrl,
createAssetUrl: async () => AsyncResult.success({ relativeUrl, expiresAt }),
openPreview,
});
const error = result._tag === "Failure" ? Cause.squash(result.cause) : undefined;
expect(isBrowserPreviewAssetUrlInvalidError(error)).toBe(true);
if (!isBrowserPreviewAssetUrlInvalidError(error)) {
throw new Error("Expected BrowserPreviewAssetUrlInvalidError");
}
expect(error).toMatchObject({
environmentId: "environment-1",
threadId: "thread-1",
filePath: "docs/report.pdf",
httpBaseUrlLength: httpBaseUrl.length,
relativeUrlLength: relativeUrl.length,
expiresAt,
});
expect(error.cause).toBe(parserCause);
expect(error.message).toBe("The environment returned an invalid asset URL.");
expect(error).not.toHaveProperty("httpBaseUrl");
expect(error).not.toHaveProperty("relativeUrl");
expect(JSON.stringify(error)).not.toContain("signed-secret-token");
expect(openPreview).not.toHaveBeenCalled();
});
});
it("does not apply an older preview response after another caller starts a newer request", async () => {
const firstSnapshot = snapshot("tab-1", "https://assets.test/first.png");
const secondSnapshot = snapshot("tab-2", "https://assets.test/second.png");
let resolveFirst!: (result: AtomCommandResult<PreviewSessionSnapshot, never>) => void;
const openPreview: OpenPreviewMutation<never> = ({ input }) =>
input.url === "https://assets.test/first.png"
? new Promise<AtomCommandResult<PreviewSessionSnapshot, never>>((resolve) => {
resolveFirst = resolve;
})
: Promise.resolve(AsyncResult.success(secondSnapshot));
const firstRequest = openUrlInPreview({
threadRef,
url: "https://assets.test/first.png",
openPreview,
});
await openUrlInPreview({
threadRef,
url: "https://assets.test/second.png",
openPreview,
});
resolveFirst(AsyncResult.success(firstSnapshot));
await firstRequest;
expect(readThreadPreviewState(threadRef).snapshot).toEqual(secondSnapshot);
expect(
selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, threadRef).surfaces,
).toEqual([{ id: "browser:tab-2", kind: "preview", resourceId: "tab-2" }]);
});
+45 -162
View File
@@ -6,20 +6,15 @@ import type {
PreviewSessionSnapshot,
ScopedThreadRef,
} from "@t3tools/contracts";
import { scopedThreadKey } from "@t3tools/client-runtime/environment";
import {
type AtomCommandResult,
mapAtomCommandResult,
} from "@t3tools/client-runtime/state/runtime";
import {
isWorkspaceBrowserPreviewPath,
isWorkspaceImagePreviewPath,
isWorkspacePreviewEntryPath,
} from "@t3tools/shared/filePreview";
import * as Cause from "effect/Cause";
import * as Schema from "effect/Schema";
import * as Data from "effect/Data";
import { AsyncResult } from "effect/unstable/reactivity";
import { resolveAssetUrl } from "~/assets/assetUrls";
import {
applyPreviewServerSnapshot,
isPreviewSupportedInRuntime,
@@ -27,123 +22,34 @@ import {
} from "~/previewStateStore";
import { useRightPanelStore } from "~/rightPanelStore";
export const isBrowserPreviewFile = isWorkspaceBrowserPreviewPath;
export const isImagePreviewFile = isWorkspaceImagePreviewPath;
export const isWorkspacePreviewFile = isWorkspacePreviewEntryPath;
export const isBrowserPreviewFile = (path: string): boolean =>
/\.(?:html?|pdf)$/i.test(path.split(/[?#]/, 1)[0] ?? "");
export class BrowserPreviewUnavailableError extends Schema.TaggedErrorClass<BrowserPreviewUnavailableError>()(
export class BrowserPreviewUnavailableError extends Data.TaggedError(
"BrowserPreviewUnavailableError",
{},
) {
override get message(): string {
return "The integrated browser is unavailable in this runtime.";
}
}
export class BrowserPreviewThreadContextUnavailableError extends Schema.TaggedErrorClass<BrowserPreviewThreadContextUnavailableError>()(
"BrowserPreviewThreadContextUnavailableError",
{},
) {
override get message(): string {
return "Thread context is unavailable.";
}
}
export class BrowserPreviewEnvironmentDisconnectedError extends Schema.TaggedErrorClass<BrowserPreviewEnvironmentDisconnectedError>()(
"BrowserPreviewEnvironmentDisconnectedError",
{
environmentId: Schema.String,
threadId: Schema.String,
},
) {
override get message(): string {
return "Environment is not connected.";
}
}
export class BrowserPreviewAssetUrlInvalidError extends Schema.TaggedErrorClass<BrowserPreviewAssetUrlInvalidError>()(
"BrowserPreviewAssetUrlInvalidError",
{
environmentId: Schema.String,
threadId: Schema.String,
filePath: Schema.String,
httpBaseUrlLength: Schema.Int,
relativeUrlLength: Schema.Int,
expiresAt: Schema.Int,
cause: Schema.Defect(),
},
) {
override get message(): string {
return "The environment returned an invalid asset URL.";
}
}
export const isBrowserPreviewAssetUrlInvalidError = Schema.is(BrowserPreviewAssetUrlInvalidError);
)<{
readonly message: string;
}> {}
export type OpenPreviewMutation<E = unknown> = (input: {
readonly environmentId: EnvironmentId;
readonly input: PreviewOpenInput;
}) => Promise<AtomCommandResult<PreviewSessionSnapshot, E>>;
interface PreviewRequest {
readonly isCurrent: () => boolean;
readonly complete: () => void;
}
const activePreviewRequestByThread = new Map<string, symbol>();
const beginPreviewRequest = (
threadRef: ScopedThreadRef,
signal: AbortSignal | undefined,
): PreviewRequest => {
const threadKey = scopedThreadKey(threadRef);
const requestId = Symbol();
activePreviewRequestByThread.set(threadKey, requestId);
return {
isCurrent: () =>
activePreviewRequestByThread.get(threadKey) === requestId && signal?.aborted !== true,
complete: () => {
if (activePreviewRequestByThread.get(threadKey) === requestId) {
activePreviewRequestByThread.delete(threadKey);
}
},
};
};
const openUrlForPreviewRequest = async <E>(
input: {
readonly threadRef: ScopedThreadRef;
readonly url: string;
readonly openPreview: OpenPreviewMutation<E>;
},
request: PreviewRequest,
): Promise<AtomCommandResult<void, E>> => {
export async function openUrlInPreview<E>(input: {
readonly threadRef: ScopedThreadRef;
readonly url: string;
readonly openPreview: OpenPreviewMutation<E>;
}): Promise<AtomCommandResult<void, E>> {
const result = await input.openPreview({
environmentId: input.threadRef.environmentId,
input: { threadId: input.threadRef.threadId, url: input.url },
});
if (!request.isCurrent()) {
return AsyncResult.success(undefined);
}
return mapAtomCommandResult(result, (snapshot) => {
applyPreviewServerSnapshot(input.threadRef, snapshot);
rememberPreviewUrl(input.threadRef, input.url);
useRightPanelStore.getState().openBrowser(input.threadRef, snapshot.tabId);
});
};
export async function openUrlInPreview<E>(input: {
readonly threadRef: ScopedThreadRef;
readonly url: string;
readonly openPreview: OpenPreviewMutation<E>;
readonly signal?: AbortSignal;
}): Promise<AtomCommandResult<void, E>> {
const request = beginPreviewRequest(input.threadRef, input.signal);
try {
return await openUrlForPreviewRequest(input, request);
} finally {
request.complete();
}
}
export async function openFileInPreview<AssetError, PreviewError>(input: {
@@ -155,61 +61,38 @@ export async function openFileInPreview<AssetError, PreviewError>(input: {
readonly input: { readonly resource: AssetResource };
}) => Promise<AtomCommandResult<AssetCreateUrlResult, AssetError>>;
readonly openPreview: OpenPreviewMutation<PreviewError>;
readonly signal?: AbortSignal;
}): Promise<
AtomCommandResult<
void,
AssetError | PreviewError | BrowserPreviewUnavailableError | BrowserPreviewAssetUrlInvalidError
>
> {
const request = beginPreviewRequest(input.threadRef, input.signal);
try {
if (!isPreviewSupportedInRuntime()) {
return AsyncResult.failure(Cause.fail(new BrowserPreviewUnavailableError()));
}
const assetResult = await input.createAssetUrl({
environmentId: input.threadRef.environmentId,
input: {
resource: {
_tag: "workspace-file",
threadId: input.threadRef.threadId,
path: input.filePath,
},
},
});
if (!request.isCurrent()) {
return AsyncResult.success(undefined);
}
if (assetResult._tag === "Failure") {
return AsyncResult.failure(assetResult.cause);
}
let assetUrl: string;
try {
assetUrl = new URL(assetResult.value.relativeUrl, input.httpBaseUrl).toString();
} catch (cause) {
return AsyncResult.failure(
Cause.fail(
new BrowserPreviewAssetUrlInvalidError({
environmentId: input.threadRef.environmentId,
threadId: input.threadRef.threadId,
filePath: input.filePath,
httpBaseUrlLength: input.httpBaseUrl.length,
relativeUrlLength: assetResult.value.relativeUrl.length,
expiresAt: assetResult.value.expiresAt,
cause,
}),
),
);
}
return await openUrlForPreviewRequest(
{
threadRef: input.threadRef,
url: assetUrl,
openPreview: input.openPreview,
},
request,
}): Promise<AtomCommandResult<void, AssetError | PreviewError | BrowserPreviewUnavailableError>> {
if (!isPreviewSupportedInRuntime()) {
return AsyncResult.failure(
Cause.fail(
new BrowserPreviewUnavailableError({
message: "The integrated browser is unavailable in this runtime.",
}),
),
);
} finally {
request.complete();
}
const assetResult = await input.createAssetUrl({
environmentId: input.threadRef.environmentId,
input: {
resource: {
_tag: "workspace-file",
threadId: input.threadRef.threadId,
path: input.filePath,
},
},
});
if (assetResult._tag === "Failure") {
return AsyncResult.failure(assetResult.cause);
}
const assetUrl = resolveAssetUrl(input.httpBaseUrl, assetResult.value.relativeUrl);
if (assetUrl === null) {
return AsyncResult.failure(
Cause.die(new Error("The environment returned an invalid asset URL.")),
);
}
return openUrlInPreview({
threadRef: input.threadRef,
url: assetUrl,
openPreview: input.openPreview,
});
}
+20 -34
View File
@@ -76,11 +76,10 @@ import { useAtomCommand } from "../state/use-atom-command";
import { useAtomQueryRunner } from "../state/use-atom-query-runner";
import { isPreviewSupportedInRuntime } from "../previewStateStore";
import {
isWorkspacePreviewFile,
isBrowserPreviewFile,
openFileInPreview,
openUrlInPreview,
BrowserPreviewEnvironmentDisconnectedError,
BrowserPreviewThreadContextUnavailableError,
BrowserPreviewUnavailableError,
} from "../browser/openFileInPreview";
class CodeHighlightErrorBoundary extends React.Component<
@@ -1061,15 +1060,11 @@ const MarkdownFileLink = memo(function MarkdownFileLink({
const error = squashAtomCommandFailure(result);
toastManager.add(
stackedThreadToast({
type: "warning",
title: "Unable to open file preview",
description:
error instanceof Error
? `${error.message} Opening the file instead.`
: "Opening the file instead.",
type: "error",
title: "Unable to open file in browser",
description: error instanceof Error ? error.message : "An error occurred.",
}),
);
handleOpenInFilePreview();
} catch (cause) {
reportMarkdownActionFailure(
{ operation: "open-file-in-browser", target: targetPath },
@@ -1077,18 +1072,14 @@ const MarkdownFileLink = memo(function MarkdownFileLink({
);
toastManager.add(
stackedThreadToast({
type: "warning",
title: "Unable to open file preview",
description:
cause instanceof Error
? `${cause.message} Opening the file instead.`
: "Opening the file instead.",
type: "error",
title: "Unable to open file in browser",
description: cause instanceof Error ? cause.message : "An error occurred.",
}),
);
handleOpenInFilePreview();
}
})();
}, [handleOpenInFilePreview, onOpenInBrowser, targetPath]);
}, [onOpenInBrowser, targetPath]);
const handleCopy = useCallback(
(value: string, title: string) => {
@@ -1293,8 +1284,12 @@ function ChatMarkdown({
(url: string) => {
if (!threadRef) {
return Promise.resolve(
AsyncResult.failure<void, BrowserPreviewThreadContextUnavailableError>(
Cause.fail(new BrowserPreviewThreadContextUnavailableError()),
AsyncResult.failure<void, BrowserPreviewUnavailableError>(
Cause.fail(
new BrowserPreviewUnavailableError({
message: "Thread context is unavailable.",
}),
),
),
);
}
@@ -1304,20 +1299,12 @@ function ChatMarkdown({
);
const openMarkdownFileInPreview = useCallback(
(path: string) => {
if (!threadRef) {
if (!threadRef || preparedConnection._tag === "None") {
return Promise.resolve(
AsyncResult.failure<void, BrowserPreviewThreadContextUnavailableError>(
Cause.fail(new BrowserPreviewThreadContextUnavailableError()),
),
);
}
if (preparedConnection._tag === "None") {
return Promise.resolve(
AsyncResult.failure<void, BrowserPreviewEnvironmentDisconnectedError>(
AsyncResult.failure<void, BrowserPreviewUnavailableError>(
Cause.fail(
new BrowserPreviewEnvironmentDisconnectedError({
environmentId: threadRef.environmentId,
threadId: threadRef.threadId,
new BrowserPreviewUnavailableError({
message: "Environment is not connected.",
}),
),
),
@@ -1481,10 +1468,9 @@ function ChatMarkdown({
threadRef={threadRef}
onOpen={openInPreferredEditor}
onOpenInBrowser={
fileLinkMeta.workspaceRelativePath !== null &&
threadRef &&
isPreviewSupportedInRuntime() &&
isWorkspacePreviewFile(fileLinkMeta.filePath)
isBrowserPreviewFile(fileLinkMeta.filePath)
? () => openMarkdownFileInPreview(fileLinkMeta.filePath)
: undefined
}
+3 -76
View File
@@ -110,8 +110,6 @@ import {
type RightPanelSurface,
useRightPanelStore,
} from "../rightPanelStore";
import { isImagePreviewFile, openFileInPreview } from "../browser/openFileInPreview";
import { resolvePathLinkTarget } from "../terminal-links";
import {
isPreviewSupportedInRuntime,
setActivePreviewTab,
@@ -181,12 +179,7 @@ import {
import { terminalEnvironment } from "../state/terminal";
import { threadEnvironment } from "../state/threads";
import { vcsEnvironment } from "../state/vcs";
import {
useEnvironmentHttpBaseUrl,
useEnvironments,
usePrimaryEnvironment,
} from "../state/environments";
import { assetEnvironment } from "../state/assets";
import { useEnvironments, usePrimaryEnvironment } from "../state/environments";
import {
useProject,
useProjects,
@@ -235,7 +228,6 @@ import { sanitizeThreadErrorMessage } from "~/rpc/transportError";
import { RightPanelSheet } from "./RightPanelSheet";
import { previewEnvironment } from "../state/preview";
import { useAtomCommand } from "../state/use-atom-command";
import { useAtomQueryRunner } from "../state/use-atom-query-runner";
import { Button } from "./ui/button";
import {
buildVersionMismatchDismissalKey,
@@ -1020,10 +1012,6 @@ function ChatViewContent(props: ChatViewProps) {
reportFailure: false,
});
const openPreview = useAtomCommand(previewEnvironment.open, { reportFailure: false });
const createAssetUrl = useAtomQueryRunner(assetEnvironment.createUrl, {
reportFailure: false,
});
const filePreviewAbortControllerRef = useRef<AbortController | null>(null);
const closePreview = useAtomCommand(previewEnvironment.close, "preview close");
const { environments } = useEnvironments();
const primaryEnvironment = usePrimaryEnvironment();
@@ -1351,9 +1339,6 @@ function ChatViewContent(props: ChatViewProps) {
? scopeProjectRef(activeThread.environmentId, activeThread.projectId)
: null;
const activeProject = useProject(activeProjectRef);
const activeEnvironmentHttpBaseUrl = useEnvironmentHttpBaseUrl(
activeProject?.environmentId ?? null,
);
const activeEnvironmentShell = useEnvironmentQuery(
activeThread ? environmentShell.stateAtom(activeThread.environmentId) : null,
);
@@ -2752,70 +2737,12 @@ function ChatViewContent(props: ChatViewProps) {
if (!activeThreadRef || !activeProject) return;
useRightPanelStore.getState().open(activeThreadRef, "files");
}, [activeProject, activeThreadRef]);
useEffect(
() => () => {
filePreviewAbortControllerRef.current?.abort();
},
[activeThreadKey],
);
const openFileSurface = useCallback(
(relativePath: string) => {
if (!activeThreadRef || !activeProject) return;
filePreviewAbortControllerRef.current?.abort();
const openFallback = () => {
useRightPanelStore.getState().openFile(activeThreadRef, relativePath);
};
if (
!isImagePreviewFile(relativePath) ||
!isPreviewSupportedInRuntime() ||
!activeWorkspaceRoot ||
!activeEnvironmentHttpBaseUrl
) {
openFallback();
return;
}
const abortController = new AbortController();
filePreviewAbortControllerRef.current = abortController;
const absolutePath = resolvePathLinkTarget(relativePath, activeWorkspaceRoot);
void (async () => {
const result = await openFileInPreview({
threadRef: activeThreadRef,
filePath: absolutePath,
httpBaseUrl: activeEnvironmentHttpBaseUrl,
createAssetUrl,
openPreview,
signal: abortController.signal,
});
if (abortController.signal.aborted) {
return;
}
if (result._tag === "Success") {
return;
}
if (isAtomCommandInterrupted(result)) {
openFallback();
return;
}
const error = squashAtomCommandFailure(result);
toastManager.add(
stackedThreadToast({
type: "warning",
title: "Unable to open image preview",
description: error instanceof Error ? error.message : "Opening the file instead.",
}),
);
openFallback();
})();
useRightPanelStore.getState().openFile(activeThreadRef, relativePath);
},
[
activeEnvironmentHttpBaseUrl,
activeProject,
activeThreadRef,
activeWorkspaceRoot,
createAssetUrl,
openPreview,
],
[activeProject, activeThreadRef],
);
const togglePreviewPanel = useCallback(() => {
if (!activeThreadRef || !isPreviewSupportedInRuntime()) return;
+23 -98
View File
@@ -21,9 +21,6 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useOpenInPreferredEditor } from "../editorPreferences";
import { type DraftId } from "../composerDraftStore";
import { openDiffFilePrimaryAction } from "../diffFileActions";
import { isImagePreviewFile, openFileInPreview } from "../browser/openFileInPreview";
import { resolvePathLinkTarget } from "../terminal-links";
import { isPreviewSupportedInRuntime } from "../previewStateStore";
import { useCheckpointDiff } from "~/lib/checkpointDiffState";
import { cn } from "~/lib/utils";
import { selectThreadDiffPanelSelection, useDiffPanelStore } from "../diffPanelStore";
@@ -64,16 +61,10 @@ import {
} from "./ui/menu";
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
import { useEnvironmentQuery } from "../state/query";
import { assetEnvironment } from "../state/assets";
import { previewEnvironment } from "../state/preview";
import { serverEnvironment } from "../state/server";
import { reviewEnvironment } from "../state/review";
import { vcsEnvironment } from "../state/vcs";
import { useEnvironmentHttpBaseUrl } from "../state/environments";
import { useAtomCommand } from "../state/use-atom-command";
import { useAtomQueryRunner } from "../state/use-atom-query-runner";
import { buildBaseRefChoices, filterBaseRefChoices } from "../lib/baseRefChoices";
import { stackedThreadToast, toastManager } from "./ui/toast";
type DiffRenderMode = "stacked" | "split";
type DiffThemeType = "light" | "dark";
@@ -222,12 +213,6 @@ export default function DiffPanel({ mode = "inline", composerDraftTarget }: Diff
: null,
);
const activeCwd = activeThread?.worktreePath ?? activeProject?.workspaceRoot;
const environmentHttpBaseUrl = useEnvironmentHttpBaseUrl(activeThread?.environmentId ?? null);
const createAssetUrl = useAtomQueryRunner(assetEnvironment.createUrl, {
reportFailure: false,
});
const openPreview = useAtomCommand(previewEnvironment.open, { reportFailure: false });
const filePreviewAbortControllerRef = useRef<AbortController | null>(null);
const serverConfig = useAtomValue(
serverEnvironment.configValueAtom(activeThread?.environmentId ?? null),
);
@@ -458,92 +443,32 @@ export default function DiffPanel({ mode = "inline", composerDraftTarget }: Diff
codeViewRef.current?.scrollTo({ type: "item", id: file.fileKey, align: "start" });
}, [codeViewFiles, selectedFilePath, selectedFileRevealRequestId]);
useEffect(
() => () => {
filePreviewAbortControllerRef.current?.abort();
},
[routeThreadRef?.environmentId, routeThreadRef?.threadId],
);
const openDiffFile = useCallback(
(filePath: string) => {
filePreviewAbortControllerRef.current?.abort();
const openFallback = () => {
openDiffFilePrimaryAction({
threadRef: routeThreadRef,
filePath,
activeCwd,
openInEditor: (targetPath) => {
void (async () => {
const result = await openInPreferredEditor(targetPath);
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
console.warn("Failed to open diff file in editor.", {
operation: "open-diff-file",
...(routeThreadRef
? {
environmentId: routeThreadRef.environmentId,
threadId: routeThreadRef.threadId,
}
: {}),
...safeErrorLogAttributes(squashAtomCommandFailure(result)),
});
}
})();
},
});
};
if (
!routeThreadRef ||
!activeCwd ||
!environmentHttpBaseUrl ||
!isPreviewSupportedInRuntime() ||
!isImagePreviewFile(filePath)
) {
openFallback();
return;
}
const abortController = new AbortController();
filePreviewAbortControllerRef.current = abortController;
void (async () => {
const result = await openFileInPreview({
threadRef: routeThreadRef,
filePath: resolvePathLinkTarget(filePath, activeCwd),
httpBaseUrl: environmentHttpBaseUrl,
createAssetUrl,
openPreview,
signal: abortController.signal,
});
if (abortController.signal.aborted) {
return;
}
if (result._tag === "Success") {
return;
}
if (isAtomCommandInterrupted(result)) {
openFallback();
return;
}
const error = squashAtomCommandFailure(result);
toastManager.add(
stackedThreadToast({
type: "warning",
title: "Unable to open image preview",
description: error instanceof Error ? error.message : "Opening the file instead.",
}),
);
openFallback();
})();
openDiffFilePrimaryAction({
threadRef: routeThreadRef,
filePath,
activeCwd,
openInEditor: (targetPath) => {
void (async () => {
const result = await openInPreferredEditor(targetPath);
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
console.warn("Failed to open diff file in editor.", {
operation: "open-diff-file",
...(routeThreadRef
? {
environmentId: routeThreadRef.environmentId,
threadId: routeThreadRef.threadId,
}
: {}),
...safeErrorLogAttributes(squashAtomCommandFailure(result)),
});
}
})();
},
});
},
[
activeCwd,
createAssetUrl,
environmentHttpBaseUrl,
openInPreferredEditor,
openPreview,
routeThreadRef,
],
[activeCwd, openInPreferredEditor, routeThreadRef],
);
const toggleDiffFileCollapsed = useCallback(
(fileKey: string) => {
@@ -15,7 +15,7 @@ import { ChevronRight, Code2, Eye, FolderTree, Globe2, LoaderCircle } from "luci
import * as Schema from "effect/Schema";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { isWorkspacePreviewFile, openFileInPreview } from "~/browser/openFileInPreview";
import { isBrowserPreviewFile, openFileInPreview } from "~/browser/openFileInPreview";
import ChatMarkdown from "~/components/ChatMarkdown";
import { OpenInPicker } from "~/components/chat/OpenInPicker";
import { useTheme } from "~/hooks/useTheme";
@@ -633,8 +633,8 @@ export default function FilePreviewPanel({
isMarkdown &&
markdownView.path === relativePath &&
(revealLine === null || markdownView.revealRequestId === revealRequestId);
const canOpenInPreview =
relativePath !== null && isPreviewSupportedInRuntime() && isWorkspacePreviewFile(relativePath);
const canOpenInBrowser =
relativePath !== null && isPreviewSupportedInRuntime() && isBrowserPreviewFile(relativePath);
const absolutePath = relativePath ? resolvePathLinkTarget(relativePath, cwd) : null;
const breadcrumbs = useMemo(
() => (relativePath ? fileBreadcrumbs(projectName, relativePath) : []),
@@ -661,7 +661,7 @@ export default function FilePreviewPanel({
});
};
const handleOpenInPreview = useCallback(() => {
const handleOpenInBrowser = useCallback(() => {
if (!absolutePath || !environmentHttpBaseUrl) return;
void (async () => {
const result = await openFileInPreview({
@@ -678,7 +678,7 @@ export default function FilePreviewPanel({
toastManager.add(
stackedThreadToast({
type: "error",
title: "Unable to open file in preview",
title: "Unable to open file in browser",
description: error instanceof Error ? error.message : "An error occurred.",
}),
);
@@ -757,15 +757,15 @@ export default function FilePreviewPanel({
</TooltipPopup>
</Tooltip>
) : null}
{canOpenInPreview ? (
{canOpenInBrowser ? (
<Tooltip>
<TooltipTrigger
render={
<Toggle
className="shrink-0"
pressed={false}
onPressedChange={handleOpenInPreview}
aria-label="Open file in preview"
onPressedChange={handleOpenInBrowser}
aria-label="Open file in preview browser"
variant="ghost"
size="sm"
>
@@ -773,7 +773,7 @@ export default function FilePreviewPanel({
</Toggle>
}
/>
<TooltipPopup>Open file in preview</TooltipPopup>
<TooltipPopup>Open file in preview browser</TooltipPopup>
</Tooltip>
) : null}
<Tooltip>
+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(