Skip to content

Commit 0ddcb1a

Browse files
juliusmarmingecodex
andcommitted
Add workspace directory browse support
- Move browse resolution and filtering into WorkspaceEntries - Wire websocket filesystemBrowse to the shared service - Add coverage for hidden, relative, and error cases Co-authored-by: codex <[email protected]>
1 parent 9448e45 commit 0ddcb1a

4 files changed

Lines changed: 203 additions & 93 deletions

File tree

‎apps/server/src/workspace/Layers/WorkspaceEntries.test.ts‎

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,11 @@ const searchWorkspaceEntries = (input: { cwd: string; query: string; limit: numb
6868
return yield* workspaceEntries.search(input);
6969
});
7070

71+
const appendSeparator = (input: string) =>
72+
input.endsWith("/") || input.endsWith("\\")
73+
? input
74+
: `${input}${process.platform === "win32" ? "\\" : "/"}`;
75+
7176
it.layer(TestLayer)("WorkspaceEntriesLive", (it) => {
7277
afterEach(() => {
7378
vi.restoreAllMocks();
@@ -275,4 +280,85 @@ it.layer(TestLayer)("WorkspaceEntriesLive", (it) => {
275280
}),
276281
);
277282
});
283+
284+
describe("browse", () => {
285+
it.effect("returns matching directories and excludes files", () =>
286+
Effect.gen(function* () {
287+
const workspaceEntries = yield* WorkspaceEntries;
288+
const path = yield* Path.Path;
289+
const cwd = yield* makeTempDir({ prefix: "t3code-workspace-browse-prefix-" });
290+
yield* writeTextFile(cwd, "alphabet.txt", "ignore me");
291+
yield* writeTextFile(cwd, "alpha/index.ts", "export {};\n");
292+
yield* writeTextFile(cwd, "alpine/index.ts", "export {};\n");
293+
294+
const result = yield* workspaceEntries.browse({
295+
partialPath: path.join(cwd, "alp"),
296+
});
297+
298+
expect(result).toEqual({
299+
parentPath: cwd,
300+
entries: [
301+
{ name: "alpha", fullPath: path.join(cwd, "alpha") },
302+
{ name: "alpine", fullPath: path.join(cwd, "alpine") },
303+
],
304+
});
305+
}),
306+
);
307+
308+
it.effect("shows dot directories in directory mode and hidden-prefix mode", () =>
309+
Effect.gen(function* () {
310+
const workspaceEntries = yield* WorkspaceEntries;
311+
const path = yield* Path.Path;
312+
const cwd = yield* makeTempDir({ prefix: "t3code-workspace-browse-hidden-" });
313+
yield* writeTextFile(cwd, ".config/settings.json", "{}");
314+
yield* writeTextFile(cwd, "config/settings.json", "{}");
315+
316+
const directoryResult = yield* workspaceEntries.browse({
317+
partialPath: appendSeparator(cwd),
318+
});
319+
const hiddenPrefixResult = yield* workspaceEntries.browse({
320+
partialPath: `${appendSeparator(cwd)}.c`,
321+
});
322+
323+
expect(directoryResult.entries.map((entry) => entry.name)).toEqual([".config", "config"]);
324+
expect(hiddenPrefixResult).toEqual({
325+
parentPath: cwd,
326+
entries: [{ name: ".config", fullPath: path.join(cwd, ".config") }],
327+
});
328+
}),
329+
);
330+
331+
it.effect("supports relative paths when cwd is provided", () =>
332+
Effect.gen(function* () {
333+
const workspaceEntries = yield* WorkspaceEntries;
334+
const path = yield* Path.Path;
335+
const cwd = yield* makeTempDir({ prefix: "t3code-workspace-browse-relative-" });
336+
yield* writeTextFile(cwd, "packages/pkg.json", "{}");
337+
338+
const result = yield* workspaceEntries.browse({
339+
cwd,
340+
partialPath: "./pack",
341+
});
342+
343+
expect(result).toEqual({
344+
parentPath: cwd,
345+
entries: [{ name: "packages", fullPath: path.join(cwd, "packages") }],
346+
});
347+
}),
348+
);
349+
350+
it.effect("rejects relative paths without cwd", () =>
351+
Effect.gen(function* () {
352+
const workspaceEntries = yield* WorkspaceEntries;
353+
354+
const error = yield* workspaceEntries
355+
.browse({
356+
partialPath: "./src",
357+
})
358+
.pipe(Effect.flip);
359+
360+
expect(error.detail).toBe("Relative filesystem browse paths require a current project.");
361+
}),
362+
);
363+
});
278364
});

