@narumitw/pi-btw 0.63.5 → 0.63.7

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,17 @@
1
1
  # @narumitw/pi-btw
2
2
 
3
+ ## 0.63.7
4
+
5
+ ### Patch Changes
6
+
7
+ - b2b91fa: Reduce main-thread tree picker allocations by joining raw text fragments only when copying and storing saved labels only when needed.
8
+
9
+ ## 0.63.6
10
+
11
+ ### Patch Changes
12
+
13
+ - aca87cf: Fix call stack overflows when opening the main-thread tree picker for deep session histories.
14
+
3
15
  ## 0.63.5
4
16
 
5
17
  ### Patch Changes
@@ -61,9 +61,7 @@ async function pickMainEntry(pi, ctx, dependencies = {}) {
61
61
  notifySafely(ctx, "No main-thread entries are available", "warning");
62
62
  return { kind: "back" };
63
63
  }
64
- const tree = sanitizeTreeForDisplay(rawTree);
65
- const rawCopyText = collectRawCopyText(rawTree);
66
- const savedLabels = collectSavedLabels(rawTree);
64
+ const { tree, rawCopyText, savedLabels } = prepareTreeSnapshot(rawTree);
67
65
  const createSelector = dependencies.createSelector ?? createNativeTreeSelector;
68
66
  const copy = dependencies.copyToClipboard ?? copyText;
69
67
  const copyControllers = /* @__PURE__ */ new Set();
@@ -84,7 +82,14 @@ async function pickMainEntry(pi, ctx, dependencies = {}) {
84
82
  };
