Skip to content

Commit 17143d3

Browse files
PR Batch Testerclaude
andcommitted
fix(pi): end a session's background work where Pi tears the session down
Guessing session ownership from keys dropped a replacement job that reused an outgoing key and listed replacement jobs on the outgoing thread. T3's bridge extension now sets a marker status from session_shutdown, the point where Pi's own TUI clears statuses. The adapter clears the outgoing roster there, and statuses set after it wait for the replacement binding. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent b307b44 commit 17143d3

4 files changed

Lines changed: 67 additions & 40 deletions

File tree

‎packages/provider-pi/src/server/adapter.test.ts‎

Lines changed: 23 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1353,30 +1353,42 @@ describe("PiAdapterV2", () => {
13531353
yield* setStatus("t3:background:docs", "Docs building");
13541354
assert.lengthOf(yield* takeRoster(), 2);
13551355

1356-
// A replaced session invalidates the old jobs' context, so they can never
1357-
// clear. A job's progress update that Pi sent mid-switch is still old work;
1358-
// a key first set mid-switch comes from the new session's start hooks.
1356+
// Pi tears the outgoing session down before the replacement starts, and
1357+
// T3's bridge marks that point. Old jobs can never clear their statuses
1358+
// after it; statuses set after it come from the replacement's start hooks,
1359+
// even under a key an old job used.
13591360
fake.queueState({ sessionFile: "/fake/replaced.jsonl" });
13601361
const replaced = yield* switchSession(
13611362
Effect.gen(function* () {
13621363
yield* setStatus("t3:background:tests", "Tests 50%");
1364+
assert.lengthOf(yield* takeRoster(), 2);
1365+
yield* setStatus("t3:session-end", "ended");
1366+
assert.lengthOf(yield* takeRoster(), 0);
1367+
yield* setStatus("t3:background:tests", "Tests restarted");
13631368
yield* setStatus("t3:background:deploy", "Deploying");
13641369
}),
13651370
false,
13661371
);
13671372
assert.equal(replaced._tag, "Success");
13681373
if (replaced._tag !== "Success") return;
1374+
// The replacement's jobs land only on the replacement binding.
1375+
const registered = yield* takeEvent((event) => event.type === "provider_thread.updated");
1376+
assert.isTrue(
1377+
registered.type === "provider_thread.updated" &&
1378+
registered.providerThread.id === replaced.success.id &&
1379+
replaced.success.id !== providerThread.id,
1380+
);
13691381
assert.deepStrictEqual(
1370-
replaced.success.pendingBackgroundTasks?.map((task) => task.taskId),
1371-
["t3:background:deploy"],
1382+
replaced.success.pendingBackgroundTasks?.map((task) => [task.taskId, task.description]),
1383+
[
1384+
["t3:background:tests", "Tests restarted"],
1385+
["t3:background:deploy", "Deploying"],
1386+
],
13721387
);
1388+
yield* setStatus("t3:background:tests");
13731389
yield* setStatus("t3:background:deploy");
1374-
yield* takeEvent(
1375-
(event) =>
1376-
event.type === "provider_thread.updated" &&
1377-
event.providerThread.id === replaced.success.id &&
1378-
event.providerThread.pendingBackgroundTasks?.length === 0,
1379-
);
1390+
assert.lengthOf(yield* takeRoster(), 1);
1391+
assert.lengthOf(yield* takeRoster(), 0);
13801392
assert.isFalse(yield* runtime.hasPendingBackgroundWork!);
13811393
}).pipe(Effect.scoped, Effect.provide(layerTest)),
13821394
);

‎packages/provider-pi/src/server/adapter.ts‎

Lines changed: 17 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ import {
7272
materializePiT3McpExtension,
7373
resolvePiLaunchArgs,
7474
} from "./mcpInjection.ts";
75-
import { PI_FILE_CHANGE_TOOLS } from "./mcpExtensionSource.ts";
75+
import { PI_FILE_CHANGE_TOOLS, PI_T3_SESSION_END_STATUS_KEY } from "./mcpExtensionSource.ts";
7676

