From f92ae7c66837283ff86ddddc03f310f558cc2a37 Mon Sep 17 00:00:00 2001 From: "omegent-app[bot]" <306514130+omegent-app[bot]@users.noreply.github.com> Date: Sun, 2 Aug 2026 06:31:43 +0000 Subject: [PATCH 1/4] feat(server): run blocking lifecycle scripts before worktree removal Add runOnWorktreeRemove and runOnPrMerged project script hooks so process and data reaping can finish before git worktree remove continues. Non-zero exit blocks removal. Also expose the flags in t3.json, scripts UI, and docs. Co-authored-by: Patrick Roza <42661+patroza@users.noreply.github.com> --- .../src/features/terminal/terminalMenu.ts | 6 +- .../server/src/git/GitWorkflowService.test.ts | 10 + apps/server/src/git/GitWorkflowService.ts | 71 ++++- .../ProjectLifecycleScriptRunner.test.ts | 211 +++++++++++++++ .../project/ProjectLifecycleScriptRunner.ts | 252 ++++++++++++++++++ apps/server/src/server.test.ts | 7 + apps/server/src/server.ts | 6 + apps/web/src/components/ChatView.tsx | 19 +- .../src/components/ProjectScriptsControl.tsx | 31 ++- apps/web/src/projectScripts.test.ts | 71 ++++- apps/web/src/projectScripts.ts | 45 +++- docs/user/source-control.md | 16 ++ packages/contracts/src/orchestration.ts | 11 + packages/contracts/src/t3ProjectFile.test.ts | 2 + packages/contracts/src/t3ProjectFile.ts | 12 + packages/shared/src/projectScripts.ts | 28 ++ packages/shared/src/t3ProjectFile.test.ts | 2 + 17 files changed, 780 insertions(+), 20 deletions(-) create mode 100644 apps/server/src/project/ProjectLifecycleScriptRunner.test.ts create mode 100644 apps/server/src/project/ProjectLifecycleScriptRunner.ts diff --git a/apps/mobile/src/features/terminal/terminalMenu.ts b/apps/mobile/src/features/terminal/terminalMenu.ts index 06cb74e9467..9d5c7c0ee83 100644 --- a/apps/mobile/src/features/terminal/terminalMenu.ts +++ b/apps/mobile/src/features/terminal/terminalMenu.ts @@ -155,7 +155,11 @@ export function resolveProjectScriptTerminalId(input: { } export function projectScriptMenuLabel(script: ProjectScript): string { - return script.runOnWorktreeCreate ? `${script.name} (setup)` : script.name; + const tags: string[] = []; + if (script.runOnWorktreeCreate) tags.push("setup"); + if (script.runOnWorktreeRemove === true) tags.push("teardown"); + if (script.runOnPrMerged === true) tags.push("pr-merged"); + return tags.length > 0 ? `${script.name} (${tags.join(", ")})` : script.name; } export function projectScriptMenuIcon(icon: ProjectScript["icon"]) { diff --git a/apps/server/src/git/GitWorkflowService.test.ts b/apps/server/src/git/GitWorkflowService.test.ts index 2ea14b951fe..28b4f33f97c 100644 --- a/apps/server/src/git/GitWorkflowService.test.ts +++ b/apps/server/src/git/GitWorkflowService.test.ts @@ -6,9 +6,17 @@ import { VcsRepositoryDetectionError } from "@t3tools/contracts"; import * as GitManager from "./GitManager.ts"; import * as GitWorkflowService from "./GitWorkflowService.ts"; +import * as ProjectLifecycleScriptRunner from "../project/ProjectLifecycleScriptRunner.ts"; import * as GitVcsDriver from "../vcs/GitVcsDriver.ts"; import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts"; +const lifecycleScriptRunnerMock = Layer.mock( + ProjectLifecycleScriptRunner.ProjectLifecycleScriptRunner, +)({ + runWorktreeRemove: () => Effect.succeed({ status: "no-script" as const }), + runPrMerged: () => Effect.succeed({ status: "no-script" as const }), +}); + function makeLayer(input: { readonly detect: VcsDriverRegistry.VcsDriverRegistry["Service"]["detect"]; }) { @@ -20,6 +28,7 @@ function makeLayer(input: { ), Layer.provide(Layer.mock(GitVcsDriver.GitVcsDriver)({})), Layer.provide(Layer.mock(GitManager.GitManager)({})), + Layer.provide(lifecycleScriptRunnerMock), ); } @@ -100,6 +109,7 @@ describe("GitWorkflowService", () => { status, }), ), + Layer.provide(lifecycleScriptRunnerMock), ); return Effect.gen(function* () { diff --git a/apps/server/src/git/GitWorkflowService.ts b/apps/server/src/git/GitWorkflowService.ts index c5446943bd1..2558912c77d 100644 --- a/apps/server/src/git/GitWorkflowService.ts +++ b/apps/server/src/git/GitWorkflowService.ts @@ -31,6 +31,7 @@ import { } from "@t3tools/contracts"; import * as GitManager from "./GitManager.ts"; +import * as ProjectLifecycleScriptRunner from "../project/ProjectLifecycleScriptRunner.ts"; import * as GitVcsDriver from "../vcs/GitVcsDriver.ts"; import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts"; @@ -135,10 +136,40 @@ function nonRepositoryListRefs(): VcsListRefsResult { }; } +function lifecycleScriptToGitCommandError( + operation: string, + input: VcsRemoveWorktreeInput, + error: ProjectLifecycleScriptRunner.ProjectLifecycleScriptRunnerError, +): GitCommandError { + if (error._tag === "ProjectLifecycleScriptFailedError") { + const detailParts = [ + error.message, + error.stderr.trim().length > 0 ? error.stderr.trim() : null, + error.stdout.trim().length > 0 ? error.stdout.trim() : null, + ].filter((part): part is string => part !== null); + return new GitCommandError({ + operation, + command: `lifecycle:${error.lifecycle}`, + cwd: input.path, + exitCode: error.exitCode ?? undefined, + detail: detailParts.join("\n"), + cause: error, + }); + } + return new GitCommandError({ + operation, + command: `lifecycle:${error.lifecycle}`, + cwd: input.path, + detail: error.message, + cause: error, + }); +} + export const make = Effect.gen(function* () { const registry = yield* VcsDriverRegistry.VcsDriverRegistry; const git = yield* GitVcsDriver.GitVcsDriver; const gitManager = yield* GitManager.GitManager; + const lifecycleScriptRunner = yield* ProjectLifecycleScriptRunner.ProjectLifecycleScriptRunner; const ensureGit = Effect.fn("GitWorkflowService.ensureGit")(function* ( operation: string, @@ -322,7 +353,45 @@ export const make = Effect.gen(function* () { ), removeWorktree: (input) => ensureGitCommand("GitWorkflowService.removeWorktree", input.cwd).pipe( - Effect.andThen(git.removeWorktree(input)), + Effect.andThen( + Effect.gen(function* () { + const lifecycleInput = { + projectCwd: input.cwd, + worktreePath: input.path, + }; + // Teardown must finish successfully before the worktree directory is removed. + yield* lifecycleScriptRunner + .runWorktreeRemove(lifecycleInput) + .pipe( + Effect.mapError((error) => + lifecycleScriptToGitCommandError( + "GitWorkflowService.removeWorktree", + input, + error, + ), + ), + ); + + const remote = yield* gitManager + .remoteStatus({ cwd: input.path }) + .pipe(Effect.catch(() => Effect.succeed(null))); + if (remote?.pr?.state === "merged") { + yield* lifecycleScriptRunner + .runPrMerged(lifecycleInput) + .pipe( + Effect.mapError((error) => + lifecycleScriptToGitCommandError( + "GitWorkflowService.removeWorktree", + input, + error, + ), + ), + ); + } + + yield* git.removeWorktree(input); + }), + ), ), createRef: (input) => ensureGitCommand("GitWorkflowService.createRef", input.cwd).pipe( diff --git a/apps/server/src/project/ProjectLifecycleScriptRunner.test.ts b/apps/server/src/project/ProjectLifecycleScriptRunner.test.ts new file mode 100644 index 00000000000..31726caa1bb --- /dev/null +++ b/apps/server/src/project/ProjectLifecycleScriptRunner.test.ts @@ -0,0 +1,211 @@ +import { describe, expect, it, vi } from "@effect/vitest"; +import { type OrchestrationProject, ProjectId } from "@t3tools/contracts"; +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 ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner"; + +import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts"; +import * as ProcessRunner from "../processRunner.ts"; +import * as ProjectLifecycleScriptRunner from "./ProjectLifecycleScriptRunner.ts"; + +const okProcessOutput = ( + overrides: Partial = {}, +): ProcessRunner.ProcessRunOutput => ({ + stdout: "", + stderr: "", + code: ChildProcessSpawner.ExitCode(0), + timedOut: false, + stdoutTruncated: false, + stderrTruncated: false, + ...overrides, +}); + +const isLifecycleFailed = Schema.is(ProjectLifecycleScriptRunner.ProjectLifecycleScriptFailedError); + +const makeProject = (scripts: OrchestrationProject["scripts"]): OrchestrationProject => ({ + id: ProjectId.make("project-1"), + title: "Project", + workspaceRoot: "/repo/project", + defaultModelSelection: null, + scripts, + createdAt: "2026-01-01T00:00:00.000Z", + updatedAt: "2026-01-01T00:00:00.000Z", + deletedAt: null, +}); + +const makeProjectionSnapshotQueryLayer = (project: OrchestrationProject | null) => + Layer.succeed(ProjectionSnapshotQuery.ProjectionSnapshotQuery, { + getCommandReadModel: () => Effect.die("unused"), + getSnapshot: () => Effect.die("unused"), + getShellSnapshot: () => Effect.die("unused"), + getArchivedShellSnapshot: () => Effect.die("unused"), + getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 1 }), + getCounts: () => Effect.die("unused"), + getActiveProjectByWorkspaceRoot: (workspaceRoot) => + Effect.succeed( + project && workspaceRoot === project.workspaceRoot ? Option.some(project) : Option.none(), + ), + getProjectShellById: (projectId) => + Effect.succeed(project && projectId === project.id ? Option.some(project) : Option.none()), + getFirstActiveThreadIdByProjectId: () => Effect.die("unused"), + getThreadCheckpointContext: () => Effect.die("unused"), + getFullThreadDiffContext: () => Effect.die("unused"), + getThreadShellById: () => Effect.die("unused"), + getThreadDetailById: () => Effect.die("unused"), + getThreadDetailSnapshot: () => Effect.die("unused"), + searchThreads: () => Effect.succeed({ matches: [] }), + }); + +const makeProcessRunnerLayer = (run: ProcessRunner.ProcessRunner["Service"]["run"]) => + Layer.succeed(ProcessRunner.ProcessRunner, { run }); + +const testLayer = ( + project: OrchestrationProject | null, + run: ProcessRunner.ProcessRunner["Service"]["run"], +) => + ProjectLifecycleScriptRunner.layer.pipe( + Layer.provideMerge(makeProjectionSnapshotQueryLayer(project)), + Layer.provideMerge(makeProcessRunnerLayer(run)), + ); + +describe("ProjectLifecycleScriptRunner", () => { + it.effect("returns no-script when no teardown script exists", () => { + const run = vi.fn(() => Effect.die("unexpected run")); + const project = makeProject([]); + + return Effect.gen(function* () { + const runner = yield* ProjectLifecycleScriptRunner.ProjectLifecycleScriptRunner; + const result = yield* runner.runWorktreeRemove({ + projectCwd: "/repo/project", + worktreePath: "/repo/worktrees/a", + }); + expect(result).toEqual({ status: "no-script" }); + expect(run).not.toHaveBeenCalled(); + }).pipe(Effect.provide(testLayer(project, run))); + }); + + it.effect("returns no-script when no project can be resolved", () => { + const run = vi.fn(() => Effect.die("unexpected run")); + return Effect.gen(function* () { + const runner = yield* ProjectLifecycleScriptRunner.ProjectLifecycleScriptRunner; + const result = yield* runner.runWorktreeRemove({ + projectCwd: "/missing", + worktreePath: "/repo/worktrees/a", + }); + expect(result).toEqual({ status: "no-script" }); + expect(run).not.toHaveBeenCalled(); + }).pipe(Effect.provide(testLayer(null, run))); + }); + + it.effect("runs the worktree-remove script and waits for a successful exit", () => { + const run = vi.fn(() => Effect.succeed(okProcessOutput({ stdout: "cleaned\n" }))); + const project = makeProject([ + { + id: "teardown", + name: "Teardown", + command: "echo cleaned", + icon: "configure", + runOnWorktreeCreate: false, + runOnWorktreeRemove: true, + }, + ]); + + return Effect.gen(function* () { + const runner = yield* ProjectLifecycleScriptRunner.ProjectLifecycleScriptRunner; + const result = yield* runner.runWorktreeRemove({ + projectCwd: "/repo/project", + worktreePath: "/repo/worktrees/a", + }); + + expect(result).toMatchObject({ + status: "completed", + scriptId: "teardown", + scriptName: "Teardown", + lifecycle: "worktree-remove", + exitCode: 0, + }); + expect(run).toHaveBeenCalledWith( + expect.objectContaining({ + command: "sh", + args: ["-c", "echo cleaned"], + cwd: "/repo/worktrees/a", + env: expect.objectContaining({ + T3CODE_PROJECT_ROOT: "/repo/project", + T3CODE_WORKTREE_PATH: "/repo/worktrees/a", + T3CODE_LIFECYCLE: "worktree-remove", + }), + }), + ); + }).pipe(Effect.provide(testLayer(project, run))); + }); + + it.effect("fails when the lifecycle script exits non-zero", () => { + const run = vi.fn(() => + Effect.succeed( + okProcessOutput({ + stderr: "still running\n", + code: ChildProcessSpawner.ExitCode(2), + }), + ), + ); + const project = makeProject([ + { + id: "teardown", + name: "Teardown", + command: "exit 2", + icon: "configure", + runOnWorktreeCreate: false, + runOnWorktreeRemove: true, + }, + ]); + + return Effect.gen(function* () { + const runner = yield* ProjectLifecycleScriptRunner.ProjectLifecycleScriptRunner; + const error = yield* runner + .runWorktreeRemove({ + projectCwd: "/repo/project", + worktreePath: "/repo/worktrees/a", + }) + .pipe(Effect.flip); + + expect(isLifecycleFailed(error)).toBe(true); + if (isLifecycleFailed(error)) { + expect(error.exitCode).toBe(2); + expect(error.scriptName).toBe("Teardown"); + expect(error.stderr).toContain("still running"); + } + }).pipe(Effect.provide(testLayer(project, run))); + }); + + it.effect("runs the pr-merged lifecycle script when requested", () => { + const run = vi.fn(() => Effect.succeed(okProcessOutput())); + const project = makeProject([ + { + id: "merged", + name: "On merge", + command: "echo reaped", + icon: "configure", + runOnWorktreeCreate: false, + runOnPrMerged: true, + }, + ]); + + return Effect.gen(function* () { + const runner = yield* ProjectLifecycleScriptRunner.ProjectLifecycleScriptRunner; + const result = yield* runner.runPrMerged({ + projectCwd: "/repo/project", + worktreePath: "/repo/worktrees/a", + }); + expect(result.status).toBe("completed"); + expect(run).toHaveBeenCalledWith( + expect.objectContaining({ + env: expect.objectContaining({ + T3CODE_LIFECYCLE: "pr-merged", + }), + }), + ); + }).pipe(Effect.provide(testLayer(project, run))); + }); +}); diff --git a/apps/server/src/project/ProjectLifecycleScriptRunner.ts b/apps/server/src/project/ProjectLifecycleScriptRunner.ts new file mode 100644 index 00000000000..73966630d8a --- /dev/null +++ b/apps/server/src/project/ProjectLifecycleScriptRunner.ts @@ -0,0 +1,252 @@ +/** + * ProjectLifecycleScriptRunner - runs blocking project lifecycle scripts + * (worktree remove / PR merged) via a real process, waiting for exit before + * the caller continues (e.g. `git worktree remove`). + * + * Unlike setup scripts (fire-and-forget in a terminal), teardown must finish + * and succeed before filesystem teardown proceeds. + * + * @module ProjectLifecycleScriptRunner + */ +import { type ProjectScript, ProjectId } from "@t3tools/contracts"; +import { + prMergedProjectScript, + projectLifecycleRuntimeEnv, + type ProjectLifecycleKind, + worktreeRemoveProjectScript, +} from "@t3tools/shared/projectScripts"; +import { HostProcessEnvironment, HostProcessPlatform } from "@t3tools/shared/hostProcess"; +import * as Context from "effect/Context"; +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 ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts"; +import * as ProcessRunner from "../processRunner.ts"; + +const LIFECYCLE_SCRIPT_TIMEOUT = "10 minutes"; +const LIFECYCLE_SCRIPT_MAX_OUTPUT_BYTES = 1_024 * 1_024; + +export interface ProjectLifecycleScriptRunnerResultNoScript { + readonly status: "no-script"; +} + +export interface ProjectLifecycleScriptRunnerResultCompleted { + readonly status: "completed"; + readonly scriptId: string; + readonly scriptName: string; + readonly lifecycle: ProjectLifecycleKind; + readonly exitCode: number | null; + readonly stdout: string; + readonly stderr: string; +} + +export type ProjectLifecycleScriptRunnerResult = + | ProjectLifecycleScriptRunnerResultNoScript + | ProjectLifecycleScriptRunnerResultCompleted; + +export interface ProjectLifecycleScriptRunnerInput { + readonly projectId?: string; + readonly projectCwd?: string; + readonly worktreePath: string; +} + +export class ProjectLifecycleScriptOperationError extends Schema.TaggedErrorClass()( + "ProjectLifecycleScriptOperationError", + { + lifecycle: Schema.Literals(["worktree-remove", "pr-merged"]), + projectId: Schema.optional(Schema.String), + projectCwd: Schema.optional(Schema.String), + worktreePath: Schema.String, + operation: Schema.Literals(["resolveProject", "runScript"]), + cause: Schema.Defect(), + }, +) { + override get message(): string { + return `Project lifecycle script operation '${this.operation}' failed for '${this.lifecycle}' in '${this.worktreePath}'.`; + } +} + +export class ProjectLifecycleScriptFailedError extends Schema.TaggedErrorClass()( + "ProjectLifecycleScriptFailedError", + { + lifecycle: Schema.Literals(["worktree-remove", "pr-merged"]), + projectId: Schema.optional(Schema.String), + projectCwd: Schema.optional(Schema.String), + worktreePath: Schema.String, + scriptId: Schema.String, + scriptName: Schema.String, + exitCode: Schema.NullOr(Schema.Number), + timedOut: Schema.Boolean, + stdout: Schema.String, + stderr: Schema.String, + }, +) { + override get message(): string { + if (this.timedOut) { + return `Lifecycle script '${this.scriptName}' (${this.lifecycle}) timed out in '${this.worktreePath}'.`; + } + const code = this.exitCode === null ? "unknown" : String(this.exitCode); + return `Lifecycle script '${this.scriptName}' (${this.lifecycle}) exited with code ${code} in '${this.worktreePath}'.`; + } +} + +export const ProjectLifecycleScriptRunnerError = Schema.Union([ + ProjectLifecycleScriptOperationError, + ProjectLifecycleScriptFailedError, +]); +export type ProjectLifecycleScriptRunnerError = typeof ProjectLifecycleScriptRunnerError.Type; + +export class ProjectLifecycleScriptRunner extends Context.Service< + ProjectLifecycleScriptRunner, + { + readonly runWorktreeRemove: ( + input: ProjectLifecycleScriptRunnerInput, + ) => Effect.Effect; + readonly runPrMerged: ( + input: ProjectLifecycleScriptRunnerInput, + ) => Effect.Effect; + } +>()("t3/project/ProjectLifecycleScriptRunner") {} + +const selectScript = ( + lifecycle: ProjectLifecycleKind, + scripts: readonly ProjectScript[], +): ProjectScript | null => + lifecycle === "worktree-remove" + ? worktreeRemoveProjectScript(scripts) + : prMergedProjectScript(scripts); + +export const make = Effect.gen(function* () { + const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery; + const processRunner = yield* ProcessRunner.ProcessRunner; + const platform = yield* HostProcessPlatform; + const hostEnvironment = yield* HostProcessEnvironment; + + const resolveProject = Effect.fn("ProjectLifecycleScriptRunner.resolveProject")(function* ( + input: ProjectLifecycleScriptRunnerInput, + lifecycle: ProjectLifecycleKind, + ) { + const errorContext = { + lifecycle, + worktreePath: input.worktreePath, + ...(input.projectId === undefined ? {} : { projectId: input.projectId }), + ...(input.projectCwd === undefined ? {} : { projectCwd: input.projectCwd }), + }; + const projectById = input.projectId + ? yield* projectionSnapshotQuery.getProjectShellById(ProjectId.make(input.projectId)).pipe( + Effect.map(Option.getOrUndefined), + Effect.mapError( + (cause) => + new ProjectLifecycleScriptOperationError({ + ...errorContext, + operation: "resolveProject", + cause, + }), + ), + ) + : null; + if (projectById) { + return projectById; + } + if (!input.projectCwd) { + return null; + } + return yield* projectionSnapshotQuery.getActiveProjectByWorkspaceRoot(input.projectCwd).pipe( + Effect.map(Option.getOrUndefined), + Effect.mapError( + (cause) => + new ProjectLifecycleScriptOperationError({ + ...errorContext, + operation: "resolveProject", + cause, + }), + ), + ); + }); + + const runLifecycle = Effect.fn("ProjectLifecycleScriptRunner.runLifecycle")(function* ( + input: ProjectLifecycleScriptRunnerInput, + lifecycle: ProjectLifecycleKind, + ) { + const errorContext = { + lifecycle, + worktreePath: input.worktreePath, + ...(input.projectId === undefined ? {} : { projectId: input.projectId }), + ...(input.projectCwd === undefined ? {} : { projectCwd: input.projectCwd }), + }; + + const project = yield* resolveProject(input, lifecycle); + if (!project) { + // Bare VCS removes (no T3 project) skip lifecycle scripts rather than failing. + return { status: "no-script" } as const; + } + const script = selectScript(lifecycle, project.scripts); + if (!script) { + return { status: "no-script" } as const; + } + + const lifecycleEnv = projectLifecycleRuntimeEnv({ + project: { cwd: project.workspaceRoot }, + worktreePath: input.worktreePath, + lifecycle, + }); + const env: NodeJS.ProcessEnv = { + ...hostEnvironment, + ...lifecycleEnv, + }; + + const isWindows = platform === "win32"; + const output = yield* processRunner + .run({ + command: isWindows ? "cmd.exe" : "sh", + args: isWindows ? ["/d", "/s", "/c", script.command] : ["-c", script.command], + cwd: input.worktreePath, + env, + timeout: LIFECYCLE_SCRIPT_TIMEOUT, + outputMode: "truncate", + maxOutputBytes: LIFECYCLE_SCRIPT_MAX_OUTPUT_BYTES, + truncatedMarker: "\n…[truncated]\n", + }) + .pipe( + Effect.mapError( + (cause) => + new ProjectLifecycleScriptOperationError({ + ...errorContext, + operation: "runScript", + cause, + }), + ), + ); + + if (output.timedOut || output.code === null || output.code !== 0) { + return yield* new ProjectLifecycleScriptFailedError({ + ...errorContext, + scriptId: script.id, + scriptName: script.name, + exitCode: output.code, + timedOut: output.timedOut, + stdout: output.stdout, + stderr: output.stderr, + }); + } + + return { + status: "completed", + scriptId: script.id, + scriptName: script.name, + lifecycle, + exitCode: output.code, + stdout: output.stdout, + stderr: output.stderr, + } as const; + }); + + return ProjectLifecycleScriptRunner.of({ + runWorktreeRemove: (input) => runLifecycle(input, "worktree-remove"), + runPrMerged: (input) => runLifecycle(input, "pr-merged"), + }); +}); + +export const layer = Layer.effect(ProjectLifecycleScriptRunner, make); diff --git a/apps/server/src/server.test.ts b/apps/server/src/server.test.ts index 1e5339d89cf..2a8e88cfd73 100644 --- a/apps/server/src/server.test.ts +++ b/apps/server/src/server.test.ts @@ -107,6 +107,7 @@ import * as PortScanner from "./preview/PortScanner.ts"; import * as BrowserTraceCollector from "./observability/BrowserTraceCollector.ts"; import * as ProjectFaviconResolver from "./project/ProjectFaviconResolver.ts"; import * as T3ProjectFileLoader from "./project/T3ProjectFileLoader.ts"; +import * as ProjectLifecycleScriptRunner from "./project/ProjectLifecycleScriptRunner.ts"; import * as ProjectSetupScriptRunner from "./project/ProjectSetupScriptRunner.ts"; import * as RepositoryIdentityResolver from "./project/RepositoryIdentityResolver.ts"; import * as ServerEnvironment from "./environment/ServerEnvironment.ts"; @@ -539,6 +540,12 @@ const buildAppUnderTest = (options?: { Layer.provideMerge(vcsDriverRegistryLayer), Layer.provideMerge(gitVcsDriverLayer), Layer.provideMerge(gitManagerLayer), + Layer.provide( + Layer.mock(ProjectLifecycleScriptRunner.ProjectLifecycleScriptRunner)({ + runWorktreeRemove: () => Effect.succeed({ status: "no-script" as const }), + runPrMerged: () => Effect.succeed({ status: "no-script" as const }), + }), + ), ); const vcsProvisioningLayer = VcsProvisioningService.layer.pipe( Layer.provide(vcsDriverRegistryLayer), diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index d89279a14cf..03c1444fb02 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -77,6 +77,7 @@ import * as GitWorkflowService from "./git/GitWorkflowService.ts"; import * as ReviewService from "./review/ReviewService.ts"; import * as SourceControlProviderRegistry from "./sourceControl/SourceControlProviderRegistry.ts"; import * as SourceControlRepositoryService from "./sourceControl/SourceControlRepositoryService.ts"; +import * as ProjectLifecycleScriptRunner from "./project/ProjectLifecycleScriptRunner.ts"; import * as ProjectSetupScriptRunner from "./project/ProjectSetupScriptRunner.ts"; import { ObservabilityLive } from "./observability/Layers/Observability.ts"; import * as ServerEnvironment from "./environment/ServerEnvironment.ts"; @@ -276,6 +277,10 @@ const GitManagerLayerLive = GitManager.layer.pipe( Layer.provideMerge(TextGeneration.layer), ); +const ProjectLifecycleScriptRunnerLayerLive = ProjectLifecycleScriptRunner.layer.pipe( + Layer.provide(ProcessRunner.layer), +); + const GitLayerLive = Layer.empty.pipe( Layer.provideMerge(GitManagerLayerLive), Layer.provideMerge(GitVcsDriver.layer), @@ -284,6 +289,7 @@ const GitLayerLive = Layer.empty.pipe( const GitWorkflowLayerLive = GitWorkflowService.layer.pipe( Layer.provideMerge(VcsDriverRegistryLayerLive), Layer.provideMerge(GitLayerLive), + Layer.provideMerge(ProjectLifecycleScriptRunnerLayerLive), ); const SourceControlRepositoryServiceLayerLive = SourceControlRepositoryService.layer.pipe( diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 744eeb52e68..5a1368b6e85 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -167,6 +167,7 @@ import { decodeProjectScriptKeybindingRule } from "~/lib/projectScriptKeybinding import { type NewProjectScriptInput } from "./ProjectScriptsControl"; import { buildProjectScript, + clearConflictingLifecycleFlags, commandForProjectScript, nextProjectScriptId, projectScriptIdFromCommand, @@ -3139,14 +3140,10 @@ function ChatViewContent(props: ChatViewProps) { activeProject.scripts.map((script) => script.id), ); const nextScript = buildProjectScript(nextId, input); - const nextScripts = input.runOnWorktreeCreate - ? [ - ...activeProject.scripts.map((script) => - script.runOnWorktreeCreate ? { ...script, runOnWorktreeCreate: false } : script, - ), - nextScript, - ] - : [...activeProject.scripts, nextScript]; + const nextScripts = [ + ...activeProject.scripts.map((script) => clearConflictingLifecycleFlags(script, input)), + nextScript, + ]; return persistProjectScripts({ projectId: activeProject.id, @@ -3174,11 +3171,7 @@ function ChatViewContent(props: ChatViewProps) { const updatedScript = buildProjectScript(existingScript.id, input); const nextScripts = activeProject.scripts.map((script) => - script.id === scriptId - ? updatedScript - : input.runOnWorktreeCreate - ? { ...script, runOnWorktreeCreate: false } - : script, + script.id === scriptId ? updatedScript : clearConflictingLifecycleFlags(script, input), ); return persistProjectScripts({ diff --git a/apps/web/src/components/ProjectScriptsControl.tsx b/apps/web/src/components/ProjectScriptsControl.tsx index 3a1d7115098..1afeff6b790 100644 --- a/apps/web/src/components/ProjectScriptsControl.tsx +++ b/apps/web/src/components/ProjectScriptsControl.tsx @@ -32,6 +32,7 @@ import { commandForProjectScript, nextProjectScriptId, primaryProjectScript, + projectScriptMenuLabel, } from "~/projectScripts"; import { shortcutLabelForCommand } from "~/keybindings"; import { @@ -100,6 +101,8 @@ export interface NewProjectScriptInput { command: string; icon: ProjectScriptIcon; runOnWorktreeCreate: boolean; + runOnWorktreeRemove: boolean; + runOnPrMerged: boolean; keybinding: string | null; /** Optional URL to open in the in-app preview when this script runs. */ previewUrl: string | null; @@ -148,6 +151,8 @@ export default function ProjectScriptsControl({ const [icon, setIcon] = useState("play"); const [iconPickerOpen, setIconPickerOpen] = useState(false); const [runOnWorktreeCreate, setRunOnWorktreeCreate] = useState(false); + const [runOnWorktreeRemove, setRunOnWorktreeRemove] = useState(false); + const [runOnPrMerged, setRunOnPrMerged] = useState(false); const [keybinding, setKeybinding] = useState(""); const [previewUrl, setPreviewUrl] = useState(""); const [autoOpenPreview, setAutoOpenPreview] = useState(false); @@ -221,6 +226,8 @@ export default function ProjectScriptsControl({ command: trimmedCommand, icon, runOnWorktreeCreate, + runOnWorktreeRemove, + runOnPrMerged, keybinding: keybindingRule?.key ?? null, previewUrl: trimmedPreviewUrl.length > 0 ? trimmedPreviewUrl : null, autoOpenPreview: trimmedPreviewUrl.length > 0 ? autoOpenPreview : false, @@ -251,6 +258,8 @@ export default function ProjectScriptsControl({ setIcon("play"); setIconPickerOpen(false); setRunOnWorktreeCreate(false); + setRunOnWorktreeRemove(false); + setRunOnPrMerged(false); setKeybinding(""); setPreviewUrl(""); setAutoOpenPreview(false); @@ -266,6 +275,8 @@ export default function ProjectScriptsControl({ setIcon(script.icon); setIconPickerOpen(false); setRunOnWorktreeCreate(script.runOnWorktreeCreate); + setRunOnWorktreeRemove(script.runOnWorktreeRemove === true); + setRunOnPrMerged(script.runOnPrMerged === true); setKeybinding(keybindingValueForCommand(keybindings, commandForProjectScript(script.id)) ?? ""); setPreviewUrl(script.previewUrl ?? ""); setAutoOpenPreview(script.autoOpenPreview ?? false); @@ -286,6 +297,8 @@ export default function ProjectScriptsControl({ command: fileScript.command, icon: fileScript.icon ?? "play", runOnWorktreeCreate: fileScript.runOnWorktreeCreate ?? false, + runOnWorktreeRemove: fileScript.runOnWorktreeRemove ?? false, + runOnPrMerged: fileScript.runOnPrMerged ?? false, keybinding: null, previewUrl: fileScript.previewUrl ?? null, autoOpenPreview: fileScript.previewUrl ? (fileScript.autoOpenPreview ?? false) : false, @@ -378,9 +391,7 @@ export default function ProjectScriptsControl({ onClick={() => onRunScript(script)} > - - {script.runOnWorktreeCreate ? `${script.name} (setup)` : script.name} - + {projectScriptMenuLabel(script)} {shortcutLabel && ( @@ -582,6 +593,20 @@ export default function ProjectScriptsControl({ onCheckedChange={(checked) => setRunOnWorktreeCreate(Boolean(checked))} /> + +