@narumitw/pi-btw 0.62.0 → 0.63.1

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.
@@ -4,7 +4,15 @@
4
4
 
5
5
  BTW keeps its side-thread policy separate from Pi's renderer and Kit's shared screens.
6
6
  Local improvements do not remove the need for a public Pi workspace API.
7
- The contracts below are proposals, not available Pi APIs. No external issue, core change, or publication is implied.
7
+ The upstream Pi contracts below are proposals, not available Pi APIs. No external issue, core change, or publication is implied.
8
+
9
+ ## Shared physical handoff extraction
10
+
11
+ The Kit `createFullscreenHandoff()` resource shares only terminal entry, native drain, stop/start, owned-overlay hiding, and restoration. BTW retains its multi-screen context adapter, private split-pane layout integration, input priority, paste handling, selection/copy, root cancellation, main-thread updates, bring-to-main, and queued settings writes.
12
+
13
+ The [retained shared matrix and verification record](https://github.com/narumiruna/pi-extensions/blob/main/packages/pi-tui-kit/docs/fullscreen-handoff.md) records two-consumer admission with Starship, lifecycle regressions, artifact and PTY smokes, dependency propagation, and exact-artifact release guards. Historical checks below do not replace the shared resource's evidence. The proposed Pi workspace-composition API remains necessary.
14
+
15
+ Pi's official [TUI guidance](https://github.com/earendil-works/pi/blob/main/packages/coding-agent/docs/tui.md) advises against a second terminal renderer. BTW intentionally deviates: a second TUI instance exists, but only one renderer actively owns the shared terminal. Extracting the physical lifecycle into Kit does not make that deviation officially supported or remove private layout access from BTW.
8
16
 
9
17
  ## Evidence boundary
10
18
 
@@ -242,7 +250,7 @@ These steps define contract tests, not instructions to open a live provider or i
242
250
 
243
251
  The Pi core maintainer owns API design, implementation, tests, and publication after repository-owner approval.
244
252
  A later authorized BTW migration must pass the existing native-dispatch and terminal-restoration regressions before removing the workaround.
245
- No new Kit API or raised BTW dependency floor is required for this handoff.
253
+ No new Kit API or raised BTW dependency floor was required for that upstream API proposal. The separate shared physical-handoff extraction above must require the Kit release that first contains its API before dependent publication.
246
254
 
247
255
  ## Verification and remaining acceptance
248
256
 
@@ -0,0 +1,45 @@
1
+ # Manual main-context import: runtime audit
2
+
3
+ [Workflow](./workflows.md#import-main-updates)
4
+
5
+ Manual import reads finalized main-session entries and appends a quoted background message to the side conversation. It does not navigate the main tree, submit a main message, stop main work, execute tools, or call a provider at confirmation time.
6
+
7
+ ## Authoritative runtime decisions
8
+
9
+ The installed Pi implementation is authoritative for the following decisions. Dependency versions come from the workspace manifests and lockfile.
10
+
11
+ | Runtime source | Relevant behavior | Import policy |
12
+ | --- | --- | --- |
13
+ | `pi-coding-agent/dist/core/agent-session.js`, `_handleAgentEvent()` | Extension and public `message_end` notifications run before `SessionManager.appendMessage()`. User, assistant, system, and tool-result messages are appended; custom messages use a separate entry type. | Read the session tree, not event payloads. Notifications request rendering only; they never commit an import. |
14
+ | `pi-coding-agent/dist/core/session-manager.js`, `getBranch()` | Walks parent IDs from the selected/current leaf; returns all entry types in source order, not the compaction-aware model projection. | Capture initial text and the last entry ID from the same synchronous branch read. Require the cursor and preview target to remain ancestors of the current leaf. |
15
+ | `pi-agent-core/dist/agent-loop.js`, `runLoop()` | Finalized error/aborted assistant responses finish the turn with no tool execution. Length-limited tool calls receive synthetic failed results instead of execution. Other completed responses can execute their calls. | Preserve response status in text. Do not wait for results from calls in error/aborted responses; wait for synthetic results from length-limited calls. |
16
+ | `pi-agent-core/dist/agent-loop.js`, tool execution and `emitToolResultMessage()` | Tool calls can execute in parallel; each final result emits message start/end. `turn_end` follows all final tool results. | Track outstanding tool-call IDs and advance only through a complete batch. Include final textual results, including error results, in actual append order. Do not use partial tool events. |
17
+ | `pi-coding-agent/dist/core/session-manager.js`, context projection and append methods | Compaction, branch summaries, and context edits change interpretation without removing all raw historical entries. | Reject any such boundary after the cursor, including one added during preview. A newly created source after a boundary uses the existing initial-context policy and starts a new import range. |
18
+
19
+ Streaming assistant deltas never enter the import snapshot. The normal runtime does not persist `pending` stream messages, but restored `pending` entries and `deferred` provider handles are treated as incomplete barriers: only earlier complete entries are eligible, and the cursor does not cross the barrier. A new side thread can use a later completed source. A finalized aborted or failed response can contain partial text; its status remains visible and no success is inferred. Pending tool batches can coexist with earlier complete entries: those earlier entries can be imported, and the pending batch remains available for a later import. A source selected between a call and its results still waits for all outstanding results.
20
+
21
+ User and assistant text, tool-call arguments, and standalone tool-result text are eligible. Thinking, image data, system messages, custom messages, and non-message state are not. Initial context retains its established extraction policy, including exclusion of standalone tool-result messages. Incremental imports deliberately add standalone tool evidence; they do not change that initial policy.
22
+
23
+ The cursor is scoped by the source session ID and the session-owned in-memory thread. Empty roots use a null entry ID. A missing cursor, an ancestor/sibling navigation that removes it, or a different session rejects import. The extension lifetime additionally aborts work on session replacement and reload.
24
+
25
+ ## Publication and request ordering
26
+
27
+ Preview data is fixed before awaiting the UI. Confirmation rechecks cancellation, session-manager ownership, source identity, current branch compatibility, side-turn count, and update count. It then commits the immutable text payload and target cursor synchronously. A duplicate or stale confirmation cannot append another update. Preview failure and cancellation leave the cursor unchanged.
28
+
29
+ Updates are separate records indexed by their position among existing side turns. Errors remain display-only. Imports are not side answers, do not enter Q&A export scopes, and do not change question counts or resume ordering. Imported-only threads remain resumable without inventing a question title.
30
+
31
+ Successful request user messages retain their serialized timestamps. Stored import messages and the optional initial background message also retain theirs. Later successful turns keep the prior serialized message sequence as an exact prefix. A failed or cancelled unanswered question is excluded as before; it is not a committed request-prefix baseline. Imports before the first successful answer use a stable initial background message followed by the imported updates and the new side question.
32
+
33
+ The provider receives each import as a user-role background message whose payload is a JSON-quoted string, not as tool traffic or an assistant response. This labels provenance but is not a general prompt-injection protection guarantee. The side model still has no tools.
34
+
35
+ ## Verification evidence
36
+
37
+ The package tests cover snapshot scope, historical/empty sources, missing or divergent cursors, context boundaries before confirmation, parallel tool results, finalized errors/aborts/length limits and their synthetic failures, pending/deferred barriers, content exclusions, and explicit size limits. Import tests cover chronology, exact serialized request prefixes, fixed previews while main advances, duplicate/stale confirmations, provider failure, cancellation, draft recovery, and imported-only resume.
38
+
39
+ The preview uses Kit's existing read-only review component, plain-text document hard wrapping, framing, theme roles, and lifecycle cancellation. Tests drive the real review with confirmation, back, hard cancel, disposal, and shutdown; callback evidence is asserted after interaction completion. Native fullscreen search tests include imported context. Shortcut tests cover fallback selection, remapping, collisions, aliases, invalid inputs, and legacy/enhanced terminal modes. Existing settings tests cover the new action through the same atomic store and invalid-file safeguards.
40
+
41
+ ## Terminal-only handoff and release limits
42
+
43
+ A terminal operator must check physical keyboard protocols, IME placement, actual clipboard behavior, and subjective visual placement after a successful build and deterministic checks. Exercise manual import while main output continues in fullscreen and both split layouts; cancel a nested preview, then verify the restored draft and pane focus. These terminal-specific behaviors are not established by mocked rendering or the non-interactive package smoke.
44
+
45
+ No live-provider request is required to verify the context-ordering contract. Do not claim terminal-only acceptance until the operator completes it. Package publication, tags, and release workflow dispatch require separate explicit user approval.
package/docs/workflows.md CHANGED
@@ -6,15 +6,56 @@
6
6
 
7
7
  `/btw` lets you start from the current conversation or choose **Start from main thread tree…** to use the root-to-selected-entry path, including the selected entry.
8
8
  The tree snapshots persisted entries and preserves the main editor draft without navigating, forking, appending to, or switching the main conversation.
9
- Side-thread context stays immutable if the main conversation later changes.
9
+
10
+ For either context source, only user and assistant messages contribute text and formatted tool-call or tool-result blocks.
11
+ Images, standalone tool-result messages, compaction summaries, branch summaries, and other session entries are excluded.
12
+ The side thread retains the last 40,000 characters of this text and adds a truncation notice when earlier content is omitted.
13
+ The initial snapshot stays immutable. Later main progress reaches the side model only after an explicit import; see [Import main updates](#import-main-updates).
10
14
  An explicit `Shift+L` label edit is the selector's only main-session mutation and persists through Pi.
11
15
  Native tree copying reports success or failure; Escape returns to the manager and Ctrl+C closes the flow.
12
16
 
13
- **Resume side thread** searches non-empty in-memory threads by their first question and question count.
17
+ **Resume side thread** searches retained in-memory threads by their first question and question count; threads containing only confirmed imports use **Main context updates** as their title.
14
18
  The first question remains the title; threads are ordered by their newest answer or visible error.
15
19
  Opening and closing without a new result does not reorder them.
16
20
  `/btw <question>` bypasses selection and always starts a new thread.
17
21
 
22
+ ## Import main updates
23
+
24
+ While the side composer is idle, use **Import main updates** (`F9` by default, then the first usable `F10` or `F11`) to review new persisted main-thread context.
25
+ The shortcut is configurable in `/btw` → **Settings**.
26
+ A `(new)` hint indicates eligible updates when the footer has room; main progress never imports content automatically.
27
+ If no shortcut is available, change the BTW shortcut or the conflicting Pi binding.
28
+ Import is unavailable while answering or draining queued side questions.
29
+
30
+ The read-only preview shows the source session, entry range, retained character count, and any omission notices.
31
+ Confirm to append exactly that snapshot, or press Escape to return without changes.
32
+ Ctrl+C closes the side flow without applying the pending import.
33
+ The main agent keeps running; entries added after the preview opens remain available for the next explicit import.
34
+ The side draft is restored when returning to the composer.
35
+
36
+ Imports contain new user text, finalized assistant text, and textual tool calls and standalone tool results in source order.
37
+ Finalized error, aborted, and length-limited assistant responses retain their status labels; they are not evidence of successful work.
38
+ Tool calls on error or aborted responses are not executed by Pi; length-limited calls receive synthetic error results instead of execution.
39
+ A tool-call batch waits until all its results exist, including parallel results; live stream deltas and partial tool updates are excluded.
40
+ Thinking, images, system instructions, and unrelated state entries are excluded.
41
+ Persisted pending responses or deferred provider handles block the cursor from advancing past them; start a new side thread from a later completed source if needed.
42
+ Each text or tool-call block is limited to 8,000 characters, and each import is limited to 40,000 characters including explicit omission notices.
43
+ Imports are limited background snapshots, not complete transcripts. Repeated imports increase total context and can increase provider cost or reach the model's context limit.
44
+ Confirmed text is sent to the selected side model's provider with the next question, not at confirmation time.
45
+
46
+ Each import appears as a searchable **Main context update**, between earlier side exchanges and later questions.
47
+ It does not count as a question or change the title.
48
+ The existing bring-to-main scopes still export successful side Q&A only, not imported main content.
49
+ Repeated imports do not duplicate the same entry range, and a later failed or cancelled side response does not undo a confirmed import.
50
+ Closing and resuming retains imports in memory, including imports made before the first question; these appear as **Main context updates** until the first question supplies a title.
51
+
52
+ The cursor must remain on the current main branch.
53
+ Navigation to an ancestor or another branch, a missing cursor, or a compaction, branch summary, or context edit after the cursor blocks import without changing the side thread.
54
+ Start a new side thread from the desired context in those cases.
55
+ Historical-tree sources can import only when they are ancestors of the current main branch.
56
+ Session replacement, reload, and restart discard imports with the rest of the retained side thread.
57
+ The [runtime audit](./main-context-runtime.md) records source boundaries, tests, and terminal-only verification limits.
58
+
18
59
  ## Read, select, and search
19
60
 
20
61
  The dedicated workspace places the scrollable transcript above pending questions, the editor, and a compact footer.
@@ -43,14 +84,15 @@ The view reports `No selection to copy`, `Copied!`, or a sanitized clipboard err
43
84
  Right-click clipboard paste is not installed because Pi has no public clipboard-read callback for this workspace.
44
85
  Ctrl+C always cancels the side flow, even if `app.message.copy` is also mapped to Ctrl+C.
45
86
 
46
- Use Pi's effective transcript-search binding (`Ctrl+Shift+F` by default) to search completed or in-progress transcript text, excluding the footer.
87
+ Use Pi's effective transcript-search binding (`Ctrl+Shift+F` by default) to search the displayed transcript, excluding the footer.
88
+ Search remains available while answering, covering previous turns and the current question; the current answer appears only after the response completes.
47
89
  The default next-match keys are Enter or `Ctrl+G`; previous-match keys are `Shift+Enter` or `Ctrl+Shift+G`.
48
90
  Pi's effective search-close binding, Escape by default, closes search and returns focus to the composer.
49
91
 
50
92
  Scroll with the mouse wheel, trackpad, or Pi's effective viewport paging bindings (`PgUp`/`PgDn` by default).
51
93
  Remapped or disabled bindings control behavior; the composer does not retain hidden literal paging shortcuts.
52
94
  The native transcript uses automatic scrollbars and previous/next-message navigation metadata.
53
- Manual scrolling stays fixed during incoming output, resize, and temporary content fits; explicitly returning to the latest content resumes follow mode.
95
+ Manual scrolling stays fixed when new turns appear, during resize, and when content temporarily fits; explicitly returning to the latest content resumes follow mode.
54
96
  On Pi 0.85 or newer, scrolling away from the latest content reveals **Jump to latest message**.
55
97
  Click it or use Pi's effective `tui.altScreen.bottom` binding (`Ctrl+End` by default) to resume following new output.
56
98
 
@@ -75,6 +117,7 @@ Completed questions, answers, and visible errors remain resumable until the exte
75
117
  ## Bring context to the main editor
76
118
 
77
119
  After a successful answer, use the bring-to-main shortcut (`Ctrl+R` by default) to choose the latest question and answer, everything from one question onward, an exact range, or the full thread.
120
+ All scopes, including the exact-range selector, use successful question-and-answer exchanges only; failed questions and error messages are excluded.
78
121
  The scope chooser reports the latest exchange and full-thread sizes.
79
122
  Question-suffix, exact-range, and full-thread choices show an exact, read-only preview before closing the side thread.
80
123
  The context block is editable after it is loaded into the main editor.
@@ -92,7 +135,7 @@ Cancel returns to the side thread without changing either draft, and concurrent
92
135
  The success message reports whether context was loaded, appended, or replaced and its approximate size.
93
136
 
94
137
  Without an explicit bring action, closing `/btw` never changes the main conversation.
95
- Resume state is memory-only: `/new`, Pi `/resume`, `/reload`, extension replacement, and process restart discard it.
138
+ Resume state is memory-only: `/new`, Pi `/resume`, `/fork`, `/reload`, extension replacement, and process restart discard it.
96
139
  Unsent drafts, steering queues, interrupted answers, and model credentials are not retained.
97
140
 
98
141
  ## Core compatibility and verification
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@narumitw/pi-btw",
3
- "version": "0.62.0",
3
+ "version": "0.63.1",
4
4
  "description": "Pi extension that adds a /btw side-question command.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -32,9 +32,9 @@
32
32
  "prepack": "npm run build"
33
33
  },
34
34
  "devDependencies": {
35
- "@earendil-works/pi-ai": "1.3.0",
36
- "@earendil-works/pi-coding-agent": "1.3.0",
37
- "@earendil-works/pi-tui": "1.3.0",
35
+ "@earendil-works/pi-ai": "1.4.0",
36
+ "@earendil-works/pi-coding-agent": "1.4.0",
37
+ "@earendil-works/pi-tui": "1.4.0",
38
38
  "esbuild": "0.28.2",
39
39
  "typescript": "7.0.2"
40
40
  },
@@ -44,7 +44,7 @@
44
44
  "directory": "packages/pi-btw"
45
45
  },
46
46
  "dependencies": {
47
- "@narumitw/pi-tui-kit": "^0.64.0"
47
+ "@narumitw/pi-tui-kit": "^0.67.0"
48
48
  },
49
49
  "peerDependencies": {
50
50
  "@earendil-works/pi-ai": "*",
package/src/btw.ts CHANGED
@@ -13,8 +13,9 @@ import {
13
13
  summarizeBringToMain,
14
14
  } from "./bring-to-main.js";
15
15
  import type { BtwDisplayModel } from "./conversation-chrome.js";
16
- import { buildConversationContext } from "./conversation-context.js";
17
16
  import { type RunBtwFullscreen, runBtwFullscreen } from "./fullscreen-ui.js";
17
+ import { importMainUpdates } from "./import-main-updates.js";
18
+ import { buildMainContextSnapshot, captureMainContextSource } from "./main-context-snapshot.js";
18
19
  import { registerBtwMainThreadUpdates } from "./main-thread-updates.js";
19
20
  import { pickMainEntry } from "./main-tree-picker.js";
20
21
  import {
@@ -43,6 +44,7 @@ import {
43
44
  createSideThread,
44
45
  type SideQuestionAuth,
45
46
  type SideThread,
47
+ sideTranscript,
46
48
  } from "./side-thread.js";
47
49
  import { sanitizeSingleLine } from "./text.js";
48
50
  import { type BtwMarkdownTransformers, prepareBtwTranscriptMarkdown } from "./transcript-markdown.js";
@@ -218,11 +220,11 @@ export default function btw(pi: ExtensionAPI, dependencies: BtwExtensionDependen
218
220
  const listResumeThreads = (resumableThreads: Map<string, BtwThreadState>): BtwResumeThreadSummary[] =>
219
221
  [...resumableThreads.values()]
220
222
  .reverse()
221
- .filter((state) => state.thread.turns.length > 0 && state.title)
223
+ .filter((state) => (state.thread.turns.length > 0 && state.title) || state.thread.updates.length > 0)
222
224
  .sort((first, second) => second.updatedAt - first.updatedAt || second.createdAt - first.createdAt)
223
225
  .map((state) => ({
224
226
  id: state.id,
225
- title: state.title ?? "Untitled side thread",
227
+ title: state.title ?? "Main context updates",
226
228
  questionCount: state.thread.turns.length,
227
229
  }));
228
230
  pi.registerCommand("btw", {
@@ -253,7 +255,7 @@ export default function btw(pi: ExtensionAPI, dependencies: BtwExtensionDependen
253
255
  }
254
256
 
255
257
  let menuResult: BtwCommandMenuResult = "start";
256
- let selectedConversationContext: string | undefined;
258
+ let selectedSource: ReturnType<typeof captureMainContextSource> | undefined;
257
259
  if (!question) {
258
260
  while (true) {
259
261
  menuResult = await showCommandMenu(pi, ctx, listResumeThreads(resumableThreads));
@@ -273,7 +275,7 @@ export default function btw(pi: ExtensionAPI, dependencies: BtwExtensionDependen
273
275
  notifySafely(ctx, "The selected main-thread branch is no longer available", "warning");
274
276
  continue;
275
277
  }
276
- selectedConversationContext = buildConversationContext(branch);
278
+ selectedSource = captureMainContextSource(ctx.sessionManager, treeResult.entryId, branch);
277
279
  menuResult = "start";
278
280
  break;
279
281
  } catch {
@@ -310,11 +312,10 @@ export default function btw(pi: ExtensionAPI, dependencies: BtwExtensionDependen
310
312
  if (lifetime.signal.aborted) return Promise.resolve({ kind: "closed" as const });
311
313
  if (!state) {
312
314
  const createdAt = Date.now();
315
+ const source = selectedSource ?? captureMainContextSource(fullscreenCtx.sessionManager);
313
316
  state = {
314
317
  id: `btw-${nextThreadNumber}`,
315
- thread: createSideThread(
316
- selectedConversationContext ?? buildConversationContext(fullscreenCtx.sessionManager.getBranch()),
317
- ),
318
+ thread: createSideThread(source.conversationContext, source.anchor),
318
319
  thinkingLevel: settings.thinkingLevel ?? pi.getThinkingLevel(),
319
320
  createdAt,
320
321
  updatedAt: createdAt,
@@ -345,7 +346,11 @@ export default function btw(pi: ExtensionAPI, dependencies: BtwExtensionDependen
345
346
  },
346
347
  );
347
348
  } finally {
348
- if (!lifetime.signal.aborted && state?.title && state.thread.turns.length > 0) {
349
+ if (
350
+ !lifetime.signal.aborted &&
351
+ state &&
352
+ ((state.title && state.thread.turns.length > 0) || state.thread.updates.length > 0)
353
+ ) {
349
354
  if (state.thread.turns.length > startingTurnCount) {
350
355
  resumableThreads.delete(state.id);
351
356
  }
@@ -400,6 +405,7 @@ interface RunBtwThreadDependencies {
400
405
  deliverBringToMain?: typeof loadBringToMainDraft;
401
406
  persistThinkingLevel?: (level: BtwThinkingLevel) => Promise<unknown>;
402
407
  now?: () => number;
408
+ importUpdates?: typeof importMainUpdates;
403
409
  }
404
410
 
405
411
  export type BtwThreadResult = { kind: "closed" };
@@ -454,7 +460,8 @@ export async function runBtwThread({
454
460
  dependencies.persistThinkingLevel ??
455
461
  ((level: BtwThinkingLevel) => updateBtwSettings({ thinkingLevel: level }, { settingsPath }));
456
462
  const now = dependencies.now ?? Date.now;
457
- const thread = state?.thread ?? createSideThread(buildConversationContext(ctx.sessionManager.getBranch()));
463
+ const source = state ? undefined : captureMainContextSource(ctx.sessionManager);
464
+ const thread = state?.thread ?? createSideThread(source?.conversationContext ?? "", source?.anchor);
458
465
  const thinkingLevels = getSupportedThinkingLevels(selected.model);
459
466
  const pendingWrites = new Set<Promise<void>>();
460
467
  const steeringQuestions: string[] = [];
@@ -495,6 +502,12 @@ export async function runBtwThread({
495
502
  provider: selected.model.provider,
496
503
  });
497
504
  if (ctx.signal?.aborted || action.kind === "close") return { kind: "closed" };
505
+ if (action.kind === "importMainUpdates") {
506
+ composerDraft = action.questionDraft;
507
+ const result = await (dependencies.importUpdates ?? importMainUpdates)(thread, ctx);
508
+ if (ctx.signal?.aborted || result === "close") return { kind: "closed" };
509
+ continue;
510
+ }
498
511
  if (action.kind === "bringToMain") {
499
512
  const choice = await chooseBringToMainAction(thread, ctx);
500
513
  if (ctx.signal?.aborted) return { kind: "closed" };
@@ -813,8 +826,8 @@ async function prepareCurrentTranscriptMarkdown(
813
826
  if (ctx.signal?.aborted) return undefined;
814
827
  const turnCount = thread.turns.length;
815
828
  const createMarkdownTransformers = ctx.signal
816
- ? await prepareBtwTranscriptMarkdown(thread.turns, pendingQuestion, ctx.signal)
817
- : await prepareBtwTranscriptMarkdown(thread.turns, pendingQuestion);
829
+ ? await prepareBtwTranscriptMarkdown(sideTranscript(thread), pendingQuestion, ctx.signal)
830
+ : await prepareBtwTranscriptMarkdown(sideTranscript(thread), pendingQuestion);
818
831
  if (!createMarkdownTransformers || ctx.signal?.aborted) return undefined;
819
832
  if (thread.turns.length === turnCount) return createMarkdownTransformers;
820
833
  }
@@ -835,7 +848,7 @@ async function askThreadQuestion(
835
848
  const view = new BtwAnsweringView(
836
849
  tui,
837
850
  theme,
838
- thread.turns,
851
+ sideTranscript(thread),
839
852
  question,
840
853
  () => {
841
854
  if (settled) return;
@@ -881,9 +894,21 @@ async function showThreadComposer(
881
894
  ): Promise<TranscriptPagerAction> {
882
895
  const createMarkdownTransformers = await prepareCurrentTranscriptMarkdown(thread, initialQuestion, ctx);
883
896
  if (!createMarkdownTransformers || ctx.signal?.aborted) return { kind: "close" };
897
+ let statusLeaf: string | null | undefined;
898
+ let hasUpdates = false;
899
+ const mainUpdates = () => {
900
+ if (ctx.signal?.aborted || !thread.source) return false;
901
+ const leaf = ctx.sessionManager.getLeafId();
902
+ if (leaf !== statusLeaf) {
903
+ statusLeaf = leaf;
904
+ hasUpdates = buildMainContextSnapshot(ctx.sessionManager, thread.source).kind === "ready";
905
+ }
906
+ return hasUpdates;
907
+ };
884
908
  return ctx.ui.custom<TranscriptPagerAction>(
885
909
  (tui, theme, keybindings, done) =>
886
- new BtwTranscriptPager(tui, theme, thread.turns, done, {
910
+ new BtwTranscriptPager(tui, theme, sideTranscript(thread), done, {
911
+ mainUpdates,
887
912
  startAtBottom,
888
913
  initialQuestion,
889
914
  model,
@@ -5,6 +5,7 @@ import {
5
5
  type Theme,
6
6
  } from "@earendil-works/pi-coding-agent";
7
7
  import { type Component, type OverlayHandle, ScrollView, type TUI, truncateToWidth } from "@earendil-works/pi-tui";
8
+ import type { createFullscreenHandoff, FullscreenHandoff } from "@narumitw/pi-tui-kit";
8
9
  import {
9
10
  type BtwFullscreenTui,
10
11
  createBtwFullscreenTui,
@@ -83,6 +84,10 @@ export async function runBtwFullscreen<T>(
83
84
  options: BtwFullscreenOptions = {},
84
85
  dependencies: BtwFullscreenDependencies = {},
85
86
  ): Promise<T> {
87
+ const { createFullscreenHandoff } = await import("@narumitw/pi-tui-kit/fullscreen-handoff");
88
+ if (ctx.signal?.aborted || options.signal?.aborted || options.canRestoreParent?.() === false) {
89
+ throw new FullscreenUiDisposedError();
90
+ }
86
91
  const createTui =
87
92
  dependencies.createTui ??
88
93
  ((parent: TUI, theme: Theme, keybindings: KeybindingsManager, fullscreenOptions: BtwFullscreenOptions) =>
@@ -121,6 +126,7 @@ export async function runBtwFullscreen<T>(
121
126
  },
122
127
  createTui,
123
128
  options,
129
+ createFullscreenHandoff,
124
130
  );
125
131
  return host;
126
132
  },
@@ -142,7 +148,7 @@ export async function runBtwFullscreen<T>(
142
148
 
143
149
  class BtwFullscreenHost<T> implements Component {
144
150
  private fullscreen: BtwFullscreenTui | undefined;
145
- private parentOverlay: OverlayHandle | undefined;
151
+ private readonly handoff: FullscreenHandoff<BtwFullscreenTui>;
146
152
  private cancelActiveCustom: (() => void) | undefined;
147
153
  private hardCancelActiveCustom: (() => void) | undefined;
148
154
  private removeHardCancelListener: (() => void) | undefined;
@@ -150,13 +156,8 @@ class BtwFullscreenHost<T> implements Component {
150
156
  private started = false;
151
157
  private disposed = false;
152
158
  private finished = false;
153
- private parentStopped = false;
154
- private parentRestoreAttempted = false;
155
- private fullscreenCreated = false;
156
- private fullscreenStopped = false;
157
- private parentRestoreQueued = false;
158
159
  private parentRestorePromise: Promise<void> | undefined;
159
- private cleanupError: unknown;
160
+ private readonly cleanupErrors: unknown[] = [];
160
161
  private removeMainThreadUpdateListener: (() => void) | undefined;
161
162
  private mainThreadRefreshTimer: ReturnType<typeof setTimeout> | undefined;
162
163
  private readonly mainThreadInput: BtwMainThreadInput;
@@ -175,6 +176,7 @@ class BtwFullscreenHost<T> implements Component {
175
176
  private readonly done: (outcome: FullscreenOutcome<T>) => void,
176
177
  private readonly createTui: BtwFullscreenTuiFactory,
177
178
  private readonly options: BtwFullscreenOptions,
179
+ createHandoff: typeof createFullscreenHandoff,
178
180
  ) {
179
181
  const initialMainInput = getFocusedComponent(parent);
180
182
  this.mainThreadInput = new BtwMainThreadInput(
@@ -185,12 +187,20 @@ class BtwFullscreenHost<T> implements Component {
185
187
  },
186
188
  () => this.fullscreen?.requestRender(),
187
189
  );
190
+ this.handoff = createHandoff<BtwFullscreenTui>(parent, {
191
+ isCurrent: () =>
192
+ !this.disposed &&
193
+ !this.finished &&
194
+ !this.lifetimeController.signal.aborted &&
195
+ this.options.canRestoreParent?.() !== false,
196
+ canRestoreParent: () => this.options.canRestoreParent?.() !== false,
197
+ });
188
198
  this.sidePaneRatio = options.sidePaneRatio;
189
199
  queueMicrotask(() => void this.start());
190
200
  }
191
201
 
192
202
  setParentOverlay(overlay: OverlayHandle): void {
193
- this.parentOverlay = overlay;
203
+ this.handoff.setOverlayHandle(overlay);
194
204
  }
195
205
 
196
206
  render(width: number): string[] {
@@ -221,12 +231,12 @@ class BtwFullscreenHost<T> implements Component {
221
231
  getParentFullscreenLayout(this.parent);
222
232
  getParentFullscreenScrollView(this.parent);
223
233
  }
224
- this.parent.stop({ preserveScreen: true });
225
- this.parentStopped = true;
226
- if (this.disposed) throw new FullscreenUiDisposedError();
227
- this.fullscreen = this.createTui(this.parent, this.theme, this.keybindings, this.options);
228
- this.fullscreenCreated = true;
229
- this.fullscreen.start();
234
+ this.fullscreen = await this.handoff.enter(() =>
235
+ this.createTui(this.parent, this.theme, this.keybindings, this.options),
236
+ );
237
+ if (!this.fullscreen || this.disposed || this.finished || this.options.canRestoreParent?.() === false) {
238
+ throw new FullscreenUiDisposedError();
239
+ }
230
240
  this.watchMainThreadUpdates();
231
241
  const shortcuts = resolveBtwShortcuts(
232
242
  this.options.keybindings,
@@ -287,11 +297,19 @@ class BtwFullscreenHost<T> implements Component {
287
297
  try {
288
298
  this.cancelActiveCustom?.();
289
299
  } catch (error) {
290
- this.cleanupError ??= error;
300
+ this.cleanupErrors.push(error);
301
+ }
302
+ this.queueParentRestore();
303
+ await this.parentRestorePromise;
304
+ if (this.cleanupErrors.length) {
305
+ outcome = {
306
+ kind: "failed",
307
+ error: combineErrors(
308
+ outcome.kind === "failed" ? [outcome.error, ...this.cleanupErrors] : this.cleanupErrors,
309
+ "Pi BTW flow and terminal cleanup failed",
310
+ ),
311
+ };
291
312
  }
292
- if (this.parentRestorePromise) await this.parentRestorePromise;
293
- else this.restoreParent();
294
- if (this.cleanupError !== undefined) outcome = { kind: "failed", error: this.cleanupError };
295
313
  this.finished = true;
296
314
  this.done(outcome);
297
315
  }
@@ -333,16 +351,13 @@ class BtwFullscreenHost<T> implements Component {
333
351
  }
334
352
 
335
353
  private queueParentRestore(): void {
336
- if (this.parentRestoreQueued || this.parentRestoreAttempted) return;
337
- this.parentRestoreQueued = true;
354
+ if (this.parentRestorePromise) return;
355
+ const restoration = this.handoff.restore().catch((error: unknown) => {
356
+ this.cleanupErrors.push(error);
357
+ });
338
358
  this.parentRestorePromise = Promise.resolve().then(async () => {
339
- try {
340
- await this.fullscreen?.terminal.drainInput?.();
341
- } catch (error) {
342
- this.cleanupError ??= error;
343
- }
344
- this.parentRestoreQueued = false;
345
359
  this.restoreParent();
360
+ await restoration;
346
361
  });
347
362
  }
348
363
 
@@ -369,50 +384,26 @@ class BtwFullscreenHost<T> implements Component {
369
384
  try {
370
385
  removeMainThreadUpdateListener?.();
371
386
  } catch (error) {
372
- this.cleanupError ??= error;
387
+ this.cleanupErrors.push(error);
373
388
  }
374
389
  try {
375
390
  this.mainThreadInput.dispose();
376
391
  } catch (error) {
377
- this.cleanupError ??= error;
392
+ this.cleanupErrors.push(error);
378
393
  }
379
394
  const removeUpstreamAbortListener = this.removeUpstreamAbortListener;
380
395
  this.removeUpstreamAbortListener = undefined;
381
396
  try {
382
397
  removeUpstreamAbortListener?.();
383
398
  } catch (error) {
384
- this.cleanupError ??= error;
399
+ this.cleanupErrors.push(error);
385
400
  }
386
401
  const removeHardCancelListener = this.removeHardCancelListener;
387
402
  this.removeHardCancelListener = undefined;
388
403
  try {
389
404
  removeHardCancelListener?.();
390
405
  } catch (error) {
391
- this.cleanupError ??= error;
392
- }
393
- if (this.fullscreenCreated && !this.fullscreenStopped) {
394
- this.fullscreenStopped = true;
395
- try {
396
- this.fullscreen?.stop({ preserveScreen: true });
397
- } catch (error) {
398
- this.cleanupError ??= error;
399
- }
400
- }
401
- if (!this.parentStopped || this.parentRestoreAttempted) return;
402
- const parentOverlay = this.parentOverlay;
403
- this.parentOverlay = undefined;
404
- try {
405
- parentOverlay?.setHidden(true);
406
- } catch (error) {
407
- this.cleanupError ??= error;
408
- }
409
- try {
410
- this.parentRestoreAttempted = true;
411
- if (this.options.canRestoreParent?.() === false) return;
412
- this.parent.start();
413
- this.parent.renderNow(false);
414
- } catch (error) {
415
- this.cleanupError ??= error;
406
+ this.cleanupErrors.push(error);
416
407
  }
417
408
  }
418
409
 
@@ -487,23 +478,23 @@ class BtwFullscreenHost<T> implements Component {
487
478
  componentDisposed = true;
488
479
  try {
489
480
  component.dispose?.();
490
- } catch {
491
- // Cleanup must continue so terminal ownership is restored.
481
+ } catch (error) {
482
+ this.cleanupErrors.push(error);
492
483
  }
493
484
  };
494
485
  const unmount = () => {
495
- let cleanupError: unknown;
486
+ const cleanupErrors: unknown[] = [];
496
487
  const removeFocusListener = removePaneFocusListener;
497
488
  removePaneFocusListener = undefined;
498
489
  try {
499
490
  removeFocusListener?.();
500
491
  } catch (error) {
501
- cleanupError = error;
492
+ cleanupErrors.push(error);
502
493
  }
503
494
  try {
504
495
  splitPane?.dispose();
505
496
  } catch (error) {
506
- cleanupError ??= error;
497
+ cleanupErrors.push(error);
507
498
  }
508
499
  splitPane = undefined;
509
500
  try {
@@ -511,18 +502,18 @@ class BtwFullscreenHost<T> implements Component {
511
502
  else if (mounted && layoutMounted) fullscreen.setLayoutRoot(undefined);
512
503
  else if (mounted && component) fullscreen.removeChild(component);
513
504
  } catch (error) {
514
- cleanupError ??= error;
505
+ cleanupErrors.push(error);
515
506
  }
516
507
  if (overlay || mounted) {
517
508
  try {
518
509
  fullscreen.setFocus(null);
519
510
  fullscreen.requestRender();
520
511
  } catch (error) {
521
- cleanupError ??= error;
512
+ cleanupErrors.push(error);
522
513
  }
523
514
  }
524
515
  disposeComponent();
525
- if (cleanupError !== undefined) throw cleanupError;
516
+ if (cleanupErrors.length) throw combineErrors(cleanupErrors, "Pi BTW custom UI cleanup failed");
526
517
  };
527
518
  const complete = () => {
528
519
  if (promiseSettled || !hasPendingValue) return;
@@ -557,7 +548,7 @@ class BtwFullscreenHost<T> implements Component {
557
548
  unmount();
558
549
  reject(error);
559
550
  } catch (cleanupError) {
560
- reject(cleanupError);
551
+ reject(combineErrors([error, cleanupError], "Pi BTW custom UI and cleanup failed"));
561
552
  }
562
553
  };
563
554
  this.cancelActiveCustom = () => {
@@ -710,6 +701,35 @@ class BtwFullscreenHost<T> implements Component {
710
701
  }
711
702
  }
712
703
 
704
+ // Keep an existing aggregate intact unless it overlaps causes already collected.
705
+ function combineErrors(errors: readonly unknown[], message: string): unknown {
706
+ const causes: unknown[] = [];
707
+ const seen = new Set<unknown>();
708
+ const remember = (error: unknown): void => {
709
+ if (seen.has(error)) return;
710
+ seen.add(error);
711
+ if (error instanceof AggregateError) error.errors.forEach(remember);
712
+ };
713
+ const overlaps = (error: unknown, visited = new Set<unknown>()): boolean => {
714
+ if (seen.has(error)) return true;
715
+ if (visited.has(error)) return false;
716
+ visited.add(error);
717
+ return error instanceof AggregateError && error.errors.some((cause: unknown) => overlaps(cause, visited));
718
+ };
719
+ const append = (error: unknown): void => {
720
+ if (seen.has(error)) return;
721
+ if (error instanceof AggregateError && overlaps(error)) {
722
+ seen.add(error);
723
+ error.errors.forEach(append);
724
+ return;
725
+ }
726
+ causes.push(error);
727
+ remember(error);
728
+ };
729
+ errors.forEach(append);
730
+ return causes.length === 1 ? causes[0] : new AggregateError(causes, message);
731
+ }
732
+
713
733
  function formatError(error: unknown): string {
714
734
  return error instanceof Error ? error.message : String(error);
715
735
  }