pi-render-btw 0.6.11 → 0.6.12

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,13 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.6.12 — 2026-09-13
4
+
5
+ - Recover interrupted streaming turns as closed history after reload.
6
+ - Rehydrate read-only Peek and live Tool Output from durable artifact details and diffs.
7
+ - Expand regression coverage for durable storage and live tool interactions.
8
+ - 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.
9
+ - 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.
10
+
3
11
  ## 0.6.11 — 2026-09-13
4
12
 
5
13
  - 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]`
@@ -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;
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";
@@ -1719,11 +1721,12 @@ export class BtwOverlayComponent extends Container implements Focusable {
1719
1721
  return;
1720
1722
  }
1721
1723
 
1722
- // Ctrl+O is live-only: it opens the complete immutable input/output of
1723
- // the focused tool without interfering with the composer.
1724
+ // Ctrl+O is live-only: it opens the read-only input/output snapshot of
1725
+ // the focused tool. It is always consumed here, including when no tool is
1726
+ // focused, so the control character can never reach the composer.
1724
1727
  if (matchesKey(data, BTW_TOOL_OUTPUT_SHORTCUT)) {
1725
- this.enterLiveToolPreview();
1726
- if (this.toolPreviewParent === "live") return;
1728
+ if (!this.peekState.active) this.enterLiveToolPreview();
1729
+ return;
1727
1730
  }
1728
1731
 
1729
1732
  const mouseEvent = parsePeekMouseInput(data);
@@ -1905,7 +1908,8 @@ export class BtwOverlayComponent extends Container implements Focusable {
1905
1908
  private buildToolPreviewLines(block: PeekBlock, innerWidth: number): string[] {
1906
1909
  // Keep the preview read-only and complete. The viewport, not the data,
1907
1910
  // supplies the bound: only the visible slice is emitted below.
1908
- const text = getToolPreviewText(block);
1911
+ const status = block.streaming ? "Status: STREAMING\n\n" : "";
1912
+ const text = `${status}${getToolPreviewText(block)}`;
1909
1913
  const lines: string[] = [];
1910
1914
  for (const line of text.split("\n")) {
1911
1915
  lines.push(...wrapTextWithAnsi(line, Math.max(1, innerWidth - 4)));
@@ -1931,6 +1935,7 @@ export class BtwOverlayComponent extends Container implements Focusable {
1931
1935
  hydrated.toolOutput = `${hydrated.toolOutput || "(no output)"}\n\nDiff:\n${artifact.diff}`;
1932
1936
  }
1933
1937
  hydrated.toolName = artifact.toolName || hydrated.toolName;
1938
+ hydrated.streaming = artifact.phase !== "end" && !artifact.isError;
1934
1939
  hydrated.isError = hydrated.isError || artifact.isError;
1935
1940
  return hydrated;
1936
1941
  }
@@ -1991,7 +1996,8 @@ export class BtwOverlayComponent extends Container implements Focusable {
1991
1996
  Math.min(this.peekToolPreviewScrollOffset, maxScroll),
1992
1997
  );
1993
1998
 
1994
- const title = `BTW Tool Output · ${getSemanticBlockLabel(block)} · read-only`;
1999
+ const streamingLabel = block.streaming ? " · STREAMING" : "";
2000
+ const title = `BTW Tool Output · ${getSemanticBlockLabel(block)}${streamingLabel} · read-only`;
1995
2001
  const lines = [
1996
2002
  this.borderLine(innerWidth, "top"),
1997
2003
  this.titleLine(this.theme.fg("accent", this.theme.bold(title)), innerWidth),
@@ -2754,8 +2760,21 @@ export default function (pi: ExtensionAPI) {
2754
2760
  let lastUiContext: ExtensionContext | ExtensionCommandContext | null = null;
2755
2761
  let activeBtwSession: BtwSessionRuntime | null = null;
2756
2762
  let btwStore: BtwTranscriptStore | null = null;
2763
+ /** The locator is published only after its snapshot reaches the store. */
2764
+ let queuedTranscriptSnapshot: DurableTranscriptSnapshot | null = null;
2765
+ let uiRefreshTimer: ReturnType<typeof setTimeout> | null = null;
2766
+ let uiRefreshContext: ExtensionContext | ExtensionCommandContext | null = null;
2767
+
2768
+ function cancelScheduledUiRefresh(): void {
2769
+ if (uiRefreshTimer !== null) {
2770
+ clearTimeout(uiRefreshTimer);
2771
+ uiRefreshTimer = null;
2772
+ }
2773
+ uiRefreshContext = null;
2774
+ }
2757
2775
 
2758
2776
  function syncUi(ctx?: ExtensionContext | ExtensionCommandContext): void {
2777
+ cancelScheduledUiRefresh();
2759
2778
  const activeCtx = ctx ?? lastUiContext;
2760
2779
  if (activeCtx?.hasUI) {
2761
2780
  activeCtx.ui.setWidget("btw", undefined);
@@ -2763,6 +2782,27 @@ export default function (pi: ExtensionAPI) {
2763
2782
  }
2764
2783
  }
2765
2784
 
2785
+ /**
2786
+ * Stable seam for live partial UI: transcript state is updated immediately,
2787
+ * while rendering is debounced so message/tool deltas share one refresh.
2788
+ */
2789
+ function scheduleUiRefresh(ctx?: ExtensionContext | ExtensionCommandContext): void {
2790
+ if (ctx) {
2791
+ lastUiContext = ctx;
2792
+ uiRefreshContext = ctx;
2793
+ } else if (!uiRefreshContext) {
2794
+ uiRefreshContext = lastUiContext;
2795
+ }
2796
+ if (uiRefreshTimer !== null) return;
2797
+ uiRefreshTimer = setTimeout(() => {
2798
+ uiRefreshTimer = null;
2799
+ const refreshContext = uiRefreshContext;
2800
+ uiRefreshContext = null;
2801
+ syncUi(refreshContext ?? undefined);
2802
+ }, BTW_UI_REFRESH_DEBOUNCE_MS);
2803
+ uiRefreshTimer.unref?.();
2804
+ }
2805
+
2766
2806
  function setOverlayStatus(status: string | null, ctx?: ExtensionContext | ExtensionCommandContext): void {
2767
2807
  overlayStatus = status;
2768
2808
  syncUi(ctx);
@@ -2779,7 +2819,11 @@ export default function (pi: ExtensionAPI) {
2779
2819
  function persistTranscriptState(): void {
2780
2820
  if (!btwStore) return;
2781
2821
  try {
2782
- const snapshot = btwStore.appendSnapshot({
2822
+ // Event callbacks only enqueue. The synchronous filesystem work happens
2823
+ // in the store's debounced drain, and only the newest state needs a
2824
+ // locator because snapshots are immutable and restore follows the last
2825
+ // locator on this branch.
2826
+ queuedTranscriptSnapshot = btwStore.enqueueSnapshot({
2783
2827
  mode: pendingMode,
2784
2828
  entries: transcriptState.entries as unknown as DurableTranscriptSnapshot["entries"],
2785
2829
  nextEntryId: transcriptState.nextEntryId,
@@ -2787,20 +2831,47 @@ export default function (pi: ExtensionAPI) {
2787
2831
  currentTurnId: transcriptState.currentTurnId,
2788
2832
  lastTurnId: transcriptState.lastTurnId,
2789
2833
  });
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
2834
  } catch {
2794
2835
  // Durable BTW storage is best effort. The in-memory transcript remains
2795
2836
  // authoritative for the current overlay when a filesystem is unavailable.
2796
2837
  }
2797
2838
  }
2798
2839
 
2840
+ /**
2841
+ * Publish the latest locator only after queued writes are durable. This is
2842
+ * used at request completion, abort/error handling, reset, and shutdown.
2843
+ */
2844
+ async function flushTranscriptState(): Promise<void> {
2845
+ const store = btwStore;
2846
+ if (!store) return;
2847
+ try {
2848
+ await store.flush();
2849
+ } catch {
2850
+ // Keep the in-memory transcript authoritative and leave failed writes in
2851
+ // the store queue for a later boundary/retry.
2852
+ return;
2853
+ }
2854
+
2855
+ const snapshot = queuedTranscriptSnapshot;
2856
+ if (!snapshot || store !== btwStore) return;
2857
+ try {
2858
+ // Keep only a small, immutable locator in the Pi session. Large tool
2859
+ // payloads remain in .pi-subagents/btw and never enter LLM context.
2860
+ pi.appendEntry(BTW_TRANSCRIPT_TYPE, makeTranscriptLocator(store, snapshot));
2861
+ if (queuedTranscriptSnapshot === snapshot) {
2862
+ queuedTranscriptSnapshot = null;
2863
+ }
2864
+ } catch {
2865
+ // The snapshot remains durable even if the host rejects the locator;
2866
+ // retrying at the next boundary keeps branch restoration best effort.
2867
+ }
2868
+ }
2869
+
2799
2870
  function persistToolArtifact(event: AgentSessionEvent): void {
2800
2871
  if (!btwStore) return;
2801
2872
  try {
2802
2873
  if (event.type === "tool_execution_start") {
2803
- btwStore.writeToolArtifact({
2874
+ btwStore.enqueueToolArtifact({
2804
2875
  toolCallId: event.toolCallId,
2805
2876
  toolName: event.toolName,
2806
2877
  phase: "start",
@@ -2808,7 +2879,7 @@ export default function (pi: ExtensionAPI) {
2808
2879
  isError: false,
2809
2880
  });
2810
2881
  } else if (event.type === "tool_execution_update") {
2811
- btwStore.writeToolArtifact({
2882
+ btwStore.enqueueToolArtifact({
2812
2883
  toolCallId: event.toolCallId,
2813
2884
  toolName: event.toolName,
2814
2885
  phase: "update",
@@ -2816,7 +2887,7 @@ export default function (pi: ExtensionAPI) {
2816
2887
  isError: false,
2817
2888
  });
2818
2889
  } else if (event.type === "tool_execution_end") {
2819
- btwStore.writeToolArtifact({
2890
+ btwStore.enqueueToolArtifact({
2820
2891
  toolCallId: event.toolCallId,
2821
2892
  toolName: event.toolName,
2822
2893
  phase: "end",
@@ -2836,6 +2907,7 @@ export default function (pi: ExtensionAPI) {
2836
2907
  }
2837
2908
 
2838
2909
  function dismissOverlay(): void {
2910
+ cancelScheduledUiRefresh();
2839
2911
  overlayRuntime?.close?.();
2840
2912
  overlayRuntime = null;
2841
2913
  }
@@ -2920,9 +2992,12 @@ export default function (pi: ExtensionAPI) {
2920
2992
  event.type === "message_start" ||
2921
2993
  event.type === "message_update" ||
2922
2994
  event.type === "message_end" ||
2995
+ event.type === "tool_execution_update" ||
2923
2996
  event.type === "turn_start"
2924
2997
  ) {
2925
- syncUi(ctx);
2998
+ // Partial assistant/tool events can arrive at token cadence. State is
2999
+ // already current; only the presentation is coalesced.
3000
+ scheduleUiRefresh(ctx);
2926
3001
  }
2927
3002
  }
2928
3003
 
@@ -2942,6 +3017,7 @@ export default function (pi: ExtensionAPI) {
2942
3017
  const current = activeBtwSession;
2943
3018
  activeBtwSession = null;
2944
3019
  if (!current) {
3020
+ await flushTranscriptState();
2945
3021
  return;
2946
3022
  }
2947
3023
 
@@ -2954,6 +3030,10 @@ export default function (pi: ExtensionAPI) {
2954
3030
  }
2955
3031
 
2956
3032
  current.session.dispose();
3033
+ // Subscription removal intentionally prevents abort-generated events from
3034
+ // mutating a replacement session. The already queued state still needs an
3035
+ // explicit durable boundary.
3036
+ await flushTranscriptState();
2957
3037
  }
2958
3038
 
2959
3039
  async function dismissOverlaySession(): Promise<void> {
@@ -3466,6 +3546,7 @@ export default function (pi: ExtensionAPI) {
3466
3546
  transcriptState = createEmptyTranscriptState();
3467
3547
  ensureBtwStore(ctx);
3468
3548
  persistTranscriptState();
3549
+ await flushTranscriptState();
3469
3550
  setOverlayDraft("");
3470
3551
  setOverlayStatus(null, ctx);
3471
3552
  if (persist) {
@@ -3486,6 +3567,7 @@ export default function (pi: ExtensionAPI) {
3486
3567
  lastUiContext = ctx;
3487
3568
  overlayStatus = null;
3488
3569
  btwStore = new BtwTranscriptStore(ctx.cwd, ctx.sessionManager.getSessionId());
3570
+ queuedTranscriptSnapshot = null;
3489
3571
 
3490
3572
  const branch = ctx.sessionManager.getBranch();
3491
3573
  let lastResetIndex = -1;
@@ -3555,6 +3637,7 @@ export default function (pi: ExtensionAPI) {
3555
3637
  // Make the recovery durable immediately so another reload observes the
3556
3638
  // same closed historical turn instead of reviving a dead stream.
3557
3639
  persistTranscriptState();
3640
+ await flushTranscriptState();
3558
3641
  }
3559
3642
  }
3560
3643
 
@@ -3586,7 +3669,11 @@ export default function (pi: ExtensionAPI) {
3586
3669
  // after restore, while current sessions retain the exact persisted state.
3587
3670
  if (!restored && pendingThread.length > 0) {
3588
3671
  persistTranscriptState();
3672
+ await flushTranscriptState();
3589
3673
  }
3674
+ // Also drain a recovery snapshot if the branch had one but no legacy
3675
+ // entries; restore must never return with a locator still only in memory.
3676
+ await flushTranscriptState();
3590
3677
  syncUi(ctx);
3591
3678
  }
3592
3679
 
@@ -3641,6 +3728,7 @@ export default function (pi: ExtensionAPI) {
3641
3728
  if (response.stopReason === "aborted") {
3642
3729
  removeTranscriptTurn(transcriptState, transcriptState.lastTurnId ?? transcriptState.currentTurnId);
3643
3730
  persistTranscriptState();
3731
+ await flushTranscriptState();
3644
3732
  setOverlayStatus("Request aborted.", ctx);
3645
3733
  return;
3646
3734
  }
@@ -3670,6 +3758,7 @@ export default function (pi: ExtensionAPI) {
3670
3758
  pendingThread.push(details);
3671
3759
  pi.appendEntry(BTW_ENTRY_TYPE, details);
3672
3760
  persistTranscriptState();
3761
+ await flushTranscriptState();
3673
3762
 
3674
3763
  const saveState = saveVisibleBtwNote(pi, details, saveRequested, wasBusy);
3675
3764
  if (saveState === "saved") {
@@ -3685,6 +3774,7 @@ export default function (pi: ExtensionAPI) {
3685
3774
  const errorMessage = error instanceof Error ? error.message : String(error);
3686
3775
  setTranscriptFailure(transcriptState, errorMessage);
3687
3776
  persistTranscriptState();
3777
+ await flushTranscriptState();
3688
3778
  setOverlayStatus("Request failed. Thread preserved for retry or follow-up.", ctx);
3689
3779
  notify(ctx, errorMessage, "error");
3690
3780
  await disposeBtwSession();
@@ -3808,7 +3898,9 @@ export default function (pi: ExtensionAPI) {
3808
3898
  });
3809
3899
 
3810
3900
  pi.on("session_shutdown", async () => {
3901
+ cancelScheduledUiRefresh();
3811
3902
  await disposeBtwSession();
3903
+ await flushTranscriptState();
3812
3904
  dismissOverlay();
3813
3905
  });
3814
3906
 
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.12",
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",