@oh-my-pi/pi-coding-agent 17.1.7 → 17.1.8
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 +35 -0
- package/dist/{CHANGELOG-5k4dq4g6.md → CHANGELOG-vt8ene9g.md} +35 -0
- package/dist/cli.js +4087 -7122
- package/dist/template-dys3vk5b.js +1671 -0
- package/dist/template-f8wx9vfn.css +1355 -0
- package/dist/template-qat058wr.html +55 -0
- package/dist/tool-views.generated-jdfmzwmn.js +35 -0
- package/dist/types/advisor/advise-tool.d.ts +0 -7
- package/dist/types/advisor/runtime.d.ts +0 -9
- package/dist/types/async/job-manager.d.ts +11 -0
- package/dist/types/cleanse/agent.d.ts +19 -0
- package/dist/types/cleanse/balance.d.ts +7 -0
- package/dist/types/cleanse/checkers.d.ts +13 -0
- package/dist/types/cleanse/index.d.ts +16 -0
- package/dist/types/cleanse/loop.d.ts +16 -0
- package/dist/types/cleanse/parsers.d.ts +13 -0
- package/dist/types/cleanse/progress.d.ts +14 -0
- package/dist/types/cleanse/types.d.ts +64 -0
- package/dist/types/commands/cleanse.d.ts +23 -0
- package/dist/types/export/html/index.d.ts +2 -0
- package/dist/types/extensibility/legacy-pi-ai-shim.d.ts +27 -1
- package/dist/types/modes/interactive-mode.d.ts +4 -3
- package/dist/types/session/async-job-delivery.d.ts +8 -0
- package/dist/types/session/model-controls.d.ts +3 -3
- package/dist/types/task/isolation-ownership.d.ts +34 -0
- package/dist/types/tools/browser/cmux/cmux-tab.d.ts +1 -2
- package/dist/types/tools/browser/tab-worker.d.ts +1 -4
- package/dist/types/tui/output-block.d.ts +5 -5
- package/package.json +16 -12
- package/scripts/bundle-dist.ts +3 -1
- package/src/advisor/advise-tool.ts +0 -11
- package/src/advisor/runtime.ts +0 -12
- package/src/async/job-manager.ts +30 -7
- package/src/cleanse/agent.ts +226 -0
- package/src/cleanse/balance.ts +79 -0
- package/src/cleanse/checkers.ts +996 -0
- package/src/cleanse/index.ts +190 -0
- package/src/cleanse/loop.ts +51 -0
- package/src/cleanse/parsers.ts +726 -0
- package/src/cleanse/progress.ts +50 -0
- package/src/cleanse/prompts/assignment.md +47 -0
- package/src/cleanse/types.ts +72 -0
- package/src/cli/update-cli.ts +3 -0
- package/src/cli/usage-cli.ts +29 -4
- package/src/cli/worktree-cli.ts +28 -11
- package/src/cli-commands.ts +1 -0
- package/src/cli.ts +2 -1
- package/src/commands/cleanse.ts +45 -0
- package/src/discovery/claude-plugins.ts +144 -34
- package/src/export/html/index.ts +17 -10
- package/src/extensibility/legacy-pi-ai-shim.ts +46 -1
- package/src/launch/broker.ts +14 -4
- package/src/modes/acp/acp-agent.ts +12 -9
- package/src/modes/acp/acp-event-mapper.ts +38 -4
- package/src/modes/components/settings-selector.ts +9 -1
- package/src/modes/interactive-mode.ts +36 -47
- package/src/modes/prompt-action-autocomplete.ts +5 -3
- package/src/prompts/goals/guided-goal-interview.md +41 -6
- package/src/prompts/system/vibe-mode-active.md +4 -1
- package/src/prompts/tools/browser.md +1 -0
- package/src/prompts/tools/goal.md +1 -1
- package/src/session/agent-session.ts +28 -4
- package/src/session/async-job-delivery.ts +8 -0
- package/src/session/model-controls.ts +4 -4
- package/src/session/session-advisors.ts +2 -7
- package/src/session/session-history-format.ts +31 -6
- package/src/slash-commands/builtin-registry.ts +5 -2
- package/src/task/isolation-ownership.ts +106 -0
- package/src/task/worktree.ts +8 -0
- package/src/tools/ask.ts +3 -3
- package/src/tools/ast-edit.ts +9 -2
- package/src/tools/browser/cmux/cmux-tab.ts +9 -14
- package/src/tools/browser/tab-worker.ts +12 -35
- package/src/tools/browser.ts +2 -2
- package/src/tools/gh-renderer.ts +3 -3
- package/src/tools/index.ts +10 -1
- package/src/tools/write.ts +35 -0
- package/src/tui/code-cell.ts +4 -4
- package/src/tui/output-block.ts +25 -8
- package/src/utils/shell-snapshot-fn-env.sh +5 -2
- package/src/web/search/render.ts +2 -2
- package/dist/types/goals/guided-setup.d.ts +0 -30
- package/src/goals/guided-setup.ts +0 -171
- package/src/prompts/goals/guided-goal-system.md +0 -33
|
@@ -0,0 +1,1671 @@
|
|
|
1
|
+
(function() {
|
|
2
|
+
'use strict';
|
|
3
|
+
|
|
4
|
+
const THEME_STORAGE_KEY = 'omp-export-theme';
|
|
5
|
+
const themeSelect = document.getElementById('theme-select');
|
|
6
|
+
let themePreference = 'auto';
|
|
7
|
+
try {
|
|
8
|
+
const stored = localStorage.getItem(THEME_STORAGE_KEY);
|
|
9
|
+
if (stored === 'light' || stored === 'dark' || stored === 'auto') themePreference = stored;
|
|
10
|
+
} catch {}
|
|
11
|
+
|
|
12
|
+
function applyThemePreference(next) {
|
|
13
|
+
themePreference = next;
|
|
14
|
+
if (next === 'light' || next === 'dark') document.documentElement.dataset.theme = next;
|
|
15
|
+
else delete document.documentElement.dataset.theme;
|
|
16
|
+
if (themeSelect) themeSelect.value = next;
|
|
17
|
+
try {
|
|
18
|
+
localStorage.setItem(THEME_STORAGE_KEY, next);
|
|
19
|
+
} catch {}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
applyThemePreference(themePreference);
|
|
23
|
+
if (themeSelect) themeSelect.addEventListener('change', () => applyThemePreference(themeSelect.value));
|
|
24
|
+
|
|
25
|
+
// ============================================================
|
|
26
|
+
// BOOT
|
|
27
|
+
// ============================================================
|
|
28
|
+
//
|
|
29
|
+
// Two boot paths share this template:
|
|
30
|
+
// - Static export: session JSON rides base64-embedded in #session-data.
|
|
31
|
+
// - Share viewer: share-loader.js sets `window.__OMP_SESSION_DATA__` to
|
|
32
|
+
// a promise resolving to the session JSON (fetched + decrypted).
|
|
33
|
+
// The entire app lives in bootSession(); its body keeps the original
|
|
34
|
+
// one-level indentation to avoid a whole-file reindent.
|
|
35
|
+
function bootSession(data) {
|
|
36
|
+
const { header, entries, leafId: defaultLeafId, systemPrompt, tools, subSessions } = data;
|
|
37
|
+
|
|
38
|
+
// Session render context: scopes entry lookups and tool-view host
|
|
39
|
+
// wiring to one transcript (main session or an embedded subagent).
|
|
40
|
+
const mainSctx = { entries, prefix: '', idPrefix: 'entry-' };
|
|
41
|
+
|
|
42
|
+
// ============================================================
|
|
43
|
+
// URL PARAMETER HANDLING
|
|
44
|
+
// ============================================================
|
|
45
|
+
|
|
46
|
+
// Parse URL parameters for deep linking: leafId and targetId
|
|
47
|
+
// Check for injected params (when loaded in iframe via srcdoc) or use window.location
|
|
48
|
+
const injectedParams = document.querySelector('meta[name="pi-url-params"]');
|
|
49
|
+
const searchString = injectedParams ? injectedParams.content : window.location.search.substring(1);
|
|
50
|
+
const urlParams = new URLSearchParams(searchString);
|
|
51
|
+
const urlLeafId = urlParams.get('leafId');
|
|
52
|
+
const urlTargetId = urlParams.get('targetId');
|
|
53
|
+
// Use URL leafId if provided, otherwise fall back to session default
|
|
54
|
+
const leafId = urlLeafId || defaultLeafId;
|
|
55
|
+
|
|
56
|
+
// ============================================================
|
|
57
|
+
// DATA STRUCTURES
|
|
58
|
+
// ============================================================
|
|
59
|
+
|
|
60
|
+
// Entry lookup by ID
|
|
61
|
+
const byId = new Map();
|
|
62
|
+
for (const entry of entries) {
|
|
63
|
+
byId.set(entry.id, entry);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// Tool call lookup (toolCallId -> {name, arguments})
|
|
67
|
+
const toolCallMap = new Map();
|
|
68
|
+
for (const entry of entries) {
|
|
69
|
+
if (entry.type === 'message' && entry.message.role === 'assistant') {
|
|
70
|
+
const content = entry.message.content;
|
|
71
|
+
if (Array.isArray(content)) {
|
|
72
|
+
for (const block of content) {
|
|
73
|
+
if (block.type === 'toolCall') {
|
|
74
|
+
toolCallMap.set(block.id, { name: block.name, arguments: block.arguments });
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// Label lookup (entryId -> label string)
|
|
82
|
+
// Labels are stored in 'label' entries that reference their target via targetId
|
|
83
|
+
const labelMap = new Map();
|
|
84
|
+
for (const entry of entries) {
|
|
85
|
+
if (entry.type === 'label' && entry.targetId && entry.label) {
|
|
86
|
+
labelMap.set(entry.targetId, entry.label);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// ============================================================
|
|
91
|
+
// TREE DATA PREPARATION (no DOM, pure data)
|
|
92
|
+
// ============================================================
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Build tree structure from flat entries.
|
|
96
|
+
* Returns array of root nodes, each with { entry, children, label }.
|
|
97
|
+
*/
|
|
98
|
+
function buildTree() {
|
|
99
|
+
const nodeMap = new Map();
|
|
100
|
+
const roots = [];
|
|
101
|
+
|
|
102
|
+
// Create nodes
|
|
103
|
+
for (const entry of entries) {
|
|
104
|
+
nodeMap.set(entry.id, {
|
|
105
|
+
entry,
|
|
106
|
+
children: [],
|
|
107
|
+
label: labelMap.get(entry.id)
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// Build parent-child relationships
|
|
112
|
+
for (const entry of entries) {
|
|
113
|
+
const node = nodeMap.get(entry.id);
|
|
114
|
+
if (entry.parentId === null || entry.parentId === undefined || entry.parentId === entry.id) {
|
|
115
|
+
roots.push(node);
|
|
116
|
+
} else {
|
|
117
|
+
const parent = nodeMap.get(entry.parentId);
|
|
118
|
+
if (parent) {
|
|
119
|
+
parent.children.push(node);
|
|
120
|
+
} else {
|
|
121
|
+
roots.push(node);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// Sort children by timestamp. Use an explicit stack so valid, deep
|
|
127
|
+
// conversation chains do not exhaust the browser call stack.
|
|
128
|
+
const sortStack = [...roots];
|
|
129
|
+
while (sortStack.length > 0) {
|
|
130
|
+
const node = sortStack.pop();
|
|
131
|
+
node.children.sort((a, b) =>
|
|
132
|
+
new Date(a.entry.timestamp).getTime() - new Date(b.entry.timestamp).getTime()
|
|
133
|
+
);
|
|
134
|
+
for (let i = node.children.length - 1; i >= 0; i--) {
|
|
135
|
+
sortStack.push(node.children[i]);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
return roots;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* Build set of entry IDs on path from root to target.
|
|
144
|
+
*/
|
|
145
|
+
function buildActivePathIds(targetId) {
|
|
146
|
+
const ids = new Set();
|
|
147
|
+
let current = byId.get(targetId);
|
|
148
|
+
while (current) {
|
|
149
|
+
ids.add(current.id);
|
|
150
|
+
// Stop if no parent or self-referencing (root)
|
|
151
|
+
if (!current.parentId || current.parentId === current.id) {
|
|
152
|
+
break;
|
|
153
|
+
}
|
|
154
|
+
current = byId.get(current.parentId);
|
|
155
|
+
}
|
|
156
|
+
return ids;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* Get array of entries from root to target (the conversation path).
|
|
161
|
+
*/
|
|
162
|
+
function getPath(targetId) {
|
|
163
|
+
const path = [];
|
|
164
|
+
let current = byId.get(targetId);
|
|
165
|
+
while (current) {
|
|
166
|
+
path.unshift(current);
|
|
167
|
+
// Stop if no parent or self-referencing (root)
|
|
168
|
+
if (!current.parentId || current.parentId === current.id) {
|
|
169
|
+
break;
|
|
170
|
+
}
|
|
171
|
+
current = byId.get(current.parentId);
|
|
172
|
+
}
|
|
173
|
+
return path;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* Flatten tree into list with indentation and connector info.
|
|
178
|
+
* Returns array of { node, indent, showConnector, isLast, gutters, isVirtualRootChild, multipleRoots }.
|
|
179
|
+
* Matches tree-selector.ts logic exactly.
|
|
180
|
+
*/
|
|
181
|
+
function flattenTree(roots, activePathIds) {
|
|
182
|
+
const result = [];
|
|
183
|
+
const multipleRoots = roots.length > 1;
|
|
184
|
+
|
|
185
|
+
// Mark which subtrees contain the active leaf. Use iterative post-order
|
|
186
|
+
// traversal so valid, deep conversation chains do not exhaust the
|
|
187
|
+
// browser call stack.
|
|
188
|
+
const containsActive = new Map();
|
|
189
|
+
const allNodes = [];
|
|
190
|
+
const activeStack = [...roots];
|
|
191
|
+
while (activeStack.length > 0) {
|
|
192
|
+
const node = activeStack.pop();
|
|
193
|
+
allNodes.push(node);
|
|
194
|
+
for (let i = node.children.length - 1; i >= 0; i--) {
|
|
195
|
+
activeStack.push(node.children[i]);
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
for (let i = allNodes.length - 1; i >= 0; i--) {
|
|
199
|
+
const node = allNodes[i];
|
|
200
|
+
let has = activePathIds.has(node.entry.id);
|
|
201
|
+
for (const child of node.children) {
|
|
202
|
+
if (containsActive.get(child)) has = true;
|
|
203
|
+
}
|
|
204
|
+
containsActive.set(node, has);
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
// Stack: [node, indent, justBranched, showConnector, isLast, gutters, isVirtualRootChild]
|
|
208
|
+
const stack = [];
|
|
209
|
+
|
|
210
|
+
// Add roots (prioritize branch containing active leaf)
|
|
211
|
+
const orderedRoots = [...roots].sort((a, b) =>
|
|
212
|
+
Number(containsActive.get(b)) - Number(containsActive.get(a))
|
|
213
|
+
);
|
|
214
|
+
for (let i = orderedRoots.length - 1; i >= 0; i--) {
|
|
215
|
+
const isLast = i === orderedRoots.length - 1;
|
|
216
|
+
stack.push([orderedRoots[i], multipleRoots ? 1 : 0, multipleRoots, multipleRoots, isLast, [], multipleRoots]);
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
while (stack.length > 0) {
|
|
220
|
+
const [node, indent, justBranched, showConnector, isLast, gutters, isVirtualRootChild] = stack.pop();
|
|
221
|
+
|
|
222
|
+
result.push({ node, indent, showConnector, isLast, gutters, isVirtualRootChild, multipleRoots });
|
|
223
|
+
|
|
224
|
+
const children = node.children;
|
|
225
|
+
const multipleChildren = children.length > 1;
|
|
226
|
+
|
|
227
|
+
// Order children (active branch first)
|
|
228
|
+
const orderedChildren = [...children].sort((a, b) =>
|
|
229
|
+
Number(containsActive.get(b)) - Number(containsActive.get(a))
|
|
230
|
+
);
|
|
231
|
+
|
|
232
|
+
// Calculate child indent (matches tree-selector.ts)
|
|
233
|
+
let childIndent;
|
|
234
|
+
if (multipleChildren) {
|
|
235
|
+
// Parent branches: children get +1
|
|
236
|
+
childIndent = indent + 1;
|
|
237
|
+
} else if (justBranched && indent > 0) {
|
|
238
|
+
// First generation after a branch: +1 for visual grouping
|
|
239
|
+
childIndent = indent + 1;
|
|
240
|
+
} else {
|
|
241
|
+
// Single-child chain: stay flat
|
|
242
|
+
childIndent = indent;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
// Build gutters for children
|
|
246
|
+
const connectorDisplayed = showConnector && !isVirtualRootChild;
|
|
247
|
+
const currentDisplayIndent = multipleRoots ? Math.max(0, indent - 1) : indent;
|
|
248
|
+
const connectorPosition = Math.max(0, currentDisplayIndent - 1);
|
|
249
|
+
const childGutters = connectorDisplayed
|
|
250
|
+
? [...gutters, { position: connectorPosition, show: !isLast }]
|
|
251
|
+
: gutters;
|
|
252
|
+
|
|
253
|
+
// Add children in reverse order for stack
|
|
254
|
+
for (let i = orderedChildren.length - 1; i >= 0; i--) {
|
|
255
|
+
const childIsLast = i === orderedChildren.length - 1;
|
|
256
|
+
stack.push([orderedChildren[i], childIndent, multipleChildren, multipleChildren, childIsLast, childGutters, false]);
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
return result;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/**
|
|
264
|
+
* Build ASCII prefix string for tree node.
|
|
265
|
+
*/
|
|
266
|
+
function buildTreePrefix(flatNode) {
|
|
267
|
+
const { indent, showConnector, isLast, gutters, isVirtualRootChild, multipleRoots } = flatNode;
|
|
268
|
+
const displayIndent = multipleRoots ? Math.max(0, indent - 1) : indent;
|
|
269
|
+
const connector = showConnector && !isVirtualRootChild ? (isLast ? '└─ ' : '├─ ') : '';
|
|
270
|
+
const connectorPosition = connector ? displayIndent - 1 : -1;
|
|
271
|
+
// Chain rows (no connector of their own) under a last-sibling (`└─`)
|
|
272
|
+
// branch stay anchored by a vertical drawn one level right of the
|
|
273
|
+
// suppressed gutter — below the branch head's content — never in the
|
|
274
|
+
// `└─` corner column itself (#2298, #2325). Chains under `├─` heads
|
|
275
|
+
// are already anchored by the sibling line (`show: true` gutter).
|
|
276
|
+
const nearestGutter = !connector ? gutters[gutters.length - 1] : undefined;
|
|
277
|
+
const chainAnchorLevel = nearestGutter && !nearestGutter.show ? nearestGutter.position + 1 : -1;
|
|
278
|
+
|
|
279
|
+
const totalChars = displayIndent * 3;
|
|
280
|
+
const prefixChars = [];
|
|
281
|
+
for (let i = 0; i < totalChars; i++) {
|
|
282
|
+
const level = Math.floor(i / 3);
|
|
283
|
+
const posInLevel = i % 3;
|
|
284
|
+
|
|
285
|
+
const gutter = gutters.find(g => g.position === level);
|
|
286
|
+
if (gutter) {
|
|
287
|
+
// Standard tree semantics: `│` only while more siblings continue
|
|
288
|
+
// below (`show`), space below a `└─`.
|
|
289
|
+
prefixChars.push(posInLevel === 0 && gutter.show ? '│' : ' ');
|
|
290
|
+
} else if (level === chainAnchorLevel) {
|
|
291
|
+
// Chain anchor for rows under a `└─` branch head.
|
|
292
|
+
prefixChars.push(posInLevel === 0 ? '│' : ' ');
|
|
293
|
+
} else if (connector && level === connectorPosition) {
|
|
294
|
+
if (posInLevel === 0) {
|
|
295
|
+
prefixChars.push(isLast ? '└' : '├');
|
|
296
|
+
} else if (posInLevel === 1) {
|
|
297
|
+
prefixChars.push('─');
|
|
298
|
+
} else {
|
|
299
|
+
prefixChars.push(' ');
|
|
300
|
+
}
|
|
301
|
+
} else {
|
|
302
|
+
prefixChars.push(' ');
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
return prefixChars.join('');
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
// ============================================================
|
|
309
|
+
// FILTERING (pure data)
|
|
310
|
+
// ============================================================
|
|
311
|
+
|
|
312
|
+
let filterMode = 'default';
|
|
313
|
+
let searchQuery = '';
|
|
314
|
+
|
|
315
|
+
function hasTextContent(content) {
|
|
316
|
+
if (typeof content === 'string') return Boolean(canonicalizeMessage(content));
|
|
317
|
+
if (Array.isArray(content)) {
|
|
318
|
+
for (const c of content) {
|
|
319
|
+
if (c.type === 'text' && c.text) {
|
|
320
|
+
if (canonicalizeMessage(c.text)) return true;
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
return false;
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
function extractContent(content) {
|
|
328
|
+
if (typeof content === 'string') return content;
|
|
329
|
+
if (Array.isArray(content)) {
|
|
330
|
+
return content
|
|
331
|
+
.filter(c => c.type === 'text' && c.text)
|
|
332
|
+
.map(c => c.text)
|
|
333
|
+
.join('');
|
|
334
|
+
}
|
|
335
|
+
return '';
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
function getSearchableText(entry, label) {
|
|
339
|
+
const parts = [];
|
|
340
|
+
if (label) parts.push(label);
|
|
341
|
+
|
|
342
|
+
switch (entry.type) {
|
|
343
|
+
case 'message': {
|
|
344
|
+
const msg = entry.message;
|
|
345
|
+
parts.push(msg.role);
|
|
346
|
+
if (msg.content) parts.push(extractContent(msg.content));
|
|
347
|
+
if (msg.role === 'bashExecution' && msg.command) parts.push(msg.command);
|
|
348
|
+
if (msg.role === 'jsExecution' && msg.code) parts.push(msg.code);
|
|
349
|
+
break;
|
|
350
|
+
}
|
|
351
|
+
case 'custom_message':
|
|
352
|
+
parts.push(entry.customType);
|
|
353
|
+
parts.push(typeof entry.content === 'string' ? entry.content : extractContent(entry.content));
|
|
354
|
+
break;
|
|
355
|
+
case 'compaction':
|
|
356
|
+
parts.push('compaction');
|
|
357
|
+
break;
|
|
358
|
+
case 'branch_summary':
|
|
359
|
+
parts.push('branch summary', entry.summary);
|
|
360
|
+
break;
|
|
361
|
+
case 'model_change':
|
|
362
|
+
parts.push('model', entry.model);
|
|
363
|
+
break;
|
|
364
|
+
case 'thinking_level_change':
|
|
365
|
+
parts.push('thinking', entry.thinkingLevel);
|
|
366
|
+
break;
|
|
367
|
+
case 'mode_change':
|
|
368
|
+
parts.push('mode', entry.mode);
|
|
369
|
+
break;
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
return parts.join(' ').toLowerCase();
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
/**
|
|
376
|
+
* Filter flat nodes based on current filterMode and searchQuery.
|
|
377
|
+
*/
|
|
378
|
+
function filterNodes(flatNodes, currentLeafId) {
|
|
379
|
+
const searchTokens = searchQuery.toLowerCase().split(/\s+/).filter(Boolean);
|
|
380
|
+
|
|
381
|
+
return flatNodes.filter(flatNode => {
|
|
382
|
+
const entry = flatNode.node.entry;
|
|
383
|
+
const label = flatNode.node.label;
|
|
384
|
+
const isCurrentLeaf = entry.id === currentLeafId;
|
|
385
|
+
|
|
386
|
+
// Always show current leaf
|
|
387
|
+
if (isCurrentLeaf) return true;
|
|
388
|
+
|
|
389
|
+
// Hide assistant messages with only tool calls (no text) unless error/aborted
|
|
390
|
+
if (entry.type === 'message' && entry.message.role === 'assistant') {
|
|
391
|
+
const msg = entry.message;
|
|
392
|
+
const hasText = hasTextContent(msg.content);
|
|
393
|
+
const isErrorOrAborted = msg.stopReason && msg.stopReason !== 'stop' && msg.stopReason !== 'toolUse';
|
|
394
|
+
if (!hasText && !isErrorOrAborted) return false;
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
// Apply filter mode
|
|
398
|
+
const isSettingsEntry = ['label', 'custom', 'model_change', 'thinking_level_change', 'mode_change', 'ttsr_injection', 'session_init'].includes(entry.type);
|
|
399
|
+
let passesFilter = true;
|
|
400
|
+
|
|
401
|
+
switch (filterMode) {
|
|
402
|
+
case 'user-only':
|
|
403
|
+
passesFilter = entry.type === 'message' && entry.message.role === 'user';
|
|
404
|
+
break;
|
|
405
|
+
case 'no-tools':
|
|
406
|
+
passesFilter = !isSettingsEntry && !(entry.type === 'message' && entry.message.role === 'toolResult');
|
|
407
|
+
break;
|
|
408
|
+
case 'labeled-only':
|
|
409
|
+
passesFilter = label !== undefined;
|
|
410
|
+
break;
|
|
411
|
+
case 'all':
|
|
412
|
+
passesFilter = true;
|
|
413
|
+
break;
|
|
414
|
+
default: // 'default'
|
|
415
|
+
passesFilter = !isSettingsEntry;
|
|
416
|
+
break;
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
if (!passesFilter) return false;
|
|
420
|
+
|
|
421
|
+
// Apply search filter
|
|
422
|
+
if (searchTokens.length > 0) {
|
|
423
|
+
const nodeText = getSearchableText(entry, label);
|
|
424
|
+
if (!searchTokens.every(t => nodeText.includes(t))) return false;
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
return true;
|
|
428
|
+
});
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
// ============================================================
|
|
432
|
+
// TREE DISPLAY TEXT (pure data -> string)
|
|
433
|
+
// ============================================================
|
|
434
|
+
|
|
435
|
+
function shortenPath(p) {
|
|
436
|
+
if (typeof p !== 'string') return '';
|
|
437
|
+
if (p.startsWith('/Users/')) {
|
|
438
|
+
const parts = p.split('/');
|
|
439
|
+
if (parts.length > 2) return '~' + p.slice(('/Users/' + parts[2]).length);
|
|
440
|
+
}
|
|
441
|
+
if (p.startsWith('/home/')) {
|
|
442
|
+
const parts = p.split('/');
|
|
443
|
+
if (parts.length > 2) return '~' + p.slice(('/home/' + parts[2]).length);
|
|
444
|
+
}
|
|
445
|
+
return p;
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
function formatToolCall(name, args) {
|
|
449
|
+
switch (name) {
|
|
450
|
+
case 'read': {
|
|
451
|
+
const path = shortenPath(String(args.path || args.file_path || ''));
|
|
452
|
+
const offset = args.offset;
|
|
453
|
+
const limit = args.limit;
|
|
454
|
+
let display = path;
|
|
455
|
+
if (offset !== undefined || limit !== undefined) {
|
|
456
|
+
const start = offset ?? 1;
|
|
457
|
+
const end = limit !== undefined ? start + limit - 1 : '';
|
|
458
|
+
display += `:${start}${end ? `-${end}` : ''}`;
|
|
459
|
+
}
|
|
460
|
+
return `[read: ${display}]`;
|
|
461
|
+
}
|
|
462
|
+
case 'write':
|
|
463
|
+
return `[write: ${shortenPath(String(args.path || args.file_path || ''))}]`;
|
|
464
|
+
case 'edit':
|
|
465
|
+
return `[edit: ${shortenPath(String(args.path || args.file_path || ''))}]`;
|
|
466
|
+
case 'bash': {
|
|
467
|
+
const rawCmd = String(args.command || '');
|
|
468
|
+
const cmd = rawCmd.replace(/[\n\t]/g, ' ').trim().slice(0, 50);
|
|
469
|
+
return `[bash: ${cmd}${rawCmd.length > 50 ? '...' : ''}]`;
|
|
470
|
+
}
|
|
471
|
+
case 'search':
|
|
472
|
+
case 'grep':
|
|
473
|
+
return `[grep: /${args.pattern || ''}/ in ${shortenPath(String((args.paths || [args.path || '.']).join(', ')))}]`;
|
|
474
|
+
case 'find':
|
|
475
|
+
case 'glob':
|
|
476
|
+
return `[glob: ${shortenPath(String((args.paths || [args.pattern || '.']).join(', ')))}]`;
|
|
477
|
+
case 'ls':
|
|
478
|
+
return `[ls: ${shortenPath(String(args.path || '.'))}]`;
|
|
479
|
+
default: {
|
|
480
|
+
const argsStr = JSON.stringify(args).slice(0, 40);
|
|
481
|
+
return `[${name}: ${argsStr}${JSON.stringify(args).length > 40 ? '...' : ''}]`;
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
function escapeHtml(text) {
|
|
487
|
+
const div = document.createElement('div');
|
|
488
|
+
div.textContent = text;
|
|
489
|
+
return div.innerHTML;
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
function canonicalizeMessage(text) {
|
|
493
|
+
if (!text) return '';
|
|
494
|
+
const trimmed = text.trim();
|
|
495
|
+
for (let i = 0; i < trimmed.length; i++) {
|
|
496
|
+
const code = trimmed.charCodeAt(i);
|
|
497
|
+
if (code !== 0x2e && code !== 0x2026 && code !== 0x20 && code !== 0x09 && code !== 0x0a && code !== 0x0d) {
|
|
498
|
+
return trimmed;
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
return '';
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
/**
|
|
505
|
+
* Truncate string to maxLen chars, append "..." if truncated.
|
|
506
|
+
*/
|
|
507
|
+
function truncate(s, maxLen = 100) {
|
|
508
|
+
if (s.length <= maxLen) return s;
|
|
509
|
+
return s.slice(0, maxLen) + '...';
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
/**
|
|
513
|
+
* Get display text for tree node (returns HTML string).
|
|
514
|
+
*/
|
|
515
|
+
function getTreeNodeDisplayHtml(entry, label) {
|
|
516
|
+
const normalize = s => s.replace(/[\n\t]/g, ' ').trim();
|
|
517
|
+
const labelHtml = label ? `<span class="tree-label">[${escapeHtml(label)}]</span> ` : '';
|
|
518
|
+
|
|
519
|
+
switch (entry.type) {
|
|
520
|
+
case 'message': {
|
|
521
|
+
const msg = entry.message;
|
|
522
|
+
if (msg.role === 'user') {
|
|
523
|
+
const content = truncate(normalize(extractContent(msg.content)));
|
|
524
|
+
return labelHtml + `<span class="tree-role-user">user:</span> ${escapeHtml(content)}`;
|
|
525
|
+
}
|
|
526
|
+
if (msg.role === 'developer') {
|
|
527
|
+
const content = truncate(normalize(extractContent(msg.content)));
|
|
528
|
+
return labelHtml + `<span class="tree-role-developer">developer:</span> ${escapeHtml(content)}`;
|
|
529
|
+
}
|
|
530
|
+
if (msg.role === 'assistant') {
|
|
531
|
+
const textContent = truncate(normalize(extractContent(msg.content)));
|
|
532
|
+
if (textContent) {
|
|
533
|
+
return labelHtml + `<span class="tree-role-assistant">assistant:</span> ${escapeHtml(textContent)}`;
|
|
534
|
+
}
|
|
535
|
+
if (msg.stopReason === 'aborted') {
|
|
536
|
+
return labelHtml + `<span class="tree-role-assistant">assistant:</span> <span class="tree-muted">(aborted)</span>`;
|
|
537
|
+
}
|
|
538
|
+
if (msg.errorMessage) {
|
|
539
|
+
return labelHtml + `<span class="tree-role-assistant">assistant:</span> <span class="tree-error">${escapeHtml(truncate(msg.errorMessage))}</span>`;
|
|
540
|
+
}
|
|
541
|
+
return labelHtml + `<span class="tree-role-assistant">assistant:</span> <span class="tree-muted">(no text)</span>`;
|
|
542
|
+
}
|
|
543
|
+
if (msg.role === 'toolResult') {
|
|
544
|
+
const toolCall = msg.toolCallId ? toolCallMap.get(msg.toolCallId) : null;
|
|
545
|
+
if (toolCall) {
|
|
546
|
+
return labelHtml + `<span class="tree-role-tool">${escapeHtml(formatToolCall(toolCall.name, toolCall.arguments))}</span>`;
|
|
547
|
+
}
|
|
548
|
+
return labelHtml + `<span class="tree-role-tool">[${msg.toolName || 'tool'}]</span>`;
|
|
549
|
+
}
|
|
550
|
+
if (msg.role === 'bashExecution') {
|
|
551
|
+
const cmd = truncate(normalize(msg.command || ''));
|
|
552
|
+
return labelHtml + `<span class="tree-role-tool">[bash]:</span> ${escapeHtml(cmd)}`;
|
|
553
|
+
}
|
|
554
|
+
if (msg.role === 'jsExecution') {
|
|
555
|
+
const code = truncate(normalize(msg.code || ''));
|
|
556
|
+
return labelHtml + `<span class="tree-role-tool">[js]:</span> ${escapeHtml(code)}`;
|
|
557
|
+
}
|
|
558
|
+
return labelHtml + `<span class="tree-muted">[${msg.role}]</span>`;
|
|
559
|
+
}
|
|
560
|
+
case 'compaction':
|
|
561
|
+
return labelHtml + `<span class="tree-compaction">[compaction: ${Math.round(entry.tokensBefore/1000)}k tokens]</span>`;
|
|
562
|
+
case 'branch_summary': {
|
|
563
|
+
const summary = truncate(normalize(entry.summary || ''));
|
|
564
|
+
return labelHtml + `<span class="tree-branch-summary">[branch summary]:</span> ${escapeHtml(summary)}`;
|
|
565
|
+
}
|
|
566
|
+
case 'custom_message': {
|
|
567
|
+
const content = typeof entry.content === 'string' ? entry.content : extractContent(entry.content);
|
|
568
|
+
return labelHtml + `<span class="tree-custom">[${escapeHtml(entry.customType)}]:</span> ${escapeHtml(truncate(normalize(content)))}`;
|
|
569
|
+
}
|
|
570
|
+
case 'model_change':
|
|
571
|
+
return labelHtml + `<span class="tree-muted">[model: ${escapeHtml(entry.model)}]</span>`;
|
|
572
|
+
case 'thinking_level_change':
|
|
573
|
+
return labelHtml + `<span class="tree-muted">[thinking: ${entry.thinkingLevel}]</span>`;
|
|
574
|
+
case 'mode_change':
|
|
575
|
+
return labelHtml + `<span class="tree-muted">[mode: ${escapeHtml(entry.mode)}]</span>`;
|
|
576
|
+
default:
|
|
577
|
+
return labelHtml + `<span class="tree-muted">[${entry.type}]</span>`;
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
// ============================================================
|
|
582
|
+
// TREE RENDERING (DOM manipulation)
|
|
583
|
+
// ============================================================
|
|
584
|
+
|
|
585
|
+
let currentLeafId = leafId;
|
|
586
|
+
let currentTargetId = urlTargetId || leafId;
|
|
587
|
+
let treeRendered = false;
|
|
588
|
+
|
|
589
|
+
function renderTree() {
|
|
590
|
+
const tree = buildTree();
|
|
591
|
+
const activePathIds = buildActivePathIds(currentLeafId);
|
|
592
|
+
const flatNodes = flattenTree(tree, activePathIds);
|
|
593
|
+
const filtered = filterNodes(flatNodes, currentLeafId);
|
|
594
|
+
const container = document.getElementById('tree-container');
|
|
595
|
+
|
|
596
|
+
// Full render only on first call or when filter/search changes
|
|
597
|
+
if (!treeRendered) {
|
|
598
|
+
container.innerHTML = '';
|
|
599
|
+
|
|
600
|
+
for (const flatNode of filtered) {
|
|
601
|
+
const entry = flatNode.node.entry;
|
|
602
|
+
const isOnPath = activePathIds.has(entry.id);
|
|
603
|
+
const isTarget = entry.id === currentTargetId;
|
|
604
|
+
|
|
605
|
+
const div = document.createElement('div');
|
|
606
|
+
div.className = 'tree-node';
|
|
607
|
+
if (isOnPath) div.classList.add('in-path');
|
|
608
|
+
if (isTarget) div.classList.add('active');
|
|
609
|
+
div.dataset.id = entry.id;
|
|
610
|
+
|
|
611
|
+
const prefix = buildTreePrefix(flatNode);
|
|
612
|
+
const prefixSpan = document.createElement('span');
|
|
613
|
+
prefixSpan.className = 'tree-prefix';
|
|
614
|
+
prefixSpan.textContent = prefix;
|
|
615
|
+
|
|
616
|
+
const marker = document.createElement('span');
|
|
617
|
+
marker.className = 'tree-marker';
|
|
618
|
+
marker.textContent = isOnPath ? '•' : ' ';
|
|
619
|
+
|
|
620
|
+
const content = document.createElement('span');
|
|
621
|
+
content.className = 'tree-content';
|
|
622
|
+
content.innerHTML = getTreeNodeDisplayHtml(entry, flatNode.node.label);
|
|
623
|
+
|
|
624
|
+
div.appendChild(prefixSpan);
|
|
625
|
+
div.appendChild(marker);
|
|
626
|
+
div.appendChild(content);
|
|
627
|
+
div.addEventListener('click', () => navigateTo(entry.id));
|
|
628
|
+
|
|
629
|
+
container.appendChild(div);
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
treeRendered = true;
|
|
633
|
+
} else {
|
|
634
|
+
// Just update markers and classes
|
|
635
|
+
const nodes = container.querySelectorAll('.tree-node');
|
|
636
|
+
for (const node of nodes) {
|
|
637
|
+
const id = node.dataset.id;
|
|
638
|
+
const isOnPath = activePathIds.has(id);
|
|
639
|
+
const isTarget = id === currentTargetId;
|
|
640
|
+
|
|
641
|
+
node.classList.toggle('in-path', isOnPath);
|
|
642
|
+
node.classList.toggle('active', isTarget);
|
|
643
|
+
|
|
644
|
+
const marker = node.querySelector('.tree-marker');
|
|
645
|
+
if (marker) {
|
|
646
|
+
marker.textContent = isOnPath ? '•' : ' ';
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
document.getElementById('tree-status').textContent = `${filtered.length} / ${flatNodes.length} entries`;
|
|
652
|
+
|
|
653
|
+
// Scroll active node into view after layout
|
|
654
|
+
setTimeout(() => {
|
|
655
|
+
const activeNode = container.querySelector('.tree-node.active');
|
|
656
|
+
if (activeNode) {
|
|
657
|
+
activeNode.scrollIntoView({ block: 'nearest' });
|
|
658
|
+
}
|
|
659
|
+
}, 0);
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
function forceTreeRerender() {
|
|
663
|
+
treeRendered = false;
|
|
664
|
+
renderTree();
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
// ============================================================
|
|
668
|
+
// MESSAGE RENDERING
|
|
669
|
+
// ============================================================
|
|
670
|
+
|
|
671
|
+
function formatTokens(count) {
|
|
672
|
+
if (count < 1000) return count.toString();
|
|
673
|
+
if (count < 10000) return (count / 1000).toFixed(1) + 'k';
|
|
674
|
+
if (count < 1000000) return Math.round(count / 1000) + 'k';
|
|
675
|
+
return (count / 1000000).toFixed(1) + 'M';
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
function formatTimestamp(ts) {
|
|
679
|
+
if (!ts) return '';
|
|
680
|
+
const date = new Date(ts);
|
|
681
|
+
return date.toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit', second: '2-digit' });
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
function replaceTabs(text) {
|
|
685
|
+
return text.replace(/\t/g, ' ');
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
function findToolResult(toolCallId, entryList) {
|
|
689
|
+
for (const entry of entryList) {
|
|
690
|
+
if (entry.type === 'message' && entry.message.role === 'toolResult') {
|
|
691
|
+
if (entry.message.toolCallId === toolCallId) {
|
|
692
|
+
return entry.message;
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
}
|
|
696
|
+
return null;
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
function formatExpandableOutput(text, maxLines, lang) {
|
|
700
|
+
text = replaceTabs(text);
|
|
701
|
+
const lines = text.split('\n');
|
|
702
|
+
const displayLines = lines.slice(0, maxLines);
|
|
703
|
+
const remaining = lines.length - maxLines;
|
|
704
|
+
|
|
705
|
+
if (lang) {
|
|
706
|
+
let highlighted;
|
|
707
|
+
try {
|
|
708
|
+
highlighted = hljs.highlight(text, { language: lang }).value;
|
|
709
|
+
} catch {
|
|
710
|
+
highlighted = escapeHtml(text);
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
if (remaining > 0) {
|
|
714
|
+
const previewCode = displayLines.join('\n');
|
|
715
|
+
let previewHighlighted;
|
|
716
|
+
try {
|
|
717
|
+
previewHighlighted = hljs.highlight(previewCode, { language: lang }).value;
|
|
718
|
+
} catch {
|
|
719
|
+
previewHighlighted = escapeHtml(previewCode);
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
return `<div class="tool-output expandable" onclick="this.classList.toggle('expanded')">
|
|
723
|
+
<div class="output-preview"><pre><code class="hljs">${previewHighlighted}</code></pre>
|
|
724
|
+
<div class="expand-hint">... (${remaining} more lines)</div></div>
|
|
725
|
+
<div class="output-full"><pre><code class="hljs">${highlighted}</code></pre></div></div>`;
|
|
726
|
+
}
|
|
727
|
+
|
|
728
|
+
return `<div class="tool-output"><pre><code class="hljs">${highlighted}</code></pre></div>`;
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
// Plain text output
|
|
732
|
+
if (remaining > 0) {
|
|
733
|
+
let out = '<div class="tool-output expandable" onclick="this.classList.toggle(\'expanded\')">';
|
|
734
|
+
out += '<div class="output-preview">';
|
|
735
|
+
for (const line of displayLines) {
|
|
736
|
+
out += `<div>${escapeHtml(replaceTabs(line))}</div>`;
|
|
737
|
+
}
|
|
738
|
+
out += `<div class="expand-hint">... (${remaining} more lines)</div></div>`;
|
|
739
|
+
out += '<div class="output-full">';
|
|
740
|
+
for (const line of lines) {
|
|
741
|
+
out += `<div>${escapeHtml(replaceTabs(line))}</div>`;
|
|
742
|
+
}
|
|
743
|
+
out += '</div></div>';
|
|
744
|
+
return out;
|
|
745
|
+
}
|
|
746
|
+
|
|
747
|
+
let out = '<div class="tool-output">';
|
|
748
|
+
for (const line of displayLines) {
|
|
749
|
+
out += `<div>${escapeHtml(replaceTabs(line))}</div>`;
|
|
750
|
+
}
|
|
751
|
+
out += '</div>';
|
|
752
|
+
return out;
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
// ============================================================
|
|
756
|
+
// TOOL CALL RENDERING
|
|
757
|
+
// ============================================================
|
|
758
|
+
//
|
|
759
|
+
// Tool calls render through the bundled <omp-tool-view> web component
|
|
760
|
+
// (tool-views.generated.js — the same React renderers collab-web uses).
|
|
761
|
+
// Payloads are handed over via a global store keyed by data-key, which
|
|
762
|
+
// survives innerHTML serialization and cloneNode round trips.
|
|
763
|
+
|
|
764
|
+
const TOOL_VIEW_DATA = new Map();
|
|
765
|
+
globalThis.__OMP_TOOL_VIEW_DATA = TOOL_VIEW_DATA;
|
|
766
|
+
let toolViewSeq = 0;
|
|
767
|
+
|
|
768
|
+
function renderToolCall(call, sctx) {
|
|
769
|
+
const result = findToolResult(call.id, sctx.entries);
|
|
770
|
+
const statusClass = result ? (result.isError ? 'error' : 'success') : 'pending';
|
|
771
|
+
const key = 'tv' + (++toolViewSeq);
|
|
772
|
+
TOOL_VIEW_DATA.set(key, {
|
|
773
|
+
name: call.name,
|
|
774
|
+
args: call.arguments || {},
|
|
775
|
+
result: result || undefined,
|
|
776
|
+
host: {
|
|
777
|
+
hasAgent: (id) => !!lookupSubSession(sctx.prefix, id),
|
|
778
|
+
openAgent: (id) => openSubSession(joinKey(sctx.prefix, id)),
|
|
779
|
+
},
|
|
780
|
+
});
|
|
781
|
+
return '<omp-tool-view class="tool-execution ' + statusClass + '" data-key="' + key + '" open></omp-tool-view>';
|
|
782
|
+
}
|
|
783
|
+
|
|
784
|
+
// ============================================================
|
|
785
|
+
// SUB-SESSION OVERLAY
|
|
786
|
+
// ============================================================
|
|
787
|
+
//
|
|
788
|
+
// Task tool cards expose agent chips (wired through the payload `host`
|
|
789
|
+
// above); clicking one opens that subagent's transcript in a stacked
|
|
790
|
+
// overlay. Keys are slash-joined agent ids relative to the main
|
|
791
|
+
// session: top-level agent 'ToolAsk', its child 'ToolAsk/Helper'.
|
|
792
|
+
|
|
793
|
+
function joinKey(prefix, id) {
|
|
794
|
+
return prefix ? prefix + '/' + id : id;
|
|
795
|
+
}
|
|
796
|
+
|
|
797
|
+
function lookupSubSession(prefix, id) {
|
|
798
|
+
return subSessions ? subSessions[joinKey(prefix, id)] : undefined;
|
|
799
|
+
}
|
|
800
|
+
|
|
801
|
+
// Render context per sub-session (entries scoped to that transcript).
|
|
802
|
+
const subSctxCache = new Map();
|
|
803
|
+
function getSubSctx(key) {
|
|
804
|
+
let sctx = subSctxCache.get(key);
|
|
805
|
+
if (!sctx) {
|
|
806
|
+
sctx = {
|
|
807
|
+
entries: subSessions[key].entries,
|
|
808
|
+
prefix: key,
|
|
809
|
+
idPrefix: 'sub-' + key.replace(/[^A-Za-z0-9_-]/g, '_') + '-entry-',
|
|
810
|
+
};
|
|
811
|
+
subSctxCache.set(key, sctx);
|
|
812
|
+
}
|
|
813
|
+
return sctx;
|
|
814
|
+
}
|
|
815
|
+
|
|
816
|
+
/**
|
|
817
|
+
* Root-to-leaf path through an arbitrary entry list (subagent
|
|
818
|
+
* transcripts are linear chains; same parent-walk as getPath).
|
|
819
|
+
*/
|
|
820
|
+
function getPathIn(entryList, targetId) {
|
|
821
|
+
const map = new Map();
|
|
822
|
+
for (const e of entryList) map.set(e.id, e);
|
|
823
|
+
let current = targetId ? map.get(targetId) : undefined;
|
|
824
|
+
if (!current && entryList.length > 0) current = entryList[entryList.length - 1];
|
|
825
|
+
const path = [];
|
|
826
|
+
while (current) {
|
|
827
|
+
path.unshift(current);
|
|
828
|
+
if (!current.parentId || current.parentId === current.id) break;
|
|
829
|
+
current = map.get(current.parentId);
|
|
830
|
+
}
|
|
831
|
+
return path;
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
const overlayStack = []; // slash-joined keys, root-first chain
|
|
835
|
+
const subSessionBodyCache = new Map(); // key -> rendered body element
|
|
836
|
+
let subOverlayEl = null;
|
|
837
|
+
let subOverlayLastFocus = null;
|
|
838
|
+
|
|
839
|
+
function ensureSubOverlay() {
|
|
840
|
+
if (subOverlayEl) return subOverlayEl;
|
|
841
|
+
subOverlayEl = document.createElement('div');
|
|
842
|
+
subOverlayEl.id = 'subsession-overlay';
|
|
843
|
+
subOverlayEl.innerHTML = `
|
|
844
|
+
<div class="subsession-backdrop"></div>
|
|
845
|
+
<div class="subsession-panel" role="dialog" aria-modal="true" aria-label="Subagent session" tabindex="-1">
|
|
846
|
+
<div class="subsession-header">
|
|
847
|
+
<nav class="subsession-breadcrumb" aria-label="Subagent breadcrumb"></nav>
|
|
848
|
+
<button type="button" class="subsession-close" title="Close (Esc)" aria-label="Close subagent view">×</button>
|
|
849
|
+
</div>
|
|
850
|
+
<div class="subsession-meta"></div>
|
|
851
|
+
<div class="subsession-body"></div>
|
|
852
|
+
</div>`;
|
|
853
|
+
subOverlayEl.querySelector('.subsession-backdrop').addEventListener('click', popSubSession);
|
|
854
|
+
subOverlayEl.querySelector('.subsession-close').addEventListener('click', closeAllSubSessions);
|
|
855
|
+
document.body.appendChild(subOverlayEl);
|
|
856
|
+
return subOverlayEl;
|
|
857
|
+
}
|
|
858
|
+
|
|
859
|
+
function buildSubSessionBody(key) {
|
|
860
|
+
let body = subSessionBodyCache.get(key);
|
|
861
|
+
if (body) return body;
|
|
862
|
+
const sub = subSessions[key];
|
|
863
|
+
const sctx = getSubSctx(key);
|
|
864
|
+
body = document.createElement('div');
|
|
865
|
+
body.className = 'subsession-messages';
|
|
866
|
+
for (const entry of getPathIn(sub.entries, sub.leafId)) {
|
|
867
|
+
const node = renderEntryToNode(entry, sctx);
|
|
868
|
+
if (node) body.appendChild(node);
|
|
869
|
+
}
|
|
870
|
+
if (!body.firstChild) {
|
|
871
|
+
const empty = document.createElement('div');
|
|
872
|
+
empty.className = 'subsession-empty';
|
|
873
|
+
empty.textContent = '(no renderable entries)';
|
|
874
|
+
body.appendChild(empty);
|
|
875
|
+
}
|
|
876
|
+
subSessionBodyCache.set(key, body);
|
|
877
|
+
return body;
|
|
878
|
+
}
|
|
879
|
+
|
|
880
|
+
function subSessionMetaText(key) {
|
|
881
|
+
const sub = subSessions[key];
|
|
882
|
+
const stats = computeStats(sub.entries);
|
|
883
|
+
const parts = [];
|
|
884
|
+
if (stats.models.length > 0) parts.push(stats.models.join(', '));
|
|
885
|
+
parts.push(sub.entries.length + (sub.entries.length === 1 ? ' entry' : ' entries'));
|
|
886
|
+
return parts.join(' · ');
|
|
887
|
+
}
|
|
888
|
+
|
|
889
|
+
function renderSubOverlay() {
|
|
890
|
+
const key = overlayStack[overlayStack.length - 1];
|
|
891
|
+
const el = ensureSubOverlay();
|
|
892
|
+
|
|
893
|
+
const crumbs = el.querySelector('.subsession-breadcrumb');
|
|
894
|
+
crumbs.innerHTML = '';
|
|
895
|
+
const segments = key.split('/');
|
|
896
|
+
for (let i = 0; i < segments.length; i++) {
|
|
897
|
+
if (i > 0) {
|
|
898
|
+
const sep = document.createElement('span');
|
|
899
|
+
sep.className = 'subsession-crumb-sep';
|
|
900
|
+
sep.textContent = '›';
|
|
901
|
+
crumbs.appendChild(sep);
|
|
902
|
+
}
|
|
903
|
+
if (i === segments.length - 1) {
|
|
904
|
+
const span = document.createElement('span');
|
|
905
|
+
span.className = 'subsession-crumb current';
|
|
906
|
+
span.textContent = segments[i];
|
|
907
|
+
crumbs.appendChild(span);
|
|
908
|
+
} else {
|
|
909
|
+
const btn = document.createElement('button');
|
|
910
|
+
btn.type = 'button';
|
|
911
|
+
btn.className = 'subsession-crumb';
|
|
912
|
+
btn.textContent = segments[i];
|
|
913
|
+
const ancestorKey = segments.slice(0, i + 1).join('/');
|
|
914
|
+
btn.addEventListener('click', () => popSubSessionTo(ancestorKey));
|
|
915
|
+
crumbs.appendChild(btn);
|
|
916
|
+
}
|
|
917
|
+
}
|
|
918
|
+
|
|
919
|
+
el.querySelector('.subsession-meta').textContent = subSessionMetaText(key);
|
|
920
|
+
|
|
921
|
+
const bodyHost = el.querySelector('.subsession-body');
|
|
922
|
+
bodyHost.innerHTML = '';
|
|
923
|
+
bodyHost.appendChild(buildSubSessionBody(key));
|
|
924
|
+
bodyHost.scrollTop = 0;
|
|
925
|
+
|
|
926
|
+
el.classList.add('open');
|
|
927
|
+
el.querySelector('.subsession-panel').focus();
|
|
928
|
+
}
|
|
929
|
+
|
|
930
|
+
function openSubSession(key) {
|
|
931
|
+
if (!subSessions || !subSessions[key]) return;
|
|
932
|
+
if (overlayStack.length === 0) {
|
|
933
|
+
subOverlayLastFocus = document.activeElement;
|
|
934
|
+
}
|
|
935
|
+
overlayStack.push(key);
|
|
936
|
+
renderSubOverlay();
|
|
937
|
+
}
|
|
938
|
+
|
|
939
|
+
function popSubSession() {
|
|
940
|
+
if (overlayStack.length === 0) return;
|
|
941
|
+
overlayStack.pop();
|
|
942
|
+
if (overlayStack.length === 0) {
|
|
943
|
+
hideSubOverlay();
|
|
944
|
+
} else {
|
|
945
|
+
renderSubOverlay();
|
|
946
|
+
}
|
|
947
|
+
}
|
|
948
|
+
|
|
949
|
+
function popSubSessionTo(key) {
|
|
950
|
+
// Rebuild the chain root..key (the stack is always a prefix chain).
|
|
951
|
+
const segments = key.split('/');
|
|
952
|
+
overlayStack.length = 0;
|
|
953
|
+
for (let i = 1; i <= segments.length; i++) {
|
|
954
|
+
overlayStack.push(segments.slice(0, i).join('/'));
|
|
955
|
+
}
|
|
956
|
+
renderSubOverlay();
|
|
957
|
+
}
|
|
958
|
+
|
|
959
|
+
function closeAllSubSessions() {
|
|
960
|
+
if (overlayStack.length === 0) return;
|
|
961
|
+
overlayStack.length = 0;
|
|
962
|
+
hideSubOverlay();
|
|
963
|
+
}
|
|
964
|
+
|
|
965
|
+
function hideSubOverlay() {
|
|
966
|
+
if (subOverlayEl) {
|
|
967
|
+
subOverlayEl.classList.remove('open');
|
|
968
|
+
subOverlayEl.querySelector('.subsession-body').innerHTML = '';
|
|
969
|
+
}
|
|
970
|
+
if (subOverlayLastFocus && typeof subOverlayLastFocus.focus === 'function') {
|
|
971
|
+
subOverlayLastFocus.focus();
|
|
972
|
+
}
|
|
973
|
+
subOverlayLastFocus = null;
|
|
974
|
+
}
|
|
975
|
+
|
|
976
|
+
|
|
977
|
+
/**
|
|
978
|
+
* Build a shareable URL for a specific message.
|
|
979
|
+
* URL format: base?gistId&leafId=<leafId>&targetId=<entryId>
|
|
980
|
+
*/
|
|
981
|
+
function buildShareUrl(entryId) {
|
|
982
|
+
// Check for injected base URL (used when loaded in iframe via srcdoc)
|
|
983
|
+
const baseUrlMeta = document.querySelector('meta[name="pi-share-base-url"]');
|
|
984
|
+
const baseUrl = baseUrlMeta ? baseUrlMeta.content : window.location.href.split('?')[0];
|
|
985
|
+
|
|
986
|
+
const url = new URL(window.location.href);
|
|
987
|
+
// Find the gist ID (first query param without value, e.g., ?abc123)
|
|
988
|
+
const gistId = Array.from(url.searchParams.keys()).find(k => !url.searchParams.get(k));
|
|
989
|
+
|
|
990
|
+
// Build the share URL
|
|
991
|
+
const params = new URLSearchParams();
|
|
992
|
+
params.set('leafId', currentLeafId);
|
|
993
|
+
params.set('targetId', entryId);
|
|
994
|
+
|
|
995
|
+
// If we have an injected base URL (iframe context), use it directly
|
|
996
|
+
if (baseUrlMeta) {
|
|
997
|
+
return `${baseUrl}&${params.toString()}`;
|
|
998
|
+
}
|
|
999
|
+
|
|
1000
|
+
// Otherwise build from current location (direct file access)
|
|
1001
|
+
url.search = gistId ? `?${gistId}&${params.toString()}` : `?${params.toString()}`;
|
|
1002
|
+
return url.toString();
|
|
1003
|
+
}
|
|
1004
|
+
|
|
1005
|
+
/**
|
|
1006
|
+
* Copy text to clipboard with visual feedback.
|
|
1007
|
+
* Uses navigator.clipboard with fallback to execCommand for HTTP contexts.
|
|
1008
|
+
*/
|
|
1009
|
+
async function copyToClipboard(text, button) {
|
|
1010
|
+
let success = false;
|
|
1011
|
+
try {
|
|
1012
|
+
if (navigator.clipboard && navigator.clipboard.writeText) {
|
|
1013
|
+
await navigator.clipboard.writeText(text);
|
|
1014
|
+
success = true;
|
|
1015
|
+
}
|
|
1016
|
+
} catch {
|
|
1017
|
+
// Clipboard API failed, try fallback
|
|
1018
|
+
}
|
|
1019
|
+
|
|
1020
|
+
// Fallback for HTTP or when Clipboard API is unavailable
|
|
1021
|
+
if (!success) {
|
|
1022
|
+
try {
|
|
1023
|
+
const textarea = document.createElement('textarea');
|
|
1024
|
+
textarea.value = text;
|
|
1025
|
+
textarea.style.position = 'fixed';
|
|
1026
|
+
textarea.style.opacity = '0';
|
|
1027
|
+
document.body.appendChild(textarea);
|
|
1028
|
+
textarea.select();
|
|
1029
|
+
success = document.execCommand('copy');
|
|
1030
|
+
document.body.removeChild(textarea);
|
|
1031
|
+
} catch {
|
|
1032
|
+
}
|
|
1033
|
+
}
|
|
1034
|
+
|
|
1035
|
+
if (success && button) {
|
|
1036
|
+
const originalHtml = button.innerHTML;
|
|
1037
|
+
button.innerHTML = '✓';
|
|
1038
|
+
button.classList.add('copied');
|
|
1039
|
+
setTimeout(() => {
|
|
1040
|
+
button.innerHTML = originalHtml;
|
|
1041
|
+
button.classList.remove('copied');
|
|
1042
|
+
}, 1500);
|
|
1043
|
+
}
|
|
1044
|
+
}
|
|
1045
|
+
|
|
1046
|
+
/**
|
|
1047
|
+
* Render the copy-link button HTML for a message.
|
|
1048
|
+
*/
|
|
1049
|
+
function renderCopyLinkButton(entryId) {
|
|
1050
|
+
return `<button class="copy-link-btn" data-entry-id="${entryId}" title="Copy link to this message">
|
|
1051
|
+
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
1052
|
+
<path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/>
|
|
1053
|
+
<path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/>
|
|
1054
|
+
</svg>
|
|
1055
|
+
</button>`;
|
|
1056
|
+
}
|
|
1057
|
+
|
|
1058
|
+
function renderEntry(entry, sctx) {
|
|
1059
|
+
const ts = formatTimestamp(entry.timestamp);
|
|
1060
|
+
const tsHtml = ts ? `<div class="message-timestamp">${ts}</div>` : '';
|
|
1061
|
+
const entryId = `${sctx.idPrefix}${entry.id}`;
|
|
1062
|
+
// Share links target main-session entries only; overlays skip them.
|
|
1063
|
+
const copyBtnHtml = sctx.prefix === '' ? renderCopyLinkButton(entry.id) : '';
|
|
1064
|
+
|
|
1065
|
+
if (entry.type === 'message') {
|
|
1066
|
+
const msg = entry.message;
|
|
1067
|
+
|
|
1068
|
+
if (msg.role === 'user') {
|
|
1069
|
+
let html = `<div class="user-message" id="${entryId}">${copyBtnHtml}${tsHtml}`;
|
|
1070
|
+
const content = msg.content;
|
|
1071
|
+
|
|
1072
|
+
if (Array.isArray(content)) {
|
|
1073
|
+
const images = content.filter(c => c.type === 'image');
|
|
1074
|
+
if (images.length > 0) {
|
|
1075
|
+
html += '<div class="message-images">';
|
|
1076
|
+
for (const img of images) {
|
|
1077
|
+
html += `<img src="data:${img.mimeType};base64,${img.data}" class="message-image" />`;
|
|
1078
|
+
}
|
|
1079
|
+
html += '</div>';
|
|
1080
|
+
}
|
|
1081
|
+
}
|
|
1082
|
+
|
|
1083
|
+
const text = typeof content === 'string' ? content :
|
|
1084
|
+
content.filter(c => c.type === 'text').map(c => c.text).join('\n');
|
|
1085
|
+
if (text.trim()) {
|
|
1086
|
+
html += `<div class="markdown-content">${safeMarkedParse(text)}</div>`;
|
|
1087
|
+
}
|
|
1088
|
+
html += '</div>';
|
|
1089
|
+
return html;
|
|
1090
|
+
}
|
|
1091
|
+
|
|
1092
|
+
if (msg.role === 'developer') {
|
|
1093
|
+
let html = `<div class="user-message developer-message" id="${entryId}">${copyBtnHtml}${tsHtml}`;
|
|
1094
|
+
const content = msg.content;
|
|
1095
|
+
const text = typeof content === 'string' ? content :
|
|
1096
|
+
content.filter(c => c.type === 'text').map(c => c.text).join('\n');
|
|
1097
|
+
if (text.trim()) {
|
|
1098
|
+
html += `<div class="markdown-content">${safeMarkedParse(text)}</div>`;
|
|
1099
|
+
}
|
|
1100
|
+
html += '</div>';
|
|
1101
|
+
return html;
|
|
1102
|
+
}
|
|
1103
|
+
|
|
1104
|
+
if (msg.role === 'assistant') {
|
|
1105
|
+
let html = `<div class="assistant-message" id="${entryId}">${copyBtnHtml}${tsHtml}`;
|
|
1106
|
+
|
|
1107
|
+
for (const block of msg.content) {
|
|
1108
|
+
if (block.type === 'text') {
|
|
1109
|
+
const canon = canonicalizeMessage(block.text);
|
|
1110
|
+
if (canon) {
|
|
1111
|
+
html += `<div class="assistant-text markdown-content">${safeMarkedParse(block.text)}</div>`;
|
|
1112
|
+
}
|
|
1113
|
+
} else if (block.type === 'thinking') {
|
|
1114
|
+
const thinking = canonicalizeMessage(block.thinking);
|
|
1115
|
+
if (!thinking) continue;
|
|
1116
|
+
html += `<div class="thinking-block">
|
|
1117
|
+
<div class="thinking-text">${escapeHtml(thinking)}</div>
|
|
1118
|
+
<div class="thinking-collapsed">Thinking ...</div>
|
|
1119
|
+
</div>`;
|
|
1120
|
+
} else if (block.type === 'image') {
|
|
1121
|
+
html += `<div class="message-images"><img src="data:${block.mimeType};base64,${block.data}" class="message-image" /></div>`;
|
|
1122
|
+
}
|
|
1123
|
+
}
|
|
1124
|
+
for (const block of msg.content) {
|
|
1125
|
+
if (block.type === 'toolCall') {
|
|
1126
|
+
html += renderToolCall(block, sctx);
|
|
1127
|
+
}
|
|
1128
|
+
}
|
|
1129
|
+
|
|
1130
|
+
if (msg.stopReason === 'aborted') {
|
|
1131
|
+
html += '<div class="error-text">Aborted</div>';
|
|
1132
|
+
} else if (msg.stopReason === 'error') {
|
|
1133
|
+
html += `<div class="error-text">Error: ${escapeHtml(msg.errorMessage || 'Unknown error')}</div>`;
|
|
1134
|
+
}
|
|
1135
|
+
|
|
1136
|
+
html += '</div>';
|
|
1137
|
+
return html;
|
|
1138
|
+
}
|
|
1139
|
+
|
|
1140
|
+
if (msg.role === 'bashExecution') {
|
|
1141
|
+
const isError = msg.cancelled || (msg.exitCode !== 0 && msg.exitCode !== null);
|
|
1142
|
+
let html = `<div class="tool-execution ${isError ? 'error' : 'success'}" id="${entryId}">${tsHtml}`;
|
|
1143
|
+
html += `<div class="tool-command">$ ${escapeHtml(msg.command)}</div>`;
|
|
1144
|
+
if (msg.output) html += formatExpandableOutput(msg.output, 10);
|
|
1145
|
+
if (msg.cancelled) {
|
|
1146
|
+
html += '<div style="color: var(--warning)">(cancelled)</div>';
|
|
1147
|
+
} else if (msg.exitCode !== 0 && msg.exitCode !== null) {
|
|
1148
|
+
html += `<div style="color: var(--error)">(exit ${msg.exitCode})</div>`;
|
|
1149
|
+
}
|
|
1150
|
+
html += '</div>';
|
|
1151
|
+
return html;
|
|
1152
|
+
}
|
|
1153
|
+
|
|
1154
|
+
if (msg.role === 'jsExecution') {
|
|
1155
|
+
const isError = msg.cancelled || (msg.exitCode !== 0 && msg.exitCode !== null);
|
|
1156
|
+
let html = `<div class="tool-execution ${isError ? 'error' : 'success'}" id="${entryId}">${tsHtml}`;
|
|
1157
|
+
html += `<div class="tool-command">$ ${escapeHtml(msg.code)}</div>`;
|
|
1158
|
+
if (msg.output) html += formatExpandableOutput(msg.output, 10);
|
|
1159
|
+
if (msg.cancelled) {
|
|
1160
|
+
html += '<div style="color: var(--warning)">(cancelled)</div>';
|
|
1161
|
+
} else if (msg.exitCode !== 0 && msg.exitCode !== null) {
|
|
1162
|
+
html += `<div style="color: var(--error)">(exit ${msg.exitCode})</div>`;
|
|
1163
|
+
}
|
|
1164
|
+
html += '</div>';
|
|
1165
|
+
return html;
|
|
1166
|
+
}
|
|
1167
|
+
|
|
1168
|
+
if (msg.role === 'toolResult') return '';
|
|
1169
|
+
}
|
|
1170
|
+
|
|
1171
|
+
if (entry.type === 'model_change') {
|
|
1172
|
+
const html = `<div class="model-change" id="${entryId}">${tsHtml}Switched to model: <span class="model-name">${escapeHtml(entry.model)}</span></div>`;
|
|
1173
|
+
return html;
|
|
1174
|
+
}
|
|
1175
|
+
|
|
1176
|
+
if (entry.type === 'thinking_level_change') {
|
|
1177
|
+
const html = `<div class="thinking-change" id="${entryId}">${tsHtml}Thinking level: <span class="thinking-level">${escapeHtml(entry.thinkingLevel)}</span></div>`;
|
|
1178
|
+
return html;
|
|
1179
|
+
}
|
|
1180
|
+
|
|
1181
|
+
|
|
1182
|
+
if (entry.type === 'compaction') {
|
|
1183
|
+
return `<div class="compaction" id="${entryId}" onclick="this.classList.toggle('expanded')">
|
|
1184
|
+
<div class="compaction-label">[compaction]</div>
|
|
1185
|
+
<div class="compaction-collapsed">Compacted from ${entry.tokensBefore.toLocaleString()} tokens</div>
|
|
1186
|
+
<div class="compaction-content"><strong>Compacted from ${entry.tokensBefore.toLocaleString()} tokens</strong>\n\n${escapeHtml(entry.summary)}</div>
|
|
1187
|
+
</div>`;
|
|
1188
|
+
}
|
|
1189
|
+
|
|
1190
|
+
if (entry.type === 'branch_summary') {
|
|
1191
|
+
return `<div class="branch-summary" id="${entryId}">${tsHtml}
|
|
1192
|
+
<div class="branch-summary-header">Branch Summary</div>
|
|
1193
|
+
<div class="markdown-content">${safeMarkedParse(entry.summary)}</div>
|
|
1194
|
+
</div>`;
|
|
1195
|
+
}
|
|
1196
|
+
|
|
1197
|
+
if (entry.type === 'custom_message' && entry.display) {
|
|
1198
|
+
return `<div class="hook-message" id="${entryId}">${tsHtml}
|
|
1199
|
+
<div class="hook-type">[${escapeHtml(entry.customType)}]</div>
|
|
1200
|
+
<div class="markdown-content">${safeMarkedParse(typeof entry.content === 'string' ? entry.content : JSON.stringify(entry.content))}</div>
|
|
1201
|
+
</div>`;
|
|
1202
|
+
}
|
|
1203
|
+
|
|
1204
|
+
return '';
|
|
1205
|
+
}
|
|
1206
|
+
|
|
1207
|
+
// ============================================================
|
|
1208
|
+
// HEADER / STATS
|
|
1209
|
+
// ============================================================
|
|
1210
|
+
|
|
1211
|
+
function computeStats(entryList) {
|
|
1212
|
+
let userMessages = 0, developerMessages = 0, assistantMessages = 0, toolResults = 0;
|
|
1213
|
+
let customMessages = 0, compactions = 0, branchSummaries = 0, toolCalls = 0;
|
|
1214
|
+
const tokens = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
|
|
1215
|
+
const cost = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
|
|
1216
|
+
const models = new Set();
|
|
1217
|
+
|
|
1218
|
+
for (const entry of entryList) {
|
|
1219
|
+
if (entry.type === 'message') {
|
|
1220
|
+
const msg = entry.message;
|
|
1221
|
+
if (msg.role === 'user') userMessages++;
|
|
1222
|
+
if (msg.role === 'developer') developerMessages++;
|
|
1223
|
+
if (msg.role === 'assistant') {
|
|
1224
|
+
assistantMessages++;
|
|
1225
|
+
if (msg.model) models.add(msg.provider ? `${msg.provider}/${msg.model}` : msg.model);
|
|
1226
|
+
if (msg.usage) {
|
|
1227
|
+
tokens.input += msg.usage.input || 0;
|
|
1228
|
+
tokens.output += msg.usage.output || 0;
|
|
1229
|
+
tokens.cacheRead += msg.usage.cacheRead || 0;
|
|
1230
|
+
tokens.cacheWrite += msg.usage.cacheWrite || 0;
|
|
1231
|
+
if (msg.usage.cost) {
|
|
1232
|
+
cost.input += msg.usage.cost.input || 0;
|
|
1233
|
+
cost.output += msg.usage.cost.output || 0;
|
|
1234
|
+
cost.cacheRead += msg.usage.cost.cacheRead || 0;
|
|
1235
|
+
cost.cacheWrite += msg.usage.cost.cacheWrite || 0;
|
|
1236
|
+
}
|
|
1237
|
+
}
|
|
1238
|
+
toolCalls += msg.content.filter(c => c.type === 'toolCall').length;
|
|
1239
|
+
}
|
|
1240
|
+
if (msg.role === 'toolResult') toolResults++;
|
|
1241
|
+
} else if (entry.type === 'compaction') {
|
|
1242
|
+
compactions++;
|
|
1243
|
+
} else if (entry.type === 'branch_summary') {
|
|
1244
|
+
branchSummaries++;
|
|
1245
|
+
} else if (entry.type === 'custom_message') {
|
|
1246
|
+
customMessages++;
|
|
1247
|
+
}
|
|
1248
|
+
}
|
|
1249
|
+
|
|
1250
|
+
return { userMessages, developerMessages, assistantMessages, toolResults, customMessages, compactions, branchSummaries, toolCalls, tokens, cost, models: Array.from(models) };
|
|
1251
|
+
}
|
|
1252
|
+
|
|
1253
|
+
const globalStats = computeStats(entries);
|
|
1254
|
+
|
|
1255
|
+
function renderHeader() {
|
|
1256
|
+
const totalCost = globalStats.cost.input + globalStats.cost.output + globalStats.cost.cacheRead + globalStats.cost.cacheWrite;
|
|
1257
|
+
|
|
1258
|
+
const tokenParts = [];
|
|
1259
|
+
if (globalStats.tokens.input) tokenParts.push(`↑${formatTokens(globalStats.tokens.input)}`);
|
|
1260
|
+
if (globalStats.tokens.output) tokenParts.push(`↓${formatTokens(globalStats.tokens.output)}`);
|
|
1261
|
+
if (globalStats.tokens.cacheRead) tokenParts.push(`R${formatTokens(globalStats.tokens.cacheRead)}`);
|
|
1262
|
+
if (globalStats.tokens.cacheWrite) tokenParts.push(`W${formatTokens(globalStats.tokens.cacheWrite)}`);
|
|
1263
|
+
|
|
1264
|
+
const msgParts = [];
|
|
1265
|
+
if (globalStats.userMessages) msgParts.push(`${globalStats.userMessages} user`);
|
|
1266
|
+
if (globalStats.developerMessages) msgParts.push(`${globalStats.developerMessages} developer`);
|
|
1267
|
+
if (globalStats.assistantMessages) msgParts.push(`${globalStats.assistantMessages} assistant`);
|
|
1268
|
+
if (globalStats.toolResults) msgParts.push(`${globalStats.toolResults} tool results`);
|
|
1269
|
+
if (globalStats.customMessages) msgParts.push(`${globalStats.customMessages} custom`);
|
|
1270
|
+
if (globalStats.compactions) msgParts.push(`${globalStats.compactions} compactions`);
|
|
1271
|
+
if (globalStats.branchSummaries) msgParts.push(`${globalStats.branchSummaries} branch summaries`);
|
|
1272
|
+
|
|
1273
|
+
let html = `
|
|
1274
|
+
<div class="header">
|
|
1275
|
+
<h1>Session: ${escapeHtml(header?.id || 'unknown')}</h1>
|
|
1276
|
+
<div class="help-bar">T toggle thinking · O toggle tools</div>
|
|
1277
|
+
<div class="header-info">
|
|
1278
|
+
<div class="info-item"><span class="info-label">Date:</span><span class="info-value">${header?.timestamp ? new Date(header.timestamp).toLocaleString() : 'unknown'}</span></div>
|
|
1279
|
+
<div class="info-item"><span class="info-label">Models:</span><span class="info-value">${globalStats.models.join(', ') || 'unknown'}</span></div>
|
|
1280
|
+
<div class="info-item"><span class="info-label">Messages:</span><span class="info-value">${msgParts.join(', ') || '0'}</span></div>
|
|
1281
|
+
<div class="info-item"><span class="info-label">Tool Calls:</span><span class="info-value">${globalStats.toolCalls}</span></div>
|
|
1282
|
+
<div class="info-item"><span class="info-label">Tokens:</span><span class="info-value">${tokenParts.join(' ') || '0'}</span></div>
|
|
1283
|
+
<div class="info-item"><span class="info-label">Cost:</span><span class="info-value">$${totalCost.toFixed(3)}</span></div>
|
|
1284
|
+
</div>
|
|
1285
|
+
</div>`;
|
|
1286
|
+
|
|
1287
|
+
if (systemPrompt) {
|
|
1288
|
+
html += `<div class="system-prompt">
|
|
1289
|
+
<div class="system-prompt-header">System Prompt</div>
|
|
1290
|
+
<div class="system-prompt-content">${escapeHtml(systemPrompt)}</div>
|
|
1291
|
+
</div>`;
|
|
1292
|
+
}
|
|
1293
|
+
|
|
1294
|
+
if (tools && tools.length > 0) {
|
|
1295
|
+
const namesHtml = tools.map(t => `<span class="tool-name-chip">${escapeHtml(t.name)}</span>`).join('');
|
|
1296
|
+
const fullHtml = tools.map(t => `<div class="tool-item"><span class="tool-item-name">${escapeHtml(t.name)}</span> - <span class="tool-item-desc">${escapeHtml(t.description)}</span></div>`).join('');
|
|
1297
|
+
html += `<div class="tools-list collapsed" onclick="this.classList.toggle('collapsed')">
|
|
1298
|
+
<div class="tools-header">Available Tools (${tools.length})</div>
|
|
1299
|
+
<div class="tools-collapsed">${namesHtml}</div>
|
|
1300
|
+
<div class="tools-content">${fullHtml}</div>
|
|
1301
|
+
</div>`;
|
|
1302
|
+
}
|
|
1303
|
+
|
|
1304
|
+
return html;
|
|
1305
|
+
}
|
|
1306
|
+
|
|
1307
|
+
// ============================================================
|
|
1308
|
+
// NAVIGATION
|
|
1309
|
+
// ============================================================
|
|
1310
|
+
|
|
1311
|
+
// Cache for rendered entry DOM nodes
|
|
1312
|
+
const entryCache = new Map();
|
|
1313
|
+
|
|
1314
|
+
function renderEntryToNode(entry, sctx) {
|
|
1315
|
+
// Cache main-session nodes only; sub-session bodies are cached whole
|
|
1316
|
+
// per key in subSessionBodyCache, so each entry renders once anyway.
|
|
1317
|
+
const cacheable = sctx.prefix === '';
|
|
1318
|
+
if (cacheable && entryCache.has(entry.id)) {
|
|
1319
|
+
return entryCache.get(entry.id).cloneNode(true);
|
|
1320
|
+
}
|
|
1321
|
+
|
|
1322
|
+
// Render to HTML string, then parse to node
|
|
1323
|
+
const html = renderEntry(entry, sctx);
|
|
1324
|
+
if (!html) return null;
|
|
1325
|
+
|
|
1326
|
+
const template = document.createElement('template');
|
|
1327
|
+
template.innerHTML = html;
|
|
1328
|
+
const node = template.content.firstElementChild;
|
|
1329
|
+
|
|
1330
|
+
// Cache the node
|
|
1331
|
+
if (cacheable && node) {
|
|
1332
|
+
entryCache.set(entry.id, node.cloneNode(true));
|
|
1333
|
+
}
|
|
1334
|
+
return node;
|
|
1335
|
+
}
|
|
1336
|
+
|
|
1337
|
+
function navigateTo(targetId, scrollMode = 'target', scrollToEntryId = null) {
|
|
1338
|
+
currentLeafId = targetId;
|
|
1339
|
+
currentTargetId = scrollToEntryId || targetId;
|
|
1340
|
+
const path = getPath(targetId);
|
|
1341
|
+
|
|
1342
|
+
renderTree();
|
|
1343
|
+
|
|
1344
|
+
document.getElementById('header-container').innerHTML = renderHeader();
|
|
1345
|
+
|
|
1346
|
+
// Build messages using cached DOM nodes
|
|
1347
|
+
const messagesEl = document.getElementById('messages');
|
|
1348
|
+
const fragment = document.createDocumentFragment();
|
|
1349
|
+
|
|
1350
|
+
for (const entry of path) {
|
|
1351
|
+
const node = renderEntryToNode(entry, mainSctx);
|
|
1352
|
+
if (node) {
|
|
1353
|
+
fragment.appendChild(node);
|
|
1354
|
+
}
|
|
1355
|
+
}
|
|
1356
|
+
|
|
1357
|
+
messagesEl.innerHTML = '';
|
|
1358
|
+
messagesEl.appendChild(fragment);
|
|
1359
|
+
|
|
1360
|
+
// Attach click handlers for copy-link buttons
|
|
1361
|
+
messagesEl.querySelectorAll('.copy-link-btn').forEach(btn => {
|
|
1362
|
+
btn.addEventListener('click', (e) => {
|
|
1363
|
+
e.stopPropagation();
|
|
1364
|
+
const entryId = btn.dataset.entryId;
|
|
1365
|
+
const shareUrl = buildShareUrl(entryId);
|
|
1366
|
+
copyToClipboard(shareUrl, btn);
|
|
1367
|
+
});
|
|
1368
|
+
});
|
|
1369
|
+
|
|
1370
|
+
// Use setTimeout(0) to ensure DOM is fully laid out before scrolling
|
|
1371
|
+
setTimeout(() => {
|
|
1372
|
+
const content = document.getElementById('content');
|
|
1373
|
+
if (scrollMode === 'bottom') {
|
|
1374
|
+
content.scrollTop = content.scrollHeight;
|
|
1375
|
+
} else if (scrollMode === 'target') {
|
|
1376
|
+
const scrollTargetId = scrollToEntryId || targetId;
|
|
1377
|
+
const targetEl = document.getElementById(`entry-${scrollTargetId}`);
|
|
1378
|
+
if (targetEl) {
|
|
1379
|
+
targetEl.scrollIntoView({ block: 'center' });
|
|
1380
|
+
if (scrollToEntryId) {
|
|
1381
|
+
targetEl.classList.add('highlight');
|
|
1382
|
+
setTimeout(() => targetEl.classList.remove('highlight'), 2000);
|
|
1383
|
+
}
|
|
1384
|
+
}
|
|
1385
|
+
}
|
|
1386
|
+
}, 0);
|
|
1387
|
+
}
|
|
1388
|
+
|
|
1389
|
+
// ============================================================
|
|
1390
|
+
// INITIALIZATION
|
|
1391
|
+
// ============================================================
|
|
1392
|
+
|
|
1393
|
+
// Escape HTML tags in text (but not code blocks)
|
|
1394
|
+
function escapeHtmlTags(text) {
|
|
1395
|
+
return text.replace(/<(?=[a-zA-Z\/])/g, '<');
|
|
1396
|
+
}
|
|
1397
|
+
|
|
1398
|
+
// Configure marked with syntax highlighting and HTML escaping for text
|
|
1399
|
+
marked.use({
|
|
1400
|
+
breaks: true,
|
|
1401
|
+
gfm: true,
|
|
1402
|
+
renderer: {
|
|
1403
|
+
// Code blocks: syntax highlight, no HTML escaping
|
|
1404
|
+
code(token) {
|
|
1405
|
+
const code = token.text;
|
|
1406
|
+
const lang = token.lang;
|
|
1407
|
+
let highlighted;
|
|
1408
|
+
if (lang && hljs.getLanguage(lang)) {
|
|
1409
|
+
try {
|
|
1410
|
+
highlighted = hljs.highlight(code, { language: lang }).value;
|
|
1411
|
+
} catch {
|
|
1412
|
+
highlighted = escapeHtml(code);
|
|
1413
|
+
}
|
|
1414
|
+
} else {
|
|
1415
|
+
// Auto-detect language if not specified
|
|
1416
|
+
try {
|
|
1417
|
+
highlighted = hljs.highlightAuto(code).value;
|
|
1418
|
+
} catch {
|
|
1419
|
+
highlighted = escapeHtml(code);
|
|
1420
|
+
}
|
|
1421
|
+
}
|
|
1422
|
+
return `<pre><code class="hljs">${highlighted}</code></pre>`;
|
|
1423
|
+
},
|
|
1424
|
+
// Text content: escape HTML tags
|
|
1425
|
+
text(token) {
|
|
1426
|
+
return token.tokens ? this.parser.parseInline(token.tokens) : escapeHtmlTags(escapeHtml(token.text));
|
|
1427
|
+
},
|
|
1428
|
+
// Inline code: escape HTML
|
|
1429
|
+
codespan(token) {
|
|
1430
|
+
return `<code>${escapeHtml(token.text)}</code>`;
|
|
1431
|
+
}
|
|
1432
|
+
}
|
|
1433
|
+
});
|
|
1434
|
+
|
|
1435
|
+
// Simple marked parse (escaping handled in renderers)
|
|
1436
|
+
function safeMarkedParse(text) {
|
|
1437
|
+
return marked.parse(text);
|
|
1438
|
+
}
|
|
1439
|
+
|
|
1440
|
+
// Search input
|
|
1441
|
+
const searchInput = document.getElementById('tree-search');
|
|
1442
|
+
searchInput.addEventListener('input', (e) => {
|
|
1443
|
+
searchQuery = e.target.value;
|
|
1444
|
+
forceTreeRerender();
|
|
1445
|
+
});
|
|
1446
|
+
|
|
1447
|
+
// Filter buttons
|
|
1448
|
+
document.querySelectorAll('.filter-btn').forEach(btn => {
|
|
1449
|
+
btn.addEventListener('click', () => {
|
|
1450
|
+
document.querySelectorAll('.filter-btn').forEach(b => b.classList.remove('active'));
|
|
1451
|
+
btn.classList.add('active');
|
|
1452
|
+
filterMode = btn.dataset.filter;
|
|
1453
|
+
forceTreeRerender();
|
|
1454
|
+
});
|
|
1455
|
+
});
|
|
1456
|
+
|
|
1457
|
+
// Sidebar toggle
|
|
1458
|
+
const sidebar = document.getElementById('sidebar');
|
|
1459
|
+
const overlay = document.getElementById('sidebar-overlay');
|
|
1460
|
+
const hamburger = document.getElementById('hamburger');
|
|
1461
|
+
const sidebarResizer = document.getElementById('sidebar-resizer');
|
|
1462
|
+
const SIDEBAR_WIDTH_STORAGE_KEY = 'pi-share:v1:sidebar-width';
|
|
1463
|
+
const MIN_CONTENT_WIDTH = 320;
|
|
1464
|
+
|
|
1465
|
+
function isMobileLayout() {
|
|
1466
|
+
return window.matchMedia('(max-width: 900px)').matches;
|
|
1467
|
+
}
|
|
1468
|
+
|
|
1469
|
+
function getSidebarBounds() {
|
|
1470
|
+
const rootStyles = getComputedStyle(document.documentElement);
|
|
1471
|
+
const minWidth = parseFloat(rootStyles.getPropertyValue('--sidebar-min-width')) || 240;
|
|
1472
|
+
const maxWidth = parseFloat(rootStyles.getPropertyValue('--sidebar-max-width')) || 720;
|
|
1473
|
+
const viewportMaxWidth = window.innerWidth - MIN_CONTENT_WIDTH;
|
|
1474
|
+
return {
|
|
1475
|
+
minWidth,
|
|
1476
|
+
maxWidth: Math.max(minWidth, Math.min(maxWidth, viewportMaxWidth))
|
|
1477
|
+
};
|
|
1478
|
+
}
|
|
1479
|
+
|
|
1480
|
+
function clampSidebarWidth(width) {
|
|
1481
|
+
const { minWidth, maxWidth } = getSidebarBounds();
|
|
1482
|
+
return Math.max(minWidth, Math.min(maxWidth, width));
|
|
1483
|
+
}
|
|
1484
|
+
|
|
1485
|
+
function applySidebarWidth(width) {
|
|
1486
|
+
document.documentElement.style.setProperty('--sidebar-width', `${Math.round(clampSidebarWidth(width))}px`);
|
|
1487
|
+
}
|
|
1488
|
+
|
|
1489
|
+
function loadSidebarWidth() {
|
|
1490
|
+
try {
|
|
1491
|
+
const raw = localStorage.getItem(SIDEBAR_WIDTH_STORAGE_KEY);
|
|
1492
|
+
if (raw === null) return null;
|
|
1493
|
+
const width = Number(raw);
|
|
1494
|
+
return Number.isFinite(width) ? width : null;
|
|
1495
|
+
} catch {
|
|
1496
|
+
return null;
|
|
1497
|
+
}
|
|
1498
|
+
}
|
|
1499
|
+
|
|
1500
|
+
function saveSidebarWidth(width) {
|
|
1501
|
+
try {
|
|
1502
|
+
localStorage.setItem(SIDEBAR_WIDTH_STORAGE_KEY, String(Math.round(clampSidebarWidth(width))));
|
|
1503
|
+
} catch {
|
|
1504
|
+
// Ignore storage failures (e.g. private browsing restrictions)
|
|
1505
|
+
}
|
|
1506
|
+
}
|
|
1507
|
+
|
|
1508
|
+
function setupSidebarResize() {
|
|
1509
|
+
const savedWidth = loadSidebarWidth();
|
|
1510
|
+
if (savedWidth !== null) {
|
|
1511
|
+
applySidebarWidth(savedWidth);
|
|
1512
|
+
}
|
|
1513
|
+
|
|
1514
|
+
if (!sidebarResizer) return;
|
|
1515
|
+
|
|
1516
|
+
let cleanupDrag = null;
|
|
1517
|
+
|
|
1518
|
+
const stopDrag = (pointerId) => {
|
|
1519
|
+
if (cleanupDrag) {
|
|
1520
|
+
cleanupDrag(pointerId);
|
|
1521
|
+
cleanupDrag = null;
|
|
1522
|
+
}
|
|
1523
|
+
};
|
|
1524
|
+
|
|
1525
|
+
sidebarResizer.addEventListener('pointerdown', (e) => {
|
|
1526
|
+
if (isMobileLayout()) return;
|
|
1527
|
+
|
|
1528
|
+
e.preventDefault();
|
|
1529
|
+
const startX = e.clientX;
|
|
1530
|
+
const startWidth = sidebar.getBoundingClientRect().width;
|
|
1531
|
+
document.body.classList.add('sidebar-resizing');
|
|
1532
|
+
sidebarResizer.setPointerCapture?.(e.pointerId);
|
|
1533
|
+
|
|
1534
|
+
const onPointerMove = (event) => {
|
|
1535
|
+
applySidebarWidth(startWidth + (event.clientX - startX));
|
|
1536
|
+
};
|
|
1537
|
+
|
|
1538
|
+
cleanupDrag = (pointerIdToRelease) => {
|
|
1539
|
+
document.body.classList.remove('sidebar-resizing');
|
|
1540
|
+
sidebarResizer.releasePointerCapture?.(pointerIdToRelease);
|
|
1541
|
+
window.removeEventListener('pointermove', onPointerMove);
|
|
1542
|
+
window.removeEventListener('pointerup', onPointerUp);
|
|
1543
|
+
window.removeEventListener('pointercancel', onPointerCancel);
|
|
1544
|
+
saveSidebarWidth(sidebar.getBoundingClientRect().width);
|
|
1545
|
+
};
|
|
1546
|
+
|
|
1547
|
+
const onPointerUp = (event) => stopDrag(event.pointerId);
|
|
1548
|
+
const onPointerCancel = (event) => stopDrag(event.pointerId);
|
|
1549
|
+
|
|
1550
|
+
window.addEventListener('pointermove', onPointerMove);
|
|
1551
|
+
window.addEventListener('pointerup', onPointerUp);
|
|
1552
|
+
window.addEventListener('pointercancel', onPointerCancel);
|
|
1553
|
+
});
|
|
1554
|
+
|
|
1555
|
+
sidebarResizer.addEventListener('dblclick', () => {
|
|
1556
|
+
if (isMobileLayout()) return;
|
|
1557
|
+
applySidebarWidth(400);
|
|
1558
|
+
saveSidebarWidth(400);
|
|
1559
|
+
});
|
|
1560
|
+
|
|
1561
|
+
window.addEventListener('resize', () => {
|
|
1562
|
+
if (isMobileLayout()) return;
|
|
1563
|
+
applySidebarWidth(sidebar.getBoundingClientRect().width);
|
|
1564
|
+
});
|
|
1565
|
+
}
|
|
1566
|
+
|
|
1567
|
+
setupSidebarResize();
|
|
1568
|
+
|
|
1569
|
+
hamburger.addEventListener('click', () => {
|
|
1570
|
+
sidebar.classList.add('open');
|
|
1571
|
+
overlay.classList.add('open');
|
|
1572
|
+
hamburger.style.display = 'none';
|
|
1573
|
+
});
|
|
1574
|
+
|
|
1575
|
+
const closeSidebar = () => {
|
|
1576
|
+
sidebar.classList.remove('open');
|
|
1577
|
+
overlay.classList.remove('open');
|
|
1578
|
+
hamburger.style.display = '';
|
|
1579
|
+
};
|
|
1580
|
+
|
|
1581
|
+
overlay.addEventListener('click', closeSidebar);
|
|
1582
|
+
document.getElementById('sidebar-close').addEventListener('click', closeSidebar);
|
|
1583
|
+
|
|
1584
|
+
// Toggle states
|
|
1585
|
+
let thinkingExpanded = false;
|
|
1586
|
+
let toolOutputsExpanded = false;
|
|
1587
|
+
|
|
1588
|
+
const toggleThinking = () => {
|
|
1589
|
+
thinkingExpanded = !thinkingExpanded;
|
|
1590
|
+
document.querySelectorAll('.thinking-text').forEach(el => {
|
|
1591
|
+
el.style.display = thinkingExpanded ? 'block' : 'none';
|
|
1592
|
+
});
|
|
1593
|
+
document.querySelectorAll('.thinking-collapsed').forEach(el => {
|
|
1594
|
+
el.style.display = thinkingExpanded ? 'none' : 'block';
|
|
1595
|
+
});
|
|
1596
|
+
};
|
|
1597
|
+
|
|
1598
|
+
const toggleToolOutputs = () => {
|
|
1599
|
+
toolOutputsExpanded = !toolOutputsExpanded;
|
|
1600
|
+
document.querySelectorAll('.tool-output.expandable').forEach(el => {
|
|
1601
|
+
el.classList.toggle('expanded', toolOutputsExpanded);
|
|
1602
|
+
});
|
|
1603
|
+
document.querySelectorAll('.compaction').forEach(el => {
|
|
1604
|
+
el.classList.toggle('expanded', toolOutputsExpanded);
|
|
1605
|
+
});
|
|
1606
|
+
};
|
|
1607
|
+
|
|
1608
|
+
// Keyboard shortcuts
|
|
1609
|
+
document.addEventListener('keydown', (e) => {
|
|
1610
|
+
if (e.key === 'Escape') {
|
|
1611
|
+
if (overlayStack.length > 0) {
|
|
1612
|
+
e.preventDefault();
|
|
1613
|
+
popSubSession();
|
|
1614
|
+
return;
|
|
1615
|
+
}
|
|
1616
|
+
searchInput.value = '';
|
|
1617
|
+
searchQuery = '';
|
|
1618
|
+
navigateTo(leafId, 'bottom');
|
|
1619
|
+
}
|
|
1620
|
+
if (e.key === 't' || e.key === 'T' || e.key === 'o' || e.key === 'O') {
|
|
1621
|
+
// Skip when typing in the sidebar search (or any other editable target)
|
|
1622
|
+
// so the chord can't fire on a user's letter input. Avoid Ctrl/Cmd-based
|
|
1623
|
+
// chords entirely — every major browser reserves Ctrl+T (new tab) and
|
|
1624
|
+
// Ctrl+O (open file), so the shortcut would never reach the page.
|
|
1625
|
+
const t = e.target;
|
|
1626
|
+
const editable =
|
|
1627
|
+
t && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.isContentEditable);
|
|
1628
|
+
if (editable) return;
|
|
1629
|
+
if (e.ctrlKey || e.metaKey || e.altKey) return;
|
|
1630
|
+
e.preventDefault();
|
|
1631
|
+
if (e.key === 't' || e.key === 'T') toggleThinking();
|
|
1632
|
+
else toggleToolOutputs();
|
|
1633
|
+
}
|
|
1634
|
+
});
|
|
1635
|
+
|
|
1636
|
+
// Initial render
|
|
1637
|
+
// If URL has targetId, scroll to that specific message; otherwise stay at top
|
|
1638
|
+
if (leafId) {
|
|
1639
|
+
if (urlTargetId && byId.has(urlTargetId)) {
|
|
1640
|
+
navigateTo(leafId, 'target', urlTargetId);
|
|
1641
|
+
} else {
|
|
1642
|
+
navigateTo(leafId, 'none');
|
|
1643
|
+
}
|
|
1644
|
+
} else if (entries.length > 0) {
|
|
1645
|
+
// Fallback: use last entry if no leafId
|
|
1646
|
+
navigateTo(entries[entries.length - 1].id, 'none');
|
|
1647
|
+
}
|
|
1648
|
+
} // end bootSession
|
|
1649
|
+
|
|
1650
|
+
function showLoadError(err) {
|
|
1651
|
+
const messages = document.getElementById('messages');
|
|
1652
|
+
if (!messages) return;
|
|
1653
|
+
const div = document.createElement('div');
|
|
1654
|
+
div.className = 'share-load-error';
|
|
1655
|
+
div.textContent = 'Failed to load session: ' + (err && err.message ? err.message : String(err));
|
|
1656
|
+
messages.appendChild(div);
|
|
1657
|
+
}
|
|
1658
|
+
|
|
1659
|
+
const pending = window.__OMP_SESSION_DATA__;
|
|
1660
|
+
if (pending && typeof pending.then === 'function') {
|
|
1661
|
+
pending.then(bootSession, showLoadError);
|
|
1662
|
+
} else {
|
|
1663
|
+
const base64 = document.getElementById('session-data').textContent;
|
|
1664
|
+
const binary = atob(base64);
|
|
1665
|
+
const bytes = new Uint8Array(binary.length);
|
|
1666
|
+
for (let i = 0; i < binary.length; i++) {
|
|
1667
|
+
bytes[i] = binary.charCodeAt(i);
|
|
1668
|
+
}
|
|
1669
|
+
bootSession(JSON.parse(new TextDecoder('utf-8').decode(bytes)));
|
|
1670
|
+
}
|
|
1671
|
+
})();
|