diff --git a/apps/server/src/orchestration-v2/ProjectSettingsUpgrade.integration.test.ts b/apps/server/src/orchestration-v2/ProjectSettingsUpgrade.integration.test.ts index 99378a88464ce..4a71d970436e6 100644 --- a/apps/server/src/orchestration-v2/ProjectSettingsUpgrade.integration.test.ts +++ b/apps/server/src/orchestration-v2/ProjectSettingsUpgrade.integration.test.ts @@ -22,6 +22,7 @@ import { runMigrations } from "../persistence/Migrations.ts"; import * as ProjectEnrichmentService from "../project/ProjectEnrichmentService.ts"; import * as ProjectService from "../project/ProjectService.ts"; import * as ModelManifest from "../provider/ModelManifest.ts"; +import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts"; import * as ProviderInstanceRegistry from "../provider/ProviderInstanceRegistry.ts"; import * as ServerSettings from "../serverSettings.ts"; import * as SourceControlProviderRegistry from "../sourceControl/SourceControlProviderRegistry.ts"; @@ -172,6 +173,7 @@ const layerRuntime = (dbPath: string) => { pruneWorktrees: () => Effect.void, }), ), + Layer.provide(Layer.mock(ProjectSetupScriptRunner.ProjectSetupScriptRunner)({})), Layer.provide(layerPlatform), ); }; diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts index e4edafd70942b..8aceb61640c56 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts @@ -62,6 +62,7 @@ import { import * as GitVcsDriver from "../vcs/GitVcsDriver.ts"; import { layerRealGit } from "./ProviderTurnStartService.testkit.ts"; import * as ProjectService from "../project/ProjectService.ts"; +import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts"; import * as ProviderAuthService from "../provider/ProviderAuthService.ts"; import * as ServerSettings from "../serverSettings.ts"; import * as ContextHandoffService from "./ContextHandoffService.ts"; @@ -162,17 +163,26 @@ function startWithMissingWorktree( ); const startRootRun = vi.fn(() => Effect.void); const pruneWorktrees = vi.fn(() => Effect.void); - const createWorktree = vi.fn(() => Effect.succeed({} as never)); + let worktreeExists = false; + const createWorktree = vi.fn(() => + Effect.sync(() => { + worktreeExists = true; + return {} as never; + }), + ); const listLocalBranchNames = vi.fn(() => Effect.succeed(["feature/restore"])); const layer = ProviderTurnStart.layer.pipe( Layer.provide( Layer.mergeAll( + Layer.mock(ProjectSetupScriptRunner.ProjectSetupScriptRunner)({ + runForThread: () => Effect.succeed({ status: "no-script" }), + }), Layer.mock(ContextHandoffService.ContextHandoffServiceV2)({}), Layer.mock(EventSink.EventSinkV2)({ writeIfRunCurrent }), IdAllocator.layer, Layer.mock(TurnItemPositionStore.TurnItemPositionStoreV2)({}), Layer.succeed(FileSystem.FileSystem, { - exists: () => Effect.succeed(false), + exists: () => Effect.succeed(worktreeExists), realPath: (target: string) => normalize(target) in realPaths ? Effect.succeed(realPaths[normalize(target)]) @@ -465,6 +475,7 @@ function makeLocalCommandHarness(input: { readonly workspaceRoot?: string; readonly gitWorkflow?: GitWorkflow.GitWorkflowService["Service"]; readonly fileSystem?: FileSystem.FileSystem; + readonly runSetup?: ProjectSetupScriptRunner.ProjectSetupScriptRunner["Service"]["runForThread"]; readonly previousNativeSession?: boolean; readonly previousMessages?: ReadonlyArray; readonly createdBy?: "agent" | "system"; @@ -1345,6 +1356,9 @@ function makeLocalCommandHarness(input: { }), IdAllocator.layer, Layer.mock(TurnItemPositionStore.TurnItemPositionStoreV2)({}), + Layer.mock(ProjectSetupScriptRunner.ProjectSetupScriptRunner)({ + runForThread: input.runSetup ?? (() => Effect.succeed({ status: "no-script" })), + }), layerWorktreeLocation(input.worktreesDir), input.fileSystem === undefined ? FileSystem.layerNoop({ exists: () => Effect.succeed(true) }) @@ -2077,6 +2091,72 @@ effectIt.effect("leaves a managed worktree folder without .git that holds user f }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); +effectIt.effect.each([ + { async: false, exitCode: 0 }, + { async: false, exitCode: 1 }, + { async: true, exitCode: 0 }, +])("restored setup respects async=$async and exitCode=$exitCode", (input) => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const worktreesDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-restore-setup-" }); + const worktreePath = path.join(worktreesDir, "project", "restore"); + const setupStarted = yield* Deferred.make(); + const setupDone = yield* Deferred.make(); + const completionObserved = yield* Deferred.make(); + const harness = makeLocalCommandHarness({ + text: "Continue", + worktreesDir, + worktreePath, + fileSystem, + failReadsAfterRunning: true, + runSetup: () => + withWorkspaceLease(worktreePath, Deferred.succeed(setupStarted, undefined)).pipe( + Effect.as({ + status: "started", + scriptId: "setup", + scriptName: "Setup", + scriptCommand: "setup", + terminalId: "setup-test", + cwd: worktreePath, + async: input.async, + completion: Deferred.await(setupDone).pipe( + Effect.tap(() => Deferred.succeed(completionObserved, undefined)), + ), + }), + ), + }); + harness.createWorktree.mockImplementation(() => + fileSystem + .makeDirectory(path.join(worktreePath, ".git"), { recursive: true }) + .pipe(Effect.as({} as never), Effect.orDie), + ); + + const startup = yield* harness.start.pipe(Effect.forkChild({ startImmediately: true })); + yield* Deferred.await(setupStarted); + if (input.async) yield* Fiber.join(startup); + else expect(harness.open).not.toHaveBeenCalled(); + yield* Deferred.succeed(setupDone, { exitCode: input.exitCode, durationMs: 0 }); + yield* Deferred.await(completionObserved); + yield* Fiber.join(startup); + + const failed = !input.async && input.exitCode !== 0; + expect(harness.projection().runs.at(-1)?.status).toBe(failed ? "failed" : "running"); + expect(harness.open).toHaveBeenCalledTimes(failed ? 0 : 1); + if (failed) { + expect(harness.projection().turnItems).toMatchObject([ + { + type: "error", + title: "Couldn't set up restored workspace", + failure: { + message: `Setup script exited with ${input.exitCode} in '${worktreePath}'.`, + }, + }, + ]); + } + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), +); + effectIt.effect( "preserves recreation interrupts and retries, then fails the final attempt before provider start", () => @@ -2785,7 +2865,7 @@ effectIt.effect.each(["cleanup-first", "startup-first"])( const path = yield* Path.Path; const workspaceRoot = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-start-" }); const worktreePath = path.join(workspaceRoot, "project", "worktree"); - yield* fileSystem.makeDirectory(worktreePath, { recursive: true }); + yield* fileSystem.makeDirectory(path.join(worktreePath, ".git"), { recursive: true }); const release = yield* Deferred.make(); const openEntered = yield* Deferred.make(); const harness = makeLocalCommandHarness({ @@ -2797,7 +2877,7 @@ effectIt.effect.each(["cleanup-first", "startup-first"])( }); harness.createWorktree.mockImplementation(() => fileSystem - .makeDirectory(worktreePath, { recursive: true }) + .makeDirectory(path.join(worktreePath, ".git"), { recursive: true }) .pipe(Effect.as({} as never), Effect.orDie), ); const open = harness.open.getMockImplementation()!; diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.testkit.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.testkit.ts index e5b72cd9f337a..e6c4459a0fdda 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.testkit.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.testkit.ts @@ -21,7 +21,10 @@ import * as Layer from "effect/Layer"; import * as GitWorkflow from "../git/GitWorkflowService.ts"; import * as ProjectService from "../project/ProjectService.ts"; -export const layer = Layer.merge( +export const layer = Layer.mergeAll( + Layer.mock(ProjectSetupScriptRunner.ProjectSetupScriptRunner)({ + runForThread: () => Effect.succeed({ status: "no-script" }), + }), Layer.mock(GitWorkflow.GitWorkflowService)({ pruneWorktrees: () => Effect.void, createWorktree: () => Effect.succeed({} as never), diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index d423d0c2ea675..68a5156b29f28 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -40,6 +40,7 @@ import { import { withTurnStartReservation, withWorkspaceLease } from "../workspace/workspaceLease.ts"; import * as GitWorkflowService from "../git/GitWorkflowService.ts"; import * as ProjectService from "../project/ProjectService.ts"; +import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts"; import * as ProviderAuthService from "../provider/ProviderAuthService.ts"; import * as ServerSettings from "../serverSettings.ts"; import { makeRestoreMissingWorktree } from "../workspace/restoreMissingWorktree.ts"; @@ -88,6 +89,15 @@ export class ProviderTurnStartError extends Schema.TaggedError()( + "WorktreeSetupScriptFailedError", + { worktreePath: Schema.String, exitCode: Schema.NullOr(Schema.Number) }, +) { + override get message(): string { + return `Setup script exited with ${this.exitCode ?? "no exit code"} in '${this.worktreePath}'.`; + } +} + /** Runs that ended without completing: their provider turn may still project as running. */ const NON_COMPLETING_TERMINAL_RUN_STATUSES: ReadonlySet = new Set([ "failed", @@ -262,6 +272,7 @@ export const layer: Layer.Layer< | ServerSettings.ServerSettingsService | GitWorkflowService.GitWorkflowService | ProjectService.ProjectService + | ProjectSetupScriptRunner.ProjectSetupScriptRunner | ProviderAuthService.ProviderAuthService | ProjectionStore.ProjectionStoreV2 | ProviderSessionManager.ProviderSessionManagerV2 @@ -278,6 +289,7 @@ export const layer: Layer.Layer< const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; const projects = yield* ProjectService.ProjectService; + const setupScripts = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner; const providerAuth = yield* ProviderAuthService.ProviderAuthService; const projectionStore = yield* ProjectionStore.ProjectionStoreV2; const providerSessions = yield* ProviderSessionManager.ProviderSessionManagerV2; @@ -814,6 +826,44 @@ export const layer: Layer.Layer< }); return; } + if (recreateResult.success !== undefined) { + const { project, worktreePath } = recreateResult.success; + // Opening the setup terminal takes its own workspace lease. + return { + worktreeSetup: Effect.gen(function* () { + const setupResult = yield* Effect.result( + Effect.gen(function* () { + const setup = yield* setupScripts.runForThread({ + threadId: projection.thread.id, + projectId: project.id, + projectCwd: project.workspaceRoot, + worktreePath, + project, + observeCompletion: {}, + }); + if (setup.status !== "started" || !setup.completion) return; + if (setup.async) { + yield* setup.completion.pipe(Effect.forkDetach); + } else { + const { exitCode } = yield* setup.completion; + if (exitCode !== 0) + return yield* new WorktreeSetupScriptFailedError({ worktreePath, exitCode }); + } + }), + ); + if (setupResult._tag === "Failure") { + yield* settleStartFailure({ + signal: "worktree-setup-failure", + title: "Couldn't set up restored workspace", + error: setupResult.failure, + message: setupResult.failure.message, + }); + return; + } + yield* startWithWorkspaceLease(input); + }), + }; + } const selectInheritedBackgroundItems = ( current: ProjectionStore.ProjectionRuntimeRecoveryState, ): ReturnType => @@ -2146,78 +2196,83 @@ export const layer: Layer.Layer< }); }); - return ProviderTurnStartServiceV2.of({ - start: Effect.fn("ProviderTurnStartService.start")( - function* (input) { - let startingRun: OrchestrationV2Run | undefined; - const captureStartingRun = (run: OrchestrationV2Run) => { - startingRun = run; - }; - return yield* Effect.gen(function* () { - // Storage cleanup removes worktrees under the same lease. Only startup - // holds it; the provider turn runs after it is released. - const { thread } = yield* projectionStore.getThreadRecords(input.threadId, []); - const cwd = - thread.worktreePath ?? - (yield* projects - .getById(thread.projectId, { includeDeleted: true }) - .pipe(Effect.map((project) => Option.getOrUndefined(project)?.workspaceRoot))); - const providerTurn = yield* cwd === undefined - ? start(input, captureStartingRun) - : withTurnStartReservation( - fileSystem, - path, - path.resolve(cwd), - thread.worktreePath === null - ? start(input, captureStartingRun) - : withWorkspaceLease( - path.resolve(thread.worktreePath), - start(input, captureStartingRun), - ), - ); - if (providerTurn !== undefined) { - // Run execution owns finalization after the running write. A later - // failure must not settle a replacement attempt committed by steering. - yield* providerTurn.pipe( - Effect.catchCauseIf( - (cause) => !Cause.hasInterruptsOnly(cause), - (cause) => - Effect.logWarning( - "Run execution failed after starting", - { runId: input.runId }, - cause, + const startWithWorkspaceLease: ProviderTurnStartServiceV2Shape["start"] = Effect.fn( + "ProviderTurnStartService.start", + )( + function* (input) { + let startingRun: OrchestrationV2Run | undefined; + const captureStartingRun = (run: OrchestrationV2Run) => { + startingRun = run; + }; + return yield* Effect.gen(function* () { + // Storage cleanup removes worktrees under the same lease. Only startup + // holds it; the provider turn runs after it is released. + const { thread } = yield* projectionStore.getThreadRecords(input.threadId, []); + const cwd = + thread.worktreePath ?? + (yield* projects + .getById(thread.projectId, { includeDeleted: true }) + .pipe(Effect.map((project) => Option.getOrUndefined(project)?.workspaceRoot))); + const providerTurn = yield* cwd === undefined + ? start(input, captureStartingRun) + : withTurnStartReservation( + fileSystem, + path, + path.resolve(cwd), + thread.worktreePath === null + ? start(input, captureStartingRun) + : withWorkspaceLease( + path.resolve(thread.worktreePath), + start(input, captureStartingRun), ), - ), ); - } - }).pipe( - Effect.catchCauseIf( - (cause) => !Cause.hasInterruptsOnly(cause), - (cause) => - Effect.fail( - new ProviderTurnStartError({ - runId: input.runId, - cause: Cause.squash(cause), - ...(startingRun?.activeAttemptId == null || startingRun.rootNodeId == null - ? {} - : { - attemptId: startingRun.activeAttemptId, - rootNodeId: startingRun.rootNodeId, - }), - }), - ), - ), - ); - }, - (effect, input) => - effect.pipe( - Effect.mapError((cause) => - isProviderTurnStartError(cause) - ? cause - : new ProviderTurnStartError({ runId: input.runId, cause }), - ), + if (providerTurn !== undefined && "worktreeSetup" in providerTurn) { + yield* providerTurn.worktreeSetup; + } else if (providerTurn !== undefined) { + // Run execution owns finalization after the running write. A later + // failure must not settle a replacement attempt committed by steering. + yield* providerTurn.pipe( + Effect.catchCauseIf( + (cause) => !Cause.hasInterruptsOnly(cause), + (cause) => + Effect.logWarning( + "Run execution failed after starting", + { runId: input.runId }, + cause, + ), + ), + ); + } + }).pipe( + Effect.catchCauseIf( + (cause) => !Cause.hasInterruptsOnly(cause), + (cause) => + Effect.fail( + new ProviderTurnStartError({ + runId: input.runId, + cause: Cause.squash(cause), + ...(startingRun?.activeAttemptId == null || startingRun.rootNodeId == null + ? {} + : { + attemptId: startingRun.activeAttemptId, + rootNodeId: startingRun.rootNodeId, + }), + }), + ), ), - ), + ); + }, + (effect, input) => + effect.pipe( + Effect.mapError((cause) => + isProviderTurnStartError(cause) + ? cause + : new ProviderTurnStartError({ runId: input.runId, cause }), + ), + ), + ); + return ProviderTurnStartServiceV2.of({ + start: startWithWorkspaceLease, failStartingRun: Effect.fn("ProviderTurnStartService.failStartingRun")( function* ({ threadId, runId, attemptId, rootNodeId }) { const projection = yield* projectionStore.getTurnStartContext(threadId, runId); diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index 9b928dceda591..9d0486651fb7c 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -64,6 +64,7 @@ import * as SqlitePersistence from "../persistence/Sqlite.ts"; import * as OrchestrationEventStore from "../persistence/OrchestrationEventStore.ts"; import * as ProjectEnrichmentService from "../project/ProjectEnrichmentService.ts"; import * as ProjectService from "../project/ProjectService.ts"; +import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts"; import * as ServerSettings from "../serverSettings.ts"; import * as McpSessionRegistryTestkit from "../mcp/McpSessionRegistry.testkit.ts"; import * as ModelManifest from "../provider/ModelManifest.ts"; @@ -107,7 +108,10 @@ import * as ThreadCommandExecutor from "./ThreadCommandExecutor.ts"; import * as DelegatedTaskQuestionReactor from "./DelegatedTaskQuestionReactor.ts"; import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; -const layerPlatformTest = Layer.merge( +const layerPlatformTest = Layer.mergeAll( + Layer.mock(ProjectSetupScriptRunner.ProjectSetupScriptRunner)({ + runForThread: () => Effect.succeed({ status: "no-script" }), + }), Layer.mergeAll(NodeServices.layer, NodeCrypto.layer), Layer.mock(SourceControlProviderRegistry.SourceControlProviderRegistry)({ resolveLink: () => Effect.die("unused title link"), diff --git a/apps/server/src/project/ProjectSetupScriptRunner.test.ts b/apps/server/src/project/ProjectSetupScriptRunner.test.ts index 0628030b8f91c..c412ade5740cc 100644 --- a/apps/server/src/project/ProjectSetupScriptRunner.test.ts +++ b/apps/server/src/project/ProjectSetupScriptRunner.test.ts @@ -46,10 +46,13 @@ const makeHarness = Effect.fn(function* (options: { readonly command?: string; readonly history?: string; readonly opening?: Deferred.Deferred; + readonly previousSession?: TerminalSessionSnapshot; readonly shell?: string | null; }) { const listeners = new Set<(event: TerminalEvent) => Effect.Effect>(); const opens: TerminalOpenInput[] = []; + const openedSessions: TerminalSessionSnapshot[] = []; + let session = options.previousSession; const writes = yield* Queue.unbounded(); const outputLines = yield* Queue.unbounded(); const terminals = Layer.mock(TerminalManager.TerminalManager)({ @@ -60,7 +63,11 @@ const makeHarness = Effect.fn(function* (options: { ? Deferred.succeed(options.opening, undefined).pipe(Effect.andThen(Effect.never)) : Effect.void, ), - Effect.as(openSnapshot(options.history ?? "")), + Effect.map(() => { + session ??= openSnapshot(options.history ?? ""); + openedSessions.push(session); + return session; + }), ), getShell: () => options.shell === null @@ -72,6 +79,16 @@ const makeHarness = Effect.fn(function* (options: { return () => listeners.delete(listener); }), write: (input) => Queue.offer(writes, input.data).pipe(Effect.asVoid), + close: () => + Effect.sync(() => { + session = undefined; + }).pipe( + Effect.andThen( + Effect.forEach([...listeners], (listener) => listener({ ...event, type: "closed" }), { + discard: true, + }), + ), + ), closeIdle: () => Effect.void, closeOnSettle: () => Effect.void, }); @@ -108,13 +125,14 @@ const makeHarness = Effect.fn(function* (options: { }); const emit = (terminalEvent: TerminalEvent) => Effect.forEach([...listeners], (listener) => listener(terminalEvent), { discard: true }); - return { start, listeners, writes, outputLines, emit, opens }; + return { start, listeners, writes, outputLines, emit, openedSessions, opens }; }); const setup = Effect.fn(function* ( options: { readonly command?: string; readonly history?: string; + readonly previousSession?: TerminalSessionSnapshot; readonly shell?: string | null; } = {}, ) { @@ -168,10 +186,13 @@ describe("ProjectSetupScriptRunner", () => { }), ); - it.effect("shows a startup prompt and types only once the line editor starts", () => + it.effect("replaces a surviving setup shell and types only once the line editor starts", () => Effect.gen(function* () { - const { result, writes, outputLines, emit } = yield* setup(); + const { result, completion, openedSessions, writes, outputLines, emit } = yield* setup({ + previousSession: openSnapshot("previous setup in the deleted checkout"), + }); expect(result).toMatchObject({ status: "started", terminalId }); + expect(openedSessions).toEqual([openSnapshot("")]); yield* emit({ ...event, type: "output", data: "Missing Node.\r\nInstall it? [y/N]: " }); yield* emit({ ...event, type: "activity", hasRunningSubprocess: true, label: "fnm" }); @@ -181,7 +202,12 @@ describe("ProjectSetupScriptRunner", () => { yield* emit({ ...event, type: "activity", hasRunningSubprocess: false, label: "zsh" }); yield* emit({ ...event, type: "output", data: "\r\n% \x1b[?2004h" }); - expect(yield* Queue.take(writes)).toContain("vp i"); + const command = yield* Queue.take(writes); + expect(command).toContain("vp i"); + const sentinel = command.match(/__T3_SETUP_DONE___[a-f0-9]+:/)?.[0]; + expect(sentinel).toBeDefined(); + yield* emit({ ...event, type: "output", data: `${sentinel}0\r\n% ` }); + expect(yield* completion).toMatchObject({ exitCode: 0 }); }), ); @@ -227,16 +253,32 @@ describe("ProjectSetupScriptRunner", () => { }), ); - it.effect("drops its terminal listeners when cancelled while the terminal opens", () => - Effect.gen(function* () { - const opening = yield* Deferred.make(); - const { start, listeners } = yield* makeHarness({ opening }); - const fiber = yield* Effect.forkChild(start); - yield* Deferred.await(opening); - expect(listeners.size).toBe(2); - yield* Fiber.interrupt(fiber); - expect(listeners.size).toBe(0); - }), + it.effect.each(["opening", "completion"] as const)( + "stops pending setup when cancelled during %s", + (phase) => + Effect.gen(function* () { + const opening = yield* Deferred.make(); + const { start, listeners, writes, emit } = yield* makeHarness( + phase === "opening" ? { opening } : {}, + ); + const pending = + phase === "opening" + ? start.pipe(Effect.asVoid) + : yield* start.pipe( + Effect.map((result) => + result.status === "started" && result.completion + ? result.completion.pipe(Effect.asVoid) + : Effect.die("setup did not start"), + ), + ); + const fiber = yield* pending.pipe(Effect.forkChild({ startImmediately: true })); + if (phase === "opening") yield* Deferred.await(opening); + expect(listeners.size).toBe(2); + yield* Fiber.interrupt(fiber); + expect(listeners.size).toBe(0); + yield* emit({ ...event, type: "output", data: "\r\n% \x1b[?2004h" }); + expect(yield* Queue.size(writes)).toBe(0); + }), ); it.effect.each([false, true])( diff --git a/apps/server/src/project/ProjectSetupScriptRunner.ts b/apps/server/src/project/ProjectSetupScriptRunner.ts index 0f2e58d121402..397909bcc89f7 100644 --- a/apps/server/src/project/ProjectSetupScriptRunner.ts +++ b/apps/server/src/project/ProjectSetupScriptRunner.ts @@ -12,6 +12,7 @@ import * as Context from "effect/Context"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; @@ -495,6 +496,19 @@ export const make = Effect.gen(function* () { trigger === "settle" ? `settle-${script.id}-${(yield* random.uuidV4()).slice(0, 8)}` : `setup-${script.id}`; + // A surviving setup shell may still hold a deleted worktree directory. + if (trigger === "setup") { + yield* terminalManager.close({ threadId: input.threadId, terminalId }).pipe( + Effect.mapError( + (cause) => + new ProjectSetupScriptOperationError({ + ...errorContext, + operation: "openTerminal", + cause, + }), + ), + ); + } const cwd = input.worktreePath; const env = { ...projectScriptRuntimeEnv({ @@ -581,7 +595,7 @@ export const make = Effect.gen(function* () { // Return once the terminal exists so callers can show it while a startup prompt waits. // PowerShell and cmd have no line-editor signal. - yield* ( + const commandWriter = yield* ( completionShell === "powershell" || completionShell === null ? Effect.succeed("ready" as const) : readiness.wait @@ -607,6 +621,13 @@ export const make = Effect.gen(function* () { ); const completion = observed?.completion.pipe( + Effect.onInterrupt(() => + Fiber.interrupt(commandWriter).pipe( + Effect.andThen(Effect.sync(() => readiness.unsubscribe())), + Effect.andThen(terminalManager.close({ threadId: input.threadId, terminalId })), + Effect.ignore, + ), + ), Effect.tap(({ exitCode }) => exitCode === 0 ? terminalManager.closeIdle({ threadId: input.threadId, terminalId }) diff --git a/apps/server/src/workspace/restoreMissingWorktree.ts b/apps/server/src/workspace/restoreMissingWorktree.ts index c2c3c00eb7741..31b118bdddfed 100644 --- a/apps/server/src/workspace/restoreMissingWorktree.ts +++ b/apps/server/src/workspace/restoreMissingWorktree.ts @@ -201,6 +201,7 @@ export const makeRestoreMissingWorktree = Effect.gen(function* () { : new WorktreeRecreateError({ worktreePath, branch, cause }), ), ); + return { project, worktreePath }; }); }); @@ -221,9 +222,11 @@ export const layerThreadWorktreeRestore = Layer.effect( const restore = yield* makeRestoreMissingWorktree; return { restore: Effect.fn("ThreadWorktreeRestore.restore")(function* (thread: WorktreeThread) { - return yield* thread.worktreePath === null - ? restore(thread) - : withWorkspaceLease(path.resolve(thread.worktreePath), restore(thread)); + return yield* ( + thread.worktreePath === null + ? restore(thread) + : withWorkspaceLease(path.resolve(thread.worktreePath), restore(thread)) + ).pipe(Effect.asVoid); }), }; }), @@ -257,6 +260,7 @@ export const makePrepareTerminalLaunch = Effect.fn( } const recover = (error: TerminalCwdNotFoundError) => restoreMissingWorktree(thread).pipe( + Effect.asVoid, Effect.catch((cause) => Effect.logWarning("failed to recreate missing worktree", { threadId: thread.id,