Skip to content

Commit 2c19283

Browse files
feat(server): persist the worktree setup send and progress on the thread (pingdotgg#11852)
Co-authored-by: Claude Fable 5 <[email protected]>
1 parent 26b8f98 commit 2c19283

29 files changed

Lines changed: 1200 additions & 207 deletions

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

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -782,9 +782,26 @@ function ThreadRouteContent(
782782
}),
783783
);
784784
}, [navigation, routeThreadIdentity, selectedThreadCreation, selectedThreadProject]);
785+
// A worktree bootstrap records a running setup on the thread before its
786+
// turn, so a thread opened from another device (or after a restart) shows
787+
// the same preparing state the sending client does. A starting session is
788+
// not enough on its own: an ordinary first turn projects one too.
789+
const awaitingBootstrapTurn = useMemo(
790+
() =>
791+
selectedThreadDetail !== null &&
792+
selectedThreadDetail.latestTurn === null &&
793+
selectedThreadDetail.activities.some(
794+
(activity) =>
795+
activity.kind === "worktree-setup" &&
796+
typeof activity.payload === "object" &&
797+
activity.payload !== null &&
798+
(activity.payload as { phase?: unknown }).phase === "running",
799+
),
800+
[selectedThreadDetail],
801+
);
785802
const creationState = ((): ThreadDetailScreenProps["creationState"] => {
786803
if (selectedThreadCreation === null) {
787-
return null;
804+
return awaitingBootstrapTurn ? { kind: "preparing", preparingWorktree: true } : null;
788805
}
789806
if (selectedThreadCreation.outcome?.kind === "failed") {
790807
return {

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -411,6 +411,7 @@ function deriveWorkLogEntries(
411411
const ordered = Arr.sort(activities, activityOrder);
412412
const entries: DerivedWorkLogEntry[] = [];
413413
for (const activity of foldUserInputActivities(ordered)) {
414+
// Mobile has no setup card, so a failed setup surfaces as an error row.
414415
if (activity.tone !== "error" && isWorktreeSetupActivity(activity.kind)) continue;
415416
if (activity.kind === "tool.started") continue;
416417
// Like web: an agent's task.started row anchors its batch. It has a fixed

‎apps/server/src/checkpointing/CheckpointDiffQuery.test.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,7 @@ describe("CheckpointDiffQuery.layer", () => {
7676
Layer.provideMerge(
7777
Layer.succeed(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
7878
getUserInputActivity: () => Effect.die("unused"),
79+
listActivitiesByKind: () => Effect.die("unused"),
7980
getCommandReadModel: () =>
8081
Effect.die("CheckpointDiffQuery should not request the command read model"),
8182
getSnapshot: () =>
@@ -191,6 +192,7 @@ describe("CheckpointDiffQuery.layer", () => {
191192
Layer.provideMerge(
192193
Layer.succeed(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
193194
getUserInputActivity: () => Effect.die("unused"),
195+
listActivitiesByKind: () => Effect.die("unused"),
194196
getCommandReadModel: () =>
195197
Effect.die("CheckpointDiffQuery should not request the command read model"),
196198
getSnapshot: () =>
@@ -281,6 +283,7 @@ describe("CheckpointDiffQuery.layer", () => {
281283
Layer.provideMerge(
282284
Layer.succeed(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
283285
getUserInputActivity: () => Effect.die("unused"),
286+
listActivitiesByKind: () => Effect.die("unused"),
284287
getCommandReadModel: () =>
285288
Effect.die("CheckpointDiffQuery should not request the command read model"),
286289
getSnapshot: () =>
@@ -356,6 +359,7 @@ describe("CheckpointDiffQuery.layer", () => {
356359
Layer.provideMerge(
357360
Layer.succeed(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
358361
getUserInputActivity: () => Effect.die("unused"),
362+
listActivitiesByKind: () => Effect.die("unused"),
359363
getCommandReadModel: () =>
360364
Effect.die("CheckpointDiffQuery should not request the command read model"),
361365
getSnapshot: () =>
@@ -416,6 +420,7 @@ describe("CheckpointDiffQuery.layer", () => {
416420
Layer.provideMerge(
417421
Layer.succeed(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
418422
getUserInputActivity: () => Effect.die("unused"),
423+
listActivitiesByKind: () => Effect.die("unused"),
419424
getCommandReadModel: () =>
420425
Effect.die("CheckpointDiffQuery should not request the command read model"),
421426
getSnapshot: () =>

‎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/Layers/OrchestrationEngine.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -420,6 +420,7 @@ describe("OrchestrationEngine", () => {
420420
Layer.provide(
421421
Layer.succeed(ProjectionSnapshotQuery, {
422422
getUserInputActivity: () => Effect.die("unused"),
423+
listActivitiesByKind: () => Effect.die("unused"),
423424
getCommandReadModel: () => Effect.succeed(commandReadModel),
424425
getSnapshot: () =>
425426
Effect.sync(() => {

‎apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts‎

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3466,3 +3466,51 @@ it.effect("omits foreign-host PRs from legacy snapshots while preserving native
34663466
}
34673467
}).pipe(Effect.provide(layer));
34683468
});
3469+
3470+
projectionSnapshotLayer("ProjectionSnapshotQuery activities by kind", (it) => {
3471+
it.effect("lists one kind across active threads only, without hydrating the threads", () =>
3472+
Effect.gen(function* () {
3473+
const query = yield* ProjectionSnapshotQuery;
3474+
const sql = yield* SqlClient.SqlClient;
3475+
const timestamp = "2026-03-02T00:00:00.000Z";
3476+
yield* sql`
3477+
INSERT INTO projection_projects (
3478+
project_id, title, workspace_root, scripts_json, created_at, updated_at
3479+
) VALUES ('project-kinds', 'Project', '/tmp/project-kinds', '[]', ${timestamp}, ${timestamp})
3480+
`;
3481+
yield* sql`
3482+
INSERT INTO projection_threads (
3483+
thread_id, project_id, title, model_selection_json, runtime_mode, interaction_mode,
3484+
created_at, updated_at, deleted_at
3485+
) VALUES
3486+
('thread-live', 'project-kinds', 'Live', '{"instanceId":"codex","model":"gpt-5"}',
3487+
'full-access', 'default', ${timestamp}, ${timestamp}, NULL),
3488+
('thread-gone', 'project-kinds', 'Gone', '{"instanceId":"codex","model":"gpt-5"}',
3489+
'full-access', 'default', ${timestamp}, ${timestamp}, ${timestamp}),
3490+
('thread-shelved', 'project-kinds', 'Shelved', '{"instanceId":"codex","model":"gpt-5"}',
3491+
'full-access', 'default', ${timestamp}, ${timestamp}, NULL)
3492+
`;
3493+
yield* sql`UPDATE projection_threads SET archived_at = ${timestamp} WHERE thread_id = 'thread-shelved'`;
3494+
yield* sql`
3495+
INSERT INTO projection_thread_activities (
3496+
activity_id, thread_id, turn_id, tone, kind, summary, payload_json, created_at
3497+
) VALUES
3498+
('setup-live', 'thread-live', NULL, 'info', 'worktree-setup', 'Setting up',
3499+
'{"phase":"running"}', ${timestamp}),
3500+
('other-live', 'thread-live', NULL, 'info', 'tool.completed', 'Other',
3501+
'{}', ${timestamp}),
3502+
('setup-gone', 'thread-gone', NULL, 'info', 'worktree-setup', 'Setting up',
3503+
'{"phase":"running"}', ${timestamp}),
3504+
('setup-shelved', 'thread-shelved', NULL, 'info', 'worktree-setup', 'Setting up',
3505+
'{"phase":"running"}', ${timestamp})
3506+
`;
3507+
3508+
const setups = yield* query.listActivitiesByKind("worktree-setup");
3509+
assert.deepEqual(
3510+
setups.map((activity) => [activity.id, activity.kind, activity.payload]),
3511+
[["setup-live", "worktree-setup", { phase: "running" }]],
3512+
);
3513+
assert.deepEqual(yield* query.listActivitiesByKind("nope"), []);
3514+
}),
3515+
);
3516+
});

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

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1450,6 +1450,40 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
14501450
),
14511451
);
14521452

1453+
const listActivityRowsByKind = SqlSchema.findAll({
1454+
Request: Schema.Struct({ kind: Schema.String }),
1455+
Result: ProjectionThreadActivityDbRowSchema,
1456+
execute: ({ kind }) => sql`
1457+
SELECT
1458+
a.activity_id AS "activityId",
1459+
a.thread_id AS "threadId",
1460+
a.turn_id AS "turnId",
1461+
a.tone,
1462+
a.kind,
1463+
a.summary,
1464+
a.payload_json AS "payload",
1465+
a.sequence,
1466+
a.created_at AS "createdAt"
1467+
FROM projection_thread_activities a
1468+
JOIN projection_threads t ON t.thread_id = a.thread_id
1469+
WHERE a.kind = ${kind}
1470+
AND t.deleted_at IS NULL
1471+
AND t.archived_at IS NULL
1472+
ORDER BY a.created_at ASC, a.activity_id ASC
1473+
`,
1474+
});
1475+
1476+
const listActivitiesByKind: ProjectionSnapshotQueryShape["listActivitiesByKind"] = (kind) =>
1477+
listActivityRowsByKind({ kind }).pipe(
1478+
Effect.map((rows) => rows.map(mapThreadActivityRow)),
1479+
Effect.mapError(
1480+
toPersistenceSqlOrDecodeError(
1481+
"ProjectionSnapshotQuery.listActivitiesByKind:query",
1482+
"ProjectionSnapshotQuery.listActivitiesByKind:decodeRow",
1483+
),
1484+
),
1485+
);
1486+
14531487
const listThreadActivityIdsByThread = SqlSchema.findAll({
14541488
Request: ThreadIdLookupInput,
14551489
Result: ProjectionThreadActivityIdRowSchema,
@@ -3692,6 +3726,7 @@ pending_approval_requests AS (
36923726
return {
36933727
getCommandReadModel,
36943728
getUserInputActivity,
3729+
listActivitiesByKind,
36953730
getSnapshot,
36963731
getShellSnapshot,
36973732
getArchivedShellSnapshot,

‎apps/server/src/orchestration/Services/ProjectionSnapshotQuery.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,15 @@ export interface ProjectionSnapshotQueryShape {
8383
readonly requestId: ApprovalRequestId;
8484
}) => Effect.Effect<Option.Option<OrchestrationThreadActivity>, ProjectionRepositoryError>;
8585

86+
/**
87+
* Read every activity of one kind across active (not deleted, not archived)
88+
* threads, without hydrating the threads. Used at startup to find state a
89+
* crashed process left behind.
90+
*/
91+
readonly listActivitiesByKind: (
92+
kind: string,
93+
) => Effect.Effect<ReadonlyArray<OrchestrationThreadActivity>, ProjectionRepositoryError>;
94+
8695
/**
8796
* Read the lightweight command snapshot used to bootstrap the in-memory
8897
* orchestration engine without hydrating message/activity/checkpoint bodies.

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

Lines changed: 81 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,53 @@ 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 yield* new OrchestrationCommandInvariantError({
1507+
commandType: command.type,
1508+
detail: `Message '${command.message.messageId}' already exists on thread '${command.threadId}'.`,
1509+
});
1510+
}
1511+
return {
1512+
...(yield* withEventBase({
1513+
aggregateKind: "thread",
1514+
aggregateId: command.threadId,
1515+
occurredAt: command.createdAt,
1516+
commandId: command.commandId,
1517+
metadata: { deferredTurn: true },
1518+
})),
1519+
type: "thread.message-sent",
1520+
payload: {
1521+
threadId: command.threadId,
1522+
messageId: command.message.messageId,
1523+
role: "user",
1524+
text: command.message.text,
1525+
attachments: command.message.attachments,
1526+
...(command.message.context !== undefined ? { context: command.message.context } : {}),
1527+
turnId: null,
1528+
streaming: false,
1529+
createdAt: command.createdAt,
1530+
updatedAt: command.createdAt,
1531+
},
1532+
};
14751533
}
14761534

14771535
case "thread.turn.interrupt": {

0 commit comments

Comments
 (0)