The best way to control Claude Code, Codex and more from any computer or phone
fix(server): terminals recreate a worktree removed by storage cleanup (#24156)
Co-authored-by: Julius Marminge <julius0216@outlook.com>
Antony committed
Nov 12, 2026 at 23:48 UTC
da345d203ccc819276821167904e591e2356e99d
5 files changed
+312
-135
apps/server/src/orchestration-v2/ProviderTurnStartService.ts
+12
-131
@@ -35,7 +35,7 @@ import * as GitWorkflowService from "../git/GitWorkflowService.ts";
35
import * as ProjectService from "../project/ProjectService.ts";
36
import * as ProviderAuthService from "../provider/ProviderAuthService.ts";
37
import * as ServerSettings from "../serverSettings.ts";
38
-import { makeIsManagedWorktreePath } from "../worktreesDirectory.ts";
38
+import { makeRestoreMissingWorktree } from "../workspace/restoreMissingWorktree.ts";
39
import * as EventSink from "./EventSink.ts";
40
import * as ProviderUsageAnalytics from "../telemetry/ProviderUsageAnalytics.ts";
41
import * as ContextHandoffService from "./ContextHandoffService.ts";
@@ -77,28 +77,6 @@ export class ProviderTurnStartError extends Schema.TaggedError<ProviderTurnStart
77
},
78
) {}
79
80
-class WorktreeRecreateError extends Schema.TaggedError<WorktreeRecreateError>()(
81
- "WorktreeRecreateError",
82
- {
83
- worktreePath: Schema.String,
84
- branch: Schema.String,
85
- cause: Schema.Defect(),
86
- },
87
-) {
88
- override get message(): string {
89
- return `Could not recreate the worktree for branch '${this.branch}' at ${this.worktreePath}.`;
90
- }
91
-}
92
-
93
-class WorktreeRecreateNoBaseError extends Schema.TaggedError<WorktreeRecreateNoBaseError>()(
94
- "WorktreeRecreateNoBaseError",
95
- { worktreePath: Schema.String, branch: Schema.String },
96
-) {
97
- override get message(): string {
98
- return `Could not recreate branch '${this.branch}' at ${this.worktreePath}: the project workspace has no commit to start it from.`;
99
- }
100
-}
101
-
80
const isProviderTurnStartError = Schema.is(ProviderTurnStartError);
81
const isProviderAdapterProtocolError = Schema.is(ProviderAdapter.ProviderAdapterProtocolError);
82
const isProviderAdapterOpenSessionError = Schema.is(
@@ -176,80 +154,14 @@ export const layer: Layer.Layer<
154
const turnAnalytics = yield* ProviderUsageAnalytics.ProviderTurnAnalytics;
155
const contextHandoffService = yield* ContextHandoffService.ContextHandoffServiceV2;
156
const idAllocator = yield* IdAllocator.IdAllocatorV2;
179
- const fileSystem = yield* FileSystem.FileSystem;
157
const path = yield* Path.Path;
181
- const gitWorkflow = yield* GitWorkflowService.GitWorkflowService;
182
- const projects = yield* ProjectService.ProjectService;
158
const providerAuth = yield* ProviderAuthService.ProviderAuthService;
159
const projectionStore = yield* ProjectionStore.ProjectionStoreV2;
160
const providerSessions = yield* ProviderSessionManager.ProviderSessionManagerV2;
161
const runExecution = yield* RunExecutionService.RunExecutionServiceV2;
162
const runtimePolicy = yield* RuntimePolicy.RuntimePolicyV2;
163
+ const restoreMissingWorktree = yield* makeRestoreMissingWorktree;
164
const turnItemPositions = yield* TurnItemPositionStore.TurnItemPositionStoreV2;
189
- const isManagedWorktreePath = yield* makeIsManagedWorktreePath;
190
-
191
- const resolveRecreateBase = Effect.fn("ProviderTurnStartService.resolveRecreateBase")(
192
- function* (cwd: string) {
193
- // Recovery can follow an external checkout, before the status cache expires.
194
- yield* gitWorkflow.invalidateLocalStatus(cwd);
195
- const { refName: currentBranch } = yield* gitWorkflow.localStatus({ cwd });
196
- if (currentBranch !== null) {
197
- const refName = `refs/heads/${currentBranch}`;
198
- return { refName, baseRefName: refName };
199
- }
200
- if (yield* gitWorkflow.hasCommit({ cwd, refName: "refs/remotes/origin/HEAD" })) {
201
- const { commitSha } = yield* gitWorkflow.resolveRemoteTrackingCommit({
202
- cwd,
203
- refName: "HEAD",
204
- fallbackRemoteName: "origin",
205
- });
206
- // Start from the commit so the thread branch does not track the default branch.
207
- return { refName: commitSha, baseRefName: "refs/remotes/origin/HEAD" };
208
- }
209
- if (yield* gitWorkflow.hasCommit({ cwd, refName: "HEAD" })) {
210
- return { refName: "HEAD", baseRefName: undefined };
211
- }
212
- return null;
213
- },
214
- );
215
-
216
- const recreateMissingWorktree = Effect.fn("ProviderTurnStartService.recreateMissingWorktree")(
217
- function* (input: {
218
- readonly cwd: string;
219
- readonly worktreePath: string;
220
- readonly branch: string;
221
- }) {
222
- const { cwd, worktreePath, branch } = input;
223
- yield* gitWorkflow.pruneWorktrees({ cwd });
224
- const localBranchNames = yield* gitWorkflow.listLocalBranchNames(cwd);
225
- if (localBranchNames.includes(branch)) {
226
- yield* gitWorkflow.createWorktree({ cwd, refName: branch, path: worktreePath });
227
- return;
228
- }
229
- // Push keeps the tracking ref current, so recovery reads it without fetching.
230
- const pushedRef = `refs/remotes/origin/${branch}`;
231
- if (yield* gitWorkflow.hasCommit({ cwd, refName: pushedRef })) {
232
- yield* gitWorkflow.createWorktree({
233
- cwd,
234
- refName: pushedRef,
235
- newRefName: branch,
236
- path: worktreePath,
237
- });
238
- return;
239
- }
240
- const base = yield* resolveRecreateBase(cwd);
241
- if (base === null) {
242
- return yield* new WorktreeRecreateNoBaseError({ worktreePath, branch });
243
- }
244
- yield* gitWorkflow.createWorktree({
245
- cwd,
246
- refName: base.refName,
247
- newRefName: branch,
248
- ...(base.baseRefName === undefined ? {} : { baseRefName: base.baseRefName }),
249
- path: worktreePath,
250
- });
251
- },
252
- );
165
166
// Build draining callbacks outside startup scope so they cannot retain full thread history.
167
const makeRunControls = (input: {
@@ -650,47 +562,16 @@ export const layer: Layer.Layer<
562
return;
563
}
564
}
653
- const { worktreePath, branch } = projection.thread;
654
- if (worktreePath !== null && branch !== null) {
655
- const exists = yield* fileSystem
656
- .exists(worktreePath)
657
- .pipe(Effect.orElseSucceed(() => true));
658
- if (!exists && (yield* isManagedWorktreePath(worktreePath))) {
659
- const project = yield* projects.getById(projection.thread.projectId).pipe(
660
- Effect.map(Option.getOrUndefined),
661
- Effect.orElseSucceed(() => undefined),
662
- );
663
- if (project !== undefined) {
664
- yield* Effect.logWarning("provider turn start recreating missing worktree", {
665
- threadId: projection.thread.id,
666
- worktreePath,
667
- branch,
668
- });
669
- const recreateResult = yield* Effect.result(
670
- recreateMissingWorktree({
671
- cwd: project.workspaceRoot,
672
- worktreePath,
673
- branch,
674
- }).pipe(
675
- Effect.mapError((cause) =>
676
- cause._tag === "WorktreeRecreateNoBaseError"
677
- ? cause
678
- : new WorktreeRecreateError({ worktreePath, branch, cause }),
679
- ),
680
- ),
681
- );
682
- if (recreateResult._tag === "Failure") {
683
- if (input.willRetry === true) return yield* recreateResult.failure;
684
- yield* settleStartFailure({
685
- signal: "worktree-recreate-failure",
686
- title: "Couldn't recreate thread workspace",
687
- error: recreateResult.failure,
688
- message: recreateResult.failure.message,
689
- });
690
- return;
691
- }
692
- }
693
- }
565
+ const recreateResult = yield* Effect.result(restoreMissingWorktree(projection.thread));
566
+ if (recreateResult._tag === "Failure") {
567
+ if (input.willRetry === true) return yield* recreateResult.failure;
568
+ yield* settleStartFailure({
569
+ signal: "worktree-recreate-failure",
570
+ title: "Couldn't recreate thread workspace",
571
+ error: recreateResult.failure,
572
+ message: recreateResult.failure.message,
573
+ });
574
+ return;
575
}
576
const selectInheritedBackgroundItems = (
577
current: ProjectionStore.ProjectionRuntimeRecoveryState,
apps/server/src/terminal/Manager.test.ts
+92
-1
@@ -4,12 +4,14 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
4
import { assert, it } from "@effect/vitest";
5
import {
6
DEFAULT_TERMINAL_ID,
7
+ ProjectId,
8
+ ThreadId,
9
+ TerminalCwdNotFoundError,
10
type TerminalAttachStreamEvent,
11
type TerminalEvent,
12
type TerminalOpenInput,
13
ProviderDriverKind,
14
ProviderInstanceId,
12
- ProjectId,
15
retainedTerminalHistory,
16
TerminalProviderInstanceNotFoundError,
17
} from "@t3tools/contracts";
@@ -36,12 +38,16 @@ import * as SynchronizedRef from "effect/SynchronizedRef";
38
import * as TestClock from "effect/testing/TestClock";
39
import { expect, vi } from "vite-plus/test";
40
41
+import * as ServerConfig from "../config.ts";
42
import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";
43
import * as ProcessRunner from "../processRunner.ts";
44
import * as ServerSettings from "../serverSettings.ts";
45
import * as ProjectService from "../project/ProjectService.ts";
46
import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts";
47
import * as TerminalManager from "./Manager.ts";
48
+import * as GitWorkflowService from "../git/GitWorkflowService.ts";
49
+import { makePrepareTerminalLaunch } from "../workspace/restoreMissingWorktree.ts";
50
+import { withWorkspaceLease } from "../workspace/workspaceLease.ts";
51
import { terminalOutputStream } from "./OutputProtocol.ts";
52
import * as PtyAdapter from "@t3tools/shared/PtyAdapter";
53
import packageJson from "../../package.json" with { type: "json" };
@@ -453,6 +459,91 @@ it.layer(
459
),
460
{ excludeTestServices: true },
461
)("TerminalManager", (it) => {
462
+ it.effect.each([
463
+ { method: "open", location: "managed" },
464
+ { method: "attach", location: "managed" },
465
+ { method: "open", location: "subdirectory" },
466
+ { method: "open", location: "unmanaged" },
467
+ { method: "open", location: "no-worktree" },
468
+ ] as const)(
469
+ "recovers $method with a $location cwd without a cleanup gap",
470
+ ({ method, location }) =>
471
+ Effect.gen(function* () {
472
+ const fs = yield* FileSystem.FileSystem;
473
+ const path = yield* Path.Path;
474
+ const { manager, ptyAdapter, baseDir } = yield* createManager();
475
+ const worktreesDir = path.join(baseDir, "worktrees");
476
+ const worktreePath =
477
+ location === "unmanaged"
478
+ ? path.join(baseDir, "missing")
479
+ : path.join(worktreesDir, "project", "feature");
480
+ const cwd = location === "subdirectory" ? path.join(worktreePath, "src") : worktreePath;
481
+ const cleanupQueued = yield* Deferred.make<Fiber.Fiber<void>>();
482
+ let creations = 0;
483
+ const prepareLaunch = yield* makePrepareTerminalLaunch(() =>
484
+ Effect.succeed({
485
+ id: ThreadId.make("thread-1"),
486
+ projectId: ProjectId.make("project-1"),
487
+ worktreePath: location === "no-worktree" ? null : worktreePath,
488
+ branch: "feature",
489
+ }),
490
+ ).pipe(
491
+ Effect.provide(
492
+ Layer.mergeAll(
493
+ Layer.mock(ServerConfig.ServerConfig)({
494
+ worktreesDir,
495
+ } as ServerConfig.ServerConfig["Service"]),
496
+ ServerSettings.layerTest(),
497
+ Layer.mock(ProjectService.ProjectService)({
498
+ getById: () => Effect.succeedSome({ workspaceRoot: baseDir } as never),
499
+ }),
500
+ Layer.mock(GitWorkflowService.GitWorkflowService)({
501
+ pruneWorktrees: () => Effect.void,
502
+ listLocalBranchNames: () => Effect.succeed(["feature"]),
503
+ createWorktree: () =>
504
+ Effect.gen(function* () {
505
+ creations++;
506
+ yield* fs.makeDirectory(cwd, { recursive: true }).pipe(Effect.orDie);
507
+ const cleanup = yield* withWorkspaceLease(
508
+ worktreePath,
509
+ Effect.sync(() => {
510
+ assert.equal(ptyAdapter.spawnInputs.length, 1);
511
+ }),
512
+ ).pipe(Effect.forkChild({ startImmediately: true }));
513
+ yield* Deferred.succeed(cleanupQueued, cleanup);
514
+ return {} as never;
515
+ }),
516
+ }),
517
+ ),
518
+ ),
519
+ );
520
+ const input = openInput({
521
+ cwd,
522
+ worktreePath: location === "subdirectory" ? null : worktreePath,
523
+ });
524
+ const launch = prepareLaunch(input).pipe(
525
+ Effect.flatMap(({ input, recover }) =>
526
+ (method === "attach"
527
+ ? manager.attachStream(input, () => Effect.void).pipe(Effect.asVoid)
528
+ : manager.open(input).pipe(Effect.asVoid)
529
+ ).pipe(Effect.provideService(TerminalManager.TerminalCwdRecovery, recover)),
530
+ ),
531
+ );
532
+ if (location === "unmanaged" || location === "no-worktree") {
533
+ const error = yield* launch.pipe(Effect.flip);
534
+ assert.deepEqual(error, new TerminalCwdNotFoundError({ cwd }));
535
+ assert.equal(creations, 0);
536
+ assert.equal(ptyAdapter.spawnInputs.length, 0);
537
+ return;
538
+ }
539
+ yield* launch;
540
+ yield* Fiber.join(yield* Deferred.await(cleanupQueued));
541
+ assert.equal(creations, 1);
542
+ assert.equal(ptyAdapter.spawnInputs.length, 1);
543
+ assert.isTrue(yield* fs.exists(cwd));
544
+ }),
545
+ );
546
+
547
it.effect("spawns lazily and reuses running terminal per thread", () =>
548
Effect.gen(function* () {
549
const { manager, ptyAdapter } = yield* createManager();
apps/server/src/terminal/Manager.ts
+13
-1
@@ -167,6 +167,10 @@ class TerminalProcessSignalError extends Schema.TaggedError<TerminalProcessSigna
167
}
168
}
169
170
+export class TerminalCwdRecovery extends Context.Reference<
171
+ (error: TerminalCwdNotFoundError) => Effect.Effect<void, TerminalCwdNotFoundError>
172
+>("t3/terminal/TerminalCwdRecovery", { defaultValue: () => (error) => Effect.fail(error) }) {}
173
+
174
export class TerminalManager extends Context.Service<
175
TerminalManager,
176
{
@@ -2206,7 +2210,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
2210
});
2211
2212
const assertValidCwd = Effect.fn("terminal.assertValidCwd")(function* (cwd: string) {
2209
- const stats = yield* fileSystem.stat(cwd).pipe(
2213
+ const stat = fileSystem.stat(cwd).pipe(
2214
Effect.catchTags({
2215
PlatformError: (cause) =>
2216
cause.reason._tag === "NotFound"
@@ -2214,6 +2218,14 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
2218
: new TerminalCwdStatError({ cwd, cause }),
2219
}),
2220
);
2221
+ const stats = yield* stat.pipe(
2222
+ Effect.catchTags({
2223
+ TerminalCwdNotFoundError: (error) =>
2224
+ Effect.flatMap(TerminalCwdRecovery, (recover) =>
2225
+ recover(error).pipe(Effect.andThen(stat)),
2226
+ ),
2227
+ }),
2228
+ );
2229
if (stats.type !== "Directory") {
2230
return yield* new TerminalCwdNotDirectoryError({ cwd });
2231
}
apps/server/src/workspace/restoreMissingWorktree.ts
new
+174
@@ -0,0 +1,174 @@
1
+import { ThreadId, type ProjectId, type TerminalCwdNotFoundError } from "@t3tools/contracts";
2
+import * as Effect from "effect/Effect";
3
+import * as FileSystem from "effect/FileSystem";
4
+import * as Option from "effect/Option";
5
+import * as Path from "effect/Path";
6
+import * as Schema from "effect/Schema";
7
+
8
+import * as GitWorkflowService from "../git/GitWorkflowService.ts";
9
+import * as ProjectService from "../project/ProjectService.ts";
10
+import { makeIsManagedWorktreePath } from "../worktreesDirectory.ts";
11
+import { isWithinRoot } from "./KnownWorkspaces.ts";
12
+import { TerminalCwdRecovery } from "../terminal/Manager.ts";
13
+
14
+class WorktreeRecreateError extends Schema.TaggedError<WorktreeRecreateError>()(
15
+ "WorktreeRecreateError",
16
+ {
17
+ worktreePath: Schema.String,
18
+ branch: Schema.String,
19
+ cause: Schema.Defect(),
20
+ },
21
+) {
22
+ override get message(): string {
23
+ return `Could not recreate the worktree for branch '${this.branch}' at ${this.worktreePath}.`;
24
+ }
25
+}
26
+
27
+class WorktreeRecreateNoBaseError extends Schema.TaggedError<WorktreeRecreateNoBaseError>()(
28
+ "WorktreeRecreateNoBaseError",
29
+ { worktreePath: Schema.String, branch: Schema.String },
30
+) {
31
+ override get message(): string {
32
+ return `Could not recreate branch '${this.branch}' at ${this.worktreePath}: the project workspace has no commit to start it from.`;
33
+ }
34
+}
35
+
36
+interface WorktreeThread {
37
+ readonly id: ThreadId;
38
+ readonly projectId: ProjectId;
39
+ readonly worktreePath: string | null;
40
+ readonly branch: string | null;
41
+}
42
+
43
+export const makeRestoreMissingWorktree = Effect.gen(function* () {
44
+ const fileSystem = yield* FileSystem.FileSystem;
45
+ const gitWorkflow = yield* GitWorkflowService.GitWorkflowService;
46
+ const projects = yield* ProjectService.ProjectService;
47
+ const isManagedWorktreePath = yield* makeIsManagedWorktreePath;
48
+
49
+ const resolveRecreateBase = Effect.fn("restoreMissingWorktree.resolveRecreateBase")(function* (
50
+ cwd: string,
51
+ ) {
52
+ // Recovery can follow an external checkout, before the status cache expires.
53
+ yield* gitWorkflow.invalidateLocalStatus(cwd);
54
+ const { refName: currentBranch } = yield* gitWorkflow.localStatus({ cwd });
55
+ if (currentBranch !== null) {
56
+ const refName = `refs/heads/${currentBranch}`;
57
+ return { refName, baseRefName: refName };
58
+ }
59
+ if (yield* gitWorkflow.hasCommit({ cwd, refName: "refs/remotes/origin/HEAD" })) {
60
+ const { commitSha } = yield* gitWorkflow.resolveRemoteTrackingCommit({
61
+ cwd,
62
+ refName: "HEAD",
63
+ fallbackRemoteName: "origin",
64
+ });
65
+ // Start from the commit so the thread branch does not track the default branch.
66
+ return { refName: commitSha, baseRefName: "refs/remotes/origin/HEAD" };
67
+ }
68
+ if (yield* gitWorkflow.hasCommit({ cwd, refName: "HEAD" })) {
69
+ return { refName: "HEAD", baseRefName: undefined };
70
+ }
71
+ return null;
72
+ });
73
+
74
+ const recreateMissingWorktree = Effect.fn("restoreMissingWorktree.recreate")(function* (input: {
75
+ readonly cwd: string;
76
+ readonly worktreePath: string;
77
+ readonly branch: string;
78
+ }) {
79
+ const { cwd, worktreePath, branch } = input;
80
+ yield* gitWorkflow.pruneWorktrees({ cwd });
81
+ const localBranchNames = yield* gitWorkflow.listLocalBranchNames(cwd);
82
+ if (localBranchNames.includes(branch)) {
83
+ yield* gitWorkflow.createWorktree({ cwd, refName: branch, path: worktreePath });
84
+ return;
85
+ }
86
+ // Push keeps the tracking ref current, so recovery reads it without fetching.
87
+ const pushedRef = `refs/remotes/origin/${branch}`;
88
+ if (yield* gitWorkflow.hasCommit({ cwd, refName: pushedRef })) {
89
+ yield* gitWorkflow.createWorktree({
90
+ cwd,
91
+ refName: pushedRef,
92
+ newRefName: branch,
93
+ path: worktreePath,
94
+ });
95
+ return;
96
+ }
97
+ const base = yield* resolveRecreateBase(cwd);
98
+ if (base === null) {
99
+ return yield* new WorktreeRecreateNoBaseError({ worktreePath, branch });
100
+ }
101
+ yield* gitWorkflow.createWorktree({
102
+ cwd,
103
+ refName: base.refName,
104
+ newRefName: branch,
105
+ ...(base.baseRefName === undefined ? {} : { baseRefName: base.baseRefName }),
106
+ path: worktreePath,
107
+ });
108
+ });
109
+
110
+ return Effect.fn("restoreMissingWorktree")(function* (thread: WorktreeThread) {
111
+ const { worktreePath, branch } = thread;
112
+ if (worktreePath === null || branch === null) return;
113
+ const exists = yield* fileSystem.exists(worktreePath).pipe(Effect.orElseSucceed(() => true));
114
+ if (exists || !(yield* isManagedWorktreePath(worktreePath))) return;
115
+ const project = yield* projects.getById(thread.projectId).pipe(
116
+ Effect.map(Option.getOrUndefined),
117
+ Effect.orElseSucceed(() => undefined),
118
+ );
119
+ if (project === undefined) return;
120
+ yield* Effect.logWarning("recreating missing worktree", {
121
+ threadId: thread.id,
122
+ worktreePath,
123
+ branch,
124
+ });
125
+ yield* recreateMissingWorktree({ cwd: project.workspaceRoot, worktreePath, branch }).pipe(
126
+ Effect.mapError((cause) =>
127
+ cause._tag === "WorktreeRecreateNoBaseError"
128
+ ? cause
129
+ : new WorktreeRecreateError({ worktreePath, branch, cause }),
130
+ ),
131
+ );
132
+ });
133
+});
134
+
135
+// Worktree setup uses terminals, so recovery must stay outside TerminalManager.
136
+export const makePrepareTerminalLaunch = Effect.fn(
137
+ "restoreMissingWorktree.makePrepareTerminalLaunch",
138
+)(function* <LookupError>(
139
+ getThreadShell: (threadId: ThreadId) => Effect.Effect<WorktreeThread | null, LookupError>,
140
+) {
141
+ const path = yield* Path.Path;
142
+ const restoreMissingWorktree = yield* makeRestoreMissingWorktree;
143
+ return Effect.fn("restoreMissingWorktree.prepareTerminalLaunch")(function* <
144
+ Input extends {
145
+ readonly threadId: string;
146
+ readonly cwd?: string | undefined;
147
+ readonly worktreePath?: string | null | undefined;
148
+ },
149
+ >(input: Input) {
150
+ const thread = yield* getThreadShell(ThreadId.make(input.threadId)).pipe(
151
+ Effect.orElseSucceed(() => null),
152
+ );
153
+ const worktreePath = thread?.worktreePath ?? null;
154
+ if (
155
+ thread === null ||
156
+ worktreePath === null ||
157
+ !isWithinRoot(path, path.resolve(input.cwd ?? worktreePath), worktreePath)
158
+ ) {
159
+ return { input, recover: TerminalCwdRecovery.defaultValue() };
160
+ }
161
+ const recover = (error: TerminalCwdNotFoundError) =>
162
+ restoreMissingWorktree(thread).pipe(
163
+ Effect.catch((cause) =>
164
+ Effect.logWarning("failed to recreate missing worktree", {
165
+ threadId: thread.id,
166
+ worktreePath,
167
+ cause,
168
+ }).pipe(Effect.andThen(Effect.fail(error))),
169
+ ),
170
+ );
171
+ // The lease must cover the worktree root, even when the terminal opens in a subdirectory.
172
+ return { input: { ...input, worktreePath }, recover };
173
+ });
174
+});
apps/server/src/ws.ts
+21
-2
@@ -191,6 +191,7 @@ import { invalidateSettingsSecrets } from "./sourceControl/sourceControlHostSecr
191
import * as DatabaseStorage from "./persistence/DatabaseStorage.ts";
192
import * as StorageCleanup from "./storageCleanup.ts";
193
import * as TerminalManager from "./terminal/Manager.ts";
194
+import { makePrepareTerminalLaunch } from "./workspace/restoreMissingWorktree.ts";
195
import { terminalOutputStream, withOutputWindow } from "./terminal/OutputProtocol.ts";
196
import * as ServerBrowser from "./preview/ServerBrowser.ts";
197
import * as DeviceService from "./device/DeviceService.ts";
@@ -1514,6 +1515,9 @@ export const layerWsRpc = (
1515
const vcsProvisioning = yield* VcsProvisioningService.VcsProvisioningService;
1516
const vcsStatusBroadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
1517
const terminalManager = yield* TerminalManager.TerminalManager;
1518
+ const prepareTerminalLaunch = yield* makePrepareTerminalLaunch(
1519
+ threadManagement.getThreadShell,
1520
+ );
1521
const previewManager = yield* PreviewManager.PreviewManager;
1522
const portDiscovery = yield* PortScanner.PortDiscovery;
1523
const providerRegistry = yield* ProviderRegistry.ProviderRegistry;
@@ -3161,9 +3165,24 @@ export const layerWsRpc = (
3165
[WS_METHODS.reviewGetBranchCommits]: (input) => review.getBranchCommits(input),
3166
[WS_METHODS.reviewGetDiffPreview]: (input) => review.getDiffPreview(input),
3167
[WS_METHODS.reviewGetDiffFileContents]: (input) => review.getDiffFileContents(input),
3164
- [WS_METHODS.terminalOpen]: (input) => terminalManager.open(input),
3168
+ [WS_METHODS.terminalOpen]: (input) =>
3169
+ prepareTerminalLaunch(input).pipe(
3170
+ Effect.flatMap((launch) =>
3171
+ terminalManager
3172
+ .open(launch.input)
3173
+ .pipe(Effect.provideService(TerminalManager.TerminalCwdRecovery, launch.recover)),
3174
+ ),
3175
+ ),
3176
[WS_METHODS.terminalAttach]: (input, metadata) =>
3166
- terminalManager.attachOutputStream(input, terminalViewerId(metadata)),
3177
+ Stream.unwrap(
3178
+ prepareTerminalLaunch(input).pipe(
3179
+ Effect.map((launch) =>
3180
+ terminalManager
3181
+ .attachOutputStream(launch.input, terminalViewerId(metadata))
3182
+ .pipe(Stream.provideService(TerminalManager.TerminalCwdRecovery, launch.recover)),
3183
+ ),
3184
+ ),
3185
+ ),
3186
[WS_METHODS.terminalWrite]: (input) => terminalManager.write(input),
3187
[WS_METHODS.terminalResize]: (input, metadata) =>
3188
terminalManager.resize(input, terminalViewerId(metadata)),