Skip to content

Commit d30b128

Browse files
PR Batch Testerclaude
andcommitted
fix(pi): list extension background work on the thread so Stop can end it
Pinned work now shows as the thread's pending background tasks, keeps the run listening like Claude's background tasks, and Stop ends the process. Pins are dropped when Pi replaces its native session, because the outgoing extension context can no longer clear them. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 2d800f7 commit d30b128

3 files changed

Lines changed: 155 additions & 40 deletions

File tree

‎docs/user/providers-pi.md‎

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -52,12 +52,14 @@ dialogs work in T3 Code. Notifications appear in the work log. Pi terminal decor
5252
titles, status lines, and widgets does not have a T3 Code equivalent.
5353

5454
T3 Code stops an idle Pi process after 30 minutes. An extension that keeps working after a turn
55-
ends, such as a background command, can keep the process alive by holding a status under the
56-
`t3:background` key, or `t3:background:<job>` for several jobs, until the work ends:
55+
ends, such as a background command, can keep the process alive by setting a non-empty status under
56+
the `t3:background` key, or `t3:background:<job>` for several jobs, until the work ends:
5757
`ctx.ui.setStatus("t3:background:build", "Build running")`, then
58-
`ctx.ui.setStatus("t3:background:build", undefined)`. The process stays up for at most four hours of
59-
background work. When the extension wakes the agent with the result, the reply appears in the
60-
thread.
58+
`ctx.ui.setStatus("t3:background:build", undefined)`. While a status is set, the thread shows as
59+
waiting on that work, and Stop ends the Pi process along with it. Without other activity, the
60+
process stays up for about four more hours after the first 30 idle minutes. Starting another Pi
61+
session in the same process, for example by rolling back, drops these statuses. When the extension
62+
wakes the agent with the result, the reply appears in the thread.
6163

6264
## Permission Modes
6365

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

Lines changed: 86 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1268,7 +1268,7 @@ describe("PiAdapterV2", () => {
12681268
}).pipe(Effect.scoped, Effect.provide(layerTest)),
12691269
);
12701270