85
83
  const onCopy = (entryId, displayText) => {
86
84
  if (settled) return;
87
- const text = entryId ? rawCopyText.get(entryId) : displayText;
85
+ let text;
86
+ try {
87
+ const source = entryId ? rawCopyText.get(entryId) : displayText;
88
+ text = typeof source === "string" ? source : source?.join("");
89
+ } catch (error) {
90
+ notifySafely(ctx, `Could not copy selected message: ${formatError(error)}`, "error");
91
+ return;
92
+ }
88
93
  if (!text) {
89
94
  notifySafely(ctx, "Selected entry has no text to copy", "warning");
90
95
  return;
@@ -125,7 +130,8 @@ async function pickMainEntry(pi, ctx, dependencies = {}) {
125
130
  }
126
131
  const persistedLabel = label === void 0 ? void 0 : sanitizeSingleLine(label);
127
132
  pi.setLabel(entryId, persistedLabel);
128
- savedLabels.set(entryId, { label: persistedLabel });
133
+ if (persistedLabel === void 0) savedLabels.delete(entryId);
134
+ else savedLabels.set(entryId, { label: persistedLabel });
129
135
  selector?.setViewLabel?.(entryId, persistedLabel);
130
136
  tui.requestRender();
131
137
  } catch (error) {
@@ -162,18 +168,37 @@ function createNativeTreeSelector(options) {
162
168
  result.setViewLabel = (entryId, label, labelTimestamp) => selector.getTreeList().updateNodeLabel(entryId, label, labelTimestamp);
163
169
  return result;
164
170
  }
165
- function sanitizeTreeForDisplay(tree) {
166
- return tree.map((node) => {
167
- const result = {
171
+ function prepareTreeSnapshot(rawTree) {
172
+ const tree = [];
173
+ const rawCopyText = /* @__PURE__ */ new Map();
174
+ const savedLabels = /* @__PURE__ */ new Map();
175
+ const stack = [{ source: rawTree, target: tree, index: 0 }];
176
+ while (stack.length > 0) {
177
+ const frame = stack[stack.length - 1];
178
+ if (frame.index === frame.source.length) {
179
+ stack.pop();
180
+ continue;
181
+ }
182
+ const node = frame.source[frame.index++];
183
+ const label = node.label === void 0 ? void 0 : sanitizeSingleLine(node.label);
184
+ const labelTimestamp = node.labelTimestamp === void 0 ? void 0 : sanitizeSingleLine(node.labelTimestamp);
185
+ const displayNode = {
168
186
  entry: sanitizeEntryForDisplay(node.entry),
169
- children: sanitizeTreeForDisplay(node.children)
187
+ children: []
170
188
  };
171
- if (node.label !== void 0) result.label = sanitizeSingleLine(node.label);
172
- if (node.labelTimestamp !== void 0) {
173
- result.labelTimestamp = sanitizeSingleLine(node.labelTimestamp);
189
+ if (label !== void 0) displayNode.label = label;
190
+ if (labelTimestamp !== void 0) displayNode.labelTimestamp = labelTimestamp;
191
+ frame.target.push(displayNode);
192
+ const source = captureRawCopySource(node.entry);
193
+ if (source !== void 0) rawCopyText.set(node.entry.id, source);
194
+ if (label !== void 0 || labelTimestamp !== void 0) {
195
+ savedLabels.set(node.entry.id, { label, labelTimestamp });
174
196
  }
175
- return result;
176
- });
197
+ if (node.children.length > 0) {
198
+ stack.push({ source: node.children, target: displayNode.children, index: 0 });
199
+ }
200
+ }
201
+ return { tree, rawCopyText, savedLabels };
177
202
  }
178
203
  function sanitizeEntryForDisplay(entry) {
179
204
  switch (entry.type) {
@@ -263,50 +288,30 @@ function sanitizeToolArguments(value, seen) {
263
288
  }
264
289
  return result;
265
290
  }
266
- function collectRawCopyText(tree) {
267
- const result = /* @__PURE__ */ new Map();
268
- const visit = (nodes) => {
269
- for (const node of nodes) {
270
- const text = getRawCopyText(node.entry);
271
- if (text !== void 0) result.set(node.entry.id, text);
272
- visit(node.children);
273
- }
274
- };
275
- visit(tree);
276
- return result;
277
- }
278
- function getRawCopyText(entry) {
279
- let text;
291
+ function captureRawCopySource(entry) {
292
+ let source;
280
293
  if (entry.type === "message") {
281
- if (entry.message.role === "bashExecution") text = entry.message.command;
294
+ if (entry.message.role === "bashExecution") source = entry.message.command;
282
295
  else if ("content" in entry.message) {
283
- text = extractRawText(entry.message.content);
284
- if (!text && entry.message.role === "assistant") text = entry.message.errorMessage;
296
+ source = captureRawText(entry.message.content);
297
+ const empty = typeof source === "string" ? source.length === 0 : source.every((part) => part.length === 0);
298
+ if (empty && entry.message.role === "assistant") source = entry.message.errorMessage;
285
299
  }
286
- } else if (entry.type === "custom_message") text = extractRawText(entry.content);
287
- else if (entry.type === "compaction" || entry.type === "branch_summary") text = entry.summary;
288
- return text?.trim() ? text : void 0;
300
+ } else if (entry.type === "custom_message") source = captureRawText(entry.content);
301
+ else if (entry.type === "compaction" || entry.type === "branch_summary") source = entry.summary;
302
+ if (typeof source === "string") return /\S/u.test(source) ? source : void 0;
303
+ return source?.some((part) => /\S/u.test(part)) ? source : void 0;
289
304
  }
290
- function extractRawText(content) {
305
+ function captureRawText(content) {
291
306
  if (typeof content === "string") return content;
292
307
  if (!Array.isArray(content)) return "";
293
- return content.filter(
294
- (block) => block !== null && typeof block === "object" && "type" in block && block.type === "text" && "text" in block && typeof block.text === "string"
295
- ).map((block) => block.text).join("");
296
- }
297
- function collectSavedLabels(tree) {
298
- const result = /* @__PURE__ */ new Map();
299
- const visit = (nodes) => {
300
- for (const node of nodes) {
301
- result.set(node.entry.id, {
302
- label: node.label === void 0 ? void 0 : sanitizeSingleLine(node.label),
303
- labelTimestamp: node.labelTimestamp === void 0 ? void 0 : sanitizeSingleLine(node.labelTimestamp)
304
- });
305
- visit(node.children);
308
+ const parts = [];
309
+ for (const block of content) {
310
+ if (block !== null && typeof block === "object" && "type" in block && block.type === "text" && "text" in block && typeof block.text === "string") {
311
+ parts.push(block.text);
306
312
  }
307
- };
308
- visit(tree);
309
- return result;
313
+ }
314
+ return parts.length === 1 ? parts[0] : parts;
310
315
  }
311
316
  async function copyText(text, signal) {
312
317
  signal.throwIfAborted();
@@ -323,6 +328,7 @@ function formatError(error) {
323
328
  return error instanceof Error ? error.message : String(error);
324
329
  }
325
330
  export {
326
- pickMainEntry
331
+ pickMainEntry,
332
+ prepareTreeSnapshot
327
333
  };
328
- //# sourceMappingURL=main-tree-picker-WHRN26NJ.ts.map
334
+ //# sourceMappingURL=main-tree-picker-3PXJARQW.ts.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/main-tree-picker.ts"],
4
+ "sourcesContent": ["import {\n copyToClipboard,\n type ExtensionAPI,\n type ExtensionCommandContext,\n type SessionEntry,\n type SessionTreeNode,\n TreeSelectorComponent,\n} from \"@earendil-works/pi-coding-agent\";\nimport { type Component, type Focusable, Key, matchesKey } from \"@earendil-works/pi-tui\";\nimport { showBtwCustomPreservingEditor } from \"./menu.js\";\nimport { sanitizeSingleLine } from \"./text.js\";\n\nexport type MainEntryPickResult = { kind: \"selected\"; entryId: string } | { kind: \"back\" } | { kind: \"closed\" };\n\nexport interface MainThreadTreeSelector extends Component, Focusable {\n onCopy?: (text: string | undefined) => void;\n setViewLabel?(entryId: string, label: string | undefined, labelTimestamp?: string): void;\n dispose?(): void;\n}\n\nexport interface MainThreadTreeSelectorOptions {\n tree: SessionTreeNode[];\n currentLeafId: string | null;\n terminalRows: number;\n onSelect: (entryId: string) => void;\n onCancel: () => void;\n onCopy: (entryId: string | undefined, displayText: string | undefined) => void;\n onLabelChange: (entryId: string, label: string | undefined) => void;\n}\n\nexport interface MainThreadTreePickerDependencies {\n createSelector?: (options: MainThreadTreeSelectorOptions) => MainThreadTreeSelector;\n copyToClipboard?: (text: string, signal: AbortSignal) => Promise<void>;\n}\n\nclass MainThreadTreePickerComponent implements Component, Focusable {\n constructor(\n private readonly selector: MainThreadTreeSelector,\n private readonly onClose: () => void,\n ) {}\n\n get focused(): boolean {\n return this.selector.focused;\n }\n\n set focused(value: boolean) {\n this.selector.focused = value;\n }\n\n get wantsKeyRelease(): boolean | undefined {\n return this.selector.wantsKeyRelease;\n }\n\n render(width: number): string[] {\n return this.selector.render(width);\n }\n\n handleInput(data: string): void {\n if (matchesKey(data, Key.ctrl(\"c\"))) {\n this.onClose();\n return;\n }\n this.selector.handleInput?.(data);\n }\n\n invalidate(): void {\n this.selector.invalidate();\n }\n\n dispose(): void {\n this.selector.dispose?.();\n this.onClose();\n }\n}\n\nexport async function pickMainEntry(\n pi: ExtensionAPI,\n ctx: ExtensionCommandContext,\n dependencies: MainThreadTreePickerDependencies = {},\n): Promise<MainEntryPickResult> {\n let rawTree: SessionTreeNode[];\n let currentLeafId: string | null;\n try {\n rawTree = ctx.sessionManager.getTree();\n currentLeafId = ctx.sessionManager.getLeafId();\n } catch {\n return { kind: \"closed\" };\n }\n\n if (rawTree.length === 0) {\n notifySafely(ctx, \"No main-thread entries are available\", \"warning\");\n return { kind: \"back\" };\n }\n\n const { tree, rawCopyText, savedLabels } = prepareTreeSnapshot(rawTree);\n const createSelector = dependencies.createSelector ?? createNativeTreeSelector;\n const copy = dependencies.copyToClipboard ?? copyText;\n const copyControllers = new Set<AbortController>();\n const copyTasks = new Set<Promise<void>>();\n const abortCopies = () => {\n for (const controller of copyControllers) {\n controller.abort(new Error(\"The main-thread tree picker closed\"));\n }\n };\n const result = await showBtwCustomPreservingEditor<MainEntryPickResult>(ctx, (tui, _theme, _keybindings, done) => {\n let settled = false;\n let selector: MainThreadTreeSelector | undefined;\n const finish = (value: MainEntryPickResult) => {\n if (settled) return;\n settled = true;\n abortCopies();\n done(value);\n };\n const onCopy = (entryId: string | undefined, displayText: string | undefined) => {\n if (settled) return;\n let text: string | undefined;\n try {\n const source = entryId ? rawCopyText.get(entryId) : displayText;\n text = typeof source === \"string\" ? source : source?.join(\"\");\n } catch (error: unknown) {\n notifySafely(ctx, `Could not copy selected message: ${formatError(error)}`, \"error\");\n return;\n }\n if (!text) {\n notifySafely(ctx, \"Selected entry has no text to copy\", \"warning\");\n return;\n }\n const controller = new AbortController();\n copyControllers.add(controller);\n let operation: Promise<void>;\n try {\n operation = copy(text, controller.signal);\n } catch (error: unknown) {\n operation = Promise.reject(error);\n }\n let task!: Promise<void>;\n task = operation\n .then(() => {\n if (!settled) notifySafely(ctx, \"Copied selected message\", \"info\");\n })\n .catch((error: unknown) => {\n if (!settled && !controller.signal.aborted) {\n notifySafely(ctx, `Could not copy selected message: ${formatError(error)}`, \"error\");\n }\n })\n .finally(() => {\n copyControllers.delete(controller);\n copyTasks.delete(task);\n });\n copyTasks.add(task);\n };\n const restoreLabel = (entryId: string) => {\n const previous = savedLabels.get(entryId);\n selector?.setViewLabel?.(entryId, previous?.label, previous?.labelTimestamp);\n tui.requestRender();\n };\n const onLabelChange = (entryId: string, label: string | undefined) => {\n if (settled) return;\n try {\n if (!ctx.sessionManager.getEntry(entryId)) {\n restoreLabel(entryId);\n notifySafely(ctx, \"The selected main-thread entry is no longer available\", \"warning\");\n return;\n }\n const persistedLabel = label === undefined ? undefined : sanitizeSingleLine(label);\n pi.setLabel(entryId, persistedLabel);\n if (persistedLabel === undefined) savedLabels.delete(entryId);\n else savedLabels.set(entryId, { label: persistedLabel });\n selector?.setViewLabel?.(entryId, persistedLabel);\n tui.requestRender();\n } catch (error: unknown) {\n restoreLabel(entryId);\n notifySafely(ctx, `Could not update tree label: ${formatError(error)}`, \"error\");\n }\n };\n selector = createSelector({\n tree,\n currentLeafId,\n terminalRows: tui.terminal.rows,\n onSelect: (entryId) => finish({ kind: \"selected\", entryId }),\n onCancel: () => finish({ kind: \"back\" }),\n onCopy,\n onLabelChange,\n });\n return new MainThreadTreePickerComponent(selector, () => finish({ kind: \"closed\" }));\n });\n abortCopies();\n await Promise.allSettled([...copyTasks]);\n\n return result ?? { kind: \"closed\" };\n}\n\nfunction createNativeTreeSelector(options: MainThreadTreeSelectorOptions): MainThreadTreeSelector {\n const selector = new TreeSelectorComponent(\n options.tree,\n options.currentLeafId,\n options.terminalRows,\n options.onSelect,\n options.onCancel,\n options.onLabelChange,\n );\n selector.onCopy = (displayText) => options.onCopy(selector.getTreeList().getSelectedNode()?.entry.id, displayText);\n const result = selector as MainThreadTreeSelector;\n result.setViewLabel = (entryId, label, labelTimestamp) =>\n selector.getTreeList().updateNodeLabel(entryId, label, labelTimestamp);\n return result;\n}\n\ntype RawCopySource = string | readonly string[];\n\n/** @internal Package-local snapshot test boundary; not an extension entrypoint. */\nexport function prepareTreeSnapshot(rawTree: readonly SessionTreeNode[]): {\n tree: SessionTreeNode[];\n rawCopyText: Map<string, RawCopySource>;\n savedLabels: Map<string, SavedLabel>;\n} {\n const tree: SessionTreeNode[] = [];\n const rawCopyText = new Map<string, RawCopySource>();\n const savedLabels = new Map<string, SavedLabel>();\n // Keep traversal state on the heap: valid session histories can be arbitrarily deep.\n const stack = [{ source: rawTree, target: tree, index: 0 }];\n while (stack.length > 0) {\n const frame = stack[stack.length - 1];\n if (frame.index === frame.source.length) {\n stack.pop();\n continue;\n }\n const node = frame.source[frame.index++];\n const label = node.label === undefined ? undefined : sanitizeSingleLine(node.label);\n const labelTimestamp = node.labelTimestamp === undefined ? undefined : sanitizeSingleLine(node.labelTimestamp);\n const displayNode: SessionTreeNode = {\n entry: sanitizeEntryForDisplay(node.entry),\n children: [],\n };\n if (label !== undefined) displayNode.label = label;\n if (labelTimestamp !== undefined) displayNode.labelTimestamp = labelTimestamp;\n frame.target.push(displayNode);\n const source = captureRawCopySource(node.entry);\n if (source !== undefined) rawCopyText.set(node.entry.id, source);\n if (label !== undefined || labelTimestamp !== undefined) {\n savedLabels.set(node.entry.id, { label, labelTimestamp });\n }\n if (node.children.length > 0) {\n stack.push({ source: node.children, target: displayNode.children, index: 0 });\n }\n }\n return { tree, rawCopyText, savedLabels };\n}\n\nfunction sanitizeEntryForDisplay(entry: SessionEntry): SessionEntry {\n switch (entry.type) {\n case \"message\": {\n const message = { ...entry.message } as Record<string, unknown>;\n if (\"content\" in entry.message) message.content = sanitizeDisplayContent(entry.message.content);\n for (const key of [\"role\", \"errorMessage\", \"command\", \"toolName\"] as const) {\n const value = message[key];\n if (typeof value === \"string\") message[key] = sanitizeSingleLine(value);\n }\n return { ...entry, message } as unknown as SessionEntry;\n }\n case \"custom_message\":\n return {\n ...entry,\n customType: sanitizeSingleLine(entry.customType),\n content: sanitizeDisplayContent(entry.content) as typeof entry.content,\n };\n case \"compaction\":\n return { ...entry, summary: sanitizeSingleLine(entry.summary) };\n case \"branch_summary\":\n return { ...entry, summary: sanitizeSingleLine(entry.summary) };\n case \"model_change\":\n return {\n ...entry,\n provider: sanitizeSingleLine(entry.provider),\n modelId: sanitizeSingleLine(entry.modelId),\n };\n case \"thinking_level_change\":\n return { ...entry, thinkingLevel: sanitizeSingleLine(entry.thinkingLevel) };\n case \"custom\":\n return { ...entry, customType: sanitizeSingleLine(entry.customType) };\n case \"context_edit\":\n return { ...entry, targetId: sanitizeSingleLine(entry.targetId) };\n case \"label\":\n return {\n ...entry,\n label: entry.label === undefined ? undefined : sanitizeSingleLine(entry.label),\n };\n case \"session_info\":\n return {\n ...entry,\n name: entry.name === undefined ? undefined : sanitizeSingleLine(entry.name),\n };\n case \"usage\":\n return {\n ...entry,\n kind: sanitizeSingleLine(entry.kind),\n provider: sanitizeSingleLine(entry.provider),\n model: sanitizeSingleLine(entry.model),\n note: entry.note === undefined ? undefined : sanitizeSingleLine(entry.note),\n };\n }\n}\n\nfunction sanitizeDisplayContent(content: unknown): unknown {\n if (typeof content === \"string\") return sanitizeSingleLine(content);\n if (!Array.isArray(content)) return content;\n return content.map((block) => {\n if (block === null || typeof block !== \"object\" || !(\"type\" in block)) return block;\n if (block.type === \"text\" && \"text\" in block && typeof block.text === \"string\") {\n return { ...block, text: sanitizeSingleLine(block.text) };\n }\n if (block.type === \"toolCall\") {\n const copy = { ...block } as Record<string, unknown>;\n if (typeof copy.name === \"string\") copy.name = sanitizeSingleLine(copy.name);\n copy.arguments = sanitizeToolArguments(copy.arguments, new WeakMap());\n return copy;\n }\n return block;\n });\n}\n\nfunction sanitizeToolArguments(value: unknown, seen: WeakMap<object, unknown>): unknown {\n if (typeof value === \"string\") return sanitizeSingleLine(value);\n if (value === null || typeof value !== \"object\") return value;\n const existing = seen.get(value);\n if (existing !== undefined) return existing;\n if (Array.isArray(value)) {\n const result: unknown[] = [];\n seen.set(value, result);\n for (const item of value) result.push(sanitizeToolArguments(item, seen));\n return result;\n }\n const result: Record<string, unknown> = {};\n seen.set(value, result);\n for (const [key, item] of Object.entries(value)) {\n result[key] = sanitizeToolArguments(item, seen);\n }\n return result;\n}\n\nfunction captureRawCopySource(entry: SessionEntry): RawCopySource | undefined {\n let source: RawCopySource | undefined;\n if (entry.type === \"message\") {\n if (entry.message.role === \"bashExecution\") source = entry.message.command;\n else if (\"content\" in entry.message) {\n source = captureRawText(entry.message.content);\n const empty = typeof source === \"string\" ? source.length === 0 : source.every((part) => part.length === 0);\n if (empty && entry.message.role === \"assistant\") source = entry.message.errorMessage;\n }\n } else if (entry.type === \"custom_message\") source = captureRawText(entry.content);\n else if (entry.type === \"compaction\" || entry.type === \"branch_summary\") source = entry.summary;\n if (typeof source === \"string\") return /\\S/u.test(source) ? source : undefined;\n return source?.some((part) => /\\S/u.test(part)) ? source : undefined;\n}\n\nfunction captureRawText(content: unknown): RawCopySource {\n if (typeof content === \"string\") return content;\n if (!Array.isArray(content)) return \"\";\n // Retain immutable strings, not live blocks or joined copies of every message.\n const parts: string[] = [];\n for (const block of content) {\n if (\n block !== null &&\n typeof block === \"object\" &&\n \"type\" in block &&\n block.type === \"text\" &&\n \"text\" in block &&\n typeof block.text === \"string\"\n ) {\n parts.push(block.text);\n }\n }\n return parts.length === 1 ? parts[0] : parts;\n}\n\ninterface SavedLabel {\n label: string | undefined;\n labelTimestamp?: string;\n}\n\nasync function copyText(text: string, signal: AbortSignal): Promise<void> {\n signal.throwIfAborted();\n await copyToClipboard(text);\n signal.throwIfAborted();\n}\n\nfunction notifySafely(\n ctx: ExtensionCommandContext,\n message: string,\n level: Parameters<ExtensionCommandContext[\"ui\"][\"notify\"]>[1],\n): void {\n try {\n ctx.ui.notify(sanitizeSingleLine(message), level);\n } catch {\n // The command context may have been replaced while the selector was open.\n }\n}\n\nfunction formatError(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n"],
5
+ "mappings": ";;;;;;;;;;;AAAA;AAAA,EACE;AAAA,EAKA;AAAA,OACK;AACP,SAAyC,KAAK,kBAAkB;AA2BhE,IAAM,gCAAN,MAAoE;AAAA,EAClE,YACmB,UACA,SACjB;AAFiB;AACA;AAAA,EAChB;AAAA,EAFgB;AAAA,EACA;AAAA,EAGnB,IAAI,UAAmB;AACrB,WAAO,KAAK,SAAS;AAAA,EACvB;AAAA,EAEA,IAAI,QAAQ,OAAgB;AAC1B,SAAK,SAAS,UAAU;AAAA,EAC1B;AAAA,EAEA,IAAI,kBAAuC;AACzC,WAAO,KAAK,SAAS;AAAA,EACvB;AAAA,EAEA,OAAO,OAAyB;AAC9B,WAAO,KAAK,SAAS,OAAO,KAAK;AAAA,EACnC;AAAA,EAEA,YAAY,MAAoB;AAC9B,QAAI,WAAW,MAAM,IAAI,KAAK,GAAG,CAAC,GAAG;AACnC,WAAK,QAAQ;AACb;AAAA,IACF;AACA,SAA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BAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAC9D;",
6
+ "names": ["result"]
7
+ }
package/dist/index.ts CHANGED
@@ -217,7 +217,7 @@ var runFullscreenOnFirstUse = async (ctx, run, options) => {
217
217
  return runBtwFullscreen(ctx, run, options);
218
218
  };
219
219
  var pickEntryOnFirstUse = async (pi, ctx) => {
220
- const { pickMainEntry } = await import("./chunks/main-tree-picker-WHRN26NJ.ts");
220
+ const { pickMainEntry } = await import("./chunks/main-tree-picker-3PXJARQW.ts");
221
221
  if (ctx.signal?.aborted) return { kind: "closed" };
222
222
  return pickMainEntry(pi, ctx);
223
223
  };
@@ -0,0 +1,39 @@
1
+ # Main-thread tree snapshots
2
+
3
+ The tree picker preserves the entries available when it opens. Display text is sanitized, but copying uses the original text captured in that snapshot, not a later lookup in the current session.
4
+
5
+ ## Allocation behavior
6
+
7
+ `prepareTreeSnapshot()` builds the sanitized tree in one iterative depth-first traversal. It keeps one raw string for single-block copy sources and an array of immutable strings for multi-block sources. It does not retain image or tool-call payloads in copy sources. The copy callback joins only the selected entry's fragments and does not cache that joined string. If joining fails, the picker reports a sanitized copy error without starting clipboard work.
8
+
9
+ Whitespace-only sources are excluded without joining them. Assistant errors replace empty content, but do not replace whitespace-only content. Copy preserves the original spaces, line breaks, terminal controls, and text-block order.
10
+
11
+ The saved-label map contains only entries with a defined label or timestamp. Empty strings and timestamp-only values remain distinct from absent values. Successful label updates replace the saved value, clearing removes it, and failed writes restore the last saved value.
12
+
13
+ The display tree still contains the full session history. Its preparation time and retained heap remain proportional to history size. Joining a selected multi-block message moves that work to each copy action; this change does not guarantee faster picker startup.
14
+
15
+ ## Measured allocation change
16
+
17
+ The baseline was repository commit `348ed352`. The comparison used the actual updated snapshot functions, without a replacement implementation. Both sides included entry sanitization and snapshot maps, but excluded Pi's core tree builder, native selector, Jiti startup, and clipboard I/O.
18
+
19
+ Measurements ran on macOS arm64 with Node `26.11.1`. Each synthetic session was a 10,000-node linear tree. Each result is the median of three separate Node processes. Each process performed three warmup preparations, then measured retained heap with `--expose-gc` before and after one preparation. The input was allocated before measurement and the output was retained through the final collection.
20
+
21
+ | Workload | Baseline heap | Updated heap | Baseline preparation | Updated preparation |
22
+ | --- | ---: | ---: | ---: | ---: |
23
+ | Short single-block messages | 6.228 MiB | 5.410 MiB | 8.07 ms | 7.71 ms |
24
+ | Four-block messages | 27.965 MiB | 18.685 MiB | 113.45 ms | 110.80 ms |
25
+ | Four-block messages, all labeled | 29.032 MiB | 20.571 MiB | 121.62 ms | 122.65 ms |
26
+ | Metadata entries | 4.184 MiB | 3.368 MiB | 2.94 ms | 2.53 ms |
27
+ | Whitespace-only blocks | 6.630 MiB | 5.812 MiB | 115.55 ms | 113.57 ms |
28
+
29
+ Message text used an entry/block prefix followed by 32 `x` characters for the short case, or 256 `x` characters per block for four-block cases. Whitespace entries had four blocks of 256 spaces. Except for the all-labeled and metadata cases, labels occurred every 1,000 entries. Metadata entries were unlabeled model changes. Disposable benchmark files were removed after the comparison.
30
+
31
+ The multi-block workload retained about 33% less snapshot heap. The other measured workloads also retained less heap. The all-labeled workload took about one millisecond longer in this sample, so the timing data does not establish a general startup-speed improvement. These samples are not deterministic test thresholds or total Pi memory measurements.
32
+
33
+ ## Verification and platform limits
34
+
35
+ `test/main-tree-snapshot.test.ts` checks fragment retention, whitespace classification, and sparse-label storage. `test/main-tree-copy.test.ts` checks copy-source branches, immutable snapshot behavior, label state transitions, missing entries, and cancellation of pending clipboard work. The existing deep-tree and Jiti tests cover native rendering and lazy package loading with 10,000 entries.
36
+
37
+ The package-directory smoke checks offline registration, RPC guards, unchanged transcript state, and shutdown. It does not verify a physical terminal or a real clipboard.
38
+
39
+ Windows terminal behavior and the original private reported session remain unverified. A Windows maintainer with a synthetic deep session can check rendering, raw copying, label rollback, and cancellation in a physical terminal. The expected behavior is unchanged; this platform check does not replace the deterministic tests or repository verification gates.
package/docs/workflows.md CHANGED
@@ -13,6 +13,7 @@ The side thread retains the last 40,000 characters of this text and adds a trunc
13
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).
14
14
  An explicit `Shift+L` label edit is the selector's only main-session mutation and persists through Pi.
15
15
  Native tree copying reports success or failure; Escape returns to the manager and Ctrl+C closes the flow.
16
+ The [tree snapshot guide](./main-tree-snapshots.md) describes allocation behavior, measurements, and verification limits.
16
17
 
17
18
  **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.
18
19
  The first question remains the title; threads are ordered by their newest answer or visible error.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@narumitw/pi-btw",
3
- "version": "0.63.5",
3
+ "version": "0.63.7",
4
4
  "description": "Pi extension that adds a /btw side-question command.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -92,9 +92,7 @@ export async function pickMainEntry(
92
92
  return { kind: "back" };
93
93
  }
94
94
 
95
- const tree = sanitizeTreeForDisplay(rawTree);
96
- const rawCopyText = collectRawCopyText(rawTree);
97
- const savedLabels = collectSavedLabels(rawTree);
95
+ const { tree, rawCopyText, savedLabels } = prepareTreeSnapshot(rawTree);
98
96
  const createSelector = dependencies.createSelector ?? createNativeTreeSelector;
99
97
  const copy = dependencies.copyToClipboard ?? copyText;
100
98
  const copyControllers = new Set<AbortController>();
@@ -115,7 +113,14 @@ export async function pickMainEntry(
115
113
  };
116
114
  const onCopy = (entryId: string | undefined, displayText: string | undefined) => {
117
115
  if (settled) return;
118
- const text = entryId ? rawCopyText.get(entryId) : displayText;
116
+ let text: string | undefined;
117
+ try {
118
+ const source = entryId ? rawCopyText.get(entryId) : displayText;
119
+ text = typeof source === "string" ? source : source?.join("");
120
+ } catch (error: unknown) {
121
+ notifySafely(ctx, `Could not copy selected message: ${formatError(error)}`, "error");
122
+ return;
123
+ }
119
124
  if (!text) {
120
125
  notifySafely(ctx, "Selected entry has no text to copy", "warning");
121
126
  return;
@@ -159,7 +164,8 @@ export async function pickMainEntry(
159
164
  }
160
165
  const persistedLabel = label === undefined ? undefined : sanitizeSingleLine(label);
161
166
  pi.setLabel(entryId, persistedLabel);
162
- savedLabels.set(entryId, { label: persistedLabel });
167
+ if (persistedLabel === undefined) savedLabels.delete(entryId);
168
+ else savedLabels.set(entryId, { label: persistedLabel });
163
169
  selector?.setViewLabel?.(entryId, persistedLabel);
164
170
  tui.requestRender();
165
171
  } catch (error: unknown) {
@@ -200,18 +206,45 @@ function createNativeTreeSelector(options: MainThreadTreeSelectorOptions): MainT
200
206
  return result;
201
207
  }
202
208
 
203
- function sanitizeTreeForDisplay(tree: readonly SessionTreeNode[]): SessionTreeNode[] {
204
- return tree.map((node) => {
205
- const result: SessionTreeNode = {
209
+ type RawCopySource = string | readonly string[];
210
+
211
+ /** @internal Package-local snapshot test boundary; not an extension entrypoint. */
212
+ export function prepareTreeSnapshot(rawTree: readonly SessionTreeNode[]): {
213
+ tree: SessionTreeNode[];
214
+ rawCopyText: Map<string, RawCopySource>;
215
+ savedLabels: Map<string, SavedLabel>;
216
+ } {
217
+ const tree: SessionTreeNode[] = [];
218
+ const rawCopyText = new Map<string, RawCopySource>();
219
+ const savedLabels = new Map<string, SavedLabel>();
220
+ // Keep traversal state on the heap: valid session histories can be arbitrarily deep.
221
+ const stack = [{ source: rawTree, target: tree, index: 0 }];
222
+ while (stack.length > 0) {
223
+ const frame = stack[stack.length - 1];
224
+ if (frame.index === frame.source.length) {
225
+ stack.pop();
226
+ continue;
227
+ }
228
+ const node = frame.source[frame.index++];
229
+ const label = node.label === undefined ? undefined : sanitizeSingleLine(node.label);
230
+ const labelTimestamp = node.labelTimestamp === undefined ? undefined : sanitizeSingleLine(node.labelTimestamp);
231
+ const displayNode: SessionTreeNode = {
206
232
  entry: sanitizeEntryForDisplay(node.entry),
207
- children: sanitizeTreeForDisplay(node.children),
233
+ children: [],
208
234
  };
209
- if (node.label !== undefined) result.label = sanitizeSingleLine(node.label);
210
- if (node.labelTimestamp !== undefined) {
211
- result.labelTimestamp = sanitizeSingleLine(node.labelTimestamp);
235
+ if (label !== undefined) displayNode.label = label;
236
+ if (labelTimestamp !== undefined) displayNode.labelTimestamp = labelTimestamp;
237
+ frame.target.push(displayNode);
238
+ const source = captureRawCopySource(node.entry);
239
+ if (source !== undefined) rawCopyText.set(node.entry.id, source);
240
+ if (label !== undefined || labelTimestamp !== undefined) {
241
+ savedLabels.set(node.entry.id, { label, labelTimestamp });
212
242
  }
213
- return result;
214
- });
243
+ if (node.children.length > 0) {
244
+ stack.push({ source: node.children, target: displayNode.children, index: 0 });
245
+ }
246
+ }
247
+ return { tree, rawCopyText, savedLabels };
215
248
  }
216
249
 
217
250
  function sanitizeEntryForDisplay(entry: SessionEntry): SessionEntry {
@@ -305,47 +338,39 @@ function sanitizeToolArguments(value: unknown, seen: WeakMap<object, unknown>):
305
338
  return result;
306
339
  }
307
340
 
308
- function collectRawCopyText(tree: readonly SessionTreeNode[]): Map<string, string> {
309
- const result = new Map<string, string>();
310
- const visit = (nodes: readonly SessionTreeNode[]) => {
311
- for (const node of nodes) {
312
- const text = getRawCopyText(node.entry);
313
- if (text !== undefined) result.set(node.entry.id, text);
314
- visit(node.children);
315
- }
316
- };
317
- visit(tree);
318
- return result;
319
- }
320
-
321
- function getRawCopyText(entry: SessionEntry): string | undefined {
322
- let text: string | undefined;
341
+ function captureRawCopySource(entry: SessionEntry): RawCopySource | undefined {
342
+ let source: RawCopySource | undefined;
323
343
  if (entry.type === "message") {
324
- if (entry.message.role === "bashExecution") text = entry.message.command;
344
+ if (entry.message.role === "bashExecution") source = entry.message.command;
325
345
  else if ("content" in entry.message) {
326
- text = extractRawText(entry.message.content);
327
- if (!text && entry.message.role === "assistant") text = entry.message.errorMessage;
346
+ source = captureRawText(entry.message.content);
347
+ const empty = typeof source === "string" ? source.length === 0 : source.every((part) => part.length === 0);
348
+ if (empty && entry.message.role === "assistant") source = entry.message.errorMessage;
328
349
  }
329
- } else if (entry.type === "custom_message") text = extractRawText(entry.content);
330
- else if (entry.type === "compaction" || entry.type === "branch_summary") text = entry.summary;
331
- return text?.trim() ? text : undefined;
350
+ } else if (entry.type === "custom_message") source = captureRawText(entry.content);
351
+ else if (entry.type === "compaction" || entry.type === "branch_summary") source = entry.summary;
352
+ if (typeof source === "string") return /\S/u.test(source) ? source : undefined;
353
+ return source?.some((part) => /\S/u.test(part)) ? source : undefined;
332
354
  }
333
355
 
334
- function extractRawText(content: unknown): string {
356
+ function captureRawText(content: unknown): RawCopySource {
335
357
  if (typeof content === "string") return content;
336
358
  if (!Array.isArray(content)) return "";
337
- return content
338
- .filter(
339
- (block): block is { type: "text"; text: string } =>
340
- block !== null &&
341
- typeof block === "object" &&
342
- "type" in block &&
343
- block.type === "text" &&
344
- "text" in block &&
345
- typeof block.text === "string",
346
- )
347
- .map((block) => block.text)
348
- .join("");
359
+ // Retain immutable strings, not live blocks or joined copies of every message.
360
+ const parts: string[] = [];
361
+ for (const block of content) {
362
+ if (
363
+ block !== null &&
364
+ typeof block === "object" &&
365
+ "type" in block &&
366
+ block.type === "text" &&
367
+ "text" in block &&
368
+ typeof block.text === "string"
369
+ ) {
370
+ parts.push(block.text);
371
+ }
372
+ }
373
+ return parts.length === 1 ? parts[0] : parts;
349
374
  }
350
375
 
351
376
  interface SavedLabel {
@@ -353,21 +378,6 @@ interface SavedLabel {
353
378
  labelTimestamp?: string;
354
379
  }
355
380
 
356
- function collectSavedLabels(tree: readonly SessionTreeNode[]): Map<string, SavedLabel> {
357
- const result = new Map<string, SavedLabel>();
358
- const visit = (nodes: readonly SessionTreeNode[]) => {
359
- for (const node of nodes) {
360
- result.set(node.entry.id, {
361
- label: node.label === undefined ? undefined : sanitizeSingleLine(node.label),
362
- labelTimestamp: node.labelTimestamp === undefined ? undefined : sanitizeSingleLine(node.labelTimestamp),
363
- });
364
- visit(node.children);
365
- }
366
- };
367
- visit(tree);
368
- return result;
369
- }
370
-
371
381
  async function copyText(text: string, signal: AbortSignal): Promise<void> {
372
382
  signal.throwIfAborted();
373
383
  await copyToClipboard(text);
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../src/main-tree-picker.ts"],
4
- "sourcesContent": ["import {\n copyToClipboard,\n type ExtensionAPI,\n type ExtensionCommandContext,\n type SessionEntry,\n type SessionTreeNode,\n TreeSelectorComponent,\n} from \"@earendil-works/pi-coding-agent\";\nimport { type Component, type Focusable, Key, matchesKey } from \"@earendil-works/pi-tui\";\nimport { showBtwCustomPreservingEditor } from \"./menu.js\";\nimport { sanitizeSingleLine } from \"./text.js\";\n\nexport type MainEntryPickResult = { kind: \"selected\"; entryId: string } | { kind: \"back\" } | { kind: \"closed\" };\n\nexport interface MainThreadTreeSelector extends Component, Focusable {\n onCopy?: (text: string | undefined) => void;\n setViewLabel?(entryId: string, label: string | undefined, labelTimestamp?: string): void;\n dispose?(): void;\n}\n\nexport interface MainThreadTreeSelectorOptions {\n tree: SessionTreeNode[];\n currentLeafId: string | null;\n terminalRows: number;\n onSelect: (entryId: string) => void;\n onCancel: () => void;\n onCopy: (entryId: string | undefined, displayText: string | undefined) => void;\n onLabelChange: (entryId: string, label: string | undefined) => void;\n}\n\nexport interface MainThreadTreePickerDependencies {\n createSelector?: (options: MainThreadTreeSelectorOptions) => MainThreadTreeSelector;\n copyToClipboard?: (text: string, signal: AbortSignal) => Promise<void>;\n}\n\nclass MainThreadTreePickerComponent implements Component, Focusable {\n constructor(\n private readonly selector: MainThreadTreeSelector,\n private readonly onClose: () => void,\n ) {}\n\n get focused(): boolean {\n return this.selector.focused;\n }\n\n set focused(value: boolean) {\n this.selector.focused = value;\n }\n\n get wantsKeyRelease(): boolean | undefined {\n return this.selector.wantsKeyRelease;\n }\n\n render(width: number): string[] {\n return this.selector.render(width);\n }\n\n handleInput(data: string): void {\n if (matchesKey(data, Key.ctrl(\"c\"))) {\n this.onClose();\n return;\n }\n this.selector.handleInput?.(data);\n }\n\n invalidate(): void {\n this.selector.invalidate();\n }\n\n dispose(): void {\n this.selector.dispose?.();\n this.onClose();\n }\n}\n\nexport async function pickMainEntry(\n pi: ExtensionAPI,\n ctx: ExtensionCommandContext,\n dependencies: MainThreadTreePickerDependencies = {},\n): Promise<MainEntryPickResult> {\n let rawTree: SessionTreeNode[];\n let currentLeafId: string | null;\n try {\n rawTree = ctx.sessionManager.getTree();\n currentLeafId = ctx.sessionManager.getLeafId();\n } catch {\n return { kind: \"closed\" };\n }\n\n if (rawTree.length === 0) {\n notifySafely(ctx, \"No main-thread entries are available\", \"warning\");\n return { kind: \"back\" };\n }\n\n const tree = sanitizeTreeForDisplay(rawTree);\n const rawCopyText = collectRawCopyText(rawTree);\n const savedLabels = collectSavedLabels(rawTree);\n const createSelector = dependencies.createSelector ?? createNativeTreeSelector;\n const copy = dependencies.copyToClipboard ?? copyText;\n const copyControllers = new Set<AbortController>();\n const copyTasks = new Set<Promise<void>>();\n const abortCopies = () => {\n for (const controller of copyControllers) {\n controller.abort(new Error(\"The main-thread tree picker closed\"));\n }\n };\n const result = await showBtwCustomPreservingEditor<MainEntryPickResult>(ctx, (tui, _theme, _keybindings, done) => {\n let settled = false;\n let selector: MainThreadTreeSelector | undefined;\n const finish = (value: MainEntryPickResult) => {\n if (settled) return;\n settled = true;\n abortCopies();\n done(value);\n };\n const onCopy = (entryId: string | undefined, displayText: string | undefined) => {\n if (settled) return;\n const text = entryId ? rawCopyText.get(entryId) : displayText;\n if (!text) {\n notifySafely(ctx, \"Selected entry has no text to copy\", \"warning\");\n return;\n }\n const controller = new AbortController();\n copyControllers.add(controller);\n let operation: Promise<void>;\n try {\n operation = copy(text, controller.signal);\n } catch (error: unknown) {\n operation = Promise.reject(error);\n }\n let task!: Promise<void>;\n task = operation\n .then(() => {\n if (!settled) notifySafely(ctx, \"Copied selected message\", \"info\");\n })\n .catch((error: unknown) => {\n if (!settled && !controller.signal.aborted) {\n notifySafely(ctx, `Could not copy selected message: ${formatError(error)}`, \"error\");\n }\n })\n .finally(() => {\n copyControllers.delete(controller);\n copyTasks.delete(task);\n });\n copyTasks.add(task);\n };\n const restoreLabel = (entryId: string) => {\n const previous = savedLabels.get(entryId);\n selector?.setViewLabel?.(entryId, previous?.label, previous?.labelTimestamp);\n tui.requestRender();\n };\n const onLabelChange = (entryId: string, label: string | undefined) => {\n if (settled) return;\n try {\n if (!ctx.sessionManager.getEntry(entryId)) {\n restoreLabel(entryId);\n notifySafely(ctx, \"The selected main-thread entry is no longer available\", \"warning\");\n return;\n }\n const persistedLabel = label === undefined ? undefined : sanitizeSingleLine(label);\n pi.setLabel(entryId, persistedLabel);\n savedLabels.set(entryId, { label: persistedLabel });\n selector?.setViewLabel?.(entryId, persistedLabel);\n tui.requestRender();\n } catch (error: unknown) {\n restoreLabel(entryId);\n notifySafely(ctx, `Could not update tree label: ${formatError(error)}`, \"error\");\n }\n };\n selector = createSelector({\n tree,\n currentLeafId,\n terminalRows: tui.terminal.rows,\n onSelect: (entryId) => finish({ kind: \"selected\", entryId }),\n onCancel: () => finish({ kind: \"back\" }),\n onCopy,\n onLabelChange,\n });\n return new MainThreadTreePickerComponent(selector, () => finish({ kind: \"closed\" }));\n });\n abortCopies();\n await Promise.allSettled([...copyTasks]);\n\n return result ?? { kind: \"closed\" };\n}\n\nfunction createNativeTreeSelector(options: MainThreadTreeSelectorOptions): MainThreadTreeSelector {\n const selector = new TreeSelectorComponent(\n options.tree,\n options.currentLeafId,\n options.terminalRows,\n options.onSelect,\n options.onCancel,\n options.onLabelChange,\n );\n selector.onCopy = (displayText) => options.onCopy(selector.getTreeList().getSelectedNode()?.entry.id, displayText);\n const result = selector as MainThreadTreeSelector;\n result.setViewLabel = (entryId, label, labelTimestamp) =>\n selector.getTreeList().updateNodeLabel(entryId, label, labelTimestamp);\n return result;\n}\n\nfunction sanitizeTreeForDisplay(tree: readonly SessionTreeNode[]): SessionTreeNode[] {\n return tree.map((node) => {\n const result: SessionTreeNode = {\n entry: sanitizeEntryForDisplay(node.entry),\n children: sanitizeTreeForDisplay(node.children),\n };\n if (node.label !== undefined) result.label = sanitizeSingleLine(node.label);\n if (node.labelTimestamp !== undefined) {\n result.labelTimestamp = sanitizeSingleLine(node.labelTimestamp);\n }\n return result;\n });\n}\n\nfunction sanitizeEntryForDisplay(entry: SessionEntry): SessionEntry {\n switch (entry.type) {\n case \"message\": {\n const message = { ...entry.message } as Record<string, unknown>;\n if (\"content\" in entry.message) message.content = sanitizeDisplayContent(entry.message.content);\n for (const key of [\"role\", \"errorMessage\", \"command\", \"toolName\"] as const) {\n const value = message[key];\n if (typeof value === \"string\") message[key] = sanitizeSingleLine(value);\n }\n return { ...entry, message } as unknown as SessionEntry;\n }\n case \"custom_message\":\n return {\n ...entry,\n customType: sanitizeSingleLine(entry.customType),\n content: sanitizeDisplayContent(entry.content) as typeof entry.content,\n };\n case \"compaction\":\n return { ...entry, summary: sanitizeSingleLine(entry.summary) };\n case \"branch_summary\":\n return { ...entry, summary: sanitizeSingleLine(entry.summary) };\n case \"model_change\":\n return {\n ...entry,\n provider: sanitizeSingleLine(entry.provider),\n modelId: sanitizeSingleLine(entry.modelId),\n };\n case \"thinking_level_change\":\n return { ...entry, thinkingLevel: sanitizeSingleLine(entry.thinkingLevel) };\n case \"custom\":\n return { ...entry, customType: sanitizeSingleLine(entry.customType) };\n case \"context_edit\":\n return { ...entry, targetId: sanitizeSingleLine(entry.targetId) };\n case \"label\":\n return {\n ...entry,\n label: entry.label === undefined ? undefined : sanitizeSingleLine(entry.label),\n };\n case \"session_info\":\n return {\n ...entry,\n name: entry.name === undefined ? undefined : sanitizeSingleLine(entry.name),\n };\n case \"usage\":\n return {\n ...entry,\n kind: sanitizeSingleLine(entry.kind),\n provider: sanitizeSingleLine(entry.provider),\n model: sanitizeSingleLine(entry.model),\n note: entry.note === undefined ? undefined : sanitizeSingleLine(entry.note),\n };\n }\n}\n\nfunction sanitizeDisplayContent(content: unknown): unknown {\n if (typeof content === \"string\") return sanitizeSingleLine(content);\n if (!Array.isArray(content)) return content;\n return content.map((block) => {\n if (block === null || typeof block !== \"object\" || !(\"type\" in block)) return block;\n if (block.type === \"text\" && \"text\" in block && typeof block.text === \"string\") {\n return { ...block, text: sanitizeSingleLine(block.text) };\n }\n if (block.type === \"toolCall\") {\n const copy = { ...block } as Record<string, unknown>;\n if (typeof copy.name === \"string\") copy.name = sanitizeSingleLine(copy.name);\n copy.arguments = sanitizeToolArguments(copy.arguments, new WeakMap());\n return copy;\n }\n return block;\n });\n}\n\nfunction sanitizeToolArguments(value: unknown, seen: WeakMap<object, unknown>): unknown {\n if (typeof value === \"string\") return sanitizeSingleLine(value);\n if (value === null || typeof value !== \"object\") return value;\n const existing = seen.get(value);\n if (existing !== undefined) return existing;\n if (Array.isArray(value)) {\n const result: unknown[] = [];\n seen.set(value, result);\n for (const item of value) result.push(sanitizeToolArguments(item, seen));\n return result;\n }\n const result: Record<string, unknown> = {};\n seen.set(value, result);\n for (const [key, item] of Object.entries(value)) {\n result[key] = sanitizeToolArguments(item, seen);\n }\n return result;\n}\n\nfunction collectRawCopyText(tree: readonly SessionTreeNode[]): Map<string, string> {\n const result = new Map<string, string>();\n const visit = (nodes: readonly SessionTreeNode[]) => {\n for (const node of nodes) {\n const text = getRawCopyText(node.entry);\n if (text !== undefined) result.set(node.entry.id, text);\n visit(node.children);\n }\n };\n visit(tree);\n return result;\n}\n\nfunction getRawCopyText(entry: SessionEntry): string | undefined {\n let text: string | undefined;\n if (entry.type === \"message\") {\n if (entry.message.role === \"bashExecution\") text = entry.message.command;\n else if (\"content\" in entry.message) {\n text = extractRawText(entry.message.content);\n if (!text && entry.message.role === \"assistant\") text = entry.message.errorMessage;\n }\n } else if (entry.type === \"custom_message\") text = extractRawText(entry.content);\n else if (entry.type === \"compaction\" || entry.type === \"branch_summary\") text = entry.summary;\n return text?.trim() ? text : undefined;\n}\n\nfunction extractRawText(content: unknown): string {\n if (typeof content === \"string\") return content;\n if (!Array.isArray(content)) return \"\";\n return content\n .filter(\n (block): block is { type: \"text\"; text: string } =>\n block !== null &&\n typeof block === \"object\" &&\n \"type\" in block &&\n block.type === \"text\" &&\n \"text\" in block &&\n typeof block.text === \"string\",\n )\n .map((block) => block.text)\n .join(\"\");\n}\n\ninterface SavedLabel {\n label: string | undefined;\n labelTimestamp?: string;\n}\n\nfunction collectSavedLabels(tree: readonly SessionTreeNode[]): Map<string, SavedLabel> {\n const result = new Map<string, SavedLabel>();\n const visit = (nodes: readonly SessionTreeNode[]) => {\n for (const node of nodes) {\n result.set(node.entry.id, {\n label: node.label === undefined ? undefined : sanitizeSingleLine(node.label),\n labelTimestamp: node.labelTimestamp === undefined ? undefined : sanitizeSingleLine(node.labelTimestamp),\n });\n visit(node.children);\n }\n };\n visit(tree);\n return result;\n}\n\nasync function copyText(text: string, signal: AbortSignal): Promise<void> {\n signal.throwIfAborted();\n await copyToClipboard(text);\n signal.throwIfAborted();\n}\n\nfunction notifySafely(\n ctx: ExtensionCommandContext,\n message: string,\n level: Parameters<ExtensionCommandContext[\"ui\"][\"notify\"]>[1],\n): void {\n try {\n ctx.ui.notify(sanitizeSingleLine(message), level);\n } catch {\n // The command context may have been replaced while the selector was open.\n }\n}\n\nfunction formatError(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n"],
5
- "mappings": ";;;;;;;;;;;AAAA;AAAA,EACE;AAAA,EAKA;AAAA,OACK;AACP,SAAyC,KAAK,kBAAkB;AA2BhE,IAAM,gCAAN,MAAoE;AAAA,EAClE,YACmB,UACA,SACjB;AAFiB;AACA;AAAA,EAChB;AAAA,EAFgB;AAAA,EACA;AAAA,EAGnB,IAAI,UAAmB;AACrB,WAAO,KAAK,SAAS;AAAA,EACvB;AAAA,EAEA,IAAI,QAAQ,OAAgB;AAC1B,SAAK,SAAS,UAAU;AAAA,EAC1B;AAAA,EAEA,IAAI,kBAAuC;AACzC,WAAO,KAAK,SAAS;AAAA,EACvB;AAAA,EAEA,OAAO,OAAyB;AAC9B,WAAO,KAAK,SAAS,OAAO,KAAK;AAAA,EACnC;AAAA,EAEA,YAAY,MAAoB;AAC9B,QAAI,WAAW,MAA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