Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
48e11f6ba2 | ||
|
|
352cca0906 | ||
|
|
a6f1072834 | ||
|
|
948bf61626 | ||
|
|
0075ca2bb2 | ||
|
|
360747433f | ||
|
|
3be757f51a | ||
|
|
60dc4af916 | ||
|
|
d389cfd4e3 | ||
|
|
6fc79737c3 | ||
|
|
cdd03591ef | ||
|
|
2fbb0565d7 | ||
|
|
a3dadc04bf | ||
|
|
1a59277dc8 | ||
|
|
6424197a19 | ||
|
|
8d4a8b4f31 | ||
|
|
23ab75e84a |
No files matched your search
@@ -18,8 +18,7 @@ export const LEGACY_CONNECTIONS_KEY = "t3code.connections";
|
||||
function catalogError(operation: string, cause: unknown) {
|
||||
return new ConnectionTransientError({
|
||||
reason: "remote-unavailable",
|
||||
detail: `Could not ${operation} the local connection catalog.`,
|
||||
cause,
|
||||
detail: `Could not ${operation} the local connection catalog: ${String(cause)}`,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -58,8 +58,23 @@ const LegacyStoredShellSnapshot = Schema.Struct({
|
||||
function catalogError(operation: string, cause: unknown) {
|
||||
return new ConnectionTransientError({
|
||||
reason: "remote-unavailable",
|
||||
detail: `Could not ${operation} the local connection catalog.`,
|
||||
cause,
|
||||
detail: `Could not ${operation} the local connection catalog: ${String(cause)}`,
|
||||
});
|
||||
}
|
||||
|
||||
function shellPersistenceError(
|
||||
operation:
|
||||
| "load-shell"
|
||||
| "save-shell"
|
||||
| "load-thread"
|
||||
| "save-thread"
|
||||
| "remove-thread"
|
||||
| "clear-environment",
|
||||
cause: unknown,
|
||||
) {
|
||||
return new ConnectionPersistenceError({
|
||||
operation,
|
||||
message: `Could not ${operation.replaceAll("-", " ")}: ${String(cause)}`,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -85,7 +100,7 @@ const threadSnapshotDirectory = Effect.fn("mobile.connectionStorage.threadSnapsh
|
||||
}
|
||||
return directory;
|
||||
},
|
||||
catch: (cause) => new ConnectionPersistenceError({ operation, cause }),
|
||||
catch: (cause) => shellPersistenceError(operation, cause),
|
||||
});
|
||||
},
|
||||
);
|
||||
@@ -102,6 +117,16 @@ const threadSnapshotFile = Effect.fn("mobile.connectionStorage.threadSnapshotFil
|
||||
);
|
||||
});
|
||||
|
||||
function targetPersistenceError(
|
||||
operation: "list-targets" | "register-connection" | "remove-connection",
|
||||
error: ConnectionTransientError,
|
||||
) {
|
||||
return new ConnectionPersistenceError({
|
||||
operation,
|
||||
message: error.message,
|
||||
});
|
||||
}
|
||||
|
||||
const secureCatalogStorage: SecureCatalogStorage = {
|
||||
getItem: (key) =>
|
||||
Effect.tryPromise({
|
||||
@@ -138,7 +163,7 @@ const shellSnapshotFileInDirectory = Effect.fn(
|
||||
directory.create({ idempotent: true, intermediates: true });
|
||||
return new File(directory, shellSnapshotFileName(environmentId));
|
||||
},
|
||||
catch: (cause) => new ConnectionPersistenceError({ operation, cause }),
|
||||
catch: (cause) => shellPersistenceError(operation, cause),
|
||||
});
|
||||
});
|
||||
|
||||
@@ -159,29 +184,18 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
const targetStore = ConnectionTargetStore.of({
|
||||
list: catalog.read.pipe(
|
||||
Effect.map((document) => document.targets),
|
||||
Effect.mapError(
|
||||
(cause) => new ConnectionPersistenceError({ operation: "list-targets", cause }),
|
||||
),
|
||||
Effect.mapError((error) => targetPersistenceError("list-targets", error)),
|
||||
),
|
||||
});
|
||||
const registrationStore = ConnectionRegistrationStore.of({
|
||||
register: (registration) =>
|
||||
catalog
|
||||
.update((document) => registerConnectionInCatalog(document, registration))
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ConnectionPersistenceError({ operation: "register-connection", cause }),
|
||||
),
|
||||
),
|
||||
.pipe(Effect.mapError((error) => targetPersistenceError("register-connection", error))),
|
||||
remove: (target) =>
|
||||
catalog
|
||||
.update((document) => removeConnectionFromCatalog(document, target))
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new ConnectionPersistenceError({ operation: "remove-connection", cause }),
|
||||
),
|
||||
),
|
||||
.pipe(Effect.mapError((error) => targetPersistenceError("remove-connection", error))),
|
||||
});
|
||||
const profileStore = ProfileStore.make({
|
||||
get: (connectionId) =>
|
||||
@@ -269,19 +283,15 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
if (file.exists) {
|
||||
const raw = yield* Effect.tryPromise({
|
||||
try: () => file.text(),
|
||||
catch: (cause) => new ConnectionPersistenceError({ operation: "load-shell", cause }),
|
||||
catch: (cause) => shellPersistenceError("load-shell", cause),
|
||||
});
|
||||
const parsed = yield* Effect.try({
|
||||
try: () => JSON.parse(raw) as unknown,
|
||||
catch: (cause) => new ConnectionPersistenceError({ operation: "load-shell", cause }),
|
||||
catch: (cause) => shellPersistenceError("load-shell", cause),
|
||||
});
|
||||
const stored = yield* Effect.fromResult(
|
||||
Schema.decodeUnknownResult(StoredShellSnapshot)(parsed),
|
||||
).pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new ConnectionPersistenceError({ operation: "load-shell", cause }),
|
||||
),
|
||||
);
|
||||
).pipe(Effect.mapError((cause) => shellPersistenceError("load-shell", cause)));
|
||||
return stored.environmentId === environmentId
|
||||
? Option.some(stored.snapshot)
|
||||
: Option.none();
|
||||
@@ -293,19 +303,15 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
}
|
||||
const legacyRaw = yield* Effect.tryPromise({
|
||||
try: () => legacyFile.text(),
|
||||
catch: (cause) => new ConnectionPersistenceError({ operation: "load-shell", cause }),
|
||||
catch: (cause) => shellPersistenceError("load-shell", cause),
|
||||
});
|
||||
const legacyParsed = yield* Effect.try({
|
||||
try: () => JSON.parse(legacyRaw) as unknown,
|
||||
catch: (cause) => new ConnectionPersistenceError({ operation: "load-shell", cause }),
|
||||
catch: (cause) => shellPersistenceError("load-shell", cause),
|
||||
});
|
||||
const legacyStored = yield* Effect.fromResult(
|
||||
Schema.decodeUnknownResult(LegacyStoredShellSnapshot)(legacyParsed),
|
||||
).pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new ConnectionPersistenceError({ operation: "load-shell", cause }),
|
||||
),
|
||||
);
|
||||
).pipe(Effect.mapError((cause) => shellPersistenceError("load-shell", cause)));
|
||||
return legacyStored.environmentId === environmentId
|
||||
? Option.some(legacyStored.snapshot)
|
||||
: Option.none();
|
||||
@@ -320,11 +326,7 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
} as const;
|
||||
const encoded = yield* Effect.fromResult(
|
||||
Schema.encodeUnknownResult(StoredShellSnapshot)(stored),
|
||||
).pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new ConnectionPersistenceError({ operation: "save-shell", cause }),
|
||||
),
|
||||
);
|
||||
).pipe(Effect.mapError((cause) => shellPersistenceError("save-shell", cause)));
|
||||
yield* Effect.try({
|
||||
try: () => {
|
||||
if (!file.exists) {
|
||||
@@ -332,7 +334,7 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
}
|
||||
file.write(JSON.stringify(encoded));
|
||||
},
|
||||
catch: (cause) => new ConnectionPersistenceError({ operation: "save-shell", cause }),
|
||||
catch: (cause) => shellPersistenceError("save-shell", cause),
|
||||
});
|
||||
}),
|
||||
loadThread: (environmentId, threadId) =>
|
||||
@@ -343,19 +345,15 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
}
|
||||
const raw = yield* Effect.tryPromise({
|
||||
try: () => file.text(),
|
||||
catch: (cause) => new ConnectionPersistenceError({ operation: "load-thread", cause }),
|
||||
catch: (cause) => shellPersistenceError("load-thread", cause),
|
||||
});
|
||||
const parsed = yield* Effect.try({
|
||||
try: () => JSON.parse(raw) as unknown,
|
||||
catch: (cause) => new ConnectionPersistenceError({ operation: "load-thread", cause }),
|
||||
catch: (cause) => shellPersistenceError("load-thread", cause),
|
||||
});
|
||||
const stored = yield* Effect.fromResult(
|
||||
Schema.decodeUnknownResult(StoredThreadSnapshot)(parsed),
|
||||
).pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new ConnectionPersistenceError({ operation: "load-thread", cause }),
|
||||
),
|
||||
);
|
||||
).pipe(Effect.mapError((cause) => shellPersistenceError("load-thread", cause)));
|
||||
return stored.environmentId === environmentId && stored.threadId === threadId
|
||||
? Option.some(stored.thread)
|
||||
: Option.none();
|
||||
@@ -370,11 +368,7 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
threadId: thread.id,
|
||||
thread,
|
||||
}),
|
||||
).pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new ConnectionPersistenceError({ operation: "save-thread", cause }),
|
||||
),
|
||||
);
|
||||
).pipe(Effect.mapError((cause) => shellPersistenceError("save-thread", cause)));
|
||||
yield* Effect.try({
|
||||
try: () => {
|
||||
if (!file.exists) {
|
||||
@@ -382,7 +376,7 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
}
|
||||
file.write(JSON.stringify(encoded));
|
||||
},
|
||||
catch: (cause) => new ConnectionPersistenceError({ operation: "save-thread", cause }),
|
||||
catch: (cause) => shellPersistenceError("save-thread", cause),
|
||||
});
|
||||
}),
|
||||
removeThread: (environmentId, threadId) =>
|
||||
@@ -395,7 +389,7 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
Effect.mapError((cause) =>
|
||||
cause._tag === "ConnectionPersistenceError"
|
||||
? cause
|
||||
: new ConnectionPersistenceError({ operation: "remove-thread", cause }),
|
||||
: shellPersistenceError("remove-thread", cause),
|
||||
),
|
||||
),
|
||||
clear: (environmentId) =>
|
||||
@@ -404,16 +398,14 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
if (file.exists) {
|
||||
yield* Effect.try({
|
||||
try: () => file.delete(),
|
||||
catch: (cause) =>
|
||||
new ConnectionPersistenceError({ operation: "clear-environment", cause }),
|
||||
catch: (cause) => shellPersistenceError("clear-environment", cause),
|
||||
});
|
||||
}
|
||||
const legacyFile = yield* legacyShellSnapshotFile(environmentId, "clear-environment");
|
||||
if (legacyFile.exists) {
|
||||
yield* Effect.try({
|
||||
try: () => legacyFile.delete(),
|
||||
catch: (cause) =>
|
||||
new ConnectionPersistenceError({ operation: "clear-environment", cause }),
|
||||
catch: (cause) => shellPersistenceError("clear-environment", cause),
|
||||
});
|
||||
}
|
||||
const threadDirectory = yield* threadSnapshotDirectory(
|
||||
@@ -423,8 +415,7 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
if (threadDirectory.exists) {
|
||||
yield* Effect.try({
|
||||
try: () => threadDirectory.delete(),
|
||||
catch: (cause) =>
|
||||
new ConnectionPersistenceError({ operation: "clear-environment", cause }),
|
||||
catch: (cause) => shellPersistenceError("clear-environment", cause),
|
||||
});
|
||||
}
|
||||
}),
|
||||
|
||||
@@ -2,7 +2,11 @@ import { assert, it } from "@effect/vitest";
|
||||
|
||||
import { EnvironmentInternalError } from "@t3tools/contracts";
|
||||
|
||||
import { ProjectCommandError } from "./project.ts";
|
||||
import {
|
||||
ProjectLiveServerDeclaredResponseError,
|
||||
ProjectLiveServerRequestError,
|
||||
projectCommandErrorFromLiveServerRequest,
|
||||
} from "./project.ts";
|
||||
|
||||
it("maps declared server failures into structural project command errors", () => {
|
||||
const cause = new EnvironmentInternalError({
|
||||
@@ -11,8 +15,9 @@ it("maps declared server failures into structural project command errors", () =>
|
||||
traceId: "trace-123",
|
||||
});
|
||||
|
||||
const error = ProjectCommandError.fromLiveServerRequest(cause);
|
||||
const error = projectCommandErrorFromLiveServerRequest(cause);
|
||||
|
||||
assert.instanceOf(error, ProjectLiveServerDeclaredResponseError);
|
||||
assert.strictEqual(error.operation, "callLiveServer");
|
||||
assert.strictEqual(error.code, "internal_error");
|
||||
assert.strictEqual(error.traceId, "trace-123");
|
||||
@@ -23,10 +28,10 @@ it("maps declared server failures into structural project command errors", () =>
|
||||
it("preserves unexpected server failures without deriving the message from them", () => {
|
||||
const cause = new Error("credential abc123 was rejected");
|
||||
|
||||
const error = ProjectCommandError.fromLiveServerRequest(cause);
|
||||
const error = projectCommandErrorFromLiveServerRequest(cause);
|
||||
|
||||
assert.instanceOf(error, ProjectLiveServerRequestError);
|
||||
assert.strictEqual(error.operation, "callLiveServer");
|
||||
assert.strictEqual(error.detail, "Failed to call the running server.");
|
||||
assert.strictEqual(error.message, "Failed to call the running server.");
|
||||
assert.strictEqual(error.cause, cause);
|
||||
});
|
||||
+138
-49
@@ -51,62 +51,148 @@ type ProjectCliDispatchCommand = Extract<
|
||||
>;
|
||||
|
||||
const isEnvironmentHttpCommonError = Schema.is(EnvironmentHttpCommonError);
|
||||
const ProjectCommandOperation = Schema.Literals([
|
||||
"generateProjectCommandId",
|
||||
"callLiveServer",
|
||||
"validateProjectTitle",
|
||||
"resolveProjectTarget",
|
||||
"addProject",
|
||||
]);
|
||||
|
||||
export class ProjectCommandError extends Schema.TaggedErrorClass<ProjectCommandError>()(
|
||||
"ProjectCommandError",
|
||||
export class ProjectCommandIdGenerationError extends Schema.TaggedErrorClass<ProjectCommandIdGenerationError>()(
|
||||
"ProjectCommandIdGenerationError",
|
||||
{
|
||||
operation: ProjectCommandOperation,
|
||||
detail: Schema.String,
|
||||
code: Schema.optional(Schema.String),
|
||||
traceId: Schema.optional(Schema.String),
|
||||
status: Schema.optional(Schema.Number),
|
||||
operation: Schema.Literal("generateProjectCommandId"),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to generate a project command identifier.";
|
||||
}
|
||||
}
|
||||
|
||||
export class ProjectLiveServerDeclaredResponseError extends Schema.TaggedErrorClass<ProjectLiveServerDeclaredResponseError>()(
|
||||
"ProjectLiveServerDeclaredResponseError",
|
||||
{
|
||||
operation: Schema.Literal("callLiveServer"),
|
||||
code: Schema.String,
|
||||
traceId: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Server request failed (${this.code}, trace ${this.traceId}).`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ProjectLiveServerUndeclaredStatusError extends Schema.TaggedErrorClass<ProjectLiveServerUndeclaredStatusError>()(
|
||||
"ProjectLiveServerUndeclaredStatusError",
|
||||
{
|
||||
operation: Schema.Literal("callLiveServer"),
|
||||
status: Schema.Int,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Server request failed with undeclared status ${this.status}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ProjectLiveServerRequestError extends Schema.TaggedErrorClass<ProjectLiveServerRequestError>()(
|
||||
"ProjectLiveServerRequestError",
|
||||
{
|
||||
operation: Schema.Literal("callLiveServer"),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to call the running server.";
|
||||
}
|
||||
}
|
||||
|
||||
export class ProjectTitleEmptyError extends Schema.TaggedErrorClass<ProjectTitleEmptyError>()(
|
||||
"ProjectTitleEmptyError",
|
||||
{
|
||||
operation: Schema.Literal("validateProjectTitle"),
|
||||
title: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Project title cannot be empty.";
|
||||
}
|
||||
}
|
||||
|
||||
export class ProjectIdentifierEmptyError extends Schema.TaggedErrorClass<ProjectIdentifierEmptyError>()(
|
||||
"ProjectIdentifierEmptyError",
|
||||
{
|
||||
operation: Schema.Literal("resolveProjectTarget"),
|
||||
identifier: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Project identifier cannot be empty.";
|
||||
}
|
||||
}
|
||||
|
||||
export class ProjectNotFoundError extends Schema.TaggedErrorClass<ProjectNotFoundError>()(
|
||||
"ProjectNotFoundError",
|
||||
{
|
||||
operation: Schema.Literal("resolveProjectTarget"),
|
||||
identifier: Schema.String,
|
||||
normalizedWorkspaceRoot: Schema.optional(Schema.String),
|
||||
activeProjectCount: Schema.Number,
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {
|
||||
static fromLiveServerRequest(cause: unknown): ProjectCommandError {
|
||||
if (isEnvironmentHttpCommonError(cause)) {
|
||||
return new ProjectCommandError({
|
||||
operation: "callLiveServer",
|
||||
detail: `Server request failed (${cause.code}, trace ${cause.traceId}).`,
|
||||
code: cause.code,
|
||||
traceId: cause.traceId,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
if (HttpClientError.isHttpClientError(cause) && cause.response !== undefined) {
|
||||
return new ProjectCommandError({
|
||||
operation: "callLiveServer",
|
||||
detail: `Server request failed with undeclared status ${cause.response.status}.`,
|
||||
status: cause.response.status,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
return new ProjectCommandError({
|
||||
override get message(): string {
|
||||
return `No active project found for '${this.identifier}'.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ProjectAlreadyExistsError extends Schema.TaggedErrorClass<ProjectAlreadyExistsError>()(
|
||||
"ProjectAlreadyExistsError",
|
||||
{
|
||||
operation: Schema.Literal("addProject"),
|
||||
projectId: ProjectId,
|
||||
workspaceRoot: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `An active project already exists for '${this.workspaceRoot}'.`;
|
||||
}
|
||||
}
|
||||
|
||||
export const ProjectCommandError = Schema.Union([
|
||||
ProjectCommandIdGenerationError,
|
||||
ProjectLiveServerDeclaredResponseError,
|
||||
ProjectLiveServerUndeclaredStatusError,
|
||||
ProjectLiveServerRequestError,
|
||||
ProjectTitleEmptyError,
|
||||
ProjectIdentifierEmptyError,
|
||||
ProjectNotFoundError,
|
||||
ProjectAlreadyExistsError,
|
||||
]);
|
||||
export type ProjectCommandError = typeof ProjectCommandError.Type;
|
||||
|
||||
export function projectCommandErrorFromLiveServerRequest(cause: unknown): ProjectCommandError {
|
||||
if (isEnvironmentHttpCommonError(cause)) {
|
||||
return new ProjectLiveServerDeclaredResponseError({
|
||||
operation: "callLiveServer",
|
||||
detail: "Failed to call the running server.",
|
||||
code: cause.code,
|
||||
traceId: cause.traceId,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
if (HttpClientError.isHttpClientError(cause) && cause.response !== undefined) {
|
||||
return new ProjectLiveServerUndeclaredStatusError({
|
||||
operation: "callLiveServer",
|
||||
status: cause.response.status,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return this.detail;
|
||||
}
|
||||
return new ProjectLiveServerRequestError({ operation: "callLiveServer", cause });
|
||||
}
|
||||
|
||||
const projectCommandUuid = Crypto.Crypto.pipe(
|
||||
Effect.flatMap((crypto) => crypto.randomUUIDv4),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProjectCommandError({
|
||||
new ProjectCommandIdGenerationError({
|
||||
operation: "generateProjectCommandId",
|
||||
detail: "Failed to generate a project command identifier.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
@@ -158,9 +244,9 @@ const resolveProjectTitle = Effect.fn("resolveProjectTitle")(function* (
|
||||
if (trimmed.length > 0) {
|
||||
return trimmed;
|
||||
}
|
||||
return yield* new ProjectCommandError({
|
||||
return yield* new ProjectTitleEmptyError({
|
||||
operation: "validateProjectTitle",
|
||||
detail: "Project title cannot be empty.",
|
||||
title: explicitTitle,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -175,9 +261,9 @@ const findActiveProjectTarget = Effect.fn("findActiveProjectTarget")(function* (
|
||||
}) {
|
||||
const trimmedIdentifier = input.identifier.trim();
|
||||
if (trimmedIdentifier.length === 0) {
|
||||
return yield* new ProjectCommandError({
|
||||
return yield* new ProjectIdentifierEmptyError({
|
||||
operation: "resolveProjectTarget",
|
||||
detail: "Project identifier cannot be empty.",
|
||||
identifier: input.identifier,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -204,9 +290,11 @@ const findActiveProjectTarget = Effect.fn("findActiveProjectTarget")(function* (
|
||||
|
||||
const resolved = exactWorkspaceMatch;
|
||||
if (!resolved) {
|
||||
return yield* new ProjectCommandError({
|
||||
return yield* new ProjectNotFoundError({
|
||||
operation: "resolveProjectTarget",
|
||||
detail: `No active project found for '${trimmedIdentifier}'.`,
|
||||
identifier: trimmedIdentifier,
|
||||
activeProjectCount: activeProjects.length,
|
||||
...(normalizedWorkspaceRoot === null ? {} : { normalizedWorkspaceRoot }),
|
||||
...(normalizedWorkspaceRootResult._tag === "Failure"
|
||||
? { cause: normalizedWorkspaceRootResult.failure }
|
||||
: {}),
|
||||
@@ -228,7 +316,7 @@ const fetchLiveOrchestrationSnapshot = (origin: string, bearerToken: string) =>
|
||||
});
|
||||
}).pipe(
|
||||
withProjectCliLiveServerTimeout,
|
||||
Effect.mapError(ProjectCommandError.fromLiveServerRequest),
|
||||
Effect.mapError(projectCommandErrorFromLiveServerRequest),
|
||||
);
|
||||
|
||||
const dispatchLiveOrchestrationCommand = (
|
||||
@@ -244,7 +332,7 @@ const dispatchLiveOrchestrationCommand = (
|
||||
} as Parameters<typeof client.orchestration.dispatch>[0]);
|
||||
}).pipe(
|
||||
withProjectCliLiveServerTimeout,
|
||||
Effect.mapError(ProjectCommandError.fromLiveServerRequest),
|
||||
Effect.mapError(projectCommandErrorFromLiveServerRequest),
|
||||
);
|
||||
|
||||
const getOfflineSnapshot = Effect.fn("getOfflineSnapshot")(function* () {
|
||||
@@ -376,9 +464,10 @@ const projectAddCommand = Command.make("add", {
|
||||
(project) => project.deletedAt === null && project.workspaceRoot === workspaceRoot,
|
||||
);
|
||||
if (existingProject) {
|
||||
return yield* new ProjectCommandError({
|
||||
return yield* new ProjectAlreadyExistsError({
|
||||
operation: "addProject",
|
||||
detail: `An active project already exists for '${workspaceRoot}'.`,
|
||||
projectId: existingProject.id,
|
||||
workspaceRoot,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import {
|
||||
EnvironmentId,
|
||||
PreviewAutomationUnavailableError,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
import * as McpInvocationContext from "./McpInvocationContext.ts";
|
||||
|
||||
it.effect("reports the scoped credential context when preview capability is unavailable", () => {
|
||||
const invocation: McpInvocationContext.McpInvocationScope = {
|
||||
environmentId: EnvironmentId.make("environment-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
providerSessionId: "provider-session-1",
|
||||
providerInstanceId: ProviderInstanceId.make("codex"),
|
||||
capabilities: new Set(),
|
||||
issuedAt: 1,
|
||||
expiresAt: 2,
|
||||
};
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const error = yield* McpInvocationContext.requireMcpCapability("preview").pipe(
|
||||
Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
|
||||
Effect.flip,
|
||||
);
|
||||
|
||||
expect(error).toBeInstanceOf(PreviewAutomationUnavailableError);
|
||||
expect(error).toMatchObject({
|
||||
capability: "preview",
|
||||
environmentId: invocation.environmentId,
|
||||
threadId: invocation.threadId,
|
||||
providerSessionId: invocation.providerSessionId,
|
||||
providerInstanceId: invocation.providerInstanceId,
|
||||
});
|
||||
expect(error.message).toBe("MCP credential does not grant the preview capability.");
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,9 @@
|
||||
import type { EnvironmentId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
|
||||
import { PreviewAutomationUnavailableError } from "@t3tools/contracts";
|
||||
import {
|
||||
type EnvironmentId,
|
||||
PreviewAutomationUnavailableError,
|
||||
type ProviderInstanceId,
|
||||
type ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
@@ -26,7 +30,11 @@ export const requireMcpCapability = Effect.fn("mcp.requireCapability")(function*
|
||||
const invocation = yield* McpInvocationContext;
|
||||
if (!invocation.capabilities.has(capability)) {
|
||||
return yield* new PreviewAutomationUnavailableError({
|
||||
message: `MCP credential does not grant the ${capability} capability.`,
|
||||
capability,
|
||||
environmentId: invocation.environmentId,
|
||||
threadId: invocation.threadId,
|
||||
providerSessionId: invocation.providerSessionId,
|
||||
providerInstanceId: invocation.providerInstanceId,
|
||||
});
|
||||
}
|
||||
return invocation;
|
||||
|
||||
@@ -4,8 +4,9 @@ import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { VcsProcessExitError } from "@t3tools/contracts";
|
||||
import { VcsProcessExitError, VcsProcessSpawnError } from "@t3tools/contracts";
|
||||
|
||||
import * as VcsProcess from "../vcs/VcsProcess.ts";
|
||||
import * as AzureDevOpsCli from "./AzureDevOpsCli.ts";
|
||||
@@ -345,11 +346,63 @@ describe("AzureDevOpsCli.layer", () => {
|
||||
const az = yield* AzureDevOpsCli.AzureDevOpsCli;
|
||||
const error = yield* az.execute({ cwd: "/repo", args: ["repos", "list"] }).pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, AzureDevOpsCli.AzureDevOpsCommandFailedError);
|
||||
assert.strictEqual(error.operation, "execute");
|
||||
assert.strictEqual(error.command, "az");
|
||||
assert.strictEqual(error.cwd, "/repo");
|
||||
assert.strictEqual(error.argumentCount, 2);
|
||||
assert.strictEqual(error.detail, "Azure DevOps CLI command failed.");
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.equal(error.message.includes("sensitive-upstream-detail"), false);
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
|
||||
it.effect("does not report a missing working directory as a missing Azure CLI", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = "/missing/repo";
|
||||
const platformCause = PlatformError.systemError({
|
||||
_tag: "NotFound",
|
||||
module: "ChildProcess",
|
||||
method: "spawn",
|
||||
syscall: "chdir",
|
||||
pathOrDescriptor: cwd,
|
||||
});
|
||||
const cause = new VcsProcessSpawnError({
|
||||
operation: "AzureDevOpsCli.execute",
|
||||
command: "az",
|
||||
cwd,
|
||||
argumentCount: 2,
|
||||
cause: platformCause,
|
||||
});
|
||||
mockRun.mockReturnValueOnce(Effect.fail(cause));
|
||||
|
||||
const az = yield* AzureDevOpsCli.AzureDevOpsCli;
|
||||
const error = yield* az.execute({ cwd, args: ["repos", "list"] }).pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, AzureDevOpsCli.AzureDevOpsCommandFailedError);
|
||||
assert.strictEqual(error.cwd, cwd);
|
||||
assert.strictEqual(error.cause, cause);
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
|
||||
it.effect("keeps invalid pull request output diagnostics structured", () =>
|
||||
Effect.gen(function* () {
|
||||
mockRun.mockReturnValueOnce(Effect.succeed(processOutput("not-json")));
|
||||
|
||||
const az = yield* AzureDevOpsCli.AzureDevOpsCli;
|
||||
const error = yield* az.getPullRequest({ cwd: "/repo", reference: "42" }).pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, AzureDevOpsCli.AzureDevOpsPullRequestDecodeError);
|
||||
assert.strictEqual(error.operation, "getPullRequest");
|
||||
assert.strictEqual(error.command, "az");
|
||||
assert.strictEqual(error.cwd, "/repo");
|
||||
assert.strictEqual(error.outputLength, 8);
|
||||
assert.strictEqual(error.detail, "Azure DevOps CLI returned invalid pull request JSON.");
|
||||
assert.exists(error.cause);
|
||||
assert.strictEqual(
|
||||
error.message,
|
||||
"Azure DevOps CLI failed in getPullRequest: Azure DevOps CLI returned invalid pull request JSON.",
|
||||
);
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
});
|
||||
@@ -1,9 +1,11 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Result from "effect/Result";
|
||||
import * as Schema from "effect/Schema";
|
||||
import {
|
||||
NonNegativeInt,
|
||||
TrimmedNonEmptyString,
|
||||
type SourceControlRepositoryVisibility,
|
||||
type VcsError,
|
||||
@@ -19,16 +21,61 @@ import * as SourceControlProvider from "./SourceControlProvider.ts";
|
||||
|
||||
const DEFAULT_TIMEOUT_MS = 30_000;
|
||||
|
||||
export class AzureDevOpsCliError extends Schema.TaggedErrorClass<AzureDevOpsCliError>()(
|
||||
"AzureDevOpsCliError",
|
||||
{
|
||||
operation: Schema.String,
|
||||
command: Schema.String,
|
||||
cwd: Schema.String,
|
||||
detail: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
const azureDevOpsCommandErrorFields = {
|
||||
operation: Schema.Literal("execute"),
|
||||
command: Schema.Literal("az"),
|
||||
cwd: Schema.String,
|
||||
argumentCount: NonNegativeInt,
|
||||
cause: Schema.Defect(),
|
||||
};
|
||||
|
||||
export class AzureDevOpsCliUnavailableError extends Schema.TaggedErrorClass<AzureDevOpsCliUnavailableError>()(
|
||||
"AzureDevOpsCliUnavailableError",
|
||||
azureDevOpsCommandErrorFields,
|
||||
) {
|
||||
get detail(): string {
|
||||
return "Azure CLI (`az`) with the Azure DevOps extension is required but not available on PATH.";
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class AzureDevOpsCliAuthenticationError extends Schema.TaggedErrorClass<AzureDevOpsCliAuthenticationError>()(
|
||||
"AzureDevOpsCliAuthenticationError",
|
||||
azureDevOpsCommandErrorFields,
|
||||
) {
|
||||
get detail(): string {
|
||||
return "Azure DevOps CLI is not authenticated. Run `az devops login` and retry.";
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class AzureDevOpsPullRequestNotFoundError extends Schema.TaggedErrorClass<AzureDevOpsPullRequestNotFoundError>()(
|
||||
"AzureDevOpsPullRequestNotFoundError",
|
||||
azureDevOpsCommandErrorFields,
|
||||
) {
|
||||
get detail(): string {
|
||||
return "Pull request not found. Check the PR number or URL and try again.";
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class AzureDevOpsCommandFailedError extends Schema.TaggedErrorClass<AzureDevOpsCommandFailedError>()(
|
||||
"AzureDevOpsCommandFailedError",
|
||||
azureDevOpsCommandErrorFields,
|
||||
) {
|
||||
get detail(): string {
|
||||
return "Azure DevOps CLI command failed.";
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
@@ -38,53 +85,109 @@ export class AzureDevOpsCliError extends Schema.TaggedErrorClass<AzureDevOpsCliE
|
||||
readonly operation: "execute";
|
||||
readonly command: "az";
|
||||
readonly cwd: string;
|
||||
readonly argumentCount: number;
|
||||
},
|
||||
error: VcsError | unknown,
|
||||
cause: VcsError,
|
||||
): AzureDevOpsCliError {
|
||||
const lower = errorText(error).toLowerCase();
|
||||
|
||||
if (lower.includes("command not found: az") || lower.includes("enoent")) {
|
||||
return new AzureDevOpsCliError({
|
||||
...context,
|
||||
detail:
|
||||
"Azure CLI (`az`) with the Azure DevOps extension is required but not available on PATH.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
const fields = { ...context, cause };
|
||||
|
||||
if (
|
||||
lower.includes("az devops login") ||
|
||||
lower.includes("please run az login") ||
|
||||
lower.includes("not logged in") ||
|
||||
lower.includes("authentication failed") ||
|
||||
lower.includes("unauthorized")
|
||||
cause._tag === "VcsProcessSpawnError" &&
|
||||
cause.cause instanceof PlatformError.PlatformError &&
|
||||
cause.cause.reason._tag === "NotFound" &&
|
||||
cause.cause.reason.pathOrDescriptor !== context.cwd &&
|
||||
cause.cause.reason.syscall !== "chdir"
|
||||
) {
|
||||
return new AzureDevOpsCliError({
|
||||
...context,
|
||||
detail: "Azure DevOps CLI is not authenticated. Run `az devops login` and retry.",
|
||||
cause: error,
|
||||
});
|
||||
return new AzureDevOpsCliUnavailableError(fields);
|
||||
}
|
||||
|
||||
if (
|
||||
lower.includes("pull request") &&
|
||||
(lower.includes("not found") || lower.includes("does not exist"))
|
||||
) {
|
||||
return new AzureDevOpsCliError({
|
||||
...context,
|
||||
detail: "Pull request not found. Check the PR number or URL and try again.",
|
||||
cause: error,
|
||||
});
|
||||
if (cause._tag === "VcsProcessExitError") {
|
||||
if (cause.failureKind === "authentication") {
|
||||
return new AzureDevOpsCliAuthenticationError(fields);
|
||||
}
|
||||
if (cause.failureKind === "not-found") {
|
||||
return new AzureDevOpsPullRequestNotFoundError(fields);
|
||||
}
|
||||
}
|
||||
|
||||
return new AzureDevOpsCliError({
|
||||
...context,
|
||||
detail: "Azure DevOps CLI command failed.",
|
||||
cause: error,
|
||||
});
|
||||
return new AzureDevOpsCommandFailedError(fields);
|
||||
}
|
||||
}
|
||||
|
||||
const azureDevOpsDecodeErrorFields = {
|
||||
command: Schema.Literal("az"),
|
||||
cwd: Schema.String,
|
||||
outputLength: NonNegativeInt,
|
||||
cause: Schema.Defect(),
|
||||
};
|
||||
|
||||
export class AzureDevOpsPullRequestListDecodeError extends Schema.TaggedErrorClass<AzureDevOpsPullRequestListDecodeError>()(
|
||||
"AzureDevOpsPullRequestListDecodeError",
|
||||
{
|
||||
operation: Schema.Literal("listPullRequests"),
|
||||
...azureDevOpsDecodeErrorFields,
|
||||
},
|
||||
) {
|
||||
get detail(): string {
|
||||
return "Azure DevOps CLI returned invalid PR list JSON.";
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class AzureDevOpsPullRequestDecodeError extends Schema.TaggedErrorClass<AzureDevOpsPullRequestDecodeError>()(
|
||||
"AzureDevOpsPullRequestDecodeError",
|
||||
{
|
||||
operation: Schema.Literal("getPullRequest"),
|
||||
...azureDevOpsDecodeErrorFields,
|
||||
},
|
||||
) {
|
||||
get detail(): string {
|
||||
return "Azure DevOps CLI returned invalid pull request JSON.";
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
const AzureDevOpsRepositoryDecodeOperation = Schema.Literals([
|
||||
"getRepositoryCloneUrls",
|
||||
"getDefaultBranch",
|
||||
"createRepository",
|
||||
]);
|
||||
|
||||
export class AzureDevOpsRepositoryDecodeError extends Schema.TaggedErrorClass<AzureDevOpsRepositoryDecodeError>()(
|
||||
"AzureDevOpsRepositoryDecodeError",
|
||||
{
|
||||
operation: AzureDevOpsRepositoryDecodeOperation,
|
||||
...azureDevOpsDecodeErrorFields,
|
||||
},
|
||||
) {
|
||||
get detail(): string {
|
||||
return "Azure DevOps CLI returned invalid repository JSON.";
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export const AzureDevOpsCliError = Schema.Union([
|
||||
AzureDevOpsCliUnavailableError,
|
||||
AzureDevOpsCliAuthenticationError,
|
||||
AzureDevOpsPullRequestNotFoundError,
|
||||
AzureDevOpsCommandFailedError,
|
||||
AzureDevOpsPullRequestListDecodeError,
|
||||
AzureDevOpsPullRequestDecodeError,
|
||||
AzureDevOpsRepositoryDecodeError,
|
||||
]);
|
||||
export type AzureDevOpsCliError = typeof AzureDevOpsCliError.Type;
|
||||
|
||||
export const isAzureDevOpsCliError = Schema.is(AzureDevOpsCliError);
|
||||
|
||||
export interface AzureDevOpsRepositoryCloneUrls {
|
||||
readonly nameWithOwner: string;
|
||||
readonly url: string;
|
||||
@@ -146,17 +249,6 @@ export class AzureDevOpsCli extends Context.Service<
|
||||
}
|
||||
>()("t3/sourceControl/AzureDevOpsCli") {}
|
||||
|
||||
function errorText(error: VcsError | unknown): string {
|
||||
if (typeof error === "object" && error !== null) {
|
||||
const tag = "_tag" in error && typeof error._tag === "string" ? error._tag : "";
|
||||
const detail = "detail" in error && typeof error.detail === "string" ? error.detail : "";
|
||||
const message = "message" in error && typeof error.message === "string" ? error.message : "";
|
||||
return [tag, detail, message].filter(Boolean).join("\n");
|
||||
}
|
||||
|
||||
return String(error);
|
||||
}
|
||||
|
||||
function normalizeChangeRequestId(reference: string): string {
|
||||
const trimmed = reference.trim().replace(/^#/, "");
|
||||
const urlMatch = /(?:pullrequest|pull-request|pull|_pulls?)\/(\d+)(?:\D.*)?$/i.exec(trimmed);
|
||||
@@ -225,19 +317,18 @@ function parseRepositorySpecifier(repository: string): {
|
||||
function decodeAzureDevOpsJson<S extends Schema.Top>(
|
||||
raw: string,
|
||||
schema: S,
|
||||
operation: "getRepositoryCloneUrls" | "getDefaultBranch" | "createRepository",
|
||||
invalidDetail: string,
|
||||
operation: typeof AzureDevOpsRepositoryDecodeOperation.Type,
|
||||
cwd: string,
|
||||
): Effect.Effect<S["Type"], AzureDevOpsCliError, S["DecodingServices"]> {
|
||||
): Effect.Effect<S["Type"], AzureDevOpsRepositoryDecodeError, S["DecodingServices"]> {
|
||||
return Schema.decodeEffect(Schema.fromJsonString(schema))(raw).pipe(
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new AzureDevOpsCliError({
|
||||
(cause) =>
|
||||
new AzureDevOpsRepositoryDecodeError({
|
||||
operation,
|
||||
command: "az",
|
||||
cwd,
|
||||
detail: invalidDetail,
|
||||
cause: error,
|
||||
outputLength: raw.length,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -257,8 +348,13 @@ export const make = Effect.gen(function* () {
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError((error) =>
|
||||
AzureDevOpsCliError.fromVcsError(
|
||||
{ operation: "execute", command: "az", cwd: input.cwd },
|
||||
AzureDevOpsCommandFailedError.fromVcsError(
|
||||
{
|
||||
operation: "execute",
|
||||
command: "az",
|
||||
cwd: input.cwd,
|
||||
argumentCount: input.args.length,
|
||||
},
|
||||
error,
|
||||
),
|
||||
),
|
||||
@@ -297,11 +393,11 @@ export const make = Effect.gen(function* () {
|
||||
Effect.flatMap((decoded) => {
|
||||
if (!Result.isSuccess(decoded)) {
|
||||
return Effect.fail(
|
||||
new AzureDevOpsCliError({
|
||||
new AzureDevOpsPullRequestListDecodeError({
|
||||
operation: "listPullRequests",
|
||||
command: "az",
|
||||
cwd: input.cwd,
|
||||
detail: "Azure DevOps CLI returned invalid PR list JSON.",
|
||||
outputLength: raw.length,
|
||||
cause: decoded.failure,
|
||||
}),
|
||||
);
|
||||
@@ -331,11 +427,11 @@ export const make = Effect.gen(function* () {
|
||||
Effect.flatMap((decoded) => {
|
||||
if (!Result.isSuccess(decoded)) {
|
||||
return Effect.fail(
|
||||
new AzureDevOpsCliError({
|
||||
new AzureDevOpsPullRequestDecodeError({
|
||||
operation: "getPullRequest",
|
||||
command: "az",
|
||||
cwd: input.cwd,
|
||||
detail: "Azure DevOps CLI returned invalid pull request JSON.",
|
||||
outputLength: raw.length,
|
||||
cause: decoded.failure,
|
||||
}),
|
||||
);
|
||||
@@ -357,7 +453,6 @@ export const make = Effect.gen(function* () {
|
||||
raw,
|
||||
RawAzureDevOpsRepositorySchema,
|
||||
"getRepositoryCloneUrls",
|
||||
"Azure DevOps CLI returned invalid repository JSON.",
|
||||
input.cwd,
|
||||
),
|
||||
),
|
||||
@@ -383,13 +478,7 @@ export const make = Effect.gen(function* () {
|
||||
}).pipe(
|
||||
Effect.map((result) => result.stdout.trim()),
|
||||
Effect.flatMap((raw) =>
|
||||
decodeAzureDevOpsJson(
|
||||
raw,
|
||||
RawAzureDevOpsRepositorySchema,
|
||||
"createRepository",
|
||||
"Azure DevOps CLI returned invalid repository JSON.",
|
||||
input.cwd,
|
||||
),
|
||||
decodeAzureDevOpsJson(raw, RawAzureDevOpsRepositorySchema, "createRepository", input.cwd),
|
||||
),
|
||||
Effect.map(normalizeRepositoryCloneUrls),
|
||||
);
|
||||
@@ -421,13 +510,7 @@ export const make = Effect.gen(function* () {
|
||||
}).pipe(
|
||||
Effect.map((result) => result.stdout.trim()),
|
||||
Effect.flatMap((raw) =>
|
||||
decodeAzureDevOpsJson(
|
||||
raw,
|
||||
RawAzureDevOpsRepositorySchema,
|
||||
"getDefaultBranch",
|
||||
"Azure DevOps CLI returned invalid repository JSON.",
|
||||
input.cwd,
|
||||
),
|
||||
decodeAzureDevOpsJson(raw, RawAzureDevOpsRepositorySchema, "getDefaultBranch", input.cwd),
|
||||
),
|
||||
Effect.map((repo) => normalizeDefaultBranch(repo.defaultBranch)),
|
||||
),
|
||||
|
||||
@@ -48,11 +48,11 @@ it.effect("maps Azure DevOps PR summaries into provider-neutral change requests"
|
||||
|
||||
it.effect("adds change-request context while retaining Azure CLI causes", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new AzureDevOpsCli.AzureDevOpsCliError({
|
||||
const cause = new AzureDevOpsCli.AzureDevOpsCommandFailedError({
|
||||
operation: "execute",
|
||||
command: "az",
|
||||
cwd: "/repo",
|
||||
detail: "Azure DevOps CLI command failed.",
|
||||
argumentCount: 2,
|
||||
cause: new Error("raw upstream detail that should remain in the cause"),
|
||||
});
|
||||
const provider = yield* makeProvider({
|
||||
|
||||
@@ -533,8 +533,8 @@ it.effect("preserves the HTTP client failure without deriving the domain message
|
||||
}),
|
||||
);
|
||||
|
||||
assert.instanceOf(error, BitbucketApi.BitbucketRequestError);
|
||||
assert.strictEqual(error.operation, "getPullRequest");
|
||||
assert.strictEqual(error.detail, "Failed to send the Bitbucket request.");
|
||||
assert.strictEqual(
|
||||
error.message,
|
||||
"Bitbucket API failed in getPullRequest: Failed to send the Bitbucket request.",
|
||||
@@ -544,6 +544,61 @@ it.effect("preserves the HTTP client failure without deriving the domain message
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
it.effect("keeps Bitbucket response bodies out of checkout diagnostics", () => {
|
||||
const responseBody = '{"error":{"message":"credential=secret-value"}}';
|
||||
const { layer } = makeLayer({
|
||||
response: () => new Response(responseBody, { status: 403 }),
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const bitbucket = yield* BitbucketApi.BitbucketApi;
|
||||
const error = yield* bitbucket
|
||||
.checkoutPullRequest({ cwd: "/repo", reference: "42" })
|
||||
.pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, BitbucketApi.BitbucketResponseError);
|
||||
assert.strictEqual(error.operation, "getPullRequest");
|
||||
assert.strictEqual(error.status, 403);
|
||||
assert.strictEqual(error.responseBodyLength, responseBody.length);
|
||||
assert.notProperty(error, "responseBody");
|
||||
assert.strictEqual(
|
||||
error.message,
|
||||
"Bitbucket API failed in getPullRequest: Bitbucket returned HTTP 403.",
|
||||
);
|
||||
assert.notInclude(error.message, "secret-value");
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
it.effect("preserves Bitbucket response body read failures as their immediate cause", () => {
|
||||
const cause = new Error("response stream failed");
|
||||
const { layer } = makeLayer({
|
||||
response: () =>
|
||||
new Response(
|
||||
new ReadableStream<Uint8Array>({
|
||||
start: (controller) => controller.error(cause),
|
||||
}),
|
||||
{ status: 502 },
|
||||
),
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const bitbucket = yield* BitbucketApi.BitbucketApi;
|
||||
const error = yield* bitbucket
|
||||
.getPullRequest({ cwd: "/repo", reference: "42" })
|
||||
.pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, BitbucketApi.BitbucketResponseBodyReadError);
|
||||
assert.strictEqual(error.operation, "getPullRequest");
|
||||
assert.strictEqual(error.status, 502);
|
||||
assert.instanceOf(error.cause, HttpClientError.HttpClientError);
|
||||
assert.strictEqual(error.cause.cause, cause);
|
||||
assert.strictEqual(
|
||||
error.message,
|
||||
"Bitbucket API failed in getPullRequest: Bitbucket returned HTTP 502.",
|
||||
);
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
it.effect("checks out same-repository pull requests with the existing Bitbucket remote", () => {
|
||||
const { git, layer } = makeLayer({
|
||||
response: () =>
|
||||
@@ -630,8 +685,9 @@ it.effect("preserves Git checkout failures without deriving the domain message f
|
||||
}),
|
||||
);
|
||||
|
||||
assert.strictEqual(error.operation, "checkoutPullRequest");
|
||||
assert.strictEqual(error.detail, "Failed to check out the Bitbucket pull request.");
|
||||
assert.instanceOf(error, BitbucketApi.BitbucketCheckoutError);
|
||||
assert.strictEqual(error.cwd, "/repo");
|
||||
assert.strictEqual(error.reference, "42");
|
||||
assert.strictEqual(
|
||||
error.message,
|
||||
"Bitbucket API failed in checkoutPullRequest: Failed to check out the Bitbucket pull request.",
|
||||
|
||||
@@ -6,6 +6,7 @@ import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
import {
|
||||
NonNegativeInt,
|
||||
TrimmedNonEmptyString,
|
||||
type SourceControlProviderAuth,
|
||||
type SourceControlRepositoryCloneUrls,
|
||||
@@ -36,20 +37,156 @@ const BitbucketApiEnvConfig = Config.all({
|
||||
apiToken: Config.string("T3CODE_BITBUCKET_API_TOKEN").pipe(Config.option),
|
||||
});
|
||||
|
||||
export class BitbucketApiError extends Schema.TaggedErrorClass<BitbucketApiError>()(
|
||||
"BitbucketApiError",
|
||||
const BitbucketApiOperation = Schema.Literals([
|
||||
"resolveRepository",
|
||||
"getRepository",
|
||||
"getBranchingModel",
|
||||
"getPullRequest",
|
||||
"listPullRequests",
|
||||
"createRepository",
|
||||
"createPullRequest",
|
||||
"probeAuth",
|
||||
"checkoutPullRequest",
|
||||
]);
|
||||
type BitbucketApiOperation = typeof BitbucketApiOperation.Type;
|
||||
|
||||
export class BitbucketRepositoryLocatorError extends Schema.TaggedErrorClass<BitbucketRepositoryLocatorError>()(
|
||||
"BitbucketRepositoryLocatorError",
|
||||
{
|
||||
operation: Schema.String,
|
||||
detail: Schema.String,
|
||||
status: Schema.optional(Schema.Number),
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
repository: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Bitbucket API failed in ${this.operation}: ${this.detail}`;
|
||||
return "Bitbucket API failed in createRepository: Bitbucket repositories must be specified as workspace/repository.";
|
||||
}
|
||||
}
|
||||
const isBitbucketApiError = Schema.is(BitbucketApiError);
|
||||
|
||||
export class BitbucketRequestError extends Schema.TaggedErrorClass<BitbucketRequestError>()(
|
||||
"BitbucketRequestError",
|
||||
{
|
||||
operation: BitbucketApiOperation,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Bitbucket API failed in ${this.operation}: Failed to send the Bitbucket request.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class BitbucketResponseError extends Schema.TaggedErrorClass<BitbucketResponseError>()(
|
||||
"BitbucketResponseError",
|
||||
{
|
||||
operation: BitbucketApiOperation,
|
||||
status: Schema.Int,
|
||||
responseBodyLength: NonNegativeInt,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Bitbucket API failed in ${this.operation}: Bitbucket returned HTTP ${this.status}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class BitbucketResponseBodyReadError extends Schema.TaggedErrorClass<BitbucketResponseBodyReadError>()(
|
||||
"BitbucketResponseBodyReadError",
|
||||
{
|
||||
operation: BitbucketApiOperation,
|
||||
status: Schema.Int,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Bitbucket API failed in ${this.operation}: Bitbucket returned HTTP ${this.status}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class BitbucketResponseDecodeError extends Schema.TaggedErrorClass<BitbucketResponseDecodeError>()(
|
||||
"BitbucketResponseDecodeError",
|
||||
{
|
||||
operation: BitbucketApiOperation,
|
||||
status: Schema.Int,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Bitbucket API failed in ${this.operation}: Bitbucket returned invalid JSON for the requested resource.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class BitbucketRepositoryVcsResolveError extends Schema.TaggedErrorClass<BitbucketRepositoryVcsResolveError>()(
|
||||
"BitbucketRepositoryVcsResolveError",
|
||||
{
|
||||
cwd: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Bitbucket API failed in resolveRepository: Failed to resolve VCS repository for ${this.cwd}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class BitbucketRepositoryRemotesListError extends Schema.TaggedErrorClass<BitbucketRepositoryRemotesListError>()(
|
||||
"BitbucketRepositoryRemotesListError",
|
||||
{
|
||||
cwd: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Bitbucket API failed in resolveRepository: Failed to list remotes for ${this.cwd}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class BitbucketRepositoryRemoteNotFoundError extends Schema.TaggedErrorClass<BitbucketRepositoryRemoteNotFoundError>()(
|
||||
"BitbucketRepositoryRemoteNotFoundError",
|
||||
{
|
||||
cwd: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Bitbucket API failed in resolveRepository: No Bitbucket repository remote was detected for ${this.cwd}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class BitbucketPullRequestBodyReadError extends Schema.TaggedErrorClass<BitbucketPullRequestBodyReadError>()(
|
||||
"BitbucketPullRequestBodyReadError",
|
||||
{
|
||||
cwd: Schema.String,
|
||||
bodyFile: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Bitbucket API failed in createPullRequest: Failed to read pull request body file ${this.bodyFile}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class BitbucketCheckoutError extends Schema.TaggedErrorClass<BitbucketCheckoutError>()(
|
||||
"BitbucketCheckoutError",
|
||||
{
|
||||
cwd: Schema.String,
|
||||
reference: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Bitbucket API failed in checkoutPullRequest: Failed to check out the Bitbucket pull request.";
|
||||
}
|
||||
}
|
||||
|
||||
export const BitbucketApiError = Schema.Union([
|
||||
BitbucketRepositoryLocatorError,
|
||||
BitbucketRequestError,
|
||||
BitbucketResponseError,
|
||||
BitbucketResponseBodyReadError,
|
||||
BitbucketResponseDecodeError,
|
||||
BitbucketRepositoryVcsResolveError,
|
||||
BitbucketRepositoryRemotesListError,
|
||||
BitbucketRepositoryRemoteNotFoundError,
|
||||
BitbucketPullRequestBodyReadError,
|
||||
BitbucketCheckoutError,
|
||||
]);
|
||||
export type BitbucketApiError = typeof BitbucketApiError.Type;
|
||||
export const isBitbucketApiError = Schema.is(BitbucketApiError);
|
||||
|
||||
const RawBitbucketRepositorySchema = Schema.Struct({
|
||||
full_name: TrimmedNonEmptyString,
|
||||
@@ -209,16 +346,14 @@ function parseBitbucketRepositorySlug(value: string): BitbucketRepositoryLocator
|
||||
}
|
||||
|
||||
function requireRepositoryLocator(
|
||||
operation: string,
|
||||
repository: string,
|
||||
): Effect.Effect<BitbucketRepositoryLocator, BitbucketApiError> {
|
||||
const locator = parseBitbucketRepositorySlug(repository);
|
||||
return locator
|
||||
? Effect.succeed(locator)
|
||||
: Effect.fail(
|
||||
new BitbucketApiError({
|
||||
operation,
|
||||
detail: "Bitbucket repositories must be specified as workspace/repository.",
|
||||
new BitbucketRepositoryLocatorError({
|
||||
repository,
|
||||
}),
|
||||
);
|
||||
}
|
||||
@@ -339,20 +474,24 @@ function authFromConfig(
|
||||
}
|
||||
|
||||
function responseError(
|
||||
operation: string,
|
||||
operation: BitbucketApiOperation,
|
||||
response: HttpClientResponse.HttpClientResponse,
|
||||
): Effect.Effect<never, BitbucketApiError> {
|
||||
return response.text.pipe(
|
||||
Effect.orElseSucceed(() => ""),
|
||||
Effect.flatMap((body) =>
|
||||
Effect.fail(
|
||||
new BitbucketApiError({
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new BitbucketResponseBodyReadError({
|
||||
operation,
|
||||
status: response.status,
|
||||
detail:
|
||||
body.trim().length > 0
|
||||
? `Bitbucket returned HTTP ${response.status}: ${body.trim()}`
|
||||
: `Bitbucket returned HTTP ${response.status}.`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.flatMap((body) =>
|
||||
Effect.fail(
|
||||
new BitbucketResponseError({
|
||||
operation,
|
||||
status: response.status,
|
||||
responseBodyLength: body.length,
|
||||
}),
|
||||
),
|
||||
),
|
||||
@@ -379,7 +518,7 @@ export const make = Effect.gen(function* () {
|
||||
};
|
||||
|
||||
const decodeResponse = <S extends Schema.Top>(
|
||||
operation: string,
|
||||
operation: BitbucketApiOperation,
|
||||
schema: S,
|
||||
response: HttpClientResponse.HttpClientResponse,
|
||||
): Effect.Effect<S["Type"], BitbucketApiError, S["DecodingServices"]> =>
|
||||
@@ -388,9 +527,9 @@ export const make = Effect.gen(function* () {
|
||||
HttpClientResponse.schemaBodyJson(schema)(success).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new BitbucketApiError({
|
||||
new BitbucketResponseDecodeError({
|
||||
operation,
|
||||
detail: "Bitbucket returned invalid JSON for the requested resource.",
|
||||
status: success.status,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
@@ -399,16 +538,15 @@ export const make = Effect.gen(function* () {
|
||||
})(response);
|
||||
|
||||
const executeJson = <S extends Schema.Top>(
|
||||
operation: string,
|
||||
operation: BitbucketApiOperation,
|
||||
request: HttpClientRequest.HttpClientRequest,
|
||||
schema: S,
|
||||
): Effect.Effect<S["Type"], BitbucketApiError, S["DecodingServices"]> =>
|
||||
httpClient.execute(withAuth(request.pipe(HttpClientRequest.acceptJson))).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new BitbucketApiError({
|
||||
new BitbucketRequestError({
|
||||
operation,
|
||||
detail: "Failed to send the Bitbucket request.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
@@ -433,9 +571,8 @@ export const make = Effect.gen(function* () {
|
||||
const handle = yield* vcsRegistry.resolve({ cwd: input.cwd }).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new BitbucketApiError({
|
||||
operation: "resolveRepository",
|
||||
detail: `Failed to resolve VCS repository for ${input.cwd}.`,
|
||||
new BitbucketRepositoryVcsResolveError({
|
||||
cwd: input.cwd,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
@@ -443,9 +580,8 @@ export const make = Effect.gen(function* () {
|
||||
const remotes = yield* handle.driver.listRemotes(input.cwd).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new BitbucketApiError({
|
||||
operation: "resolveRepository",
|
||||
detail: `Failed to list remotes for ${input.cwd}.`,
|
||||
new BitbucketRepositoryRemotesListError({
|
||||
cwd: input.cwd,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
@@ -457,9 +593,8 @@ export const make = Effect.gen(function* () {
|
||||
if (parsed) return parsed;
|
||||
}
|
||||
|
||||
return yield* new BitbucketApiError({
|
||||
operation: "resolveRepository",
|
||||
detail: `No Bitbucket repository remote was detected for ${input.cwd}.`,
|
||||
return yield* new BitbucketRepositoryRemoteNotFoundError({
|
||||
cwd: input.cwd,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -600,7 +735,7 @@ export const make = Effect.gen(function* () {
|
||||
getRepositoryCloneUrls: (input) =>
|
||||
getRepository(input).pipe(Effect.map(normalizeRepositoryCloneUrls)),
|
||||
createRepository: (input) =>
|
||||
requireRepositoryLocator("createRepository", input.repository).pipe(
|
||||
requireRepositoryLocator(input.repository).pipe(
|
||||
Effect.flatMap((repository) =>
|
||||
executeJson(
|
||||
"createRepository",
|
||||
@@ -625,9 +760,9 @@ export const make = Effect.gen(function* () {
|
||||
const description = yield* fileSystem.readFileString(input.bodyFile).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new BitbucketApiError({
|
||||
operation: "createPullRequest",
|
||||
detail: `Failed to read pull request body file ${input.bodyFile}.`,
|
||||
new BitbucketPullRequestBodyReadError({
|
||||
cwd: input.cwd,
|
||||
bodyFile: input.bodyFile,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
@@ -743,9 +878,9 @@ export const make = Effect.gen(function* () {
|
||||
Effect.mapError((cause) =>
|
||||
isBitbucketApiError(cause)
|
||||
? cause
|
||||
: new BitbucketApiError({
|
||||
operation: "checkoutPullRequest",
|
||||
detail: "Failed to check out the Bitbucket pull request.",
|
||||
: new BitbucketCheckoutError({
|
||||
cwd: input.cwd,
|
||||
reference: input.reference,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
|
||||
@@ -53,11 +53,10 @@ it.effect("maps Bitbucket PR summaries into provider-neutral change requests", (
|
||||
|
||||
it.effect("adds repository context while retaining Bitbucket API causes", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new BitbucketApi.BitbucketApiError({
|
||||
const upstreamCause = new Error("raw upstream failure");
|
||||
const cause = new BitbucketApi.BitbucketRequestError({
|
||||
operation: "getRepository",
|
||||
detail: "upstream detail that should remain in the cause",
|
||||
status: 503,
|
||||
cause: new Error("raw upstream failure"),
|
||||
cause: upstreamCause,
|
||||
});
|
||||
const provider = yield* makeProvider({
|
||||
getRepositoryCloneUrls: () => Effect.fail(cause),
|
||||
@@ -86,7 +85,7 @@ it.effect("adds repository context while retaining Bitbucket API causes", () =>
|
||||
},
|
||||
);
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.equal(error.message.includes(cause.detail), false);
|
||||
assert.equal(error.message.includes(upstreamCause.message), false);
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
@@ -315,10 +315,11 @@ layer("GitLabCli.layer", (it) => {
|
||||
Effect.gen(function* () {
|
||||
const cause = new VcsProcessExitError({
|
||||
operation: "GitLabCli.execute",
|
||||
command: "glab mr view 4888",
|
||||
command: "glab",
|
||||
cwd: "/repo",
|
||||
exitCode: 1,
|
||||
detail: "GET 404 merge request not found",
|
||||
failureKind: "not-found",
|
||||
});
|
||||
mockedRun.mockReturnValueOnce(Effect.fail(cause));
|
||||
|
||||
@@ -330,11 +331,37 @@ layer("GitLabCli.layer", (it) => {
|
||||
});
|
||||
}).pipe(Effect.flip);
|
||||
|
||||
assert.equal(error.message.includes("Merge request not found"), true);
|
||||
assert.equal(error.message.includes("Merge request 4888 was not found"), true);
|
||||
assert.strictEqual(error._tag, "GitLabMergeRequestNotFoundError");
|
||||
assert.strictEqual(error.command, "glab");
|
||||
assert.strictEqual(error.cwd, "/repo");
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.equal(error.message.includes(cause.detail), false);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps non-merge-request not-found failures generic", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new VcsProcessExitError({
|
||||
operation: "GitLabCli.execute",
|
||||
command: "glab",
|
||||
cwd: "/repo",
|
||||
exitCode: 1,
|
||||
detail: "GET 404 project not found",
|
||||
failureKind: "not-found",
|
||||
});
|
||||
mockedRun.mockReturnValueOnce(Effect.fail(cause));
|
||||
|
||||
const error = yield* Effect.gen(function* () {
|
||||
const glab = yield* GitLabCli.GitLabCli;
|
||||
return yield* glab.getRepositoryCloneUrls({
|
||||
cwd: "/repo",
|
||||
repository: "missing/project",
|
||||
});
|
||||
}).pipe(Effect.flip);
|
||||
|
||||
assert.strictEqual(error._tag, "GitLabCliCommandError");
|
||||
assert.strictEqual(error.cause, cause);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,6 +1,7 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Match from "effect/Match";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Result from "effect/Result";
|
||||
import * as Schema from "effect/Schema";
|
||||
@@ -21,13 +22,92 @@ import type * as SourceControlProvider from "./SourceControlProvider.ts";
|
||||
|
||||
const DEFAULT_TIMEOUT_MS = 30_000;
|
||||
|
||||
export class GitLabCliError extends Schema.TaggedErrorClass<GitLabCliError>()("GitLabCliError", {
|
||||
operation: Schema.String,
|
||||
command: Schema.String,
|
||||
const gitLabCliExecutionErrorContext = {
|
||||
operation: Schema.Literal("execute"),
|
||||
command: Schema.Literal("glab"),
|
||||
cwd: Schema.String,
|
||||
detail: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
}) {
|
||||
cause: Schema.Defect(),
|
||||
};
|
||||
|
||||
const gitLabCliDecodeErrorContext = {
|
||||
command: Schema.Literal("glab"),
|
||||
cwd: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
};
|
||||
|
||||
export class GitLabCliUnavailableError extends Schema.TaggedErrorClass<GitLabCliUnavailableError>()(
|
||||
"GitLabCliUnavailableError",
|
||||
gitLabCliExecutionErrorContext,
|
||||
) {
|
||||
get detail(): string {
|
||||
return "GitLab CLI (`glab`) is required but not available on PATH.";
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class GitLabCliAuthenticationError extends Schema.TaggedErrorClass<GitLabCliAuthenticationError>()(
|
||||
"GitLabCliAuthenticationError",
|
||||
gitLabCliExecutionErrorContext,
|
||||
) {
|
||||
get detail(): string {
|
||||
return "GitLab CLI is not authenticated. Run `glab auth login` and retry.";
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class GitLabMergeRequestNotFoundError extends Schema.TaggedErrorClass<GitLabMergeRequestNotFoundError>()(
|
||||
"GitLabMergeRequestNotFoundError",
|
||||
{
|
||||
...gitLabCliExecutionErrorContext,
|
||||
reference: Schema.String,
|
||||
},
|
||||
) {
|
||||
get detail(): string {
|
||||
return `Merge request ${this.reference} was not found. Check the MR number or URL and try again.`;
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
|
||||
static fromVcsError(
|
||||
context: {
|
||||
readonly operation: "execute";
|
||||
readonly command: "glab";
|
||||
readonly cwd: string;
|
||||
readonly reference: string;
|
||||
},
|
||||
error: VcsError,
|
||||
): GitLabCliError {
|
||||
if (error._tag === "VcsProcessExitError" && error.failureKind === "not-found") {
|
||||
return new GitLabMergeRequestNotFoundError({ ...context, cause: error });
|
||||
}
|
||||
|
||||
return GitLabCliCommandError.fromVcsError(
|
||||
{
|
||||
operation: context.operation,
|
||||
command: context.command,
|
||||
cwd: context.cwd,
|
||||
},
|
||||
error,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export class GitLabCliCommandError extends Schema.TaggedErrorClass<GitLabCliCommandError>()(
|
||||
"GitLabCliCommandError",
|
||||
gitLabCliExecutionErrorContext,
|
||||
) {
|
||||
get detail(): string {
|
||||
return "GitLab CLI command failed.";
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
@@ -38,51 +118,108 @@ export class GitLabCliError extends Schema.TaggedErrorClass<GitLabCliError>()("G
|
||||
readonly command: "glab";
|
||||
readonly cwd: string;
|
||||
},
|
||||
error: VcsError | unknown,
|
||||
error: VcsError,
|
||||
): GitLabCliError {
|
||||
const lower = errorText(error).toLowerCase();
|
||||
|
||||
if (lower.includes("command not found: glab") || isVcsProcessSpawnError(error)) {
|
||||
return new GitLabCliError({
|
||||
...context,
|
||||
detail: "GitLab CLI (`glab`) is required but not available on PATH.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
if (
|
||||
lower.includes("authentication failed") ||
|
||||
lower.includes("not logged in") ||
|
||||
lower.includes("glab auth login") ||
|
||||
lower.includes("token")
|
||||
) {
|
||||
return new GitLabCliError({
|
||||
...context,
|
||||
detail: "GitLab CLI is not authenticated. Run `glab auth login` and retry.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
if (
|
||||
lower.includes("merge request not found") ||
|
||||
lower.includes("not found") ||
|
||||
lower.includes("404")
|
||||
) {
|
||||
return new GitLabCliError({
|
||||
...context,
|
||||
detail: "Merge request not found. Check the MR number or URL and try again.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
return new GitLabCliError({
|
||||
...context,
|
||||
detail: "GitLab CLI command failed.",
|
||||
cause: error,
|
||||
return Match.valueTags(error, {
|
||||
VcsProcessSpawnError: (cause) => new GitLabCliUnavailableError({ ...context, cause }),
|
||||
VcsProcessExitError: (cause) => {
|
||||
switch (cause.failureKind) {
|
||||
case "authentication":
|
||||
return new GitLabCliAuthenticationError({ ...context, cause });
|
||||
case "not-found":
|
||||
case "command-failed":
|
||||
case undefined:
|
||||
return new GitLabCliCommandError({ ...context, cause });
|
||||
}
|
||||
},
|
||||
VcsProcessTimeoutError: (cause) => new GitLabCliCommandError({ ...context, cause }),
|
||||
VcsOutputDecodeError: (cause) => new GitLabCliCommandError({ ...context, cause }),
|
||||
VcsRepositoryDetectionError: (cause) => new GitLabCliCommandError({ ...context, cause }),
|
||||
VcsUnsupportedOperationError: (cause) => new GitLabCliCommandError({ ...context, cause }),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export class GitLabMergeRequestListDecodeError extends Schema.TaggedErrorClass<GitLabMergeRequestListDecodeError>()(
|
||||
"GitLabMergeRequestListDecodeError",
|
||||
{
|
||||
...gitLabCliDecodeErrorContext,
|
||||
operation: Schema.Literal("listMergeRequests"),
|
||||
},
|
||||
) {
|
||||
get detail(): string {
|
||||
return "GitLab CLI returned invalid MR list JSON.";
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class GitLabMergeRequestDecodeError extends Schema.TaggedErrorClass<GitLabMergeRequestDecodeError>()(
|
||||
"GitLabMergeRequestDecodeError",
|
||||
{
|
||||
...gitLabCliDecodeErrorContext,
|
||||
operation: Schema.Literal("getMergeRequest"),
|
||||
reference: Schema.String,
|
||||
},
|
||||
) {
|
||||
get detail(): string {
|
||||
return "GitLab CLI returned invalid merge request JSON.";
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class GitLabRepositoryDecodeError extends Schema.TaggedErrorClass<GitLabRepositoryDecodeError>()(
|
||||
"GitLabRepositoryDecodeError",
|
||||
{
|
||||
...gitLabCliDecodeErrorContext,
|
||||
operation: Schema.Literals(["getRepositoryCloneUrls", "createRepository", "getDefaultBranch"]),
|
||||
repository: Schema.optional(Schema.String),
|
||||
},
|
||||
) {
|
||||
get detail(): string {
|
||||
return "GitLab CLI returned invalid repository JSON.";
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class GitLabNamespaceDecodeError extends Schema.TaggedErrorClass<GitLabNamespaceDecodeError>()(
|
||||
"GitLabNamespaceDecodeError",
|
||||
{
|
||||
...gitLabCliDecodeErrorContext,
|
||||
operation: Schema.Literal("createRepository"),
|
||||
namespacePath: Schema.String,
|
||||
},
|
||||
) {
|
||||
get detail(): string {
|
||||
return "GitLab CLI returned invalid namespace JSON.";
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export const GitLabCliError = Schema.Union([
|
||||
GitLabCliUnavailableError,
|
||||
GitLabCliAuthenticationError,
|
||||
GitLabMergeRequestNotFoundError,
|
||||
GitLabCliCommandError,
|
||||
GitLabMergeRequestListDecodeError,
|
||||
GitLabMergeRequestDecodeError,
|
||||
GitLabRepositoryDecodeError,
|
||||
GitLabNamespaceDecodeError,
|
||||
]);
|
||||
export type GitLabCliError = typeof GitLabCliError.Type;
|
||||
export const isGitLabCliError = Schema.is(GitLabCliError);
|
||||
|
||||
export interface GitLabMergeRequestSummary {
|
||||
readonly number: number;
|
||||
readonly title: string;
|
||||
@@ -102,17 +239,6 @@ export interface GitLabRepositoryCloneUrls {
|
||||
readonly sshUrl: string;
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
export class GitLabCli extends Context.Service<
|
||||
GitLabCli,
|
||||
{
|
||||
@@ -168,15 +294,6 @@ export class GitLabCli extends Context.Service<
|
||||
}
|
||||
>()("t3/sourceControl/GitLabCli") {}
|
||||
|
||||
function isVcsProcessSpawnError(error: unknown): boolean {
|
||||
return (
|
||||
typeof error === "object" &&
|
||||
error !== null &&
|
||||
"_tag" in error &&
|
||||
error._tag === "VcsProcessSpawnError"
|
||||
);
|
||||
}
|
||||
|
||||
const RawGitLabRepositoryCloneUrlsSchema = Schema.Struct({
|
||||
path_with_namespace: TrimmedNonEmptyString,
|
||||
web_url: TrimmedNonEmptyString,
|
||||
@@ -192,6 +309,14 @@ const RawGitLabNamespaceSchema = Schema.Struct({
|
||||
id: Schema.Number,
|
||||
});
|
||||
|
||||
const decodeGitLabRepositoryCloneUrls = Schema.decodeEffect(
|
||||
Schema.fromJsonString(RawGitLabRepositoryCloneUrlsSchema),
|
||||
);
|
||||
const decodeGitLabDefaultBranch = Schema.decodeEffect(
|
||||
Schema.fromJsonString(RawGitLabDefaultBranchSchema),
|
||||
);
|
||||
const decodeGitLabNamespace = Schema.decodeEffect(Schema.fromJsonString(RawGitLabNamespaceSchema));
|
||||
|
||||
function normalizeRepositoryCloneUrls(
|
||||
raw: Schema.Schema.Type<typeof RawGitLabRepositoryCloneUrlsSchema>,
|
||||
): GitLabRepositoryCloneUrls {
|
||||
@@ -202,27 +327,6 @@ function normalizeRepositoryCloneUrls(
|
||||
};
|
||||
}
|
||||
|
||||
function decodeGitLabJson<S extends Schema.Top>(
|
||||
raw: string,
|
||||
schema: S,
|
||||
operation: "getRepositoryCloneUrls" | "getDefaultBranch" | "createRepository",
|
||||
invalidDetail: string,
|
||||
cwd: string,
|
||||
): Effect.Effect<S["Type"], GitLabCliError, S["DecodingServices"]> {
|
||||
return Schema.decodeEffect(Schema.fromJsonString(schema))(raw).pipe(
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new GitLabCliError({
|
||||
operation,
|
||||
command: "glab",
|
||||
cwd,
|
||||
detail: invalidDetail,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
function stateArgs(state: "open" | "closed" | "merged" | "all"): ReadonlyArray<string> {
|
||||
switch (state) {
|
||||
case "open":
|
||||
@@ -283,7 +387,10 @@ function parseRepositoryPath(repository: string): {
|
||||
export const make = Effect.gen(function* () {
|
||||
const process = yield* VcsProcess.VcsProcess;
|
||||
|
||||
const execute: GitLabCli["Service"]["execute"] = (input) =>
|
||||
const run = (
|
||||
input: Parameters<GitLabCli["Service"]["execute"]>[0],
|
||||
mapError: (error: VcsError) => GitLabCliError,
|
||||
) =>
|
||||
process
|
||||
.run({
|
||||
operation: "GitLabCli.execute",
|
||||
@@ -292,14 +399,32 @@ export const make = Effect.gen(function* () {
|
||||
cwd: input.cwd,
|
||||
timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError((error) =>
|
||||
GitLabCliError.fromVcsError(
|
||||
{ operation: "execute", command: "glab", cwd: input.cwd },
|
||||
error,
|
||||
),
|
||||
),
|
||||
);
|
||||
.pipe(Effect.mapError(mapError));
|
||||
|
||||
const execute: GitLabCli["Service"]["execute"] = (input) =>
|
||||
run(input, (error) =>
|
||||
GitLabCliCommandError.fromVcsError(
|
||||
{ operation: "execute", command: "glab", cwd: input.cwd },
|
||||
error,
|
||||
),
|
||||
);
|
||||
|
||||
const executeMergeRequest = (input: {
|
||||
readonly cwd: string;
|
||||
readonly reference: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
}) =>
|
||||
run(input, (error) =>
|
||||
GitLabMergeRequestNotFoundError.fromVcsError(
|
||||
{
|
||||
operation: "execute",
|
||||
command: "glab",
|
||||
cwd: input.cwd,
|
||||
reference: input.reference,
|
||||
},
|
||||
error,
|
||||
),
|
||||
);
|
||||
|
||||
return GitLabCli.of({
|
||||
execute,
|
||||
@@ -326,11 +451,10 @@ export const make = Effect.gen(function* () {
|
||||
Effect.flatMap((decoded) => {
|
||||
if (!Result.isSuccess(decoded)) {
|
||||
return Effect.fail(
|
||||
new GitLabCliError({
|
||||
new GitLabMergeRequestListDecodeError({
|
||||
operation: "listMergeRequests",
|
||||
command: "glab",
|
||||
cwd: input.cwd,
|
||||
detail: "GitLab CLI returned invalid MR list JSON.",
|
||||
cause: decoded.failure,
|
||||
}),
|
||||
);
|
||||
@@ -342,8 +466,9 @@ export const make = Effect.gen(function* () {
|
||||
),
|
||||
),
|
||||
getMergeRequest: (input) =>
|
||||
execute({
|
||||
executeMergeRequest({
|
||||
cwd: input.cwd,
|
||||
reference: input.reference,
|
||||
args: ["mr", "view", input.reference, "--output", "json"],
|
||||
}).pipe(
|
||||
Effect.map((result) => result.stdout.trim()),
|
||||
@@ -352,11 +477,11 @@ export const make = Effect.gen(function* () {
|
||||
Effect.flatMap((decoded) => {
|
||||
if (!Result.isSuccess(decoded)) {
|
||||
return Effect.fail(
|
||||
new GitLabCliError({
|
||||
new GitLabMergeRequestDecodeError({
|
||||
operation: "getMergeRequest",
|
||||
command: "glab",
|
||||
cwd: input.cwd,
|
||||
detail: "GitLab CLI returned invalid merge request JSON.",
|
||||
reference: input.reference,
|
||||
cause: decoded.failure,
|
||||
}),
|
||||
);
|
||||
@@ -374,12 +499,17 @@ export const make = Effect.gen(function* () {
|
||||
}).pipe(
|
||||
Effect.map((result) => result.stdout.trim()),
|
||||
Effect.flatMap((raw) =>
|
||||
decodeGitLabJson(
|
||||
raw,
|
||||
RawGitLabRepositoryCloneUrlsSchema,
|
||||
"getRepositoryCloneUrls",
|
||||
"GitLab CLI returned invalid repository JSON.",
|
||||
input.cwd,
|
||||
decodeGitLabRepositoryCloneUrls(raw).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new GitLabRepositoryDecodeError({
|
||||
operation: "getRepositoryCloneUrls",
|
||||
command: "glab",
|
||||
cwd: input.cwd,
|
||||
repository: input.repository,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
Effect.map(normalizeRepositoryCloneUrls),
|
||||
@@ -393,12 +523,17 @@ export const make = Effect.gen(function* () {
|
||||
}).pipe(
|
||||
Effect.map((result) => result.stdout.trim()),
|
||||
Effect.flatMap((raw) =>
|
||||
decodeGitLabJson(
|
||||
raw,
|
||||
RawGitLabNamespaceSchema,
|
||||
"createRepository",
|
||||
"GitLab CLI returned invalid namespace JSON.",
|
||||
input.cwd,
|
||||
decodeGitLabNamespace(raw).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new GitLabNamespaceDecodeError({
|
||||
operation: "createRepository",
|
||||
command: "glab",
|
||||
cwd: input.cwd,
|
||||
namespacePath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
Effect.map((namespace) => namespace.id),
|
||||
@@ -428,12 +563,17 @@ export const make = Effect.gen(function* () {
|
||||
),
|
||||
Effect.map((result) => result.stdout.trim()),
|
||||
Effect.flatMap((raw) =>
|
||||
decodeGitLabJson(
|
||||
raw,
|
||||
RawGitLabRepositoryCloneUrlsSchema,
|
||||
"createRepository",
|
||||
"GitLab CLI returned invalid repository JSON.",
|
||||
input.cwd,
|
||||
decodeGitLabRepositoryCloneUrls(raw).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new GitLabRepositoryDecodeError({
|
||||
operation: "createRepository",
|
||||
command: "glab",
|
||||
cwd: input.cwd,
|
||||
repository: input.repository,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
Effect.map(normalizeRepositoryCloneUrls),
|
||||
@@ -467,19 +607,24 @@ export const make = Effect.gen(function* () {
|
||||
}).pipe(
|
||||
Effect.map((result) => result.stdout.trim()),
|
||||
Effect.flatMap((raw) =>
|
||||
decodeGitLabJson(
|
||||
raw,
|
||||
RawGitLabDefaultBranchSchema,
|
||||
"getDefaultBranch",
|
||||
"GitLab CLI returned invalid repository JSON.",
|
||||
input.cwd,
|
||||
decodeGitLabDefaultBranch(raw).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new GitLabRepositoryDecodeError({
|
||||
operation: "getDefaultBranch",
|
||||
command: "glab",
|
||||
cwd: input.cwd,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
Effect.map((value) => value.default_branch ?? null),
|
||||
),
|
||||
checkoutMergeRequest: (input) =>
|
||||
execute({
|
||||
executeMergeRequest({
|
||||
cwd: input.cwd,
|
||||
reference: input.reference,
|
||||
args: ["mr", "checkout", input.reference],
|
||||
}).pipe(Effect.asVoid),
|
||||
});
|
||||
|
||||
@@ -54,11 +54,10 @@ it.effect("maps GitLab MR summaries into provider-neutral change requests", () =
|
||||
|
||||
it.effect("adds repository context while retaining GitLab CLI causes", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new GitLabCli.GitLabCliError({
|
||||
const cause = new GitLabCli.GitLabCliCommandError({
|
||||
operation: "execute",
|
||||
command: "glab",
|
||||
cwd: "/repo",
|
||||
detail: "GitLab CLI command failed.",
|
||||
cause: new Error("raw upstream detail that should remain in the cause"),
|
||||
});
|
||||
const provider = yield* makeProvider({
|
||||
|
||||
@@ -151,20 +151,29 @@ export const make = Effect.gen(function* () {
|
||||
if (!(yield* RcMap.has(workspaceSearchIndexes.rcMap, normalizedCwd))) {
|
||||
return;
|
||||
}
|
||||
const recoverRefreshFailure = (
|
||||
cause:
|
||||
| WorkspaceSearchIndex.WorkspaceSearchIndexCreateFailed
|
||||
| WorkspaceSearchIndex.WorkspaceSearchIndexScanTimedOut
|
||||
| WorkspaceSearchIndex.WorkspaceSearchIndexRefreshFailed,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
yield* Effect.logWarning("Failed to refresh workspace search index", {
|
||||
cwd,
|
||||
cause,
|
||||
});
|
||||
yield* workspaceSearchIndexes.invalidate(normalizedCwd);
|
||||
});
|
||||
yield* Effect.gen(function* () {
|
||||
const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;
|
||||
yield* searchIndex.refresh();
|
||||
}).pipe(
|
||||
Effect.provide(workspaceSearchIndexes.get(normalizedCwd)),
|
||||
Effect.catch((cause) =>
|
||||
Effect.gen(function* () {
|
||||
yield* Effect.logWarning("Failed to refresh workspace search index", {
|
||||
cwd,
|
||||
cause,
|
||||
});
|
||||
yield* workspaceSearchIndexes.invalidate(normalizedCwd);
|
||||
}),
|
||||
),
|
||||
Effect.catchTags({
|
||||
WorkspaceSearchIndexCreateFailed: recoverRefreshFailure,
|
||||
WorkspaceSearchIndexScanTimedOut: recoverRefreshFailure,
|
||||
WorkspaceSearchIndexRefreshFailed: recoverRefreshFailure,
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { FileFinder } from "@ff-labs/fff-node";
|
||||
import { afterEach, expect, it } from "@effect/vitest";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import { vi } from "vite-plus/test";
|
||||
|
||||
import * as WorkspaceSearchIndex from "./WorkspaceSearchIndex.ts";
|
||||
@@ -49,6 +51,35 @@ it.effect("keeps returned FileFinder creation diagnostics out of the cause chain
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves FileFinder destroy failures as structured defects", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("native destroy failed");
|
||||
const finder = {
|
||||
destroy: vi.fn(() => {
|
||||
throw cause;
|
||||
}),
|
||||
isScanning: vi.fn(() => false),
|
||||
} as unknown as FileFinder;
|
||||
vi.spyOn(FileFinder, "create").mockReturnValueOnce({ ok: true, value: finder });
|
||||
|
||||
const exit = yield* Effect.scoped(WorkspaceSearchIndex.make("/workspace/project")).pipe(
|
||||
Effect.exit,
|
||||
);
|
||||
|
||||
expect(Exit.isFailure(exit)).toBe(true);
|
||||
if (Exit.isFailure(exit)) {
|
||||
expect(Cause.hasDies(exit.cause)).toBe(true);
|
||||
const error = Cause.squash(exit.cause);
|
||||
expect(error).toBeInstanceOf(WorkspaceSearchIndex.WorkspaceSearchIndexDestroyFailed);
|
||||
expect(error).toMatchObject({
|
||||
_tag: "WorkspaceSearchIndexDestroyFailed",
|
||||
cwd: "/workspace/project",
|
||||
cause,
|
||||
});
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves search and refresh failures with operation context", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
|
||||
@@ -71,6 +71,18 @@ export class WorkspaceSearchIndexRefreshFailed extends Schema.TaggedErrorClass<W
|
||||
}
|
||||
}
|
||||
|
||||
export class WorkspaceSearchIndexDestroyFailed extends Schema.TaggedErrorClass<WorkspaceSearchIndexDestroyFailed>()(
|
||||
"WorkspaceSearchIndexDestroyFailed",
|
||||
{
|
||||
cwd: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to destroy the workspace search index for '${this.cwd}'.`;
|
||||
}
|
||||
}
|
||||
|
||||
export type WorkspaceSearchIndexError =
|
||||
| WorkspaceSearchIndexCreateFailed
|
||||
| WorkspaceSearchIndexScanTimedOut
|
||||
@@ -201,7 +213,10 @@ const waitForScan = <E>(cwd: string, finder: FileFinder, onFailure: (cause: unkn
|
||||
|
||||
export const make = Effect.fn("WorkspaceSearchIndex.make")(function* (cwd: string) {
|
||||
const finder = yield* Effect.acquireRelease(createFinder(cwd), (finder) =>
|
||||
Effect.sync(() => finder.destroy()),
|
||||
Effect.try({
|
||||
try: () => finder.destroy(),
|
||||
catch: (cause) => new WorkspaceSearchIndexDestroyFailed({ cwd, cause }),
|
||||
}).pipe(Effect.orDie),
|
||||
);
|
||||
yield* waitForScan(
|
||||
cwd,
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
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" }]);
|
||||
});
|
||||
@@ -6,15 +6,20 @@ 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 Data from "effect/Data";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { AsyncResult } from "effect/unstable/reactivity";
|
||||
|
||||
import { resolveAssetUrl } from "~/assets/assetUrls";
|
||||
import {
|
||||
applyPreviewServerSnapshot,
|
||||
isPreviewSupportedInRuntime,
|
||||
@@ -22,34 +27,123 @@ import {
|
||||
} from "~/previewStateStore";
|
||||
import { useRightPanelStore } from "~/rightPanelStore";
|
||||
|
||||
export const isBrowserPreviewFile = (path: string): boolean =>
|
||||
/\.(?:html?|pdf)$/i.test(path.split(/[?#]/, 1)[0] ?? "");
|
||||
export const isBrowserPreviewFile = isWorkspaceBrowserPreviewPath;
|
||||
export const isImagePreviewFile = isWorkspaceImagePreviewPath;
|
||||
export const isWorkspacePreviewFile = isWorkspacePreviewEntryPath;
|
||||
|
||||
export class BrowserPreviewUnavailableError extends Data.TaggedError(
|
||||
export class BrowserPreviewUnavailableError extends Schema.TaggedErrorClass<BrowserPreviewUnavailableError>()(
|
||||
"BrowserPreviewUnavailableError",
|
||||
)<{
|
||||
readonly message: string;
|
||||
}> {}
|
||||
{},
|
||||
) {
|
||||
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);
|
||||
|
||||
export type OpenPreviewMutation<E = unknown> = (input: {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly input: PreviewOpenInput;
|
||||
}) => Promise<AtomCommandResult<PreviewSessionSnapshot, E>>;
|
||||
|
||||
export async function openUrlInPreview<E>(input: {
|
||||
readonly threadRef: ScopedThreadRef;
|
||||
readonly url: string;
|
||||
readonly openPreview: OpenPreviewMutation<E>;
|
||||
}): Promise<AtomCommandResult<void, 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>> => {
|
||||
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: {
|
||||
@@ -61,38 +155,61 @@ export async function openFileInPreview<AssetError, PreviewError>(input: {
|
||||
readonly input: { readonly resource: AssetResource };
|
||||
}) => Promise<AtomCommandResult<AssetCreateUrlResult, AssetError>>;
|
||||
readonly openPreview: OpenPreviewMutation<PreviewError>;
|
||||
}): Promise<AtomCommandResult<void, AssetError | PreviewError | BrowserPreviewUnavailableError>> {
|
||||
if (!isPreviewSupportedInRuntime()) {
|
||||
return AsyncResult.failure(
|
||||
Cause.fail(
|
||||
new BrowserPreviewUnavailableError({
|
||||
message: "The integrated browser is unavailable in this runtime.",
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
const assetResult = await input.createAssetUrl({
|
||||
environmentId: input.threadRef.environmentId,
|
||||
input: {
|
||||
resource: {
|
||||
_tag: "workspace-file",
|
||||
threadId: input.threadRef.threadId,
|
||||
path: input.filePath,
|
||||
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 (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.")),
|
||||
});
|
||||
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,
|
||||
);
|
||||
} finally {
|
||||
request.complete();
|
||||
}
|
||||
return openUrlInPreview({
|
||||
threadRef: input.threadRef,
|
||||
url: assetUrl,
|
||||
openPreview: input.openPreview,
|
||||
});
|
||||
}
|
||||
@@ -76,10 +76,11 @@ import { useAtomCommand } from "../state/use-atom-command";
|
||||
import { useAtomQueryRunner } from "../state/use-atom-query-runner";
|
||||
import { isPreviewSupportedInRuntime } from "../previewStateStore";
|
||||
import {
|
||||
isBrowserPreviewFile,
|
||||
isWorkspacePreviewFile,
|
||||
openFileInPreview,
|
||||
openUrlInPreview,
|
||||
BrowserPreviewUnavailableError,
|
||||
BrowserPreviewEnvironmentDisconnectedError,
|
||||
BrowserPreviewThreadContextUnavailableError,
|
||||
} from "../browser/openFileInPreview";
|
||||
|
||||
class CodeHighlightErrorBoundary extends React.Component<
|
||||
@@ -1060,11 +1061,15 @@ const MarkdownFileLink = memo(function MarkdownFileLink({
|
||||
const error = squashAtomCommandFailure(result);
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Unable to open file in browser",
|
||||
description: error instanceof Error ? error.message : "An error occurred.",
|
||||
type: "warning",
|
||||
title: "Unable to open file preview",
|
||||
description:
|
||||
error instanceof Error
|
||||
? `${error.message} Opening the file instead.`
|
||||
: "Opening the file instead.",
|
||||
}),
|
||||
);
|
||||
handleOpenInFilePreview();
|
||||
} catch (cause) {
|
||||
reportMarkdownActionFailure(
|
||||
{ operation: "open-file-in-browser", target: targetPath },
|
||||
@@ -1072,14 +1077,18 @@ const MarkdownFileLink = memo(function MarkdownFileLink({
|
||||
);
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Unable to open file in browser",
|
||||
description: cause instanceof Error ? cause.message : "An error occurred.",
|
||||
type: "warning",
|
||||
title: "Unable to open file preview",
|
||||
description:
|
||||
cause instanceof Error
|
||||
? `${cause.message} Opening the file instead.`
|
||||
: "Opening the file instead.",
|
||||
}),
|
||||
);
|
||||
handleOpenInFilePreview();
|
||||
}
|
||||
})();
|
||||
}, [onOpenInBrowser, targetPath]);
|
||||
}, [handleOpenInFilePreview, onOpenInBrowser, targetPath]);
|
||||
|
||||
const handleCopy = useCallback(
|
||||
(value: string, title: string) => {
|
||||
@@ -1284,12 +1293,8 @@ function ChatMarkdown({
|
||||
(url: string) => {
|
||||
if (!threadRef) {
|
||||
return Promise.resolve(
|
||||
AsyncResult.failure<void, BrowserPreviewUnavailableError>(
|
||||
Cause.fail(
|
||||
new BrowserPreviewUnavailableError({
|
||||
message: "Thread context is unavailable.",
|
||||
}),
|
||||
),
|
||||
AsyncResult.failure<void, BrowserPreviewThreadContextUnavailableError>(
|
||||
Cause.fail(new BrowserPreviewThreadContextUnavailableError()),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -1299,12 +1304,20 @@ function ChatMarkdown({
|
||||
);
|
||||
const openMarkdownFileInPreview = useCallback(
|
||||
(path: string) => {
|
||||
if (!threadRef || preparedConnection._tag === "None") {
|
||||
if (!threadRef) {
|
||||
return Promise.resolve(
|
||||
AsyncResult.failure<void, BrowserPreviewUnavailableError>(
|
||||
AsyncResult.failure<void, BrowserPreviewThreadContextUnavailableError>(
|
||||
Cause.fail(new BrowserPreviewThreadContextUnavailableError()),
|
||||
),
|
||||
);
|
||||
}
|
||||
if (preparedConnection._tag === "None") {
|
||||
return Promise.resolve(
|
||||
AsyncResult.failure<void, BrowserPreviewEnvironmentDisconnectedError>(
|
||||
Cause.fail(
|
||||
new BrowserPreviewUnavailableError({
|
||||
message: "Environment is not connected.",
|
||||
new BrowserPreviewEnvironmentDisconnectedError({
|
||||
environmentId: threadRef.environmentId,
|
||||
threadId: threadRef.threadId,
|
||||
}),
|
||||
),
|
||||
),
|
||||
@@ -1468,9 +1481,10 @@ function ChatMarkdown({
|
||||
threadRef={threadRef}
|
||||
onOpen={openInPreferredEditor}
|
||||
onOpenInBrowser={
|
||||
fileLinkMeta.workspaceRelativePath !== null &&
|
||||
threadRef &&
|
||||
isPreviewSupportedInRuntime() &&
|
||||
isBrowserPreviewFile(fileLinkMeta.filePath)
|
||||
isWorkspacePreviewFile(fileLinkMeta.filePath)
|
||||
? () => openMarkdownFileInPreview(fileLinkMeta.filePath)
|
||||
: undefined
|
||||
}
|
||||
|
||||
@@ -110,6 +110,8 @@ import {
|
||||
type RightPanelSurface,
|
||||
useRightPanelStore,
|
||||
} from "../rightPanelStore";
|
||||
import { isImagePreviewFile, openFileInPreview } from "../browser/openFileInPreview";
|
||||
import { resolvePathLinkTarget } from "../terminal-links";
|
||||
import {
|
||||
isPreviewSupportedInRuntime,
|
||||
setActivePreviewTab,
|
||||
@@ -179,7 +181,12 @@ import {
|
||||
import { terminalEnvironment } from "../state/terminal";
|
||||
import { threadEnvironment } from "../state/threads";
|
||||
import { vcsEnvironment } from "../state/vcs";
|
||||
import { useEnvironments, usePrimaryEnvironment } from "../state/environments";
|
||||
import {
|
||||
useEnvironmentHttpBaseUrl,
|
||||
useEnvironments,
|
||||
usePrimaryEnvironment,
|
||||
} from "../state/environments";
|
||||
import { assetEnvironment } from "../state/assets";
|
||||
import {
|
||||
useProject,
|
||||
useProjects,
|
||||
@@ -228,6 +235,7 @@ 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,
|
||||
@@ -1012,6 +1020,10 @@ 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();
|
||||
@@ -1339,6 +1351,9 @@ 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,
|
||||
);
|
||||
@@ -2737,12 +2752,70 @@ 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;
|
||||
useRightPanelStore.getState().openFile(activeThreadRef, relativePath);
|
||||
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();
|
||||
})();
|
||||
},
|
||||
[activeProject, activeThreadRef],
|
||||
[
|
||||
activeEnvironmentHttpBaseUrl,
|
||||
activeProject,
|
||||
activeThreadRef,
|
||||
activeWorkspaceRoot,
|
||||
createAssetUrl,
|
||||
openPreview,
|
||||
],
|
||||
);
|
||||
const togglePreviewPanel = useCallback(() => {
|
||||
if (!activeThreadRef || !isPreviewSupportedInRuntime()) return;
|
||||
|
||||
@@ -21,6 +21,9 @@ 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";
|
||||
@@ -61,10 +64,16 @@ 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";
|
||||
@@ -213,6 +222,12 @@ 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),
|
||||
);
|
||||
@@ -443,32 +458,92 @@ 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) => {
|
||||
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)),
|
||||
});
|
||||
}
|
||||
})();
|
||||
},
|
||||
});
|
||||
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();
|
||||
})();
|
||||
},
|
||||
[activeCwd, openInPreferredEditor, routeThreadRef],
|
||||
[
|
||||
activeCwd,
|
||||
createAssetUrl,
|
||||
environmentHttpBaseUrl,
|
||||
openInPreferredEditor,
|
||||
openPreview,
|
||||
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 { isBrowserPreviewFile, openFileInPreview } from "~/browser/openFileInPreview";
|
||||
import { isWorkspacePreviewFile, 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 canOpenInBrowser =
|
||||
relativePath !== null && isPreviewSupportedInRuntime() && isBrowserPreviewFile(relativePath);
|
||||
const canOpenInPreview =
|
||||
relativePath !== null && isPreviewSupportedInRuntime() && isWorkspacePreviewFile(relativePath);
|
||||
const absolutePath = relativePath ? resolvePathLinkTarget(relativePath, cwd) : null;
|
||||
const breadcrumbs = useMemo(
|
||||
() => (relativePath ? fileBreadcrumbs(projectName, relativePath) : []),
|
||||
@@ -661,7 +661,7 @@ export default function FilePreviewPanel({
|
||||
});
|
||||
};
|
||||
|
||||
const handleOpenInBrowser = useCallback(() => {
|
||||
const handleOpenInPreview = 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 browser",
|
||||
title: "Unable to open file in preview",
|
||||
description: error instanceof Error ? error.message : "An error occurred.",
|
||||
}),
|
||||
);
|
||||
@@ -757,15 +757,15 @@ export default function FilePreviewPanel({
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
) : null}
|
||||
{canOpenInBrowser ? (
|
||||
{canOpenInPreview ? (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Toggle
|
||||
className="shrink-0"
|
||||
pressed={false}
|
||||
onPressedChange={handleOpenInBrowser}
|
||||
aria-label="Open file in preview browser"
|
||||
onPressedChange={handleOpenInPreview}
|
||||
aria-label="Open file in preview"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
>
|
||||
@@ -773,7 +773,7 @@ export default function FilePreviewPanel({
|
||||
</Toggle>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup>Open file in preview browser</TooltipPopup>
|
||||
<TooltipPopup>Open file in preview</TooltipPopup>
|
||||
</Tooltip>
|
||||
) : null}
|
||||
<Tooltip>
|
||||
|
||||
@@ -70,10 +70,7 @@ describe("makeCatalogBackend", () => {
|
||||
const error = yield* backend.write("{}").pipe(Effect.flip);
|
||||
|
||||
expect(error).toBeInstanceOf(ConnectionTransientError);
|
||||
expect(error.message).toBe("Could not save the local connection catalog.");
|
||||
expect(error.cause).toEqual(
|
||||
new Error("Desktop secure storage is unavailable in this system context."),
|
||||
);
|
||||
expect(error.message).toContain("Desktop secure storage is unavailable");
|
||||
expect(setConnectionCatalog).toHaveBeenCalledWith("{}");
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -63,8 +63,26 @@ const encodeStoredThreadSnapshot = Schema.encodeEffect(StoredThreadSnapshotJson)
|
||||
function catalogError(operation: string, cause: unknown) {
|
||||
return new ConnectionTransientError({
|
||||
reason: "remote-unavailable",
|
||||
detail: `Could not ${operation} the local connection catalog.`,
|
||||
cause,
|
||||
detail: `Could not ${operation} the local connection catalog: ${String(cause)}`,
|
||||
});
|
||||
}
|
||||
|
||||
function persistenceError(
|
||||
operation:
|
||||
| "list-targets"
|
||||
| "register-connection"
|
||||
| "remove-connection"
|
||||
| "load-shell"
|
||||
| "save-shell"
|
||||
| "load-thread"
|
||||
| "save-thread"
|
||||
| "remove-thread"
|
||||
| "clear-environment",
|
||||
cause: unknown,
|
||||
) {
|
||||
return new ConnectionPersistenceError({
|
||||
operation,
|
||||
message: `Could not ${operation.replaceAll("-", " ")}: ${String(cause)}`,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -215,7 +233,7 @@ export function makeCatalogBackend(database: IDBDatabase): CatalogBackend {
|
||||
: Effect.fail(
|
||||
catalogError(
|
||||
"save",
|
||||
new Error("Desktop secure storage is unavailable in this system context."),
|
||||
"Desktop secure storage is unavailable in this system context.",
|
||||
),
|
||||
),
|
||||
),
|
||||
@@ -312,29 +330,18 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
const targetStore = ConnectionTargetStore.of({
|
||||
list: catalog.read.pipe(
|
||||
Effect.map((document) => document.targets),
|
||||
Effect.mapError(
|
||||
(cause) => new ConnectionPersistenceError({ operation: "list-targets", cause }),
|
||||
),
|
||||
Effect.mapError((cause) => persistenceError("list-targets", cause)),
|
||||
),
|
||||
});
|
||||
const registrationStore = ConnectionRegistrationStore.of({
|
||||
register: (registration) =>
|
||||
catalog
|
||||
.update((document) => registerConnectionInCatalog(document, registration))
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ConnectionPersistenceError({ operation: "register-connection", cause }),
|
||||
),
|
||||
),
|
||||
.pipe(Effect.mapError((cause) => persistenceError("register-connection", cause))),
|
||||
remove: (target) =>
|
||||
catalog
|
||||
.update((document) => removeConnectionFromCatalog(document, target))
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new ConnectionPersistenceError({ operation: "remove-connection", cause }),
|
||||
),
|
||||
),
|
||||
.pipe(Effect.mapError((cause) => persistenceError("remove-connection", cause))),
|
||||
});
|
||||
const profileStore = ProfileStore.make({
|
||||
get: (connectionId) =>
|
||||
@@ -423,9 +430,7 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
return Effect.succeed(Option.none());
|
||||
}
|
||||
return decodeStoredShellSnapshot(raw).pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new ConnectionPersistenceError({ operation: "load-shell", cause }),
|
||||
),
|
||||
Effect.mapError((cause) => persistenceError("load-shell", cause)),
|
||||
Effect.map((stored) =>
|
||||
stored.environmentId === environmentId
|
||||
? Option.some(stored.snapshot)
|
||||
@@ -436,7 +441,7 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
Effect.mapError((cause) =>
|
||||
cause._tag === "ConnectionPersistenceError"
|
||||
? cause
|
||||
: new ConnectionPersistenceError({ operation: "load-shell", cause }),
|
||||
: persistenceError("load-shell", cause),
|
||||
),
|
||||
),
|
||||
saveShell: (environmentId, snapshot) =>
|
||||
@@ -445,17 +450,13 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
schemaVersion: SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION,
|
||||
environmentId,
|
||||
snapshot,
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new ConnectionPersistenceError({ operation: "save-shell", cause }),
|
||||
),
|
||||
);
|
||||
}).pipe(Effect.mapError((cause) => persistenceError("save-shell", cause)));
|
||||
yield* writeDatabaseValue(database, SHELL_STORE_NAME, environmentId, encoded);
|
||||
}).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
cause._tag === "ConnectionPersistenceError"
|
||||
? cause
|
||||
: new ConnectionPersistenceError({ operation: "save-shell", cause }),
|
||||
: persistenceError("save-shell", cause),
|
||||
),
|
||||
),
|
||||
loadThread: (environmentId, threadId) =>
|
||||
@@ -469,9 +470,7 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
return Effect.succeed(Option.none());
|
||||
}
|
||||
return decodeStoredThreadSnapshot(raw).pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new ConnectionPersistenceError({ operation: "load-thread", cause }),
|
||||
),
|
||||
Effect.mapError((cause) => persistenceError("load-thread", cause)),
|
||||
Effect.map((stored) =>
|
||||
stored.environmentId === environmentId && stored.threadId === threadId
|
||||
? Option.some(stored.thread)
|
||||
@@ -482,7 +481,7 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
Effect.mapError((cause) =>
|
||||
cause._tag === "ConnectionPersistenceError"
|
||||
? cause
|
||||
: new ConnectionPersistenceError({ operation: "load-thread", cause }),
|
||||
: persistenceError("load-thread", cause),
|
||||
),
|
||||
),
|
||||
saveThread: (environmentId, thread) =>
|
||||
@@ -492,11 +491,7 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
environmentId,
|
||||
threadId: thread.id,
|
||||
thread,
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new ConnectionPersistenceError({ operation: "save-thread", cause }),
|
||||
),
|
||||
);
|
||||
}).pipe(Effect.mapError((cause) => persistenceError("save-thread", cause)));
|
||||
yield* writeDatabaseValue(
|
||||
database,
|
||||
THREAD_STORE_NAME,
|
||||
@@ -507,7 +502,7 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
Effect.mapError((cause) =>
|
||||
cause._tag === "ConnectionPersistenceError"
|
||||
? cause
|
||||
: new ConnectionPersistenceError({ operation: "save-thread", cause }),
|
||||
: persistenceError("save-thread", cause),
|
||||
),
|
||||
),
|
||||
removeThread: (environmentId, threadId) =>
|
||||
@@ -515,11 +510,7 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
database,
|
||||
THREAD_STORE_NAME,
|
||||
threadCacheKey(environmentId, threadId),
|
||||
).pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new ConnectionPersistenceError({ operation: "remove-thread", cause }),
|
||||
),
|
||||
),
|
||||
).pipe(Effect.mapError((cause) => persistenceError("remove-thread", cause))),
|
||||
clear: (environmentId) =>
|
||||
Effect.all(
|
||||
[
|
||||
@@ -531,11 +522,7 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
),
|
||||
],
|
||||
{ concurrency: "unbounded", discard: true },
|
||||
).pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new ConnectionPersistenceError({ operation: "clear-environment", cause }),
|
||||
),
|
||||
),
|
||||
).pipe(Effect.mapError((cause) => persistenceError("clear-environment", cause))),
|
||||
});
|
||||
|
||||
return Context.make(ConnectionTargetStore, targetStore).pipe(
|
||||
|
||||
@@ -81,7 +81,6 @@ export class ConnectionTransientError extends Schema.TaggedErrorClass<Connection
|
||||
reason: ConnectionTransientReason,
|
||||
detail: Schema.String,
|
||||
traceId: Schema.optionalKey(Schema.String),
|
||||
cause: Schema.optionalKey(Schema.Defect()),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
|
||||
@@ -689,13 +689,12 @@ describe("EnvironmentRegistry", () => {
|
||||
|
||||
it.effect("keeps the runtime registered when durable removal fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const persistenceCause = new Error("Storage is unavailable.");
|
||||
const harness = yield* makeHarness([RELAY_TARGET], [], [], {
|
||||
beforeRegistrationRemove: () =>
|
||||
Effect.fail(
|
||||
new Persistence.ConnectionPersistenceError({
|
||||
operation: "remove-connection",
|
||||
cause: persistenceCause,
|
||||
message: "Storage is unavailable.",
|
||||
}),
|
||||
),
|
||||
});
|
||||
@@ -712,8 +711,6 @@ describe("EnvironmentRegistry", () => {
|
||||
const error = yield* Effect.flip(registry.removeRelayEnvironments());
|
||||
|
||||
expect(error._tag).toBe("ConnectionPersistenceError");
|
||||
expect(error.message).toBe("Could not remove connection.");
|
||||
expect(error.cause).toBe(persistenceCause);
|
||||
expect(yield* Ref.get(harness.releasedSessions)).toBe(0);
|
||||
expect((yield* SubscriptionRef.get(registry.entries)).has(RELAY_TARGET.environmentId)).toBe(
|
||||
true,
|
||||
|
||||
@@ -26,13 +26,9 @@ export class ConnectionPersistenceError extends Schema.TaggedErrorClass<Connecti
|
||||
"remove-thread",
|
||||
"clear-environment",
|
||||
]),
|
||||
cause: Schema.Defect(),
|
||||
message: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Could not ${this.operation.replaceAll("-", " ")}.`;
|
||||
}
|
||||
}
|
||||
) {}
|
||||
|
||||
export class ConnectionTargetStore extends Context.Service<
|
||||
ConnectionTargetStore,
|
||||
|
||||
@@ -453,8 +453,18 @@ export type PreviewAutomationResponse = typeof PreviewAutomationResponse.Type;
|
||||
|
||||
export class PreviewAutomationUnavailableError extends Schema.TaggedErrorClass<PreviewAutomationUnavailableError>()(
|
||||
"PreviewAutomationUnavailableError",
|
||||
{ message: Schema.String },
|
||||
) {}
|
||||
{
|
||||
capability: Schema.Literal("preview"),
|
||||
environmentId: EnvironmentId,
|
||||
threadId: ThreadId,
|
||||
providerSessionId: TrimmedNonEmptyString,
|
||||
providerInstanceId: ProviderInstanceId,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `MCP credential does not grant the ${this.capability} capability.`;
|
||||
}
|
||||
}
|
||||
|
||||
const PreviewAutomationScopeErrorFields = {
|
||||
operation: PreviewAutomationOperation,
|
||||
|
||||
@@ -82,6 +82,11 @@ const payloadKind = (payload: unknown): CodexAppServerPayloadKind => {
|
||||
return typeof payload;
|
||||
};
|
||||
|
||||
const protocolMessageFields = ["id", "method", "params", "result", "error"] as const;
|
||||
|
||||
export const CodexAppServerProtocolMessageField = Schema.Literals(protocolMessageFields);
|
||||
export type CodexAppServerProtocolMessageField = typeof CodexAppServerProtocolMessageField.Type;
|
||||
|
||||
export interface CodexAppServerRequestDiagnostics {
|
||||
readonly method?: string;
|
||||
readonly requestId?: string;
|
||||
@@ -157,7 +162,8 @@ export class CodexAppServerProtocolParseError extends Schema.TaggedErrorClass<Co
|
||||
operation: CodexAppServerProtocolParseOperation,
|
||||
method: Schema.optionalKey(Schema.String),
|
||||
requestId: Schema.optionalKey(Schema.String),
|
||||
detail: Schema.optionalKey(Schema.String),
|
||||
payloadKind: Schema.optionalKey(CodexAppServerPayloadKind),
|
||||
presentFields: Schema.optionalKey(Schema.Array(CodexAppServerProtocolMessageField)),
|
||||
issueCount: Schema.optionalKey(Schema.Number),
|
||||
issueKinds: Schema.optionalKey(Schema.Array(CodexAppServerSchemaIssueKind)),
|
||||
maximumPathDepth: Schema.optionalKey(Schema.Number),
|
||||
@@ -196,6 +202,31 @@ export class CodexAppServerProtocolParseError extends Schema.TaggedErrorClass<Co
|
||||
cause,
|
||||
});
|
||||
}
|
||||
|
||||
static fromUnroutableMessage(message: unknown) {
|
||||
const diagnostics = { payloadKind: payloadKind(message) };
|
||||
if (typeof message !== "object" || message === null || Array.isArray(message)) {
|
||||
return new CodexAppServerProtocolParseError({
|
||||
operation: "route-wire-message",
|
||||
...diagnostics,
|
||||
});
|
||||
}
|
||||
|
||||
const presentFields = protocolMessageFields.filter((field) => field in message);
|
||||
const method =
|
||||
"method" in message && typeof message.method === "string" ? message.method : undefined;
|
||||
const requestId =
|
||||
"id" in message && (typeof message.id === "string" || typeof message.id === "number")
|
||||
? String(message.id)
|
||||
: undefined;
|
||||
return new CodexAppServerProtocolParseError({
|
||||
operation: "route-wire-message",
|
||||
...diagnostics,
|
||||
presentFields,
|
||||
...(method === undefined ? {} : { method }),
|
||||
...(requestId === undefined ? {} : { requestId }),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export class CodexAppServerTransportError extends Schema.TaggedErrorClass<CodexAppServerTransportError>()(
|
||||
|
||||
@@ -311,6 +311,36 @@ it.layer(NodeServices.layer)("effect-codex-app-server protocol", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("describes unroutable messages with safe structural diagnostics", () =>
|
||||
Effect.gen(function* () {
|
||||
const secret = "codex-unroutable-secret-sentinel";
|
||||
const { stdio, input } = yield* makeInMemoryStdio();
|
||||
const termination = yield* Deferred.make<CodexError.CodexAppServerError>();
|
||||
yield* CodexProtocol.makeCodexAppServerPatchedProtocol({
|
||||
stdio,
|
||||
onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
|
||||
});
|
||||
|
||||
yield* Queue.offer(
|
||||
input,
|
||||
encodeJsonl({ id: true, method: "thread/start", params: { token: secret } }),
|
||||
);
|
||||
|
||||
const error = yield* Deferred.await(termination);
|
||||
assert.instanceOf(error, CodexError.CodexAppServerProtocolParseError);
|
||||
assert.deepInclude(error, {
|
||||
operation: "route-wire-message",
|
||||
method: "thread/start",
|
||||
payloadKind: "object",
|
||||
presentFields: ["id", "method", "params"],
|
||||
});
|
||||
assert.isUndefined(error.requestId);
|
||||
assert.notProperty(error, "detail");
|
||||
assert.notProperty(error, "cause");
|
||||
assert.notInclude(error.message, secret);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("classifies an input stream ending without inventing a cause", () =>
|
||||
Effect.gen(function* () {
|
||||
const { stdio, input } = yield* makeInMemoryStdio();
|
||||
|
||||
@@ -310,10 +310,7 @@ export const makeCodexAppServerPatchedProtocol = Effect.fn("makeCodexAppServerPa
|
||||
return handleResponse(message);
|
||||
}
|
||||
return Effect.fail(
|
||||
new CodexError.CodexAppServerProtocolParseError({
|
||||
detail: "Received protocol message in an unknown shape",
|
||||
operation: "route-wire-message",
|
||||
}),
|
||||
CodexError.CodexAppServerProtocolParseError.fromUnroutableMessage(message),
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
@@ -9,15 +9,17 @@ import * as Stream from "effect/Stream";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import {
|
||||
BuildScriptError,
|
||||
BuildCommandFailedError,
|
||||
createStageWorkspaceConfig,
|
||||
createStagePnpmConfig,
|
||||
createBuildConfig,
|
||||
DESKTOP_ASAR_UNPACK,
|
||||
InvalidMacPasskeyRpDomainError,
|
||||
InvalidMacPasskeyPublishableKeyError,
|
||||
InvalidMockUpdateServerPortError,
|
||||
isMacPasskeySigningConfigurationError,
|
||||
LinuxIconResizeError,
|
||||
MacPasskeySigningConfigurationResolutionError,
|
||||
MissingMacPasskeyProvisioningProfileError,
|
||||
renderMacPasskeyEntitlements,
|
||||
resolveClerkPasskeyNativeArtifacts,
|
||||
@@ -249,10 +251,16 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {
|
||||
const aggregateCause = error.cause as AggregateError;
|
||||
assert.lengthOf(aggregateCause.errors, 2);
|
||||
assert.strictEqual(aggregateCause.cause, aggregateCause.errors[0]);
|
||||
assert.instanceOf(aggregateCause.errors[0], BuildScriptError);
|
||||
assert.instanceOf(aggregateCause.errors[1], BuildScriptError);
|
||||
assert.include((aggregateCause.errors[0] as BuildScriptError).message, "magick linux icon");
|
||||
assert.include((aggregateCause.errors[1] as BuildScriptError).message, "convert linux icon");
|
||||
assert.instanceOf(aggregateCause.errors[0], BuildCommandFailedError);
|
||||
assert.instanceOf(aggregateCause.errors[1], BuildCommandFailedError);
|
||||
const primaryError = aggregateCause.errors[0] as BuildCommandFailedError;
|
||||
const fallbackError = aggregateCause.errors[1] as BuildCommandFailedError;
|
||||
assert.equal(primaryError.command, "magick linux icon 512x512");
|
||||
assert.equal(primaryError.exitCode, 1);
|
||||
assert.include(primaryError.message, "magick linux icon");
|
||||
assert.equal(fallbackError.command, "convert linux icon 512x512");
|
||||
assert.equal(fallbackError.exitCode, 2);
|
||||
assert.include(fallbackError.message, "convert linux icon");
|
||||
assert.deepStrictEqual(
|
||||
commands.map(({ command }) => command),
|
||||
["magick", "convert"],
|
||||
@@ -356,7 +364,7 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {
|
||||
it("preserves known passkey signing configuration errors at the build boundary", () => {
|
||||
const decodingCause = new Error("publishable-key-decode-failed");
|
||||
const knownError = new InvalidMacPasskeyPublishableKeyError({ cause: decodingCause });
|
||||
const error = BuildScriptError.fromMacPasskeySigningConfiguration(knownError);
|
||||
const error = MacPasskeySigningConfigurationResolutionError.fromCause(knownError);
|
||||
|
||||
assert.strictEqual(error, knownError);
|
||||
assert.instanceOf(error, InvalidMacPasskeyPublishableKeyError);
|
||||
@@ -367,9 +375,9 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {
|
||||
it("wraps unknown passkey signing configuration defects without copying cause text", () => {
|
||||
const secret = "pk_test_do-not-retain";
|
||||
const cause = new Error(secret);
|
||||
const error = BuildScriptError.fromMacPasskeySigningConfiguration(cause);
|
||||
const error = MacPasskeySigningConfigurationResolutionError.fromCause(cause);
|
||||
|
||||
assert.instanceOf(error, BuildScriptError);
|
||||
assert.instanceOf(error, MacPasskeySigningConfigurationResolutionError);
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.equal(error.message, "Failed to resolve macOS passkey signing configuration.");
|
||||
assert.notInclude(error.message, secret);
|
||||
@@ -453,6 +461,27 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it("classifies invalid configured ports with the decoder's number grammar", () => {
|
||||
const cause = new Error("invalid configured port");
|
||||
|
||||
assert.equal(
|
||||
InvalidMockUpdateServerPortError.fromConfigValue("0x10", cause).reason,
|
||||
"not-numeric",
|
||||
);
|
||||
assert.equal(
|
||||
InvalidMockUpdateServerPortError.fromConfigValue("12.5", cause).reason,
|
||||
"not-integer",
|
||||
);
|
||||
assert.equal(
|
||||
InvalidMockUpdateServerPortError.fromConfigValue("65536", cause).reason,
|
||||
"out-of-range",
|
||||
);
|
||||
assert.strictEqual(
|
||||
InvalidMockUpdateServerPortError.fromConfigValue("0x10", cause).cause,
|
||||
cause,
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("resolves default platform and architecture from host references", () =>
|
||||
Effect.gen(function* () {
|
||||
const resolved = yield* resolveBuildOptions({
|
||||
|
||||
@@ -18,7 +18,6 @@ import { resolveCatalogDependencies } from "./lib/resolve-catalog.ts";
|
||||
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import * as Config from "effect/Config";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
@@ -126,19 +125,238 @@ const getDefaultArch = Effect.fn("getDefaultArch")(function* (platform: typeof B
|
||||
return yield* getDefaultBuildArch(platform, config);
|
||||
});
|
||||
|
||||
export class BuildScriptError extends Data.TaggedError("BuildScriptError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
}> {
|
||||
static fromMacPasskeySigningConfiguration(
|
||||
export class MacPasskeySigningConfigurationResolutionError extends Schema.TaggedErrorClass<MacPasskeySigningConfigurationResolutionError>()(
|
||||
"MacPasskeySigningConfigurationResolutionError",
|
||||
{
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
static fromCause(
|
||||
cause: unknown,
|
||||
): MacPasskeySigningConfigurationError | BuildScriptError {
|
||||
): MacPasskeySigningConfigurationError | MacPasskeySigningConfigurationResolutionError {
|
||||
return isMacPasskeySigningConfigurationError(cause)
|
||||
? cause
|
||||
: new BuildScriptError({
|
||||
message: "Failed to resolve macOS passkey signing configuration.",
|
||||
cause,
|
||||
});
|
||||
: new MacPasskeySigningConfigurationResolutionError({ cause });
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return "Failed to resolve macOS passkey signing configuration.";
|
||||
}
|
||||
}
|
||||
|
||||
export class ClerkPasskeyNativePackageMissingError extends Schema.TaggedErrorClass<ClerkPasskeyNativePackageMissingError>()(
|
||||
"ClerkPasskeyNativePackageMissingError",
|
||||
{
|
||||
packageName: Schema.String,
|
||||
binaryFileName: Schema.String,
|
||||
packageEntryPath: Schema.String,
|
||||
platform: BuildPlatform,
|
||||
arch: BuildArch,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Clerk passkey native package is missing: ${this.packageName}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class UnsupportedHostBuildPlatformError extends Schema.TaggedErrorClass<UnsupportedHostBuildPlatformError>()(
|
||||
"UnsupportedHostBuildPlatformError",
|
||||
{
|
||||
hostPlatform: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Unsupported host platform '${this.hostPlatform}'.`;
|
||||
}
|
||||
}
|
||||
|
||||
const InvalidMockUpdateServerPortReason = Schema.Literals([
|
||||
"not-numeric",
|
||||
"not-integer",
|
||||
"out-of-range",
|
||||
]);
|
||||
|
||||
export class InvalidMockUpdateServerPortError extends Schema.TaggedErrorClass<InvalidMockUpdateServerPortError>()(
|
||||
"InvalidMockUpdateServerPortError",
|
||||
{
|
||||
reason: InvalidMockUpdateServerPortReason,
|
||||
inputLength: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Invalid mock update server port.";
|
||||
}
|
||||
|
||||
static fromConfigValue(configuredPort: string, cause: unknown) {
|
||||
return new InvalidMockUpdateServerPortError({
|
||||
reason: invalidMockUpdateServerPortReason(configuredPort),
|
||||
inputLength: configuredPort.length,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export class BuildCommandFailedError extends Schema.TaggedErrorClass<BuildCommandFailedError>()(
|
||||
"BuildCommandFailedError",
|
||||
{
|
||||
command: Schema.String,
|
||||
exitCode: Schema.Int,
|
||||
stdoutTail: Schema.optionalKey(Schema.String),
|
||||
stderrTail: Schema.optionalKey(Schema.String),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
const outputSections = [
|
||||
`Command: ${this.command}`,
|
||||
formatOutputSection("stdout", this.stdoutTail ?? ""),
|
||||
formatOutputSection("stderr", this.stderrTail ?? ""),
|
||||
].filter((section): section is string => section !== undefined);
|
||||
const outputSuffix = outputSections.length > 0 ? `\n\n${outputSections.join("\n\n")}` : "";
|
||||
return `Command exited with non-zero exit code (${this.exitCode})${outputSuffix}`;
|
||||
}
|
||||
}
|
||||
|
||||
const desktopIconPlatformNames = {
|
||||
mac: "macOS",
|
||||
linux: "Linux",
|
||||
win: "Windows",
|
||||
} satisfies Record<typeof BuildPlatform.Type, string>;
|
||||
|
||||
export class DesktopIconSourceMissingError extends Schema.TaggedErrorClass<DesktopIconSourceMissingError>()(
|
||||
"DesktopIconSourceMissingError",
|
||||
{
|
||||
platform: BuildPlatform,
|
||||
sourcePath: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Desktop ${desktopIconPlatformNames[this.platform]} icon source is missing at ${this.sourcePath}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class BundledClientAssetsMissingError extends Schema.TaggedErrorClass<BundledClientAssetsMissingError>()(
|
||||
"BundledClientAssetsMissingError",
|
||||
{
|
||||
indexPath: Schema.String,
|
||||
missingFiles: Schema.Array(Schema.String),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
const preview = this.missingFiles.slice(0, 6).join(", ");
|
||||
const suffix = this.missingFiles.length > 6 ? ` (+${this.missingFiles.length - 6} more)` : "";
|
||||
return `Bundled client references missing files in ${this.indexPath}: ${preview}${suffix}. Rebuild web/server artifacts.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class UnsupportedDesktopBuildPlatformError extends Schema.TaggedErrorClass<UnsupportedDesktopBuildPlatformError>()(
|
||||
"UnsupportedDesktopBuildPlatformError",
|
||||
{
|
||||
platform: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Unsupported platform '${this.platform}'.`;
|
||||
}
|
||||
}
|
||||
|
||||
const dependencyResolutionDescriptions = {
|
||||
"server-production": "production dependencies",
|
||||
"workspace-overrides": "overrides",
|
||||
"desktop-runtime": "desktop runtime dependencies",
|
||||
} as const;
|
||||
const DependencyResolutionKind = Schema.Literals([
|
||||
"server-production",
|
||||
"workspace-overrides",
|
||||
"desktop-runtime",
|
||||
]);
|
||||
|
||||
export class DesktopBuildDependencyResolutionError extends Schema.TaggedErrorClass<DesktopBuildDependencyResolutionError>()(
|
||||
"DesktopBuildDependencyResolutionError",
|
||||
{
|
||||
kind: DependencyResolutionKind,
|
||||
manifestPath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Could not resolve ${dependencyResolutionDescriptions[this.kind]} from ${this.manifestPath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class MissingServerProductionDependenciesError extends Schema.TaggedErrorClass<MissingServerProductionDependenciesError>()(
|
||||
"MissingServerProductionDependenciesError",
|
||||
{
|
||||
manifestPath: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Could not resolve production dependencies from ${this.manifestPath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
const DesktopBuildInputArtifact = Schema.Literals([
|
||||
"desktop-dist",
|
||||
"desktop-resources",
|
||||
"server-dist",
|
||||
"bundled-server-client",
|
||||
]);
|
||||
type DesktopBuildInputArtifact = typeof DesktopBuildInputArtifact.Type;
|
||||
const desktopBuildInputArtifactNames = {
|
||||
"desktop-dist": "desktopDist",
|
||||
"desktop-resources": "desktopResources",
|
||||
"server-dist": "serverDist",
|
||||
"bundled-server-client": "bundled server client",
|
||||
} satisfies Record<DesktopBuildInputArtifact, string>;
|
||||
|
||||
export class MissingDesktopBuildInputError extends Schema.TaggedErrorClass<MissingDesktopBuildInputError>()(
|
||||
"MissingDesktopBuildInputError",
|
||||
{
|
||||
artifact: DesktopBuildInputArtifact,
|
||||
artifactPath: Schema.String,
|
||||
buildCommand: Schema.Literal("vp run build:desktop"),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Missing ${desktopBuildInputArtifactNames[this.artifact]} at ${this.artifactPath}. Run '${this.buildCommand}' first.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class MacProvisioningProfileNotFoundError extends Schema.TaggedErrorClass<MacProvisioningProfileNotFoundError>()(
|
||||
"MacProvisioningProfileNotFoundError",
|
||||
{
|
||||
provisioningProfilePath: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `macOS provisioning profile not found: ${this.provisioningProfilePath}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopBuildDistDirectoryMissingError extends Schema.TaggedErrorClass<DesktopBuildDistDirectoryMissingError>()(
|
||||
"DesktopBuildDistDirectoryMissingError",
|
||||
{
|
||||
distPath: Schema.String,
|
||||
platform: BuildPlatform,
|
||||
arch: BuildArch,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Build completed but dist directory was not found at ${this.distPath}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopBuildNoArtifactsProducedError extends Schema.TaggedErrorClass<DesktopBuildNoArtifactsProducedError>()(
|
||||
"DesktopBuildNoArtifactsProducedError",
|
||||
{
|
||||
distPath: Schema.String,
|
||||
platform: BuildPlatform,
|
||||
arch: BuildArch,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Build completed but no files were produced in ${this.distPath}`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -616,8 +834,12 @@ const stageClerkPasskeyNativeBinaries = Effect.fn("stageClerkPasskeyNativeBinari
|
||||
const sourcePath = yield* Effect.try({
|
||||
try: () => packageRequire.resolve(artifact.packageName),
|
||||
catch: (cause) =>
|
||||
new BuildScriptError({
|
||||
message: `Clerk passkey native package is missing: ${artifact.packageName}`,
|
||||
new ClerkPasskeyNativePackageMissingError({
|
||||
packageName: artifact.packageName,
|
||||
binaryFileName: artifact.binaryFileName,
|
||||
packageEntryPath,
|
||||
platform,
|
||||
arch,
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
@@ -691,6 +913,18 @@ const MockUpdateServerPortSchema = Schema.NumberFromString.check(
|
||||
);
|
||||
const decodeMockUpdateServerPort = Schema.decodeUnknownEffect(MockUpdateServerPortSchema);
|
||||
|
||||
function invalidMockUpdateServerPortReason(
|
||||
configuredPort: string,
|
||||
): typeof InvalidMockUpdateServerPortReason.Type {
|
||||
const parsed = Number(configuredPort);
|
||||
if (!Number.isFinite(parsed)) return "not-numeric";
|
||||
if (!Number.isInteger(parsed)) return "not-integer";
|
||||
if (parsed < 1 || parsed > 65535) return "out-of-range";
|
||||
// This mapper is only called after schema decoding failed. An otherwise
|
||||
// valid integer therefore used a representation the decoder did not accept.
|
||||
return "not-numeric";
|
||||
}
|
||||
|
||||
const resolveBooleanFlag = (flag: Option.Option<boolean>, envValue: boolean) =>
|
||||
Option.getOrElse(flag, () => envValue);
|
||||
const mergeOptions = <A>(a: Option.Option<A>, b: Option.Option<A>, defaultValue: A) =>
|
||||
@@ -722,9 +956,7 @@ export const resolveBuildOptions = Effect.fn("resolveBuildOptions")(function* (
|
||||
);
|
||||
|
||||
if (!platform) {
|
||||
return yield* new BuildScriptError({
|
||||
message: `Unsupported host platform '${hostPlatform}'.`,
|
||||
});
|
||||
return yield* new UnsupportedHostBuildPlatformError({ hostPlatform });
|
||||
}
|
||||
|
||||
const target = mergeOptions(input.target, env.target, PLATFORM_CONFIG[platform].defaultTarget);
|
||||
@@ -745,17 +977,16 @@ export const resolveBuildOptions = Effect.fn("resolveBuildOptions")(function* (
|
||||
const verbose = resolveBooleanFlag(input.verbose, env.verbose);
|
||||
|
||||
const mockUpdates = resolveBooleanFlag(input.mockUpdates, env.mockUpdates);
|
||||
const configuredMockUpdateServerPort = Option.getOrUndefined(env.mockUpdateServerPort);
|
||||
const mockUpdateServerPort =
|
||||
Option.getOrUndefined(input.mockUpdateServerPort) ??
|
||||
(yield* resolveMockUpdateServerPort(Option.getOrUndefined(env.mockUpdateServerPort)).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new BuildScriptError({
|
||||
message: "Invalid mock update server port.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
));
|
||||
(configuredMockUpdateServerPort === undefined
|
||||
? undefined
|
||||
: yield* resolveMockUpdateServerPort(configuredMockUpdateServerPort).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
InvalidMockUpdateServerPortError.fromConfigValue(configuredMockUpdateServerPort, cause),
|
||||
),
|
||||
));
|
||||
|
||||
return {
|
||||
platform,
|
||||
@@ -775,7 +1006,7 @@ export const resolveBuildOptions = Effect.fn("resolveBuildOptions")(function* (
|
||||
const runCommand = Effect.fn("runCommand")(function* (
|
||||
command: ChildProcess.Command,
|
||||
options: {
|
||||
readonly label?: string;
|
||||
readonly label: string;
|
||||
readonly verbose: boolean;
|
||||
},
|
||||
) {
|
||||
@@ -791,14 +1022,11 @@ const runCommand = Effect.fn("runCommand")(function* (
|
||||
);
|
||||
|
||||
if (exitCode !== 0) {
|
||||
const outputSections = [
|
||||
options.label ? `Command: ${options.label}` : undefined,
|
||||
formatOutputSection("stdout", stdout),
|
||||
formatOutputSection("stderr", stderr),
|
||||
].filter((section): section is string => section !== undefined);
|
||||
const outputSuffix = outputSections.length > 0 ? `\n\n${outputSections.join("\n\n")}` : "";
|
||||
return yield* new BuildScriptError({
|
||||
message: `Command exited with non-zero exit code (${exitCode})${outputSuffix}`,
|
||||
return yield* new BuildCommandFailedError({
|
||||
command: options.label,
|
||||
exitCode,
|
||||
...(stdout.trim() ? { stdoutTail: stdout } : {}),
|
||||
...(stderr.trim() ? { stderrTail: stderr } : {}),
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -845,8 +1073,9 @@ function stageMacIcons(stageResourcesDir: string, sourcePng: string, verbose: bo
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
if (!(yield* fs.exists(sourcePng))) {
|
||||
return yield* new BuildScriptError({
|
||||
message: `Desktop macOS icon source is missing at ${sourcePng}`,
|
||||
return yield* new DesktopIconSourceMissingError({
|
||||
platform: "mac",
|
||||
sourcePath: sourcePng,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -871,8 +1100,9 @@ function stageLinuxIcons(stageResourcesDir: string, sourcePng: string, verbose:
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
if (!(yield* fs.exists(sourcePng))) {
|
||||
return yield* new BuildScriptError({
|
||||
message: `Desktop Linux icon source is missing at ${sourcePng}`,
|
||||
return yield* new DesktopIconSourceMissingError({
|
||||
platform: "linux",
|
||||
sourcePath: sourcePng,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -931,8 +1161,9 @@ function stageWindowsIcons(stageResourcesDir: string, sourceIco: string) {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
if (!(yield* fs.exists(sourceIco))) {
|
||||
return yield* new BuildScriptError({
|
||||
message: `Desktop Windows icon source is missing at ${sourceIco}`,
|
||||
return yield* new DesktopIconSourceMissingError({
|
||||
platform: "win",
|
||||
sourcePath: sourceIco,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -969,10 +1200,9 @@ function validateBundledClientAssets(clientDir: string) {
|
||||
}
|
||||
|
||||
if (missing.length > 0) {
|
||||
const preview = missing.slice(0, 6).join(", ");
|
||||
const suffix = missing.length > 6 ? ` (+${missing.length - 6} more)` : "";
|
||||
return yield* new BuildScriptError({
|
||||
message: `Bundled client references missing files in ${indexPath}: ${preview}${suffix}. Rebuild web/server artifacts.`,
|
||||
return yield* new BundledClientAssetsMissingError({
|
||||
indexPath,
|
||||
missingFiles: missing,
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -1174,8 +1404,8 @@ const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (
|
||||
|
||||
const platformConfig = PLATFORM_CONFIG[options.platform];
|
||||
if (!platformConfig) {
|
||||
return yield* new BuildScriptError({
|
||||
message: `Unsupported platform '${options.platform}'.`,
|
||||
return yield* new UnsupportedDesktopBuildPlatformError({
|
||||
platform: options.platform,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1183,16 +1413,17 @@ const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (
|
||||
|
||||
const serverDependencies = serverPackageJson.dependencies;
|
||||
if (!serverDependencies || Object.keys(serverDependencies).length === 0) {
|
||||
return yield* new BuildScriptError({
|
||||
message: "Could not resolve production dependencies from apps/server/package.json.",
|
||||
return yield* new MissingServerProductionDependenciesError({
|
||||
manifestPath: "apps/server/package.json",
|
||||
});
|
||||
}
|
||||
|
||||
const resolvedOverrides = yield* Effect.try({
|
||||
try: () => resolveCatalogDependencies(workspaceOverrides, workspaceCatalog, "apps/desktop"),
|
||||
catch: (cause) =>
|
||||
new BuildScriptError({
|
||||
message: "Could not resolve overrides from pnpm-workspace.yaml.",
|
||||
new DesktopBuildDependencyResolutionError({
|
||||
kind: "workspace-overrides",
|
||||
manifestPath: "pnpm-workspace.yaml",
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
@@ -1200,16 +1431,18 @@ const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (
|
||||
const resolvedServerDependencies = yield* Effect.try({
|
||||
try: () => resolveCatalogDependencies(serverDependencies, workspaceCatalog, "apps/server"),
|
||||
catch: (cause) =>
|
||||
new BuildScriptError({
|
||||
message: "Could not resolve production dependencies from apps/server/package.json.",
|
||||
new DesktopBuildDependencyResolutionError({
|
||||
kind: "server-production",
|
||||
manifestPath: "apps/server/package.json",
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
const resolvedDesktopRuntimeDependencies = yield* Effect.try({
|
||||
try: () => resolveDesktopRuntimeDependencies(desktopPackageJson.dependencies, workspaceCatalog),
|
||||
catch: (cause) =>
|
||||
new BuildScriptError({
|
||||
message: "Could not resolve desktop runtime dependencies from apps/desktop/package.json.",
|
||||
new DesktopBuildDependencyResolutionError({
|
||||
kind: "desktop-runtime",
|
||||
manifestPath: "apps/desktop/package.json",
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
@@ -1243,17 +1476,25 @@ const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (
|
||||
);
|
||||
}
|
||||
|
||||
for (const [label, dir] of Object.entries(distDirs)) {
|
||||
if (!(yield* fs.exists(dir))) {
|
||||
return yield* new BuildScriptError({
|
||||
message: `Missing ${label} at ${dir}. Run 'vp run build:desktop' first.`,
|
||||
const requiredBuildInputs = [
|
||||
{ artifact: "desktop-dist", artifactPath: distDirs.desktopDist },
|
||||
{ artifact: "desktop-resources", artifactPath: distDirs.desktopResources },
|
||||
{ artifact: "server-dist", artifactPath: distDirs.serverDist },
|
||||
] as const;
|
||||
for (const input of requiredBuildInputs) {
|
||||
if (!(yield* fs.exists(input.artifactPath))) {
|
||||
return yield* new MissingDesktopBuildInputError({
|
||||
...input,
|
||||
buildCommand: "vp run build:desktop",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (!(yield* fs.exists(bundledClientEntry))) {
|
||||
return yield* new BuildScriptError({
|
||||
message: `Missing bundled server client at ${bundledClientEntry}. Run 'vp run build:desktop' first.`,
|
||||
return yield* new MissingDesktopBuildInputError({
|
||||
artifact: "bundled-server-client",
|
||||
artifactPath: bundledClientEntry,
|
||||
buildCommand: "vp run build:desktop",
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1285,7 +1526,7 @@ const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (
|
||||
options.platform === "mac" && options.signed
|
||||
? yield* Effect.try({
|
||||
try: () => resolveMacPasskeySigningConfiguration(loadRepoEnv({ repoRoot })),
|
||||
catch: BuildScriptError.fromMacPasskeySigningConfiguration,
|
||||
catch: MacPasskeySigningConfigurationResolutionError.fromCause,
|
||||
})
|
||||
: undefined;
|
||||
const macPasskeySigning = configuredMacPasskeySigning
|
||||
@@ -1302,8 +1543,8 @@ const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (
|
||||
: undefined;
|
||||
if (macPasskeySigning && macEntitlementsPath) {
|
||||
if (!(yield* fs.exists(macPasskeySigning.provisioningProfilePath))) {
|
||||
return yield* new BuildScriptError({
|
||||
message: `macOS provisioning profile not found: ${macPasskeySigning.provisioningProfilePath}`,
|
||||
return yield* new MacProvisioningProfileNotFoundError({
|
||||
provisioningProfilePath: macPasskeySigning.provisioningProfilePath,
|
||||
});
|
||||
}
|
||||
yield* fs.writeFileString(macEntitlementsPath, renderMacPasskeyEntitlements(macPasskeySigning));
|
||||
@@ -1442,8 +1683,10 @@ const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (
|
||||
|
||||
const stageDistDir = path.join(stageAppDir, "dist");
|
||||
if (!(yield* fs.exists(stageDistDir))) {
|
||||
return yield* new BuildScriptError({
|
||||
message: `Build completed but dist directory was not found at ${stageDistDir}`,
|
||||
return yield* new DesktopBuildDistDirectoryMissingError({
|
||||
distPath: stageDistDir,
|
||||
platform: options.platform,
|
||||
arch: options.arch,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1462,8 +1705,10 @@ const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (
|
||||
}
|
||||
|
||||
if (copiedArtifacts.length === 0) {
|
||||
return yield* new BuildScriptError({
|
||||
message: `Build completed but no files were produced in ${stageDistDir}`,
|
||||
return yield* new DesktopBuildNoArtifactsProducedError({
|
||||
distPath: stageDistDir,
|
||||
platform: options.platform,
|
||||
arch: options.arch,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -1,18 +1,142 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import * as HostProcess from "@t3tools/shared/hostProcess";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
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 Sink from "effect/Sink";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { NativeStaticCheckCommandError } from "./mobile-native-static-check.ts";
|
||||
import { collectSources, runCommand } from "./mobile-native-static-check.ts";
|
||||
|
||||
it("describes failed native static-analysis commands structurally", () => {
|
||||
const error = new NativeStaticCheckCommandError({
|
||||
command: "swiftlint",
|
||||
args: ["lint", "--strict"],
|
||||
cwd: "/repo/apps/mobile",
|
||||
exitCode: 2,
|
||||
const processHandle = (
|
||||
exitCode: Effect.Effect<ChildProcessSpawner.ExitCode, PlatformError.PlatformError>,
|
||||
) =>
|
||||
ChildProcessSpawner.makeHandle({
|
||||
pid: ChildProcessSpawner.ProcessId(1),
|
||||
exitCode,
|
||||
isRunning: Effect.succeed(false),
|
||||
kill: () => Effect.void,
|
||||
unref: Effect.succeed(Effect.void),
|
||||
stdin: Sink.drain,
|
||||
stdout: Stream.empty,
|
||||
stderr: Stream.empty,
|
||||
all: Stream.empty,
|
||||
getInputFd: () => Sink.drain,
|
||||
getOutputFd: () => Stream.empty,
|
||||
});
|
||||
|
||||
assert.equal(error.command, "swiftlint");
|
||||
assert.deepStrictEqual(error.args, ["lint", "--strict"]);
|
||||
assert.equal(error.cwd, "/repo/apps/mobile");
|
||||
assert.equal(error.exitCode, 2);
|
||||
assert.equal(error.message, "Native static check command 'swiftlint' exited with code 2.");
|
||||
const provideSpawner = (spawn: ChildProcessSpawner.ChildProcessSpawner["Service"]["spawn"]) =>
|
||||
Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, ChildProcessSpawner.make(spawn));
|
||||
|
||||
const runSwiftLint = runCommand("swiftlint", ["lint", "--strict"], "/repo/apps/mobile").pipe(
|
||||
Effect.provideService(HostProcess.HostProcessPlatform, "linux"),
|
||||
);
|
||||
|
||||
it.layer(NodeServices.layer)("mobile native source discovery", (it) => {
|
||||
it.effect("preserves the failed discovery operation, path, and exact cause", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const root = yield* fs.makeTempDirectoryScoped({ prefix: "mobile-native-static-check-" });
|
||||
const missingDirectory = path.join(root, "missing");
|
||||
|
||||
const error = yield* collectSources(missingDirectory, root).pipe(Effect.flip);
|
||||
|
||||
assert.equal(error._tag, "NativeStaticCheckSourceDiscoveryError");
|
||||
assert.equal(error.operation, "read-directory");
|
||||
assert.equal(error.path, missingDirectory);
|
||||
assert.instanceOf(error.cause, PlatformError.PlatformError);
|
||||
assert.equal(error.message, "Native source discovery operation 'read-directory' failed.");
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("preserves process spawn context and the exact cause", () => {
|
||||
const cause = PlatformError.systemError({
|
||||
_tag: "NotFound",
|
||||
module: "ChildProcess",
|
||||
method: "spawn",
|
||||
description: "swiftlint was not found",
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const error = yield* runSwiftLint.pipe(
|
||||
Effect.provide(provideSpawner(() => Effect.fail(cause))),
|
||||
Effect.flip,
|
||||
);
|
||||
|
||||
if (error._tag !== "NativeStaticCheckProcessError") {
|
||||
return assert.fail(`Unexpected error: ${error._tag}`);
|
||||
}
|
||||
assert.equal(error.operation, "spawn");
|
||||
assert.equal(error.command, "swiftlint");
|
||||
assert.equal(error.argumentCount, 2);
|
||||
assert.equal(error.cwd, "/repo/apps/mobile");
|
||||
assert.equal(error.shell, false);
|
||||
assert.equal(error.cause, cause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
"Native static check process operation 'spawn' failed for command 'swiftlint'.",
|
||||
);
|
||||
assert.notProperty(error, "args");
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("preserves process wait context and the exact cause", () => {
|
||||
const cause = PlatformError.systemError({
|
||||
_tag: "Unknown",
|
||||
module: "ChildProcess",
|
||||
method: "exitCode",
|
||||
description: "status unavailable",
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const error = yield* runSwiftLint.pipe(
|
||||
Effect.provide(provideSpawner(() => Effect.succeed(processHandle(Effect.fail(cause))))),
|
||||
Effect.flip,
|
||||
);
|
||||
|
||||
if (error._tag !== "NativeStaticCheckProcessError") {
|
||||
return assert.fail(`Unexpected error: ${error._tag}`);
|
||||
}
|
||||
assert.equal(error.operation, "wait-for-exit");
|
||||
assert.equal(error.command, "swiftlint");
|
||||
assert.equal(error.argumentCount, 2);
|
||||
assert.equal(error.cwd, "/repo/apps/mobile");
|
||||
assert.equal(error.shell, false);
|
||||
assert.equal(error.cause, cause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
"Native static check process operation 'wait-for-exit' failed for command 'swiftlint'.",
|
||||
);
|
||||
assert.notProperty(error, "args");
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("reports non-zero exits without manufacturing a cause", () =>
|
||||
Effect.gen(function* () {
|
||||
const error = yield* runSwiftLint.pipe(
|
||||
Effect.provide(
|
||||
provideSpawner(() =>
|
||||
Effect.succeed(processHandle(Effect.succeed(ChildProcessSpawner.ExitCode(2)))),
|
||||
),
|
||||
),
|
||||
Effect.flip,
|
||||
);
|
||||
|
||||
if (error._tag !== "NativeStaticCheckCommandError") {
|
||||
return assert.fail(`Unexpected error: ${error._tag}`);
|
||||
}
|
||||
assert.equal(error.command, "swiftlint");
|
||||
assert.equal(error.argumentCount, 2);
|
||||
assert.equal(error.cwd, "/repo/apps/mobile");
|
||||
assert.equal(error.shell, false);
|
||||
assert.equal(error.exitCode, 2);
|
||||
assert.notProperty(error, "cause");
|
||||
assert.notProperty(error, "args");
|
||||
}),
|
||||
);
|
||||
@@ -8,7 +8,6 @@ import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Logger from "effect/Logger";
|
||||
import * as Path from "effect/Path";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { Command } from "effect/unstable/cli";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
@@ -18,12 +17,44 @@ interface NativeStaticTool {
|
||||
readonly installHint: string;
|
||||
}
|
||||
|
||||
const NonNegativeInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));
|
||||
|
||||
export class NativeStaticCheckSourceDiscoveryError extends Schema.TaggedErrorClass<NativeStaticCheckSourceDiscoveryError>()(
|
||||
"NativeStaticCheckSourceDiscoveryError",
|
||||
{
|
||||
operation: Schema.Literals(["resolve-root", "read-directory", "stat-entry"]),
|
||||
path: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Native source discovery operation '${this.operation}' failed.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class NativeStaticCheckProcessError extends Schema.TaggedErrorClass<NativeStaticCheckProcessError>()(
|
||||
"NativeStaticCheckProcessError",
|
||||
{
|
||||
operation: Schema.Literals(["spawn", "wait-for-exit"]),
|
||||
command: Schema.String,
|
||||
argumentCount: NonNegativeInt,
|
||||
cwd: Schema.String,
|
||||
shell: Schema.Boolean,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Native static check process operation '${this.operation}' failed for command '${this.command}'.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class NativeStaticCheckCommandError extends Schema.TaggedErrorClass<NativeStaticCheckCommandError>()(
|
||||
"NativeStaticCheckCommandError",
|
||||
{
|
||||
command: Schema.String,
|
||||
args: Schema.Array(Schema.String),
|
||||
argumentCount: NonNegativeInt,
|
||||
cwd: Schema.String,
|
||||
shell: Schema.Boolean,
|
||||
exitCode: Schema.Int,
|
||||
},
|
||||
) {
|
||||
@@ -59,8 +90,17 @@ const excludedDirectories = new Set([
|
||||
]);
|
||||
const generatedNativeProjectDirectories = new Set(["android", "ios"]);
|
||||
|
||||
const mobileAppRootUrl = new URL("../apps/mobile", import.meta.url);
|
||||
const appRoot = Effect.service(Path.Path).pipe(
|
||||
Effect.flatMap((path) => path.fromFileUrl(new URL("../apps/mobile", import.meta.url))),
|
||||
Effect.flatMap((path) => path.fromFileUrl(mobileAppRootUrl)),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new NativeStaticCheckSourceDiscoveryError({
|
||||
operation: "resolve-root",
|
||||
path: mobileAppRootUrl.pathname,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const commandOutputOptions = {
|
||||
@@ -77,7 +117,7 @@ const warnMissingTool = (tool: NativeStaticTool, checkName: string) =>
|
||||
`${tool.command} is not installed; skipping ${checkName}. Install it with '${tool.installHint}' or run 'brew bundle install --file apps/mobile/Brewfile'.`,
|
||||
);
|
||||
|
||||
const runCommand = Effect.fn("runCommand")(function* (
|
||||
export const runCommand = Effect.fn("runCommand")(function* (
|
||||
command: string,
|
||||
args: ReadonlyArray<string>,
|
||||
cwd: string,
|
||||
@@ -85,42 +125,86 @@ const runCommand = Effect.fn("runCommand")(function* (
|
||||
yield* Console.log(`$ ${[command, ...args].join(" ")}`);
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const spawnCommand = yield* resolveSpawnCommand(command, args);
|
||||
const child = yield* spawner.spawn(
|
||||
ChildProcess.make(spawnCommand.command, spawnCommand.args, {
|
||||
cwd,
|
||||
...commandOutputOptions,
|
||||
shell: spawnCommand.shell,
|
||||
}),
|
||||
const processContext = {
|
||||
command,
|
||||
argumentCount: spawnCommand.args.length,
|
||||
cwd,
|
||||
shell: spawnCommand.shell,
|
||||
} as const;
|
||||
const child = yield* spawner
|
||||
.spawn(
|
||||
ChildProcess.make(spawnCommand.command, spawnCommand.args, {
|
||||
cwd,
|
||||
...commandOutputOptions,
|
||||
shell: spawnCommand.shell,
|
||||
}),
|
||||
)
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new NativeStaticCheckProcessError({
|
||||
...processContext,
|
||||
operation: "spawn",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const exitCode = Number(
|
||||
yield* child.exitCode.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new NativeStaticCheckProcessError({
|
||||
...processContext,
|
||||
operation: "wait-for-exit",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
const exitCode = Number(yield* child.exitCode);
|
||||
|
||||
if (exitCode !== 0) {
|
||||
return yield* new NativeStaticCheckCommandError({
|
||||
command,
|
||||
args,
|
||||
cwd,
|
||||
...processContext,
|
||||
exitCode,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
function collectSources(
|
||||
export function collectSources(
|
||||
directory: string,
|
||||
root: string,
|
||||
): Effect.Effect<
|
||||
ReadonlyArray<string>,
|
||||
PlatformError.PlatformError,
|
||||
NativeStaticCheckSourceDiscoveryError,
|
||||
FileSystem.FileSystem | Path.Path
|
||||
> {
|
||||
return Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const entries = yield* fs.readDirectory(directory);
|
||||
const entries = yield* fs.readDirectory(directory).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new NativeStaticCheckSourceDiscoveryError({
|
||||
operation: "read-directory",
|
||||
path: directory,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const sources: Array<string> = [];
|
||||
|
||||
for (const entry of entries) {
|
||||
const entryPath = path.join(directory, entry);
|
||||
const stat = yield* fs.stat(entryPath);
|
||||
const stat = yield* fs.stat(entryPath).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new NativeStaticCheckSourceDiscoveryError({
|
||||
operation: "stat-entry",
|
||||
path: entryPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
if (stat.type === "Directory") {
|
||||
const isGeneratedNativeProjectDirectory =
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Path from "effect/Path";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
|
||||
import {
|
||||
readDesktopBaseVersion,
|
||||
resolveNightlyBaseVersion,
|
||||
resolveNightlyReleaseMetadata,
|
||||
resolveNightlyTargetVersion,
|
||||
@@ -43,3 +48,49 @@ it("derives nightly metadata including the short commit sha in the release name"
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
it.layer(NodeServices.layer)("readDesktopBaseVersion", (it) => {
|
||||
it.effect("preserves desktop package read context and its platform cause", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const rootDir = yield* fs.makeTempDirectoryScoped({
|
||||
prefix: "resolve-nightly-release-read-",
|
||||
});
|
||||
const packageJsonPath = path.join(rootDir, "apps/desktop/package.json");
|
||||
|
||||
const error = yield* readDesktopBaseVersion(rootDir).pipe(Effect.flip);
|
||||
|
||||
if (error._tag !== "NightlyReleaseDesktopPackageError") {
|
||||
return assert.fail(`Unexpected error: ${error._tag}`);
|
||||
}
|
||||
assert.equal(error.operation, "read");
|
||||
assert.equal(error.packageJsonPath, packageJsonPath);
|
||||
assert.instanceOf(error.cause, PlatformError.PlatformError);
|
||||
assert.notInclude(error.message, String((error.cause as Error).message));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves desktop package decode context and its schema cause", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const rootDir = yield* fs.makeTempDirectoryScoped({
|
||||
prefix: "resolve-nightly-release-decode-",
|
||||
});
|
||||
const packageJsonPath = path.join(rootDir, "apps/desktop/package.json");
|
||||
yield* fs.makeDirectory(path.dirname(packageJsonPath), { recursive: true });
|
||||
yield* fs.writeFileString(packageJsonPath, "{");
|
||||
|
||||
const error = yield* readDesktopBaseVersion(rootDir).pipe(Effect.flip);
|
||||
|
||||
if (error._tag !== "NightlyReleaseDesktopPackageError") {
|
||||
return assert.fail(`Unexpected error: ${error._tag}`);
|
||||
}
|
||||
assert.equal(error.operation, "decode");
|
||||
assert.equal(error.packageJsonPath, packageJsonPath);
|
||||
assert.ok(error.cause !== undefined);
|
||||
assert.notInclude(error.message, String((error.cause as Error).message));
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -40,6 +40,19 @@ export class InvalidDesktopPackageVersionError extends Schema.TaggedErrorClass<I
|
||||
}
|
||||
}
|
||||
|
||||
export class NightlyReleaseDesktopPackageError extends Schema.TaggedErrorClass<NightlyReleaseDesktopPackageError>()(
|
||||
"NightlyReleaseDesktopPackageError",
|
||||
{
|
||||
operation: Schema.Literals(["read", "decode"]),
|
||||
packageJsonPath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to ${this.operation} desktop package metadata at ${this.packageJsonPath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
const RepoRoot = Effect.service(Path.Path).pipe(
|
||||
Effect.flatMap((path) => path.fromFileUrl(new URL("..", import.meta.url))),
|
||||
);
|
||||
@@ -77,16 +90,33 @@ export const resolveNightlyReleaseMetadata = (
|
||||
};
|
||||
};
|
||||
|
||||
const readDesktopBaseVersion = Effect.fn("readDesktopBaseVersion")(function* (
|
||||
export const readDesktopBaseVersion = Effect.fn("readDesktopBaseVersion")(function* (
|
||||
rootDir: string | undefined,
|
||||
) {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const workspaceRoot = rootDir ? path.resolve(rootDir) : yield* RepoRoot;
|
||||
const packageJsonPath = path.join(workspaceRoot, "apps/desktop/package.json");
|
||||
const packageJson = yield* fs
|
||||
.readFileString(packageJsonPath)
|
||||
.pipe(Effect.flatMap(decodeDesktopPackageJson));
|
||||
const packageJsonSource = yield* fs.readFileString(packageJsonPath).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new NightlyReleaseDesktopPackageError({
|
||||
operation: "read",
|
||||
packageJsonPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const packageJson = yield* decodeDesktopPackageJson(packageJsonSource).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new NightlyReleaseDesktopPackageError({
|
||||
operation: "decode",
|
||||
packageJsonPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
return yield* resolveNightlyTargetVersion(packageJson.version);
|
||||
});
|
||||
|
||||
|
||||
@@ -1,7 +1,33 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
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 { resolvePreviousReleaseTag } from "./resolve-previous-release-tag.ts";
|
||||
import { listGitTags, resolvePreviousReleaseTag } from "./resolve-previous-release-tag.ts";
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
|
||||
function mockHandle(options: {
|
||||
readonly exitCode: number;
|
||||
readonly stdout?: string;
|
||||
readonly stderr?: string;
|
||||
}) {
|
||||
return ChildProcessSpawner.makeHandle({
|
||||
pid: ChildProcessSpawner.ProcessId(1),
|
||||
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(options.exitCode)),
|
||||
isRunning: Effect.succeed(false),
|
||||
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 ?? "")),
|
||||
all: Stream.empty,
|
||||
getInputFd: () => Sink.drain,
|
||||
getOutputFd: () => Stream.empty,
|
||||
});
|
||||
}
|
||||
|
||||
it.effect("selects the latest earlier stable tag and ignores nightlies", () =>
|
||||
Effect.gen(function* () {
|
||||
@@ -37,3 +63,68 @@ it.effect("reports the invalid tag with its release channel", () =>
|
||||
assert.equal(error.message, "Invalid nightly release tag 'v1.2.0'.");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves git tag spawn context and the exact platform cause", () => {
|
||||
const cause = PlatformError.systemError({
|
||||
_tag: "NotFound",
|
||||
module: "ChildProcess",
|
||||
method: "spawn",
|
||||
description: "git was not found",
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const error = yield* listGitTags("/repo").pipe(
|
||||
Effect.scoped,
|
||||
Effect.provideService(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() => Effect.fail(cause)),
|
||||
),
|
||||
Effect.flip,
|
||||
);
|
||||
|
||||
if (error._tag !== "ReleaseTagListProcessError") {
|
||||
return assert.fail(`Unexpected error: ${error._tag}`);
|
||||
}
|
||||
assert.equal(error.operation, "spawn");
|
||||
assert.equal(error.executable, "git");
|
||||
assert.equal(error.argumentCount, 2);
|
||||
assert.equal(error.cwd, "/repo");
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.notProperty(error, "args");
|
||||
assert.notInclude(error.message, cause.message);
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("reports git tag non-zero exits without manufacturing a cause", () =>
|
||||
Effect.gen(function* () {
|
||||
const error = yield* listGitTags("/repo").pipe(
|
||||
Effect.scoped,
|
||||
Effect.provideService(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() =>
|
||||
Effect.succeed(
|
||||
mockHandle({
|
||||
exitCode: 17,
|
||||
stdout: "v1.2.3\n",
|
||||
stderr: "fatal: repository unavailable\n",
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
Effect.flip,
|
||||
);
|
||||
|
||||
if (error._tag !== "ReleaseTagListProcessExitError") {
|
||||
return assert.fail(`Unexpected error: ${error._tag}`);
|
||||
}
|
||||
assert.equal(error.executable, "git");
|
||||
assert.equal(error.argumentCount, 2);
|
||||
assert.equal(error.cwd, "/repo");
|
||||
assert.equal(error.exitCode, 17);
|
||||
assert.equal(error.stdoutLength, 7);
|
||||
assert.equal(error.stderrLength, 30);
|
||||
assert.notProperty(error, "cause");
|
||||
assert.notProperty(error, "stdout");
|
||||
assert.notProperty(error, "stderr");
|
||||
}),
|
||||
);
|
||||
@@ -2,7 +2,6 @@
|
||||
|
||||
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import * as Array from "effect/Array";
|
||||
import * as Config from "effect/Config";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
@@ -27,6 +26,39 @@ export class InvalidReleaseTagError extends Schema.TaggedErrorClass<InvalidRelea
|
||||
}
|
||||
}
|
||||
|
||||
const releaseTagListProcessContext = {
|
||||
executable: Schema.Literal("git"),
|
||||
argumentCount: Schema.Number,
|
||||
cwd: Schema.String,
|
||||
};
|
||||
|
||||
export class ReleaseTagListProcessError extends Schema.TaggedErrorClass<ReleaseTagListProcessError>()(
|
||||
"ReleaseTagListProcessError",
|
||||
{
|
||||
...releaseTagListProcessContext,
|
||||
operation: Schema.Literals(["spawn", "communicate", "wait-for-exit"]),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to list release tags during process operation "${this.operation}".`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ReleaseTagListProcessExitError extends Schema.TaggedErrorClass<ReleaseTagListProcessExitError>()(
|
||||
"ReleaseTagListProcessExitError",
|
||||
{
|
||||
...releaseTagListProcessContext,
|
||||
exitCode: Schema.Number,
|
||||
stdoutLength: Schema.Number,
|
||||
stderrLength: Schema.Number,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Release tag listing exited with code ${this.exitCode}.`;
|
||||
}
|
||||
}
|
||||
|
||||
interface StableVersion {
|
||||
readonly major: number;
|
||||
readonly minor: number;
|
||||
@@ -172,20 +204,80 @@ export const resolvePreviousReleaseTag = (
|
||||
return candidates[0]?.tag;
|
||||
});
|
||||
|
||||
const listGitTags = Effect.fn("listGitTags")(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const child = yield* spawner.spawn(ChildProcess.make("git", ["tag", "--list"]));
|
||||
const tags = yield* child.stdout.pipe(
|
||||
const collectStreamAsString = <E>(stream: Stream.Stream<Uint8Array, E>): Effect.Effect<string, E> =>
|
||||
stream.pipe(
|
||||
Stream.decodeText(),
|
||||
Stream.runFold(
|
||||
() => "",
|
||||
(acc, chunk) => acc + chunk,
|
||||
),
|
||||
Effect.map(String.split(/\r?\n/)),
|
||||
Effect.map(Array.map(String.trim)),
|
||||
Effect.map(Array.filter(String.isNonEmpty)),
|
||||
);
|
||||
return tags;
|
||||
|
||||
export const listGitTags = Effect.fn("listGitTags")(function* (cwd = process.cwd()) {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const args = ["tag", "--list"] as const;
|
||||
const context = {
|
||||
executable: "git",
|
||||
argumentCount: args.length,
|
||||
cwd,
|
||||
} as const;
|
||||
const child = yield* spawner.spawn(ChildProcess.make("git", args, { cwd })).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ReleaseTagListProcessError({
|
||||
...context,
|
||||
operation: "spawn",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const [stdout, stderr, exitCode] = yield* Effect.all(
|
||||
[
|
||||
collectStreamAsString(child.stdout).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ReleaseTagListProcessError({
|
||||
...context,
|
||||
operation: "communicate",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
collectStreamAsString(child.stderr).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ReleaseTagListProcessError({
|
||||
...context,
|
||||
operation: "communicate",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
child.exitCode.pipe(
|
||||
Effect.map(Number),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ReleaseTagListProcessError({
|
||||
...context,
|
||||
operation: "wait-for-exit",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
|
||||
if (exitCode !== 0) {
|
||||
return yield* new ReleaseTagListProcessExitError({
|
||||
...context,
|
||||
exitCode,
|
||||
stdoutLength: stdout.length,
|
||||
stderrLength: stderr.length,
|
||||
});
|
||||
}
|
||||
|
||||
return stdout.split(/\r?\n/).map(String.trim).filter(String.isNonEmpty);
|
||||
});
|
||||
|
||||
const writeOutput = Effect.fn("writeOutput")(function* (
|
||||
|
||||
Reference in new issue
Block a user