repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

fix(os-notifier): notify only after agent settles

9a882c80456101be93f0b15762a01f6589446122

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Changed files (5)

docs/super/plans/2026-07-12-os-notifier.md

Modified
133 133 - encode Windows PowerShell script as UTF-16LE Base64 for `-EncodedCommand`
134 134 - pass macOS title/body through `osascript` argv to avoid shell interpolation
135 135 - add `oscBackend(env)`
136 -- add minimal active/pending eligibility bookkeeping driven by `input`, `agent_start`, and `agent_end`; steering and follow-ups stay within the active lifecycle
136 +- add minimal active/pending eligibility bookkeeping driven by `input`, `agent_start`, and `agent_settled`; steering, retries, and follow-ups stay within the active lifecycle
137 137 - remove `notify:send`, `notify:ui`, startup probes, backend caching, and warning notifications
139 139 - [ ] **Step 6: Run extension tests**
183 183 Use `execFile(command, args, callback)` without a shell.
184 184 On `error` or nonzero command completion, write exactly one selected OSC fallback.
185 +Trigger delivery from `agent_settled`, using the latest `agent_end` outcome.
185 186 Ignore OSC write errors.
186 187 Do not block or throw into Pi lifecycle handlers.

docs/super/specs/2026-07-12-os-notifier-design.md

Modified
29 29 - Pi runs in TUI mode: `ctx.mode === "tui"`.
30 30 - The completed agent run belongs to direct input with `event.source === "interactive"`.
31 -- The terminal is unfocused when `agent_end` fires.
31 +- The terminal is unfocused when `agent_settled` fires.
33 33 The extension records input origin in extension-instance memory because `agent_end` does not expose it.
34 34 It tracks pending pre-start input separately from the active agent lifecycle.
40 40 Interactive steering and queued follow-up input make the active agent lifecycle eligible.
41 41 RPC, SDK, extension, JSON, and print activity never makes a run eligible.
43 -Every eligible unfocused completion notifies, regardless of duration.
43 +Low-level `agent_end` events update the latest outcome without notifying.
44 +`agent_settled` notifies only after retries, compaction, and queued follow-ups finish.
45 +Every eligible unfocused settled completion notifies, regardless of duration.
44 46 Focused completions are discarded rather than deferred.
46 48 ## Outcomes and Urgency
110 112 - outcome and metadata formatting
111 113 - platform command construction
112 114 - native execution and OSC fallback
113 -- Pi lifecycle hooks
115 +- Pi lifecycle hooks, using `agent_settled` as the final completion boundary
115 117 `focus.ts` remains the small, reference-counted DECSET `?1004` focus helper.
116 118 No backend interface, factory, configuration layer, or compatibility event bridge is introduced.
132 134 - direct interactive TUI eligibility
133 135 - suppression for RPC, JSON, print, SDK-style, and extension input
134 136 - pending versus active-lifecycle input-origin bookkeeping
135 -- focused-terminal suppression
137 +- focused-terminal suppression and no notification before `agent_settled`
136 138 - native success and native failure through a controlled fake executable on the current platform
137 139 - loading through the real Pi extension harness

extensions/os-notifier/README.md

Modified
20 20 - `session_start` attaches terminal focus tracking in TUI mode.
21 21 - `input` records direct interactive input origin.
22 -- `agent_start` starts duration measurement and assigns queued input origin.
23 -- `agent_end` sends an eligible completion notification while unfocused.
22 +- `agent_start` starts duration measurement for the active lifecycle.
23 +- `agent_end` records the latest low-level outcome.
24 +- `agent_settled` sends the final eligible notification while unfocused.
24 25 - `session_shutdown` clears in-memory state and focus tracking.
26 27 ## Eligibility
30 31 - `ctx.mode === "tui"`
31 32 - input source `interactive`
32 -- terminal unfocused at `agent_end`
33 +- terminal unfocused at `agent_settled`
34 35 RPC, JSON, print, SDK-driven, extension-driven, and subagent-style turns stay silent.
35 36 Interactive steering and queued follow-ups make their active agent lifecycle eligible.

extensions/os-notifier/__tests__/harness.test.ts

