pi-better-goal 0.1.14 → 0.1.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -15,7 +15,7 @@ Use `pi-better-goal` when a Pi session should keep an explicit objective visible
15
15
  - `/goal` runtime for starting, pausing, resuming, completing, and clearing the current objective.
16
16
  - A compact goal widget that does not replace Pi's footer.
17
17
  - Background activity tracking for subagents and other registered providers.
18
- - A follow-up wake when active background work drains to zero.
18
+ - A progress-aware follow-up loop that holds after repeated identical outcomes.
19
19
 
20
20
  ## Install
21
21
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-better-goal",
3
- "version": "0.1.14",
3
+ "version": "0.1.16",
4
4
  "description": "Pi extension for goal tracking with background-aware continuation.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -35,6 +35,8 @@
35
35
  "image": "https://raw.githubusercontent.com/1aboveio/pi-better-harness/main/docs/images/package-gallery/pi-better-goal.png"
36
36
  },
37
37
  "scripts": {
38
+ "pretest": "node ../../scripts/sync-shared-log-utils.mjs",
39
+ "prepack": "node ../../scripts/sync-shared-log-utils.mjs",
38
40
  "test": "node --import tsx --test test/*.test.ts",
39
41
  "typecheck": "tsc --noEmit",
40
42
  "verify": "npm run typecheck && npm test"
@@ -0,0 +1,98 @@
1
+ import { createHash } from "node:crypto";
2
+
3
+ export interface ContinuationEvidence {
4
+ signature: string;
5
+ summary: string;
6
+ }
7
+
8
+ interface MessageLike {
9
+ role?: unknown;
10
+ content?: unknown;
11
+ toolName?: unknown;
12
+ isError?: unknown;
13
+ details?: unknown;
14
+ }
15
+
16
+ function isRecord(value: unknown): value is Record<string, unknown> {
17
+ return value !== null && typeof value === "object" && !Array.isArray(value);
18
+ }
19
+
20
+ function canonicalJson(value: unknown): string {
21
+ if (value === null || typeof value !== "object") {
22
+ return JSON.stringify(value);
23
+ }
24
+ if (Array.isArray(value)) {
25
+ return `[${value.map(canonicalJson).join(",")}]`;
26
+ }
27
+ const record = value as Record<string, unknown>;
28
+ return `{${Object.keys(record).sort().map((key) => `${JSON.stringify(key)}:${canonicalJson(record[key])}`).join(",")}}`;
29
+ }
30
+
31
+ function resultContent(content: unknown): unknown[] {
32
+ if (!Array.isArray(content)) {
33
+ return [content];
34
+ }
35
+ return content.map((block) => {
36
+ if (!isRecord(block)) {
37
+ return block;
38
+ }
39
+ if (block.type === "text") {
40
+ return { type: "text", text: block.text };
41
+ }
42
+ if (block.type === "image") {
43
+ return { type: "image", data: block.data, mimeType: block.mimeType };
44
+ }
45
+ return block;
46
+ });
47
+ }
48
+
49
+ /**
50
+ * Hash stable, observable turn evidence without persisting tool arguments or output.
51
+ * Call IDs, timestamps, thinking, usage, and provider metadata are deliberately excluded.
52
+ */
53
+ export function continuationEvidence(messages: readonly unknown[]): ContinuationEvidence {
54
+ const records: unknown[] = [];
55
+ const toolNames: string[] = [];
56
+
57
+ for (const candidate of messages) {
58
+ if (!isRecord(candidate)) {
59
+ continue;
60
+ }
61
+ const message = candidate as MessageLike;
62
+ if (message.role === "assistant" && Array.isArray(message.content)) {
63
+ const actions = message.content.flatMap((block) => {
64
+ if (!isRecord(block) || block.type !== "toolCall" || typeof block.name !== "string") {
65
+ return [];
66
+ }
67
+ toolNames.push(block.name);
68
+ return [{ name: block.name, arguments: block.arguments }];
69
+ });
70
+ const text = message.content.flatMap((block) =>
71
+ isRecord(block) && block.type === "text" ? [{ text: block.text }] : [],
72
+ );
73
+ if (actions.length > 0 || text.length > 0) {
74
+ records.push({ role: "assistant", actions, text });
75
+ }
76
+ continue;
77
+ }
78
+ if (message.role === "toolResult") {
79
+ const toolName = typeof message.toolName === "string" ? message.toolName : "unknown";
80
+ toolNames.push(toolName);
81
+ records.push({
82
+ role: "toolResult",
83
+ toolName,
84
+ isError: message.isError === true,
85
+ content: resultContent(message.content),
86
+ details: message.details,
87
+ });
88
+ }
89
+ }
90
+
91
+ const payload = canonicalJson(records.length > 0 ? records : [{ role: "empty" }]);
92
+ const signature = createHash("sha256").update(payload).digest("hex");
93
+ const distinctTools = [...new Set(toolNames)];
94
+ return {
95
+ signature,
96
+ summary: distinctTools.length > 0 ? distinctTools.join(", ") : "no observable action",
97
+ };
98
+ }
package/src/goal-clock.ts CHANGED
@@ -8,6 +8,7 @@ export interface GoalTiming {
8
8
  }
9
9
 
10
10
  export const COMPLETED_GOAL_RETENTION_SECONDS = 30;
11
+ export const ACTIVE_GOAL_REFRESH_MS = 10_000;
11
12
 
12
13
  export function isGoalClockVisible(
13
14
  goal: GoalSnapshot,
@@ -19,6 +20,17 @@ export function isGoalClockVisible(
19
20
  return now - goal.completedAt < COMPLETED_GOAL_RETENTION_SECONDS;
20
21
  }
21
22
 
23
+ export function goalClockRefreshDelayMs(goal: GoalSnapshot, nowMs = Date.now()): number | null {
24
+ if (goal.status === "active") {
25
+ return ACTIVE_GOAL_REFRESH_MS;
26
+ }
27
+ if (goal.status !== "complete" || goal.completedAt === null) {
28
+ return null;
29
+ }
30
+ const deadlineMs = (goal.completedAt + COMPLETED_GOAL_RETENTION_SECONDS) * 1_000;
31
+ return deadlineMs > nowMs ? deadlineMs - nowMs : null;
32
+ }
33
+
22
34
  export function goalTiming(goal: GoalSnapshot, now = Math.floor(Date.now() / 1000)): GoalTiming {
23
35
  const activeDelta =
24
36
  goal.status === "active" && goal.activeStartedAt !== null
package/src/goal-state.ts CHANGED
@@ -25,6 +25,15 @@ interface GoalLike {
25
25
 
26
26
  export type GoalEntrySource = "command" | "tool" | "runtime";
27
27
 
28
+ export interface ContinuationState {
29
+ goalId: string;
30
+ lastEvidenceSignature: string | null;
31
+ lastEvidenceSummary: string;
32
+ noProgressRetries: number;
33
+ blocked: boolean;
34
+ updatedAt: number;
35
+ }
36
+
28
37
  export type GoalCustomEntry =
29
38
  | {
30
39
  version: 1;
@@ -39,6 +48,12 @@ export type GoalCustomEntry =
39
48
  source: GoalEntrySource;
40
49
  clearedGoalId: string | null;
41
50
  at: number;
51
+ }
52
+ | {
53
+ version: 1;
54
+ kind: "continuation-state";
55
+ state: ContinuationState;
56
+ at: number;
42
57
  };
43
58
 
44
59
  function isGoalStatus(value: unknown): value is GoalStatus {
@@ -57,6 +72,23 @@ function isGoalLike(value: unknown): value is GoalLike {
57
72
  );
58
73
  }
59
74
 
75
+ function isContinuationState(value: unknown): value is ContinuationState {
76
+ if (!value || typeof value !== "object") {
77
+ return false;
78
+ }
79
+ const candidate = value as Partial<ContinuationState>;
80
+ return (
81
+ typeof candidate.goalId === "string" &&
82
+ (candidate.lastEvidenceSignature === null || typeof candidate.lastEvidenceSignature === "string") &&
83
+ typeof candidate.lastEvidenceSummary === "string" &&
84
+ typeof candidate.noProgressRetries === "number" &&
85
+ Number.isInteger(candidate.noProgressRetries) &&
86
+ candidate.noProgressRetries >= 0 &&
87
+ typeof candidate.blocked === "boolean" &&
88
+ typeof candidate.updatedAt === "number"
89
+ );
90
+ }
91
+
60
92
  function unixSeconds(): number {
61
93
  return Math.floor(Date.now() / 1000);
62
94
  }
@@ -141,6 +173,21 @@ export function goalClearEntry(clearedGoalId: string | null, source: GoalEntrySo
141
173
  return { version: 1, kind: "clear", source, clearedGoalId, at: unixSeconds() };
142
174
  }
143
175
 
176
+ export function createContinuationState(goalId: string, now = unixSeconds()): ContinuationState {
177
+ return {
178
+ goalId,
179
+ lastEvidenceSignature: null,
180
+ lastEvidenceSummary: "",
181
+ noProgressRetries: 0,
182
+ blocked: false,
183
+ updatedAt: now,
184
+ };
185
+ }
186
+
187
+ export function continuationStateEntry(state: ContinuationState): GoalCustomEntry {
188
+ return { version: 1, kind: "continuation-state", state, at: unixSeconds() };
189
+ }
190
+
144
191
  export function goalWithStatus(
145
192
  goal: GoalSnapshot,
146
193
  status: GoalStatus,
@@ -214,4 +261,18 @@ export function reconstructGoalSnapshot(entries: Iterable<SessionEntryLike>): Go
214
261
 
215
262
  export function currentGoalSnapshot(ctx: ExtensionContext): GoalSnapshot | null {
216
263
  return reconstructGoalSnapshot(ctx.sessionManager.getBranch() as Iterable<SessionEntryLike>);
264
+ }
265
+
266
+ export function currentContinuationState(ctx: ExtensionContext, goalId: string): ContinuationState | null {
267
+ let state: ContinuationState | null = null;
268
+ for (const entry of ctx.sessionManager.getBranch() as Iterable<SessionEntryLike>) {
269
+ if (entry.type !== "custom" || entry.customType !== EXTENSION_NAME || !entry.data || typeof entry.data !== "object") {
270
+ continue;
271
+ }
272
+ const data = entry.data as { kind?: unknown; state?: unknown };
273
+ if (data.kind === "continuation-state" && isContinuationState(data.state) && data.state.goalId === goalId) {
274
+ state = data.state;
275
+ }
276
+ }
277
+ return state;
217
278
  }
package/src/index.ts CHANGED
@@ -9,7 +9,10 @@ import {
9
9
  type BackgroundDrainTracker,
10
10
  } from "./activity.js";
11
11
  import {
12
+ continuationStateEntry,
13
+ createContinuationState,
12
14
  createGoalSnapshot,
15
+ currentContinuationState,
13
16
  currentGoalSnapshot,
14
17
  goalClearEntry,
15
18
  goalSetEntry,
@@ -17,7 +20,14 @@ import {
17
20
  validateObjective,
18
21
  validateTokenBudget,
19
22
  } from "./goal-state.js";
20
- import { goalTiming, isGoalClockVisible, renderGoalClockLine } from "./goal-clock.js";
23
+ import { continuationEvidence, type ContinuationEvidence } from "./continuation.js";
24
+ import {
25
+ goalClockRefreshDelayMs,
26
+ goalTiming,
27
+ isGoalClockVisible,
28
+ renderGoalClockLine,
29
+ } from "./goal-clock.js";
30
+ import { createRenderScheduler } from "./shared-render-scheduler.js";
21
31
  import { collectSubagentActivity } from "./subagents.js";
22
32
  import {
23
33
  EVENT_ACTIVITY,
@@ -33,6 +43,7 @@ import {
33
43
 
34
44
  const POLL_INTERVAL_MS = 2_000;
35
45
  const DEFAULT_IDLE_CONTINUATION_DELAY_MS = 30_000;
46
+ const DEFAULT_MAX_NO_PROGRESS_RETRIES = 3;
36
47
  const WAKE_DISABLED =
37
48
  process.env.PI_BETTER_GOAL_DISABLE_WAKE === "1" ||
38
49
  process.env.PI_BETTER_EXTENSION_DISABLE_WAKE === "1";
@@ -40,6 +51,10 @@ const IDLE_CONTINUATION_DELAY_MS = parseDurationEnv(
40
51
  process.env.PI_BETTER_GOAL_IDLE_CONTINUATION_DELAY_MS,
41
52
  DEFAULT_IDLE_CONTINUATION_DELAY_MS,
42
53
  );
54
+ const MAX_NO_PROGRESS_RETRIES = parseRetryLimit(
55
+ process.env.PI_BETTER_GOAL_MAX_NO_PROGRESS_RETRIES,
56
+ DEFAULT_MAX_NO_PROGRESS_RETRIES,
57
+ );
43
58
 
44
59
  function parseDurationEnv(raw: string | undefined, fallback: number): number {
45
60
  if (raw === undefined || raw.trim() === "") {
@@ -49,6 +64,14 @@ function parseDurationEnv(raw: string | undefined, fallback: number): number {
49
64
  return Number.isFinite(parsed) && parsed >= 0 ? parsed : fallback;
50
65
  }
51
66
 
67
+ function parseRetryLimit(raw: string | undefined, fallback: number): number {
68
+ if (raw === undefined || raw.trim() === "") {
69
+ return fallback;
70
+ }
71
+ const parsed = Number(raw);
72
+ return Number.isInteger(parsed) && parsed >= 0 ? parsed : fallback;
73
+ }
74
+
52
75
  function continuationPrompt(goal: GoalSnapshot): string {
53
76
  return [
54
77
  "Continue working toward the active thread goal.",
@@ -59,12 +82,15 @@ function continuationPrompt(goal: GoalSnapshot): string {
59
82
  ].join("\n");
60
83
  }
61
84
 
62
- function formatGoal(goal: GoalSnapshot | null): string {
85
+ function formatGoal(goal: GoalSnapshot | null, continuation: ReturnType<typeof currentContinuationState> = null): string {
63
86
  if (!goal) {
64
87
  return "No goal is set.";
65
88
  }
66
89
  const budget = goal.tokenBudget === null ? "none" : String(goal.tokenBudget);
67
90
  const timing = goalTiming(goal);
91
+ const continuationStatus = continuation?.blocked
92
+ ? `Automatic continuation: waiting after ${continuation.noProgressRetries} identical retries (${continuation.lastEvidenceSummary})`
93
+ : `Automatic continuation: retry limit ${MAX_NO_PROGRESS_RETRIES}`;
68
94
  return [
69
95
  `Goal: ${goal.objective}`,
70
96
  `Status: ${goal.status}`,
@@ -72,6 +98,7 @@ function formatGoal(goal: GoalSnapshot | null): string {
72
98
  `Tokens used: ${goal.usage.tokensUsed}`,
73
99
  `Active time: ${timing.activeSeconds}s`,
74
100
  `Elapsed time: ${timing.elapsedSeconds}s`,
101
+ continuationStatus,
75
102
  ].join("\n");
76
103
  }
77
104
 
@@ -110,14 +137,25 @@ export default function (pi: ExtensionAPI): void {
110
137
  let continuationQueuedFor: string | null = null;
111
138
  let idleContinuationTimer: ReturnType<typeof setTimeout> | undefined;
112
139
  let idleContinuationSignature = "";
140
+ let refreshGoalWidget: (() => void) | undefined;
141
+ let lastAgentEvidence: ContinuationEvidence | null = null;
113
142
 
114
143
  const getGoal = (ctx: ExtensionContext): GoalSnapshot | null => currentGoalSnapshot(ctx);
115
144
 
145
+ const appendContinuationState = (state: ReturnType<typeof createContinuationState>): void => {
146
+ pi.appendEntry(EXTENSION_NAME, continuationStateEntry(state));
147
+ };
148
+
149
+ const resetContinuationState = (goal: GoalSnapshot): void => {
150
+ appendContinuationState(createContinuationState(goal.goalId));
151
+ };
152
+
116
153
  const setGoal = (goal: GoalSnapshot, ctx: ExtensionContext, source: "command" | "tool" | "runtime"): void => {
117
154
  pi.appendEntry(EXTENSION_NAME, goalSetEntry(goal, source));
118
155
  continuationQueuedFor = null;
119
156
  backgroundDrainTracker = null;
120
157
  clearIdleContinuation();
158
+ refreshGoalWidget?.();
121
159
  };
122
160
 
123
161
  const clearGoal = (ctx: ExtensionContext, source: "command" | "tool" | "runtime"): void => {
@@ -126,6 +164,7 @@ export default function (pi: ExtensionAPI): void {
126
164
  continuationQueuedFor = null;
127
165
  backgroundDrainTracker = null;
128
166
  clearIdleContinuation();
167
+ refreshGoalWidget?.();
129
168
  };
130
169
 
131
170
  const queueGoalContinuation = (goal: GoalSnapshot): void => {
@@ -134,6 +173,7 @@ export default function (pi: ExtensionAPI): void {
134
173
  }
135
174
  clearIdleContinuation();
136
175
  continuationQueuedFor = goal.goalId;
176
+ resetContinuationState(goal);
137
177
  pi.sendMessage(
138
178
  {
139
179
  customType: EXTENSION_NAME,
@@ -162,6 +202,9 @@ export default function (pi: ExtensionAPI): void {
162
202
  if (WAKE_DISABLED || goal.status !== "active" || continuationQueuedFor === goal.goalId) {
163
203
  return;
164
204
  }
205
+ if (kind === "continuation" && currentContinuationState(ctx, goal.goalId)?.blocked) {
206
+ return;
207
+ }
165
208
  const signature = `${goal.goalId}:${kind}`;
166
209
  if (idleContinuationTimer && idleContinuationSignature === signature) {
167
210
  return;
@@ -193,6 +236,10 @@ export default function (pi: ExtensionAPI): void {
193
236
  return;
194
237
  }
195
238
 
239
+ // A background drain is a meaningful external state transition and reopens a held goal.
240
+ if (kind === "background-drained") {
241
+ resetContinuationState(goal);
242
+ }
196
243
  continuationQueuedFor = goal.goalId;
197
244
  const content = kind === "background-drained"
198
245
  ? "Background activity for the active goal is no longer running. Inspect any subagent callbacks or final results, then continue the completion audit before marking the goal complete.\n\n" +
@@ -260,9 +307,13 @@ export default function (pi: ExtensionAPI): void {
260
307
  }
261
308
 
262
309
  if (ctx.hasUI) {
310
+ const goal = getGoal(ctx);
311
+ const continuation = goal ? currentContinuationState(ctx, goal.goalId) : null;
263
312
  const status = snapshot.backgroundRunning
264
313
  ? `bg ${snapshot.activeBackgroundCount}${snapshot.unhealthyBackgroundCount ? `, ${snapshot.unhealthyBackgroundCount} unhealthy` : ""}`
265
- : undefined;
314
+ : continuation?.blocked
315
+ ? "waiting: no progress"
316
+ : undefined;
266
317
  try {
267
318
  ctx.ui.setStatus(EXTENSION_NAME, status);
268
319
  } catch {
@@ -308,18 +359,26 @@ export default function (pi: ExtensionAPI): void {
308
359
  ctx.ui.setWidget(
309
360
  EXTENSION_NAME,
310
361
  (tui, theme) => {
311
- const timer = setInterval(() => tui.requestRender(), 1_000);
312
- timer.unref?.();
362
+ const scheduler = createRenderScheduler(() => tui.requestRender());
363
+ const refresh = (): void => scheduler.request();
364
+ refreshGoalWidget = refresh;
365
+
313
366
  return {
314
367
  dispose() {
315
- clearInterval(timer);
368
+ scheduler.dispose();
369
+ if (refreshGoalWidget === refresh) {
370
+ refreshGoalWidget = undefined;
371
+ }
316
372
  },
317
373
  invalidate() {},
318
374
  render(width: number): string[] {
319
375
  const goal = getGoal(ctx);
376
+ scheduler.cancel();
320
377
  if (!goal || !isGoalClockVisible(goal)) {
321
378
  return [];
322
379
  }
380
+ const nextRenderDelay = goalClockRefreshDelayMs(goal);
381
+ if (nextRenderDelay !== null) scheduler.schedule(nextRenderDelay);
323
382
  const fg = typeof theme?.fg === "function"
324
383
  ? (color: string, value: string) => theme.fg(color as never, value)
325
384
  : undefined;
@@ -348,7 +407,7 @@ export default function (pi: ExtensionAPI): void {
348
407
  const current = getGoal(ctx);
349
408
 
350
409
  if (!trimmed) {
351
- ctx.ui.notify(formatGoal(current), "info");
410
+ ctx.ui.notify(formatGoal(current, current ? currentContinuationState(ctx, current.goalId) : null), "info");
352
411
  return;
353
412
  }
354
413
 
@@ -417,9 +476,10 @@ export default function (pi: ExtensionAPI): void {
417
476
  parameters: Type.Object({}),
418
477
  async execute(_toolCallId, _params, _signal, _onUpdate, ctx) {
419
478
  const goal = getGoal(ctx);
479
+ const continuation = goal ? currentContinuationState(ctx, goal.goalId) : null;
420
480
  return {
421
- content: [{ type: "text", text: formatGoal(goal) }],
422
- details: { goal, timing: goal ? goalTiming(goal) : null, hasGoal: goal !== null },
481
+ content: [{ type: "text", text: formatGoal(goal, continuation) }],
482
+ details: { goal, continuation, timing: goal ? goalTiming(goal) : null, hasGoal: goal !== null },
423
483
  };
424
484
  },
425
485
  });
@@ -495,6 +555,16 @@ export default function (pi: ExtensionAPI): void {
495
555
  startPolling();
496
556
  });
497
557
 
558
+ pi.on("input", async (event, ctx) => {
559
+ if (event.source === "extension") {
560
+ return;
561
+ }
562
+ const goal = getGoal(ctx);
563
+ if (goal?.status === "active") {
564
+ resetContinuationState(goal);
565
+ }
566
+ });
567
+
498
568
  pi.on("before_agent_start", async (event, ctx) => {
499
569
  currentCtx = ctx;
500
570
  const goal = currentGoalSnapshot(ctx);
@@ -518,15 +588,44 @@ export default function (pi: ExtensionAPI): void {
518
588
  foregroundRunning = true;
519
589
  clearIdleContinuation();
520
590
  continuationQueuedFor = null;
591
+ lastAgentEvidence = null;
521
592
  await publishSnapshot(ctx);
522
593
  });
523
594
 
595
+ pi.on("agent_end", async (event, _ctx) => {
596
+ lastAgentEvidence = continuationEvidence(event.messages);
597
+ });
598
+
524
599
  pi.on("agent_settled", async (_event, ctx) => {
525
600
  currentCtx = ctx;
526
601
  foregroundRunning = false;
527
602
  const snapshot = await publishSnapshot(ctx);
528
603
  const goal = getGoal(ctx);
529
604
  if (goal?.status === "active" && !snapshot.backgroundRunning) {
605
+ const previous = currentContinuationState(ctx, goal.goalId) ?? createContinuationState(goal.goalId);
606
+ const evidence = lastAgentEvidence ?? continuationEvidence([]);
607
+ const repeated = previous.lastEvidenceSignature === evidence.signature;
608
+ const noProgressRetries = repeated ? previous.noProgressRetries + 1 : 0;
609
+ const blocked = repeated && noProgressRetries >= MAX_NO_PROGRESS_RETRIES;
610
+ appendContinuationState({
611
+ goalId: goal.goalId,
612
+ lastEvidenceSignature: evidence.signature,
613
+ lastEvidenceSummary: evidence.summary,
614
+ noProgressRetries,
615
+ blocked,
616
+ updatedAt: Math.floor(Date.now() / 1000),
617
+ });
618
+ if (blocked) {
619
+ refreshGoalWidget?.();
620
+ if (ctx.hasUI) {
621
+ ctx.ui.setStatus(EXTENSION_NAME, "waiting: no progress");
622
+ ctx.ui.notify(
623
+ `Goal automatic continuation is waiting after ${noProgressRetries} identical retries (${evidence.summary}). New input or background activity will resume it.`,
624
+ "warning",
625
+ );
626
+ }
627
+ return;
628
+ }
530
629
  scheduleIdleContinuation(goal, ctx, "continuation", snapshot);
531
630
  }
532
631
  });
@@ -0,0 +1,47 @@
1
+ // Generated from packages/render-scheduler/index.ts. Do not edit directly.
2
+ export interface RenderScheduler {
3
+ request(): void;
4
+ schedule(delayMs: number): void;
5
+ cancel(): void;
6
+ dispose(): void;
7
+ pending(): boolean;
8
+ }
9
+
10
+ /**
11
+ * Schedule TUI paints as replaceable one-shot deadlines. Callers reschedule
12
+ * only while visible state still changes; static and hidden UI stays idle.
13
+ */
14
+ export function createRenderScheduler(requestRender: () => void): RenderScheduler {
15
+ let timer: ReturnType<typeof setTimeout> | undefined;
16
+ let disposed = false;
17
+
18
+ const cancel = (): void => {
19
+ if (timer) clearTimeout(timer);
20
+ timer = undefined;
21
+ };
22
+
23
+ return {
24
+ request() {
25
+ if (disposed) return;
26
+ cancel();
27
+ requestRender();
28
+ },
29
+ schedule(delayMs: number) {
30
+ if (disposed) return;
31
+ cancel();
32
+ timer = setTimeout(() => {
33
+ timer = undefined;
34
+ if (!disposed) requestRender();
35
+ }, Math.max(0, delayMs));
36
+ timer.unref?.();
37
+ },
38
+ cancel,
39
+ dispose() {
40
+ disposed = true;
41
+ cancel();
42
+ },
43
+ pending() {
44
+ return timer !== undefined;
45
+ },
46
+ };
47
+ }