pi-ext
bugabingas pi extensions
owned by admin
fix(masks): preserve masks through recovery and queued work
47c455158deff60694ab85eb016dcfd7e90eaf76
Oliver Jan Krylow <oliver@bugabinga.net> ·
SSH signature · not checked
Browse filesCompare with HEAD
Changed files (3)
extensions/masks/README.md
Modified14 14 - `/masks` opens the fuzzy mask picker.
15 15 - `/masks <name>` equips one mask directly.
16 +- `/masks-cancel` discards deferred masked prompts without interrupting the current run.
22 -- `input` detects prompt templates declaring a mask.
23 +- `input` detects masked templates and defers busy follow-ups.
23 24 - `before_agent_start` equips a prompt mask.
24 -- `agent_end` restores the previous model and thinking level.
25 +- `turn_end` restores after successful completion; `agent_settled` restores after recovery and starts the next deferred prompt.
25 26 - `session_start` reports invalid mask settings.
50 51 Settings are global because masks describe personal model access and bindings.
51 52 Run `/reload` after changing them.
53 -Prompt templates may equip a mask for one agent run:
54 +Prompt templates may equip a mask for one prompt and its tool loop:
63 64 `mask` must exactly match a configured mask name.
64 -The mask lasts through the prompt's tool loop and is restored at `agent_end`.
65 -Masked prompts cannot be queued while another agent run is active.
65 +The mask lasts through tools and automatic retries, then restores before the next ordinary follow-up.
66 +Failed mask switches abort the prompt; failed restoration blocks later prompts until restoration succeeds.
68 +Busy masked follow-ups use an extension-owned FIFO queue, shown in the footer.
69 +They run after Pi's native queue drains, not in mixed submission order.
70 +Templates and masks are resolved at execution; attached images are preserved.
71 +Steering a masked template is rejected because it would change the current run's model.
72 +Abort, error, tree navigation, and session shutdown discard deferred prompts.
73 +Pi's native queue editor does not manage this queue; use `/masks-cancel`.
75 +Pi provides no dispatch acknowledgement: rejected or failed dispatches can lose a prompt and stall the remaining queue.
76 +Concurrent input during masked preparation is rejected instead of risking the wrong model.
77 +If dispatch fails during preparation, `/reload` clears the reservation and deferred queue.
extensions/masks/__tests__/harness.test.ts
Modified 2 2 import { mkdirSync, mkdtempSync, rmSync, writeFileSync }
from "node:fs";
3 3 import { tmpdir }
from "node:os";
4 4 import { join }
from "node:path";
5 5 import { fileURLToPath }
from "node:url";
6 -import { afterEach, describe, expect, it }
from "vitest";
6 +import { afterEach, describe, expect, it, vi }
from "vitest";
7 7 import { createTestSession, type TestSession }
from "../../../test/harness";
8 8 import { __test }
from "../index.ts";
38 38 return t.session.extensionRunner.
createCommandContext();
41 +type Request = { text
: string; model
: string; thinking
: string | undefined };
43 +async function queuedSession(
47 + )
=> Promise<
Record<
string,
unknown>
| undefined>,
48 +)
: Promise<
Request[]> {
49 + const cwd
= writeSettings({
52 + { name:
"focused", model:
"openai/gpt-4o-mini", thinkingLevel:
"high" },
53 + { name:
"quick", model:
"openai/gpt-4o", thinkingLevel:
"low" },
57 + writePrompt(
"review",
"---\nmask: focused\n---\nReview $1.");
58 + writePrompt(
"plan",
"---\nmask: quick\n---\nPlan $1.");
59 + writeFileSync(
join(cwd,
"fixture.txt"),
"fixture");
60 + t
= await createTestSession({ cwd, extensions: [
extensionPath()] });
61 + for (
const name
of [
"gpt-4o",
"gpt-4o-mini"]) {
62 + context().modelRegistry.
find(
"openai", name).reasoning
= true;
64 + t.session.settingsManager.
setRetryEnabled(
false);
65 + const requests
: Request[]
= [];
66 + t.session.agent.
streamFn = async (model
: any, ctx
: any, options
: any)
=> {
69 + .
filter((m
: any)
=> m.role
=== "user")
71 + ?.
content.
filter((p
: any)
=> p.
type === "text")
72 + .
map((p
: any)
=> p.
text)
75 + thinking: options.reasoning,
77 + let reply
: Record<
string,
unknown>
| undefined;
78 + if (
!options.signal.aborted) {
79 + requests.
push(request);
80 + reply
= await onRequest(request, requests.
length - 1);
84 + content: [{ type:
"text", text:
"Done." }],
86 + provider: model.provider,
94 + cost: { input:
0, output:
0, cacheRead:
0, cacheWrite:
0, total:
0 },
96 + stopReason: options.signal.aborted
? "aborted" : "stop",
97 + timestamp:
Date.
now(),
101 + async *[
Symbol.asyncIterator]() {
102 + yield { type:
"done", reason: message.stopReason, message };
104 + result:
async ()
=> message,
110 +async function queue(text
: string)
: Promise<
void> {
111 + await t?.session.
sendUserMessage(text, {
112 + expandPromptTemplates:
true,
113 + deliverAs:
"followUp",
117 +async function settled(count
: number, requests
: Request[])
: Promise<
void> {
118 + await expect.
poll(()
=> requests.
length).
toBe(count);
119 + await expect.
poll(()
=> t?.session.isIdle).
toBe(
true);
123 + vi.
restoreAllMocks();
44 126 if (
root)
rmSync(
root, { recursive:
true, force:
true });
82 164 if (
!model)
throw new Error(
"missing harness model");
83 165 model.reasoning
= true;
85 - expect([
...extension().commands.
keys()]).
toEqual([
"masks"]);
167 + expect([
...extension().commands.
keys()]).
toEqual([
"masks-cancel",
"masks"]);
86 168 expect([
...extension().shortcuts.
keys()]).
toEqual([
141 223 const inputHandler
= extension().handlers.
get(
"input")[
0];
142 224 const beforeHandler
= extension().handlers.
get(
"before_agent_start")[
0];
143 - const endHandler
= extension().handlers.
get(
"agent_end")[
0];
225 + const endHandler
= extension().handlers.
get(
"agent_settled")[
0];
145 227 await inputHandler(
146 228 { type:
"input", text:
"/review", source:
"interactive" },
161 243 expect(t.session.thinkingLevel).
toBe(
"high");
163 - await endHandler({ type:
"agent_end", messages: [] },
context());
245 + await endHandler({ type:
"agent_settled" },
context());
164 246 expect(t.session.model.provider).
toBe(
"openai");
165 247 expect(t.session.model.
id).
toBe(
"gpt-4o");
166 248 expect(t.session.thinkingLevel).
toBe(
"off");
169 - it(
"rejects masked prompt templates queued mid-run",
async ()
=> {
251 + it(
"defers masked follow-ups without changing the running model",
async ()
=> {
170 252 const cwd
= writeSettings({
194 276 expect(result).
toEqual({ action:
"handled" });
195 - expect(t.events.
uiCallsFor(
"notify").
at(
-1)?.args).
toEqual([
196 - "Prompt /review: masked prompts cannot be queued mid-run",
277 + expect(t.session.thinkingLevel).
toBe(
"off");
278 + expect(t.events.
uiCallsFor(
"setStatus").
at(
-1)?.args).
toEqual([
280 + "masks: 1 deferred · /masks-cancel",
284 + it(
"runs deferred masks FIFO after native follow-ups and restores between them",
async ()
=> {
285 + const requests
= await queuedSession(
async (_request, index)
=> {
287 + await queue(
"/review first");
288 + await queue(
"ordinary follow-up");
289 + await queue(
"/plan second");
290 + expect(t?.session.model.
id).
toBe(
"gpt-4o");
294 + await t?.session.
prompt(
"start");
295 + await settled(
4, requests);
296 + expect(requests).
toEqual([
297 + { text:
"start", model:
"gpt-4o", thinking:
undefined },
298 + { text:
"ordinary follow-up", model:
"gpt-4o", thinking:
undefined },
299 + { text:
"Review first.", model:
"gpt-4o-mini", thinking:
"high" },
300 + { text:
"Plan second.", model:
"gpt-4o", thinking:
"low" },
302 + expect(t?.session.model.
id).
toBe(
"gpt-4o");
303 + expect(t?.session.thinkingLevel).
toBe(
"off");
306 + it(
"keeps the mask through tools, then restores before an ordinary follow-up",
async ()
=> {
307 + const requests
= await queuedSession(
async (_request, index)
=> {
309 + await queue(
"ordinary follow-up");
314 + id:
"read-fixture",
316 + arguments: { path:
"fixture.txt" },
319 + stopReason:
"toolUse",
324 + await t?.session.
prompt(
"/review first");
325 + await settled(
3, requests);
327 + requests.
map(({ model, thinking })
=> ({ model, thinking })),
329 + { model:
"gpt-4o-mini", thinking:
"high" },
330 + { model:
"gpt-4o-mini", thinking:
"high" },
331 + { model:
"gpt-4o", thinking:
undefined },
335 + it.
each([
"aborted",
"error"])(
336 + "discards deferred masks on %s and restores",
337 + async (stopReason)
=> {
338 + const requests
= await queuedSession(
async ()
=> {
339 + await queue(
"/plan later");
340 + return { stopReason, errorMessage:
"test failure" };
342 + await t?.session.
prompt(
"/review now");
343 + await settled(
1, requests);
344 + expect(t?.session.model.
id).
toBe(
"gpt-4o");
345 + expect(t?.session.thinkingLevel).
toBe(
"off");
346 + expect(t?.events.
uiCallsFor(
"notify").
at(
-1)?.args).
toEqual([
347 + "Cancelled 1 deferred masked prompts",
353 + it(
"cancels deferred prompts explicitly without stopping the current run",
async ()
=> {
354 + const requests
= await queuedSession(
async ()
=> {
355 + await queue(
"/plan later");
356 + await t?.session.
prompt(
"/masks-cancel");
357 + expect(
context().signal?.aborted).
toBe(
false);
360 + await t?.session.
prompt(
"/review now");
361 + await settled(
1, requests);
362 + expect(t?.session.thinkingLevel).
toBe(
"off");
365 + it(
"rejects steering without changing the active mask",
async ()
=> {
366 + const requests
= await queuedSession(
async ()
=> {
367 + await t?.session.
sendUserMessage(
"/plan later", {
368 + expandPromptTemplates:
true,
369 + deliverAs:
"steer",
371 + expect(t?.session.thinkingLevel).
toBe(
"high");
374 + await t?.session.
prompt(
"/review now");
375 + await settled(
1, requests);
376 + expect(t?.events.
uiCallsFor(
"notify").
at(
-1)?.args).
toEqual([
377 + "Prompt /plan: use follow-up delivery, not steering",
382 + it.
each([
"session_tree",
"session_shutdown"])(
383 + "clears deferred prompts on %s",
385 + const requests
= await queuedSession(
async ()
=> undefined);
386 + await extension().handlers.
get(
"input")[
0](
389 + text:
"/plan later",
390 + source:
"extension",
391 + streamingBehavior:
"followUp",
393 + {
...context(),
isIdle: ()
=> false },
395 + await extension().handlers.
get(type)[
0](
396 + { type, reason:
"reload" },
399 + await extension().handlers.
get(
"agent_settled")[
0](
400 + { type:
"agent_settled" },
403 + expect(requests).
toHaveLength(
0);
404 + expect(t?.events.
uiCallsFor(
"setStatus").
at(
-1)?.args).
toEqual([
411 + it(
"does not run the prompt under the wrong model when equipping fails",
async ()
=> {
412 + const requests
= await queuedSession(
async ()
=> undefined);
413 + vi.
spyOn(t?.session.extensionRunner.runtime,
"setModel").
mockResolvedValue(
416 + await t?.session.
prompt(
"/review now");
417 + expect(requests).
toHaveLength(
0);
420 + .
uiCallsFor(
"notify")
421 + .
some((call)
=> String(call.args[
0]).
includes(
"no credentials")),
425 + it(
"cancels deferred prompts and aborts when restoration fails",
async ()
=> {
426 + const requests
= await queuedSession(
async ()
=> {
427 + await queue(
"/plan later");
429 + t?.session.extensionRunner.runtime,
431 + ).
mockRejectedValue(
new Error(
"offline"));
434 + await t?.session.
prompt(
"/review now");
435 + await settled(
1, requests);
438 + .
uiCallsFor(
"notify")
439 + .
some((call)
=> String(call.args[
0]).
includes(
"Failed to restore")),
443 + it(
"retains the mask through automatic retry",
async ()
=> {
444 + const requests
= await queuedSession(
async (_request, index)
=> 446 + ? { stopReason:
"error", errorMessage:
"503 service unavailable" }
449 + vi.
spyOn(t?.session.settingsManager,
"getRetrySettings").
mockReturnValue({
454 + await t?.session.
prompt(
"/review retry");
455 + await settled(
2, requests);
457 + requests.
map(({ model, thinking })
=> ({ model, thinking })),
459 + { model:
"gpt-4o-mini", thinking:
"high" },
460 + { model:
"gpt-4o-mini", thinking:
"high" },
462 + expect(t?.session.model.
id).
toBe(
"gpt-4o");
463 + expect(t?.session.thinkingLevel).
toBe(
"off");
466 + it(
"keeps the mask for overflow recovery instead of skipping the same-model check",
async ()
=> {
467 + const requests
= await queuedSession(
async (_request, index)
=> 470 + stopReason:
"error",
471 + errorMessage:
"maximum context length exceeded",
476 + .
spyOn(t?.session,
"_runAutoCompaction")
477 + .
mockImplementation(
async ()
=> {
478 + expect(t?.session.model.
id).
toBe(
"gpt-4o-mini");
481 + await t?.session.
prompt(
"/review overflow");
482 + await settled(
2, requests);
483 + expect(compact).
toHaveBeenCalledWith(
"overflow",
true);
484 + expect(requests[
1]).
toEqual({
485 + text:
"Review overflow.",
486 + model:
"gpt-4o-mini",
489 + expect(t?.session.thinkingLevel).
toBe(
"off");
492 + it.
each([
"input",
"equip"])(
493 + "rejects competing preflights during %s without losing the mask",
495 + const requests
= await queuedSession(
async ()
=> undefined);
496 + const entered
= Promise.
withResolvers<
void>();
497 + const release
= Promise.
withResolvers<
void>();
498 + if (stage
=== "input") {
500 + .handlers.
get(
"before_agent_start")
501 + .
unshift(
async ()
=> {
503 + await release.promise;
506 + const runtime
= t?.session.extensionRunner.runtime;
507 + const setModel
= runtime.setModel.
bind(runtime);
508 + vi.
spyOn(runtime,
"setModel").
mockImplementation(
async (model)
=> {
510 + await release.promise;
511 + return setModel(model);
514 + const first
= t?.session.
prompt(
"/review first");
515 + await entered.promise;
517 + await t?.session.
prompt(
"ordinary concurrent prompt");
518 + await t?.session.
prompt(
"/plan second");
523 + expect(requests).
toEqual([
524 + { text:
"Review first.", model:
"gpt-4o-mini", thinking:
"high" },
526 + expect(t?.session.model.
id).
toBe(
"gpt-4o");
527 + expect(t?.session.thinkingLevel).
toBe(
"off");
531 + it(
"blocks later prompts until a failed restoration succeeds",
async ()
=> {
532 + let failRestore
= true;
533 + const requests
= await queuedSession(
async ()
=> undefined);
534 + const runtime
= t?.session.extensionRunner.runtime;
535 + const setModel
= runtime.setModel.
bind(runtime);
536 + vi.
spyOn(runtime,
"setModel").
mockImplementation(
async (model
: any)
=> {
537 + if (model.
id === "gpt-4o" && failRestore)
return false;
538 + return setModel(model);
540 + await t?.session.
prompt(
"/review first");
541 + await t?.session.
prompt(
"ordinary blocked prompt");
542 + await t?.session.
prompt(
"/plan blocked");
543 + expect(requests).
toHaveLength(
1);
544 + failRestore
= false;
545 + await t?.session.
prompt(
"ordinary recovered prompt");
546 + expect(requests[
1]).
toEqual({
547 + text:
"ordinary recovered prompt",
549 + thinking:
undefined,
553 + it(
"cancels deferred prompts on a late abort after a successful response",
async ()
=> {
554 + const requests
= await queuedSession(
async ()
=> {
555 + await queue(
"/plan later");
558 + const runtime
= t?.session.extensionRunner.runtime;
559 + const setModel
= runtime.setModel.
bind(runtime);
560 + vi.
spyOn(runtime,
"setModel").
mockImplementation(
async (model
: any)
=> {
561 + if (model.
id === "gpt-4o")
context().
abort();
562 + return setModel(model);
564 + await t?.session.
prompt(
"/review now");
565 + await settled(
1, requests);
566 + expect(t?.events.
uiCallsFor(
"notify").
at(
-1)?.args).
toEqual([
567 + "Cancelled 1 deferred masked prompts",
570 + expect(t?.session.thinkingLevel).
toBe(
"off");
573 + it(
"restores before a native follow-up after a terminating tool batch",
async ()
=> {
574 + const requests
= await queuedSession(
async (_request, index)
=> {
575 + if (index
!== 0)
return undefined;
576 + await queue(
"ordinary follow-up");
581 + id:
"blocked-read",
583 + arguments: { path:
"fixture.txt" },
586 + stopReason:
"toolUse",
589 + extension().handlers.
set(
"tool_call", [
590 + async ()
=> ({ block:
true, terminate:
true, reason:
"Finished" }),
592 + await t?.session.
prompt(
"/review now");
593 + await settled(
2, requests);
594 + expect(requests[
1]).
toEqual({
595 + text:
"ordinary follow-up",
597 + thinking:
undefined,
601 + it(
"preserves images and repeated masked follow-ups",
async ()
=> {
604 + mimeType:
"image/png",
605 + data:
"fixture-image",
607 + const requests
= await queuedSession(
async (_request, index)
=> {
609 + await t?.session.
sendUserMessage(
610 + [{ type:
"text", text:
"/review same" }, image],
612 + expandPromptTemplates:
true,
613 + deliverAs:
"followUp",
616 + await queue(
"/review same");
620 + await t?.session.
prompt(
"start");
621 + await settled(
3, requests);
622 + expect(requests.
slice(
1)).
toEqual([
623 + { text:
"Review same.", model:
"gpt-4o-mini", thinking:
"high" },
624 + { text:
"Review same.", model:
"gpt-4o-mini", thinking:
"high" },
626 + expect(t?.events.messages).
toContainEqual(
627 + expect.
objectContaining({
629 + content: [{ type:
"text", text:
"Review same." }, image],
634 + it(
"defers busy input during recovery when Pi omits streamingBehavior",
async ()
=> {
635 + const requests
= await queuedSession(
async ()
=> undefined);
636 + await extension().handlers.
get(
"input")[
0](
637 + { type:
"input", text:
"/plan later", source:
"extension" },
638 + {
...context(),
isIdle: ()
=> false },
640 + await extension().handlers.
get(
"agent_settled")[
0](
641 + { type:
"agent_settled" },
644 + await settled(
1, requests);
645 + expect(requests[
0]).
toEqual({
646 + text:
"Plan later.",
201 652 it(
"fuzzy-matches non-prefix mask queries", ()
=> {
202 653 const parsed
= __test.
parseMasksSettings({
extensions/masks/index.ts
Modified 2 2 import { readFileSync }
from "node:fs";
6 7 }
from "@earendil-works/pi-coding-agent";
20 21 const SETTINGS_KEY
= "masks";
21 22 const DEFAULT_PICKER_SHORTCUT
= "alt+m";
23 +type ThinkingLevel = Parameters<
ExtensionAPI[
"setThinkingLevel"]>[
0];
22 24 const THINKING_LEVELS
= [
32 +]
as const satisfies readonly ThinkingLevel[];
32 -type ThinkingLevel = (
typeof THINKING_LEVELS)[
number];
33 34 type Shortcut = Parameters<
ExtensionAPI[
"registerShortcut"]>[
0];
282 283 export default function masksExtension(pi
: ExtensionAPI)
: void {
283 284 const { config, errors }
= readMasksSettings();
284 285 let pendingMask
: Mask | undefined;
286 + const deferred
: Pick<
InputEvent,
"text" | "images">[]
= [];
287 + let abortNextRun
= false;
288 + let preparing
= false;
289 + let detachAbort
: (()
=> void)
| undefined;
290 + const terminatingTools
= new Set<
string>();
285 291 let restoreState
: 287 293 model
: NonNullable<
ExtensionContext[
"model"]>;
298 + function showQueue(ctx
: ExtensionContext)
: void {
302 + ? `masks: ${deferred.length} deferred · /masks-cancel` 307 + function cancelQueue(ctx
: ExtensionContext)
: void {
308 + const count
= deferred.
length;
309 + deferred.
length = 0;
312 + ctx.ui.
notify(
`Cancelled ${count} deferred masked prompts`,
"warning");
315 + pi.
registerCommand(
"masks-cancel", {
317 + "Cancel deferred masked prompts without interrupting the current run",
318 + handler:
async (_args, ctx)
=> cancelQueue(ctx),
292 321 async function chooseMask(ctx
: ExtensionContext)
: Promise<
void> {
293 322 if (config.items.
length === 0) {
294 323 ctx.ui.
notify(
"No masks configured in settings.json",
"warning");
342 - pi.
on(
"input", (event, ctx)
=> {
371 + pi.
on(
"input",
async (event, ctx)
=> {
374 + "Masked prompt is preparing; retry after it starts, or /reload after a dispatch failure",
377 + return { action:
"handled" };
379 + if (ctx.
isIdle()
&& restoreState) {
381 + await restoreTemporaryMask(ctx);
383 + if (restoreState)
return { action:
"handled" };
343 385 pendingMask
= undefined;
344 386 const commandName
= promptCommandName(
event.
text);
345 387 if (
!commandName)
return { action:
"continue" };
378 420 return { action:
"handled" };
380 422 if (
!ctx.
isIdle()) {
382 - `Prompt /${commandName}: masked prompts cannot be queued mid-run`,
423 + if (
event.streamingBehavior
=== "steer") {
425 + `Prompt /${commandName}: use follow-up delivery, not steering`,
428 + return { action:
"handled" };
430 + deferred.
push({ text:
event.
text, images:
event.
images });
385 432 return { action:
"handled" };
387 434 pendingMask
= mask;
388 436 return { action:
"continue" };
397 445 `Mask "${mask.name}": no current model to restore`,
448 + abortNextRun
= true;
403 452 model: ctx.model,
404 453 thinkingLevel: pi.
getThinkingLevel(),
406 - if (
await applyMask(pi, mask, ctx)) restoreState
= previous;
456 + abortNextRun
= !(
await applyMask(pi, mask, ctx));
458 + abortNextRun
= true;
459 + ctx.ui.
notify(
`Failed to equip prompt mask: ${String(error)}`,
"error");
463 + pi.
on(
"agent_start", (_event, ctx)
=> {
466 + const signal
= ctx.signal;
467 + const cancel = ()
=> cancelQueue(ctx);
468 + signal?.
addEventListener(
"abort", cancel, { once:
true });
469 + detachAbort = ()
=> signal?.
removeEventListener(
"abort", cancel);
470 + if (signal?.aborted)
cancel();
471 + if (
!abortNextRun)
return;
472 + abortNextRun
= false;
409 477 async function restoreTemporaryMask(ctx
: ExtensionContext)
: Promise<
void> {
410 478 const previous
= restoreState;
411 - restoreState
= undefined;
412 479 if (
!previous)
return;
413 - if (
!(
await pi.
setModel(previous.model))) {
414 - ctx.ui.
notify(
"Failed to restore model after prompt mask",
"error");
481 + if (
!(
await pi.
setModel(previous.model)))
482 + throw new Error(
"Model unavailable");
483 + pi.
setThinkingLevel(previous.thinkingLevel);
484 + restoreState
= undefined;
488 + `Failed to restore model after prompt mask: ${String(error)}`,
417 - pi.
setThinkingLevel(previous.thinkingLevel);
420 - pi.
on(
"agent_end",
async (_event, ctx)
=> restoreTemporaryMask(ctx));
495 + pi.
on(
"turn_start", ()
=> terminatingTools.
clear());
496 + pi.
on(
"tool_execution_end", (event)
=> {
497 + if (
event.result.terminate
=== true) terminatingTools.
add(
event.toolCallId);
499 + pi.
on(
"turn_end",
async (event, ctx)
=> {
500 + if (
event.message.role
!== "assistant")
return;
501 + const tools
= event.message.
content.
filter(
502 + (part)
=> part.
type === "toolCall",
506 + ? tools.
every((tool)
=> terminatingTools.
has(tool.
id))
507 + : event.message.stopReason
=== "stop" 509 + await restoreTemporaryMask(ctx);
512 + pi.
on(
"agent_end",
async (event, ctx)
=> {
514 + event.messages.
some(
516 + message.role
=== "assistant" && 517 + (message.stopReason
=== "aborted" || message.stopReason
=== "error"),
522 + pi.
on(
"agent_settled",
async (_event, ctx)
=> {
523 + if (
!ctx.
isIdle())
return;
524 + await restoreTemporaryMask(ctx);
526 + detachAbort
= undefined;
527 + if (restoreState
|| preparing
|| !ctx.
isIdle())
return;
528 + const next
= deferred.
shift();
531 + pi.
sendUserMessage(
532 + [{ type:
"text", text: next.
text },
...(next.
images ?? [])],
533 + { expandPromptTemplates:
true, deliverAs:
"followUp" },
421 536 pi.
on(
"session_start", (_event, ctx)
=> {
422 537 for (
const error
of errors) ctx.ui.
notify(error,
"warning");
424 - pi.
on(
"session_shutdown",
async (_event, ctx)
=> {
539 + async function reset(ctx
: ExtensionContext)
: Promise<
void> {
425 540 pendingMask
= undefined;
541 + abortNextRun
= false;
544 + detachAbort
= undefined;
426 546 await restoreTemporaryMask(ctx);
548 + pi.
on(
"session_tree",
async (_event, ctx)
=> reset(ctx));
549 + pi.
on(
"session_shutdown",
async (_event, ctx)
=> reset(ctx));
430 552 export const __test
= {