pi-branch-out 0.1.11 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -24,20 +24,47 @@ From the dot314 git bundle (filtered install):
24
24
  }
25
25
  ```
26
26
 
27
- After installing, copy `extensions/branch-out/config.json.example` to `extensions/branch-out/config.json` and adjust to taste.
27
+ After installing, copy `extensions/branch-out/config.json.example` to `extensions/branch-out/config.json` and adjust to taste. Pi `>=0.87.1` is required for the session snapshot and native tree selector APIs.
28
28
 
29
- ## Command
29
+ ## Commands
30
30
 
31
31
  ```text
32
- /branch [--model <query>] [message]
32
+ /branch-tree [--model <query>] [message]
33
+ /branch [--tree] [--model <query>] [message]
33
34
  ```
34
35
 
35
- Both arguments are optional and independent.
36
+ `/branch-tree` is the shortcut for `/branch --tree`. In short terminals, the picker reduces the tree viewport while keeping the focused entry visible and a preview row available; when the terminal cannot show both safely, it displays a resize prompt instead of accepting a hidden fork point.
36
37
 
37
- `/branch` works while the parent is responding or running tools. The child starts with the entries on the parent's active path when you run the command, even if the session file is behind. An unfinished streamed response and later tool results are not included. The parent continues its turn.
38
+ Use `/branch-tree` to select a historical entry, or `/branch` to fork from the current position. `/branch --tree` is equivalent to `/branch-tree`; both use the same handler and accept a model query and an optional draft message.
38
39
 
40
+ - **`--tree`** — open Pi's native session-tree selector and fork the child from the selected entry without navigating the parent. Selecting a user message restores its prompt in the child editor; selecting another entry forks through that entry. `Esc` cancels without creating a child.
39
41
  - **`--model <query>`** — target model for the child session. Accepts a fully qualified `provider/model-id` or a fuzzy query scoped to the current provider. If the query does not resolve safely the child keeps the parent's model.
40
- - **`message`** — prefilled text in the child session's editor with a 10-second auto-submit countdown. Typing anything or pressing `Esc` cancels the countdown; `Enter` sends immediately.
42
+ - **`message`** — prefilled text in the child session's editor with a 10-second auto-submit countdown. Typing anything or pressing `Esc` cancels the countdown; `Enter` sends immediately. When a text-only user message is selected, the supplied instructions are appended to the restored prompt. Restoring a historical prompt without new instructions leaves it in the editor without auto-submitting it.
43
+
44
+ Examples:
45
+
46
+ ```text
47
+ /branch-tree
48
+ /branch-tree --model flash
49
+ /branch-tree Please focus on the failure mechanism
50
+ /branch --tree
51
+ ```
52
+
53
+ The selector uses Pi's native session tree, including search, filtering, folding, labels, and sibling branches. The current leaf is initially selected. A live preview below the tree shows the focused entry before you choose where to fork. Markdown content and ordinary tool results use Pi's Markdown renderer; Bash commands and `read` results with a recognized file path receive syntax highlighting. Hidden thinking blocks are not shown. Attachment placeholders identify content that remains in the child. The footer explains whether the selected entry is included or restored as an editable prompt. Previews are capped at the reference picker's limits of 7,000 characters or 200 rendered lines, with an explicit notice; this never truncates the child session's history.
54
+
55
+ | Key | Action |
56
+ |-----|--------|
57
+ | `Tab` | Toggle between a larger tree and a larger preview; both remain visible |
58
+ | `Shift+Up` / `Shift+Down` | Scroll the preview by one line |
59
+ | `Shift+PageUp` / `Shift+PageDown` | Page through the preview |
60
+ | `Enter` | Fork from the focused entry |
61
+ | `Esc` | Clear an active search, or close the picker without forking |
62
+
63
+ Native navigation, search, filters, labels, spacing, and borders keep their configured bindings. Copy actions are omitted from this picker. Selection changes reset the preview scroll; resizing the terminal or toggling the layout preserves the selected node. Very large previews are capped at 7,000 characters or 200 rendered lines with an explicit notice; this never truncates the child session's history.
64
+
65
+ Selecting a node does not navigate or interrupt the parent session. Label edits are persisted through Pi's `setLabel` API.
66
+
67
+ Selecting a text-only user message forks before it and restores its prompt in the child editor for editing. Messages with attachments are retained intact through the selected message, so images are preserved without repeating the prompt. Selecting an assistant or other entry forks through that entry. The child opens using the existing terminal backend. The tree picker requires Pi's interactive terminal UI; ordinary `/branch` usage is unchanged.
41
68
 
42
69
  ## Config
43
70
 
@@ -96,8 +123,12 @@ rm /tmp/pi-branch-out-layout-state.json
96
123
 
97
124
  | Value | Behavior |
98
125
  |-------|----------|
99
- | `true` | Focus stays in the pane that ran `/branch` (default) |
100
- | `false` | Focus moves to the newly created pane |
126
+ | `true` | Ask the terminal to keep the source pane selected (default) |
127
+ | `false` | Allow the terminal's normal child-focus behavior |
128
+
129
+ This applies to both `/branch` and `/branch-tree` and is read on every launch. Focus behavior depends on the backend and desktop environment. A successful CLI switch or an active-pane marker does not establish that subsequent keyboard input will reach the child, particularly over a remote connection.
130
+
131
+ Use the terminal's native pane-switching shortcuts when automatic focus is unreliable. Orca's default bindings are `Cmd+]` / `Cmd+[` on macOS and `Ctrl+]` / `Ctrl+[` on Linux and Windows for the next / previous pane. These follow the desktop client's platform; custom Orca bindings take precedence. Wait for the child Pi editor to start before typing.
101
132
 
102
133
  ## Terminal backend routing
103
134
 
@@ -10,8 +10,8 @@ import type {
10
10
  ExtensionContext,
11
11
  SessionEntry,
12
12
  } from "@earendil-works/pi-coding-agent"
13
- import { SessionManager } from "@earendil-works/pi-coding-agent"
14
- import { Key, matchesKey } from "@earendil-works/pi-tui"
13
+ import { getLanguageFromPath, getMarkdownTheme, highlightCode, SessionManager, TreeSelectorComponent } from "@earendil-works/pi-coding-agent"
14
+ import { Key, Markdown, matchesKey, truncateToWidth } from "@earendil-works/pi-tui"
15
15
 
16
16
  const TERMINAL_FLAG = "branch-out-terminal"
17
17
  const STATUS_KEY = "branch-out-terminal"
@@ -481,17 +481,299 @@ function getModelCandidates(ctx: ExtensionContext): ScopedModelCandidate[] {
481
481
  return []
482
482
  }
483
483
 
484
- function parseBranchArgs(rawArgs: string): { modelQuery?: string; message: string } {
484
+ function parseBranchArgs(rawArgs: string): { modelQuery?: string; tree: boolean; message: string } {
485
485
  let remaining = rawArgs.trim()
486
486
  let modelQuery: string | undefined
487
+ let tree = false
487
488
 
488
- const modelMatch = remaining.match(/^--model\s+(\S+)(?:\s+|$)/)
489
- if (modelMatch) {
490
- modelQuery = modelMatch[1]
491
- remaining = remaining.slice(modelMatch[0].length).trimStart()
489
+ while (remaining) {
490
+ if (/^--tree(?:\s+|$)/.test(remaining)) {
491
+ tree = true
492
+ remaining = remaining.slice("--tree".length).trimStart()
493
+ continue
494
+ }
495
+
496
+ const modelMatch = remaining.match(/^--model\s+(\S+)(?:\s+|$)/)
497
+ if (modelMatch) {
498
+ modelQuery = modelMatch[1]
499
+ remaining = remaining.slice(modelMatch[0].length).trimStart()
500
+ continue
501
+ }
502
+
503
+ break
504
+ }
505
+
506
+ return { modelQuery, tree, message: remaining }
507
+ }
508
+
509
+ function getMessageText(entry: SessionEntry): string {
510
+ if (entry.type !== "message" || !("content" in entry.message)) return ""
511
+ const content = (entry.message as { content?: unknown }).content
512
+ if (typeof content === "string") return content
513
+ if (!Array.isArray(content)) return ""
514
+ return content
515
+ .filter((part: unknown): part is { type: "text"; text: string } => (
516
+ typeof part === "object" && part !== null && "type" in part && part.type === "text" && "text" in part && typeof part.text === "string"
517
+ ))
518
+ .map((part) => part.text)
519
+ .join("\n")
520
+ }
521
+
522
+ function hasNonTextContent(entry: SessionEntry): boolean {
523
+ if (entry.type !== "message" || !("content" in entry.message)) return false
524
+ const content = (entry.message as { content?: unknown }).content
525
+ return Array.isArray(content) && content.some((part: unknown) => (
526
+ typeof part !== "object" || part === null || !("type" in part) || part.type !== "text"
527
+ ))
528
+ }
529
+
530
+ function buildEntryPath(entries: SessionEntry[], targetId: string): SessionEntry[] | undefined {
531
+ const entriesById = new Map(entries.map((entry) => [entry.id, entry]))
532
+ const reversedPath: SessionEntry[] = []
533
+ let current = entriesById.get(targetId)
534
+ if (!current) return undefined
535
+ while (current) {
536
+ reversedPath.push(current)
537
+ current = current.parentId ? entriesById.get(current.parentId) : undefined
538
+ }
539
+ if (reversedPath[reversedPath.length - 1]?.parentId) return undefined
540
+ return reversedPath.reverse()
541
+ }
542
+
543
+ function buildTreeForkSelection(
544
+ entries: SessionEntry[],
545
+ targetId: string,
546
+ ): { branch: SessionEntry[]; message: string } | undefined {
547
+ const branch = buildEntryPath(entries, targetId)
548
+ if (!branch) return undefined
549
+
550
+ const selectedEntry = branch[branch.length - 1]
551
+ if (selectedEntry.type !== "message" || selectedEntry.message.role !== "user" || hasNonTextContent(selectedEntry)) {
552
+ // Keep attachments in their original message rather than reconstructing them from editor text.
553
+ return { branch, message: "" }
492
554
  }
493
555
 
494
- return { modelQuery, message: remaining }
556
+ return { branch: branch.slice(0, -1), message: getMessageText(selectedEntry) }
557
+ }
558
+
559
+ const MAX_PREVIEW_CHARS = 7_000
560
+ const MAX_PREVIEW_LINES = 200
561
+ const MAX_PREVIEW_PARENT_DEPTH = 30
562
+ const SELECTOR_HEIGHT_RATIO = 0.65
563
+
564
+ type SessionTree = ReturnType<ExtensionCommandContext["sessionManager"]["getTree"]>
565
+
566
+ function previewCode(text: string, language = ""): string {
567
+ const clipped = text.slice(0, MAX_PREVIEW_CHARS)
568
+ const fence = "`".repeat(Math.max(3, ...Array.from(clipped.matchAll(/`+/g), (match) => match[0].length + 1)))
569
+ return `${fence}${language}\n${clipped}\n${fence}${text.length > clipped.length ? "\n[Preview truncated]" : ""}`
570
+ }
571
+
572
+ function previewContent(content: unknown): string {
573
+ if (typeof content === "string") return content
574
+ if (!Array.isArray(content)) return ""
575
+ return content.map((part: unknown) => {
576
+ if (typeof part !== "object" || part === null || !("type" in part)) return ""
577
+ if (part.type === "thinking") return ""
578
+ if (part.type === "text" && "text" in part && typeof part.text === "string") return part.text
579
+ if (part.type === "toolCall" && "name" in part) {
580
+ const args = "arguments" in part ? JSON.stringify(part.arguments, null, 2) : ""
581
+ return `Tool: ${part.name}\n${previewCode(args ?? "", "json")}`
582
+ }
583
+ return `[${part.type} attachment]`
584
+ }).filter(Boolean).join("\n\n")
585
+ }
586
+
587
+ function renderBranchPreview(entry: SessionEntry, entries: Map<string, SessionEntry>, width: number): string[] {
588
+ let text = ""
589
+ let highlightLanguage = ""
590
+ if (entry.type === "message") {
591
+ const message = entry.message
592
+ text = "content" in message ? previewContent(message.content) : ""
593
+ if (message.role === "bashExecution") {
594
+ text = `Command:\n${previewCode(message.command, "bash")}\n\nOutput:\n${message.output || "(no output)"}`
595
+ if (message.exitCode !== undefined) text += `\n\nExit code: ${message.exitCode}`
596
+ if (message.truncated) text += `\n\nFull output: ${message.fullOutputPath ?? "truncated"}`
597
+ } else if (message.role === "toolResult") {
598
+ // A read result's language comes from the matching call on this node's own ancestry.
599
+ let language = ""
600
+ let parent = entry.parentId ? entries.get(entry.parentId) : undefined
601
+ for (let depth = 0; parent && depth < MAX_PREVIEW_PARENT_DEPTH; depth += 1) {
602
+ if (parent.type === "message" && parent.message.role === "assistant") {
603
+ const call = parent.message.content.find((part: { type: string; id?: string }) => part.type === "toolCall" && part.id === message.toolCallId)
604
+ if (call?.type === "toolCall") {
605
+ const file = call.arguments.path ?? call.arguments.file_path
606
+ if (message.toolName === "read" && typeof file === "string") language = getLanguageFromPath(file) ?? ""
607
+ break
608
+ }
609
+ }
610
+ parent = parent.parentId ? entries.get(parent.parentId) : undefined
611
+ }
612
+ if (message.toolName === "read" && language) highlightLanguage = language
613
+ if (message.isError && text) text = `Tool error:\n\n${text}`
614
+ }
615
+ if (!text && "errorMessage" in message && message.errorMessage) text = `(error) ${message.errorMessage}`
616
+ } else if (entry.type === "custom_message") {
617
+ text = previewContent(entry.content)
618
+ } else if (entry.type === "compaction" || entry.type === "branch_summary") {
619
+ text = entry.summary
620
+ } else if (entry.type === "model_change") {
621
+ text = `Model: ${entry.provider}/${entry.modelId}`
622
+ } else if (entry.type === "thinking_level_change") {
623
+ text = `Thinking level: ${entry.thinkingLevel}`
624
+ } else if (entry.type === "label") {
625
+ text = `Label: ${entry.label ?? "(cleared)"}`
626
+ } else if (entry.type === "session_info") {
627
+ text = `Session: ${entry.name ?? "(unnamed)"}`
628
+ } else if (entry.type === "custom") {
629
+ text = `Extension entry: ${entry.customType}`
630
+ }
631
+ if (text.length > MAX_PREVIEW_CHARS) text = `${text.slice(0, MAX_PREVIEW_CHARS)}\n\n[Preview truncated]`
632
+ const lines = highlightLanguage
633
+ ? highlightCode(text, highlightLanguage).map((line) => truncateToWidth(line, width))
634
+ : new Markdown(text || "(no text content)", 0, 0, getMarkdownTheme()).render(width)
635
+ return lines.length > MAX_PREVIEW_LINES
636
+ ? [...lines.slice(0, MAX_PREVIEW_LINES - 1), "[Preview truncated]"]
637
+ : [...lines]
638
+ }
639
+
640
+ async function selectSessionTreeEntry(
641
+ pi: ExtensionAPI,
642
+ ctx: ExtensionCommandContext,
643
+ tree: SessionTree,
644
+ currentLeafId: string | null,
645
+ ): Promise<string | undefined> {
646
+ return ctx.ui.custom<string | undefined>((tui, theme, keybindings, done) => {
647
+ let editingLabel = false
648
+ let expanded = false
649
+ let scrollOffset = 0
650
+ let previewHeight = 1
651
+ let canSelect = false
652
+ let cache: { id: string; width: number; lines: string[] } | undefined
653
+ const entries = new Map<string, SessionEntry>()
654
+ const pending = [...tree]
655
+ while (pending.length) {
656
+ const node = pending.pop()!
657
+ entries.set(node.entry.id, node.entry)
658
+ pending.push(...node.children)
659
+ }
660
+
661
+ const selector = new TreeSelectorComponent(
662
+ tree,
663
+ currentLeafId,
664
+ Math.floor(tui.terminal.rows * SELECTOR_HEIGHT_RATIO),
665
+ (id) => { if (canSelect) done(id) },
666
+ () => done(undefined),
667
+ (entryId, label) => {
668
+ editingLabel = false
669
+ pi.setLabel(entryId, label)
670
+ },
671
+ currentLeafId ?? undefined,
672
+ )
673
+ const treeList = selector.getTreeList()
674
+ // Pi has no public tree viewport setter. Keep this one sizing assumption checked,
675
+ // and retain the native list so selection, search, folding and labels stay native.
676
+ const viewport = treeList as unknown as { maxVisibleLines: number }
677
+ const children = selector.children
678
+ if (!Number.isInteger(viewport.maxVisibleLines) || children.length <= 3
679
+ || !children[3].render(200).join(" ").includes("filters")) {
680
+ throw new Error("Pi's session tree layout changed; the branch preview needs an update")
681
+ }
682
+ const key = (action: Parameters<typeof keybindings.getKeys>[0]) => keybindings.getKeys(action)[0] ?? ""
683
+ const help = {
684
+ invalidate() {},
685
+ render(width: number) {
686
+ return [
687
+ `${key("tui.select.up")}/${key("tui.select.down")} move · ${key("tui.editor.cursorLeft")}/${key("tui.editor.cursorRight")} page · ${key("app.tree.foldOrUp")}/${key("app.tree.unfoldOrDown")} branch · ${key("app.tree.editLabel")} label · ${key("app.tree.filter.cycleForward")} filters`,
688
+ `${key("tui.select.confirm")} fork · ${key("tui.select.cancel")} cancel · tab resize preview · shift+↑/↓ scroll · shift+pgup/pgdn page`,
689
+ ].map((line) => truncateToWidth(theme.fg("dim", ` ${line}`), width))
690
+ },
691
+ }
692
+ // Preserve the native title, spacing and borders; only replace copy hints with fork guidance.
693
+ children[3] = help
694
+ const editLabel = treeList.onLabelEdit
695
+ treeList.onLabelEdit = (id, label) => {
696
+ editingLabel = true
697
+ editLabel?.(id, label)
698
+ }
699
+
700
+ const picker = {
701
+ get focused() { return selector.focused },
702
+ set focused(value: boolean) { selector.focused = value },
703
+ get capturesViewportInput() { return !editingLabel },
704
+ invalidate() {
705
+ cache = undefined
706
+ selector.invalidate()
707
+ },
708
+ handleInput(data: string) {
709
+ if (editingLabel) {
710
+ selector.handleInput(data)
711
+ if (keybindings.matches(data, "tui.select.cancel")) editingLabel = false
712
+ } else if (keybindings.matches(data, "tui.select.cancel")) {
713
+ if (canSelect) selector.handleInput(data)
714
+ else done(undefined)
715
+ } else if (matchesKey(data, Key.tab)) {
716
+ expanded = !expanded
717
+ } else if (matchesKey(data, "shift+up")) {
718
+ scrollOffset -= 1
719
+ } else if (matchesKey(data, "shift+down")) {
720
+ scrollOffset += 1
721
+ } else if (matchesKey(data, "shift+pageUp")) {
722
+ scrollOffset -= Math.max(1, previewHeight - 1)
723
+ } else if (matchesKey(data, "shift+pageDown")) {
724
+ scrollOffset += Math.max(1, previewHeight - 1)
725
+ } else if (!keybindings.matches(data, "app.message.copy")) {
726
+ // Recheck the viewport before accepting Enter after a terminal resize.
727
+ picker.render(tui.terminal.columns)
728
+ if (canSelect) selector.handleInput(data)
729
+ }
730
+ tui.requestRender()
731
+ },
732
+ render(width: number): string[] {
733
+ const height = Math.max(1, tui.terminal.rows)
734
+ const fit = (line: string) => truncateToWidth(line, Math.max(1, width))
735
+ viewport.maxVisibleLines = 1
736
+ selector.invalidate()
737
+ const chromeHeight = selector.render(width).length - (editingLabel ? 0 : treeList.render(width).length)
738
+ canSelect = width >= 20 && height >= chromeHeight + 5
739
+ if (!canSelect) return [fit(theme.fg("warning", "Resize terminal to choose a fork point. Esc cancels."))]
740
+ if (editingLabel) return selector.render(width).map(fit)
741
+
742
+ const treeRatio = expanded ? 0.3 : SELECTOR_HEIGHT_RATIO
743
+ const preferredTreeLines = Math.floor(Math.floor(height * treeRatio) / 2)
744
+ const availableTreeLines = height - chromeHeight - 4
745
+ viewport.maxVisibleLines = Math.max(1, Math.min(preferredTreeLines, availableTreeLines))
746
+ selector.invalidate()
747
+ const treeLines = selector.render(width)
748
+ previewHeight = Math.max(1, height - treeLines.length - 2)
749
+ const entry = treeList.getSelectedNode()?.entry
750
+ if (cache?.id !== entry?.id) scrollOffset = 0
751
+ if (entry && (!cache || cache.id !== entry.id || cache.width !== width)) {
752
+ cache = { id: entry.id, width, lines: renderBranchPreview(entry, entries, width) }
753
+ } else if (!entry) cache = undefined
754
+ const body = cache?.lines ?? ["No matching entry"]
755
+ scrollOffset = Math.max(0, Math.min(scrollOffset, Math.max(0, body.length - previewHeight)))
756
+ const visible = body.slice(scrollOffset, scrollOffset + previewHeight)
757
+ while (visible.length < previewHeight) visible.push("")
758
+ const role = entry?.type === "message"
759
+ ? entry.message.role === "toolResult" ? `${entry.message.role} · ${entry.message.toolName}` : entry.message.role
760
+ : entry?.type ?? ""
761
+ const header = theme.fg("accent", `─ Preview: ${role} · ${scrollOffset + 1}–${Math.min(body.length, scrollOffset + previewHeight)}/${body.length} ─`)
762
+ const restoresPrompt = entry?.type === "message" && entry.message.role === "user" && !hasNonTextContent(entry)
763
+ const action = !entry ? "Choose a session entry to fork from"
764
+ : restoresPrompt ? "Fork before this prompt; restore it in the child editor"
765
+ : "Fork through this entry; parent stays at its current position"
766
+ return [...treeLines, header, ...visible, theme.fg("muted", action)].map(fit)
767
+ },
768
+ }
769
+ return picker
770
+ })
771
+ }
772
+
773
+ function appendBranchInstructions(message: string, extra: string): string {
774
+ const trimmedExtra = extra.trim()
775
+ if (!trimmedExtra) return message
776
+ return message ? `${message}\n\n${trimmedExtra}` : trimmedExtra
495
777
  }
