dsh-agent-control-center 0.2.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/client.js CHANGED
@@ -1,12 +1,12 @@
1
1
  // Generated by scripts/build-client.mjs from src/client/ — do not edit.
2
- // DSH client module: dsh-agent-control-center@0.2.0 (10 i18n fragments, 9 pages)
2
+ // DSH client module: dsh-agent-control-center@0.3.1 (12 i18n fragments, 11 pages)
3
3
  window.__ModuleLoader__.load({
4
4
  id: "dsh-agent-control-center",
5
5
  factory(require) {
6
6
  'use strict'
7
7
  const React = require('react')
8
8
  const h = React.createElement
9
- const ACC_VERSION = "0.2.0"
9
+ const ACC_VERSION = "0.3.1"
10
10
  /* ---- kernel.js ---- */
11
11
  /* ---------------------------------------------------------------------------
12
12
  * ACC kernel — shared runtime attached to every page script.
@@ -91,6 +91,7 @@ ACC.t = function translate(key, fallback) {
91
91
  * @param {{
92
92
  * id: string,
93
93
  * titleKey: string,
94
+ * group?: 'edit' | 'insight' | 'maintain',
94
95
  * order?: number,
95
96
  * descriptionKey?: string,
96
97
  * icon?: string,
@@ -106,6 +107,7 @@ ACC.registerPage = function registerPage(definition) {
106
107
  ACC.pages.push({
107
108
  id: definition.id,
108
109
  titleKey: definition.titleKey,
110
+ group: typeof definition.group === 'string' ? definition.group : undefined,
109
111
  descriptionKey: definition.descriptionKey,
110
112
  icon: typeof definition.icon === 'string' ? definition.icon : undefined,
111
113
  order: typeof definition.order === 'number' ? definition.order : 100,
@@ -269,6 +271,17 @@ const ACC_ICONS = {
269
271
  ['path', { d: 'M13.35 2.85v3.95h-3.95' }],
270
272
  ],
271
273
  close: [['path', { d: 'M4.2 4.2l7.6 7.6M11.8 4.2l-7.6 7.6' }]],
274
+ // Pages added in 0.3.0 (instruction preview, session export).
275
+ 'file-text': [
276
+ ['path', { d: 'M3.9 1.9h4.85L12.1 5.25v8.85H3.9z' }],
277
+ ['path', { d: 'M8.6 2.1v3.4h3.4' }],
278
+ ['path', { d: 'M5.9 7.5h4.2M5.9 10h4.2' }],
279
+ ],
280
+ download: [
281
+ ['path', { d: 'M8 2.2v7.1' }],
282
+ ['path', { d: 'M5.1 6.6 8 9.5l2.9-2.9' }],
283
+ ['path', { d: 'M2.9 11.2v1.35a1.2 1.2 0 0 0 1.2 1.2h7.8a1.2 1.2 0 0 0 1.2-1.2v-1.35' }],
284
+ ],
272
285
  check: [['path', { d: 'M3.3 8.4 6.3 11.4 12.7 5.1' }]],
273
286
  dot: [['circle', { cx: 8, cy: 8, r: 2.4 }]],
274
287
  }
@@ -1103,6 +1116,9 @@ ACC.addI18n({
1103
1116
  'nav.ariaLabel': '控制台页面导航',
1104
1117
  'nav.refreshStatus': '刷新状态',
1105
1118
  'nav.refreshStatusHint': '只刷新宿主健康状态,不重新加载当前页面',
1119
+ 'nav.group.edit': '编辑与指令',
1120
+ 'nav.group.insight': '会话与洞察',
1121
+ 'nav.group.maintain': '维护',
1106
1122
  'nav.desc.overview': '环境、宿主能力与今天的关键数字',
1107
1123
  'nav.desc.agents': 'AGENTS.md 指令链的读取、编辑、校验与备份',
1108
1124
  'nav.desc.tools': '宿主导出的工具清单、定义状态与调用统计',
@@ -1151,6 +1167,9 @@ ACC.addI18n({
1151
1167
  'nav.ariaLabel': 'Control center page navigation',
1152
1168
  'nav.refreshStatus': 'Refresh status',
1153
1169
  'nav.refreshStatusHint': 'Refreshes host health only; the current page is not reloaded',
1170
+ 'nav.group.edit': 'Editing & instructions',
1171
+ 'nav.group.insight': 'Sessions & insights',
1172
+ 'nav.group.maintain': 'Maintenance',
1154
1173
  'nav.desc.overview': 'Environment, host capabilities and today’s key numbers',
1155
1174
  'nav.desc.agents': 'Read, edit, validate and back up the AGENTS.md instruction chain',
1156
1175
  'nav.desc.tools': 'Tools exposed by the host, their definition state and call statistics',
@@ -1533,6 +1552,422 @@ ACC.addI18n({
1533
1552
  })
1534
1553
  ;
1535
1554
 
1555
+ /* ---- i18n/export.js ---- */
1556
+ /* Export page vocabulary (module K). Every user-visible string lives here.
1557
+ * The build checks zh/en key parity, so both dictionaries stay in lockstep. */
1558
+ ACC.addI18n({
1559
+ zh: {
1560
+ 'nav.export': '会话导出',
1561
+ 'nav.desc.export': '把会话只读导出为 Markdown 或 JSON,可复制与下载',
1562
+
1563
+ 'export.policyNote': '只读导出:不删除、不归档、不上传。',
1564
+ 'export.policySource': '宿主策略原文',
1565
+ 'export.loading': '正在读取导出能力…',
1566
+ 'export.loadFailed': '导出能力读取失败',
1567
+ 'export.moduleMissing': '当前宿主插件构建没有加载 export 模块(版本 {version})。',
1568
+ 'export.errorHint': '页面本身已加载;若当前宿主缺少导出方法,请升级并重启插件后重试,本页不会显示假数据。',
1569
+ 'export.unavailableHint': '请升级并重启 Agent Control Center,确认宿主提供 export.* 方法后重试;本页不会显示假数据。',
1570
+ 'export.capabilityHint': '导出需要宿主提供 sessionQuery 服务(含 readSession);请在支持该能力的版本中重启插件后重试。',
1571
+ 'export.unknownReason': '宿主未返回原因',
1572
+ 'export.reasonLabel': '原因',
1573
+ 'export.nextStepLabel': '下一步',
1574
+
1575
+ 'export.pickTitle': '选择会话',
1576
+ 'export.sessionsCount': '显示 {shown} / 共 {total} 个会话',
1577
+ 'export.searchActive': '筛选:{query}',
1578
+ 'export.searchPlaceholder': '按标题或会话 ID 搜索…',
1579
+ 'export.searchAria': '搜索可导出的会话',
1580
+ 'export.searchClear': '清空搜索',
1581
+ 'export.sessionsListAria': '可导出的会话列表',
1582
+ 'export.loadingSessions': '正在读取会话列表…',
1583
+ 'export.loadFailedSessions': '会话列表加载失败',
1584
+ 'export.emptySessions': '没有可导出的会话',
1585
+ 'export.emptySessionsHint': '宿主没有返回可导出的会话记录;可以刷新后重试。',
1586
+ 'export.emptySearch': '没有匹配的会话',
1587
+ 'export.emptySearchHint': '换个关键词,或清空搜索。',
1588
+ 'export.untitled': '未命名会话',
1589
+ 'export.archived': '已归档',
1590
+ 'export.originLabel': '来源',
1591
+ 'export.eventCount': '{count} 个事件',
1592
+
1593
+ 'export.settingsTitle': '导出设置',
1594
+ 'export.settingsHint': '格式、工具结果与字节上限只影响下一次生成。',
1595
+ 'export.format': '格式',
1596
+ 'export.formatAria': '导出格式',
1597
+ 'export.formatMarkdown': 'Markdown',
1598
+ 'export.formatJson': 'JSON',
1599
+ 'export.includeToolResults': '包含工具结果',
1600
+ 'export.includeToolResultsHint': '关闭后工具调用只保留摘要,导出更小。',
1601
+ 'export.maxBytes': '字节上限',
1602
+ 'export.maxBytesHint': '超过上限时按事件边界截断,不会留下半个事件。',
1603
+ 'export.limit64': '64 KiB',
1604
+ 'export.limit256': '256 KiB',
1605
+ 'export.limit1m': '1 MiB',
1606
+
1607
+ 'export.resultTitle': '导出结果',
1608
+ 'export.resultHint': '先看概况,再生成预览;生成不会写入任何会话记录。',
1609
+ 'export.selectHint': '从左侧选择一个会话',
1610
+ 'export.selectHintHint': '选中后会先显示概况,再按当前设置生成导出。',
1611
+ 'export.summaryLoading': '正在统计会话…',
1612
+ 'export.summaryFailed': '会话概况加载失败',
1613
+ 'export.countEvents': '事件',
1614
+ 'export.countUser': '用户消息',
1615
+ 'export.countAssistant': '助手消息',
1616
+ 'export.countToolCalls': '工具调用',
1617
+ 'export.countToolResults': '工具结果',
1618
+ 'export.countToolErrors': '工具错误',
1619
+ 'export.countErrors': '错误',
1620
+ 'export.estimatedMarkdown': 'Markdown 估算',
1621
+ 'export.estimatedJson': 'JSON 估算',
1622
+ 'export.generate': '生成导出',
1623
+ 'export.generating': '正在生成…',
1624
+ 'export.generateFailed': '生成导出失败',
1625
+ 'export.generateHint': '设置改动后需要重新生成;复制与下载使用最近一次结果。',
1626
+ 'export.resultBytes': '导出字节',
1627
+ 'export.resultTotalBytes': '完整字节',
1628
+ 'export.truncated': '截断',
1629
+ 'export.truncatedYes': '已截断',
1630
+ 'export.truncatedNo': '未截断',
1631
+ 'export.omittedEvents': '省略事件',
1632
+ 'export.generatedAt': '生成时间',
1633
+ 'export.truncatedNotice': '超出字节上限,已按事件边界省略 {count} 个事件。',
1634
+ 'export.warnings': '提示',
1635
+ 'export.preview': '预览',
1636
+ 'export.previewEmpty': '导出内容为空',
1637
+ 'export.copy': '复制',
1638
+ 'export.copied': '已复制',
1639
+ 'export.copyFailed': '复制失败(浏览器未授权剪贴板)',
1640
+ 'export.download': '下载',
1641
+ 'export.downloaded': '已开始下载',
1642
+ 'export.downloadFailed': '下载失败(浏览器不支持 Blob 下载)',
1643
+ },
1644
+ en: {
1645
+ 'nav.export': 'Export',
1646
+ 'nav.desc.export': 'Read-only session export to Markdown or JSON, with copy and download',
1647
+
1648
+ 'export.policyNote': 'Read-only export: it never deletes, archives or uploads anything.',
1649
+ 'export.policySource': 'Host policy text',
1650
+ 'export.loading': 'Reading export capabilities…',
1651
+ 'export.loadFailed': 'Could not read export capabilities',
1652
+ 'export.moduleMissing': 'The current host plugin build does not load the export module (version {version}).',
1653
+ 'export.errorHint': 'The page itself loaded; if the host is missing the export methods, upgrade and restart the plugin, then retry. This page never shows made-up data.',
1654
+ 'export.unavailableHint': 'Upgrade and restart Agent Control Center so the host exposes the export.* methods, then retry; this page never shows made-up data.',
1655
+ 'export.capabilityHint': 'Export needs the host sessionQuery service with readSession; restart the plugin on a build that provides it, then retry.',
1656
+ 'export.unknownReason': 'The host returned no reason',
1657
+ 'export.reasonLabel': 'Reason',
1658
+ 'export.nextStepLabel': 'Next step',
1659
+
1660
+ 'export.pickTitle': 'Choose a session',
1661
+ 'export.sessionsCount': 'Showing {shown} of {total} sessions',
1662
+ 'export.searchActive': 'Filtered by: {query}',
1663
+ 'export.searchPlaceholder': 'Search by title or session ID…',
1664
+ 'export.searchAria': 'Search exportable sessions',
1665
+ 'export.searchClear': 'Clear search',
1666
+ 'export.sessionsListAria': 'Exportable session list',
1667
+ 'export.loadingSessions': 'Loading the session list…',
1668
+ 'export.loadFailedSessions': 'Could not load the session list',
1669
+ 'export.emptySessions': 'No sessions available for export',
1670
+ 'export.emptySessionsHint': 'The host returned no exportable session records; refresh and retry.',
1671
+ 'export.emptySearch': 'No sessions match the search',
1672
+ 'export.emptySearchHint': 'Try another keyword, or clear the search.',
1673
+ 'export.untitled': 'Untitled session',
1674
+ 'export.archived': 'Archived',
1675
+ 'export.originLabel': 'Origin',
1676
+ 'export.eventCount': '{count} events',
1677
+
1678
+ 'export.settingsTitle': 'Export settings',
1679
+ 'export.settingsHint': 'Format, tool results and the byte limit only affect the next generated export.',
1680
+ 'export.format': 'Format',
1681
+ 'export.formatAria': 'Export format',
1682
+ 'export.formatMarkdown': 'Markdown',
1683
+ 'export.formatJson': 'JSON',
1684
+ 'export.includeToolResults': 'Include tool results',
1685
+ 'export.includeToolResultsHint': 'When off, tool calls keep only summaries and the export is smaller.',
1686
+ 'export.maxBytes': 'Byte limit',
1687
+ 'export.maxBytesHint': 'Over the limit, events are dropped at event boundaries; never half an event.',
1688
+ 'export.limit64': '64 KiB',
1689
+ 'export.limit256': '256 KiB',
1690
+ 'export.limit1m': '1 MiB',
1691
+
1692
+ 'export.resultTitle': 'Export result',
1693
+ 'export.resultHint': 'Review the summary, then generate a preview; generation never writes session records.',
1694
+ 'export.selectHint': 'Pick a session from the left',
1695
+ 'export.selectHintHint': 'A selected session shows its summary first; then export with the current settings.',
1696
+ 'export.summaryLoading': 'Counting the session…',
1697
+ 'export.summaryFailed': 'Could not load the session summary',
1698
+ 'export.countEvents': 'Events',
1699
+ 'export.countUser': 'User messages',
1700
+ 'export.countAssistant': 'Assistant messages',
1701
+ 'export.countToolCalls': 'Tool calls',
1702
+ 'export.countToolResults': 'Tool results',
1703
+ 'export.countToolErrors': 'Tool errors',
1704
+ 'export.countErrors': 'Errors',
1705
+ 'export.estimatedMarkdown': 'Markdown estimate',
1706
+ 'export.estimatedJson': 'JSON estimate',
1707
+ 'export.generate': 'Generate export',
1708
+ 'export.generating': 'Generating…',
1709
+ 'export.generateFailed': 'Could not generate the export',
1710
+ 'export.generateHint': 'Changing settings requires regenerating; copy and download use the latest result.',
1711
+ 'export.resultBytes': 'Export bytes',
1712
+ 'export.resultTotalBytes': 'Full size',
1713
+ 'export.truncated': 'Truncation',
1714
+ 'export.truncatedYes': 'Truncated',
1715
+ 'export.truncatedNo': 'Not truncated',
1716
+ 'export.omittedEvents': 'Omitted events',
1717
+ 'export.generatedAt': 'Generated',
1718
+ 'export.truncatedNotice': 'Over the byte limit; {count} events omitted at event boundaries.',
1719
+ 'export.warnings': 'Warnings',
1720
+ 'export.preview': 'Preview',
1721
+ 'export.previewEmpty': 'The export is empty',
1722
+ 'export.copy': 'Copy',
1723
+ 'export.copied': 'Copied',
1724
+ 'export.copyFailed': 'Copy failed (the browser denied clipboard access)',
1725
+ 'export.download': 'Download',
1726
+ 'export.downloaded': 'Download started',
1727
+ 'export.downloadFailed': 'Download failed (Blob download unsupported)',
1728
+ },
1729
+ })
1730
+ ;
1731
+
1732
+ /* ---- i18n/instruction.js ---- */
1733
+ /* Instruction preview page vocabulary (module J). Every user-visible string
1734
+ * lives here; the English dictionary is a complete mirror of the Chinese one
1735
+ * (scripts/build-client.mjs rejects a mismatch). Host-provided text (reasons,
1736
+ * hints, notes) is never translated here: pages show it through ACC.l10n.host
1737
+ * and disclose the original in the raw block when the English UI would leak
1738
+ * Chinese. */
1739
+ ACC.addI18n({
1740
+ zh: {
1741
+ 'nav.instruction': '指令预览',
1742
+ 'nav.desc.instruction': '按文件与会话两条视角只读查看模型实际收到的指令内容',
1743
+
1744
+ 'instruction.readOnly': '只读:不修改任何指令文件',
1745
+ 'instruction.tabsLabel': '指令视图',
1746
+ 'instruction.tabFiles': '按文件重组(近似)',
1747
+ 'instruction.tabSession': '按会话精确',
1748
+ 'instruction.tabCompare': '对比',
1749
+ 'instruction.failed': '指令预览加载失败',
1750
+ 'instruction.unavailableTitle': '指令预览不可用',
1751
+ 'instruction.reasonGeneric': '宿主报告该数据源不可用;原始原因见下方。',
1752
+ 'instruction.hintGeneric': '宿主未提供进一步提示。',
1753
+ 'instruction.hint': '提示',
1754
+ 'instruction.rawHostText': '原始宿主文本(英文界面折叠显示)',
1755
+ 'instruction.moduleAUnavailable': '文件侧不可用:AGENTS.md 模块(模块 A)未加载,只能查看会话精确视图。',
1756
+
1757
+ 'instruction.chainTitle': '指令链(按文件)',
1758
+ 'instruction.chainUnavailableTitle': '指令链不可用',
1759
+ 'instruction.chainUserGlobal': '用户全局链',
1760
+ 'instruction.chainProject': '项目链',
1761
+ 'instruction.budgetFits': '预算内',
1762
+ 'instruction.budgetOver': '超出预算',
1763
+ 'instruction.budgetUsage': '{rendered} / {max}',
1764
+ 'instruction.budgetRaw': '原始文件字节 {bytes}',
1765
+ 'instruction.budgetSource': '预算来源',
1766
+ 'instruction.budgetSourceUnknown': '预算来源未知',
1767
+ 'instruction.chainCwd': '工作目录',
1768
+ 'instruction.chainProjectRoot': '项目根目录',
1769
+ 'instruction.chainSource': '目录来源',
1770
+ 'instruction.chainFilesCount': '文件:{count}',
1771
+ 'instruction.displayPath': '显示路径',
1772
+ 'instruction.source': '来源',
1773
+ 'instruction.flags': '标记',
1774
+ 'instruction.badgeEffective': '生效中',
1775
+ 'instruction.badgeOmitted': '预算省略',
1776
+ 'instruction.badgeTruncated': '预算截断',
1777
+ 'instruction.badgeDeduped': '已去重',
1778
+ 'instruction.badgeDedupedBy': '去重于 {path}',
1779
+ 'instruction.sourceUserGlobal': '用户全局',
1780
+ 'instruction.sourceProject': '项目',
1781
+ 'instruction.sourceAgentsHome': '共享 agents 根',
1782
+ 'instruction.sourceProjectLocal': '项目本地覆盖',
1783
+ 'instruction.sourceUnknown': '其它来源',
1784
+ 'instruction.chainEmpty': '未发现指令文件',
1785
+ 'instruction.chainEmptyHint': '当前工作目录没有可读的 AGENTS.md 指令文件,因此没有可重组的链。',
1786
+ 'instruction.chainWarnings': '链警告',
1787
+ 'instruction.chainTruncated': '响应超限:部分文件行已被省略;请以宿主侧的完整清单为准。',
1788
+
1789
+ 'instruction.previewTitle': '渲染后的指令预览',
1790
+ 'instruction.previewExact': '与宿主注入格式一致(精确)',
1791
+ 'instruction.previewApprox': '按预算重组的近似文本(exact=false)',
1792
+ 'instruction.exact': '精确',
1793
+ 'instruction.approximate': '近似',
1794
+ 'instruction.copied': '已复制',
1795
+ 'instruction.copyFailed': '复制失败',
1796
+ 'instruction.copyPreview': '复制预览文本',
1797
+ 'instruction.previewBytes': '字节数 {bytes}',
1798
+ 'instruction.previewSections': '文件段:{count}',
1799
+ 'instruction.previewOmitted': '预算省略了 {count} 个文件',
1800
+ 'instruction.previewTruncated': '预算截断了 {count} 个文件',
1801
+ 'instruction.previewResponseTruncated': '响应超过上限,预览文本已截断;完整文本请以会话精确视图为准。',
1802
+ 'instruction.previewNote': '文件侧是按宿主预算重组的近似文本;只有「精确」徽标表示与宿主注入格式完全一致。',
1803
+ 'instruction.previewEmpty': '宿主未返回预览文本',
1804
+ 'instruction.previewEmptyHint': '文件侧没有可渲染的文本;请确认 AGENTS.md 模块与指令预算可用。',
1805
+
1806
+ 'instruction.sessionPickTitle': '会话选择',
1807
+ 'instruction.sessionPickHint': '选择一条会话后读取其持久化的指令事件;只读,不会续跑或修改会话。',
1808
+ 'instruction.sessionPick': '选择会话',
1809
+ 'instruction.sessionPickAria': '选择要查看指令的会话',
1810
+ 'instruction.sessionListLoaded': '已加载会话:{count}',
1811
+ 'instruction.sessionsFailed': '会话列表加载失败',
1812
+ 'instruction.sessionListRefresh': '刷新会话列表',
1813
+ 'instruction.sessionsEmpty': '宿主还没有会话',
1814
+ 'instruction.sessionsEmptyHint': '先在宿主中开始一轮对话;指令块写入会话日志后会出现在这里。',
1815
+ 'instruction.untitled': '未命名会话',
1816
+ 'instruction.sessionFailed': '会话指令加载失败',
1817
+ 'instruction.sessionUnavailableTitle': '会话精确视图不可用',
1818
+ 'instruction.sessionBlocksTitle': '会话中的指令块',
1819
+ 'instruction.sessionId': '会话 ID',
1820
+ 'instruction.sessionInstructionCount': '指令块:{count}',
1821
+ 'instruction.sessionEmpty': '该会话没有记录指令块',
1822
+ 'instruction.sessionEmptyHint': '会话日志中没有 agent-instructions 事件;宿主只在首次注入指令时写入。',
1823
+ 'instruction.sessionReason': '宿主说明',
1824
+ 'instruction.baseline': '基线',
1825
+ 'instruction.change': '变更',
1826
+ 'instruction.blockTitle': '指令块 #{seq}',
1827
+ 'instruction.blockTime': '时间',
1828
+ 'instruction.blockTruncated': '已截断',
1829
+ 'instruction.blockTruncatedHint': '响应超限,该块文本已截断;完整内容请到宿主会话日志中查看。',
1830
+ 'instruction.blockEmpty': '该块没有可显示的文本',
1831
+ 'instruction.blockCollapsed': '内容较长({bytes}),已折叠',
1832
+ 'instruction.expand': '展开内容',
1833
+ 'instruction.collapse': '收起内容',
1834
+ 'instruction.copyBlock': '复制指令块',
1835
+ 'instruction.copyBlockAria': '复制指令块 #{seq}',
1836
+
1837
+ 'instruction.noSelection': '先选择一个会话',
1838
+ 'instruction.noSelectionHint': '会话数据按需读取;选中会话后才会请求指令块与对比结果。',
1839
+ 'instruction.compareFailed': '对比加载失败',
1840
+ 'instruction.compareUnavailableTitle': '对比不可用',
1841
+ 'instruction.compareTitle': '文件侧与会话侧对比',
1842
+ 'instruction.compareSubtitle': '差值 = 会话侧字节 − 文件侧字节;正数表示会话侧更大。',
1843
+ 'instruction.compareFilesBytes': '文件侧重构字节',
1844
+ 'instruction.compareSessionBytes': '会话侧精确字节',
1845
+ 'instruction.compareDeltaBytes': '差值(正数=会话侧更大)',
1846
+ 'instruction.sameText': '文本一致',
1847
+ 'instruction.differentText': '文本不一致',
1848
+ 'instruction.exactFilesYes': '文件侧精确',
1849
+ 'instruction.exactFilesNo': '文件侧近似',
1850
+ 'instruction.sessionItemsValue': '会话侧指令块:{count}',
1851
+ 'instruction.compareWhy': '两侧文本不同:文件侧是按预算重组的近似文本(可能省略、截断或去重),会话侧是宿主当时实际注入的精确文本;字节差异由此而来。',
1852
+ 'instruction.compareNote': '对比说明',
1853
+ },
1854
+ en: {
1855
+ 'nav.instruction': 'Instruction preview',
1856
+ 'nav.desc.instruction': 'Read-only view of the instruction text the model actually received, by files and by session',
1857
+
1858
+ 'instruction.readOnly': 'Read-only: no instruction file is ever modified',
1859
+ 'instruction.tabsLabel': 'Instruction views',
1860
+ 'instruction.tabFiles': 'By files (approximate)',
1861
+ 'instruction.tabSession': 'By session (exact)',
1862
+ 'instruction.tabCompare': 'Compare',
1863
+ 'instruction.failed': 'Could not load the instruction preview',
1864
+ 'instruction.unavailableTitle': 'Instruction preview unavailable',
1865
+ 'instruction.reasonGeneric': 'The host reported this source as unavailable; the raw reason is shown below.',
1866
+ 'instruction.hintGeneric': 'The host gave no further hint.',
1867
+ 'instruction.hint': 'Hint',
1868
+ 'instruction.rawHostText': 'Raw host text (collapsed in the English UI)',
1869
+ 'instruction.moduleAUnavailable': 'The files side is unavailable: the AGENTS.md module (module A) is not loaded, so only the exact session view can be shown.',
1870
+
1871
+ 'instruction.chainTitle': 'Instruction chain (by files)',
1872
+ 'instruction.chainUnavailableTitle': 'Instruction chain unavailable',
1873
+ 'instruction.chainUserGlobal': 'User-global chain',
1874
+ 'instruction.chainProject': 'Project chain',
1875
+ 'instruction.budgetFits': 'Within budget',
1876
+ 'instruction.budgetOver': 'Over budget',
1877
+ 'instruction.budgetUsage': '{rendered} / {max}',
1878
+ 'instruction.budgetRaw': 'Raw file bytes {bytes}',
1879
+ 'instruction.budgetSource': 'Budget source',
1880
+ 'instruction.budgetSourceUnknown': 'Budget source unknown',
1881
+ 'instruction.chainCwd': 'Working directory',
1882
+ 'instruction.chainProjectRoot': 'Project root',
1883
+ 'instruction.chainSource': 'Directory source',
1884
+ 'instruction.chainFilesCount': 'Files: {count}',
1885
+ 'instruction.displayPath': 'Display path',
1886
+ 'instruction.source': 'Source',
1887
+ 'instruction.flags': 'Flags',
1888
+ 'instruction.badgeEffective': 'In effect',
1889
+ 'instruction.badgeOmitted': 'Budget-omitted',
1890
+ 'instruction.badgeTruncated': 'Budget-truncated',
1891
+ 'instruction.badgeDeduped': 'Deduplicated',
1892
+ 'instruction.badgeDedupedBy': 'Deduplicated by {path}',
1893
+ 'instruction.sourceUserGlobal': 'User global',
1894
+ 'instruction.sourceProject': 'Project',
1895
+ 'instruction.sourceAgentsHome': 'Shared agents root',
1896
+ 'instruction.sourceProjectLocal': 'Project-local overlay',
1897
+ 'instruction.sourceUnknown': 'Other source',
1898
+ 'instruction.chainEmpty': 'No instruction files discovered',
1899
+ 'instruction.chainEmptyHint': 'The current working directory has no readable AGENTS.md instruction file, so there is no chain to reconstruct.',
1900
+ 'instruction.chainWarnings': 'Chain warnings',
1901
+ 'instruction.chainTruncated': 'The response hit its ceiling, so some file rows were omitted; use the host-side full list as the reference.',
1902
+
1903
+ 'instruction.previewTitle': 'Rendered instruction preview',
1904
+ 'instruction.previewExact': 'Matches the host injection format (exact)',
1905
+ 'instruction.previewApprox': 'Reconstructed under budget (exact=false)',
1906
+ 'instruction.exact': 'Exact',
1907
+ 'instruction.approximate': 'Approximate',
1908
+ 'instruction.copied': 'Copied',
1909
+ 'instruction.copyFailed': 'Copy failed',
1910
+ 'instruction.copyPreview': 'Copy preview text',
1911
+ 'instruction.previewBytes': 'Size {bytes}',
1912
+ 'instruction.previewSections': 'File sections: {count}',
1913
+ 'instruction.previewOmitted': '{count} files omitted by budget',
1914
+ 'instruction.previewTruncated': '{count} files truncated by budget',
1915
+ 'instruction.previewResponseTruncated': 'The response exceeded its ceiling, so the preview text was clipped; use the exact session view for the full text.',
1916
+ 'instruction.previewNote': 'The files side is a reconstruction under the host budget; only the Exact badge means it matches the host injection format byte for byte.',
1917
+ 'instruction.previewEmpty': 'The host returned no preview text',
1918
+ 'instruction.previewEmptyHint': 'The files side rendered no text; check that the AGENTS.md module and the instruction budget are available.',
1919
+
1920
+ 'instruction.sessionPickTitle': 'Session selection',
1921
+ 'instruction.sessionPickHint': 'Pick a session to read its durable instruction events; read-only, it never resumes or modifies a session.',
1922
+ 'instruction.sessionPick': 'Select a session',
1923
+ 'instruction.sessionPickAria': 'Session whose instructions to inspect',
1924
+ 'instruction.sessionListLoaded': 'Sessions loaded: {count}',
1925
+ 'instruction.sessionsFailed': 'Could not load the session list',
1926
+ 'instruction.sessionListRefresh': 'Refresh the session list',
1927
+ 'instruction.sessionsEmpty': 'The host has no sessions yet',
1928
+ 'instruction.sessionsEmptyHint': 'Start a turn in the host first; instruction blocks appear here once they are written to the session log.',
1929
+ 'instruction.untitled': 'Untitled session',
1930
+ 'instruction.sessionFailed': 'Could not load the session instructions',
1931
+ 'instruction.sessionUnavailableTitle': 'Exact session view unavailable',
1932
+ 'instruction.sessionBlocksTitle': 'Instruction blocks in this session',
1933
+ 'instruction.sessionId': 'Session ID',
1934
+ 'instruction.sessionInstructionCount': 'Instruction blocks: {count}',
1935
+ 'instruction.sessionEmpty': 'This session recorded no instruction blocks',
1936
+ 'instruction.sessionEmptyHint': 'The session log has no agent-instructions event; the host writes one only when it first injects instructions.',
1937
+ 'instruction.sessionReason': 'Host explanation',
1938
+ 'instruction.baseline': 'Baseline',
1939
+ 'instruction.change': 'Change',
1940
+ 'instruction.blockTitle': 'Instruction block #{seq}',
1941
+ 'instruction.blockTime': 'Time',
1942
+ 'instruction.blockTruncated': 'Truncated',
1943
+ 'instruction.blockTruncatedHint': 'The response hit its ceiling and this block was clipped; read the full text in the host session log.',
1944
+ 'instruction.blockEmpty': 'This block has no displayable text',
1945
+ 'instruction.blockCollapsed': 'Long content ({bytes}), collapsed',
1946
+ 'instruction.expand': 'Show content',
1947
+ 'instruction.collapse': 'Hide content',
1948
+ 'instruction.copyBlock': 'Copy block',
1949
+ 'instruction.copyBlockAria': 'Copy instruction block #{seq}',
1950
+
1951
+ 'instruction.noSelection': 'Select a session first',
1952
+ 'instruction.noSelectionHint': 'Session data is read on demand; instruction blocks and the comparison are requested only after you pick a session.',
1953
+ 'instruction.compareFailed': 'Could not load the comparison',
1954
+ 'instruction.compareUnavailableTitle': 'Comparison unavailable',
1955
+ 'instruction.compareTitle': 'Files side vs session side',
1956
+ 'instruction.compareSubtitle': 'Delta = session-side bytes − files-side bytes; a positive value means the session side is larger.',
1957
+ 'instruction.compareFilesBytes': 'Files-side bytes',
1958
+ 'instruction.compareSessionBytes': 'Session-side bytes',
1959
+ 'instruction.compareDeltaBytes': 'Delta (positive = session side larger)',
1960
+ 'instruction.sameText': 'Same text',
1961
+ 'instruction.differentText': 'Different text',
1962
+ 'instruction.exactFilesYes': 'Files side exact',
1963
+ 'instruction.exactFilesNo': 'Files side approximate',
1964
+ 'instruction.sessionItemsValue': 'Session-side blocks: {count}',
1965
+ 'instruction.compareWhy': 'The two sides differ: the files side is a reconstruction under budget (files may be omitted, truncated, or deduplicated), while the session side is the exact text the host injected; the byte difference follows from that.',
1966
+ 'instruction.compareNote': 'Comparison note',
1967
+ },
1968
+ })
1969
+ ;
1970
+
1536
1971
  /* ---- i18n/meta.js ---- */
1537
1972
  ACC.addI18n({
1538
1973
  zh: {
@@ -4480,6 +4915,7 @@ ACC.l10n = (function createL10n() {
4480
4915
  id: 'agents',
4481
4916
  titleKey: 'nav.agents',
4482
4917
  order: 20,
4918
+ group: 'edit',
4483
4919
  render: (props) => h(AgentsPage, props),
4484
4920
  })
4485
4921
  })()
@@ -4953,168 +5389,1487 @@ ACC.l10n = (function createL10n() {
4953
5389
  ),
4954
5390
  },
4955
5391
  {
4956
- key: 'present',
4957
- label: t('diagnostics.status'),
4958
- render: (row) => h(C.Badge, { tone: row.present ? 'success' : 'warn' }, row.present ? t('diagnostics.capabilityPresent') : t('diagnostics.capabilityMissing')),
5392
+ key: 'present',
5393
+ label: t('diagnostics.status'),
5394
+ render: (row) => h(C.Badge, { tone: row.present ? 'success' : 'warn' }, row.present ? t('diagnostics.capabilityPresent') : t('diagnostics.capabilityMissing')),
5395
+ },
5396
+ ],
5397
+ rows: capabilities,
5398
+ rowKey: 'name',
5399
+ }),
5400
+ ),
5401
+ )
5402
+ }
5403
+
5404
+ /** @param {{ t: Function }} props */
5405
+ function DiagnosticsPage(props) {
5406
+ const { t } = props
5407
+ // The explicit Run button must not reuse a cached pass.
5408
+ const forceRun = ACC.useRef(false)
5409
+ const state = ACC.useAsync((context) => {
5410
+ const refresh = forceRun.current
5411
+ forceRun.current = false
5412
+ return ACC.api('diagnostics.run', refresh ? { refresh: true } : {}, context)
5413
+ }, [])
5414
+ const [statusFilter, setStatusFilter] = ACC.useState('')
5415
+ const [closedGroups, setClosedGroups] = ACC.useState({})
5416
+ const [fixTarget, setFixTarget] = ACC.useState(null)
5417
+ const [fixing, setFixing] = ACC.useState(null)
5418
+ const [fixReport, setFixReport] = ACC.useState(null)
5419
+ const [fixError, setFixError] = ACC.useState(null)
5420
+ const [exporting, setExporting] = ACC.useState(null)
5421
+ const [exported, setExported] = ACC.useState(null)
5422
+ const [exportError, setExportError] = ACC.useState(null)
5423
+
5424
+ const runFix = ACC.useCallback(async (id) => {
5425
+ setFixing(id)
5426
+ setFixError(null)
5427
+ setFixReport(null)
5428
+ try {
5429
+ const result = await ACC.api('diagnostics.fix', { id })
5430
+ setFixReport(result)
5431
+ state.reload()
5432
+ } catch (error) {
5433
+ setFixError(error)
5434
+ } finally {
5435
+ setFixing(null)
5436
+ setFixTarget(null)
5437
+ }
5438
+ }, [state.reload])
5439
+
5440
+ const runExport = ACC.useCallback(async (format) => {
5441
+ setExportError(null)
5442
+ setExporting(format)
5443
+ try {
5444
+ const result = await ACC.api('diagnostics.export', { format })
5445
+ const text = format === 'md' ? result.text : JSON.stringify(result.document, null, 2)
5446
+ setExported({ format, filename: result.filename, text })
5447
+ } catch (error) {
5448
+ setExportError(error)
5449
+ } finally {
5450
+ setExporting(null)
5451
+ }
5452
+ }, [])
5453
+
5454
+ if (state.status === 'loading') return h(C.Loading, { label: t('diagnostics.running') })
5455
+ if (state.status === 'error') return h(C.ErrorBox, { error: state.error, onRetry: state.reload, label: t('diagnostics.failed') })
5456
+
5457
+ const report = state.data || {}
5458
+ const filter = statusFilter
5459
+ const openGroups = {}
5460
+ for (const key of Object.keys(closedGroups)) openGroups[key] = !closedGroups[key]
5461
+ const fixTitle = fixTarget === null ? '' : t(`diagnostics.check.${fixTarget}`)
5462
+
5463
+ return h(
5464
+ 'div',
5465
+ { style: PAGE_STYLE },
5466
+ h(
5467
+ C.Card,
5468
+ {
5469
+ title: t('diagnostics.title'),
5470
+ subtitle: t('diagnostics.subtitle'),
5471
+ actions: [
5472
+ h(C.Btn, { key: 'run', tone: 'primary', onClick: () => { forceRun.current = true; state.reload() } }, t('diagnostics.run')),
5473
+ h(C.Btn, { key: 'md', disabled: exporting !== null, onClick: () => runExport('md') }, exporting === 'md' ? t('diagnostics.exporting') : t('diagnostics.exportMd')),
5474
+ h(C.Btn, { key: 'json', disabled: exporting !== null, onClick: () => runExport('json') }, exporting === 'json' ? t('diagnostics.exporting') : t('diagnostics.exportJson')),
5475
+ ],
5476
+ },
5477
+ h(
5478
+ 'div',
5479
+ { className: 'acc-row', style: { justifyContent: 'space-between' } },
5480
+ h('span', { className: 'acc-muted' }, `${t('diagnostics.generatedAt')}: ${report.generatedAt ? ACC.l10n.dateTime(report.generatedAt, t) : '—'}`),
5481
+ h('span', { className: 'acc-muted' }, report.cached === true ? t('diagnostics.cached') : t('diagnostics.fresh')),
5482
+ ),
5483
+ ),
5484
+ exportError ? h(C.ErrorBox, { error: exportError, label: t('diagnostics.exportFailed') }) : null,
5485
+ fixError ? h(C.ErrorBox, { error: fixError, label: t('diagnostics.fixFailed') }) : null,
5486
+ fixReport
5487
+ ? h(
5488
+ C.Notice,
5489
+ { tone: fixReport.fixed ? 'success' : 'warn' },
5490
+ h('div', null, `${t('diagnostics.fixDone')}: ${t(`diagnostics.check.${fixReport.id}`)}`),
5491
+ h('div', { className: 'acc-muted', style: { fontSize: '11px' } }, ACC.l10n.map(fixReport.fixed ? 'diagnostics.fixApplied' : 'diagnostics.fixNoChange')),
5492
+ ACC.l10n.raw(t('diagnostics.rawEvidence'), `${String(fixReport.action || '')}\n${String(fixReport.detail || '')}`),
5493
+ h(
5494
+ 'div',
5495
+ { className: 'acc-grid-2', style: { marginTop: '6px' } },
5496
+ h('div', null, h('div', { className: 'acc-muted' }, `${t('diagnostics.before')} · ${fixReport.before.status}`), h('div', { className: 'acc-mono' }, clip(fixReport.before.evidence, 200))),
5497
+ h('div', null, h('div', { className: 'acc-muted' }, `${t('diagnostics.after')} · ${fixReport.after.status}`), h('div', { className: 'acc-mono' }, clip(fixReport.after.evidence, 200))),
5498
+ ),
5499
+ fixReport.recheckedAt ? h('div', { className: 'acc-muted' }, `${t('diagnostics.rechecked')}: ${ACC.l10n.dateTime(fixReport.recheckedAt, t)}`) : null,
5500
+ )
5501
+ : null,
5502
+ state.data && state.data.items && state.data.items.length === 0
5503
+ ? h(C.Empty, {
5504
+ title: t('diagnostics.empty'),
5505
+ hint: t('diagnostics.emptyHint'),
5506
+ action: h(C.Btn, { tone: 'primary', onClick: state.reload }, t('diagnostics.run')),
5507
+ })
5508
+ : h(DiagnosticsBody, {
5509
+ report,
5510
+ t,
5511
+ statusFilter: filter,
5512
+ onStatus: setStatusFilter,
5513
+ openGroups,
5514
+ toggleGroup: (group) => setClosedGroups((previous) => ({ ...previous, [group]: !previous[group] })),
5515
+ expanded: (open) => {
5516
+ if (open) {
5517
+ setClosedGroups({})
5518
+ return
5519
+ }
5520
+ const next = {}
5521
+ for (const bucket of report.summary && Array.isArray(report.summary.groups) ? report.summary.groups : []) next[bucket.group] = true
5522
+ setClosedGroups(next)
5523
+ },
5524
+ onFix: (id) => setFixTarget(id),
5525
+ fixing,
5526
+ }),
5527
+ exported ? h(ExportDialog, { t, exported, onClose: () => setExported(null) }) : null,
5528
+ fixTarget === null
5529
+ ? null
5530
+ : h(
5531
+ C.Modal,
5532
+ {
5533
+ title: t('diagnostics.fixTitle'),
5534
+ onClose: () => setFixTarget(null),
5535
+ footer: h(
5536
+ 'div',
5537
+ { className: 'acc-row', style: { justifyContent: 'flex-end' } },
5538
+ h(C.Btn, { tone: 'ghost', onClick: () => setFixTarget(null) }, t('common.cancel')),
5539
+ h(C.Btn, { tone: 'primary', onClick: () => runFix(fixTarget) }, t('diagnostics.fixCta')),
5540
+ ),
5541
+ },
5542
+ h('p', { style: { margin: 0 } }, `${t('diagnostics.fixTarget')}: ${fixTitle}`),
5543
+ h(C.Notice, { tone: 'warn' }, t('diagnostics.fixConfirm')),
5544
+ h(C.Notice, { tone: 'info' }, t('diagnostics.fixScope')),
5545
+ ),
5546
+ )
5547
+ }
5548
+
5549
+ ACC.registerPage({
5550
+ id: 'diagnostics',
5551
+ titleKey: 'nav.diagnostics',
5552
+ order: 70,
5553
+ group: 'maintain',
5554
+ render: (props) => h(DiagnosticsPage, props),
5555
+ })
5556
+ })()
5557
+ ;
5558
+
5559
+ /* ---- pages/export.js ---- */
5560
+ /* Export page — read-only session export to Markdown or JSON.
5561
+ *
5562
+ * Data flow: `export.diagnostics` gates the page and supplies the policy note,
5563
+ * `export.sessions` feeds the picker, `export.summary` describes the selected
5564
+ * session, and `export.session` renders the payload. Any response may report
5565
+ * `{ available: false, reason, hint }`; that block is shown as given and never
5566
+ * replaced by a made-up result.
5567
+ *
5568
+ * Layout: the host scrolls the settings content column, so this page only adds
5569
+ * padding and vertical gaps. It never takes over height or overflow. Every
5570
+ * interactive control is a plain `acc-*` primitive or an ACC component.
5571
+ */
5572
+ (function exportPage() {
5573
+ const { useState, useEffect, useCallback, useRef } = React
5574
+
5575
+ const PAGE_STYLE = { display: 'flex', flexDirection: 'column', gap: '12px', padding: '8px 0' }
5576
+ const STACK_STYLE = { display: 'flex', flexDirection: 'column', gap: '10px', minWidth: 0 }
5577
+ const CLAMP_STYLE = { overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', minWidth: 0 }
5578
+ const MUTED_SMALL_STYLE = { color: 'var(--dsw-alias-label-tertiary, #81858c)', fontSize: '11px' }
5579
+
5580
+ const SEARCH_DEBOUNCE_MS = 250
5581
+ const SESSIONS_LIMIT = 50
5582
+ const DEFAULT_MAX_BYTES = 256 * 1024
5583
+ const MAX_BYTES_OPTIONS = [64 * 1024, 256 * 1024, 1024 * 1024]
5584
+ const FALLBACK_FORMATS = ['markdown', 'json']
5585
+
5586
+ /** @param {unknown} value @returns {boolean} */
5587
+ function hasText(value) {
5588
+ return typeof value === 'string' && value.length > 0
5589
+ }
5590
+
5591
+ /** @param {unknown} value @param {Function} t @returns {string} */
5592
+ function bytesText(value, t) {
5593
+ return typeof value === 'number' && Number.isFinite(value) ? ACC.fmt.bytes(value) : String(t('common.unknown'))
5594
+ }
5595
+
5596
+ /** @param {unknown} value @returns {string} */
5597
+ function numberText(value) {
5598
+ return typeof value === 'number' && Number.isFinite(value) ? ACC.fmt.num(value) : '—'
5599
+ }
5600
+
5601
+ /** @param {unknown} value @returns {string} */
5602
+ function timeText(value) {
5603
+ if (typeof value === 'number' && Number.isFinite(value)) return ACC.fmt.relTime(value)
5604
+ return hasText(value) ? ACC.fmt.relTime(value) : '—'
5605
+ }
5606
+
5607
+ /** @param {unknown} value @returns {string} */
5608
+ function dateTimeText(value) {
5609
+ return hasText(value) ? ACC.fmt.dateTime(value) : '—'
5610
+ }
5611
+
5612
+ /** @param {number} value @param {Function} t @returns {string} */
5613
+ function limitLabel(value, t) {
5614
+ if (value === 64 * 1024) return t('export.limit64')
5615
+ if (value === 256 * 1024) return t('export.limit256')
5616
+ if (value === 1024 * 1024) return t('export.limit1m')
5617
+ return ACC.fmt.bytes(value)
5618
+ }
5619
+
5620
+ /** @param {unknown} value @returns {string} */
5621
+ function formatLabel(value) {
5622
+ return value === 'json' ? 'JSON' : 'Markdown'
5623
+ }
5624
+
5625
+ /** @param {unknown} value @returns {string[]} host warning lines, never objects */
5626
+ function warningList(value) {
5627
+ if (!Array.isArray(value)) return []
5628
+ return value.map((entry) => String(entry)).filter((entry) => entry.length > 0)
5629
+ }
5630
+
5631
+ /**
5632
+ * Show a host `{available:false}` block verbatim: the reason and the next
5633
+ * step. A response without either field gets the localized fallback so an
5634
+ * unavailable capability is never rendered as an empty success.
5635
+ * @param {{ data?: unknown, t: Function }} props
5636
+ */
5637
+ function UnavailableNote(props) {
5638
+ const t = props.t
5639
+ const data = props.data !== null && typeof props.data === 'object' ? props.data : {}
5640
+ const reason = hasText(data.reason) ? data.reason : t('export.unknownReason')
5641
+ const hint = hasText(data.hint) ? data.hint : t('export.capabilityHint')
5642
+ return h(
5643
+ C.Notice,
5644
+ { tone: 'warn' },
5645
+ h(
5646
+ 'div',
5647
+ { style: STACK_STYLE },
5648
+ h('div', null, `${t('export.reasonLabel')}: ${reason}`),
5649
+ h('div', null, `${t('export.nextStepLabel')}: ${hint}`),
5650
+ ),
5651
+ )
5652
+ }
5653
+
5654
+ /**
5655
+ * The always-visible policy line: a localized read-only statement plus the
5656
+ * host's own `policy.note` when the diagnostics response carries one.
5657
+ * @param {{ policy?: unknown, t: Function }} props
5658
+ */
5659
+ function PolicyLine(props) {
5660
+ const t = props.t
5661
+ const policy = props.policy !== null && typeof props.policy === 'object' ? props.policy : null
5662
+ const hostNote = policy !== null && hasText(policy.note) ? policy.note : null
5663
+ return h(
5664
+ C.Notice,
5665
+ { tone: 'info' },
5666
+ h(
5667
+ 'div',
5668
+ { style: STACK_STYLE },
5669
+ h(
5670
+ 'div',
5671
+ { className: 'acc-row', style: { gap: '6px' } },
5672
+ h(C.Icon, { name: 'check', size: 14 }),
5673
+ h('span', null, t('export.policyNote')),
5674
+ ),
5675
+ hostNote === null ? null : h('span', { style: MUTED_SMALL_STYLE }, `${t('export.policySource')}: ${hostNote}`),
5676
+ ),
5677
+ )
5678
+ }
5679
+
5680
+ /**
5681
+ * Blob download helper. The anchor is never appended to the document, and
5682
+ * the object URL is revoked after the click so repeated downloads do not
5683
+ * leak URLs; pending timers are cleared on unmount.
5684
+ */
5685
+ function useDownload() {
5686
+ const timers = useRef([])
5687
+ useEffect(
5688
+ () => () => {
5689
+ for (const timer of timers.current) clearTimeout(timer)
5690
+ timers.current = []
5691
+ },
5692
+ [],
5693
+ )
5694
+ return useCallback((input) => {
5695
+ const blob = new Blob([input.text], { type: input.mime })
5696
+ const url = URL.createObjectURL(blob)
5697
+ const anchor = document.createElement('a')
5698
+ anchor.href = url
5699
+ anchor.download = input.filename
5700
+ anchor.click()
5701
+ const timer = setTimeout(() => URL.revokeObjectURL(url), 1000)
5702
+ timers.current.push(timer)
5703
+ }, [])
5704
+ }
5705
+
5706
+ /**
5707
+ * The interactive body. It is mounted only after diagnostics proved the
5708
+ * capability available, so every request here has a real host method behind
5709
+ * it and no component has to guess why the host said "no".
5710
+ * @param {{ t: Function, diagnostics: any }} props
5711
+ */
5712
+ function ExportBody(props) {
5713
+ const t = props.t
5714
+ const diagnostics = props.diagnostics
5715
+ const formats = Array.isArray(diagnostics.formats) && diagnostics.formats.length > 0 ? diagnostics.formats : FALLBACK_FORMATS
5716
+ const limits = diagnostics.limits !== null && typeof diagnostics.limits === 'object' ? diagnostics.limits : {}
5717
+ const initialFormat = formats.includes('markdown') ? 'markdown' : String(formats[0])
5718
+ const rawDefaultBytes = typeof limits.defaultBytes === 'number' && Number.isFinite(limits.defaultBytes) ? limits.defaultBytes : DEFAULT_MAX_BYTES
5719
+ const initialMaxBytes = MAX_BYTES_OPTIONS.includes(rawDefaultBytes) ? rawDefaultBytes : DEFAULT_MAX_BYTES
5720
+
5721
+ const [input, setInput] = useState('')
5722
+ const [query, setQuery] = useState('')
5723
+ const [selectedId, setSelectedId] = useState(null)
5724
+ const [format, setFormat] = useState(initialFormat)
5725
+ const [includeToolResults, setIncludeToolResults] = useState(diagnostics.includeToolResultsDefault !== false)
5726
+ const [maxBytes, setMaxBytes] = useState(initialMaxBytes)
5727
+ const [result, setResult] = useState(null)
5728
+ const [generating, setGenerating] = useState(false)
5729
+ const [generateError, setGenerateError] = useState(null)
5730
+ const [copyState, setCopyState] = useState('idle')
5731
+ const [downloadState, setDownloadState] = useState('idle')
5732
+ const controllerRef = useRef(null)
5733
+ const download = useDownload()
5734
+
5735
+ useEffect(() => {
5736
+ const timer = setTimeout(() => setQuery(input.trim()), SEARCH_DEBOUNCE_MS)
5737
+ return () => clearTimeout(timer)
5738
+ }, [input])
5739
+
5740
+ const feed = ACC.useAsync((context) => ACC.api('export.sessions', { limit: SESSIONS_LIMIT, query }, context), [query])
5741
+ const summary = ACC.useAsync(
5742
+ (context) => (selectedId === null ? Promise.resolve(null) : ACC.api('export.summary', { id: selectedId }, context)),
5743
+ [selectedId],
5744
+ )
5745
+
5746
+ const settingsKey = `${selectedId === null ? '' : selectedId}\u0000${format}\u0000${String(maxBytes)}\u0000${includeToolResults ? '1' : '0'}`
5747
+ useEffect(() => {
5748
+ setResult(null)
5749
+ setGenerateError(null)
5750
+ setCopyState('idle')
5751
+ setDownloadState('idle')
5752
+ if (controllerRef.current !== null) {
5753
+ controllerRef.current.abort()
5754
+ controllerRef.current = null
5755
+ }
5756
+ setGenerating(false)
5757
+ }, [settingsKey])
5758
+
5759
+ useEffect(
5760
+ () => () => {
5761
+ if (controllerRef.current !== null) controllerRef.current.abort()
5762
+ },
5763
+ [],
5764
+ )
5765
+
5766
+ useEffect(() => {
5767
+ if (copyState === 'idle' && downloadState === 'idle') return undefined
5768
+ const timer = setTimeout(() => {
5769
+ setCopyState('idle')
5770
+ setDownloadState('idle')
5771
+ }, 2000)
5772
+ return () => clearTimeout(timer)
5773
+ }, [copyState, downloadState])
5774
+
5775
+ const generate = useCallback(async () => {
5776
+ if (selectedId === null) return
5777
+ if (controllerRef.current !== null) controllerRef.current.abort()
5778
+ const controller = new AbortController()
5779
+ controllerRef.current = controller
5780
+ setGenerating(true)
5781
+ setGenerateError(null)
5782
+ setResult(null)
5783
+ setCopyState('idle')
5784
+ setDownloadState('idle')
5785
+ try {
5786
+ const data = await ACC.api(
5787
+ 'export.session',
5788
+ { id: selectedId, format, maxBytes, includeToolResults },
5789
+ { signal: controller.signal },
5790
+ )
5791
+ if (controllerRef.current === controller) setResult(data)
5792
+ } catch (error) {
5793
+ if (error !== null && error !== undefined && error.name === 'AbortError') return
5794
+ if (controllerRef.current === controller) {
5795
+ setGenerateError(error === null || error === undefined ? new Error(t('export.generateFailed')) : error)
5796
+ }
5797
+ } finally {
5798
+ if (controllerRef.current === controller) {
5799
+ controllerRef.current = null
5800
+ setGenerating(false)
5801
+ }
5802
+ }
5803
+ }, [selectedId, format, maxBytes, includeToolResults, t])
5804
+
5805
+ const copyResult = useCallback(() => {
5806
+ const text = result !== null && typeof result.text === 'string' ? result.text : ''
5807
+ if (text.length === 0) {
5808
+ setCopyState('failed')
5809
+ return
5810
+ }
5811
+ if (typeof navigator !== 'undefined' && navigator.clipboard && typeof navigator.clipboard.writeText === 'function') {
5812
+ navigator.clipboard.writeText(text).then(() => setCopyState('done'), () => setCopyState('failed'))
5813
+ return
5814
+ }
5815
+ setCopyState('failed')
5816
+ }, [result])
5817
+
5818
+ const downloadResult = useCallback(() => {
5819
+ if (result === null || typeof result.text !== 'string' || result.text.length === 0) {
5820
+ setDownloadState('failed')
5821
+ return
5822
+ }
5823
+ try {
5824
+ const extension = result.format === 'json' ? 'json' : 'md'
5825
+ const sourceId = result.sessionId === undefined || result.sessionId === null ? (selectedId === null ? '' : selectedId) : result.sessionId
5826
+ download({
5827
+ filename: `session-${String(sourceId).slice(0, 8)}.${extension}`,
5828
+ mime: result.format === 'json' ? 'application/json;charset=utf-8' : 'text/markdown;charset=utf-8',
5829
+ text: result.text,
5830
+ })
5831
+ setDownloadState('done')
5832
+ } catch {
5833
+ setDownloadState('failed')
5834
+ }
5835
+ }, [result, selectedId, download])
5836
+
5837
+ const feedData = feed.status === 'ready' && feed.data !== null && typeof feed.data === 'object' ? feed.data : null
5838
+ const items = feedData !== null && Array.isArray(feedData.items) ? feedData.items : []
5839
+ const total = feedData !== null && typeof feedData.total === 'number' ? feedData.total : items.length
5840
+ const summaryData = summary.status === 'ready' && summary.data !== null && typeof summary.data === 'object' ? summary.data : null
5841
+ const summaryReady = summaryData !== null && summaryData.available === true
5842
+ const resultData = result !== null && typeof result === 'object' ? result : null
5843
+
5844
+ /** One focusable session row; Enter/Space select it through native button semantics. */
5845
+ function renderSessionRow(row) {
5846
+ const rowData = row !== null && typeof row === 'object' ? row : {}
5847
+ const id = rowData.id === undefined || rowData.id === null ? '' : String(rowData.id)
5848
+ const active = selectedId === id
5849
+ const title = hasText(rowData.title) ? rowData.title : t('export.untitled')
5850
+ return h(
5851
+ 'button',
5852
+ {
5853
+ key: id.length > 0 ? id : title,
5854
+ type: 'button',
5855
+ className: `acc-list-item${active ? ' is-selected' : ''}`,
5856
+ 'aria-pressed': active,
5857
+ title: id,
5858
+ onClick: () => setSelectedId(id),
5859
+ style: { flexDirection: 'column', alignItems: 'stretch', gap: '3px' },
5860
+ },
5861
+ h(
5862
+ 'div',
5863
+ { className: 'acc-row', style: { gap: '6px', minWidth: 0 } },
5864
+ h('span', { style: { ...CLAMP_STYLE, flex: '1 1 auto', fontWeight: 600 } }, title),
5865
+ rowData.archived === true ? h(C.Badge, { tone: 'warn' }, t('export.archived')) : null,
5866
+ ),
5867
+ h(
5868
+ 'div',
5869
+ { className: 'acc-row', style: { gap: '8px' } },
5870
+ h('span', { style: MUTED_SMALL_STYLE }, timeText(rowData.updatedAt)),
5871
+ h(
5872
+ 'span',
5873
+ { style: MUTED_SMALL_STYLE },
5874
+ t('export.eventCount', { count: typeof rowData.eventCount === 'number' ? rowData.eventCount : '—' }),
5875
+ ),
5876
+ hasText(rowData.origin) ? h('span', { style: MUTED_SMALL_STYLE }, `${t('export.originLabel')}: ${rowData.origin}`) : null,
5877
+ ),
5878
+ )
5879
+ }
5880
+
5881
+ const pickerCard = h(
5882
+ C.Card,
5883
+ {
5884
+ title: t('export.pickTitle'),
5885
+ subtitle: feedData !== null && feedData.available === true
5886
+ ? `${t('export.sessionsCount', { shown: items.length, total })}${query.length > 0 ? ` · ${t('export.searchActive', { query })}` : ''}`
5887
+ : undefined,
5888
+ },
5889
+ h(
5890
+ 'div',
5891
+ { className: 'acc-row' },
5892
+ h('input', {
5893
+ className: 'acc-input acc-grow',
5894
+ type: 'search',
5895
+ value: input,
5896
+ placeholder: t('export.searchPlaceholder'),
5897
+ 'aria-label': t('export.searchAria'),
5898
+ onChange: (event) => setInput(event.target.value),
5899
+ onKeyDown: (event) => {
5900
+ if (event.key === 'Escape') setInput('')
5901
+ },
5902
+ }),
5903
+ input.length > 0 ? h(C.Btn, { tone: 'ghost', onClick: () => setInput('') }, t('export.searchClear')) : null,
5904
+ ),
5905
+ feed.status === 'loading'
5906
+ ? h(C.Loading, { label: t('export.loadingSessions') })
5907
+ : feed.status === 'error'
5908
+ ? h(C.ErrorBox, { error: feed.error, onRetry: feed.reload, label: t('export.loadFailedSessions') })
5909
+ : feedData !== null && feedData.available === false
5910
+ ? h(
5911
+ 'div',
5912
+ { style: STACK_STYLE },
5913
+ h(UnavailableNote, { data: feedData, t }),
5914
+ h('div', { className: 'acc-row' }, h(C.Btn, { onClick: feed.reload, icon: 'retry' }, t('common.retry'))),
5915
+ )
5916
+ : items.length === 0
5917
+ ? h(C.Empty, {
5918
+ title: query.length > 0 ? t('export.emptySearch') : t('export.emptySessions'),
5919
+ hint: query.length > 0 ? t('export.emptySearchHint') : t('export.emptySessionsHint'),
5920
+ action: h(
5921
+ 'div',
5922
+ { className: 'acc-row' },
5923
+ query.length > 0 ? h(C.Btn, { tone: 'ghost', onClick: () => setInput('') }, t('export.searchClear')) : null,
5924
+ h(C.Btn, { onClick: feed.reload, icon: 'retry' }, t('common.retry')),
5925
+ ),
5926
+ })
5927
+ : h('div', { className: 'acc-list', role: 'group', 'aria-label': t('export.sessionsListAria') }, items.map(renderSessionRow)),
5928
+ )
5929
+
5930
+ const settingsCard = h(
5931
+ C.Card,
5932
+ { title: t('export.settingsTitle'), subtitle: t('export.settingsHint') },
5933
+ h(
5934
+ 'div',
5935
+ { style: STACK_STYLE },
5936
+ h(
5937
+ 'div',
5938
+ { className: 'acc-field' },
5939
+ h('span', { className: 'acc-label' }, t('export.format')),
5940
+ h(
5941
+ 'div',
5942
+ { className: 'acc-tabs', role: 'tablist', 'aria-label': t('export.formatAria') },
5943
+ formats.map((entry) => {
5944
+ const value = String(entry)
5945
+ const active = format === value
5946
+ return h(
5947
+ 'button',
5948
+ {
5949
+ key: value,
5950
+ type: 'button',
5951
+ role: 'tab',
5952
+ 'aria-selected': active,
5953
+ className: `acc-tab${active ? ' is-active' : ''}`,
5954
+ onClick: () => setFormat(value),
5955
+ },
5956
+ value === 'json' ? t('export.formatJson') : value === 'markdown' ? t('export.formatMarkdown') : value,
5957
+ )
5958
+ }),
5959
+ ),
5960
+ ),
5961
+ h(
5962
+ 'label',
5963
+ { className: 'acc-row', style: { cursor: 'pointer', alignItems: 'flex-start' } },
5964
+ h('input', { type: 'checkbox', checked: includeToolResults, onChange: (event) => setIncludeToolResults(event.target.checked) }),
5965
+ h(
5966
+ 'span',
5967
+ { style: { display: 'flex', flexDirection: 'column', gap: '2px' } },
5968
+ h('span', null, t('export.includeToolResults')),
5969
+ h('span', { style: MUTED_SMALL_STYLE }, t('export.includeToolResultsHint')),
5970
+ ),
5971
+ ),
5972
+ h(
5973
+ 'div',
5974
+ { className: 'acc-field' },
5975
+ h('label', { className: 'acc-label', htmlFor: 'acc-export-max-bytes' }, t('export.maxBytes')),
5976
+ h(
5977
+ 'select',
5978
+ {
5979
+ id: 'acc-export-max-bytes',
5980
+ className: 'acc-select',
5981
+ value: String(maxBytes),
5982
+ 'aria-label': t('export.maxBytes'),
5983
+ onChange: (event) => setMaxBytes(Number(event.target.value)),
5984
+ },
5985
+ MAX_BYTES_OPTIONS.map((option) => h('option', { key: String(option), value: String(option) }, limitLabel(option, t))),
5986
+ ),
5987
+ h('span', { style: MUTED_SMALL_STYLE }, t('export.maxBytesHint')),
5988
+ ),
5989
+ ),
5990
+ )
5991
+
5992
+ const counts = summaryReady && summaryData.counts !== null && typeof summaryData.counts === 'object' ? summaryData.counts : {}
5993
+ const estimated = summaryReady && summaryData.estimatedBytes !== null && typeof summaryData.estimatedBytes === 'object' ? summaryData.estimatedBytes : {}
5994
+ const summaryWarnings = summaryReady ? warningList(summaryData.warnings) : []
5995
+ const summaryBlock = h(
5996
+ 'div',
5997
+ { style: STACK_STYLE },
5998
+ h(C.KeyValues, {
5999
+ items: [
6000
+ { label: t('export.countEvents'), value: numberText(counts.events) },
6001
+ { label: t('export.countUser'), value: numberText(counts.userMessages) },
6002
+ { label: t('export.countAssistant'), value: numberText(counts.assistantMessages) },
6003
+ { label: t('export.countToolCalls'), value: numberText(counts.toolCalls) },
6004
+ { label: t('export.countToolResults'), value: numberText(counts.toolResults) },
6005
+ { label: t('export.countToolErrors'), value: numberText(counts.toolErrors) },
6006
+ { label: t('export.countErrors'), value: numberText(counts.errors) },
6007
+ ],
6008
+ }),
6009
+ h(
6010
+ 'div',
6011
+ { className: 'acc-row' },
6012
+ h(C.Badge, { tone: 'neutral' }, `${t('export.estimatedMarkdown')}: ${bytesText(estimated.markdown, t)}`),
6013
+ h(C.Badge, { tone: 'neutral' }, `${t('export.estimatedJson')}: ${bytesText(estimated.json, t)}`),
6014
+ ),
6015
+ summaryWarnings.length === 0 ? null : h(C.Notice, { tone: 'info' }, `${t('export.warnings')}: ${summaryWarnings.join(' · ')}`),
6016
+ )
6017
+
6018
+ const resultWarnings = resultData !== null && resultData.available === true ? warningList(resultData.warnings) : []
6019
+ const generationBlock = generateError !== null
6020
+ ? h(C.ErrorBox, { error: generateError, onRetry: generate, label: t('export.generateFailed') })
6021
+ : resultData === null
6022
+ ? h(C.Notice, { tone: 'info' }, t('export.generateHint'))
6023
+ : resultData.available === false
6024
+ ? h(
6025
+ 'div',
6026
+ { style: STACK_STYLE },
6027
+ h(UnavailableNote, { data: resultData, t }),
6028
+ h('div', { className: 'acc-row' }, h(C.Btn, { onClick: generate, icon: 'retry' }, t('common.retry'))),
6029
+ )
6030
+ : h(
6031
+ 'div',
6032
+ { style: STACK_STYLE },
6033
+ h(C.KeyValues, {
6034
+ items: [
6035
+ { label: t('export.resultBytes'), value: bytesText(resultData.bytes, t) },
6036
+ { label: t('export.resultTotalBytes'), value: bytesText(resultData.totalBytes, t) },
6037
+ {
6038
+ label: t('export.truncated'),
6039
+ value: h(
6040
+ C.Badge,
6041
+ { tone: resultData.truncated === true ? 'warn' : 'success' },
6042
+ resultData.truncated === true ? t('export.truncatedYes') : t('export.truncatedNo'),
6043
+ ),
6044
+ },
6045
+ { label: t('export.omittedEvents'), value: numberText(resultData.omittedEvents) },
6046
+ { label: t('export.format'), value: formatLabel(resultData.format) },
6047
+ { label: t('export.generatedAt'), value: dateTimeText(resultData.generatedAt) },
6048
+ ],
6049
+ }),
6050
+ resultData.truncated === true
6051
+ ? h(C.Notice, { tone: 'warn' }, t('export.truncatedNotice', { count: numberText(resultData.omittedEvents) }))
6052
+ : null,
6053
+ resultWarnings.length === 0 ? null : h(C.Notice, { tone: 'info' }, `${t('export.warnings')}: ${resultWarnings.join(' · ')}`),
6054
+ h(
6055
+ 'div',
6056
+ { className: 'acc-row' },
6057
+ h(C.Btn, { tone: 'primary', onClick: copyResult }, copyState === 'done' ? t('export.copied') : t('export.copy')),
6058
+ h(C.Btn, { onClick: downloadResult }, downloadState === 'done' ? t('export.downloaded') : t('export.download')),
6059
+ h(
6060
+ 'span',
6061
+ { style: MUTED_SMALL_STYLE, 'aria-live': 'polite' },
6062
+ copyState === 'failed' ? t('export.copyFailed') : downloadState === 'failed' ? t('export.downloadFailed') : '',
6063
+ ),
6064
+ ),
6065
+ h(
6066
+ 'div',
6067
+ { style: STACK_STYLE },
6068
+ h('span', { className: 'acc-label' }, t('export.preview')),
6069
+ typeof resultData.text === 'string' && resultData.text.length > 0
6070
+ ? h(C.Code, { text: resultData.text })
6071
+ : h(C.Empty, { title: t('export.previewEmpty') }),
6072
+ ),
6073
+ )
6074
+
6075
+ const resultBody = selectedId === null
6076
+ ? h(C.Empty, { title: t('export.selectHint'), hint: t('export.selectHintHint') })
6077
+ : h(
6078
+ 'div',
6079
+ { style: STACK_STYLE },
6080
+ summary.status === 'loading'
6081
+ ? h(C.Loading, { label: t('export.summaryLoading') })
6082
+ : summary.status === 'error'
6083
+ ? h(C.ErrorBox, { error: summary.error, onRetry: summary.reload, label: t('export.summaryFailed') })
6084
+ : summaryReady
6085
+ ? h('div', { style: STACK_STYLE }, summaryBlock, generationBlock)
6086
+ : summaryData !== null && summaryData.available === false
6087
+ ? h(
6088
+ 'div',
6089
+ { style: STACK_STYLE },
6090
+ h(UnavailableNote, { data: summaryData, t }),
6091
+ h('div', { className: 'acc-row' }, h(C.Btn, { onClick: summary.reload, icon: 'retry' }, t('common.retry'))),
6092
+ )
6093
+ : null,
6094
+ )
6095
+
6096
+ const generateButton = h(
6097
+ C.Btn,
6098
+ {
6099
+ tone: 'primary',
6100
+ onClick: generate,
6101
+ disabled: selectedId === null || !summaryReady || generating,
6102
+ title: selectedId === null ? t('export.selectHint') : !summaryReady ? t('export.summaryLoading') : t('export.generateHint'),
6103
+ },
6104
+ generating ? t('export.generating') : t('export.generate'),
6105
+ )
6106
+
6107
+ return h(
6108
+ 'div',
6109
+ { style: STACK_STYLE },
6110
+ pickerCard,
6111
+ settingsCard,
6112
+ h(C.Card, { title: t('export.resultTitle'), subtitle: t('export.resultHint'), actions: generateButton }, resultBody),
6113
+ )
6114
+ }
6115
+
6116
+ /**
6117
+ * The capability reader. It runs only after the host's module registry
6118
+ * proved an `export` module is loaded, so `export.diagnostics` cannot fail
6119
+ * merely because an older plugin build never registered the methods.
6120
+ * @param {{ t: Function, moduleEntry: any }} props
6121
+ */
6122
+ function ExportCapability(props) {
6123
+ const t = props.t
6124
+ const moduleEntry = props.moduleEntry !== null && typeof props.moduleEntry === 'object' ? props.moduleEntry : {}
6125
+ const diagnostics = ACC.useAsync((context) => ACC.api('export.diagnostics', {}, context), [])
6126
+ const policy = diagnostics.status === 'ready' && diagnostics.data !== null && typeof diagnostics.data === 'object' ? diagnostics.data.policy : null
6127
+ const top = h(PolicyLine, { t, policy })
6128
+
6129
+ if (diagnostics.status === 'loading') {
6130
+ return h('div', { style: PAGE_STYLE }, top, h(C.Loading, { label: t('export.loading') }))
6131
+ }
6132
+
6133
+ if (diagnostics.status === 'error') {
6134
+ const failure = diagnostics.error !== null && typeof diagnostics.error === 'object' ? diagnostics.error : {}
6135
+ const hostHint = hasText(failure.hint) ? failure.hint : ''
6136
+ const errorForBox = {
6137
+ code: String(failure.code || failure.name || 'error'),
6138
+ message: hasText(failure.message) ? failure.message : t('export.loadFailed'),
6139
+ hint: hostHint.length > 0 ? hostHint : t('export.unavailableHint'),
6140
+ }
6141
+ return h(
6142
+ 'div',
6143
+ { style: PAGE_STYLE },
6144
+ top,
6145
+ h(C.Notice, { tone: 'warn' }, t('export.errorHint')),
6146
+ h(C.ErrorBox, { error: errorForBox, onRetry: diagnostics.reload, label: t('export.loadFailed') }),
6147
+ )
6148
+ }
6149
+
6150
+ const data = diagnostics.data !== null && typeof diagnostics.data === 'object' ? diagnostics.data : {}
6151
+ if (data.available !== true) {
6152
+ // The module probe knows why a loaded module is degraded; without it the
6153
+ // note falls back to the localized capability hint.
6154
+ const shown = { available: false, reason: hasText(data.reason) ? data.reason : moduleEntry.detail, hint: data.hint }
6155
+ return h(
6156
+ 'div',
6157
+ { style: PAGE_STYLE },
6158
+ top,
6159
+ h(
6160
+ 'div',
6161
+ { style: STACK_STYLE },
6162
+ h(UnavailableNote, { data: shown, t }),
6163
+ h('div', { className: 'acc-row' }, h(C.Btn, { onClick: diagnostics.reload, icon: 'retry' }, t('common.retry'))),
6164
+ ),
6165
+ )
6166
+ }
6167
+
6168
+ return h('div', { style: PAGE_STYLE }, top, h(ExportBody, { t, diagnostics: data }))
6169
+ }
6170
+
6171
+ /**
6172
+ * Page entry: read the host's module registry first and keep the policy line
6173
+ * on screen in every state. A host build without the `export` module gets an
6174
+ * explicit unavailable error with the next step instead of a request that
6175
+ * could only 404; a host that has the module proceeds to the capability
6176
+ * reader. Loading and failure stay distinct states too.
6177
+ * @param {{ t: Function }} props
6178
+ */
6179
+ function ExportPage(props) {
6180
+ const t = props.t
6181
+ const health = ACC.useAsync((context) => ACC.health(context), [])
6182
+ const top = h(PolicyLine, { t, policy: null })
6183
+
6184
+ if (health.status === 'loading') {
6185
+ return h('div', { style: PAGE_STYLE }, top, h(C.Loading, { label: t('export.loading') }))
6186
+ }
6187
+
6188
+ if (health.status === 'error') {
6189
+ return h('div', { style: PAGE_STYLE }, top, h(C.ErrorBox, { error: health.error, onRetry: health.reload, label: t('export.loadFailed') }))
6190
+ }
6191
+
6192
+ const healthData = health.data !== null && typeof health.data === 'object' ? health.data : {}
6193
+ const modules = Array.isArray(healthData.modules) ? healthData.modules : []
6194
+ const moduleEntry = modules.find((entry) => entry !== null && typeof entry === 'object' && entry.id === 'export')
6195
+
6196
+ if (moduleEntry === undefined) {
6197
+ const version = hasText(healthData.version) ? healthData.version : t('common.unknown')
6198
+ return h(
6199
+ 'div',
6200
+ { style: PAGE_STYLE },
6201
+ top,
6202
+ h(C.Notice, { tone: 'warn' }, t('export.errorHint')),
6203
+ h(C.ErrorBox, {
6204
+ error: { code: 'not_found', message: t('export.moduleMissing', { version }), hint: t('export.unavailableHint') },
6205
+ onRetry: health.reload,
6206
+ label: t('export.loadFailed'),
6207
+ }),
6208
+ )
6209
+ }
6210
+
6211
+ return h(ExportCapability, { t, moduleEntry })
6212
+ }
6213
+
6214
+ ACC.registerPage({
6215
+ id: 'export',
6216
+ titleKey: 'nav.export',
6217
+ descriptionKey: 'nav.desc.export',
6218
+ icon: 'download',
6219
+ order: 110,
6220
+ group: 'insight',
6221
+ render: (props) => h(ExportPage, props),
6222
+ })
6223
+ })()
6224
+ ;
6225
+
6226
+ /* ---- pages/instruction.js ---- */
6227
+ /* Instruction preview page (module J) — read-only view of what the model
6228
+ * received.
6229
+ *
6230
+ * Three views of the same instruction surface:
6231
+ * files — module A's chain discovery plus its rendered text: the
6232
+ * approximation the host can rebuild without a session;
6233
+ * session — the durable `agent-instructions` blocks of one session: the exact
6234
+ * text the host injected;
6235
+ * compare — byte and text comparison of the two sides, with the reason a
6236
+ * difference is expected.
6237
+ *
6238
+ * Nothing here writes an instruction file, resumes a session or invents text:
6239
+ * every `{available:false}` payload renders its reason and hint, and a thrown
6240
+ * request renders the shared error state with a retry. The settings content
6241
+ * column already scrolls and pads its content, so this page owns vertical
6242
+ * rhythm only and never claims height/overflow. */
6243
+ (function instructionPage() {
6244
+ /** Root rhythm: vertical only (the host owns padding and scrolling). */
6245
+ const PAGE_STYLE = { display: 'flex', flexDirection: 'column', gap: '16px', padding: '8px 0' }
6246
+ const STACK_STYLE = { display: 'flex', flexDirection: 'column', gap: '10px', minWidth: 0 }
6247
+ const BUDGET_STACK_STYLE = { display: 'flex', flexDirection: 'column', gap: '12px', minWidth: 0 }
6248
+ const BUDGET_ROW_STYLE = { display: 'flex', flexDirection: 'column', gap: '4px', minWidth: 0 }
6249
+ const FACT_STYLE = { display: 'flex', flexDirection: 'column', gap: '2px', minWidth: 0 }
6250
+ const FACT_LABEL_STYLE = { color: 'var(--dsw-alias-label-tertiary, #81858c)', font: '11px/16px var(--dsw-font-family, sans-serif)' }
6251
+ const FACT_VALUE_STYLE = { font: '600 18px/24px var(--dsw-font-family, sans-serif)', fontVariantNumeric: 'tabular-nums' }
6252
+ const MUTED_STYLE = { color: 'var(--dsw-alias-label-tertiary, #81858c)', font: '12px/18px var(--dsw-font-family, sans-serif)' }
6253
+ const BREAK_STYLE = { minWidth: 0, wordBreak: 'break-word' }
6254
+ const LIST_STYLE = { margin: 0, paddingInlineStart: '18px', color: 'var(--dsw-alias-label-secondary, #61666b)' }
6255
+
6256
+ /** Above this many characters a block starts collapsed to keep cards dense. */
6257
+ const LONG_BLOCK_CHARS = 900
6258
+ /** The session picker lists the host's first page of sessions. */
6259
+ const SESSION_PAGE_SIZE = 50
6260
+
6261
+ const VIEWS = [
6262
+ { id: 'files', labelKey: 'instruction.tabFiles' },
6263
+ { id: 'session', labelKey: 'instruction.tabSession' },
6264
+ { id: 'compare', labelKey: 'instruction.tabCompare' },
6265
+ ]
6266
+
6267
+ /** @param {unknown} value @returns {string} */
6268
+ function textOf(value) {
6269
+ return value === null || value === undefined ? '' : String(value)
6270
+ }
6271
+
6272
+ /** @param {unknown} value @returns {string} signed byte delta; positive means the session side is larger */
6273
+ function signedBytes(value, t) {
6274
+ if (typeof value !== 'number' || !Number.isFinite(value)) return t('common.unknown')
6275
+ if (value === 0) return ACC.l10n.bytes(0, t)
6276
+ return `${value > 0 ? '+' : '-'}${ACC.l10n.bytes(Math.abs(value), t)}`
6277
+ }
6278
+
6279
+ /** Localized label for a chain file's discovered source. @param {Function} t @param {unknown} source */
6280
+ function sourceLabel(t, source) {
6281
+ if (source === 'user-global') return t('instruction.sourceUserGlobal')
6282
+ if (source === 'project') return t('instruction.sourceProject')
6283
+ if (source === 'agents-home') return t('instruction.sourceAgentsHome')
6284
+ if (source === 'project-local') return t('instruction.sourceProjectLocal')
6285
+ return t('instruction.sourceUnknown')
6286
+ }
6287
+
6288
+ /** @param {unknown} source */
6289
+ function sourceTone(source) {
6290
+ return source === 'user-global' || source === 'agents-home' ? 'info' : 'neutral'
6291
+ }
6292
+
6293
+ /** Inline copy feedback (the host has no toast service). */
6294
+ function CopyButton(props) {
6295
+ const [state, setState] = ACC.useState('idle')
6296
+ const copy = ACC.useCallback(() => {
6297
+ const text = textOf(props.text)
6298
+ if (text.length === 0) {
6299
+ setState('failed')
6300
+ return
6301
+ }
6302
+ if (typeof navigator !== 'undefined' && navigator.clipboard && typeof navigator.clipboard.writeText === 'function') {
6303
+ navigator.clipboard.writeText(text).then(() => setState('done'), () => setState('failed'))
6304
+ return
6305
+ }
6306
+ setState('failed')
6307
+ }, [props.text])
6308
+ ACC.useEffect(() => {
6309
+ if (state === 'idle') return undefined
6310
+ const timer = setTimeout(() => setState('idle'), 1800)
6311
+ return () => clearTimeout(timer)
6312
+ }, [state])
6313
+ const label = state === 'done' ? props.t('instruction.copied') : state === 'failed' ? props.t('instruction.copyFailed') : props.label
6314
+ return h(C.Btn, { tone: 'ghost', onClick: copy, title: label, ariaLabel: props.ariaLabel || label }, label)
6315
+ }
6316
+
6317
+ /**
6318
+ * `{available:false}` body: reason and hint from the host, plus the original
6319
+ * text in the collapsible raw block when the English UI would show Chinese.
6320
+ * @param {{ data?: any, t: Function, onRetry?: Function }} props
6321
+ */
6322
+ function UnavailableBody(props) {
6323
+ const t = props.t
6324
+ const data = props.data !== null && typeof props.data === 'object' ? props.data : {}
6325
+ const reason = ACC.l10n.host('instruction.reasonGeneric', data.reason)
6326
+ const hint = ACC.l10n.host('instruction.hintGeneric', data.hint)
6327
+ const raw = [textOf(data.reason), textOf(data.hint)].filter((entry) => entry.length > 0).join('\n')
6328
+ return h(
6329
+ 'div',
6330
+ { style: STACK_STYLE },
6331
+ reason.length > 0
6332
+ ? h('div', { className: 'acc-row' }, h('span', { style: MUTED_STYLE }, `${t('common.reason')}:`), h('span', { style: BREAK_STYLE }, reason))
6333
+ : null,
6334
+ hint.length > 0
6335
+ ? h('div', { className: 'acc-row' }, h('span', { style: MUTED_STYLE }, `${t('instruction.hint')}:`), h('span', { style: BREAK_STYLE }, hint))
6336
+ : null,
6337
+ raw.length > 0 ? ACC.l10n.raw(t('instruction.rawHostText'), raw) : null,
6338
+ props.onRetry ? h(C.Toolbar, null, h(C.Btn, { icon: 'retry', onClick: props.onRetry }, t('common.retry'))) : null,
6339
+ )
6340
+ }
6341
+
6342
+ /** @param {{ data?: any, t: Function, title: string, onRetry?: Function }} props */
6343
+ function UnavailablePanel(props) {
6344
+ return h(C.Card, { title: props.title }, h(UnavailableBody, { data: props.data, t: props.t, onRetry: props.onRetry }))
6345
+ }
6346
+
6347
+ /** Budget bar for one chain: renderedBytes / maxBytes plus the fits badge. */
6348
+ function BudgetBar(props) {
6349
+ const t = props.t
6350
+ const chain = props.chain !== null && typeof props.chain === 'object' ? props.chain : {}
6351
+ const renderedBytes = typeof chain.renderedBytes === 'number' && Number.isFinite(chain.renderedBytes) ? chain.renderedBytes : null
6352
+ const rawBytes = typeof chain.bytes === 'number' && Number.isFinite(chain.bytes) ? chain.bytes : null
6353
+ // Module A reports per-chain maxima in some deployments and one top-level
6354
+ // maximum in others; either source is authoritative, never a guessed value.
6355
+ const maxBytes = typeof chain.maxBytes === 'number' && Number.isFinite(chain.maxBytes) && chain.maxBytes > 0
6356
+ ? chain.maxBytes
6357
+ : typeof props.maxBytes === 'number' && Number.isFinite(props.maxBytes) && props.maxBytes > 0
6358
+ ? props.maxBytes
6359
+ : null
6360
+ const files = typeof chain.files === 'number' && Number.isFinite(chain.files) ? chain.files : null
6361
+ const fits = chain.fits === true
6362
+ const ratio = renderedBytes !== null && maxBytes !== null ? Math.max(0, Math.min(1, renderedBytes / maxBytes)) : null
6363
+ const usage = renderedBytes !== null && maxBytes !== null
6364
+ ? t('instruction.budgetUsage', { rendered: ACC.l10n.bytes(renderedBytes, t), max: ACC.l10n.bytes(maxBytes, t) })
6365
+ : t('common.unknown')
6366
+ return h(
6367
+ 'div',
6368
+ { style: BUDGET_ROW_STYLE },
6369
+ h(
6370
+ 'div',
6371
+ { className: 'acc-row', style: { justifyContent: 'space-between' } },
6372
+ h('span', null, props.label),
6373
+ h('span', { className: 'acc-muted', style: { fontVariantNumeric: 'tabular-nums' } }, usage),
6374
+ ),
6375
+ ratio === null
6376
+ ? null
6377
+ : h(
6378
+ 'div',
6379
+ { className: 'acc-bar', role: 'img', 'aria-label': `${props.label}: ${usage} · ${fits ? t('instruction.budgetFits') : t('instruction.budgetOver')}` },
6380
+ h('div', { className: `acc-bar-fill${fits ? '' : ' is-warn'}`, style: { width: `${Math.round(ratio * 100)}%` } }),
6381
+ ),
6382
+ h(
6383
+ 'div',
6384
+ { className: 'acc-row', style: { gap: '6px' } },
6385
+ h(C.Badge, { tone: fits ? 'success' : 'warn' }, fits ? t('instruction.budgetFits') : t('instruction.budgetOver')),
6386
+ rawBytes !== null ? h('span', { style: MUTED_STYLE }, t('instruction.budgetRaw', { bytes: ACC.l10n.bytes(rawBytes, t) })) : null,
6387
+ files !== null ? h('span', { style: MUTED_STYLE }, t('instruction.chainFilesCount', { count: ACC.fmt.num(files) })) : null,
6388
+ ),
6389
+ )
6390
+ }
6391
+
6392
+ /** One badge per chain flag the host set on a file row. */
6393
+ function FileFlags(props) {
6394
+ const t = props.t
6395
+ const row = props.row !== null && typeof props.row === 'object' ? props.row : {}
6396
+ const badges = []
6397
+ if (row.inEffectiveChain === true) badges.push(h(C.Badge, { key: 'effective', tone: 'success' }, t('instruction.badgeEffective')))
6398
+ if (row.deduped === true) {
6399
+ badges.push(
6400
+ h(
6401
+ C.Badge,
6402
+ { key: 'deduped', tone: 'neutral', title: row.dedupedBy ? t('instruction.badgeDedupedBy', { path: textOf(row.dedupedBy) }) : undefined },
6403
+ t('instruction.badgeDeduped'),
6404
+ ),
6405
+ )
6406
+ }
6407
+ if (row.budgetOmitted === true) badges.push(h(C.Badge, { key: 'omitted', tone: 'warn' }, t('instruction.badgeOmitted')))
6408
+ if (row.budgetTruncated === true) badges.push(h(C.Badge, { key: 'truncated', tone: 'danger' }, t('instruction.badgeTruncated')))
6409
+ if (badges.length === 0) return h('span', { className: 'acc-cell-empty' }, t('common.none'))
6410
+ return h('div', { className: 'acc-row', style: { gap: '4px' } }, badges)
6411
+ }
6412
+
6413
+ /** Chain rows: display path, source, bytes and the budget/dedup flags. */
6414
+ function ChainTable(props) {
6415
+ const t = props.t
6416
+ return h(C.Table, {
6417
+ columns: [
6418
+ {
6419
+ key: 'displayPath',
6420
+ label: t('instruction.displayPath'),
6421
+ render: (row) => h(C.Mono, { text: textOf(row.displayPath) || textOf(row.path) || '—', title: textOf(row.path) || undefined }),
6422
+ },
6423
+ { key: 'source', label: t('instruction.source'), render: (row) => h(C.Badge, { tone: sourceTone(row.source) }, sourceLabel(t, row.source)) },
6424
+ { key: 'bytes', label: t('common.bytes'), align: 'right', render: (row) => ACC.l10n.bytes(row.bytes, t) },
6425
+ { key: 'flags', label: t('instruction.flags'), render: (row) => h(FileFlags, { row, t }) },
6426
+ ],
6427
+ rows: Array.isArray(props.files) ? props.files : [],
6428
+ rowKey: 'path',
6429
+ empty: h(C.Empty, { title: t('instruction.chainEmpty'), hint: t('instruction.chainEmptyHint') }),
6430
+ })
6431
+ }
6432
+
6433
+ /** Chain warnings are host free text: listed in Chinese, disclosed raw in English. */
6434
+ function ChainWarnings(props) {
6435
+ const t = props.t
6436
+ const warnings = props.warnings.map(textOf).filter((entry) => entry.length > 0)
6437
+ if (warnings.length === 0) return null
6438
+ if (ACC.l10n.lang() === 'en' && ACC.l10n.hasCjk(warnings.join(''))) {
6439
+ return ACC.l10n.raw(t('instruction.rawHostText'), warnings.join('\n'))
6440
+ }
6441
+ return h(
6442
+ 'div',
6443
+ { style: STACK_STYLE },
6444
+ h('div', { className: 'acc-muted' }, t('instruction.chainWarnings')),
6445
+ h('ul', { style: LIST_STYLE }, warnings.map((warning, index) => h('li', { key: String(index) }, warning))),
6446
+ )
6447
+ }
6448
+
6449
+ /** Files view, first card: discovery rows plus the budget bars. */
6450
+ function ChainCard(props) {
6451
+ const t = props.t
6452
+ const chain = props.chain
6453
+ const chains = chain.chains !== null && typeof chain.chains === 'object' ? chain.chains : {}
6454
+ const budget = chain.budget !== null && typeof chain.budget === 'object' ? chain.budget : {}
6455
+ const files = Array.isArray(chain.files) ? chain.files : []
6456
+ const warnings = Array.isArray(chain.warnings) ? chain.warnings : []
6457
+ const maxBytes = typeof budget.maxBytes === 'number' && Number.isFinite(budget.maxBytes) ? budget.maxBytes : null
6458
+ const budgetSource = textOf(budget.source)
6459
+ const cwd = textOf(chain.cwd)
6460
+ const projectRoot = textOf(chain.projectRoot)
6461
+ const cwdSource = textOf(chain.cwdSource)
6462
+ return h(
6463
+ C.Card,
6464
+ {
6465
+ title: t('instruction.chainTitle'),
6466
+ subtitle: t('instruction.chainFilesCount', { count: ACC.fmt.num(files.length) }),
6467
+ actions: h(
6468
+ 'div',
6469
+ { className: 'acc-row' },
6470
+ h(C.Btn, { tone: 'ghost', icon: 'retry', onClick: props.reload, title: t('common.refresh'), ariaLabel: t('common.refresh') }, t('common.refresh')),
6471
+ ),
6472
+ },
6473
+ h(
6474
+ 'div',
6475
+ { style: BUDGET_STACK_STYLE },
6476
+ h(BudgetBar, { label: t('instruction.chainUserGlobal'), chain: chains.userGlobal, maxBytes, t }),
6477
+ h(BudgetBar, { label: t('instruction.chainProject'), chain: chains.project, maxBytes, t }),
6478
+ ),
6479
+ h(C.KeyValues, {
6480
+ items: [
6481
+ { label: t('instruction.chainCwd'), value: cwd.length > 0 ? h(C.Mono, { text: cwd }) : t('common.unknown') },
6482
+ { label: t('instruction.chainProjectRoot'), value: projectRoot.length > 0 ? h(C.Mono, { text: projectRoot }) : t('common.unknown') },
6483
+ { label: t('instruction.chainSource'), value: cwdSource.length > 0 ? cwdSource : t('common.unknown') },
6484
+ {
6485
+ label: t('instruction.budgetSource'),
6486
+ value: budgetSource.length > 0
6487
+ ? budgetSource
6488
+ : maxBytes !== null
6489
+ ? `${t('instruction.budgetUsage', { rendered: ACC.l10n.bytes(0, t), max: ACC.l10n.bytes(maxBytes, t) })}`
6490
+ : t('instruction.budgetSourceUnknown'),
6491
+ },
6492
+ ],
6493
+ }),
6494
+ h(ChainWarnings, { warnings, t }),
6495
+ chain.truncated === true ? h(C.Notice, { tone: 'warn' }, t('instruction.chainTruncated')) : null,
6496
+ h(ChainTable, { files, t }),
6497
+ )
6498
+ }
6499
+
6500
+ /** Files view, second card: the rendered text (approximation) plus byte count. */
6501
+ function PreviewCard(props) {
6502
+ const t = props.t
6503
+ const preview = props.preview !== null && typeof props.preview === 'object' ? props.preview : null
6504
+ if (preview === null) return null
6505
+ if (preview.available !== true) {
6506
+ return h(C.Card, { title: t('instruction.previewTitle') }, h(UnavailableBody, { data: preview, t, onRetry: props.reload }))
6507
+ }
6508
+ const text = typeof preview.text === 'string' ? preview.text : ''
6509
+ const exact = preview.exact === true
6510
+ const bytes = typeof preview.bytes === 'number' && Number.isFinite(preview.bytes) ? preview.bytes : null
6511
+ const sections = Array.isArray(preview.sections) ? preview.sections : []
6512
+ const omitted = Array.isArray(preview.omitted) ? preview.omitted : []
6513
+ const truncated = Array.isArray(preview.truncated) ? preview.truncated : []
6514
+ const note = ACC.l10n.host('instruction.previewNote', preview.note)
6515
+ const actions = h(
6516
+ 'div',
6517
+ { className: 'acc-row' },
6518
+ h(
6519
+ C.Badge,
6520
+ { tone: exact ? 'success' : 'warn', title: exact ? t('instruction.previewExact') : t('instruction.previewApprox') },
6521
+ exact ? t('instruction.exact') : t('instruction.approximate'),
6522
+ ),
6523
+ bytes !== null ? h('span', { className: 'acc-muted', style: { fontVariantNumeric: 'tabular-nums' } }, t('instruction.previewBytes', { bytes: ACC.l10n.bytes(bytes, t) })) : null,
6524
+ text.length > 0 ? h(CopyButton, { text, t, label: t('instruction.copyPreview') }) : null,
6525
+ )
6526
+ return h(
6527
+ C.Card,
6528
+ { title: t('instruction.previewTitle'), actions },
6529
+ h(
6530
+ 'div',
6531
+ { style: STACK_STYLE },
6532
+ text.length > 0 ? h(C.Code, { text }) : h(C.Empty, { title: t('instruction.previewEmpty'), hint: t('instruction.previewEmptyHint') }),
6533
+ sections.length > 0 ? h('div', { style: { ...MUTED_STYLE, fontSize: '11px' } }, t('instruction.previewSections', { count: ACC.fmt.num(sections.length) })) : null,
6534
+ omitted.length > 0 ? h(C.Notice, { tone: 'warn' }, t('instruction.previewOmitted', { count: ACC.fmt.num(omitted.length) })) : null,
6535
+ truncated.length > 0 ? h(C.Notice, { tone: 'warn' }, t('instruction.previewTruncated', { count: ACC.fmt.num(truncated.length) })) : null,
6536
+ preview.responseTruncated === true ? h(C.Notice, { tone: 'warn' }, t('instruction.previewResponseTruncated')) : null,
6537
+ note.length > 0 ? h('div', { style: MUTED_STYLE }, note) : null,
6538
+ ACC.l10n.raw(t('instruction.rawHostText'), preview.note),
6539
+ ),
6540
+ )
6541
+ }
6542
+
6543
+ /** Files view: discovery and rendering are independent requests. */
6544
+ function FilesView(props) {
6545
+ const t = props.t
6546
+ const state = ACC.useAsync(
6547
+ (context) => Promise.all([ACC.api('instruction.chain', {}, context), ACC.api('instruction.preview', {}, context)]),
6548
+ [],
6549
+ )
6550
+ if (state.status === 'loading') return h(C.Loading, { label: t('common.loading') })
6551
+ if (state.status === 'error') return h(C.ErrorBox, { error: state.error, onRetry: state.reload, label: t('instruction.failed') })
6552
+ const pair = Array.isArray(state.data) ? state.data : []
6553
+ const chain = pair[0]
6554
+ const preview = pair[1]
6555
+ return h(
6556
+ 'div',
6557
+ { style: STACK_STYLE },
6558
+ chain !== null && typeof chain === 'object' && chain.available === true
6559
+ ? h(ChainCard, { chain, t, reload: state.reload })
6560
+ : h(UnavailablePanel, { data: chain, t, title: t('instruction.chainUnavailableTitle'), onRetry: state.reload }),
6561
+ h(PreviewCard, { preview, t, reload: state.reload }),
6562
+ )
6563
+ }
6564
+
6565
+ /** Host session rows; `items` is the documented field, `rows` a tolerated alias. */
6566
+ function sessionItems(feed) {
6567
+ if (feed === null || feed === undefined || feed.status !== 'ready') return []
6568
+ const data = feed.data
6569
+ if (data === null || typeof data !== 'object') return []
6570
+ const list = Array.isArray(data.items) ? data.items : Array.isArray(data.rows) ? data.rows : []
6571
+ return list.filter((row) => row !== null && typeof row === 'object' && typeof row.id === 'string' && row.id.length > 0)
6572
+ }
6573
+
6574
+ /** Picker label: the title when the host has one, never a fabricated id title. */
6575
+ function sessionOptionLabel(row, t) {
6576
+ const title = typeof row.title === 'string' && row.title.length > 0 ? row.title : t('instruction.untitled')
6577
+ const at = typeof row.updatedAt === 'number' && Number.isFinite(row.updatedAt) ? ACC.l10n.dateTime(row.updatedAt, t) : ''
6578
+ return at.length > 0 && at !== t('common.unknown') ? `${title} · ${at}` : title
6579
+ }
6580
+
6581
+ /** Session picker shared by the session and compare views. */
6582
+ function SessionPickerCard(props) {
6583
+ const t = props.t
6584
+ const feed = props.feed
6585
+ const items = sessionItems(feed)
6586
+ const data = feed !== null && feed !== undefined && feed.status === 'ready' ? feed.data : null
6587
+ const unavailable = data !== null && typeof data === 'object' && data.available === false
6588
+ let body = null
6589
+ if (feed === undefined || feed === null) body = null
6590
+ else if (feed.status === 'loading') body = h(C.Loading, { label: t('common.loading') })
6591
+ else if (feed.status === 'error') body = h(C.ErrorBox, { error: feed.error, onRetry: feed.reload, label: t('instruction.sessionsFailed') })
6592
+ else if (unavailable) body = h(UnavailableBody, { data, t, onRetry: feed.reload })
6593
+ else if (items.length === 0) {
6594
+ body = h(C.Empty, {
6595
+ title: t('instruction.sessionsEmpty'),
6596
+ hint: t('instruction.sessionsEmptyHint'),
6597
+ action: h(C.Btn, { onClick: feed.reload }, t('common.refresh')),
6598
+ })
6599
+ } else {
6600
+ body = h(
6601
+ 'div',
6602
+ { className: 'acc-row' },
6603
+ h(
6604
+ 'select',
6605
+ {
6606
+ className: 'acc-select',
6607
+ value: props.value,
6608
+ 'aria-label': t('instruction.sessionPickAria'),
6609
+ onChange: (event) => props.onChange(event.target.value),
6610
+ },
6611
+ h('option', { value: '' }, t('instruction.sessionPick')),
6612
+ items.map((row) => h('option', { key: row.id, value: row.id }, sessionOptionLabel(row, t))),
6613
+ ),
6614
+ h('span', { className: 'acc-muted', style: { fontVariantNumeric: 'tabular-nums' } }, t('instruction.sessionListLoaded', { count: ACC.fmt.num(items.length) })),
6615
+ )
6616
+ }
6617
+ return h(
6618
+ C.Card,
6619
+ {
6620
+ title: t('instruction.sessionPickTitle'),
6621
+ subtitle: t('instruction.sessionPickHint'),
6622
+ actions: feed === undefined || feed === null
6623
+ ? null
6624
+ : h(C.Btn, { tone: 'ghost', icon: 'retry', onClick: feed.reload, title: t('instruction.sessionListRefresh'), ariaLabel: t('instruction.sessionListRefresh') }, t('common.refresh')),
6625
+ },
6626
+ body,
6627
+ )
6628
+ }
6629
+
6630
+ /** One durable instruction block, collapsible when the text is long. */
6631
+ function InstructionBlock(props) {
6632
+ const t = props.t
6633
+ const item = props.item !== null && typeof props.item === 'object' ? props.item : {}
6634
+ const text = typeof item.text === 'string' ? item.text : ''
6635
+ const truncated = item.truncated === true
6636
+ const long = text.length > LONG_BLOCK_CHARS
6637
+ const [open, setOpen] = ACC.useState(!long)
6638
+ const seqText = typeof item.seq === 'number' ? ACC.fmt.num(item.seq) : textOf(item.seq)
6639
+ const bytesText = ACC.l10n.bytes(item.bytes, t)
6640
+ return h(
6641
+ C.Card,
6642
+ {
6643
+ title: t('instruction.blockTitle', { seq: seqText }),
6644
+ subtitle: `${t('instruction.blockTime')}: ${ACC.l10n.dateTime(item.at, t)} · ${bytesText}`,
6645
+ actions: h(
6646
+ 'div',
6647
+ { className: 'acc-row' },
6648
+ h(C.Badge, { tone: item.baseline === true ? 'success' : 'neutral' }, item.baseline === true ? t('instruction.baseline') : t('instruction.change')),
6649
+ truncated ? h(C.Badge, { tone: 'warn' }, t('instruction.blockTruncated')) : null,
6650
+ text.length > 0 ? h(CopyButton, { text, t, label: t('instruction.copyBlock'), ariaLabel: t('instruction.copyBlockAria', { seq: seqText }) }) : null,
6651
+ long
6652
+ ? h(
6653
+ 'button',
6654
+ {
6655
+ type: 'button',
6656
+ className: 'acc-btn acc-btn-ghost',
6657
+ 'aria-expanded': open,
6658
+ onClick: () => setOpen((value) => !value),
4959
6659
  },
4960
- ],
4961
- rows: capabilities,
4962
- rowKey: 'name',
4963
- }),
4964
- ),
6660
+ h('span', { 'aria-hidden': 'true' }, open ? '▾' : '▸'),
6661
+ open ? t('instruction.collapse') : t('instruction.expand'),
6662
+ )
6663
+ : null,
6664
+ ),
6665
+ },
6666
+ open
6667
+ ? h(
6668
+ 'div',
6669
+ { style: STACK_STYLE },
6670
+ text.length > 0 ? h(C.Code, { text }) : h('div', { className: 'acc-muted' }, t('instruction.blockEmpty')),
6671
+ truncated ? h(C.Notice, { tone: 'warn' }, t('instruction.blockTruncatedHint')) : null,
6672
+ )
6673
+ : h('div', { className: 'acc-muted' }, t('instruction.blockCollapsed', { bytes: bytesText })),
4965
6674
  )
