@narumitw/pi-plan-mode 0.60.0 → 0.60.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@narumitw/pi-plan-mode",
3
- "version": "0.60.0",
3
+ "version": "0.60.2",
4
4
  "description": "Pi extension that adds a Codex-like read-only /plan collaboration mode.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -48,6 +48,6 @@
48
48
  "directory": "packages/pi-plan-mode"
49
49
  },
50
50
  "dependencies": {
51
- "@narumitw/pi-tui-kit": "^0.69.1"
51
+ "@narumitw/pi-tui-kit": "^0.70.0"
52
52
  }
53
53
  }
package/src/plan-mode.ts CHANGED
@@ -9,6 +9,7 @@ import type {
9
9
  InputEvent,
10
10
  InputSource,
11
11
  } from "@earendil-works/pi-coding-agent";
12
+ import type { EditorStatusWidgetState } from "@narumitw/pi-tui-kit/editor-status-widget";
12
13
  import { completePlanArguments } from "./command.js";
13
14
  import {
14
15
  normalizePlanModeCompletion,
@@ -90,6 +91,7 @@ import {
90
91
  type PlanModeWorkflowToolPolicy,
91
92
  restorePlanModeState,
92
93
  } from "./state.js";
94
+ import { createPlanModeStatePersistence } from "./state-persistence.js";
93
95
  import { planModeToolAvailability } from "./tool-availability.js";
94
96
  import {
95
97
  canSelectToolInPlanMode,
@@ -167,6 +169,9 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
167
169
  let workflowOwner: WorkflowMutexOwner | undefined;
168
170
  let currentSession: object | undefined;
169
171
  let currentSessionContext: ExtensionContext | undefined;
172
+ let shutdownStarted = false;
173
+ let shutdownTask: Promise<void> | undefined;
174
+ let widgetState: EditorStatusWidgetState = { collapsed: false };
170
175
  let interactiveUiPromise: Promise<InteractiveUi> | undefined;
171
176
  const loadInteractiveUi = () => {
172
177
  if (dependencies.loadInteractiveUi) return dependencies.loadInteractiveUi();
@@ -204,7 +209,10 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
204
209
  let settingsReloadTimer: ReturnType<typeof setTimeout> | undefined;
205
210
  const implementationRetention = createImplementationRetentionCoordinator();
206
211
  const finalizationRequest = createFinalizationRequestCoordinator();
207
- const persistState = () => pi.appendEntry<PlanModeState>(STATE_ENTRY_TYPE, state);
212
+ const statePersistence = createPlanModeStatePersistence(STATE_ENTRY_TYPE, (snapshot) =>
213
+ pi.appendEntry<PlanModeState>(STATE_ENTRY_TYPE, snapshot),
214
+ );
215
+ const persistState = () => statePersistence.persist(state, currentSessionContext?.sessionManager.getBranch() ?? []);
208
216
  const interaction = createInteractionCoordinator(pi, {
209
217
  getState: () => state,
210
218
  setState: (next) => {
@@ -409,6 +417,11 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
409
417
  "The interactive /plan menu is unavailable in print and JSON modes. Use /plan start or /plan <prompt>.",
410
418
  );
411
419
  }
420
+ // Opening the existing manager restores the summary without changing Plan mode.
421
+ if (ctx.mode === "tui" && widgetState.collapsed) {
422
+ widgetState.collapsed = false;
423
+ updateUi(ctx);
424
+ }
412
425
  if (!state.enabled) {
413
426
  if (state.activeImplementation && ctx.hasUI) {
414
427
  await showActivePlanMenu(ctx);
@@ -515,8 +528,11 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
515
528
  cancelDeferredFreshImplementation();
516
529
  const generation = ++menuGeneration;
517
530
  finalizationRequest.reset();
531
+ widgetState = { collapsed: false };
518
532
  currentSession = ctx.sessionManager;
519
533
  currentSessionContext = ctx;
534
+ shutdownStarted = false;
535
+ shutdownTask = undefined;
520
536
  workflowOwner = undefined;
521
537
  workflowMutex.bindSession(ctx.sessionManager);
522
538
  refreshStateBeforeFirstAgentStart = event.reason === "new";
@@ -532,6 +548,7 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
532
548
  settings = { thinkingLevel: "inherit" };
533
549
  const branch = ctx.sessionManager.getBranch();
534
550
  const restoredState = restorePlanModeState(branch, STATE_ENTRY_TYPE);
551
+ statePersistence.restore(restoredState);
535
552
  restoreModeContractTracking(branch, restoredState);
536
553
  state = { enabled: false, awaitingAction: false };
537
554
  await applyPlanModeSettings(generation, ctx, true);
@@ -588,6 +605,7 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
588
605
  const branch = ctx.sessionManager.getBranch();
589
606
  const restoredState = restorePlanModeState(branch, STATE_ENTRY_TYPE);
590
607
  restoreModeContractTracking(branch, restoredState);
608
+ statePersistence.restore(restoredState);
591
609
  if (!installRestoredState(restoredState, ctx)) return;
592
610
  implementationRetention.restore(state.activeImplementation);
593
611
  startPlanModeSettingsWatch(menuGeneration);
@@ -596,7 +614,7 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
596
614
  });
597
615
 
598
616
  pi.on("thinking_level_select", (event) => {
599
- if (!state.enabled || !state.appliedThinkingLevel) return;
617
+ if (shutdownStarted || !state.enabled || !state.appliedThinkingLevel) return;
600
618
  if (event.level !== state.appliedThinkingLevel) {
601
619
  state = {
602
620
  ...state,
@@ -608,11 +626,17 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
608
626
  }
609
627
  });
610
628
 
611
- pi.on("session_shutdown", async (_event, ctx) => {
629
+ pi.on("session_shutdown", (_event, ctx) => {
612
630
  if (currentSession !== undefined && currentSession !== ctx.sessionManager) {
613
631
  workflowMutex.unbindSession(ctx.sessionManager);
614
632
  return;
615
633
  }
634
+ shutdownTask ??= shutdownPlanModeSession(ctx);
635
+ return shutdownTask;
636
+ });
637
+
638
+ async function shutdownPlanModeSession(ctx: ExtensionContext) {
639
+ shutdownStarted = true;
616
640
  interaction.disposeSession();
617
641
  invalidateReadyMenu();
618
642
  cancelDeferredFreshImplementation();
@@ -635,7 +659,7 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
635
659
  );
636
660
  }
637
661
  finalizationRequest.reset();
638
- menuGeneration += 1;
662
+ const shutdownGeneration = ++menuGeneration;
639
663
  menuController.abort(new DOMException("Plan-mode session shut down", "AbortError"));
640
664
  readyPresentationIntent = undefined;
641
665
  latestCommandContext = undefined;
@@ -645,28 +669,37 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
645
669
  workflowAllowedToolNames = undefined;
646
670
  pendingWorkflowToolPolicy = undefined;
647
671
  implementationRetention.reset();
672
+ const shutdownIsCurrent = () =>
673
+ shutdownGeneration === menuGeneration && (currentSession === undefined || currentSession === shutdownSession);
648
674
  if (runtimeApplication) await runtimeApplication.completion;
649
- if (currentSession !== undefined && currentSession !== shutdownSession) {
650
- workflowMutex.unbindSession(shutdownSession);
675
+ if (!shutdownIsCurrent()) {
676
+ if (currentSession !== shutdownSession) workflowMutex.unbindSession(shutdownSession);
651
677
  return;
652
678
  }
653
679
  await awaitPlanModeSettingsWrites(dependencies.settingsPath);
654
- if (currentSession !== undefined && currentSession !== shutdownSession) {
655
- workflowMutex.unbindSession(shutdownSession);
680
+ if (!shutdownIsCurrent()) {
681
+ if (currentSession !== shutdownSession) workflowMutex.unbindSession(shutdownSession);
656
682
  return;
657
683
  }
658
- captureManualThinkingLevel();
659
- persistState();
660
- if (state.enabled) restoreThinkingLevel();
661
- stopPlanModeSettingsWatch();
662
- clearUi(ctx);
663
- releaseWorkflowOwner();
664
- workflowMutex.unbindSession(ctx.sessionManager);
665
- if (currentSession === ctx.sessionManager) {
666
- currentSession = undefined;
667
- currentSessionContext = undefined;
684
+ try {
685
+ captureManualThinkingLevel();
686
+ persistState();
687
+ } finally {
688
+ try {
689
+ if (state.enabled) restoreThinkingLevel();
690
+ } finally {
691
+ stopPlanModeSettingsWatch();
692
+ clearUi(ctx);
693
+ releaseWorkflowOwner();
694
+ workflowMutex.unbindSession(ctx.sessionManager);
695
+ if (currentSession === ctx.sessionManager) {
696
+ currentSession = undefined;
697
+ currentSessionContext = undefined;
698
+ widgetState = { collapsed: false };
699
+ }
700
+ }
668
701
  }
669
- });
702
+ }
670
703
 
671
704
  pi.on("tool_call", async (event, ctx) => {
672
705
  const requiredHelper =
@@ -1761,6 +1794,7 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
1761
1794
  implementationRetention.reset();
1762
1795
  const branch = ctx.sessionManager.getBranch();
1763
1796
  const restoredState = restorePlanModeState(branch, STATE_ENTRY_TYPE);
1797
+ statePersistence.restore(restoredState);
1764
1798
  restoreModeContractTracking(branch, restoredState);
1765
1799
  if (!installRestoredState(restoredState, ctx)) return;
1766
1800
  implementationRetention.restore(state.activeImplementation);
@@ -2065,6 +2099,7 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
2065
2099
 
2066
2100
  function bindWorkflowSessionIfNeeded(ctx: ExtensionContext) {
2067
2101
  if (currentSession === ctx.sessionManager) return;
2102
+ widgetState = { collapsed: false };
2068
2103
  currentSession = ctx.sessionManager;
2069
2104
  workflowOwner = undefined;
2070
2105
  workflowMutex.bindSession(ctx.sessionManager);
@@ -2108,7 +2143,7 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
2108
2143
  }
2109
2144
 
2110
2145
  function updateUi(ctx: ExtensionContext) {
2111
- updatePlanModeUi(ctx, state, formatToolSummary, interaction.shortcutLabel(ctx));
2146
+ updatePlanModeUi(ctx, state, formatToolSummary, interaction.shortcutLabel(ctx), widgetState);
2112
2147
  }
2113
2148
 
2114
2149
  function clearUi(ctx: ExtensionContext) {
@@ -1,55 +1,85 @@
1
1
  import type { ExtensionAPI, ExtensionContext, Theme } from "@earendil-works/pi-coding-agent";
2
2
  import { stripTerminalSequences } from "@earendil-works/pi-tui";
3
- import { EditorStatusWidget } from "@narumitw/pi-tui-kit/editor-status-widget";
3
+ import { EditorStatusWidget, type EditorStatusWidgetState } from "@narumitw/pi-tui-kit/editor-status-widget";
4
4
  import type { PlanModeState } from "./state.js";
5
5
 
6
6
  const STATUS_KEY = "plan-mode";
7
7
  const PLAN_WIDGET_KEY = "plan-mode-plan";
8
8
  const BIDI_CONTROLS = /[\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/gu;
9
9
 
10
+ interface PlanModeWidgetPresentation {
11
+ summary: string;
12
+ body: readonly string[];
13
+ fallback: readonly string[];
14
+ }
15
+
10
16
  export function updatePlanModeUi(
11
17
  ctx: ExtensionContext,
12
18
  state: PlanModeState,
13
19
  toolSummary: () => string,
14
20
  interactionShortcut?: string,
21
+ widgetState?: EditorStatusWidgetState,
15
22
  ) {
16
23
  ctx.ui.setStatus(STATUS_KEY, formatStatus(state));
17
24
  const discussion = state.interactionMode === "discussion";
18
25
  const interactionHint = formatInteractionHint(state, ctx.mode === "tui" ? interactionShortcut : undefined);
19
- let lines: string[] | undefined;
26
+ let presentation: PlanModeWidgetPresentation | undefined;
20
27
  if (state.enabled && state.latestPlan) {
21
- lines = [
22
- "Proposed plan ready",
23
- ...(discussion ? ["Plan mode: free discussion"] : []),
24
- "Use /plan to implement, save, revise, or exit Plan mode.",
25
- interactionHint,
26
- ];
28
+ const actions = "Use /plan to implement, save, revise, or exit Plan mode.";
29
+ presentation = {
30
+ summary: discussion ? "Ready · Free discussion" : "Ready",
31
+ body: ["File edits remain blocked.", actions, interactionHint],
32
+ fallback: [
33
+ "Proposed plan ready",
34
+ ...(discussion ? ["Plan mode: free discussion"] : []),
35
+ actions,
36
+ interactionHint,
37
+ ],
38
+ };
27
39
  } else if (state.enabled) {
28
- lines = [
29
- discussion ? "Plan mode: free discussion" : "Plan mode: planning",
30
- toolSummary(),
31
- discussion
32
- ? "Plain-text questions are allowed; questionnaires are paused."
33
- : "Finish with plan_mode_complete when decision-ready.",
34
- interactionHint,
35
- ];
40
+ const tools = toolSummary();
41
+ const discussionHint = "Plain-text questions are allowed; questionnaires are paused.";
42
+ presentation = {
43
+ summary: discussion ? "Free discussion" : "Planning",
44
+ body: ["File edits remain blocked.", tools, ...(discussion ? [discussionHint] : []), interactionHint],
45
+ fallback: [
46
+ discussion ? "Plan mode: free discussion" : "Plan mode: planning",
47
+ tools,
48
+ discussion ? discussionHint : "Finish with plan_mode_complete when decision-ready.",
49
+ interactionHint,
50
+ ],
51
+ };
36
52
  } else if (state.savedPlan) {
37
- lines = ["Plan saved for later", "Use /plan to show, implement, or clear it."];
53
+ const actions = "Use /plan to show, implement, or clear it.";
54
+ presentation = { summary: "Saved", body: [actions], fallback: ["Plan saved for later", actions] };
38
55
  } else if (state.activeImplementation) {
39
- lines = ["Implementation plan active", "Use /plan to show, replace, or clear it."];
56
+ const actions = "Use /plan to show, replace, or clear it.";
57
+ presentation = {
58
+ summary: "Implementation active",
59
+ body: [actions],
60
+ fallback: ["Implementation plan active", actions],
61
+ };
40
62
  }
41
63
 
42
- publishPlanModeWidget(ctx, lines);
64
+ publishPlanModeWidget(ctx, presentation, widgetState);
43
65
  }
44
66
 
45
67
  export function renderPlanModeWidget(lines: readonly string[], theme: Theme, width: number): string[] {
46
68
  return createPlanModeWidget(lines, theme).render(width);
47
69
  }
48
70
 
49
- function createPlanModeWidget(lines: readonly string[], theme: Theme): EditorStatusWidget {
71
+ function createPlanModeWidget(
72
+ lines: readonly string[],
73
+ theme: Theme,
74
+ state?: EditorStatusWidgetState,
75
+ summary?: string,
76
+ ): EditorStatusWidget {
50
77
  // Kit normalizes fractional and invalid widths before clipping sanitized body rows.
51
78
  return new EditorStatusWidget({
52
79
  theme,
80
+ name: "Plan mode",
81
+ summary,
82
+ state,
53
83
  renderBody: () =>
54
84
  lines.map((line, index) => {
55
85
  const text = sanitizePlanModeWidgetLine(line);
@@ -119,18 +149,24 @@ export function planModeStatusText(state: PlanModeState, toolSummary: () => stri
119
149
  return "Plan mode is off.";
120
150
  }
121
151
 
122
- function publishPlanModeWidget(ctx: ExtensionContext, lines: readonly string[] | undefined) {
123
- if (!lines) {
152
+ function publishPlanModeWidget(
153
+ ctx: ExtensionContext,
154
+ presentation: PlanModeWidgetPresentation | undefined,
155
+ widgetState?: EditorStatusWidgetState,
156
+ ) {
157
+ if (!presentation) {
124
158
  ctx.ui.setWidget(PLAN_WIDGET_KEY, undefined);
125
159
  return;
126
160
  }
127
161
  if (ctx.mode !== "tui") {
128
- ctx.ui.setWidget(PLAN_WIDGET_KEY, [...lines]);
162
+ ctx.ui.setWidget(PLAN_WIDGET_KEY, [...presentation.fallback]);
129
163
  return;
130
164
  }
131
165
 
132
- const snapshot = [...lines];
133
- ctx.ui.setWidget(PLAN_WIDGET_KEY, (_tui, theme) => createPlanModeWidget(snapshot, theme));
166
+ const snapshot = [...presentation.body];
167
+ ctx.ui.setWidget(PLAN_WIDGET_KEY, (_tui, theme) =>
168
+ createPlanModeWidget(snapshot, theme, widgetState, presentation.summary),
169
+ );
134
170
  }
135
171
 
136
172
  function formatInteractionHint(state: PlanModeState, interactionShortcut?: string) {
@@ -0,0 +1,34 @@
1
+ import { isDeepStrictEqual } from "node:util";
2
+ import { type PlanModeState, restorePlanModeState } from "./state.js";
3
+
4
+ export function createPlanModeStatePersistence(stateEntryType: string, append: (state: PlanModeState) => void) {
5
+ let persisted = JSON.stringify({ enabled: false, awaitingAction: false });
6
+ let appendFailed = false;
7
+
8
+ return {
9
+ restore(state: PlanModeState) {
10
+ persisted = JSON.stringify(state);
11
+ appendFailed = false;
12
+ },
13
+ persist(state: PlanModeState, branch: unknown[]) {
14
+ const serialized = JSON.stringify(state);
15
+ // Detach the append payload from runtime state. Pi retains this object in memory.
16
+ const payload = JSON.parse(serialized) as PlanModeState;
17
+ if (!appendFailed && isDeepStrictEqual(payload, JSON.parse(persisted))) {
18
+ // A repeated no-plan entry can still be needed to stop recovery from a later tool result.
19
+ const clearsRecoveredPlan =
20
+ state.enabled && !state.latestPlan && restorePlanModeState(branch, stateEntryType).latestPlan !== undefined;
21
+ if (!clearsRecoveredPlan) return;
22
+ }
23
+ try {
24
+ append(payload);
25
+ } catch (error: unknown) {
26
+ // A failed append can leave the in-memory branch uncertain. Let rollback repair it.
27
+ appendFailed = true;
28
+ throw error;
29
+ }
30
+ persisted = serialized;
31
+ appendFailed = false;
32
+ },
33
+ };
34
+ }