496
778
 
497
779
  function isEditableInput(data: string): boolean {
@@ -1303,12 +1585,12 @@ function resolveBranchModel(
1303
1585
  }
1304
1586
 
1305
1587
  const match = resolveClosestModelCandidate(modelQuery, getModelCandidates(ctx), {
1306
- preferredProvider: ctx.model.provider,
1588
+ preferredProvider: currentModel.provider,
1307
1589
  })
1308
1590
  if (!match) {
1309
1591
  return {
1310
1592
  targetModel: currentModel,
1311
- notice: `Model '${modelQuery}' did not resolve safely; using ${ctx.model.provider}/${ctx.model.id}`,
1593
+ notice: `Model '${modelQuery}' did not resolve safely; using ${currentModel.provider}/${currentModel.id}`,
1312
1594
  }
1313
1595
  }
1314
1596
 
@@ -1338,7 +1620,7 @@ function writeBranchSnapshot(
1338
1620
  }
1339
1621
  }
1340
1622
  const entries = [...branch]
1341
- let parentId = branch[branch.length - 1].id
1623
+ let parentId = entries.at(-1)?.id ?? null
1342
1624
  for (const label of latestLabels.values()) {
1343
1625
  if (branchIds.has(label.id)) continue
1344
1626
  entries.push({ ...label, parentId })
@@ -1374,64 +1656,100 @@ export default function (pi: ExtensionAPI) {
1374
1656
  await applyPendingBranchLaunch(pi, ctx)
1375
1657
  })