4966
6675
  }
4967
6676
 
4968
- /** @param {{ t: Function }} props */
4969
- function DiagnosticsPage(props) {
4970
- const { t } = props
4971
- // The explicit Run button must not reuse a cached pass.
4972
- const forceRun = ACC.useRef(false)
4973
- const state = ACC.useAsync((context) => {
4974
- const refresh = forceRun.current
4975
- forceRun.current = false
4976
- return ACC.api('diagnostics.run', refresh ? { refresh: true } : {}, context)
4977
- }, [])
4978
- const [statusFilter, setStatusFilter] = ACC.useState('')
4979
- const [closedGroups, setClosedGroups] = ACC.useState({})
4980
- const [fixTarget, setFixTarget] = ACC.useState(null)
4981
- const [fixing, setFixing] = ACC.useState(null)
4982
- const [fixReport, setFixReport] = ACC.useState(null)
4983
- const [fixError, setFixError] = ACC.useState(null)
4984
- const [exporting, setExporting] = ACC.useState(null)
4985
- const [exported, setExported] = ACC.useState(null)
4986
- const [exportError, setExportError] = ACC.useState(null)
4987
-
4988
- const runFix = ACC.useCallback(async (id) => {
4989
- setFixing(id)
4990
- setFixError(null)
4991
- setFixReport(null)
4992
- try {
4993
- const result = await ACC.api('diagnostics.fix', { id })
4994
- setFixReport(result)
4995
- state.reload()
4996
- } catch (error) {
4997
- setFixError(error)
4998
- } finally {
4999
- setFixing(null)
5000
- setFixTarget(null)
5001
- }
5002
- }, [state.reload])
5003
-
5004
- const runExport = ACC.useCallback(async (format) => {
5005
- setExportError(null)
5006
- setExporting(format)
5007
- try {
5008
- const result = await ACC.api('diagnostics.export', { format })
5009
- const text = format === 'md' ? result.text : JSON.stringify(result.document, null, 2)
5010
- setExported({ format, filename: result.filename, text })
5011
- } catch (error) {
5012
- setExportError(error)
5013
- } finally {
5014
- setExporting(null)
6677
+ /** Session view: picker plus the exact instruction blocks of the picked session. */
6678
+ function SessionView(props) {
6679
+ const t = props.t
6680
+ const state = ACC.useAsync(
6681
+ (context) => (props.sessionId.length === 0 ? null : ACC.api('instruction.session', { sessionId: props.sessionId }, context)),
6682
+ [props.sessionId],
6683
+ )
6684
+ let content = null
6685
+ if (props.sessionId.length === 0) {
6686
+ content = h(C.Empty, { title: t('instruction.noSelection'), hint: t('instruction.noSelectionHint') })
6687
+ } else if (state.status === 'loading') {
6688
+ content = h(C.Loading, { label: t('common.loading') })
6689
+ } else if (state.status === 'error') {
6690
+ content = h(C.ErrorBox, { error: state.error, onRetry: state.reload, label: t('instruction.sessionFailed') })
6691
+ } else {
6692
+ const data = state.data
6693
+ if (data === null || typeof data !== 'object') {
6694
+ content = h(C.Empty, { title: t('instruction.noSelection'), hint: t('instruction.noSelectionHint') })
6695
+ } else if (data.available !== true) {
6696
+ content = h(UnavailablePanel, { data, t, title: t('instruction.sessionUnavailableTitle'), onRetry: state.reload })
6697
+ } else {
6698
+ const items = Array.isArray(data.items) ? data.items : []
6699
+ const reason = ACC.l10n.host('instruction.sessionReason', data.reason)
6700
+ content = h(
6701
+ 'div',
6702
+ { style: STACK_STYLE },
6703
+ h(
6704
+ 'div',
6705
+ { className: 'acc-row', style: { justifyContent: 'space-between' } },
6706
+ h('span', { className: 'acc-muted' }, t('instruction.sessionInstructionCount', { count: ACC.fmt.num(items.length) })),
6707
+ h(
6708
+ 'span',
6709
+ { className: 'acc-row', style: { gap: '4px' } },
6710
+ h('span', { style: MUTED_STYLE }, `${t('instruction.sessionId')}:`),
6711
+ h(C.Mono, { text: props.sessionId, title: props.sessionId, className: 'acc-muted' }),
6712
+ ),
6713
+ ),
6714
+ reason.length > 0 ? h('div', { style: MUTED_STYLE }, `${t('instruction.sessionReason')}: ${reason}`) : null,
6715
+ items.length === 0
6716
+ ? h(C.Empty, { title: t('instruction.sessionEmpty'), hint: t('instruction.sessionEmptyHint') })
6717
+ : h(
6718
+ 'div',
6719
+ { style: STACK_STYLE },
6720
+ h('h3', { className: 'acc-section-title' }, t('instruction.sessionBlocksTitle')),
6721
+ items.map((item, index) => h(InstructionBlock, { key: `${textOf(item.seq)}-${index}`, item, t })),
6722
+ ),
6723
+ )
5015
6724
  }
5016
- }, [])
5017
-
5018
- if (state.status === 'loading') return h(C.Loading, { label: t('diagnostics.running') })
5019
- if (state.status === 'error') return h(C.ErrorBox, { error: state.error, onRetry: state.reload, label: t('diagnostics.failed') })
6725
+ }
6726
+ return h(
6727
+ 'div',
6728
+ { style: STACK_STYLE },
6729
+ h(SessionPickerCard, { feed: props.sessions, value: props.sessionId, onChange: props.onSelect, t }),
6730
+ content,
6731
+ )
6732
+ }
5020
6733
 
5021
- const report = state.data || {}
5022
- const filter = statusFilter
5023
- const openGroups = {}
5024
- for (const key of Object.keys(closedGroups)) openGroups[key] = !closedGroups[key]
5025
- const fixTitle = fixTarget === null ? '' : t(`diagnostics.check.${fixTarget}`)
6734
+ /** One headline number in the comparison grid. */
6735
+ function CompareStat(props) {
6736
+ return h('div', { style: FACT_STYLE }, h('span', { style: FACT_LABEL_STYLE }, props.label), h('strong', { style: FACT_VALUE_STYLE }, props.value))
6737
+ }
5026
6738
 
6739
+ /** Comparison result: three byte counts, text/format badges and one explanation. */
6740
+ function CompareResult(props) {
6741
+ const t = props.t
6742
+ const data = props.data
6743
+ const same = data.sameText === true
6744
+ const exactFiles = data.exactFiles === true
6745
+ const sessionItems = typeof data.sessionItems === 'number' && Number.isFinite(data.sessionItems) ? data.sessionItems : null
6746
+ const note = ACC.l10n.host('instruction.compareNote', data.note)
5027
6747
  return h(
5028
- 'div',
5029
- { style: PAGE_STYLE },
6748
+ C.Card,
6749
+ { title: t('instruction.compareTitle'), subtitle: t('instruction.compareSubtitle') },
5030
6750
  h(
5031
- C.Card,
5032
- {
5033
- title: t('diagnostics.title'),
5034
- subtitle: t('diagnostics.subtitle'),
5035
- actions: [
5036
- h(C.Btn, { key: 'run', tone: 'primary', onClick: () => { forceRun.current = true; state.reload() } }, t('diagnostics.run')),
5037
- h(C.Btn, { key: 'md', disabled: exporting !== null, onClick: () => runExport('md') }, exporting === 'md' ? t('diagnostics.exporting') : t('diagnostics.exportMd')),
5038
- h(C.Btn, { key: 'json', disabled: exporting !== null, onClick: () => runExport('json') }, exporting === 'json' ? t('diagnostics.exporting') : t('diagnostics.exportJson')),
5039
- ],
5040
- },
6751
+ 'div',
6752
+ { style: STACK_STYLE },
5041
6753
  h(
5042
6754
  'div',
5043
- { className: 'acc-row', style: { justifyContent: 'space-between' } },
5044
- h('span', { className: 'acc-muted' }, `${t('diagnostics.generatedAt')}: ${report.generatedAt ? ACC.l10n.dateTime(report.generatedAt, t) : '—'}`),
5045
- h('span', { className: 'acc-muted' }, report.cached === true ? t('diagnostics.cached') : t('diagnostics.fresh')),
6755
+ { className: 'acc-grid-fit' },
6756
+ h(CompareStat, { label: t('instruction.compareFilesBytes'), value: ACC.l10n.bytes(data.filesBytes, t) }),
6757
+ h(CompareStat, { label: t('instruction.compareSessionBytes'), value: ACC.l10n.bytes(data.sessionBytes, t) }),
6758
+ h(CompareStat, { label: t('instruction.compareDeltaBytes'), value: signedBytes(data.deltaBytes, t) }),
6759
+ ),
6760
+ h(
6761
+ 'div',
6762
+ { className: 'acc-row' },
6763
+ h(C.Badge, { tone: same ? 'success' : 'warn' }, same ? t('instruction.sameText') : t('instruction.differentText')),
6764
+ h(C.Badge, { tone: exactFiles ? 'success' : 'warn' }, exactFiles ? t('instruction.exactFilesYes') : t('instruction.exactFilesNo')),
6765
+ sessionItems === null ? null : h(C.Badge, { tone: 'neutral' }, t('instruction.sessionItemsValue', { count: ACC.fmt.num(sessionItems) })),
5046
6766
  ),
6767
+ same ? null : h(C.Notice, { tone: 'warn' }, t('instruction.compareWhy')),
6768
+ note.length > 0 ? h('div', { style: MUTED_STYLE }, note) : null,
6769
+ ACC.l10n.raw(t('instruction.rawHostText'), data.note),
5047
6770
  ),
5048
- exportError ? h(C.ErrorBox, { error: exportError, label: t('diagnostics.exportFailed') }) : null,
5049
- fixError ? h(C.ErrorBox, { error: fixError, label: t('diagnostics.fixFailed') }) : null,
5050
- fixReport
5051
- ? h(
5052
- C.Notice,
5053
- { tone: fixReport.fixed ? 'success' : 'warn' },
5054
- h('div', null, `${t('diagnostics.fixDone')}: ${t(`diagnostics.check.${fixReport.id}`)}`),
5055
- h('div', { className: 'acc-muted', style: { fontSize: '11px' } }, ACC.l10n.map(fixReport.fixed ? 'diagnostics.fixApplied' : 'diagnostics.fixNoChange')),
5056
- ACC.l10n.raw(t('diagnostics.rawEvidence'), `${String(fixReport.action || '')}\n${String(fixReport.detail || '')}`),
5057
- h(
5058
- 'div',
5059
- { className: 'acc-grid-2', style: { marginTop: '6px' } },
5060
- h('div', null, h('div', { className: 'acc-muted' }, `${t('diagnostics.before')} · ${fixReport.before.status}`), h('div', { className: 'acc-mono' }, clip(fixReport.before.evidence, 200))),
5061
- h('div', null, h('div', { className: 'acc-muted' }, `${t('diagnostics.after')} · ${fixReport.after.status}`), h('div', { className: 'acc-mono' }, clip(fixReport.after.evidence, 200))),
5062
- ),
5063
- fixReport.recheckedAt ? h('div', { className: 'acc-muted' }, `${t('diagnostics.rechecked')}: ${ACC.l10n.dateTime(fixReport.recheckedAt, t)}`) : null,
5064
- )
5065
- : null,
5066
- state.data && state.data.items && state.data.items.length === 0
5067
- ? h(C.Empty, {
5068
- title: t('diagnostics.empty'),
5069
- hint: t('diagnostics.emptyHint'),
5070
- action: h(C.Btn, { tone: 'primary', onClick: state.reload }, t('diagnostics.run')),
5071
- })
5072
- : h(DiagnosticsBody, {
5073
- report,
5074
- t,
5075
- statusFilter: filter,
5076
- onStatus: setStatusFilter,
5077
- openGroups,
5078
- toggleGroup: (group) => setClosedGroups((previous) => ({ ...previous, [group]: !previous[group] })),
5079
- expanded: (open) => {
5080
- if (open) {
5081
- setClosedGroups({})
5082
- return
5083
- }
5084
- const next = {}
5085
- for (const bucket of report.summary && Array.isArray(report.summary.groups) ? report.summary.groups : []) next[bucket.group] = true
5086
- setClosedGroups(next)
5087
- },
5088
- onFix: (id) => setFixTarget(id),
5089
- fixing,
5090
- }),
5091
- exported ? h(ExportDialog, { t, exported, onClose: () => setExported(null) }) : null,
5092
- fixTarget === null
5093
- ? null
5094
- : h(
5095
- C.Modal,
6771
+ )
6772
+ }
6773
+
6774
+ /** Compare view: files approximation vs the session's exact baseline block. */
6775
+ function CompareView(props) {
6776
+ const t = props.t
6777
+ const state = ACC.useAsync(
6778
+ (context) => (props.sessionId.length === 0 ? null : ACC.api('instruction.compare', { sessionId: props.sessionId }, context)),
6779
+ [props.sessionId],
6780
+ )
6781
+ let content = null
6782
+ if (props.sessionId.length === 0) {
6783
+ content = h(C.Empty, { title: t('instruction.noSelection'), hint: t('instruction.noSelectionHint') })
6784
+ } else if (state.status === 'loading') {
6785
+ content = h(C.Loading, { label: t('common.loading') })
6786
+ } else if (state.status === 'error') {
6787
+ content = h(C.ErrorBox, { error: state.error, onRetry: state.reload, label: t('instruction.compareFailed') })
6788
+ } else {
6789
+ const data = state.data
6790
+ if (data === null || typeof data !== 'object') {
6791
+ content = h(C.Empty, { title: t('instruction.noSelection'), hint: t('instruction.noSelectionHint') })
6792
+ } else if (data.available !== true) {
6793
+ content = h(UnavailablePanel, { data, t, title: t('instruction.compareUnavailableTitle'), onRetry: state.reload })
6794
+ } else {
6795
+ content = h(CompareResult, { data, t })
6796
+ }
6797
+ }
6798
+ return h(
6799
+ 'div',
6800
+ { style: STACK_STYLE },
6801
+ h(SessionPickerCard, { feed: props.sessions, value: props.sessionId, onChange: props.onSelect, t }),
6802
+ content,
6803
+ )
6804
+ }
6805
+
6806
+ /** @param {{ t: Function, navigate: Function }} props */
6807
+ function InstructionPage(props) {
6808
+ const t = props.t
6809
+ const summary = ACC.useAsync((context) => ACC.api('instruction.summary', {}, context), [])
6810
+ const sessions = ACC.useAsync((context) => ACC.api('sessions.list', { page: 1, limit: SESSION_PAGE_SIZE }, context), [])
6811
+ const [view, setView] = ACC.useState('files')
6812
+ const [sessionId, setSessionId] = ACC.useState('')
6813
+
6814
+ // Picking the most recent session keeps the exact/compare views usable
6815
+ // without a second interaction; the user can change it at any time.
6816
+ ACC.useEffect(() => {
6817
+ if (sessionId.length > 0 || sessions.status !== 'ready') return
6818
+ const rows = sessionItems(sessions)
6819
+ if (rows.length > 0) setSessionId(String(rows[0].id))
6820
+ // eslint-disable-next-line react-hooks/exhaustive-deps
6821
+ }, [sessionId, sessions.status, sessions.data])
6822
+
6823
+ const readOnly = h(C.Notice, { tone: 'info' }, t('instruction.readOnly'))
6824
+ let body = null
6825
+ if (summary.status === 'loading') {
6826
+ body = h(C.Loading, { label: t('common.loading') })
6827
+ } else if (summary.status === 'error') {
6828
+ body = h(C.ErrorBox, { error: summary.error, onRetry: summary.reload, label: t('instruction.failed') })
6829
+ } else if (summary.data === null || typeof summary.data !== 'object' || summary.data.available !== true) {
6830
+ body = h(UnavailablePanel, { data: summary.data, t, title: t('instruction.unavailableTitle'), onRetry: summary.reload })
6831
+ } else {
6832
+ const tabs = h(
6833
+ 'div',
6834
+ { className: 'acc-tabs', role: 'tablist', 'aria-label': t('instruction.tabsLabel') },
6835
+ VIEWS.map((entry) =>
6836
+ h(
6837
+ 'button',
5096
6838
  {
5097
- title: t('diagnostics.fixTitle'),
5098
- onClose: () => setFixTarget(null),
5099
- footer: h(
5100
- 'div',
5101
- { className: 'acc-row', style: { justifyContent: 'flex-end' } },
5102
- h(C.Btn, { tone: 'ghost', onClick: () => setFixTarget(null) }, t('common.cancel')),
5103
- h(C.Btn, { tone: 'primary', onClick: () => runFix(fixTarget) }, t('diagnostics.fixCta')),
5104
- ),
6839
+ key: entry.id,
6840
+ type: 'button',
6841
+ role: 'tab',
6842
+ 'aria-selected': view === entry.id,
6843
+ className: `acc-tab${view === entry.id ? ' is-active' : ''}`,
6844
+ onClick: () => setView(entry.id),
5105
6845
  },
5106
- h('p', { style: { margin: 0 } }, `${t('diagnostics.fixTarget')}: ${fixTitle}`),
5107
- h(C.Notice, { tone: 'warn' }, t('diagnostics.fixConfirm')),
5108
- h(C.Notice, { tone: 'info' }, t('diagnostics.fixScope')),
6846
+ t(entry.labelKey),
5109
6847
  ),
5110
- )
6848
+ ),
6849
+ )
6850
+ body = h(
6851
+ 'div',
6852
+ { style: STACK_STYLE },
6853
+ summary.data.moduleA === false ? h(C.Notice, { tone: 'warn' }, t('instruction.moduleAUnavailable')) : null,
6854
+ h(C.Toolbar, null, tabs),
6855
+ view === 'files'
6856
+ ? h(FilesView, { t })
6857
+ : view === 'session'
6858
+ ? h(SessionView, { t, sessions, sessionId, onSelect: setSessionId })
6859
+ : h(CompareView, { t, sessions, sessionId, onSelect: setSessionId }),
6860
+ )
6861
+ }
6862
+ return h('div', { style: PAGE_STYLE }, readOnly, body)
5111
6863
  }
5112
6864
 
5113
6865
  ACC.registerPage({
5114
- id: 'diagnostics',
5115
- titleKey: 'nav.diagnostics',
5116
- order: 70,
5117
- render: (props) => h(DiagnosticsPage, props),
6866
+ id: 'instruction',
6867
+ titleKey: 'nav.instruction',
6868
+ descriptionKey: 'nav.desc.instruction',
6869
+ icon: 'file-text',
6870
+ order: 40,
6871
+ group: 'edit',
6872
+ render: (props) => h(InstructionPage, props),
5118
6873
  })
5119
6874
  })()
