Skip to content
TypeScript

fix(server): a missing t3.json is no longer a failed read (#19949)

Wishb430de5c9bdd
diff --git a/apps/mobile/src/features/threads/new-task-flow-provider.tsx b/apps/mobile/src/features/threads/new-task-flow-provider.tsx
index 1da765bc775..27754c86dad 100644
--- a/apps/mobile/src/features/threads/new-task-flow-provider.tsx
+++ b/apps/mobile/src/features/threads/new-task-flow-provider.tsx
@@ -453,13 +453,17 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
canReadFiles && selectedProject !== null && selectedProject.workspaceRoot !== ""
? projectEnvironment.readFile({
environmentId: selectedProject.environmentId,
- input: { cwd: selectedProject.workspaceRoot, relativePath: T3_PROJECT_FILE_NAME },
+ input: {
+ cwd: selectedProject.workspaceRoot,
+ relativePath: T3_PROJECT_FILE_NAME,
+ allowMissing: true,
+ },
})
: null,
);
const t3ProjectFileData = t3ProjectFileQuery.data as ProjectReadFileResult | null;
const t3ProjectFile =
- t3ProjectFileData === null || t3ProjectFileData.truncated
+ t3ProjectFileData === null || t3ProjectFileData.exists === false || t3ProjectFileData.truncated
? null
: parseT3ProjectFile(t3ProjectFileData.contents);
const projectSettings = resolveProjectSettings(
diff --git a/apps/server/src/workspace/WorkspaceFileSystem.test.ts b/apps/server/src/workspace/WorkspaceFileSystem.test.ts
index ae956e69d0c..89f4167a3ae 100644
--- a/apps/server/src/workspace/WorkspaceFileSystem.test.ts
+++ b/apps/server/src/workspace/WorkspaceFileSystem.test.ts
@@ -4,9 +4,11 @@ import * as NodeChildProcess from "node:child_process";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it, describe, expect } from "@effect/vitest";
import * as Effect from "effect/Effect";
+import * as Exit from "effect/Exit";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
+import * as Tracer from "effect/Tracer";
import * as ServerConfig from "../config.ts";
import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
@@ -274,6 +276,19 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceFileSystemLive", (i
resolvedPath,
});
expect("cause" in error).toBe(false);
+
+ yield* fileSystem.symlink(outsideDir, path.join(cwd, "linked-dir"));
+ const missingChildError = yield* workspaceFileSystem
+ .readFile(
+ Object.assign(
+ { cwd, relativePath: "linked-dir/missing/t3.json" },
+ { allowMissing: true },
+ ),
+ )
+ .pipe(Effect.flip);
+ expect(missingChildError).toBeInstanceOf(
+ WorkspaceFileSystem.WorkspaceFilePathEscapeError,
+ );
}),
);
@@ -285,18 +300,20 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceFileSystemLive", (i
const cwd = yield* makeTempDir;
yield* fileSystem.makeDirectory(path.join(cwd, "src"));
- const error = yield* workspaceFileSystem
- .readFile({ cwd, relativePath: "src" })
- .pipe(Effect.flip);
const resolvedPath = yield* fileSystem.realPath(path.join(cwd, "src"));
+ for (const options of [{}, { allowMissing: true }]) {
+ const error = yield* workspaceFileSystem
+ .readFile(Object.assign({ cwd, relativePath: "src" }, options))
+ .pipe(Effect.flip);
- expect(error).toBeInstanceOf(WorkspaceFileSystem.WorkspacePathNotFileError);
- expect(error).toMatchObject({
- workspaceRoot: cwd,
- relativePath: "src",
- resolvedPath,
- });
- expect("cause" in error).toBe(false);
+ expect(error).toBeInstanceOf(WorkspaceFileSystem.WorkspacePathNotFileError);
+ expect(error).toMatchObject({
+ workspaceRoot: cwd,
+ relativePath: "src",
+ resolvedPath,
+ });
+ expect("cause" in error).toBe(false);
+ }
}),
);
@@ -348,6 +365,44 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceFileSystemLive", (i
expect((error.cause as NodeJS.ErrnoException).code).toBe("ENOENT");
}),
);
+
+ it.effect("returns an absent optional file without any failed spans", () =>
+ Effect.gen(function* () {
+ const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
+ const cwd = yield* makeTempDir;
+ const spans: Array<Tracer.NativeSpan> = [];
+ const tracer = Tracer.make({
+ span: (options) => {
+ const span = new Tracer.NativeSpan(options);
+ spans.push(span);
+ return span;
+ },
+ });
+
+ const result = yield* workspaceFileSystem
+ .readFile(Object.assign({ cwd, relativePath: "t3.json" }, { allowMissing: true }))
+ .pipe(Effect.withTracer(tracer), Effect.exit);
+
+ expect(spans.length).toBeGreaterThan(0);
+ // Diagnostics counts nested failures even when the outer read recovers.
+ expect
+ .soft(
+ spans
+ .filter((span) => span.status._tag === "Ended" && Exit.isFailure(span.status.exit))
+ .map((span) => span.name),
+ )
+ .toEqual([]);
+ expect(result).toEqual(
+ Exit.succeed({
+ relativePath: "t3.json",
+ contents: "",
+ byteLength: 0,
+ truncated: false,
+ exists: false,
+ }),
+ );
+ }),
+ );
});
describe("writeFile", () => {
diff --git a/apps/server/src/workspace/WorkspaceFileSystem.ts b/apps/server/src/workspace/WorkspaceFileSystem.ts
index 96fe5a0d234..9f7945cc0a9 100644
--- a/apps/server/src/workspace/WorkspaceFileSystem.ts
+++ b/apps/server/src/workspace/WorkspaceFileSystem.ts
@@ -240,7 +240,13 @@ export const make = Effect.gen(function* () {
operation: "realpath-target",
cause,
}),
- });
+ }).pipe(
+ Effect.catchIf(
+ (error) =>
+ input.allowMissing === true && (error.cause as NodeJS.ErrnoException).code === "ENOENT",
+ () => Effect.succeed(null),
+ ),
+ );
return { relativePath: requestedPath, realTargetPath };
}
@@ -261,8 +267,36 @@ export const make = Effect.gen(function* () {
cause,
}),
});
- const realTargetPath = yield* Effect.tryPromise({
- try: () => NodeFSP.realpath(target.absolutePath),
+ const resolved = yield* Effect.tryPromise({
+ try: async () => {
+ let candidate = target.absolutePath;
+ for (;;) {
+ try {
+ return {
+ realTargetPath: path.join(
+ await NodeFSP.realpath(candidate),
+ path.relative(candidate, target.absolutePath),
+ ),
+ exists: candidate === target.absolutePath,
+ };
+ } catch (error) {
+ if (!input.allowMissing || (error as NodeJS.ErrnoException).code !== "ENOENT") {
+ throw error;
+ }
+ // Like writes, missing reads must check the nearest existing ancestor.
+ // An existing entry that cannot resolve is a dangling link, not absence.
+ const exists = await NodeFSP.lstat(candidate).then(
+ () => true,
+ (cause: NodeJS.ErrnoException) => {
+ if (cause.code !== "ENOENT") throw cause;
+ return false;
+ },
+ );
+ if (exists || path.dirname(candidate) === candidate) throw error;
+ candidate = path.dirname(candidate);
+ }
+ }
+ },
catch: (cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
@@ -273,22 +307,33 @@ export const make = Effect.gen(function* () {
cause,
}),
});
- if (!isInsideRealRoot(realWorkspaceRoot, realTargetPath)) {
+ if (!isInsideRealRoot(realWorkspaceRoot, resolved.realTargetPath)) {
return yield* new WorkspaceFilePathEscapeError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedWorkspaceRoot: realWorkspaceRoot,
- resolvedPath: realTargetPath,
+ resolvedPath: resolved.realTargetPath,
});
}
- return { relativePath: target.relativePath, realTargetPath };
+ return {
+ relativePath: target.relativePath,
+ realTargetPath: resolved.exists ? resolved.realTargetPath : null,
+ };
});
const readFile: WorkspaceFileSystem["Service"]["readFile"] = Effect.fn(
"WorkspaceFileSystem.readFile",
)(function* (input) {
const target = yield* resolveReadTarget(input);
+ const absentResult = {
+ relativePath: target.relativePath,
+ contents: "",
+ byteLength: 0,
+ truncated: false,
+ exists: false,
+ };
const realTargetPath = target.realTargetPath;
+ if (realTargetPath === null) return absentResult;
return yield* Effect.acquireUseRelease(
Effect.tryPromise({
@@ -308,9 +353,16 @@ export const make = Effect.gen(function* () {
operation: "open",
cause,
}),
- }),
+ }).pipe(
+ Effect.catchIf(
+ (error) =>
+ input.allowMissing === true && (error.cause as NodeJS.ErrnoException).code === "ENOENT",
+ () => Effect.succeed(null),
+ ),
+ ),
(handle) =>
Effect.gen(function* () {
+ if (handle === null) return absentResult;
const stat = yield* Effect.tryPromise({
try: () => handle.stat(),
catch: (cause) =>
@@ -362,18 +414,20 @@ export const make = Effect.gen(function* () {
};
}),
(handle) =>
- Effect.tryPromise({
- try: () => handle.close(),
- catch: (cause) =>
- new WorkspaceFileSystemOperationError({
- workspaceRoot: input.cwd,
- relativePath: input.relativePath,
- resolvedPath: realTargetPath,
- operationPath: realTargetPath,
- operation: "close",
- cause,
+ handle === null
+ ? Effect.void
+ : Effect.tryPromise({
+ try: () => handle.close(),
+ catch: (cause) =>
+ new WorkspaceFileSystemOperationError({
+ workspaceRoot: input.cwd,
+ relativePath: input.relativePath,
+ resolvedPath: realTargetPath,
+ operationPath: realTargetPath,
+ operation: "close",
+ cause,
+ }),
}),
- }),
);
});
diff --git a/apps/web/src/components/files/projectFilesQueryState.ts b/apps/web/src/components/files/projectFilesQueryState.ts
index b68f7a3f951..a32e0556d8d 100644
--- a/apps/web/src/components/files/projectFilesQueryState.ts
+++ b/apps/web/src/components/files/projectFilesQueryState.ts
@@ -4,6 +4,7 @@ import {
type ProjectListEntriesResult,
ProjectReadFileError,
type ProjectReadFileResult,
+ T3_PROJECT_FILE_NAME,
} from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import * as Option from "effect/Option";
@@ -71,7 +72,11 @@ export function getProjectFileQueryAtom(
) {
return projectEnvironment.readFile({
environmentId,
- input: { cwd, relativePath: relativePath ?? EMPTY_PROJECT_FILE_PATH },
+ input: {
+ cwd,
+ relativePath: relativePath ?? EMPTY_PROJECT_FILE_PATH,
+ ...(relativePath === T3_PROJECT_FILE_NAME ? { allowMissing: true } : {}),
+ },
});
}
@@ -112,7 +117,8 @@ export function getProjectFileContents(
const optimistic = getOptimisticProjectFileQueryData(environmentId, cwd, relativePath);
if (optimistic) return optimistic.contents;
const result = appAtomRegistry.get(getProjectFileQueryAtom(environmentId, cwd, relativePath));
- return Option.getOrUndefined(AsyncResult.value(result))?.contents;
+ const data = Option.getOrUndefined(AsyncResult.value(result));
+ return data?.exists === false ? undefined : data?.contents;
}
export function getUnsavedProjectFileQueryData(
@@ -259,15 +265,15 @@ export function useProjectFileQuery(
const result = useAtomValue(atom);
const refreshAtom = useAtomRefresh(atom);
const refresh = () => refreshAtom();
+ const readData = Option.getOrNull(AsyncResult.value(result));
+ const isMissing = readData?.exists === false;
const optimisticResult = useAtomValue(
optimisticFileAtom(environmentId, cwd, relativePath ?? EMPTY_PROJECT_FILE_PATH),
);
const optimisticFile = relativePath === null ? null : optimisticResult;
const cause = failureCause(result);
const readError = isProjectReadFileError(cause) ? cause : null;
- const data = canReadFiles
- ? (optimisticFile?.data ?? Option.getOrNull(AsyncResult.value(result)))
- : null;
+ const data = canReadFiles ? (optimisticFile?.data ?? (isMissing ? null : readData)) : null;
const isNotFile = readError?.failure === "path_not_file";
return {
@@ -276,7 +282,9 @@ export function useProjectFileQuery(
!isQueryEnabled || fileAccess.isPending
? null
: canReadFiles
- ? errorMessage(cause)
+ ? isMissing && !optimisticFile
+ ? `'${relativePath}' does not exist.`
+ : errorMessage(cause)
: (fileAccess.error ?? "This connection cannot read host files."),
isPending: isQueryEnabled && (fileAccess.isPending || result.waiting),
readError,
diff --git a/apps/web/src/components/settings/SettingsScopeContext.tsx b/apps/web/src/components/settings/SettingsScopeContext.tsx
index d3200a34a39..6c170bdd1a0 100644
--- a/apps/web/src/components/settings/SettingsScopeContext.tsx
+++ b/apps/web/src/components/settings/SettingsScopeContext.tsx
@@ -33,7 +33,9 @@ const memberProjectFilesAtom = Atom.family((membersKey: string) => {
Option.getOrNull(AsyncResult.value(result));
files.set(
physicalProjectKey,
- data === null || data.truncated ? null : parseT3ProjectFile(data.contents),
+ data === null || data.exists === false || data.truncated
+ ? null
+ : parseT3ProjectFile(data.contents),
);
}
return files;
diff --git a/apps/web/src/lib/t3ProjectFileDefaults.ts b/apps/web/src/lib/t3ProjectFileDefaults.ts
index e6210ae5c76..b5000b4ddd9 100644
--- a/apps/web/src/lib/t3ProjectFileDefaults.ts
+++ b/apps/web/src/lib/t3ProjectFileDefaults.ts
@@ -23,6 +23,6 @@ export async function readT3ProjectFile(
T3_PROJECT_FILE_NAME,
result._tag === "Success" ? result.value : null,
);
- if (data === null || data.truncated) return null;
+ if (data === null || data.exists === false || data.truncated) return null;
return parseT3ProjectFile(data.contents);
}
diff --git a/packages/client-runtime/src/state/projectCommands.test.ts b/packages/client-runtime/src/state/projectCommands.test.ts
index 9d7d47ea9d8..a138bde04f7 100644
--- a/packages/client-runtime/src/state/projectCommands.test.ts
+++ b/packages/client-runtime/src/state/projectCommands.test.ts
@@ -3,6 +3,8 @@ import {
AuthFilesystemWriteScope,
EnvironmentId,
ProjectId,
+ ProjectReadFileInput,
+ ProjectReadFileResult,
ThreadId,
type AuthSessionState,
type ScopedProjectRef,
@@ -15,6 +17,7 @@ import * as Deferred from "effect/Deferred";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
+import * as Schema from "effect/Schema";
import * as SubscriptionRef from "effect/SubscriptionRef";
import * as Stream from "effect/Stream";
import { Atom, AtomRegistry, AsyncResult } from "effect/reactivity";
@@ -26,6 +29,8 @@ import type { RpcSession } from "../rpc/session.ts";
import type { EnvironmentProject } from "./models.ts";
import { createProjectEnvironmentAtoms } from "./projectCommands.ts";
+const decodeReadFileInput = Schema.decodeUnknownSync(ProjectReadFileInput);
+const decodeReadFileResult = Schema.decodeUnknownSync(ProjectReadFileResult);
const ENVIRONMENT_ID = EnvironmentId.make("environment-1");
vi.mock("./session.ts", () => ({
createEnvironmentSessionAtoms: () => ({ sessionStateAtom: sessions }),
@@ -43,7 +48,10 @@ const PROJECT = {
const makeHarness = Effect.fn("TestProjectCommands.makeHarness")(function* () {
const metadataRequests: string[][] = [];
const file = { byteLength: 5 };
- const readResponse = { wait: Effect.void as Effect.Effect<void> };
+ const readResponse = {
+ wait: Effect.void as Effect.Effect<void>,
+ missing: false,
+ };
const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
target: { environmentId: ENVIRONMENT_ID },
session: yield* SubscriptionRef.make(
@@ -54,7 +62,17 @@ const makeHarness = Effect.fn("TestProjectCommands.makeHarness")(function* () {
Effect.gen(function* () {
const byteLength = file.byteLength;
yield* readResponse.wait;
- return { relativePath: "foo", byteLength, contents: "old", truncated: false };
+ return decodeReadFileResult(
+ readResponse.missing
+ ? {
+ relativePath: "foo",
+ byteLength: 0,
+ contents: "",
+ truncated: false,
+ exists: false,
+ }
+ : { relativePath: "foo", byteLength, contents: "old", truncated: false },
+ );
}),
[WS_METHODS.projectsWriteFile]: () =>
Effect.sync(() => {
@@ -65,10 +83,11 @@ const makeHarness = Effect.fn("TestProjectCommands.makeHarness")(function* () {
Effect.sync(() => {
metadataRequests.push(input.paths);
return {
- entries: input.paths.map(() => ({
- kind: "file" as const,
- byteLength: file.byteLength,
- })),
+ entries: input.paths.map(() =>
+ readResponse.missing
+ ? null
+ : { kind: "file" as const, byteLength: file.byteLength },
+ ),
};
}),
},
@@ -126,6 +145,35 @@ const makeHarness = Effect.fn("TestProjectCommands.makeHarness")(function* () {
});
describe("writeFile metadata", () => {
+ it.effect("preserves optional read results without seeding metadata for an absent file", () =>
+ Effect.gen(function* () {
+ const h = yield* makeHarness();
+ h.readResponse.missing = true;
+ const input = { cwd: "/repo", relativePath: "foo", allowMissing: true };
+ expect.soft(decodeReadFileInput(input)).toEqual(input);
+ const result = yield* AtomRegistry.getResult(
+ h.registry,
+ h.commands.readFile({ environmentId: ENVIRONMENT_ID, input }),
+ { suspendOnWaiting: true },
+ );
+ expect.soft(result).toEqual({
+ relativePath: "foo",
+ byteLength: 0,
+ contents: "",
+ truncated: false,
+ exists: false,
+ });
+ const metadata = h.commands.fileMetadata({
+ environmentId: ENVIRONMENT_ID,
+ input: { path: "/repo/foo" },
+ });
+ expect(
+ yield* AtomRegistry.getResult(h.registry, metadata, { suspendOnWaiting: true }),
+ ).toBeNull();
+ expect(h.metadataRequests).toEqual([["/repo/foo"]]);
+ }).pipe(Effect.scoped),
+ );
+
it.effect("reuses a current file read without another metadata request", () =>
Effect.gen(function* () {
const h = yield* makeHarness();
diff --git a/packages/client-runtime/src/state/projectCommands.ts b/packages/client-runtime/src/state/projectCommands.ts
index 12b57e48a46..ca9b8c7d024 100644
--- a/packages/client-runtime/src/state/projectCommands.ts
+++ b/packages/client-runtime/src/state/projectCommands.ts
@@ -143,7 +143,10 @@ export function createProjectEnvironmentAtoms<R, E>(
execute: (input) =>
fileMetadata.seedAfterRead(
request(WS_METHODS.projectsReadFile, input),
- (result, isCurrent) => fileMetadata.rememberFile(input.cwd, result, isCurrent),
+ (result, isCurrent) =>
+ result.exists === false
+ ? Effect.void
+ : fileMetadata.rememberFile(input.cwd, result, isCurrent),
),
}),
optimisticFile: (target: OptimisticProjectFileTarget) =>
diff --git a/packages/contracts/src/project.ts b/packages/contracts/src/project.ts
index d377311620a..ef4477575ff 100644
--- a/packages/contracts/src/project.ts
+++ b/packages/contracts/src/project.ts
@@ -418,6 +418,8 @@ export const ProjectReadFileInput = Schema.Struct({
// Workspace-relative, or an absolute host path for a file outside the
// workspace. Only workspace-relative paths can be written back.
relativePath: TrimmedNonEmptyString.check(Schema.isMaxLength(PROJECT_READ_FILE_PATH_MAX_LENGTH)),
+ // Optional files can be absent without failing the read.
+ allowMissing: Schema.optional(Schema.Boolean),
});
export type ProjectReadFileInput = typeof ProjectReadFileInput.Type;
@@ -426,6 +428,8 @@ export const ProjectReadFileResult = Schema.Struct({
contents: Schema.String,
byteLength: NonNegativeInt,
truncated: Schema.Boolean,
+ // Omitted by older servers; false only for an absent optional file.
+ exists: Schema.optional(Schema.Boolean),
});
export type ProjectReadFileResult = typeof ProjectReadFileResult.Type;