Add workspace file browser and preview panel (#3087)
This commit is contained in:
1 parent
477795697d
commit
de8bdc10fa
62 files changed
+2850
-9551
No files matched your search
@@ -4357,6 +4357,42 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("routes websocket rpc projects.listEntries and projects.readFile", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const workspaceDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-ws-project-files-" });
|
||||
yield* fs.makeDirectory(path.join(workspaceDir, "src"), { recursive: true });
|
||||
yield* fs.writeFileString(
|
||||
path.join(workspaceDir, "src", "index.ts"),
|
||||
"export const answer = 42;\n",
|
||||
);
|
||||
|
||||
yield* buildAppUnderTest();
|
||||
|
||||
const wsUrl = yield* getWsServerUrl("/ws");
|
||||
const response = yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) =>
|
||||
Effect.all({
|
||||
listing: client[WS_METHODS.projectsListEntries]({ cwd: workspaceDir }),
|
||||
file: client[WS_METHODS.projectsReadFile]({
|
||||
cwd: workspaceDir,
|
||||
relativePath: "src/index.ts",
|
||||
}),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
assert.isTrue(response.listing.entries.some((entry) => entry.path === "src/index.ts"));
|
||||
assert.deepEqual(response.file, {
|
||||
relativePath: "src/index.ts",
|
||||
contents: "export const answer = 42;\n",
|
||||
byteLength: 26,
|
||||
truncated: false,
|
||||
});
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("routes websocket rpc projects.searchEntries excludes gitignored files", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
|
||||
@@ -87,6 +87,35 @@ it.layer(TestLayer)("WorkspaceEntriesLive", (it) => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe("list", () => {
|
||||
it.effect("returns the complete cached workspace index", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTempDir();
|
||||
yield* writeTextFile(cwd, "src/components/Composer.tsx");
|
||||
yield* writeTextFile(cwd, "README.md");
|
||||
yield* writeTextFile(cwd, "node_modules/pkg/index.js");
|
||||
|
||||
const workspaceEntries = yield* WorkspaceEntries;
|
||||
const result = yield* workspaceEntries.list({ cwd });
|
||||
|
||||
expect(result.entries).toEqual(
|
||||
expect.arrayContaining([
|
||||
{ path: "src", kind: "directory" },
|
||||
{ path: "src/components", kind: "directory", parentPath: "src" },
|
||||
{
|
||||
path: "src/components/Composer.tsx",
|
||||
kind: "file",
|
||||
parentPath: "src/components",
|
||||
},
|
||||
{ path: "README.md", kind: "file" },
|
||||
]),
|
||||
);
|
||||
expect(result.entries.some((entry) => entry.path.startsWith("node_modules"))).toBe(false);
|
||||
expect(result.truncated).toBe(false);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
describe("search", () => {
|
||||
it.effect("returns files and directories relative to cwd", () =>
|
||||
Effect.gen(function* () {
|
||||
|
||||
@@ -530,9 +530,24 @@ export const makeWorkspaceEntries = Effect.gen(function* () {
|
||||
},
|
||||
);
|
||||
|
||||
const list: WorkspaceEntriesShape["list"] = Effect.fn("WorkspaceEntries.list")(function* (input) {
|
||||
const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd);
|
||||
return yield* Cache.get(workspaceIndexCache, normalizedCwd).pipe(
|
||||
Effect.map((index) => ({
|
||||
entries: index.entries.map(({ path: entryPath, kind, parentPath }) => ({
|
||||
path: entryPath,
|
||||
kind,
|
||||
...(parentPath ? { parentPath } : {}),
|
||||
})),
|
||||
truncated: index.truncated,
|
||||
})),
|
||||
);
|
||||
});
|
||||
|
||||
return {
|
||||
browse,
|
||||
invalidate,
|
||||
list,
|
||||
search,
|
||||
} satisfies WorkspaceEntriesShape;
|
||||
});
|
||||
|
||||
@@ -54,6 +54,64 @@ const writeTextFile = Effect.fn("writeTextFile")(function* (
|
||||
});
|
||||
|
||||
it.layer(TestLayer)("WorkspaceFileSystemLive", (it) => {
|
||||
describe("readFile", () => {
|
||||
it.effect("reads UTF-8 files relative to the workspace root", () =>
|
||||
Effect.gen(function* () {
|
||||
const workspaceFileSystem = yield* WorkspaceFileSystem;
|
||||
const cwd = yield* makeTempDir;
|
||||
yield* writeTextFile(cwd, "src/index.ts", "export const answer = 42;\n");
|
||||
|
||||
const result = yield* workspaceFileSystem.readFile({
|
||||
cwd,
|
||||
relativePath: "src/index.ts",
|
||||
});
|
||||
|
||||
expect(result).toEqual({
|
||||
relativePath: "src/index.ts",
|
||||
contents: "export const answer = 42;\n",
|
||||
byteLength: 26,
|
||||
truncated: false,
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects reads outside the workspace root", () =>
|
||||
Effect.gen(function* () {
|
||||
const workspaceFileSystem = yield* WorkspaceFileSystem;
|
||||
const cwd = yield* makeTempDir;
|
||||
|
||||
const error = yield* workspaceFileSystem
|
||||
.readFile({ cwd, relativePath: "../escape.md" })
|
||||
.pipe(Effect.flip);
|
||||
|
||||
expect(error.message).toContain(
|
||||
"Workspace file path must be relative to the project root: ../escape.md",
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects symlinks that resolve outside the workspace root", () =>
|
||||
Effect.gen(function* () {
|
||||
const workspaceFileSystem = yield* WorkspaceFileSystem;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const cwd = yield* makeTempDir;
|
||||
const outsideDir = yield* makeTempDir;
|
||||
yield* writeTextFile(outsideDir, "secret.txt", "outside\n");
|
||||
yield* fileSystem.symlink(
|
||||
path.join(outsideDir, "secret.txt"),
|
||||
path.join(cwd, "linked-secret.txt"),
|
||||
);
|
||||
|
||||
const error = yield* workspaceFileSystem
|
||||
.readFile({ cwd, relativePath: "linked-secret.txt" })
|
||||
.pipe(Effect.flip);
|
||||
|
||||
expect(error.message).toContain("resolves outside the project root");
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
describe("writeFile", () => {
|
||||
it.effect("writes files relative to the workspace root", () =>
|
||||
Effect.gen(function* () {
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off
|
||||
import fsPromises from "node:fs/promises";
|
||||
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
@@ -11,12 +14,74 @@ import {
|
||||
import { WorkspaceEntries } from "../Services/WorkspaceEntries.ts";
|
||||
import { WorkspacePaths } from "../Services/WorkspacePaths.ts";
|
||||
|
||||
const PROJECT_READ_FILE_MAX_BYTES = 1024 * 1024;
|
||||
|
||||
export const makeWorkspaceFileSystem = Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const workspacePaths = yield* WorkspacePaths;
|
||||
const workspaceEntries = yield* WorkspaceEntries;
|
||||
|
||||
const readFile: WorkspaceFileSystemShape["readFile"] = Effect.fn("WorkspaceFileSystem.readFile")(
|
||||
function* (input) {
|
||||
const target = yield* workspacePaths.resolveRelativePathWithinRoot({
|
||||
workspaceRoot: input.cwd,
|
||||
relativePath: input.relativePath,
|
||||
});
|
||||
|
||||
const result = yield* Effect.tryPromise({
|
||||
try: async () => {
|
||||
const [realWorkspaceRoot, realTargetPath] = await Promise.all([
|
||||
fsPromises.realpath(input.cwd),
|
||||
fsPromises.realpath(target.absolutePath),
|
||||
]);
|
||||
const relativeRealPath = path.relative(realWorkspaceRoot, realTargetPath);
|
||||
if (
|
||||
relativeRealPath.startsWith(`..${path.sep}`) ||
|
||||
relativeRealPath === ".." ||
|
||||
path.isAbsolute(relativeRealPath)
|
||||
) {
|
||||
throw new Error("Workspace file path resolves outside the project root.");
|
||||
}
|
||||
|
||||
const handle = await fsPromises.open(realTargetPath, "r");
|
||||
try {
|
||||
const stat = await handle.stat();
|
||||
if (!stat.isFile()) {
|
||||
throw new Error("Workspace path is not a file.");
|
||||
}
|
||||
const bytesToRead = Math.min(stat.size, PROJECT_READ_FILE_MAX_BYTES);
|
||||
const buffer = Buffer.alloc(bytesToRead);
|
||||
const { bytesRead } = await handle.read(buffer, 0, bytesToRead, 0);
|
||||
const fileBytes = buffer.subarray(0, bytesRead);
|
||||
if (fileBytes.includes(0)) {
|
||||
throw new Error("Binary files cannot be previewed as text.");
|
||||
}
|
||||
const contents = new TextDecoder("utf-8").decode(fileBytes);
|
||||
return {
|
||||
relativePath: target.relativePath,
|
||||
contents,
|
||||
byteLength: stat.size,
|
||||
truncated: stat.size > PROJECT_READ_FILE_MAX_BYTES,
|
||||
};
|
||||
} finally {
|
||||
await handle.close();
|
||||
}
|
||||
},
|
||||
catch: (cause) =>
|
||||
new WorkspaceFileSystemError({
|
||||
cwd: input.cwd,
|
||||
relativePath: input.relativePath,
|
||||
operation: "workspaceFileSystem.readFile",
|
||||
detail: cause instanceof Error ? cause.message : String(cause),
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
|
||||
return result;
|
||||
},
|
||||
);
|
||||
|
||||
const writeFile: WorkspaceFileSystemShape["writeFile"] = Effect.fn(
|
||||
"WorkspaceFileSystem.writeFile",
|
||||
)(function* (input) {
|
||||
@@ -52,7 +117,7 @@ export const makeWorkspaceFileSystem = Effect.gen(function* () {
|
||||
yield* workspaceEntries.invalidate(input.cwd);
|
||||
return { relativePath: target.relativePath };
|
||||
});
|
||||
return { writeFile } satisfies WorkspaceFileSystemShape;
|
||||
return { readFile, writeFile } satisfies WorkspaceFileSystemShape;
|
||||
});
|
||||
|
||||
export const WorkspaceFileSystemLive = Layer.effect(WorkspaceFileSystem, makeWorkspaceFileSystem);
|
||||
@@ -13,6 +13,8 @@ import type * as Effect from "effect/Effect";
|
||||
import type {
|
||||
FilesystemBrowseInput,
|
||||
FilesystemBrowseResult,
|
||||
ProjectListEntriesInput,
|
||||
ProjectListEntriesResult,
|
||||
ProjectSearchEntriesInput,
|
||||
ProjectSearchEntriesResult,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -50,6 +52,13 @@ export interface WorkspaceEntriesShape {
|
||||
input: FilesystemBrowseInput,
|
||||
) => Effect.Effect<FilesystemBrowseResult, WorkspaceEntriesBrowseError>;
|
||||
|
||||
/**
|
||||
* List the cached workspace index for a project root.
|
||||
*/
|
||||
readonly list: (
|
||||
input: ProjectListEntriesInput,
|
||||
) => Effect.Effect<ProjectListEntriesResult, WorkspaceEntriesError>;
|
||||
|
||||
/**
|
||||
* Search indexed workspace entries for files and directories matching the
|
||||
* provided query.
|
||||
|
||||
@@ -10,7 +10,12 @@ import * as Schema from "effect/Schema";
|
||||
import * as Context from "effect/Context";
|
||||
import type * as Effect from "effect/Effect";
|
||||
|
||||
import type { ProjectWriteFileInput, ProjectWriteFileResult } from "@t3tools/contracts";
|
||||
import type {
|
||||
ProjectReadFileInput,
|
||||
ProjectReadFileResult,
|
||||
ProjectWriteFileInput,
|
||||
ProjectWriteFileResult,
|
||||
} from "@t3tools/contracts";
|
||||
import { WorkspacePathOutsideRootError } from "./WorkspacePaths.ts";
|
||||
|
||||
export class WorkspaceFileSystemError extends Schema.TaggedErrorClass<WorkspaceFileSystemError>()(
|
||||
@@ -22,12 +27,26 @@ export class WorkspaceFileSystemError extends Schema.TaggedErrorClass<WorkspaceF
|
||||
detail: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {}
|
||||
) {
|
||||
override get message(): string {
|
||||
return this.detail;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* WorkspaceFileSystemShape - Service API for workspace-relative file operations.
|
||||
*/
|
||||
export interface WorkspaceFileSystemShape {
|
||||
/**
|
||||
* Read a UTF-8 text file relative to the workspace root.
|
||||
*/
|
||||
readonly readFile: (
|
||||
input: ProjectReadFileInput,
|
||||
) => Effect.Effect<
|
||||
ProjectReadFileResult,
|
||||
WorkspaceFileSystemError | WorkspacePathOutsideRootError
|
||||
>;
|
||||
|
||||
/**
|
||||
* Write a file relative to the workspace root.
|
||||
*
|
||||
|
||||
@@ -34,6 +34,8 @@ import {
|
||||
OrchestrationGetSnapshotError,
|
||||
OrchestrationGetTurnDiffError,
|
||||
ORCHESTRATION_WS_METHODS,
|
||||
ProjectListEntriesError,
|
||||
ProjectReadFileError,
|
||||
ProjectSearchEntriesError,
|
||||
ProjectWriteFileError,
|
||||
RelayClientInstallFailedError,
|
||||
@@ -160,6 +162,8 @@ const RPC_REQUIRED_SCOPE = new Map<string, AuthEnvironmentScope>([
|
||||
[WS_METHODS.sourceControlLookupRepository, AuthOrchestrationReadScope],
|
||||
[WS_METHODS.sourceControlCloneRepository, AuthOrchestrationOperateScope],
|
||||
[WS_METHODS.sourceControlPublishRepository, AuthOrchestrationOperateScope],
|
||||
[WS_METHODS.projectsListEntries, AuthOrchestrationReadScope],
|
||||
[WS_METHODS.projectsReadFile, AuthOrchestrationReadScope],
|
||||
[WS_METHODS.projectsSearchEntries, AuthOrchestrationReadScope],
|
||||
[WS_METHODS.projectsWriteFile, AuthOrchestrationOperateScope],
|
||||
[WS_METHODS.shellOpenInEditor, AuthOrchestrationOperateScope],
|
||||
@@ -1172,6 +1176,33 @@ const makeWsRpcLayer = (currentSession: AuthenticatedSession) =>
|
||||
),
|
||||
{ "rpc.aggregate": "workspace" },
|
||||
),
|
||||
[WS_METHODS.projectsListEntries]: (input) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.projectsListEntries,
|
||||
workspaceEntries.list(input).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProjectListEntriesError({
|
||||
message: `Failed to list workspace entries: ${cause.detail}`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
{ "rpc.aggregate": "workspace" },
|
||||
),
|
||||
[WS_METHODS.projectsReadFile]: (input) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.projectsReadFile,
|
||||
workspaceFileSystem.readFile(input).pipe(
|
||||
Effect.mapError((cause) => {
|
||||
const message = isWorkspacePathOutsideRootError(cause)
|
||||
? "Workspace file path must stay within the project root."
|
||||
: `Failed to read workspace file: ${cause.detail}`;
|
||||
return new ProjectReadFileError({ message, cause });
|
||||
}),
|
||||
),
|
||||
{ "rpc.aggregate": "workspace" },
|
||||
),
|
||||
[WS_METHODS.projectsWriteFile]: (input) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.projectsWriteFile,
|
||||
|
||||
Reference in new issue
Block a user