@narumitw/pi-plan-mode 0.58.0 → 0.58.2

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.
Files changed (39) hide show
  1. package/dist/chunks/{chunk-QHHHBTDO.js → chunk-L2CXUWCH.ts} +29 -111
  2. package/dist/chunks/chunk-L2CXUWCH.ts.map +7 -0
  3. package/dist/chunks/{interactive-ui-UNJGC2RQ.js → interactive-ui-VHZ5GODE.ts} +13 -41
  4. package/dist/chunks/interactive-ui-VHZ5GODE.ts.map +7 -0
  5. package/dist/index.ts +25 -82
  6. package/dist/index.ts.map +2 -2
  7. package/package.json +50 -51
  8. package/src/active-implementation-menu.ts +57 -60
  9. package/src/command.ts +22 -22
  10. package/src/completion-tool.ts +53 -56
  11. package/src/extension-runtime.ts +5 -5
  12. package/src/finalization-request.ts +40 -44
  13. package/src/fresh-handoff-coordinator.ts +38 -41
  14. package/src/fresh-implementation.ts +293 -310
  15. package/src/implementation-models.ts +25 -30
  16. package/src/implementation-retention.ts +109 -123
  17. package/src/message-transform.ts +218 -252
  18. package/src/mode-contract.ts +46 -49
  19. package/src/plan-action-controller.ts +134 -155
  20. package/src/plan-action-menus.ts +390 -408
  21. package/src/plan-export-controller.ts +23 -28
  22. package/src/plan-export-screen.ts +13 -13
  23. package/src/plan-export.ts +85 -102
  24. package/src/plan-launch-menu.ts +119 -119
  25. package/src/plan-mode.ts +2017 -2098
  26. package/src/presentation.ts +84 -108
  27. package/src/prompt.ts +1 -1
  28. package/src/question-tool.ts +239 -267
  29. package/src/required-tools.ts +15 -19
  30. package/src/saved-plan-menu.ts +82 -84
  31. package/src/saved-plan-preflight.ts +29 -33
  32. package/src/settings-menu.ts +470 -513
  33. package/src/settings.ts +393 -452
  34. package/src/state.ts +167 -198
  35. package/src/tool-policy.ts +634 -699
  36. package/src/tool-selection.ts +39 -44
  37. package/src/workflow-mutex.ts +66 -66
  38. package/dist/chunks/chunk-QHHHBTDO.js.map +0 -7
  39. package/dist/chunks/interactive-ui-UNJGC2RQ.js.map +0 -7
