pi-bro 0.31.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/CHANGELOG.md CHANGED
@@ -2,6 +2,15 @@
2
2
 
3
3
  All notable changes to pi-bro are documented here.
4
4
 
5
+ ## [0.32.0] - 2026-11-07
6
+
7
+ ### Highlights
8
+
9
+ - BTW and Grill Me preserve completed private discussions, access choices and drafts across ordinary Pi reload/restart/resume through non-model-facing custom session entries.
10
+ - Simplify restores its most recent source and explanation; Show restores the last rendered result and focus. Cleared state stays cleared.
11
+ - Session branches inherit their prior private state but later edits remain separate. No global user memory database or automatic context injection.
12
+ - Added session restore validation and test coverage. Recovery still depends on Pi saving its session entries; abrupt host crashes during an active call are not guaranteed.
13
+
5
14
  ## [0.31.0] - 2026-11-07
6
15
 
7
16
  ### Added
package/README.md CHANGED
@@ -105,16 +105,18 @@ which may keep it under their own policies. Paths below are under
105
105
 
106
106
  | Feature | What is sent | What Bro keeps on disk |
107
107
  | --- | --- | --- |
108
- | Explain | The agent's last reply, your pasted text, or text extracted from your file or webpage, plus your preferences | Nothing; the last result stays in memory |
108
+ | Explain | The agent's last reply, your pasted text, or text extracted from your file or webpage, plus your preferences | Last result as a private Pi session entry |
109
109
  | Architecture Docs | Repository source, existing architecture docs, focus and preferences; only selected backend can see snapshot files | Generated Markdown, JSON graph and offline HTML in `docs/architecture/`; temporary inspection copy is removed |
110
- | Show | User and assistant text from recent turns (no tool calls, tool results, reasoning or images), plus your preferences | Diagram pages in `pi-bro-<uid>/` in your system temp folder |
111
- | Side questions | Your questions and up to the last 8 turns of conversation text, plus your preferences | Nothing; the thread stays in memory |
112
- | Grill Me | Topic, interview turns, up to the last 8 main-session text turns and preferences; any workspace files the selected inspector reads | Nothing; interview and brief are in memory |
110
+ | Show | User and assistant text from recent turns (no tool calls, tool results, reasoning or images), plus your preferences | Last result in the private Pi session, plus temporary diagram pages in `pi-bro-<uid>/` |
111
+ | Side questions | Your questions and up to the last 8 turns of conversation text, plus your preferences | Private Pi session entries with completed turns, mode and draft |
112
+ | Grill Me | Topic, interview turns, up to the last 8 main-session text turns and preferences; any workspace files the selected inspector reads | Private Pi session entries with the interview and brief |
113
113
  | Overthink | Current session projection, including tool evidence, plus private user-editable questions, to the active Pi provider | Global questions in `bro-overthink-defaults.json`; per-session questions and latest private note in Pi session custom entries |
114
114
  | Elevate | Your objective, selected findings, all current-branch user/assistant text; Full also includes tool-call arguments and text results, and preferences | Nothing; the workflow stays in memory |
115
115
  | Guided Review | The PR description and diff, the files the backend reads, your questions, plus your preferences | Reviews and captured source in `bro-reviews/`, with no automatic cleanup |
116
116
  | Advisor | The agent's system instructions, tool list and whole conversation, including tool calls and results (reasoning and images omitted), plus your steering | Steering in `bro-advisor.md` and the session file |
117
117
 
118
+ Session-scoped Bro entries live **inside Pi's session file**. They stay out of the model's conversation, but are not secret from someone who can read, back up, export, or share that file. Check the session content before sharing it; this feature does not encrypt or redact exports.
119
+
118
120
  `/bro url` also connects straight to the website, which sees your IP address.
119
121
  Bro runs each CLI as you, with your environment. It never reads or copies an
120
122
  external CLI's provider credentials, but a CLI signs in its own way, which can
