The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 22, 22:00 UTC
fix(pi): fork and revert past turns whose session entry was never captured (#20521)
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com> Co-authored-by: Julius Marminge <julius0216@outlook.com>
Henry Chu committed
Oct 20, 2026 at 01:15 UTC
8c8e187d01789af005afbe4e090870bca7f7a358
2 files changed
+327
-31
packages/provider-pi/src/server/adapter.test.ts
+209
@@ -72,6 +72,71 @@ const FAKE_SESSION_FILE = "/fake/.pi/agent/sessions/--workspace--/0001_abc.jsonl
72
/** Deliberately outside the valid pid range so a group-kill can never land. */
73
const FAKE_PID = 999_999_999;
74
75
+const at = (seconds: number) => DateTime.makeUnsafe(seconds * 1000);
76
+
77
+const sessionMessage = (
78
+ id: string,
79
+ parentId: string | null,
80
+ role: "user" | "assistant",
81
+ seconds: number,
82
+) => ({
83
+ type: "message",
84
+ id,
85
+ parentId,
86
+ timestamp: DateTime.formatIso(at(seconds)),
87
+ message: { role, content: [] },
88
+});
89
+
90
+const TURN_ONE_ENTRIES = [
91
+ sessionMessage("u1", null, "user", 10),
92
+ sessionMessage("a1", "u1", "assistant", 20),
93
+ sessionMessage("steer1", "a1", "user", 30),
94
+ sessionMessage("a1b", "steer1", "assistant", 40),
95
+];
96
+const UNCAPTURED_TURN_TREE = {
97
+ entries: [
98
+ ...TURN_ONE_ENTRIES,
99
+ sessionMessage("u2", "a1b", "user", 110),
100
+ sessionMessage("a2", "u2", "assistant", 120),
101
+ sessionMessage("steer2", "a2", "user", 130),
102
+ sessionMessage("a2b", "steer2", "assistant", 140),
103
+ ],
104
+ leafId: "a2b",
105
+};
106
+
107
+function uncapturedTurns(
108
+ providerThreadId: ProviderThreadId,
109
+ window = { startedAt: 150, completedAt: 200 },
110
+): ReadonlyArray<OrchestrationV2ProviderTurn> {
111
+ const turn = (
112
+ ordinal: number,
113
+ nativeTurnRef: OrchestrationV2ProviderTurn["nativeTurnRef"],
114
+ status: OrchestrationV2ProviderTurn["status"],
115
+ startedAt: number,
116
+ completedAt: number,
117
+ ): OrchestrationV2ProviderTurn => ({
118
+ id: ProviderTurnId.make(`turn-${ordinal}`),
119
+ providerThreadId,
120
+ nodeId: NodeId.make(`node-${ordinal}`),
121
+ runAttemptId: null,
122
+ nativeTurnRef,
123
+ ordinal,
124
+ status,
125
+ startedAt: at(startedAt),
126
+ completedAt: at(completedAt),
127
+ });
128
+ return [
129
+ turn(1, { driver: PI_PROVIDER, nativeId: "u1", strength: "strong" }, "completed", 0, 50),
130
+ turn(
131
+ 2,
132
+ { driver: PI_PROVIDER, nativeId: "synthetic-2", strength: "weak" },
133
+ "cancelled",
134
+ window.startedAt,
135
+ window.completedAt,
136
+ ),
137
+ ];
138
+}
139
+
140
const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
141
runtimeMode: "full-access",
142
interactionMode: "default",
@@ -1902,6 +1967,50 @@ describe("PiAdapterV2", () => {
1967
}).pipe(Effect.scoped, Effect.provide(layerTest)),
1968
);
1969
1970
+ it.effect("natively forks before a turn whose start entry was never captured", () =>
1971
+ Effect.gen(function* () {
1972
+ const fake = yield* makeFakePi;
1973
+ const forkFake = yield* makeFakePi;
1974
+ const forkFile = "/fake/forked.jsonl";
1975
+ const { runtime } = yield* openRuntime(fake, "default", THREAD_ID, SESSION_ID, forkFake);
1976
+ const source = yield* runtime.ensureThread({
1977
+ threadId: THREAD_ID,
1978
+ modelSelection: modelSelection("default"),
1979
+ runtimePolicy,
1980
+ });
1981
+ const forkAtFirst = (turns: ReadonlyArray<OrchestrationV2ProviderTurn>) =>
1982
+ runtime.forkThread({
1983
+ sourceProviderThread: source,
1984
+ sourceProviderTurns: turns,
1985
+ providerTurnId: turns[0]!.id,
1986
+ targetThreadId: ThreadId.make("fork-target"),
1987
+ });
1988
+ const forkedEntries = () =>
1989
+ forkFake
1990
+ .allRequests()
1991
+ .filter((request) => request.type === "fork")
1992
+ .map((request) => request.entryId);
1993
+
1994
+ // A later prompt cannot stand in for a cancelled turn that ended before it landed.
1995
+ forkFake.queueEntries(UNCAPTURED_TURN_TREE);
1996
+ const unresolved = yield* forkAtFirst(
1997
+ uncapturedTurns(source.id, { startedAt: 60, completedAt: 100 }),
1998
+ ).pipe(Effect.result);
1999
+ assert.deepEqual(forkedEntries(), []);
2000
+ assert.equal(unresolved._tag, "Failure");
2001
+
2002
+ forkFake.queueEntries(UNCAPTURED_TURN_TREE);
2003
+ forkFake.queueState({ sessionFile: forkFile });
2004
+ fake.queueState({ sessionFile: forkFile });
2005
+ const forked = yield* forkAtFirst(
2006
+ uncapturedTurns(source.id, { startedAt: 100, completedAt: 200 }),
2007
+ );
2008
+ assert.equal(forked.nativeThreadRef?.nativeId, forkFile);
2009
+ assert.deepEqual(forkedEntries(), ["u2"]);
2010
+ assert.isFalse(fake.allRequests().some((request) => request.type === "fork"));
2011
+ }).pipe(Effect.scoped, Effect.provide(layerTest)),
2012
+ );
2013
+
2014
it.effect("presents explicitly namespaced MCP extension tools", () =>
2015
Effect.gen(function* () {
2016
const fake = yield* makeFakePi;
@@ -2697,6 +2806,106 @@ describe("PiAdapterV2", () => {
2806
}).pipe(Effect.scoped, Effect.provide(layerTest)),
2807
);
2808
2809
+ it.effect("rolls back past a turn whose start entry was never captured", () =>
2810
+ Effect.gen(function* () {
2811
+ const fake = yield* makeFakePi;
2812
+ const { runtime } = yield* openRuntime(fake);
2813
+ const providerThread = yield* runtime.ensureThread({
2814
+ threadId: THREAD_ID,
2815
+ modelSelection: modelSelection("default"),
2816
+ runtimePolicy,
2817
+ });
2818
+ const rollBackToFirst = (turns: ReadonlyArray<OrchestrationV2ProviderTurn>) =>
2819
+ runtime.rollbackThread({
2820
+ providerThread,
2821
+ target: {
2822
+ type: "provider_turn",
2823
+ checkpointId: CheckpointId.make("checkpoint-1"),
2824
+ appRunOrdinal: 1,
2825
+ providerTurn: turns[0]!,
2826
+ },
2827
+ providerThreadTurns: turns,
2828
+ });
2829
+ const forkedEntries = () =>
2830
+ fake
2831
+ .allRequests()
2832
+ .filter((request) => request.type === "fork")
2833
+ .map((request) => request.entryId);
2834
+
2835
+ fake.queueEntries(UNCAPTURED_TURN_TREE);
2836
+ const unresolved = yield* rollBackToFirst(
2837
+ uncapturedTurns(providerThread.id, { startedAt: 60, completedAt: 100 }),
2838
+ ).pipe(Effect.result);
2839
+ assert.deepEqual(forkedEntries(), []);
2840
+ assert.equal(unresolved._tag, "Failure");
2841
+
2842
+ fake.queueEntries({ entries: TURN_ONE_ENTRIES, leafId: "a1b" });
2843
+ const missing = yield* rollBackToFirst(uncapturedTurns(providerThread.id)).pipe(
2844
+ Effect.result,
2845
+ );
2846
+ assert.deepEqual(forkedEntries(), []);
2847
+ assert.equal(missing._tag, "Failure");
2848
+
2849
+ // An adopted wake precedes its T3 turn, but follows turn 1 and its steer.
2850
+ fake.queueEntries(UNCAPTURED_TURN_TREE);
2851
+ yield* rollBackToFirst(uncapturedTurns(providerThread.id));
2852
+ assert.deepEqual(forkedEntries(), ["u2"]);
2853
+ }).pipe(Effect.scoped, Effect.provide(layerTest)),
2854
+ );
2855
+
2856
+ it.effect("preserves inherited history when rolling back an uncaptured first turn", () =>
2857
+ Effect.gen(function* () {
2858
+ const fake = yield* makeFakePi;
2859
+ const { runtime } = yield* openRuntime(fake);
2860
+ const providerThread = yield* runtime.ensureThread({
2861
+ threadId: THREAD_ID,
2862
+ modelSelection: modelSelection("default"),
2863
+ runtimePolicy,
2864
+ });
2865
+ const rollBackToStart = (startedAt: number) =>
2866
+ runtime.rollbackThread({
2867
+ providerThread: { ...providerThread, createdAt: at(50) },
2868
+ target: {
2869
+ type: "thread_start",
2870
+ checkpointId: CheckpointId.make("checkpoint-start"),
2871
+ appRunOrdinal: 0,
2872
+ },
2873
+ providerThreadTurns: [
2874
+ {
2875
+ ...uncapturedTurns(providerThread.id)[1]!,
2876
+ ordinal: 1,
2877
+ startedAt: at(startedAt),
2878
+ },
2879
+ ],
2880
+ });
2881
+ const forkedEntries = () =>
2882
+ fake
2883
+ .allRequests()
2884
+ .filter((request) => request.type === "fork")
2885
+ .map((request) => request.entryId);
2886
+
2887
+ const entries = {
2888
+ entries: [
2889
+ ...TURN_ONE_ENTRIES,
2890
+ sessionMessage("u2", "a1b", "user", 100),
2891
+ sessionMessage("a2", "u2", "assistant", 120),
2892
+ sessionMessage("u3", "a2", "user", 160),
2893
+ sessionMessage("a3", "u3", "assistant", 180),
2894
+ ],
2895
+ leafId: "a3",
2896
+ };
2897
+
2898
+ // The adopted wake precedes T3's first turn; its steer must be discarded with it.
2899
+ fake.queueEntries(entries);
2900
+ yield* rollBackToStart(150);
2901
+ assert.deepEqual(forkedEntries(), ["u2"]);
2902
+
2903
+ fake.queueEntries(entries);
2904
+ yield* rollBackToStart(100);
2905
+ assert.deepEqual(forkedEntries(), ["u2", "u2"]);
2906
+ }).pipe(Effect.scoped, Effect.provide(layerTest)),
2907
+ );
2908
+
2909
it.effect("settles a command-only prompt from its deferred ack and idle probe", () =>
2910
Effect.gen(function* () {
2911
const fake = yield* makeFakePi;
packages/provider-pi/src/server/adapter.ts
+118
-31
@@ -1421,13 +1421,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
1421
1422
const listSessionEntries = (since: string | null, timeoutMs: number) =>
1423
request({ type: "get_entries", ...(since === null ? {} : { since }) }, timeoutMs).pipe(
1424
- Effect.map((data) => {
1425
- const leafId = recordField(data, "leafId");
1426
- const entries = piSessionEntries(recordField(data, "entries"));
1427
- return entries !== null && (typeof leafId === "string" || leafId === null)
1428
- ? { entries, leafId }
1429
- : null;
1430
- }),
1424
+ Effect.map(piSessionListing),
1425
Effect.orElseSucceed(() => null),
1426
);
1427
@@ -2880,13 +2874,15 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
2874
if (pendingWake !== null) {
2875
return yield* protocolError("Cannot roll back while native Pi work awaits a turn");
2876
}
2883
- const forkEntryId = piRollbackForkEntry(rollbackInput);
2884
- if (forkEntryId === null) {
2877
+ const boundary = piForkBoundary(rollbackInput);
2878
+ if (boundary.type === "nothing") {
2879
return piThreadSnapshot(state.providerThread);
2880
}
2887
- if (forkEntryId === undefined) {
2888
- return yield* protocolError("Pi rollback target has no captured session-tree entry");
2889
- }
2881
+ const forkEntryId = yield* piForkEntry(
2882
+ boundary,
2883
+ rollbackInput.providerThread.createdAt,
2884
+ request({ type: "get_entries" }),
2885
+ );
2886
return yield* Effect.acquireUseRelease(
2887
sessionEventPermit.withPermits(1)(
2888
Effect.gen(function* () {
@@ -3005,16 +3001,13 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
3001
if (forkInput.providerTurnId !== undefined && target === undefined) {
3002
return yield* protocolError("Pi fork target turn is missing");
3003
}
3008
- const beforeEntry =
3004
+ const boundary: PiForkBoundary =
3005
target === undefined
3010
- ? null
3011
- : piRollbackForkEntry({
3006
+ ? { type: "nothing" }
3007
+ : piForkBoundary({
3008
target: { type: "provider_turn", providerTurn: target },
3009
providerThreadTurns: sourceTurns,
3010
});
3015
- if (beforeEntry === undefined) {
3016
- return yield* protocolError("Pi fork boundary has no captured session-tree entry");
3017
- }
3011
// CLI --fork uses Pi's own session format and sets the destination cwd. RPC
3012
// switch_session/clone alone would retain the source cwd.
3013
const forkLaunch = buildPiRpcLaunch({
@@ -3038,6 +3031,14 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
3031
Effect.ignore,
3032
Effect.forkScoped,
3033
);
3034
+ const beforeEntry =
3035
+ boundary.type === "nothing"
3036
+ ? null
3037
+ : yield* piForkEntry(
3038
+ boundary,
3039
+ source.createdAt,
3040
+ forkConnection.request({ type: "get_entries" }),
3041
+ );
3042
if (beforeEntry !== null) {
3043
const result = yield* forkConnection.request({
3044
type: "fork",
@@ -3111,6 +3112,21 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
3112
interface PiSessionEntry {
3113
readonly parentId: string | null;
3114
readonly isUserMessage: boolean;
3115
+ /** Pi's `timestamp` as epoch milliseconds; null when missing or unparsable. */
3116
+ readonly timestamp: number | null;
3117
+}
3118
+
3119
+interface PiSessionListing {
3120
+ readonly entries: ReadonlyMap<string, PiSessionEntry>;
3121
+ readonly leafId: string | null;
3122
+}
3123
+
3124
+function piSessionListing(data: unknown): PiSessionListing | null {
3125
+ const leafId = recordField(data, "leafId");
3126
+ const entries = piSessionEntries(recordField(data, "entries"));
3127
+ return entries !== null && (typeof leafId === "string" || leafId === null)
3128
+ ? { entries, leafId }
3129
+ : null;
3130
}
3131
3132
function piSessionEntries(entries: unknown): ReadonlyMap<string, PiSessionEntry> | null {
@@ -3121,11 +3137,16 @@ function piSessionEntries(entries: unknown): ReadonlyMap<string, PiSessionEntry>
3137
const parentId = recordField(entry, "parentId");
3138
if (id === undefined || byId.has(id) || (parentId !== null && typeof parentId !== "string"))
3139
return null;
3140
+ const timestamp = recordString(entry, "timestamp");
3141
byId.set(id, {
3142
parentId,
3143
isUserMessage:
3144
recordField(entry, "type") === "message" &&
3145
recordString(recordField(entry, "message"), "role") === "user",
3146
+ timestamp:
3147
+ timestamp === undefined
3148
+ ? null
3149
+ : Option.getOrNull(Option.map(DateTime.make(timestamp), DateTime.toEpochMillis)),
3150
});
3151
}
3152
return byId;
@@ -3154,26 +3175,92 @@ function walkPiBranch(
3175
return { entryCount: visited.size, userEntryIds, reachedStop: current === stopAt };
3176
}
3177
3178
+type PiForkBoundary =
3179
+ | { readonly type: "entry"; readonly entryId: string }
3180
+ | { readonly type: "nothing" }
3181
+ | {
3182
+ readonly type: "uncaptured";
3183
+ readonly turn: OrchestrationV2ProviderTurn;
3184
+ readonly target: OrchestrationV2ProviderTurn | null;
3185
+ };
3186
+
3187
/**
3188
* Turns without a ref left nothing on the active branch, so the boundary is the first discarded
3159
- * turn that has one. Returns `null` when no such turn follows the target (nothing to discard) and
3160
- * `undefined` when the boundary turn has no captured entry ref (only turn-boundary refs recorded
3161
- * by `captureTurnTreeRefs` are strong).
3189
+ * turn that has one. `uncaptured` is a boundary turn still carrying its synthetic ref (only
3190
+ * `captureTurnTreeRefs` records strong ones); `piForkEntry` locates it in the session tree.
3191
*/
3163
-function piRollbackForkEntry(input: {
3192
+function piForkBoundary(input: {
3193
readonly target:
3194
| { readonly type: "thread_start" }
3195
| { readonly type: "provider_turn"; readonly providerTurn: OrchestrationV2ProviderTurn };
3196
readonly providerThreadTurns: ReadonlyArray<OrchestrationV2ProviderTurn>;
3168
-}): string | null | undefined {
3169
- const boundaryOrdinal =
3170
- input.target.type === "thread_start" ? 0 : input.target.providerTurn.ordinal;
3171
- const ref = input.providerThreadTurns
3172
- .filter((turn) => turn.ordinal > boundaryOrdinal && turn.nativeTurnRef !== null)
3173
- .sort((a, b) => a.ordinal - b.ordinal)[0]?.nativeTurnRef;
3174
- if (ref == null) return null;
3175
- if (ref.strength !== "strong" || ref.nativeId === null) return undefined;
3176
- return ref.nativeId;
3197
+}): PiForkBoundary {
3198
+ const target = input.target.type === "thread_start" ? null : input.target.providerTurn;
3199
+ const boundary = input.providerThreadTurns
3200
+ .filter((turn) => turn.ordinal > (target?.ordinal ?? 0) && turn.nativeTurnRef !== null)
3201
+ .sort((a, b) => a.ordinal - b.ordinal)[0];
3202
+ const ref = boundary?.nativeTurnRef;
3203
+ if (boundary === undefined || ref == null) return { type: "nothing" };
3204
+ return ref.strength === "strong" && ref.nativeId !== null
3205
+ ? { type: "entry", entryId: ref.nativeId }
3206
+ : { type: "uncaptured", turn: boundary, target };
3207
+}
3208
+
3209
+/** Reads the session tree only for an uncaptured boundary. */
3210
+function piForkEntry<E>(
3211
+ boundary: Exclude<PiForkBoundary, { type: "nothing" }>,
3212
+ providerThreadCreatedAt: DateTime.Utc,
3213
+ readEntries: Effect.Effect<unknown, E>,
3214
+): Effect.Effect<string, E | ProviderAdapter.ProviderAdapterProtocolError> {
3215
+ if (boundary.type === "entry") return Effect.succeed(boundary.entryId);
3216
+ return readEntries.pipe(
3217
+ Effect.flatMap((data) => {
3218
+ const listing = piSessionListing(data);
3219
+ const entryId =
3220
+ listing === null
3221
+ ? undefined
3222
+ : piUncapturedForkEntry(listing, boundary, providerThreadCreatedAt);
3223
+ return entryId === undefined
3224
+ ? Effect.fail(
3225
+ new ProviderAdapter.ProviderAdapterProtocolError({
3226
+ driver: PI_PROVIDER,
3227
+ detail: `Pi turn ${boundary.turn.ordinal} has no captured session-tree entry and none was found in the session tree`,
3228
+ }),
3229
+ )
3230
+ : Effect.succeed(entryId);
3231
+ }),
3232
+ );
3233
+}
3234
+
3235
+/**
3236
+ * Pi shares the server clock. An adopted wake can precede its T3 turn, so search from the target
3237
+ * turn's end through the boundary turn's end. At thread start, use the earlier of thread creation
3238
+ * and turn start to include adopted wakes while preserving inherited session history.
3239
+ */
3240
+function piUncapturedForkEntry(
3241
+ listing: PiSessionListing,
3242
+ boundary: Extract<PiForkBoundary, { type: "uncaptured" }>,
3243
+ providerThreadCreatedAt: DateTime.Utc,
3244
+): string | undefined {
3245
+ const { startedAt, completedAt } = boundary.turn;
3246
+ if (startedAt === null || completedAt === null) return undefined;
3247
+ const from =
3248
+ boundary.target === null
3249
+ ? Math.min(DateTime.toEpochMillis(providerThreadCreatedAt), DateTime.toEpochMillis(startedAt))
3250
+ : DateTime.toEpochMillis(boundary.target.completedAt ?? startedAt);
3251
+ const to = DateTime.toEpochMillis(completedAt);
3252
+ const targetRef = boundary.target?.nativeTurnRef;
3253
+ const stopAt = targetRef?.strength === "strong" ? targetRef.nativeId : null;
3254
+ if (stopAt !== null && !listing.entries.has(stopAt)) return undefined;
3255
+ const walk = walkPiBranch(listing.entries, listing.leafId, stopAt);
3256
+ if (walk === null || !walk.reachedStop) return undefined;
3257
+ let earliest: string | undefined;
3258
+ for (const id of walk.userEntryIds) {
3259
+ const timestamp = listing.entries.get(id)?.timestamp;
3260
+ if (timestamp == null) return undefined;
3261
+ if (timestamp >= from && timestamp <= to) earliest = id;
3262
+ }
3263
+ return earliest;
3264
}
3265
3266
function piSubagentOutput(result: unknown): string {