The best way to control Claude Code, Codex and more from any computer or phone
fix(server): a fork made after Edit from here no longer shows the rewound turns (#34823)
Julius Marminge committed
Nov 11, 2026 at 23:46 UTC
8024e50c6fef20525f5360448cede149fbda460f
2 files changed
+274
-28
apps/server/src/orchestration-v2/ProjectionStore.test.ts
+187
@@ -9006,6 +9006,193 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => {
9006
}),
9007
);
9008
9009
+ it.effect("hides source turns rewound before the fork from a fork's visible items", () =>
9010
+ Effect.gen(function* () {
9011
+ const projectionStore = yield* ProjectionStore.ProjectionStoreV2;
9012
+ const now = yield* DateTime.now;
9013
+ const rewoundAt = DateTime.add(now, { minutes: 1 });
9014
+ const forkedAt = DateTime.add(now, { minutes: 2 });
9015
+ const prefix = "projection-fork-after-rewind";
9016
+ const projectId = ProjectId.make(`project:${prefix}`);
9017
+ const sourceThreadId = ThreadId.make(`thread:${prefix}:source`);
9018
+ const targetThreadId = ThreadId.make(`thread:${prefix}:target`);
9019
+ const sourceProviderThreadId = ProviderThreadId.make(`provider-thread:${prefix}:source`);
9020
+ const runIds = [1, 2, 3].map((ordinal) => RunId.make(`run:${prefix}:${ordinal}`));
9021
+ const nodeIds = [1, 2, 3].map((ordinal) => NodeId.make(`node:${prefix}:${ordinal}`));
9022
+ const threadPayload = (input: {
9023
+ readonly id: ThreadId;
9024
+ readonly forkedFrom: { type: "run"; threadId: ThreadId; runId: RunId } | null;
9025
+ readonly createdAt: DateTime.Utc;
9026
+ }) => ({
9027
+ createdBy: "user" as const,
9028
+ creationSource: "web" as const,
9029
+ id: input.id,
9030
+ projectId,
9031
+ title: input.id,
9032
+ providerInstanceId,
9033
+ modelSelection,
9034
+ runtimeMode: "full-access" as const,
9035
+ interactionMode: "default" as const,
9036
+ branch: null,
9037
+ worktreePath: null,
9038
+ activeProviderThreadId: sourceProviderThreadId,
9039
+ lineage:
9040
+ input.forkedFrom === null
9041
+ ? { parentThreadId: null, relationshipToParent: null, rootThreadId: sourceThreadId }
9042
+ : {
9043
+ parentThreadId: sourceThreadId,
9044
+ relationshipToParent: "fork" as const,
9045
+ rootThreadId: sourceThreadId,
9046
+ },
9047
+ forkedFrom: input.forkedFrom,
9048
+ createdAt: input.createdAt,
9049
+ updatedAt: input.createdAt,
9050
+ archivedAt: null,
9051
+ settledOverride: null,
9052
+ settledAt: null,
9053
+ lastVisitedAt: null,
9054
+ deletedAt: null,
9055
+ });
9056
+ const runPayload = (index: number, status: "completed" | "rolled_back") => ({
9057
+ id: runIds[index]!,
9058
+ threadId: sourceThreadId,
9059
+ ordinal: index + 1,
9060
+ providerInstanceId,
9061
+ modelSelection,
9062
+ providerThreadId: sourceProviderThreadId,
9063
+ userMessageId: MessageId.make(`message:${prefix}:user:${index + 1}`),
9064
+ rootNodeId: nodeIds[index]!,
9065
+ activeAttemptId: null,
9066
+ status,
9067
+ requestedAt: now,
9068
+ startedAt: now,
9069
+ completedAt: status === "rolled_back" ? rewoundAt : now,
9070
+ checkpointId: null,
9071
+ contextHandoffId: null,
9072
+ });
9073
+
9074
+ yield* projectionStore.apply({
9075
+ id: EventId.make(`event:${prefix}:source-thread`),
9076
+ type: "thread.created",
9077
+ threadId: sourceThreadId,
9078
+ occurredAt: now,
9079
+ payload: threadPayload({ id: sourceThreadId, forkedFrom: null, createdAt: now }),
9080
+ });
9081
+ for (const [index, text] of ["one", "two", "three"].entries()) {
9082
+ const runId = runIds[index]!;
9083
+ const nodeId = nodeIds[index]!;
9084
+ const ordinal = index + 1;
9085
+ yield* projectionStore.apply({
9086
+ id: EventId.make(`event:${prefix}:run-${ordinal}`),
9087
+ type: "run.created",
9088
+ threadId: sourceThreadId,
9089
+ runId,
9090
+ nodeId,
9091
+ driver,
9092
+ occurredAt: now,
9093
+ payload: runPayload(index, "completed"),
9094
+ });
9095
+ for (const [offset, role] of (["user", "assistant"] as const).entries()) {
9096
+ const itemBase = {
9097
+ id: TurnItemId.make(`turn-item:${prefix}:${role}:${ordinal}`),
9098
+ threadId: sourceThreadId,
9099
+ runId,
9100
+ nodeId,
9101
+ providerThreadId: sourceProviderThreadId,
9102
+ providerTurnId: null,
9103
+ nativeItemRef: null,
9104
+ parentItemId: null,
9105
+ ordinal: ordinal * 100 + offset,
9106
+ status: "completed" as const,
9107
+ title: null,
9108
+ startedAt: now,
9109
+ completedAt: now,
9110
+ updatedAt: now,
9111
+ messageId: MessageId.make(`message:${prefix}:${role}:${ordinal}`),
9112
+ };
9113
+ yield* projectionStore.apply({
9114
+ id: EventId.make(`event:${prefix}:${role}-item-${ordinal}`),
9115
+ type: "turn-item.updated",
9116
+ threadId: sourceThreadId,
9117
+ runId,
9118
+ nodeId,
9119
+ driver,
9120
+ occurredAt: now,
9121
+ payload:
9122
+ role === "user"
9123
+ ? {
9124
+ ...itemBase,
9125
+ createdBy: "user",
9126
+ creationSource: "web",
9127
+ type: "user_message",
9128
+ inputIntent: "turn_start",
9129
+ text: `prompt ${text}`,
9130
+ attachments: [],
9131
+ }
9132
+ : {
9133
+ ...itemBase,
9134
+ type: "assistant_message",
9135
+ text: `reply ${text}`,
9136
+ streaming: false,
9137
+ },
9138
+ });
9139
+ }
9140
+ // Edit from here on prompt two rewinds run 2 before prompt three is sent.
9141
+ if (ordinal === 2) {
9142
+ yield* projectionStore.apply({
9143
+ id: EventId.make(`event:${prefix}:run-2-rolled-back`),
9144
+ type: "run.updated",
9145
+ threadId: sourceThreadId,
9146
+ runId,
9147
+ nodeId,
9148
+ driver,
9149
+ occurredAt: rewoundAt,
9150
+ payload: runPayload(index, "rolled_back"),
9151
+ });
9152
+ }
9153
+ }
9154
+
9155
+ const forkedFrom = { type: "run" as const, threadId: sourceThreadId, runId: runIds[2]! };
9156
+ yield* projectionStore.apply({
9157
+ id: EventId.make(`event:${prefix}:target-thread`),
9158
+ type: "thread.created",
9159
+ threadId: targetThreadId,
9160
+ occurredAt: forkedAt,
9161
+ payload: threadPayload({ id: targetThreadId, forkedFrom, createdAt: forkedAt }),
9162
+ });
9163
+
9164
+ const visibleTexts = (rows: ReadonlyArray<{ readonly item: OrchestrationV2TurnItem }>) =>
9165
+ rows.map((row) =>
9166
+ row.item.type === "user_message" || row.item.type === "assistant_message"
9167
+ ? row.item.text
9168
+ : row.item.type,
9169
+ );
9170
+ const source = yield* projectionStore.getThreadProjection(sourceThreadId);
9171
+ assert.deepEqual(visibleTexts(source.visibleTurnItems), [
9172
+ "prompt one",
9173
+ "reply one",
9174
+ "prompt three",
9175
+ "reply three",
9176
+ ]);
9177
+ const expected = ["prompt one", "reply one", "prompt three", "reply three", "fork"];
9178
+ const target = yield* projectionStore.getThreadProjection(targetThreadId);
9179
+ assert.deepEqual(visibleTexts(target.visibleTurnItems), expected);
9180
+ const page = yield* projectionStore.getTimelinePage(targetThreadId, {
9181
+ view: "activity",
9182
+ limit: 10,
9183
+ });
9184
+ assert.deepEqual(visibleTexts(page.items), expected);
9185
+ const window = yield* projectionStore.getThreadSnapshotWindow(targetThreadId, {
9186
+ rowLimit: 10,
9187
+ });
9188
+ assert.deepEqual(visibleTexts(window.projection.visibleTurnItems), expected);
9189
+ assert.equal(
9190
+ (yield* projectionStore.getThreadShell(targetThreadId))?.visibleItemCount,
9191
+ expected.length,
9192
+ );
9193
+ }),
9194
+ );
9195
+
9196
it.effect("a pull request watch keeps a finished thread working until it ends", () =>
9197
Effect.gen(function* () {
9198
const store = yield* ProjectionStore.ProjectionStoreV2;
apps/server/src/orchestration-v2/ProjectionStore.ts
+87
-28
@@ -741,6 +741,7 @@ type ProjectionWindow = Omit<
741
"anchorThreadId"
742
> & {
743
readonly suppressLocal?: boolean | undefined;
744
+ readonly forkCreatedAt?: DateTime.Utc | undefined;
745
readonly historyAnchor?: { readonly threadId: ThreadId; readonly itemId: TurnItemId } | undefined;
746
};
747
@@ -1071,6 +1072,12 @@ type ShellRunRow = {
1072
readonly thread_id: string;
1073
readonly run_id: string;
1074
readonly ordinal: number;
1075
+ readonly rolled_back_at: string | null;
1076
+};
1077
+
1078
+type ShellRun = {
1079
+ readonly ordinal: number;
1080
+ readonly rolledBackAt: DateTime.Utc | null;
1081
};
1082
1083
type SettlementThreadRow = Pick<
@@ -1415,16 +1422,40 @@ function isTurnItemAtOrBeforeRun(input: {
1422
return ordinal !== undefined && ordinal <= input.sourceRunOrdinal;
1423
}
1424
1425
+// Rollback stamps completedAt; a fork made after the rewind never received that run.
1426
+function runRolledBackAt(run: Pick<OrchestrationV2Run, "status" | "completedAt">) {
1427
+ return run.status === "rolled_back" ? run.completedAt : null;
1428
+}
1429
+
1430
+function isRolledBackBeforeFork(
1431
+ rolledBackAt: DateTime.Utc | null,
1432
+ forkCreatedAt: DateTime.Utc,
1433
+): boolean {
1434
+ return rolledBackAt !== null && DateTime.isLessThan(rolledBackAt, forkCreatedAt);
1435
+}
1436
+
1437
+function forkInheritedRunOrdinals(
1438
+ runs: ReadonlyArray<OrchestrationV2Run>,
1439
+ forkCreatedAt: DateTime.Utc,
1440
+): Map<RunId, number> {
1441
+ return new Map(
1442
+ runs
1443
+ .filter((run) => !isRolledBackBeforeFork(runRolledBackAt(run), forkCreatedAt))
1444
+ .map((run) => [run.id, run.ordinal]),
1445
+ );
1446
+}
1447
+
1448
function visibleTurnItemsThroughRun(input: {
1449
readonly sourceProjection: OrchestrationV2ThreadProjection;
1450
readonly sourceRunId: NonNullable<OrchestrationV2TurnItem["runId"]>;
1451
+ readonly forkCreatedAt: DateTime.Utc;
1452
}): Array<Omit<OrchestrationV2ProjectedTurnItem, "position">> {
1453
const sourceRun = input.sourceProjection.runs.find((run) => run.id === input.sourceRunId);
1454
if (sourceRun === undefined) {
1455
return [];
1456
}
1457
1427
- const runOrdinalById = new Map(input.sourceProjection.runs.map((run) => [run.id, run.ordinal]));
1458
+ const runOrdinalById = forkInheritedRunOrdinals(input.sourceProjection.runs, input.forkCreatedAt);
1459
const inheritedPrefix = input.sourceProjection.visibleTurnItems
1460
.filter(
1461
(row) => row.item.threadId !== input.sourceProjection.thread.id || row.item.type === "fork",
@@ -1484,6 +1515,7 @@ function buildVisibleTurnItems(input: {
1515
: visibleTurnItemsThroughRun({
1516
sourceProjection: input.sourceProjection,
1517
sourceRunId: forkedFrom.runId,
1518
+ forkCreatedAt: input.projection.thread.createdAt,
1519
});
1520
const markerItem = makeForkMarkerTurnItem({
1521
targetProjection: input.projection,
@@ -1832,7 +1864,7 @@ type ShellThreadState = {
1864
readonly itemCount: number;
1865
readonly runlessItemCount: number;
1866
readonly updatedAt: OrchestrationV2ThreadProjection["updatedAt"];
1835
- readonly runOrdinalById: ReadonlyMap<RunId, number>;
1867
+ readonly runsById: ReadonlyMap<RunId, ShellRun>;
1868
readonly itemCountByRunId: ReadonlyMap<RunId, number>;
1869
};
1870
@@ -1859,16 +1891,21 @@ function shellStatusFromStoredRunStatus(status: string | null): OrchestrationV2S
1891
function itemCountThroughRun(input: {
1892
readonly state: ShellThreadState;
1893
readonly runId: RunId;
1894
+ readonly forkCreatedAt: DateTime.Utc;
1895
}): number {
1863
- const runOrdinal = input.state.runOrdinalById.get(input.runId);
1896
+ const runOrdinal = input.state.runsById.get(input.runId)?.ordinal;
1897
if (runOrdinal === undefined) {
1898
return 0;
1899
}
1900
1901
let count = input.state.thread.historyOrigin === "v1_import" ? input.state.runlessItemCount : 0;
1902
for (const [runId, itemCount] of input.state.itemCountByRunId) {
1870
- const itemRunOrdinal = input.state.runOrdinalById.get(runId);
1871
- if (itemRunOrdinal !== undefined && itemRunOrdinal <= runOrdinal) {
1903
+ const itemRun = input.state.runsById.get(runId);
1904
+ if (
1905
+ itemRun !== undefined &&
1906
+ itemRun.ordinal <= runOrdinal &&
1907
+ !isRolledBackBeforeFork(itemRun.rolledBackAt, input.forkCreatedAt)
1908
+ ) {
1909
count += itemCount;
1910
}
1911
}
@@ -1925,7 +1962,11 @@ function visibleItemCountForShell(input: {
1962
1963
return (
1964
inheritedPrefixCount +
1928
- itemCountThroughRun({ state: sourceState, runId: forkedFrom.runId }) +
1965
+ itemCountThroughRun({
1966
+ state: sourceState,
1967
+ runId: forkedFrom.runId,
1968
+ forkCreatedAt: state.thread.createdAt,
1969
+ }) +
1970
1 +
1971
state.itemCount
1972
);
@@ -3035,12 +3076,23 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
3076
AND json_extract(source_thread.payload_json, '$.historyOrigin') = 'v1_import'
3077
)
3078
)
3038
- OR run.ordinal <= (
3039
- SELECT required_run.ordinal
3040
- FROM orchestration_v2_projection_runs AS required_run
3041
- WHERE required_run.thread_id = item.thread_id
3042
- AND required_run.run_id = ${window.requiredRunId ?? null}
3043
- LIMIT 1
3079
+ OR (
3080
+ run.ordinal <= (
3081
+ SELECT required_run.ordinal
3082
+ FROM orchestration_v2_projection_runs AS required_run
3083
+ WHERE required_run.thread_id = item.thread_id
3084
+ AND required_run.run_id = ${window.requiredRunId ?? null}
3085
+ LIMIT 1
3086
+ )
3087
+ AND NOT COALESCE(
3088
+ run.status = 'rolled_back'
3089
+ AND julianday(run.completed_at) < julianday(${
3090
+ window.forkCreatedAt === undefined
3091
+ ? null
3092
+ : DateTime.formatIso(window.forkCreatedAt)
3093
+ }),
3094
+ 0
3095
+ )
3096
)
3097
)
3098
AND NOT (
@@ -4154,6 +4206,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
4206
userTurnLimit: window.userTurnLimit,
4207
deferWork: window.deferWork,
4208
requiredRunId: forkedFrom.runId,
4209
+ forkCreatedAt: projection.thread.createdAt,
4210
suppressLocal: anchor === undefined || anchorIsInDescendant,
4211
...(anchor === undefined || anchorIsInDescendant
4212
? {}
@@ -6048,7 +6101,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
6101
const sourceRun = source.records.runs.find((run) => run.id === fork.runId);
6102
let inherited: Array<TimelineIndexRow> = [];
6103
if (sourceRun !== undefined) {
6051
- const ordinals = new Map(source.records.runs.map((run) => [run.id, run.ordinal]));
6104
+ const ordinals = forkInheritedRunOrdinals(source.records.runs, records.thread.createdAt);
6105
const sourceItems = source.local.map((row) => row.item);
6106
inherited = [
6107
...source.visible.filter(
@@ -6728,11 +6781,13 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
6781
const selectShellRunRows = (threadIds?: ReadonlyArray<ThreadId>) =>
6782
threadIds === undefined
6783
? sql<ShellRunRow>`
6731
- SELECT thread_id, run_id, ordinal
6784
+ SELECT thread_id, run_id, ordinal,
6785
+ CASE WHEN status = 'rolled_back' THEN completed_at END AS rolled_back_at
6786
FROM orchestration_v2_projection_runs
6787
`
6788
: sql<ShellRunRow>`
6735
- SELECT thread_id, run_id, ordinal
6789
+ SELECT thread_id, run_id, ordinal,
6790
+ CASE WHEN status = 'rolled_back' THEN completed_at END AS rolled_back_at
6791
FROM orchestration_v2_projection_runs
6792
WHERE thread_id IN (SELECT value FROM json_each(${encodeIdList(threadIds)}))
6793
`;
@@ -6809,13 +6864,17 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
6864
readonly runRows: ReadonlyArray<ShellRunRow>;
6865
readonly itemCountRows: ReadonlyArray<ShellRunItemCountRow>;
6866
}) => {
6812
- const runOrdinalsByThreadId = new Map<ThreadId, Map<RunId, number>>();
6867
+ const runsByThreadId = new Map<ThreadId, Map<RunId, ShellRun>>();
6868
for (const row of input.runRows) {
6869
const threadId = ThreadId.make(row.thread_id);
6870
const runId = RunId.make(row.run_id);
6816
- const existing = runOrdinalsByThreadId.get(threadId) ?? new Map<RunId, number>();
6817
- existing.set(runId, row.ordinal);
6818
- runOrdinalsByThreadId.set(threadId, existing);
6871
+ const existing = runsByThreadId.get(threadId) ?? new Map<RunId, ShellRun>();
6872
+ existing.set(runId, {
6873
+ ordinal: row.ordinal,
6874
+ rolledBackAt:
6875
+ row.rolled_back_at === null ? null : DateTime.makeUnsafe(row.rolled_back_at),
6876
+ });
6877
+ runsByThreadId.set(threadId, existing);
6878
}
6879
const itemCountsByThreadId = new Map<ThreadId, Map<RunId, number>>();
6880
for (const row of input.itemCountRows) {
@@ -6825,7 +6884,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
6884
existing.set(runId, row.item_count);
6885
itemCountsByThreadId.set(threadId, existing);
6886
}
6828
- return { runOrdinalsByThreadId, itemCountsByThreadId };
6887
+ return { runsByThreadId, itemCountsByThreadId };
6888
};
6889
6890
const shellItemCountMap = (rows: ReadonlyArray<ShellItemCountRow>) =>
@@ -7096,7 +7155,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
7155
/* Runs once per shell row; the enclosing snapshot or thread read owns the span. */
7156
Effect.fnUntraced(function* (input: {
7157
readonly row: ShellThreadRow;
7099
- readonly runOrdinalsByThreadId: ReadonlyMap<ThreadId, Map<RunId, number>>;
7158
+ readonly runsByThreadId: ReadonlyMap<ThreadId, Map<RunId, ShellRun>>;
7159
readonly itemCountsByThreadId: ReadonlyMap<ThreadId, Map<RunId, number>>;
7160
readonly shellItemCountsByThreadId: ReadonlyMap<
7161
ThreadId,
@@ -7113,7 +7172,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
7172
}) {
7173
const {
7174
row,
7116
- runOrdinalsByThreadId,
7175
+ runsByThreadId,
7176
itemCountsByThreadId,
7177
shellItemCountsByThreadId,
7178
providerThreadsByThreadId,
@@ -7279,7 +7338,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
7338
itemCount: shellItemCountsByThreadId.get(thread.id)?.itemCount ?? 0,
7339
runlessItemCount: shellItemCountsByThreadId.get(thread.id)?.runlessItemCount ?? 0,
7340
updatedAt: thread.updatedAt,
7282
- runOrdinalById: runOrdinalsByThreadId.get(ThreadId.make(row.thread_id)) ?? new Map(),
7341
+ runsById: runsByThreadId.get(ThreadId.make(row.thread_id)) ?? new Map(),
7342
itemCountByRunId: itemCountsByThreadId.get(ThreadId.make(row.thread_id)) ?? new Map(),
7343
} satisfies ShellThreadState;
7344
});
@@ -7368,7 +7427,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
7427
providerThreadRows,
7428
pendingTurnItemRows,
7429
}: Effect.Success<ReturnType<typeof readShellSnapshotRows>>) {
7371
- const { runOrdinalsByThreadId, itemCountsByThreadId } = runMapsByThreadId({
7430
+ const { runsByThreadId, itemCountsByThreadId } = runMapsByThreadId({
7431
runRows,
7432
itemCountRows,
7433
});
@@ -7378,7 +7437,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
7437
const states = yield* Effect.forEach(threadRows, (row) =>
7438
shellThreadStateFromRow({
7439
row,
7381
- runOrdinalsByThreadId,
7440
+ runsByThreadId,
7441
itemCountsByThreadId,
7442
shellItemCountsByThreadId,
7443
providerThreadsByThreadId,
@@ -7484,7 +7543,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
7543
shellThreadStateFromRow({
7544
row,
7545
// Awareness never consumes timeline counts or inherited fork history.
7487
- runOrdinalsByThreadId: new Map(),
7546
+ runsByThreadId: new Map(),
7547
itemCountsByThreadId: new Map(),
7548
shellItemCountsByThreadId: new Map(),
7549
providerThreadsByThreadId,
@@ -7775,7 +7834,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
7834
),
7835
),
7836
]);
7778
- const { runOrdinalsByThreadId, itemCountsByThreadId } = runMapsByThreadId({
7837
+ const { runsByThreadId, itemCountsByThreadId } = runMapsByThreadId({
7838
runRows,
7839
itemCountRows,
7840
});
@@ -7786,7 +7845,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
7845
const states = yield* Effect.forEach([...rowsByThreadId.values()], (row) =>
7846
shellThreadStateFromRow({
7847
row,
7789
- runOrdinalsByThreadId,
7848
+ runsByThreadId,
7849
itemCountsByThreadId,
7850
shellItemCountsByThreadId,
7851
providerThreadsByThreadId,