1376
1658
 
1377
- pi.registerCommand("branch", {
1378
- description: "Fork current session into a new terminal tab or split pane, optionally queueing --model <query> and a draft message",
1379
- handler: async (args, ctx) => {
1380
- const sessionFile = ctx.sessionManager.getSessionFile()
1381
- if (!sessionFile) {
1382
- if (ctx.hasUI) ctx.ui.notify("Session is not persisted. Restart without --no-session.", "error")
1383
- return
1659
+ const handleBranch = async (args: string, ctx: ExtensionCommandContext, treeByDefault = false) => {
1660
+ const sessionFile = ctx.sessionManager.getSessionFile()
1661
+ if (!sessionFile) {
1662
+ if (ctx.hasUI) ctx.ui.notify("Session is not persisted. Restart without --no-session.", "error")
1663
+ return
1664
+ }
1665
+
1666
+ const { modelQuery, tree, message } = parseBranchArgs(args)
1667
+ const selectFromHistory = tree || treeByDefault
1668
+ // Snapshot the live path before the first await. The active leaf need not
1669
+ // exist in the on-disk file, and must not be replaced by a different leaf.
1670
+ const branch = ctx.sessionManager.getBranch()
1671
+ const sessionEntries = selectFromHistory ? ctx.sessionManager.getEntries() : branch
1672
+ if (!sessionEntries.some((entry) => entry.type === "message" && (entry.message.role === "user" || entry.message.role === "assistant"))) {
1673
+ if (ctx.hasUI) ctx.ui.notify("No messages yet. Nothing to branch.", "error")
1674
+ return
1675
+ }
1676
+
1677
+ let branchToSnapshot = branch
1678
+ let queuedMessage = message
1679
+
1680
+ if (selectFromHistory) {
1681
+ if (!ctx.hasUI || ctx.mode !== "tui") {
1682
+ throw new Error("History selection requires Pi's interactive terminal UI")
1384
1683
  }
1385
1684
 
1386
- // Snapshot the live path before the first await. The active leaf need not
1387
- // exist in the on-disk file, and must not be replaced by a different leaf.
1388
- const branch = ctx.sessionManager.getBranch()
1389
- if (!branch.some((entry) => entry.type === "message" && (entry.message.role === "user" || entry.message.role === "assistant"))) {
1390
- if (ctx.hasUI) ctx.ui.notify("No messages yet. Nothing to branch.", "error")
1685
+ const sessionTree = ctx.sessionManager.getTree()
1686
+ const currentLeafId = ctx.sessionManager.getLeafId()
1687
+ const selectedId = await selectSessionTreeEntry(pi, ctx, sessionTree, currentLeafId)
1688
+ if (!selectedId) return
1689
+
1690
+ const selection = buildTreeForkSelection(sessionEntries, selectedId)
1691
+ if (!selection) {
1692
+ ctx.ui.notify("Could not resolve the selected session tree entry", "error")
1391
1693
  return
1392
1694
  }
1393
1695
 
1394
- const { modelQuery, message } = parseBranchArgs(args)
1395
- const forkFile = writeBranchSnapshot(ctx.sessionManager, sessionFile, branch)
1396
-
1397
- const trimmedMessage = message.trim()
1398
- const hasLaunchCustomization = Boolean(modelQuery || trimmedMessage)
1399
- let launchData: BranchLaunchData | undefined
1400
-
1401
- if (hasLaunchCustomization) {
1402
- const launchSession = SessionManager.open(forkFile)
1403
- const modelResolution = resolveBranchModel(ctx, modelQuery)
1404
- launchData = {
1405
- launchId: `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
1406
- message: trimmedMessage || undefined,
1407
- autoSubmitSeconds: AUTO_SUBMIT_SECONDS,
1408
- modelNotice: modelResolution.notice,
1409
- targetModel: modelResolution.targetModel,
1410
- }
1411
- launchSession.appendCustomEntry(BRANCH_LAUNCH_CUSTOM_TYPE, launchData)
1412
- }
1696
+ branchToSnapshot = selection.branch
1697
+ queuedMessage = appendBranchInstructions(selection.message, message)
1698
+ }
1413
1699
 
1414
- await openForkInTerminal(pi, ctx, forkFile)
1700
+ const forkFile = writeBranchSnapshot(ctx.sessionManager, sessionFile, branchToSnapshot)
1701
+ const inheritedLaunch = selectFromHistory ? readBranchLaunchData(branchToSnapshot) : undefined
1702
+ if (inheritedLaunch) {
1703
+ // A history entry may precede its launch-applied marker. Do not replay an old launch draft.
1704
+ SessionManager.open(forkFile).appendCustomEntry(BRANCH_LAUNCH_APPLIED_CUSTOM_TYPE, { launchId: inheritedLaunch.launchId })
1705
+ }
1415
1706
 
1416
- if (ctx.hasUI) {
1417
- if (!launchData) {
1418
- ctx.ui.notify("Created fork and requested terminal launch", "info")
1419
- return
1420
- }
1707
+ const trimmedMessage = queuedMessage.trim()
1708
+ const hasLaunchCustomization = Boolean(modelQuery || trimmedMessage)
1709
+ let launchData: BranchLaunchData | undefined
1710
+
1711
+ if (hasLaunchCustomization) {
1712
+ const launchSession = SessionManager.open(forkFile)
1713
+ const modelResolution = resolveBranchModel(ctx, modelQuery)
1714
+ launchData = {
1715
+ launchId: `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
1716
+ message: trimmedMessage || undefined,
1717
+ autoSubmitSeconds: selectFromHistory && !message.trim() ? 0 : AUTO_SUBMIT_SECONDS,
1718
+ modelNotice: modelResolution.notice,
1719
+ targetModel: modelResolution.targetModel,
1720
+ }
1721
+ launchSession.appendCustomEntry(BRANCH_LAUNCH_CUSTOM_TYPE, launchData)
1722
+ }
1723
+
1724
+ await openForkInTerminal(pi, ctx, forkFile)
1421
1725
 
1422
- const details = [
1423
- launchData.targetModel
1424
- ? `${launchData.targetModel.provider}/${launchData.targetModel.id}`
1425
- : ctx.model ? `${ctx.model.provider}/${ctx.model.id}` : undefined,
1426
- launchData.message ? "draft queued" : undefined,
1427
- ].filter(Boolean).join(" · ")
1428
- ctx.ui.notify(
1429
- details
1430
- ? `Created fork and requested terminal launch (${details})`
1431
- : "Created fork and requested terminal launch",
1432
- "info",
1433
- )
1726
+ if (ctx.hasUI) {
1727
+ if (!launchData) {
1728
+ ctx.ui.notify("Created fork and requested terminal launch", "info")
1729
+ return
1434
1730
  }
1435
- },
1731
+
1732
+ const details = [
1733
+ launchData.targetModel
1734
+ ? `${launchData.targetModel.provider}/${launchData.targetModel.id}`
1735
+ : ctx.model ? `${ctx.model.provider}/${ctx.model.id}` : undefined,
1736
+ launchData.message ? "draft queued" : undefined,
1737
+ ].filter(Boolean).join(" · ")
1738
+ ctx.ui.notify(
1739
+ details
1740
+ ? `Created fork and requested terminal launch (${details})`
1741
+ : "Created fork and requested terminal launch",
1742
+ "info",
1743
+ )
1744
+ }
1745
+ }
1746
+
1747
+ pi.registerCommand("branch", {
1748
+ description: "Fork the current session into a new terminal; optionally use --tree, --model <query>, and a draft message",
1749
+ handler: handleBranch,
1750
+ })
1751
+ pi.registerCommand("branch-tree", {
1752
+ description: "Select a history entry in Pi's session tree and fork it into a new terminal; optionally use --model <query> and a draft message",
1753
+ handler: (args, ctx) => handleBranch(args, ctx, true),
1436
1754
  })
1437
1755
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "pi-branch-out",
3
- "version": "0.1.11",
4
- "description": "Fork the current Pi session into a split terminal pane or new tab with rotating layout policies, and with optional model and message queuing, and support for cmux, tmux, iTerm2, Terminal.app, Ghostty, Warp, and Orca.",
3
+ "version": "0.2.0",
4
+ "description": "Fork Pi sessions into split terminal panes or new tabs, with a history picker and live message previews, rotating layouts, and optional model selection and message queuing. Supports cmux, tmux, iTerm2, Terminal.app, Ghostty, Warp, and Orca.",
5
5
  "keywords": ["pi-package", "pi", "pi-coding-agent"],
6
6
  "license": "MIT",
7
7
  "repository": {
@@ -17,7 +17,7 @@
17
17
  "extensions": ["extensions/branch-out/index.ts"]
18
18
  },
19
19
  "peerDependencies": {
20
- "@earendil-works/pi-coding-agent": ">=0.74.0"
20
+ "@earendil-works/pi-coding-agent": ">=0.87.1"
21
21
  },
22
22
  "scripts": {
23
23
  "prepack": "node ../../scripts/pi-package-prepack.mjs",