5120
6875
  ;
@@ -6029,6 +7784,7 @@ ACC.l10n = (function createL10n() {
6029
7784
  id: 'meta',
6030
7785
  titleKey: 'nav.meta',
6031
7786
  order: 60,
7787
+ group: 'insight',
6032
7788
  render: (props) => h(MetaPage, props),
6033
7789
  })
6034
7790
  })()
@@ -6365,6 +8121,7 @@ ACC.l10n = (function createL10n() {
6365
8121
  id: 'overview',
6366
8122
  titleKey: 'nav.overview',
6367
8123
  order: 10,
8124
+ group: 'insight',
6368
8125
  render: (props) => h(OverviewPage, props),
6369
8126
  })
6370
8127
  })()
@@ -6861,6 +8618,7 @@ ACC.l10n = (function createL10n() {
6861
8618
  id: 'recovery',
6862
8619
  titleKey: 'nav.recovery',
6863
8620
  order: 90,
8621
+ group: 'maintain',
6864
8622
  render: (props) => h(RecoveryPage, props),
6865
8623
  })
6866
8624
  })()
@@ -7899,6 +9657,7 @@ ACC.l10n = (function createL10n() {
7899
9657
  id: 'sessions',
7900
9658
  titleKey: 'nav.sessions',
7901
9659
  order: 30,
9660
+ group: 'insight',
7902
9661
  render: (props) => h(SessionsPage, props),
7903
9662
  })
