fix(pi): expire and cancel extension approvals (#17840)
This commit is contained in:
1 parent
62da1cd48b
commit
6e9c5a851c
4 files changed
+172
-6
No files matched your search
@@ -2912,6 +2912,110 @@ describe("PiAdapterV2", () => {
|
||||
}).pipe(Effect.scoped, Effect.provide(layerTest)),
|
||||
);
|
||||
|
||||
it.effect("expires native dialogs and rejects stale answers without caching approval", () =>
|
||||
Effect.gen(function* () {
|
||||
const fake = yield* makeFakePi;
|
||||
const { runtime, takeEvent } = yield* openRuntime(fake);
|
||||
yield* runtime.ensureThread({
|
||||
threadId: THREAD_ID,
|
||||
modelSelection: modelSelection("default"),
|
||||
runtimePolicy,
|
||||
});
|
||||
const dialog = {
|
||||
type: "extension_ui_request",
|
||||
method: "confirm",
|
||||
title: "Allow extension?",
|
||||
message: "Approve this operation",
|
||||
};
|
||||
yield* fake.emit({ ...dialog, id: "timed-dialog", timeout: 1000 });
|
||||
const pending = yield* takeEvent(
|
||||
(event) => event.type === "turn_item.updated" && event.turnItem.type === "approval_request",
|
||||
);
|
||||
assert.isTrue(
|
||||
pending.type === "turn_item.updated" && pending.turnItem.type === "approval_request",
|
||||
);
|
||||
if (pending.type !== "turn_item.updated" || pending.turnItem.type !== "approval_request")
|
||||
return;
|
||||
const requestId = pending.turnItem.requestId;
|
||||
yield* TestClock.adjust(Duration.seconds(1));
|
||||
yield* takeEvent(
|
||||
(event) =>
|
||||
event.type === "runtime_request.updated" &&
|
||||
event.runtimeRequest.id === requestId &&
|
||||
event.runtimeRequest.status === "cancelled",
|
||||
);
|
||||
assert.equal((yield* fake.takeRequest("extension_ui_response"))["cancelled"], true);
|
||||
const late = yield* Effect.result(
|
||||
runtime.respondToRuntimeRequest({
|
||||
requestId: pending.turnItem.requestId,
|
||||
decision: "acceptForSession",
|
||||
}),
|
||||
);
|
||||
assert.equal(late._tag, "Failure");
|
||||
yield* fake.emit({ ...dialog, id: "fresh-dialog", timeout: 1000 });
|
||||
const fresh = yield* takeEvent(
|
||||
(event) =>
|
||||
event.type === "runtime_request.updated" &&
|
||||
event.runtimeRequest.status === "pending" &&
|
||||
event.runtimeRequest.nativeRequestRef?.nativeId === "fresh-dialog",
|
||||
);
|
||||
if (fresh.type !== "runtime_request.updated") return;
|
||||
yield* runtime.respondToRuntimeRequest({
|
||||
requestId: fresh.runtimeRequest.id,
|
||||
decision: "accept",
|
||||
});
|
||||
assert.equal((yield* fake.takeRequest("extension_ui_response"))["id"], "fresh-dialog");
|
||||
// The old expiry must not cancel an already answered request, and zero disables expiry.
|
||||
yield* fake.emit({ ...dialog, id: "zero-timeout", timeout: 0 });
|
||||
const zero = yield* takeEvent(
|
||||
(event) =>
|
||||
event.type === "runtime_request.updated" &&
|
||||
event.runtimeRequest.status === "pending" &&
|
||||
event.runtimeRequest.nativeRequestRef?.nativeId === "zero-timeout",
|
||||
);
|
||||
yield* TestClock.adjust(Duration.seconds(60));
|
||||
if (zero.type !== "runtime_request.updated") return;
|
||||
yield* runtime.respondToRuntimeRequest({
|
||||
requestId: zero.runtimeRequest.id,
|
||||
decision: "decline",
|
||||
});
|
||||
const response = yield* fake.takeRequest("extension_ui_response");
|
||||
assert.equal(response["id"], "zero-timeout");
|
||||
assert.equal(response["confirmed"], false);
|
||||
}).pipe(Effect.scoped, Effect.provide(layerTest)),
|
||||
);
|
||||
|
||||
it.effect("cancels startup dialogs when Pi exits before a turn exists", () =>
|
||||
Effect.gen(function* () {
|
||||
const fake = yield* makeFakePi;
|
||||
const { runtime, takeEvent } = yield* openRuntime(fake);
|
||||
yield* runtime.ensureThread({
|
||||
threadId: THREAD_ID,
|
||||
modelSelection: modelSelection("default"),
|
||||
runtimePolicy,
|
||||
});
|
||||
yield* fake.emit({
|
||||
type: "extension_ui_request",
|
||||
id: "startup",
|
||||
method: "confirm",
|
||||
title: "Trust project?",
|
||||
});
|
||||
const pending = yield* takeEvent(
|
||||
(event) =>
|
||||
event.type === "runtime_request.updated" && event.runtimeRequest.status === "pending",
|
||||
);
|
||||
if (pending.type !== "runtime_request.updated") return;
|
||||
yield* fake.closeStdout;
|
||||
const cancelled = yield* takeEvent(
|
||||
(event) =>
|
||||
event.type === "runtime_request.updated" &&
|
||||
event.runtimeRequest.id === pending.runtimeRequest.id &&
|
||||
event.runtimeRequest.status === "cancelled",
|
||||
);
|
||||
assert.isTrue(cancelled.type === "runtime_request.updated");
|
||||
}).pipe(Effect.scoped, Effect.provide(layerTest)),
|
||||
);
|
||||
|
||||
it.effect("remembers session approvals only for identical confirmation content", () =>
|
||||
Effect.gen(function* () {
|
||||
const fake = yield* makeFakePi;
|
||||
|
||||
@@ -56,6 +56,7 @@ import * as Option from "effect/Option";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Queue from "effect/Queue";
|
||||
import * as Schema from "effect/Schema";
|
||||
@@ -456,6 +457,8 @@ interface PendingPiPrompt {
|
||||
readonly method: "select" | "confirm" | "input" | "editor";
|
||||
readonly questionId: string;
|
||||
readonly approvalKey: string;
|
||||
readonly expiresAt: number | null;
|
||||
expirationFiber: Fiber.Fiber<void> | null;
|
||||
runtimeRequest: OrchestrationV2RuntimeRequest;
|
||||
readonly node: OrchestrationV2ExecutionNode;
|
||||
readonly turnItem: OrchestrationV2TurnItem;
|
||||
@@ -1270,6 +1273,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
|
||||
|
||||
const cancelPrompt = (pending: PendingPiPrompt, resolvedAt: DateTime.Utc) =>
|
||||
Effect.gen(function* () {
|
||||
if (pending.expirationFiber !== null) yield* Fiber.interrupt(pending.expirationFiber);
|
||||
yield* connection
|
||||
.send({
|
||||
type: "extension_ui_response",
|
||||
@@ -1368,6 +1372,12 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
|
||||
const state = threadState;
|
||||
const turn = state?.activeTurn ?? null;
|
||||
const createdAt = yield* DateTime.now;
|
||||
const timeout = recordNumber(event, "timeout");
|
||||
// Pi treats zero as no timeout and negative durations as immediate expiry.
|
||||
const expiresAt =
|
||||
timeout === undefined || timeout === 0
|
||||
? null
|
||||
: DateTime.toEpochMillis(createdAt) + Math.max(0, timeout);
|
||||
const requestId = yield* idAllocator.allocate.runtimeRequest({
|
||||
driver: PI_PROVIDER,
|
||||
...(turn === null ? {} : { providerTurnId: turn.providerTurn.id }),
|
||||
@@ -1440,15 +1450,18 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
|
||||
requestId,
|
||||
questions: [piQuestion(nativeRequestId, method, title, event)],
|
||||
};
|
||||
pendingPrompts.set(String(requestId), {
|
||||
const pending: PendingPiPrompt = {
|
||||
nativeRequestId,
|
||||
method,
|
||||
questionId: nativeRequestId,
|
||||
approvalKey,
|
||||
expiresAt,
|
||||
expirationFiber: null,
|
||||
runtimeRequest,
|
||||
node,
|
||||
turnItem,
|
||||
});
|
||||
};
|
||||
pendingPrompts.set(String(requestId), pending);
|
||||
yield* emit({
|
||||
type: "runtime_request.updated",
|
||||
driver: PI_PROVIDER,
|
||||
@@ -1457,6 +1470,22 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
|
||||
});
|
||||
yield* emit({ type: "node.updated", driver: PI_PROVIDER, node });
|
||||
yield* emit({ type: "turn_item.updated", driver: PI_PROVIDER, turnItem });
|
||||
if (expiresAt !== null) {
|
||||
const now = yield* DateTime.now;
|
||||
pending.expirationFiber = yield* Effect.sleep(
|
||||
Duration.millis(Math.max(0, expiresAt - DateTime.toEpochMillis(now))),
|
||||
).pipe(
|
||||
Effect.andThen(
|
||||
Queue.offer(connection.events, {
|
||||
type: "t3.ui_request_expired",
|
||||
requestId: String(requestId),
|
||||
pending,
|
||||
}),
|
||||
),
|
||||
Effect.asVoid,
|
||||
Effect.forkIn(scope),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
const emitExtensionError = Effect.fnUntraced(function* (event: PiRpcRecord) {
|
||||
@@ -2132,6 +2161,15 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
|
||||
}
|
||||
return;
|
||||
}
|
||||
case "t3.ui_request_expired": {
|
||||
const requestId = recordString(event, "requestId");
|
||||
if (requestId === undefined) return;
|
||||
const pending = pendingPrompts.get(requestId);
|
||||
if (pending === undefined || pending !== event["pending"]) return;
|
||||
pendingPrompts.delete(requestId);
|
||||
yield* cancelPrompt(pending, yield* DateTime.now);
|
||||
return;
|
||||
}
|
||||
case "t3.flush_extension_errors": {
|
||||
// Startup extension failures are informational and do not block
|
||||
// Pi, so attach them to the next real turn instead of creating a
|
||||
@@ -2211,7 +2249,6 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
|
||||
rollbackBarrier,
|
||||
protocolError("Pi transport closed during rollback"),
|
||||
);
|
||||
const hadPendingWake = pendingWake !== null;
|
||||
pendingWake = null;
|
||||
const interrupted = state?.activeTurn?.interrupted === true;
|
||||
if (state?.activeTurn != null) {
|
||||
@@ -2223,7 +2260,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
|
||||
class: "transport_error",
|
||||
});
|
||||
yield* finalizeTurn(state, false);
|
||||
} else if (hadPendingWake) {
|
||||
} else {
|
||||
yield* cancelPendingPrompts(yield* DateTime.now);
|
||||
}
|
||||
if (unsolicitedActivityDetected) {
|
||||
@@ -2844,6 +2881,17 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
|
||||
`No pending Pi extension request ${requestInput.requestId}`,
|
||||
);
|
||||
}
|
||||
const answeredAt = yield* DateTime.now;
|
||||
if (
|
||||
pending.expiresAt !== null &&
|
||||
DateTime.toEpochMillis(answeredAt) >= pending.expiresAt
|
||||
) {
|
||||
pendingPrompts.delete(String(requestInput.requestId));
|
||||
yield* cancelPrompt(pending, answeredAt);
|
||||
return yield* protocolError(
|
||||
`Pi extension request ${requestInput.requestId} has expired`,
|
||||
);
|
||||
}
|
||||
const response = piUiResponse(pending, requestInput.decision, requestInput.answers);
|
||||
yield* connection.send({
|
||||
type: "extension_ui_response",
|
||||
@@ -2853,6 +2901,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
|
||||
// Dropped only once Pi has the answer, so a failed send leaves the
|
||||
// request retryable and still cancellable during teardown.
|
||||
pendingPrompts.delete(String(requestInput.requestId));
|
||||
if (pending.expirationFiber !== null) yield* Fiber.interrupt(pending.expirationFiber);
|
||||
if (pending.method === "confirm" && requestInput.decision === "acceptForSession") {
|
||||
sessionApprovals.add(pending.approvalKey);
|
||||
}
|
||||
|
||||
@@ -249,7 +249,16 @@ describe("Pi tool discovery permissions", () => {
|
||||
it("allows discovery without confirmation and still gates the discovered tool", async () => {
|
||||
type ToolCallHook = (
|
||||
event: { toolName: string; input: unknown },
|
||||
ctx: { ui: { confirm: (title: string, detail: string) => Promise<boolean> } },
|
||||
ctx: {
|
||||
signal: AbortSignal;
|
||||
ui: {
|
||||
confirm: (
|
||||
title: string,
|
||||
detail: string,
|
||||
options: { signal: AbortSignal },
|
||||
) => Promise<boolean>;
|
||||
};
|
||||
},
|
||||
) => Promise<{ block: true; reason: string } | undefined>;
|
||||
let toolCall: ToolCallHook | undefined;
|
||||
let searchPath = "builtin:tool-search";
|
||||
@@ -270,9 +279,12 @@ describe("Pi tool discovery permissions", () => {
|
||||
});
|
||||
assert.isDefined(toolCall);
|
||||
const confirmations: string[] = [];
|
||||
const controller = new AbortController();
|
||||
const ctx = {
|
||||
signal: controller.signal,
|
||||
ui: {
|
||||
confirm: async (title: string) => {
|
||||
confirm: async (title: string, _detail: string, options: { signal: AbortSignal }) => {
|
||||
assert.strictEqual(options.signal, controller.signal);
|
||||
confirmations.push(title);
|
||||
return false;
|
||||
},
|
||||
|
||||
@@ -318,6 +318,7 @@ export default async function t3McpExtension(pi: ExtensionAPI) {
|
||||
const approved = await ctx.ui.confirm(
|
||||
\`Allow \${event.toolName}?\`,
|
||||
toolInputSummary(event.input),
|
||||
{ signal: ctx.signal },
|
||||
);
|
||||
if (!approved) {
|
||||
return { block: true, reason: \`\${event.toolName} was declined in T3 Code.\` };
|
||||
|
||||
Reference in new issue
Block a user