7777
export const PI_PROVIDER = ProviderDriverKind.make("pi");
7878
const PI_DRIVER_KIND = PI_PROVIDER;
@@ -549,8 +549,9 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
549549
let pendingWake: PiWake | null = null;
550550
// Status key to its text, which becomes the task description.
551551
const backgroundWork = new Map<string, string>();
552-
// The last bound thread, whose roster lists backgroundWork. Unlike
553-
// threadState it survives a failed or vetoed session switch.
552+
// The thread whose roster lists backgroundWork. Unlike threadState it
553+
// survives a vetoed or failed switch, and it is null between a session's
554+
// teardown and the next binding, when new statuses have no owner yet.
554555
let backgroundWorkState: PiThreadState | null = null;
555556
let rollbackBarrier: Deferred.Deferred<
556557
void,
@@ -677,11 +678,8 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
677678
const syncBackgroundWork = (state: PiThreadState) =>
678679
updateProviderThread(state, { pendingBackgroundTasks: pendingBackgroundTasks() });
679680

680-
const lifecycleRequest = Effect.fn("PiAdapter.lifecycleRequest")(function* (
681-
record: PiRpcRecord,
682-
) {
683-
const outgoingKeys = new Set(backgroundWork.keys());
684-
const result = yield* request(record, PI_SESSION_TIMEOUT_MS).pipe(
681+
const lifecycleRequest = (record: PiRpcRecord) =>
682+
request(record, PI_SESSION_TIMEOUT_MS).pipe(
685683
// A local timeout does not cancel Pi's lifecycle hook. Retire the
686684
// process before fallback can race its eventual switch/new-session.
687685
Effect.tapError((error) =>
@@ -697,20 +695,6 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
697695
}),
698696
Effect.onInterrupt(() => connection.terminate),
699697
);
700-
if (recordField(result, "cancelled") !== true && outgoingKeys.size > 0) {
701-
// Pi invalidates the outgoing session's extension context, so its
702-
// jobs can no longer clear their statuses; Pi's own TUI drops them
703-
// here too. Responses bypass the pump, so first apply every status
704-
// Pi sent before replying. Keys first set during the switch belong
705-
// to the replacement session's start hooks.
706-
const drained = yield* Deferred.make<void>();
707-
if (yield* Queue.offer(connection.events, { type: "t3.drain", drained }))
708-
yield* Deferred.await(drained);
709-
for (const key of outgoingKeys) backgroundWork.delete(key);
710-
if (backgroundWorkState !== null) yield* syncBackgroundWork(backgroundWorkState);
711-
}
712-
return result;
713-
});
714698

