@niracler/encore 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,6 +3,33 @@
3
3
  // --- i18n.mjs ---
4
4
  const DICTS = {
5
5
  zh: {
6
+ workspaceWrite: '工作区可写',
7
+ contextLabel: '上下文',
8
+ itemCount: '{n} 条',
9
+ agentSent: '已派出',
10
+ agentStopped: '已叫停',
11
+ agentRateLimited: '额度中断',
12
+ agentFailed: '失败',
13
+ agentDone: '已交回',
14
+ turnTag: '第 {n} 轮',
15
+ replyTag: '第 {n} 次回复',
16
+ stepTag: '第 {n} 步',
17
+ thinking: '思考',
18
+ reasoning: '推理过程',
19
+ preview: '预览',
20
+ draft: '草稿',
21
+ rule: '规则',
22
+ promptTitle: '提问 #{n}',
23
+ sessionStart: '会话开始',
24
+ userMessage: '用户消息',
25
+ assistantReply: '助手回复',
26
+ appendedPrompt: '已将用户消息加入上下文',
27
+ waitingForTools: '等待助手推理与调用工具',
28
+ synthesizing: '汇总结果({tools})',
29
+ directResponse: '直接回复',
30
+ completedResponse: '回复完成',
31
+ toolCalls: '工具调用 × {n}',
32
+ archivedTools: '已归档 {n} 条工具输出(-{tokens}k tokens)',
6
33
  langCode: 'zh-CN',
7
34
  toggleLangLabel: 'EN',
8
35
  toggleLangTitle: 'Switch to English',
@@ -19,12 +46,12 @@ const DICTS = {
19
46
  sendThisPrompt: '发送本轮提问',
20
47
  waitNextStep: '等待下一步',
21
48
  composerPlaceholder: '向 Agent 发送消息…',
22
- composerFinished: '会话已结束 · 点击上方任意消息可回看当时上下文',
49
+ composerFinished: '会话已结束 · 点击上方任意消息可查看当时的上下文快照',
23
50
  emptyHintStart: '点击左下角 <b>▶ 播放</b>',
24
51
  emptyHintOrSend: ' 或输入框蓝色发送键 <b>↑</b>',
25
52
  emptyHintEnd: ',体验完整对话与上下文生长',
26
- activeContext: '当前上下文',
27
- snapInitial: '快照:启动初始态',
53
+ activeContext: '上下文快照',
54
+ snapInitial: '初始上下文',
28
55
  snapInspect: '回看:第 {step} / {total} 步',
29
56
  snapCurrent: '第 {step} / {total} 步',
30
57
  usedSuffix: '已用',
@@ -35,20 +62,20 @@ const DICTS = {
35
62
  legendSys: '系统提示词',
36
63
  legendSchema: '工具定义',
37
64
  legendUser: '用户消息',
38
- legendMem: '注入内容',
65
+ legendMem: '记忆规则',
39
66
  legendSkill: '技能注入',
40
67
  legendMsg: '助手回复',
41
68
  legendTool: '工具输出',
42
69
  catSys: '系统提示词(System Prompt)',
43
70
  catSchema: '工具定义(Tool Schemas & MCP)',
44
71
  catUser: '用户消息(User Messages)',
45
- catMem: '注入内容(Memory & Rules)',
72
+ catMem: '记忆规则(Memory & Rules)',
46
73
  catSkill: '技能注入(Skills)',
47
- catMsg: '助手回复(Assistant Messages)',
74
+ catMsg: '助手回复(Assistant Replies)',
48
75
  catTool: '工具输出(Tool Outputs)',
49
76
  contextInspector: '上下文明细',
50
77
  contextInspectorHint: '点击色块或消息定格展开',
51
- emptyCategory: '当前步骤暂无条目',
78
+ emptyCategory: '当前步骤暂无记录',
52
79
  viewFullPayload: '查看完整内容 ↗',
53
80
  omittedImages: '({prefix}{count} 张附图未收录)',
54
81
  omittedImagesAlso: '另有 ',
@@ -62,15 +89,29 @@ const DICTS = {
62
89
  compactModalTitle: '上下文压缩摘要',
63
90
  asksYou: '{tool} 问你',
64
91
  deliverablesTitle: '交回的成果',
65
- subagentReportTitle: '子任务报告 · {label}',
92
+ inputFiles: '随消息附上的文件',
93
+ fileVerified: '已核对为会话当时的版本',
94
+ fileExportCopy: '已收录导出时的版本,无法确认是否与会话当时一致',
95
+ fileHashMismatch: '已收录导出时的版本,与会话记录的校验值不符',
96
+ fileMissing: '未找到原文件,无法回看',
97
+ fileOutsideRoot: '文件位于资产根目录之外,未收录',
98
+ fileUnreadable: '未能读取原文件,无法回看',
99
+ viewChanges: '查看改动', beforeRevision: '原稿', afterRevision: '校订稿', openSourcePage: '打开这一页',
100
+ readPdf: '阅读报告', readWorkbook: '查看完整表格', downloadFile: '下载 {type}',
101
+ pdfPages: '{n} 页', sheetCount: '{n} 张工作表', sheetName: '工作表', emptySheet: '空白工作表',
102
+ pageNumber: '页码', pdfPage: '第 {n} 页', prevPage: '上一页', nextPage: '下一页',
103
+ zoom: '缩放', fitWidth: '适合宽度', loadingSheet: '正在读取表格…', sheetLoadError: '读取失败,可重新打开预览或下载原文件。',
104
+ landscape: '横版',
105
+ portrait: '竖版',
106
+ subagentReportTitle: '子 Agent 报告 · {label}',
66
107
  viewReport: '查看报告',
67
108
  refFrameEyebrow: '📎 参考画面',
68
- aiFrameEyebrow: '🖼 中间过程效果图',
109
+ aiFrameEyebrow: '🖼 过程画面',
69
110
  frameSub: '{time} 产出 · 点击放大查看',
70
111
  docEyebrow: '📄 中间文稿产出 · {file}',
71
112
  docSub: '{time} 写入 · 约 {kb}k 字 · 点击阅读草稿',
72
113
  audioEyebrow: '🔊 过程配音试听({count} 段)',
73
- lightboxDefaultTitle: '效果图预览',
114
+ lightboxDefaultTitle: '画面预览',
74
115
  docModalDefaultTitle: '中间文稿预览',
75
116
  closePreview: '关闭预览',
76
117
  tlAria: '回放时间轴与控制',
@@ -79,10 +120,10 @@ const DICTS = {
79
120
  tlStepMeta: '第 {step} 步 · {time}',
80
121
  tlCompressPin: '压缩 #{seq}',
81
122
  tlCompressTitle: '🗜 上下文压缩 #{seq}(-{dropped}k)',
82
- tlPromptTitle: '💬 提问 #{turn}:{summary}',
123
+ tlPromptTitle: '💬 第 {turn} 轮:{summary}',
83
124
  tlStepFallback: '步骤详情',
84
125
  defaultRefFrame: '参考画面 #{n}',
85
- defaultAiFrame: '过程产出 #{n}',
126
+ defaultAiFrame: '过程画面 #{n}',
86
127
  defaultAudioClip: '试听片段',
87
128
  statSearch: '搜索 {n} 次',
88
129
  statOpen: '打开 {n} 个网页',
@@ -93,13 +134,40 @@ const DICTS = {
93
134
  statCode: '运行 {n} 段代码',
94
135
  statEdit: '写 {n} 个文件',
95
136
  statSkill: '加载 {n} 个技能',
96
- statAgent: '派出 {n} 个子任务',
97
- statReply: '收到 {n} 份子任务结果',
137
+ statAgent: '派出 {n} 个子 Agent',
138
+ statReply: '收到 {n} 份子 Agent 报告',
98
139
  statOther: '其他操作 {n} 次',
99
140
  statSep: ',',
100
141
  execToolsFallback: '执行工具',
101
142
  },
102
143
  en: {
144
+ workspaceWrite: 'Workspace Write',
145
+ contextLabel: 'Context',
146
+ itemCount: '{n} records',
147
+ agentSent: 'Dispatched',
148
+ agentStopped: 'Stopped',
149
+ agentRateLimited: 'Rate limited',
150
+ agentFailed: 'Failed',
151
+ agentDone: 'Returned',
152
+ turnTag: 'Turn #{n}',
153
+ replyTag: 'Reply #{n}',
154
+ stepTag: 'Step {n}',
155
+ thinking: 'Thinking',
156
+ reasoning: 'Reasoning',
157
+ preview: 'Preview',
158
+ draft: 'Draft',
159
+ rule: 'Rule',
160
+ promptTitle: 'Prompt #{n}',
161
+ sessionStart: 'Session start',
162
+ userMessage: 'User message',
163
+ assistantReply: 'Assistant reply',
164
+ appendedPrompt: 'User message appended to context',
165
+ waitingForTools: 'Waiting for agent reasoning and tool calls',
166
+ synthesizing: 'Synthesizing ({tools})',
167
+ directResponse: 'Direct response',
168
+ completedResponse: 'Completed response',
169
+ toolCalls: 'Tool calls × {n}',
170
+ archivedTools: 'Archived {n} tool outputs (-{tokens}k tokens)',
103
171
  langCode: 'en',
104
172
  toggleLangLabel: '中文',
105
173
  toggleLangTitle: '切换到中文',
@@ -120,8 +188,8 @@ const DICTS = {
120
188
  emptyHintStart: 'Click <b>▶ Play</b> at the bottom-left',
121
189
  emptyHintOrSend: ' or the blue <b>↑</b> send button',
122
190
  emptyHintEnd: ' to replay the conversation and live context growth',
123
- activeContext: 'Active Context',
124
- snapInitial: 'Snapshot: Initial Mount',
191
+ activeContext: 'Context Snapshot',
192
+ snapInitial: 'Initial Context',
125
193
  snapInspect: 'Inspecting: Step {step} / {total}',
126
194
  snapCurrent: 'Step {step} / {total}',
127
195
  usedSuffix: 'used',
@@ -131,7 +199,7 @@ const DICTS = {
131
199
  outputReserveTitle: 'Max Output Reserve (8%)',
132
200
  legendSys: 'System Prompt',
133
201
  legendSchema: 'Tool Schemas',
134
- legendUser: 'User Prompts',
202
+ legendUser: 'User Messages',
135
203
  legendMem: 'Memory & Rules',
136
204
  legendSkill: 'Skills',
137
205
  legendMsg: 'Assistant',
@@ -139,13 +207,13 @@ const DICTS = {
139
207
  catSys: 'System Prompt',
140
208
  catSchema: 'Tool Schemas & MCP',
141
209
  catUser: 'User Messages',
142
- catMem: 'Memory & Injected Rules',
210
+ catMem: 'Memory & Rules',
143
211
  catSkill: 'Skills',
144
- catMsg: 'Assistant Messages',
212
+ catMsg: 'Assistant Replies',
145
213
  catTool: 'Tool Outputs',
146
214
  contextInspector: 'Context Inspector',
147
215
  contextInspectorHint: 'Click a bar segment or message to inspect',
148
- emptyCategory: 'No items at this step',
216
+ emptyCategory: 'No records at this step',
149
217
  viewFullPayload: 'View full payload ↗',
150
218
  omittedImages: '({prefix}{count} attached image(s) omitted)',
151
219
  omittedImagesAlso: 'plus ',
@@ -159,10 +227,24 @@ const DICTS = {
159
227
  compactModalTitle: 'Compaction Summary',
160
228
  asksYou: '{tool} asks',
161
229
  deliverablesTitle: 'Deliverables',
230
+ inputFiles: 'Attachments',
231
+ fileVerified: 'Verified against the version in the session',
232
+ fileExportCopy: 'Captured at export. Its version at the time of the session could not be confirmed.',
233
+ fileHashMismatch: 'Captured at export. Its checksum differs from the one recorded in the session.',
234
+ fileMissing: 'Original file not found. No copy is available.',
235
+ fileOutsideRoot: 'Outside the asset roots. No copy was included.',
236
+ fileUnreadable: 'The original file could not be read. No copy is available.',
237
+ viewChanges: 'View changes', beforeRevision: 'Original', afterRevision: 'Revised', openSourcePage: 'Open this page',
238
+ readPdf: 'Read PDF', readWorkbook: 'View workbook', downloadFile: 'Download {type}',
239
+ pdfPages: '{n} pages', sheetCount: '{n} sheets', sheetName: 'Sheet', emptySheet: 'Empty worksheet',
240
+ pageNumber: 'Page', pdfPage: 'Page {n}', prevPage: 'Previous page', nextPage: 'Next page',
241
+ zoom: 'Zoom', fitWidth: 'Fit width', loadingSheet: 'Loading workbook…', sheetLoadError: 'Could not read workbook. Reopen the preview to retry or download the file.',
242
+ landscape: 'Landscape',
243
+ portrait: 'Portrait',
162
244
  subagentReportTitle: 'Sub-agent Report · {label}',
163
245
  viewReport: 'View Report',
164
- refFrameEyebrow: '📎 Reference Image',
165
- aiFrameEyebrow: '🖼 Stage Output',
246
+ refFrameEyebrow: '📎 Reference Frame',
247
+ aiFrameEyebrow: '🖼 Agent Frame',
166
248
  frameSub: 'Produced at {time} · Click to enlarge',
167
249
  docEyebrow: '📄 Draft Document · {file}',
168
250
  docSub: 'Written at {time} · ~{kb}k chars · Click to read',
@@ -176,10 +258,10 @@ const DICTS = {
176
258
  tlStepMeta: 'Step {step} · {time}',
177
259
  tlCompressPin: 'Compact #{seq}',
178
260
  tlCompressTitle: '🗜 Compaction #{seq} (-{dropped}k)',
179
- tlPromptTitle: '💬 Prompt #{turn}: {summary}',
261
+ tlPromptTitle: '💬 Turn #{turn}: {summary}',
180
262
  tlStepFallback: 'Step details',
181
- defaultRefFrame: 'Reference #{n}',
182
- defaultAiFrame: 'Stage Output #{n}',
263
+ defaultRefFrame: 'Reference Frame #{n}',
264
+ defaultAiFrame: 'Agent Frame #{n}',
183
265
  defaultAudioClip: 'Audio clip',
184
266
  statSearch: 'searched {n}x',
185
267
  statOpen: 'opened {n} page(s)',
@@ -286,6 +368,9 @@ function isTableSeparator(line) {
286
368
  return cells.length > 0 && cells.every(c => /^:?-{2,}:?$/.test(c))
287
369
  }
288
370
 
371
+ const openingFence = /^ {0,3}(`{3,})([^`]*)$/
372
+ const closingFence = /^ {0,3}(`{3,})[ \t]*$/
373
+
289
374
  function renderMarkdown(source) {
290
375
  const raw = String(source ?? '').replace(/\r\n/g, '\n').trim()
291
376
  if (!raw) return ''
@@ -302,16 +387,17 @@ function renderMarkdown(source) {
302
387
  continue
303
388
  }
304
389
 
305
- const fence = line.match(/^```([\w-]*)\s*$/)
390
+ const fence = line.match(openingFence)
306
391
  if (fence) {
307
- const lang = fence[1]
392
+ const lang = fence[2].trim().split(/\s+/, 1)[0]
308
393
  const codeLines = []
309
394
  i++
310
- while (i < lines.length && !/^```\s*$/.test(lines[i])) {
311
- codeLines.push(lines[i])
312
- i++
395
+ while (i < lines.length) {
396
+ const codeLine = lines[i++]
397
+ const close = codeLine.match(closingFence)
398
+ if (close && close[1].length >= fence[1].length) break
399
+ codeLines.push(codeLine)
313
400
  }
314
- if (i < lines.length) i++
315
401
  const cls = lang ? ` class="language-${escapeHtml(lang)}"` : ''
316
402
  out.push(`<pre><code${cls}>${escapeHtml(codeLines.join('\n'))}</code></pre>`)
317
403
  continue
@@ -377,11 +463,12 @@ function renderMarkdown(source) {
377
463
  continue
378
464
  }
379
465
 
380
- const paraLines = []
466
+ const paraLines = [renderInline(line)]
467
+ i++
381
468
  while (
382
469
  i < lines.length &&
383
470
  lines[i].trim() !== '' &&
384
- !/^```/.test(lines[i]) &&
471
+ !openingFence.test(lines[i]) &&
385
472
  !/^(#{1,6})\s+/.test(lines[i]) &&
386
473
  !/^(?:-{3,}|\*{3,}|_{3,})\s*$/.test(lines[i].trim()) &&
387
474
  !/^\s*>\s?/.test(lines[i]) &&
@@ -392,9 +479,7 @@ function renderMarkdown(source) {
392
479
  paraLines.push(renderInline(lines[i]))
393
480
  i++
394
481
  }
395
- if (paraLines.length) {
396
- out.push(`<p>${paraLines.join('<br>')}</p>`)
397
- }
482
+ out.push(`<p>${paraLines.join('<br>')}</p>`)
398
483
  }
399
484
 
400
485
  return out.join('\n')
@@ -433,13 +518,21 @@ function resolveWindowCapacity(tool = 'codex', model = '', contextWindow = 0) {
433
518
  return { tokens: 200000, label: '200k' }
434
519
  }
435
520
 
436
- function kindOf(stats = {}) {
521
+ function kindOf(stats = {}, fallbackKind = '') {
522
+ if (fallbackKind && kinds[fallbackKind]) return kinds[fallbackKind]
437
523
  const found = Object.keys(stats).map(key => kinds[key] || 'make')
438
524
  return order.find(kind => found.includes(kind)) || 'make'
439
525
  }
440
526
 
441
527
  function extractSkillNames(item, knownSkills = new Set()) {
442
528
  const names = new Set()
529
+ if (typeof item.skill === 'string' && item.skill.trim()) {
530
+ names.add(item.skill.trim())
531
+ } else if (Array.isArray(item.skill)) {
532
+ for (const entry of item.skill) {
533
+ if (typeof entry === 'string' && entry.trim()) names.add(entry.trim())
534
+ }
535
+ }
443
536
  const text = `${item.text || ''}\n${item.summary || ''}\n${item.input || ''}`
444
537
  const known = new Set([
445
538
  ...knownSkills,
@@ -460,83 +553,112 @@ function extractFileChips(work) {
460
553
  const tools = []
461
554
  const changes = []
462
555
  const memories = []
556
+ const pushTarget = (rawTarget, isEdit) => {
557
+ const target = String(rawTarget || '').trim().split(/[/\\]/).pop()
558
+ if (!target) return
559
+ if (/AGENTS\.md|CLAUDE\.md|memory/i.test(target)) memories.push(target)
560
+ else tools.push(target)
561
+ if (isEdit) changes.push(target)
562
+ }
463
563
  for (const item of work) {
564
+ const isEdit = Boolean(item.kind === 'edit' || item.stats?.edit)
565
+ const explicitFiles = [
566
+ ...(typeof item.file === 'string' && item.file.trim() ? [item.file.trim()] : []),
567
+ ...(Array.isArray(item.files) ? item.files : []),
568
+ ]
464
569
  const summary = String(item.summary || '')
465
570
  const input = String(item.input || '')
466
- for (const match of summary.matchAll(/(?:读取|写入|修改|查看)\s+([^\s,;,]+)/g)) {
467
- const target = match[1].trim()
468
- if (!target) continue
469
- if (/AGENTS\.md|CLAUDE\.md|memory/i.test(target)) memories.push(target)
470
- else tools.push(target)
471
- if (summary.startsWith('写入') || summary.startsWith('修改')) changes.push(target)
472
- }
473
- for (const match of input.matchAll(/\*\*\* (?:Add|Update|Delete) File: ([^\n\\"]+)/g)) {
474
- const name = match[1].trim().split('/').pop()
475
- if (name) {
476
- tools.push(name)
477
- changes.push(name)
571
+ if (explicitFiles.length) {
572
+ for (const f of [...new Set(explicitFiles)]) pushTarget(f, isEdit)
573
+ } else {
574
+ for (const match of summary.matchAll(/(?:读取|写入|修改|查看)\s+([^\s,;,]+)/g)) {
575
+ pushTarget(match[1], summary.startsWith('写入') || summary.startsWith('修改') || isEdit)
576
+ }
577
+ for (const match of input.matchAll(/\*\*\* (?:Add|Update|Delete) File: ([^\n\\"]+)/g)) {
578
+ pushTarget(match[1], true)
579
+ }
580
+ for (const match of input.matchAll(/"(?:file_path|path)"\s*:\s*"([^"]+)"/g)) {
581
+ pushTarget(match[1], isEdit)
478
582
  }
479
583
  }
480
- for (const match of input.matchAll(/"(?:file_path|path)"\s*:\s*"([^"]+)"/g)) {
481
- const name = match[1].trim().split('/').pop()
482
- if (!name) continue
483
- if (/AGENTS\.md|CLAUDE\.md|memory/i.test(name)) memories.push(name)
484
- else tools.push(name)
485
- if (item.stats?.edit) changes.push(name)
486
- }
487
- if (!tools.length && summary) tools.push(summary.slice(0, 28))
584
+ }
585
+ if (!tools.length && work[0]?.summary) {
586
+ tools.push(String(work[0].summary).slice(0, 28))
488
587
  }
489
588
  return { tools, changes, memories }
490
589
  }
491
590
 
591
+ function documentEdits(item) {
592
+ const input = String(item.input || '').trim()
593
+ if (!input) return []
594
+ const isEdit = item.kind === 'edit' || item.stats?.edit
595
+ const summaryFile = String(item.summary || '').match(/^(?:写入|修改|Write|Edit)\s+([^\s、,]+\.md)(?:\s|$)/i)?.[1]
596
+ if (!isEdit && !summaryFile && item.name !== 'apply_patch') return []
597
+ if (!/^\*\*\* Begin Patch\b/.test(input)) {
598
+ const path = isEdit && typeof item.file === 'string' && /\.md$/i.test(item.file.trim())
599
+ ? item.file.trim() : summaryFile
600
+ return path ? [{ path, content: input }] : []
601
+ }
602
+
603
+ const edits = []
604
+ let current
605
+ for (const line of input.split(/\r?\n/)) {
606
+ const header = line.match(/^\*\*\* (Add|Update|Delete) File: (.+)$/)
607
+ if (header) {
608
+ current = undefined
609
+ if (header[1] !== 'Delete') {
610
+ current = { path: header[2].trim(), lines: [] }
611
+ edits.push(current)
612
+ }
613
+ } else if (line === '*** End Patch') {
614
+ break
615
+ } else if (line.startsWith('…(中间省略 ')) {
616
+ // A clipped section may contain a file header. Wait for the next one.
617
+ current = undefined
618
+ } else if (current && line.startsWith('*** Move to: ')) {
619
+ current.path = line.slice('*** Move to: '.length).trim()
620
+ } else if (current && /^[+ ]/.test(line)) {
621
+ current.lines.push(line.slice(1))
622
+ }
623
+ }
624
+ return edits.map(({ path, lines }) => ({ path, content: lines.join('\n').trim() }))
625
+ }
626
+
492
627
  function extractStepDocs(toolItems, stepIndex) {
493
- const byFile = new Map()
628
+ const byPath = new Map()
494
629
  toolItems.forEach((item, idx) => {
495
- if (!item.input) return
496
- const m = String(item.summary || '').match(/^(?:写入|修改|Write|Edit)\s+([^\s、,]+\.md)(?:\s|$)/i)
497
- if (!m) return
498
- const file = m[1]
499
- if (file.startsWith('_') || /^\d{4}-\d{2}-\d{2}\.md$/.test(file)) return
500
- let content = String(item.input).trim()
501
- if (/^\*\*\* Begin Patch\b/.test(content)) {
502
- const bodyLines = content
503
- .split('\n')
504
- .filter(line => !/^(\*\*\* (?:Begin Patch|End Patch|Add File:|Update File:|Delete File:|Move to:)|@@)/.test(line) && !line.startsWith('-'))
505
- .map(line => (line.startsWith('+') || line.startsWith(' ')) ? line.slice(1) : line)
506
- content = bodyLines.join('\n').trim()
507
- }
508
- let bodyWithoutFm = content
509
- let fmTitle = ''
510
- const fmMatch = content.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/)
511
- if (fmMatch) {
512
- fmTitle = fmMatch[1].match(/^\s*title\s*:\s*['"]?([^\r\n'"]+)['"]?\s*$/m)?.[1]?.trim() || ''
513
- bodyWithoutFm = fmMatch[2].trim()
514
- }
515
- const headingMatch = bodyWithoutFm.match(/^#{1,3}\s+([^\r\n]+)/m)
516
- if (!headingMatch && !fmTitle) return
517
- const title = (headingMatch ? headingMatch[1].replace(/^#+\s*/, '').trim() : fmTitle) || file
518
- byFile.set(file, {
519
- id: `doc-${stepIndex}-${idx}`,
520
- file,
521
- title,
522
- chars: content.length,
523
- content: bodyWithoutFm || content,
524
- t: item.t || 0,
525
- })
630
+ for (const [part, { path, content }] of documentEdits(item).entries()) {
631
+ const file = path.split(/[/\\]/).pop()
632
+ if (!/\.md$/i.test(file) || file.startsWith('_') || /^\d{4}-\d{2}-\d{2}\.md$/.test(file)) continue
633
+ const fm = content.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/)
634
+ const body = fm ? fm[2].trim() : content
635
+ const heading = body.match(/^#{1,3}\s+([^\r\n]+)/m)?.[1]?.replace(/^#+\s*/, '').trim()
636
+ const title = heading || fm?.[1].match(/^\s*title\s*:\s*['"]?([^\r\n'"]+)['"]?\s*$/m)?.[1]?.trim()
637
+ if (!title) continue
638
+ byPath.set(path, {
639
+ id: part ? `doc-${stepIndex}-${idx}-${part}` : `doc-${stepIndex}-${idx}`,
640
+ file,
641
+ title,
642
+ chars: content.length,
643
+ content: body || content,
644
+ t: item.t || 0,
645
+ })
646
+ }
526
647
  })
527
- return [...byFile.values()]
648
+ return [...byPath.values()]
528
649
  }
529
650
 
530
- function extractStepSubagents(toolItems, stepIndex) {
651
+ function extractStepSubagents(toolItems, stepIndex, t) {
531
652
  const list = []
532
653
  toolItems.forEach((item, idx) => {
533
654
  const rawSum = String(item.summary || '')
534
655
  const isSub = Boolean(
656
+ item.kind === 'agent' ||
535
657
  item.stats?.agent ||
536
658
  item.agent ||
537
659
  item.name === 'agent_message' ||
538
660
  item.name === 'agent-message' ||
539
- (item.stats?.reply && /Agent\s+"|^子任务/.test(rawSum) && !/Background command/i.test(rawSum))
661
+ ((item.kind === 'reply' || item.stats?.reply) && /Agent\s+"|^子任务/.test(rawSum) && !/Background command/i.test(rawSum))
540
662
  )
541
663
  if (!isSub) return
542
664
  const label = (
@@ -547,21 +669,22 @@ function extractStepSubagents(toolItems, stepIndex) {
547
669
  .replace(/\s+交回结果$/, '')
548
670
  .trim()
549
671
  )
550
- if (!label || /^给子任务发消息/.test(rawSum)) return
672
+ const isSendMsg = /^(?:send_message|collaboration__send_message)$/.test(item.name || '')
673
+ if (!label || isSendMsg || /^给子任务发消息/.test(rawSum)) return
551
674
  const combined = `${rawSum}\n${item.output || ''}`
552
675
  const isAsyncSpawn = /^(?:spawn_agent|collaboration__spawn_agent|followup_task|collaboration__followup_task)$/.test(item.name || '')
553
676
  let state = 'sent'
554
- let badge = '派出'
677
+ let badge = t('agentSent')
555
678
  let report = ''
556
679
  if (/was stopped|中途打断|已取消/i.test(combined)) {
557
680
  state = 'stopped'
558
- badge = '已叫停'
681
+ badge = t('agentStopped')
559
682
  } else if (/failed:|terminated early|rate_limit|hit your session limit|^Error:\s*Failed/im.test(combined)) {
560
683
  state = 'failed'
561
- badge = /limit|429/i.test(combined) ? '额度中断' : '失败'
562
- } else if (item.stats?.reply || (!isAsyncSpawn && item.output && item.output.length > 80 && !item.output.trim().startsWith('{'))) {
684
+ badge = /limit|429/i.test(combined) ? t('agentRateLimited') : t('agentFailed')
685
+ } else if (item.kind === 'reply' || item.stats?.reply || (!isAsyncSpawn && item.output && item.output.length > 80 && !item.output.trim().startsWith('{'))) {
563
686
  state = 'done'
564
- badge = '已交回'
687
+ badge = t('agentDone')
565
688
  if (item.output && item.output.length > 40 && !item.output.trim().startsWith('{')) {
566
689
  report = String(item.output).trim()
567
690
  }
@@ -614,6 +737,28 @@ function defaultSystemPrompts(toolName) {
614
737
  },
615
738
  ]
616
739
  }
740
+ if (toolName === 'workbuddy') {
741
+ return [
742
+ {
743
+ id: 'sys-core',
744
+ stepIndex: -1,
745
+ tokEst: 3200,
746
+ tag: 'Core',
747
+ title: 'WorkBuddy Desktop Agent · Core Role & Execution Rules',
748
+ meta: '≈3.2k · Initial',
749
+ payload: `You are WorkBuddy, a desktop agent bound to the active local workspace directory.\n\n# Core Responsibilities\n1. Search and read workspace documents, spreadsheets, PDFs, and images on demand; ground answers in primary sources.\n2. Decompose complex research into parallel sub-tasks and synthesize verified deliverables.\n3. Confirm with the user before overwriting formal documents or sending external messages.`,
750
+ },
751
+ {
752
+ id: 'sys-workspace',
753
+ stepIndex: -1,
754
+ tokEst: 1800,
755
+ tag: 'Workspace',
756
+ title: 'Workspace File I/O & Deliverable Conventions',
757
+ meta: '≈1.8k · Initial',
758
+ payload: `# Workspace Conventions\n- Inspect directory structure and project notes before modifying files.\n- Save intermediate drafts, tables, and final reports under the designated workspace path.`,
759
+ },
760
+ ]
761
+ }
617
762
  return [
618
763
  {
619
764
  id: 'sys-core',
@@ -645,6 +790,14 @@ function defaultToolSchemas(toolName) {
645
790
  { id: 'schema-agent-skill', stepIndex: -1, tokEst: 2000, tag: 'Schema', title: 'Agent / Skill / TodoWrite · Delegation & Skills', meta: '≈2.0k · Schema', payload: '{\n "tools": ["Agent", "Skill", "TodoWrite"]\n}' },
646
791
  ]
647
792
  }
793
+ if (toolName === 'workbuddy') {
794
+ return [
795
+ { id: 'schema-wb-read', stepIndex: -1, tokEst: 1800, tag: 'Schema', title: 'read_file / list_dir · Workspace Document Reader', meta: '≈1.8k · Schema', payload: '{\n "tools": ["read_file", "list_dir"]\n}' },
796
+ { id: 'schema-wb-write', stepIndex: -1, tokEst: 1900, tag: 'Schema', title: 'write_file / edit_file · Deliverable & Note Writer', meta: '≈1.9k · Schema', payload: '{\n "tools": ["write_file", "edit_file"]\n}' },
797
+ { id: 'schema-wb-web', stepIndex: -1, tokEst: 2000, tag: 'Schema', title: 'web_search / run_command · Web Research & Scripts', meta: '≈2.0k · Schema', payload: '{\n "tools": ["web_search", "run_command"]\n}' },
798
+ { id: 'schema-wb-agent', stepIndex: -1, tokEst: 2100, tag: 'Schema', title: 'Agent · Parallel Research Sub-tasks', meta: '≈2.1k · Schema', payload: '{\n "tools": ["Agent"]\n}' },
799
+ ]
800
+ }
648
801
  return [
649
802
  { id: 'schema-exec', stepIndex: -1, tokEst: 2200, tag: 'Schema', title: 'exec_command / write_stdin · Shell Execution', meta: '≈2.2k · Schema', payload: '{\n "name": "exec_command",\n "parameters": { "cmd": "string", "workdir": "string" }\n}' },
650
803
  { id: 'schema-patch', stepIndex: -1, tokEst: 2100, tag: 'Schema', title: 'apply_patch · Freeform File Patching', meta: '≈2.1k · Schema', payload: '{\n "name": "apply_patch",\n "grammar": "*** Begin Patch ... *** End Patch"\n}' },
@@ -795,7 +948,9 @@ function buildSteps(items, end, sessionTool = 'codex', sessionModel = '', frames
795
948
  }
796
949
  for (const item of items) {
797
950
  if (item.type === 'tool' || item.type === 'reasoning') {
951
+ if (item.deliverables?.length) flushWork()
798
952
  work.push(item)
953
+ if (item.deliverables?.length) flushWork()
799
954
  continue
800
955
  }
801
956
  flushWork()
@@ -905,7 +1060,7 @@ function buildSteps(items, end, sessionTool = 'codex', sessionModel = '', frames
905
1060
  name,
906
1061
  color,
907
1062
  itemCount: records.length,
908
- count: `${records.length} Items`,
1063
+ count: t('itemCount', { n: records.length }),
909
1064
  tok: `≈${(curTok / 1000).toFixed(1)}k`,
910
1065
  pct: `${kindPct(curTok)}%`,
911
1066
  delta: stepIdx >= 0 ? fmtCountDelta(records.length, prevCount) : '',
@@ -1015,8 +1170,8 @@ function buildSteps(items, end, sessionTool = 'codex', sessionModel = '', frames
1015
1170
  id: `user-${userSeq}`,
1016
1171
  stepIndex: index,
1017
1172
  tokEst: userTok,
1018
- tag: `Turn #${turnCount}`,
1019
- title: cleanPromptText.slice(0, 56) || 'User message',
1173
+ tag: t('turnTag', { n: turnCount }),
1174
+ title: cleanPromptText.slice(0, 56) || t('userMessage'),
1020
1175
  meta: `≈${(userTok / 1000).toFixed(1)}k · ${stepTime}s`,
1021
1176
  payload: String(first.text || ''),
1022
1177
  ...(first.images?.length ? { images: first.images } : {}),
@@ -1033,7 +1188,7 @@ function buildSteps(items, end, sessionTool = 'codex', sessionModel = '', frames
1033
1188
  tokEst: skTok,
1034
1189
  tag: 'SKILL.md',
1035
1190
  title: `${skill}/SKILL.md`,
1036
- meta: `≈${(skTok / 1000).toFixed(1)}k · Turn #${turnCount}`,
1191
+ meta: `≈${(skTok / 1000).toFixed(1)}k · ${t('turnTag', { n: turnCount })}`,
1037
1192
  payload: `# ${skill} (SKILL.md)\nLoaded into active context.`,
1038
1193
  }))
1039
1194
  }
@@ -1042,10 +1197,10 @@ function buildSteps(items, end, sessionTool = 'codex', sessionModel = '', frames
1042
1197
  primaryCat = 'user'
1043
1198
  speedLabel = '1.0×'
1044
1199
  dwellMs = 1500
1045
- detailTitle = `Prompt #${turnCount}`
1200
+ detailTitle = t('promptTitle', { n: turnCount })
1046
1201
  detailSnippet = (first.text || '').slice(0, 260)
1047
- inBrief = 'User message appended to context'
1048
- responseBrief = 'Waiting for Agent reasoning & tool calls'
1202
+ inBrief = t('appendedPrompt')
1203
+ responseBrief = t('waitingForTools')
1049
1204
  } else if (group.groupType === 'compact') {
1050
1205
  compactSeq++
1051
1206
  const cItem = first
@@ -1098,10 +1253,10 @@ function buildSteps(items, end, sessionTool = 'codex', sessionModel = '', frames
1098
1253
  speedLabel = '0.8×'
1099
1254
  dwellMs = 2100
1100
1255
  spotlight = 'context-compact'
1101
- detailTitle = `Context Compaction #${compactInfo.seq}`
1256
+ detailTitle = t('compactTitle', { seq: compactInfo.seq })
1102
1257
  detailSnippet = summaryText.slice(0, 260)
1103
1258
  inBrief = `${(preTokens / 1000).toFixed(1)}k → ${(postTokens / 1000).toFixed(1)}k`
1104
- responseBrief = `Archived ${archivedTools} tool outputs (-${(droppedTokens / 1000).toFixed(1)}k tokens)`
1259
+ responseBrief = t('archivedTools', { n: archivedTools, tokens: (droppedTokens / 1000).toFixed(1) })
1105
1260
  } else if (group.groupType === 'assistant') {
1106
1261
  msgSeq++
1107
1262
  const cleanReply = (first.text || '').replace(/\s+/g, ' ').trim()
@@ -1112,8 +1267,8 @@ function buildSteps(items, end, sessionTool = 'codex', sessionModel = '', frames
1112
1267
  id: `msg-${msgSeq}`,
1113
1268
  stepIndex: index,
1114
1269
  tokEst: msgTok,
1115
- tag: `Reply #${msgSeq}`,
1116
- title: cleanReply.slice(0, 56) || 'Assistant reply',
1270
+ tag: t('replyTag', { n: msgSeq }),
1271
+ title: cleanReply.slice(0, 56) || t('assistantReply'),
1117
1272
  meta: `≈${(msgTok / 1000).toFixed(1)}k · ${stepTime}s`,
1118
1273
  payload: String(first.text || ''),
1119
1274
  }))
@@ -1127,17 +1282,17 @@ function buildSteps(items, end, sessionTool = 'codex', sessionModel = '', frames
1127
1282
  primaryCat = 'msg'
1128
1283
  speedLabel = '1.0×'
1129
1284
  dwellMs = 1750
1130
- detailTitle = 'Assistant Response'
1285
+ detailTitle = t('assistantReply')
1131
1286
  detailSnippet = (first.text || '').slice(0, 260)
1132
- inBrief = allTools.length ? `Synthesizing (${allTools.slice(-2).join(', ')})` : 'Direct response'
1133
- responseBrief = cleanReply.slice(0, 96) || 'Completed response'
1287
+ inBrief = allTools.length ? t('synthesizing', { tools: allTools.slice(-2).join(', ') }) : t('directResponse')
1288
+ responseBrief = cleanReply.slice(0, 96) || t('completedResponse')
1134
1289
  } else {
1135
1290
  const toolItems = group.items.filter(item => item.type === 'tool')
1136
1291
  const reasoningItems = group.items.filter(item => item.type === 'reasoning')
1137
1292
  const stats = sumStats(toolItems)
1138
1293
  const extracted = extractFileChips(toolItems)
1139
1294
  stepDocs = extractStepDocs(toolItems, index)
1140
- stepSubagents = extractStepSubagents(toolItems, index)
1295
+ stepSubagents = extractStepSubagents(toolItems, index, t)
1141
1296
  stepAudios = extractStepAudios(toolItems, t)
1142
1297
  allTools.push(...extracted.tools)
1143
1298
  allChanges.push(...extracted.changes)
@@ -1152,9 +1307,9 @@ function buildSteps(items, end, sessionTool = 'codex', sessionModel = '', frames
1152
1307
  id: `mem-dyn-${memRecords.length + 1}`,
1153
1308
  stepIndex: index,
1154
1309
  tokEst: memTok,
1155
- tag: 'Rule',
1310
+ tag: t('rule'),
1156
1311
  title: `${memName}`,
1157
- meta: `≈${(memTok / 1000).toFixed(1)}k · Step ${index + 1}`,
1312
+ meta: `≈${(memTok / 1000).toFixed(1)}k · ${t('stepTag', { n: index + 1 })}`,
1158
1313
  payload: `# ${memName}\nLoaded into context during step ${index + 1}.`,
1159
1314
  }))
1160
1315
  }
@@ -1170,9 +1325,9 @@ function buildSteps(items, end, sessionTool = 'codex', sessionModel = '', frames
1170
1325
  id: `think-${msgSeq}`,
1171
1326
  stepIndex: index,
1172
1327
  tokEst: rTok,
1173
- tag: 'Thinking',
1328
+ tag: t('thinking'),
1174
1329
  title: rItem.text.replace(/\s+/g, ' ').trim().slice(0, 54),
1175
- meta: `≈${(rTok / 1000).toFixed(1)}k · Reasoning`,
1330
+ meta: `≈${(rTok / 1000).toFixed(1)}k · ${t('reasoning')}`,
1176
1331
  payload: String(rItem.text),
1177
1332
  }))
1178
1333
  }
@@ -1198,7 +1353,7 @@ function buildSteps(items, end, sessionTool = 'codex', sessionModel = '', frames
1198
1353
  tokEst: skTok,
1199
1354
  tag: 'SKILL.md',
1200
1355
  title: `${skill}/SKILL.md`,
1201
- meta: `≈${(skTok / 1000).toFixed(1)}k · Step ${index + 1}`,
1356
+ meta: `≈${(skTok / 1000).toFixed(1)}k · ${t('stepTag', { n: index + 1 })}`,
1202
1357
  payload: String(item.output || item.input || `# ${skill} (SKILL.md)`),
1203
1358
  }))
1204
1359
  }
@@ -1223,7 +1378,7 @@ function buildSteps(items, end, sessionTool = 'codex', sessionModel = '', frames
1223
1378
  payload: parts.join('\n\n'),
1224
1379
  ...(item.images?.length ? { images: item.images } : {}),
1225
1380
  }))
1226
- const isSpot = Boolean(item.stats?.edit || item.stats?.skill)
1381
+ const isSpot = Boolean(item.kind === 'edit' || item.kind === 'skill' || item.stats?.edit || item.stats?.skill)
1227
1382
  rawMontage.push({
1228
1383
  tag: toolTag,
1229
1384
  title: cleanSum.slice(0, 56),
@@ -1238,7 +1393,7 @@ function buildSteps(items, end, sessionTool = 'codex', sessionModel = '', frames
1238
1393
  toolRecords.push(registerRecord({
1239
1394
  id: `frame-${++toolSeq}`,
1240
1395
  stepIndex: index,
1241
- tag: 'Preview',
1396
+ tag: t('preview'),
1242
1397
  title: `${fr.label}`,
1243
1398
  meta: '≈1.2k tok',
1244
1399
  payload: `Preview frame: ${fr.label}`,
@@ -1246,7 +1401,7 @@ function buildSteps(items, end, sessionTool = 'codex', sessionModel = '', frames
1246
1401
  }))
1247
1402
  }
1248
1403
  rawMontage.push({
1249
- tag: 'Preview',
1404
+ tag: t('preview'),
1250
1405
  title: `${fr.label}`,
1251
1406
  isSpot: true,
1252
1407
  speed: '🖼',
@@ -1254,7 +1409,7 @@ function buildSteps(items, end, sessionTool = 'codex', sessionModel = '', frames
1254
1409
  }
1255
1410
  for (const doc of stepDocs) {
1256
1411
  rawMontage.push({
1257
- tag: 'Draft',
1412
+ tag: t('draft'),
1258
1413
  title: `${doc.title}`,
1259
1414
  isSpot: true,
1260
1415
  speed: '📄',
@@ -1301,7 +1456,7 @@ function buildSteps(items, end, sessionTool = 'codex', sessionModel = '', frames
1301
1456
  dwellMs = 1100
1302
1457
  }
1303
1458
  if (toolItems.length) {
1304
- detailTitle = `Tool Call × ${toolItems.length}`
1459
+ detailTitle = t('toolCalls', { n: toolItems.length })
1305
1460
  detailSnippet = toolItems.slice(0, 3).map(item => item.summary).join('\n')
1306
1461
  const primaryTool = toolItems[0]?.name || 'tool'
1307
1462
  inBrief = `${primaryTool} · ${toolItems.slice(0, 2).map(i => i.summary).join(';')}`
@@ -1392,7 +1547,7 @@ function buildSteps(items, end, sessionTool = 'codex', sessionModel = '', frames
1392
1547
  snippet: detailSnippet,
1393
1548
  },
1394
1549
  brief: {
1395
- user: latestUserPrompt || 'Session Start',
1550
+ user: latestUserPrompt || t('sessionStart'),
1396
1551
  in: inBrief,
1397
1552
  response: responseBrief,
1398
1553
  },
@@ -1416,10 +1571,10 @@ function timeline(session, { lang = 'zh' } = {}) {
1416
1571
  ...item,
1417
1572
  t: at(item.time),
1418
1573
  ...(item.done ? { d: Math.min(end, at(item.done)) } : {}),
1419
- ...(item.type === 'tool' ? { k: kindOf(item.stats) } : {}),
1574
+ ...(item.type === 'tool' ? { k: kindOf(item.stats, item.kind) } : {}),
1420
1575
  }))
1421
1576
  const lanes = items
1422
- .filter(item => item.type === 'tool' && item.agent && item.d !== undefined && (item.stats?.agent || item.name === 'followup_task'))
1577
+ .filter(item => item.type === 'tool' && item.agent && item.d !== undefined && (item.kind === 'agent' || item.stats?.agent || item.name === 'followup_task'))
1423
1578
  .map(item => ({ agent: item.agent, s: item.t, e: Math.max(item.t, item.d) }))
1424
1579
  const waits = []
1425
1580
  items.forEach((item, index) => {
@@ -1463,8 +1618,12 @@ function timeline(session, { lang = 'zh' } = {}) {
1463
1618
  function sumStats(items) {
1464
1619
  const totals = {}
1465
1620
  for (const item of items || []) {
1466
- for (const [key, value] of Object.entries(item.stats || {})) {
1467
- totals[key] = (totals[key] || 0) + value
1621
+ if (item.stats && Object.keys(item.stats).length) {
1622
+ for (const [key, value] of Object.entries(item.stats)) {
1623
+ totals[key] = (totals[key] || 0) + value
1624
+ }
1625
+ } else if (item.kind) {
1626
+ totals[item.kind] = (totals[item.kind] || 0) + 1
1468
1627
  }
1469
1628
  }
1470
1629
  return totals
@@ -1495,13 +1654,184 @@ function describeStats(stats, keys = statKeyMap.map(([key]) => key), lang = 'zh'
1495
1654
  .join(t('statSep'))
1496
1655
  }
1497
1656
 
1657
+ // --- attachment-reader.mjs ---
1658
+ function attachmentTable(rows, { compact = false } = {}) {
1659
+ if (!rows.length) return ''
1660
+ const head = rows[0].map(cell => `<th scope="col">${escapeHtml(cell)}</th>`).join('')
1661
+ const body = rows.slice(1).map(row => {
1662
+ const cells = row.map(value => {
1663
+ const text = String(value ?? '')
1664
+ const content = !compact && text.length > 70
1665
+ ? `<details><summary>${escapeHtml(text.slice(0, 52))}…</summary>${escapeHtml(text)}</details>`
1666
+ : escapeHtml(text)
1667
+ return `<td>${content}</td>`
1668
+ })
1669
+ return `<tr>${cells.join('')}</tr>`
1670
+ })
1671
+ return `<table><thead><tr>${head}</tr></thead><tbody>${body.join('')}</tbody></table>`
1672
+ }
1673
+
1674
+ function renderRevision(file, t, url) {
1675
+ const change = file.preview.change
1676
+ if (!change || !file.revision) return ''
1677
+ const revision = file.revision
1678
+ const pdf = file.preview.type === 'pdf'
1679
+ const location = pdf ? t('pdfPage', { n: revision.page }) : `${revision.sheet} · ${revision.cell}`
1680
+ const before = Array.from(change.before), after = Array.from(change.after)
1681
+ const shorter = Math.min(before.length, after.length)
1682
+ let start = 0, end = 0
1683
+ while (start < shorter && before[start] === after[start]) start++
1684
+ while (end < shorter - start && before.at(-1 - end) === after.at(-1 - end)) end++
1685
+ function side(chars, original) {
1686
+ const stop = chars.length - end
1687
+ const tag = original ? 'del' : 'ins'
1688
+ const text = escapeHtml(chars.slice(0, start).join(''))
1689
+ + `<${tag}>${escapeHtml(chars.slice(start, stop).join(''))}</${tag}>`
1690
+ + escapeHtml(chars.slice(stop).join(''))
1691
+ const src = url(original ? revision.href : file.href)
1692
+ const link = pdf
1693
+ ? `<a href="${escapeHtml(src)}#page=${Number(revision.page)}" target="_blank" rel="noopener noreferrer">${t('openSourcePage')}</a>`
1694
+ : `<a href="${escapeHtml(src)}" download>${t('downloadFile', { type: 'Excel' })}</a>`
1695
+ return `<section><strong>${t(original ? 'beforeRevision' : 'afterRevision')}</strong><p>${text}</p>${link}</section>`
1696
+ }
1697
+ return `<details class="session-revision"><summary>${t('viewChanges')}</summary>
1698
+ <div class="session-revision-context"><b>${escapeHtml(revision.label)}</b><span>${escapeHtml(location)}</span></div>
1699
+ <div class="session-revision-pair">${side(before, true)}${side(after, false)}</div></details>`
1700
+ }
1701
+
1702
+ function renderAttachment(file, t, url) {
1703
+ const preview = file.preview
1704
+ const pdf = preview.type === 'pdf'
1705
+ const type = pdf ? 'PDF' : 'Excel'
1706
+ const action = t(pdf ? 'readPdf' : 'readWorkbook')
1707
+ const count = pdf ? t('pdfPages', { n: preview.pages.length }) : t('sheetCount', { n: preview.count })
1708
+ const download = `<a href="${escapeHtml(url(file.href))}" download${file.availability ? `="${escapeHtml(file.title)}"` : ''}>${t('downloadFile', { type })}</a>`
1709
+ const title = escapeHtml(file.title)
1710
+ const toolbar = pdf
1711
+ ? `<button type="button" data-page-prev aria-label="${t('prevPage')}">‹</button>
1712
+ <label>${t('pageNumber')} <input data-page-number type="number" min="1" max="${preview.pages.length}" value="1"> / ${preview.pages.length}</label>
1713
+ <button type="button" data-page-next aria-label="${t('nextPage')}">›</button>
1714
+ <select data-page-zoom aria-label="${t('zoom')}"><option value="100">${t('fitWidth')}</option><option value="125">125%</option><option value="150">150%</option></select>`
1715
+ : `<label>${t('sheetName')} <select data-sheet-picker></select></label>`
1716
+ const content = pdf
1717
+ ? `<template>${preview.pages.map((page, i) => `<img loading="lazy" src="${escapeHtml(url(page.src))}" width="${Number(page.width)}" height="${Number(page.height)}" alt="${escapeHtml(t('pdfPage', { n: i + 1 }))}">`).join('')}</template>`
1718
+ : ''
1719
+ const source = pdf ? '' : ` data-workbook-src="${escapeHtml(url(preview.src))}" data-first-sheet="${escapeHtml(preview.sheet)}"`
1720
+ const summary = pdf
1721
+ ? `<img class="session-pdf-cover" src="${escapeHtml(url(file.cover || preview.pages[0].src))}" alt="" loading="lazy">`
1722
+ : ''
1723
+ return `<section class="session-attachment" data-attachment="${preview.type}"${source}>
1724
+ <div class="session-attachment-head">${summary}<div><strong>${title}</strong>
1725
+ <small>${type} · ${count}${file.meta ? ' · ' + escapeHtml(file.meta) : ''}</small></div></div>
1726
+ ${pdf ? '' : `<div class="session-sheet-sample">${attachmentTable(preview.rows, { compact: true })}</div>`}
1727
+ <div class="session-attachment-actions"><button type="button" data-open-attachment>${action}</button>${download}</div>
1728
+ ${renderRevision(file, t, url)}
1729
+ <dialog class="session-attachment-dialog" aria-label="${title}">
1730
+ <header><strong>${title}</strong>${download}<button type="button" data-close-attachment aria-label="${t('closePreview')}">✕</button></header>
1731
+ <div class="session-attachment-toolbar">${toolbar}</div>
1732
+ <div class="session-attachment-viewport" role="region" aria-label="${title}" tabindex="0"></div>
1733
+ </dialog>${content}
1734
+ </section>`
1735
+ }
1736
+
1737
+ function attachPdfReader(card, viewport) {
1738
+ viewport.append(card.querySelector('template').content.cloneNode(true))
1739
+ const pages = [...viewport.querySelectorAll('img')]
1740
+ const number = card.querySelector('[data-page-number]')
1741
+ const previous = card.querySelector('[data-page-prev]')
1742
+ const next = card.querySelector('[data-page-next]')
1743
+ function setPage(n) {
1744
+ number.value = n
1745
+ previous.disabled = n === 1
1746
+ next.disabled = n === pages.length
1747
+ }
1748
+ function jump(n) {
1749
+ n = Math.max(1, Math.min(pages.length, Math.round(n) || 1))
1750
+ pages[n - 1].scrollIntoView({ block: 'start', inline: 'nearest' })
1751
+ setPage(n)
1752
+ }
1753
+ number.addEventListener('change', () => jump(number.valueAsNumber))
1754
+ number.addEventListener('keydown', event => {
1755
+ if (event.key === 'Enter') jump(number.valueAsNumber)
1756
+ })
1757
+ previous.addEventListener('click', () => jump(number.valueAsNumber - 1))
1758
+ next.addEventListener('click', () => jump(number.valueAsNumber + 1))
1759
+ card.querySelector('[data-page-zoom]').addEventListener('change', event => {
1760
+ viewport.style.setProperty('--attachment-page-width', event.target.value + '%')
1761
+ jump(number.valueAsNumber)
1762
+ })
1763
+ viewport.addEventListener('scroll', () => {
1764
+ if (document.activeElement === number) return
1765
+ const top = viewport.getBoundingClientRect().top + 32
1766
+ const i = pages.findIndex(page => page.getBoundingClientRect().bottom > top)
1767
+ setPage(i < 0 ? pages.length : i + 1)
1768
+ }, { passive: true })
1769
+ setPage(1)
1770
+ }
1771
+
1772
+ async function attachWorkbookReader(card, viewport, t) {
1773
+ const response = await fetch(card.dataset.workbookSrc)
1774
+ if (!response.ok) throw new Error('HTTP ' + response.status)
1775
+ const sheets = await response.json()
1776
+ const picker = card.querySelector('[data-sheet-picker]')
1777
+ for (const sheet of sheets) picker.add(new Option(sheet.sheet, sheet.sheet))
1778
+ picker.value = card.dataset.firstSheet
1779
+ function selectSheet() {
1780
+ viewport.innerHTML = attachmentTable(sheets[picker.selectedIndex].data) || escapeHtml(t('emptySheet'))
1781
+ viewport.scrollTo(0, 0)
1782
+ }
1783
+ picker.addEventListener('change', selectSheet)
1784
+ selectSheet()
1785
+ }
1786
+
1787
+ function attachAttachmentReaders(container, t, pauseReplay) {
1788
+ for (const card of container.querySelectorAll('[data-attachment]')) {
1789
+ const revision = card.querySelector('.session-revision')
1790
+ revision?.addEventListener('toggle', () => {
1791
+ if (revision.open) {
1792
+ pauseReplay()
1793
+ revision.scrollIntoView({ block: 'nearest' })
1794
+ }
1795
+ })
1796
+ const dialog = card.querySelector('dialog')
1797
+ const viewport = card.querySelector('.session-attachment-viewport')
1798
+ let initialized = false
1799
+ card.querySelector('[data-open-attachment]').addEventListener('click', async () => {
1800
+ pauseReplay()
1801
+ dialog.showModal()
1802
+ if (initialized) return
1803
+ initialized = true
1804
+ if (card.dataset.attachment === 'pdf') {
1805
+ attachPdfReader(card, viewport)
1806
+ } else {
1807
+ viewport.textContent = t('loadingSheet')
1808
+ try {
1809
+ await attachWorkbookReader(card, viewport, t)
1810
+ } catch {
1811
+ viewport.textContent = t('sheetLoadError')
1812
+ initialized = false
1813
+ }
1814
+ }
1815
+ })
1816
+ card.querySelector('[data-close-attachment]').addEventListener('click', () => dialog.close())
1817
+ dialog.addEventListener('click', event => {
1818
+ if (event.target === dialog) {
1819
+ const box = dialog.getBoundingClientRect()
1820
+ if (event.clientX < box.left || event.clientX > box.right || event.clientY < box.top || event.clientY > box.bottom) dialog.close()
1821
+ }
1822
+ })
1823
+ }
1824
+ }
1825
+
1498
1826
  // --- render.mjs ---
1499
1827
  const escape = escapeHtml
1500
1828
 
1501
1829
 
1502
1830
 
1831
+
1503
1832
  const toolLabels = {
1504
1833
  codex: 'Codex',
1834
+ workbuddy: 'WorkBuddy',
1505
1835
  'claude-code': 'Claude Code',
1506
1836
  'claude-ai': 'Claude',
1507
1837
  }
@@ -1823,12 +2153,51 @@ function contextSidebar(line, t) {
1823
2153
  </aside>`
1824
2154
  }
1825
2155
 
2156
+ function renderDeliverable(file, t, baseUrl) {
2157
+ if (!file.availability) return renderFileContents(file, t, baseUrl)
2158
+ if (file.availability === 'missing') {
2159
+ const notice = { 'outside-root': 'fileOutsideRoot', unreadable: 'fileUnreadable' }[file.unavailableReason] || 'fileMissing'
2160
+ return `<section class="session-file-missing" data-availability="missing"><strong>${escape(file.title)}</strong><small>${escape(t(notice))}</small></section>`
2161
+ }
2162
+ const notice = t(file.availability === 'verified' ? 'fileVerified' : file.sessionSha256 ? 'fileHashMismatch' : 'fileExportCopy')
2163
+ return `<div class="session-file-copy" data-availability="${escape(file.availability)}"><small>${escape(notice)}</small>${renderFileContents(file, t, baseUrl)}</div>`
2164
+ }
2165
+
2166
+ function renderFileContents(file, t, baseUrl) {
2167
+ if (file.preview?.type === 'xlsx' || file.preview?.pages?.length && file.preview.type === 'pdf') {
2168
+ return renderAttachment(file, t, src => resolveAsset(src, baseUrl))
2169
+ }
2170
+ const href = escape(resolveAsset(file.href, baseUrl))
2171
+ const cover = escape(resolveAsset(file.cover, baseUrl))
2172
+ const title = escape(file.title)
2173
+ const caption = `<b>${title}</b>${file.meta ? `<small>${escape(file.meta)}</small>` : ''}`
2174
+ if (!validVideo.test(file.href)) {
2175
+ if (file.availability) return `<a class="session-file-download" href="${href}" download="${title}">${caption}</a>`
2176
+ return `<a class="session-file" href="${href}" target="_blank" rel="noopener noreferrer">${cover ? `<img src="${cover}" alt="" width="56" height="79" loading="lazy">` : ''}<span>${caption}</span></a>`
2177
+ }
2178
+ const formats = file.portrait?.href ? `<div class="session-video-formats">
2179
+ <button type="button" data-video-format="landscape" data-src="${href}" data-cover="${cover}" aria-pressed="true">${t('landscape')}</button>
2180
+ <button type="button" data-video-format="portrait" data-src="${escape(resolveAsset(file.portrait.href, baseUrl))}" data-cover="${escape(resolveAsset(file.portrait.cover, baseUrl))}" aria-pressed="false">${t('portrait')}</button>
2181
+ </div>` : ''
2182
+ return `<figure class="session-video">
2183
+ <figcaption><span>${caption}</span>${formats}</figcaption>
2184
+ <video controls playsinline loading="lazy" preload="none" width="960" height="540" aria-label="${title}" src="${href}"${cover ? ` poster="${cover}"` : ''}></video>
2185
+ </figure>`
2186
+ }
2187
+
1826
2188
  function renderLog(session, line, { t, baseUrl = '' }) {
1827
2189
  const tool = toolLabels[session.tool] || session.tool || 'Agent'
1828
2190
  const render = text => renderMarkdown(localLinks(text))
1829
2191
  const entries = []
1830
2192
  let shown = -Infinity
1831
2193
  let stepIndex = 0
2194
+ let delivery = 0
2195
+
2196
+ function addFiles(files, step, time, atEnd = false, label = 'deliverablesTitle') {
2197
+ if (!files?.length) return
2198
+ const html = files.map(file => renderDeliverable(file, t, baseUrl)).join('')
2199
+ entries.push(`<li class="session-entry session-ai session-files" data-delivery="${++delivery}"${atEnd ? ' data-final-files' : ''} data-for-step="${step}" data-t="${time}"><div class="session-bubble"><span class="session-who">${escape(t(label))}</span>${html}</div></li>`)
2200
+ }
1832
2201
 
1833
2202
  const stamp = (seconds, forStep) => {
1834
2203
  if (seconds - shown < 300) return ''
@@ -1884,7 +2253,12 @@ function renderLog(session, line, { t, baseUrl = '' }) {
1884
2253
 
1885
2254
  for (const item of line.items) {
1886
2255
  if (item.type === 'tool' || item.type === 'reasoning') {
2256
+ if (item.deliverables?.length) flush()
1887
2257
  work.push(item)
2258
+ if (item.deliverables?.length) {
2259
+ flush()
2260
+ addFiles(item.deliverables, stepIndex - 1, item.t)
2261
+ }
1888
2262
  continue
1889
2263
  }
1890
2264
  flush()
@@ -1912,20 +2286,10 @@ function renderLog(session, line, { t, baseUrl = '' }) {
1912
2286
  } else {
1913
2287
  entries.push(`${stamp(item.t, stepIndex - 1)}<li class="session-entry session-ai" data-step="${stepIndex - 1}" data-echo-cat="msg" data-kind="reply" data-t="${item.t}"><div class="session-bubble">${item.question ? `<span class="session-who">${escape(t('asksYou', { tool }))}</span>` : ''}<div class="session-ai-body">${render(item.text)}</div>${renderStepArtifacts(stepMeta, { renderMd: render, t, baseUrl })}</div></li>`)
1914
2288
  }
2289
+ addFiles(item.deliverables, stepIndex - 1, item.t, false, item.type === 'user' ? 'inputFiles' : 'deliverablesTitle')
1915
2290
  }
1916
2291
  flush()
1917
-
1918
- const deliverables = session.deliverables || session.files || []
1919
- const filesHtml = deliverables.map(file => {
1920
- const href = escape(resolveAsset(file.href, baseUrl))
1921
- const cover = file.cover ? escape(resolveAsset(file.cover, baseUrl)) : ''
1922
- return validVideo.test(file.href)
1923
- ? `<figure class="session-video"><video controls preload="none" playsinline width="960" height="540"${cover ? ` poster="${cover}"` : ''}><source src="${href}" type="video/mp4"></video><figcaption><b>${escape(file.title)}</b>${file.meta ? `<small>${escape(file.meta)}</small>` : ''}</figcaption></figure>`
1924
- : `<a class="session-file" href="${href}" target="_blank" rel="noopener noreferrer">${cover ? `<img src="${cover}" alt="" width="56" height="79" loading="lazy">` : ''}<span><b>${escape(file.title)}</b>${file.meta ? `<small>${escape(file.meta)}</small>` : ''}</span></a>`
1925
- }).join('')
1926
- if (filesHtml) {
1927
- entries.push(`<li class="session-entry session-ai session-files" data-for-step="${Math.max(0, line.steps.length - 1)}" data-t="${line.end}"><div class="session-bubble"><span class="session-who">${escape(t('deliverablesTitle'))}</span>${filesHtml}</div></li>`)
1928
- }
2292
+ addFiles(session.deliverables || session.files, Math.max(0, line.steps.length - 1), line.end, true)
1929
2293
  return `<ol class="session-log">${entries.join('')}</ol>`
1930
2294
  }
1931
2295
 
@@ -2000,7 +2364,13 @@ function buildPlayerData(session, line, { baseUrl = '' } = {}) {
2000
2364
  }
2001
2365
  }
2002
2366
 
2003
- function renderPlayerWidget(session, computedTimeline, { lang = 'zh', baseUrl = '' } = {}) {
2367
+ function renderPlayerWidget(session, computedTimeline, {
2368
+ lang = 'zh',
2369
+ baseUrl = '',
2370
+ backHref = '',
2371
+ backLabel = '',
2372
+ showLangToggle = !backHref,
2373
+ } = {}) {
2004
2374
  const t = createTranslator(lang || session.lang || 'zh')
2005
2375
  const line = computedTimeline || timeline(session, { lang: t.lang })
2006
2376
  const tool = toolLabels[session.tool] || session.tool || 'Agent'
@@ -2011,18 +2381,24 @@ function renderPlayerWidget(session, computedTimeline, { lang = 'zh', baseUrl =
2011
2381
  const firstPromptDraft = rawFirstPrompt && rawFirstPrompt !== '(中途打断)' ? rawFirstPrompt : ''
2012
2382
  const hasInitialDraft = Boolean(firstPromptDraft)
2013
2383
  const dataJson = JSON.stringify(buildPlayerData(session, line, { baseUrl })).replace(/</g, '\\u003c')
2384
+ const leadBadge = backHref && backLabel
2385
+ ? `<a class="session-back" href="${escape(backHref)}">${escape(backLabel)}</a>`
2386
+ : `<span class="encore-brand-badge" aria-hidden="true">ENCORE</span>`
2387
+ const rightControls = showLangToggle
2388
+ ? `<div class="session-topbar-right">
2389
+ <button type="button" class="encore-lang-btn" data-encore-lang-toggle title="${escape(t('toggleLangTitle'))}">${escape(t('toggleLangLabel'))}</button>
2390
+ </div>`
2391
+ : ''
2014
2392
 
2015
2393
  return `<div class="session-app" data-encore-lang="${escape(t.lang)}">
2016
2394
  <header class="session-topbar">
2017
2395
  <div class="session-topbar-left">
2018
- <span class="encore-brand-badge" aria-hidden="true">ENCORE</span>
2396
+ ${leadBadge}
2019
2397
  <span class="session-topbar-sep" aria-hidden="true">/</span>
2020
2398
  <h1 class="session-title">${escape(title)}</h1>
2021
2399
  <span class="session-model-pill">${escape(tool)}${session.model ? ` · ${escape(session.model)}` : ''}</span>
2022
2400
  </div>
2023
- <div class="session-topbar-right">
2024
- <button type="button" class="encore-lang-btn" data-encore-lang-toggle title="${escape(t('toggleLangTitle'))}">${escape(t('toggleLangLabel'))}</button>
2025
- </div>
2401
+ ${rightControls}
2026
2402
  </header>
2027
2403
  <section class="session-player" aria-label="${escape(t('tlAria'))}" hidden>
2028
2404
  ${scrubber(line)}
@@ -2046,7 +2422,7 @@ function renderPlayerWidget(session, computedTimeline, { lang = 'zh', baseUrl =
2046
2422
  <div class="session-composer-bar">
2047
2423
  <span class="session-composer-left">
2048
2424
  <span class="session-composer-plus" aria-hidden="true">+</span>
2049
- <span class="session-composer-perm" data-session-stage-badge>Workspace Write</span>
2425
+ <span class="session-composer-perm" data-session-stage-badge>${escape(t('workspaceWrite'))}</span>
2050
2426
  </span>
2051
2427
  <span class="session-composer-right">
2052
2428
  <span class="session-composer-model">${escape(session.model || tool)}</span>
@@ -2429,7 +2805,36 @@ function attachPlayerController(containerEl, playerData, { lang = 'zh', initialS
2429
2805
  }
2430
2806
 
2431
2807
  if (play) play.hidden = false
2808
+ attachAttachmentReaders(containerEl, t, () => { if (playing) setPlaying(false) })
2432
2809
  if (log) log.classList.add('is-staged')
2810
+ for (const formats of containerEl.querySelectorAll('.session-video-formats')) {
2811
+ const figure = formats.closest('figure')
2812
+ const video = figure.querySelector('video')
2813
+ formats.addEventListener('click', async event => {
2814
+ const button = event.target.closest('[data-video-format]')
2815
+ if (!button || button.getAttribute('aria-pressed') === 'true') return
2816
+ const time = video.currentTime
2817
+ const resume = !video.paused && !video.ended
2818
+ formats.querySelector('[aria-pressed="true"]').setAttribute('aria-pressed', 'false')
2819
+ button.setAttribute('aria-pressed', 'true')
2820
+ video.dataset.format = button.dataset.videoFormat
2821
+ if (button.dataset.cover) video.poster = button.dataset.cover
2822
+ else video.removeAttribute('poster')
2823
+ video.preload = time > 0 ? 'metadata' : 'none'
2824
+ video.src = button.dataset.src
2825
+ video.load()
2826
+ if (time > 0) video.currentTime = time
2827
+ figure.scrollIntoView({ block: 'nearest' })
2828
+ if (resume) {
2829
+ try {
2830
+ await video.play()
2831
+ } catch (error) {
2832
+ // Switching again or pausing can interrupt the pending play request.
2833
+ if (error.name !== 'AbortError') throw error
2834
+ }
2835
+ }
2836
+ })
2837
+ }
2433
2838
  if (scrubber) {
2434
2839
  scrubber.classList.add('is-ready')
2435
2840
  scrubber.removeAttribute('aria-hidden')
@@ -2656,7 +3061,7 @@ function attachPlayerController(containerEl, playerData, { lang = 'zh', initialS
2656
3061
  : shorten(s.summary || t('tlStepFallback'), 24)
2657
3062
  const tokStr = `${((s.contextSnapshot?.totalTokens || 0) / 1000).toFixed(1)}k`
2658
3063
  tlPop.style.left = `${pct.toFixed(1)}%`
2659
- tlPop.innerHTML = `${thumbHtml}<span class="session-tl-pop-meta"><small>${escapeHtml(t('tlStepMeta', { step: idx + 1, time: elapsedClock(s.t) }))}</small><b>${escapeHtml(headTitle)}</b><span>Context ≈${escapeHtml(tokStr)}</span></span>`
3064
+ tlPop.innerHTML = `${thumbHtml}<span class="session-tl-pop-meta"><small>${escapeHtml(t('tlStepMeta', { step: idx + 1, time: elapsedClock(s.t) }))}</small><b>${escapeHtml(headTitle)}</b><span>${escapeHtml(t('contextLabel'))} ≈${escapeHtml(tokStr)}</span></span>`
2660
3065
  tlPop.hidden = false
2661
3066
  }
2662
3067
 
@@ -3109,6 +3514,9 @@ function attachPlayerController(containerEl, playerData, { lang = 'zh', initialS
3109
3514
  if (!future) latestVisibleEntry = item.entry
3110
3515
  }
3111
3516
  for (const aux of auxEntries) {
3517
+ if (aux.forStep > playHead && aux.entry.matches('.session-files:not(.is-future)')) {
3518
+ aux.entry.querySelectorAll('video').forEach(video => video.pause())
3519
+ }
3112
3520
  aux.entry.classList.toggle('is-future', aux.forStep > playHead)
3113
3521
  }
3114
3522
 
@@ -3236,8 +3644,8 @@ function attachPlayerController(containerEl, playerData, { lang = 'zh', initialS
3236
3644
  })
3237
3645
 
3238
3646
  const onKeyDown = event => {
3239
- if (event.defaultPrevented || event.metaKey || event.ctrlKey || event.altKey) return
3240
- if (event.target.closest('input, textarea, select, a, audio, video, summary, [contenteditable]')) return
3647
+ if (lightbox?.open || event.target.closest('dialog[open]') || event.defaultPrevented || event.metaKey || event.ctrlKey || event.altKey) return
3648
+ if (event.target.closest('input, textarea, select, a, audio, video, .session-video-formats, summary, [contenteditable]')) return
3241
3649
  if (event.key === ' ' && event.target.closest('button')) return
3242
3650
  if (event.key === 'ArrowLeft') {
3243
3651
  setPlaying(false)
@@ -3252,9 +3660,8 @@ function attachPlayerController(containerEl, playerData, { lang = 'zh', initialS
3252
3660
  }
3253
3661
  event.preventDefault()
3254
3662
  }
3255
- if (typeof document !== 'undefined') {
3256
- document.addEventListener('keydown', onKeyDown)
3257
- }
3663
+ if (!appEl.hasAttribute('tabindex')) appEl.tabIndex = -1
3664
+ appEl.addEventListener('keydown', onKeyDown)
3258
3665
 
3259
3666
  if (scrubber) {
3260
3667
  const fromPointer = event => {
@@ -3284,9 +3691,7 @@ function attachPlayerController(containerEl, playerData, { lang = 'zh', initialS
3284
3691
  destroy() {
3285
3692
  clearStepAnimations()
3286
3693
  camera.stop()
3287
- if (typeof document !== 'undefined') {
3288
- document.removeEventListener('keydown', onKeyDown)
3289
- }
3694
+ appEl.removeEventListener('keydown', onKeyDown)
3290
3695
  },
3291
3696
  goToStage,
3292
3697
  setPlaying,
@@ -3303,6 +3708,25 @@ async function createEncorePlayer(targetEl, sourceOrSession, options = {}) {
3303
3708
  if (!session && el.getAttribute('src')) {
3304
3709
  sourceOrSession = el.getAttribute('src')
3305
3710
  }
3711
+ const preRenderedData = !session && !sourceOrSession
3712
+ ? el.querySelector('[data-encore-session-data], #session-data')
3713
+ : null
3714
+ if (preRenderedData) {
3715
+ document.documentElement.classList.add('js-session')
3716
+ el.classList.add('session-wrap')
3717
+ el.querySelector('[data-encore-lang-toggle]')?.remove()
3718
+ const appNode = el.querySelector('.session-app')
3719
+ const activeLang = resolveLang(options.lang || el.dataset.lang || appNode?.dataset.encoreLang || 'zh')
3720
+ const playerData = JSON.parse(preRenderedData.textContent)
3721
+ const activeController = attachPlayerController(el, playerData, {
3722
+ lang: activeLang,
3723
+ initialStep: options.initialStep ?? -1,
3724
+ })
3725
+ return {
3726
+ setLang: () => {},
3727
+ getController: () => activeController,
3728
+ }
3729
+ }
3306
3730
  if (typeof sourceOrSession === 'string') {
3307
3731
  const srcUrl = sourceOrSession
3308
3732
  if (!baseUrl) {
@@ -3336,7 +3760,7 @@ async function createEncorePlayer(targetEl, sourceOrSession, options = {}) {
3336
3760
  if (activeController) activeController.destroy()
3337
3761
  activeLang = resolveLang(lang)
3338
3762
  const line = timeline(session, { lang: activeLang })
3339
- el.innerHTML = renderPlayerWidget(session, line, { lang: activeLang, baseUrl })
3763
+ el.innerHTML = renderPlayerWidget(session, line, { lang: activeLang, baseUrl, showLangToggle: options.showLangToggle })
3340
3764
  if (session.title && document.querySelectorAll('[data-encore-player]').length <= 1) {
3341
3765
  document.title = `${session.title} · Encore`
3342
3766
  }
@@ -3363,7 +3787,19 @@ async function autoMountEncorePlayers() {
3363
3787
  if (node.dataset.encoreMounted) continue
3364
3788
  node.dataset.encoreMounted = '1'
3365
3789
  try {
3366
- await createEncorePlayer(node)
3790
+ const player = await createEncorePlayer(node)
3791
+ const showLinkedDelivery = () => {
3792
+ const match = /^#delivery-(\d+)$/.exec(location.hash)
3793
+ const files = match ? node.querySelector(`[data-delivery="${match[1]}"]`)
3794
+ : location.hash === '#deliverables' && [...node.querySelectorAll('[data-delivery]')].at(-1)
3795
+ if (!files) return
3796
+ const controller = player.getController()
3797
+ controller.setPlaying(false)
3798
+ controller.goToStage(Number(files.dataset.forStep), false)
3799
+ files.scrollIntoView({ block: 'start' })
3800
+ }
3801
+ showLinkedDelivery()
3802
+ window.addEventListener('hashchange', showLinkedDelivery)
3367
3803
  } catch (err) {
3368
3804
  node.innerHTML = `<div class="encore-load-error">Failed to load session replay: ${escapeHtml(err.message || String(err))}</div>`
3369
3805
  }
@@ -3371,8 +3807,10 @@ async function autoMountEncorePlayers() {
3371
3807
  }
3372
3808
 
3373
3809
  if (typeof globalThis !== 'undefined') {
3810
+ globalThis.createSessionPlaybackModel = createSessionPlaybackModel
3374
3811
  globalThis.EncorePlayer = {
3375
3812
  create: createEncorePlayer,
3813
+ attach: attachPlayerController,
3376
3814
  mountAll: autoMountEncorePlayers,
3377
3815
  createSessionPlaybackModel,
3378
3816
  }