7904
9663
  })()
@@ -8937,6 +10696,7 @@ ACC.l10n = (function createL10n() {
8937
10696
  id: 'templates',
8938
10697
  titleKey: 'nav.templates',
8939
10698
  order: 80,
10699
+ group: 'edit',
8940
10700
  render: (props) => h(TemplatesPage, props),
8941
10701
  })
8942
10702
  })()
@@ -9661,6 +11421,7 @@ ACC.l10n = (function createL10n() {
9661
11421
  id: 'tools',
9662
11422
  titleKey: 'nav.tools',
9663
11423
  order: 20,
11424
+ group: 'insight',
9664
11425
  render: (props) => h(ToolsPage, props),
9665
11426
  })
9666
11427
  })()
@@ -10283,6 +12044,7 @@ ACC.l10n = (function createL10n() {
10283
12044
  id: 'usage',
10284
12045
  titleKey: 'nav.usage',
10285
12046
  order: 50,
12047
+ group: 'insight',
10286
12048
  render: (props) => h(UsagePage, props),
10287
12049
  })
10288
12050
  })()
@@ -10412,6 +12174,19 @@ body, .acc-root {
10412
12174
  scrollbar-gutter: stable;
10413
12175
  padding: 2px 4px 2px 0;
10414
12176
  }