package/package.json CHANGED
@@ -1,53 +1,52 @@
1
1
  {
2
- "name": "@narumitw/pi-plan-mode",
3
- "version": "0.58.0",
4
- "description": "Pi extension that adds a Codex-like read-only /plan collaboration mode.",
5
- "type": "module",
6
- "license": "MIT",
7
- "private": false,
8
- "keywords": [
9
- "pi-package",
10
- "pi-extension",
11
- "pi",
12
- "plan-mode",
13
- "planning"
14
- ],
15
- "files": [
16
- "src",
17
- "dist",
18
- "docs",
19
- "README.md",
20
- "LICENSE"
21
- ],
22
- "pi": {
23
- "extensions": [
24
- "./dist/index.ts"
25
- ]
26
- },
27
- "scripts": {
28
- "build": "node scripts/build-runtime.mjs",
29
- "check": "npm run build && biome check . && npm run typecheck",
30
- "format": "biome check --write .",
31
- "typecheck": "tsc --noEmit",
32
- "prepack": "npm run build"
33
- },
34
- "peerDependencies": {
35
- "@earendil-works/pi-coding-agent": "*",
36
- "@earendil-works/pi-tui": "*"
37
- },
38
- "devDependencies": {
39
- "@biomejs/biome": "2.5.11",
40
- "@earendil-works/pi-coding-agent": "0.85.0",
41
- "@earendil-works/pi-tui": "0.85.0",
42
- "esbuild": "0.28.2",
43
- "typescript": "7.0.2"
44
- },
45
- "repository": {
46
- "type": "git",
47
- "url": "https://github.com/narumiruna/pi-extensions",
48
- "directory": "packages/pi-plan-mode"
49
- },
50
- "dependencies": {
51
- "@narumitw/pi-tui-kit": "^0.59.0"
52
- }
2
+ "name": "@narumitw/pi-plan-mode",
3
+ "version": "0.58.2",
4
+ "description": "Pi extension that adds a Codex-like read-only /plan collaboration mode.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "private": false,
8
+ "keywords": [
9
+ "pi-package",
10
+ "pi-extension",
11
+ "pi",
12
+ "plan-mode",
13
+ "planning"
14
+ ],
15
+ "files": [
16
+ "src",
17
+ "dist",
18
+ "docs",
19
+ "README.md",
20
+ "LICENSE"
21
+ ],
22
+ "pi": {
23
+ "extensions": [
24
+ "./dist/index.ts"
25
+ ]
26
+ },
27
+ "scripts": {
28
+ "build": "node scripts/build-runtime.mjs",
29
+ "check": "npm run build && biome check . && npm run typecheck",
30
+ "format": "biome check --write .",
31
+ "typecheck": "tsc --noEmit",
32
+ "prepack": "npm run build"
33
+ },
34
+ "peerDependencies": {
35
+ "@earendil-works/pi-coding-agent": "*",
36
+ "@earendil-works/pi-tui": "*"
37
+ },
38
+ "devDependencies": {
39
+ "@earendil-works/pi-coding-agent": "0.86.0",
40
+ "@earendil-works/pi-tui": "0.86.0",
41
+ "esbuild": "0.28.2",
42
+ "typescript": "7.0.2"
43
+ },
44
+ "repository": {
45
+ "type": "git",
46
+ "url": "https://github.com/narumiruna/pi-extensions",
47
+ "directory": "packages/pi-plan-mode"
48
+ },
49
+ "dependencies": {
50
+ "@narumitw/pi-tui-kit": "^0.59.0"
51
+ }
53
52
  }
@@ -3,66 +3,63 @@ import { defineMenu, runMenu } from "@narumitw/pi-tui-kit";
3
3
  import { type PlanExportDestinationProvider, planExportInputScreen } from "./plan-export-screen.js";
4
4
 
5
5
  interface ActiveImplementationMenuOptions {
6
- statusText: string;
7
- getExportDestination: PlanExportDestinationProvider;
8
- signal: AbortSignal;
9
- isCurrent(): boolean;
10
- show(): void;
11
- exportPlan(path: string, signal: AbortSignal): Promise<boolean>;
12
- settings(signal: AbortSignal): Promise<boolean>;
13
- startNew(): void;
14
- clear(): void;
6
+ statusText: string;
7
+ getExportDestination: PlanExportDestinationProvider;
8
+ signal: AbortSignal;
9
+ isCurrent(): boolean;
10
+ show(): void;
11
+ exportPlan(path: string, signal: AbortSignal): Promise<boolean>;
12
+ settings(signal: AbortSignal): Promise<boolean>;
13
+ startNew(): void;
14
+ clear(): void;
15
15
  }
16
16
 
