Compare commits

..
Author SHA1 Message Date
Cursor AgentandJulius Marminge faf9d87071 Format Effect refactors
Co-authored-by: Julius Marminge <[email protected]>
2026-07-01 16:11:08 +00:00
Cursor AgentandJulius Marminge 6cc87a3ab0 Use Schema JSON fixtures in diagnostics tests
Co-authored-by: Julius Marminge <[email protected]>
2026-07-01 16:09:55 +00:00
Cursor AgentandJulius Marminge 2789bbe9fd Assert Effect platform file errors
Co-authored-by: Julius Marminge <[email protected]>
2026-07-01 16:07:20 +00:00
Cursor AgentandJulius Marminge ea6ebcd134 Refine server Effect usage
Co-authored-by: Julius Marminge <[email protected]>
2026-07-01 16:06:02 +00:00
17 changed files with 289 additions and 262 deletions

No files matched your search

+3 -9
View File
@@ -26,8 +26,6 @@ import {
useClerkSettingsSheetDetent,
} from "../features/cloud/ClerkSettingsSheetDetent";
import { useAgentNotificationNavigation } from "../features/agent-awareness/notificationNavigation";
import { pushScreenAnimation } from "../lib/pushScreenAnimation";
import { useHeaderBlurEffect } from "../lib/useHeaderBlurEffect";
import { useThemeColor } from "../lib/useThemeColor";
function AppNavigator() {
@@ -47,9 +45,7 @@ function AppNavigatorContent() {
const { collapse, isExpanded } = useClerkSettingsSheetDetent();
const colorScheme = useColorScheme();
const statusBarBg = useThemeColor("--color-status-bar");
const screenColor = useThemeColor("--color-screen");
const sheetStyle = useResolveClassNames("bg-sheet");
const headerBlurEffect = useHeaderBlurEffect();
useAgentNotificationNavigation();
useThreadOutboxDrain();
@@ -100,10 +96,9 @@ function AppNavigatorContent() {
<Stack.Screen
name="index"
options={{
contentStyle: { backgroundColor: screenColor },
contentStyle: { backgroundColor: "transparent" },
headerShown: true,
headerTransparent: true,
headerBlurEffect,
headerShadowVisible: false,
}}
/>
@@ -117,10 +112,9 @@ function AppNavigatorContent() {
<Stack.Screen
name="threads/[environmentId]/[threadId]"
options={{
animation: pushScreenAnimation,
contentStyle: { backgroundColor: screenColor },
animation: "slide_from_right",
contentStyle: { backgroundColor: "transparent" },
gestureEnabled: true,
fullScreenGestureEnabled: true,
headerShown: false,
}}
/>
+1 -2
View File
@@ -1,6 +1,5 @@
import Stack from "expo-router/stack";
import { useResolveClassNames } from "uniwind";
import { pushScreenAnimation } from "../../lib/pushScreenAnimation";
import { useThemeColor } from "../../lib/useThemeColor";
export const unstable_settings = {
@@ -24,7 +23,7 @@ export default function ConnectionsLayout() {
}}
>
<Stack.Screen name="index" options={{ animation: "none" }} />
<Stack.Screen name="new" options={{ animation: pushScreenAnimation }} />
<Stack.Screen name="new" options={{ animation: "slide_from_right" }} />
</Stack>
);
}
+5 -9
View File
@@ -2,7 +2,6 @@ import Stack from "expo-router/stack";
import { useResolveClassNames } from "uniwind";
import { NewTaskFlowProvider } from "../../features/threads/new-task-flow-provider";
import { pushScreenAnimation } from "../../lib/pushScreenAnimation";
import { useThemeColor } from "../../lib/useThemeColor";
export const unstable_settings = {
@@ -30,24 +29,21 @@ export default function NewTaskLayout() {
<Stack.Screen name="index" options={{ animation: "none", title: "Choose project" }} />
<Stack.Screen
name="add-project/index"
options={{ animation: pushScreenAnimation, title: "New project" }}
options={{ animation: "slide_from_right", title: "New project" }}
/>
<Stack.Screen
name="add-project/repository"
options={{ animation: pushScreenAnimation, title: "Repository" }}
options={{ animation: "slide_from_right", title: "Repository" }}
/>
<Stack.Screen
name="add-project/destination"
options={{ animation: pushScreenAnimation, title: "Clone destination" }}
options={{ animation: "slide_from_right", title: "Clone destination" }}
/>
<Stack.Screen
name="add-project/local"
options={{ animation: pushScreenAnimation, title: "Local folder" }}
/>
<Stack.Screen
name="draft"
options={{ animation: pushScreenAnimation, title: "New task" }}
options={{ animation: "slide_from_right", title: "Local folder" }}
/>
<Stack.Screen name="draft" options={{ animation: "slide_from_right", title: "New task" }} />
</Stack>
</NewTaskFlowProvider>
);
+5 -6
View File
@@ -3,7 +3,6 @@ import { useCallback } from "react";
import { useResolveClassNames } from "uniwind";
import { useClerkSettingsSheetDetent } from "../../features/cloud/ClerkSettingsSheetDetent";
import { pushScreenAnimation } from "../../lib/pushScreenAnimation";
import { useThemeColor } from "../../lib/useThemeColor";
export const unstable_settings = {
@@ -38,25 +37,25 @@ export default function SettingsLayout() {
<Stack.Screen name="index" options={{ animation: "none", title: "Settings" }} />
<Stack.Screen
name="environments"
options={{ animation: pushScreenAnimation, title: "Environments" }}
options={{ animation: "slide_from_right", title: "Environments" }}
/>
<Stack.Screen
name="environment-new"
options={{ animation: pushScreenAnimation, title: "Add Environment" }}
options={{ animation: "slide_from_right", title: "Add Environment" }}
/>
<Stack.Screen
name="waitlist"
options={{ animation: pushScreenAnimation, title: "Join the waitlist" }}
options={{ animation: "slide_from_right", title: "Join the waitlist" }}
/>
<Stack.Screen
name="archive"
listeners={{ transitionEnd: handleExpandedRouteTransitionEnd }}
options={{ animation: pushScreenAnimation, title: "Archived Threads" }}
options={{ animation: "slide_from_right", title: "Archived Threads" }}
/>
<Stack.Screen
name="auth"
listeners={{ transitionEnd: handleExpandedRouteTransitionEnd }}
options={{ animation: pushScreenAnimation, title: "Sign in" }}
options={{ animation: "slide_from_right", title: "Sign in" }}
/>
</Stack>
);
@@ -2,11 +2,7 @@ import Stack from "expo-router/stack";
import { StyleSheet } from "react-native";
import { useResolveClassNames } from "uniwind";
import { pushScreenAnimation } from "../../../../lib/pushScreenAnimation";
import { useHeaderBlurEffect } from "../../../../lib/useHeaderBlurEffect";
export default function ThreadLayout() {
const headerBlurEffect = useHeaderBlurEffect();
const sheetStyle = StyleSheet.flatten(useResolveClassNames("bg-sheet"));
const headerBg = {
backgroundColor: (sheetStyle as { backgroundColor?: string })?.backgroundColor,
@@ -20,7 +16,6 @@ export default function ThreadLayout() {
contentStyle: { backgroundColor: "transparent" },
headerShown: true,
headerTransparent: true,
headerBlurEffect,
headerShadowVisible: false,
headerTitle: "",
}}
@@ -50,9 +45,8 @@ export default function ThreadLayout() {
<Stack.Screen
name="review"
options={{
animation: pushScreenAnimation,
animation: "slide_from_right",
contentStyle: sheetStyle,
fullScreenGestureEnabled: true,
headerBackButtonDisplayMode: "minimal",
headerShown: true,
headerTitle: "Files changed",
@@ -64,9 +58,8 @@ export default function ThreadLayout() {
<Stack.Screen
name="files/index"
options={{
animation: pushScreenAnimation,
animation: "slide_from_right",
contentStyle: sheetStyle,
fullScreenGestureEnabled: true,
headerBackButtonDisplayMode: "minimal",
headerShown: true,
headerTitle: "Files",
@@ -78,9 +71,8 @@ export default function ThreadLayout() {
<Stack.Screen
name="files/[...path]"
options={{
animation: pushScreenAnimation,
animation: "slide_from_right",
contentStyle: sheetStyle,
fullScreenGestureEnabled: true,
headerBackButtonDisplayMode: "minimal",
headerShown: true,
headerTitle: "File",
@@ -103,11 +95,8 @@ export default function ThreadLayout() {
<Stack.Screen
name="terminal"
options={{
animation: pushScreenAnimation,
animation: "slide_from_right",
contentStyle: { backgroundColor: "#050505" },
// No fullScreenGestureEnabled here: the terminal consumes
// horizontal pans (readline editing, mouse reporting), so
// back-swipe stays confined to the screen edge.
headerBackButtonDisplayMode: "minimal",
headerShown: true,
headerShadowVisible: false,
@@ -2,8 +2,6 @@ import Stack from "expo-router/stack";
import { StyleSheet } from "react-native";
import { useResolveClassNames } from "uniwind";
import { pushScreenAnimation } from "../../../../../lib/pushScreenAnimation";
export const unstable_settings = {
anchor: "index",
};
@@ -25,7 +23,7 @@ export default function GitSheetLayout() {
<Stack.Screen
name="commit"
options={{
animation: pushScreenAnimation,
animation: "slide_from_right",
headerShown: true,
headerTitle: "Commit changes",
headerBackTitle: "",
@@ -36,7 +34,7 @@ export default function GitSheetLayout() {
<Stack.Screen
name="branches"
options={{
animation: pushScreenAnimation,
animation: "slide_from_right",
headerShown: true,
headerTitle: "Branches & worktrees",
headerBackTitle: "",
@@ -47,7 +45,7 @@ export default function GitSheetLayout() {
<Stack.Screen
name="review"
options={{
animation: pushScreenAnimation,
animation: "slide_from_right",
headerShown: true,
headerTitle: "Review changes",
headerBackTitle: "",
@@ -19,7 +19,6 @@ import { cn } from "../../lib/cn";
import { tryOpenExternalUrl } from "../../lib/openExternalUrl";
import { buildThreadFilesNavigation } from "../../lib/routes";
import { MOBILE_TYPOGRAPHY } from "../../lib/typography";
import { useHeaderBlurEffect } from "../../lib/useHeaderBlurEffect";
import { useThemeColor } from "../../lib/useThemeColor";
import { useThreadSelection } from "../../state/use-thread-selection";
import { useSelectedThreadWorktree } from "../../state/use-selected-thread-worktree";
@@ -445,7 +444,6 @@ function FilesToolbarBottomFade() {
export function ThreadFilesTreeScreen() {
const router = useRouter();
const headerBlurEffect = useHeaderBlurEffect();
const [searchQuery, setSearchQuery] = useState("");
const { cwd, environmentId, projectName, selectedThread, threadId } = useThreadFilesWorkspace();
const entriesQuery = useEnvironmentQuery(
@@ -483,7 +481,6 @@ export function ThreadFilesTreeScreen() {
title: "Files",
headerShown: true,
headerTransparent: true,
headerBlurEffect,
headerStyle: { backgroundColor: "transparent" },
headerShadowVisible: false,
headerTitle: () => <FilesHeaderTitle projectName={projectName} />,
@@ -11,7 +11,6 @@ import {
import { Stack } from "expo-router";
import { Text as RNText, View } from "react-native";
import { useHeaderBlurEffect } from "../../lib/useHeaderBlurEffect";
import { useThemeColor } from "../../lib/useThemeColor";
import { MOBILE_TYPOGRAPHY } from "../../lib/typography";
import type { HomeProjectSortOrder } from "./homeThreadList";
@@ -73,7 +72,6 @@ export function HomeHeader(props: {
readonly onOpenSettings: () => void;
readonly onStartNewTask: () => void;
}) {
const headerBlurEffect = useHeaderBlurEffect();
const iconColor = useThemeColor("--color-icon");
const mutedColor = useThemeColor("--color-foreground-muted");
const subtleColor = useThemeColor("--color-subtle");
@@ -90,7 +88,6 @@ export function HomeHeader(props: {
headerShown: true,
headerTransparent: true,
headerStyle: { backgroundColor: "transparent" },
headerBlurEffect,
headerShadowVisible: false,
headerTintColor: iconColor,
headerTitle: "",
@@ -19,7 +19,6 @@ import { AppText as Text } from "../../components/AppText";
import { environmentCatalog } from "../../connection/catalog";
import { useEnvironmentPresentation } from "../../state/presentation";
import { useAtomCommand } from "../../state/use-atom-command";
import { useHeaderBlurEffect } from "../../lib/useHeaderBlurEffect";
import { useThemeColor } from "../../lib/useThemeColor";
import { MOBILE_TYPOGRAPHY } from "../../lib/typography";
import { useThreadDraftForThread } from "../../state/use-thread-composer-state";
@@ -114,7 +113,6 @@ function ReviewSelectionActionBar(props: {
export function ReviewSheet() {
const insets = useSafeAreaInsets();
const colorScheme = useColorScheme();
const headerBlurEffect = useHeaderBlurEffect();
const headerForeground = String(useThemeColor("--color-foreground"));
const headerMuted = String(useThemeColor("--color-foreground-muted"));
const headerIcon = String(useThemeColor("--color-icon"));
@@ -243,7 +241,6 @@ export function ReviewSheet() {
<Stack.Screen
options={{
headerTransparent: true,
headerBlurEffect,
headerShadowVisible: false,
headerTintColor: headerIcon,
headerStyle: {
@@ -253,11 +253,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
() =>
Gesture.Pan()
.enabled(!isSplitLayout)
// Confine the drawer pan to the top-left corner where it completes
// (see the `event.y` check below). Covering the full left edge stole
// the touch from the native swipe-back gesture, leaving back
// navigation dead below the header.
.hitSlop({ left: 0, width: 40, top: 0, height: drawerGestureThreshold })
.hitSlop({ left: 0, width: 40 })
.activeOffsetX([10, 999])
.failOffsetY([-24, 24])
.onEnd((event) => {
@@ -5,7 +5,6 @@ import { EnvironmentId, type ProjectScript } from "@t3tools/contracts";
import { projectScriptCwd, projectScriptRuntimeEnv } from "@t3tools/shared/projectScripts";
import { Pressable, ScrollView, Text as RNText, View } from "react-native";
import { useWorkspaceState } from "../../state/workspace";
import { useHeaderBlurEffect } from "../../lib/useHeaderBlurEffect";
import { useThemeColor } from "../../lib/useThemeColor";
import { useEnvironmentQuery } from "../../state/query";
import { dismissGitActionResult, useGitActionProgress } from "../../state/use-vcs-action-state";
@@ -105,7 +104,6 @@ export function ThreadRouteScreen() {
const iconColor = String(useThemeColor("--color-icon"));
const foregroundColor = String(useThemeColor("--color-foreground"));
const secondaryFg = String(useThemeColor("--color-foreground-secondary"));
const headerBlurEffect = useHeaderBlurEffect();
/* ─── Git status for native header trigger ───────────────────────── */
const gitStatus = useEnvironmentQuery(
@@ -328,7 +326,6 @@ export function ThreadRouteScreen() {
headerShown: true,
headerTransparent: true,
headerStyle: { backgroundColor: "transparent" },
headerBlurEffect,
headerShadowVisible: false,
headerTintColor: iconColor,
headerBackTitle: "",
@@ -1,12 +0,0 @@
import { Platform } from "react-native";
/**
* Stack animation for pushed (non-sheet) screens.
*
* iOS keeps the default push animation: forcing `slide_from_right` switches
* react-native-screens to its custom swipe animator, which paints a black
* void behind the outgoing screen during interactive swipe-back. The native
* default is visually the same slide with proper parallax over the previous
* screen. Android has no interactive pop, so it keeps `slide_from_right`.
*/
export const pushScreenAnimation = Platform.OS === "ios" ? "default" : "slide_from_right";
@@ -1,15 +0,0 @@
import { useColorScheme } from "react-native";
/**
* Blur effect for transparent navigation headers.
*
* Recent iOS betas stopped drawing the implicit material behind transparent
* navigation bars, and the trait-adaptive `systemChromeMaterial` resolves to
* its light variant there even while the app renders in dark mode — so pick
* the light/dark variant explicitly from the app color scheme.
*/
export function useHeaderBlurEffect() {
return useColorScheme() === "dark"
? ("systemChromeMaterialDark" as const)
: ("systemChromeMaterialLight" as const);
}
@@ -1,8 +1,9 @@
import { describe, expect, it } from "@effect/vitest";
import { assert, describe, expect, it } from "@effect/vitest";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as Sink from "effect/Sink";
import * as Stream from "effect/Stream";
import { ChildProcessSpawner } from "effect/unstable/process";
@@ -11,6 +12,7 @@ import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as ProcessDiagnostics from "./ProcessDiagnostics.ts";
const encoder = new TextEncoder();
const encodeJsonFixture = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
function mockHandle(result: {
readonly stdout?: string;
@@ -67,6 +69,108 @@ describe("ProcessDiagnostics", () => {
}),
);
it.effect("parses Windows CIM JSON arrays with command fallback defaults", () =>
Effect.sync(() => {
const rows = ProcessDiagnostics.parseWindowsProcessRows(
encodeJsonFixture([
{
ProcessId: 10,
ParentProcessId: 1,
CommandLine: "node server.js",
Name: "node.exe",
Status: "Running",
WorkingSetSize: 1234.4,
PercentProcessorTime: 2.5,
},
{
ProcessId: 11,
ParentProcessId: 10,
CommandLine: "",
Name: "agent.exe",
},
]),
);
assert.deepEqual(rows, [
{
pid: 10,
ppid: 1,
pgid: null,
status: "Running",
cpuPercent: 2.5,
rssBytes: 1234,
elapsed: "",
command: "node server.js",
},
{
pid: 11,
ppid: 10,
pgid: null,
status: "Live",
cpuPercent: 0,
rssBytes: 0,
elapsed: "",
command: "agent.exe",
},
]);
}),
);
it.effect("parses single Windows CIM JSON objects", () =>
Effect.sync(() => {
const rows = ProcessDiagnostics.parseWindowsProcessRows(
encodeJsonFixture({
ProcessId: 20,
ParentProcessId: 10,
CommandLine: "codex app-server",
WorkingSetSize: 4096,
PercentProcessorTime: 1,
}),
);
assert.deepEqual(rows, [
{
pid: 20,
ppid: 10,
pgid: null,
status: "Live",
cpuPercent: 1,
rssBytes: 4096,
elapsed: "",
command: "codex app-server",
},
]);
}),
);
it.effect("ignores malformed Windows CIM output and invalid records", () =>
Effect.sync(() => {
assert.deepEqual(ProcessDiagnostics.parseWindowsProcessRows("{not-json"), []);
assert.deepEqual(
ProcessDiagnostics.parseWindowsProcessRows(
encodeJsonFixture([
{ ProcessId: 0, ParentProcessId: 1, CommandLine: "missing-pid" },
{ ProcessId: 30, ParentProcessId: -1, CommandLine: "missing-parent" },
{ ProcessId: 31, ParentProcessId: 1, CommandLine: "" },
{ ProcessId: 32, ParentProcessId: 1, CommandLine: "valid" },
]),
),
[
{
pid: 32,
ppid: 1,
pgid: null,
status: "Live",
cpuPercent: 0,
rssBytes: 0,
elapsed: "",
command: "valid",
},
],
);
}),
);
it.effect("aggregates only descendants of the server process", () =>
Effect.sync(() => {
const diagnostics = ProcessDiagnostics.aggregateProcessDiagnostics({
@@ -121,6 +121,21 @@ const ProcessDiagnosticsError = Schema.Union([
type ProcessDiagnosticsError = typeof ProcessDiagnosticsError.Type;
const isProcessDiagnosticsError = Schema.is(ProcessDiagnosticsError);
const WindowsCimProcessRecord = Schema.Struct({
ProcessId: Schema.Number,
ParentProcessId: Schema.Number,
CommandLine: Schema.optional(Schema.NullOr(Schema.String)),
Name: Schema.optional(Schema.NullOr(Schema.String)),
WorkingSetSize: Schema.optional(Schema.NullOr(Schema.Number)),
PercentProcessorTime: Schema.optional(Schema.NullOr(Schema.Number)),
Status: Schema.optional(Schema.NullOr(Schema.String)),
});
type WindowsCimProcessRecord = typeof WindowsCimProcessRecord.Type;
const decodeWindowsCimProcessRecord = Schema.decodeUnknownOption(WindowsCimProcessRecord);
const decodeWindowsCimProcessJson = Schema.decodeUnknownOption(
Schema.fromJsonString(Schema.Unknown),
);
function parsePositiveInt(value: string): number | null {
const parsed = Number.parseInt(value, 10);
return Number.isInteger(parsed) && parsed > 0 ? parsed : null;
@@ -201,51 +216,57 @@ export function parsePosixProcessRows(output: string): ReadonlyArray<ProcessRow>
return rows;
}
function normalizeWindowsProcessRow(value: unknown): ProcessRow | null {
if (typeof value !== "object" || value === null) return null;
const record = value as Record<string, unknown>;
const pid = typeof record.ProcessId === "number" ? record.ProcessId : null;
const ppid = typeof record.ParentProcessId === "number" ? record.ParentProcessId : null;
const commandLine =
typeof record.CommandLine === "string" && record.CommandLine.trim().length > 0
? record.CommandLine
: typeof record.Name === "string"
? record.Name
: null;
const workingSet =
typeof record.WorkingSetSize === "number" && Number.isFinite(record.WorkingSetSize)
? Math.max(0, Math.round(record.WorkingSetSize))
: 0;
const cpuPercent =
typeof record.PercentProcessorTime === "number" && Number.isFinite(record.PercentProcessorTime)
? Math.max(0, record.PercentProcessorTime)
: 0;
if (!pid || pid <= 0 || ppid === null || ppid < 0 || !commandLine) return null;
return {
pid,
ppid,
pgid: null,
status: typeof record.Status === "string" && record.Status.length > 0 ? record.Status : "Live",
cpuPercent,
rssBytes: workingSet,
elapsed: "",
command: commandLine,
};
function nonEmptyStringOption(value: string | null | undefined): Option.Option<string> {
return typeof value === "string" && value.trim().length > 0 ? Option.some(value) : Option.none();
}
function parseWindowsProcessRows(output: string): ReadonlyArray<ProcessRow> {
function optionalNonNegativeNumber(value: number | null | undefined): number {
return typeof value === "number" && Number.isFinite(value) ? Math.max(0, value) : 0;
}
function normalizeWindowsProcessRow(value: unknown): Option.Option<ProcessRow> {
return Option.flatMap(decodeWindowsCimProcessRecord(value), (record) => {
if (
!Number.isInteger(record.ProcessId) ||
record.ProcessId <= 0 ||
!Number.isInteger(record.ParentProcessId) ||
record.ParentProcessId < 0
) {
return Option.none();
}
return Option.map(
nonEmptyStringOption(record.CommandLine).pipe(
Option.orElse(() => nonEmptyStringOption(record.Name)),
),
(command) => ({
pid: record.ProcessId,
ppid: record.ParentProcessId,
pgid: null,
status: Option.getOrElse(nonEmptyStringOption(record.Status), () => "Live"),
cpuPercent: optionalNonNegativeNumber(record.PercentProcessorTime),
rssBytes: Math.round(optionalNonNegativeNumber(record.WorkingSetSize)),
elapsed: "",
command,
}),
);
});
}
export function parseWindowsProcessRows(output: string): ReadonlyArray<ProcessRow> {
if (output.trim().length === 0) return [];
try {
const parsed = JSON.parse(output) as unknown;
const records = Array.isArray(parsed) ? parsed : [parsed];
return records.flatMap((record) => {
const row = normalizeWindowsProcessRow(record);
return row ? [row] : [];
});
} catch {
return [];
}
return Option.match(decodeWindowsCimProcessJson(output), {
onNone: () => [],
onSome: (parsed) => {
const rows: ProcessRow[] = [];
const records = Array.isArray(parsed) ? parsed : [parsed];
for (const record of records) {
const row = normalizeWindowsProcessRow(record);
if (Option.isSome(row)) rows.push(row.value);
}
return rows;
},
});
}
export function buildDescendantEntries(
@@ -185,8 +185,15 @@ it.layer(TestLayer, { excludeTestServices: true })("WorkspaceFileSystemLive", (i
operationPath: resolvedPath,
operation: "realpath-target",
});
expect(error.cause).toBeInstanceOf(Error);
expect((error.cause as NodeJS.ErrnoException).code).toBe("ENOENT");
expect(error.cause).toMatchObject({
_tag: "PlatformError",
reason: {
_tag: "NotFound",
module: "FileSystem",
method: "realPath",
pathOrDescriptor: resolvedPath,
},
});
}),
);
});
+90 -127
View File
@@ -1,4 +1,3 @@
// @effect-diagnostics nodeBuiltinImport:off
/**
* WorkspaceFileSystem - Effect service contract for workspace file mutations.
*
@@ -7,8 +6,6 @@
*
* @module WorkspaceFileSystem
*/
import * as NodeFSP from "node:fs/promises";
import type {
ProjectReadFileInput,
ProjectReadFileResult,
@@ -19,6 +16,7 @@ import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
@@ -26,6 +24,7 @@ import * as WorkspaceEntries from "./WorkspaceEntries.ts";
import * as WorkspacePaths from "./WorkspacePaths.ts";
const PROJECT_READ_FILE_MAX_BYTES = 1024 * 1024;
const PROJECT_READ_FILE_MAX_SIZE = FileSystem.Size(PROJECT_READ_FILE_MAX_BYTES);
export class WorkspaceFileSystemOperationError extends Schema.TaggedErrorClass<WorkspaceFileSystemOperationError>()(
"WorkspaceFileSystemOperationError",
@@ -132,6 +131,23 @@ export const make = Effect.gen(function* () {
const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
const operationError =
(
input: ProjectReadFileInput | ProjectWriteFileInput,
resolvedPath: string,
operationPath: string,
operation: WorkspaceFileSystemOperationError["operation"],
) =>
(cause: unknown) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath,
operationPath,
operation,
cause,
});
const readFile: WorkspaceFileSystem["Service"]["readFile"] = Effect.fn(
"WorkspaceFileSystem.readFile",
)(function* (input) {
@@ -140,30 +156,20 @@ export const make = Effect.gen(function* () {
relativePath: input.relativePath,
});
const realWorkspaceRoot = yield* Effect.tryPromise({
try: () => NodeFSP.realpath(input.cwd),
catch: (cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: target.absolutePath,
operationPath: input.cwd,
operation: "realpath-workspace-root",
cause,
}),
});
const realTargetPath = yield* Effect.tryPromise({
try: () => NodeFSP.realpath(target.absolutePath),
catch: (cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: target.absolutePath,
operationPath: target.absolutePath,
operation: "realpath-target",
cause,
}),
});
const realWorkspaceRoot = yield* fileSystem
.realPath(input.cwd)
.pipe(
Effect.mapError(
operationError(input, target.absolutePath, input.cwd, "realpath-workspace-root"),
),
);
const realTargetPath = yield* fileSystem
.realPath(target.absolutePath)
.pipe(
Effect.mapError(
operationError(input, target.absolutePath, target.absolutePath, "realpath-target"),
),
);
const relativeRealPath = path.relative(realWorkspaceRoot, realTargetPath);
if (
relativeRealPath.startsWith(`..${path.sep}`) ||
@@ -178,84 +184,48 @@ export const make = Effect.gen(function* () {
});
}
return yield* Effect.acquireUseRelease(
Effect.tryPromise({
try: () => NodeFSP.open(realTargetPath, "r"),
catch: (cause) =>
new WorkspaceFileSystemOperationError({
return yield* Effect.scoped(
Effect.gen(function* () {
const file = yield* fileSystem
.open(realTargetPath, { flag: "r" })
.pipe(Effect.mapError(operationError(input, realTargetPath, realTargetPath, "open")));
const stat = yield* file.stat.pipe(
Effect.mapError(operationError(input, realTargetPath, realTargetPath, "stat")),
);
if (stat.type !== "File") {
return yield* new WorkspacePathNotFileError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
operationPath: realTargetPath,
operation: "open",
cause,
}),
});
}
const bytesToRead =
stat.size > PROJECT_READ_FILE_MAX_SIZE ? PROJECT_READ_FILE_MAX_BYTES : Number(stat.size);
const fileBytes =
bytesToRead === 0
? new Uint8Array()
: yield* file
.readAlloc(bytesToRead)
.pipe(
Effect.map(Option.getOrElse(() => new Uint8Array())),
Effect.mapError(operationError(input, realTargetPath, realTargetPath, "read")),
);
if (fileBytes.includes(0)) {
return yield* new WorkspaceBinaryFileError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
});
}
return {
relativePath: target.relativePath,
contents: new TextDecoder("utf-8").decode(fileBytes),
byteLength: Number(stat.size),
truncated: stat.size > PROJECT_READ_FILE_MAX_SIZE,
};
}),
(handle) =>
Effect.gen(function* () {
const stat = yield* Effect.tryPromise({
try: () => handle.stat(),
catch: (cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
operationPath: realTargetPath,
operation: "stat",
cause,
}),
});
if (!stat.isFile()) {
return yield* new WorkspacePathNotFileError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
});
}
const bytesToRead = Math.min(stat.size, PROJECT_READ_FILE_MAX_BYTES);
const buffer = Buffer.alloc(bytesToRead);
const { bytesRead } = yield* Effect.tryPromise({
try: () => handle.read(buffer, 0, bytesToRead, 0),
catch: (cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
operationPath: realTargetPath,
operation: "read",
cause,
}),
});
const fileBytes = buffer.subarray(0, bytesRead);
if (fileBytes.includes(0)) {
return yield* new WorkspaceBinaryFileError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
});
}
return {
relativePath: target.relativePath,
contents: new TextDecoder("utf-8").decode(fileBytes),
byteLength: stat.size,
truncated: stat.size > PROJECT_READ_FILE_MAX_BYTES,
};
}),
(handle) =>
Effect.tryPromise({
try: () => handle.close(),
catch: (cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
operationPath: realTargetPath,
operation: "close",
cause,
}),
}),
);
});
@@ -267,32 +237,25 @@ export const make = Effect.gen(function* () {
relativePath: input.relativePath,
});
yield* fileSystem.makeDirectory(path.dirname(target.absolutePath), { recursive: true }).pipe(
Effect.mapError(
(cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: target.absolutePath,
operationPath: path.dirname(target.absolutePath),
operation: "make-directory",
cause,
}),
),
);
yield* fileSystem.writeFileString(target.absolutePath, input.contents).pipe(
Effect.mapError(
(cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: target.absolutePath,
operationPath: target.absolutePath,
operation: "write-file",
cause,
}),
),
);
yield* fileSystem
.makeDirectory(path.dirname(target.absolutePath), { recursive: true })
.pipe(
Effect.mapError(
operationError(
input,
target.absolutePath,
path.dirname(target.absolutePath),
"make-directory",
),
),
);
yield* fileSystem
.writeFileString(target.absolutePath, input.contents)
.pipe(
Effect.mapError(
operationError(input, target.absolutePath, target.absolutePath, "write-file"),
),
);
yield* workspaceEntries.refresh(input.cwd);
return { relativePath: target.relativePath };
});