repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

feat(os-notifier): notify when Pi awaits input

f811fc16bc562dac78b5582160665794f27bff07

Oliver Krylow <o.krylow@isp-insoft.de> ·

SSH signature · not checked

Browse filesCompare with HEAD

Changed files (3)

+180 / −17 text lines

Diff layout

extensions/os-notifier/README.md

Modified

+8 / −4 text lines

11# os-notifier
3Native-first OS notifications for direct interactive Pi completion.
3Native-first OS notifications when direct interactive Pi work completes or blocks awaiting input.
55## Install / load
2323- `before_agent_start` confirms the accepted input that starts a lifecycle.
2424- `agent_start` starts duration measurement for the active lifecycle.
2525- `agent_end` records the latest low-level outcome.
26- `ui_prompt_start` notifies once when eligible work blocks on an extension UI prompt while unfocused.
27- `ui_prompt_end` rearms blocked-input notification delivery.
2628- `agent_settled` sends the final eligible notification while unfocused.
2729- `session_shutdown` clears in-memory state, pane identity, and focus tracking.
3335- `ctx.mode === "tui"`
3436- input source `interactive`
35- terminal unfocused at `agent_settled`
37- terminal unfocused when the blocking prompt starts or at `agent_settled`
3739RPC, JSON, print, SDK-driven, extension-driven, and subagent-style turns stay silent.
3840The accepted input that starts the lifecycle determines eligibility.
3941Later steering and follow-ups do not reclassify extension-driven work.
40Focused completions are discarded rather than deferred.
42Focused completions and prompt waits are discarded rather than deferred.
43Only Pi extension UI prompts are detected; arbitrary subprocesses waiting on stdin are outside this extension's scope.
4245## Native delivery
5861## Content
60Notifications include outcome, duration, project, Git branch, session name, model, bounded user prompt, and bounded failure detail.
63Completion notifications include outcome, duration, project, Git branch, session name, model, bounded user prompt, and bounded failure detail.
64Blocked-input notifications include prompt kind, title, project, Git branch, and session name.
6165The accepted starting prompt remains available when a retry's final event omits user messages.
6266Dynamic text is sanitized and passed without shell interpolation.

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

Modified

+85 / −0 text lines

