pi-render-btw 0.6.11 → 0.6.13

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
@@ -1,5 +1,18 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.6.13 — 2026-09-14
4
+
5
+ - Keep the BTW/Peek/Tool Output title-row `[Esc]` affordance visible beside long titles.
6
+ - Highlight `[Esc]` on hover and close the current surface on a normalized or legacy SGR mouse click.
7
+
8
+ ## 0.6.12 — 2026-09-13
9
+
10
+ - Recover interrupted streaming turns as closed history after reload.
11
+ - Rehydrate read-only Peek and live Tool Output from durable artifact details and diffs.
12
+ - Expand regression coverage for durable storage and live tool interactions.
13
+ - Show runtime-provided partial tool output in the read-only viewer with a `STREAMING` marker, then update the same tool row in place when the final result arrives.
14
+ - Consume `Ctrl+O` with no focused tool instead of forwarding it to the composer; show an explicit no-output state when a tool has not emitted output.
15
+
3
16
  ## 0.6.11 — 2026-09-13
4
17
 
5
18
  - Persist BTW transcript snapshots and complete tool artifacts under `.pi-subagents/btw/`.
package/README.md CHANGED
@@ -97,7 +97,8 @@ pi install /path/to/pi-render-btw
97
97
  - the composer uses Pi's native editor behavior for undo, paste, prompt history, and Tab file-path completion (including `@` prefixes) relative to the BTW working directory
98
98
  - `Esc` still dismisses BTW immediately while the overlay is focused
99
99
  - hovering and left-clicking a transcript row focuses one shared USER/ASSISTANT/Tool target; clicking a Tool row toggles its compact details and double-clicking collapses it
100
- - with a focused Tool row, `Ctrl+O` opens a read-only full Input/Output viewer; its wheel, `j/k`, arrows, `g/G`, PageUp/PageDown, and `Esc` controls stay inside the viewer
100
+ - with a focused Tool row, `Ctrl+O` opens a read-only Input/Output viewer; while the runtime emits partial tool updates it shows the latest provided data with a `STREAMING` marker, and after tool completion it switches to the final result
101
+ - if the runtime has not provided tool output yet, the viewer shows an explicit no-output state rather than inventing content; its wheel, `j/k`, arrows, `g/G`, PageUp/PageDown, and `Esc` controls stay inside the viewer
101
102
  - BTW opens top-centered so the main session remains visible underneath it
102
103
 
103
104
  ### `/btw:new [question]`
@@ -127,7 +128,7 @@ pi install /path/to/pi-render-btw
127
128
  - normalized mouse hover highlights a block and a left click selects it; press/release events do not change selection
128
129
  - `M` copies the selected message; `o` opens it read-only in nvim
129
130
  - `Esc`, `q`, or `Ctrl+C` returns to the BTW composer; press `Esc` again in the composer to dismiss BTW
130
- - the Peek and Tool Output headers show `[Esc]`; wheel input is handled locally without changing the main viewport
131
+ - the Peek and Tool Output headers show a hoverable `[Esc]` close/back affordance; wheel input is handled locally without changing the main viewport
131
132
 
132
133
  ### `/btw:clear`
133
134
 
@@ -44,6 +44,8 @@ export interface PeekBlock {
44
44
  /** Serialized input/output used only for the read-only tool preview. */
45
45
  toolInput?: string;
46
46
  toolOutput?: string;
47
+ /** True while the runtime has only supplied a partial tool result. */
48
+ streaming?: boolean;
47
49
  isError?: boolean;
48
50
  truncated?: boolean;
49
51
  }
@@ -96,7 +98,8 @@ export function buildPeekBlocks(
96
98
  showTools: boolean,
97
99
  ): PeekBlock[] {
98
100
  const blocks: PeekBlock[] = [];
99
- const toolData = new Map<string, { input?: string; output?: string; isError?: boolean; toolName?: string }>();
101
+ const toolData = new Map<string, { input?: string; output?: string; isError?: boolean; streaming?: boolean; toolName?: string }>();
102
+ const toolResultIds = new Set<string>();
100
103
  let id = 0;
101
104
 
102
105
  // Tool calls and results are separate transcript entries, but a preview should
@@ -111,7 +114,9 @@ export function buildPeekBlocks(
111
114
  } else {
112
115
  current.output = entry.fullContent ?? entry.content ?? entry.text ?? current.output;
113
116
  current.isError = entry.isError;
117
+ current.streaming = entry.streaming === true;
114
118
  current.toolName = entry.toolName ?? current.toolName;
119
+ toolResultIds.add(entry.toolCallId);
115
120
  }
116
121
  toolData.set(entry.toolCallId, current);
117
122
  }
@@ -156,6 +161,7 @@ export function buildPeekBlocks(
156
161
  toolName: entry.toolName ?? paired?.toolName,
157
162
  toolInput: entry.args ?? entry.text ?? paired?.input,
158
163
  toolOutput: paired?.output,
164
+ streaming: paired?.streaming ?? !toolResultIds.has(entry.toolCallId ?? ""),
159
165
  isError: paired?.isError,
160
166
  });
161
167
  } else if (entry.type === "tool-result") {
@@ -171,6 +177,7 @@ export function buildPeekBlocks(
171
177
  toolName: entry.toolName ?? paired?.toolName,
172
178
  toolInput: paired?.input,
173
179
  toolOutput: entry.fullContent ?? entry.content ?? entry.text ?? paired?.output,
180
+ streaming: entry.streaming === true || paired?.streaming === true,
174
181
  isError: entry.isError,
175
182
  truncated: entry.truncated,
176
183
  });
@@ -1,12 +1,17 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import {
3
3
  appendFileSync,
4
+ closeSync,
4
5
  existsSync,
6
+ fstatSync,
5
7
  mkdirSync,
8
+ openSync,
6
9
  readFileSync,
10
+ readSync,
7
11
  renameSync,
8
12
  unlinkSync,
9
13
  writeFileSync,
14
+ writeSync,
10
15
  } from "node:fs";
11
16
  import path from "node:path";
12
17
 
@@ -103,6 +108,29 @@ function stringifyJson(value: unknown): string {
103
108
  }
104
109
  }
105
110
 
