pi-bro 0.30.0 → 0.32.0

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/src/btw.ts CHANGED
@@ -349,7 +349,7 @@ export class BtwModal implements Focusable {
349
349
 
350
350
  export async function openBtwModal(
351
351
  ctx: ExtensionCommandContext,
352
- options: { thread: BtwThread; initialQuestion?: string },
352
+ options: { thread: BtwThread; initialQuestion?: string; onChange?: () => void },
353
353
  ): Promise<void> {
354
354
  const thread = options.thread;
355
355
 
@@ -358,6 +358,25 @@ export async function openBtwModal(
358
358
  (tui, theme, _keybindings, done) => {
359
359
  let closed = false;
360
360
  let controller: AbortController | undefined;
361
+ let activeTurn: { pending?: BtwTurn; original?: BtwTurn } | undefined;
362
+ // Discard an unfinished reply immediately on close, before another modal can
363
+ // reuse the same thread. A cancelled retry restores the completed old turn.
364
+ const discardUnfinished = () => {
365
+ const work = activeTurn;
366
+ if (!work) return;
367
+ let position = thread.turns.length;
368
+ if (work.pending) {
369
+ const index = thread.turns.indexOf(work.pending);
370
+ if (index >= 0) {
371
+ position = index;
372
+ thread.turns.splice(index, 1);
373
+ }
374
+ }
375
+ if (work.original && !thread.turns.includes(work.original)) {
376
+ thread.turns.splice(position, 0, work.original);
377
+ }
378
+ activeTurn = undefined;
379
+ };
361
380
 
362
381
  const transcript = () => formatBtwTranscript(thread.turns);
363
382
 
@@ -376,13 +395,18 @@ export async function openBtwModal(
376
395
  closed = true;
377
396
  saveDraft();
378
397
  controller?.abort();
398
+ discardUnfinished();
399
+ options.onChange?.();
379
400
  done(undefined);
380
401
  };
381
402
 
382
403
  const modal = new BtwModal(tui, theme, close, submit, () => {
404
+ if (closed) return; // Close already saved and cleaned this thread.
383
405
  closed = true;
384
406
  saveDraft();
385
407
  controller?.abort();
408
+ discardUnfinished();
409
+ options.onChange?.();
386
410
  });
387
411
  modal.onInput = () => {
388
412
  composerTouched = true;
@@ -393,6 +417,8 @@ export async function openBtwModal(
393
417
  const runTurn = async (question: string, replaced?: BtwTurn) => {
394
418
  if (controller) return;
395
419
  const turnController = new AbortController();
420
+ const work: { pending?: BtwTurn; original?: BtwTurn } = { original: replaced };
421
+ activeTurn = work;
396
422
  controller = turnController;
397
423
  modal.setRunning(true);
398
424
 
@@ -402,20 +428,22 @@ export async function openBtwModal(
402
428
  settings = await readSettings();
403
429
  preferences = await readPreferences();
404
430
  } catch (error) {
405
- if (replaced) thread.turns.push(replaced);
406
- if (!replaced && !options.initialQuestion) modal.setComposerText(question);
431
+ if (activeTurn === work) discardUnfinished();
432
+ if (!closed && !replaced && !options.initialQuestion) modal.setComposerText(question);
407
433
  if (controller === turnController) controller = undefined;
408
- if (!closed) { modal.setRunning(false); modal.setNotice(errorMessage(error), "error"); }
434
+ if (!closed) { modal.setRunning(false); modal.setNotice(errorMessage(error), "error"); options.onChange?.(); }
409
435
  return;
410
436
  }
411
- // Closing (or reopening) during the reads above must not touch the shared thread.
437
+ // Do not restore a cancelled retry twice after close/dispose.
412
438
  if (closed || turnController.signal.aborted) {
413
- if (replaced) thread.turns.push(replaced);
414
- if (!replaced && !options.initialQuestion) modal.setComposerText(question);
439
+ if (activeTurn === work) discardUnfinished();
415
440
  if (controller === turnController) controller = undefined;
416
441
  return;
417
442
  }
418
- if (bindBtwBackend(thread, capabilityBackend(settings, "btw"))) modal.setNotice("Backend changed — started a fresh side thread.", "warning");
443
+ if (bindBtwBackend(thread, capabilityBackend(settings, "btw"))) {
444
+ work.original = undefined; // An old-backend retry must not recreate discarded history.
445
+ modal.setNotice("Backend changed — started a fresh side thread.", "warning");
446
+ }
419
447
  if (thread.turns.length === 0) {
420
448
  thread.conversationId = undefined;
421
449
  const context = captureShowTranscript(ctx, BTW_CONTEXT_TURNS, BTW_CONTEXT_MAX)?.text;
@@ -428,7 +456,9 @@ export async function openBtwModal(
428
456
  const context = conversationId ? undefined : thread.context;
429
457
  const full = thread.full;
430
458
 
431
- thread.turns.push({ question, answer: "…" });
459
+ const pending = { question, answer: "…" };
460
+ work.pending = pending;
461
+ thread.turns.push(pending);
432
462
  modal.setText(transcript());
433
463
  modal.scrollToEnd();
434
464
 
@@ -444,11 +474,11 @@ export async function openBtwModal(
444
474
  turnController.signal,
445
475
  (partial) => {
446
476
  if (closed || turnController.signal.aborted) return;
447
- thread.turns[thread.turns.length - 1]!.answer = partial;
477
+ pending.answer = partial;
448
478
  modal.setText(transcript());
449
479
  },
450
480
  );
451
- if (turnController.signal.aborted) return;
481
+ if (closed || turnController.signal.aborted) return;
452
482
  if (result.expiredContinuation) {
453
483
  // The native session is gone. Drop the dead id, rebuild the prompt from this thread's own
454
484
  // transcript AND its captured main-session context (the local `context` is undefined
@@ -462,7 +492,7 @@ export async function openBtwModal(
462
492
  turnController.signal,
463
493
  (partial) => {
464
494
  if (closed || turnController.signal.aborted) return;
465
- thread.turns[thread.turns.length - 1]!.answer = partial;
495
+ pending.answer = partial;
466
496
  modal.setText(transcript());
467
497
  },
468
498
  );
@@ -473,16 +503,21 @@ export async function openBtwModal(
473
503
  thread.sessionFull = full;
474
504
  thread.sessionPreferences = preferences;
475
505
  }
476
- thread.turns[thread.turns.length - 1]!.answer = result.text;
506
+ pending.answer = result.text;
477
507
  } catch (error) {
478
508
  if (turnController.signal.aborted || closed) return;
479
- thread.turns[thread.turns.length - 1]!.answer = `_${errorMessage(error)}_`;
509
+ pending.answer = `_${errorMessage(error)}_`;
480
510
  modal.setNotice(errorMessage(error), "error");
481
511
  } finally {
482
512
  if (controller === turnController) controller = undefined;
513
+ if (activeTurn === work) {
514
+ if (closed || turnController.signal.aborted) discardUnfinished();
515
+ else activeTurn = undefined;
516
+ }
483
517
  if (!closed) {
484
518
  modal.setRunning(false);
485
519
  modal.setText(transcript());
520
+ options.onChange?.();
486
521
  }
487
522
  }
488
523
  };
@@ -491,6 +526,7 @@ export async function openBtwModal(
491
526
  toggleBtwMode(thread);
492
527
  modal.setFull(thread.full);
493
528
  modal.setNotice(`Mode: ${btwModeLabel(thread.full)}`, "info");
529
+ options.onChange?.();
494
530
  };
495
531
 
496
532
  const clear = () => {
@@ -503,6 +539,7 @@ export async function openBtwModal(
503
539
  modal.clearComposer();
504
540
  modal.setNotice("");
505
541
  modal.setText("");
542
+ options.onChange?.();
506
543
  };
507
544
 
508
545
  const retry = () => {
@@ -11,10 +11,14 @@ import {
11
11
  } from "./config-navigation.ts";
12
12
 
13
13
  type MenuItem = {value:string;label:string};
14
- const rowsFor=(screen:ConfigNavScreen):readonly MenuItem[]=>{
14
+ const rowsFor=(screen:ConfigNavScreen, automatic:boolean):readonly MenuItem[]=>{
15
15
  if(screen==="root")return CONFIG_ROOT;
16
16
  if(screen==="global")return CONFIG_GLOBAL;
17
17
  if(screen==="features")return CONFIG_FEATURES;
18
+ if(screen==="overthink")return [
19
+ {value:"overthink-defaults",label:"Default questions — edit starting set"},
20
+ {value:"overthink-toggle",label:"Automatic checks — "+(automatic?"On":"Off")+" (Enter to toggle)"},
21
+ ];
18
22
  if(screen==="advisor")return [
19
23
  {value:"advisor-settings",label:"Backend, model and effort"},
20
24
  {value:"advisor-steer",label:"Persistent advisor steering brief"},
@@ -25,6 +29,7 @@ const rowsFor=(screen:ConfigNavScreen):readonly MenuItem[]=>{
25
29
  export function createConfigNavigationModal(
26
30
  state:ConfigNavState,
27
31
  settings:BroSettings,
32
+ automatic = true,
28
33
  ): (tui:TuiLike,theme:Theme,keys:unknown,done:(result:ConfigNavAction)=>void)=>Component {
29
34
  return (tui,theme,_keys,done)=>{
30
35
  let closed=false;
@@ -33,7 +38,7 @@ export function createConfigNavigationModal(
33
38
  const finish=(result:ConfigNavAction)=>{if(closed)return;closed=true;done(result);};
34
39
  const go=(screen:ConfigNavScreen)=>{
35
40
  state.screen=screen;
36
- const items=rowsFor(screen) as SelectItem[];
41
+ const items=rowsFor(screen, automatic) as SelectItem[];
37
42
  list=new SelectList(items,Math.min(items.length,Math.max(1,modalHeight(tui)-10)),getSelectListTheme());
38
43
  list.onSelect=item=>choose(item.value);
39
44
  list.onCancel=back;
@@ -53,11 +58,16 @@ export function createConfigNavigationModal(
53
58
  }
54
59
  if(state.screen==="features"){
55
60
  if(value==="advisor"){go("advisor");return;}
61
+ if(value==="overthink"){go("overthink");return;}
56
62
  if(value==="elevate"||value==="grill-me"||value==="remember-me"||value==="architecture"){
57
63
  state.inherited=value;go("inherited");return;
58
64
  }
59
65
  if(value==="explain"||value==="show"||value==="btw"||value==="review")return finish({kind:"settings",page:value});
60
66
  }
67
+ if(state.screen==="overthink"){
68
+ if(value==="overthink-defaults")return finish({kind:"overthink-defaults"});
69
+ if(value==="overthink-toggle")return finish({kind:"overthink-toggle"});
70
+ }
61
71
  if(state.screen==="advisor"){
62
72
  if(value==="advisor-steer")return finish({kind:"advisor-steer"});
63
73
  if(value==="advisor-settings")return finish({kind:"settings",page:"advisor"});
@@ -73,6 +83,7 @@ export function createConfigNavigationModal(
73
83
  s==="global"?"Bro · config / Global":
74
84
  s==="features"?"Bro · config / Features":
75
85
  s==="advisor"?"Bro · config / Features / Advisor":
86
+ s==="overthink"?"Bro · config / Features / Overthink":
76
87
  "Bro · config / Features / "+(state.inherited??"Inherited");
77
88
  };
78
89
  const subtitle=()=>{
@@ -80,6 +91,7 @@ export function createConfigNavigationModal(
80
91
  if(state.screen==="global")return "Defaults are shared. Doctor runs only when selected.";
81
92
  if(state.screen==="features")return "Feature model overrides are optional; inherited features use BTW.";
82
93
  if(state.screen==="advisor")return "Steering keeps its own file; changing models does not change steering.";
94
+ if(state.screen==="overthink")return "Automatic checks use the active Pi model. No backend override.";
83
95
  if(state.inherited)return inheritedConfigDescription(settings,state.inherited);
84
96
  return "Inherits BTW";
85
97
  };
@@ -4,11 +4,11 @@ import { capabilityBackend, capabilityOverride, capabilityPair } from "./setting
4
4
  import { reviewBackendNotice } from "./backend.ts";
5
5
 
6
6
  export type ConfigSettingsPage = "defaults" | Capability;
7
- export type ConfigNavScreen = "root" | "global" | "features" | "advisor" | "inherited";
7
+ export type ConfigNavScreen = "root" | "global" | "features" | "advisor" | "inherited" | "overthink";
8
8
  export type ConfigNavState = { screen: ConfigNavScreen; inherited?: "elevate"|"grill-me"|"remember-me"|"architecture" };
9
9
  export type ConfigNavAction =
10
10
  | {kind:"settings";page:ConfigSettingsPage}
11
- | {kind:"preferences"|"doctor"|"advisor-steer"|"close"};
11
+ | {kind:"preferences"|"doctor"|"advisor-steer"|"overthink-defaults"|"overthink-toggle"|"close"};
12
12
 
13
13
  export const CONFIG_ROOT = [
14
14
  {value:"global",label:"Global — shared defaults, preferences and Doctor"},
@@ -28,6 +28,7 @@ export const CONFIG_FEATURES = [
28
28
  {value:"elevate",label:"Elevate — inherits BTW"},
29
29
  {value:"grill-me",label:"Grill Me — inherits BTW"},
30
30
  {value:"remember-me",label:"Remember Me — inherits BTW"},
31
+ {value:"overthink",label:"Overthink — automatic checks and default questions"},
31
32
  {value:"architecture",label:"Architecture Docs — inherits BTW"},
32
33
  ] as const;
33
34
 
package/src/doctor.ts CHANGED
@@ -22,6 +22,8 @@ import { createConfigNavigationModal } from "./config-navigation-ui.ts";
22
22
  import { type ConfigNavAction, type ConfigNavState } from "./config-navigation.ts";
23
23
  import { showBroModal, showPreferencesModal, showAdvisorSteerModal } from "./explain-modal.ts";
24
24
  import { openBroOverlay } from "./modal-kit.ts";
25
+ import { openOverthinkDefaults } from "./overthink.ts";
26
+ import { readAutomaticChecks, writeAutomaticChecks } from "./overthink-state.ts";
25
27
  import {
26
28
  type AgyEffort,
27
29
  type AgyModelFamily,
@@ -661,8 +663,11 @@ export async function showBroConfigModal(ctx: ExtensionCommandContext, pi: Exten
661
663
  ctx.ui.notify("Settings unavailable: "+errorMessage(error)+". Global > Doctor can diagnose.", "warning");
662
664
  current = { backend:"agy",model:"(unavailable)",effort:"default",mode:"balanced",showTurns:1,overrides:{} };
663
665
  }
666
+ let automatic = true;
667
+ try { automatic = await readAutomaticChecks(); }
668
+ catch (error) { ctx.ui.notify("Overthink automatic setting: " + errorMessage(error), "warning"); }
664
669
  const selected = await openBroOverlay<ConfigNavAction>(
665
- ctx, createConfigNavigationModal(navigation,current), {mouse:true}
670
+ ctx, createConfigNavigationModal(navigation,current,automatic), {mouse:true}
666
671
  );
667
672
  if (!selected || selected.kind === "close") return;
668
673
  if (selected.kind === "preferences") {
@@ -673,6 +678,19 @@ export async function showBroConfigModal(ctx: ExtensionCommandContext, pi: Exten
673
678
  await showAdvisorSteerModal(ctx,pi);
674
679
  continue;
675
680
  }
681
+ if (selected.kind === "overthink-toggle") {
682
+ try {
683
+ const next = !(await readAutomaticChecks());
684
+ await writeAutomaticChecks(next);
685
+ ctx.ui.notify("Overthink automatic checks: " + (next ? "On" : "Off"), "info");
686
+ } catch (error) { ctx.ui.notify("Overthink automatic checks: " + errorMessage(error), "error"); }
687
+ continue;
688
+ }
689
+ if (selected.kind === "overthink-defaults") {
690
+ try { await openOverthinkDefaults(ctx); }
691
+ catch (error) { ctx.ui.notify("Overthink defaults: " + errorMessage(error), "error"); }
692
+ continue;
693
+ }
676
694
  if (selected.kind === "doctor") {
677
695
  await showBroModal(ctx,{
678
696
  loadingText:"Checking Bro setup…",
@@ -414,6 +414,11 @@ Quick reference. Full user guide: https://github.com/tranhoangnguyen03/pi-bro/bl
414
414
 
415
415
  - \`/bro grill-me [topic]\` — private decision interview. Use /consolidate, /insert-last-message or /help. Full-access risk: docs/grill-me.md.
416
416
 
417
+ ## Overthink
418
+
419
+ - \`/bro overthink\` — view private automatic second-look notes without running a model. Ctrl+R forces retry; Ctrl+E edits this session's questions; ? shows help; Ctrl+C copies. Uses the active Pi model and thinking level only. No separate backend settings.
420
+ - \`/bro config\` → Features → Overthink provides automatic on/off and editable global starting questions; session edits stay with their Pi session. See docs/overthink.md.
421
+
417
422
  ## Side conversation
418
423
 
419
424
  - \`/bro btw [question]\` — open a side conversation seeded with recent main-session context. It starts conversation-only; reopening keeps the thread and its mode.
@@ -429,7 +434,7 @@ Quick reference. Full user guide: https://github.com/tranhoangnguyen03/pi-bro/bl
429
434
  ## Configure and check
430
435
 
431
436
  - \`/bro preferences\` — tell Bro about yourself and how you like answers; added to explain, show, btw, Elevate and Guided Review prompts, never the advisor (**Ctrl+S** save, **Ctrl+K** delete, **Ctrl+C** copy, **Esc** close)
432
- - \`/bro config\` — Global (shared defaults, preferences, Doctor) and Features (Simplify, Show, BTW, Review, Advisor and BTW-inherited workflows). The same model pickers, safe saves and error handling remain; Esc backs out.
437
+ - \`/bro config\` — Global (shared defaults, preferences, Doctor) and Features (Simplify, Show, BTW, Review, Advisor, Overthink defaults and BTW-inherited workflows). The same model pickers, safe saves and error handling remain; Esc backs out.
433
438
  - \`/bro mode [brief|balanced|faithful]\` — view or choose the explanation mode
434
439
  - \`/bro doctor\` — check settings, preferences, and every selected backend without running a model turn
435
440
 
package/src/grill.ts CHANGED
@@ -20,7 +20,7 @@ import { errorMessage } from "./util.ts";
20
20
  export async function openGrillModal(
21
21
  ctx: ExtensionCommandContext,
22
22
  thread: GrillThread,
23
- options: { start?: boolean } = {},
23
+ options: { start?: boolean; onChange?: () => void } = {},
24
24
  ): Promise<void> {
25
25
  const openingBackend = capabilityBackend(await readSettings(), "btw");
26
26
  await openBroOverlay<void>(
@@ -55,12 +55,14 @@ export async function openGrillModal(
55
55
  if (closed) return;
56
56
  closed = true;
57
57
  saveDraft();
58
+ if (!controller) options.onChange?.();
58
59
  controller?.abort();
59
60
  done(undefined);
60
61
  };
61
62
  const modal = new BtwModal(tui, theme, close, submit, () => {
62
63
  closed = true;
63
64
  saveDraft();
65
+ if (!controller) options.onChange?.();
64
66
  controller?.abort();
65
67
  }, {
66
68
  title: "Bro · grill-me",
@@ -153,7 +155,7 @@ export async function openGrillModal(
153
155
  pendingTurn = undefined;
154
156
  pendingReply = undefined;
155
157
  if (controller === attempt) controller = undefined;
156
- if (!closed) { modal.setRunning(false); modal.setText(transcript()); }
158
+ if (!closed) { modal.setRunning(false); modal.setText(transcript()); options.onChange?.(); }
157
159
  }
158
160
  };
159
161
 
@@ -197,7 +199,7 @@ export async function openGrillModal(
197
199
  } finally {
198
200
  pendingSummary = undefined;
199
201
  if (controller === attempt) controller = undefined;
200
- if (!closed) { modal.setRunning(false); modal.setText(transcript()); }
202
+ if (!closed) { modal.setRunning(false); modal.setText(transcript()); options.onChange?.(); }
201
203
  }
202
204
  };
203
205
 
@@ -225,6 +227,7 @@ export async function openGrillModal(
225
227
  delete thread.draft;
226
228
  modal.clearComposer();
227
229
  modal.setText(transcript());
230
+ options.onChange?.();
228
231
  void runTurn(topic);
229
232
  };
230
233
 
@@ -241,6 +244,7 @@ export async function openGrillModal(
241
244
  thread.fullAccess = true;
242
245
  refreshHeader();
243
246
  modal.setNotice(permissionNotice(activeBackend), "warning");
247
+ options.onChange?.();
244
248
  } else clear(pending.slice(4));
245
249
  return;
246
250
  }
@@ -252,6 +256,7 @@ export async function openGrillModal(
252
256
  refreshHeader();
253
257
  modal.clearComposer();
254
258
  modal.setNotice(`Depth: ${thread.depth}. Applies to the next question.`);
259
+ options.onChange?.();
255
260
  return;
256
261
  }
257
262
  if (action.kind === "access") {
@@ -263,6 +268,7 @@ export async function openGrillModal(
263
268
  thread.fullAccess = action.value === "full";
264
269
  refreshHeader();
265
270
  modal.setNotice(permissionNotice(activeBackend));
271
+ options.onChange?.();
266
272
  }
267
273
  return;
268
274
  }
package/src/modal-kit.ts CHANGED
@@ -118,10 +118,13 @@ export class Scroller {
118
118
  private follow = false;
119
119
 
120
120
  /** `followEnd`: scrolling to the end pins the view to new text until the reader scrolls up. */
121
- constructor(
122
- private readonly onScroll: () => void,
123
- private readonly options: { followEnd?: boolean } = {},
124
- ) {}
121
+ private readonly onScroll: () => void;
122
+ private readonly options: { followEnd?: boolean };
123
+
124
+ constructor(onScroll: () => void, options: { followEnd?: boolean } = {}) {
125
+ this.onScroll = onScroll;
126
+ this.options = options;
127
+ }
125
128
 
126
129
  view(lines: string[], rows: number): string[] {
127
130
  this.rows = Math.max(1, rows);
@@ -0,0 +1,131 @@
1
+ /** One question list editor for global defaults and session snapshots. */
2
+ import { Input, matchesKey, truncateToWidth, type Component, type TUI } from "@earendil-works/pi-tui";
3
+ import { modalHeight, openBroOverlay, renderFrame, Scroller, formatNotice, type Theme } from "./modal-kit.ts";
4
+ import type { ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
5
+ import { checkQuestions, MAX_OVERTHINK_QUESTIONS, MAX_OVERTHINK_QUESTION_CHARS } from "./overthink-state.ts";
6
+ import { errorMessage } from "./util.ts";
7
+
8
+ type EditorOptions = {
9
+ title: string; questions: string[]; reset: () => Promise<string[]>;
10
+ save: (questions: string[]) => Promise<void> | void;
11
+ };
12
+
13
+ export function createOverthinkQuestionEditor(options: EditorOptions) {
14
+ return (tui: TUI, theme: Theme, _keys: unknown, done: (value?: void) => void): Component => {
15
+ let questions = [...options.questions];
16
+ let saved = JSON.stringify(questions);
17
+ let cursor = 0;
18
+ let mode: "list" | "edit" = "list";
19
+ let input = new Input();
20
+ let editingIndex = -1;
21
+ let pending = false;
22
+ let closed = false;
23
+ let resetArmed = false;
24
+ let discardArmed = false;
25
+ let notice = "";
26
+ const scroller = new Scroller(() => tui.requestRender());
27
+ const dirty = () => JSON.stringify(questions) !== saved;
28
+ const warn = (message: string, tone: "info" | "success" | "error" | "warning" = "info") => {
29
+ notice = formatNotice(theme, message, tone); tui.requestRender();
30
+ };
31
+ const beginEdit = (index: number) => {
32
+ mode = "edit"; editingIndex = index;
33
+ input = new Input();
34
+ input.setValue(questions[index] ?? "");
35
+ input.onSubmit = (value: string) => {
36
+ const trimmed = value.trim();
37
+ if (!trimmed || trimmed.length > MAX_OVERTHINK_QUESTION_CHARS || /[\r\n]/.test(trimmed)) {
38
+ warn("Enter one nonempty question (max " + MAX_OVERTHINK_QUESTION_CHARS + " characters).", "warning"); return;
39
+ }
40
+ if (editingIndex === questions.length) questions.push(trimmed);
41
+ else questions[editingIndex] = trimmed;
42
+ mode = "list"; cursor = editingIndex; resetArmed = false;
43
+ discardArmed = false; notice = ""; tui.requestRender();
44
+ };
45
+ tui.requestRender();
46
+ };
47
+ const save = async () => {
48
+ if (pending) return;
49
+ let clean: string[];
50
+ try { clean = checkQuestions(questions); }
51
+ catch (error) { warn(errorMessage(error), "error"); return; }
52
+ pending = true; tui.requestRender();
53
+ try { await options.save(clean); saved = JSON.stringify(clean); questions = clean; warn("Questions saved.", "success"); }
54
+ catch (error) { warn("Save failed: " + errorMessage(error), "error"); }
55
+ finally { pending = false; tui.requestRender(); }
56
+ };
57
+ const reset = async () => {
58
+ pending = true; tui.requestRender();
59
+ try {
60
+ questions = checkQuestions(await options.reset());
61
+ cursor = 0; scroller.toStart(); resetArmed = false; discardArmed = false;
62
+ warn("Reset in editor. Ctrl+S to save.", "warning");
63
+ } catch (error) { warn("Reset failed: " + errorMessage(error), "error"); }
64
+ finally { pending = false; tui.requestRender(); }
65
+ };
66
+ return {
67
+ render(width: number) {
68
+ const height = modalHeight(tui);
69
+ const list = questions.length ? questions.map((question, index) =>
70
+ (index === cursor ? theme.fg("accent", "> ") : " ") +
71
+ theme.fg(index === cursor ? "accent" : "text", truncateToWidth(String(index + 1) + ". " + question, Math.max(8, width - 6), "…"))
72
+ ) : [theme.fg("muted", "No questions. Add one, or save an empty list to disable checks.")];
73
+ return renderFrame(theme, width, height, {
74
+ header: () => theme.fg("accent", theme.bold(options.title)) + (dirty() ? " *" : ""),
75
+ body: (rows, inner) => mode === "edit"
76
+ ? ["Edit question:", ...input.render(inner)].slice(0, rows)
77
+ : scroller.view(list, rows),
78
+ notice,
79
+ hints: mode === "edit" ? "Enter apply · Esc cancel edit" :
80
+ "↑/↓ select · Enter edit · Ctrl+N add · Ctrl+X delete · Alt+↑/↓ move · Ctrl+D reset · Ctrl+S save · Esc close",
81
+ fill: true,
82
+ });
83
+ },
84
+ invalidate() {},
85
+ handleInput(data: string) {
86
+ if (pending || closed) return;
87
+ if (mode === "edit") {
88
+ if (matchesKey(data, "escape")) { mode = "list"; notice = ""; tui.requestRender(); return; }
89
+ input.handleInput(data); tui.requestRender(); return;
90
+ }
91
+ if (matchesKey(data, "escape")) {
92
+ if (resetArmed) { resetArmed = false; warn("Reset cancelled."); return; }
93
+ if (dirty() && !discardArmed) { discardArmed = true; warn("Unsaved questions. Esc again to discard, Ctrl+S to save.", "warning"); return; }
94
+ closed = true; done(); return;
95
+ }
96
+ discardArmed = false;
97
+ if (matchesKey(data, "ctrl+s")) { void save(); return; }
98
+ if (matchesKey(data, "ctrl+n")) {
99
+ if (questions.length >= MAX_OVERTHINK_QUESTIONS) { warn("Maximum " + MAX_OVERTHINK_QUESTIONS + " questions.", "warning"); return; }
100
+ beginEdit(questions.length); return;
101
+ }
102
+ if (matchesKey(data, "ctrl+d")) {
103
+ if (!resetArmed) { resetArmed = true; warn("Ctrl+D again to reset this list, then Ctrl+S to save.", "warning"); return; }
104
+ void reset(); return;
105
+ }
106
+ resetArmed = false;
107
+ if (matchesKey(data, "ctrl+x") && questions.length) {
108
+ questions.splice(cursor, 1); cursor = Math.min(cursor, Math.max(0, questions.length - 1));
109
+ warn("Question removed from draft. Ctrl+S to save."); return;
110
+ }
111
+ if (matchesKey(data, "alt+up") && cursor > 0) {
112
+ [questions[cursor - 1], questions[cursor]] = [questions[cursor]!, questions[cursor - 1]!];
113
+ cursor--; tui.requestRender(); return;
114
+ }
115
+ if (matchesKey(data, "alt+down") && cursor < questions.length - 1) {
116
+ [questions[cursor + 1], questions[cursor]] = [questions[cursor]!, questions[cursor + 1]!];
117
+ cursor++; tui.requestRender(); return;
118
+ }
119
+ if (matchesKey(data, "up")) { cursor = Math.max(0, cursor - 1); scroller.by(-1); tui.requestRender(); return; }
120
+ if (matchesKey(data, "down")) { cursor = Math.min(questions.length - 1, cursor + 1); scroller.by(1); tui.requestRender(); return; }
121
+ if (matchesKey(data, "return") || matchesKey(data, "enter")) {
122
+ if (questions.length) beginEdit(cursor);
123
+ }
124
+ },
125
+ };
126
+ };
127
+ }
128
+
129
+ export async function openOverthinkQuestionEditor(ctx: ExtensionCommandContext, options: EditorOptions): Promise<void> {
130
+ await openBroOverlay<void>(ctx, createOverthinkQuestionEditor(options));
131
+ }