44import { createTestSession, type TestSession } from "../../../test/harness";
55import {
66 agentDoneNotification,
7 agentWaitingNotification,
78 deliverNative,
89 nativeCommand,
910 oscBackend,
159160 state.input("interactive");
160161 state.prepare();
161162 state.start("tui");
163 expect(state.isEligible()).toBe(true);
162164 state.start("tui");
163165 expect(state.settle()).toBe(true);
166 expect(state.isEligible()).toBe(false);
164167 });
166169 it("accepts input prepared after a pre-prompt compaction run starts", () => {
184187});
186189describe("os-notifier payload", () => {
190 it("includes bounded context when Pi needs input", () => {
191 expect(
192 agentWaitingNotification(
193 { kind: "confirm", title: "Allow destructive operation?" },
194 {
195 cwd: "/home/oli/Workspace/dotfiles",
196 branch: "trunk",
197 sessionName: "notifier work",
198 },
199 ),
200 ).toEqual({
201 title: "Pi needs input",
202 message:
203 "Confirmation • Allow destructive operation? • dotfiles • trunk • notifier work",
204 severity: "warning",
205 });
206 });
187208 it("includes rich bounded context in completion body", () => {
188209 expect(
189210 agentDoneNotification(
273294 expect(t.session.extensionRunner.extensions[0].path).toBe(extensionPath);
274295 });
297 it.skipIf(process.platform !== "linux")(
298 "notifies once per uninterrupted unfocused interactive prompt wait",
299 async () => {
300 const extensionPath = path.resolve(import.meta.dirname, "../index.ts");
301 t = await createTestSession({ extensions: [extensionPath] });
302 const bin = join(t.cwd, "bin");
303 const log = join(t.cwd, "notify.log");
304 const executable = join(bin, "notify-send");
305 mkdirSync(bin);
306 writeFileSync(
307 executable,
308 `#!${process.execPath}\nrequire("node:fs").appendFileSync(process.env.TEST_NOTIFY_LOG, JSON.stringify(process.argv.slice(2)) + "\\n");\n`,
309 );
310 chmodSync(executable, 0o755);
311 t.env.PATH = `${bin}${delimiter}${t.env.PATH ?? ""}`;
312 t.env.TEST_NOTIFY_LOG = log;
313 t.session.extensionRunner.setUIContext(
314 t.session.extensionRunner.getUIContext(),
315 "tui",
316 );
317 focusState.focused = false;
319 await t.session.extensionRunner.emit({
320 type: "input",
321 text: "test notification",
322 source: "interactive",
323 } as never);
324 await t.session.extensionRunner.emitBeforeAgentStart(
325 "test notification",
326 undefined,
327 "BASE",
328 {} as never,
329 );
330 await t.session.extensionRunner.emit({ type: "agent_start" } as never);
331 const prompt = {
332 type: "ui_prompt_start",
333 reason: "ui_prompt",
334 kind: "confirm",
335 title: "Continue?",
336 } as const;
337 await t.session.extensionRunner.emit(prompt as never);
338 await waitFor(
339 () => readFileSync(log, "utf8").trim().split("\n").length === 1,
340 );
341 await t.session.extensionRunner.emit(prompt as never);
342 await new Promise((resolve) => setTimeout(resolve, 50));
343 expect(readFileSync(log, "utf8").trim().split("\n")).toHaveLength(1);
345 await t.session.extensionRunner.emit({
346 type: "ui_prompt_end",
347 reason: "ui_prompt",
348 kind: "confirm",
349 title: "Continue?",
350 } as never);
351 await t.session.extensionRunner.emit(prompt as never);
352 await waitFor(
353 () => readFileSync(log, "utf8").trim().split("\n").length === 2,
354 );
355 const args = JSON.parse(readFileSync(log, "utf8").trim().split("\n")[0]);
356 expect(args).toContain("Pi needs input");
357 expect(args.join(" ")).toContain("Confirmation • Continue?");
358 },
359 );
276361 it.skipIf(process.platform !== "linux")(
277362 "uses native delivery only for unfocused interactive TUI runs",
278363 async () => {

extensions/os-notifier/index.ts

Modified

+87 / −13 text lines

118118 return isAbsolute(target) ? target : resolve(worktreeDir, target);
121export function agentWaitingNotification(
122 event: {
123 kind: "select" | "confirm" | "input" | "editor" | "custom";
124 title?: string;
125 },
126 meta: { cwd?: string; branch?: string; sessionName?: string },
127): AgentDoneNotification {
128 const kind = {
129 select: "Selection",
130 confirm: "Confirmation",
131 input: "Input",
132 editor: "Editor",
133 custom: "Request",
134 }[event.kind];
135 return {
136 title: "Pi needs input",
137 message: [
138 kind,
139 compact(event.title, ERROR_LIMIT),
140 meta.cwd ? compact(basename(meta.cwd)) : "",
141 compact(meta.branch),
142 compact(meta.sessionName),
143 ]
144 .filter(Boolean)
145 .join(" • "),
146 severity: "warning",
147 };
148}
121150export function agentDoneNotification(
122151 event: { messages?: unknown[] },
123152 meta: {
365394 }
367396 settle(): boolean {
368 const eligible = this.current;
397 const eligible = this.isEligible();
369398 this.reset();
370399 return eligible;
371400 }
402 isEligible(): boolean {
403 return this.current;
404 }
373406 clear(): void {
374407 this.reset();
375408 }
390423 let acceptedPrompt: string | undefined;
391424 let lastAgentEnd: { messages?: unknown[] } | undefined;
392425 let focusAttached = false;
426 let awaitingInput = false;
428 const deliver = (notification: AgentDoneNotification): void => {
429 void deliverNative(
430 nativeCommand(
431 process.platform,
432 notification.title,
433 notification.message,
434 notification.severity,
435 ),
436 notification.title,
437 notification.message,
438 notification.severity,
439 oscBackend(process.env),
440 );
441 };
394443 pi.on("session_start", async (_event, ctx) => {
395444 if (ctx.mode === "tui") {
427476 lastAgentEnd = event;
428477 });
479 type PromptEvent = {
480 kind: "select" | "confirm" | "input" | "editor" | "custom";
481 title?: string;
482 };
483 const onPromptStart = pi.on as unknown as (
484 event: "ui_prompt_start",
485 handler: (
486 event: PromptEvent,
487 ctx: ExtensionContext,
488 ) => Promise<void> | void,
489 ) => void;
490 const onPromptEnd = pi.on as unknown as (
491 event: "ui_prompt_end",
492 handler: (
493 event: PromptEvent,
494 ctx: ExtensionContext,
495 ) => Promise<void> | void,
496 ) => void;
497 onPromptStart("ui_prompt_start", async (event, ctx) => {
498 if (awaitingInput) return;
499 awaitingInput = true;
500 if (!eligibility.isEligible() || focus.isFocused()) return;
501 deliver(
502 agentWaitingNotification(event, {
503 cwd: ctx.cwd,
504 branch: currentGitBranch(ctx.cwd),
505 sessionName: pi.getSessionName(),
506 }),
507 );
508 });
509 onPromptEnd("ui_prompt_end", async () => {
510 awaitingInput = false;
511 });
430513 // lazy: transitive 0.78 types lag Pi runtime; remove cast when they expose agent_settled.
431514 const onAgentSettled = pi.on as unknown as (
432515 event: "agent_settled",
446529 sessionName: pi.getSessionName(),
447530 prompt: acceptedPrompt,
448531 });
449 void deliverNative(
450 nativeCommand(
451 process.platform,
452 notification.title,
453 notification.message,
454 notification.severity,
455 ),
456 notification.title,
457 notification.message,
458 notification.severity,
459 oscBackend(process.env),
460 );
532 deliver(notification);
461533 }
534 awaitingInput = false;
462535 agentStartedAt = undefined;
463536 candidatePrompt = undefined;
464537 acceptedPrompt = undefined;
471544 candidatePrompt = undefined;
472545 acceptedPrompt = undefined;
473546 lastAgentEnd = undefined;
547 awaitingInput = false;
474548 if (focusAttached) {
475549 writeUserVar("agent", "");
476550 writeUserVar("agent_session", "");