Skip to content

Commit 48713fc

Browse files
feat(server): persist the worktree setup send and progress on the thread
A worktree bootstrap kept the user's message and the setup progress only in the sending client's component state and an in-memory tracker. Reloading, navigating away, opening the thread from another device, or a server restart mid-setup landed on an empty "Send a message" thread; the tracker also ran as a child of the RPC fiber, so a dropped socket abandoned the half-built worktree without ever starting the turn. The bootstrap now persists the message right after thread.create through a new internal thread.message.user.append command, and records the setup snapshot as a worktree-setup activity (running at start, settled at the end) under a fixed id. thread.turn.start recognizes the pre-persisted message and only emits the turn request. The bootstrap fiber is detached from the connection. The web client drops its owner-key and handoff bookkeeping and derives the card from the route thread id, the recorded activity, and the live stream; the draft route promotes as soon as the message is persisted. Mobile shows the preparing state from the projection for threads opened elsewhere. Co-Authored-By: Claude Fable 5 <[email protected]>
1 parent a62e7d6 commit 48713fc

15 files changed

Lines changed: 722 additions & 162 deletions

File tree

‎apps/mobile/src/features/threads/ThreadRouteScreen.tsx‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -782,9 +782,20 @@ function ThreadRouteContent(
782782
}),
783783
);
784784
}, [navigation, routeThreadIdentity, selectedThreadCreation, selectedThreadProject]);
785+
// A worktree bootstrap persists the user message before its turn, so a
786+
// thread opened from another device (or after a restart) shows the same
787+
// preparing state the sending client does.
788+
const awaitingBootstrapTurn = useMemo(
789+
() =>
790+
selectedThreadDetail !== null &&
791+
selectedThreadDetail.latestTurn === null &&
792+
selectedThreadDetail.session === null &&
793+
selectedThreadDetail.messages.some((message) => message.role === "user"),
794+
[selectedThreadDetail],
795+
);
785796
const creationState = ((): ThreadDetailScreenProps["creationState"] => {
786797
if (selectedThreadCreation === null) {
787-
return null;
798+
return awaitingBootstrapTurn ? { kind: "preparing", preparingWorktree: true } : null;
788799
}
789800
if (selectedThreadCreation.outcome?.kind === "failed") {
790801
return {

‎apps/mobile/src/lib/threadActivity.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -411,7 +411,12 @@ function deriveWorkLogEntries(
411411
const ordered = Arr.sort(activities, activityOrder);
412412
const entries: DerivedWorkLogEntry[] = [];
413413
for (const activity of foldUserInputActivities(ordered)) {
414-
if (activity.tone !== "error" && isWorktreeSetupActivity(activity.kind)) continue;
414+
if (
415+
isWorktreeSetupActivity(activity.kind) &&
416+
(activity.tone !== "error" || activity.kind === "worktree-setup")
417+
) {
418+
continue;
419+
}
415420
if (activity.kind === "tool.started") continue;
416421
// Like web: an agent's task.started row anchors its batch. It has a fixed
417422
// id and timestamp, unlike progress ticks, whose stable per-task id is

‎apps/server/src/orchestration/Layers/CheckpointReactor.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -630,8 +630,12 @@ const make = Effect.gen(function* () {
630630
>,
631631
) {
632632
if (event.type === "thread.message-sent") {
633+
// A bootstrap message lands before the worktree exists; its baseline
634+
// would snapshot the project checkout. The turn-start event that
635+
// follows captures it against the right cwd.
633636
if (
634637
event.metadata.historyImport === true ||
638+
event.metadata.deferredTurn === true ||
635639
event.payload.role !== "user" ||
636640
event.payload.streaming ||
637641
event.payload.turnId !== null

‎apps/server/src/orchestration/decider.ts‎

Lines changed: 78 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1390,35 +1390,47 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
13901390
detail: `Proposed plan '${sourceProposedPlan?.planId}' belongs to thread '${sourceThread.id}' in a different project.`,
13911391
});
13921392
}
1393-
const userMessageEvent: Omit<OrchestrationEvent, "sequence"> = {
1394-
...(yield* withEventBase({
1395-
aggregateKind: "thread",
1396-
aggregateId: command.threadId,
1397-
occurredAt: command.createdAt,
1398-
commandId: command.commandId,
1399-
})),
1400-
type: "thread.message-sent",
1401-
payload: {
1402-
threadId: command.threadId,
1403-
messageId: command.message.messageId,
1404-
role: "user",
1405-
text: command.message.text,
1406-
attachments: command.message.attachments,
1407-
...(command.message.context !== undefined ? { context: command.message.context } : {}),
1408-
turnId: null,
1409-
streaming: false,
1410-
createdAt: command.createdAt,
1411-
updatedAt: command.createdAt,
1412-
},
1413-
};
1393+
// A worktree bootstrap persists the message ahead of the turn with
1394+
// `thread.message.user.append`; the turn then only references it.
1395+
const persistedUserMessage = targetThread.messages.find(
1396+
(message) =>
1397+
message.id === command.message.messageId &&
1398+
message.role === "user" &&
1399+
message.turnId === null,
1400+
);
1401+
const userMessageEvent: Omit<OrchestrationEvent, "sequence"> | null = persistedUserMessage
1402+
? null
1403+
: {
1404+
...(yield* withEventBase({
1405+
aggregateKind: "thread",
1406+
aggregateId: command.threadId,
1407+
occurredAt: command.createdAt,
1408+
commandId: command.commandId,
1409+
})),
1410+
type: "thread.message-sent",
1411+
payload: {
1412+
threadId: command.threadId,
1413+
messageId: command.message.messageId,
1414+
role: "user",
1415+
text: command.message.text,
1416+
attachments: command.message.attachments,
1417+
...(command.message.context !== undefined
1418+
? { context: command.message.context }
1419+
: {}),
1420+
turnId: null,
1421+
streaming: false,
1422+
createdAt: command.createdAt,
1423+
updatedAt: command.createdAt,
1424+
},
1425+
};
14141426
const turnStartRequestedEvent: Omit<OrchestrationEvent, "sequence"> = {
14151427
...(yield* withEventBase({
14161428
aggregateKind: "thread",
14171429
aggregateId: command.threadId,
14181430
occurredAt: command.createdAt,
14191431
commandId: command.commandId,
14201432
})),
1421-
causationEventId: userMessageEvent.eventId,
1433+
...(userMessageEvent ? { causationEventId: userMessageEvent.eventId } : {}),
14221434
type: "thread.turn-start-requested",
14231435
payload: {
14241436
threadId: command.threadId,
@@ -1471,7 +1483,50 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
14711483
},
14721484
});
14731485
}
1474-
return [...lifecycleResetEvents, userMessageEvent, turnStartRequestedEvent];
1486+
return [
1487+
...lifecycleResetEvents,
1488+
...(userMessageEvent ? [userMessageEvent] : []),
1489+
turnStartRequestedEvent,
1490+
];
1491+
}
1492+
1493+
case "thread.message.user.append": {
1494+
if (isImportedAgentSessionMessageId(command.message.messageId)) {
1495+
return yield* new OrchestrationCommandInvariantError({
1496+
commandType: command.type,
1497+
detail: `Message id '${command.message.messageId}' uses the reserved imported-session namespace.`,
1498+
});
1499+
}
1500+
const thread = yield* requireThread({
1501+
readModel,
1502+
command,
1503+
threadId: command.threadId,
1504+
});
1505+
if (thread.messages.some((message) => message.id === command.message.messageId)) {
1506+
return [];
1507+
}
1508+
return {
1509+
...(yield* withEventBase({
1510+
aggregateKind: "thread",
1511+
aggregateId: command.threadId,
1512+
occurredAt: command.createdAt,
1513+
commandId: command.commandId,
1514+
metadata: { deferredTurn: true },
1515+
})),
1516+
type: "thread.message-sent",
1517+
payload: {
1518+
threadId: command.threadId,
1519+
messageId: command.message.messageId,
1520+
role: "user",
1521+
text: command.message.text,
1522+
attachments: command.message.attachments,
1523+
...(command.message.context !== undefined ? { context: command.message.context } : {}),
1524+
turnId: null,
1525+
streaming: false,
1526+
createdAt: command.createdAt,
1527+
updatedAt: command.createdAt,
1528+
},
1529+
};
14751530
}
14761531

14771532
case "thread.turn.interrupt": {
Lines changed: 137 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,137 @@
1+
import * as NodeServices from "@effect/platform-node/NodeServices";
2+
import { expect, it } from "@effect/vitest";
3+
import {
4+
CommandId,
5+
EventId,
6+
MessageId,
7+
ProjectId,
8+
ProviderInstanceId,
9+
ThreadId,
10+
} from "@t3tools/contracts";
11+
import * as Effect from "effect/Effect";
12+
13+
import { decideOrchestrationCommand } from "./decider.ts";
14+
import { createEmptyReadModel, projectEvent } from "./projector.ts";
15+
16+
const createdAt = "2026-08-24T10:00:00.000Z";
17+
const projectId = ProjectId.make("project-1");
18+
const threadId = ThreadId.make("thread-bootstrap");
19+
const messageId = MessageId.make("message-bootstrap");
20+
21+
const readModelWithThread = Effect.gen(function* () {
22+
const withProject = yield* projectEvent(createEmptyReadModel(createdAt), {
23+
sequence: 1,
24+
eventId: EventId.make("event-project-created"),
25+
aggregateKind: "project",
26+
aggregateId: projectId,
27+
type: "project.created",
28+
occurredAt: createdAt,
29+
commandId: CommandId.make("command-project-created"),
30+
causationEventId: null,
31+
correlationId: CommandId.make("command-project-created"),
32+
metadata: {},
33+
payload: {
34+
projectId,
35+
title: "Project",
36+
workspaceRoot: "/tmp/project",
37+
defaultModelSelection: null,
38+
scripts: [],
39+
createdAt,
40+
updatedAt: createdAt,
41+
},
42+
});
43+
return yield* projectEvent(withProject, {
44+
sequence: 2,
45+
eventId: EventId.make("event-thread-created"),
46+
aggregateKind: "thread",
47+
aggregateId: threadId,
48+
type: "thread.created",
49+
occurredAt: createdAt,
50+
commandId: CommandId.make("command-thread-created"),
51+
causationEventId: null,
52+
correlationId: CommandId.make("command-thread-created"),
53+
metadata: {},
54+
payload: {
55+
threadId,
56+
projectId,
57+
title: "Bootstrap thread",
58+
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" },
59+
runtimeMode: "full-access",
60+
interactionMode: "default",
61+
branch: null,
62+
worktreePath: null,
63+
createdAt,
64+
updatedAt: createdAt,
65+
},
66+
});
67+
});
68+
69+
const appendCommand = {
70+
type: "thread.message.user.append" as const,
71+
commandId: CommandId.make("command-append"),
72+
threadId,
73+
message: { messageId, text: "Build it", attachments: [] },
74+
createdAt,
75+
};
76+
77+
const turnStartCommand = {
78+
type: "thread.turn.start" as const,
79+
commandId: CommandId.make("command-turn-start"),
80+
threadId,
81+
message: { messageId, role: "user" as const, text: "Build it", attachments: [] },
82+
runtimeMode: "full-access" as const,
83+
interactionMode: "default" as const,
84+
createdAt,
85+
};
86+
87+
it.layer(NodeServices.layer)("thread.message.user.append", (it) => {
88+
it.effect("persists a user message without a turn, tagged as deferred", () =>
89+
Effect.gen(function* () {
90+
const readModel = yield* readModelWithThread;
91+
const planned = yield* decideOrchestrationCommand({ command: appendCommand, readModel });
92+
const events = Array.isArray(planned) ? planned : [planned];
93+
expect(events.map((event) => event.type)).toEqual(["thread.message-sent"]);
94+
expect(events[0]?.metadata.deferredTurn).toBe(true);
95+
expect(events[0]?.payload).toMatchObject({ messageId, role: "user", turnId: null });
96+
}),
97+
);
98+
99+
it.effect("is idempotent for an already persisted message id", () =>
100+
Effect.gen(function* () {
101+
const readModel = yield* readModelWithThread;
102+
const first = yield* decideOrchestrationCommand({ command: appendCommand, readModel });
103+
const firstEvent = Array.isArray(first) ? first[0]! : first;
104+
const withMessage = yield* projectEvent(readModel, { ...firstEvent, sequence: 3 });
105+
const again = yield* decideOrchestrationCommand({
106+
command: appendCommand,
107+
readModel: withMessage,
108+
});
109+
expect(again).toEqual([]);
110+
}),
111+
);
112+
113+
it.effect("lets the following turn start reference the message instead of re-sending it", () =>
114+
Effect.gen(function* () {
115+
const readModel = yield* readModelWithThread;
116+
const appended = yield* decideOrchestrationCommand({ command: appendCommand, readModel });
117+
const appendedEvent = Array.isArray(appended) ? appended[0]! : appended;
118+
const withMessage = yield* projectEvent(readModel, { ...appendedEvent, sequence: 3 });
119+
120+
const planned = yield* decideOrchestrationCommand({
121+
command: turnStartCommand,
122+
readModel: withMessage,
123+
});
124+
const events = Array.isArray(planned) ? planned : [planned];
125+
expect(events.map((event) => event.type)).toEqual(["thread.turn-start-requested"]);
126+
expect(events[0]?.payload).toMatchObject({ messageId });
127+
128+
// Without the append the turn start still carries the message itself.
129+
const direct = yield* decideOrchestrationCommand({ command: turnStartCommand, readModel });
130+
const directEvents = Array.isArray(direct) ? direct : [direct];
131+
expect(directEvents.map((event) => event.type)).toEqual([
132+
"thread.message-sent",
133+
"thread.turn-start-requested",
134+
]);
135+
}),
136+
);
137+
});

‎apps/server/src/project/WorktreeSetupTracker.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -63,11 +63,12 @@ export class WorktreeSetupTracker extends Context.Service<
6363
stageId: WorktreeSetupStageId,
6464
line: string,
6565
) => Effect.Effect<void>;
66+
/** Returns the settled snapshot, or null when nothing was tracked. */
6667
readonly finish: (
6768
threadId: ThreadId,
6869
phase: "done" | "failed" | "cancelled",
6970
error?: string | null,
70-
) => Effect.Effect<void>;
71+
) => Effect.Effect<WorktreeSetupSnapshot | null>;
7172
/**
7273
* Drops the cancel handle. Called right before the turn is dispatched so a
7374
* late cancel cannot roll back a thread whose agent has already started.
@@ -279,7 +280,7 @@ export const make = Effect.gen(function* () {
279280
),
280281
},
281282
}));
282-
if (!snapshot) return;
283+
if (!snapshot) return null;
283284
yield* clearRetention(threadId);
284285
const fiber = yield* remove(threadId).pipe(
285286
Effect.delay(FINISHED_RETENTION),
@@ -292,6 +293,7 @@ export const make = Effect.gen(function* () {
292293
Effect.forkDetach,
293294
);
294295
retentionFibers.set(threadId, fiber);
296+
return snapshot;
295297
});
296298

297299
const markUncancellable: WorktreeSetupTracker["Service"]["markUncancellable"] = (threadId) =>

0 commit comments

Comments
 (0)