17
- export async function showActiveImplementationMenu(
18
- ctx: ExtensionContext,
19
- options: ActiveImplementationMenuOptions,
20
- ) {
21
- type Screen = "active" | "export";
22
- type Action = "show" | "export" | "settings" | "start-new" | "clear";
23
- const menu = defineMenu<undefined, Screen, Action, ExtensionContext>({
24
- start: "active",
25
- screens: {
26
- active: () => ({
27
- kind: "actions",
28
- title: "Active implementation plan",
29
- lines: [options.statusText],
30
- items: [
31
- { id: "show", label: "Show active implementation plan", action: "show" },
32
- { id: "export", label: "Export plan…", to: "export" },
33
- { id: "settings", label: "Settings", action: "settings" },
34
- { id: "start-new", label: "Start a new plan", action: "start-new" },
35
- { id: "clear", label: "Clear active implementation plan", action: "clear" },
36
- ],
37
- hint: "close",
38
- }),
39
- export: () => planExportInputScreen(options.getExportDestination),
40
- },
41
- actions: {
42
- show: async () => {
43
- options.show();
44
- return { kind: "close" };
45
- },
46
- export: async ({ value, signal }) =>
47
- (await options.exportPlan(value ?? "", signal)) ? { kind: "close" } : { kind: "rejected" },
48
- settings: async ({ signal }) => {
49
- const close = await options.settings(signal);
50
- if (signal.aborted || !options.isCurrent()) return { kind: "rejected" };
51
- return close ? { kind: "close" } : { kind: "stay" };
52
- },
53
- "start-new": async () => {
54
- options.startNew();
55
- return { kind: "close" };
56
- },
57
- clear: async () => {
58
- options.clear();
59
- return { kind: "close" };
60
- },
61
- },
62
- });
63
- await runMenu(ctx, menu, {
64
- getState: () => undefined,
65
- signal: options.signal,
66
- isCurrent: options.isCurrent,
67
- });
17
+ export async function showActiveImplementationMenu(ctx: ExtensionContext, options: ActiveImplementationMenuOptions) {
18
+ type Screen = "active" | "export";
19
+ type Action = "show" | "export" | "settings" | "start-new" | "clear";
20
+ const menu = defineMenu<undefined, Screen, Action, ExtensionContext>({
21
+ start: "active",
22
+ screens: {
23
+ active: () => ({
24
+ kind: "actions",
25
+ title: "Active implementation plan",
26
+ lines: [options.statusText],
27
+ items: [
28
+ { id: "show", label: "Show active implementation plan", action: "show" },
29
+ { id: "export", label: "Export plan…", to: "export" },
30
+ { id: "settings", label: "Settings", action: "settings" },
31
+ { id: "start-new", label: "Start a new plan", action: "start-new" },
32
+ { id: "clear", label: "Clear active implementation plan", action: "clear" },
33
+ ],
34
+ hint: "close",
35
+ }),
36
+ export: () => planExportInputScreen(options.getExportDestination),
37
+ },
38
+ actions: {
39
+ show: async () => {
40
+ options.show();
41
+ return { kind: "close" };
42
+ },
43
+ export: async ({ value, signal }) =>
44
+ (await options.exportPlan(value ?? "", signal)) ? { kind: "close" } : { kind: "rejected" },
45
+ settings: async ({ signal }) => {
46
+ const close = await options.settings(signal);
47
+ if (signal.aborted || !options.isCurrent()) return { kind: "rejected" };
48
+ return close ? { kind: "close" } : { kind: "stay" };
49
+ },
50
+ "start-new": async () => {
51
+ options.startNew();
52
+ return { kind: "close" };
53
+ },
54
+ clear: async () => {
55
+ options.clear();
56
+ return { kind: "close" };
57
+ },
58
+ },
59
+ });
60
+ await runMenu(ctx, menu, {
61
+ getState: () => undefined,
62
+ signal: options.signal,
63
+ isCurrent: options.isCurrent,
64
+ });
68
65
  }
package/src/command.ts CHANGED
@@ -1,31 +1,31 @@
1
1
  export interface CommandArgumentCompletion {
2
- value: string;
3
- label: string;
4
- description?: string;
2
+ value: string;
3
+ label: string;
4
+ description?: string;
5
5
  }
6
6
 
7
7
  const PLAN_COMMAND_COMPLETIONS: readonly CommandArgumentCompletion[] = [
8
- { value: "start", label: "start", description: "Start Plan mode without sending a prompt" },
9
- { value: "show", label: "show", description: "Show the ready, saved, or active plan" },
10
- { value: "finalize", label: "finalize", description: "Request a completed plan" },
11
- { value: "implement", label: "implement", description: "Implement the completed or saved plan" },
12
- { value: "save", label: "save", description: "Save the completed plan for later" },
13
- { value: "settings", label: "settings", description: "Open Plan mode settings" },
14
- { value: "export", label: "export", description: "Export the stored plan to a Markdown file" },
15
- { value: "exit", label: "exit", description: "Leave Plan mode or clear a saved/active plan" },
16
- { value: "off", label: "off", description: "Leave Plan mode or clear a saved/active plan" },
17
- {
18
- value: "tools",
19
- label: "tools",
20
- description: "Choose tools before starting this Plan workflow",
21
- },
8
+ { value: "start", label: "start", description: "Start Plan mode without sending a prompt" },
9
+ { value: "show", label: "show", description: "Show the ready, saved, or active plan" },
10
+ { value: "finalize", label: "finalize", description: "Request a completed plan" },
11
+ { value: "implement", label: "implement", description: "Implement the completed or saved plan" },
12
+ { value: "save", label: "save", description: "Save the completed plan for later" },
13
+ { value: "settings", label: "settings", description: "Open Plan mode settings" },
14
+ { value: "export", label: "export", description: "Export the stored plan to a Markdown file" },
15
+ { value: "exit", label: "exit", description: "Leave Plan mode or clear a saved/active plan" },
16
+ { value: "off", label: "off", description: "Leave Plan mode or clear a saved/active plan" },
17
+ {
18
+ value: "tools",
19
+ label: "tools",
20
+ description: "Choose tools before starting this Plan workflow",
21
+ },
22
22
  ];
23
23
 
24
24
  export function completePlanArguments(argumentPrefix: string): CommandArgumentCompletion[] | null {
25
- const prefix = argumentPrefix.trimStart().toLowerCase();
26
- if (prefix === "") return [...PLAN_COMMAND_COMPLETIONS];
27
- if (/\s/.test(prefix)) return null;
25
+ const prefix = argumentPrefix.trimStart().toLowerCase();
26
+ if (prefix === "") return [...PLAN_COMMAND_COMPLETIONS];
27
+ if (/\s/.test(prefix)) return null;
28
28
 
29
- const matches = PLAN_COMMAND_COMPLETIONS.filter((item) => item.value.startsWith(prefix));
30
- return matches.length > 0 ? [...matches] : null;
29
+ const matches = PLAN_COMMAND_COMPLETIONS.filter((item) => item.value.startsWith(prefix));
30
+ return matches.length > 0 ? [...matches] : null;
31
31
  }
@@ -6,86 +6,83 @@ export const PLAN_MODE_COMPLETE_VERSION = 1;
6
6
  export const PLAN_MODE_MAX_CHARS = 50_000;
7
7
 
8
8
  export type PlanModeCompletionDetails = {
9
- version: typeof PLAN_MODE_COMPLETE_VERSION;
10
- source: typeof PLAN_MODE_COMPLETE_TOOL_NAME;
11
- plan: string;
9
+ version: typeof PLAN_MODE_COMPLETE_VERSION;
10
+ source: typeof PLAN_MODE_COMPLETE_TOOL_NAME;
11
+ plan: string;
12
12
  };
13
13
 
14
14
  export const PLAN_MODE_COMPLETE_PARAMS = {
15
- type: "object",
16
- additionalProperties: false,
17
- required: ["plan"],
18
- properties: {
19
- plan: {
20
- type: "string",
21
- minLength: 1,
22
- maxLength: PLAN_MODE_MAX_CHARS,
23
- description: "The complete decision-ready implementation plan in Markdown.",
24
- },
25
- },
15
+ type: "object",
16
+ additionalProperties: false,
17
+ required: ["plan"],
18
+ properties: {
19
+ plan: {
20
+ type: "string",
21
+ minLength: 1,
22
+ maxLength: PLAN_MODE_MAX_CHARS,
23
+ description: "The complete decision-ready implementation plan in Markdown.",
24
+ },
25
+ },
26
26
  } as const;
27
27
 
28
28
  type NormalizePlanModeCompletionResult = { ok: true; plan: string } | { ok: false; error: string };
29
29
 
30
30
  export function normalizePlanModeCompletion(input: unknown): NormalizePlanModeCompletionResult {
31
- if (!isRecord(input) || typeof input.plan !== "string") {
32
- return { ok: false, error: "plan must be a string" };
33
- }
34
- const plan = input.plan.trim();
35
- if (!plan) return { ok: false, error: "plan must not be empty" };
36
- if (plan.length > PLAN_MODE_MAX_CHARS) {
37
- return {
38
- ok: false,
39
- error: `plan must not exceed ${PLAN_MODE_MAX_CHARS} characters`,
40
- };
41
- }
42
- return { ok: true, plan };
31
+ if (!isRecord(input) || typeof input.plan !== "string") {
32
+ return { ok: false, error: "plan must be a string" };
33
+ }
34
+ const plan = input.plan.trim();
35
+ if (!plan) return { ok: false, error: "plan must not be empty" };
36
+ if (plan.length > PLAN_MODE_MAX_CHARS) {
37
+ return {
38
+ ok: false,
39
+ error: `plan must not exceed ${PLAN_MODE_MAX_CHARS} characters`,
40
+ };
41
+ }
42
+ return { ok: true, plan };
43
43
  }
44
44
 
45
45
  export function planFromCompletionDetails(value: unknown) {
46
- if (!isRecord(value)) return undefined;
47
- if (
48
- value.version !== PLAN_MODE_COMPLETE_VERSION ||
49
- value.source !== PLAN_MODE_COMPLETE_TOOL_NAME
50
- ) {
51
- return undefined;
52
- }
53
- const normalized = normalizePlanModeCompletion({ plan: value.plan });
54
- return normalized.ok ? normalized.plan : undefined;
46
+ if (!isRecord(value)) return undefined;
47
+ if (value.version !== PLAN_MODE_COMPLETE_VERSION || value.source !== PLAN_MODE_COMPLETE_TOOL_NAME) {
48
+ return undefined;
49
+ }
50
+ const normalized = normalizePlanModeCompletion({ plan: value.plan });
51
+ return normalized.ok ? normalized.plan : undefined;
55
52
  }
56
53
 
57
54
  export function planModeCompleted(plan: string) {
58
- return {
59
- content: [{ type: "text" as const, text: `**Proposed Plan**\n\n${plan}` }],
60
- details: {
61
- version: PLAN_MODE_COMPLETE_VERSION,
62
- source: PLAN_MODE_COMPLETE_TOOL_NAME,
63
- plan,
64
- } satisfies PlanModeCompletionDetails,
65
- terminate: true,
66
- };
55
+ return {
56
+ content: [{ type: "text" as const, text: `**Proposed Plan**\n\n${plan}` }],
57
+ details: {
58
+ version: PLAN_MODE_COMPLETE_VERSION,
59
+ source: PLAN_MODE_COMPLETE_TOOL_NAME,
60
+ plan,
61
+ } satisfies PlanModeCompletionDetails,
62
+ terminate: true,
63
+ };
67
64
  }
68
65
 
69
66
  type PlanModeCompletionRenderResult = {
70
- content: Array<{ type: string; text?: string }>;
71
- details?: unknown;
67
+ content: Array<{ type: string; text?: string }>;
68
+ details?: unknown;
72
69
  };
73
70
 
74
71
  export function planModeCompletionMarkdown(result: PlanModeCompletionRenderResult) {
75
- const content = result.content
76
- .filter((block) => block.type === "text" && typeof block.text === "string")
77
- .map((block) => block.text)
78
- .join("\n")
79
- .trim();
80
- if (content) return content;
81
- const plan = planFromCompletionDetails(result.details);
82
- return plan ? `**Proposed Plan**\n\n${plan}` : "";
72
+ const content = result.content
73
+ .filter((block) => block.type === "text" && typeof block.text === "string")
74
+ .map((block) => block.text)
75
+ .join("\n")
76
+ .trim();
77
+ if (content) return content;
78
+ const plan = planFromCompletionDetails(result.details);
79
+ return plan ? `**Proposed Plan**\n\n${plan}` : "";
83
80
  }
84
81
 
85
82
  export function renderPlanModeCompletion(result: PlanModeCompletionRenderResult) {
86
- return new Markdown(planModeCompletionMarkdown(result), 0, 0, getMarkdownTheme());
83
+ return new Markdown(planModeCompletionMarkdown(result), 0, 0, getMarkdownTheme());
87
84
  }
88
85
 
89
86
  function isRecord(value: unknown): value is Record<string, unknown> {
90
- return typeof value === "object" && value !== null && !Array.isArray(value);
87
+ return typeof value === "object" && value !== null && !Array.isArray(value);
91
88
  }
@@ -1,7 +1,7 @@
1
1
  export function isStaleExtensionContextError(error: unknown) {
2
- return (
3
- error instanceof Error &&
4
- (error.message.includes("This extension ctx is stale after session replacement or reload") ||
5
- error.message.includes("Extension context is no longer active"))
6
- );
2
+ return (
3
+ error instanceof Error &&
4
+ (error.message.includes("This extension ctx is stale after session replacement or reload") ||
5
+ error.message.includes("Extension context is no longer active"))
6
+ );
7
7
  }
@@ -1,57 +1,53 @@
1
1
  export const FINALIZE_PLAN_PROMPT =
2
- "Finalize the current implementation plan now. If any material decision remains, use plan_mode_question instead. Otherwise call plan_mode_complete alone as your final action with the complete decision-ready plan.";
2
+ "Finalize the current implementation plan now. If any material decision remains, use plan_mode_question instead. Otherwise call plan_mode_complete alone as your final action with the complete decision-ready plan.";
3
3
 
4
4
  export const RETRY_FINALIZE_PLAN_PROMPT =
5
- "Your previous finalization response did not call plan_mode_question or plan_mode_complete. Both tools are available in the current Plan-mode request. If a material decision remains, call plan_mode_question now. Otherwise call plan_mode_complete alone with the complete decision-ready plan. Do not respond with prose about tool availability.";
5
+ "Your previous finalization response did not call plan_mode_question or plan_mode_complete. Both tools are available in the current Plan-mode request. If a material decision remains, call plan_mode_question now. Otherwise call plan_mode_complete alone with the complete decision-ready plan. Do not respond with prose about tool availability.";
6
6
 
7
7
  export type FinalizationRunOutcome = "normal" | "cancelled" | "error";
8
8
  export type FinalizationSettlementAction = "retry" | "failed" | undefined;
9
9
 
10
10
  interface PendingFinalizationRequest {
11
- workflowGeneration: number;
12
- retryCount: number;
13
- awaitingSettlement: boolean;
11
+ workflowGeneration: number;
12
+ retryCount: number;
13
+ awaitingSettlement: boolean;
14
14
  }
15
15
 
16
16
  export function createFinalizationRequestCoordinator() {
17
- let pending: PendingFinalizationRequest | undefined;
17
+ let pending: PendingFinalizationRequest | undefined;
18
18
 
19
- return {
20
- request(workflowGeneration: number) {
21
- pending = { workflowGeneration, retryCount: 0, awaitingSettlement: false };
22
- },
23
- satisfy() {
24
- pending = undefined;
25
- },
26
- observeRunEnd(workflowGeneration: number, outcome: FinalizationRunOutcome) {
27
- if (!pending || pending.workflowGeneration !== workflowGeneration) return;
28
- if (outcome !== "normal") {
29
- pending = undefined;
30
- return;
31
- }
32
- pending.awaitingSettlement = true;
33
- },
34
- settle(workflowGeneration: number): FinalizationSettlementAction {
35
- if (
36
- !pending ||
37
- pending.workflowGeneration !== workflowGeneration ||
38
- !pending.awaitingSettlement
39
- ) {
40
- return undefined;
41
- }
42
- if (pending.retryCount === 0) {
43
- pending.retryCount = 1;
44
- pending.awaitingSettlement = false;
45
- return "retry";
46
- }
47
- pending = undefined;
48
- return "failed";
49
- },
50
- reset() {
51
- pending = undefined;
52
- },
53
- hasPendingRequest() {
54
- return pending !== undefined;
55
- },
56
- };
19
+ return {
20
+ request(workflowGeneration: number) {
21
+ pending = { workflowGeneration, retryCount: 0, awaitingSettlement: false };
22
+ },
23
+ satisfy() {
24
+ pending = undefined;
25
+ },
26
+ observeRunEnd(workflowGeneration: number, outcome: FinalizationRunOutcome) {
27
+ if (!pending || pending.workflowGeneration !== workflowGeneration) return;
28
+ if (outcome !== "normal") {
29
+ pending = undefined;
30
+ return;
31
+ }
32
+ pending.awaitingSettlement = true;
33
+ },
34
+ settle(workflowGeneration: number): FinalizationSettlementAction {
35
+ if (!pending || pending.workflowGeneration !== workflowGeneration || !pending.awaitingSettlement) {
36
+ return undefined;
37
+ }
38
+ if (pending.retryCount === 0) {
39
+ pending.retryCount = 1;
40
+ pending.awaitingSettlement = false;
41
+ return "retry";
42
+ }
43
+ pending = undefined;
44
+ return "failed";
45
+ },
46
+ reset() {
47
+ pending = undefined;
48
+ },
49
+ hasPendingRequest() {
50
+ return pending !== undefined;
51
+ },
52
+ };
57
53
  }
@@ -1,55 +1,52 @@
1
1
  export interface DeferredFreshHandoffDependencies {
2
- schedule(callback: () => void): unknown;
3
- cancel(handle: unknown): void;
2
+ schedule(callback: () => void): unknown;
3
+ cancel(handle: unknown): void;
4
4
  }
5
5
 
6
6
  export interface DeferredFreshHandoffCoordinator {
7
- schedule(
8
- run: (isCurrent: () => boolean) => Promise<void>,
9
- onError: (error: unknown) => void,
10
- ): void;
11
- cancel(): void;
7
+ schedule(run: (isCurrent: () => boolean) => Promise<void>, onError: (error: unknown) => void): void;
8
+ cancel(): void;
12
9
  }
13
10
 
14
11
  const defaultDependencies: DeferredFreshHandoffDependencies = {
15
- schedule: (callback) => setTimeout(callback, 0),
16
- cancel: (handle) => clearTimeout(handle as ReturnType<typeof setTimeout>),
12
+ schedule: (callback) => setTimeout(callback, 0),
13
+ cancel: (handle) => clearTimeout(handle as ReturnType<typeof setTimeout>),
17
14
  };
18
15
 
19
16
  export function createDeferredFreshHandoffCoordinator(
20
- dependencies: DeferredFreshHandoffDependencies = defaultDependencies,
17
+ dependencies: DeferredFreshHandoffDependencies = defaultDependencies,
21
18
  ): DeferredFreshHandoffCoordinator {
22
- let generation = 0;
23
- let pending: { generation: number; handle: unknown } | undefined;
19
+ let generation = 0;
20
+ let pending: { generation: number; handle: unknown } | undefined;
24
21
 
25
- const cancel = () => {
26
- generation += 1;
27
- if (!pending) return;
28
- dependencies.cancel(pending.handle);
29
- pending = undefined;
30
- };
22
+ const cancel = () => {
23
+ generation += 1;
24
+ if (!pending) return;
25
+ dependencies.cancel(pending.handle);
26
+ pending = undefined;
27
+ };
31
28
 
32
- return {
33
- schedule(run, onError) {
34
- cancel();
35
- const taskGeneration = generation;
36
- const handle = dependencies.schedule(() => {
37
- if (pending?.generation !== taskGeneration || generation !== taskGeneration) return;
38
- pending = undefined;
39
- const isCurrent = () => generation === taskGeneration;
40
- void Promise.resolve()
41
- .then(() => run(isCurrent))
42
- .catch((error: unknown) => {
43
- if (!isCurrent()) return;
44
- try {
45
- onError(error);
46
- } catch {
47
- // Detached error reporting must not create another unhandled rejection.
48
- }
49
- });
50
- });
51
- pending = { generation: taskGeneration, handle };
52
- },
53
- cancel,
54
- };
29
+ return {
30
+ schedule(run, onError) {
31
+ cancel();
32
+ const taskGeneration = generation;
33
+ const handle = dependencies.schedule(() => {
34
+ if (pending?.generation !== taskGeneration || generation !== taskGeneration) return;
35
+ pending = undefined;
36
+ const isCurrent = () => generation === taskGeneration;
37
+ void Promise.resolve()
38
+ .then(() => run(isCurrent))
39
+ .catch((error: unknown) => {
40
+ if (!isCurrent()) return;
41
+ try {
42
+ onError(error);
43
+ } catch {
44
+ // Detached error reporting must not create another unhandled rejection.
45
+ }
46
+ });
47
+ });
48
+ pending = { generation: taskGeneration, handle };
49
+ },
50
+ cancel,
51
+ };
55
52
  }