12177
+ /* Section label above each rail group: 11px uppercase micro-heading. The rail
12178
+ * is 176px, so a long English label truncates instead of wrapping; the full
12179
+ * text stays in the DOM (accessible name) and in the title attribute. */
12180
+ .acc-nav-group {
12181
+ padding: 8px 8px 2px;
12182
+ color: var(--acc-fg-faint);
12183
+ font: 600 11px/16px var(--acc-font);
12184
+ letter-spacing: .08em;
12185
+ text-transform: uppercase;
12186
+ white-space: nowrap;
12187
+ overflow: hidden;
12188
+ text-overflow: ellipsis;
12189
+ }
10415
12190
  .acc-nav-item {
10416
12191
  position: relative;
10417
12192
  display: flex;
@@ -10472,6 +12247,17 @@ body, .acc-root {
10472
12247
  .acc-nav-horizontal .acc-nav-icon { width: 14px; height: 14px; }
10473
12248
  .acc-nav-horizontal .acc-nav-label { flex: 0 1 auto; }
10474
12249
  .acc-nav-horizontal .acc-nav-state { position: static; margin-inline-start: 2px; max-width: 72px; }
12250
+ /* A hairline marks the group boundary in the wrapped bar; the rail uses its
12251
+ * label and the narrow select its optgroup, so this appears mid-only. */
12252
+ .acc-nav-sep {
12253
+ flex: none;
12254
+ align-self: center;
12255
+ width: 2px;
12256
+ height: 8px;
12257
+ margin: 0 4px;
12258
+ border-radius: 1px;
12259
+ background: var(--acc-border);
12260
+ }
10475
12261
 
10476
12262
  /* ---- navigation: dropdown (narrow) ------------------------------------- */
10477
12263
  .acc-narrowbar { position: relative; display: flex; align-items: center; min-width: 0; }
@@ -10831,6 +12617,19 @@ const ACC_LAYOUT_RAIL_MIN = 640
10831
12617
  /** Below this the navigation becomes a dropdown. */
10832
12618
  const ACC_LAYOUT_BAR_MIN = 460
10833
12619
 
12620
+ /**
12621
+ * Fixed navigation group order, shared by the rail, the wrapped bar and the
12622
+ * narrow select. The landing page (Overview) lives in `insight`, so that group
12623
+ * leads and the active tab sits at the start of every surface.
12624
+ */
12625
+ const ACC_NAV_GROUPS = ['insight', 'edit', 'maintain']
12626
+ /**
12627
+ * Fallback split for pages that register no `group`: ≤20 edit, ≤60 insight,
12628
+ * everything later maintain. Explicit `group` always wins, so pages stay
12629
+ * correctly placed when their order changes to fit a different section.
12630
+ */
12631
+ const ACC_NAV_INSIGHT_MAX_ORDER = 60
12632
+
10834
12633
  /** @param {{ id: string, icon?: string, state?: string }} page @returns {string} */
10835
12634
  function pageIcon(page) {
10836
12635
  if (page && typeof page.icon === 'string' && ACC.icons[page.icon]) return page.icon
@@ -10853,6 +12652,31 @@ function layoutForWidth(width) {
10853
12652
  return 'narrow'
10854
12653
  }
10855
12654
 
12655
+ /**
12656
+ * Resolve one page's navigation group. An explicit `group` wins; otherwise
12657
+ * `order` keeps pages written before the groups existed in a sensible slot.
12658
+ * @param {{ group?: string, order?: number }} page
12659
+ * @returns {'edit' | 'insight' | 'maintain'}
12660
+ */
12661
+ function groupOf(page) {
12662
+ if (page && ACC_NAV_GROUPS.includes(page.group)) return page.group
12663
+ const order = page && typeof page.order === 'number' ? page.order : 100
12664
+ if (order <= 20) return 'edit'
12665
+ return order <= ACC_NAV_INSIGHT_MAX_ORDER ? 'insight' : 'maintain'
12666
+ }
12667
+
12668
+ /**
12669
+ * Bucket already-sorted pages into the fixed group order. Empty groups are
12670
+ * dropped so a label never appears without pages under it.
12671
+ * @param {readonly object[]} pages
12672
+ * @returns {Array<{ id: 'edit' | 'insight' | 'maintain', pages: object[] }>}
12673
+ */
12674
+ function groupedPages(pages) {
12675
+ const buckets = { edit: [], insight: [], maintain: [] }
12676
+ for (const page of pages) buckets[groupOf(page)].push(page)
12677
+ return ACC_NAV_GROUPS.filter((id) => buckets[id].length > 0).map((id) => ({ id, pages: buckets[id] }))
12678
+ }
12679
+
10856
12680
  /**
10857
12681
  * The one settings page. Owns internal navigation only; each page owns its
10858
12682
  * data, loading/error/empty states and destructive confirmations.
@@ -10861,6 +12685,7 @@ function layoutForWidth(width) {
10861
12685
  function AccSection(props) {
10862
12686
  const t = props.t
10863
12687
  const pages = ACC.pagesSorted()
12688
+ const navGroups = groupedPages(pages)
10864
12689
  const rootRef = useRef(null)
10865
12690
  const [activeId, setActiveId] = useState(() => {
10866
12691
  try {
@@ -10986,9 +12811,28 @@ function AccSection(props) {
10986
12811
  'div',
10987
12812
  { className: wide ? 'acc-body' : 'acc-body acc-body-narrow' },
10988
12813
  wide
10989
- ? h('nav', { className: 'acc-nav', 'aria-label': t('nav.ariaLabel') }, pages.map(renderNavItem))
12814
+ ? h(
12815
+ 'nav',
12816
+ { className: 'acc-nav', 'aria-label': t('nav.ariaLabel') },
12817
+ navGroups.flatMap((group) => {
12818
+ const label = t(`nav.group.${group.id}`)
12819
+ return [
12820
+ h('div', { key: `group-${group.id}`, className: 'acc-nav-group', title: label }, label),
12821
+ ...group.pages.map(renderNavItem),
12822
+ ]
12823
+ }),
12824
+ )
10990
12825
  : layout === 'mid'
10991
- ? h('nav', { className: 'acc-nav acc-nav-horizontal', 'aria-label': t('nav.ariaLabel') }, pages.map(renderNavItem))
12826
+ ? h(
12827
+ 'nav',
12828
+ { className: 'acc-nav acc-nav-horizontal', 'aria-label': t('nav.ariaLabel') },
12829
+ navGroups.flatMap((group, index) => [
12830
+ ...(index === 0
12831
+ ? []
12832
+ : [h('span', { key: `sep-${group.id}`, className: 'acc-nav-sep', 'aria-hidden': 'true' })]),
12833
+ ...group.pages.map(renderNavItem),
12834
+ ]),
12835
+ )
10992
12836
  : h(
10993
12837
  'div',
10994
12838
  { className: 'acc-narrowbar' },
@@ -11001,7 +12845,13 @@ function AccSection(props) {
11001
12845
  'aria-label': t('nav.ariaLabel'),
11002
12846
  onChange: (event) => setActiveId(event.target.value),
11003
12847
  },
11004
- pages.map((page) => h('option', { key: page.id, value: page.id }, t(page.titleKey))),
12848
+ navGroups.map((group) =>
12849
+ h(
12850
+ 'optgroup',
12851
+ { key: `group-${group.id}`, label: t(`nav.group.${group.id}`) },
12852
+ group.pages.map((page) => h('option', { key: page.id, value: page.id }, t(page.titleKey))),
12853
+ ),
12854
+ ),
11005
12855
  ),
11006
12856
  ),
11007
12857
  h(