dsh-better-tips 0.0.0-stage → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/client.js ADDED
@@ -0,0 +1,1048 @@
1
+ /** Original errors with supplementary evidence and concise troubleshooting checks. */
2
+ window.__ModuleLoader__.load({
3
+ id: 'dsh-better-tips',
4
+ factory (require) {
5
+ const React = require('react')
6
+ const h = React.createElement
7
+ const NS = 'better-tips'
8
+ const KIND = 'better-tips-compaction'
9
+ const CSS_TAG = 'dsh-better-tips/BetterTips.css'
10
+ const zh = {
11
+ 'ui.authProtected': '认证错误正文已隐藏,避免回显凭据。请核对密钥、接口地址和模型权限。',
12
+ 'ui.authBodyProtected': '认证响应正文已受保护;仅保留安全的状态与请求标识。',
13
+ 'ui.details': '底层原始详情', 'ui.bottom': '底层', 'ui.unconfirmed': '关联未确认',
14
+ 'ui.candidates': '候选捕获 · {count}', 'ui.loading': '加载中',
15
+ 'ui.empty': '未取得额外网络诊断', 'ui.disabled': '额外网络诊断已关闭', 'ui.captureUnavailable': '额外网络诊断不可用', 'ui.loadFailed': '详情读取失败 · {message}',
16
+ 'ui.refresh': '重新读取', 'ui.bodyPending': '响应正文读取中', 'ui.bodyEmpty': '响应正文为空',
17
+ 'ui.bodyTruncated': '响应正文已截断', 'ui.bodyUnreadable': '响应正文读取失败',
18
+ 'ui.copyCapture': '复制截获错误', 'ui.copyError': '复制完整错误', 'ui.copyCoordinate': '复制日志坐标', 'ui.copyPath': '复制路径',
19
+ 'ui.copied': '已复制', 'ui.copyFailed': '复制失败,请手动选择文本', 'ui.copying': '复制中',
20
+ 'ui.error': '失败', 'ui.stopped': '已停止', 'ui.retry': '重试',
21
+ 'ui.retried': '已重试', 'ui.cancelled': '重试取消', 'ui.scheduled': '等待重试',
22
+ 'compact.title': '上下文已压缩', 'compact.completed': '{items} 条 · ~{tokens} tokens',
23
+ 'compact.running': '压缩中', 'compact.done': '压缩完成',
24
+ 'compact.failed': '压缩失败', 'compact.failedAuto': '自动压缩失败',
25
+ 'compact.recordMissing': '本次压缩的具体失败记录尚未加载,当前仅有命令提示。', 'compact.recordFailed': '本次压缩失败记录读取失败。',
26
+ 'compact.errorProtected': '压缩失败;持久化诊断缺少错误类型,正文已隐藏以避免回显凭据。',
27
+ 'compact.attempt': '尝试 {index}',
28
+ 'ui.expand': '错误详情', 'ui.original': 'DSH 原生报错', 'ui.network': '插件捕获的底层报错',
29
+ 'ui.nativeExcerpt': 'DSH 原生报错 · 摘要', 'ui.overviewSource': '插件整理 · 重试概览', 'ui.open': '展开', 'ui.close': '收起',
30
+ 'ui.earlierErrors': '更早的报错 · {count}', 'ui.earlierBlock': '更早的报错',
31
+ 'ui.history': '重试记录 · {count}', 'ui.record': '失败记录 {index}',
32
+ 'ui.categoryOverview': '类别概览', 'ui.different': '{count} 类错误',
33
+ 'ui.attempts': '请求尝试 · {count}', 'ui.logSection': '日志定位',
34
+ 'ui.timingMatch': '按时间关联 · 未确认请求身份', 'ui.wait': '计划等待 {ms} ms',
35
+ 'ui.historyNote': '按发生顺序;同一重试的等待与开始状态仅记一次。',
36
+ 'report.copy': '一键复制排障报告', 'report.building': '生成中', 'report.partial': '已复制 · 部分信息缺失',
37
+ 'report.fallback': '复制失败,可选择下方报告文本',
38
+ 'report.notice': '分享前检查:报错或响应可能回显输入;仅过滤常见凭据,不保证清除个人信息。',
39
+ 'compact.usage': '摘要请求用量(非会话总量)', 'log.contextWarning': '相邻事件可能含会话内容,分享前请检查。',
40
+ 'report.responseState': '响应状态',
41
+ 'report.intro': '记录于{time}:使用“{provider}”渠道的“{model}”模型时遇到{error}。',
42
+ 'report.plugins': '已启用第三方插件', 'report.pluginsPartial': '部分插件信息未能确认', 'report.pluginsUnavailable': '清单读取失败或不可用', 'report.pluginsNone': '无',
43
+ 'report.missing': '未记录', 'report.version': '截止生成本报告时', 'report.native': 'DSH 原生报错', 'report.underlying': '插件捕获的底层报错',
44
+ 'report.noEvidence': '未取得唯一匹配的底层证据', 'report.ambiguous': '有多个候选,未混入报告', 'report.readFailed': '读取失败',
45
+ 'report.unconfirmed': '同一时间附近捕获到以下报错:', 'report.summaryError': '摘要请求报错',
46
+ 'report.response': '响应摘要', 'report.truncated': '已省略,全文见错误详情', 'report.protected': '认证正文已隐藏',
47
+ 'report.timing': '请求耗时', 'report.wait': '计划等待(非实测)', 'report.retry': '重试记录',
48
+ 'report.help': '请协助排查;以上是已保留的错误证据,并非已确认根因。',
49
+ 'check.mixed': '本组包含不同错误;展开后按每条记录分别排查,勿将最后一种错误视为全部原因。',
50
+ }
51
+ const en = {
52
+ 'ui.authProtected': 'Authentication error text is hidden to avoid echoing credentials. Check the key, endpoint and model permissions.',
53
+ 'ui.authBodyProtected': 'Authentication response text is protected; only safe status and request identifiers are retained.',
54
+ 'ui.details': 'Underlying raw details', 'ui.bottom': 'Underlying', 'ui.unconfirmed': 'Unconfirmed match',
55
+ 'ui.candidates': 'Candidate captures · {count}', 'ui.loading': 'Loading',
56
+ 'ui.empty': 'No additional network diagnosis', 'ui.disabled': 'Additional network diagnosis is disabled', 'ui.captureUnavailable': 'Additional network diagnosis unavailable', 'ui.loadFailed': 'Details unavailable · {message}',
57
+ 'ui.refresh': 'Read again', 'ui.bodyPending': 'Reading response body', 'ui.bodyEmpty': 'Response body is empty',
58
+ 'ui.bodyTruncated': 'Response body truncated', 'ui.bodyUnreadable': 'Response body read failed',
59
+ 'ui.copyCapture': 'Copy captured error', 'ui.copyError': 'Copy full error', 'ui.copyCoordinate': 'Copy log coordinates', 'ui.copyPath': 'Copy path',
60
+ 'ui.copied': 'Copied', 'ui.copyFailed': 'Copy failed; select the text manually', 'ui.copying': 'Copying',
61
+ 'ui.error': 'Failed', 'ui.stopped': 'Stopped', 'ui.retry': 'Retrying',
62
+ 'ui.retried': 'Retried', 'ui.cancelled': 'Retry cancelled', 'ui.scheduled': 'Retry scheduled',
63
+ 'compact.title': 'Context compacted', 'compact.completed': '{items} items · ~{tokens} tokens',
64
+ 'compact.running': 'Compacting', 'compact.done': 'Compaction complete',
65
+ 'compact.failed': 'Compaction failed', 'compact.failedAuto': 'Automatic compaction failed',
66
+ 'compact.recordMissing': 'The specific failure record for this compaction is not loaded; only the command notice is available.', 'compact.recordFailed': 'Could not read this compaction failure record.',
67
+ 'compact.errorProtected': 'Compaction failed; durable diagnosis has no error type, so its text is withheld to avoid credential echoes.',
68
+ 'compact.attempt': 'Attempt {index}',
69
+ 'ui.expand': 'Error details', 'ui.original': 'DSH native error', 'ui.network': 'Plugin-captured underlying error',
70
+ 'ui.nativeExcerpt': 'DSH native error · excerpt', 'ui.overviewSource': 'Plugin summary · retries', 'ui.open': 'Expand', 'ui.close': 'Collapse',
71
+ 'ui.earlierErrors': 'Earlier errors · {count}', 'ui.earlierBlock': 'Earlier error',
72
+ 'ui.history': 'Retry history · {count}', 'ui.record': 'Failure record {index}',
73
+ 'ui.categoryOverview': 'Category overview', 'ui.different': '{count} error categories',
74
+ 'ui.attempts': 'Request attempts · {count}', 'ui.logSection': 'Log location',
75
+ 'ui.timingMatch': 'Time correlation · request identity unconfirmed', 'ui.wait': 'planned wait {ms} ms',
76
+ 'ui.historyNote': 'Chronological; scheduled and started states of one retry count once.',
77
+ 'report.copy': 'Copy troubleshooting report', 'report.building': 'Preparing', 'report.partial': 'Copied · some information missing',
78
+ 'report.fallback': 'Copy failed; select the report below',
79
+ 'report.notice': 'Review before sharing: errors/responses may echo input. Common credential filtering is not personal-data removal.',
80
+ 'compact.usage': 'Summary request usage (not session total)', 'log.contextWarning': 'Nearby events may contain conversation content. Review before sharing.',
81
+ 'report.responseState': 'Response state',
82
+ 'report.intro': 'At {time}, model “{model}” via provider “{provider}” returned {error}.',
83
+ 'report.plugins': 'Enabled third-party plugins', 'report.pluginsPartial': 'Some plugin information could not be verified', 'report.pluginsUnavailable': 'Inventory unavailable or read failed', 'report.pluginsNone': 'none',
84
+ 'report.missing': 'not recorded', 'report.version': 'As of this report', 'report.native': 'DSH native error', 'report.underlying': 'Plugin-captured underlying error',
85
+ 'report.noEvidence': 'No uniquely matched underlying evidence', 'report.ambiguous': 'Multiple candidates omitted', 'report.readFailed': 'Read failed',
86
+ 'report.unconfirmed': 'The following was captured around the same time:', 'report.summaryError': 'Summary request error',
87
+ 'report.response': 'Response excerpt', 'report.truncated': 'omitted; full text in error details', 'report.protected': 'Authentication text withheld',
88
+ 'report.timing': 'Request duration', 'report.wait': 'Planned wait (not measured)', 'report.retry': 'Retry record',
89
+ 'report.help': 'Please help investigate. These are retained observations, not a confirmed root cause.',
90
+ 'check.mixed': 'This chain contains different errors; inspect each record rather than treating the last as the cause of all failures.',
91
+ }
92
+ const checks = {
93
+ generic: ['展开错误详情,核对请求地址与服务端日志。', 'Expand error details; verify the endpoint and server logs.'],
94
+ dnsName: ['核对 API 域名及 DNS 解析结果。', 'Verify the API hostname and DNS resolution.'],
95
+ dnsTemporary: ['检查 DNS 服务,稍后重试。', 'Check DNS availability, then retry later.'],
96
+ refused: ['核对目标端口,确认服务及代理正在监听。', 'Verify the target port and that the service and proxy are listening.'],
97
+ unreachable: ['检查网络路由、VPN 与防火墙。', 'Check routing, VPN and firewall rules.'],
98
+ socket: ['检查代理与上游连接;持续发生时核对双方日志。', 'Check proxy and upstream connections; inspect both logs if persistent.'],
99
+ connectTimeout: ['检查目标地址、代理与防火墙,再核对连接超时设置。', 'Check the endpoint, proxy and firewall, then the connection timeout.'],
100
+ headersTimeout: ['核对上游响应头等待时间及代理超时设置。', 'Check upstream response-header latency and proxy timeouts.'],
101
+ bodyTimeout: ['检查流式连接与上游输出停顿,核对读取超时设置。', 'Check stream connectivity and upstream stalls, then read timeouts.'],
102
+ certExpired: ['核对系统时间及服务端证书有效期。', 'Check the system clock and server certificate validity.'],
103
+ certChain: ['检查服务端证书链与本机信任库;不要关闭证书校验。', 'Check the server certificate chain and local trust store; keep verification enabled.'],
104
+ certName: ['核对 API 域名与证书域名是否一致。', 'Check that the API hostname matches the certificate names.'],
105
+ tls: ['核对代理 TLS 配置、证书及协议兼容性。', 'Check proxy TLS settings, certificates and protocol compatibility.'],
106
+ request: ['查看响应正文,核对请求参数与模型支持范围。', 'Inspect the response body; verify parameters and model support.'],
107
+ unauthorized: ['核对 API 密钥、请求地址及认证方式。', 'Verify the API key, endpoint and authentication scheme.'],
108
+ forbidden: ['核对账号、模型权限及网关访问策略。', 'Check account/model permissions and gateway access policies.'],
109
+ notFound: ['核对 API 路径、接口版本及模型标识。', 'Verify the API path, version and model ID.'],
110
+ conflict: ['查看响应正文,确认冲突状态后再重试。', 'Inspect the response body and resolve the conflicting state before retrying.'],
111
+ tooLarge: ['减少上下文、附件或单次请求大小,并核对网关限制。', 'Reduce context, attachments or request size; check gateway limits.'],
112
+ rateLimit: ['核对 Retry-After、并发和速率限制,退避后重试。', 'Check Retry-After, concurrency and rate limits; retry with backoff.'],
113
+ headersLarge: ['精简请求头,核对代理请求头大小限制。', 'Reduce request headers and check proxy header-size limits.'],
114
+ closed: ['核对取消记录及客户端、代理超时日志。', 'Check cancellation records and client/proxy timeout logs.'],
115
+ server: ['凭 request-id 核对服务端日志,稍后重试。', 'Check server logs using the request ID, then retry later.'],
116
+ gateway: ['核对网关与上游日志、健康状态及超时设置。', 'Check gateway/upstream logs, health and timeouts.'],
117
+ context: ['压缩上下文或减少输入,核对模型上下文上限。', 'Compact context or reduce input; verify the model context limit.'],
118
+ quota: ['核对账号余额、用量配额及计费状态。', 'Check account balance, usage quota and billing status.'],
119
+ credentials: ['检查凭据、账号状态及模型访问权限。', 'Check credentials, account status and model access.'],
120
+ model: ['核对模型标识及当前账号可用的模型列表。', 'Verify the model ID against models available to this account.'],
121
+ config: ['核对提供方地址、协议及模型配置。', 'Check provider endpoint, protocol and model configuration.'],
122
+ adapter: ['确认已启用与当前模型协议匹配的适配器。', 'Ensure an adapter matching the model protocol is enabled.'],
123
+ image: ['按原始提示处理图片或减少图片输入。', 'Follow the original image instructions or reduce image input.'],
124
+ aborted: ['核对是否主动取消;非预期中止时检查超时设置。', 'Check for intentional cancellation; inspect timeouts if unexpected.'],
125
+ timeout: ['检查网络与上游耗时,区分连接和读取超时。', 'Check network/upstream latency; distinguish connection and read timeouts.'],
126
+ finishReason: ['核对 finish_reason、接口兼容性、上游提前结束及代理超时。', 'Check finish_reason, API compatibility, early upstream completion and proxy timeouts.'],
127
+ transport: ['查看会话日志;有网络诊断时核对连接与代理。', 'Inspect the session log; check connectivity and proxy details when network evidence is available.'],
128
+ empty: ['检查上游返回内容、流式协议及模型接口兼容性。', 'Check upstream output, streaming protocol and model API compatibility.'],
129
+ tokens: ['核对摘要输出 token 上限及模型限制。', 'Check the summary output-token cap and model limits.'],
130
+ stream: ['核对流式响应中断时的代理与上游日志。', 'Check proxy and upstream logs at the stream interruption.'],
131
+ tools: ['核对工具服务与会话生命周期;保留堆栈排查失效上下文。', 'Check tool services and session lifecycle; retain the stack for inactive-context diagnosis.'],
132
+ }
133
+ zh['ui.advice'] = '排查'
134
+ en['ui.advice'] = 'Check'
135
+ for (const [key, [cn, english]] of Object.entries(checks)) {
136
+ zh[`check.${key}`] = cn
137
+ en[`check.${key}`] = english
138
+ }
139
+ const CODE_CHECKS = Object.freeze({
140
+ ENOTFOUND: 'dnsName', EAI_AGAIN: 'dnsTemporary', ECONNREFUSED: 'refused',
141
+ ENETUNREACH: 'unreachable', EHOSTUNREACH: 'unreachable',
142
+ ECONNRESET: 'socket', EPIPE: 'socket', UND_ERR_SOCKET: 'socket',
143
+ UND_ERR_CONNECT_TIMEOUT: 'connectTimeout', UND_ERR_HEADERS_TIMEOUT: 'headersTimeout', UND_ERR_BODY_TIMEOUT: 'bodyTimeout',
144
+ CERT_HAS_EXPIRED: 'certExpired', CERT_NOT_YET_VALID: 'certExpired',
145
+ UNABLE_TO_VERIFY_LEAF_SIGNATURE: 'certChain', UNABLE_TO_GET_ISSUER_CERT_LOCALLY: 'certChain',
146
+ DEPTH_ZERO_SELF_SIGNED_CERT: 'certChain', SELF_SIGNED_CERT_IN_CHAIN: 'certChain',
147
+ ERR_TLS_CERT_ALTNAME_INVALID: 'certName', EPROTO: 'tls',
148
+ AUTH: 'credentials', MISSING_CREDENTIAL: 'credentials', INVALID_CREDENTIAL: 'credentials', ACCOUNT_SIGNED_OUT: 'credentials',
149
+ QUOTA: 'quota', ACCOUNT_QUOTA: 'quota', CONTEXT_WINDOW_EXCEEDED: 'context',
150
+ IMAGE_OFFLOAD_REQUIRED: 'image', INVALID_MODEL: 'model', INVALID_CONFIG: 'config', NO_ADAPTER: 'adapter',
151
+ ABORTED: 'aborted', INTERRUPTED: 'aborted', TIMEOUT: 'timeout', ETIMEDOUT: 'timeout',
152
+ TRANSPORT: 'transport', SERVER: 'server', EMPTY_RESPONSE: 'empty', RATE_LIMIT: 'rateLimit', MAX_TOKENS: 'tokens',
153
+ context_length_exceeded: 'context', insufficient_quota: 'quota', invalid_api_key: 'unauthorized',
154
+ authentication_error: 'unauthorized', permission_error: 'forbidden', model_not_found: 'model',
155
+ rate_limit_exceeded: 'rateLimit', rate_limit_error: 'rateLimit', invalid_request_error: 'request',
156
+ overloaded_error: 'server', api_error: 'server',
157
+ })
158
+ const HTTP_CHECKS = Object.freeze({
159
+ 400: 'request', 401: 'unauthorized', 402: 'quota', 403: 'forbidden', 404: 'notFound',
160
+ 408: 'timeout', 409: 'conflict', 413: 'tooLarge', 422: 'request', 429: 'rateLimit',
161
+ 431: 'headersLarge', 499: 'closed', 500: 'server', 502: 'gateway', 503: 'server', 504: 'gateway',
162
+ 520: 'gateway', 521: 'gateway', 522: 'gateway', 523: 'gateway', 524: 'gateway', 525: 'tls', 526: 'certChain',
163
+ })
164
+ Object.assign(zh, {
165
+ 'log.open': '打开日志', 'log.close': '收起日志', 'log.title': '会话原始日志',
166
+ 'log.loading': '读取日志中', 'log.unavailable': '日志读取不可用', 'log.missing': '未找到对应原始事件;未跳转到其他记录。',
167
+ 'log.noCoordinate': '该错误缺少精确日志坐标', 'log.failed': '日志读取失败 · {message}',
168
+ 'log.target': '错误所在事件', 'log.context': '相邻事件', 'log.capture': '网络捕获 · 内存记录',
169
+ 'log.protected': '显示副本已隐藏认证正文及常见凭据;持久化原始日志未改写。',
170
+ 'log.notWire': '会话日志不是上游原始网络报文。',
171
+ 'log.file': '日志文件', 'log.pathMissing': '实际日志路径不可用',
172
+ 'log.metadataLoading': '读取日志路径与源码位置', 'log.metadataFailed': '路径与源码信息读取失败',
173
+ 'log.sourceMatch': '源码匹配(非调用堆栈)', 'log.sourceUnknown': '未取得可核验的生成函数。',
174
+ 'log.producer': '报错生成', 'log.classifier': '错误分类',
175
+ 'log.logical': '按 seq 定位;不是文件行号,压缩日志需解码查看。',
176
+ })
177
+ Object.assign(en, {
178
+ 'log.open': 'Open log', 'log.close': 'Close log', 'log.title': 'Raw session log',
179
+ 'log.loading': 'Loading log', 'log.unavailable': 'Log reader unavailable', 'log.missing': 'Exact source event not found; no other record was substituted.',
180
+ 'log.noCoordinate': 'This error has no exact log coordinates', 'log.failed': 'Log read failed · {message}',
181
+ 'log.target': 'Error source event', 'log.context': 'Nearby events', 'log.capture': 'Network capture · in memory',
182
+ 'log.protected': 'This display copy hides authentication text and common credentials; the durable source log is unchanged.',
183
+ 'log.notWire': 'Session events are not raw upstream network packets.',
184
+ 'log.file': 'Log file', 'log.pathMissing': 'Physical log path unavailable',
185
+ 'log.metadataLoading': 'Loading log path and source location', 'log.metadataFailed': 'Log path and source lookup failed',
186
+ 'log.sourceMatch': 'Source match (not an execution stack)', 'log.sourceUnknown': 'No verified error-producing function.',
187
+ 'log.producer': 'Error producer', 'log.classifier': 'Error classifier',
188
+ 'log.logical': 'Locate by seq, not file line number; compressed logs require decoding.',
189
+ })
190
+ let sessionService
191
+ const CSS = [
192
+ '.bt_errorGroup{margin:8px 0;padding:2px 0 4px 12px;border-left:2px solid var(--dsw-alias-state-error-primary);display:grid;gap:4px;font-size:var(--dsh-content-font-size-secondary,13px);line-height:1.65;min-width:0}',
193
+ '.bt_originalRow{grid-column:1/-1;display:grid;gap:3px;min-width:0}',
194
+ '.bt_originalRow>.bt_title{font-size:12px;color:var(--dsw-alias-label-secondary)}',
195
+ '.bt_original,.bt_preview{margin:0;font:inherit;font-family:ui-monospace,monospace;color:var(--dsw-alias-state-error-primary);white-space:pre-wrap;overflow-wrap:anywhere;min-width:0;user-select:text}',
196
+ '.bt_protected{grid-column:1/-1;color:var(--dsw-alias-label-secondary);font-size:12px}',
197
+ '.bt_error,.bt_compact{margin:2px 0;font-size:var(--dsh-content-font-size-secondary,13px);line-height:1.6;min-width:0}',
198
+ '.bt_error>summary,.bt_compact>summary{display:flex;align-items:baseline;flex-wrap:wrap;gap:4px 8px;cursor:pointer;list-style:none;min-width:0;min-height:28px;padding:2px 0}',
199
+ '.bt_error>summary::-webkit-details-marker,.bt_compact>summary::-webkit-details-marker{display:none}',
200
+ '.bt_error>summary:before,.bt_compact>summary:before{content:"›";flex:none;color:var(--dsw-alias-label-secondary)}',
201
+ '.bt_error[open]>summary:before,.bt_compact[open]>summary:before{content:"⌄"}',
202
+ '.bt_title{flex:none;color:var(--dsw-alias-label-secondary)}',
203
+ '.bt_error .bt_primary{color:var(--dsw-alias-state-error-primary)}',
204
+ '.bt_primary{color:var(--dsw-alias-state-error-primary);font:inherit;font-family:ui-monospace,monospace;min-width:0;white-space:pre-wrap;overflow-wrap:anywhere}',
205
+ '.bt_logOpen{flex:1 1 100%;min-width:0}',
206
+ '.bt_actions{display:flex;align-items:center;flex-wrap:wrap;gap:4px 8px;min-width:0}',
207
+ '.bt_action,.bt_logButton{display:inline-flex;align-items:center;justify-content:center;gap:4px;border:1px solid var(--dsw-alias-border-l1);border-radius:3px;background:transparent;color:var(--dsw-alias-label-primary);font:400 12px/1.4 system-ui,sans-serif;min-height:24px;padding:2px 7px;cursor:pointer;text-decoration:none;width:fit-content}',
208
+ '.bt_action:hover,.bt_logButton:hover{border-color:var(--dsw-alias-state-error-primary);background:var(--dsw-alias-bg-layer-2);color:var(--dsw-alias-label-primary)}',
209
+ '.bt_action:disabled,.bt_logButton:disabled{cursor:not-allowed;opacity:.55;text-decoration:none}',
210
+ '.bt_action:focus-visible{outline:2px solid var(--dsw-alias-state-error-primary);outline-offset:2px}',
211
+ '.bt_flag{flex:none;font-size:11px;color:var(--dsw-alias-label-secondary)}',
212
+ '.bt_body{margin:4px 0 6px 14px;display:grid;gap:6px;min-width:0}',
213
+ '.bt_body>.bt_refresh{justify-self:start}',
214
+ '.bt_raw{margin:0;padding:6px 8px;white-space:pre-wrap;overflow-wrap:anywhere;max-height:340px;overflow:auto;',
215
+ 'font:12px/1.6 ui-monospace,monospace;color:var(--dsw-alias-label-primary);',
216
+ 'border:.5px solid var(--dsw-alias-border-l1);border-radius:var(--dsw-radius-sm);user-select:text}',
217
+ '.bt_meta{color:var(--dsw-alias-label-secondary);font-size:12px;overflow-wrap:anywhere}',
218
+ '.bt_capture{display:grid;gap:3px;min-width:0}',
219
+ '.bt_advice,.bt_captureAdvice{display:flex;align-items:baseline;flex-wrap:wrap;gap:4px 8px;padding:2px 0;color:var(--dsw-alias-label-primary);font-size:12px;overflow-wrap:anywhere}.bt_advice>.bt_title,.bt_captureAdvice>.bt_title{font-weight:600;color:var(--dsw-alias-state-error-primary)}',
220
+ '.bt_logButton:focus-visible{outline:2px solid var(--dsw-alias-state-error-primary);outline-offset:2px}',
221
+ '.bt_logPanel{margin:6px 0;padding:8px;border:1px solid var(--dsw-alias-border-l1);border-radius:6px;min-width:0}',
222
+ '.bt_logTarget{border-left:3px solid var(--dsw-alias-state-error-primary);padding-left:8px;min-width:0}',
223
+ '.bt_logHeading{font-size:12px;color:var(--dsw-alias-label-secondary);overflow-wrap:anywhere}',
224
+ '.bt_advice{grid-column:1/-1;margin:1px 0 2px;min-width:0}',
225
+ '.bt_compact{color:var(--dsw-alias-label-secondary)}',
226
+ '.bt_error>summary:focus-visible,.bt_compact>summary:focus-visible{outline:2px solid var(--dsw-alias-state-error-primary);outline-offset:2px}',
227
+ '.bt_detailBody{margin:4px 0 8px 10px;gap:10px}.bt_section{min-width:0;border-top:1px solid var(--dsw-alias-border-l1);padding-top:7px}.bt_heading{margin:0 0 4px;font:inherit;font-size:12px;font-weight:600;color:var(--dsw-alias-label-secondary)}',
228
+ '.bt_section>summary,.bt_attempt>summary{display:flex;align-items:baseline;flex-wrap:wrap;gap:4px 8px;min-height:28px;cursor:pointer}.bt_section>summary:focus-visible,.bt_attempt>summary:focus-visible{outline:2px solid var(--dsw-alias-state-error-primary);outline-offset:2px}.bt_attempt{min-width:0;margin:4px 0;padding-left:10px;border-left:1px solid var(--dsw-alias-border-l1)}.bt_attempt>div{display:grid;gap:5px;padding:6px 0}.bt_attemptPreview{color:var(--dsw-alias-state-error-primary);overflow-wrap:anywhere}',
229
+ '.bt_attempt>summary,.bt_network>summary{list-style:none}.bt_attempt>summary::-webkit-details-marker,.bt_network>summary::-webkit-details-marker{display:none}.bt_attempt>summary:before,.bt_network>summary:before{content:"›";flex:none;color:var(--dsw-alias-label-secondary)}.bt_attempt[open]>summary:before,.bt_network[open]>summary:before{content:"⌄"}.bt_attemptPreview{font:inherit;font-family:ui-monospace,monospace}.bt_original{max-height:340px;overflow:auto}.bt_network>summary{display:flex;align-items:baseline;flex-wrap:wrap;gap:4px 8px;min-height:28px;cursor:pointer}.bt_network>summary:focus-visible{outline:2px solid var(--dsw-alias-state-error-primary);outline-offset:2px}',
230
+ '.bt_reportText>summary{cursor:pointer;min-height:28px;font-size:12px;color:var(--dsw-alias-label-secondary)}.bt_reportText>summary:focus-visible,.bt_reportText pre:focus-visible{outline:2px solid var(--dsw-alias-state-error-primary);outline-offset:2px}',
231
+ '.bt_source{font:600 12px/1.6 system-ui,sans-serif;color:var(--dsw-alias-label-primary)}',
232
+ '.bt_errorGroup details{min-width:0}.bt_errorGroup details>summary,.bt_compact>summary{display:flex;align-items:center;flex-wrap:wrap;gap:5px 8px;min-height:32px;padding:4px 8px;border:1px solid var(--dsw-alias-border-l1);border-radius:5px;background:var(--dsw-alias-bg-layer-2);color:var(--dsw-alias-label-primary);cursor:pointer;list-style:none}',
233
+ '.bt_errorGroup details>summary::-webkit-details-marker{display:none}.bt_errorGroup details>summary:before,.bt_compact>summary:before{content:none}.bt_errorGroup details[open]>summary:before,.bt_compact[open]>summary:before{content:none}',
234
+ '.bt_toggleLabel{display:inline-flex;flex:none;padding:1px 5px;border-radius:3px;background:var(--dsw-alias-bg-layer-1);font:600 12px/1.7 system-ui,sans-serif;color:var(--dsw-alias-label-primary)}.bt_toggleLabel>.bt_whenOpen{display:none}details[open]>summary>.bt_toggleLabel>.bt_whenOpen{display:inline}details[open]>summary>.bt_toggleLabel>.bt_whenClosed{display:none}',
235
+ '.bt_errorGroup details>summary:hover,.bt_compact>summary:hover{border-color:var(--dsw-alias-state-error-primary)}.bt_errorGroup details>summary:focus-visible{outline:2px solid var(--dsw-alias-state-error-primary);outline-offset:2px}',
236
+ '.bt_detailBody{margin:0;padding:0}.bt_section{border-top:0;padding-top:4px}.bt_attempt{margin:8px 0;padding:0;border-left:0}',
237
+ '.bt_depth{display:grid;gap:8px;min-width:0;margin:8px 0 8px 10px;padding:4px 0 4px 12px;border-left:2px solid var(--dsw-alias-state-error-primary)}.bt_errorGroup .bt_depth>.bt_body{margin:0;padding:0}.bt_attempt>.bt_depth{padding:4px 0 4px 12px}.bt_logPanel{margin-left:10px;border-left:2px solid var(--dsw-alias-state-error-primary)}',
238
+ '.bt_heading{margin-bottom:5px}.bt_original{font-size:12px}.bt_toggleLabel[hidden]{display:none}',
239
+ '.bt_earlierNode{border-left:0;padding-left:0}.bt_earlierNode>.bt_depth,.bt_earlierErrors>.bt_depth,.bt_earlierError>.bt_depth{border-left:0;margin-left:0;padding-left:0}',
240
+ '.bt_earlierNode>summary{display:flex;align-items:center;gap:8px;cursor:pointer;list-style:none;font-size:12px;color:var(--dsw-alias-label-secondary)}.bt_earlierNode>summary::-webkit-details-marker{display:none}.bt_earlierNode>summary:focus-visible{outline:2px solid var(--dsw-alias-state-error-primary);outline-offset:2px}',
241
+ '.bt_failureTitle{font-size:17px;font-weight:700;line-height:1.5;color:var(--dsw-alias-state-error-primary)}',
242
+ '.bt_detailPair{display:grid;grid-template-columns:minmax(0,1fr);align-items:start;gap:8px;min-width:0}.bt_detailPair>details{margin:0}.bt_detailPair .bt_depth{margin-left:0;padding-left:8px}',
243
+ '.bt_errorGroup>.bt_network>.bt_body{margin-left:0}.bt_primary{font-size:15px;line-height:1.6}.bt_original{font-size:14px}',
244
+ '.bt_history{padding-top:0;display:grid;gap:6px}.bt_history>.bt_attempt{margin:0}.bt_history .bt_attempt>.bt_network>.bt_body{margin-left:0}.bt_attempt>.bt_captureAdvice{display:flex;align-items:baseline;gap:4px 8px;padding:2px 0}',
245
+ '@media(max-width:640px){.bt_errorGroup{grid-template-columns:minmax(0,1fr);padding-left:9px}.bt_detailPair{grid-template-columns:minmax(0,1fr)}}',
246
+ ].join('')
247
+ const text = (value) => value === undefined || value === null ? '' : String(value)
248
+ const rawFailure = (failure) => [failure?.code ? `[${failure.code}]` : '', text(failure?.message)].filter(Boolean).join(' ')
249
+
250
+ /** Native codes only; never infer a cause from the Harness category. */
251
+ function nativeHeadline (detail) {
252
+ if (!detail) return ''
253
+ if (detail.kind === 'response') return [`HTTP ${detail.status ?? '?'}`, text(detail.statusText)].filter(Boolean).join(' ')
254
+ const chain = []
255
+ let error = detail.error
256
+ for (let depth = 0; error && depth < 16; depth++, error = error.cause) chain.push(error)
257
+ const coded = chain.filter((entry) => entry.code !== undefined && entry.code !== '')
258
+ return rawFailure(coded.at(-1) ?? chain.at(-1)) || (detail.kind === 'stream' ? `HTTP ${detail.status ?? 200}` : '')
259
+ }
260
+ const knownCheck = (code) => Object.hasOwn(CODE_CHECKS, code) ? CODE_CHECKS[code] : undefined
261
+ const httpCheck = (status) => HTTP_CHECKS[status] ?? (status >= 500 && status <= 599 ? 'server' : 'generic')
262
+ function providerCheck (body) {
263
+ try {
264
+ const parsed = JSON.parse(body)
265
+ const error = parsed?.error
266
+ // Only structured, allowlisted provider codes; arbitrary response prose is not a diagnosis.
267
+ for (const code of [error?.code, error?.type, parsed?.code, parsed?.type]) {
268
+ if (typeof code === 'string' && knownCheck(code)) return knownCheck(code)
269
+ }
270
+ } catch { /* Truncated/non-JSON bodies stay raw evidence. */ }
271
+ return undefined
272
+ }
273
+ function failureCheck (failure) {
274
+ if (text(failure?.message) === 'Stream ended without finish_reason') return 'finishReason'
275
+ const byCode = knownCheck(text(failure?.code))
276
+ if (byCode) return byCode
277
+ const message = text(failure?.message)
278
+ const prefix = message.match(/^\s*\[?([A-Z][A-Z0-9_]+)\]?(?=\s|:|$)/)?.[1]
279
+ if (prefix && knownCheck(prefix)) return knownCheck(prefix)
280
+ const status = message.match(/^\s*(?:HTTP\s+)?([45]\d{2})(?=\s|:|$)/)?.[1]
281
+ if (status) return httpCheck(Number(status))
282
+ if (message === 'terminated') return 'stream'
283
+ if (message === 'cannot get required service "tools" in inactive context') return 'tools'
284
+ return 'generic'
285
+ }
286
+ function detailCheck (detail) {
287
+ if (detail?.kind === 'response') return (!detail.bodyState || detail.bodyState === 'complete' ? providerCheck(detail.body) : undefined) ?? httpCheck(detail.status)
288
+ let native
289
+ for (let error = detail?.error, depth = 0; error && depth < 16; depth++, error = error.cause) {
290
+ if (error.code) native = error.code
291
+ }
292
+ if (native) return knownCheck(text(native)) ?? 'generic'
293
+ return detail?.kind === 'stream' ? 'stream' : failureCheck(detail?.error)
294
+ }
295
+ function adviceRow (key, t, className = 'bt_advice') {
296
+ return h('div', { className }, h('span', { className: 'bt_title' }, t('ui.advice')),
297
+ h('span', null, t(`check.${key}`)))
298
+ }
299
+ function captureText (item) {
300
+ const detail = item?.detail ?? {}
301
+ const lines = []
302
+ if (detail.status !== undefined) lines.push([`HTTP ${detail.status}`, detail.statusText].filter(Boolean).join(' '))
303
+ const endpoint = `${detail.host ?? ''}${detail.path ?? ''}`
304
+ if (endpoint) lines.push(endpoint)
305
+ for (const [key, value] of Object.entries(detail.headers ?? {})) lines.push(`${key}: ${value}`)
306
+ let error = detail.error
307
+ for (let depth = 0; error && depth < 16; depth++, error = error.cause) {
308
+ lines.push([depth ? '←' : '', error.name, rawFailure(error)].filter(Boolean).join(' '))
309
+ const fields = ['errno', 'syscall', 'address', 'port'].filter((key) => error[key] !== undefined)
310
+ if (fields.length) lines.push(fields.map((key) => `${key}=${error[key]}`).join(' '))
311
+ }
312
+ if (detail.bytes !== undefined) lines.push(`bytes=${detail.bytes}`)
313
+ if (detail.elapsedMs !== undefined) lines.push(`elapsedMs=${detail.elapsedMs}`)
314
+ if (item?.lagMs !== undefined) lines.push(`lagMs=${item.lagMs}`)
315
+ if (detail.body) lines.push('', text(detail.body))
316
+ return lines.join('\n')
317
+ }
318
+ async function fetchJson (url, signal) {
319
+ const response = await fetch(url, { credentials: 'same-origin', headers: { accept: 'application/json' }, signal })
320
+ if (!response.ok) throw new Error(`HTTP ${response.status}`)
321
+ return response.json()
322
+ }
323
+ function useEvidence (url, revision) {
324
+ const [state, setState] = React.useState(null)
325
+ const [refreshIndex, setRefreshIndex] = React.useState(0)
326
+ const identity = JSON.stringify([url, revision, refreshIndex])
327
+ const cache = React.useRef(null)
328
+ React.useEffect(() => {
329
+ if (!url) return undefined
330
+ if (cache.current?.identity === identity) { setState(cache.current); return undefined }
331
+ setState(null)
332
+ let cancelled = false
333
+ const controller = new AbortController()
334
+ const publish = (value) => { if (!cancelled) setState({ ...value, identity }) }
335
+ const timeout = setTimeout(() => { controller.abort(); publish({ error: 'Request timeout' }) }, 10000)
336
+ Promise.resolve().then(() => {
337
+ if (controller.signal.aborted) return undefined
338
+ return fetchJson(url, controller.signal)
339
+ }).then((data) => {
340
+ if (!cancelled && !controller.signal.aborted) {
341
+ cache.current = { data, identity }
342
+ setState(cache.current)
343
+ }
344
+ }).catch((error) => { if (!controller.signal.aborted) publish({ error: text(error?.message ?? error) }) })
345
+ .finally(() => clearTimeout(timeout))
346
+ return () => { cancelled = true; clearTimeout(timeout); controller.abort() }
347
+ }, [url, revision, refreshIndex])
348
+ return [state?.identity === identity ? state : null, () => setRefreshIndex((value) => value + 1)]
349
+ }
350
+ function CopyButton ({ value, label, t }) {
351
+ const [status, setStatus] = React.useState('')
352
+ const alive = React.useRef(true)
353
+ React.useEffect(() => { alive.current = true; return () => { alive.current = false } }, [])
354
+ const copy = async () => {
355
+ setStatus('ui.copying')
356
+ try {
357
+ if (typeof navigator?.clipboard?.writeText !== 'function') throw new Error('clipboard unavailable')
358
+ await navigator.clipboard.writeText(value)
359
+ if (alive.current) setStatus('ui.copied')
360
+ } catch { if (alive.current) setStatus('ui.copyFailed') }
361
+ }
362
+ return h('span', { className: 'bt_actions' },
363
+ h('button', { type: 'button', className: 'bt_action bt_copy', disabled: !value || status === 'ui.copying', onClick: copy }, t(label)),
364
+ status ? h('span', { className: 'bt_meta', role: 'status' }, t(status)) : null)
365
+ }
366
+ function disclosureBlock (props, summary, ...children) {
367
+ return h('details', props, summary, h('div', { className: 'bt_depth' }, ...children))
368
+ }
369
+ function toggleLabel (t) {
370
+ return h('span', { className: 'bt_toggleLabel' },
371
+ h('span', { className: 'bt_whenClosed' }, '▶ ' + t('ui.open')),
372
+ h('span', { className: 'bt_whenOpen' }, '▼ ' + t('ui.close')))
373
+ }
374
+ function RefreshButton ({ refresh, t }) {
375
+ return refresh ? h('button', { type: 'button', className: 'bt_action bt_refresh', onClick: refresh }, t('ui.refresh')) : null
376
+ }
377
+ function capturePreview (detail) {
378
+ const headline = nativeHeadline(detail)
379
+ let message = ''
380
+ if (detail?.kind === 'response' && !detail.protected && detail.bodyReason !== 'credential-protection') {
381
+ message = text(detail.body)
382
+ if (!detail.bodyState || detail.bodyState === 'complete') {
383
+ try {
384
+ const parsed = JSON.parse(message)
385
+ const providerMessage = parsed?.error?.message ?? parsed?.message
386
+ if (typeof providerMessage === 'string') message = providerMessage
387
+ } catch { /* Non-JSON responses stay literal. */ }
388
+ }
389
+ }
390
+ return failurePreview({ message: [headline, message].filter(Boolean).join(' · ') })
391
+ }
392
+ function captureDetails (item, t, unconfirmed = false) {
393
+ return item?.detail ? disclosureBlock({ className: 'bt_networkDetails' },
394
+ h('summary', { className: 'bt_meta' }, toggleLabel(t), t('ui.details')),
395
+ unconfirmed ? h('div', { className: 'bt_meta' }, t('ui.unconfirmed')) : null,
396
+ unconfirmed ? adviceRow(detailCheck(item.detail), t, 'bt_captureAdvice') : null,
397
+ h('pre', { className: 'bt_raw' }, captureText(item))) : null
398
+ }
399
+ function captureBlock (item, index, t, unconfirmed = false, showFailure = false, details = true, inlineCopy = true, captureAdvice = true) {
400
+ const preview = capturePreview(item?.detail)
401
+ return h('div', { className: 'bt_capture', key: `capture-${index}` },
402
+ unconfirmed ? h('span', { className: 'bt_meta' }, t('ui.unconfirmed')) : null,
403
+ showFailure && item?.failure ? h('span', { className: 'bt_meta' }, rawFailure(item.failure)) : null,
404
+ preview.value ? h('code', { className: 'bt_primary' }, preview.value) : null,
405
+ inlineCopy ? h(CopyButton, { value: captureText(item), label: 'ui.copyCapture', t }) : null,
406
+ details ? captureDetails(item, t) : null,
407
+ item?.detail?.kind === 'response' && (item.detail.bodyReason === 'credential-protection' || item.detail.bodyState !== 'complete' && item.detail.bodyState !== undefined || !item.detail.body) ? h('span', { className: 'bt_meta' },
408
+ t(item.detail.bodyReason === 'credential-protection' ? 'ui.authBodyProtected' : item.detail.bodyState === 'pending' ? 'ui.bodyPending' : item.detail.bodyState === 'truncated' ? 'ui.bodyTruncated'
409
+ : item.detail.bodyState === 'unreadable' || item.detail.bodyState === 'error' ? 'ui.bodyUnreadable'
410
+ : 'ui.bodyEmpty')) : null,
411
+ unconfirmed && captureAdvice ? adviceRow(detailCheck(item?.detail), t, 'bt_captureAdvice') : null)
412
+ }
413
+ function networkSection (selection, state, refresh, t, details = true) {
414
+ return h('section', { className: 'bt_section bt_network' },
415
+ h('h4', { className: 'bt_heading' }, t('ui.network')),
416
+ evidenceBody({ state, ...selection, refresh, details }, t))
417
+ }
418
+ function evidenceBody ({ state, failure, chosen, unconfirmed, candidates = [], extra, refresh, details = true, inlineCopy = true, captureAdvice = true }, t) {
419
+ return h('div', { className: 'bt_body' },
420
+ rawFailure(failure) ? h('pre', { className: 'bt_raw' }, rawFailure(failure)) : null,
421
+ chosen?.detail ? captureBlock(chosen, 0, t, unconfirmed, false, details, inlineCopy, captureAdvice) : null,
422
+ candidates.length ? disclosureBlock( null,
423
+ h('summary', { className: 'bt_meta' }, toggleLabel(t), t('ui.candidates', { count: candidates.length })),
424
+ ...candidates.map((item, index) => disclosureBlock( { className: 'bt_attempt', key: item.attemptId ?? index },
425
+ h('summary', { className: 'bt_meta' }, toggleLabel(t), t('ui.record', { index: index + 1 }), failurePreview(item.failure).value),
426
+ captureBlock(item, index, t, true, true)))) : null,
427
+ !state ? h('span', { className: 'bt_meta' }, t('ui.loading'))
428
+ : state.error ? h('span', { className: 'bt_meta' }, t('ui.loadFailed', { message: state.error }))
429
+ : !chosen?.detail && !candidates.length && !extra ? h('span', { className: 'bt_meta' }, t(state.data?.capture?.installed === false ? state.data.capture.reason === 'config-disabled' ? 'ui.disabled' : 'ui.captureUnavailable' : 'ui.empty')) : null,
430
+ h(RefreshButton, { refresh, t }),
431
+ extra ?? null)
432
+ }
433
+ function selectStep (state, step, failure, row = {}, sessionId) {
434
+ const items = (Array.isArray(state?.data?.items) ? state.data.items : []).filter((item) => item?.step === step)
435
+ const exact = items.filter((item) => text(item.failure?.message) === text(failure.message) && text(item.failure?.code) === text(failure.code))
436
+ let matches = exact
437
+ let timeBased = false
438
+ const attemptId = row.attemptId ?? failure.attemptId
439
+ if (attemptId) matches = exact.filter((item) => item.attemptId === attemptId)
440
+ else if (exact.length > 1 && Number.isFinite(row.time)) {
441
+ timeBased = true
442
+ const near = exact.filter((item) => Number.isFinite(item.failureTime) && Math.abs(item.failureTime - row.time) <= 10)
443
+ const distance = near.length ? Math.min(...near.map((item) => Math.abs(item.failureTime - row.time))) : Infinity
444
+ matches = near.filter((item) => Math.abs(item.failureTime - row.time) === distance)
445
+ }
446
+ const chosen = matches.length === 1 ? matches[0] : !exact.length && items.length === 1 ? items[0] : undefined
447
+ const context = chosen?.context ?? chosen?.detail?.context
448
+ const confirmed = !timeBased && !!chosen && matches.length === 1 && matches[0] === chosen && chosen.provenance === 'request-context'
449
+ && chosen.approximate !== true && context?.sessionId === sessionId
450
+ && typeof chosen.attemptId === 'string' && chosen.attemptId !== '' && context.attemptId === chosen.attemptId
451
+ && typeof context.provider === 'string' && context.provider !== ''
452
+ && (!row.provider || context.provider === row.provider)
453
+ && (!attemptId || context.attemptId === attemptId)
454
+ return { chosen, unconfirmed: !!chosen && !confirmed, candidates: chosen ? [] : items }
455
+ }
456
+ function requestUrl (sessionId, turn, kind) {
457
+ if (!sessionId || !Number.isSafeInteger(turn)) return ''
458
+ return `api/better-tips/details?${new URLSearchParams({ sessionId, turn: String(turn), source: 'row', kind })}`
459
+ }
460
+ function logCoordinate (node) {
461
+ const data = node?.data ?? {}
462
+ const kind = node?.kind ?? data.kind
463
+ if (kind === 'model-retry' || data.current) {
464
+ return { kind: 'retry', seq: data.current?.seq, data: data.current ?? {} }
465
+ }
466
+ if (kind === 'manual-compaction' || data.command) {
467
+ return { kind: 'command', seq: data.command?.seq, data: data.command ?? {} }
468
+ }
469
+ if (kind === KIND || data.compactionId) {
470
+ return { kind: 'compaction', seq: data.endSeq ?? node?.anchorSeq, data }
471
+ }
472
+ return { kind: 'terminal', seq: data.seq ?? node?.anchorSeq, data }
473
+ }
474
+ const validSeq = (seq) => Number.isSafeInteger(seq) && seq >= 0
475
+ function matchesLog (event, coordinate) {
476
+ const actual = event?.data ?? {}
477
+ const expected = coordinate.data
478
+ const same = (key) => expected[key] === undefined || actual[key] === expected[key]
479
+ if (coordinate.kind === 'retry') return event.type === 'llm/retry' && ['turn', 'step', 'retryId', 'retry'].every(same)
480
+ if (coordinate.kind === 'command') return event.type === 'command/done' && expected.commandId && actual.commandId === expected.commandId
481
+ if (coordinate.kind === 'compaction') return event.type === 'compaction/end' && expected.compactionId && actual.compactionId === expected.compactionId
482
+ return event.type === 'turn/end' && same('turn')
483
+ }
484
+ function logWindow (binding, coordinate) {
485
+ const events = (binding.eventSource.getSnapshot()?.entries ?? [])
486
+ .filter((entry) => entry.type === 'event').map((entry) => entry.event)
487
+ let matches
488
+ if (coordinate.kind === 'command') {
489
+ matches = events.filter((event) => event.seq >= coordinate.seq && matchesLog(event, coordinate))
490
+ } else {
491
+ matches = events.filter((event) => event.seq === coordinate.seq && matchesLog(event, coordinate))
492
+ }
493
+ if (matches.length !== 1) return { missing: true }
494
+ const target = matches[0]
495
+ const index = events.indexOf(target)
496
+ return { target, events: events.slice(Math.max(0, index - 3), index + 4) }
497
+ }
498
+ function safeLogValue (value) {
499
+ if (typeof value === 'string') return value
500
+ .replace(/Bearer\s+[A-Za-z0-9._~+/=-]{8,}/gi, 'Bearer [redacted]')
501
+ .replace(/sk-[A-Za-z0-9._-]{8,}/gi, 'sk-[redacted]')
502
+ .replace(/\b(?:api[_-]?key|token|secret)["']?\s*[:=]\s*["']?[A-Za-z0-9._~+/=-]{8,}/gi, '[credential redacted]')
503
+ if (Array.isArray(value)) return value.map(safeLogValue)
504
+ if (!value || typeof value !== 'object') return value
505
+ const compactionError = value.type === 'compaction/end' && typeof value.data?.error === 'string'
506
+ ? safeCompactionFailure(value.data.error) : undefined
507
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [key,
508
+ value.type === 'compaction/end' && key === 'data' && typeof item?.error === 'string'
509
+ ? safeLogValue({ ...item, error: compactionError?.message || '[compaction diagnostic hidden]' })
510
+ : value.code === 'AUTH' && (key === 'message' || key === 'body') ? '[AUTH diagnostic hidden]' : safeLogValue(item)]))
511
+ }
512
+ const reportTime = (value, t) => {
513
+ if (!Number.isFinite(value) || Math.abs(value) > 8640000000000000) return t('report.missing')
514
+ return new Date(value).toLocaleString('zh-CN', { hour12: false }) + ' (' + Intl.DateTimeFormat().resolvedOptions().timeZone + ')'
515
+ }
516
+ const reportExcerpt = (value, limit, t) => {
517
+ const clean = text(value).replace(/\s+/g, ' ').trim()
518
+ const chars = Array.from(clean)
519
+ return chars.length > limit ? chars.slice(0, limit).join('') + '… [' + t('report.truncated') + ']' : clean
520
+ }
521
+ /** A short support message, not a dump of every diagnostic field. Full evidence stays in the UI. */
522
+ function troubleshootingReport ({ failure, row = {}, selection = {}, runtime, title, error, capture, record }, t) {
523
+ const selected = selection.chosen
524
+ const detail = selected?.detail
525
+ const protectedAuth = failure?.code === 'AUTH' || selected?.failure?.code === 'AUTH' || selected?.thrown?.code === 'AUTH' || detail?.protected === true
526
+ const missing = t('report.missing')
527
+ let native = protectedAuth ? '[AUTH] ' + t('report.protected') : rawFailure(failure) || missing
528
+ if (!protectedAuth) {
529
+ const wrapper = text(failure?.message).match(/^\s*(?:HTTP\s+)?([45]\d{2}):\s*(\{[\s\S]*\})\s*$/)
530
+ if (wrapper) {
531
+ try {
532
+ const parsed = JSON.parse(wrapper[2])
533
+ const message = parsed?.error?.message ?? parsed?.message
534
+ if (typeof message === 'string') native = [failure?.code ? '[' + failure.code + ']' : '', 'HTTP ' + wrapper[1], message].filter(Boolean).join(' ')
535
+ } catch {}
536
+ }
537
+ }
538
+ const headline = protectedAuth ? '[AUTH]' : failurePreview(failure).value || title
539
+ const lines = [t('report.intro', {
540
+ time: reportTime(row.time ?? row.endedAt, t),
541
+ provider: row.provider || record?.provider || selected?.context?.provider || missing,
542
+ model: record?.model || selected?.context?.model || missing,
543
+ error: reportExcerpt(headline, 100, t).replace(/[.。…]+$/, ''),
544
+ }), t('report.version') + ': DSH ' + (runtime?.dshVersion || missing) + ' · Better Tips ' + (runtime?.pluginVersion || missing)]
545
+ const plugins = Array.isArray(runtime?.enabledPlugins) ? runtime.enabledPlugins : []
546
+ const pluginNames = [...new Set(plugins.filter((plugin) => typeof plugin?.name === 'string' && plugin.name.trim())
547
+ .map((plugin) => plugin.name + '@' + (typeof plugin.version === 'string' && plugin.version.trim() ? plugin.version : missing)))].sort()
548
+ const inventory = runtime?.pluginsStatus === 'complete' ? pluginNames.join('、') || t('report.pluginsNone')
549
+ : (pluginNames.length ? pluginNames.join('、') + ' · ' : '') + t(runtime?.pluginsStatus === 'partial' ? 'report.pluginsPartial' : 'report.pluginsUnavailable')
550
+ lines.push(t('report.plugins') + ': ' + inventory, '', t('report.native') + ': ' + reportExcerpt(native, 600, t))
551
+ if (record || selection.unconfirmed) lines.push('', t('report.unconfirmed'))
552
+ if (record) lines.push(t('report.summaryError') + ': ' +
553
+ (protectedAuth ? t('report.protected') : reportExcerpt(rawFailure(selected?.failure ?? selected?.thrown) || (selected?.finishReason ? 'finish=' + selected.finishReason : missing), 300, t)))
554
+ if (!detail) lines.push(t('report.underlying') + ': ' +
555
+ (error ? t('report.noEvidence') + ' · ' + t('report.readFailed') + ': ' + reportExcerpt(error, 80, t)
556
+ : capture?.installed === false ? t(capture.reason === 'config-disabled' ? 'ui.disabled' : 'ui.captureUnavailable')
557
+ : t('report.noEvidence') + (selection.candidates?.length ? ' · ' + t('report.ambiguous') : '')))
558
+ else {
559
+ const safeDetail = protectedAuth ? { kind: detail.kind, status: detail.status } : detail
560
+ lines.push(t('report.underlying') + ': ' + reportExcerpt(nativeHeadline(safeDetail) || missing, 300, t))
561
+ const headers = detail.headers ?? {}
562
+ const requestId = failure?.requestId || headers['x-request-id'] || headers['request-id'] || headers['x-correlation-id'] || headers['cf-ray']
563
+ if (requestId) lines.push('request-id: ' + reportExcerpt(requestId, 160, t))
564
+ if (detail.host || detail.path) lines.push('API: ' + (detail.host || '') + (detail.path || ''))
565
+ if (!protectedAuth && detail.body) {
566
+ let body = detail.body
567
+ try { const parsed = JSON.parse(body); body = parsed?.error?.message ?? parsed?.message ?? body } catch {}
568
+ const response = reportExcerpt(body, 300, t)
569
+ // Often pi-ai already includes the same provider message; do not repeat it.
570
+ if (response && !native.includes(text(body))) lines.push(t('report.response') + ': ' + response)
571
+ }
572
+ if (protectedAuth) lines.push(t('report.protected'))
573
+ else if (detail.bodyState && detail.bodyState !== 'complete') lines.push(t('report.responseState') + ': ' + detail.bodyState)
574
+ }
575
+ const params = []
576
+ if (Number.isFinite(detail?.elapsedMs)) params.push(t('report.timing') + ' ' + detail.elapsedMs + ' ms')
577
+ if (Number.isFinite(row.delayMs)) params.push(t('report.wait') + ' ' + row.delayMs + ' ms')
578
+ if (row.retry !== undefined) params.push(t('report.retry') + ' ' + row.retry + '/' + (row.maxRetries ?? '?'))
579
+ const after = failure?.providerRetryAfterMs ?? detail?.headers?.['retry-after']
580
+ if (after !== undefined) params.push('Retry-After ' + after + (failure?.providerRetryAfterMs !== undefined ? ' ms' : ''))
581
+ if (params.length) lines.push(params.join(';'))
582
+ lines.push('', t('report.help'))
583
+ return safeLogValue(lines.join('\n'))
584
+ }
585
+ function ReportButton ({ url, state, select, failure, row, title, record, t }) {
586
+ const [status, setStatus] = React.useState('')
587
+ const [report, setReport] = React.useState('')
588
+ const alive = React.useRef(true)
589
+ const operation = React.useRef(null)
590
+ React.useEffect(() => {
591
+ alive.current = true
592
+ return () => { alive.current = false; operation.current?.abort() }
593
+ }, [])
594
+ const copy = async () => {
595
+ if (operation.current) return
596
+ const controller = new AbortController()
597
+ operation.current = controller
598
+ setStatus('report.building')
599
+ const timer = setTimeout(() => controller.abort(), 10000)
600
+ let data = state?.data
601
+ let problem = state?.error
602
+ try {
603
+ if (!data && url) {
604
+ try { data = await fetchJson(url, controller.signal); problem = undefined }
605
+ catch (error) { problem = controller.signal.aborted ? 'Request timeout' : text(error?.message ?? error) }
606
+ }
607
+ if (!alive.current || operation.current !== controller) return
608
+ let environment
609
+ try { environment = await fetchJson('api/better-tips/environment', controller.signal) }
610
+ catch { environment = undefined }
611
+ if (!alive.current || operation.current !== controller) return
612
+ const selected = select?.({ data }) ?? {}
613
+ const runtime = { ...data?.runtime, ...environment?.runtime,
614
+ enabledPlugins: environment?.runtime?.enabledPlugins,
615
+ pluginsStatus: Array.isArray(environment?.runtime?.enabledPlugins) ? environment.runtime.pluginsStatus ?? 'unavailable' : 'unavailable' }
616
+ const value = troubleshootingReport({ failure, row, title, runtime,
617
+ selection: selected, record: selected.record ?? record, error: problem, capture: data?.capture }, t)
618
+ setReport(value)
619
+ const partial = !runtime?.dshVersion || runtime.pluginsStatus !== 'complete' || !selected.chosen?.detail || !!problem
620
+ try {
621
+ if (typeof navigator?.clipboard?.writeText !== 'function') throw new Error('clipboard unavailable')
622
+ await navigator.clipboard.writeText(value)
623
+ if (alive.current && operation.current === controller) setStatus(partial ? 'report.partial' : 'ui.copied')
624
+ } catch { if (alive.current && operation.current === controller) setStatus('report.fallback') }
625
+ } finally { clearTimeout(timer); if (operation.current === controller) operation.current = null }
626
+ }
627
+ return h('div', { className: 'bt_report' },
628
+ h('div', { className: 'bt_actions' },
629
+ h('button', { type: 'button', className: 'bt_action bt_reportCopy', title: t('report.notice'), disabled: status === 'report.building', onClick: copy }, t('report.copy')),
630
+ status ? h('span', { className: 'bt_meta', role: 'status' }, t(status)) : null),
631
+ report && status === 'report.fallback' ? h('div', { className: 'bt_reportText' },
632
+ h('pre', { className: 'bt_raw', tabIndex: 0 }, report)) : null)
633
+ }
634
+ function RawLog ({ sessionId, node, t, capture, unconfirmed }) {
635
+ const [open, setOpen] = React.useState(false)
636
+ const [state, setState] = React.useState(null)
637
+ const [readIndex, setReadIndex] = React.useState(0)
638
+ const coordinate = logCoordinate(node)
639
+ const identity = JSON.stringify([sessionId, coordinate])
640
+ React.useEffect(() => {
641
+ if (!open) return undefined
642
+ let cancelled = false
643
+ let release
644
+ setState(null)
645
+ const fail = (error) => { if (!cancelled) setState({ error: text(error?.message ?? error) }) }
646
+ try {
647
+ const binding = sessionService?.binding(sessionId)
648
+ if (!binding?.eventSource || typeof binding.session?.loadThrough !== 'function') {
649
+ setState({ unavailable: true })
650
+ return undefined
651
+ }
652
+ const readCurrent = () => {
653
+ if (cancelled) return
654
+ try { setState(logWindow(binding, coordinate)) } catch (error) { fail(error) }
655
+ }
656
+ release = binding.eventSource.subscribe(readCurrent)
657
+ Promise.resolve(binding.session.loadThrough(coordinate.seq)).then(readCurrent, fail)
658
+ } catch (error) { fail(error) }
659
+ return () => { cancelled = true; release?.() }
660
+ }, [open, identity, readIndex])
661
+ const target = state?.target
662
+ const metadataUrl = open && target ? `api/better-tips/log-metadata?${new URLSearchParams({ sessionId, seq: String(target.seq) })}` : ''
663
+ const [metadata, refreshMetadata] = useEvidence(metadataUrl, target?.seq)
664
+ return h('div', { className: open ? 'bt_log bt_logOpen' : 'bt_log' },
665
+ h('button', { type: 'button', className: 'bt_logButton', disabled: !sessionId || !validSeq(coordinate.seq),
666
+ title: validSeq(coordinate.seq) ? t('log.title') : t('log.noCoordinate'), 'aria-expanded': open,
667
+ onClick: () => setOpen((value) => !value) }, t(open ? 'log.close' : 'log.open')),
668
+ open ? h('section', { className: 'bt_logPanel', 'aria-label': t('log.title') },
669
+ h('div', { className: 'bt_logHeading' }, `${t('log.title')} · ${sessionId}`),
670
+ h('div', { className: 'bt_meta' }, t('log.protected')),
671
+ h('div', { className: 'bt_actions' },
672
+ target ? h(CopyButton, { value: `${sessionId} · seq=${target.seq}`, label: 'ui.copyCoordinate', t }) : null,
673
+ h(RefreshButton, { refresh: () => { setReadIndex((value) => value + 1); refreshMetadata() }, t })),
674
+ !state ? h('div', { className: 'bt_meta' }, t('log.loading'))
675
+ : state.error ? h('div', { className: 'bt_meta', role: 'status' }, t('log.failed', { message: state.error }))
676
+ : state.unavailable ? h('div', { className: 'bt_meta', role: 'status' }, t('log.unavailable'))
677
+ : state.missing ? h('div', { className: 'bt_meta', role: 'status' }, t('log.missing')) : null,
678
+ target ? h('div', { className: 'bt_logMetadata' },
679
+ !metadata ? h('div', { className: 'bt_meta' }, t('log.metadataLoading'))
680
+ : metadata.error ? h('div', { className: 'bt_meta' }, `${t('log.metadataFailed')} · ${metadata.error}`)
681
+ : h(React.Fragment, null,
682
+ h('div', { className: 'bt_logHeading' }, t('log.file')),
683
+ h('pre', { className: 'bt_raw bt_logPath' }, metadata.data?.log?.status === 'found' ? metadata.data.log.path : t('log.pathMissing')),
684
+ metadata.data?.log?.status === 'found' ? h(CopyButton, { value: metadata.data.log.path, label: 'ui.copyPath', t }) : null,
685
+ h('div', { className: 'bt_meta' }, `seq=${target.seq} · ${t('log.logical')}`),
686
+ ...(metadata.data?.sources?.length ? [h('div', { className: 'bt_meta', key: 'source-title' }, t('log.sourceMatch')),
687
+ ...metadata.data.sources.map((source, index) => h('div', { className: 'bt_logSource', key: index },
688
+ h('div', { className: 'bt_logHeading' }, `${t(source.role === 'classifier' ? 'log.classifier' : 'log.producer')} · ${source.function}`),
689
+ h('pre', { className: 'bt_raw' }, `${source.path}:${source.line}`)))]
690
+ : [h('div', { className: 'bt_meta', key: 'unknown-source' }, t('log.sourceUnknown'))]))) : null,
691
+ target ? h('div', { className: 'bt_logTarget', 'data-seq': target.seq },
692
+ h('div', { className: 'bt_logHeading' }, `${t('log.target')} · #${target.seq} · ${target.type}`),
693
+ h('pre', { className: 'bt_raw bt_logJson' }, JSON.stringify(safeLogValue(target), null, 2))) : null,
694
+ target ? disclosureBlock( { className: 'bt_logContext' }, h('summary', { className: 'bt_meta' }, toggleLabel(t), t('log.context')),
695
+ h('div', { className: 'bt_meta' }, t('log.contextWarning')),
696
+ ...state.events.filter((event) => event !== target).map((event) => disclosureBlock( { key: event.seq },
697
+ h('summary', { className: 'bt_meta' }, toggleLabel(t), `#${event.seq} · ${event.type}`),
698
+ h('pre', { className: 'bt_raw' }, JSON.stringify(safeLogValue(event), null, 2))))) : null,
699
+ capture?.detail ? disclosureBlock( null,
700
+ h('summary', { className: 'bt_meta' }, toggleLabel(t), `${t('log.capture')}${capture.detail.id !== undefined ? ` · #${capture.detail.id}` : ''}${unconfirmed ? ` · ${t('ui.unconfirmed')}` : ''}`),
701
+ h('pre', { className: 'bt_raw' }, JSON.stringify(safeLogValue(capture.detail), null, 2))) : null,
702
+ h('div', { className: 'bt_meta' }, t('log.notWire'))) : null)
703
+ }
704
+ /** Literal excerpt, not a diagnosis. Complete text remains in the disclosure. */
705
+ function failurePreview (failure) {
706
+ const original = rawFailure(failure)
707
+ let excerpt = original
708
+ const message = text(failure?.message)
709
+ const structured = message.match(/^\s*(?:HTTP\s+)?([45]\d{2}):\s*(\{[\s\S]*\})\s*$/)
710
+ if (structured) {
711
+ try {
712
+ const body = JSON.parse(structured[2])
713
+ const providerMessage = body?.error?.message ?? body?.message
714
+ if (typeof providerMessage === 'string') excerpt = [failure?.code ? `[${failure.code}]` : '', `HTTP ${structured[1]}`, providerMessage].filter(Boolean).join(' ')
715
+ } catch { /* Unparseable source stays a literal excerpt. */ }
716
+ }
717
+ const first = excerpt.split(/\r?\n/, 1)[0]
718
+ const points = Array.from(first)
719
+ const shortened = excerpt !== original || points.length > 120 || first.length < original.length
720
+ return { value: points.slice(0, 120).join('') + (points.length > 120 || first.length < excerpt.length ? '…' : ''), shortened }
721
+ }
722
+ function originalControls (failure, t) {
723
+ return h('div', { className: 'bt_originalControls' },
724
+ h('pre', { className: 'bt_original' }, rawFailure(failure)),
725
+ h(CopyButton, { value: rawFailure(failure), label: 'ui.copyError', t }))
726
+ }
727
+ function errorRow (title, failure, state, selection, t, log, disclosure = {}) {
728
+ const check = selection.check ?? (text(failure?.message) === 'Stream ended without finish_reason' ? 'finishReason'
729
+ : selection.chosen?.detail && !selection.unconfirmed ? detailCheck(selection.chosen.detail) : failureCheck(failure))
730
+ const nativeFallback = disclosure.fallbackNative && !selection.chosen?.detail
731
+ return h('div', { className: 'bt_errorGroup' },
732
+ h('div', { className: 'bt_failureTitle' }, title),
733
+ nativeFallback ? h('section', { className: 'bt_section bt_nativeFallback' },
734
+ h('h4', { className: 'bt_heading' }, t('ui.original')),
735
+ originalControls(failure, t),
736
+ evidenceBody({ state }, t))
737
+ : disclosure.historyOnly ? null : networkSection(selection, state, null, t, false),
738
+ disclosure.nativeStatus ?? null,
739
+ disclosure.historyOnly ? null : failure?.code === 'AUTH' && !failure.message ? h('div', { className: 'bt_protected' }, t('ui.authProtected')) : adviceRow(check, t),
740
+ disclosure.historyOnly ? null : disclosure.report ?? null,
741
+ disclosure.historyOnly ? disclosure.history : h('div', { className: 'bt_detailPair' },
742
+ captureDetails(selection.chosen, t),
743
+ disclosureBlock({ className: 'bt_error bt_disclosure', open: disclosure.open, onToggle: disclosure.onToggle },
744
+ h('summary', null, toggleLabel(t), h('span', { className: 'bt_title' }, t(nativeFallback ? 'ui.logSection' : 'ui.original')), disclosure.countLabel || null),
745
+ h('div', { className: 'bt_body bt_detailBody' },
746
+ nativeFallback ? null : originalControls(failure, t),
747
+ disclosure.history ?? null,
748
+ log ? h('section', { className: 'bt_section' },
749
+ h('h4', { className: 'bt_heading' }, t('ui.logSection')),
750
+ h(RawLog, { ...log, key: JSON.stringify([log.sessionId, logCoordinate(log.node)]), t, capture: selection.chosen, unconfirmed: selection.unconfirmed })) : null))),
751
+ !disclosure.historyOnly ? h(RefreshButton, { refresh: log?.refresh, t }) : null)
752
+ }
753
+ function ErrorCard ({ title, failure, sessionId, node, url, revision, select, history, countLabel, historyOnly, reportFailure, reportRow, t }) {
754
+ const [open, setOpen] = React.useState(false)
755
+ const [state, refresh] = useEvidence(url, revision)
756
+ const selection = select(state)
757
+ return errorRow(title, failure, state, selection, t, { sessionId, node, refresh }, {
758
+ open, onToggle: (event) => { if (!event.target || event.target === event.currentTarget) setOpen(event.currentTarget.open) },
759
+ countLabel: countLabel?.(state), history: history?.(state, refresh), historyOnly, overview: selection.check === 'mixed',
760
+ report: h(ReportButton, { key: JSON.stringify([sessionId, logCoordinate(node), revision]), url, state, select,
761
+ failure: reportFailure ?? failure, row: reportRow ?? node?.data, title, t }),
762
+ })
763
+ }
764
+ function TurnErrorRow ({ node, sessionId, t = (key) => key }) {
765
+ const data = node?.data ?? {}
766
+ const failure = { message: data.message, code: data.code, status: data.status,
767
+ requestId: data.requestId, providerRetryAfterMs: data.providerRetryAfterMs }
768
+ if (!node) return null
769
+ return h(ErrorCard, { title: t(data.code === 'INTERRUPTED' || data.code === 'ACCOUNT_SIGNED_OUT' ? 'ui.stopped' : 'ui.error'),
770
+ failure, sessionId, node, t, url: requestUrl(sessionId, data.turn, 'terminal'), revision: rawFailure(failure),
771
+ select: (state) => selectStep(state, data.step, failure, data, sessionId) })
772
+ }
773
+ function retryTitle (current, t) {
774
+ const label = current.retryState === 'cancelled' ? 'ui.cancelled'
775
+ : current.retryState === 'started' ? 'ui.retried' : current.retryState === 'scheduled' ? 'ui.retry' : 'ui.scheduled'
776
+ const maximum = current.mode === 'always' ? '∞' : current.maxRetries ?? '?'
777
+ const delay = Number.isFinite(current.delayMs) ? ' · ' + t('ui.wait', { ms: Math.round(current.delayMs) }) : ''
778
+ return t(label) + ' ' + current.retry + '/' + maximum + delay
779
+ }
780
+ function isErrorNode (node) {
781
+ return node?.visibility !== 'hidden' && (node?.kind === 'turn-error' || node?.kind === 'model-retry' || node?.kind === KIND
782
+ || node?.kind === 'manual-compaction' && node.data?.command?.outcome?.kind === 'error')
783
+ }
784
+ function followingError (snapshot, node) {
785
+ const order = snapshot?.order
786
+ const index = order?.indexOf(node?.key) ?? -1
787
+ if (index < 0 || !snapshot?.nodes?.get) return ''
788
+ let latest = ''
789
+ for (let at = index + 1; at < order.length; at++) {
790
+ const next = snapshot.nodes.get(order[at])
791
+ if (!next) return latest
792
+ if (isErrorNode(next)) latest = next.key
793
+ }
794
+ return latest
795
+ }
796
+ function ErrorSequenceRow ({ component, useChat, node, t, ...props }) {
797
+ const successor = typeof useChat === 'function' ? useChat((snapshot) => followingError(snapshot, node)) : ''
798
+ const identity = JSON.stringify([props.sessionId, node?.key, successor])
799
+ const [choice, setChoice] = React.useState(null)
800
+ const open = choice?.identity === identity && choice.open
801
+ const content = () => h(component, { ...props, node, t,
802
+ key: JSON.stringify([props.sessionId, node?.key, node?.id, logCoordinate(node), node?.data?.message, node?.data?.endedAt]) })
803
+ if (!successor || !isErrorNode(node)) return content()
804
+ return disclosureBlock({ className: 'bt_earlierNode bt_errorGroup', open,
805
+ onToggle: (event) => { if (!event.target || event.target === event.currentTarget) setChoice({ identity, open: event.currentTarget.open }) } },
806
+ h('summary', null, toggleLabel(t), t('ui.earlierBlock')),
807
+ open ? content() : null)
808
+ }
809
+ function earlierErrors (blocks, t) {
810
+ if (blocks.length < 2) return blocks
811
+ return [disclosureBlock({ className: 'bt_earlierErrors', key: 'earlier:' + blocks.at(-1).props.key },
812
+ h('summary', null, toggleLabel(t), t('ui.earlierErrors', { count: blocks.length - 1 })),
813
+ ...blocks.slice(0, -1).map((block, index) => disclosureBlock({ className: 'bt_earlierError', key: block.props.key },
814
+ h('summary', null, toggleLabel(t), t('ui.record', { index: index + 1 })), block))), blocks.at(-1)]
815
+ }
816
+ function retryHistory (attempts, state, sessionId, node, t, refresh) {
817
+ const blocks = attempts.map((attempt, index) => {
818
+ const failure = attempt.failure ?? {}
819
+ const selection = selectStep(state, attempt.step, failure, attempt, sessionId)
820
+ const attemptNode = { ...node, kind: 'model-retry', data: { current: attempt } }
821
+ const check = text(failure.message) === 'Stream ended without finish_reason' ? 'finishReason'
822
+ : selection.chosen?.detail && !selection.unconfirmed ? detailCheck(selection.chosen.detail) : failureCheck(failure)
823
+ return h('div', { className: 'bt_attempt', key: attempt.seq ?? attempt.attemptId ?? index },
824
+ index < attempts.length - 1 ? h('div', { className: 'bt_heading' }, retryTitle(attempt, t)) : null,
825
+ networkSection({ ...selection, inlineCopy: false, captureAdvice: false }, state, null, t, false),
826
+ failure.code === 'AUTH' && !failure.message ? h('div', { className: 'bt_meta' }, t('ui.authProtected')) : adviceRow(check, t, index === attempts.length - 1 ? 'bt_captureAdvice bt_advice' : 'bt_captureAdvice'),
827
+ selection.chosen?.detail ? h(CopyButton, { value: captureText(selection.chosen), label: 'ui.copyCapture', t }) : null,
828
+ h(ReportButton, { key: JSON.stringify([sessionId, attempt.seq, attempt.attemptId]),
829
+ url: requestUrl(sessionId, attempt.turn, 'retry'), state,
830
+ select: (fresh) => selectStep(fresh, attempt.step, failure, attempt, sessionId),
831
+ failure, row: attempt, title: retryTitle(attempt, t), t }),
832
+ h('div', { className: 'bt_detailPair' },
833
+ captureDetails(selection.chosen, t, selection.unconfirmed),
834
+ disclosureBlock({ className: 'bt_attemptNative' },
835
+ h('summary', null, toggleLabel(t), t('ui.original'), validSeq(attempt.seq) ? ' · seq=' + attempt.seq : ''),
836
+ originalControls(failure, t),
837
+ h(RawLog, { key: JSON.stringify([sessionId, logCoordinate(attemptNode)]), sessionId, node: attemptNode, t, capture: selection.chosen, unconfirmed: selection.unconfirmed }))))
838
+ })
839
+ const grouped = earlierErrors(blocks, t)
840
+ return h('section', { className: 'bt_section bt_history' },
841
+ ...grouped.toReversed(), h(RefreshButton, { refresh, t }))
842
+ }
843
+ function ModelRetryRow ({ node, sessionId, t = (key) => key }) {
844
+ const current = node?.data?.current ?? {}
845
+ const failure = current.failure ?? {}
846
+ if (current.retry === undefined) return null
847
+ // Native node.attempts is producer-correlated durable history, not the volatile capture cache.
848
+ const attempts = node.data.attempts?.length ? node.data.attempts : [current]
849
+ return h(ErrorCard, { title: retryTitle(current, t), failure, sessionId, node, t, historyOnly: true,
850
+ url: requestUrl(sessionId, current.turn, 'retry'), revision: JSON.stringify([node.id, attempts.length, current.seq, current.retry, current.retryState, failure]),
851
+ select: (state) => selectStep(state, current.step, failure, current, sessionId),
852
+ history: (state, refresh) => retryHistory(attempts, state, sessionId, node, t, refresh) })
853
+ }
854
+ function compactionUrl (sessionId) {
855
+ return sessionId ? `api/better-tips/compaction?${new URLSearchParams({ sessionId, source: 'compaction-row' })}` : ''
856
+ }
857
+ /** Timing is correlation, not proof of request identity. */
858
+ function selectCompaction (state, { startAt, endAt, status }) {
859
+ let best
860
+ let distance = Infinity
861
+ for (const record of state?.data?.records ?? []) {
862
+ if (record.status !== status && !(status === 'error' && ['thrown', 'max-tokens', 'incomplete'].includes(record.status))) continue
863
+ const start = record.startedAt
864
+ const end = record.endedAt ?? start
865
+ if (Number.isFinite(startAt) && start < startAt - 5000) continue
866
+ const delta = Number.isFinite(endAt) ? Math.abs(end - endAt) : Math.abs(start - startAt)
867
+ const window = Number.isFinite(endAt) ? 120000 : 600000
868
+ if (Number.isFinite(delta) && delta <= window && delta < distance) { best = record; distance = delta }
869
+ }
870
+ return best
871
+ }
872
+ function compactionExtra (record, t) {
873
+ if (!record) return null
874
+ const facts = [record.provider, record.model, Number.isFinite(record.durationMs) ? record.durationMs + ' ms' : ''].filter(Boolean)
875
+ if (record.usage) facts.push(t('compact.usage') + ': ' + JSON.stringify(record.usage))
876
+ if (record.delays?.length) facts.push('retryDelayMs=' + record.delays.join(','))
877
+ return h('section', { className: 'bt_section bt_compactionHistory' },
878
+ h('h4', { className: 'bt_heading' }, t('ui.attempts', { count: record.attempts?.length ?? 0 })),
879
+ h('div', { className: 'bt_meta' }, t('ui.timingMatch')),
880
+ h('div', { className: 'bt_meta' }, facts.join(' · ')),
881
+ ...earlierErrors((record.attempts ?? []).map((attempt, index) => {
882
+ const failure = attempt.failure ?? attempt.thrown
883
+ return h('div', { className: 'bt_attempt', key: attempt.attemptId ?? record.id + ':' + (attempt.index ?? index) },
884
+ h('h4', { className: 'bt_heading' }, t('compact.attempt', { index: attempt.index ?? index + 1 }) + (attempt.finishReason ? ' · finish=' + attempt.finishReason : '')),
885
+ attempt.detail ? networkSection({ chosen: attempt, unconfirmed: true }, { data: {} }, null, t, false) : h('span', { className: 'bt_meta' }, t('ui.empty')),
886
+ h('div', { className: 'bt_detailPair' },
887
+ captureDetails(attempt, t),
888
+ failure ? disclosureBlock({ className: 'bt_attemptNative' },
889
+ h('summary', null, toggleLabel(t), t('ui.original')),
890
+ originalControls(failure, t)) : null))
891
+ }), t))
892
+ }
893
+ function safeCompactionFailure (message) {
894
+ if (typeof message !== 'string') return undefined
895
+ // errorChain persists text, not the original error code. Unknown text may
896
+ // be an AUTH message; never recover it merely because the transaction matches.
897
+ if (/\bAUTH\b/.test(message)) return { code: 'AUTH', message: '' }
898
+ if (message === 'summarization truncated at the token cap (incomplete checkpoint)') return { code: 'MAX_TOKENS', message }
899
+ if (message === 'summarization produced no text summary content'
900
+ || message === 'compaction summary cannot contain image output'
901
+ || /^summary is not smaller than the shadowed content \(\d+ estimated framed tokens >= \d+\)$/.test(message)
902
+ || /^compaction: (?:session surface changed during summarization|selected surface changed before summarization began|the selected span changed during summarization|the selected span was rewritten during summarization)$/.test(message)) return { message }
903
+ return undefined
904
+ }
905
+ function useManualCompactionFailure (sessionId, command) {
906
+ const identity = JSON.stringify([sessionId, command?.commandId, command?.seq])
907
+ const [state, setState] = React.useState(null)
908
+ React.useEffect(() => {
909
+ if (!sessionId || !command?.commandId) return undefined
910
+ let cancelled = false
911
+ let release
912
+ const publish = (value) => { if (!cancelled) setState((previous) => value.error && previous?.identity === identity && previous.failure ? previous : { identity, ...value }) }
913
+ try {
914
+ const binding = sessionService?.binding(sessionId)
915
+ if (!binding?.eventSource) { publish({ missing: true }); return undefined }
916
+ const read = () => {
917
+ if (cancelled) return
918
+ try {
919
+ const events = (binding.eventSource.getSnapshot()?.entries ?? []).filter((entry) => entry.type === 'event').map((entry) => entry.event)
920
+ const own = events.filter((event) => event.data?.sourceCommandId === command.commandId)
921
+ const ids = new Set(own.filter((event) => event.type === 'compaction/start' || event.type === 'compaction/end').map((event) => event.data.compactionId).filter((id) => typeof id === 'string' && id))
922
+ const done = events.filter((event) => event.type === 'command/done' && event.data?.commandId === command.commandId)
923
+ const ends = ids.size === 1 && done.length <= 1 ? own.filter((event) => event.type === 'compaction/end' && ids.has(event.data.compactionId)
924
+ && validSeq(event.seq) && (!validSeq(command.seq) || event.seq >= command.seq)
925
+ && (done.length !== 1 || event.seq <= done[0].seq)) : []
926
+ const event = ends.length === 1 ? ends[0] : undefined
927
+ if (!event || typeof event.data.error !== 'string' || !event.data.error) { publish({ missing: true }); return }
928
+ const failure = safeCompactionFailure(event.data.error)
929
+ if (!failure) { publish({ missing: true }); return }
930
+ publish({ eventSeq: event.seq, compactionId: event.data.compactionId, time: event.time, failure })
931
+ } catch { publish({ error: true }) }
932
+ }
933
+ release = binding.eventSource.subscribe(read)
934
+ read()
935
+ if (validSeq(command.seq) && typeof binding.session?.loadThrough === 'function') {
936
+ Promise.resolve(binding.session.loadThrough(command.seq)).then(read, () => publish({ error: true }))
937
+ }
938
+ } catch { publish({ error: true }) }
939
+ return () => { cancelled = true; release?.() }
940
+ }, [identity])
941
+ return state?.identity === identity ? state : null
942
+ }
943
+ function CompactionErrorCard ({ title, fallback, sessionId, node, match, revision, t }) {
944
+ const [open, setOpen] = React.useState(false)
945
+ const [state, refresh] = useEvidence(compactionUrl(sessionId), revision)
946
+ const record = selectCompaction(state, match)
947
+ const command = node?.data?.command
948
+ const nativeRecord = useManualCompactionFailure(sessionId, command)
949
+ const chosen = record?.attempts?.at(-1)
950
+ const protect = chosen?.failure?.code === 'AUTH' || chosen?.thrown?.code === 'AUTH' || chosen?.detail?.protected
951
+ const nativeFailure = nativeRecord?.failure ?? (command ? { message: fallback } : safeCompactionFailure(fallback))
952
+ const failure = protect ? { code: 'AUTH', message: '' } : nativeFailure ?? { message: t('compact.errorProtected') }
953
+ const selection = { chosen, unconfirmed: !!record }
954
+ return errorRow(title, failure, state, selection, t, { sessionId, node, refresh }, {
955
+ nativeStatus: !chosen?.detail && (chosen?.failure || chosen?.thrown) ? h('section', { className: 'bt_summaryFailure' },
956
+ h('h4', { className: 'bt_heading' }, t('report.summaryError') + ' · ' + t('ui.unconfirmed')),
957
+ protect ? h('div', { className: 'bt_protected' }, t('ui.authProtected'))
958
+ : originalControls(chosen.failure ?? chosen.thrown, t))
959
+ : chosen?.finishReason ? h('section', { className: 'bt_summaryFailure' },
960
+ h('h4', { className: 'bt_heading' }, t('report.summaryError') + ' · ' + t('ui.unconfirmed')),
961
+ h('code', { className: 'bt_meta' }, 'finish=' + chosen.finishReason))
962
+ : command && !nativeRecord?.failure ? h('div', { className: 'bt_meta' }, t(nativeRecord?.error ? 'compact.recordFailed' : 'compact.recordMissing')) : null,
963
+ fallbackNative: true,
964
+ open, onToggle: (event) => { if (!event.target || event.target === event.currentTarget) setOpen(event.currentTarget.open) }, network: false,
965
+ report: h(ReportButton, { key: JSON.stringify([sessionId, logCoordinate(node), revision, nativeRecord?.eventSeq, failure]),
966
+ url: compactionUrl(sessionId), state, failure, row: command ?? node?.data, title, t,
967
+ select: (fresh) => {
968
+ const matched = selectCompaction(fresh, match)
969
+ const attempt = matched?.attempts?.at(-1)
970
+ return { chosen: attempt, unconfirmed: !!matched, record: matched }
971
+ } }),
972
+ history: h(React.Fragment, null, compactionExtra(record, t),
973
+ !state || state.error || !record ? evidenceBody({ state, refresh }, t) : h(RefreshButton, { refresh, t })),
974
+ })
975
+ }
976
+ function CompactionMarker ({ data, title, sessionId, t }) {
977
+ const [open, setOpen] = React.useState(false)
978
+ const [state] = useEvidence(open ? compactionUrl(sessionId) : '', data.time)
979
+ const counts = Number.isSafeInteger(data.shadowedItemCount) && Number.isSafeInteger(data.shadowedTokenCount)
980
+ ? t('compact.completed', { items: data.shadowedItemCount, tokens: data.shadowedTokenCount }) : ''
981
+ return disclosureBlock( { className: 'bt_compact', open, onToggle: (event) => { if (!event.target || event.target === event.currentTarget) setOpen(event.currentTarget.open) } },
982
+ h('summary', null, toggleLabel(t), h('span', { className: 'bt_title' }, title), counts),
983
+ h('div', { className: 'bt_body' }, compactionExtra(selectCompaction(state, { endAt: data.time, status: 'ok' }), t),
984
+ data.summary ? h('pre', { className: 'bt_raw' }, data.summary) : null))
985
+ }
986
+ function CompactionRow ({ node, sessionId, t = (key) => key }) {
987
+ return h(CompactionMarker, { data: node?.data ?? {}, title: t('compact.title'), sessionId, t })
988
+ }
989
+ function ManualCompactionRow ({ node, sessionId, t = (key) => key }) {
990
+ const data = node?.data ?? {}
991
+ const command = data.command ?? {}
992
+ if (data.compaction) return h(CompactionMarker, { data: data.compaction, title: t('compact.title'), sessionId, t })
993
+ if (command.outcome?.kind === 'error') return h(CompactionErrorCard, { title: t('compact.failed'), fallback: command.outcome.text,
994
+ sessionId, node, t, match: { startAt: command.time, status: 'error' }, revision: command.commandId + ':' + command.outcome.kind })
995
+ return h('div', { className: 'bt_compact' }, command.outcome?.text || t(command.outcome ? 'compact.done' : 'compact.running'))
996
+ }
997
+ function CompactionFailureRow ({ node, sessionId, t = (key) => key }) {
998
+ const data = node?.data ?? {}
999
+ return h(CompactionErrorCard, { title: t('compact.failedAuto'), fallback: data.error,
1000
+ sessionId, node, t, match: { endAt: data.endedAt, status: 'error' }, revision: data.endedAt })
1001
+ }
1002
+ const compactionFailureDefinition = {
1003
+ kind: KIND, target: 'chat',
1004
+ match: (event) => {
1005
+ if (!['compaction/start', 'compaction/end', 'compaction/summary'].includes(event.type)) return null
1006
+ const data = event.data ?? {}
1007
+ if (data.sourceCommandId !== undefined || !data.compactionId) return null
1008
+ return { id: data.compactionId, role: event.type === 'compaction/start' ? 'start' : 'update' }
1009
+ },
1010
+ start: (_context, match) => ({ compactionId: match.event.data.compactionId, startedAt: match.event.time, error: null }),
1011
+ update: (context, match) => match.event.type === 'compaction/end'
1012
+ ? { ...context.state, endedAt: match.event.time, endSeq: match.event.seq, error: match.event.data.error ?? null } : context.state,
1013
+ buildViewNode: (context) => {
1014
+ const end = context.matches?.find((match) => match.event.type === 'compaction/end')
1015
+ const state = context.state ?? (end ? { ...end.event.data, endedAt: end.event.time, endSeq: end.event.seq } : undefined)
1016
+ const anchor = context.start ?? end ?? context.matches?.[0]
1017
+ if (!state?.error || !anchor) return null
1018
+ return { key: context.key, kind: KIND, id: context.id, target: 'chat',
1019
+ anchorSeq: state.endSeq ?? anchor.event.seq, location: anchor.location, groupTree: 'turn', visibility: 'visible', data: state }
1020
+ },
1021
+ }
1022
+ return {
1023
+ inject: ['slots', 'locale', 'uiConversation'],
1024
+ apply (ctx) {
1025
+ sessionService = ctx.get?.('sessions')
1026
+ ctx.effect(() => {
1027
+ if (typeof document === 'undefined') return () => {}
1028
+ if (document.querySelector(`style[data-plugin-css=${JSON.stringify(CSS_TAG)}]`)) return () => {}
1029
+ const tag = document.createElement('style')
1030
+ tag.dataset.plugin = 'dsh-better-tips'
1031
+ tag.dataset.pluginCss = CSS_TAG
1032
+ tag.textContent = CSS
1033
+ document.head.appendChild(tag)
1034
+ return () => tag.remove()
1035
+ }, 'better-tips: styles')
1036
+ ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'better-tips: dictionaries')
1037
+ ctx.effect(() => ctx.uiConversation.events.register(compactionFailureDefinition), 'better-tips: compaction failure definition')
1038
+ ctx.slots.inject('conversation.chat.node', function* () {
1039
+ for (const [key, component] of [
1040
+ ['turn-error', TurnErrorRow], ['model-retry', ModelRetryRow], ['compaction', CompactionRow],
1041
+ ['manual-compaction', ManualCompactionRow], [KIND, CompactionFailureRow],
1042
+ ]) yield ctx.slots.register({ name: 'conversation.chat.node', key, priority: -100, locale: NS },
1043
+ key === 'compaction' ? component : (props) => h(ErrorSequenceRow, { ...props, component }))
1044
+ })
1045
+ },
1046
+ }
1047
+ },
1048
+ })