‎apps/server/src/workspace/Layers/WorkspaceEntries.ts‎

Lines changed: 85 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
1+
import * as OS from "node:os";
12
import fsPromises from "node:fs/promises";
23
import type { Dirent } from "node:fs";
34

45
import { Cache, Duration, Effect, Exit, Layer, Option, Path } from "effect";
56

6-
import { type ProjectEntry } from "@t3tools/contracts";
7+
import { type FilesystemBrowseInput, type ProjectEntry } from "@t3tools/contracts";
8+
import { isExplicitRelativePath, isWindowsAbsolutePath } from "@t3tools/shared/path";
79
import {
810
insertRankedSearchResult,
911
normalizeSearchQuery,
@@ -14,6 +16,7 @@ import {
1416
import { GitCore } from "../../git/Services/GitCore.ts";
1517
import {
1618
WorkspaceEntries,
19+
WorkspaceEntriesBrowseError,
1720
WorkspaceEntriesError,
1821
type WorkspaceEntriesShape,
1922
} from "../Services/WorkspaceEntries.ts";
@@ -52,6 +55,16 @@ function toPosixPath(input: string): string {
5255
return input.replaceAll("\\", "/");
5356
}
5457

58+
function expandHomePath(input: string, path: Path.Path): string {
59+
if (input === "~") {
60+
return OS.homedir();
61+
}
62+
if (input.startsWith("~/") || input.startsWith("~\\")) {
63+
return path.join(OS.homedir(), input.slice(2));
64+
}
65+
return input;
66+
}
67+
5568
function parentPathOf(input: string): string | undefined {
5669
const separatorIndex = input.lastIndexOf("/");
5770
if (separatorIndex === -1) {
@@ -129,6 +142,36 @@ function directoryAncestorsOf(relativePath: string): string[] {
129142
return directories;
130143
}
131144

145+
const resolveBrowseTarget = (
146+
input: FilesystemBrowseInput,
147+
pathService: Path.Path,
148+
): Effect.Effect<string, WorkspaceEntriesBrowseError> =>
149+
Effect.gen(function* () {
150+
if (process.platform !== "win32" && isWindowsAbsolutePath(input.partialPath)) {
151+
return yield* new WorkspaceEntriesBrowseError({
152+
cwd: input.cwd,
153+
partialPath: input.partialPath,
154+
operation: "workspaceEntries.resolveBrowseTarget",
155+
detail: "Windows-style paths are only supported on Windows.",
156+
});
157+
}
158+
159+
if (!isExplicitRelativePath(input.partialPath)) {
160+
return pathService.resolve(expandHomePath(input.partialPath, pathService));
161+
}
162+
163+
if (!input.cwd) {
164+
return yield* new WorkspaceEntriesBrowseError({
165+
cwd: input.cwd,
166+
partialPath: input.partialPath,
167+
operation: "workspaceEntries.resolveBrowseTarget",
168+
detail: "Relative filesystem browse paths require a current project.",
169+
});
170+
}
171+
172+
return pathService.resolve(expandHomePath(input.cwd, pathService), input.partialPath);
173+
});
174+
132175
export const makeWorkspaceEntries = Effect.gen(function* () {
133176
const path = yield* Path.Path;
134177
const gitOption = yield* Effect.serviceOption(GitCore);
@@ -379,6 +422,46 @@ export const makeWorkspaceEntries = Effect.gen(function* () {
379422
},
380423
);
381424

425+
const browse: WorkspaceEntriesShape["browse"] = Effect.fn("WorkspaceEntries.browse")(
426+
function* (input) {
427+
const resolvedInputPath = yield* resolveBrowseTarget(input, path);
428+
const endsWithSeparator = /[\\/]$/.test(input.partialPath) || input.partialPath === "~";
429+
const parentPath = endsWithSeparator ? resolvedInputPath : path.dirname(resolvedInputPath);
430+
const prefix = endsWithSeparator ? "" : path.basename(resolvedInputPath);
431+
432+
const dirents = yield* Effect.tryPromise({
433+
try: () => fsPromises.readdir(parentPath, { withFileTypes: true }),
434+
catch: (cause) =>
435+
new WorkspaceEntriesBrowseError({
436+
cwd: input.cwd,
437+
partialPath: input.partialPath,
438+
operation: "workspaceEntries.browse.readDirectory",
439+
detail: `Unable to browse '${parentPath}': ${cause instanceof Error ? cause.message : String(cause)}`,
440+
cause,
441+
}),
442+
});
443+
444+
const showHidden = endsWithSeparator || prefix.startsWith(".");
445+
const lowerPrefix = prefix.toLowerCase();
446+
447+
return {
448+
parentPath,
449+
entries: dirents
450+
.filter(
451+
(dirent) =>
452+
dirent.isDirectory() &&
453+
dirent.name.toLowerCase().startsWith(lowerPrefix) &&
454+
(showHidden || !dirent.name.startsWith(".")),
455+
)
456+
.map((dirent) => ({
457+
name: dirent.name,
458+
fullPath: path.join(parentPath, dirent.name),
459+
}))
460+
.toSorted((left, right) => left.name.localeCompare(right.name)),
461+
};
462+
},
463+
);
464+
382465
const search: WorkspaceEntriesShape["search"] = Effect.fn("WorkspaceEntries.search")(
383466
function* (input) {
384467
const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd);
@@ -415,6 +498,7 @@ export const makeWorkspaceEntries = Effect.gen(function* () {
415498
);
416499

417500
return {
501+
browse,
418502
invalidate,
419503
search,
420504
} satisfies WorkspaceEntriesShape;

‎apps/server/src/workspace/Services/WorkspaceEntries.ts‎

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,12 @@
99
import { Schema, Context } from "effect";
1010
import type { Effect } from "effect";
1111

12-
import type { ProjectSearchEntriesInput, ProjectSearchEntriesResult } from "@t3tools/contracts";
12+
import type {
13+
FilesystemBrowseInput,
14+
FilesystemBrowseResult,
15+
ProjectSearchEntriesInput,
16+
ProjectSearchEntriesResult,
17+
} from "@t3tools/contracts";
1318

1419
export class WorkspaceEntriesError extends Schema.TaggedErrorClass<WorkspaceEntriesError>()(
1520
"WorkspaceEntriesError",
@@ -21,11 +26,29 @@ export class WorkspaceEntriesError extends Schema.TaggedErrorClass<WorkspaceEntr
2126
},
2227
) {}
2328

29+
export class WorkspaceEntriesBrowseError extends Schema.TaggedErrorClass<WorkspaceEntriesBrowseError>()(
30+
"WorkspaceEntriesBrowseError",
31+
{
32+
cwd: Schema.optional(Schema.String),
33+
partialPath: Schema.String,
34+
operation: Schema.String,
35+
detail: Schema.String,
36+
cause: Schema.optional(Schema.Defect),
37+
},
38+
) {}
39+
2440
/**
2541
* WorkspaceEntriesShape - Service API for workspace entry search and cache
2642
* invalidation.
2743
*/
2844
export interface WorkspaceEntriesShape {
45+
/**
46+
* Browse matching directories for the provided partial path.
47+
*/
48+
readonly browse: (
49+
input: FilesystemBrowseInput,
50+
) => Effect.Effect<FilesystemBrowseResult, WorkspaceEntriesBrowseError>;
51+
2952
/**
3053
* Search indexed workspace entries for files and directories matching the
3154
* provided query.

‎apps/server/src/ws.ts‎

Lines changed: 8 additions & 91 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,4 @@
1-
import {
2-
Cause,
3-
Duration,
4-
Effect,
5-
FileSystem,
6-
Layer,
7-
Option,
8-
Path,
9-
Queue,
10-
Ref,
11-
Schema,
12-
Stream,
13-
} from "effect";
1+
import { Cause, Duration, Effect, Layer, Option, Queue, Ref, Schema, Stream } from "effect";
142
import {
153
type AuthAccessStreamEvent,
164
AuthSessionId,
@@ -35,7 +23,6 @@ import {
3523
WS_METHODS,
3624
WsRpcGroup,
3725
} from "@t3tools/contracts";
38-
import { isExplicitRelativePath, isWindowsAbsolutePath } from "@t3tools/shared/path";
3926
import { clamp } from "effect/Number";
4027
import { HttpRouter, HttpServerRequest } from "effect/unstable/http";
4128
import { RpcSerialization, RpcServer } from "effect/unstable/rpc";
@@ -76,7 +63,6 @@ import {
7663
type SessionCredentialChange,
7764
} from "./auth/Services/SessionCredentialService";
7865
import { respondToAuthError } from "./auth/http";
79-
import { expandHomePath } from "./os-jank";
8066

8167
function isThreadDetailEvent(event: OrchestrationEvent): event is Extract<
8268
OrchestrationEvent,
@@ -786,84 +772,15 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
786772
[WS_METHODS.filesystemBrowse]: (input) =>
787773
observeRpcEffect(
788774
WS_METHODS.filesystemBrowse,
789-
Effect.gen(function* () {
790-
const fileSystem = yield* FileSystem.FileSystem;
791-
const pathService = yield* Path.Path;
792-
793-
if (process.platform !== "win32" && isWindowsAbsolutePath(input.partialPath)) {
794-
return yield* Effect.fail(
775+
workspaceEntries.browse(input).pipe(
776+
Effect.mapError(
777+
(cause) =>
795778
new FilesystemBrowseError({
796-
message: "Windows-style paths are only supported on Windows.",
779+
message: cause.detail,
780+
cause,
797781
}),
798-
);
799-
}
800-
801-
// Resolve the input path
802-
let resolvedInputPath: string;
803-
if (!isExplicitRelativePath(input.partialPath)) {
804-
resolvedInputPath = yield* expandHomePath(input.partialPath);
805-
resolvedInputPath = pathService.resolve(resolvedInputPath);
806-
} else {
807-
if (!input.cwd) {
808-
return yield* Effect.fail(
809-
new FilesystemBrowseError({
810-
message: "Relative filesystem browse paths require a current project.",
811-
}),
812-
);
813-
}
814-
const expandedCwd = yield* expandHomePath(input.cwd);
815-
resolvedInputPath = pathService.resolve(expandedCwd, input.partialPath);
816-
}
817-
818-
// Determine if the input ends with a separator (directory mode) or if it's a prefix (file mode)
819-
const endsWithSep = /[\\/]$/.test(input.partialPath) || input.partialPath === "~";
820-
const parentDir = endsWithSep
821-
? resolvedInputPath
822-
: pathService.dirname(resolvedInputPath);
823-
const prefix = endsWithSep ? "" : pathService.basename(resolvedInputPath);
824-
825-
// Read the directory
826-
const names: Array<string> = yield* fileSystem.readDirectory(parentDir).pipe(
827-
Effect.mapError(
828-
(cause) =>
829-
new FilesystemBrowseError({
830-
message: `Unable to browse '${parentDir}': ${Cause.pretty(Cause.fail(cause)).trim()}`,
831-
}),
832-
),
833-
);
834-
835-
// Filter and sort entries
836-
const showHidden = endsWithSep || prefix.startsWith(".");
837-
const lowerPrefix = prefix.toLowerCase();
838-
const filtered = names
839-
.filter(
840-
(name: string) =>
841-
name.toLowerCase().startsWith(lowerPrefix) &&
842-
(showHidden || !name.startsWith(".")),
843-
)
844-
.sort((left: string, right: string) => left.localeCompare(right));
845-
846-
// Get stats for each entry to filter to directories only
847-
const entries = yield* Effect.forEach(
848-
filtered,
849-
(name: string) =>
850-
fileSystem.stat(pathService.join(parentDir, name)).pipe(
851-
Effect.match({
852-
onFailure: () => null,
853-
onSuccess: (s) =>
854-
s.type === "Directory"
855-
? { name, fullPath: pathService.join(parentDir, name) }
856-
: null,
857-
}),
858-
),
859-
{ concurrency: 16 },
860-
);
861-
862-
return {
863-
parentPath: parentDir,
864-
entries: entries.filter((e): e is { name: string; fullPath: string } => e !== null),
865-
};
866-
}),
782+
),
783+
),
867784
{ "rpc.aggregate": "workspace" },
868785
),
869786
[WS_METHODS.subscribeGitStatus]: (input) =>

0 commit comments

Comments
 (0)