Modified
93 93 const state = new TurnEligibility();
94 94 state.input("interactive");
95 95 state.start("tui");
96 - expect(state.end()).toBe(true);
96 + expect(state.settle()).toBe(true);
98 98 state.input("rpc");
99 99 state.start("tui");
100 - expect(state.end()).toBe(false);
100 + expect(state.settle()).toBe(false);
102 102 state.input("interactive");
103 103 state.start("rpc");
104 - expect(state.end()).toBe(false);
104 + state.input("interactive", "followUp");
105 + expect(state.settle()).toBe(false);
107 108 it("attributes queued follow-up input to the active lifecycle without leaking", () => {
109 110 state.input("extension");
110 111 state.start("tui");
111 112 state.input("interactive", "followUp");
112 - expect(state.end()).toBe(true);
113 + expect(state.settle()).toBe(true);
114 115 state.input("extension");
115 116 state.start("tui");
116 - expect(state.end()).toBe(false);
117 + expect(state.settle()).toBe(false);
119 120 it("interactive steering makes the active run eligible", () => {
121 122 state.input("extension");
122 123 state.start("tui");
123 124 state.input("interactive", "steer");
124 - expect(state.end()).toBe(true);
125 + expect(state.settle()).toBe(true);
126 + });
128 + it("preserves eligibility across low-level retries until settlement", () => {
129 + const state = new TurnEligibility();
130 + state.input("interactive");
131 + state.start("tui");
132 + state.start("tui");
133 + expect(state.settle()).toBe(true);
230 239 focusState.focused = false;
231 - await emitCompletion(t, "interactive");
240 + await emitCompletion(t, "interactive", false);
241 + await new Promise((resolve) => setTimeout(resolve, 50));
242 + expect(() => readFileSync(log, "utf8")).toThrow();
243 + await t.session.extensionRunner.emit({ type: "agent_settled" } as never);
232 244 await waitFor(() => readFileSync(log, "utf8").trim().length > 0);
233 245 const first = readFileSync(log, "utf8").trim().split("\n");
234 246 expect(JSON.parse(first[0])).toContain("Pi finished");
253 265 async function emitCompletion(
254 266 t: TestSession,
255 267 source: "interactive" | "rpc" | "extension",
268 + settle = true,
256 269 ): Promise<void> {
257 270 await t.session.extensionRunner.emit({
258 271 type: "input",
267 280 { role: "assistant", stopReason: "stop" },
269 282 } as never);
283 + if (settle) {
284 + await t.session.extensionRunner.emit({ type: "agent_settled" } as never);
272 288 async function waitFor(

extensions/os-notifier/index.ts

Modified
1 1 import { execFile } from "node:child_process";
2 2 import { existsSync, readFileSync, statSync } from "node:fs";
3 3 import { dirname, isAbsolute, join, resolve } from "node:path";
4 -import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
4 +import type {
5 + ExtensionAPI,
6 + ExtensionContext,
7 +} from "@earendil-works/pi-coding-agent";
5 8 import * as focus from "./focus.js";
7 10 export type NotificationSeverity = "info" | "warning" | "error";
315 318 export class TurnEligibility {
316 319 private active = false;
320 + private activeTui = false;
317 321 private current = false;
318 322 private pending = false;
320 324 input(source: InputSource, _behavior?: StreamingBehavior): void {
321 325 const eligible = source === "interactive";
322 326 if (this.active) {
323 - this.current ||= eligible;
327 + this.current ||= this.activeTui && eligible;
324 328 return;
326 330 this.pending = eligible;
329 333 start(mode: string): void {
334 + if (this.active) return;
330 335 this.active = true;
331 - this.current = mode === "tui" && this.pending;
336 + this.activeTui = mode === "tui";
337 + this.current = this.activeTui && this.pending;
332 338 this.pending = false;
335 - end(): boolean {
341 + settle(): boolean {
336 342 const eligible = this.current;
337 343 this.active = false;
344 + this.activeTui = false;
338 345 this.current = false;
339 346 return eligible;
342 349 clear(): void {
343 350 this.active = false;
351 + this.activeTui = false;
344 352 this.current = false;
345 353 this.pending = false;
349 357 export default function (pi: ExtensionAPI) {
350 358 const eligibility = new TurnEligibility();
351 359 let agentStartedAt: number | undefined;
360 + let lastAgentEnd: { messages?: unknown[] } | undefined;
352 361 let focusAttached = false;
354 363 pi.on("session_start", async (_event, ctx) => {
365 374 pi.on("agent_start", async (_event, ctx) => {
366 375 eligibility.start(ctx.mode);
367 - agentStartedAt = Date.now();
376 + agentStartedAt ??= Date.now();
370 - pi.on("agent_end", async (event, ctx) => {
371 - const shouldNotify = eligibility.end();
372 - if (shouldNotify && !focus.isFocused()) {
373 - const notification = agentDoneNotification(event, {
379 + pi.on("agent_end", async (event) => {
380 + lastAgentEnd = event;
381 + });
383 + // lazy: transitive 0.78 types lag Pi runtime; remove cast when they expose agent_settled.
384 + const onAgentSettled = pi.on as unknown as (
385 + event: "agent_settled",
386 + handler: (event: unknown, ctx: ExtensionContext) => Promise<void> | void,
387 + ) => void;
388 + onAgentSettled("agent_settled", async (_event, ctx) => {
389 + const shouldNotify = eligibility.settle();
390 + if (shouldNotify && lastAgentEnd && !focus.isFocused()) {
391 + const notification = agentDoneNotification(lastAgentEnd, {
374 392 cwd: ctx.cwd,
375 393 model: ctx.model,
376 394 durationMs:
396 414 agentStartedAt = undefined;
415 + lastAgentEnd = undefined;
399 418 pi.on("session_shutdown", async () => {
400 419 eligibility.clear();
401 420 agentStartedAt = undefined;
421 + lastAgentEnd = undefined;
402 422 if (focusAttached) {
403 423 focus.detach();
404 424 focusAttached = false;