7
import * as DateTime from "effect/DateTime";
8
import * as Duration from "effect/Duration";
9
import * as Effect from "effect/Effect";
10
+import * as Fiber from "effect/Fiber";
11
import * as Layer from "effect/Layer";
12
import * as Option from "effect/Option";
13
import * as Path from "effect/Path";
14
import * as Queue from "effect/Queue";
15
import * as Ref from "effect/Ref";
16
+import * as Schedule from "effect/Schedule";
17
import * as Schema from "effect/Schema";
18
import * as Stream from "effect/Stream";
19
import {
131
import { linkCreatedPullRequest } from "./git/linkCreatedPullRequest.ts";
132
import * as ReviewService from "./review/ReviewService.ts";
133
import * as ProjectSetupScriptRunner from "./project/ProjectSetupScriptRunner.ts";
134
+import * as WorktreeSetupTracker from "./project/WorktreeSetupTracker.ts";
135
import * as AgentSessionScanner from "./project/AgentSessionScanner.ts";
136
import { importRecentAgentThreads } from "./project/AgentSessionImporter.ts";
137
import * as ServerEnvironment from "./environment/ServerEnvironment.ts";
600
return true;
601
});
602
const projectSetupScriptRunner = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner;
603
+ const worktreeSetupTracker = yield* WorktreeSetupTracker.WorktreeSetupTracker;
604
const agentSessionScanner = yield* AgentSessionScanner.AgentSessionScanner;
605
const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
606
const backgroundPolicy = yield* BackgroundPolicy.BackgroundPolicy;
995
let targetProjectId = bootstrap?.createThread?.projectId;
996
let targetProjectCwd = bootstrap?.prepareWorktree?.projectCwd;
997
let targetWorktreePath = bootstrap?.createThread?.worktreePath ?? null;
998
+ // The setup script's terminal, once started. Cancel closes only this
999
+ // one so terminals the user opened meanwhile survive.
1000
+ let setupTerminalId: string | null = null;
1001
1002
const cleanupCreatedThread = () =>
1003
createdThread
1090
);
1091
});
1092
1093
+ const tracked = bootstrap?.prepareWorktree !== undefined;
1094
+ const threadId = command.threadId;
1095
+ const track = (effect: Effect.Effect<void>) => (tracked ? effect : Effect.void);
1096
+
1097
+ // Runs the setup script and, for tracked bootstraps, waits for it to
1098
+ // exit so the card can show the exit code and the agent stage never
1099
+ // starts on a half-installed tree. Untracked callers keep the old
1100
+ // fire-and-forget behavior.
1101
const runSetupProgram = () =>
1102
Effect.gen(function* () {
1103
if (!bootstrap?.runSetupScript || !targetWorktreePath) {
1104
+ yield* track(worktreeSetupTracker.stageStatus(threadId, "setup-script", "skipped"));
1105
return;
1106
}
1107
const worktreePath = targetWorktreePath;
1108
const requestedAt = yield* nowIso;
1093
- yield* projectSetupScriptRunner
1109
+ yield* track(worktreeSetupTracker.stageStatus(threadId, "setup-script", "running"));
1110
+ const setupResult = yield* projectSetupScriptRunner
1111
.runForThread({
1095
- threadId: command.threadId,
1112
+ threadId,
1113
...(targetProjectId ? { projectId: targetProjectId } : {}),
1114
...(targetProjectCwd ? { projectCwd: targetProjectCwd } : {}),
1115
worktreePath,
1116
+ ...(tracked
1117
+ ? {
1118
+ observeCompletion: {
1119
+ onOutputLine: (line) =>
1120
+ worktreeSetupTracker.appendTail(threadId, "setup-script", line),
1121
+ },
1122
+ }
1123
+ : {}),
1124
})
1125
.pipe(
1126
Effect.matchEffect({
1129
error,
1130
requestedAt,
1131
worktreePath,
1107
- }),
1132
+ }).pipe(
1133
+ Effect.andThen(
1134
+ track(
1135
+ worktreeSetupTracker.stageStatus(
1136
+ threadId,
1137
+ "setup-script",
1138
+ "failed",
1139
+ "failed to start",
1140
+ ),
1141
+ ),
1142
+ ),
1143
+ Effect.as(null),
1144
+ ),
1145
onSuccess: (setupResult) => {
1146
if (setupResult.status !== "started") {
1110
- return Effect.void;
1147
+ return track(
1148
+ worktreeSetupTracker.stageStatus(
1149
+ threadId,
1150
+ "setup-script",
1151
+ "skipped",
1152
+ "no setup script",
1153
+ ),
1154
+ ).pipe(Effect.as(null));
1155
}
1156
+ setupTerminalId = setupResult.terminalId;
1157
return recordSetupScriptStarted({
1158
requestedAt,
1159
worktreePath,
1160
scriptId: setupResult.scriptId,
1161
scriptName: setupResult.scriptName,
1162
terminalId: setupResult.terminalId,
1118
- });
1163
+ }).pipe(
1164
+ Effect.andThen(
1165
+ track(
1166
+ worktreeSetupTracker.update(threadId, (snapshot) => ({
1167
+ ...snapshot,
1168
+ setupScript: {
1169
+ name: setupResult.scriptName,
1170
+ command: setupResult.scriptCommand,
1171
+ terminalId: setupResult.terminalId,
1172
+ },
1173
+ })),
1174
+ ),
1175
+ ),
1176
+ Effect.as(setupResult),
1177
+ );
1178
},
1179
}),
1180
);
1181
+ if (!tracked || !setupResult?.completion) {
1182
+ return;
1183
+ }
1184
+ // The setup script is best effort, like the untracked path: a
1185
+ // failed install must not throw away the worktree the user just
1186
+ // waited for. The card keeps the failed stage and its terminal.
1187
+ const completion = yield* setupResult.completion;
1188
+ if (completion.exitCode === 0) {
1189
+ yield* worktreeSetupTracker.stageStatus(threadId, "setup-script", "done");
1190
+ return;
1191
+ }
1192
+ const detail =
1193
+ completion.exitCode === null
1194
+ ? "terminal closed before the script finished"
1195
+ : `exit ${completion.exitCode}`;
1196
+ yield* worktreeSetupTracker.stageStatus(threadId, "setup-script", "failed", detail);
1197
});
1198
1199
const bootstrapProgram = Effect.gen(function* () {
1213
remoteName: "origin",
1214
}));
1215
if (startFromOrigin) {
1216
+ yield* track(worktreeSetupTracker.stageStatus(threadId, "fetch", "running"));
1217
yield* gitWorkflow.fetchRemote({
1218
cwd: prepareWorktree.projectCwd,
1219
remoteName: "origin",
1230
fallbackRemoteName: "origin",
1231
});
1232
worktreeBaseRef = resolvedRemoteBase.commitSha;
1233
+ yield* track(
1234
+ worktreeSetupTracker.stageStatus(
1235
+ threadId,
1236
+ "fetch",
1237
+ "done",
1238
+ `origin/${prepareWorktree.baseBranch} at ${resolvedRemoteBase.commitSha.slice(0, 7)}`,
1239
+ ),
1240
+ );
1241
+ } else {
1242
+ yield* track(
1243
+ worktreeSetupTracker.stageStatus(
1244
+ threadId,
1245
+ "fetch",
1246
+ "warning",
1247
+ `origin/${prepareWorktree.baseBranch} not found, using local branch`,
1248
+ ),
1249
+ );
1250
}
1251
+ } else {
1252
+ yield* track(worktreeSetupTracker.stageStatus(threadId, "fetch", "skipped"));
1253
}
1254
1255
const resolvedWorktreeBaseRef = worktreeBaseRef ?? prepareWorktree.baseBranch;
1258
refName: resolvedWorktreeBaseRef,
1259
});
1260
worktreeBaseRef = resolvedWorktreeBaseRef;
1261
+ yield* track(
1262
+ worktreeSetupTracker.update(threadId, (snapshot) => ({
1263
+ ...snapshot,
1264
+ baseRef: resolvedWorktreeBaseRef,
1265
+ })),
1266
+ );
1267
+ }
1268
+
1269
+ if (prepareWorktree && !shouldPrepareWorktree) {
1270
+ // Not a git repo, or the base has no commit: the thread runs in
1271
+ // the project checkout instead. The card says so and moves on.
1272
+ yield* track(
1273
+ worktreeSetupTracker.update(threadId, (snapshot) => ({
1274
+ ...snapshot,
1275
+ stages: snapshot.stages.map((stage) =>
1276
+ stage.id === "fetch" || stage.id === "checkout" || stage.id === "submodules"
1277
+ ? { ...stage, status: "skipped", detail: "using project checkout" }
1278
+ : stage,
1279
+ ),
1280
+ })),
1281
+ );
1282
}
1283
1284
if (bootstrap?.createThread) {
1304
}
1305
1306
if (prepareWorktree && shouldPrepareWorktree && worktreeBaseRef) {
1191
- const worktree = yield* gitWorkflow.createWorktree({
1192
- cwd: prepareWorktree.projectCwd,
1193
- refName: worktreeBaseRef,
1194
- newRefName: prepareWorktree.branch,
1195
- baseRefName: prepareWorktree.baseBranch,
1196
- path: null,
1197
- });
1307
+ yield* worktreeSetupTracker.stageStatus(threadId, "checkout", "running");
1308
+ let checkoutTotal: number | null = null;
1309
+ const worktree = yield* gitWorkflow.createWorktree(
1310
+ {
1311
+ cwd: prepareWorktree.projectCwd,
1312
+ refName: worktreeBaseRef,
1313
+ newRefName: prepareWorktree.branch,
1314
+ baseRefName: prepareWorktree.baseBranch,
1315
+ path: null,
1316
+ },
1317
+ {
1318
+ progress: {
1319
+ // Git has registered the directory at this point, so a
1320
+ // cancel during the submodule step can still remove it.
1321
+ onWorktreeClaimed: (path) =>
1322
+ Effect.sync(() => {
1323
+ targetWorktreePath = path;
1324
+ }),
1325
+ onCheckoutProgress: ({ percent, completed, total }) => {
1326
+ checkoutTotal = total;
1327
+ return worktreeSetupTracker.stage(threadId, "checkout", {
1328
+ percent,
1329
+ detail: `${completed.toLocaleString("en-US")} / ${total.toLocaleString("en-US")} files`,
1330
+ });
1331
+ },
1332
+ onSubmodulesStarted: () =>
1333
+ worktreeSetupTracker
1334
+ .stageStatus(
1335
+ threadId,
1336
+ "checkout",
1337
+ "done",
1338
+ checkoutTotal === null
1339
+ ? null
1340
+ : `${checkoutTotal.toLocaleString("en-US")} files`,
1341
+ )
1342
+ .pipe(
1343
+ Effect.andThen(
1344
+ worktreeSetupTracker.stageStatus(threadId, "submodules", "running"),
1345
+ ),
1346
+ ),
1347
+ onSubmoduleLine: (line) => {
1348
+ const submodulePath = /Submodule path '([^']+)'/.exec(line)?.[1];
1349
+ return submodulePath === undefined
1350
+ ? Effect.void
1351
+ : worktreeSetupTracker.stage(threadId, "submodules", {
1352
+ detail: submodulePath,
1353
+ });
1354
+ },
1355
+ onSubmodulesFinished: ({ ok, detail }) =>
1356
+ worktreeSetupTracker.stageStatus(
1357
+ threadId,
1358
+ "submodules",
1359
+ ok ? "done" : "warning",
1360
+ ok ? undefined : (detail ?? "submodule checkout failed"),
1361
+ ),
1362
+ },
1363
+ },
1364
+ );
1365
+ const checkoutEndedAt = yield* nowIso;
1366
+ yield* worktreeSetupTracker.update(threadId, (snapshot) => ({
1367
+ ...snapshot,
1368
+ worktreePath: worktree.worktree.path,
1369
+ stages: snapshot.stages.map((stage) => {
1370
+ if (stage.id === "checkout" && stage.status === "running") {
1371
+ return {
1372
+ ...stage,
1373
+ status: "done",
1374
+ percent: 100,
1375
+ endedAt: checkoutEndedAt,
1376
+ detail:
1377
+ checkoutTotal === null
1378
+ ? stage.detail
1379
+ : `${checkoutTotal.toLocaleString("en-US")} files`,
1380
+ };
1381
+ }
1382
+ if (stage.id === "submodules" && stage.status === "pending") {
1383
+ return { ...stage, status: "skipped", detail: "none" };
1384
+ }
1385
+ return stage;
1386
+ }),
1387
+ }));
1388
targetWorktreePath = worktree.worktree.path;
1389
yield* dispatchFromClient({
1390
type: "thread.meta.update",
1391
commandId: yield* serverCommandId("bootstrap-thread-meta-update"),
1202
- threadId: command.threadId,
1392
+ threadId,
1393
branch: worktree.worktree.refName,
1394
worktreePath: targetWorktreePath,
1395
});
1398
1399
yield* runSetupProgram();
1400
1211
- return yield* dispatchFromClient(finalTurnStartCommand);
1401
+ yield* track(worktreeSetupTracker.stageStatus(threadId, "agent", "running"));
1402
+ // Past this point a cancel would roll back a thread whose turn has
1403
+ // started. Drop the cancel handle and make the handoff atomic.
1404
+ yield* track(worktreeSetupTracker.markUncancellable(threadId));
1405
+ const started = yield* Effect.uninterruptible(
1406
+ dispatchFromClient(finalTurnStartCommand),
1407
+ );
1408
+ yield* track(
1409
+ worktreeSetupTracker
1410
+ .stageStatus(threadId, "agent", "done")
1411
+ .pipe(Effect.andThen(worktreeSetupTracker.finish(threadId, "done"))),
1412
+ );
1413
+ return started;
1414
});
1415
1214
- return yield* bootstrapProgram.pipe(
1416
+ const runBootstrap = tracked
1417
+ ? Effect.gen(function* () {
1418
+ const fiber = yield* Effect.forkChild(bootstrapProgram);
1419
+ yield* worktreeSetupTracker.begin({
1420
+ threadId,
1421
+ branch: bootstrap?.prepareWorktree?.branch ?? null,
1422
+ baseRef: bootstrap?.prepareWorktree?.baseBranch ?? null,
1423
+ stages: ["fetch", "checkout", "submodules", "setup-script", "agent"],
1424
+ fiber,
1425
+ });
1426
+ return yield* Fiber.join(fiber);
1427
+ })
1428
+ : bootstrapProgram;
1429
+
1430
+ const cleanupAndFail = (
1431
+ cause: Cause.Cause<unknown>,
1432
+ dispatchError: OrchestrationDispatchCommandError,
1433
+ ) =>
1434
+ Effect.uninterruptible(cleanupCreatedThread()).pipe(
1435
+ Effect.matchCauseEffect({
1436
+ onFailure: (cleanupCause) =>
1437
+ Effect.logWarning("bootstrap thread cleanup failed", {
1438
+ threadId,
1439
+ detail: Cause.pretty(cleanupCause),
1440
+ }).pipe(Effect.flatMap(() => Effect.fail(dispatchError))),
1441
+ onSuccess: (threadDeleted) =>
1442
+ Effect.fail(
1443
+ threadDeleted
1444
+ ? new OrchestrationDispatchCommandError({
1445
+ message: dispatchError.message,
1446
+ ...(dispatchError.cause !== undefined
1447
+ ? { cause: dispatchError.cause }
1448
+ : {}),
1449
+ bootstrapThreadDisposition: "deleted",
1450
+ })
1451
+ : dispatchError,
1452
+ ),
1453
+ }),
1454
+ );
1455
+
1456
+ return yield* runBootstrap.pipe(
1457
Effect.catchCause((cause) => {
1458
const dispatchError = toBootstrapDispatchCommandCauseError(cause);
1459
if (Cause.hasInterruptsOnly(cause)) {
1218
- return Effect.fail(dispatchError);
1460
+ // A user cancel interrupts the forked bootstrap fiber. The
1461
+ // created thread is rolled back like any other failure so the
1462
+ // draft returns to the composer. The setup terminal is closed
1463
+ // first so a still-running script cannot hold files open in
1464
+ // the worktree while git removes it. Closing kills the
1465
+ // process asynchronously, so the removal retries briefly.
1466
+ const closeSetupTerminal = setupTerminalId
1467
+ ? terminalManager.close({
1468
+ threadId,
1469
+ terminalId: setupTerminalId,
1470
+ deleteHistory: true,
1471
+ })
1472
+ : Effect.void;
1473
+ const removeCreatedWorktree =
1474
+ tracked && targetWorktreePath && bootstrap?.prepareWorktree
1475
+ ? closeSetupTerminal.pipe(
1476
+ Effect.ignoreCause({ log: true }),
1477
+ Effect.andThen(
1478
+ gitWorkflow
1479
+ .removeWorktree({
1480
+ cwd: bootstrap.prepareWorktree.projectCwd,
1481
+ path: targetWorktreePath,
1482
+ force: true,
1483
+ })
1484
+ .pipe(
1485
+ Effect.retry({ times: 4, schedule: Schedule.spaced("500 millis") }),
1486
+ ),
1487
+ ),
1488
+ Effect.ignoreCause({ log: true }),
1489
+ Effect.uninterruptible,
1490
+ )
1491
+ : Effect.void;
1492
+ return track(worktreeSetupTracker.finish(threadId, "cancelled")).pipe(
1493
+ Effect.andThen(removeCreatedWorktree),
1494
+ Effect.andThen(
1495
+ tracked
1496
+ ? cleanupAndFail(
1497
+ cause,
1498
+ new OrchestrationDispatchCommandError({
1499
+ message: "Worktree setup cancelled.",
1500
+ }),
1501
+ )
1502
+ : Effect.fail(dispatchError),
1503
+ ),
1504
+ );
1505
}
1220
- return Effect.uninterruptible(cleanupCreatedThread()).pipe(
1221
- Effect.matchCauseEffect({
1222
- onFailure: (cleanupCause) =>
1223
- Effect.logWarning("bootstrap thread cleanup failed", {
1224
- threadId: command.threadId,
1225
- detail: Cause.pretty(cleanupCause),
1226
- }).pipe(Effect.flatMap(() => Effect.fail(dispatchError))),
1227
- onSuccess: (threadDeleted) =>
1228
- Effect.fail(
1229
- threadDeleted
1230
- ? new OrchestrationDispatchCommandError({
1231
- message: dispatchError.message,
1232
- ...(dispatchError.cause !== undefined
1233
- ? { cause: dispatchError.cause }
1234
- : {}),
1235
- bootstrapThreadDisposition: "deleted",
1236
- })
1237
- : dispatchError,
1238
- ),
1239
- }),
1240
- );
1506
+ return track(
1507
+ worktreeSetupTracker.finish(threadId, "failed", dispatchError.message),
1508
+ ).pipe(Effect.andThen(cleanupAndFail(cause, dispatchError)));
1509
}),
1510
);
1511
});
2882
"rpc.aggregate": "vcs",
2883
},
2884
),
2885
+ [WS_METHODS.subscribeWorktreeSetup]: (input) =>
2886
+ observeRpcStream(
2887
+ WS_METHODS.subscribeWorktreeSetup,
2888
+ worktreeSetupTracker.stream(input.threadId),
2889
+ { "rpc.aggregate": "vcs" },
2890
+ ),
2891
+ [WS_METHODS.worktreeSetupCancel]: (input) =>
2892
+ observeRpcEffect(
2893
+ WS_METHODS.worktreeSetupCancel,
2894
+ worktreeSetupTracker
2895
+ .cancel(input.threadId)
2896
+ .pipe(Effect.map((cancelled) => ({ cancelled }))),
2897
+ { "rpc.aggregate": "vcs" },
2898
+ ),
2899
[WS_METHODS.vcsRefreshStatus]: (input) =>
2900
observeRpcEffect(
2901
WS_METHODS.vcsRefreshStatus,