diff --git a/apps/server/src/cli/project.test.ts b/apps/server/src/cli/project.test.ts index 5e33ad84bc120..c0042a1aa514b 100644 --- a/apps/server/src/cli/project.test.ts +++ b/apps/server/src/cli/project.test.ts @@ -127,7 +127,7 @@ it.effect("adds, renames, and removes projects through the V2 project CLI domain yield* runCli(["project", "add", workspaceRoot, "--title", "Alpha", "--base-dir", baseDir]); const added = (yield* readProjects(baseDir)).projects[0]; assert.equal(added?.title, "Alpha"); - assert.equal(added?.workspaceRoot, workspaceRoot); + assert.equal(added?.workspaceRoot, NodeFS.realpathSync(workspaceRoot)); yield* runCli(["project", "rename", workspaceRoot, "Beta", "--base-dir", baseDir]); assert.equal((yield* readProjects(baseDir)).projects[0]?.title, "Beta"); @@ -230,7 +230,8 @@ it.effect("does not send a token to whatever took over a dead server's port", () const makeProjectLookupFixture = Effect.fn("ProjectCliTest.makeProjectLookupFixture")(function* () { const fs = yield* FileSystem.FileSystem; - const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-v2-project-lookup-" }); + const temporaryRoot = yield* fs.makeTempDirectoryScoped({ prefix: "t3-v2-project-lookup-" }); + const root = yield* fs.realPath(temporaryRoot); const baseDir = NodePath.join(root, "state"); const workspaceRoot = NodePath.join(root, "workspace"); yield* fs.makeDirectory(workspaceRoot); @@ -500,7 +501,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))( }), ); - it.effect("normalizes existing paths without conflating separately registered symlinks", () => + it.effect("normalizes existing paths and resolves symlink aliases to the same project", () => Effect.gen(function* () { const { baseDir, workspaceRoot, project } = yield* makeProjectLookupFixture(); yield* runCli([ @@ -514,25 +515,55 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))( assert.equal((yield* readProjects(baseDir)).projects[0]?.title, "Normalized"); const aliasPath = `${workspaceRoot}-alias`; NodeFS.symlinkSync(workspaceRoot, aliasPath, "junction"); - const unknownAlias = yield* runCli([ - "project", - "remove", - aliasPath, - "--base-dir", - baseDir, - ]).pipe(Effect.flip); - assert.include(unknownAlias.message, "No active project found"); - yield* runCli(["project", "add", aliasPath, "--base-dir", baseDir]); - const added = (yield* readProjects(baseDir)).projects; - assert.equal(added.length, 2); - const aliasProject = added.find((entry) => entry.workspaceRoot === aliasPath); - assert.isDefined(aliasProject); - assert.notEqual(aliasProject?.id, project.id); - yield* runCli(["project", "remove", `${aliasPath}${NodePath.sep}.`, "--base-dir", baseDir]); + const duplicate = yield* runCli(["project", "add", aliasPath, "--base-dir", baseDir]).pipe( + Effect.flip, + ); + assert.include(duplicate.message, "already exists"); assert.deepEqual( (yield* readProjects(baseDir)).projects.map((entry) => entry.id), [project.id], ); + const physicalRoot = `${workspaceRoot}-physical`; + NodeFS.mkdirSync(physicalRoot); + yield* runCli(["project", "add", physicalRoot, "--base-dir", baseDir]); + const physicalProject = (yield* readProjects(baseDir)).projects.find( + (entry) => entry.workspaceRoot === physicalRoot, + ); + assert.isDefined(physicalProject); + NodeFS.rmdirSync(physicalRoot); + NodeFS.renameSync(workspaceRoot, physicalRoot); + NodeFS.symlinkSync(`${workspaceRoot}-physical`, workspaceRoot, "junction"); + yield* runCli([ + "project", + "rename", + `${workspaceRoot}${NodePath.sep}.`, + "Saved alias", + "--base-dir", + baseDir, + ]); + const renamed = (yield* readProjects(baseDir)).projects; + assert.equal(renamed.find((entry) => entry.id === project.id)?.title, "Saved alias"); + assert.equal( + renamed.find((entry) => entry.id === physicalProject.id)?.title, + physicalProject.title, + ); + yield* runCli(["project", "remove", physicalProject.id, "--base-dir", baseDir]); + yield* withProjectService(baseDir, (projects) => + projects.update({ + commandId: CommandId.make("project-cli-archive-legacy-alias"), + projectId: project.id, + archived: true, + }), + ); + yield* runCli(["project", "add", ` ${aliasPath} `, "--base-dir", baseDir]); + const restored = (yield* readProjects(baseDir)).projects; + assert.lengthOf(restored, 1); + assert.equal(restored[0]?.id, project.id); + assert.isNull(restored[0]?.archivedAt); + yield* runCli(["project", "rename", aliasPath, "Legacy", "--base-dir", baseDir]); + assert.equal((yield* readProjects(baseDir)).projects[0]?.title, "Legacy"); + yield* runCli(["project", "remove", `${aliasPath}${NodePath.sep}.`, "--base-dir", baseDir]); + assert.lengthOf((yield* readProjects(baseDir)).projects, 0); assert.isTrue(NodeFS.existsSync(workspaceRoot)); }), ); diff --git a/apps/server/src/cli/project.ts b/apps/server/src/cli/project.ts index 3e59c5bd4735c..72fc142a7be59 100644 --- a/apps/server/src/cli/project.ts +++ b/apps/server/src/cli/project.ts @@ -7,6 +7,8 @@ import { type ProjectSnapshot, ProjectId, } from "@t3tools/contracts"; +import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion"; +import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Console from "effect/Console"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Duration from "effect/Duration"; @@ -300,11 +302,24 @@ const findActiveProjectTarget = Effect.fn("findActiveProjectTarget")(function* ( ? normalizedWorkspaceRootResult.success : normalizedWorkspaceRootResult.failure.normalizedWorkspaceRoot; - const exactWorkspaceMatch = activeProjects.find( - (project) => project.workspaceRoot === normalizedWorkspaceRoot, + const path = yield* Path.Path; + const savedWorkspaceRoot = path.resolve( + expandHomePath(trimmedIdentifier, yield* HostProcess.HomeDirectory), ); - - const resolved = exactWorkspaceMatch; + const exactWorkspaceMatch = + activeProjects.find((project) => project.workspaceRoot === savedWorkspaceRoot) ?? + activeProjects.find((project) => project.workspaceRoot === normalizedWorkspaceRoot); + + const resolved = + exactWorkspaceMatch ?? + Option.getOrUndefined( + yield* Effect.findFirst(activeProjects, (project) => + normalizeWorkspaceRootForProjectCommand(project.workspaceRoot).pipe( + Effect.map((root) => root === normalizedWorkspaceRoot), + Effect.orElseSucceed(() => false), + ), + ), + ); if (!resolved) { return yield* new ProjectNotFoundError({ operation: "resolveProjectTarget", @@ -488,9 +503,14 @@ const projectAddCommand = Command.make("add", { ) => Effect.Effect; }) { const workspaceRoot = yield* normalizeWorkspaceRootForProjectCommand(flags.workspaceRoot); - const existingProject = snapshot.projects.find( - (project) => project.deletedAt === null && project.workspaceRoot === workspaceRoot, - ); + const path = yield* Path.Path; + const target = yield* findActiveProjectTarget({ + snapshot, + identifier: path.resolve( + expandHomePath(flags.workspaceRoot.trim(), yield* HostProcess.HomeDirectory), + ), + }).pipe(Effect.catchTags({ ProjectNotFoundError: () => Effect.undefined })); + const existingProject = snapshot.projects.find((project) => project.id === target?.id); // Re-adding an archived project's folder restores it, matching the clients. if (existingProject?.archivedAt != null) { const title = Option.isSome(flags.title) diff --git a/apps/server/src/project/ProjectService.test.ts b/apps/server/src/project/ProjectService.test.ts index 492379beecc26..f4986f662f1ed 100644 --- a/apps/server/src/project/ProjectService.test.ts +++ b/apps/server/src/project/ProjectService.test.ts @@ -10,6 +10,8 @@ import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; import * as FileSystem from "effect/FileSystem"; +import * as Path from "effect/Path"; +import { symlinksSupported } from "@t3tools/shared/testing/symlinks"; import * as Layer from "effect/Layer"; import * as Metric from "effect/Metric"; import * as Option from "effect/Option"; @@ -99,10 +101,15 @@ const layerTestFor = ( | ProjectFaviconResolver.ProjectFaviconResolver | RepositoryIdentityResolver.RepositoryIdentityResolver >, + workspaceLayer: Layer.Layer< + WorkspacePaths.WorkspacePaths, + never, + FileSystem.FileSystem | Path.Path + > = layerWorkspacePaths, ) => RuntimeLayer.layerProjectService.pipe( Layer.provideMerge(ProjectEnrichmentService.layer), - Layer.provideMerge(layerWorkspacePaths), + Layer.provideMerge(workspaceLayer), Layer.provideMerge(projectMetadataLayer), Layer.provideMerge(SqlitePersistence.layerMemory), Layer.provideMerge(ServerSettings.layerTest()), @@ -113,6 +120,85 @@ const layerTestFor = ( const layerTest = layerTestFor(layerMetadata); +it.effect.skipIf(!symlinksSupported)( + "reuses symlinked checkouts, including legacy roots, without merging distinct folders", + () => + Effect.gen(function* () { + const service = yield* ProjectService.ProjectService; + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const sql = yield* SqlClient.SqlClient; + const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "project-alias-" }); + const physicalParent = path.join(cwd, "Development", "Code"); + const aliasParent = path.join(cwd, "Code"); + yield* fs.makeDirectory(physicalParent, { recursive: true }); + yield* fs.symlink(physicalParent, aliasParent); + const root = path.join(physicalParent, "project"); + const alias = path.join(aliasParent, "project"); + const input = { + commandId: CommandId.make("command:alias:first"), + projectId: ProjectId.make("project:alias:first"), + title: "Alias", + workspaceRoot: alias, + createWorkspaceRootIfMissing: true, + }; + const first = { project: yield* service.create(input) }; + const canonicalRoot = yield* fs.realPath(root); + assert.equal(first.project.workspaceRoot, canonicalRoot); + // Older versions persisted the unresolved path. Keep that project's identity and settings. + yield* sql`UPDATE projection_projects SET workspace_root = ${alias} + WHERE project_id = ${input.projectId}`; + const second = yield* service.bootstrap({ + ...input, + commandId: CommandId.make("command:alias:second"), + projectId: ProjectId.make("project:alias:second"), + workspaceRoot: root, + }); + assert.isFalse(second.created); + assert.equal(second.project.id, first.project.id); + const conflict = yield* service + .create({ + ...input, + commandId: CommandId.make("command:alias:duplicate"), + projectId: ProjectId.make("project:alias:duplicate"), + workspaceRoot: root, + }) + .pipe(Effect.flip); + assert.equal(conflict._tag, "ProjectConflictError"); + const separate = yield* service.create({ + ...input, + commandId: CommandId.make("command:alias:separate"), + projectId: ProjectId.make("project:alias:separate"), + workspaceRoot: path.join(cwd, "other", "project"), + createWorkspaceRootIfMissing: true, + }); + assert.notEqual(separate.id, first.project.id); + const moveConflict = yield* service + .update({ + commandId: CommandId.make("command:alias:move"), + projectId: separate.id, + workspaceRoot: alias, + }) + .pipe(Effect.flip); + assert.equal(moveConflict._tag, "ProjectConflictError"); + assert.equal( + Option.getOrThrow(yield* service.getByWorkspaceRoot(alias)).id, + first.project.id, + ); + assert.equal( + Option.getOrThrow(yield* service.getByWorkspaceRoot(root, { includeDeleted: true })).id, + first.project.id, + ); + assert.lengthOf((yield* service.snapshot).projects, 2); + }).pipe( + Effect.provide( + layerTestFor(layerMetadata, WorkspacePaths.layer).pipe( + Layer.provideMerge(NodeServices.layer), + ), + ), + ), +); + it.effect("resolves only the requested active project page in creation order", () => Effect.gen(function* () { const inspected = yield* Ref.make>(new Set()); diff --git a/apps/server/src/project/ProjectService.ts b/apps/server/src/project/ProjectService.ts index 1db031456f2d7..0472143602036 100644 --- a/apps/server/src/project/ProjectService.ts +++ b/apps/server/src/project/ProjectService.ts @@ -250,6 +250,39 @@ export const make = Effect.gen(function* () { ), ); + const findByWorkspaceRoot = Effect.fn("ProjectService.findByWorkspaceRoot")(function* ( + workspaceRoot: string, + options?: { readonly includeDeleted?: boolean }, + ) { + if (options?.includeDeleted !== true) { + const exact = yield* projects + .findActiveByWorkspaceRoot(workspaceRoot) + .pipe( + Effect.mapError( + (cause) => new ProjectOperationError({ operation: "read-project", cause }), + ), + ); + if (Option.isSome(exact)) return exact; + } + const rows = yield* projects + .list(options) + .pipe( + Effect.mapError( + (cause) => new ProjectOperationError({ operation: "list-projects", cause }), + ), + ); + const exact = rows.find((row) => row.workspaceRoot === workspaceRoot); + if (exact !== undefined) return Option.some(exact); + // Older registrations can still store a symlink spelling. Resolve without rewriting their history. + return yield* Effect.findFirst(rows, (row) => + normalizeWorkspaceRoot({ workspaceRoot: row.workspaceRoot }).pipe( + Effect.map((root) => root === workspaceRoot), + // An unavailable checkout cannot establish a matching filesystem identity. + Effect.orElseSucceed(() => false), + ), + ); + }); + const rejectWorktreeContainer = Effect.fn("ProjectService.rejectWorktreeContainer")(function* ( projectId: ProjectId, workspaceRoot: string, @@ -272,9 +305,7 @@ export const make = Effect.gen(function* () { workspaceRoot === undefined ? undefined : Option.getOrUndefined( - yield* projects - .findActiveByWorkspaceRoot(workspaceRoot) - .pipe(Effect.mapError(dispatchError)), + yield* findByWorkspaceRoot(workspaceRoot).pipe(Effect.mapError(dispatchError)), ); const now = yield* DateTime.now; const eventId = yield* idAllocator.allocate @@ -377,19 +408,7 @@ export const make = Effect.gen(function* () { "ProjectService.getByWorkspaceRoot", )(function* (workspaceRoot, options) { const normalized = yield* normalizeWorkspaceRoot({ workspaceRoot }); - const row = yield* ( - options?.includeDeleted === true - ? projects - .list({ includeDeleted: true }) - .pipe( - Effect.map((rows) => - Option.fromUndefinedOr(rows.find((row) => row.workspaceRoot === normalized)), - ), - ) - : projects.findActiveByWorkspaceRoot(normalized) - ).pipe( - Effect.mapError((cause) => new ProjectOperationError({ operation: "list-projects", cause })), - ); + const row = yield* findByWorkspaceRoot(normalized, options); return Option.isNone(row) ? Option.none() : Option.some(yield* hydrate(row.value)); }); diff --git a/apps/server/src/workspace/WorkspaceEntries.ts b/apps/server/src/workspace/WorkspaceEntries.ts index ad1d2c2ae0ebe..304635ae46721 100644 --- a/apps/server/src/workspace/WorkspaceEntries.ts +++ b/apps/server/src/workspace/WorkspaceEntries.ts @@ -87,6 +87,7 @@ export const WorkspaceEntriesError = Schema.Union([ WorkspacePaths.WorkspaceRootCreateFailedError, WorkspacePaths.WorkspaceRootStatFailedError, WorkspacePaths.WorkspaceRootNotDirectoryError, + WorkspacePaths.WorkspaceRootUnsupportedPathError, WorkspaceSearchIndex.WorkspaceSearchIndexCreateFailed, WorkspaceSearchIndex.WorkspaceSearchIndexScanTimedOut, WorkspaceSearchIndex.WorkspaceSearchIndexSearchFailed, diff --git a/apps/server/src/workspace/WorkspacePaths.test.ts b/apps/server/src/workspace/WorkspacePaths.test.ts index b178c621453b8..86ea26cd88cbb 100644 --- a/apps/server/src/workspace/WorkspacePaths.test.ts +++ b/apps/server/src/workspace/WorkspacePaths.test.ts @@ -23,22 +23,33 @@ const makeTempDir = Effect.fn("makeTempDir")(function* () { it.layer(layerTest)("WorkspacePathsLive", (it) => { describe("normalizeWorkspaceRoot", () => { - it.effect("creates missing directories when createIfMissing is enabled", () => - Effect.gen(function* () { - const workspacePaths = yield* WorkspacePaths.WorkspacePaths; - const fileSystem = yield* FileSystem.FileSystem; - const cwd = yield* makeTempDir(); - const path = yield* Path.Path; - const missingPath = path.join(cwd, "nested", "new-project"); + it.effect( + "creates missing roots and rejects aliases whose resolved paths cannot be preserved", + () => + Effect.gen(function* () { + const workspacePaths = yield* WorkspacePaths.WorkspacePaths; + const fileSystem = yield* FileSystem.FileSystem; + const cwd = yield* makeTempDir(); + const path = yield* Path.Path; + const missingPath = path.join(cwd, "nested", "new-project"); - const resolved = yield* workspacePaths.normalizeWorkspaceRoot(missingPath, { - createIfMissing: true, - }); - const stat = yield* fileSystem.stat(resolved); + const resolved = yield* workspacePaths.normalizeWorkspaceRoot(missingPath, { + createIfMissing: true, + }); + const stat = yield* fileSystem.stat(resolved); - expect(resolved).toBe(missingPath); - expect(stat.type).toBe("Directory"); - }), + expect(resolved).toBe(yield* fileSystem.realPath(missingPath)); + expect(stat.type).toBe("Directory"); + + if (HostProcess.Platform.defaultValue() !== "win32") { + const spacedRoot = path.join(cwd, "spaced "); + const aliasRoot = path.join(cwd, "alias"); + yield* fileSystem.makeDirectory(spacedRoot); + yield* fileSystem.symlink(spacedRoot, aliasRoot); + const error = yield* workspacePaths.normalizeWorkspaceRoot(aliasRoot).pipe(Effect.flip); + expect(error._tag).toBe("WorkspaceRootUnsupportedPathError"); + } + }), ); }); diff --git a/apps/server/src/workspace/WorkspacePaths.ts b/apps/server/src/workspace/WorkspacePaths.ts index e630643c71be6..43ee3b8230c3c 100644 --- a/apps/server/src/workspace/WorkspacePaths.ts +++ b/apps/server/src/workspace/WorkspacePaths.ts @@ -38,7 +38,7 @@ export class WorkspaceRootStatFailedError extends Schema.TaggedError()( + "WorkspaceRootUnsupportedPathError", + { + workspaceRoot: Schema.String, + normalizedWorkspaceRoot: Schema.String, + }, +) { + override get message(): string { + return `Workspace root resolves to a path ending in whitespace. Rename the directory before adding it: ${JSON.stringify(this.normalizedWorkspaceRoot)}`; + } +} + export class WorkspacePathOutsideRootError extends Schema.TaggedError()( "WorkspacePathOutsideRootError", { @@ -76,6 +88,7 @@ export const WorkspacePathsError = Schema.Union([ WorkspaceRootCreateFailedError, WorkspaceRootStatFailedError, WorkspaceRootNotDirectoryError, + WorkspaceRootUnsupportedPathError, WorkspacePathOutsideRootError, ]); export type WorkspacePathsError = typeof WorkspacePathsError.Type; @@ -92,6 +105,7 @@ export class WorkspacePaths extends Context.Service< | WorkspaceRootCreateFailedError | WorkspaceRootStatFailedError | WorkspaceRootNotDirectoryError + | WorkspaceRootUnsupportedPathError >; readonly resolveRelativePathWithinRoot: (input: { workspaceRoot: string; @@ -170,7 +184,25 @@ const make = Effect.gen(function* () { normalizedWorkspaceRoot, }); } - return normalizedWorkspaceRoot; + const realRoot = yield* fileSystem.realPath(normalizedWorkspaceRoot).pipe( + Effect.mapError( + (cause) => + new WorkspaceRootStatFailedError({ + workspaceRoot, + normalizedWorkspaceRoot, + phase: "resolve-real-path", + cause, + }), + ), + ); + // Existing path contracts trim strings, which would persist a different directory. + if (realRoot !== realRoot.trimEnd()) { + return yield* new WorkspaceRootUnsupportedPathError({ + workspaceRoot, + normalizedWorkspaceRoot: realRoot, + }); + } + return realRoot; }); const resolveRelativePathWithinRoot: WorkspacePaths["Service"]["resolveRelativePathWithinRoot"] = diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index bbe80f28e9681..ec2ccb7985a1a 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -608,6 +608,12 @@ function projectEntriesFailureContext(error: WorkspaceEntries.WorkspaceEntriesEr failure: "workspace_root_create_failed", normalizedCwd: error.normalizedWorkspaceRoot, }; + case "WorkspaceRootUnsupportedPathError": + return { + failure: "workspace_root_stat_failed", + normalizedCwd: error.normalizedWorkspaceRoot, + detail: error.message, + }; case "WorkspaceRootStatFailedError": return { failure: "workspace_root_stat_failed",