Skip to content
TypeScript

feat(server): persist the worktree setup send and progress on the thread (#11852)

Julius Marminge2c19283afed1
diff --git a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx
index f22540e768d..0942647c7a7 100644
--- a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx
+++ b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx
@@ -782,9 +782,26 @@ function ThreadRouteContent(
}),
);
}, [navigation, routeThreadIdentity, selectedThreadCreation, selectedThreadProject]);
+ // A worktree bootstrap records a running setup on the thread before its
+ // turn, so a thread opened from another device (or after a restart) shows
+ // the same preparing state the sending client does. A starting session is
+ // not enough on its own: an ordinary first turn projects one too.
+ const awaitingBootstrapTurn = useMemo(
+ () =>
+ selectedThreadDetail !== null &&
+ selectedThreadDetail.latestTurn === null &&
+ selectedThreadDetail.activities.some(
+ (activity) =>
+ activity.kind === "worktree-setup" &&
+ typeof activity.payload === "object" &&
+ activity.payload !== null &&
+ (activity.payload as { phase?: unknown }).phase === "running",
+ ),
+ [selectedThreadDetail],
+ );
const creationState = ((): ThreadDetailScreenProps["creationState"] => {
if (selectedThreadCreation === null) {
- return null;
+ return awaitingBootstrapTurn ? { kind: "preparing", preparingWorktree: true } : null;
}
if (selectedThreadCreation.outcome?.kind === "failed") {
return {
diff --git a/apps/mobile/src/lib/threadActivity.ts b/apps/mobile/src/lib/threadActivity.ts
index f1550042eae..f284812dc8a 100644
--- a/apps/mobile/src/lib/threadActivity.ts
+++ b/apps/mobile/src/lib/threadActivity.ts
@@ -411,6 +411,7 @@ function deriveWorkLogEntries(
const ordered = Arr.sort(activities, activityOrder);
const entries: DerivedWorkLogEntry[] = [];
for (const activity of foldUserInputActivities(ordered)) {
+ // Mobile has no setup card, so a failed setup surfaces as an error row.
if (activity.tone !== "error" && isWorktreeSetupActivity(activity.kind)) continue;
if (activity.kind === "tool.started") continue;
// Like web: an agent's task.started row anchors its batch. It has a fixed
diff --git a/apps/server/src/checkpointing/CheckpointDiffQuery.test.ts b/apps/server/src/checkpointing/CheckpointDiffQuery.test.ts
index 45bc2778f0e..82fac97f8c8 100644
--- a/apps/server/src/checkpointing/CheckpointDiffQuery.test.ts
+++ b/apps/server/src/checkpointing/CheckpointDiffQuery.test.ts
@@ -76,6 +76,7 @@ describe("CheckpointDiffQuery.layer", () => {
Layer.provideMerge(
Layer.succeed(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
getUserInputActivity: () => Effect.die("unused"),
+ listActivitiesByKind: () => Effect.die("unused"),
getCommandReadModel: () =>
Effect.die("CheckpointDiffQuery should not request the command read model"),
getSnapshot: () =>
@@ -191,6 +192,7 @@ describe("CheckpointDiffQuery.layer", () => {
Layer.provideMerge(
Layer.succeed(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
getUserInputActivity: () => Effect.die("unused"),
+ listActivitiesByKind: () => Effect.die("unused"),
getCommandReadModel: () =>
Effect.die("CheckpointDiffQuery should not request the command read model"),
getSnapshot: () =>
@@ -281,6 +283,7 @@ describe("CheckpointDiffQuery.layer", () => {
Layer.provideMerge(
Layer.succeed(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
getUserInputActivity: () => Effect.die("unused"),
+ listActivitiesByKind: () => Effect.die("unused"),
getCommandReadModel: () =>
Effect.die("CheckpointDiffQuery should not request the command read model"),
getSnapshot: () =>
@@ -356,6 +359,7 @@ describe("CheckpointDiffQuery.layer", () => {
Layer.provideMerge(
Layer.succeed(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
getUserInputActivity: () => Effect.die("unused"),
+ listActivitiesByKind: () => Effect.die("unused"),
getCommandReadModel: () =>
Effect.die("CheckpointDiffQuery should not request the command read model"),
getSnapshot: () =>
@@ -416,6 +420,7 @@ describe("CheckpointDiffQuery.layer", () => {
Layer.provideMerge(
Layer.succeed(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
getUserInputActivity: () => Effect.die("unused"),
+ listActivitiesByKind: () => Effect.die("unused"),
getCommandReadModel: () =>
Effect.die("CheckpointDiffQuery should not request the command read model"),
getSnapshot: () =>
diff --git a/apps/server/src/orchestration/Layers/CheckpointReactor.ts b/apps/server/src/orchestration/Layers/CheckpointReactor.ts
index 9cfcc2e7491..38868430ca0 100644
--- a/apps/server/src/orchestration/Layers/CheckpointReactor.ts
+++ b/apps/server/src/orchestration/Layers/CheckpointReactor.ts
@@ -630,8 +630,12 @@ const make = Effect.gen(function* () {
>,
) {
if (event.type === "thread.message-sent") {
+ // A bootstrap message lands before the worktree exists; its baseline
+ // would snapshot the project checkout. The turn-start event that
+ // follows captures it against the right cwd.
if (
event.metadata.historyImport === true ||
+ event.metadata.deferredTurn === true ||
event.payload.role !== "user" ||
event.payload.streaming ||
event.payload.turnId !== null
diff --git a/apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts b/apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts
index 7ea1d588acf..4a2e99f3ebc 100644
--- a/apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts
+++ b/apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts
@@ -420,6 +420,7 @@ describe("OrchestrationEngine", () => {
Layer.provide(
Layer.succeed(ProjectionSnapshotQuery, {
getUserInputActivity: () => Effect.die("unused"),
+ listActivitiesByKind: () => Effect.die("unused"),
getCommandReadModel: () => Effect.succeed(commandReadModel),
getSnapshot: () =>
Effect.sync(() => {
diff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts
index 2b113adec7a..6183dbc6616 100644
--- a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts
+++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts
@@ -3466,3 +3466,51 @@ it.effect("omits foreign-host PRs from legacy snapshots while preserving native
}
}).pipe(Effect.provide(layer));
});
+
+projectionSnapshotLayer("ProjectionSnapshotQuery activities by kind", (it) => {
+ it.effect("lists one kind across active threads only, without hydrating the threads", () =>
+ Effect.gen(function* () {
+ const query = yield* ProjectionSnapshotQuery;
+ const sql = yield* SqlClient.SqlClient;
+ const timestamp = "2026-03-02T00:00:00.000Z";
+ yield* sql`
+ INSERT INTO projection_projects (
+ project_id, title, workspace_root, scripts_json, created_at, updated_at
+ ) VALUES ('project-kinds', 'Project', '/tmp/project-kinds', '[]', ${timestamp}, ${timestamp})
+ `;
+ yield* sql`
+ INSERT INTO projection_threads (
+ thread_id, project_id, title, model_selection_json, runtime_mode, interaction_mode,
+ created_at, updated_at, deleted_at
+ ) VALUES
+ ('thread-live', 'project-kinds', 'Live', '{"instanceId":"codex","model":"gpt-5"}',
+ 'full-access', 'default', ${timestamp}, ${timestamp}, NULL),
+ ('thread-gone', 'project-kinds', 'Gone', '{"instanceId":"codex","model":"gpt-5"}',
+ 'full-access', 'default', ${timestamp}, ${timestamp}, ${timestamp}),
+ ('thread-shelved', 'project-kinds', 'Shelved', '{"instanceId":"codex","model":"gpt-5"}',
+ 'full-access', 'default', ${timestamp}, ${timestamp}, NULL)
+ `;
+ yield* sql`UPDATE projection_threads SET archived_at = ${timestamp} WHERE thread_id = 'thread-shelved'`;
+ yield* sql`
+ INSERT INTO projection_thread_activities (
+ activity_id, thread_id, turn_id, tone, kind, summary, payload_json, created_at
+ ) VALUES
+ ('setup-live', 'thread-live', NULL, 'info', 'worktree-setup', 'Setting up',
+ '{"phase":"running"}', ${timestamp}),
+ ('other-live', 'thread-live', NULL, 'info', 'tool.completed', 'Other',
+ '{}', ${timestamp}),
+ ('setup-gone', 'thread-gone', NULL, 'info', 'worktree-setup', 'Setting up',
+ '{"phase":"running"}', ${timestamp}),
+ ('setup-shelved', 'thread-shelved', NULL, 'info', 'worktree-setup', 'Setting up',
+ '{"phase":"running"}', ${timestamp})
+ `;
+
+ const setups = yield* query.listActivitiesByKind("worktree-setup");
+ assert.deepEqual(
+ setups.map((activity) => [activity.id, activity.kind, activity.payload]),
+ [["setup-live", "worktree-setup", { phase: "running" }]],
+ );
+ assert.deepEqual(yield* query.listActivitiesByKind("nope"), []);
+ }),
+ );
+});
diff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts
index d5487e6ffab..edfee6fbdd9 100644
--- a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts
+++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts
@@ -1450,6 +1450,40 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
),
);
+ const listActivityRowsByKind = SqlSchema.findAll({
+ Request: Schema.Struct({ kind: Schema.String }),
+ Result: ProjectionThreadActivityDbRowSchema,
+ execute: ({ kind }) => sql`
+ SELECT
+ a.activity_id AS "activityId",
+ a.thread_id AS "threadId",
+ a.turn_id AS "turnId",
+ a.tone,
+ a.kind,
+ a.summary,
+ a.payload_json AS "payload",
+ a.sequence,
+ a.created_at AS "createdAt"
+ FROM projection_thread_activities a
+ JOIN projection_threads t ON t.thread_id = a.thread_id
+ WHERE a.kind = ${kind}
+ AND t.deleted_at IS NULL
+ AND t.archived_at IS NULL
+ ORDER BY a.created_at ASC, a.activity_id ASC
+ `,
+ });
+
+ const listActivitiesByKind: ProjectionSnapshotQueryShape["listActivitiesByKind"] = (kind) =>
+ listActivityRowsByKind({ kind }).pipe(
+ Effect.map((rows) => rows.map(mapThreadActivityRow)),
+ Effect.mapError(
+ toPersistenceSqlOrDecodeError(
+ "ProjectionSnapshotQuery.listActivitiesByKind:query",
+ "ProjectionSnapshotQuery.listActivitiesByKind:decodeRow",
+ ),
+ ),
+ );
+
const listThreadActivityIdsByThread = SqlSchema.findAll({
Request: ThreadIdLookupInput,
Result: ProjectionThreadActivityIdRowSchema,
@@ -3692,6 +3726,7 @@ pending_approval_requests AS (
return {
getCommandReadModel,
getUserInputActivity,
+ listActivitiesByKind,
getSnapshot,
getShellSnapshot,
getArchivedShellSnapshot,
diff --git a/apps/server/src/orchestration/Services/ProjectionSnapshotQuery.ts b/apps/server/src/orchestration/Services/ProjectionSnapshotQuery.ts
index a485848ec44..46f269a0cf4 100644
--- a/apps/server/src/orchestration/Services/ProjectionSnapshotQuery.ts
+++ b/apps/server/src/orchestration/Services/ProjectionSnapshotQuery.ts
@@ -83,6 +83,15 @@ export interface ProjectionSnapshotQueryShape {
readonly requestId: ApprovalRequestId;
}) => Effect.Effect<Option.Option<OrchestrationThreadActivity>, ProjectionRepositoryError>;
+ /**
+ * Read every activity of one kind across active (not deleted, not archived)
+ * threads, without hydrating the threads. Used at startup to find state a
+ * crashed process left behind.
+ */
+ readonly listActivitiesByKind: (
+ kind: string,
+ ) => Effect.Effect<ReadonlyArray<OrchestrationThreadActivity>, ProjectionRepositoryError>;
+
/**
* Read the lightweight command snapshot used to bootstrap the in-memory
* orchestration engine without hydrating message/activity/checkpoint bodies.
diff --git a/apps/server/src/orchestration/decider.ts b/apps/server/src/orchestration/decider.ts
index f8809ccc27e..86be0610f80 100644
--- a/apps/server/src/orchestration/decider.ts
+++ b/apps/server/src/orchestration/decider.ts
@@ -1390,27 +1390,39 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
detail: `Proposed plan '${sourceProposedPlan?.planId}' belongs to thread '${sourceThread.id}' in a different project.`,
});
}
- const userMessageEvent: Omit<OrchestrationEvent, "sequence"> = {
- ...(yield* withEventBase({
- aggregateKind: "thread",
- aggregateId: command.threadId,
- occurredAt: command.createdAt,
- commandId: command.commandId,
- })),
- type: "thread.message-sent",
- payload: {
- threadId: command.threadId,
- messageId: command.message.messageId,
- role: "user",
- text: command.message.text,
- attachments: command.message.attachments,
- ...(command.message.context !== undefined ? { context: command.message.context } : {}),
- turnId: null,
- streaming: false,
- createdAt: command.createdAt,
- updatedAt: command.createdAt,
- },
- };
+ // A worktree bootstrap persists the message ahead of the turn with
+ // `thread.message.user.append`; the turn then only references it.
+ const persistedUserMessage = targetThread.messages.find(
+ (message) =>
+ message.id === command.message.messageId &&
+ message.role === "user" &&
+ message.turnId === null,
+ );
+ const userMessageEvent: Omit<OrchestrationEvent, "sequence"> | null = persistedUserMessage
+ ? null
+ : {
+ ...(yield* withEventBase({
+ aggregateKind: "thread",
+ aggregateId: command.threadId,
+ occurredAt: command.createdAt,
+ commandId: command.commandId,
+ })),
+ type: "thread.message-sent",
+ payload: {
+ threadId: command.threadId,
+ messageId: command.message.messageId,
+ role: "user",
+ text: command.message.text,
+ attachments: command.message.attachments,
+ ...(command.message.context !== undefined
+ ? { context: command.message.context }
+ : {}),
+ turnId: null,
+ streaming: false,
+ createdAt: command.createdAt,
+ updatedAt: command.createdAt,
+ },
+ };
const turnStartRequestedEvent: Omit<OrchestrationEvent, "sequence"> = {
...(yield* withEventBase({
aggregateKind: "thread",
@@ -1418,7 +1430,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
occurredAt: command.createdAt,
commandId: command.commandId,
})),
- causationEventId: userMessageEvent.eventId,
+ ...(userMessageEvent ? { causationEventId: userMessageEvent.eventId } : {}),
type: "thread.turn-start-requested",
payload: {
threadId: command.threadId,
@@ -1471,7 +1483,53 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
},
});
}
- return [...lifecycleResetEvents, userMessageEvent, turnStartRequestedEvent];
+ return [
+ ...lifecycleResetEvents,
+ ...(userMessageEvent ? [userMessageEvent] : []),
+ turnStartRequestedEvent,
+ ];
+ }
+
+ case "thread.message.user.append": {
+ if (isImportedAgentSessionMessageId(command.message.messageId)) {
+ return yield* new OrchestrationCommandInvariantError({
+ commandType: command.type,
+ detail: `Message id '${command.message.messageId}' uses the reserved imported-session namespace.`,
+ });
+ }
+ const thread = yield* requireThread({
+ readModel,
+ command,
+ threadId: command.threadId,
+ });
+ if (thread.messages.some((message) => message.id === command.message.messageId)) {
+ return yield* new OrchestrationCommandInvariantError({
+ commandType: command.type,
+ detail: `Message '${command.message.messageId}' already exists on thread '${command.threadId}'.`,
+ });
+ }
+ return {
+ ...(yield* withEventBase({
+ aggregateKind: "thread",
+ aggregateId: command.threadId,
+ occurredAt: command.createdAt,
+ commandId: command.commandId,
+ metadata: { deferredTurn: true },
+ })),
+ type: "thread.message-sent",
+ payload: {
+ threadId: command.threadId,
+ messageId: command.message.messageId,
+ role: "user",
+ text: command.message.text,
+ attachments: command.message.attachments,
+ ...(command.message.context !== undefined ? { context: command.message.context } : {}),
+ turnId: null,
+ streaming: false,
+ createdAt: command.createdAt,
+ updatedAt: command.createdAt,
+ },
+ };
}
case "thread.turn.interrupt": {
diff --git a/apps/server/src/orchestration/decider.userMessageAppend.test.ts b/apps/server/src/orchestration/decider.userMessageAppend.test.ts
new file mode 100644
index 00000000000..4ebbf30e120
--- /dev/null
+++ b/apps/server/src/orchestration/decider.userMessageAppend.test.ts
@@ -0,0 +1,137 @@
+import * as NodeServices from "@effect/platform-node/NodeServices";
+import { expect, it } from "@effect/vitest";
+import {
+ CommandId,
+ EventId,
+ MessageId,
+ ProjectId,
+ ProviderInstanceId,
+ ThreadId,
+} from "@t3tools/contracts";
+import * as Effect from "effect/Effect";
+
+import { decideOrchestrationCommand } from "./decider.ts";
+import { createEmptyReadModel, projectEvent } from "./projector.ts";
+
+const createdAt = "2026-08-24T10:00:00.000Z";
+const projectId = ProjectId.make("project-1");
+const threadId = ThreadId.make("thread-bootstrap");
+const messageId = MessageId.make("message-bootstrap");
+
+const readModelWithThread = Effect.gen(function* () {
+ const withProject = yield* projectEvent(createEmptyReadModel(createdAt), {
+ sequence: 1,
+ eventId: EventId.make("event-project-created"),
+ aggregateKind: "project",
+ aggregateId: projectId,
+ type: "project.created",
+ occurredAt: createdAt,
+ commandId: CommandId.make("command-project-created"),
+ causationEventId: null,
+ correlationId: CommandId.make("command-project-created"),
+ metadata: {},
+ payload: {
+ projectId,
+ title: "Project",
+ workspaceRoot: "/tmp/project",
+ defaultModelSelection: null,
+ scripts: [],
+ createdAt,
+ updatedAt: createdAt,
+ },
+ });
+ return yield* projectEvent(withProject, {
+ sequence: 2,
+ eventId: EventId.make("event-thread-created"),
+ aggregateKind: "thread",
+ aggregateId: threadId,
+ type: "thread.created",
+ occurredAt: createdAt,
+ commandId: CommandId.make("command-thread-created"),
+ causationEventId: null,
+ correlationId: CommandId.make("command-thread-created"),
+ metadata: {},
+ payload: {
+ threadId,
+ projectId,
+ title: "Bootstrap thread",
+ modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" },
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ branch: null,
+ worktreePath: null,
+ createdAt,
+ updatedAt: createdAt,
+ },
+ });
+});
+
+const appendCommand = {
+ type: "thread.message.user.append" as const,
+ commandId: CommandId.make("command-append"),
+ threadId,
+ message: { messageId, text: "Build it", attachments: [] },
+ createdAt,
+};
+
+const turnStartCommand = {
+ type: "thread.turn.start" as const,
+ commandId: CommandId.make("command-turn-start"),
+ threadId,
+ message: { messageId, role: "user" as const, text: "Build it", attachments: [] },
+ runtimeMode: "full-access" as const,
+ interactionMode: "default" as const,
+ createdAt,
+};
+
+it.layer(NodeServices.layer)("thread.message.user.append", (it) => {
+ it.effect("persists a user message without a turn, tagged as deferred", () =>
+ Effect.gen(function* () {
+ const readModel = yield* readModelWithThread;
+ const planned = yield* decideOrchestrationCommand({ command: appendCommand, readModel });
+ const events = Array.isArray(planned) ? planned : [planned];
+ expect(events.map((event) => event.type)).toEqual(["thread.message-sent"]);
+ expect(events[0]?.metadata.deferredTurn).toBe(true);
+ expect(events[0]?.payload).toMatchObject({ messageId, role: "user", turnId: null });
+ }),
+ );
+
+ it.effect("rejects a message id that already exists on the thread", () =>
+ Effect.gen(function* () {
+ const readModel = yield* readModelWithThread;
+ const first = yield* decideOrchestrationCommand({ command: appendCommand, readModel });
+ const firstEvent = Array.isArray(first) ? first[0]! : first;
+ const withMessage = yield* projectEvent(readModel, { ...firstEvent, sequence: 3 });
+ const error = yield* Effect.flip(
+ decideOrchestrationCommand({ command: appendCommand, readModel: withMessage }),
+ );
+ expect(error._tag).toBe("OrchestrationCommandInvariantError");
+ expect(error.message).toContain("already exists");
+ }),
+ );
+
+ it.effect("lets the following turn start reference the message instead of re-sending it", () =>
+ Effect.gen(function* () {
+ const readModel = yield* readModelWithThread;
+ const appended = yield* decideOrchestrationCommand({ command: appendCommand, readModel });
+ const appendedEvent = Array.isArray(appended) ? appended[0]! : appended;
+ const withMessage = yield* projectEvent(readModel, { ...appendedEvent, sequence: 3 });
+
+ const planned = yield* decideOrchestrationCommand({
+ command: turnStartCommand,
+ readModel: withMessage,
+ });
+ const events = Array.isArray(planned) ? planned : [planned];
+ expect(events.map((event) => event.type)).toEqual(["thread.turn-start-requested"]);
+ expect(events[0]?.payload).toMatchObject({ messageId });
+
+ // Without the append the turn start still carries the message itself.
+ const direct = yield* decideOrchestrationCommand({ command: turnStartCommand, readModel });
+ const directEvents = Array.isArray(direct) ? direct : [direct];
+ expect(directEvents.map((event) => event.type)).toEqual([
+ "thread.message-sent",
+ "thread.turn-start-requested",
+ ]);
+ }),
+ );
+});
diff --git a/apps/server/src/orchestration/projector.test.ts b/apps/server/src/orchestration/projector.test.ts
index 39aaacd8739..c4e1996f1dd 100644
--- a/apps/server/src/orchestration/projector.test.ts
+++ b/apps/server/src/orchestration/projector.test.ts
@@ -1170,4 +1170,70 @@ describe("orchestration projector", () => {
expect(thread?.checkpoints[0]?.turnId).toBe("turn-100");
expect(thread?.checkpoints.at(-1)?.turnId).toBe("turn-599");
});
+
+ effectIt.effect("keeps the worktree setup record past the activity retention cap", () =>
+ Effect.gen(function* () {
+ const createdAt = "2026-03-01T10:00:00.000Z";
+ const threadId = "thread-setup-retained";
+ const afterCreate = yield* projectEvent(
+ createEmptyReadModel(createdAt),
+ makeEvent({
+ sequence: 1,
+ type: "thread.created",
+ aggregateKind: "thread",
+ aggregateId: threadId,
+ occurredAt: createdAt,
+ commandId: "cmd-create-setup-retained",
+ payload: {
+ threadId,
+ projectId: "project-1",
+ title: "setup retained",
+ modelSelection: {
+ provider: ProviderDriverKind.make("codex"),
+ model: "gpt-5-codex",
+ },
+ runtimeMode: "full-access",
+ branch: null,
+ worktreePath: null,
+ createdAt,
+ updatedAt: createdAt,
+ },
+ }),
+ );
+ const activityEvent = (sequence: number, id: string, kind: string) =>
+ makeEvent({
+ sequence,
+ type: "thread.activity-appended",
+ aggregateKind: "thread",
+ aggregateId: threadId,
+ occurredAt: `2026-03-01T10:${String(Math.floor(sequence / 60) % 60).padStart(2, "0")}:${String(sequence % 60).padStart(2, "0")}.000Z`,
+ commandId: `cmd-activity-${sequence}`,
+ payload: {
+ threadId,
+ activity: {
+ id,
+ tone: "info",
+ kind,
+ summary: kind,
+ payload: {},
+ turnId: null,
+ createdAt: `2026-03-01T10:${String(Math.floor(sequence / 60) % 60).padStart(2, "0")}:${String(sequence % 60).padStart(2, "0")}.000Z`,
+ },
+ },
+ });
+ let model = yield* projectEvent(
+ afterCreate,
+ activityEvent(2, `worktree-setup:${threadId}`, "worktree-setup"),
+ );
+ for (let index = 0; index < 600; index += 1) {
+ model = yield* projectEvent(
+ model,
+ activityEvent(3 + index, `tool-${index}`, "tool.completed"),
+ );
+ }
+ const thread = model.threads.find((entry) => entry.id === threadId);
+ expect(thread?.activities).toHaveLength(501);
+ expect(thread?.activities[0]?.id).toBe(`worktree-setup:${threadId}`);
+ }),
+ );
});
diff --git a/apps/server/src/orchestration/projector.ts b/apps/server/src/orchestration/projector.ts
index fae607eb70e..53013770b15 100644
--- a/apps/server/src/orchestration/projector.ts
+++ b/apps/server/src/orchestration/projector.ts
@@ -13,6 +13,7 @@ import {
OrchestrationMessage,
OrchestrationSession,
OrchestrationThread,
+ WORKTREE_SETUP_ACTIVITY_KIND,
} from "@t3tools/contracts";
import {
legacyLinkedPullRequestOf,
@@ -76,7 +77,13 @@ function retainThreadActivities(activities: OrchestrationThread["activities"]) {
}
const pendingActivities = new Set(pending.values());
return activities.filter(
- (activity, index) => index >= recentStart || pendingActivities.has(activity),
+ (activity, index) =>
+ index >= recentStart ||
+ pendingActivities.has(activity) ||
+ // The worktree setup record is upserted under one id for the thread's
+ // whole life and is the only durable copy of a running setup; an async
+ // setup script can outlast a chatty first turn.
+ activity.kind === WORKTREE_SETUP_ACTIVITY_KIND,
);
}
diff --git a/apps/server/src/project/AgentSessionScanner.test.ts b/apps/server/src/project/AgentSessionScanner.test.ts
index 41c6c8a961c..b1cba460f95 100644
--- a/apps/server/src/project/AgentSessionScanner.test.ts
+++ b/apps/server/src/project/AgentSessionScanner.test.ts
@@ -38,6 +38,7 @@ const makeProjectionSnapshotQueryLayer = (importedWorkspaceRoots: ReadonlyArray<
Layer.succeed(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
getCommandReadModel: () => Effect.die("unused"),
getUserInputActivity: () => Effect.die("unused"),
+ listActivitiesByKind: () => Effect.die("unused"),
getSnapshot: () => Effect.die("unused"),
getShellSnapshot: () =>
Effect.succeed({
diff --git a/apps/server/src/project/ProjectSetupScriptRunner.test.ts b/apps/server/src/project/ProjectSetupScriptRunner.test.ts
index 36dbc0ad58a..8bfd86bf6ac 100644
--- a/apps/server/src/project/ProjectSetupScriptRunner.test.ts
+++ b/apps/server/src/project/ProjectSetupScriptRunner.test.ts
@@ -29,6 +29,7 @@ const makeProject = (scripts: OrchestrationProject["scripts"]): OrchestrationPro
const makeProjectionSnapshotQueryLayer = (project: OrchestrationProject) =>
Layer.succeed(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
getUserInputActivity: () => Effect.die("unused"),
+ listActivitiesByKind: () => Effect.die("unused"),
getCommandReadModel: () => Effect.die("unused"),
getSnapshot: () => Effect.die("unused"),
getShellSnapshot: () => Effect.die("unused"),
diff --git a/apps/server/src/project/WorktreeSetupTracker.ts b/apps/server/src/project/WorktreeSetupTracker.ts
index 41c84f2d649..8f6686d9274 100644
--- a/apps/server/src/project/WorktreeSetupTracker.ts
+++ b/apps/server/src/project/WorktreeSetupTracker.ts
@@ -63,11 +63,12 @@ export class WorktreeSetupTracker extends Context.Service<
stageId: WorktreeSetupStageId,
line: string,
) => Effect.Effect<void>;
+ /** Returns the settled snapshot, or null when nothing was tracked. */
readonly finish: (
threadId: ThreadId,
phase: "done" | "failed" | "cancelled",
error?: string | null,
- ) => Effect.Effect<void>;
+ ) => Effect.Effect<WorktreeSetupSnapshot | null>;
/**
* Drops the cancel handle. Called right before the turn is dispatched so a
* late cancel cannot roll back a thread whose agent has already started.
@@ -279,7 +280,7 @@ export const make = Effect.gen(function* () {
),
},
}));
- if (!snapshot) return;
+ if (!snapshot) return null;
yield* clearRetention(threadId);
const fiber = yield* remove(threadId).pipe(
Effect.delay(FINISHED_RETENTION),
@@ -292,6 +293,7 @@ export const make = Effect.gen(function* () {
Effect.forkDetach,
);
retentionFibers.set(threadId, fiber);
+ return snapshot;
});
const markUncancellable: WorktreeSetupTracker["Service"]["markUncancellable"] = (threadId) =>
diff --git a/apps/server/src/provider/Layers/ProviderService.test.ts b/apps/server/src/provider/Layers/ProviderService.test.ts
index 927d2a7d4b6..1d86bc98134 100644
--- a/apps/server/src/provider/Layers/ProviderService.test.ts
+++ b/apps/server/src/provider/Layers/ProviderService.test.ts
@@ -4966,6 +4966,7 @@ describe("agent browser access", () => {
getTurnStartMessage: () => Effect.die("unused"),
getImportedAgentSessionSources: () => Effect.die("unused"),
getUserInputActivity: () => Effect.die("unused"),
+ listActivitiesByKind: () => Effect.die("unused"),
getCommandReadModel: () => Effect.die("unused"),
getSnapshot: () => Effect.die("unused"),
getShellSnapshot: () => Effect.die("unused"),
diff --git a/apps/server/src/provider/Layers/ProviderSessionReaper.test.ts b/apps/server/src/provider/Layers/ProviderSessionReaper.test.ts
index a8036c426a9..e36d04f08df 100644
--- a/apps/server/src/provider/Layers/ProviderSessionReaper.test.ts
+++ b/apps/server/src/provider/Layers/ProviderSessionReaper.test.ts
@@ -234,6 +234,7 @@ describe("ProviderSessionReaper", () => {
Layer.provideMerge(
Layer.succeed(ProjectionSnapshotQuery, {
getUserInputActivity: () => Effect.die("unused"),
+ listActivitiesByKind: () => Effect.die("unused"),
getCommandReadModel: () => Effect.die("unused"),
getSnapshot: () => Effect.die("unused"),
getShellSnapshot: () => Effect.die("unused"),
diff --git a/apps/server/src/server.test.ts b/apps/server/src/server.test.ts
index 109d926b74c..47bfdb513c2 100644
--- a/apps/server/src/server.test.ts
+++ b/apps/server/src/server.test.ts
@@ -44,7 +44,7 @@ import {
WS_METHODS,
WsRpcGroup,
EditorId,
- type WorktreeSetupSnapshot,
+ WorktreeSetupSnapshot,
type WorktreeSetupStageId,
} from "@t3tools/contracts";
import {
@@ -10836,21 +10836,24 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
),
);
- assert.equal(response.sequence, 6);
+ assert.equal(response.sequence, 8);
assert.deepEqual(
dispatchedCommands.map((command) => command.type),
[
"thread.create",
+ "thread.message.user.append",
+ "thread.activity.append",
"thread.session.set",
"thread.meta.update",
"thread.activity.append",
"thread.activity.append",
"thread.turn.start",
+ "thread.activity.append",
],
);
// The checkout can take minutes, so the thread reads as working from
// the moment setup starts rather than only once the turn is dispatched.
- const preparingCommand = dispatchedCommands[1];
+ const preparingCommand = dispatchedCommands[3];
assertTrue(preparingCommand?.type === "thread.session.set");
if (preparingCommand?.type === "thread.session.set") {
assert.equal(preparingCommand.session.status, "starting");
@@ -10913,9 +10916,25 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
);
assert.deepEqual(
setupActivities.map((command) => command.activity.kind),
- ["setup-script.requested", "setup-script.started"],
+ ["worktree-setup", "setup-script.requested", "setup-script.started", "worktree-setup"],
);
- const finalCommand = dispatchedCommands[5];
+ // The setup record is upserted under one id: running once the thread
+ // exists, settled at the end, so a late client renders the outcome
+ // without the in-memory tracker.
+ const runningActivity = setupActivities[0]?.activity;
+ const settledActivity = setupActivities.at(-1)?.activity;
+ assert.equal(runningActivity?.id, settledActivity?.id);
+ assert.equal(settledActivity?.tone, "info");
+ assertTrue(Schema.is(WorktreeSetupSnapshot)(runningActivity?.payload));
+ if (Schema.is(WorktreeSetupSnapshot)(runningActivity?.payload)) {
+ assert.equal(runningActivity.payload.phase, "running");
+ }
+ assertTrue(Schema.is(WorktreeSetupSnapshot)(settledActivity?.payload));
+ if (Schema.is(WorktreeSetupSnapshot)(settledActivity?.payload)) {
+ assert.equal(settledActivity.payload.phase, "done");
+ assert.equal(settledActivity.payload.threadId, ThreadId.make("thread-bootstrap"));
+ }
+ const finalCommand = dispatchedCommands[7];
assertTrue(finalCommand?.type === "thread.turn.start");
if (finalCommand?.type === "thread.turn.start") {
assert.equal(finalCommand.bootstrap, undefined);
@@ -11110,13 +11129,19 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
),
);
- assert.equal(response.sequence, 2);
+ assert.equal(response.sequence, 4);
assert.equal(createWorktree.mock.calls.length, 0);
assert.deepEqual(
dispatchedCommands.map((command) => command.type),
- ["thread.create", "thread.turn.start"],
+ [
+ "thread.create",
+ "thread.message.user.append",
+ "thread.activity.append",
+ "thread.turn.start",
+ "thread.activity.append",
+ ],
);
- const finalCommand = dispatchedCommands[1];
+ const finalCommand = dispatchedCommands[3];
assertTrue(finalCommand?.type === "thread.turn.start");
if (finalCommand?.type === "thread.turn.start") {
assert.equal(finalCommand.bootstrap, undefined);
@@ -11197,11 +11222,17 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
),
);
- assert.equal(response.sequence, 2);
+ assert.equal(response.sequence, 4);
assert.equal(createWorktree.mock.calls.length, 0);
assert.deepEqual(
dispatchedCommands.map((command) => command.type),
- ["thread.create", "thread.turn.start"],
+ [
+ "thread.create",
+ "thread.message.user.append",
+ "thread.activity.append",
+ "thread.turn.start",
+ "thread.activity.append",
+ ],
);
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
@@ -11297,20 +11328,23 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
),
);
- assert.equal(response.sequence, 5);
+ assert.equal(response.sequence, 7);
assert.deepEqual(
dispatchedCommands.map((command) => command.type),
[
"thread.create",
+ "thread.message.user.append",
+ "thread.activity.append",
"thread.session.set",
"thread.meta.update",
"thread.activity.append",
"thread.turn.start",
+ "thread.activity.append",
],
);
const setupFailureActivity = dispatchedCommands.find(
(command): command is Extract<OrchestrationCommand, { type: "thread.activity.append" }> =>
- command.type === "thread.activity.append",
+ command.type === "thread.activity.append" && command.activity.kind !== "worktree-setup",
);
assert.equal(setupFailureActivity?.activity.kind, "setup-script.failed");
assert.deepEqual(setupFailureActivity?.activity.payload, {
@@ -11430,15 +11464,18 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
),
);
- assert.equal(response.sequence, 5);
+ assert.equal(response.sequence, 7);
assert.deepEqual(
dispatchedCommands.map((command) => command.type),
[
"thread.create",
+ "thread.message.user.append",
+ "thread.activity.append",
"thread.session.set",
"thread.meta.update",
"thread.activity.append",
"thread.turn.start",
+ "thread.activity.append",
],
);
const setupActivities = dispatchedCommands.filter(
@@ -11447,7 +11484,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
);
assert.deepEqual(
setupActivities.map((command) => command.activity.kind),
- ["setup-script.requested"],
+ ["worktree-setup", "setup-script.requested", "worktree-setup"],
);
assertTrue(
setupActivities.every((command) => command.activity.kind !== "setup-script.failed"),
@@ -11593,8 +11630,15 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
assert.equal(stageStatus(running, "agent"), "pending");
assert.isFalse(turnStarted());
+ // The client that sent the message goes away mid-setup (a reload or a
+ // dropped socket). The bootstrap belongs to the server, not the
+ // connection: the thread already exists for every client, so it must
+ // finish and start the turn regardless.
+ yield* Fiber.interrupt(dispatchFiber);
+ assert.isFalse(turnStarted());
+
yield* Deferred.succeed(scriptExit, undefined);
- yield* Fiber.join(dispatchFiber);
+ yield* snapshotWhere((snapshot) => stageStatus(snapshot, "agent") === "done");
assertTrue(turnStarted());
const settled = yield* snapshotWhere((snapshot) => snapshot.phase !== "running");
assert.equal(settled.phase, "done");
@@ -11701,7 +11745,14 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
assert.strictEqual(result.failure.bootstrapThreadDisposition, "deleted");
assert.deepEqual(
dispatchedCommands.map((command) => command.type),
- ["thread.create", "thread.session.set", "thread.delete"],
+ [
+ "thread.create",
+ "thread.message.user.append",
+ "thread.activity.append",
+ "thread.session.set",
+ "thread.activity.append",
+ "thread.delete",
+ ],
);
assert.isDefined(pendingAttachmentId);
assert.isTrue(
@@ -11814,7 +11865,12 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
}),
),
);
- assert.deepEqual(trace, ["thread.create", "drain:1", "thread.turn.start"]);
+ assert.deepEqual(trace, [
+ "thread.create",
+ "drain:1",
+ "thread.message.user.append",
+ "thread.turn.start",
+ ]);
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
@@ -11899,11 +11955,19 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
assert.strictEqual(result.failure.bootstrapThreadDisposition, undefined);
assert.deepEqual(
dispatchedCommands.map((command) => command.type),
- ["thread.create", "thread.session.set", "thread.delete", "thread.session.set"],
+ [
+ "thread.create",
+ "thread.message.user.append",
+ "thread.activity.append",
+ "thread.session.set",
+ "thread.activity.append",
+ "thread.delete",
+ "thread.session.set",
+ ],
);
// The surviving thread must not keep its preparing session, or it would
// read as working forever.
- const failedSession = dispatchedCommands[3];
+ const failedSession = dispatchedCommands[6];
assertTrue(failedSession?.type === "thread.session.set");
if (failedSession?.type === "thread.session.set") {
assert.equal(failedSession.session.status, "error");
diff --git a/apps/server/src/serverRuntimeStartup.test.ts b/apps/server/src/serverRuntimeStartup.test.ts
index 158606e95b1..4a8aca46bdd 100644
--- a/apps/server/src/serverRuntimeStartup.test.ts
+++ b/apps/server/src/serverRuntimeStartup.test.ts
@@ -164,6 +164,7 @@ it.effect("resolveAutoBootstrapWelcomeTargets returns existing project and threa
} as never),
Effect.provideService(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
getUserInputActivity: () => Effect.die("unused"),
+ listActivitiesByKind: () => Effect.succeed([]),
getCommandReadModel: () => Effect.die("unused"),
getSnapshot: () => Effect.die("unused"),
getShellSnapshot: () => Effect.die("unused"),
@@ -293,6 +294,7 @@ it.effect.each([
} as never),
Effect.provideService(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
getUserInputActivity: () => Effect.die("unused"),
+ listActivitiesByKind: () => Effect.succeed([]),
getCommandReadModel: () => Effect.die("unused"),
getSnapshot: () => Effect.die("unused"),
getShellSnapshot: () => Effect.die("unused"),
@@ -378,6 +380,7 @@ it.effect(
} as never),
Effect.provideService(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
getUserInputActivity: () => Effect.die("unused"),
+ listActivitiesByKind: () => Effect.succeed([]),
getCommandReadModel: () => Effect.die("unused"),
getSnapshot: () => Effect.die("unused"),
getShellSnapshot: () => Effect.die("unused"),
@@ -441,6 +444,7 @@ it.effect("resolveAutoBootstrapWelcomeTargets preserves typed UUID generation fa
} as never),
Effect.provideService(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
getUserInputActivity: () => Effect.die("unused"),
+ listActivitiesByKind: () => Effect.succeed([]),
getCommandReadModel: () => Effect.die("unused"),
getSnapshot: () => Effect.die("unused"),
getShellSnapshot: () => Effect.die("unused"),
diff --git a/apps/server/src/serverRuntimeStartup.ts b/apps/server/src/serverRuntimeStartup.ts
index ec820e2f0e6..1468e1efecb 100644
--- a/apps/server/src/serverRuntimeStartup.ts
+++ b/apps/server/src/serverRuntimeStartup.ts
@@ -1,5 +1,6 @@
import {
CommandId,
+ EventId,
DEFAULT_MODEL,
DEFAULT_PROVIDER_INTERACTION_MODE,
DEFAULT_SERVER_SETTINGS,
@@ -10,6 +11,9 @@ import {
ProviderInstanceId,
ThreadId,
TurnId,
+ WORKTREE_SETUP_ACTIVITY_KIND,
+ WorktreeSetupSnapshot,
+ worktreeSetupActivityId,
} from "@t3tools/contracts";
import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
import * as Cause from "effect/Cause";
@@ -742,6 +746,91 @@ export const reconcileProviderSessions = Effect.gen(function* () {
),
);
+const decodeWorktreeSetupSnapshot = Schema.decodeUnknownOption(WorktreeSetupSnapshot);
+
+/**
+ * A worktree bootstrap records its setup snapshot on the thread while it runs
+ * and settles it when it finishes. The bootstrap itself lives only in memory,
+ * so a process exit mid-setup leaves a `running` record with nobody to finish
+ * it. Before the turn started that also strands the persisted user message, so
+ * the setup is marked failed and the user is told to send again. After the
+ * handoff only an async setup script was still running; its stage is marked
+ * failed and the setup settles as done, like any other script failure.
+ */
+export const reconcileWorktreeSetups = Effect.gen(function* () {
+ const crypto = yield* Crypto.Crypto;
+ const orchestrationEngine = yield* OrchestrationEngine.OrchestrationEngineService;
+ const query = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
+ // The command read model carries no activity bodies; read the setup
+ // records directly, live threads only.
+ const recordedSetups = yield* query.listActivitiesByKind(WORKTREE_SETUP_ACTIVITY_KIND);
+ const interruptedAt = DateTime.formatIso(yield* DateTime.now);
+
+ for (const recorded of recordedSetups) {
+ const snapshot = decodeWorktreeSetupSnapshot(recorded.payload);
+ if (Option.isNone(snapshot) || snapshot.value.phase !== "running") continue;
+ if (recorded.id !== worktreeSetupActivityId(snapshot.value.threadId)) continue;
+ const threadId = snapshot.value.threadId;
+
+ const turnStarted = snapshot.value.stages.some(
+ (stage) => stage.id === "agent" && stage.status === "done",
+ );
+ const interrupted: WorktreeSetupSnapshot = {
+ ...snapshot.value,
+ phase: turnStarted ? "done" : "failed",
+ endedAt: interruptedAt,
+ error: turnStarted
+ ? null
+ : "The server restarted before the worktree setup finished. Send the message again.",
+ stages: snapshot.value.stages.map((stage) =>
+ stage.status === "running" || stage.status === "pending"
+ ? {
+ ...stage,
+ status: "failed",
+ endedAt: interruptedAt,
+ detail: "interrupted by a server restart",
+ }
+ : stage,
+ ),
+ sequence: snapshot.value.sequence + 1,
+ };
+ yield* orchestrationEngine
+ .dispatch({
+ type: "thread.activity.append",
+ commandId: CommandId.make(yield* crypto.randomUUIDv4),
+ threadId,
+ activity: {
+ id: EventId.make(worktreeSetupActivityId(threadId)),
+ tone: "error",
+ kind: WORKTREE_SETUP_ACTIVITY_KIND,
+ summary: turnStarted
+ ? "Setup script interrupted by a server restart"
+ : "Worktree setup interrupted by a server restart",
+ payload: interrupted,
+ turnId: null,
+ createdAt: snapshot.value.startedAt,
+ },
+ createdAt: interruptedAt,
+ })
+ .pipe(
+ Effect.catchCause((cause) =>
+ Cause.hasInterrupts(cause)
+ ? Effect.failCause(cause)
+ : Effect.logWarning("failed to settle interrupted worktree setup", {
+ threadId,
+ cause,
+ }),
+ ),
+ );
+ }
+}).pipe(
+ Effect.catchCause((cause) =>
+ Cause.hasInterrupts(cause)
+ ? Effect.failCause(cause)
+ : Effect.logWarning("worktree setup startup reconciliation failed", { cause }),
+ ),
+);
+
interface StartupOptions {
readonly activate?: Effect.Effect<void>;
readonly awaitAuxiliaryParked?: Effect.Effect<void>;
@@ -881,6 +970,7 @@ export const make = (options?: StartupOptions) =>
);
yield* runStartupPhase("provider-sessions.reconcile", reconcileProviderSessions);
+ yield* runStartupPhase("worktree-setups.reconcile", reconcileWorktreeSetups);
yield* Effect.logDebug("startup phase: syncing clean projects");
yield* runStartupPhase("projects.auto-pull", syncAutoPullProjects);
diff --git a/apps/server/src/serverRuntimeStartup.worktreeSetup.test.ts b/apps/server/src/serverRuntimeStartup.worktreeSetup.test.ts
new file mode 100644
index 00000000000..fda60d88971
--- /dev/null
+++ b/apps/server/src/serverRuntimeStartup.worktreeSetup.test.ts
@@ -0,0 +1,156 @@
+import * as NodeServices from "@effect/platform-node/NodeServices";
+import {
+ EventId,
+ type OrchestrationCommand,
+ ThreadId,
+ WORKTREE_SETUP_ACTIVITY_KIND,
+ WorktreeSetupSnapshot,
+ worktreeSetupActivityId,
+ type WorktreeSetupPhase,
+} from "@t3tools/contracts";
+import { assert, it } from "@effect/vitest";
+import * as Effect from "effect/Effect";
+import * as Schema from "effect/Schema";
+import * as Stream from "effect/Stream";
+
+import * as OrchestrationEngine from "./orchestration/Services/OrchestrationEngine.ts";
+import * as ProjectionSnapshotQuery from "./orchestration/Services/ProjectionSnapshotQuery.ts";
+import * as ServerRuntimeStartup from "./serverRuntimeStartup.ts";
+
+const startedAt = "2026-08-20T12:00:00.000Z";
+
+const snapshotFor = (
+ threadId: ThreadId,
+ phase: WorktreeSetupPhase,
+ agentStatus: "pending" | "done" = phase === "running" ? "pending" : "done",
+): WorktreeSetupSnapshot => ({
+ threadId,
+ phase,
+ startedAt,
+ endedAt: phase === "running" ? null : startedAt,
+ branch: "feature",
+ baseRef: "main",
+ worktreePath: null,
+ setupScript: null,
+ stages: [
+ {
+ id: "checkout",
+ status: "done",
+ startedAt,
+ endedAt: startedAt,
+ percent: null,
+ detail: null,
+ tail: [],
+ },
+ {
+ id: "setup-script",
+ status: phase === "running" ? "running" : "done",
+ startedAt,
+ endedAt: phase === "running" ? null : startedAt,
+ percent: null,
+ detail: null,
+ tail: [],
+ },
+ {
+ id: "agent",
+ status: agentStatus,
+ startedAt: null,
+ endedAt: null,
+ percent: null,
+ detail: null,
+ tail: [],
+ },
+ ],
+ error: null,
+ sequence: 4,
+});
+
+const recordedSetup = (id: string, phase: WorktreeSetupPhase, agentStatus?: "pending" | "done") => {
+ const threadId = ThreadId.make(id);
+ return {
+ id: EventId.make(worktreeSetupActivityId(threadId)),
+ tone: "info" as const,
+ kind: WORKTREE_SETUP_ACTIVITY_KIND,
+ summary: "Setting up worktree",
+ payload: snapshotFor(threadId, phase, agentStatus),
+ turnId: null,
+ createdAt: startedAt,
+ };
+};
+
+const run = (activities: ReadonlyArray<ReturnType<typeof recordedSetup>>) =>
+ Effect.gen(function* () {
+ const dispatched: Array<OrchestrationCommand> = [];
+ yield* ServerRuntimeStartup.reconcileWorktreeSetups.pipe(
+ Effect.provideService(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
+ listActivitiesByKind: (kind: string) =>
+ Effect.succeed(kind === WORKTREE_SETUP_ACTIVITY_KIND ? activities : []),
+ } as unknown as ProjectionSnapshotQuery.ProjectionSnapshotQuery["Service"]),
+ Effect.provideService(OrchestrationEngine.OrchestrationEngineService, {
+ readEvents: () => Stream.empty,
+ readThreadEvents: () => Stream.empty,
+ getThreadReplayStats: () => Effect.die("unused"),
+ dispatch: (command) =>
+ Effect.sync(() => {
+ dispatched.push(command);
+ return { sequence: dispatched.length };
+ }),
+ streamDomainEvents: Stream.empty,
+ subscribeDomainEvents: Effect.succeed(Stream.empty),
+ latestSequence: Effect.succeed(0),
+ }),
+ Effect.provide(NodeServices.layer),
+ );
+ return dispatched;
+ });
+
+it.effect("marks setups still recorded as running failed after a restart", () =>
+ Effect.gen(function* () {
+ const dispatched = yield* run([
+ recordedSetup("thread-running", "running"),
+ recordedSetup("thread-done", "done"),
+ recordedSetup("thread-failed", "failed"),
+ ]);
+
+ assert.equal(dispatched.length, 1);
+ const command = dispatched[0]!;
+ assert.equal(command.type, "thread.activity.append");
+ if (command.type !== "thread.activity.append") return;
+ assert.equal(command.threadId, ThreadId.make("thread-running"));
+ assert.equal(command.activity.id, worktreeSetupActivityId(ThreadId.make("thread-running")));
+ assert.equal(command.activity.tone, "error");
+ const payload = yield* Schema.decodeUnknownEffect(WorktreeSetupSnapshot)(
+ command.activity.payload,
+ );
+ assert.equal(payload.phase, "failed");
+ assert.isNotNull(payload.endedAt);
+ assert.equal(payload.sequence, 5);
+ assert.deepEqual(
+ payload.stages.map((stage) => stage.status),
+ ["done", "failed", "failed"],
+ );
+ }),
+);
+
+it.effect(
+ "settles an async setup script whose turn already started without failing the setup",
+ () =>
+ Effect.gen(function* () {
+ const dispatched = yield* run([recordedSetup("thread-async", "running", "done")]);
+
+ assert.equal(dispatched.length, 1);
+ const command = dispatched[0]!;
+ if (command.type !== "thread.activity.append") return assert.fail(command.type);
+ const payload = yield* Schema.decodeUnknownEffect(WorktreeSetupSnapshot)(
+ command.activity.payload,
+ );
+ // The turn is live; only the background script was lost. Nothing asks the
+ // user to resend, and the setup reads as done with a failed script stage.
+ assert.equal(payload.phase, "done");
+ assert.isNull(payload.error);
+ assert.deepEqual(
+ payload.stages.map((stage) => stage.status),
+ ["done", "failed", "done"],
+ );
+ }),
+);
diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts
index debefdd62a9..72d941d7b82 100644
--- a/apps/server/src/ws.ts
+++ b/apps/server/src/ws.ts
@@ -76,6 +76,9 @@ import {
type PullRequestRef,
WS_METHODS,
WsRpcGroup,
+ WORKTREE_SETUP_ACTIVITY_KIND,
+ worktreeSetupActivityId,
+ type WorktreeSetupSnapshot,
} from "@t3tools/contracts";
import { resolveServerBackgroundActivitySettings } from "@t3tools/shared/backgroundActivitySettings";
import { HttpRouter, HttpServerRequest, HttpServerRespondable } from "effect/unstable/http";
@@ -775,6 +778,44 @@ const makeWsRpcLayer = (
),
);
+ // The worktree setup's durable record: one activity per thread, upserted
+ // by a fixed id when the setup starts and again when it settles. Live
+ // progress keeps streaming from the tracker; this is what a reload or
+ // another client reads. Best effort: the thread may already be gone
+ // after a failed bootstrap.
+ const recordWorktreeSetup = (snapshot: WorktreeSetupSnapshot) =>
+ serverCommandId("worktree-setup-activity").pipe(
+ Effect.flatMap((commandId) =>
+ dispatchFromClient({
+ type: "thread.activity.append",
+ commandId,
+ threadId: snapshot.threadId,
+ activity: {
+ id: EventId.make(worktreeSetupActivityId(snapshot.threadId)),
+ tone:
+ snapshot.phase === "failed" ||
+ snapshot.stages.some((stage) => stage.status === "failed")
+ ? "error"
+ : "info",
+ kind: WORKTREE_SETUP_ACTIVITY_KIND,
+ summary:
+ snapshot.phase === "running"
+ ? "Setting up worktree"
+ : snapshot.phase === "done"
+ ? "Worktree ready"
+ : snapshot.phase === "cancelled"
+ ? "Worktree setup cancelled"
+ : "Worktree setup failed",
+ payload: snapshot,
+ turnId: null,
+ createdAt: snapshot.startedAt,
+ },
+ createdAt: snapshot.endedAt ?? snapshot.startedAt,
+ }),
+ ),
+ Effect.ignoreCause({ log: true }),
+ );
+
const toBootstrapDispatchCommandCauseError = (cause: Cause.Cause<unknown>) => {
const error = Cause.squash(cause);
return isOrchestrationDispatchCommandError(error)
@@ -1361,6 +1402,28 @@ const makeWsRpcLayer = (
// terminals and provider sessions under the reused thread id.
yield* threadDeletionReactor.drainThrough(created.sequence);
createdThread = true;
+ // Persist the send now rather than with the turn: the thread is
+ // real from here on, so any client (or a reload) sees the message
+ // while the worktree is still being prepared. The turn start
+ // later references this id instead of re-sending the text.
+ yield* dispatchFromClient({
+ type: "thread.message.user.append",
+ commandId: yield* serverCommandId("bootstrap-thread-message"),
+ threadId: command.threadId,
+ message: {
+ messageId: command.message.messageId,
+ text: command.message.text,
+ attachments: command.message.attachments,
+ ...(command.message.context !== undefined
+ ? { context: command.message.context }
+ : {}),
+ },
+ createdAt: command.createdAt,
+ });
+ if (tracked) {
+ const running = yield* worktreeSetupTracker.get(threadId);
+ if (running) yield* recordWorktreeSetup(running);
+ }
}
if (prepareWorktree && shouldPrepareWorktree && worktreeBaseRef) {
@@ -1496,7 +1559,15 @@ const makeWsRpcLayer = (
// running so the client keeps its row next to the agent's work,
// and settles when the script exits. The turn already started, so
// the wait cannot fail the dispatch.
- const settle = track(worktreeSetupTracker.finish(threadId, "done"));
+ const settle = tracked
+ ? worktreeSetupTracker
+ .finish(threadId, "done")
+ .pipe(
+ Effect.flatMap((snapshot) =>
+ snapshot ? recordWorktreeSetup(snapshot) : Effect.void,
+ ),
+ )
+ : Effect.void;
if (pendingSetupScript) {
yield* Fiber.join(pendingSetupScript).pipe(
Effect.ignoreCause({ log: true }),
@@ -1509,20 +1580,6 @@ const makeWsRpcLayer = (
return started;
});
- const runBootstrap = tracked
- ? Effect.gen(function* () {
- const fiber = yield* Effect.forkChild(bootstrapProgram);
- yield* worktreeSetupTracker.begin({
- threadId,
- branch: bootstrap?.prepareWorktree?.branch ?? null,
- baseRef: bootstrap?.prepareWorktree?.baseBranch ?? null,
- stages: ["fetch", "checkout", "submodules", "setup-script", "agent"],
- fiber,
- });
- return yield* Fiber.join(fiber);
- })
- : bootstrapProgram;
-
const cleanupAndFail = (
cause: Cause.Cause<unknown>,
dispatchError: OrchestrationDispatchCommandError,
@@ -1561,7 +1618,7 @@ const makeWsRpcLayer = (
}),
);
- return yield* runBootstrap.pipe(
+ const settledBootstrapProgram = bootstrapProgram.pipe(
Effect.catchCause((cause) => {
const dispatchError = toBootstrapDispatchCommandCauseError(cause);
if (Cause.hasInterruptsOnly(cause)) {
@@ -1597,7 +1654,15 @@ const makeWsRpcLayer = (
Effect.uninterruptible,
)
: Effect.void;
- return track(worktreeSetupTracker.finish(threadId, "cancelled")).pipe(
+ return track(
+ worktreeSetupTracker
+ .finish(threadId, "cancelled")
+ .pipe(
+ Effect.flatMap((snapshot) =>
+ snapshot ? recordWorktreeSetup(snapshot) : Effect.void,
+ ),
+ ),
+ ).pipe(
Effect.andThen(removeCreatedWorktree),
Effect.andThen(
tracked
@@ -1612,10 +1677,45 @@ const makeWsRpcLayer = (
);
}
return track(
- worktreeSetupTracker.finish(threadId, "failed", dispatchError.message),
+ worktreeSetupTracker
+ .finish(threadId, "failed", dispatchError.message)
+ .pipe(
+ Effect.flatMap((snapshot) =>
+ snapshot ? recordWorktreeSetup(snapshot) : Effect.void,
+ ),
+ ),
).pipe(Effect.andThen(cleanupAndFail(cause, dispatchError)));
}),
);
+
+ // The bootstrap outlives the connection that asked for it: a reload
+ // or a dropped socket must not abandon a half-made worktree, and
+ // the thread it created is already visible to every client. The
+ // RPC only waits on the detached fiber; a user cancel interrupts it
+ // through the tracker.
+ const runBootstrap = tracked
+ ? Effect.gen(function* () {
+ // Fork and register as one step: a detached fiber keeps going
+ // if the caller is interrupted, so it must never exist without
+ // the tracker entry that cancel and the stage updates key on.
+ const fiber = yield* Effect.uninterruptible(
+ Effect.gen(function* () {
+ const fiber = yield* Effect.forkDetach(settledBootstrapProgram);
+ yield* worktreeSetupTracker.begin({
+ threadId,
+ branch: bootstrap?.prepareWorktree?.branch ?? null,
+ baseRef: bootstrap?.prepareWorktree?.baseBranch ?? null,
+ stages: ["fetch", "checkout", "submodules", "setup-script", "agent"],
+ fiber,
+ });
+ return fiber;
+ }),
+ );
+ return yield* Fiber.join(fiber);
+ })
+ : settledBootstrapProgram;
+
+ return yield* runBootstrap;
});
const dispatchNormalizedCommand = (
diff --git a/apps/web/src/components/ChatView.logic.test.ts b/apps/web/src/components/ChatView.logic.test.ts
index 6f2a9e1199f..c226a3a65c7 100644
--- a/apps/web/src/components/ChatView.logic.test.ts
+++ b/apps/web/src/components/ChatView.logic.test.ts
@@ -59,6 +59,8 @@ import {
restorePlanFollowUpComposer,
resolveComposerProviderSelection,
resolveDraftPromotionNavigationTarget,
+ findRecordedWorktreeSetup,
+ resolveVisibleWorktreeSetup,
observeProactivePanelUserChoice,
resolveProactiveTurnDiffAction,
resolveThreadMetadataUpdateForNextTurn,
@@ -1016,20 +1018,10 @@ describe("draft promotion during worktree setup", () => {
const serverThreadRef = { environmentId, threadId };
it.each([null, "idle", "starting", "ready"] as const)(
- "keeps the draft mounted while the first turn waits with session %s",
+ "keeps the draft mounted until the server owns the send, with session %s",
(status) => {
const serverThread = makeThread({
- messages: [
- {
- id: MessageId.make("submitted-message"),
- role: "user",
- text: "Start in a new worktree",
- turnId: null,
- createdAt: now,
- updatedAt: now,
- streaming: false,
- },
- ],
+ messages: [],
session: status ? { ...readySession, status } : null,
});
@@ -1043,6 +1035,31 @@ describe("draft promotion during worktree setup", () => {
},
);
+ it("promotes once the bootstrap persisted the user message, before any turn", () => {
+ const serverThread = makeThread({
+ messages: [
+ {
+ id: MessageId.make("submitted-message"),
+ role: "user",
+ text: "Start in a new worktree",
+ turnId: null,
+ createdAt: now,
+ updatedAt: now,
+ streaming: false,
+ },
+ ],
+ session: null,
+ });
+
+ expect(
+ resolveDraftPromotionNavigationTarget({
+ serverThreadRef,
+ serverThread,
+ backgroundSubmissionPending: false,
+ }),
+ ).toEqual(serverThreadRef);
+ });
+
it("promotes when the provider starts the first turn", () => {
const latestTurn = { ...completedTurn, state: "running" as const, completedAt: null };
@@ -2472,3 +2489,133 @@ describe("restorePlanFollowUpComposer", () => {
});
});
});
+
+describe("worktree setup visibility", () => {
+ const stage = (
+ id: "fetch" | "checkout" | "submodules" | "setup-script" | "agent",
+ status: "done" | "running" | "failed" | "pending",
+ ) => ({
+ id,
+ status,
+ startedAt: now,
+ endedAt: status === "running" || status === "pending" ? null : now,
+ percent: null,
+ detail: null,
+ tail: [],
+ });
+ const base = {
+ threadId,
+ phase: "running" as const,
+ startedAt: now,
+ endedAt: null,
+ branch: "feature",
+ baseRef: "main",
+ worktreePath: null,
+ setupScript: null,
+ stages: [stage("checkout", "running"), stage("agent", "pending")],
+ error: null,
+ sequence: 1,
+ };
+ const settledDone = {
+ ...base,
+ phase: "done" as const,
+ endedAt: now,
+ stages: [stage("checkout", "done"), stage("setup-script", "done"), stage("agent", "done")],
+ };
+
+ it("reads the settled snapshot back from the thread's activities", () => {
+ const activities = [
+ { kind: "setup-script.started", payload: {} },
+ { kind: "worktree-setup", payload: settledDone },
+ { kind: "worktree-setup", payload: { not: "a snapshot" } },
+ ];
+ expect(findRecordedWorktreeSetup(activities, threadId)).toEqual(settledDone);
+ expect(findRecordedWorktreeSetup(activities, ThreadId.make("other"))).toBeNull();
+ });
+
+ it("shows a running setup and hides a clean one once the turn started", () => {
+ expect(
+ resolveVisibleWorktreeSetup({
+ live: base,
+ recorded: null,
+ turnStarted: false,
+ isWorking: true,
+ }),
+ ).toEqual(base);
+ expect(
+ resolveVisibleWorktreeSetup({
+ live: null,
+ recorded: settledDone,
+ turnStarted: false,
+ isWorking: true,
+ }),
+ ).toEqual(settledDone);
+ expect(
+ resolveVisibleWorktreeSetup({
+ live: null,
+ recorded: settledDone,
+ turnStarted: true,
+ isWorking: true,
+ }),
+ ).toBeNull();
+ });
+
+ it("keeps a failed script visible for the running turn and a failed setup always", () => {
+ const scriptFailed = {
+ ...settledDone,
+ stages: [stage("checkout", "done"), stage("setup-script", "failed"), stage("agent", "done")],
+ };
+ expect(
+ resolveVisibleWorktreeSetup({
+ live: null,
+ recorded: scriptFailed,
+ turnStarted: true,
+ isWorking: true,
+ }),
+ ).toEqual(scriptFailed);
+ expect(
+ resolveVisibleWorktreeSetup({
+ live: null,
+ recorded: scriptFailed,
+ turnStarted: true,
+ isWorking: false,
+ }),
+ ).toBeNull();
+ const failed = { ...settledDone, phase: "failed" as const, error: "git exploded" };
+ expect(
+ resolveVisibleWorktreeSetup({
+ live: null,
+ recorded: failed,
+ turnStarted: true,
+ isWorking: false,
+ }),
+ ).toEqual(failed);
+ });
+
+ it("prefers whichever snapshot is newer by sequence", () => {
+ expect(
+ resolveVisibleWorktreeSetup({
+ live: { ...base, sequence: 3 },
+ recorded: { ...settledDone, sequence: 7 },
+ turnStarted: false,
+ isWorking: false,
+ }),
+ ).toEqual({ ...settledDone, sequence: 7 });
+ expect(
+ resolveVisibleWorktreeSetup({
+ live: { ...settledDone, sequence: 9 },
+ recorded: { ...base, sequence: 1 },
+ turnStarted: false,
+ isWorking: false,
+ }),
+ ).toEqual({ ...settledDone, sequence: 9 });
+ expect(
+ resolveVisibleWorktreeSetup({
+ live: base,
+ recorded: null,
+ turnStarted: false,
+ isWorking: false,
+ }),
+ ).toEqual(base);
+ });
+});
diff --git a/apps/web/src/components/ChatView.logic.ts b/apps/web/src/components/ChatView.logic.ts
index eae137201d3..1dbe11f6c4c 100644
--- a/apps/web/src/components/ChatView.logic.ts
+++ b/apps/web/src/components/ChatView.logic.ts
@@ -18,6 +18,8 @@ import {
type ThreadId,
type ThreadLinkedPullRequest,
type TurnId,
+ WORKTREE_SETUP_ACTIVITY_KIND,
+ WorktreeSetupSnapshot,
} from "@t3tools/contracts";
import { parseScopedThreadKey } from "@t3tools/client-runtime/environment";
import { resolveAssetUrl } from "@t3tools/client-runtime/state/assets";
@@ -40,6 +42,7 @@ import {
type TurnDiffSummary,
} from "../types";
import { type ComposerImageAttachment, type DraftThreadState } from "../composerDraftStore";
+import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import { appAtomRegistry } from "../rpc/atomRegistry";
import { environmentThreadDetails } from "../state/threads";
@@ -251,6 +254,52 @@ export function toolGroupConsumesUpwardNavigation(target: EventTarget | null): b
return false;
}
+const decodeWorktreeSetupSnapshot = Schema.decodeUnknownOption(WorktreeSetupSnapshot);
+
+/**
+ * The worktree setup the server recorded on the thread, if any: running once
+ * the bootstrap created the thread, then the settled outcome. It is what a
+ * reload or a second client renders, and what tells them to attach the live
+ * stream while it still says running.
+ */
+export function findRecordedWorktreeSetup(
+ activities: ReadonlyArray<{ readonly kind: string; readonly payload: unknown }>,
+ threadId: ThreadId,
+): WorktreeSetupSnapshot | null {
+ for (let index = activities.length - 1; index >= 0; index -= 1) {
+ const activity = activities[index]!;
+ if (activity.kind !== WORKTREE_SETUP_ACTIVITY_KIND) continue;
+ const decoded = decodeWorktreeSetupSnapshot(activity.payload);
+ if (Option.isSome(decoded) && decoded.value.threadId === threadId) return decoded.value;
+ }
+ return null;
+}
+
+/**
+ * Which setup snapshot the timeline shows, if any. The live stream wins while
+ * it has a newer sequence; the recorded activity covers everything else. A
+ * running setup always shows. Once settled, the card stays only while it
+ * still says something the turn does not: the turn has not started yet, or a
+ * stage failed and the turn is still running so the exit code stays reachable.
+ */
+export function resolveVisibleWorktreeSetup(input: {
+ live: WorktreeSetupSnapshot | null;
+ recorded: WorktreeSetupSnapshot | null;
+ turnStarted: boolean;
+ isWorking: boolean;
+}): WorktreeSetupSnapshot | null {
+ const snapshot =
+ input.live && (!input.recorded || input.live.sequence >= input.recorded.sequence)
+ ? input.live
+ : input.recorded;
+ if (!snapshot) return null;
+ if (snapshot.phase === "running") return snapshot;
+ if (snapshot.phase !== "done") return snapshot;
+ if (!input.turnStarted) return snapshot;
+ const stageFailed = snapshot.stages.some((stage) => stage.status === "failed");
+ return stageFailed && input.isWorking ? snapshot : null;
+}
+
export function resolveDraftHeroState(input: {
isLocalDraftThread: boolean;
hasTimelineEntries: boolean;
@@ -405,7 +454,7 @@ export function resolveThreadSwitchTimeline<T extends readonly unknown[]>(input:
export function resolveDraftPromotionNavigationTarget(input: {
serverThreadRef: ScopedThreadRef | null;
- serverThread: Pick<Thread, "latestTurn" | "session"> | null | undefined;
+ serverThread: Pick<Thread, "latestTurn" | "session" | "messages"> | null | undefined;
backgroundSubmissionPending: boolean;
}): ScopedThreadRef | null {
if (input.backgroundSubmissionPending) {
@@ -415,9 +464,13 @@ export function resolveDraftPromotionNavigationTarget(input: {
const turnStarted = input.serverThread?.latestTurn?.startedAt != null;
const startupStopped =
sessionStatus === "error" || sessionStatus === "stopped" || sessionStatus === "interrupted";
- // Keep local preparation feedback mounted until the server can render the
- // running turn or its startup error on the canonical thread route.
- return turnStarted || startupStopped ? input.serverThreadRef : null;
+ // A worktree bootstrap persists the user message before the turn, so the
+ // thread route can render the send and the live setup by itself. Otherwise
+ // keep the draft mounted until the server can render the running turn or
+ // its startup error.
+ const messagePersisted =
+ input.serverThread?.messages.some((message) => message.role === "user") ?? false;
+ return turnStarted || startupStopped || messagePersisted ? input.serverThreadRef : null;
}
export function scheduleEnvironmentReconnectWarning(showWarning: () => void): () => void {
diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx
index 53683ce7ed6..4182fa03ffa 100644
--- a/apps/web/src/components/ChatView.tsx
+++ b/apps/web/src/components/ChatView.tsx
@@ -435,6 +435,8 @@ import {
resolveComposerInteractionMode,
resolveComposerProviderSelection,
resolveDraftHeroState,
+ findRecordedWorktreeSetup,
+ resolveVisibleWorktreeSetup,
restorePlanFollowUpComposer,
isPaintOnlyThreadTimeline,
peekHeldThreadTimeline,
@@ -1430,16 +1432,6 @@ function releaseChatTimelineAnchor<T extends { readonly messageId: MessageId | n
return current.messageId === null ? current : { ...current, messageId: null };
}
-/**
- * Worktree setups whose async setup script may still be running after the
- * draft route hands off to the created thread. Keyed by scoped thread key;
- * entries are removed once the setup settles.
- */
-const pendingWorktreeSetupByThreadKey = new Map<
- string,
- { environmentId: EnvironmentId; threadId: ThreadId }
->();
-
export default function ChatView(props: ChatViewProps) {
const {
environmentId,
@@ -1662,19 +1654,9 @@ export default function ChatView(props: ChatViewProps) {
return () => revokeBlobPreviewUrl(src);
}, [expandedImage]);
const [optimisticUserMessages, setOptimisticUserMessages] = useState<ChatMessage[]>([]);
- // The bootstrap worktree setup this composer last dispatched. Set when a
- // worktree send starts and cleared once the turn starts or the next send
- // begins, so a failed or cancelled card stays until the user acts.
- const [worktreeSetupRef, setWorktreeSetupRef] = useState<{
- environmentId: EnvironmentId;
- threadId: ThreadId;
- ownerKey: string;
- } | null>(() => {
- // The draft route unmounts when it promotes to the created thread, while an
- // async setup script may still be running. Adopt the ref the draft left.
- const handed = pendingWorktreeSetupByThreadKey.get(routeThreadKey);
- return handed ? { ...handed, ownerKey: routeThreadKey } : null;
- });
+ // Last live snapshot from the setup stream. The server drops a finished
+ // snapshot after a grace period and emits null; holding it here bridges the
+ // gap until the settled activity arrives on the thread projection.
const [heldWorktreeSetup, setHeldWorktreeSetup] = useState<WorktreeSetupSnapshot | null>(null);
// Set by "Work locally": the draft whose restored message should be resent
// once the cancelled dispatch has settled and the draft is in local mode.
@@ -3157,7 +3139,7 @@ export default function ChatView(props: ChatViewProps) {
resetLocalDispatch,
localDispatchStartedAt,
latestUserMessageAt,
- isPreparingWorktree,
+ isPreparingWorktree: isLocallyPreparingWorktree,
isSendBusy,
backgroundSubmissionPending,
} = useLocalDispatchState({
@@ -3193,8 +3175,30 @@ export default function ChatView(props: ChatViewProps) {
(isSendBusy || phase === "connecting" || phase === "running") &&
compactRequestIsActive &&
!compactionSettled;
+ // The server records a running worktree setup on the thread for the whole
+ // bootstrap window. That record, with no turn yet, is how a reload or another
+ // client sees a worktree still being prepared, so it counts as working like
+ // the local dispatch that started it. It settles on every failure path and
+ // on restart, so this cannot outlive the setup. The placeholder "starting"
+ // session is not used here: an ordinary first turn projects one too, and it
+ // already drives the connecting state on its own.
+ const recordedWorktreeSetup = useMemo(
+ () => findRecordedWorktreeSetup(activeThread?.activities ?? [], routeThreadRef.threadId),
+ [activeThread?.activities, routeThreadRef.threadId],
+ );
+ const awaitingBootstrapTurn =
+ activeServerThread !== null &&
+ activeServerThread.id === routeThreadRef.threadId &&
+ activeServerThread.latestTurn === null &&
+ recordedWorktreeSetup?.phase === "running";
const isWorking =
- phase === "running" || isSendBusy || isConnecting || isRevertingCheckpoint || isCompacting;
+ phase === "running" ||
+ isSendBusy ||
+ isConnecting ||
+ isRevertingCheckpoint ||
+ isCompacting ||
+ awaitingBootstrapTurn;
+ const isPreparingWorktree = isLocallyPreparingWorktree || awaitingBootstrapTurn;
const activeWorkStartedAt = deriveActiveWorkStartedAt(
activeLatestTurn,
activeThread?.session ?? null,
@@ -3487,115 +3491,57 @@ export default function ChatView(props: ChatViewProps) {
activeThreadKey,
);
const displayedThreadRef = parseScopedThreadKey(displayedTimelineKey);
- // Live stages of a bootstrap worktree setup. The subscription follows the
- // thread that was set up, not the route: a deleted bootstrap thread rotates
- // the draft's thread id, and the failed card must survive that.
- const worktreeSetupOwnerKey = draftId ?? routeThreadKey;
- const worktreeSetupActive =
- worktreeSetupRef !== null && worktreeSetupRef.ownerKey === worktreeSetupOwnerKey;
- // A thread reopened mid-setup has no dispatch ref: this view remounted.
- // The server projects a starting session before any message or turn exists
- // for exactly that window, so follow the setup stream from the thread's own
- // state. The ref is adopted below so the card then follows the same
- // lifecycle as the original send, including an async setup script that
- // keeps running after the agent's turn lands.
- const resumedWorktreeSetupRef =
- !worktreeSetupActive &&
- isServerThread &&
- activeThreadRef !== null &&
- activeThreadShell?.session?.status === "starting" &&
- activeThreadShell.latestTurn === null &&
- activeThreadShell.latestUserMessageAt === null
- ? activeThreadRef
- : null;
- useEffect(() => {
- if (!resumedWorktreeSetupRef) return;
- // Only a ref owned by this route survives adoption. This component is
- // reused across routes, so a ref left by another thread's send is stale
- // here and would leave the resumed setup with no target after handoff.
- setWorktreeSetupRef((current) =>
- current?.ownerKey === worktreeSetupOwnerKey
- ? current
- : { ...resumedWorktreeSetupRef, ownerKey: worktreeSetupOwnerKey },
- );
- }, [resumedWorktreeSetupRef, worktreeSetupOwnerKey]);
- // The setup runs on the environment that received the dispatch, so both
- // the subscription and cancel target that one even if the draft's machine
- // picker changes underneath.
- const worktreeSetupTarget = useMemo(
- () =>
- worktreeSetupActive
- ? { environmentId: worktreeSetupRef.environmentId, threadId: worktreeSetupRef.threadId }
- : resumedWorktreeSetupRef,
- [resumedWorktreeSetupRef, worktreeSetupActive, worktreeSetupRef],
- );
+ // Live stages of a bootstrap worktree setup. A worktree send creates the
+ // server thread under the route's thread id before anything else, so the
+ // stream is keyed by that id alone: no owner bookkeeping, and a remount,
+ // reload, or second client picks it up the same way. The subscription is
+ // held only while a snapshot can still change.
+ const routeThreadPreparesWorktree =
+ (isPreparingWorktree && activeThread?.id === routeThreadRef.threadId) ||
+ heldWorktreeSetup?.phase === "running";
const worktreeSetupQuery = useEnvironmentQuery(
- worktreeSetupTarget
+ routeThreadPreparesWorktree
? vcsEnvironment.worktreeSetup({
- environmentId: worktreeSetupTarget.environmentId,
- input: { threadId: worktreeSetupTarget.threadId },
+ environmentId: routeThreadRef.environmentId,
+ input: { threadId: routeThreadRef.threadId },
})
: null,
);
const latestWorktreeSetup = worktreeSetupQuery.data;
useEffect(() => {
- // The server drops finished snapshots after a grace period and emits null.
- // Hold the last real snapshot so a settled card does not vanish.
if (latestWorktreeSetup) setHeldWorktreeSetup(latestWorktreeSetup);
}, [latestWorktreeSetup]);
- const worktreeSetup =
- worktreeSetupTarget !== null && heldWorktreeSetup?.threadId === worktreeSetupTarget.threadId
- ? heldWorktreeSetup
- : null;
- // A finished card is dropped once the agent's turn shows in the timeline:
- // the card belongs to the send, and the agent takes over from there. An
- // async setup script keeps the snapshot running past the handoff and its
- // row leaves the moment the script exits cleanly; a failed script stays
- // for the rest of the turn so the exit code and terminal remain reachable.
- const worktreeSetupDoneAndTurnVisible =
- worktreeSetup?.phase === "done" &&
- activeThread?.latestTurn?.startedAt != null &&
- (!isWorking || !worktreeSetup.stages.some((stage) => stage.status === "failed"));
useEffect(() => {
- if (!worktreeSetupDoneAndTurnVisible) return;
- setWorktreeSetupRef(null);
setHeldWorktreeSetup(null);
- }, [worktreeSetupDoneAndTurnVisible]);
- // The handoff entry only matters while the setup is still running: once it
- // settles in any phase, a later mount of the thread must not adopt it.
- const worktreeSetupSettledKey =
- worktreeSetup && worktreeSetup.phase !== "running" && worktreeSetupRef
- ? scopedThreadKey(scopeThreadRef(worktreeSetupRef.environmentId, worktreeSetupRef.threadId))
- : null;
- useEffect(() => {
- if (worktreeSetupSettledKey) pendingWorktreeSetupByThreadKey.delete(worktreeSetupSettledKey);
- }, [worktreeSetupSettledKey]);
+ }, [routeThreadKey]);
+ const liveWorktreeSetup =
+ heldWorktreeSetup?.threadId === routeThreadRef.threadId ? heldWorktreeSetup : null;
+ const worktreeSetup = resolveVisibleWorktreeSetup({
+ live: liveWorktreeSetup,
+ recorded: recordedWorktreeSetup,
+ turnStarted: activeThread?.latestTurn?.startedAt != null,
+ isWorking,
+ });
// Sends wait for the agent handoff, not for the setup script: an async
// script keeps the snapshot running while the agent already works, and a
- // follow-up must not be held behind a slow install. A resumed setup has no
- // snapshot until its first stream event, so that gap blocks as well. The
- // gap is judged by the shell, not by the resumed ref, since adopting the
- // ref clears it before the query has delivered anything.
- const worktreeSetupAwaitingFirstSnapshot =
- worktreeSetup === null &&
- worktreeSetupTarget !== null &&
- isServerThread &&
- activeThreadShell?.session?.status === "starting" &&
- activeThreadShell.latestTurn === null;
+ // follow-up must not be held behind a slow install. Before the first
+ // snapshot arrives the starting session stands in for it.
const worktreeSetupBlocksSend =
worktreeSetup !== null
? worktreeSetup.phase === "running" && !worktreeSetupAgentStarted(worktreeSetup)
- : worktreeSetupAwaitingFirstSnapshot;
+ : isServerThread &&
+ activeThreadShell?.session?.status === "starting" &&
+ activeThreadShell.latestTurn === null;
const cancelWorktreeSetup = useAtomCommand(vcsEnvironment.cancelWorktreeSetup, {
reportFailure: false,
});
const onCancelWorktreeSetup = useCallback(() => {
- if (!worktreeSetup || !worktreeSetupTarget || worktreeSetup.phase !== "running") return;
+ if (!worktreeSetup || worktreeSetup.phase !== "running") return;
void cancelWorktreeSetup({
- environmentId: worktreeSetupTarget.environmentId,
+ environmentId: routeThreadRef.environmentId,
input: { threadId: worktreeSetup.threadId },
});
- }, [cancelWorktreeSetup, worktreeSetup, worktreeSetupTarget]);
+ }, [cancelWorktreeSetup, routeThreadRef.environmentId, worktreeSetup]);
// The setup terminal belongs to the thread that was set up. A failed
// bootstrap deletes that thread and closes its terminals, so only offer the
// terminal while the setup thread is still the active one.
@@ -7588,17 +7534,6 @@ export default function ChatView(props: ChatViewProps) {
preparingWorktree: Boolean(baseBranchForWorktree),
submissionIntent: resolvedSubmissionIntent,
});
- setWorktreeSetupRef(
- baseBranchForWorktree
- ? { environmentId, threadId: threadIdForSend, ownerKey: worktreeSetupOwnerKey }
- : null,
- );
- if (baseBranchForWorktree) {
- pendingWorktreeSetupByThreadKey.set(
- scopedThreadKey(scopeThreadRef(environmentId, threadIdForSend)),
- { environmentId, threadId: threadIdForSend },
- );
- }
const messageIdForSend = newMessageId();
const messageCreatedAt = new Date().toISOString();
@@ -8692,11 +8627,11 @@ export default function ChatView(props: ChatViewProps) {
// setup (the bootstrap created it), so this keys off the route, not
// `isLocalDraftThread`.
const onWorktreeSetupWorkLocally = useCallback(() => {
- if (!worktreeSetup || !worktreeSetupRef || worktreeSetup.phase !== "running" || !draftId) {
+ if (!worktreeSetup || worktreeSetup.phase !== "running" || !draftId) {
return;
}
const target = {
- environmentId: worktreeSetupRef.environmentId,
+ environmentId: routeThreadRef.environmentId,
input: { threadId: worktreeSetup.threadId },
};
void (async () => {
@@ -8704,7 +8639,7 @@ export default function ChatView(props: ChatViewProps) {
if (result._tag !== "Success" || !result.value.cancelled) return;
setWorkLocallyResendDraftId(draftId);
})();
- }, [cancelWorktreeSetup, draftId, worktreeSetup, worktreeSetupRef]);
+ }, [cancelWorktreeSetup, draftId, routeThreadRef.environmentId, worktreeSetup]);
const onSendRef = useRef(onSend);
onSendRef.current = onSend;
// Resend once the cancelled dispatch has settled and the composer is free.
diff --git a/apps/web/src/session-logic.ts b/apps/web/src/session-logic.ts
index 6a0920681bc..20a5671da85 100644
--- a/apps/web/src/session-logic.ts
+++ b/apps/web/src/session-logic.ts
@@ -468,7 +468,12 @@ export function deriveWorkLogEntries(
}
const entries: DerivedWorkLogEntry[] = [];
for (const activity of foldUserInputActivities(ordered)) {
- if (activity.tone !== "error" && isWorktreeSetupActivity(activity.kind)) continue;
+ if (
+ isWorktreeSetupActivity(activity.kind) &&
+ (activity.tone !== "error" || activity.kind === "worktree-setup")
+ ) {
+ continue;
+ }
if (activity.kind === "tool.started") continue;
// Agent task.started rows are CTA seeds: they carry the true spawn turn,
// which is the batch key (completions of background subagents arrive
diff --git a/packages/client-runtime/src/work-log/presentation.ts b/packages/client-runtime/src/work-log/presentation.ts
index bfb04eda324..48d30fc488d 100644
--- a/packages/client-runtime/src/work-log/presentation.ts
+++ b/packages/client-runtime/src/work-log/presentation.ts
@@ -11,8 +11,17 @@ import { resolveMediaSource } from "@t3tools/client-runtime/media-source";
import { parseChangeRequestUrl } from "@t3tools/shared/changeRequestUrl";
import { isWorkspaceImagePreviewPath } from "@t3tools/shared/filePreview";
+/**
+ * Activities the worktree setup card already represents. The settled record
+ * is rendered by the card on web (and mobile's status row), never as a
+ * worklog entry, so it is hidden from the activity feed even when it failed.
+ */
export function isWorktreeSetupActivity(kind: string): boolean {
- return kind === "setup-script.requested" || kind === "setup-script.started";
+ return (
+ kind === "setup-script.requested" ||
+ kind === "setup-script.started" ||
+ kind === "worktree-setup"
+ );
}
export type WorkLogToolLifecycleStatus = RuntimeItemStatus | "stopped";
diff --git a/packages/contracts/src/orchestration.ts b/packages/contracts/src/orchestration.ts
index f7aaf4fa261..aa2dd54fecb 100644
--- a/packages/contracts/src/orchestration.ts
+++ b/packages/contracts/src/orchestration.ts
@@ -1440,6 +1440,24 @@ const ThreadHistoryImportCommand = Schema.Struct({
).check(Schema.isNonEmpty()),
});
+/**
+ * Persists a user message without starting a turn. Used by worktree bootstraps
+ * so the send is durable while the worktree is still being prepared; the
+ * turn that follows references the same message id.
+ */
+const ThreadMessageUserAppendCommand = Schema.Struct({
+ type: Schema.Literal("thread.message.user.append"),
+ commandId: CommandId,
+ threadId: ThreadId,
+ message: Schema.Struct({
+ messageId: MessageId,
+ text: Schema.String,
+ attachments: Schema.Array(ChatAttachment),
+ context: Schema.optional(OrchestrationMessageContext),
+ }),
+ createdAt: IsoDateTime,
+});
+
const ThreadProposedPlanUpsertCommand = Schema.Struct({
type: Schema.Literal("thread.proposed-plan.upsert"),
commandId: CommandId,
@@ -1537,6 +1555,7 @@ const InternalOrchestrationCommand = Schema.Union([
ThreadMessageAssistantDeltaCommand,
ThreadMessageAssistantCompleteCommand,
ThreadHistoryImportCommand,
+ ThreadMessageUserAppendCommand,
ThreadProposedPlanUpsertCommand,
ThreadTurnDiffCompleteCommand,
ThreadActivityAppendCommand,
@@ -1878,6 +1897,12 @@ export const OrchestrationEventMetadata = Schema.Struct({
requestId: Schema.optional(ApprovalRequestId),
ingestedAt: Schema.optional(IsoDateTime),
historyImport: Schema.optional(Schema.Boolean),
+ /**
+ * The user message was persisted ahead of its turn (worktree bootstrap).
+ * Reactors that key off a user message as "turn is starting" wait for the
+ * turn-start event instead.
+ */
+ deferredTurn: Schema.optional(Schema.Boolean),
origin: Schema.optional(OrchestrationClientOrigin),
});
export type OrchestrationEventMetadata = typeof OrchestrationEventMetadata.Type;
diff --git a/packages/contracts/src/worktreeSetup.ts b/packages/contracts/src/worktreeSetup.ts
index 9f3a9f33be2..19a0795c9ab 100644
--- a/packages/contracts/src/worktreeSetup.ts
+++ b/packages/contracts/src/worktreeSetup.ts
@@ -71,6 +71,17 @@ export const WorktreeSetupSnapshot = Schema.Struct({
});
export type WorktreeSetupSnapshot = typeof WorktreeSetupSnapshot.Type;
+/**
+ * Thread activity that carries a `WorktreeSetupSnapshot` as its payload. The
+ * bootstrap writes it under a fixed id once the thread exists (phase running)
+ * and again when the setup settles, so the projection always holds the
+ * latest known state: a client attaches the live stream while it says
+ * running and renders the outcome from it afterwards, on any device or
+ * after a reload.
+ */
+export const WORKTREE_SETUP_ACTIVITY_KIND = "worktree-setup";
+export const worktreeSetupActivityId = (threadId: ThreadId) => `worktree-setup:${threadId}`;
+
export const WorktreeSetupSubscribeInput = Schema.Struct({
threadId: ThreadId,
});