repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

fix(good-job): detach background work from session context

6307a5d5c26b8d4af3905c8abe2e29270a3f6042

Oliver Jan Krylow <oliver@bugabinga.net> ·

SSH signature · not checked

Browse filesCompare with HEAD

Changed files (3)

extensions/good-job/__tests__/harness.test.ts

Modified
114 114 "Implemented and tested the shared fix.",
116 116 expect(JSON.stringify(sentMessages[2])).toContain("successful_behaviors");
117 - const notifications = t.events.ui
118 - .filter((call) => call.method === "notify")
119 - .map((call) => call.args[0]);
117 + const notifications = await eventually(
118 + async () =>
119 + t?.events.ui
120 + .filter((call) => call.method === "notify")
121 + .map((call) => call.args[0]) ?? [],
122 + (value) =>
123 + value.some((message) => String(message).includes("good-job learned")),
124 + );
120 125 expect(notifications).toEqual(
121 126 expect.arrayContaining([
122 127 expect.stringContaining("good-job queued"),

extensions/good-job/implementation.ts

Modified
43 43 const MAX_TOKENS = 1_200;
45 45 type ContextSnapshot = Message[];
46 +type BackgroundContext = {
47 + modelRegistry: ExtensionContext["modelRegistry"];
48 + ui?: ExtensionContext["ui"];
49 +};
47 51 type Opener = { command: string; args: string[] };
48 52 type GoodJobSettings = {
70 74 return ctx.model ? { provider: ctx.model.provider, id: ctx.model.id } : null;
77 +function backgroundContext(ctx: ExtensionContext): BackgroundContext {
78 + return {
79 + modelRegistry: ctx.modelRegistry,
80 + ui: ctx.hasUI ? ctx.ui : undefined,
81 + };
73 84 function isObject(value: unknown): value is Record<string, unknown> {
74 85 return value !== null && typeof value === "object" && !Array.isArray(value);
229 240 async start(ctx: ExtensionContext): Promise<void> {
241 + const background = backgroundContext(ctx);
242 + const cwd = ctx.cwd;
230 243 const previousPump = this.pumpPromise;
231 244 const generation = ++this.generation;
232 245 this.activeController?.abort();
233 246 if (previousPump) await previousPump;
234 247 if (generation !== this.generation) return;
235 248 this.pumpRequested = false;
236 - this.readSettings(ctx.cwd);
249 + this.readSettings(cwd);
237 250 if (!this.openerChecked) {
238 251 this.openerChecked = true;
239 - if (!this.opener && ctx.hasUI)
240 - ctx.ui.notify(
252 + if (!this.opener)
253 + background.ui?.notify(
241 254 "good-job: directory opening unavailable; no platform opener found",
242 255 "info",
245 258 if (!existsSync(this.paths.root)) return;
246 - await this.recoverAndPump(ctx, generation);
259 + await this.recoverAndPump(background, generation);
249 262 async stop(ctx: ExtensionContext): Promise<void> {
263 + const ui = ctx.hasUI ? ctx.ui : undefined;
250 264 this.generation++;
251 265 this.pumpRequested = false;
252 266 this.activeController?.abort();
253 267 await this.pumpPromise;
254 268 this.activeController = undefined;
255 - this.stopSpinner(ctx);
269 + this.stopSpinner(ui);
258 272 async capture(praise: string, ctx: ExtensionContext): Promise<void> {
273 + const background = backgroundContext(ctx);
259 274 this.readSettings(ctx.cwd);
260 275 const sessionContext = buildSessionContext(
261 276 ctx.sessionManager.getEntries(),
273 288 await ensureLayout(this.paths);
274 289 await enqueueJob(job, this.paths);
275 290 this.snapshots.set(job.id, snapshot);
276 - if (ctx.hasUI)
277 - ctx.ui.notify(`good-job queued · ${job.id.slice(0, 8)}`, "info");
278 - void this.pump(ctx, this.generation, job.id);
291 + background.ui?.notify(`good-job queued · ${job.id.slice(0, 8)}`, "info");
292 + void this.pump(background, this.generation, job.id);
281 295 async runCommand(args: string, ctx: ExtensionContext): Promise<void> {
319 333 private async recoverAndPump(
320 - ctx: ExtensionContext,
334 + ctx: BackgroundContext,
321 335 generation: number,
322 336 ): Promise<void> {
323 337 await ensureLayout(this.paths);
328 342 private pump(
329 - ctx: ExtensionContext,
343 + ctx: BackgroundContext,
330 344 generation: number,
331 345 preferredId?: string,
332 346 ): Promise<void> {
337 351 this.pumpRequested = false;
338 352 this.pumpPromise = this.pumpJobs(ctx, generation, preferredId)
339 353 .catch((error) => {
340 - if (generation === this.generation && ctx.hasUI)
341 - ctx.ui.notify(
354 + if (generation === this.generation)
355 + ctx.ui?.notify(
342 356 `good-job queue failed: ${boundedError(error)}`,
343 357 "error",
354 368 private async pumpJobs(
355 - ctx: ExtensionContext,
369 + ctx: BackgroundContext,
356 370 generation: number,
357 371 preferredId?: string,
358 372 ): Promise<void> {
369 383 await this.process(claimed.job, claimed.path, ctx, generation);
371 385 } finally {
372 - this.stopSpinner(ctx);
386 + this.stopSpinner(ctx.ui);
376 390 private async process(
377 391 job: GoodJobJob,
378 392 claimPath: string,
379 - ctx: ExtensionContext,
393 + ctx: BackgroundContext,
380 394 generation: number,
381 395 ): Promise<void> {
382 396 const controller = new AbortController();
436 450 await commitRecord(record, claimPath, this.paths);
437 451 this.snapshots.delete(job.id);
438 - if (ctx.hasUI)
439 - ctx.ui.notify(
440 - `good-job learned · ${record.learning.achievement}`,
441 - "info",
442 - );
452 + ctx.ui?.notify(
453 + `good-job learned · ${record.learning.achievement}`,
454 + "info",
455 + );
443 456 } catch (error) {
444 457 if (controller.signal.aborted || generation !== this.generation) return;
448 461 } catch (storageError) {
449 462 console.error("[good-job] could not persist failure", storageError);
451 - if (ctx.hasUI)
452 - ctx.ui.notify(`good-job failed: ${boundedError(error)}`, "error");
464 + ctx.ui?.notify(`good-job failed: ${boundedError(error)}`, "error");
453 465 } finally {
454 466 if (this.activeController === controller)
455 467 this.activeController = undefined;
459 - private startSpinner(ctx: ExtensionContext, count: number): void {
460 - this.stopSpinner(ctx);
461 - if (!ctx.hasUI || count === 0) return;
471 + private startSpinner(ctx: BackgroundContext, count: number): void {
472 + const { ui } = ctx;
473 + this.stopSpinner(ui);
474 + if (!ui || count === 0) return;
462 475 this.spinnerCount = count;
463 476 this.spinnerStartedAt = Date.now();
464 477 const render = () => {
467 480 Math.floor((Date.now() - this.spinnerStartedAt) / 120) %
468 481 SPINNER.length
469 482 ] ?? SPINNER[0];
470 - ctx.ui.setStatus(
483 + ui.setStatus(
471 484 STATUS_KEY,
472 - ctx.ui.theme.fg(
485 + ui.theme.fg(
473 486 "accent",
474 487 `${frame} good-job learning${this.spinnerCount > 1 ? ` (${this.spinnerCount})` : ""}`,
480 493 this.spinnerTimer.unref?.();
483 - private stopSpinner(ctx: ExtensionContext): void {
496 + private stopSpinner(ui?: ExtensionContext["ui"]): void {
484 497 if (this.spinnerTimer) clearInterval(this.spinnerTimer);
485 498 this.spinnerTimer = undefined;
486 - if (ctx.hasUI) ctx.ui.setStatus(STATUS_KEY, undefined);
499 + ui?.setStatus(STATUS_KEY, undefined);
489 502 private async list(ctx: ExtensionContext): Promise<void> {

extensions/good-job/index.ts

Modified
33 33 pi.on("input", async (event, ctx) => {
34 34 if (event.source === "extension" || !isGoodJobTrigger(event.text))
35 35 return { action: "continue" };
36 + const ui = ctx.hasUI ? ctx.ui : undefined;
36 37 try {
37 38 await sessionReady;
38 39 await (await getRuntime()).capture(event.text, ctx);
39 40 } catch (error) {
40 41 const message = error instanceof Error ? error.message : String(error);
41 - if (ctx.hasUI)
42 - ctx.ui.notify(`good-job could not queue: ${message}`, "error");
42 + ui?.notify(`good-job could not queue: ${message}`, "error");
44 44 return { action: "handled" };