Skip to content

Commit f9e1bd7

Browse files
committed
fix(pi): expire extension approval requests
1 parent 8c777fb commit f9e1bd7

4 files changed

Lines changed: 172 additions & 6 deletions

File tree

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

Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2551,6 +2551,110 @@ describe("PiAdapterV2", () => {
25512551
}).pipe(Effect.scoped, Effect.provide(layerTest)),
25522552
);
25532553

2554+
it.effect("expires native dialogs and rejects stale answers without caching approval", () =>
2555+
Effect.gen(function* () {
2556+
const fake = yield* makeFakePi;
2557+
const { runtime, takeEvent } = yield* openRuntime(fake);
2558+
yield* runtime.ensureThread({
2559+
threadId: THREAD_ID,
2560+
modelSelection: modelSelection("default"),
2561+
runtimePolicy,
2562+
});
2563+
const dialog = {
2564+
type: "extension_ui_request",
2565+
method: "confirm",
2566+
title: "Allow extension?",
2567+
message: "Approve this operation",
2568+
};
2569+
yield* fake.emit({ ...dialog, id: "timed-dialog", timeout: 1000 });
2570+
const pending = yield* takeEvent(
2571+
(event) => event.type === "turn_item.updated" && event.turnItem.type === "approval_request",
2572+
);
2573+
assert.isTrue(
2574+
pending.type === "turn_item.updated" && pending.turnItem.type === "approval_request",
2575+
);
2576+
if (pending.type !== "turn_item.updated" || pending.turnItem.type !== "approval_request")
2577+
return;
2578+
const requestId = pending.turnItem.requestId;
2579+
yield* TestClock.adjust(Duration.seconds(1));
2580+
yield* takeEvent(
2581+
(event) =>
2582+
event.type === "runtime_request.updated" &&
2583+
event.runtimeRequest.id === requestId &&
2584+
event.runtimeRequest.status === "cancelled",
2585+
);
2586+
assert.equal((yield* fake.takeRequest("extension_ui_response"))["cancelled"], true);
2587+
const late = yield* Effect.result(
2588+
runtime.respondToRuntimeRequest({
2589+
requestId: pending.turnItem.requestId,
2590+
decision: "acceptForSession",
2591+
}),
2592+
);
2593+
assert.equal(late._tag, "Failure");
2594+
yield* fake.emit({ ...dialog, id: "fresh-dialog", timeout: 1000 });
2595+
const fresh = yield* takeEvent(
2596+
(event) =>
2597+
event.type === "runtime_request.updated" &&
2598+
event.runtimeRequest.status === "pending" &&
2599+
event.runtimeRequest.nativeRequestRef?.nativeId === "fresh-dialog",
2600+
);
2601+
if (fresh.type !== "runtime_request.updated") return;
2602+
yield* runtime.respondToRuntimeRequest({
2603+
requestId: fresh.runtimeRequest.id,
2604+
decision: "accept",
2605+
});
2606+
assert.equal((yield* fake.takeRequest("extension_ui_response"))["id"], "fresh-dialog");
2607+
// The old expiry must not cancel an already answered request, and zero disables expiry.
2608+
yield* fake.emit({ ...dialog, id: "zero-timeout", timeout: 0 });
2609+
const zero = yield* takeEvent(
2610+
(event) =>
2611+
event.type === "runtime_request.updated" &&
2612+
event.runtimeRequest.status === "pending" &&
2613+
event.runtimeRequest.nativeRequestRef?.nativeId === "zero-timeout",
2614+
);
2615+
yield* TestClock.adjust(Duration.seconds(60));
2616+
if (zero.type !== "runtime_request.updated") return;
2617+
yield* runtime.respondToRuntimeRequest({
2618+
requestId: zero.runtimeRequest.id,
2619+
decision: "decline",
2620+
});
2621+
const response = yield* fake.takeRequest("extension_ui_response");
2622+
assert.equal(response["id"], "zero-timeout");
2623+
assert.equal(response["confirmed"], false);
2624+
}).pipe(Effect.scoped, Effect.provide(layerTest)),
2625+
);
2626+
2627+
it.effect("cancels startup dialogs when Pi exits before a turn exists", () =>
2628+
Effect.gen(function* () {
2629+
const fake = yield* makeFakePi;
2630+
const { runtime, takeEvent } = yield* openRuntime(fake);
2631+
yield* runtime.ensureThread({
2632+
threadId: THREAD_ID,
2633+
modelSelection: modelSelection("default"),
2634+
runtimePolicy,
2635+
});
2636+
yield* fake.emit({
2637+
type: "extension_ui_request",
2638+
id: "startup",
2639+
method: "confirm",
2640+
title: "Trust project?",
2641+
});
2642+
const pending = yield* takeEvent(
2643+
(event) =>
2644+
event.type === "runtime_request.updated" && event.runtimeRequest.status === "pending",
2645+
);
2646+
if (pending.type !== "runtime_request.updated") return;
2647+
yield* fake.closeStdout;
2648+
const cancelled = yield* takeEvent(
2649+
(event) =>
2650+
event.type === "runtime_request.updated" &&
2651+
event.runtimeRequest.id === pending.runtimeRequest.id &&
2652+
event.runtimeRequest.status === "cancelled",
2653+
);
2654+
assert.isTrue(cancelled.type === "runtime_request.updated");
2655+
}).pipe(Effect.scoped, Effect.provide(layerTest)),
2656+
);
2657+
25542658
it.effect("remembers session approvals only for identical confirmation content", () =>
25552659
Effect.gen(function* () {
25562660
const fake = yield* makeFakePi;

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

Lines changed: 53 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@ import * as Option from "effect/Option";
5454
import * as Duration from "effect/Duration";
5555
import * as Effect from "effect/Effect";
5656
import * as FileSystem from "effect/FileSystem";
57+
import * as Fiber from "effect/Fiber";
5758
import * as Layer from "effect/Layer";
5859
import * as Queue from "effect/Queue";
5960
import * as Schema from "effect/Schema";
@@ -354,6 +355,8 @@ interface PendingPiPrompt {
354355
readonly method: "select" | "confirm" | "input" | "editor";
355356
readonly questionId: string;
356357
readonly approvalKey: string;
358+
readonly expiresAt: number | null;
359+
expirationFiber: Fiber.Fiber<void> | null;
357360
runtimeRequest: OrchestrationV2RuntimeRequest;
358361
readonly node: OrchestrationV2ExecutionNode;
359362
readonly turnItem: OrchestrationV2TurnItem;
@@ -1165,6 +1168,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
11651168

11661169
const cancelPrompt = (pending: PendingPiPrompt, resolvedAt: DateTime.Utc) =>
11671170
Effect.gen(function* () {
1171+
if (pending.expirationFiber !== null) yield* Fiber.interrupt(pending.expirationFiber);
11681172
yield* connection
11691173
.send({
11701174
type: "extension_ui_response",
@@ -1263,6 +1267,12 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
12631267
const state = threadState;
12641268
const turn = state?.activeTurn ?? null;
12651269
const createdAt = yield* DateTime.now;
1270+
const timeout = recordNumber(event, "timeout");
1271+
// Pi treats zero as no timeout and negative durations as immediate expiry.
1272+
const expiresAt =
1273+
timeout === undefined || timeout === 0
1274+
? null
1275+
: DateTime.toEpochMillis(createdAt) + Math.max(0, timeout);
12661276
const requestId = yield* idAllocator.allocate.runtimeRequest({
12671277
driver: PI_PROVIDER,
12681278
...(turn === null ? {} : { providerTurnId: turn.providerTurn.id }),
@@ -1335,15 +1345,18 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
13351345
requestId,
13361346
questions: [piQuestion(nativeRequestId, method, title, event)],
13371347
};
1338-
pendingPrompts.set(String(requestId), {
1348+
const pending: PendingPiPrompt = {
13391349
nativeRequestId,
13401350
method,
13411351
questionId: nativeRequestId,
13421352
approvalKey,
1353+
expiresAt,
1354+
expirationFiber: null,
13431355
runtimeRequest,
13441356
node,
13451357
turnItem,
1346-
});
1358+
};
1359+
pendingPrompts.set(String(requestId), pending);
13471360
yield* emit({
13481361
type: "runtime_request.updated",
13491362
driver: PI_PROVIDER,
@@ -1352,6 +1365,22 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
13521365
});
13531366
yield* emit({ type: "node.updated", driver: PI_PROVIDER, node });
13541367
yield* emit({ type: "turn_item.updated", driver: PI_PROVIDER, turnItem });
1368+
if (expiresAt !== null) {
1369+
const now = yield* DateTime.now;
1370+
pending.expirationFiber = yield* Effect.sleep(
1371+
Duration.millis(Math.max(0, expiresAt - DateTime.toEpochMillis(now))),
1372+
).pipe(
1373+
Effect.andThen(
1374+
Queue.offer(connection.events, {
1375+
type: "t3.ui_request_expired",
1376+
requestId: String(requestId),
1377+
pending,
1378+
}),
1379+
),
1380+
Effect.asVoid,
1381+
Effect.forkIn(scope),
1382+
);
1383+
}
13551384
});
13561385

13571386
const emitExtensionError = Effect.fnUntraced(function* (event: PiRpcRecord) {
@@ -2028,6 +2057,15 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
20282057
}
20292058
return;
20302059
}
2060+
case "t3.ui_request_expired": {
2061+
const requestId = recordString(event, "requestId");
2062+
if (requestId === undefined) return;
2063+
const pending = pendingPrompts.get(requestId);
2064+
if (pending === undefined || pending !== event["pending"]) return;
2065+
pendingPrompts.delete(requestId);
2066+
yield* cancelPrompt(pending, yield* DateTime.now);
2067+
return;
2068+
}
20312069
case "t3.flush_extension_errors": {
20322070
// Startup extension failures are informational and do not block
20332071
// Pi, so attach them to the next real turn instead of creating a
@@ -2107,7 +2145,6 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
21072145
rollbackBarrier,
21082146
protocolError("Pi transport closed during rollback"),
21092147
);
2110-
const hadPendingWake = pendingWake !== null;
21112148
pendingWake = null;
21122149
const interrupted = state?.activeTurn?.interrupted === true;
21132150
if (state?.activeTurn != null) {
@@ -2119,7 +2156,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
21192156
class: "transport_error",
21202157
});
21212158
yield* finalizeTurn(state, false);
2122-
} else if (hadPendingWake) {
2159+
} else {
21232160
yield* cancelPendingPrompts(yield* DateTime.now);
21242161
}
21252162
if (unsolicitedActivityDetected) {
@@ -2738,6 +2775,17 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
27382775
`No pending Pi extension request ${requestInput.requestId}`,
27392776
);
27402777
}
2778+
const answeredAt = yield* DateTime.now;
2779+
if (
2780+
pending.expiresAt !== null &&
2781+
DateTime.toEpochMillis(answeredAt) >= pending.expiresAt
2782+
) {
2783+
pendingPrompts.delete(String(requestInput.requestId));
2784+
yield* cancelPrompt(pending, answeredAt);
2785+
return yield* protocolError(
2786+
`Pi extension request ${requestInput.requestId} has expired`,
2787+
);
2788+
}
27412789
const response = piUiResponse(pending, requestInput.decision, requestInput.answers);
27422790
yield* connection.send({
27432791
type: "extension_ui_response",
@@ -2747,6 +2795,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
27472795
// Dropped only once Pi has the answer, so a failed send leaves the
27482796
// request retryable and still cancellable during teardown.
27492797
pendingPrompts.delete(String(requestInput.requestId));
2798+
if (pending.expirationFiber !== null) yield* Fiber.interrupt(pending.expirationFiber);
27502799
if (pending.method === "confirm" && requestInput.decision === "acceptForSession") {
27512800
sessionApprovals.add(pending.approvalKey);
27522801
}

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

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -304,7 +304,16 @@ describe("Pi tool discovery permissions", () => {
304304
it("allows discovery without confirmation and still gates the discovered tool", async () => {
305305
type ToolCallHook = (
306306
event: { toolName: string; input: unknown },
307-
ctx: { ui: { confirm: (title: string, detail: string) => Promise<boolean> } },
307+
ctx: {
308+
signal: AbortSignal;
309+
ui: {
310+
confirm: (
311+
title: string,
312+
detail: string,
313+
options: { signal: AbortSignal },
314+
) => Promise<boolean>;
315+
};
316+
},
308317
) => Promise<{ block: true; reason: string } | undefined>;
309318
let toolCall: ToolCallHook | undefined;
310319
let searchPath = "builtin:tool-search";
@@ -325,9 +334,12 @@ describe("Pi tool discovery permissions", () => {
325334
});
326335
assert.isDefined(toolCall);
327336
const confirmations: string[] = [];
337+
const controller = new AbortController();
328338
const ctx = {
339+
signal: controller.signal,
329340
ui: {
330-
confirm: async (title: string) => {
341+
confirm: async (title: string, _detail: string, options: { signal: AbortSignal }) => {
342+
assert.strictEqual(options.signal, controller.signal);
331343
confirmations.push(title);
332344
return false;
333345
},

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -286,6 +286,7 @@ export default async function t3McpExtension(pi: ExtensionAPI) {
286286
const approved = await ctx.ui.confirm(
287287
\`Allow \${event.toolName}?\`,
288288
toolInputSummary(event.input),
289+
{ signal: ctx.signal },
289290
);
290291
if (!approved) {
291292
return { block: true, reason: \`\${event.toolName} was declined in T3 Code.\` };

0 commit comments

Comments
 (0)