1271-
it.effect("keeps the session while an extension reports background work", () =>
1271+
it.effect("lists extension background work until it ends or Pi swaps sessions", () =>
12721272
Effect.gen(function* () {
12731273
const fake = yield* makeFakePi;
12741274
const { runtime, takeEvent } = yield* openRuntime(fake);
@@ -1277,40 +1277,104 @@ describe("PiAdapterV2", () => {
12771277
modelSelection: modelSelection("default"),
12781278
runtimePolicy,
12791279
});
1280-
let barrier = 0;
1281-
const setStatus = Effect.fnUntraced(function* (statusKey: string, statusText?: string) {
1282-
yield* fake.emit({
1280+
const setStatus = (statusKey: string, statusText?: string) =>
1281+
fake.emit({
12831282
type: "extension_ui_request",
12841283
id: `status-${statusKey}`,
12851284
method: "setStatus",
12861285
statusKey,
12871286
...(statusText === undefined ? {} : { statusText }),
12881287
});
1289-
// setStatus is fire-and-forget; a dialog marks that Pi's earlier output was handled.
1290-
barrier += 1;
1291-
yield* fake.emit({
1292-
type: "extension_ui_request",
1293-
id: `barrier-${barrier}`,
1294-
method: "confirm",
1295-
title: `Barrier ${barrier}`,
1296-
});
1297-
yield* takeEvent(
1298-
(event) =>
1299-
event.type === "runtime_request.updated" &&
1300-
event.runtimeRequest.nativeRequestRef?.nativeId === `barrier-${barrier}`,
1301-
);
1288+
const takeRoster = Effect.fnUntraced(function* () {
1289+
const event = yield* takeEvent((event) => event.type === "provider_thread.updated");
1290+
assert.isTrue(event.type === "provider_thread.updated");
1291+
if (event.type !== "provider_thread.updated") return [];
1292+
return (event.providerThread.pendingBackgroundTasks ?? []).map((task) => [
1293+
event.providerThread.id,
1294+
task.taskId,
1295+
task.description,
1296+
]);
13021297
});
13031298

1299+
assert.lengthOf(yield* takeRoster(), 0);
13041300
yield* setStatus("lint", "Lint clean");
1305-
assert.isFalse(yield* runtime.hasPendingBackgroundWork!);
1306-
yield* setStatus("t3:background:build", "Build running");
1301+
yield* setStatus("t3:background:build", "\u001b[32mBuild running\u001b[0m");
1302+
assert.deepStrictEqual(yield* takeRoster(), [
1303+
[providerThread.id, "t3:background:build", "Build running"],
1304+
]);
13071305
yield* setStatus("t3:background:tests", "Tests running");
1306+
assert.lengthOf(yield* takeRoster(), 2);
13081307
assert.isTrue(yield* runtime.hasPendingBackgroundWork!);
1309-
// Completion arrives as a native wake, so the settled run stays closed.
1310-
assert.isFalse(yield* runtime.hasPendingBackgroundWorkForThread!(providerThread));
1308+
assert.isTrue(yield* runtime.hasPendingBackgroundWorkForThread!(providerThread));
13111309
yield* setStatus("t3:background:build");
1310+
assert.deepStrictEqual(yield* takeRoster(), [
1311+
[providerThread.id, "t3:background:tests", "Tests running"],
1312+
]);
1313+
1314+
// A vetoed switch keeps the outgoing session, so its job is still listed.
1315+
fake.vetoNextNewSession();
1316+
const vetoed = yield* runtime
1317+
.ensureThread({
1318+
threadId: THREAD_ID,
1319+
modelSelection: modelSelection("default"),
1320+
runtimePolicy,
1321+
})
1322+
.pipe(Effect.flip);
1323+
assert.equal(vetoed._tag, "ProviderAdapterEnsureThreadError");
1324+
assert.lengthOf(yield* takeRoster(), 0);
1325+
assert.lengthOf(yield* takeRoster(), 1);
13121326
assert.isTrue(yield* runtime.hasPendingBackgroundWork!);
1313-
yield* setStatus("t3:background:tests", "");
1327+
1328+
// A replaced session invalidates the job's context, so it can never clear.
1329+
const replacement = yield* runtime.ensureThread({
1330+
threadId: THREAD_ID,
1331+
modelSelection: modelSelection("default"),
1332+
runtimePolicy,
1333+
});
1334+
// The vetoed switch already unbound the thread; its roster still empties.
1335+
assert.lengthOf(yield* takeRoster(), 0);
1336+
const registered = yield* takeEvent((event) => event.type === "provider_thread.updated");
1337+
assert.isTrue(
1338+
registered.type === "provider_thread.updated" &&
1339+
registered.providerThread.id === replacement.id &&
1340+
replacement.id !== providerThread.id,
1341+
);
1342+
assert.deepStrictEqual(replacement.pendingBackgroundTasks, []);
1343+
assert.isFalse(yield* runtime.hasPendingBackgroundWork!);
1344+
yield* setStatus("t3:background:deploy", "Deploying");
1345+
assert.lengthOf(yield* takeRoster(), 1);
1346+
yield* setStatus("t3:background:deploy", "");
1347+
assert.lengthOf(yield* takeRoster(), 0);
1348+
assert.isFalse(yield* runtime.hasPendingBackgroundWork!);
1349+
}).pipe(Effect.scoped, Effect.provide(layerTest)),
1350+
);
1351+
1352+
it.effect("lets Stop end a process kept alive by extension background work", () =>
1353+
Effect.gen(function* () {
1354+
const fake = yield* makeFakePi;
1355+
const { runtime, takeEvent } = yield* openRuntime(fake);
1356+
const providerThread = yield* runtime.ensureThread({
1357+
threadId: THREAD_ID,
1358+
modelSelection: modelSelection("default"),
1359+
runtimePolicy,
1360+
});
1361+
yield* fake.emit({
1362+
type: "extension_ui_request",
1363+
id: "status",
1364+
method: "setStatus",
1365+
statusKey: "t3:background",
1366+
statusText: "Build running",
1367+
});
1368+
yield* takeEvent((event) => event.type === "provider_thread.updated");
1369+
yield* runtime.interruptTurn({
1370+
providerThread,
1371+
providerTurnId: ProviderTurnId.make("settled-turn"),
1372+
requestRuntimeRestart: true,
1373+
});
1374+
yield* takeEvent(
1375+
(event) =>
1376+
event.type === "provider_session.updated" && event.providerSession.status === "stopped",
1377+
);
13141378
assert.isFalse(yield* runtime.hasPendingBackgroundWork!);
13151379
}).pipe(Effect.scoped, Effect.provide(layerTest)),
13161380
);

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

Lines changed: 62 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import * as HostProcess from "@t3tools/shared/HostProcess";
22
import { AgentScope } from "@t3tools/shared/AgentScope";
33
import { getModelSelectionStringOptionValue } from "@t3tools/shared/model";
44
import { readToolOutputImage } from "@t3tools/shared/toolOutput";
5+
import * as NodeUtil from "node:util";
56
import * as Predicate from "effect/Predicate";
67
import {
78
defaultInstanceIdForDriver,
@@ -90,13 +91,14 @@ const PI_SESSION_TIMEOUT_MS = 60_000;
9091
const PI_UNSOLICITED_ACTIVITY_ERROR =
9192
"Pi started agent work outside an active T3 turn. The session was stopped to prevent invisible tool execution.";
9293
const SETTLE_PROBE_MAX_ATTEMPTS = 3;
94+
const SETTLE_PROBE_RETRY_DELAY = Duration.millis(100);
9395
/**
9496
* Pi has no native signal for extension work that outlives a turn. Extensions
95-
* hold a status under this key, or `<key>:<job>`, until the work ends, so the
96-
* idle release keeps the process (and the work) alive.
97+
* hold a status under this key, or `<key>:<job>`, until the work ends. Each one
98+
* is a pending background task, so the idle release keeps the process (and the
99+
* work) alive and Stop can end it.
97100
*/
98101
const PI_BACKGROUND_WORK_STATUS_KEY = "t3:background";
99-
const SETTLE_PROBE_RETRY_DELAY = Duration.millis(100);
100102

101103
const PiProviderCapabilitiesV2 = {
102104
runtimePolicy: { enforcement: "client-boundary" },
@@ -545,7 +547,11 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
545547
let stopRequested = false;
546548
let unsolicitedActivityDetected = false;
547549
let pendingWake: PiWake | null = null;
548-
const backgroundWorkStatusKeys = new Set<string>();
550+
// Status key to its text, which becomes the task description.
551+
const backgroundWork = new Map<string, string>();
552+
// The thread whose roster lists backgroundWork, kept past lifecycle
553+
// failures that clear threadState so its roster can still be emptied.
554+
let backgroundWorkState: PiThreadState | null = null;
549555
let rollbackBarrier: Deferred.Deferred<
550556
void,
551557
ProviderAdapter.ProviderAdapterProtocolError
@@ -555,6 +561,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
555561
Effect.gen(function* () {
556562
closed = true;
557563
pendingWake = null;
564+
backgroundWork.clear();
558565
if (rollbackBarrier !== null)
559566
yield* Deferred.fail(
560567
rollbackBarrier,
@@ -660,8 +667,27 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
660667
return null;
661668
};
662669

663-
const lifecycleRequest = (record: PiRpcRecord) =>
664-
request(record, PI_SESSION_TIMEOUT_MS).pipe(
670+
const pendingBackgroundTasks = () =>
671+
Array.from(backgroundWork, ([taskId, description]) => ({
672+
taskId,
673+
kind: "background_task" as const,
674+
description,
675+
}));
676+
677+
const syncBackgroundWork = (state: PiThreadState) => {
678+
backgroundWorkState = state;
679+
return updateProviderThread(state, { pendingBackgroundTasks: pendingBackgroundTasks() });
680+
};
681+
682+
const lifecycleRequest = Effect.fnUntraced(function* (record: PiRpcRecord) {
683+
// Pi invalidates the outgoing session's extension context, so its jobs
684+
// can no longer clear their statuses. Pi's own TUI drops them here too.
685+
const outgoingWork = new Map(backgroundWork);
686+
const outgoingState = backgroundWorkState;
687+
backgroundWork.clear();
688+
if (outgoingState !== null && outgoingWork.size > 0)
689+
yield* syncBackgroundWork(outgoingState);
690+
const result = yield* request(record, PI_SESSION_TIMEOUT_MS).pipe(
665691
// A local timeout does not cancel Pi's lifecycle hook. Retire the
666692
// process before fallback can race its eventual switch/new-session.
667693
Effect.tapError((error) =>
@@ -677,6 +703,14 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
677703
}),
678704
Effect.onInterrupt(() => connection.terminate),
679705
);
706+
if (recordField(result, "cancelled") === true && outgoingWork.size > 0) {
707+
for (const [key, description] of outgoingWork) {
708+
if (!backgroundWork.has(key)) backgroundWork.set(key, description);
709+
}
710+
if (outgoingState !== null) yield* syncBackgroundWork(outgoingState);
711+
}
712+
return result;
713+
});
680714

681715
const tokenUsageFromStats = (
682716
stats: unknown,
@@ -1249,11 +1283,16 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
12491283
) {
12501284
return;
12511285
}
1252-
if ((recordString(event, "statusText") ?? "").length > 0) {
1253-
backgroundWorkStatusKeys.add(statusKey);
1254-
} else {
1255-
backgroundWorkStatusKeys.delete(statusKey);
1286+
const description = NodeUtil.stripVTControlCharacters(
1287+
recordString(event, "statusText") ?? "",
1288+
).trim();
1289+
if (description.length > 0) {
1290+
if (backgroundWork.get(statusKey) === description) return;
1291+
backgroundWork.set(statusKey, description);
1292+
} else if (!backgroundWork.delete(statusKey)) {
1293+
return;
12561294
}
1295+
if (threadState !== null) yield* syncBackgroundWork(threadState);
12571296
return;
12581297
}
12591298
if (method === "notify") {
@@ -2269,6 +2308,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
22692308
providerSessionId: input.providerSessionId,
22702309
nativeThreadRef: providerRef(nativeId),
22712310
...(needsNewSession ? { nativeConversationHeadRef: null, contextUsage: null } : {}),
2311+
pendingBackgroundTasks: pendingBackgroundTasks(),
22722312
status: "idle",
22732313
updatedAt: createdAt,
22742314
}
@@ -2289,11 +2329,12 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
22892329
lastRunOrdinal: null,
22902330
handoffIds: [],
22912331
forkedFrom: null,
2292-
pendingBackgroundTasks: [],
2332+
pendingBackgroundTasks: pendingBackgroundTasks(),
22932333
createdAt,
22942334
updatedAt: createdAt,
22952335
};
22962336
threadState = { providerThread, activeTurn: null };
2337+
backgroundWorkState = threadState;
22972338
const baselineEntries = yield* request({ type: "get_entries" }).pipe(
22982339
Effect.orElseSucceed(() => undefined),
22992340
);
@@ -2397,12 +2438,15 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
23972438
},
23982439
events: Stream.fromQueue(events),
23992440
hasPendingBackgroundWork: Effect.sync(
2400-
() => pendingWake !== null || backgroundWorkStatusKeys.size > 0,
2441+
() => pendingWake !== null || backgroundWork.size > 0,
24012442
),
24022443
hasPendingBackgroundWorkForThread: (providerThread) =>
24032444
Effect.sync(
2404-
() => pendingWake !== null && pendingWake.state.providerThread.id === providerThread.id,
2445+
() =>
2446+
(pendingWake !== null && pendingWake.state.providerThread.id === providerThread.id) ||
2447+
(backgroundWork.size > 0 && threadState?.providerThread.id === providerThread.id),
24052448
),
2449+
backgroundTasksEndWithProcess: true,
24062450
getModelContextWindow: (selection) => {
24072451
if (selection.instanceId !== options.instanceId) return undefined;
24082452
const slug =
@@ -2706,6 +2750,11 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
27062750
if (turn === null && interruptInput.requestRuntimeRestart === true) {
27072751
if (pendingWake !== null)
27082752
yield* sessionEventPermit.withPermits(1)(stopPendingWake(pendingWake));
2753+
else if (backgroundWork.size > 0) {
2754+
stopRequested = true;
2755+
backgroundWork.clear();
2756+
yield* connection.terminate;
2757+
}
27092758
return;
27102759
}
27112760
if (turn === null || turn.providerTurn.id !== interruptInput.providerTurnId) {

0 commit comments

Comments
 (0)