715699
const tokenUsageFromStats = (
716700
stats: unknown,
@@ -1277,6 +1261,15 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
12771261
if (method === undefined) return;
12781262
if (method === "setStatus") {
12791263
const statusKey = recordString(event, "statusKey");
1264+
if (statusKey === PI_T3_SESSION_END_STATUS_KEY) {
1265+
// The outgoing jobs can never clear their statuses now.
1266+
const outgoingState = backgroundWorkState;
1267+
backgroundWorkState = null;
1268+
if (backgroundWork.size === 0) return;
1269+
backgroundWork.clear();
1270+
if (outgoingState !== null) yield* syncBackgroundWork(outgoingState);
1271+
return;
1272+
}
12801273
if (
12811274
statusKey !== PI_BACKGROUND_WORK_STATUS_KEY &&
12821275
statusKey?.startsWith(`${PI_BACKGROUND_WORK_STATUS_KEY}:`) !== true
@@ -2112,12 +2105,6 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
21122105
}
21132106
return;
21142107
}
2115-
case "t3.drain": {
2116-
const drained = event["drained"];
2117-
if (Deferred.isDeferred<void, never>(drained))
2118-
yield* Deferred.succeed(drained, undefined);
2119-
return;
2120-
}
21212108
case "t3.rollback_barrier": {
21222109
if (rollbackBarrier !== null && event["barrier"] === rollbackBarrier)
21232110
yield* Deferred.succeed(rollbackBarrier, undefined);
@@ -3049,9 +3036,11 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
30493036
appliedSessionName = null;
30503037
lastKnownLeaf = leafId;
30513038
leafCursorStale = entriesData === undefined;
3039+
backgroundWorkState = state;
30523040
yield* updateProviderThread(state, {
30533041
nativeThreadRef: providerRef(forkSessionFile),
30543042
nativeConversationHeadRef: leafId === null ? null : providerRef(leafId),
3043+
pendingBackgroundTasks: pendingBackgroundTasks(),
30553044
});
30563045
rollbackBarrier = null;
30573046
return piThreadSnapshot(state.providerThread);

‎packages/provider-pi/src/server/mcpExtensionSource.test.ts‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import * as NodeModule from "node:module";
66
import * as NodeVM from "node:vm";
77
import { assert, describe, it } from "@effect/vitest";
88

9-
import { PI_T3_MCP_EXTENSION_SOURCE } from "./mcpExtensionSource.ts";
9+
import { PI_T3_MCP_EXTENSION_SOURCE, PI_T3_SESSION_END_STATUS_KEY } from "./mcpExtensionSource.ts";
1010
import { loadMcpBridge } from "./mcpBridge.testkit.ts";
1111

1212
type RequestHook = (
@@ -77,6 +77,19 @@ describe("Pi orchestration prompt section", () => {
7777
});
7878
});
7979

80+
describe("Pi session teardown", () => {
81+
it("marks where the outgoing session's background work ends", async () => {
82+
const bridge = await loadMcpBridge();
83+
const statuses: Array<readonly [string, string | undefined]> = [];
84+
const ui = {
85+
notify: assert.fail,
86+
setStatus: (key: string, text: string | undefined) => statuses.push([key, text]),
87+
};
88+
await bridge.handlers.get("session_shutdown")!({ systemPrompt: "" }, { ui });
89+
assert.deepStrictEqual(statuses, [[PI_T3_SESSION_END_STATUS_KEY, "ended"]]);
90+
});
91+
});
92+
8093
describe("Pi MCP tool results", () => {
8194
it("returns mixed screenshot blocks and typed script output without repeating structured text", async () => {
8295
const content = [

‎packages/provider-pi/src/server/mcpExtensionSource.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,12 @@ export const T3_PI_MCP_EXTENSION_PATH_ENV = "T3_PI_MCP_EXTENSION_PATH";
1717
*/
1818
export const PI_FILE_CHANGE_TOOLS = ["edit", "write"] as const;
1919

20+
/**
21+
* The bridge sets this status as Pi tears down a session. Pi's RPC stream does
22+
* not mark the boundary otherwise, and the outgoing extension context dies here.
23+
*/
24+
export const PI_T3_SESSION_END_STATUS_KEY = "t3:session-end";
25+
2026
export const PI_T3_MCP_EXTENSION_SOURCE = `\
2127
import { stripFrontmatter, type ExtensionAPI, type ExtensionContext } from "@earendil-works/pi-coding-agent";
2228
import * as NodeFSP from "node:fs/promises";
@@ -31,6 +37,7 @@ const ORCHESTRATION_INSTRUCTIONS = ${JSON.stringify(T3_CODE_ORCHESTRATION_INSTRU
3137
const PROTOCOL = "2025-06-18";
3238
const READ_ONLY_TOOLS = new Set(["read", "grep", "find", "ls"]);
3339
const FILE_CHANGE_TOOLS = new Set(${JSON.stringify(PI_FILE_CHANGE_TOOLS)});
40+
const SESSION_END_STATUS_KEY = ${JSON.stringify(PI_T3_SESSION_END_STATUS_KEY)};
3441
3542
type RuntimeMode = "approval-required" | "auto-accept-edits" | "auto" | "full-access";
3643
@@ -339,6 +346,12 @@ export default async function t3McpExtension(pi: ExtensionAPI) {
339346
}
340347
});
341348
349+
// T3 drops the outgoing session's background work here, where Pi's own TUI
350+
// clears extension statuses before invalidating their contexts.
351+
pi.on("session_shutdown", (_event, ctx) => {
352+
ctx.ui.setStatus(SESSION_END_STATUS_KEY, "ended");
353+
});
354+
342355
const endpoint = env(URL_ENV);
343356
const token = env(TOKEN_ENV);
344357
if (endpoint === undefined || token === undefined) {

0 commit comments

Comments
 (0)