@@ -148,8 +150,7 @@ and [Privacy and safety](docs/reference/data-and-permissions.md#privacy-and-safe
148
150
  - No fallback: if the chosen backend, model or effort fails, Bro shows that
149
151
  backend's error instead of switching. → Run `/bro doctor`.
150
152
  - Elevate runs fresh restricted calls through the BTW model setting. Restricted does not always mean sandboxed; see [access and retention](docs/reference/data-and-permissions.md). The shortcut may not work in all terminals: use `/bro elevate` instead.
151
- - BTW and Grill Me threads and the last explanation live in memory only and clear on
152
- reload or restart.
153
+ - BTW, Grill Me and the latest explanation/Show result use private session entries; they survive normal Pi reload/resume. A new session starts fresh and later fork changes stay separate. Abrupt crashes during active calls are not guaranteed.
153
154
  - Guided Review runs in local interactive Pi only and does not post to
154
155
  GitHub.
155
156
 
@@ -46,6 +46,7 @@ asked in.
46
46
  mode.
47
47
  - A turn is capped at 2 minutes in conversation-only mode and 10 minutes in
48
48
  full permission mode.
49
- - Bro's thread lives in memory only — it clears when you switch Pi sessions,
50
- reload extensions, or quit Pi. Changing the BTW backend starts a fresh
49
+ - Bro saves its completed thread, mode and draft as private Pi session entries.
50
+ Reloading or continuing the same session restores them. `/tree` restores the selected branch's state, and an aborted reply is discarded rather than saved as `…`. Reopening unchanged state adds no new disk entry. A new session starts fresh;
51
+ a fork initially inherits the shared history then changes independently. Changing the BTW backend starts a fresh
51
52
  thread; native session IDs never cross backends.
package/docs/grill-me.md CHANGED
@@ -53,7 +53,7 @@ Grill Me uses the **BTW model/backend/effort** selection from `/bro config`, but
53
53
  - Full access can read, edit and execute commands. Bro instructs the model not to make changes, but cannot enforce that instruction. There is no automatic escalation.
54
54
  - Each turn makes a fresh backend call replaying the complete interview. Long interviews cost more and may exceed context limits; there is no hidden truncation or fallback.
55
55
  - The provider receives your topic, interview history, Bro preferences and up to eight recent main-session user/assistant text turns (40,000 characters). Captured context excludes tool calls/results, hidden reasoning and images. Backend tools can inspect additional workspace content.
56
- - Bro keeps the interview in memory, lost on reload, session change or exit. Backend/provider retention is separate; see [backend retention](reference/data-and-permissions.md#backends-access-and-retention).
56
+ - Bro stores completed interview turns, depth, access choice and drafts in private Pi session entries. The current Pi session restores them after reload or resume; a new session starts fresh, and forks diverge after inheriting earlier choices. Backend/provider retention is separate; see [backend retention](reference/data-and-permissions.md#backends-access-and-retention).
57
57
  - Closing discards partial output, preserves completed replies, and restores cancelled input unless a newer draft exists. Retry preserves the previous reply until replacement succeeds. Cancellation cannot undo backend changes; descendant cleanup on Windows and abrupt host shutdown are not guaranteed.
58
58
 
59
59
  ## Comparison
@@ -126,12 +126,9 @@ See [feature guide](../features/architecture.md).
126
126
  reaches the main editor only through `/insert` or `/insert-all`, and advisor
127
127
  results appear as normal tool results in the executor's transcript.
128
128
  - **Saved reviews**: Guided Review records, questions, drafts and captured Git source persist under the host's `getAgentDir()/bro-reviews/`. No automatic cleanup or sync is provided; see [storage and removal](../guided-review.md#access-privacy-and-storage).
129
- - **Memory**: the latest explanation (for `/bro open`) and the BTW thread live
130
- only in process memory and clear when you switch Pi sessions, reload
131
- extensions, or quit Pi. Backend-native sessions can persist independently.
132
- Standing advisor priorities are stored in `~/.pi/agent/bro-advisor.md`, and
133
- the session steering brief is stored as session-scoped extension data
134
- (`bro-advisor-steering`) in the session file.
129
+ - **Private session continuity**: completed BTW and Grill Me turns, modes, drafts, the latest Simplify state and the last Show result are saved as Pi `custom` entries inside the current session file. They survive normal reload/restart and are never added to the main model or Advisor snapshot. A fork initially inherits earlier entries; later updates stay on its own branch. This is local disk storage, not a global memory store or an abrupt-crash guarantee. Backend-native sessions may persist independently.
130
+ Standing Advisor priorities are stored in `~/.pi/agent/bro-advisor.md`, and
131
+ the session steering brief uses another `custom` entry (`bro-advisor-steering`). Session entries remain readable to anyone with the session file; export/sharing may include them. The private boundary is model-context isolation, not encrypted storage or export redaction.
135
132
  - **File safety**: `/bro file` reads only regular files whose resolved path is
136
133
  inside Pi's current workspace, including after resolving symlinks. Bro's
137
134
  extractor does not modify them.
@@ -43,7 +43,7 @@ tool before giving it to Bro.
43
43
  - Direct webpage fetching does not currently use `HTTP_PROXY`, `HTTPS_PROXY`,
44
44
  or other proxy environment variables.
45
45
  - `/bro elevate` is pre-execution only. It does not validate expert claims, run source research or keep a persistent thread. Invalid discovery JSON can be retried with the [Retry] button; if it recurs, choose another BTW backend/model in `/bro config`. See [Elevate](../elevate.md).
46
- - `/bro btw` threads are memory-only and do not survive reloads or restarts.
46
+ - `/bro btw` threads are saved in the Pi session file and restored on reload/restart. With the Pi backend, the native side session is memory-only, so the first turn after a restart reseeds it from the saved transcript and shows an expiry notice.
47
47
  - The Agy advisor requires Agy CLI `>=1.1.15`.
48
48
  - Show captures only the conversation text of what already happened in the
49
49
  current session — the last few turns' user and assistant messages, with
@@ -166,7 +166,7 @@ See [Troubleshooting and current limits](reference/troubleshooting.md#troublesho
166
166
 
167
167
  ## Simplify modal
168
168
 
169
- `/bro` opens Simplify and explains the latest completed assistant reply. `/bro simplify` returns to the most recent Simplify screen without another model request. Inside, `/simplify`, `/text <text>`, `/file <path>` and `/url <url>` produce one explanation at a time; `/copy` copies the answer, `/clear` clears it, and `/help` shows controls. Press **M** with an empty composer to change the explanation mode and rerun; **R** retries. The saved default mode remains unchanged. The current screen is kept only within the Pi session. Old `/bro text|file|url|open` forms remain callable for compatibility.
169
+ `/bro` opens Simplify and explains the latest completed assistant reply. `/bro simplify` returns to the most recent Simplify screen without another model request. Inside, `/simplify`, `/text <text>`, `/file <path>` and `/url <url>` produce one explanation at a time; `/copy` copies the answer, `/clear` clears it, and `/help` shows controls. Press **M** with an empty composer to change the explanation mode and rerun; **R** retries. The saved default mode remains unchanged. The latest result is preserved in private Pi session entries across reload/restart and stays off the main model's context. Old `/bro text|file|url|open` forms remain callable for compatibility.
170
170
 
171
171
  ## Bro command discovery and Config navigation
172
172
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-bro",
3
- "version": "0.31.0",
3
+ "version": "0.32.0",
4
4
  "description": "A sidekick for you and your Pi agent: plain-language explanations, side questions, diagrams, PR review and second opinions, without cluttering the agent's context.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -61,6 +61,7 @@
61
61
  "src/remember.ts",
62
62
  "src/simplify-engine.ts",
63
63
  "src/simplify-ui.ts",
64
+ "src/session-state.ts",
64
65
  "src/explain-modal.ts",
65
66
  "src/review.ts",
66
67
  "src/review-source.ts",
@@ -104,7 +105,7 @@
104
105
  "scripts": {
105
106
  "docs:check": "node scripts/check-docs.mjs && node --test test/docs-quality.test.mjs",
106
107
  "typecheck": "tsc --noEmit",
107
- "test": "npm run typecheck && npm run docs:check && node .github/scripts/release-utils.mjs selftest && node --test test/architecture.test.mjs test/architecture-review.test.mjs test/architecture-controller.test.mjs test/elevate-docs.test.mjs test/elevate.test.ts test/overthink.test.ts test/simplify.test.ts test/simplify-modal.test.mjs test/grill.test.ts test/config-navigation.test.ts test/config-navigation-modal.test.mjs test/remember.test.ts test/remember-modal.test.mjs test/review-ux.test.mjs test/review-doctor.test.mjs test/review-versions.test.mjs test/review-regeneration.test.mjs test/review-modal.test.mjs test/review.test.ts test/review-ui.test.mjs test/review-session.test.mjs test/helpers.test.mjs test/prompt.test.ts test/backend.test.ts test/claude.test.ts test/grok.test.ts test/codex.test.ts test/muse.test.ts test/settings.test.ts test/sources.test.ts test/release.test.ts test/show-html.test.ts test/smoke-rpc.test.ts test/ui-capabilities.test.ts test/modal-contract.test.mjs benchmark/*.test.ts && sh ./test/smoke-test.sh",
108
+ "test": "npm run typecheck && npm run docs:check && node .github/scripts/release-utils.mjs selftest && node --test test/architecture.test.mjs test/architecture-review.test.mjs test/architecture-controller.test.mjs test/elevate-docs.test.mjs test/elevate.test.ts test/overthink.test.ts test/simplify.test.ts test/simplify-modal.test.mjs test/session-state.test.ts test/session-lifecycle.test.mjs test/grill.test.ts test/config-navigation.test.ts test/config-navigation-modal.test.mjs test/remember.test.ts test/remember-modal.test.mjs test/review-ux.test.mjs test/review-doctor.test.mjs test/review-versions.test.mjs test/review-regeneration.test.mjs test/review-modal.test.mjs test/review.test.ts test/review-ui.test.mjs test/review-session.test.mjs test/helpers.test.mjs test/prompt.test.ts test/backend.test.ts test/claude.test.ts test/grok.test.ts test/codex.test.ts test/muse.test.ts test/settings.test.ts test/sources.test.ts test/release.test.ts test/show-html.test.ts test/smoke-rpc.test.ts test/ui-capabilities.test.ts test/modal-contract.test.mjs benchmark/*.test.ts && sh ./test/smoke-test.sh",
108
109
  "benchmark:dry-run": "node benchmark/run.ts dry-run",
109
110
  "benchmark:run": "node benchmark/run.ts run",
110
111
  "benchmark:report": "node benchmark/run.ts report",
package/src/bro.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
1
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
2
  import { ADVISOR_STEERING_FILE, ADVISOR_TOOL_NAME, registerAdvisorTool } from "./advisor.ts";
3
3
  import {
4
4
  type BtwThread,
@@ -50,6 +50,7 @@ import {
50
50
  } from "./sources.ts";
51
51
  import { hasBroCustomUi } from "./ui-capabilities.ts";
52
52
  import { errorMessage, unquote, withDoctor } from "./util.ts";
53
+ import { BTW_SESSION_ENTRY, GRILL_SESSION_ENTRY, SIMPLIFY_SESSION_ENTRY, LAST_RESULT_SESSION_ENTRY, restorePrivateBroState, privateSessionEntrySnapshots } from "./session-state.ts";
53
54
 
54
55
  export * from "./util.ts";
55
56
  export * from "./ui-capabilities.ts";
@@ -71,6 +72,7 @@ export * from "./simplify-engine.ts";
71
72
  export * from "./simplify-ui.ts";
72
73
  export * from "./overthink-state.ts";
73
74
  export * from "./overthink.ts";
75
+ export * from "./session-state.ts";
74
76
 
75
77
  const COMMANDS = [
76
78
  { value: "architecture", label: "architecture", description: "Document this repository in docs/architecture/ with diagrams and an offline map" },
@@ -107,21 +109,54 @@ export default async function bro(pi: ExtensionAPI) {
107
109
  let lastShowSteering: string | undefined;
108
110
  let btwThread: BtwThread | undefined;
109
111
  let grillThread: GrillThread | undefined;
112
+ let savedSnapshots = new Map<string, string>();
113
+ // Pi custom entries are append-only. Save a new snapshot only if its content changed.
114
+ // Reset the comparison on /tree: a new branch must never inherit the old branch's state.
115
+ const appendChanged = (type: string, value: unknown) => {
116
+ const data = structuredClone(value);
117
+ const serialized = JSON.stringify(data);
118
+ if (savedSnapshots.get(type) === serialized) return;
119
+ pi.appendEntry(type, data);
120
+ savedSnapshots.set(type, serialized);
121
+ };
110
122
  const remember = (result: ModalResult, showSteering?: string) => {
111
123
  if (result.source) {
112
124
  lastResult = result;
113
125
  lastShowSteering = showSteering;
126
+ appendChanged(LAST_RESULT_SESSION_ENTRY, { result, steering: showSteering });
114
127
  }
115
128
  };
129
+ const saveSimplify = () => {
130
+ if (!savedSnapshots.has(SIMPLIFY_SESSION_ENTRY) && !simplifyState.result && !simplifyState.draft) return;
131
+ appendChanged(SIMPLIFY_SESSION_ENTRY, { state: simplifyState });
132
+ };
133
+ const saveBtw = () => {
134
+ if (!btwThread) return;
135
+ // Visiting an empty BTW modal does not need a disk entry.
136
+ if (!savedSnapshots.has(BTW_SESSION_ENTRY) &&
137
+ !btwThread.turns.length && !btwThread.draft && !btwThread.full) return;
138
+ appendChanged(BTW_SESSION_ENTRY, { thread: btwThread });
139
+ };
140
+ const saveGrill = () => {
141
+ if (!grillThread) return;
142
+ if (!savedSnapshots.has(GRILL_SESSION_ENTRY) &&
143
+ !grillThread.topic && !grillThread.turns.length && !grillThread.draft) return;
144
+ appendChanged(GRILL_SESSION_ENTRY, { thread: grillThread });
145
+ };
146
+ const restore = (ctx: ExtensionContext) => {
147
+ const branch = ctx.sessionManager.getBranch();
148
+ const restored = restorePrivateBroState(branch);
149
+ savedSnapshots = privateSessionEntrySnapshots(branch);
150
+ lastResult = restored.lastResult;
151
+ lastShowSteering = restored.lastShowSteering;
152
+ simplifyState = restored.simplify;
153
+ btwThread = restored.btw;
154
+ grillThread = restored.grill;
155
+ };
116
156
 
117
157
  pi.on("session_shutdown", async () => { stopGuidedReviews(); });
118
-
119
- pi.on("session_start", async (_event, _ctx) => {
120
- lastResult = undefined;
121
- simplifyState = {};
122
- btwThread = undefined;
123
- grillThread = undefined;
124
- });
158
+ pi.on("session_start", async (_event, ctx) => { restore(ctx); });
159
+ pi.on("session_tree", async (_event, ctx) => { restore(ctx); });
125
160
 
126
161
  registerAdvisorTool(pi);
127
162
  registerAboutUserTool(pi);
@@ -146,7 +181,7 @@ export default async function bro(pi: ExtensionAPI) {
146
181
 
147
182
  if (action === "simplify") {
148
183
  if (value) { ctx.ui.notify("Use /bro simplify to reopen the last Simplify view; use /text, /file or /url inside it.", "warning"); return; }
149
- try { await openSimplifyWorkflow(ctx, simplifyState, {kind:"resume"}); if (simplifyState.result) remember(simplifyState.result); }
184
+ try { await openSimplifyWorkflow(ctx, simplifyState, {kind:"resume"}); saveSimplify(); if (simplifyState.result) remember(simplifyState.result); }
150
185
  catch (error) { ctx.ui.notify(withDoctor(error), "error"); }
151
186
  return;
152
187
  }
@@ -183,6 +218,7 @@ export default async function bro(pi: ExtensionAPI) {
183
218
  : {kind:action as "text" | "file" | "url", input:value};
184
219
  try {
185
220
  await openSimplifyWorkflow(ctx, simplifyState, initial);
221
+ saveSimplify();
186
222
  if (simplifyState.result) remember(simplifyState.result);
187
223
  } catch (error) { ctx.ui.notify(withDoctor(error), "error"); }
188
224
  return;
@@ -298,9 +334,14 @@ export default async function bro(pi: ExtensionAPI) {
298
334
  try {
299
335
  const btwBackend = capabilityBackend(await readSettings(), "btw");
300
336
  const thread = resolveBtwThread(btwThread);
301
- if (bindBtwBackend(thread, btwBackend)) ctx.ui.notify("Backend changed — started a fresh side thread.", "info");
337
+ const backendChanged = bindBtwBackend(thread, btwBackend);
338
+ if (backendChanged) ctx.ui.notify("Backend changed — started a fresh side thread.", "info");
302
339
  btwThread = thread;
303
- await openBtwModal(ctx, { thread, initialQuestion: parsed.question });
340
+ if (backendChanged) saveBtw();
341
+ await openBtwModal(ctx, {
342
+ thread, initialQuestion: parsed.question,
343
+ onChange: () => { if (btwThread === thread) saveBtw(); },
344
+ });
304
345
  } catch (error) {
305
346
  ctx.ui.notify(withDoctor(error), "error");
306
347
  }
@@ -321,7 +362,9 @@ export default async function bro(pi: ExtensionAPI) {
321
362
  const start = Boolean(parsed.topic);
322
363
  if (start) grillThread = { topic: parsed.topic, depth: parsed.depth, turns: [], fullAccess: false };
323
364
  else grillThread ??= { topic: "", depth: parsed.depth, turns: [], fullAccess: false };
324
- try { await openGrillModal(ctx, grillThread, { start }); }
365
+ const thread = grillThread;
366
+ if (start) saveGrill();
367
+ try { await openGrillModal(ctx, thread, { start, onChange: () => { if (grillThread === thread) saveGrill(); } }); }
325
368
  catch (error) { ctx.ui.notify(withDoctor(error), "error"); }
326
369
  return;
327
370
  }
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 = () => {
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
  }
@@ -0,0 +1,91 @@
1
+ /** Private per-session Bro state. Custom entries are not sent to the main model or advisor. */
2
+ import type { SessionEntry } from "@earendil-works/pi-coding-agent";
3
+ import type { BtwThread } from "./btw.ts";
4
+ import type { GrillThread } from "./grill-engine.ts";
5
+ import type { ModalResult } from "./explain-modal.ts";
6
+ import type { SimplifyState } from "./simplify-ui.ts";
7
+ import { isRecord } from "./util.ts";
8
+
9
+ export const BTW_SESSION_ENTRY = "bro-btw-thread";
10
+ export const GRILL_SESSION_ENTRY = "bro-grill-thread";
11
+ export const SIMPLIFY_SESSION_ENTRY = "bro-simplify-state";
12
+ export const LAST_RESULT_SESSION_ENTRY = "bro-last-result";
13
+
14
+ /** Last on-branch snapshot per feature, used to avoid duplicate append-only writes.
15
+ * A tree move rebuilds these signatures from its own branch, not the old one.
16
+ */
17
+ export function privateSessionEntrySnapshots(branch: readonly SessionEntry[]): Map<string, string> {
18
+ const types = new Set<string>([
19
+ BTW_SESSION_ENTRY, GRILL_SESSION_ENTRY, SIMPLIFY_SESSION_ENTRY, LAST_RESULT_SESSION_ENTRY,
20
+ ]);
21
+ const saved = new Map<string, string>();
22
+ for (const entry of branch) {
23
+ if (entry.type === "custom" && types.has(entry.customType) && isRecord(entry.data)) {
24
+ saved.set(entry.customType, JSON.stringify(entry.data));
25
+ }
26
+ }
27
+ return saved;
28
+ }
29
+
30
+
31
+ export type PrivateBroSessionState = {
32
+ btw?: BtwThread;
33
+ grill?: GrillThread;
34
+ simplify: SimplifyState;
35
+ lastResult?: ModalResult;
36
+ lastShowSteering?: string;
37
+ };
38
+
39
+ const textTurns = (value: unknown): boolean =>
40
+ Array.isArray(value) && value.every(turn =>
41
+ isRecord(turn) && typeof turn.question === "string" && typeof turn.answer === "string");
42
+
43
+ function btwThread(value: unknown): BtwThread | undefined {
44
+ if (!isRecord(value) || !textTurns(value.turns) || typeof value.full !== "boolean") return undefined;
45
+ if (value.backend !== undefined && typeof value.backend !== "string") return undefined;
46
+ return value as unknown as BtwThread;
47
+ }
48
+
49
+ function grillThread(value: unknown): GrillThread | undefined {
50
+ if (!isRecord(value) || typeof value.topic !== "string" || !textTurns(value.turns) ||
51
+ !["light", "balanced", "exhaustive"].includes(String(value.depth)) ||
52
+ typeof value.fullAccess !== "boolean") return undefined;
53
+ return value as unknown as GrillThread;
54
+ }
55
+
56
+ function modalResult(value: unknown): ModalResult | undefined {
57
+ if (!isRecord(value) || typeof value.text !== "string") return undefined;
58
+ if (value.source !== undefined && (!isRecord(value.source) || typeof value.source.text !== "string")) return undefined;
59
+ return value as unknown as ModalResult;
60
+ }
61
+
62
+ function simplifyState(value: unknown): SimplifyState {
63
+ if (!isRecord(value)) return {};
64
+ const result = modalResult(value.result);
65
+ if (value.result !== undefined && !result?.source) return {};
66
+ return {
67
+ ...(result ? { result: result as SimplifyState["result"] } : {}),
68
+ ...(value.view === "result" || value.view === "help" || value.view === "empty" ? { view: value.view } : {}),
69
+ ...(typeof value.draft === "string" ? { draft: value.draft } : {}),
70
+ ...(typeof value.error === "string" ? { error: value.error } : {}),
71
+ };
72
+ }
73
+
74
+ /** Last matching entry on the active branch wins. A cleared state cannot resurrect. */
75
+ export function restorePrivateBroState(branch: readonly SessionEntry[]): PrivateBroSessionState {
76
+ const restored: PrivateBroSessionState = { simplify: {} };
77
+ for (const entry of branch) {
78
+ if (entry.type !== "custom" || !isRecord(entry.data)) continue;
79
+ const value = entry.data;
80
+ switch (entry.customType) {
81
+ case BTW_SESSION_ENTRY: restored.btw = btwThread(value.thread); break;
82
+ case GRILL_SESSION_ENTRY: restored.grill = grillThread(value.thread); break;
83
+ case SIMPLIFY_SESSION_ENTRY: restored.simplify = simplifyState(value.state); break;
84
+ case LAST_RESULT_SESSION_ENTRY:
85
+ restored.lastResult = modalResult(value.result);
86
+ restored.lastShowSteering = typeof value.steering === "string" ? value.steering : undefined;
87
+ break;
88
+ }
89
+ }
90
+ return restored;
91
+ }