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 21, 16:00 UTC
fix(pi): resumed threads run in the worktree after a handoff (#36586)
Julius Marminge committed
Nov 14, 2026 at 00:54 UTC
bebaf3ec04d015ad99260e9be418900f5822fcaf
2 files changed
+129
-51
packages/provider-pi/src/server/adapter.test.ts
+45
@@ -2108,6 +2108,51 @@ describe("PiAdapterV2", () => {
2108
}).pipe(Effect.scoped, Effect.provide(layerTest)),
2109
);
2110
2111
+ it.effect("forks a resumed session recorded in another cwd into the runtime cwd", () =>
2112
+ Effect.gen(function* () {
2113
+ const host = yield* ProviderHost.ProviderHost;
2114
+ const fileSystem = yield* FileSystem.FileSystem;
2115
+ const fake = yield* makeFakePi;
2116
+ const forkFake = yield* makeFakePi;
2117
+ const forkFile = "/fake/forked-into-worktree.jsonl";
2118
+ const { runtime } = yield* openRuntime(fake, "default", THREAD_ID, SESSION_ID, forkFake);
2119
+ const providerThread = yield* runtime.ensureThread({
2120
+ threadId: THREAD_ID,
2121
+ modelSelection: modelSelection("default"),
2122
+ runtimePolicy,
2123
+ });
2124
+ const dir = yield* fileSystem.makeTempDirectoryScoped();
2125
+ const sessionAt = (sessionCwd: string) =>
2126
+ Effect.gen(function* () {
2127
+ const file = `${dir}/${sessionCwd.length}.jsonl`;
2128
+ yield* fileSystem.writeFileString(
2129
+ file,
2130
+ `${JSON.stringify({ type: "session", version: 3, id: "s", cwd: sessionCwd })}\n{}\n`,
2131
+ );
2132
+ return {
2133
+ ...providerThread,
2134
+ nativeThreadRef: { driver: PI_PROVIDER, nativeId: file, strength: "strong" as const },
2135
+ };
2136
+ });
2137
+ const lastSwitch = () =>
2138
+ fake.allRequests().findLast((request) => request.type === "switch_session")?.sessionPath;
2139
+
2140
+ const sameCwd = yield* sessionAt(host.paths.cwd);
2141
+ yield* runtime.resumeThread({ providerThread: sameCwd });
2142
+ assert.equal(lastSwitch(), sameCwd.nativeThreadRef?.nativeId);
2143
+ assert.isFalse(forkFake.allRequests().some((request) => request.type === "get_state"));
2144
+
2145
+ const otherCwd = yield* sessionAt(`${host.paths.cwd}-original-checkout`);
2146
+ forkFake.queueState({ sessionFile: forkFile });
2147
+ fake.queueState({ sessionFile: forkFile });
2148
+ const resumed = yield* runtime.resumeThread({ providerThread: otherCwd });
2149
+ const args = forkFake.lastSpawn().args;
2150
+ assert.equal(args[args.indexOf("--fork") + 1], otherCwd.nativeThreadRef?.nativeId);
2151
+ assert.equal(lastSwitch(), forkFile);
2152
+ assert.equal(resumed.nativeThreadRef?.nativeId, forkFile);
2153
+ }).pipe(Effect.scoped, Effect.provide(layerTest)),
2154
+ );
2155
+
2156
it.effect("creates a distinct native session after a failed resume", () =>
2157
Effect.gen(function* () {
2158
const fake = yield* makeFakePi;
packages/provider-pi/src/server/adapter.ts
+84
-51
@@ -2582,6 +2582,82 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
2582
}
2583
});
2584
2585
+ // CLI --fork uses Pi's own session format and sets the destination cwd. RPC
2586
+ // switch_session/clone alone would retain the source cwd.
2587
+ const forkSessionIntoCwd = Effect.fnUntraced(function* (
2588
+ sourceFile: string,
2589
+ boundary: PiForkBoundary,
2590
+ providerThreadCreatedAt: DateTime.Utc,
2591
+ ) {
2592
+ const forkLaunch = buildPiRpcLaunch({
2593
+ launchArgs: resolvedLaunchArgs.args,
2594
+ environment: options.environment,
2595
+ mcpSession: undefined,
2596
+ extensionPath: undefined,
2597
+ shortLived: true,
2598
+ disableExtensions: true,
2599
+ disableTools: true,
2600
+ });
2601
+ return yield* Effect.scoped(
2602
+ Effect.gen(function* () {
2603
+ const forkConnection = yield* makePiRpcConnection({
2604
+ command: options.settings.binaryPath || "pi",
2605
+ args: [...forkLaunch.args, "--fork", sourceFile],
2606
+ cwd,
2607
+ env: forkLaunch.env,
2608
+ });
2609
+ yield* Stream.fromQueue(forkConnection.events).pipe(
2610
+ Stream.runDrain,
2611
+ Effect.ignore,
2612
+ Effect.forkScoped,
2613
+ );
2614
+ const beforeEntry =
2615
+ boundary.type === "nothing"
2616
+ ? null
2617
+ : yield* piForkEntry(
2618
+ boundary,
2619
+ providerThreadCreatedAt,
2620
+ forkConnection.request({ type: "get_entries" }),
2621
+ );
2622
+ if (beforeEntry !== null) {
2623
+ const result = yield* forkConnection.request({
2624
+ type: "fork",
2625
+ entryId: beforeEntry,
2626
+ });
2627
+ if (recordField(result, "cancelled") === true) {
2628
+ return yield* protocolError("A Pi extension cancelled the session fork");
2629
+ }
2630
+ }
2631
+ const state = yield* forkConnection.request({ type: "get_state" });
2632
+ const file = recordString(state, "sessionFile");
2633
+ if (file === undefined || file === sourceFile) {
2634
+ return yield* protocolError("Pi fork did not create a distinct session file");
2635
+ }
2636
+ return file;
2637
+ }),
2638
+ ).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner));
2639
+ });
2640
+
2641
+ // A workspace handoff restarts Pi in a new cwd, but the session header still names the old one.
2642
+ const sessionFileInCwd = Effect.fnUntraced(function* (
2643
+ sessionFile: string,
2644
+ providerThreadCreatedAt: DateTime.Utc,
2645
+ ) {
2646
+ const header = yield* fileSystem.stream(sessionFile).pipe(
2647
+ Stream.decodeText(),
2648
+ Stream.splitLines,
2649
+ Stream.runHead,
2650
+ Effect.map(Option.getOrUndefined),
2651
+ Effect.orElseSucceed(() => undefined),
2652
+ );
2653
+ if (header === undefined) return sessionFile;
2654
+ const sessionCwd = recordString(Option.getOrUndefined(decodeSessionHeader(header)), "cwd");
2655
+ if (sessionCwd === undefined || sessionCwd === cwd) return sessionFile;
2656
+ const realCwd = yield* fileSystem.realPath(cwd).pipe(Effect.orElseSucceed(() => cwd));
2657
+ if (sessionCwd === realCwd) return sessionFile;
2658
+ return yield* forkSessionIntoCwd(sessionFile, { type: "nothing" }, providerThreadCreatedAt);
2659
+ });
2660
+
2661
const registerThread = Effect.fnUntraced(function* (
2662
threadInput: ProviderAdapter.ProviderAdapterV2EnsureThreadInput,
2663
publish = true,
@@ -2621,8 +2697,11 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
2697
baselineThinking = null;
2698
contextWindow = null;
2699
const result = yield* lifecycleRequest(
2624
- resumeId != null
2625
- ? { type: "switch_session", sessionPath: resumeId }
2700
+ resumeId != null && existing !== undefined
2701
+ ? {
2702
+ type: "switch_session",
2703
+ sessionPath: yield* sessionFileInCwd(resumeId, existing.createdAt),
2704
+ }
2705
: { type: "new_session" },
2706
);
2707
if (recordField(result, "cancelled") === true) {
@@ -3474,55 +3553,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
3553
target: { type: "provider_turn", providerTurn: target },
3554
providerThreadTurns: sourceTurns,
3555
});
3477
- // CLI --fork uses Pi's own session format and sets the destination cwd. RPC
3478
- // switch_session/clone alone would retain the source cwd.
3479
- const forkLaunch = buildPiRpcLaunch({
3480
- launchArgs: resolvedLaunchArgs.args,
3481
- environment: options.environment,
3482
- mcpSession: undefined,
3483
- extensionPath: undefined,
3484
- shortLived: true,
3485
- disableExtensions: true,
3486
- disableTools: true,
3487
- });
3488
- const nativeId = yield* Effect.scoped(
3489
- Effect.gen(function* () {
3490
- const forkConnection = yield* makePiRpcConnection({
3491
- command: options.settings.binaryPath || "pi",
3492
- args: [...forkLaunch.args, "--fork", sourceFile],
3493
- cwd,
3494
- env: forkLaunch.env,
3495
- });
3496
- yield* Stream.fromQueue(forkConnection.events).pipe(
3497
- Stream.runDrain,
3498
- Effect.ignore,
3499
- Effect.forkScoped,
3500
- );
3501
- const beforeEntry =
3502
- boundary.type === "nothing"
3503
- ? null
3504
- : yield* piForkEntry(
3505
- boundary,
3506
- source.createdAt,
3507
- forkConnection.request({ type: "get_entries" }),
3508
- );
3509
- if (beforeEntry !== null) {
3510
- const result = yield* forkConnection.request({
3511
- type: "fork",
3512
- entryId: beforeEntry,
3513
- });
3514
- if (recordField(result, "cancelled") === true) {
3515
- return yield* protocolError("A Pi extension cancelled the session fork");
3516
- }
3517
- }
3518
- const state = yield* forkConnection.request({ type: "get_state" });
3519
- const file = recordString(state, "sessionFile");
3520
- if (file === undefined || file === sourceFile) {
3521
- return yield* protocolError("Pi fork did not create a distinct session file");
3522
- }
3523
- return file;
3524
- }),
3525
- ).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner));
3556
+ const nativeId = yield* forkSessionIntoCwd(sourceFile, boundary, source.createdAt);
3557
const now = yield* DateTime.now;
3558
return yield* registerThread(
3559
{
@@ -3576,6 +3607,8 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
3607
});
3608
});
3609
3610
+const decodeSessionHeader = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Unknown));
3611
+
3612
interface PiSessionEntry {
3613
readonly parentId: string | null;
3614
readonly isUserMessage: boolean;