repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

Register ui command

45ef0f4c322452f10032b8bcefa166c634aa3009

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

unsigned

Browse filesCompare with HEAD

Changed files (2)

extensions/ui/__tests__/harness.test.ts

Added
new file mode 100644
1 +import path from "node:path";
2 +import { afterEach, describe, expect, it } from "vitest";
3 +import { createTestSession, type TestSession } from "../../../test/harness";
5 +describe("ui pi-test-harness", () => {
6 + let t: TestSession | undefined;
8 + afterEach(() => {
9 + t?.dispose();
10 + t = undefined;
11 + });
13 + it("loads in real Pi extension runtime", async () => {
14 + const extensionPath = path.resolve(import.meta.dirname, "../index.ts");
15 + t = await createTestSession({ extensions: [extensionPath] });
17 + expect(t.session.extensionRunner.extensions).toHaveLength(1);
18 + expect(t.session.extensionRunner.extensions[0].path).toBe(extensionPath);
19 + });
21 + it("registers the /ui command without starting a runtime", async () => {
22 + const extensionPath = path.resolve(import.meta.dirname, "../index.ts");
23 + t = await createTestSession({ extensions: [extensionPath] });
24 + const extension = t.session.extensionRunner.extensions[0];
26 + expect([...extension.commands.keys()]).toEqual(["ui"]);
27 + expect([...extension.tools.keys()]).toHaveLength(0);
28 + expect(t.events.uiCallsFor("setWidget")).toHaveLength(0);
29 + });
30 +});

extensions/ui/index.ts

Added
new file mode 100644
1 +import path from "node:path";
2 +import type {
3 + ExtensionAPI,
4 + ExtensionCommandContext,
5 + ExtensionContext,
6 +} from "@earendil-works/pi-coding-agent";
7 +import { matchesKey } from "@earendil-works/pi-tui";
8 +import { humanError, redactToken, uiError, type UiError } from "./errors";
9 +import { createUiRuntime, type UiRuntime } from "./runtime";
11 +const COMMANDS = ["off", "status", "open", "qr"];
12 +const WIDGET_KEY = "ui";
14 +export default function uiExtension(pi: ExtensionAPI): void {
15 + let runtime: UiRuntime | undefined;
16 + let terminalUnsubscribe: (() => void) | undefined;
18 + function setWidget(ctx: ExtensionContext): void {
19 + if (!ctx.hasUI) return;
20 + ctx.ui.setWidget(WIDGET_KEY, runtime?.widgetLines(), {
21 + placement: "aboveEditor",
22 + });
23 + }
25 + async function stop(ctx: ExtensionContext, reason: string): Promise<void> {
26 + terminalUnsubscribe?.();
27 + terminalUnsubscribe = undefined;
28 + const current = runtime;
29 + runtime = undefined;
30 + if (ctx.hasUI) {
31 + ctx.ui.setWidget(WIDGET_KEY, undefined);
32 + ctx.ui.setWorkingVisible(true);
33 + }
34 + if (current) await current.stop(reason);
35 + }
37 + async function start(ctx: ExtensionCommandContext): Promise<void> {
38 + if (runtime) {
39 + setWidget(ctx);
40 + ctx.ui.notify(
41 + `ui already active: ${redactToken(runtime.status().url ?? "")}`,
42 + "info",
43 + );
44 + return;
45 + }
47 + if (ctx.hasUI) ctx.ui.setWorkingVisible(false);
48 + runtime = await createUiRuntime({
49 + sessionLabel: sessionLabel(pi, ctx),
50 + onChange: () => setWidget(ctx),
51 + });
52 + terminalUnsubscribe = ctx.hasUI
53 + ? ctx.ui.onTerminalInput((data) => {
54 + if (!matchesKey(data, "escape")) return undefined;
55 + void stop(ctx, "escape").then(() =>
56 + ctx.ui.notify("ui stopped", "info"),
57 + );
58 + return { consume: true };
59 + })
60 + : undefined;
61 + setWidget(ctx);
62 + ctx.ui.notify(`ui open: ${redactToken(runtime.status().url ?? "")}`, "info");
63 + }
65 + pi.registerCommand("ui", {
66 + description:
67 + "Start or control the browser UI runtime. Usage: /ui [off|status|open|qr]",
68 + getArgumentCompletions(prefix) {
69 + const trimmed = prefix.trimStart();
70 + return COMMANDS.filter((item) => item.startsWith(trimmed)).map((value) => ({
71 + value,
72 + label: value,
73 + }));
74 + },
75 + async handler(args, ctx) {
76 + const command = args.trim();
77 + try {
78 + if (!command) return await start(ctx);
79 + if (command === "off") return await stop(ctx, "command");
80 + if (command === "status") return status(ctx);
81 + if (command === "open") return await open(ctx);
82 + if (command === "qr") return await redrawQr(ctx);
83 + throw uiError(
84 + "runtime_not_active",
85 + `Unknown /ui subcommand: ${command}`,
86 + {
87 + action: "Use /ui, /ui off, /ui status, /ui open, or /ui qr.",
88 + retryable: true,
89 + },
90 + );
91 + } catch (error) {
92 + ctx.ui.notify(formatError(error), "error");
93 + setWidget(ctx);
94 + }
95 + },
96 + });
98 + pi.on("session_shutdown", async (_event, ctx) => {
99 + await stop(ctx, "session shutdown");
100 + });
102 + function status(ctx: ExtensionCommandContext): void {
103 + if (!runtime) return ctx.ui.notify("ui inactive", "info");
104 + const current = runtime.status();
105 + ctx.ui.notify(
106 + `ui ${current.state}: ${redactToken(current.url ?? "")}`,
107 + "info",
108 + );
109 + setWidget(ctx);
112 + async function open(ctx: ExtensionCommandContext): Promise<void> {
113 + if (!runtime) throw inactiveError();
114 + await runtime.open();
115 + ctx.ui.notify("ui open requested", "info");
118 + async function redrawQr(ctx: ExtensionCommandContext): Promise<void> {
119 + if (!runtime) throw inactiveError();
120 + await runtime.redrawQr();
121 + setWidget(ctx);
125 +function sessionLabel(pi: ExtensionAPI, ctx: ExtensionContext): string {
126 + const name = pi.getSessionName() ?? path.basename(ctx.cwd);
127 + return `ui: ${name || "session"}`;
130 +function inactiveError(): UiError {
131 + return uiError("runtime_not_active", "UI runtime is not active", {
132 + action: "Run /ui first.",
133 + retryable: true,
134 + });
137 +function formatError(error: unknown): string {
138 + if (isUiError(error)) return humanError(error);
139 + return error instanceof Error ? error.message : String(error);
142 +function isUiError(error: unknown): error is UiError {
143 + return (
144 + error instanceof Error &&
145 + "code" in error &&
146 + "action" in error &&
147 + "retryable" in error
148 + );