111
+ /**
112
+ * Append one JSONL record without assuming the previous process reached EOF.
113
+ * A killed append can leave a valid record without its trailing newline; add
114
+ * the separator before the next record so that readSnapshot can still recover
115
+ * every later complete record.
116
+ */
117
+ function appendJsonLine(filePath: string, value: unknown): void {
118
+ const fd = openSync(filePath, "a+");
119
+ try {
120
+ const size = fstatSync(fd).size;
121
+ if (size > 0) {
122
+ const lastByte = Buffer.allocUnsafe(1);
123
+ readSync(fd, lastByte, 0, 1, size - 1);
124
+ if (lastByte[0] !== 0x0a) {
125
+ writeSync(fd, "\n", undefined, "utf8");
126
+ }
127
+ }
128
+ writeSync(fd, `${JSON.stringify(value, jsonReplacer)}\n`, undefined, "utf8");
129
+ } finally {
130
+ closeSync(fd);
131
+ }
132
+ }
133
+
106
134
  function writeJsonAtomic(filePath: string, value: unknown): void {
107
135
  const temporaryPath = `${filePath}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
108
136
  try {
@@ -246,6 +274,26 @@ function rebuildToolCalls(entries: DurableTranscriptEntry[]): Map<string, { turn
246
274
  return toolCalls;
247
275
  }
248
276
 
277
+ function mergeToolArtifact(previous: ToolArtifactWrite | undefined, next: ToolArtifactWrite): ToolArtifactWrite {
278
+ if (!previous) return { ...next };
279
+ return {
280
+ ...previous,
281
+ ...next,
282
+ // A start event owns input and update/end events own output. Keep both
283
+ // when several events are collapsed into one durable write.
284
+ input: next.input !== undefined ? next.input : previous.input,
285
+ output: next.output !== undefined ? next.output : previous.output,
286
+ isError: next.isError ?? previous.isError,
287
+ };
288
+ }
289
+
290
+ const DURABLE_WRITE_DEBOUNCE_MS = 16;
291
+
292
+ type FlushWaiter = {
293
+ resolve: () => void;
294
+ reject: (error: unknown) => void;
295
+ };
296
+
249
297
  /**
250
298
  * Project-local durable BTW store. The Pi session only stores small immutable
251
299
  * locators; all potentially large tool payloads stay under .pi-subagents/btw.
@@ -255,6 +303,14 @@ export class BtwTranscriptStore {
255
303
  readonly threadDir: string;
256
304
  readonly transcriptPath: string;
257
305
  readonly toolsDir: string;
306
+ /** At most one transcript snapshot is needed between durable boundaries. */
307
+ private pendingSnapshot: DurableTranscriptSnapshot | null = null;
308
+ /** Tool updates are coalesced by call id; end always supersedes update. */
309
+ private readonly pendingToolArtifacts = new Map<string, ToolArtifactWrite>();
310
+ private drainTimer: ReturnType<typeof setTimeout> | null = null;
311
+ private draining = false;
312
+ private readonly flushWaiters: FlushWaiter[] = [];
313
+ private lastWriteError: unknown = null;
258
314
 
259
315
  constructor(projectDir: string, sessionId: string) {
260
316
  const normalizedProjectDir = path.resolve(projectDir || process.cwd());
@@ -266,22 +322,159 @@ export class BtwTranscriptStore {
266
322
  mkdirSync(this.toolsDir, { recursive: true });
267
323
  }
268
324
 
269
- appendSnapshot(snapshot: Omit<DurableTranscriptSnapshot, "schemaVersion" | "recordId" | "threadId" | "timestamp">): DurableTranscriptSnapshot {
270
- mkdirSync(this.threadDir, { recursive: true });
271
- const recordId = `${Date.now().toString(36)}-${stableId(`${this.threadId}:${Date.now()}:${Math.random()}`)}`;
272
- const persisted: DurableTranscriptSnapshot = {
325
+ private makeSnapshot(
326
+ snapshot: Omit<DurableTranscriptSnapshot, "schemaVersion" | "recordId" | "threadId" | "timestamp">,
327
+ ): DurableTranscriptSnapshot {
328
+ const now = Date.now();
329
+ const recordId = `${now.toString(36)}-${stableId(`${this.threadId}:${now}:${Math.random()}`)}`;
330
+ return {
273
331
  schemaVersion: BTW_TRANSCRIPT_SCHEMA_VERSION,
274
332
  recordId,
275
333
  threadId: this.threadId,
276
- timestamp: Date.now(),
334
+ timestamp: now,
277
335
  ...snapshot,
278
336
  };
337
+ }
338
+
339
+ private appendSnapshotRecord(snapshot: DurableTranscriptSnapshot): void {
340
+ mkdirSync(this.threadDir, { recursive: true });
279
341
  // transcript.jsonl is line-delimited: keep each immutable snapshot on one
280
342
  // physical line so a partial/corrupt record cannot hide later records.
281
- appendFileSync(this.transcriptPath, `${JSON.stringify(persisted, jsonReplacer)}\n`, "utf8");
343
+ appendJsonLine(this.transcriptPath, snapshot);
344
+ }
345
+
346
+ /**
347
+ * Synchronous escape hatch retained for callers that explicitly need a
348
+ * record before returning. Normal event handling uses enqueueSnapshot and
349
+ * flushes at request/shutdown boundaries instead.
350
+ */
351
+ appendSnapshot(snapshot: Omit<DurableTranscriptSnapshot, "schemaVersion" | "recordId" | "threadId" | "timestamp">): DurableTranscriptSnapshot {
352
+ const persisted = this.makeSnapshot(snapshot);
353
+ this.appendSnapshotRecord(persisted);
354
+ return persisted;
355
+ }
356
+
357
+ /** Queue the newest immutable snapshot and schedule a debounced drain. */
358
+ enqueueSnapshot(
359
+ snapshot: Omit<DurableTranscriptSnapshot, "schemaVersion" | "recordId" | "threadId" | "timestamp">,
360
+ ): DurableTranscriptSnapshot {
361
+ const persisted = this.makeSnapshot(snapshot);
362
+ this.pendingSnapshot = persisted;
363
+ this.scheduleDrain();
282
364
  return persisted;
283
365
  }
284
366
 
367
+ /** Alias for callers that use queue terminology. */
368
+ queueSnapshot(
369
+ snapshot: Omit<DurableTranscriptSnapshot, "schemaVersion" | "recordId" | "threadId" | "timestamp">,
370
+ ): DurableTranscriptSnapshot {
371
+ return this.enqueueSnapshot(snapshot);
372
+ }
373
+
374
+ /** Queue a tool event; repeated partial updates collapse to one write. */
375
+ enqueueToolArtifact(artifact: ToolArtifactWrite): void {
376
+ const current = this.pendingToolArtifacts.get(artifact.toolCallId);
377
+ this.pendingToolArtifacts.set(artifact.toolCallId, mergeToolArtifact(current, artifact));
378
+ this.scheduleDrain();
379
+ }
380
+
381
+ /** Alias for callers that use queue terminology. */
382
+ queueToolArtifact(artifact: ToolArtifactWrite): void {
383
+ this.enqueueToolArtifact(artifact);
384
+ }
385
+
386
+ private scheduleDrain(): void {
387
+ if (this.drainTimer !== null || this.draining) return;
388
+ this.drainTimer = setTimeout(() => {
389
+ this.drainTimer = null;
390
+ this.drainQueue();
391
+ }, DURABLE_WRITE_DEBOUNCE_MS);
392
+ // Pending writes are flushed explicitly by request/shutdown paths. They
393
+ // must not keep a non-interactive process alive on their own.
394
+ this.drainTimer.unref?.();
395
+ }
396
+
397
+ private settleFlushWaiters(error?: unknown): void {
398
+ if (this.flushWaiters.length === 0) return;
399
+ const waiters = this.flushWaiters.splice(0);
400
+ for (const waiter of waiters) {
401
+ if (error === undefined) waiter.resolve();
402
+ else waiter.reject(error);
403
+ }
404
+ }
405
+
406
+ private drainQueue(): void {
407
+ if (this.draining) return;
408
+ if (this.pendingSnapshot === null && this.pendingToolArtifacts.size === 0) {
409
+ this.settleFlushWaiters();
410
+ return;
411
+ }
412
+
413
+ this.draining = true;
414
+ const snapshot = this.pendingSnapshot;
415
+ this.pendingSnapshot = null;
416
+ const artifacts = [...this.pendingToolArtifacts.values()];
417
+ this.pendingToolArtifacts.clear();
418
+ let snapshotCommitted = false;
419
+ let artifactIndex = 0;
420
+
421
+ try {
422
+ if (snapshot) {
423
+ this.appendSnapshotRecord(snapshot);
424
+ snapshotCommitted = true;
425
+ }
426
+ for (; artifactIndex < artifacts.length; artifactIndex++) {
427
+ this.writeToolArtifact(artifacts[artifactIndex]!);
428
+ }
429
+ this.lastWriteError = null;
430
+ this.settleFlushWaiters();
431
+ } catch (error) {
432
+ // Keep failed work available for an explicit retry. If the append threw
433
+ // after writing its bytes, the duplicate is harmless and the locator
434
+ // still resolves to a valid latest record after the retry.
435
+ if (snapshot && !snapshotCommitted && this.pendingSnapshot === null) {
436
+ this.pendingSnapshot = snapshot;
437
+ }
438
+ for (let i = artifactIndex; i < artifacts.length; i++) {
439
+ const artifact = artifacts[i]!;
440
+ this.pendingToolArtifacts.set(
441
+ artifact.toolCallId,
442
+ mergeToolArtifact(this.pendingToolArtifacts.get(artifact.toolCallId), artifact),
443
+ );
444
+ }
445
+ this.lastWriteError = error;
446
+ this.settleFlushWaiters(error);
447
+ } finally {
448
+ this.draining = false;
449
+ if (this.pendingSnapshot !== null || this.pendingToolArtifacts.size > 0) {
450
+ this.scheduleDrain();
451
+ }
452
+ }
453
+ }
454
+
455
+ /** Drain all queued snapshot/artifact writes before a durable boundary. */
456
+ flush(): Promise<void> {
457
+ if (this.drainTimer !== null) {
458
+ clearTimeout(this.drainTimer);
459
+ this.drainTimer = null;
460
+ }
461
+
462
+ if (this.pendingSnapshot === null && this.pendingToolArtifacts.size === 0 && !this.draining) {
463
+ if (this.lastWriteError !== null) {
464
+ const error = this.lastWriteError;
465
+ this.lastWriteError = null;
466
+ return Promise.reject(error);
467
+ }
468
+ return Promise.resolve();
469
+ }
470
+
471
+ const result = new Promise<void>((resolve, reject) => {
472
+ this.flushWaiters.push({ resolve, reject });
473
+ });
474
+ this.drainQueue();
475
+ return result;
476
+ }
477
+
285
478
  readSnapshot(recordId?: string): RestoredTranscript | null {
286
479
  if (!existsSync(this.transcriptPath)) return null;
287
480
  let latest: DurableTranscriptSnapshot | null = null;
@@ -1,5 +1,9 @@
1
+ import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
2
+ import { tmpdir } from "node:os";
3
+ import path from "node:path";
1
4
  import { describe, expect, it } from "vitest";
2
5
  import { BtwOverlayComponent } from "./btw.ts";
6
+ import { BtwTranscriptStore } from "./btw/transcript-store.ts";
3
7
 
4
8
  const theme = {
5
9
  bg: (_name: string, text: string) => text,
@@ -382,6 +386,270 @@ describe("BTW transcript message layout", () => {
382
386
  expect(component.render(80)).toHaveLength(10);
383
387
  });
384
388
 
389
+ it("persists line-delimited snapshots and complete tool artifacts", () => {
390
+ const projectDir = mkdtempSync(path.join(tmpdir(), "pi-btw-store-test-"));
391
+ try {
392
+ const store = new BtwTranscriptStore(projectDir, "session-1");
393
+ const snapshot = store.appendSnapshot({
394
+ mode: "contextual",
395
+ entries: [
396
+ { id: 1, turnId: 1, type: "turn-boundary", phase: "start" },
397
+ { id: 2, turnId: 1, type: "tool-call", toolCallId: "call-1", toolName: "write", args: "{\"path\":\"a\"}" },
398
+ { id: 3, turnId: 1, type: "tool-result", toolCallId: "call-1", toolName: "write", content: "ok", fullContent: "ok", truncated: false, isError: false, streaming: false },
399
+ ],
400
+ nextEntryId: 4,
401
+ nextTurnId: 2,
402
+ currentTurnId: null,
403
+ lastTurnId: 1,
404
+ });
405
+
406
+ expect(readFileSync(store.transcriptPath, "utf8").trim().split(/\r?\n/)).toHaveLength(1);
407
+ expect(store.readSnapshot(snapshot.recordId)?.snapshot.entries).toHaveLength(3);
408
+
409
+ store.writeToolArtifact({
410
+ toolCallId: "call-1",
411
+ toolName: "write",
412
+ phase: "start",
413
+ input: { path: "a" },
414
+ });
415
+ store.writeToolArtifact({
416
+ toolCallId: "call-1",
417
+ toolName: "write",
418
+ phase: "end",
419
+ output: { content: [{ type: "text", text: "ok" }], details: { durationMs: 3, diff: "@@ -1 +1 @@" } },
420
+ });
421
+
422
+ const artifact = store.readToolArtifact("call-1");
423
+ expect(artifact?.input).toEqual({ path: "a" });
424
+ expect(artifact?.details).toEqual({ durationMs: 3, diff: "@@ -1 +1 @@" });
425
+ expect(artifact?.diff).toBe("@@ -1 +1 @@\n");
426
+ } finally {
427
+ rmSync(projectDir, { recursive: true, force: true });
428
+ }
429
+ });
430
+
431
+ it("recovers a valid record appended after an unterminated EOF", () => {
432
+ const projectDir = mkdtempSync(path.join(tmpdir(), "pi-btw-store-eof-test-"));
433
+ try {
434
+ const store = new BtwTranscriptStore(projectDir, "session-eof");
435
+ const base = {
436
+ mode: "contextual" as const,
437
+ entries: [],
438
+ nextEntryId: 1,
439
+ nextTurnId: 1,
440
+ currentTurnId: null,
441
+ lastTurnId: null,
442
+ };
443
+ store.appendSnapshot(base);
444
+ writeFileSync(store.transcriptPath, readFileSync(store.transcriptPath, "utf8").replace(/\n$/, ""));
445
+
446
+ const next = store.appendSnapshot(base);
447
+ const lines = readFileSync(store.transcriptPath, "utf8").trim().split(/\r?\n/);
448
+ expect(lines).toHaveLength(2);
449
+ expect(store.readSnapshot(next.recordId)?.snapshot.recordId).toBe(next.recordId);
450
+ } finally {
451
+ rmSync(projectDir, { recursive: true, force: true });
452
+ }
453
+ });
454
+
455
+ it("coalesces queued snapshots and tool updates until an explicit flush", async () => {
456
+ const projectDir = mkdtempSync(path.join(tmpdir(), "pi-btw-store-queue-test-"));
457
+ try {
458
+ const store = new BtwTranscriptStore(projectDir, "session-queue");
459
+ const first = store.enqueueSnapshot({
460
+ mode: "contextual",
461
+ entries: [],
462
+ nextEntryId: 1,
463
+ nextTurnId: 1,
464
+ currentTurnId: null,
465
+ lastTurnId: null,
466
+ });
467
+ const second = store.enqueueSnapshot({
468
+ mode: "tangent",
469
+ entries: [{ id: 1, turnId: 1, type: "turn-boundary", phase: "start" }],
470
+ nextEntryId: 2,
471
+ nextTurnId: 2,
472
+ currentTurnId: 1,
473
+ lastTurnId: 1,
474
+ });
475
+ store.enqueueToolArtifact({
476
+ toolCallId: "call-queue",
477
+ toolName: "read",
478
+ phase: "start",
479
+ input: { path: "a.txt" },
480
+ });
481
+ store.enqueueToolArtifact({
482
+ toolCallId: "call-queue",
483
+ toolName: "read",
484
+ phase: "update",
485
+ output: { content: [{ type: "text", text: "partial" }] },
486
+ });
487
+ store.enqueueToolArtifact({
488
+ toolCallId: "call-queue",
489
+ toolName: "read",
490
+ phase: "end",
491
+ output: { content: [{ type: "text", text: "complete" }] },
492
+ });
493
+
494
+ expect(existsSync(store.transcriptPath)).toBe(false);
495
+ await store.flush();
496
+
497
+ expect(store.readSnapshot(first.recordId)).toBeNull();
498
+ expect(store.readSnapshot(second.recordId)?.snapshot.mode).toBe("tangent");
499
+ expect(store.readToolArtifact("call-queue")?.input).toEqual({ path: "a.txt" });
500
+ expect(store.readToolArtifact("call-queue")?.output).toEqual({ content: [{ type: "text", text: "complete" }] });
501
+ } finally {
502
+ rmSync(projectDir, { recursive: true, force: true });
503
+ }
504
+ });
505
+
506
+ it("focuses and expands a live tool, scrolls locally, and opens Ctrl+O output", () => {
507
+ const entries = [
508
+ { id: 1, turnId: 1, type: "tool-call", toolCallId: "call-1", toolName: "write", args: "compact input" },
509
+ { id: 2, turnId: 1, type: "tool-result", toolCallId: "call-1", toolName: "write", content: "compact output", fullContent: Array.from({ length: 40 }, (_, index) => `line ${index}`).join("\n"), truncated: true, isError: false, streaming: false },
510
+ ] as any;
511
+ const artifact = {
512
+ toolCallId: "call-1",
513
+ toolName: "write",
514
+ phase: "end" as const,
515
+ isError: false,
516
+ input: { path: "full.txt" },
517
+ output: { content: [{ type: "text", text: "full output" }] },
518
+ details: { durationMs: 3 },
519
+ diff: "@@ -1 +1 @@\n",
520
+ };
521
+ let dismissed = 0;
522
+ const component = new BtwOverlayComponent(
523
+ tui,
524
+ theme,
525
+ keybindings,
526
+ () => entries,
527
+ () => null,
528
+ () => "contextual",
529
+ () => {},
530
+ () => { dismissed++; },
531
+ () => {},
532
+ undefined,
533
+ undefined,
534
+ () => artifact,
535
+ );
536
+
537
+ component.render(80);
538
+ const contentTop = (component as any).transcriptContentTop as number;
539
+ const hostToolRow = contentTop - 1;
540
+ component.handleMouse({ type: "press", button: "left", x: 5, y: hostToolRow } as any);
541
+ component.handleMouse({ type: "release", button: "left", x: 5, y: hostToolRow } as any);
542
+ expect((component as any).liveFocusedToolCallId).toBeNull();
543
+
544
+ component.handleMouse({ type: "move", button: "none", x: 5, y: hostToolRow } as any);
545
+ expect((component as any).liveHoveredEntryId).toBe(1);
546
+ component.handleMouse({ type: "click", button: "left", x: 5, y: hostToolRow } as any);
547
+ expect((component as any).liveFocusedToolCallId).toBe("call-1");
548
+ expect((component as any).liveExpandedToolCallId).toBe("call-1");
549
+ (component as any).followTranscript = false;
550
+ (component as any).transcriptScrollOffset = 0;
551
+ expect(component.render(80).join("\n")).toContain("line 0");
552
+
553
+ component.handleMouse({ type: "wheel", button: "none", x: 5, y: hostToolRow, wheelDelta: 1 } as any);
554
+ expect((component as any).transcriptScrollOffset).toBeGreaterThan(0);
555
+
556
+ component.handleInput("\x0f");
557
+ const output = component.render(80).join("\n");
558
+ expect(output).toContain("BTW Tool Output");
559
+ expect(output).toContain("full.txt");
560
+ expect(output).toContain("durationMs");
561
+ expect(output).toContain("Diff:");
562
+ component.handleInput("\x1b");
563
+ expect((component as any).toolPreviewParent).toBeNull();
564
+ expect(dismissed).toBe(0);
565
+
566
+ component.handleMouse({ type: "click", button: "left", x: 5, y: hostToolRow } as any);
567
+ component.handleMouse({ type: "click", button: "left", clickCount: 2, x: 5, y: hostToolRow } as any);
568
+ expect((component as any).liveExpandedToolCallId).toBeNull();
569
+ });
570
+
571
+ it("shows live partial tool output as STREAMING and updates it in place", () => {
572
+ let entries: any[] = [
573
+ { id: 1, turnId: 1, type: "tool-call", toolCallId: "call-live", toolName: "bash", args: "{\"command\":\"echo hi\"}" },
574
+ { id: 2, turnId: 1, type: "tool-result", toolCallId: "call-live", toolName: "bash", content: "partial output", fullContent: "partial output", truncated: false, isError: false, streaming: true },
575
+ ];
576
+ const component = new BtwOverlayComponent(
577
+ tui,
578
+ theme,
579
+ keybindings,
580
+ () => entries,
581
+ () => null,
582
+ () => "contextual",
583
+ () => {},
584
+ () => {},
585
+ () => {},
586
+ );
587
+
588
+ component.render(80);
589
+ const contentTop = (component as any).transcriptContentTop as number;
590
+ component.handleMouse({ type: "click", button: "left", x: 5, y: contentTop - 1 } as any);
591
+ component.handleInput("\x0f");
592
+ let output = component.render(80).join("\n");
593
+ expect(output).toContain("STREAMING");
594
+ expect(output).toContain("partial output");
595
+ expect(output).toContain("echo hi");
596
+
597
+ entries = [
598
+ entries[0],
599
+ { ...entries[1], content: "final output", fullContent: "final output", streaming: false },
600
+ ];
601
+ output = component.render(80).join("\n");
602
+ expect(output).toContain("final output");
603
+ expect(output).not.toContain("STREAMING");
604
+
605
+ component.handleInput("\x1b");
606
+ expect((component as any).toolPreviewParent).toBeNull();
607
+ });
608
+
609
+ it("consumes Ctrl+O without a focused tool", () => {
610
+ const component = new BtwOverlayComponent(
611
+ tui,
612
+ theme,
613
+ keybindings,
614
+ () => [],
615
+ () => null,
616
+ () => "contextual",
617
+ () => {},
618
+ () => {},
619
+ () => {},
620
+ );
621
+ component.setDraft("keep this draft");
622
+ component.handleInput("\x0f");
623
+
624
+ expect((component as any).toolPreviewParent).toBeNull();
625
+ expect((component as any).input.getText()).toBe("keep this draft");
626
+ });
627
+
628
+ it("marks a focused tool with no result as streaming without inventing output", () => {
629
+ const entries = [
630
+ { id: 1, turnId: 1, type: "tool-call", toolCallId: "call-pending", toolName: "read", args: "{\"path\":\"pending.txt\"}" },
631
+ ];
632
+ const component = new BtwOverlayComponent(
633
+ tui,
634
+ theme,
635
+ keybindings,
636
+ () => entries as any,
637
+ () => null,
638
+ () => "contextual",
639
+ () => {},
640
+ () => {},
641
+ () => {},
642
+ );
643
+ component.render(80);
644
+ const contentTop = (component as any).transcriptContentTop as number;
645
+ component.handleMouse({ type: "click", button: "left", x: 5, y: contentTop - 1 } as any);
646
+ component.handleInput("\x0f");
647
+
648
+ const output = component.render(80).join("\n");
649
+ expect(output).toContain("STREAMING");
650
+ expect(output).toContain("(no output)");
651
+ });
652
+
385
653
  it("keeps Enter and Escape composer behavior outside Peek", () => {
386
654
  let submitted = "";
387
655
  let dismissed = 0;
@@ -408,6 +676,75 @@ describe("BTW transcript message layout", () => {
408
676
  expect(dismissed).toBe(1);
409
677
  });
410
678
 
679
+ it("keeps the title [Esc] affordance visible, highlights it on hover, and closes on click", () => {
680
+ let dismissed = 0;
681
+ const component = new BtwOverlayComponent(
682
+ tui,
683
+ theme,
684
+ keybindings,
685
+ () => [],
686
+ () => null,
687
+ () => "contextual",
688
+ () => {},
689
+ () => { dismissed++; },
690
+ () => {},
691
+ );
692
+
693
+ const lines = component.render(24);
694
+ expect(lines[1]).toMatch(/\[Esc\]│$/);
695
+
696
+ const hover = component.handleMouse({ type: "move", button: "none", x: 20, y: 1 } as any);
697
+ expect((component as any).hoveredEscapeHint).toBe(true);
698
+ expect(hover).toEqual({ handled: true, render: true });
699
+
700
+ const click = component.handleMouse({ type: "click", button: "left", x: 20, y: 1 } as any);
701
+ expect(click).toEqual({ handled: true, render: false });
702
+ expect(dismissed).toBe(1);
703
+ });
704
+
705
+ it("uses the title [Esc] button in Peek as back, not overlay dismissal", () => {
706
+ let dismissed = 0;
707
+ const component = new BtwOverlayComponent(
708
+ tui,
709
+ theme,
710
+ keybindings,
711
+ () => [],
712
+ () => null,
713
+ () => "contextual",
714
+ () => {},
715
+ () => { dismissed++; },
716
+ () => {},
717
+ );
718
+
719
+ component.handleInput("\x10");
720
+ component.render(80);
721
+ component.handleMouse({ type: "click", button: "left", x: 76, y: 1 } as any);
722
+
723
+ expect((component as any).peekState.active).toBe(false);
724
+ expect(dismissed).toBe(0);
725
+ });
726
+
727
+ it("closes from the title [Esc] button through the raw SGR fallback", () => {
728
+ let dismissed = 0;
729
+ const component = new BtwOverlayComponent(
730
+ tui,
731
+ theme,
732
+ keybindings,
733
+ () => [],
734
+ () => null,
735
+ () => "contextual",
736
+ () => {},
737
+ () => { dismissed++; },
738
+ () => {},
739
+ );
740
+
741
+ component.render(80);
742
+ component.handleInput("\x1b[<0;77;2M");
743
+ component.handleInput("\x1b[<0;77;2m");
744
+
745
+ expect(dismissed).toBe(1);
746
+ });
747
+
411
748
  it("configures fd-backed completion for @ path suggestions", () => {
412
749
  const component = new BtwOverlayComponent(
413
750
  tui,
package/extensions/btw.ts CHANGED
@@ -1110,6 +1110,8 @@ function notify(ctx: ExtensionContext | ExtensionCommandContext, message: string
1110
1110
  /** Minimum rows for fixed overlay chrome outside the transcript viewport (without input lines).
1111
1111
  * render() computes the actual value dynamically: chrome = 8 + inputLines. */
1112
1112
  const BTW_OVERLAY_CHROME_BASE = 8;
1113
+ /** Coalesce provider/tool deltas into one render per frame-ish interval. */
1114
+ const BTW_UI_REFRESH_DEBOUNCE_MS = 16;
1113
1115
 
1114
1116
  function getOverlayTitle(mode: BtwThreadMode): string {
1115
1117
  return mode === "tangent" ? "BTW tangent" : "BTW";
@@ -1173,6 +1175,8 @@ export class BtwOverlayComponent extends Container implements Focusable {
1173
1175
  private peekToolPreviewLines: string[] = [];
1174
1176
  private peekToolPreviewScrollOffset = 0;
1175
1177
  private expandedToolId: number | null = null;
1178
+ private hoveredEscapeHint = false;
1179
+ private rawEscapePress = false;
1176
1180
  /** The same bounded preview is used by Peek and by the live BTW panel. */
1177
1181
  private toolPreviewParent: "peek" | "live" | null = null;
1178
1182
  private liveToolPreviewBlock: PeekBlock | null = null;
@@ -1332,9 +1336,17 @@ export class BtwOverlayComponent extends Container implements Focusable {
1332
1336
  }
1333
1337
 
1334
1338
  private titleLine(title: string, innerWidth: number): string {
1335
- const escapeHint = this.theme.fg("dim", "[Esc]");
1336
- const gap = Math.max(1, innerWidth - visibleWidth(title) - visibleWidth(escapeHint));
1337
- return this.frameLine(`${title}${" ".repeat(gap)}${escapeHint}`, innerWidth);
1339
+ const escapeLabel = "[Esc]";
1340
+ const escapeHint = this.hoveredEscapeHint
1341
+ ? this.theme.fg("text", this.theme.bold(escapeLabel))
1342
+ : this.theme.fg("dim", escapeLabel);
1343
+ const escapeWidth = visibleWidth(escapeLabel);
1344
+ // Reserve the close label before truncating the title so a long tool name
1345
+ // can never hide the only visible mouse/keyboard dismissal affordance.
1346
+ const titleWidth = Math.max(0, innerWidth - escapeWidth - 1);
1347
+ const clippedTitle = truncateToWidth(title, titleWidth, "");
1348
+ const gap = Math.max(1, innerWidth - visibleWidth(clippedTitle) - escapeWidth);
1349
+ return this.frameLine(`${clippedTitle}${" ".repeat(gap)}${escapeHint}`, innerWidth);
1338
1350
  }
1339
1351
 
1340
1352
  private wrapTranscript(innerWidth: number): string[] {
@@ -1567,6 +1579,23 @@ export class BtwOverlayComponent extends Container implements Focusable {
1567
1579
  return null;
1568
1580
  }
1569
1581
 
1582
+ /** The title row is line 2 in one-based local coordinates. */
1583
+ private isEscapeHintHit(x: number, y: number): boolean {
1584
+ const labelWidth = visibleWidth("[Esc]");
1585
+ const labelStart = this.lastRenderWidth - labelWidth;
1586
+ return y === 2 && x >= labelStart && x < this.lastRenderWidth;
1587
+ }
1588
+
1589
+ private closeEscapeTarget(): void {
1590
+ if (this.toolPreviewParent !== null) {
1591
+ this.exitToolPreview();
1592
+ } else if (this.peekState.active) {
1593
+ this.exitPeekMode();
1594
+ } else {
1595
+ this.onDismissCallback();
1596
+ }
1597
+ }
1598
+
1570
1599
  /**
1571
1600
  * Viewer-local mouse seam. Newer Pi TUI hosts call `handleMouse` with
1572
1601
  * zero-based `{ type, button, x, y, wheelDelta }` events; older hosts and
@@ -1610,6 +1639,32 @@ export class BtwOverlayComponent extends Container implements Focusable {
1610
1639
  delta: event.wheelDelta,
1611
1640
  };
1612
1641
 
1642
+ const overEscapeHint = this.isEscapeHintHit(normalized.x, normalized.y);
1643
+ if (normalized.action === "move" || normalized.action === "drag") {
1644
+ const hoverChanged = overEscapeHint !== this.hoveredEscapeHint;
1645
+ this.hoveredEscapeHint = overEscapeHint;
1646
+ if (overEscapeHint) {
1647
+ return { handled: true, render: hoverChanged };
1648
+ }
1649
+ // Continue routing a move outside the title to update transcript/block
1650
+ // hover state. In preview mode there is no other hover target.
1651
+ if (hoverChanged && this.toolPreviewParent !== null) {
1652
+ return { handled: true, render: true };
1653
+ }
1654
+ }
1655
+ if (overEscapeHint && normalized.button === 0) {
1656
+ if (normalized.action === "press") {
1657
+ return { handled: true, capture: true, render: false };
1658
+ }
1659
+ if (normalized.action === "click") {
1660
+ this.closeEscapeTarget();
1661
+ return { handled: true, render: false };
1662
+ }
1663
+ if (normalized.action === "release") {
1664
+ return { handled: true, render: false };
1665
+ }
1666
+ }
1667
+
1613
1668
  if (normalized.action === "wheel") {
1614
1669
  const delta = Math.trunc(normalized.delta ?? 0);
1615
1670
  if (this.toolPreviewParent !== null) {
@@ -1719,11 +1774,12 @@ export class BtwOverlayComponent extends Container implements Focusable {
1719
1774
  return;
1720
1775
  }
1721
1776
 
1722
- // Ctrl+O is live-only: it opens the complete immutable input/output of
1723
- // the focused tool without interfering with the composer.
1777
+ // Ctrl+O is live-only: it opens the read-only input/output snapshot of
1778
+ // the focused tool. It is always consumed here, including when no tool is
1779
+ // focused, so the control character can never reach the composer.
1724
1780
  if (matchesKey(data, BTW_TOOL_OUTPUT_SHORTCUT)) {
1725
- this.enterLiveToolPreview();
1726
- if (this.toolPreviewParent === "live") return;
1781
+ if (!this.peekState.active) this.enterLiveToolPreview();
1782
+ return;
1727
1783
  }
1728
1784
 
1729
1785
  const mouseEvent = parsePeekMouseInput(data);
@@ -1738,9 +1794,22 @@ export class BtwOverlayComponent extends Container implements Focusable {
1738
1794
  }
1739
1795
  return;
1740
1796
  }
1741
- // Consume bounded SGR button events locally. Without an explicit host
1742
- // click dispatch, press/release are deliberately no-ops rather than input.
1743
- if (mouseEvent) return;
1797
+ // Consume bounded SGR button events locally. Older hosts do not expose
1798
+ // normalized click dispatch, so retain the close-button press/release
1799
+ // pair as the one actionable fallback; transcript clicks remain read-only.
1800
+ if (mouseEvent) {
1801
+ const overEscapeHint = this.isEscapeHintHit(mouseEvent.x, mouseEvent.y);
1802
+ this.handleMouse(mouseEvent);
1803
+ if (mouseEvent.button === 0 && mouseEvent.action === "press") {
1804
+ this.rawEscapePress = overEscapeHint;
1805
+ } else if (mouseEvent.button === 0 && mouseEvent.action === "release") {
1806
+ const close = this.rawEscapePress && overEscapeHint;
1807
+ this.rawEscapePress = false;
1808
+ if (close) this.closeEscapeTarget();
1809
+ }
1810
+ return;
1811
+ }
1812
+ this.rawEscapePress = false;
1744
1813
 
1745
1814
  // Peek mode active → route all input to peek handler
1746
1815
  if (this.peekState.active) {
@@ -1905,7 +1974,8 @@ export class BtwOverlayComponent extends Container implements Focusable {
1905
1974
  private buildToolPreviewLines(block: PeekBlock, innerWidth: number): string[] {
1906
1975
  // Keep the preview read-only and complete. The viewport, not the data,
1907
1976
  // supplies the bound: only the visible slice is emitted below.
1908
- const text = getToolPreviewText(block);
1977
+ const status = block.streaming ? "Status: STREAMING\n\n" : "";
1978
+ const text = `${status}${getToolPreviewText(block)}`;
1909
1979
  const lines: string[] = [];
1910
1980
  for (const line of text.split("\n")) {
1911
1981
  lines.push(...wrapTextWithAnsi(line, Math.max(1, innerWidth - 4)));
@@ -1931,6 +2001,7 @@ export class BtwOverlayComponent extends Container implements Focusable {
1931
2001
  hydrated.toolOutput = `${hydrated.toolOutput || "(no output)"}\n\nDiff:\n${artifact.diff}`;
1932
2002
  }
1933
2003
  hydrated.toolName = artifact.toolName || hydrated.toolName;
2004
+ hydrated.streaming = artifact.phase !== "end" && !artifact.isError;
1934
2005
  hydrated.isError = hydrated.isError || artifact.isError;
1935
2006
  return hydrated;
1936
2007
  }
@@ -1991,7 +2062,8 @@ export class BtwOverlayComponent extends Container implements Focusable {
1991
2062
  Math.min(this.peekToolPreviewScrollOffset, maxScroll),
1992
2063
  );
1993
2064
 
1994
- const title = `BTW Tool Output · ${getSemanticBlockLabel(block)} · read-only`;
2065
+ const streamingLabel = block.streaming ? " · STREAMING" : "";
2066
+ const title = `BTW Tool Output · ${getSemanticBlockLabel(block)}${streamingLabel} · read-only`;
1995
2067
  const lines = [
1996
2068
  this.borderLine(innerWidth, "top"),
1997
2069
  this.titleLine(this.theme.fg("accent", this.theme.bold(title)), innerWidth),
@@ -2754,8 +2826,21 @@ export default function (pi: ExtensionAPI) {
2754
2826
  let lastUiContext: ExtensionContext | ExtensionCommandContext | null = null;
2755
2827
  let activeBtwSession: BtwSessionRuntime | null = null;
2756
2828
  let btwStore: BtwTranscriptStore | null = null;
2829
+ /** The locator is published only after its snapshot reaches the store. */
2830
+ let queuedTranscriptSnapshot: DurableTranscriptSnapshot | null = null;
2831
+ let uiRefreshTimer: ReturnType<typeof setTimeout> | null = null;
2832
+ let uiRefreshContext: ExtensionContext | ExtensionCommandContext | null = null;
2833
+
2834
+ function cancelScheduledUiRefresh(): void {
2835
+ if (uiRefreshTimer !== null) {
2836
+ clearTimeout(uiRefreshTimer);
2837
+ uiRefreshTimer = null;
2838
+ }
2839
+ uiRefreshContext = null;
2840
+ }
2757
2841
 
2758
2842
  function syncUi(ctx?: ExtensionContext | ExtensionCommandContext): void {
2843
+ cancelScheduledUiRefresh();
2759
2844
  const activeCtx = ctx ?? lastUiContext;
2760
2845
  if (activeCtx?.hasUI) {
2761
2846
  activeCtx.ui.setWidget("btw", undefined);
@@ -2763,6 +2848,27 @@ export default function (pi: ExtensionAPI) {
2763
2848
  }
2764
2849
  }
2765
2850
 
2851
+ /**
2852
+ * Stable seam for live partial UI: transcript state is updated immediately,
2853
+ * while rendering is debounced so message/tool deltas share one refresh.
2854
+ */
2855
+ function scheduleUiRefresh(ctx?: ExtensionContext | ExtensionCommandContext): void {
2856
+ if (ctx) {
2857
+ lastUiContext = ctx;
2858
+ uiRefreshContext = ctx;
2859
+ } else if (!uiRefreshContext) {
2860
+ uiRefreshContext = lastUiContext;
2861
+ }
2862
+ if (uiRefreshTimer !== null) return;
2863
+ uiRefreshTimer = setTimeout(() => {
2864
+ uiRefreshTimer = null;
2865
+ const refreshContext = uiRefreshContext;
2866
+ uiRefreshContext = null;
2867
+ syncUi(refreshContext ?? undefined);
2868
+ }, BTW_UI_REFRESH_DEBOUNCE_MS);
2869
+ uiRefreshTimer.unref?.();
2870
+ }
2871
+
2766
2872
  function setOverlayStatus(status: string | null, ctx?: ExtensionContext | ExtensionCommandContext): void {
2767
2873
  overlayStatus = status;
2768
2874
  syncUi(ctx);
@@ -2779,7 +2885,11 @@ export default function (pi: ExtensionAPI) {
2779
2885
  function persistTranscriptState(): void {
2780
2886
  if (!btwStore) return;
2781
2887
  try {
2782
- const snapshot = btwStore.appendSnapshot({
2888
+ // Event callbacks only enqueue. The synchronous filesystem work happens
2889
+ // in the store's debounced drain, and only the newest state needs a
2890
+ // locator because snapshots are immutable and restore follows the last
2891
+ // locator on this branch.
2892
+ queuedTranscriptSnapshot = btwStore.enqueueSnapshot({
2783
2893
  mode: pendingMode,
2784
2894
  entries: transcriptState.entries as unknown as DurableTranscriptSnapshot["entries"],
2785
2895
  nextEntryId: transcriptState.nextEntryId,
@@ -2787,20 +2897,47 @@ export default function (pi: ExtensionAPI) {
2787
2897
  currentTurnId: transcriptState.currentTurnId,
2788
2898
  lastTurnId: transcriptState.lastTurnId,
2789
2899
  });
2790
- // Keep only a small, immutable locator in the Pi session. Large tool
2791
- // payloads remain in .pi-subagents/btw and never enter LLM context.
2792
- pi.appendEntry(BTW_TRANSCRIPT_TYPE, makeTranscriptLocator(btwStore, snapshot));
2793
2900
  } catch {
2794
2901
  // Durable BTW storage is best effort. The in-memory transcript remains
2795
2902
  // authoritative for the current overlay when a filesystem is unavailable.
2796
2903
  }
2797
2904
  }
2798
2905
 
2906
+ /**
2907
+ * Publish the latest locator only after queued writes are durable. This is
2908
+ * used at request completion, abort/error handling, reset, and shutdown.
2909
+ */
2910
+ async function flushTranscriptState(): Promise<void> {
2911
+ const store = btwStore;
2912
+ if (!store) return;
2913
+ try {
2914
+ await store.flush();
2915
+ } catch {
2916
+ // Keep the in-memory transcript authoritative and leave failed writes in
2917
+ // the store queue for a later boundary/retry.
2918
+ return;
2919
+ }
2920
+
2921
+ const snapshot = queuedTranscriptSnapshot;
2922
+ if (!snapshot || store !== btwStore) return;
2923
+ try {
2924
+ // Keep only a small, immutable locator in the Pi session. Large tool
2925
+ // payloads remain in .pi-subagents/btw and never enter LLM context.
2926
+ pi.appendEntry(BTW_TRANSCRIPT_TYPE, makeTranscriptLocator(store, snapshot));
2927
+ if (queuedTranscriptSnapshot === snapshot) {
2928
+ queuedTranscriptSnapshot = null;
2929
+ }
2930
+ } catch {
2931
+ // The snapshot remains durable even if the host rejects the locator;
2932
+ // retrying at the next boundary keeps branch restoration best effort.
2933
+ }
2934
+ }
2935
+
2799
2936
  function persistToolArtifact(event: AgentSessionEvent): void {
2800
2937
  if (!btwStore) return;
2801
2938
  try {
2802
2939
  if (event.type === "tool_execution_start") {
2803
- btwStore.writeToolArtifact({
2940
+ btwStore.enqueueToolArtifact({
2804
2941
  toolCallId: event.toolCallId,
2805
2942
  toolName: event.toolName,
2806
2943
  phase: "start",
@@ -2808,7 +2945,7 @@ export default function (pi: ExtensionAPI) {
2808
2945
  isError: false,
2809
2946
  });
2810
2947
  } else if (event.type === "tool_execution_update") {
2811
- btwStore.writeToolArtifact({
2948
+ btwStore.enqueueToolArtifact({
2812
2949
  toolCallId: event.toolCallId,
2813
2950
  toolName: event.toolName,
2814
2951
  phase: "update",
@@ -2816,7 +2953,7 @@ export default function (pi: ExtensionAPI) {
2816
2953
  isError: false,
2817
2954
  });
2818
2955
  } else if (event.type === "tool_execution_end") {
2819
- btwStore.writeToolArtifact({
2956
+ btwStore.enqueueToolArtifact({
2820
2957
  toolCallId: event.toolCallId,
2821
2958
  toolName: event.toolName,
2822
2959
  phase: "end",
@@ -2836,6 +2973,7 @@ export default function (pi: ExtensionAPI) {
2836
2973
  }
2837
2974
 
2838
2975
  function dismissOverlay(): void {
2976
+ cancelScheduledUiRefresh();
2839
2977
  overlayRuntime?.close?.();
2840
2978
  overlayRuntime = null;
2841
2979
  }
@@ -2920,9 +3058,12 @@ export default function (pi: ExtensionAPI) {
2920
3058
  event.type === "message_start" ||
2921
3059
  event.type === "message_update" ||
2922
3060
  event.type === "message_end" ||
3061
+ event.type === "tool_execution_update" ||
2923
3062
  event.type === "turn_start"
2924
3063
  ) {
2925
- syncUi(ctx);
3064
+ // Partial assistant/tool events can arrive at token cadence. State is
3065
+ // already current; only the presentation is coalesced.
3066
+ scheduleUiRefresh(ctx);
2926
3067
  }
2927
3068
  }
2928
3069
 
@@ -2942,6 +3083,7 @@ export default function (pi: ExtensionAPI) {
2942
3083
  const current = activeBtwSession;
2943
3084
  activeBtwSession = null;
2944
3085
  if (!current) {
3086
+ await flushTranscriptState();
2945
3087
  return;
2946
3088
  }
2947
3089
 
@@ -2954,6 +3096,10 @@ export default function (pi: ExtensionAPI) {
2954
3096
  }
2955
3097
 
2956
3098
  current.session.dispose();
3099
+ // Subscription removal intentionally prevents abort-generated events from
3100
+ // mutating a replacement session. The already queued state still needs an
3101
+ // explicit durable boundary.
3102
+ await flushTranscriptState();
2957
3103
  }
2958
3104
 
2959
3105
  async function dismissOverlaySession(): Promise<void> {
@@ -3466,6 +3612,7 @@ export default function (pi: ExtensionAPI) {
3466
3612
  transcriptState = createEmptyTranscriptState();
3467
3613
  ensureBtwStore(ctx);
3468
3614
  persistTranscriptState();
3615
+ await flushTranscriptState();
3469
3616
  setOverlayDraft("");
3470
3617
  setOverlayStatus(null, ctx);
3471
3618
  if (persist) {
@@ -3486,6 +3633,7 @@ export default function (pi: ExtensionAPI) {
3486
3633
  lastUiContext = ctx;
3487
3634
  overlayStatus = null;
3488
3635
  btwStore = new BtwTranscriptStore(ctx.cwd, ctx.sessionManager.getSessionId());
3636
+ queuedTranscriptSnapshot = null;
3489
3637
 
3490
3638
  const branch = ctx.sessionManager.getBranch();
3491
3639
  let lastResetIndex = -1;
@@ -3555,6 +3703,7 @@ export default function (pi: ExtensionAPI) {
3555
3703
  // Make the recovery durable immediately so another reload observes the
3556
3704
  // same closed historical turn instead of reviving a dead stream.
3557
3705
  persistTranscriptState();
3706
+ await flushTranscriptState();
3558
3707
  }
3559
3708
  }
3560
3709
 
@@ -3586,7 +3735,11 @@ export default function (pi: ExtensionAPI) {
3586
3735
  // after restore, while current sessions retain the exact persisted state.
3587
3736
  if (!restored && pendingThread.length > 0) {
3588
3737
  persistTranscriptState();
3738
+ await flushTranscriptState();
3589
3739
  }
3740
+ // Also drain a recovery snapshot if the branch had one but no legacy
3741
+ // entries; restore must never return with a locator still only in memory.
3742
+ await flushTranscriptState();
3590
3743
  syncUi(ctx);
3591
3744
  }
3592
3745
 
@@ -3641,6 +3794,7 @@ export default function (pi: ExtensionAPI) {
3641
3794
  if (response.stopReason === "aborted") {
3642
3795
  removeTranscriptTurn(transcriptState, transcriptState.lastTurnId ?? transcriptState.currentTurnId);
3643
3796
  persistTranscriptState();
3797
+ await flushTranscriptState();
3644
3798
  setOverlayStatus("Request aborted.", ctx);
3645
3799
  return;
3646
3800
  }
@@ -3670,6 +3824,7 @@ export default function (pi: ExtensionAPI) {
3670
3824
  pendingThread.push(details);
3671
3825
  pi.appendEntry(BTW_ENTRY_TYPE, details);
3672
3826
  persistTranscriptState();
3827
+ await flushTranscriptState();
3673
3828
 
3674
3829
  const saveState = saveVisibleBtwNote(pi, details, saveRequested, wasBusy);
3675
3830
  if (saveState === "saved") {
@@ -3685,6 +3840,7 @@ export default function (pi: ExtensionAPI) {
3685
3840
  const errorMessage = error instanceof Error ? error.message : String(error);
3686
3841
  setTranscriptFailure(transcriptState, errorMessage);
3687
3842
  persistTranscriptState();
3843
+ await flushTranscriptState();
3688
3844
  setOverlayStatus("Request failed. Thread preserved for retry or follow-up.", ctx);
3689
3845
  notify(ctx, errorMessage, "error");
3690
3846
  await disposeBtwSession();
@@ -3808,7 +3964,9 @@ export default function (pi: ExtensionAPI) {
3808
3964
  });
3809
3965
 
3810
3966
  pi.on("session_shutdown", async () => {
3967
+ cancelScheduledUiRefresh();
3811
3968
  await disposeBtwSession();
3969
+ await flushTranscriptState();
3812
3970
  dismissOverlay();
3813
3971
  });
3814
3972
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-render-btw",
3
- "version": "0.6.11",
3
+ "version": "0.6.13",
4
4
  "description": "A pi extension for parallel side conversations with /btw — with markdown rendering in the floating window",
5
5
  "type": "module",
6
6
  "license": "MIT",