dsh-context-redline 0.1.0 → 0.1.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/CHANGELOG.md +21 -1
- package/README.md +6 -4
- package/README.zh.md +6 -4
- package/UPSTREAM.md +8 -0
- package/lib/client.js +17 -17
- package/lib/client.js.map +1 -1
- package/lib/index.d.ts +1 -1
- package/lib/index.js +25 -19
- package/package.json +32 -34
package/lib/client.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.js","names":["sheetMarkup","stores","useSyncExternalStore","useMemo","useSyncExternalStore","useState","useRef","memo","useMemo","useState","useRef","useState","primitives","useRef","createPortal","useState","useCallback","MarkdownText","useState","useMemo","useCallback","writeClipboard","useMemo","useState","useId","useRef","useState","Component","useRef","useState","useRef","useCallback","useMemo","useState","useRef","useMemo","useCallback","h","useState","Menu","useRef","useMemo","useState","useRef","useCallback","ERR","useState","useRef","createPortal","h","useCallback","useRef","useState","useCallback","memo","useState","useCallback","useMemo","useRef","h","Tooltip","h"],"sources":["../src/client/i18n.ts","../icon.svg?raw","../src/client/icon.tsx","../src/client/modalStore.ts","../src/client/command.ts","../src/client/dockMeasure.ts","../src/client/categories.ts","../src/client/headline.ts","../src/shared/estimate.ts","../src/client/services.ts","../src/client/historyPage.ts","../src/shared/redline-route.ts","../src/client/timelineSource.ts","../src/shared/types.ts","../src/client/assemble.ts","../src/client/dna.ts","../src/shared/fileOps.ts","../src/client/callSummary.ts","../src/client/components/detailNote.tsx","../src/shared/redline-ability.ts","../src/client/components/redlineEdit.tsx","../src/shared/redline-errors.ts","../src/shared/redline-drafts.ts","../src/client/components/nodes.tsx","../src/client/overscroll.ts","../src/client/components/trendChart.tsx","../src/client/components/fetchOnMiss.tsx","../src/client/primitives.ts","../src/client/format.ts","../src/shared/imageTokens.ts","../src/client/components/images.tsx","../src/client/components/richText.tsx","../src/client/components/browser.tsx","../src/client/components/stackedBar.tsx","../src/client/components/currentComposition.tsx","../src/client/components/errorBoundary.tsx","../src/client/components/escapeClose.ts","../src/client/redlineChannel.ts","../src/client/redlineDrafts.ts","../src/client/components/contextModal.tsx","../src/client/settingsJump.ts","../src/client/components/settingsCard.tsx","../src/client/settings.ts","../src/client/brief.ts","../src/shared/redline-origins.ts","../src/shared/redline-capacity.ts","../src/client/childSessions.ts","../src/client/components/childCard.tsx","../src/client/components/events.tsx","../src/client/components/upgradeGate.tsx","../src/client/components/requestDetail.tsx","../src/client/components/statsContext.tsx","../src/client/sidebar.ts","../src/client/viewFocus.ts","../src/client/surfaceVisibility.ts","../src/client/revealScroll.ts","../src/client/components/contextView.tsx","../src/client/components/contextJump.tsx","../src/client/placement.ts","../src/client/viewkit.ts","../src/client/index.ts"],"sourcesContent":["/**\n * Bilingual dictionaries (zh/en) for every UI string; missing keys resolve\n * through the harness locale service (active → en → common → the key itself).\n */\n\nexport type Translate = (key: string, params?: Record<string, string | number>) => string\n\nexport const DICT_ZH: Record<string, string> = {\n 'tab': '上下文批改',\n 'sidebar.guideDescription': '查看上下文的构成、统计、演变。',\n 'cat.system': '系统提示词', 'cat.tools': '工具定义', 'cat.user': '用户消息',\n 'cat.inject': '注入内容', 'cat.skill': '技能注入', 'cat.assistant': '助手消息', 'cat.tool': '工具结果',\n 'overview.title': '当前上下文',\n 'overview.estimate': 'tokens(估算)',\n 'overview.free': '剩余窗口',\n 'overview.used': '上下文已用',\n 'overview.ofUsed': '占已用上下文',\n 'overview.compactReserve': '自动压缩预留:占用达 {pct}% 窗口时触发压缩,此区域一般不实际占用',\n 'stats.title': '上下文统计',\n 'stats.viewHint': '(当前视图:第 {t} 轮 · 第 {s} 步',\n 'stats.viewLive': ' · 当前)',\n 'stats.bmeta': '本步可见 {n} 条 · ≈{k} tokens',\n // S1.1:缺 token 的条数要说出来(不许把 ≈ 说成完整数字)。\n 'stats.missing': '(另有 {m} 条无 token,未计入)',\n 'stats.visibleItems': '模型可见条目',\n 'stats.shadowedNote': '(另 {n} 条被遮蔽)',\n 'stats.userMsgs': '用户消息',\n 'stats.injectItems': '注入内容',\n 'stats.cacheHit': '缓存命中',\n 'stats.cost': '费用',\n 'trend.title': '上下文趋势',\n 'gran.step': '步骤', 'gran.turn': '轮次',\n // 规模读数(docs/03 R1.5,与 demo 的 granLabel 同一句)\n 'trend.gran.turn': '按轮次(共 {n} 轮)',\n 'trend.gran.step': '按步骤(共 {n} 次请求)',\n 'settings.title': '上下文', 'settings.desc': 'dsh-context-redline 插件中上下文面板的偏好设置',\n 'settings.placement': '入口位置',\n 'placement.tab': '标签页', 'placement.sidebar': '侧边栏', 'placement.all': '全部',\n 'settings.gran': '趋势图 · 默认粒度',\n 'settings.mode': '趋势图 · 默认展示方式',\n 'settings.toolSort': '工具定义 · 默认排序',\n 'settings.fileSort': '文件活动 · 默认排序',\n 'settings.expand': '展开', 'settings.collapse': '收起',\n 'settings.readOnly': '当前环境的设置为只读',\n 'gran.total': '全量', 'gran.delta': '增量',\n 'gran.modeHint': '全量:累计构成;增量:相对上一条请求的变化量',\n 'trend.focus': '仅展示 {cat}',\n 'trend.adaptive': '自适应',\n 'trend.adaptiveHint': '按当前可视范围内的柱子重新缩放高度,滚动时随之变化',\n 'trend.empty': '发起一轮对话后,这里会展示每次模型请求的上下文构成',\n 'detail.step': '第 {t} 轮 · 第 {s} 步 (共 {n} 步)',\n 'detail.turn': '第 {t} 轮 · 共 {n} 步',\n 'detail.lastStep': '末步',\n 'detail.estTotal': '估算合计 ≈ {n}',\n 'detail.actual': '实际 {n}',\n 'detail.output': '输出 {n}',\n 'detail.cache': '缓存 {n}%',\n 'brief.turn': '本轮',\n 'brief.input': '输入',\n 'brief.reply': '回复',\n 'brief.more': '+{n}',\n 'brief.noInputs': '(无新增)',\n 'brief.locate': '在上下文浏览器中查看',\n 'jump.title': '在上下文视图中查看此轮',\n 'brief.turnTip': '这一轮开场时用户发送的消息;回合内的每一步都会回显同一条',\n 'brief.inputTip': '上一步回复之后、本次请求发出前新进入上下文的内容——通常是上一步所调工具的结果;每轮的第一步无新增',\n 'brief.replyTip': '这一步模型返回的内容(文本回复或工具调用);此步发起的调用,其结果会出现在下一柱的「输入」行',\n 'events.title': '上下文事件',\n 'events.empty': '暂无上下文事件(压缩、注入、模型切换会出现在这里)',\n 'events.at': '第 {t} 轮 · 第 {s} 步',\n 'events.range': '第 {t} 轮 · 第 {a}→{b} 步',\n 'events.rangeTo': '第 {a} 轮 · 第 {as} 步 → 第 {b} 轮 · 第 {bs} 步',\n 'kind.inject': '注入', 'kind.compaction': '压缩', 'kind.prune': '剪枝', 'kind.model': '切换', 'kind.mode': '模式',\n 'files.title': '文件活动',\n 'files.sort.count': '按次数', 'files.sort.latest': '按最新', 'files.sort.path': '按路径',\n 'loading': '正在读取会话日志…',\n 'detail.loading': '正在加载历史数据…',\n 'detail.loadFailed': '历史数据加载失败,点击重试',\n 'error': '上下文数据读取失败:',\n 'error.retry': '重试',\n 'gate.title': '请更新 DeepSeek Harness 版本',\n 'gate.body': 'dsh-context-redline 插件支持 DeepSeek Harness v{minimum} 或更新版本。',\n 'gate.current': '当前版本',\n 'gate.minimum': '最低要求',\n 'gate.orNewer': '及更新的版本',\n 'gate.ok': '知道了',\n 'footer': 'Token 数量统计:「估算」与 DeepSeek Harness 内置 tokenMeter 相同的固定密度启发式(约 4 字符 ≈ 1 token);「实际」为供应商上报用量。',\n 'tip.step': '第 {t} 轮 · 第 {s} 步 (共 {n} 步)',\n 'tip.turn': '第 {t} 轮 · 共 {n} 步',\n 'tip.turn1': '第 {t} 轮 · 共 1 步',\n 'tip.total': '合计 ≈ {n}',\n 'tip.cat': '{cat} ≈ {n}',\n 'tip.delta': 'Δ {n}',\n 'ev.compaction': '压缩上下文(摘要替换 {n} 条消息)',\n 'ev.prune': '剪枝工具输出',\n 'ev.skill': 'Skill 注入({name})',\n 'ev.model': '模型切换:{a} → {b}',\n 'ev.mode.plan.on': '进入计划模式', 'ev.mode.plan.off': '退出计划模式',\n 'form.instructions': '指令注入', 'form.catalog': '目录更新', 'form.snapshot': '状态快照',\n 'form.notice': '通知', 'form.relay': '代理转发', 'form.recall': '历史召回', 'form.context': '上下文注入',\n 'node.toolResult': '工具结果',\n 'node.calls': '调用 ',\n 'node.empty': '(空回复)',\n 'node.nonText': '(非文本消息)',\n 'node.snapshot': '快照: ',\n 'node.skillTag': '技能 · {name}',\n 'cmd.label': '上下文',\n 'cmd.section': '上下文',\n 'cmd.desc': '查看当前上下文构成,浏览各步骤组成',\n 'cmd.close': '关闭',\n 'browser.title': '上下文浏览器',\n // ── 编辑(当前 demo 的契约:docs/03 §2–§4 + docs/11 D15/D16/D17/D19/D20)──\n 'redline.edit': '编辑',\n 'redline.drop': '丢弃这条改动',\n // 「删除」(`docs/03` R4.8):这一条**不写进新会话**。只记在插件本地,当前会话一个字都不写。\n 'redline.exclude': '删除',\n 'redline.exclude.tip': '把这一条删掉:只记在插件本地,当前会话不受影响;开启新会话时,被删的条目不会出现在里面。你之前对它的修改会原样留着 —— 取消删除就能拿回来。',\n 'redline.unexclude': '取消删除',\n 'redline.unexclude.tip': '取消删除:这一条重新参与投递;如果你之前改过它,改后的正文会原样回来。',\n 'redline.excluded': '已删除',\n 'redline.excluded.tip': '这一条已被删除:它不会被写进新会话。取消删除可原样恢复(含你改过的正文)。',\n 'redline.local': '已改(本地)',\n 'redline.local.tip': '已保存在插件本地:当前会话的模型看不到。确认开启普通新会话时,改后的正文会逐字写进第一句话。',\n 'redline.advanced': '高级编辑',\n 'redline.advanced.tip': '工具结果的「编辑」属于高级编辑:打开顶部的「高级编辑」开关即可看到(避免几十条工具结果把常用动作淹掉)。',\n 'redline.reason.assistant': '旧日志不改;迁移副本可编辑',\n 'redline.reason.system': '宿主保护:改不了',\n 'redline.reason.shadowed': '已被接替',\n 'redline.reason.compacted': '被压缩埋掉了',\n 'redline.reason.other': '这一条改不了',\n 'redline.field.body': '正文',\n 'redline.field.thinking': '思考文本',\n 'redline.field.result': '结果文本',\n 'redline.field.isError': '标记为错误(isError)',\n 'redline.field.advanced': '高级:思考文本',\n 'redline.dest.local': '只写本地 · 确认开新会话时才带进去',\n 'redline.multiParagraph': '这条消息有多个文本段落;改写后会合并为一段。',\n 'redline.save': '保存',\n 'redline.save.tip': '只写插件本地(当前会话的模型看不到、会话日志不动)。同一行再次保存会覆盖这一条;确认开启普通新会话时才逐字带进第一句话。',\n 'redline.cancel': '取消(Esc)',\n 'child.title': '承载会话',\n 'child.bmeta': '活跃 {a} · 共 {n} 个',\n // 来源(M5-12):三态各自一句 —— 台账里有 / 没有 / 台账读不出来。**不猜**。\n 'child.src.own.carrier': '本项目发起 · 普通会话',\n 'child.src.own.official': '历史 · 官方成员',\n 'child.src.own.bare': '本项目发起 · 裸子会话',\n 'child.src.other': '不是在这儿开的',\n 'child.src.unknown': '来源未知',\n 'child.src.tip': '来源来自我们自己记的台账:官方那本子会话目录里只有 mode / label,没有来源字段(docs/01 F59)。「不是在这儿开的」只说明不是这个面板建的 —— 不猜是谁建的。',\n // 分母只在真读到上限时才写(M5-13);读不到就退回上一条,不编数字。\n 'child.spawn.head': '开新会话执行',\n 'child.spawn.hint': '批改后的上下文只会写进这个新会话',\n 'child.spawn.button': '开启新会话',\n 'child.spawn.note': '在当前工作区左侧新开一个零历史普通会话,只带你确认保留或修改的内容;删除项不会进去,任务结果会自动回到当前会话。',\n 'child.list.head': '承载会话',\n 'child.list.hint': '这个面板开启的普通会话 · 看状态与来源',\n 'child.empty': '(还没有承载会话)',\n 'child.mode.one-shot': '一次性',\n 'child.mode.continuable': '多轮',\n 'child.mode.unknown': '模式未知',\n 'child.state.running': '运行中',\n 'child.state.idle': '空闲',\n 'child.state.gone': '已结束',\n 'child.state.unloaded': '未加载',\n 'child.state.unknown': '状态未知',\n 'child.hint.running': '运行中:轮次闭合前只能看,不能改(要改就先等它空闲,或打断它)。',\n 'child.hint.idle': '空闲:用父会话页头右侧的「N 个子智能体」目录打开旧子会话。',\n 'child.hint.carrierIdle': '空闲:从左侧会话列表打开它,就能查看和继续批改它自己的上下文。',\n 'child.hint.gone': '这个历史子会话当前不在本进程里,只能查看。',\n 'child.hint.unloaded': '普通会话当前未加载;从左侧会话列表打开即可恢复。',\n 'child.hint.unknown': '读不到它的状态 —— 打开它之前先按\"只能查看\"打算。',\n 'child.confirm.metrics': '约 {bytes} 字节(UTF-8,含 {edits} 条本地改动)',\n 'child.confirm.title': '开启普通新会话',\n 'child.confirm.intro': '确认后会在当前工作区新开一个零历史普通会话,只写入下面逐字列出的迁移内容;删除项不进入。任务结束后,结果会原样自动回到当前会话。',\n 'child.confirm.preparing': '正在准备……',\n 'child.confirm.taskLabel': '首条任务',\n 'child.confirm.taskHint': '会成为普通新会话的第一句话;新会话模型可见,当前会话模型不可见。',\n 'child.confirm.taskPlaceholder': '一句话说清这次要它干什么。',\n 'child.confirm.modelLabel': '执行模型',\n 'child.confirm.effortDefault': '使用模型默认值',\n 'child.confirm.finalLabel': '最终发送全文',\n 'child.confirm.finalHint': '下面就是实际写入新会话的完整第一句话。可直接删段、改字或重排;确认后逐字冻结。',\n 'child.confirm.ok': '确认创建',\n 'child.confirm.cancel': '取消',\n 'redline.blocked.turnOpen': '当前轮次还没结束 —— 改动只能在轮次边界提交。',\n 'redline.blocked.notLive': '这个会话不在本进程里,只能查看,不能编辑。',\n 'redline.err.turn-open': '当前轮次还没结束 —— 改动只能在轮次边界提交',\n 'redline.err.no-change': '没有实质改动 —— 内容和上次保存的一模一样',\n 'redline.err.empty-content': '正文与思考文本不能同时为空',\n 'redline.err.not-live': '这个会话不在本进程里,只能查看,不能编辑',\n 'redline.err.transport': '保存没有送到宿主(网络或服务问题),你的输入还在',\n 'redline.err.bad-request': '这条改动的参数不合法(这是缺陷,请把这条报出来)',\n 'redline.err.internal': '宿主保存失败,你的输入还在',\n 'redline.err.unknown-op': '这一条请求宿主不认(多半是页面版本比插件旧):刷新页面再试',\n // 来源台账(M5-12):读不出来时要说**原因**,不许只写\"来源未知\"(错误码 → 人话)。\n 'redline.err.origin-corrupt': '本地那份「来源」台账读不出来(可能被手改过或写坏过)—— 删掉它就能重建;这只影响界面显示的来源,不影响任何会话',\n 'redline.err.origin-schema': '本地那份「来源」台账来自另一个版本的插件 —— 删掉它就能重建;不影响任何会话',\n 'redline.err.no-draft': '这一条还没有本地改动可丢',\n 'redline.err.empty-task': '子会话的第一句话必须由你自己写 —— 它要做什么不能替你决定',\n 'redline.err.no-subagents': '这台运行时没有可用的子会话服务:只能把改好的正文手动带过去',\n 'redline.err.child-start-unconfirmed': '子会话服务没有返回可核对的会话身份,所以没有把它说成已开启',\n 'redline.err.child-start-failed': '子会话没有创建成功(官方成员与备用路径都没能完成)—— 你的本地改动还在',\n 'redline.err.drafts-changed': '本地改动在确认后变了:请重新打开确认框,核对将要带入的新版本',\n 'redline.err.assistant-immutable': '助手消息在平台上无法改写(两条规则互斥):这一条不能作为目标',\n 'redline.err.unsupported-type': '这一类内容(系统提示词 / 工具定义等)由宿主保护,本插件不能改',\n 'redline.err.shadowed': '这一条已被后来的一条接替,已不在模型可见内容里',\n 'redline.err.not-found': '按这个位置找不到这一条(可能来自旧页面,或已被裁出窗口)',\n 'redline.err.draft-corrupt': '本地改动文件读不出来:它已损坏。可以丢弃本地改动后重试',\n 'redline.err.draft-schema': '本地改动文件的格式版本不认识(多半是升级/降级造成的)',\n 'redline.err.bad-range': '范围参数不完整或顺序反了',\n 'redline.err.history-unavailable': '这一版的历史原文在这台运行时上读不回来',\n 'redline.advancedToggle': '高级编辑',\n 'redline.advancedToggle.tip': '打开后,工具结果的「编辑」会出现(默认收起,避免几十条工具结果把常用动作淹掉)。',\n 'browser.live': '当前(下一次请求)',\n 'browser.liveNow': '当前 · 下一次请求',\n 'browser.items': '{n} 项',\n 'browser.missingLive': '… 另有 {n} 条更早的消息也在上下文中(超出展示窗口)',\n 'browser.approx': '该步骤涉及的部分已移除消息超出保留范围,以下为近似构成',\n // 对比基线(照参考插件 0.60.0 的 browser.base.* 逐字)与两级选择器(docs/03 R1.13)\n 'browser.base.step': '比前步',\n 'browser.base.turn': '比前轮',\n 'browser.base.tip': '变动对比的基线:比前步=与上一步对比;比前轮=与上一轮最后一步对比(首轮无基线,全部计为变动)',\n 'browser.turnPick': '第 {t} 轮(共 {n} 步)',\n 'browser.stepPick': '第 {s} 步(共 {n} 步)',\n 'browser.dna': 'DNA 模式',\n 'browser.dnaTip': '按模型读取上下文的次序逐条展示每一项:系统提示词、工具定义,然后是按时间排列的消息;悬停查看条目,点击定位到下方列表',\n 'browser.noHeader': '此数据来自旧版插件:仅提供 token 估算,无实际内容',\n 'browser.noEpoch': '该步骤的头部内容(系统提示词 / 工具定义)不在保留范围内',\n 'browser.headerMetaOnly': '此环境不支持按需读取头部内容,仅显示 token 估算',\n 'browser.noSystem': '该请求头部未包含系统提示词',\n 'browser.noContent': '完整内容不在当前加载的消息窗口内(在聊天页加载更早历史后可查看)',\n 'browser.search.user': '按消息内容过滤…',\n 'browser.search.inject': '按注入内容过滤…',\n 'browser.search.skill': '按技能过滤…',\n 'browser.search.assistant': '按回复或调用过滤…',\n 'browser.search.tool': '按工具或参数过滤…',\n 'browser.rowNoMatch': '没有匹配当前过滤条件的行',\n 'browser.loading': '正在从更早的会话历史加载完整内容…',\n 'browser.notInLog': '会话日志中未找到该条目的完整内容(可能已被压缩或清理)',\n 'browser.loadFailed': '内容加载失败,点击重试',\n 'tool.desc': '描述',\n 'tool.params': '参数',\n 'tool.paramsEmpty': '(无参数)',\n 'tool.plugin': '该工具的注册插件(仅供参考)',\n 'tool.unknown': '未知插件',\n 'tool.unknownTitle': '因早于上下文插件加载或原插件已卸载,无法查询该工具的提供者',\n 'tool.jsonToggle': '查看原始 JSON',\n 'tool.jsonHide': '收起',\n 'tool.search': '按名称、描述或参数过滤…',\n 'tool.sort.size': '按大小', 'tool.sort.count': '按次数', 'tool.sort.name': '按名称',\n 'tool.sortTip': '工具排序:按当前步骤中的调用次数(默认)、token 大小或名称',\n 'tool.hitsTip': '当前展示步骤的上下文中,该工具被调用并返回结果的次数',\n 'tool.noMatch': '没有匹配当前过滤条件的工具',\n 'rich.raw': '原文',\n 'rich.md': 'Markdown',\n 'rich.toMd': '按 Markdown 渲染查看',\n 'rich.toRaw': '查看原始文本',\n 'rich.copy': '复制原文', 'rich.copied': '已复制',\n 'rich.md.copy': '复制', 'rich.md.copied': '已复制',\n 'rich.md.footnotes': '脚注',\n 'block.thinking': '思考',\n 'block.answer': '回答',\n 'block.content': '内容', 'block.result': '结果', 'block.summary': '摘要',\n // Line-count chip on a tool-result's payload card (the singular/plural\n // split is a no-op in zh, where the measure word never inflects).\n 'block.line': '{n} 行', 'block.lines': '{n} 行',\n 'call.ok': '正常', 'call.fail': '失败', 'call.exit': 'exit {n}',\n 'node.failed': '工具执行失败',\n 'attach.images': '图片附件',\n 'attach.other': '其他内容',\n 'attach.image': '图片',\n 'attach.open': '查看原图',\n 'attach.preview': '图片预览',\n 'attach.close': '关闭',\n 'attach.loading': '…',\n 'attach.loadFailed': '加载失败 · 点击重试',\n 'attach.raw': '原图',\n 'attach.sent': '发送',\n 'attach.token': 'Token',\n 'attach.tokensTip': '按 DeepSeek 官方图片尺寸换算(单图上限 384 tokens)估算的 token 消耗',\n 'ov.entry': '上下文批改 · 洞察',\n 'ov.title': '上下文批改 · 洞察',\n}\n\nexport const DICT_EN: Record<string, string> = {\n 'tab': 'Context Redline',\n 'sidebar.guideDescription': 'Inspect context composition, stats, and evolution.',\n 'cat.system': 'System Prompt', 'cat.tools': 'Tool Schemas', 'cat.user': 'User Messages',\n 'cat.inject': 'Injected Context', 'cat.skill': 'Skill Injections', 'cat.assistant': 'Assistant Messages', 'cat.tool': 'Tool Results',\n 'overview.title': 'Current Context',\n 'overview.estimate': 'tokens (estimated)',\n 'overview.free': 'Free Window',\n 'overview.used': 'of context used',\n 'overview.ofUsed': 'of used context',\n 'overview.compactReserve': 'Auto-compaction reserve: auto-compaction triggers at {pct}% of the window — this area is normally kept as headroom, not actually used',\n 'stats.title': 'Context Stats',\n 'stats.viewHint': '(showing turn {t} · step {s}',\n 'stats.viewLive': ' · live)',\n 'stats.bmeta': '{n} items visible in this step · ≈{k} tokens',\n 'stats.missing': '({m} more have no token and are not counted)',\n 'stats.visibleItems': 'Model-visible items',\n 'stats.shadowedNote': ' ({n} more superseded)',\n 'stats.userMsgs': 'User messages',\n 'stats.injectItems': 'Injected items',\n 'stats.cacheHit': 'Cache Hit',\n 'stats.cost': 'Cost',\n 'trend.title': 'Context Trend',\n 'gran.step': 'Step', 'gran.turn': 'Turn',\n 'trend.gran.turn': 'By turn ({n} turns)',\n 'trend.gran.step': 'By step ({n} requests)',\n 'settings.title': 'Context', 'settings.desc': 'Preferences for Context panel in dsh-context-redline plugin',\n 'settings.placement': 'Entry Options',\n 'placement.tab': 'Tab', 'placement.sidebar': 'Sidebar', 'placement.all': 'All',\n 'settings.gran': 'Trend Chart · Default granularity',\n 'settings.mode': 'Trend Chart · Default display',\n 'settings.toolSort': 'Tool Schemas · Default sort',\n 'settings.fileSort': 'File Activity · Default sort',\n 'settings.expand': 'Expand', 'settings.collapse': 'Collapse',\n 'settings.readOnly': 'Settings are read-only in this environment',\n 'gran.total': 'Total', 'gran.delta': 'Delta',\n 'gran.modeHint': 'Total: cumulative makeup; Delta: change vs the previous request',\n 'trend.focus': 'Showing {cat} only',\n 'trend.adaptive': 'Adaptive',\n 'trend.adaptiveHint': 'Rescale bar heights to the visible range, following the scroll',\n 'trend.empty': 'Send a message and each model request’s context makeup shows up here',\n 'detail.step': 'Turn {t} · Step {s} of {n}',\n 'detail.turn': 'Turn {t} · {n} steps',\n 'detail.lastStep': 'Last Step',\n 'detail.estTotal': 'Estimated ≈ {n}',\n 'detail.actual': 'Actual {n}',\n 'detail.output': 'Output {n}',\n 'detail.cache': 'Cache {n}%',\n 'brief.turn': 'User',\n 'brief.input': 'In',\n 'brief.reply': 'Response',\n 'brief.more': '+{n}',\n 'brief.noInputs': '(nothing new)',\n 'brief.locate': 'Reveal in Context Browser',\n 'jump.title': 'View this turn in the Context view',\n 'brief.turnTip': 'The user message that opened this turn — every step of the turn recalls it',\n 'brief.inputTip': 'What entered after the previous reply and before this request went out — usually the previous tool-call results; a turn opener has nothing new',\n 'brief.replyTip': 'What the model returned on this step (a text reply or tool calls) — results of calls made here appear in the In row of the next bar',\n 'events.title': 'Context Events',\n 'events.empty': 'No context events yet (compaction, injections, model switches appear here)',\n 'events.at': 'Turn {t} · Step {s}',\n 'events.range': 'Turn {t} · Step {a}→{b}',\n 'events.rangeTo': 'Turn {a} · Step {as} → Turn {b} · Step {bs}',\n 'kind.inject': 'Inject', 'kind.compaction': 'Compact', 'kind.prune': 'Prune', 'kind.model': 'Switch', 'kind.mode': 'Mode',\n 'files.title': 'File Activity',\n 'files.sort.count': 'Most active', 'files.sort.latest': 'Latest', 'files.sort.path': 'By path',\n 'loading': 'Reading the session log…',\n 'detail.loading': 'Loading history…',\n 'detail.loadFailed': 'History failed to load — click to retry',\n 'error': 'Failed to read context data: ',\n 'error.retry': 'Retry',\n 'gate.title': 'Update DeepSeek Harness',\n 'gate.body': 'dsh-context-redline supports DeepSeek Harness v{minimum} or newer.',\n 'gate.current': 'Current',\n 'gate.minimum': 'Minimum required',\n 'gate.orNewer': 'or newer',\n 'gate.ok': 'Got it',\n 'footer': 'Token amount: “Estimated” uses the same fixed-density heuristic as DeepSeek Harness’s built-in tokenMeter (~4 chars ≈ 1 token); “Actual” is provider-reported usage.',\n 'tip.step': 'Turn {t} · Step {s} of {n}',\n 'tip.turn': 'Turn {t} · {n} steps',\n 'tip.turn1': 'Turn {t} · 1 step',\n 'tip.total': 'Total ≈ {n}',\n 'tip.cat': '{cat} ≈ {n}',\n 'tip.delta': 'Δ {n}',\n 'ev.compaction': 'Context compacted (summary replaced {n} messages)',\n 'ev.prune': 'Tool output pruned',\n 'ev.skill': 'Skill injected ({name})',\n 'ev.model': 'Model switched: {a} → {b}',\n 'ev.mode.plan.on': 'Plan mode on', 'ev.mode.plan.off': 'Plan mode off',\n 'form.instructions': 'Instructions', 'form.catalog': 'Catalog Update', 'form.snapshot': 'State Snapshot',\n 'form.notice': 'Notice', 'form.relay': 'Agent Relay', 'form.recall': 'Recall', 'form.context': 'Context Injection',\n 'node.toolResult': 'Tool Result',\n 'node.calls': 'Calls ',\n 'node.empty': '(empty reply)',\n 'node.nonText': '(non-text message)',\n 'node.snapshot': 'Snapshot: ',\n 'node.skillTag': 'Skill · {name}',\n 'cmd.label': 'Context',\n 'cmd.section': 'Context',\n 'cmd.desc': 'View current context makeup, browse per-step composition',\n 'cmd.close': 'Close',\n 'browser.title': 'Context Browser',\n 'redline.edit': 'Edit',\n 'redline.drop': 'Discard this change',\n 'redline.exclude': 'Delete',\n 'redline.exclude.tip': 'Delete this item: recorded in the plugin only, this session is unaffected; when you open the new session, deleted items are not in it. Any edit you made is kept — cancel the delete to get it back.',\n 'redline.unexclude': 'Cancel delete',\n 'redline.unexclude.tip': 'Cancel the delete: this item is carried again; if you had edited it, your edited text comes back exactly as it was.',\n 'redline.excluded': 'Deleted',\n 'redline.excluded.tip': 'This item is deleted: it will not be written into the new session. Cancel the delete to restore it exactly (including your edited text).',\n 'redline.local': 'Edited (local)',\n 'redline.local.tip': 'Saved in the plugin only: this session\\'s model cannot see it. Confirmation carries the edited text verbatim into the ordinary new session\\'s first message.',\n 'redline.advanced': 'Advanced editing',\n 'redline.advanced.tip': 'Editing a tool result is an advanced action: turn on the Advanced editing switch at the top to see it (dozens of tool results would otherwise bury the common actions).',\n 'redline.reason.assistant': 'Old log stays unchanged; the migration copy is editable',\n 'redline.reason.system': 'Host-protected',\n 'redline.reason.shadowed': 'Superseded',\n 'redline.reason.compacted': 'Buried by compaction',\n 'redline.reason.other': 'Cannot be edited',\n 'redline.field.body': 'Body',\n 'redline.field.thinking': 'Thinking text',\n 'redline.field.result': 'Result text',\n 'redline.field.isError': 'Mark as an error (isError)',\n 'redline.field.advanced': 'Advanced: thinking text',\n 'redline.dest.local': 'Local only · carried after you confirm a new session',\n 'redline.multiParagraph': 'This message has several text paragraphs; a rewrite merges them into one.',\n 'redline.save': 'Save',\n 'redline.save.tip': 'Writes the plugin\\'s local store only (this session\\'s model cannot see it, the log is untouched). Saving again overwrites that row; confirmation carries it verbatim into the ordinary new session\\'s first message.',\n 'redline.cancel': 'Cancel (Esc)',\n 'child.title': 'Carrier sessions',\n 'child.bmeta': '{a} active · {n} total',\n 'child.src.own.carrier': 'Started here · ordinary session',\n 'child.src.own.official': 'Legacy · official member',\n 'child.src.own.bare': 'Started here · bare child',\n 'child.src.other': 'Not started here',\n 'child.src.unknown': 'Origin unknown',\n 'child.src.tip': 'Origin comes from our own ledger: the official child catalog carries only mode / label and no origin field (docs/01 F59). \"Not started here\" only means this panel did not create it - we do not guess who did.',\n 'child.spawn.head': 'Run in a new session',\n 'child.spawn.hint': 'Only the confirmed redlined context is written there',\n 'child.spawn.button': 'Open new session',\n 'child.spawn.note': 'Open a zero-history ordinary session in this workspace, carrying only content you kept or edited. Deleted items stay out, and the final result returns here automatically.',\n 'child.list.head': 'Carrier sessions',\n 'child.list.hint': 'Ordinary sessions opened by this panel · state and source',\n 'child.empty': '(no carrier sessions yet)',\n 'child.mode.one-shot': 'one-shot',\n 'child.mode.continuable': 'continuable',\n 'child.mode.unknown': 'mode unknown',\n 'child.state.running': 'running',\n 'child.state.idle': 'idle',\n 'child.state.gone': 'finished',\n 'child.state.unloaded': 'not loaded',\n 'child.state.unknown': 'state unknown',\n 'child.hint.running': 'Running: you can look until its turn closes, but not edit (wait for it to go idle, or interrupt it).',\n 'child.hint.idle': 'Idle: open a legacy child from the parent header\\'s “N subagents” directory.',\n 'child.hint.carrierIdle': 'Idle: open this ordinary session from the left session list to inspect or redline its context.',\n 'child.hint.gone': 'This legacy child session is not live in this process: view only.',\n 'child.hint.unloaded': 'This ordinary session is not loaded; open it from the left session list to resume it.',\n 'child.hint.unknown': 'Its state could not be read — assume view only until you open it.',\n 'child.confirm.metrics': 'about {bytes} bytes (UTF-8, carrying {edits} local edits)',\n 'child.confirm.title': 'Open an ordinary new session',\n 'child.confirm.preparing': 'Preparing…',\n 'child.confirm.intro': 'Confirmation opens a zero-history ordinary session in this workspace. Only the migration content listed below is written there; deleted items stay out. The final result returns here verbatim.',\n 'child.confirm.taskLabel': 'First task',\n 'child.confirm.taskHint': 'It becomes the ordinary new session\\'s first message; that model sees it, this session\\'s model does not.',\n 'child.confirm.taskPlaceholder': 'One sentence saying what this session should do.',\n 'child.confirm.modelLabel': 'Execution model',\n 'child.confirm.effortDefault': 'Use model default',\n 'child.confirm.finalLabel': 'Final message to send',\n 'child.confirm.finalHint': 'This is the exact first user message written to the new session. Delete, edit, or reorder freely; confirmation freezes these bytes.',\n 'child.confirm.ok': 'Create it',\n 'child.confirm.cancel': 'Cancel',\n 'redline.blocked.turnOpen': 'This turn has not finished — edits can only be committed on a turn boundary.',\n 'redline.blocked.notLive': 'This session is not live in this process: view only, no editing.',\n 'redline.err.turn-open': 'This turn has not finished — edits can only be committed on a turn boundary',\n 'redline.err.no-change': 'Nothing substantive changed — this is identical to what is already in effect',\n 'redline.err.empty-content': 'The body and the thinking text cannot both be empty',\n 'redline.err.not-live': 'This session is not live in this process: view only, no editing',\n 'redline.err.transport': 'The save did not reach the host (network or service): your input is kept',\n 'redline.err.bad-request': 'The save arguments were invalid (this is a defect — please report it)',\n 'redline.err.internal': 'The host failed to save; your input is kept',\n 'redline.err.unknown-op': 'The host does not know this request (the page is probably older than the plugin): reload and retry',\n 'redline.err.origin-corrupt': 'The local origin ledger cannot be read (hand-edited or written badly) - deleting it rebuilds it; this only affects the origin shown in the UI, never a session',\n 'redline.err.origin-schema': 'The local origin ledger comes from another plugin version - deleting it rebuilds it; no session is affected',\n 'redline.err.no-draft': 'There is no local edit on this row to discard',\n 'redline.err.empty-task': 'The first task must be written by you — the plugin cannot decide what the child does',\n 'redline.err.no-subagents': 'This runtime exposes no child-session service: carry the edited text over by hand',\n 'redline.err.child-start-unconfirmed': 'The child-session service returned no verifiable session identity, so it is not reported as started',\n 'redline.err.child-start-failed': 'The child session was not created (neither the official-member nor fallback path completed); your local edits remain',\n 'redline.err.drafts-changed': 'Local edits changed after this confirmation was prepared: reopen it and review the current version',\n 'redline.err.assistant-immutable': 'An assistant message cannot be rewritten on this platform (two rules are mutually exclusive)',\n 'redline.err.unsupported-type': 'This kind of content (system prompt / tool definitions) is host-protected and cannot be edited here',\n 'redline.err.shadowed': 'A later item superseded this one, so it is no longer part of what the model sees',\n 'redline.err.not-found': 'Nothing is at that position (an older page, or the row fell out of the window)',\n 'redline.err.draft-corrupt': 'The local edit file cannot be read: it is corrupt. Discard the local edits and retry',\n 'redline.err.draft-schema': 'The local edit file has a format version this build does not know',\n 'redline.err.bad-range': 'The range arguments were incomplete or reversed',\n 'redline.err.history-unavailable': 'The full text of that version cannot be read back on this runtime',\n 'redline.advancedToggle': 'Advanced editing',\n 'redline.advancedToggle.tip': 'Turn on to reveal Edit on tool results (hidden by default so dozens of tool results cannot bury the common actions).',\n 'browser.live': 'Live (Next Request)',\n 'browser.liveNow': 'Live · Next Request',\n 'browser.items': '{n} Items',\n 'browser.missingLive': '… {n} earlier messages are also part of the context (outside the served window)',\n 'browser.approx': 'Some removed messages of this step exceed retention — the makeup below is approximate',\n 'browser.base.step': 'vs. previous step',\n 'browser.base.turn': 'vs. previous turn',\n 'browser.base.tip': 'Baseline for the change markers: vs. previous step (what this step added or dropped) or vs. the previous turn\\'s last step (how this turn moved as a whole). The first turn has no baseline, so everything counts as a change.',\n 'browser.turnPick': 'Turn {t} ({n} steps)',\n 'browser.stepPick': 'Step {s} of {n}',\n 'browser.dna': 'DNA Mode',\n 'browser.dnaTip': 'One band per item in the order the model reads the context — system prompt, tool schemas, then messages chronologically; hover for details, click to open its row below',\n 'browser.noHeader': 'Served by an older plugin build: token estimates only, no content',\n 'browser.noEpoch': 'The header content (System Prompt / Tool Schemas) of this step is outside retention',\n 'browser.headerMetaOnly': 'This environment cannot fetch header content on demand; token estimates only',\n 'browser.noSystem': 'This request header carried no system prompt',\n 'browser.noContent': 'Full content is outside the loaded message window (load older history in Chat to view)',\n 'browser.search.user': 'Filter by message text…',\n 'browser.search.inject': 'Filter injected context…',\n 'browser.search.skill': 'Filter skills…',\n 'browser.search.assistant': 'Filter by reply or calls…',\n 'browser.search.tool': 'Filter by tool or arguments…',\n 'browser.rowNoMatch': 'No rows match the current filter',\n 'browser.loading': 'Loading full content from older session history…',\n 'browser.notInLog': 'This item is not in the session log anymore (it may have been compacted away or cleared)',\n 'browser.loadFailed': 'Load failed — click to retry',\n 'tool.desc': 'Description',\n 'tool.params': 'Parameters',\n 'tool.paramsEmpty': '(no parameters)',\n 'tool.plugin': 'The registering plugin of this tool (for reference)',\n 'tool.unknown': 'Unknown plugin',\n 'tool.unknownTitle': 'The tool was registered before the context plugin loaded, or its plugin has been unloaded, so its provider cannot be determined',\n 'tool.jsonToggle': 'View Raw JSON',\n 'tool.jsonHide': 'Collapse',\n 'tool.search': 'Filter by name, description, or parameters…',\n 'tool.sort.size': 'By size', 'tool.sort.count': 'By calls', 'tool.sort.name': 'By name',\n 'tool.sortTip': 'Sort tools by call count in the shown step (default), token size, or name',\n 'tool.hitsTip': 'Times this tool was called and answered within the shown step’s context',\n 'tool.noMatch': 'No tools match the current filter',\n 'rich.raw': 'Raw',\n 'rich.md': 'Markdown',\n 'rich.toMd': 'View as Markdown',\n 'rich.toRaw': 'View Raw Text',\n 'rich.copy': 'Copy Raw Text', 'rich.copied': 'Copied',\n 'rich.md.copy': 'Copy', 'rich.md.copied': 'Copied',\n 'rich.md.footnotes': 'Footnotes',\n 'block.thinking': 'Reasoning',\n 'block.answer': 'Response',\n 'block.content': 'Content', 'block.result': 'Result', 'block.summary': 'Summary',\n 'block.line': '1 line', 'block.lines': '{n} lines',\n 'call.ok': 'OK', 'call.fail': 'Failed', 'call.exit': 'exit {n}',\n 'node.failed': 'Tool execution failed',\n 'attach.images': 'Images',\n 'attach.other': 'Other content',\n 'attach.image': 'Image',\n 'attach.open': 'Open full image',\n 'attach.preview': 'Image preview',\n 'attach.close': 'Close',\n 'attach.loading': '…',\n 'attach.loadFailed': 'Load failed · click to retry',\n 'attach.raw': 'Raw',\n 'attach.sent': 'Sent',\n 'attach.token': 'Token',\n 'attach.tokensTip': 'Estimated token cost via DeepSeek\\'s official image-size conversion (384-token cap per image)',\n 'ov.entry': 'Context Redline · Insights',\n 'ov.title': 'Context Redline · Insights',\n}\n","export default \"<svg xmlns=\\\"http://www.w3.org/2000/svg\\\" viewBox=\\\"0 0 1024 1024\\\"><!-- Original artwork for dsh-context-redline (MIT). Not derived from the dsh-context icon: this is a redline-on-context-rows motif drawn for this fork. -->\\n <path d=\\\"M109 168H109A13 13 0 0 1 122 181V843A13 13 0 0 1 109 856H109A13 13 0 0 1 96 843V181A13 13 0 0 1 109 168Z\\\" fill=\\\"#7C5CD6\\\"/>\\n <path d=\\\"M206 168H898A30 30 0 0 1 928 198V230A30 30 0 0 1 898 260H206A30 30 0 0 1 176 230V198A30 30 0 0 1 206 168Z\\\" fill=\\\"#5B6478\\\"/>\\n <path d=\\\"M206 300H746A30 30 0 0 1 776 330V362A30 30 0 0 1 746 392H206A30 30 0 0 1 176 362V330A30 30 0 0 1 206 300Z\\\" fill=\\\"#4F63C8\\\"/>\\n <path d=\\\"M206 432H850A30 30 0 0 1 880 462V494A30 30 0 0 1 850 524H206A30 30 0 0 1 176 494V462A30 30 0 0 1 206 432Z\\\" fill=\\\"#E0A32E\\\"/>\\n <path d=\\\"M206 564H666A30 30 0 0 1 696 594V626A30 30 0 0 1 666 656H206A30 30 0 0 1 176 626V594A30 30 0 0 1 206 564Z\\\" fill=\\\"#2FA3A0\\\"/>\\n <path d=\\\"M206 696H818A30 30 0 0 1 848 726V758A30 30 0 0 1 818 788H206A30 30 0 0 1 176 758V726A30 30 0 0 1 206 696Z\\\" fill=\\\"#D0342C\\\"/>\\n <path d=\\\"M206 828H506A30 30 0 0 1 536 858V890A30 30 0 0 1 506 920H206A30 30 0 0 1 176 890V858A30 30 0 0 1 206 828Z\\\" fill=\\\"#5B6478\\\"/>\\n <path d=\\\"M225 877L871 372L899 375L899 375L895 403L249 908L221 905L221 905Z\\\" fill=\\\"#D0342C\\\"/>\\n <path d=\\\"M794 372H824A24 24 0 0 1 848 396V426A24 24 0 0 1 824 450H794A24 24 0 0 1 770 426V396A24 24 0 0 1 794 372Z\\\" fill=\\\"#D0342C\\\"/>\\n <path d=\\\"M250 974a46 46 0 1 0 92 0 46 46 0 1 0-92 0Z\\\" fill=\\\"#7C5CD6\\\"/>\\n</svg>\\n\"","/**\n * The Context emblem: the colourful document sheet, bundled rather than read\n * off the harness primitives so the plugin's identity is self-contained.\n *\n * The single graphic source is the package-root `icon.svg` — the same file\n * package.json `icon` hands to the Host's package-meta reader, which serves\n * it to the Plugins page's package cards. The client bundle inlines the\n * file's markup at build time (the `?raw` channel in tsdown.config.ts) and\n * re-renders it at every requested size. Fixed fills, never `currentColor` —\n * the sheet is deliberately polychrome on both light and dark chrome.\n */\n\nimport sheetMarkup from '../../icon.svg?raw'\nimport type { ReactElement } from 'react'\nimport type { Translate } from './i18n'\n\n/** Everything between the file's `<svg>` tags: the sheet's strokes in paint order, whitespace-folded. */\nconst SHEET_MARKUP = sheetMarkup\n .slice(sheetMarkup.indexOf('>') + 1, sheetMarkup.lastIndexOf('</svg>'))\n .trim()\n .replace(/>\\s+</g, '><')\n\n/** The emblem's props, matching the harness `IconProps` the guide capsule hands it. */\nexport interface ContextIconProps {\n /** Square edge in px. */\n size?: number\n /** Extra class for layout placement. */\n className?: string\n}\n\n/** The colourful document sheet at the requested square edge. */\nexport function ContextIcon({ size = 20, className }: ContextIconProps): ReactElement {\n return (\n <svg\n width={size}\n height={size}\n viewBox=\"0 0 1024 1024\"\n className={className}\n aria-hidden=\"true\"\n xmlns=\"http://www.w3.org/2000/svg\"\n dangerouslySetInnerHTML={{ __html: SHEET_MARKUP }}\n />\n )\n}\n\n/**\n * The tab chip's title seat (`sidebar.right.pane.tab.title`): the emblem before\n * the label, so the chip reads as the files chip does. The label comes from the\n * plugin's own bound translate — read at render, so the chip follows the active\n * locale — rather than the tab-information hook, which a foreign or\n * not-yet-committed tab record can throw on. It carries a trailing gutter\n * (`.redline-title-label`) so the active chip's fade lands past the text, never on\n * the last glyphs.\n * @param t - the plugin-namespace translate bound in `apply`.\n * @returns the title component to register under the tab type's id.\n */\nexport function makeContextTabTitle(t: Translate): () => ReactElement {\n return function ContextTabTitle(): ReactElement {\n return (\n <>\n <ContextIcon size={16} className=\"redline-title-icon\" />\n <span className=\"redline-title-label\">{t('tab')}</span>\n </>\n )\n }\n}\n","/**\n * Per-session open-state stores for the /redline modal, plus the deferred\n * token-consume guards. Module-level so the state survives overlay remounts;\n * the trigger source (pick/enter) opens it, the overlay component subscribes\n * and renders. Implements the ObservableSnapshot pair the slot `hooks`\n * compartment binds as a `useContextModal` selector hook.\n */\n\nimport type { TokenSpan } from './services'\n\nexport interface ModalStore {\n subscribe(listener: () => void): () => void\n getSnapshot(): boolean\n set(open: boolean): void\n}\n\nconst stores = new Map<string, ModalStore>()\n\nexport function modalStoreOf(sessionId: string): ModalStore {\n const existing = stores.get(sessionId)\n if (existing !== undefined) return existing\n let open = false\n const listeners = new Set<() => void>()\n const store: ModalStore = {\n subscribe(listener) {\n listeners.add(listener)\n return () => { listeners.delete(listener) }\n },\n getSnapshot: () => open,\n set(next) {\n if (next === open) return\n open = next\n for (const listener of listeners) listener()\n },\n }\n stores.set(sessionId, store)\n return store\n}\n\n// ---- deferred token consumption -------------------------------------------\n// The `/redline` token stays in the composer while the modal is open and is\n// consumed only when the modal closes. Each open path records the guard the\n// input shell understands (span CAS for menu picks, bare-token equality for\n// enter); the close path takes it and dispatches the scoped\n// `slash/input-consume-token` event. A stale guard (the user typed meanwhile)\n// fails soft inside the shell — the draft is left untouched.\n\nexport type ConsumeGuard =\n | { kind: 'span'; span: TokenSpan }\n | { kind: 'bare-token'; token: string }\n\nconst pendingConsume = new Map<string, ConsumeGuard>()\n\nexport function setPendingConsume(sessionId: string, guard: ConsumeGuard): void {\n pendingConsume.set(sessionId, guard)\n}\n\nexport function takePendingConsume(sessionId: string): ConsumeGuard | undefined {\n const guard = pendingConsume.get(sessionId)\n if (guard !== undefined) pendingConsume.delete(sessionId)\n return guard\n}\n","/**\n * `/redline` — a client-owned slash command that opens the context modal\n * (current composition + recent trend) in the center of the page.\n *\n * Implemented as the plugin's own '/' trigger source instead of a host\n * command: nothing is dispatched to the host, no session log records are\n * written, and nothing becomes model-visible — the invocation never enters\n * the message history. Both paths answer `'handled'` and open the modal,\n * leaving the `/redline` token in the composer while it is open; the modal's\n * close path consumes the token then (see modalStore.ts).\n */\n\nimport { ContextIcon } from './icon'\nimport { modalStoreOf, setPendingConsume } from './modalStore'\nimport type { ClientCtx, InputTriggersFace } from './services'\nimport type { ViewKit } from './viewkit'\n\nconst COMMAND = 'redline'\nconst LINE = '/' + COMMAND\n\nexport function registerContextCommand(ctx: ClientCtx, kit: ViewKit): void {\n // Wait for the SERVICE, not for module arrival order: dsh composes\n // the client from finer modules, so `inputTriggers` may not be provided\n // yet when this plugin applies. A harness without the service never fires\n // the callback — the tab keeps working and only the command is absent.\n ctx.inject(['inputTriggers'], (ictx) => {\n const inputTriggers = (ictx as ClientCtx).get('inputTriggers') as InputTriggersFace | undefined\n if (inputTriggers === undefined || typeof inputTriggers.registerSource !== 'function') return\n ictx.effect(() => inputTriggers.registerSource({\n trigger: '/',\n name: COMMAND,\n order: 1,\n candidates: (_session, req) => {\n if (req.position !== 'leading') return Promise.resolve([])\n const query = req.query.trim().toLowerCase()\n if (query !== '' && !COMMAND.startsWith(query)) return Promise.resolve([])\n // A sectioned candidate replaces the menu's source-title row, which\n // otherwise renders the raw, unlocalizable source name (`context` is\n // not a key of the harness's own slash.menu dictionary). Label and\n // glyph are pure display data: builds that predate their rendering\n // keep showing the bare name.\n return Promise.resolve([{\n name: COMMAND,\n label: kit.t('cmd.label'),\n icon: ContextIcon,\n section: kit.t('cmd.section'),\n description: kit.t('cmd.desc'),\n }])\n },\n onPick: (pick) => {\n // Open and remember the token span: the modal's close path consumes\n // it (span CAS — a draft changed meanwhile is left untouched).\n setPendingConsume(pick.session.sessionId, { kind: 'span', span: pick.span })\n modalStoreOf(pick.session.sessionId).set(true)\n return 'handled'\n },\n matchEnter: (session, line) => {\n if (line !== LINE) return Promise.resolve(undefined)\n setPendingConsume(session.sessionId, { kind: 'bare-token', token: LINE })\n modalStoreOf(session.sessionId).set(true)\n return Promise.resolve<'handled'>('handled')\n },\n }), 'dsh-context-redline: /redline command')\n })\n}\n","/**\n * The /redline modal's dock inset: the width of the shell's sidebar track, so the fixed backdrop can start at the sidebar's right edge and\n * center the dialog over the main column instead of the whole viewport. The only host anchor is the app frame's inline grid template\n * (`<sidebar>px …` — the sidebar-leading px track is the one contract every\n * supported baseline shares; the center/right tracks' spellings differ per\n * generation) found by walking up from the backdrop. Anything unresolved — no\n * frame, unparsable template, a hostile node in the chain —\n * degrades to a 0 inset, the full-viewport mask.\n */\n\n/** The dock measure for one backdrop position: the mask inset and the frame to observe for template rewrites. */\nexport interface DockMeasure {\n /** Mask inset from the viewport's left edge, in px (0 = full-viewport mask). */\n left: number\n /** The element owning the inline grid template; null when unresolved (nothing to observe). */\n frame: HTMLElement | null\n}\n\nconst LEADING_PX_TRACK = /^(\\d+(?:\\.\\d+)?)px/\n\n/** Measure the sidebar track width from the backdrop's ancestor chain, or resolve to the full-viewport mask. */\nexport function measureDock(start: HTMLElement | null): DockMeasure {\n try {\n for (let el = start?.parentElement ?? null; el !== null; el = el.parentElement) {\n const template = el.style.gridTemplateColumns\n if (template === '') continue\n const track = LEADING_PX_TRACK.exec(template.trim())\n if (track === null) return { left: 0, frame: null }\n return { left: Number(track[1]), frame: el }\n }\n } catch { /* a hostile node in the chain degrades to the full-viewport mask */ }\n return { left: 0, frame: null }\n}\n","/**\n * Category presentation config: the seven priced buckets (system, tool\n * schemas, and the five surface categories) with their chart colors, plus\n * the part builders behind the composition card.\n *\n * Two figures ride on every part, mirroring the official chat context\n * meter's own split: `raw` is the heuristic count (the meter panel's `~`\n * rows — identical to the ring panel by construction when the official\n * `contextBreakdown` projection feeds it), while `value` is the\n * provider-anchored bar width (the ring's fill proportioned by the\n * heuristic ratios). Without a provider anchor the two are equal.\n */\n\nimport type { Category, ContextBreakdown, RequestRecord, Snapshot, TokenUsage } from '../shared/types'\n\nexport interface PartsPart {\n key: string\n color: string\n /** Bar-width figure (provider-anchored when an anchor applies). */\n value: number\n /** Heuristic count shown by the legend and tooltips (defaults to value). */\n raw?: number\n /** Tooltip display name (defaults to the category label of `key`) — DNA mode names individual items. */\n label?: string\n /** Shared-hover group: an incoming hover key equal to a part's group lights it (DNA bands light per category). */\n group?: string\n}\n\nexport const CATS: { key: Category | 'system' | 'tools'; color: string }[] = [\n { key: 'system', color: 'var(--redline-color-indigo-500)' },\n { key: 'tools', color: 'var(--redline-color-amber-500)' },\n { key: 'user', color: 'var(--redline-color-green-500)' },\n { key: 'inject', color: 'var(--redline-color-purple-500)' },\n { key: 'skill', color: 'var(--redline-color-orange-500)' },\n { key: 'assistant', color: 'var(--redline-color-blue-500)' },\n { key: 'tool', color: 'var(--redline-color-teal-500)' },\n]\n\n/** Category key → bar color, for per-item bands (the browser's DNA mode) that bypass the CATS-order part builders. */\nexport const CAT_COLOR = Object.fromEntries(CATS.map(c => [c.key, c.color])) as Record<Category | 'system' | 'tools', string>\n\nconst MESSAGE_CATS: readonly (Category | 'system' | 'tools')[] = ['user', 'inject', 'skill', 'assistant', 'tool']\n\nexport function partsOf(breakdown: Snapshot['current'] | RequestRecord): PartsPart[] {\n return CATS.map((c) => {\n return { key: c.key, color: c.color, value: breakdown[c.key] || 0 }\n })\n}\n\n/**\n * Build the pie-consistent raw parts: system/tools/messages take the\n * OFFICIAL `contextBreakdown` figures when delivered (the exact counts the\n * chat ring's panel shows), with the message bucket subdivided into the\n * four surface categories by the fold's per-category ratios (rounding\n * residue lands on the largest category, so the four always sum exactly to\n * the official message figure). Absent the projection, the fold's own sums\n * serve — the same fixed estimator, so identical on image-free sessions.\n */\nexport function officialParts(\n current: Snapshot['current'],\n breakdown: ContextBreakdown | null,\n): PartsPart[] {\n const foldSurface = current.user + current.inject + current.skill + current.assistant + current.tool\n const system = breakdown?.systemTokens ?? current.system\n const tools = breakdown?.toolsTokens ?? current.tools\n const messages = breakdown?.messageTokens ?? foldSurface\n const shares: Record<string, number> = { system, tools }\n if (foldSurface > 0) {\n let assigned = 0\n let largest: Category = 'user'\n for (const cat of MESSAGE_CATS) {\n const count = Math.round(messages * (current[cat as Category] / foldSurface))\n shares[cat] = count\n assigned += count\n if (current[cat as Category] > current[largest]) largest = cat as Category\n }\n // Rounding residue lands on the largest category; clamp so a tiny\n // message bucket with several rounded-up shares never goes negative.\n shares[largest] = Math.max(0, shares[largest] + messages - assigned)\n } else {\n for (const cat of MESSAGE_CATS) shares[cat] = 0\n }\n return CATS.map(c => ({\n key: c.key,\n color: c.color,\n /* v8 ignore next 1 -- `shares` is initialized with system/tools and both\n foldSurface arms assign every MESSAGE_CATS key, so each key is always\n defined; the fallback is defensive. */\n value: shares[c.key] ?? 0,\n }))\n}\n\n/**\n * Reproportion heuristic parts so they sum to a provider-anchored target —\n * the same trick the official ContextMeter uses: the heuristic breakdown\n * supplies the composition RATIOS, the provider sample the total. The\n * anchored figure rides `value` (bar widths); the heuristic count stays on\n * `raw` for the legend and tooltips. Returns the parts unchanged when no\n * anchor applies.\n */\nexport function anchoredParts(parts: PartsPart[], target: number | null): PartsPart[] {\n const sourced = parts.map(p => ({ ...p, raw: p.raw ?? p.value }))\n if (target === null || target <= 0) return sourced\n let total = 0\n for (const p of sourced) total += p.raw\n if (total <= 0) return sourced\n if (total === target) return sourced.map(p => ({ ...p, value: p.raw }))\n const scale = target / total\n return sourced.map(p => ({ ...p, value: Math.round(p.raw * scale) }))\n}\n\n/**\n * The Token card's billed split, by WHAT the tokens are rather than by how\n * the provider cached them: the six composition categories share the\n * provider-reported prompt-side total (uncached + cache read + cache write —\n * the chat stats line's billed input) by the composition card's own\n * estimated ratios, and the provider's exact output count closes the ring as\n * the seventh part. Only the per-category split is estimated — every\n * category's sum and the output figure are provider-reported, so the parts\n * total equals the chat line's whole-session token count by construction. A\n * zero/negative prompt total (or a hostile negative output) never invents a\n * split: the prompt parts zero out / the output clamps at 0.\n */\nexport function billedParts(\n current: Snapshot['current'],\n breakdown: ContextBreakdown | null,\n usage: TokenUsage,\n): PartsPart[] {\n const input = usage.uncachedInputTokens + usage.cacheReadTokens + usage.cacheWriteTokens\n const estimated = officialParts(current, breakdown)\n const prompt = input > 0\n ? anchoredParts(estimated, input)\n : estimated.map(p => ({ ...p, value: 0 }))\n return [...prompt, { key: 'output', color: 'var(--redline-color-pink-500)', value: Math.max(0, usage.outputTokens) }]\n}\n","/**\n * Provider-anchored headline derivation, shared by the Context tab and the\n * /redline popup: the best-known occupancy of the next request, the route\n * capacity it scales against, and the composition parts anchored to that\n * total (heuristic ratios, provider-anchored sum).\n *\n * Two official token-meter projections feed it, the same keys the chat's\n * composer ring reads: `contextPressure` supplies the anchored total (the\n * ring's percentage), and `contextBreakdown` supplies the composition\n * counts (the ring panel's system/tools/messages `~` rows) so the legend\n * figures stay identical to the panel's by construction. Either key absent\n * (older harness, meter not composed) degrades to the fold's own sums —\n * the same fixed estimator.\n */\n\nimport type { ContextBreakdown, ContextPressure, ContextTimeline } from '../shared/types'\nimport { anchoredParts, officialParts, type PartsPart } from './categories'\n\nexport interface Headline {\n /** Best-known occupancy of the next request (projected ?? derived ?? heuristic total). */\n tokens: number\n window?: number\n /** tokens / window, clamped to 100; null without a window. */\n pct: number | null\n /**\n * Composition parts: `value` is the provider-anchored bar width (the\n * ring's fill), `raw` the official heuristic count (the ring panel's\n * rows) shown by the legend and tooltips.\n */\n parts: PartsPart[]\n}\n\nexport function headlineOf(\n data: ContextTimeline,\n pressure: ContextPressure | null = null,\n breakdown: ContextBreakdown | null = null,\n): Headline {\n const current = data.current\n // The official projection's whole value is the newest usage sample carried\n // forward by the heuristic surface movement since it was taken — the same\n // formula the chat ring displays. Fields are last-wins; absent until a\n // provider reports usage.\n const projected = pressure !== null && typeof pressure.projectedTokens === 'number'\n ? pressure.projectedTokens\n : undefined\n // Fallback anchor: the newest request's provider prompt plus the heuristic\n // surface movement since it was logged (same shape as the projection, one\n // request behind). The split-generation wire head carries that record's\n // billing summary as `last` (the request records ride the detail channel);\n // the inline generation reads its newest record directly.\n const last = data.last\n const requests = data.requests\n const lastReq = requests.length > 0 ? requests[requests.length - 1] : null\n const anchor = last !== undefined ? last : lastReq\n const derived = anchor !== null && typeof anchor.prompt === 'number'\n ? anchor.prompt + (current.total - anchor.total)\n : undefined\n const occupancyTokens = projected ?? derived ?? null\n const window = pressure !== null && typeof pressure.contextWindow === 'number'\n ? pressure.contextWindow\n : data.contextWindow\n const tokens = occupancyTokens ?? current.total\n const pct = window !== undefined && window > 0 ? Math.min(100, Math.round(tokens / window * 100)) : null\n const parts = anchoredParts(\n officialParts(current, breakdown),\n occupancyTokens !== null && tokens > 0 ? tokens : null,\n )\n return { tokens, window, pct, parts }\n}\n","/**\n * Token heuristics shared by the host fold and the client boundary — the\n * harness token-meter's own fixed-density figure (dsh-token-meter/estimate.ts:\n * ~4 chars ≈ 1 token, +4 role framing). Priced identically on both sides so a\n * legacy value normalized at the client boundary matches what the host view\n * would have served.\n */\n\nconst CHARS_PER_TOKEN = 4\nconst ROLE_OVERHEAD = 4\n\n/** Price rendered system-prompt text; 0 for absent/empty/non-string input. */\nexport function estimateSystemTokens(text: unknown): number {\n if (typeof text !== 'string' || text.length === 0) return 0\n return Math.ceil(text.length / CHARS_PER_TOKEN) + ROLE_OVERHEAD\n}\n\n/**\n * Price a `system/message` payload's content exactly like the harness's\n * token-meter (`estimateSystemMessage`): text density over EVERY text block\n * plus role framing, with no per-block overhead — an adapter serializes the\n * prompt as plain text, so a text block costs its characters alone. Any other\n * block (or a hostile element) falls back to its JSON length. 0 for empty\n * content, which the harness reads as \"no system prompt\".\n */\nexport function estimateSystemContent(blocks: unknown): number {\n if (!Array.isArray(blocks) || blocks.length === 0) return 0\n let characters = 0\n for (const block of blocks) {\n const text = block !== null && typeof block === 'object' && (block as { type?: unknown }).type === 'text'\n ? (block as { text?: unknown }).text\n : undefined\n if (typeof text === 'string') {\n characters += text.length\n continue\n }\n try {\n const json: unknown = JSON.stringify(block)\n if (typeof json === 'string') characters += json.length\n } catch {\n // A cyclic/hostile block contributes no characters instead of throwing the fold.\n }\n }\n return Math.ceil(characters / CHARS_PER_TOKEN) + ROLE_OVERHEAD\n}\n","/**\n * Client-side harness boundary — the exact API surface this plugin consumes\n * from the harness web half, plus the sanitizers that re-prove every\n * delivered value at that boundary.\n *\n * The plugin bundles its own code but relies on the reader to deliver the\n * framework standard kit to slot components (`sessionId`, `useChat`,\n * `useProjection`, `t` …); only the small faces below are referenced across\n * modules. The INTERFACES are type-only (the runtime services come from the\n * user's harness); the `*Of` functions are the runtime guards the\n * no-white-screen guarantee rides on. Data arrives as pushed session\n * projections (`useProjection` standard seat); the ONE exception is the\n * gateway history page read (`remote.session.page`, see historyPage.ts) that\n * fetches a request-header epoch's content on demand.\n */\n\nimport type { Context } from '@deepseek-ai/cordis'\nimport type { ComponentType } from 'react'\nimport { estimateSystemTokens } from '../shared/estimate'\nimport type { ActivityDay, ContextActivity, ContextBreakdown, ContextHeaders, ContextPressure, ContextTimeline, CostModelUsage, HeaderEpochContent, SystemPromptNode, TimingTotals, TokenUsage, ToolTimingTotals } from '../shared/types'\n\nexport interface LocaleService {\n register(ns: string, dicts: Record<string, Record<string, string>>): () => void\n bind(ns: string): (key: string, params?: Record<string, string | number>) => string\n getLocale?(): { active: string }\n}\n\nexport interface SlotRegistration {\n name: string\n /** List slots dispatch on id + order. */\n id?: string\n order?: number\n /** Keyed slots (e.g. settings.plugin.item) dispatch on the entry key. */\n key?: string\n /** optional dictionary namespace; the framework then synthesizes the `t` seat. */\n locale?: string\n label?: () => string\n /** optional business face factory; a `hooks` compartment binds selector hooks onto props. */\n inject?: (sessionId?: string) => unknown\n}\n\nexport interface SlotsService {\n inject(name: string, callback: () => unknown): unknown\n register(\n registration: SlotRegistration,\n component: (props: { sessionId?: string } & Record<string, unknown>) => unknown,\n ): unknown\n}\n\n/**\n * One guide-page capsule a right-Sidebar tab type contributes (dsh\n * 0.1.5-rc.1+): the glyph, the title, and the optional one-line description,\n * exactly the fields `SidebarRightGuideEntry` carries.\n */\nexport interface SidebarGuideEntryLike {\n /** Ascending position among every registered type's entries. */\n order: number\n title: () => string\n /**\n * One line under the title on what picking the capsule opens; the guide\n * renders it only while it lists few enough entries. Optional, so a line\n * whose guide body ignores it simply goes without.\n */\n description?: () => string\n icon?: ComponentType<{ size?: number }>\n}\n\n/** One right-Sidebar tab type registration (the fields this plugin uses). */\nexport interface SidebarTabDefinitionLike {\n /** This implementation's identity, unique across every registration. */\n id: string\n /** What `openTab` names; also the page address's discriminator. */\n kind: string\n /** The tab chip's text, captured when the tab opens. */\n title: () => string\n /** Entry capsules for the guide page (omitted = the type stays off it). */\n guide?: readonly SidebarGuideEntryLike[]\n}\n\n/**\n * The right Sidebar's tab-type registry (`ctx.sidebarRightTabs`), as far as\n * this plugin consumes it. OPTIONAL by contract: the service ships only on the\n * 0.1.5 line (0.1.5-rc.1+ supported), so the plugin reaches it through a\n * deferred inject and stays fully functional (no pending fiber, no throw)\n * without it.\n */\nexport interface SidebarTabsFace {\n register(definition: SidebarTabDefinitionLike): () => void\n}\n\n/**\n * The right Sidebar's navigation face (`ctx.sidebarRight`), as far as this\n * plugin consumes it: `openResource` claims a `dsh-resource://file/…` address\n * through the shipped preview type and reveals the column in the same step.\n * The same optional generation as {@link SidebarTabsFace}; the caller re-proves\n * the verb at runtime and falls back to the system opener when it is absent or\n * refuses the address.\n */\nexport interface SidebarResourceFace {\n openResource(address: string): void\n}\n\n/**\n * The conversation node, as far as the Context browser consumes it: the\n * framework's finalized chat nodes carry the source surface event's `seq`\n * plus the full content — the browser joins its surface nodes on `seq` to\n * show actual content without carrying it through the projection.\n */\nexport interface ConversationNodeLike {\n kind: string\n seq: number\n /**\n * The durable message id (assistant nodes on the harness chat nodes; absent\n * on synthetic/interrupted replies) — the key the chat's assistant-action\n * seat addresses a finalized reply by.\n */\n messageId?: unknown\n content?: readonly unknown[]\n blocks?: readonly unknown[]\n call?: { name: string; argsRaw: string } | null\n isError?: boolean\n summary?: string | null\n /**\n * Nested Code-Mode call tree (dsh's recursive ToolCallBlock[]) on a tool\n * result whose call ran sub-dispatches — a PTC `run_code` program. Consumed\n * structurally only (fileActivity): every block is re-proved at runtime and\n * malformed shapes drop out instead of throwing.\n */\n subCalls?: readonly unknown[]\n /** The tool result's bounded presentation meta (a search's matched files), as the join delivers it. */\n meta?: unknown\n}\n\n/**\n * A durable image attachment reference, as far as this plugin consumes it\n * (dsh's `ImageAttachmentRef`, minimally re-typed so the plugin stays free\n * of an attachment-package dependency). The durable log holds only this ref\n * — never inline bytes. On every supported line the width/height/bytes\n * describe the NORMALIZED raster under a deployment-resolvable policy\n * (defaults: total-pixel budget 2048×2048, long edge capped at 8192px);\n * `originalDimensions` carries the pre-normalization size when normalization\n * reduced the image.\n */\nexport interface ImageRefLike {\n attachmentId: string\n name?: string\n bytes?: number\n width?: number\n height?: number\n originalDimensions?: { width: number; height: number }\n}\n\n/** Loads a session-authorized display URL for one durable image reference. */\nexport type ImageLoader = (attachment: ImageRefLike) => Promise<string>\n\n/**\n * The harness conversation client service, minimally typed for image\n * resolution — the same call the chat view's own message images ride on\n * (`ctx.uiConversation.imageUrl`).\n */\nexport interface UiConversationFace {\n imageUrl?(sessionId: string, attachment: ImageRefLike): Promise<string>\n}\n\n/**\n * A session-authorized durable-image loader over the harness conversation\n * face (`uiConversation.imageUrl`), or undefined when the service is not\n * composed — the caller degrades to metadata-only cards. Hostile snapshots\n * and throwing service reads are caught: this helper can never take a\n * render down.\n */\nexport function imageLoaderOf(\n ctx: ClientCtx,\n sessionId: string | undefined,\n): ImageLoader | undefined {\n if (typeof sessionId !== 'string' || sessionId === '') return undefined\n try {\n const conversation = ctx.get('uiConversation') as UiConversationFace | undefined\n if (conversation !== undefined && typeof conversation.imageUrl === 'function') {\n const imageUrl = conversation.imageUrl.bind(conversation)\n return attachment => imageUrl(sessionId, attachment)\n }\n } catch { /* absent or hostile service — metadata-only cards */ }\n return undefined\n}\n\n/**\n * The `useChat` standard seat (the finalized chat nodes live on a per-view\n * `ChatSnapshot` whose `legacy` slice keeps the plain `ConversationNode[]`).\n * Minimally typed: the selector receives the harness snapshot (untrusted —\n * re-proved outside), and the slice it returns must be reference-stable so\n * the framework's selector-hook equality can gate re-renders.\n */\nexport type UseChatLike = <T>(selector: (snapshot: unknown) => T) => T\n\n/**\n * The conversation-window nodes this plugin joins on, from the `useChat`\n * seat (`ChatSnapshot.legacy.nodes`). Returns undefined when the seat does\n * not deliver a real array (absent seat, foreign harness, hostile snapshot)\n * — callers render without the join, never an error.\n */\nexport function conversationNodesOf(props: {\n useChat?: UseChatLike\n}): readonly ConversationNodeLike[] | undefined {\n const useChat: unknown = props.useChat\n if (typeof useChat !== 'function') return undefined\n try {\n // `s.legacy` is a stable object; the array is read outside the selector.\n const slice = (useChat as UseChatLike)((s: unknown) =>\n s !== null && typeof s === 'object' ? (s as { legacy?: unknown }).legacy : undefined)\n const nodes = slice !== null && typeof slice === 'object' ? (slice as { nodes?: unknown }).nodes : undefined\n return Array.isArray(nodes) ? nodes as readonly ConversationNodeLike[] : undefined\n } catch { /* hostile seat — the join degrades to nothing */ }\n return undefined\n}\n\n/**\n * The framework standard kit of a session-scope slot component, as far as\n * this plugin consumes it: the resolve session id and the key-addressed\n * projection reader that delivers the `redlineTimeline` value (undefined =\n * the host unit is absent or no value has arrived yet).\n */\nexport interface SessionStandardProps {\n sessionId?: string\n useProjection?: (key: string) => unknown\n /** The chat-view snapshot seat (see {@link UseChatLike}). */\n useChat?: UseChatLike\n}\n\n/**\n * The Context view's props: the framework standard kit plus this plugin's own\n * host marker. The right Sidebar's panel registration sets `host`, so the SAME\n * view drops the head cards a narrow column cannot serve.\n */\nexport interface ContextViewProps extends SessionStandardProps {\n /** Set only by the right-Sidebar registration; absent in the conversation tab and the /redline modal. */\n host?: 'sidebar'\n}\n\n/**\n * Read one projection key through the standard seat, narrowed at the\n * boundary: null when the seat is absent (a harness without the projection\n * pipeline) or the delivered value fails the narrow. The seat is a real\n * hook — call this unconditionally at the top of the component, one call\n * per key, in a stable order.\n */\nexport function projectionOf<T>(props: SessionStandardProps, key: string, narrow: (value: unknown) => T | null): T | null {\n if (typeof props.useProjection !== 'function') return null\n return narrow(props.useProjection(key))\n}\n\nexport type ClientCtx = Context & {\n locale: LocaleService\n slots: SlotsService\n}\n\n/**\n * Narrow an unknown projection value to a string-keyed record, or null when\n * it is not one. The boundary type is Record<string, unknown> on purpose:\n * every field read below must re-prove itself (the no-white-screen\n * guarantee), so no field may borrow the wire type before its check.\n * Shared by every sanitizer here and by the agent-tree derivation\n * (agentTree.ts) — the ONE record guard for the whole client half.\n */\nexport function asRecord(value: unknown): Record<string, unknown> | null {\n if (value === null || value === undefined || typeof value !== 'object') return null\n return value as Record<string, unknown>\n}\n\n/**\n * Safe finite-number read: a missing/non-numeric/NaN field degrades to 0\n * instead of leaking into the UI as NaN percentages or broken arithmetic.\n */\nexport function numOf(value: unknown): number {\n return typeof value === 'number' && Number.isFinite(value) ? value : 0\n}\n\n/** Shared per-item collection guard: drop non-object entries, keep the rest. */\nexport function objectsOf<T>(value: unknown): T[] {\n if (!Array.isArray(value)) return []\n return value.filter((v): v is T => v !== null && typeof v === 'object')\n}\n\n/**\n * The fast path's collection check: a real array whose entries are ALL\n * records. A null/primitive entry would pass a bare Array.isArray yet throw\n * on the first property read downstream (`req.seq` on null), so it sends the\n * value down the sanitizing slow path, where `objectsOf` drops it.\n */\nfunction recordsOnly(value: unknown): boolean {\n return Array.isArray(value) && value.every(e => e !== null && typeof e === 'object')\n}\n\n/**\n * Narrow a delivered `unsupported` gate record (the host's baseline gate —\n * see host/fallback.ts): both version strings re-proved, anything else\n * degrades to null (no gate shown) instead of rendering garbage.\n */\nexport function unsupportedOf(value: unknown): { current: string; minimum: string } | null {\n const data = asRecord(value)\n if (data === null) return null\n if (typeof data.current !== 'string' || typeof data.minimum !== 'string') return null\n return { current: data.current, minimum: data.minimum }\n}\n\n/**\n * The session-cost raw material, re-proved per provider/model/period/bucket\n * (the shape the client's cost.ts prices): a branch, model, or period that\n * is not a plain record drops whole — never a half-proved row — and bucket\n * fields zero out via numOf, so garbage can only price as zero, never as\n * NaN. Absent stays absent.\n */\nfunction costOf(value: unknown): ContextTimeline['cost'] | undefined {\n const data = asRecord(value)\n if (data === null || Array.isArray(data)) return undefined\n const out: NonNullable<ContextTimeline['cost']> = {}\n for (const provider of Object.keys(data)) {\n const models = asRecord(data[provider])\n if (models === null || Array.isArray(models)) continue\n const branch: Record<string, CostModelUsage> = {}\n for (const model of Object.keys(models)) {\n const periods = asRecord(models[model])\n if (periods === null || Array.isArray(periods)) continue\n const copy: CostModelUsage = {}\n for (const period of ['peak', 'off'] as const) {\n const b = asRecord(periods[period])\n if (b === null || Array.isArray(b)) continue\n copy[period] = {\n uncached: numOf(b.uncached),\n cacheRead: numOf(b.cacheRead),\n cacheWrite: numOf(b.cacheWrite),\n output: numOf(b.output),\n }\n }\n branch[model] = copy\n }\n out[provider] = branch\n }\n return out\n}\n\n/** The fast-path structural check for `cost`: every branch is a plain record (bucket fields re-prove in costOf/cost.ts). */\nfunction costFastOk(value: unknown): boolean {\n if (value === undefined) return true\n const data = asRecord(value)\n if (data === null || Array.isArray(data)) return false\n return Object.keys(data).every((provider) => {\n const models = asRecord(data[provider])\n return models !== null && !Array.isArray(models)\n })\n}\n\n/**\n * Narrow a delivered projection value to a RENDER-SAFE context timeline —\n * the client's no-white-screen guarantee against backend/parse failures.\n *\n * A value that is not a record at all (capability absent, nothing delivered\n * yet) stays `null` and callers show the loading screen. A record that fails\n * the wire shape (corrupt checkpoint restore, a failed/older host payload,\n * plugin drift) is SANITIZED instead of rejected: every collection becomes\n * an array, non-object entries are dropped, `current` becomes a numeric\n * breakdown, and wrong-typed scalars are dropped or zeroed — so the whole\n * tab still renders with every usable piece of data instead of throwing\n * during render and unmounting the conversation view.\n */\nexport function timelineOf(value: unknown): ContextTimeline | null {\n const data = asRecord(value)\n if (data === null) return null\n const current = data.current\n // The wire shape check for the cheap pass-through path: `current` must be\n // a full numeric breakdown (the host always sends all seven fields), and\n // every collection must be a real list. Anything else takes the slow path\n // and is rebuilt into the safe shape below.\n const numericBreakdown = current !== null && typeof current === 'object'\n && ['system', 'tools', 'user', 'inject', 'skill', 'assistant', 'tool', 'total']\n .every(k => typeof (current as Record<string, unknown>)[k] === 'number')\n if (numericBreakdown\n && recordsOnly(data.requests)\n && recordsOnly(data.events)\n && recordsOnly(data.nodes)\n && recordsOnly(data.archive)\n && systemsFastOk(data.systems)\n && timingFastOk(data.timing)\n && costFastOk(data.cost)) {\n // Well-formed: pass the delivered value through untouched (cheap, and reference-stable so plain re-renders stay zero-copy).\n return data as unknown as ContextTimeline\n }\n const safeCurrent: Record<string, unknown> = current !== null && typeof current === 'object' ? current as Record<string, unknown> : {}\n const cost = costOf(data.cost)\n const timing = timingOf(data.timing)\n // The baseline-gate record survives sanitizing: a fallback payload that\n // somehow fails the fast path must still pop the gate modal.\n const unsupported = unsupportedOf(data.unsupported)\n // The split-generation head fields survive sanitizing too.\n const counts = countsOf(data.counts)\n const last = lastOf(data.last)\n const safe: ContextTimeline = {\n ok: true,\n ...(unsupported !== null ? { unsupported } : {}),\n ...(typeof data.model === 'string' ? { model: data.model } : {}),\n ...(typeof data.provider === 'string' ? { provider: data.provider } : {}),\n ...(typeof data.contextWindow === 'number' ? { contextWindow: data.contextWindow } : {}),\n current: {\n system: numOf(safeCurrent.system),\n tools: numOf(safeCurrent.tools),\n user: numOf(safeCurrent.user),\n inject: numOf(safeCurrent.inject),\n skill: numOf(safeCurrent.skill),\n assistant: numOf(safeCurrent.assistant),\n tool: numOf(safeCurrent.tool),\n total: numOf(safeCurrent.total),\n },\n requests: objectsOf(data.requests),\n events: objectsOf(data.events),\n nodes: objectsOf(data.nodes),\n droppedNodes: numOf(data.droppedNodes),\n ...(typeof data.images === 'number' ? { images: data.images } : {}),\n ...(typeof data.toolCalls === 'number' ? { toolCalls: data.toolCalls } : {}),\n ...(typeof data.humanInputs === 'number' ? { humanInputs: data.humanInputs } : {}),\n ...(typeof data.lastUser === 'string' && data.lastUser !== '' ? { lastUser: data.lastUser.slice(0, 200) } : {}),\n archive: objectsOf(data.archive),\n ...(counts !== undefined ? { counts } : {}),\n ...(last !== undefined ? { last } : {}),\n ...(typeof data.detailRev === 'number' && Number.isFinite(data.detailRev) ? { detailRev: data.detailRev } : {}),\n ...(cost !== undefined ? { cost } : {}),\n ...(timing !== null ? { timing } : {}),\n ...(data.systems !== undefined ? { systems: systemsOf(data.systems) } : {}),\n ...(typeof data.surfaceFloor === 'number' ? { surfaceFloor: data.surfaceFloor } : {}),\n ...(typeof data.archiveFloor === 'number' ? { archiveFloor: data.archiveFloor } : {}),\n ...(data.fileOps !== undefined ? { fileOps: objectsOf(data.fileOps) } : {}),\n ...(typeof data.fileOpsFloor === 'number' ? { fileOpsFloor: data.fileOpsFloor } : {}),\n }\n return safe\n}\n\n/**\n * The live system-prompt nodes, re-proved per entry and sorted by seq: an\n * entry missing a finite seq/time/tokens drops out (the browser then falls\n * back to the header epoch), so a hostile collection can never produce a NaN\n * prompt figure or an unfetchable seq. Absent or empty stays absent.\n */\nfunction systemsOf(value: unknown): ContextTimeline['systems'] {\n const list = objectsOf<Record<string, unknown>>(value)\n const out: SystemPromptNode[] = []\n for (const entry of list) {\n const { seq, time, tokens } = entry\n if (typeof seq !== 'number' || !Number.isFinite(seq)) continue\n if (typeof time !== 'number' || !Number.isFinite(time)) continue\n if (typeof tokens !== 'number' || !Number.isFinite(tokens)) continue\n out.push({ seq, time, tokens })\n }\n return out.sort((a, b) => a.seq - b.seq)\n}\n\n/**\n * The fast path's check for the live system-prompt nodes: every entry must\n * carry the three finite numbers the browser reads — `seq` for the per-step\n * resolution, `time` for the DNA band, `tokens` for its width. A primitive\n * entry, or one whose fields are not numbers, sends the payload down the\n * sanitizing slow path (`systemsOf` drops it) instead of leaking `undefined`\n * into the bar math. An absent list is fine.\n */\nfunction systemsFastOk(value: unknown): boolean {\n if (value === undefined) return true\n if (!Array.isArray(value)) return false\n return value.every((entry) => {\n if (entry === null || typeof entry !== 'object') return false\n const { seq, time, tokens } = entry as Record<string, unknown>\n return typeof seq === 'number' && Number.isFinite(seq)\n && typeof time === 'number' && Number.isFinite(time)\n && typeof tokens === 'number' && Number.isFinite(tokens)\n })\n}\n\n/**\n * The split head's count figures, re-proved field by field: a present-but-\n * partial record zeroes its unreadable fields (the stats board's no-NaN\n * guarantee), an absent or non-record value stays absent (legacy generation\n * — callers derive the counts from the collections instead).\n */\nfunction countsOf(value: unknown): ContextTimeline['counts'] {\n const data = asRecord(value)\n if (data === null) return undefined\n return {\n turns: numOf(data.turns),\n steps: numOf(data.steps),\n injects: numOf(data.injects),\n compactions: numOf(data.compactions),\n prunes: numOf(data.prunes),\n }\n}\n\n/** The split head's newest-request summary; absent or shapeless stays absent. */\nfunction lastOf(value: unknown): ContextTimeline['last'] {\n const data = asRecord(value)\n if (data === null) return undefined\n if (typeof data.seq !== 'number' || !Number.isFinite(data.seq)) return undefined\n if (typeof data.total !== 'number' || !Number.isFinite(data.total)) return undefined\n return {\n seq: data.seq,\n total: data.total,\n ...(typeof data.prompt === 'number' && Number.isFinite(data.prompt) ? { prompt: data.prompt } : {}),\n }\n}\n\n/**\n * Narrow a delivered projection value to the official token-meter\n * `contextPressure` projection (provider-anchored occupancy of the next\n * request). Absent key or value = the meter's projection is not composed\n * (e.g. a harness without the session-projection registry) — callers fall\n * back to their derived anchor, so the UI degrades gracefully. The three\n * fields are independent last-wins records on the wire (dsh's strict wire\n * schema), so each is re-proved on its own: a wrong-typed field drops out,\n * the readable ones survive.\n */\nexport function contextPressureOf(value: unknown): ContextPressure | null {\n const data = asRecord(value)\n if (data === null) return null\n const out: ContextPressure = {}\n if (typeof data.pressureTokens === 'number' && Number.isFinite(data.pressureTokens)) out.pressureTokens = data.pressureTokens\n if (typeof data.projectedTokens === 'number' && Number.isFinite(data.projectedTokens)) out.projectedTokens = data.projectedTokens\n if (typeof data.contextWindow === 'number' && Number.isFinite(data.contextWindow)) out.contextWindow = data.contextWindow\n return out\n}\n\n/**\n * Narrow a delivered projection value to the official token-meter\n * `contextBreakdown` projection (the heuristic composition rows of the chat\n * ring's panel). Every figure must be a finite number — a partial/corrupt\n * value degrades to null so the composition card falls back to the fold's\n * own sums instead of mixing sources.\n */\nexport function contextBreakdownOf(value: unknown): ContextBreakdown | null {\n const data = asRecord(value)\n if (data === null) return null\n const { systemTokens, toolsTokens, messageTokens } = data\n if (typeof systemTokens !== 'number' || !Number.isFinite(systemTokens)) return null\n if (typeof toolsTokens !== 'number' || !Number.isFinite(toolsTokens)) return null\n if (typeof messageTokens !== 'number' || !Number.isFinite(messageTokens)) return null\n return { systemTokens, toolsTokens, messageTokens }\n}\n\n/**\n * Narrow a delivered projection value to the official token-meter\n * `tokenUsage` projection (durable cumulative provider usage). Absent key or\n * value = the meter's projection is not composed (or no request has reported\n * usage yet) — callers drop the cache-hit cell to a dash. The wire schema is\n * strict with all four buckets REQUIRED (dsh token-meter's projectionSchema),\n * so a partial/corrupt value degrades the whole value to null instead of\n * undercounting the billed total.\n */\nexport function tokenUsageOf(value: unknown): TokenUsage | null {\n const data = asRecord(value)\n if (data === null) return null\n const { uncachedInputTokens, outputTokens, cacheReadTokens, cacheWriteTokens } = data\n if (typeof uncachedInputTokens !== 'number' || !Number.isFinite(uncachedInputTokens)) return null\n if (typeof outputTokens !== 'number' || !Number.isFinite(outputTokens)) return null\n if (typeof cacheReadTokens !== 'number' || !Number.isFinite(cacheReadTokens)) return null\n if (typeof cacheWriteTokens !== 'number' || !Number.isFinite(cacheWriteTokens)) return null\n return { uncachedInputTokens, outputTokens, cacheReadTokens, cacheWriteTokens }\n}\n\n/**\n * A non-negative finite number (the timing totals' every field): NaN or a\n * negative degrades to 0 instead of leaking into donut shares.\n */\nfunction msNumOf(value: unknown): number {\n return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : 0\n}\n\n/**\n * The OPTIONAL timing scalars (the generation split's spans and block counts):\n * a real non-negative number passes, anything else — including absence — reads\n * as undefined so the field stays absent on the narrowed value (see\n * `timingOf`).\n */\nfunction optNumOf(value: unknown): number | undefined {\n return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : undefined\n}\n\n/**\n * Cheap whole-value check for the pass-through path of `timelineOf`: absent\n * timing passes; present timing must already be well-formed (every scalar\n * numeric, every per-name row shaped) — anything else sends the payload down\n * the sanitizing slow path.\n */\nfunction timingFastOk(value: unknown): boolean {\n if (value === undefined) return true\n if (value === null || typeof value !== 'object' || Array.isArray(value)) return false\n const t = value as Record<string, unknown>\n for (const k of ['wallMs', 'ttftMs', 'genMs', 'calls', 'toolsMs', 'toolCalls']) {\n if (typeof t[k] !== 'number') return false\n }\n // The generation split and the block counts are optional but, when present,\n // must be finite non-negative numbers — the same gate the slow path applies,\n // so a hostile bucket cannot slip through the fast path (see `timingOf`).\n for (const k of ['reasoningMs', 'textMs', 'toolArgMs', 'reasoningBlocks', 'textBlocks', 'toolArgBlocks']) {\n const v = t[k]\n if (v !== undefined && (typeof v !== 'number' || !Number.isFinite(v) || v < 0)) return false\n }\n const tools = t.tools\n if (tools === null || typeof tools !== 'object' || Array.isArray(tools)) return false\n for (const k in tools) {\n const row = (tools as Record<string, unknown>)[k]\n if (row === null || typeof row !== 'object') return false\n if (typeof (row as Record<string, unknown>).calls !== 'number') return false\n if (typeof (row as Record<string, unknown>).ms !== 'number') return false\n }\n return true\n}\n\n/**\n * Narrow a delivered timing totals value (see TimingTotals) to a RENDER-SAFE\n * shape — the timing card's no-white-screen guarantee. A value that is not a\n * record stays null (the card renders its empty state); wrong-typed scalars\n * zero out and per-name rows failing the shape drop individually, so one\n * hostile row never blanks the ranking.\n */\nexport function timingOf(value: unknown): TimingTotals | null {\n const data = asRecord(value)\n if (data === null) return null\n const tools: Record<string, ToolTimingTotals> = {}\n const rawTools = data.tools\n if (rawTools !== null && typeof rawTools === 'object' && !Array.isArray(rawTools)) {\n for (const k in rawTools) {\n // A JSON-delivered record can carry an own '__proto__' key; assigning it\n // would set the prototype instead of a row — skip it.\n if (k === '__proto__' || !Object.hasOwn(rawTools, k)) continue\n const row = (rawTools as Record<string, unknown>)[k]\n if (row === null || typeof row !== 'object') continue\n const calls = (row as Record<string, unknown>).calls\n const ms = (row as Record<string, unknown>).ms\n if (typeof calls !== 'number' || !(calls >= 0) || typeof ms !== 'number' || !(ms >= 0)) continue\n tools[k] = { calls, ms }\n }\n }\n const totals: TimingTotals = {\n wallMs: msNumOf(data.wallMs),\n ttftMs: msNumOf(data.ttftMs),\n genMs: msNumOf(data.genMs),\n calls: msNumOf(data.calls),\n toolsMs: msNumOf(data.toolsMs),\n toolCalls: msNumOf(data.toolCalls),\n tools,\n }\n // The optional scalars stay ABSENT when the host did not serve them (a row\n // cached before the split / the counts) or served a non-number: the card\n // renders the un-split shape / no qualifier instead of meaningless zeros.\n const reasoning = optNumOf(data.reasoningMs)\n if (reasoning !== undefined) totals.reasoningMs = reasoning\n const reasoningBlocks = optNumOf(data.reasoningBlocks)\n if (reasoningBlocks !== undefined) totals.reasoningBlocks = reasoningBlocks\n const textMs = optNumOf(data.textMs)\n if (textMs !== undefined) totals.textMs = textMs\n const textBlocks = optNumOf(data.textBlocks)\n if (textBlocks !== undefined) totals.textBlocks = textBlocks\n const toolArgMs = optNumOf(data.toolArgMs)\n if (toolArgMs !== undefined) totals.toolArgMs = toolArgMs\n const toolArgBlocks = optNumOf(data.toolArgBlocks)\n if (toolArgBlocks !== undefined) totals.toolArgBlocks = toolArgBlocks\n return totals\n}\n\n/**\n * Narrow a delivered projection value to the plugin's `redlineHeaders`\n * (request-header epoch METADATA — boundaries, token prices, attribution).\n * Absent key = an older Host half without the companion unit — the Context\n * browser degrades its system/tools sections to a metadata-only note.\n *\n * Entry-level shape is checked too: a malformed epoch (corrupt payload with\n * a missing tools list, a wrong-typed systemTokens, or a tool row whose\n * name/tokens the browser reads blindly — `tool.name.toLowerCase()` and\n * `b.tokens - a.tokens` throw on junk) would crash the browser's\n * tools/sections reads, so the WHOLE projection degrades to null and the\n * card falls back to its metadata-only note. The epoch CONTENT is\n * not part of this value — the browser fetches it per epoch on demand.\n *\n * The pre-#37 wire generation carries the system TEXT instead of its token\n * price (a host still running the old view — stale watch build, an app not\n * restarted since the upgrade — serves it from its cache verbatim), so the\n * two generations are normalized to the metadata shape here: unpriced legacy\n * entries get the shared meter heuristic applied, priced ones and\n * new-shape values pass through untouched.\n */\nexport function headersOf(value: unknown): ContextHeaders | null {\n const headers = asRecord(value)\n if (headers === null || !Array.isArray(headers.headers)) return null\n for (const h of headers.headers as unknown[]) {\n if (h === null || typeof h !== 'object') return null\n const entry = h as { tools?: unknown; systemTokens?: unknown }\n if (!Array.isArray(entry.tools)) return null\n if (entry.systemTokens !== undefined && (typeof entry.systemTokens !== 'number' || !Number.isFinite(entry.systemTokens))) return null\n for (const t of entry.tools as unknown[]) {\n if (t === null || typeof t !== 'object') return null\n const tool = t as { name?: unknown; tokens?: unknown; plugin?: unknown }\n if (typeof tool.name !== 'string') return null\n if (typeof tool.tokens !== 'number' || !Number.isFinite(tool.tokens)) return null\n if (tool.plugin !== undefined && typeof tool.plugin !== 'string') return null\n }\n }\n let legacy = false\n for (const entry of headers.headers as { systemTokens?: unknown; system?: unknown }[]) {\n if (entry.systemTokens === undefined && typeof entry.system === 'string' && entry.system !== '') {\n legacy = true\n break\n }\n }\n if (!legacy) return headers as unknown as ContextHeaders\n return {\n headers: (headers.headers as { systemTokens?: number; system?: unknown }[]).map((entry) => {\n if (entry.systemTokens !== undefined) return entry\n return { ...entry, systemTokens: estimateSystemTokens(entry.system) || undefined }\n }),\n } as unknown as ContextHeaders\n}\n\n/**\n * Narrow a delivered `redlineActivity` value (the per-day ledger the Context\n * Overview's heatmap and usage chart read off each session-list row) to a\n * render-safe shape. Absent or non-record stays null (an older host serves no\n * such key — the heatmap renders its empty note). Per-day re-proved: a\n * malformed key or a wrong-typed figure drops just that entry, a malformed\n * pricing record drops just the fee (the day's tokens survive), a hostile day\n * record can never produce a NaN cell, and a well-formed payload passes\n * through untouched (reference-stable for the selector equality).\n */\nexport function activityOf(value: unknown): ContextActivity | null {\n const data = asRecord(value)\n if (data === null) return null\n const rawDays = asRecord(data.days)\n if (rawDays === null || Array.isArray(rawDays)) return null\n const days: Record<string, ActivityDay> = {}\n let dirty = false\n for (const key of Object.keys(rawDays)) {\n const entry = asRecord(rawDays[key])\n const tokens = entry?.tokens\n const requests = entry?.requests\n if (!/^\\d{4}-\\d{2}-\\d{2}$/.test(key)\n || entry === null || Array.isArray(entry)\n || typeof tokens !== 'number' || !Number.isFinite(tokens) || tokens < 0\n || typeof requests !== 'number' || !Number.isFinite(requests) || requests < 0) {\n dirty = true\n continue\n }\n // The day's pricing record (additive-optional): re-proved by the SAME\n // sanitizer the timeline's session-cost rides. Absent stays absent; a\n // record with no readable branch drops whole (empty ≠ zero — a truly\n // metered day always carries a branch), keeping the day's own figures.\n const proved = costOf(entry.cost)\n const cost = proved !== undefined && Object.keys(proved).length > 0 ? proved : undefined\n if (entry.cost !== undefined && cost === undefined) dirty = true\n days[key] = { tokens, requests, ...(cost !== undefined ? { cost } : {}) }\n }\n // Fully well-formed: pass the delivered value through untouched (cheap, and\n // reference-stable for the selector equality); otherwise the sanitized copy.\n return dirty ? { days } : data as unknown as ContextActivity\n}\n\nexport interface TriggerCandidate {\n name: string\n /** Display title; the name itself when absent (a differing title renders the name as a trailing alias). */\n label?: string\n /** Visual heading of this candidate's group; its presence suppresses the menu's source-title row. */\n section?: string\n description?: string\n /** Row glyph, rendered at a 16px edge. */\n icon?: ComponentType<{ size?: number }>\n}\n\n/** Pick-moment snapshot of the trigger token span (draftRev CAS). */\nexport interface TokenSpan {\n start: number\n end: number\n draftRev: number\n}\n\nexport interface TriggerPick {\n candidate: TriggerCandidate\n session: { sessionId: string }\n position: string\n via: string\n span: TokenSpan\n}\n\nexport type SourcePickOutcome = 'handled' | undefined\n\n/**\n * The harness input-trigger service (`ctx.inputTriggers`), as far as this\n * plugin consumes it: registering one '/' source whose candidates, picks,\n * and enter adjudication all stay on the client.\n */\nexport interface InputTriggersFace {\n registerSource(src: {\n trigger: '/'\n name: string\n order?: number\n candidates(\n session: { sessionId: string },\n req: { query: string; position: string; signal: AbortSignal },\n ): Promise<readonly TriggerCandidate[]>\n onPick(pick: TriggerPick): SourcePickOutcome\n matchEnter?(\n session: { sessionId: string },\n line: string,\n signal: AbortSignal,\n ): Promise<SourcePickOutcome>\n }): () => void\n}\n\n/** The session scope (`ctx.sessions.scope`), used to dispatch the scoped consume-token event. */\nexport interface SessionScopeFace {\n bail(subject: unknown, event: string, payload: unknown): unknown\n}\n\nexport interface SessionsFace {\n scope(id: string): SessionScopeFace | undefined\n /**\n * Select a listed session as current — the retired selection spelling,\n * still served through the 0.1.5 line and gone since the 0.1.6 selection\n * refactor (issue #90: the verb's home is now the view owner). Re-proved at\n * the call site via {@link openSessionVia}, which prefers the newer face.\n */\n open?(id: string): void\n /**\n * Re-pull the session-list baseline (the rows' projection column included).\n * The overview rides it on open so host-side backfill rows (backfill.ts)\n * reach a long-connected browser without a reload.\n */\n refresh?(): Promise<unknown>\n}\n\n/** One history page row: the raw event plus the optional host-computed view. */\nexport interface HistoryEntryLike {\n event?: unknown\n}\n\n/**\n * The seq-anchored history page verb of the harness gateway remotes: the\n * session namespace mounts as a traced cordis service literally named\n * `remote.session`. The plugin resolves it through the DECLARED inject\n * (`watchHistoryFaces` in historyPage.ts — a non-declared read of the\n * traced proxy throws), so reads are undefined on harnesses that never\n * mount it rather than crashing. `throughSeq` is the inclusive log cut (a\n * seq that must exist in the log), `beforeSeq` the exclusive upper bound,\n * and the response wraps the rows in a `ClientResult`-style envelope. Rows\n * are `SessionHistoryRecord`s — `{type:'event', event}` entries plus packed\n * `{type:'chunks', …}` runs the mapper skips (every event the fold needs —\n * user/assistant messages, tool calls/results, compaction summaries — is\n * always served verbatim; only streaming deltas pack).\n */\nexport interface SessionPageFace {\n page(request: {\n address: { kind: 'session'; sessionId: string }\n throughSeq: number\n beforeSeq?: number\n maxMessages?: number\n }, signal?: AbortSignal): Promise<unknown>\n}\n\n/**\n * The connection service face, as far as this plugin consumes it: the\n * generic Connection RPC caller (the harness's unary channel transport)\n * plus the loopback fact the harness's own open affordances gate on.\n */\nexport interface ConnectionFace {\n /** Whether the page reaches the Host on the operator's own machine. */\n isLoopback?: boolean\n rpc?: {\n call?(channel: string, endpoint: string, payload: unknown, signal?: AbortSignal): Promise<unknown>\n }\n}\n\n/** The session-namespace workspace-opener remotes, ridden through the generic '/api' channel. */\nconst OPEN_CHANNEL = '/api'\nconst CAN_OPEN_ENDPOINT = 'session/canOpenWorkspacePath'\nconst OPEN_ENDPOINT = 'session/openWorkspacePath'\n\n/**\n * The connection's bound generic-RPC caller, or undefined when the service\n * is absent or hostile — every read is guarded, so this can never throw.\n */\nexport function rpcCallOf(ctx: ClientCtx): ((channel: string, endpoint: string, payload: unknown) => Promise<unknown>) | undefined {\n try {\n const rpc = asRecord((ctx.get('connection') as ConnectionFace | undefined)?.rpc)\n const fn = rpc?.call\n if (rpc !== null && typeof fn === 'function') {\n return (fn as (channel: string, endpoint: string, payload: unknown) => Promise<unknown>).bind(rpc)\n }\n } catch { /* absent or hostile connection — the caller degrades off */ }\n return undefined\n}\n\n/**\n * The SESSION's workspace root — the `cwd` its session-list row carries (the\n * host session canon, not the host process's own launch directory) — or\n * undefined when the face is absent, the snapshot is malformed, or the row\n * names no cwd. Every field is re-proved — the no-white-screen guarantee.\n */\nexport function workspaceOf(ctx: ClientCtx, sessionId: string | undefined): string | undefined {\n if (typeof sessionId !== 'string' || sessionId === '') return undefined\n // The snapshot and its rows are host data — a hostile object may throw on\n // the call or on property access, and the card must never blank over it.\n try {\n const sessions = ctx.get('sessions') as { list?: { getSnapshot(): unknown } } | undefined\n const snapshot = typeof sessions?.list?.getSnapshot === 'function' ? sessions.list.getSnapshot() : undefined\n const byId = snapshot !== null && typeof snapshot === 'object' ? (snapshot as { byId?: unknown }).byId : undefined\n const row: unknown = byId !== null && typeof byId === 'object' ? (byId as Record<string, unknown>)[sessionId] : undefined\n const cwd = row !== null && typeof row === 'object' ? (row as { cwd?: unknown }).cwd : undefined\n return typeof cwd === 'string' && cwd !== '' ? cwd : undefined\n } catch {\n return undefined\n }\n}\n\n/**\n * Whether this deployment can hand a path to the user's native desktop: the\n * page must reach the Host on the operator's own machine (`isLoopback`, the\n * harness's own gate) AND the session controller's opener capability remote\n * must answer true. The capability is an RPC round-trip now (the synchronous\n * host-description fact is gone), so the answer is asynchronous; every\n * absence, hostility, or transport failure resolves false — never a rejection.\n */\nexport async function canOpenPathsOf(ctx: ClientCtx): Promise<boolean> {\n const call = rpcCallOf(ctx)\n if (call === undefined) return false\n try {\n const connection = ctx.get('connection') as ConnectionFace | undefined\n if (connection?.isLoopback !== true) return false\n const result = await call(OPEN_CHANNEL, CAN_OPEN_ENDPOINT, { args: {} })\n const r = asRecord(result)\n return r !== null && r.ok === true && r.value === true\n } catch {\n return false\n }\n}\n\n/**\n * The system path opener over the session controller's open remote, or\n * undefined when the connection carries no RPC caller. Fire-and-forget:\n * rejections (unknown path, no desktop, offline) swallow — the affordance\n * is best-effort by nature.\n */\nexport function openPathVia(ctx: ClientCtx): ((path: string) => void) | undefined {\n const call = rpcCallOf(ctx)\n if (call === undefined) return undefined\n return (path: string): void => {\n try {\n // `args` is a plain object keyed by the remote's declared parameter\n // names (the gateway's wire contract — an array is rejected host-side).\n void call(OPEN_CHANNEL, OPEN_ENDPOINT, { args: { request: { path } } })\n .catch(() => { /* the open is best-effort; a failure stays silent */ })\n } catch { /* same contract, for a synchronously throwing transport */ }\n }\n}\n\n/**\n * The right Sidebar's resource opener over `ctx.sidebarRight`, or undefined\n * when this harness serves no such column (every line older than 0.1.5-rc.1) or\n * the face is hostile — the caller then keeps its system-open degradation.\n * Synchronous, and it reports whether the column took the address: `openResource`\n * throws for a no-type-claims address or with no session surface mounted, and an\n * unwired preview must fall back rather than become an inert click. The face is\n * re-proved at call time (the service can land or be revoked across an HMR\n * reload), so the returned closure reads it per open.\n */\nexport function openResourceVia(ctx: ClientCtx): ((address: string) => boolean) | undefined {\n // The face is untrusted at the boundary, so the raw service is re-proved as a\n // record with a callable `openResource` (never trusted off the cast).\n const faceOf = (): SidebarResourceFace | undefined => {\n try {\n const face = asRecord(ctx.get('sidebarRight'))\n return face !== null && typeof face.openResource === 'function'\n ? face as unknown as SidebarResourceFace\n : undefined\n } catch {\n return undefined\n }\n }\n if (faceOf() === undefined) return undefined\n return (address: string): boolean => {\n const face = faceOf()\n if (face === undefined) return false\n try {\n face.openResource(address)\n return true\n } catch {\n // No preview type claims it, or no session surface is mounted: the caller\n // falls back instead of showing an inert affordance.\n return false\n }\n }\n}\n\n/**\n * Jump to one session — the harness's own session-selection verb (issue #90).\n * Every supported line selects through the view owner (`uiWorkspace`\n * .openSession, the sidebar row click's own verb); the sessions service's own\n * `open` is the retired spelling (still served through the 0.1.5 line, gone\n * since the 0.1.6 selection refactor) and stays as the degradation path for a\n * composition without the workspace module. Both faces are re-proved per call\n * (a service can land or be revoked across an HMR reload) and the verb is\n * invoked bound (the service instance reads its own state); a generation\n * serving neither, or a hostile face, swallows — the jump is best-effort by\n * nature.\n */\nexport function openSessionVia(ctx: ClientCtx, id: string): void {\n try {\n const workspace = asRecord(ctx.get('uiWorkspace'))\n const open = workspace?.openSession\n if (typeof open === 'function') {\n open.call(workspace, id)\n return\n }\n const sessions = asRecord(ctx.get('sessions'))\n const legacy = sessions?.open\n if (typeof legacy === 'function') legacy.call(sessions, id)\n } catch { /* absent or hostile face — the jump is best-effort */ }\n}\n\n/**\n * On-demand full content for one surface-node seq: resolves the joined\n * conversation node, `null` when the durable log does not hold the seq,\n * rejects on transport/RPC failure (the caller distinguishes the three).\n */\nexport type ContentFetcher = (seq: number) => Promise<ConversationNodeLike | null>\n\n/**\n * On-demand CONTENT for one `redlineHeaders` epoch seq: the fetched system\n * prompt and tool schemas (see historyPage.ts), `null` when the durable log\n * does not hold the epoch, rejects on transport/RPC failure (the caller\n * distinguishes the three).\n */\nexport type HeaderFetcher = (seq: number) => Promise<HeaderEpochContent | null>\n","/**\n * Targeted full-content fetch for the Context browser — the fallback that\n * replaces blind tail paging. When a surface node's seq is outside the\n * conversation window, ONE seq-anchored history read returns the page\n * containing that event: the host cuts pages on whole append-origin message\n * boundaries, so the newest group on the page covers `seq` whenever the\n * durable log still holds it. The read rides the harness gateway remotes\n * (`remote.session.page`, with the inclusive cut `throughSeq` pinned to the\n * target seq) and the raw events map into the same conversation-node shapes\n * the window join delivers (a thin display subset of dsh's own fold).\n * Fetched nodes cache per session — history is immutable, so a seq never\n * needs fetching twice.\n *\n * The remote face is resolved through the DECLARED inject\n * (`watchHistoryFaces`): this plugin's module inject lists only slots/\n * locale, and NONDECLARED reads of the traced service proxy throw \"cannot\n * get property … without inject\" and can take a view down. The injection\n * callback runs under a fiber that declares both `remote` and\n * `remote.session` (the dsh idiom), so the property path resolves there and\n * nowhere else; the resolved face is re-proved and a hostile read leaves\n * the slot unset instead of ever throwing.\n */\n\nimport { useSyncExternalStore } from 'react'\nimport type {\n ClientCtx, ContentFetcher, ConversationNodeLike, HeaderFetcher,\n HistoryEntryLike, SessionPageFace,\n} from './services'\nimport type { HeaderEpochContent } from '../shared/types'\n\n/** Narrow one served row to a validated durable event envelope, or null. */\nfunction eventOf(entry: unknown): { type: string; seq: number; data: Record<string, unknown> } | null {\n if (entry === null || typeof entry !== 'object') return null\n // History records wrap the envelope in an `event` field\n // (`{type:'event'|'chunks', event}`); a bare envelope passes too, so shape\n // drift degrades instead of breaking the page. Packed chunk-row records\n // flow through as unknown types and project to nothing downstream — only\n // final events matter here.\n const inner = (entry as HistoryEntryLike).event ?? entry\n if (typeof inner !== 'object') return null\n const e = inner as { type?: unknown; seq?: unknown; data?: unknown }\n if (typeof e.type !== 'string' || typeof e.seq !== 'number' || !Number.isFinite(e.seq)) return null\n const data = e.data !== null && typeof e.data === 'object' ? e.data as Record<string, unknown> : {}\n return { type: e.type, seq: e.seq, data }\n}\n\n/** All string texts of an event's message-content shape joined (compaction summaries). */\nfunction textOf(blocks: unknown): string | null {\n if (!Array.isArray(blocks)) return null\n let out = ''\n for (const b of blocks) {\n const text = b !== null && typeof b === 'object' ? (b as { type?: unknown; text?: unknown }).text : undefined\n if (typeof text === 'string') out += text\n }\n return out.trim() === '' ? null : out\n}\n\n/**\n * The system prompt's exact rendered text — every text block joined with NO\n * normalization: a whitespace-only prompt is still the prompt the model\n * received (the host prices it as text), so it must render rather than read\n * as absent. Null when the content carries no text block at all.\n */\nfunction systemTextOf(blocks: unknown): string | null {\n if (!Array.isArray(blocks)) return null\n let out = ''\n let seen = false\n for (const b of blocks) {\n const text = b !== null && typeof b === 'object' ? (b as { type?: unknown; text?: unknown }).text : undefined\n if (typeof text === 'string') {\n out += text\n seen = true\n }\n }\n return seen ? out : null\n}\n\n/**\n * One assistant content block → the snapshot block vocabulary the browser\n * already renders (`kind`: text/reasoning/image/tool-call); unmappable\n * blocks pass through raw and degrade to the generic JSON section.\n */\nfunction assistantBlockOf(block: unknown): Record<string, unknown> {\n const b = block !== null && typeof block === 'object' ? block as { type?: unknown; text?: unknown; attachment?: unknown; name?: unknown; arguments?: unknown } : null\n switch (b?.type) {\n case 'text': case 'reasoning':\n return { kind: b.type, ...(typeof b.text === 'string' ? { text: b.text } : {}) }\n case 'image':\n return { kind: 'image', ...(b.attachment !== undefined ? { attachment: b.attachment } : {}) }\n case 'tool-call':\n return {\n kind: 'tool-call',\n name: typeof b.name === 'string' ? b.name : '?',\n argsRaw: b.arguments,\n }\n default:\n return block !== null && typeof block === 'object' ? block as Record<string, unknown> : { value: block }\n }\n}\n\n/**\n * Map one history page into joined conversation nodes keyed by their event\n * seq — the display subset of the browser's join: user messages, assistant\n * blocks, tool results paired with their in-page call head, and compaction\n * checkpoints paired with their summary event. Everything else (headers,\n * boundaries, chunks, bare calls) projects to nothing.\n */\nexport function pageNodesOf(entries: readonly unknown[]): Map<number, ConversationNodeLike> {\n const nodes = new Map<number, ConversationNodeLike>()\n const calls = new Map<string, { name: string; argsRaw: string }>()\n const summaries = new Map<string, string>()\n for (const entry of entries) {\n const ev = eventOf(entry)\n if (ev === null) continue\n const { type, seq, data } = ev\n if (type === 'tool/call') {\n if (typeof data.callId === 'string') {\n calls.set(data.callId, {\n name: typeof data.name === 'string' ? data.name : '?',\n // The durable envelope stores arguments as a raw JSON string.\n argsRaw: typeof data.arguments === 'string' ? data.arguments : '',\n })\n }\n continue\n }\n if (type === 'compaction/summary') {\n if (typeof data.compactionId === 'string') {\n const summary = textOf(data.summary)\n if (summary !== null) summaries.set(data.compactionId, summary)\n }\n continue\n }\n if (type === 'user/message') {\n const source = data.source !== null && typeof data.source === 'object' ? data.source as Record<string, unknown> : null\n const compactionId = source !== null\n && source.kind === 'plugin' && typeof source.compactionId === 'string'\n ? source.compactionId\n : null\n if (compactionId !== null) {\n // A compaction checkpoint: the model-visible envelope never renders —\n // the marker shows its summary instead (null when the page cut left\n // the summary event outside).\n nodes.set(seq, { kind: 'compaction', seq, summary: summaries.get(compactionId) ?? null })\n continue\n }\n nodes.set(seq, {\n kind: 'user',\n seq,\n content: Array.isArray(data.content) ? data.content as readonly unknown[] : [],\n })\n continue\n }\n if (type === 'assistant/message') {\n const message = data.message !== null && typeof data.message === 'object' ? data.message as Record<string, unknown> : null\n const content = message !== null && Array.isArray(message.content) ? message.content : []\n nodes.set(seq, {\n kind: 'assistant',\n seq,\n blocks: (content as unknown[]).map(assistantBlockOf),\n })\n continue\n }\n if (type === 'tool/result') {\n const message = data.message !== null && typeof data.message === 'object' ? data.message as Record<string, unknown> : null\n const source = message?.source !== null && typeof message?.source === 'object' ? message.source as Record<string, unknown> : null\n const first = Array.isArray(message?.content) ? (message.content as unknown[])[0] : undefined\n const block = first !== null && typeof first === 'object' ? first as Record<string, unknown> : null\n const callId = typeof source?.callId === 'string' ? source.callId\n : typeof block?.toolCallId === 'string' ? block.toolCallId\n : null\n const call = callId !== null ? calls.get(callId) ?? null : null\n nodes.set(seq, {\n kind: 'tool-result',\n seq,\n call,\n content: block !== null && Array.isArray(block.content) ? block.content as readonly unknown[] : [],\n isError: block?.isError === true || data.error === true,\n })\n continue\n }\n }\n return nodes\n}\n\n/** The `page` verb of a history face, re-proved and bound to its owner.\n * Hostile objects (any accessor backed by host state can throw) degrade to\n * undefined instead of escaping the read. */\nfunction readPageOf(face: unknown): SessionPageFace['page'] | undefined {\n if (face === null || typeof face !== 'object') return undefined\n try {\n const fn = (face as Record<string, unknown>).page\n return typeof fn === 'function' ? (fn as SessionPageFace['page']).bind(face) : undefined\n } catch {\n return undefined\n }\n}\n\n/**\n * The gateway history page verb, resolved through the DECLARED inject\n * (see {@link watchHistoryFaces}) and bound up front: a method extracted\n * unbound loses `this`, and the traced `remote` proxy that hands it out\n * requires the inject to resolve at all.\n */\nlet declaredPage: SessionPageFace['page'] | undefined\n\nconst faceListeners = new Set<() => void>()\n\nfunction setPageFace(page: SessionPageFace['page'] | undefined): void {\n declaredPage = page\n for (const listener of [...faceListeners]) listener()\n}\n\n/** The page face resolved so far, for non-React readers (the fetcher builders). */\nexport function historyFace(): SessionPageFace['page'] | undefined {\n return declaredPage\n}\n\n/** Subscribe to face resolution and revocation (plugin reload/HMR). */\nexport function subscribeHistoryFace(listener: () => void): () => void {\n faceListeners.add(listener)\n return () => { faceListeners.delete(listener) }\n}\n\n/** The store snapshot both useSyncExternalStore seats read (client and hydration). */\nfunction faceSnapshot(): SessionPageFace['page'] | undefined {\n return declaredPage\n}\n\n/**\n * The React seat over the resolved page face. A mount can RACE the declared\n * inject — a watch rebuild (patchReload) remounts the slot components before\n * the injected fiber re-fires — so the first render may legitimately see no\n * face. Subscribing keeps that transient state from sticking: the fetchers\n * derived downstream rebuild when the face lands (or is revoked), instead of\n * degrading to the static note for the mount's whole lifetime.\n */\nexport function useHistoryFace(): SessionPageFace['page'] | undefined {\n return useSyncExternalStore(subscribeHistoryFace, faceSnapshot, faceSnapshot)\n}\n\n/**\n * Register the plugin's history face with the harness through the DECLARED\n * inject — both `remote` AND `remote.session` (the ui-chat idiom) must be in\n * one fiber's requirement list, because the traced `remote` proxy resolves\n * `.session` through the context and each name needs the other's\n * declaration; an undeclared read of the traced proxy throws instead of\n * resolving. The callback re-runs on every unload/remount, so it owns the\n * slot's lifetime. The face itself is re-proven: a never-fired invocation\n * or a hostile property read leaves the slot unset — nothing here can throw.\n */\nexport function watchHistoryFaces(ctx: ClientCtx): void {\n ctx.inject(['remote', 'remote.session'], (c) => {\n try {\n const session = (c as ClientCtx & { remote?: { session?: SessionPageFace } }).remote?.session\n setPageFace(session !== undefined ? readPageOf(session) : undefined)\n } catch {\n setPageFace(undefined)\n }\n return () => { setPageFace(undefined) }\n })\n}\n\n/** The rows array of a successful history page, under the served envelope. */\nfunction rowsOf(response: unknown): readonly unknown[] {\n // Envelope unwrapping: the remote resolves to the ClientResult itself\n // ({ok, value}). A bare {records} payload passes too. Anything else\n // rejects so the caller can offer a retry instead of claiming absence.\n let payload: unknown = response\n if (payload !== null && typeof payload === 'object' && 'ok' in payload) {\n const r = payload as { ok?: unknown; value?: unknown }\n if (r.ok !== true || r.value === null || typeof r.value !== 'object') {\n throw new Error('history rpc failed')\n }\n payload = r.value\n }\n if (payload === null || typeof payload !== 'object') throw new Error('history rpc failed')\n const rows = (payload as { records?: unknown }).records\n if (!Array.isArray(rows)) throw new Error('history rpc failed')\n return rows\n}\n\n/**\n * The session's history reader over the gateway remotes (`remote.session.page`),\n * from the declared-inject slot. The page cuts message-aligned pages, so the\n * returned read covers `seq` whenever the durable log still holds it: the\n * inclusive cut is pinned to the seq itself, the exclusive bound one past\n * it. Undefined when the slot holds no face (the inject never fired or\n * served no usable page verb) — callers keep their static degradation.\n */\nfunction pageReaderOf(sessionId: string): ((seq: number) => Promise<unknown>) | undefined {\n // The face resolved at build time: absent face = the caller's static\n // degradation, a resolved face stays bound for the fetcher's lifetime.\n const page = declaredPage\n if (page === undefined) return undefined\n return (seq) => {\n // The inclusive log cut pinned to the target seq, the exclusive bound\n // one past it.\n return page({\n address: { kind: 'session' as const, sessionId },\n throughSeq: seq,\n beforeSeq: seq + 1,\n }, new AbortController().signal)\n }\n}\n\n/**\n * Build the browser's per-session fetcher over the gateway history face\n * (`remote.session.page`): message-aligned pages whose inclusive cut pinned\n * to `seq` (exclusive bound one past it) cover the seq whenever the durable\n * log still holds it. Undefined when no face was resolved at build time —\n * the caller keeps its static preview-plus-hint degradation. Found nodes\n * cache in the closure: one mount re-reading a row never re-fetches.\n */\nexport function makeContentFetcher(sessionId: string): ContentFetcher | undefined {\n const read = pageReaderOf(sessionId)\n if (read === undefined) return undefined\n // Fetched nodes cache in the closure: history is immutable, so one mount\n // re-reading a row never re-fetches.\n const cache = new Map<number, ConversationNodeLike>()\n return async (seq) => {\n const hit = cache.get(seq)\n if (hit !== undefined) return hit\n // The whole envelope is re-proven (no-white-screen guarantee): a failed or\n // malformed read rejects so the browser offers a retry instead of guessing.\n const node = pageNodesOf(rowsOf(await read(seq))).get(seq) ?? null\n if (node !== null) cache.set(seq, node)\n return node\n }\n}\n\n/**\n * Map one raw durable event into the epoch content the browser renders. A\n * `request/header` yields each tool's producer description and raw schema; a\n * `system/message` yields the prompt text alone (its tools live in the\n * request header). Both mirror the host fold's per-entry guards — a null or\n * primitive tool entry degrades to an unnamed row instead of throwing the\n * read. Null when the event carries neither.\n */\nfunction headerContentOf(event: { type: string; data: Record<string, unknown> }): HeaderEpochContent | null {\n const { type, data } = event\n if (type === 'system/message') {\n const message = data.message !== null && typeof data.message === 'object'\n ? data.message as Record<string, unknown>\n : null\n const system = systemTextOf(message?.content)\n return system === null ? null : { system, tools: [] }\n }\n const rawHeader = data.header !== null && typeof data.header === 'object'\n ? data.header as Record<string, unknown>\n : null\n if (rawHeader === null) return null\n const toolsRaw = Array.isArray(rawHeader.tools) ? rawHeader.tools : []\n const tools: HeaderEpochContent['tools'] = []\n for (const t of toolsRaw) {\n const tool = t !== null && typeof t === 'object' ? t as Record<string, unknown> : null\n tools.push({\n name: tool !== null && typeof tool.name === 'string' ? tool.name : '?',\n ...(tool !== null && typeof tool.description === 'string' && tool.description !== ''\n ? { description: tool.description }\n : {}),\n schema: t,\n })\n }\n return { tools }\n}\n\n/**\n * The on-demand CONTENT fetch for the browser's System and Tools sections —\n * the lazy counterpart of the node fetcher above. One seq-anchored history\n * read off the requested seq returns the page holding that event (non-message\n * events ride the page verbatim); a `request/header` maps to the epoch's\n * tools, a `system/message` to the prompt's text. Landed content caches per\n * seq (history is immutable), and OLDER\n * epochs sharing the page cache for free — stepping back through epochs walks\n * the same pages. Undefined when no history face exists — the browser keeps a\n * metadata-only degradation instead.\n */\nexport function makeHeaderFetcher(sessionId: string): HeaderFetcher | undefined {\n const read = pageReaderOf(sessionId)\n if (read === undefined) return undefined\n const cache = new Map<number, HeaderEpochContent>()\n return async (seq) => {\n const hit = cache.get(seq)\n if (hit !== undefined) return hit\n // Same re-prove contract as the node fetcher: a failed or malformed read\n // rejects so the browser offers a retry instead of guessing.\n const rows = rowsOf(await read(seq))\n let picked: HeaderEpochContent | null = null\n for (const entry of rows) {\n const ev = eventOf(entry)\n if (ev === null || (ev.type !== 'request/header' && ev.type !== 'system/message')) continue\n const content = headerContentOf(ev)\n if (content === null) continue\n // The page's exclusive bound is seq + 1, so every content event on it\n // is the picked one or an OLDER one — cache them all.\n cache.set(ev.seq, content)\n if (ev.seq === seq) picked = content\n }\n return picked\n }\n}\n","/**\n * The 上下文批改 RPC surface shared by BOTH halves — the single source of truth\n * for the route path, request/response envelope, and operation vocabulary.\n * This is the only place allowed to spell the path: duplicating it risks a\n * silent Client/Host drift into 404s.\n *\n * Namespacing is a HARD constraint, not a preference: the connection registry\n * THROWS on a duplicate exact path (`exact Fetch route \"…\" is already\n * registered`), and the panel coexists with `dsh-context@0.60.0`, which owns\n * `/api/dsh-context/*` (`docs/01` F1, `UPSTREAM.md` §3.1 row 1).\n */\n\n/** Our authenticated `/api` prefix. Everything below hangs off it. */\nexport const REDLINE_API_PREFIX = '/api/dsh-context-redline'\n\n/**\n * The edit-surface channel: ONE endpoint with an `op` discriminator\n * (`docs/02` §5.2), so adding an op never adds a route.\n */\nexport const REDLINE_CHANNEL_ROUTE = `${REDLINE_API_PREFIX}/redline`\n\n/** Upstream's on-demand timeline detail route, renamed (M1-04). */\nexport const REDLINE_DETAIL_ROUTE = `${REDLINE_API_PREFIX}/detail`\n\n/** Upstream's platform-balance route, renamed (M1-04). */\nexport const REDLINE_BALANCE_ROUTE = `${REDLINE_API_PREFIX}/balance`\n\n/** Upstream's cold-history warm-up route, renamed (M1-04). */\nexport const REDLINE_BACKFILL_ROUTE = `${REDLINE_API_PREFIX}/backfill`\n\n/** Every route this plugin registers, for the namespace contract and tests. */\nexport const REDLINE_ROUTES: readonly string[] = [\n REDLINE_CHANNEL_ROUTE,\n REDLINE_DETAIL_ROUTE,\n REDLINE_BALANCE_ROUTE,\n REDLINE_BACKFILL_ROUTE,\n]\n\n/** Success envelope (`docs/02` §5.1). */\nexport interface RedlineOk<T> {\n readonly ok: true\n readonly value: T\n}\n\n/** Failure envelope: a STABLE machine code plus a short wire message. */\nexport interface RedlineFailure {\n readonly ok: false\n readonly error: {\n /** One of `REDLINE_ERROR` (`src/shared/redline-errors.ts`). */\n readonly code: string\n /** Short English wire text. The user-facing wording is the client's i18n. */\n readonly message: string\n }\n}\n\nexport type RedlineEnvelope<T> = RedlineOk<T> | RedlineFailure\n\n/**\n * One call on the channel. `op` is the discriminator; every other field is\n * op-specific. The vocabulary itself is declared with its handlers in\n * `src/host/redline-channel.ts` (M2 fills the table).\n */\nexport interface RedlineCall {\n readonly op: string\n readonly sessionId?: string\n readonly [field: string]: unknown\n}\n\n/** The success half of the envelope. */\nexport function redlineOk<T>(value: T): RedlineOk<T> {\n return { ok: true, value }\n}\n\n/** The failure half of the envelope. */\nexport function redlineFailure(code: string, message: string): RedlineFailure {\n return { ok: false, error: { code, message } }\n}\n\n/**\n * Narrow an untrusted JSON body to a {@link RedlineCall}. Returns null for\n * anything that is not an object with a non-empty string `op`.\n */\nexport function asRedlineCall(body: unknown): RedlineCall | null {\n if (body === null || typeof body !== 'object' || Array.isArray(body)) return null\n const op = (body as { op?: unknown }).op\n if (typeof op !== 'string' || op === '') return null\n return body as RedlineCall\n}\n","/**\n * The timeline source behind the Context tab and the /redline modal —\n * reconciles the two `redlineTimeline` wire generations into the single\n * value the cards have always rendered.\n *\n * Generations (the marker is `detailRev` on the delivered value):\n * - INLINE (older hosts, channel-less deployments, the baseline-gate\n * fallback): the wire value carries the collections in place. It passes\n * through untouched — no fetch ever happens.\n * - SPLIT (current host with the detail route live): the wire value is the\n * slim head (~1KB — every session.list row, control baseline, and push\n * frame carries it whole). The collections arrive from the plugin's\n * `/api/dsh-context-redline/detail` fetch route (host/detail.ts): one targeted read\n * when the tab/modal first opens, then a debounced refetch whenever the\n * pushed `detailRev` outruns the served detail. Closed tabs fetch nothing.\n *\n * The no-stale-content guarantees: the store is per session and shared by\n * the tab and the modal; a refetch is single-flight with a trailing edge\n * (a rev bumped mid-flight re-reads after settle); responses race-safe by\n * revision (latest wins, with the refold exception — a host that refolded\n * restarts the revision, and a response matching the requested rev is\n * accepted regardless of order); a transport failure keeps the last good\n * detail and backs off; an absent answer (the session left the live set)\n * stops the trailing until the head moves again. With no detail at all,\n * failure surfaces as a retryable note on the detail cards instead of an\n * empty chart.\n */\n\nimport { useEffect, useMemo, useSyncExternalStore } from 'react'\nimport type { ContextTimeline, ContextTimelineDetail } from '../shared/types'\nimport type { ClientCtx, SessionStandardProps } from './services'\nimport { asRecord, numOf, objectsOf, projectionOf, timelineOf } from './services'\nimport { REDLINE_DETAIL_ROUTE } from '../shared/redline-route'\n\n// The detail route of host/detail.ts — re-declared here: the client bundle\n// inlines every import, and the host module must never reach it. Same-origin\n// POST under the harness's authenticated `/api` fence.\nconst DETAIL_ROUTE = REDLINE_DETAIL_ROUTE\n\n/**\n * Narrow the detail endpoint's payload to a render-safe value (the same\n * boundary rigor as `timelineOf`): collections re-proved per item, scalars\n * zeroed, a missing/NaN revision rejects the whole payload (the caller then\n * shows the retryable failure note instead of half-merged data).\n */\nexport function detailOf(value: unknown): ContextTimelineDetail | null {\n const data = asRecord(value)\n if (data === null) return null\n if (typeof data.rev !== 'number' || !Number.isFinite(data.rev) || data.rev < 0) return null\n // The slim head rides the payload for the Agent network's cold-node ring\n // fetch; a missing or malformed head only degrades that composition (the\n // detail cards never read it), so it drops out instead of rejecting the\n // payload the cards consume.\n const head = timelineOf(data.head)\n return {\n rev: data.rev,\n ...(head !== null ? { head } : {}),\n requests: objectsOf(data.requests),\n events: objectsOf(data.events),\n nodes: objectsOf(data.nodes),\n droppedNodes: numOf(data.droppedNodes),\n archive: objectsOf(data.archive),\n ...(typeof data.surfaceFloor === 'number' ? { surfaceFloor: data.surfaceFloor } : {}),\n ...(typeof data.archiveFloor === 'number' ? { archiveFloor: data.archiveFloor } : {}),\n ...(data.fileOps !== undefined ? { fileOps: objectsOf(data.fileOps) } : {}),\n ...(typeof data.fileOpsFloor === 'number' ? { fileOpsFloor: data.fileOpsFloor } : {}),\n }\n}\n\n/**\n * The detail reader over the plugin's own `/api` fetch route (host/detail.ts).\n * Same-origin POST through the harness's authenticated fence; the returned\n * thunk resolves the session's current detail, `null` when the session is not\n * live anymore, and rejects on transport failure or a malformed payload (the\n * store turns the two into the retryable state).\n */\nexport function makeDetailFetcher(\n ctx: ClientCtx,\n sessionId: string,\n): (() => Promise<ContextTimelineDetail | null>) | undefined {\n void ctx\n if (sessionId === '') return undefined\n return async () => {\n const response = await fetch(DETAIL_ROUTE, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ sessionId }),\n })\n if (!response.ok) throw new Error(`dsh-context-redline: detail route HTTP ${response.status}`)\n const r = asRecord(await response.json())\n if (r === null || r.ok !== true) throw new Error('dsh-context-redline: detail read failed')\n if (r.value === null) return null\n const detail = detailOf(r.value)\n if (detail === null) throw new Error('dsh-context-redline: detail read malformed')\n return detail\n }\n}\n\n/** The store's observable snapshot, rebuilt on every transition (identity-gated for useSyncExternalStore). */\nexport interface DetailSnap {\n /** The newest accepted detail (kept while a refetch is in flight — the cards never flicker back to loading). */\n detail: ContextTimelineDetail | null\n /** The last read settled without data (transport failure or absence) and there is no detail to show. */\n failed: boolean\n /** A read is scheduled or in flight. */\n pending: boolean\n}\n\nconst EMPTY_SNAP: DetailSnap = { detail: null, failed: false, pending: false }\n\n/** The fetch debounce base; each consecutive failure doubles the wait, capped at 3 doublings. */\nconst DETAIL_DEBOUNCE_MS = 300\n\n/**\n * One session's detail ledger. Exported for tests (a zero debounce makes the\n * machine synchronous-ish); the app reaches it through `detailStoreOf`.\n */\nexport class DetailStore {\n private detail: ContextTimelineDetail | null = null\n /** The revision of `detail` (latest-wins cursor); -1 before the first landing. */\n private acceptedRev = -1\n /** The newest revision the head has asked for. */\n private wantedRev = -1\n /** The head rev the IN-FLIGHT (or scheduled) read targets — the refold exception's acceptance key. */\n private targetRev = -1\n /** The head rev seen last — a DECREASE means the host refolded (revisions restart). */\n private lastHeadRev = -1\n private failed = false\n private inFlight = false\n private timer: ReturnType<typeof setTimeout> | null = null\n private failures = 0\n private readonly listeners = new Set<() => void>()\n private snap: DetailSnap = EMPTY_SNAP\n\n constructor(\n private readonly fetcher: (() => Promise<ContextTimelineDetail | null>) | undefined,\n private readonly baseDelay: number = DETAIL_DEBOUNCE_MS,\n ) {}\n\n readonly subscribe = (fn: () => void): (() => void) => {\n this.listeners.add(fn)\n return () => this.listeners.delete(fn)\n }\n\n readonly getSnapshot = (): DetailSnap => this.snap\n\n /**\n * The head's current revision arrived: schedule the trailing-edge read\n * when it outruns the served detail. A rev DECREASE means the host\n * refolded the session (a discarded checkpoint, a restart): revisions are\n * no longer comparable, so the ledger resets and refetches.\n */\n request(rev: number): void {\n if (rev < this.lastHeadRev) {\n this.acceptedRev = -1\n this.wantedRev = -1\n this.detail = null\n this.failed = false\n }\n this.lastHeadRev = rev\n if (rev <= this.acceptedRev || rev <= this.wantedRev) return\n this.wantedRev = rev\n this.schedule()\n }\n\n /** Re-arm after a failure (the cards' retry note): immediate, backoff reset. */\n readonly retry = (): void => {\n this.failures = 0\n if (this.detail !== null) return\n if (this.timer !== null) {\n clearTimeout(this.timer)\n this.timer = null\n }\n if (!this.inFlight) void this.fire()\n }\n\n private schedule(): void {\n if (this.timer !== null) return\n this.timer = setTimeout(() => {\n this.timer = null\n void this.fire()\n }, this.baseDelay * 2 ** Math.min(this.failures, 3))\n this.emit()\n }\n\n private async fire(): Promise<void> {\n // A trailing timer fired while an earlier read is still in flight — that\n // read's settle re-arms when the wanted rev still outruns the served one.\n if (this.inFlight) return\n if (this.fetcher === undefined) {\n // No session id to read for: the typed failure arms the cards' note.\n // (The slim head is only served when the host route went live, so this\n // is the exotic path.)\n this.failed = true\n this.emit()\n return\n }\n this.inFlight = true\n this.targetRev = this.wantedRev\n this.emit()\n try {\n const d = await this.fetcher()\n if (d !== null) {\n // Latest-wins, with the refold exception: a response matching the\n // requested rev is the current truth even when its number trails a\n // pre-refold landing.\n if (d.rev >= this.acceptedRev || d.rev === this.targetRev) {\n this.detail = d\n this.acceptedRev = d.rev\n }\n this.failures = 0\n this.failed = false\n } else {\n // Absent (the session left the live set): keep the last detail, stop\n // the trailing until the head moves again (a disposed session's rev\n // never does), and arm the note only when nothing is showable.\n this.wantedRev = this.acceptedRev\n this.failed = this.detail === null\n this.failures++\n }\n } catch {\n this.failed = this.detail === null\n this.failures++\n }\n this.inFlight = false\n // The head moved while the read settled (or an earlier read lost the\n // race): trail once more, debounced.\n if (this.wantedRev > this.acceptedRev) this.schedule()\n this.emit()\n }\n\n private emit(): void {\n const pending = this.timer !== null || this.inFlight\n const next: DetailSnap = { detail: this.detail, failed: this.failed, pending }\n if (next.detail === this.snap.detail && next.failed === this.snap.failed && next.pending === this.snap.pending) return\n this.snap = next\n for (const fn of this.listeners) fn()\n }\n}\n\n/** Page-lifetime per-session stores (the tab and the modal share one). */\nconst stores = new Map<string, DetailStore>()\n\nexport function detailStoreOf(ctx: ClientCtx, sessionId: string): DetailStore {\n let store = stores.get(sessionId)\n if (store === undefined) {\n store = new DetailStore(makeDetailFetcher(ctx, sessionId))\n stores.set(sessionId, store)\n }\n return store\n}\n\n/** Test isolation: drop every cached store. */\nexport function resetTimelineDetailStores(): void {\n stores.clear()\n}\n\nexport type DetailState = 'legacy' | 'loading' | 'ready' | 'failed'\n\nexport interface TimelineSource {\n /**\n * The value the cards render — the inline generation's value untouched, or\n * the slim head merged with the fetched detail collections (empty while\n * the first read is in flight; `detailState` names that).\n */\n data: ContextTimeline | null\n detailState: DetailState\n retryDetail: () => void\n}\n\nconst noopSubscribe = (): (() => void) => () => {}\nconst noopRetry = (): void => {}\n\n/**\n * The view's one read of the timeline (see the module header for the\n * generation rules). Hook-order safe: every hook runs unconditionally, the\n * branches below only shape the returned record.\n */\nexport function useTimelineSource(ctx: ClientCtx, props: SessionStandardProps): TimelineSource {\n const head = projectionOf(props, 'redlineTimeline', timelineOf)\n const sessionId = typeof props.sessionId === 'string' ? props.sessionId : ''\n // The split marker: the slim head carries the detail revision; anything\n // else (the inline value, the gate fallback, a corrupt payload) is the\n // inline generation — `headRev` null means no detail channel work at all.\n const headRev = head !== null && typeof head.detailRev === 'number' ? head.detailRev : null\n const slim = headRev !== null\n const store = useMemo(\n () => (slim ? detailStoreOf(ctx, sessionId) : null),\n [ctx, sessionId, slim],\n )\n const snap = useSyncExternalStore(\n store !== null ? store.subscribe : noopSubscribe,\n store !== null ? store.getSnapshot : () => EMPTY_SNAP,\n )\n useEffect(() => {\n if (store !== null && headRev !== null) store.request(headRev)\n }, [store, headRev])\n\n return useMemo<TimelineSource>(() => {\n if (head === null) return { data: null, detailState: 'loading', retryDetail: noopRetry }\n if (!slim || store === null) return { data: head, detailState: 'legacy', retryDetail: noopRetry }\n const detail = snap.detail\n const data: ContextTimeline = detail === null\n ? head\n : {\n ...head,\n requests: detail.requests,\n events: detail.events,\n nodes: detail.nodes,\n droppedNodes: detail.droppedNodes,\n archive: detail.archive,\n // Slim heads serve no floors; the detail's pair lands whole here.\n ...(detail.surfaceFloor !== undefined ? { surfaceFloor: detail.surfaceFloor } : {}),\n ...(detail.archiveFloor !== undefined ? { archiveFloor: detail.archiveFloor } : {}),\n ...(detail.fileOps !== undefined ? { fileOps: detail.fileOps } : {}),\n ...(detail.fileOpsFloor !== undefined ? { fileOpsFloor: detail.fileOpsFloor } : {}),\n }\n const detailState: DetailState = detail !== null ? 'ready' : snap.failed ? 'failed' : 'loading'\n return { data, detailState, retryDetail: store.retry }\n }, [head, slim, store, snap])\n}\n","/**\n * Shared wire contract — the snapshot model exchanged between the Host and Client halves. Delivered as the `view()` payload of the\n * `redlineTimeline`/`redlineHeaders` session projections (registered on `ctx.sessionProjections`; the registry pushes finished views as\n * `session/projection` frames — see host/timeline.ts). TYPE-ONLY host-side module: both halves import these as `import type`, so nothing\n * from here ever reaches the runtime bundles.\n */\n\nimport type { ActivityState } from '../host/activity'\nimport type { HeadersState } from '../host/headers'\nimport type { TimelineState } from '../host/fold'\n// The registry package ROOT carries the `@deepseek-ai/cordis` Context\n// augmentation (`sessionProjections` service); the `/types` subpath below\n// only declares the merge-extensible maps.\nimport type {} from '@deepseek-ai/dsh-session-projection'\nimport type {} from '@deepseek-ai/dsh-session-projection/types'\n\ndeclare module '@deepseek-ai/dsh-session-projection/types' {\n // Both maps take the plugin keys: `SessionProjectionMap` names the\n // client-visible wire values, `SessionProjectionStateMap` constrains the\n // unit `key`s and their fold-state types (the split arrived with\n // dsh 0.1.1 — the definition's K constraint moved to the state map).\n interface SessionProjectionMap {\n /**\n * The plugin's context timeline: current composition, counters, and the\n * headline anchor. Since the split generation the wire value is the SLIM\n * head (every delivery channel — session.list rows, control baselines,\n * push frames — carries it whole); the per-request history, context\n * events, and the surface/archive collections ride the on-demand detail\n * channel ({@link ContextTimelineDetail}, host/detail.ts). Channel-less\n * hosts keep the inline generation (the collections stay in the value).\n * Key absence = the plugin's host half is not composed.\n */\n redlineTimeline: ContextTimeline\n /**\n * The request-header CONTENT epochs (full system prompt + tool schemas)\n * behind the timeline's envelope figures. A separate unit so the hot\n * `redlineTimeline` value stays lean: headers change rarely, so this\n * value (and its pushes) change only when a `request/header` lands.\n * The Context browser card reads it to show the actual prompt/schema\n * content of a picked step (key absence = older host: tokens only).\n */\n redlineHeaders: ContextHeaders\n /**\n * The per-day activity ledger (billed tokens + completed requests keyed\n * by local day) behind the Context Dashboard's heatmap — the timeline's\n * \"current snapshot\" cannot draw a per-day chart, so the overview reads\n * this off every session-list row's projection column. Tiny (one small\n * record per day, retention-capped), so riding every list row costs\n * nothing next to the timeline head. Key absence = older host: the\n * heatmap degrades to its empty note.\n */\n redlineActivity: ContextActivity\n }\n interface SessionProjectionStateMap {\n redlineTimeline: TimelineState\n redlineHeaders: HeadersState\n redlineActivity: ActivityState\n }\n}\n\n/**\n * The priced surface buckets. `skill` carries every skill-machinery content\n * the harness injects (issue #66): the `<available_skills>` catalog digest,\n * a user-explicit `/name` invocation's instructions message, and the content\n * a `skill`-tool load returns (modeled as a tool result by the harness).\n */\nexport type Category = 'user' | 'inject' | 'skill' | 'assistant' | 'tool'\n\n/**\n * One live system-prompt node (Snapshot.systems) — the harness models the\n * system prompt as a surface node, so its TEXT is fetched on demand from the\n * `system/message` event at `seq`. `tokens` is the node's heuristic\n * price (0 for a dormant empty node, which the harness reads as \"no system\n * prompt\"); the effective figure is the LAST node with `tokens > 0`.\n */\nexport interface SystemPromptNode {\n seq: number\n time: number\n tokens: number\n}\n\n/**\n * The stats board's count figures, precomputed host-side over the RETAINED\n * request/event records (the same set the detail payload serves). Carried by\n * the split-generation wire head so the board — and the Agent card's\n * per-session request tally — never need the collections themselves.\n * `steps` doubles as the retained request-record count.\n */\nexport interface TimelineCounts {\n turns: number\n steps: number\n injects: number\n compactions: number\n prunes: number\n}\n\n/**\n * The newest retained request record's billing summary — the headline's\n * derived-occupancy anchor (`prompt + surface movement since`), carried by\n * the split-generation wire head so the headline never needs the request\n * records themselves.\n */\nexport interface TimelineLast {\n seq: number\n total: number\n prompt?: number\n}\n\n/** One day's ledger entry in the `redlineActivity` projection. */\nexport interface ActivityDay {\n /**\n * Billed tokens folded from provider-reported usage that day (prompt-side\n * input + cache read/write + output). Requests without a usage settlement\n * count only toward `requests` — a fabricated 0 never understates the day.\n */\n tokens: number\n /** Completed model calls (assistant settlements) that day. */\n requests: number\n /**\n * The day's billed buckets keyed provider → model → pricing period — the\n * same SessionCostUsage raw material the timeline's session-cost totals\n * carry, scoped to the day the requests INITIATED in, so the client prices\n * each day off the same model-price book as the KPI band. ADDITIVE-OPTIONAL:\n * absent on rows folded before the field existed (older plugin builds), on\n * days whose settlements predate any model header, and on settlements the\n * provider left unmetered — the usage chart degrades to tokens-only bars.\n */\n cost?: SessionCostUsage\n}\n\n/**\n * The per-session daily activity ledger (`redlineActivity` wire value):\n * day key (`YYYY-MM-DD`, host-local — see shared/days.ts) → that day's\n * billed volume, retention-capped by the fold. The Context Dashboard merges\n * every listed session's ledger into its activity heatmap.\n */\nexport interface ContextActivity {\n days: Record<string, ActivityDay>\n}\n\n/**\n * The per-user display-preference vocabulary of the `dsh-context-redline` settings\n * namespace — the ONE declaration both halves share: the Host registers the\n * namespace schema against it (host/settings.ts), the Client binds the scope\n * and edits fields by name (client/settings.ts). Type-only, so both bundles\n * erase it.\n */\nexport type DefaultGranularity = 'step' | 'turn'\n\nexport type DefaultTrendMode = 'total' | 'delta'\n\n/** File Activity row order: most operations first, most-recently-touched first, or path ascending. */\nexport type DefaultFileSort = 'count' | 'latest' | 'path'\n\n/** Tool-definition row order: largest schema first, most call hits first, or name ascending. */\nexport type DefaultToolSort = 'size' | 'count' | 'name'\n\n/** Where the Context view is offered: the conversation tab, the right Sidebar, or both. */\nexport type DefaultPlacement = 'all' | 'tab' | 'sidebar'\n\n/** Whether the Context Insights panel's sidebar entry is offered at all. */\n\nexport interface PluginSettings {\n defaultPlacement: DefaultPlacement\n defaultGranularity: DefaultGranularity\n defaultTrendMode: DefaultTrendMode\n defaultToolSort: DefaultToolSort\n defaultFileSort: DefaultFileSort\n}\n\n/** The section fields the settings card edits, as the Host schema names them. */\nexport type SettingsField = keyof PluginSettings\n\nexport interface Snapshot {\n ok: boolean\n /**\n * The host's baseline-gate record, present ONLY when the running harness\n * is below the plugin's supported baseline: the host then folds nothing\n * and every figure in this snapshot is zero/empty. The client keeps\n * rendering the (blank) cards and pops the upgrade gate modal naming\n * `current` (the detected harness version) and `minimum` (the baseline).\n */\n unsupported?: {\n current: string\n minimum: string\n }\n model?: string\n provider?: string\n contextWindow?: number\n current: {\n system: number\n tools: number\n user: number\n inject: number\n skill: number\n assistant: number\n tool: number\n total: number\n }\n /**\n * Image blocks live in the CURRENT context (user uploads plus tool-result\n * images, nested blocks included) — the sum over the live surface nodes'\n * `imgs`, so compaction/prune shrink it. Absent from older hosts; clients\n * treat absence as zero.\n */\n images?: number\n /**\n * Tool calls whose result is live in the CURRENT context (one `tool/result`\n * folds to one `tool` surface node). Calls still in flight and results\n * compacted/pruned out of the surface are not counted. Absent from older\n * hosts; clients treat absence as zero.\n */\n toolCalls?: number\n /**\n * Whole-session human-input tally: every non-injection `user/message`\n * (the user's own messages) plus every answered `ask_user_question`\n * result (one per answer submission). A running total over the COMPLETE\n * log — turns the retained window no longer holds still count. Absent\n * from older hosts; clients treat absence as zero.\n */\n humanInputs?: number\n /**\n * The user's newest own message as a one-line bounded preview (first text\n * block, whitespace collapsed, ~80 chars): the session cards' footer line.\n * Additive-optional — absent from rows folded before the field existed\n * (older hosts, idle sessions' cached rows); clients hide the line then.\n */\n lastUser?: string\n /**\n * Split-generation head fields — present exactly when the host serves the\n * SLIM head (the heavy collections moved to the on-demand detail channel,\n * host/detail.ts) and absent on the inline generation (older or\n * channel-less hosts serve the collections in place). `detailRev` is the\n * detail's revision marker: it bumps whenever the detail collections\n * change, so an open tab refetches on the push alone.\n */\n counts?: TimelineCounts\n last?: TimelineLast\n detailRev?: number\n /**\n * The per-request history / context-event collections. On the split\n * generation these stay ABSENT from the wire value (every session.list row,\n * control baseline, and push frame would carry them whole otherwise); the\n * client fills them from the detail channel ({@link ContextTimelineDetail}).\n */\n requests: RequestRecord[]\n events: ContextEventRecord[]\n /**\n * Cumulative session-cost raw material (per-provider, per-model billed\n * token totals — see SessionCostUsage). Absent until a request with a\n * known model reports usage.\n */\n cost?: SessionCostUsage\n /**\n * Whole-session timing totals (see TimingTotals). Absent until the first\n * step lifecycle completes in the log (older plugin builds never folded\n * one — clients treat absence as an empty timing card).\n */\n timing?: TimingTotals\n /**\n * The live system-prompt nodes, oldest first — the browser's per-step source\n * for the System section. Absent on rows folded before this field existed\n * (older plugin builds; the client then falls back to the header epoch's\n * own `systemTokens`, the legacy wire shape those builds served).\n */\n systems?: SystemPromptNode[]\n /**\n * The served live surface: the newest `maxNodes` tail PLUS every live inject node older than the tail (injections land first and are\n * few,\n * so they are pinned). Seq-ordered, oldest first.\n */\n nodes: SurfaceNode[]\n /** Live nodes not served (the overflow beyond `maxNodes`, minus pinned injects — see `nodes`). */\n droppedNodes: number\n /**\n * Recently REMOVED surface nodes (compaction/prune shadows), each stamped\n * with `gone` (the replacing event's seq). Together with `nodes` this lets\n * the Context browser reconstruct the assembled surface of any retained\n * step: alive at request R = seq < R.seq && (gone undefined || gone > R.seq).\n */\n archive: SurfaceNode[]\n /**\n * Coverage floor of the served live `nodes`: the newest seq among the\n * `droppedNodes` live nodes not served. Present only when droppedNodes > 0.\n */\n surfaceFloor?: number\n /**\n * Coverage floor of `archive`: the newest `gone` among archive entries the\n * retention bounds dropped. Steps with seq < archiveFloor may miss removed\n * nodes (the browser shows the reconstruction as approximate).\n */\n archiveFloor?: number\n /**\n * The fold-derived file-operation log and its trim floor — present on the\n * INLINE wire value (channel-less hosts) and on the detail payload\n * (ContextTimelineDetail), absent from the slim head (they ride the detail\n * channel there).\n */\n fileOps?: FileOpRecord[]\n fileOpsFloor?: number\n}\n\n/**\n * The on-demand DETAIL payload of the split `redlineTimeline` generation —\n * the heavy collections (per-request records, context events, the served\n * surface window, and the removed-node archive) that the slim wire head no\n * longer carries through every delivery channel. The host serves it off the\n * live fold state at the `/dsh-context-redline` `detail` endpoint (host/detail.ts);\n * `rev` mirrors the head's `detailRev` at build time and acts as the\n * client's latest-wins cursor.\n */\nexport interface ContextTimelineDetail {\n rev: number\n /**\n * The slim wire head at the SAME fold cut as the collections: the\n * composition scalars (`current`), the window/model envelope, and the\n * precomputed counts. Sessions listed cold (never attached since the\n * requesting unit last changed) carry no `redlineTimeline` projection row\n * for the browser's list reads, so the Agent network card fetches this\n * head per node to render their composition rings. The host always serves\n * it; optional so a payload missing it still serves the collections (the\n * detail cards) and only the ring composition degrades.\n */\n head?: ContextTimeline\n requests: RequestRecord[]\n events: ContextEventRecord[]\n nodes: SurfaceNode[]\n droppedNodes: number\n archive: SurfaceNode[]\n surfaceFloor?: number\n archiveFloor?: number\n /**\n * The fold-derived file-operation log (shared/fileOps.ts): one record per\n * executed file op, newest-retained, covering the full log (never\n * window-bound like the client-side join derivation it replaces on this\n * generation). Code-Mode nested dispatches book ops located on their\n * parent run_code result (`parent`).\n */\n fileOps?: FileOpRecord[]\n /** The newest dropped op's seq when the op log trimmed (coverage honesty, same family as archiveFloor). */\n fileOpsFloor?: number\n}\n\n/**\n * One executed file operation (a settled file-tool call with a resolved\n * target), folded host-side from the durable tool lifecycle: the call's\n * name+arguments (`tool/call`), the result's presentation meta and error\n * (`tool/result`), or a nested Code-Mode settle (`tool/ptc-dispatch`,\n * located on its parent run_code result via `parent` + `program`).\n *\n * `gone` is NOT host-stamped: the client joins it from the detail's archive\n * at render time (the op's result node leaving the live surface marks where\n * its content is still viewable). Line deltas are estimates read off the\n * call ARGUMENTS (an edit's old/new strings, a write's content), never off\n * result payloads.\n */\nexport interface FileOpRecord {\n seq: number\n /** The op's file; for a pathless search the searched PATTERN (`pattern: true`). */\n path: string\n kind: 'read' | 'write' | 'search'\n tool: string\n time?: number\n err: boolean\n added: number\n removed: number\n /** What was searched for, when a search named both a path and a pattern. */\n detail?: string\n /** Meta-attributed search op only: matched lines the result reported for this file. */\n hits?: number\n /** Read ops only: the exact 1-based window the result meta reported, else the `limit`-argument estimate (`est: true`). */\n read?: { start: number; count: number } | { count: number; est: true }\n /** Nested Code-Mode op only: the run_code result node the op ran under (the locate target). */\n parent?: number\n /** Nested Code-Mode op only: the run_code program's model-authored description. */\n program?: string\n /** The searched-pattern marker: `path` is a pattern, not a file — display must not relativize it. */\n pattern?: true\n /** Client-joined archive stamp (see the type note); absent on the wire. */\n gone?: number\n}\n\n/**\n * The `redlineTimeline` projection's whole value — the same snapshot the Client has always rendered. `ok` is always `true` here (a\n * delivered projection is by definition available); kept for wire compatibility with the snapshot shape.\n */\nexport type ContextTimeline = Snapshot\n\n/**\n * The official token-meter `contextPressure` projection (registered by\n * `@deepseek-ai/dsh-token-meter` on the same `SessionProjectionMap`): the\n * provider-anchored occupancy of the NEXT request. The Client reads this key\n * directly instead of the Host mirroring it inside `redlineTimeline`\n * (token-meter owns estimation and replay — the docs' stated division of\n * labor). Fields are independent last-wins records; absent until a provider\n * reports usage. Absent key/value = the registry (or the meter) is not\n * composed — the Client falls back to its derived anchor.\n */\nexport interface ContextPressure {\n /** Provider-reported prompt size of the most recent request (input + cache). */\n pressureTokens?: number\n /** pressureTokens + heuristic surface movement since the sample (clamped ≥ 0). */\n projectedTokens?: number\n /** Newest recorded route capacity (last-wins). */\n contextWindow?: number\n}\n\n/**\n * The official token-meter `contextBreakdown` projection: the heuristic\n * composition rows the chat ring's click-open panel shows (system prompt,\n * tool schemas, conversation). The Client reads this key directly so the\n * composition card's proportions AND counts stay identical to the panel's\n * by construction; the message bucket is subdivided into the plugin's four\n * surface categories by the fold's per-category ratios. Absent key/value =\n * an older harness without the meter's projection units — callers fall back\n * to the fold's own sums (identical estimator, minus the image correction).\n */\nexport interface ContextBreakdown {\n systemTokens: number\n toolsTokens: number\n messageTokens: number\n}\n\n/**\n * The official token-meter `tokenUsage` projection (registered by\n * `@deepseek-ai/dsh-token-meter` on the same `SessionProjectionMap`): durable\n * cumulative provider-reported usage across the COMPLETE session log. The four\n * buckets are disjoint (reasoning tokens are already inside `outputTokens`).\n * The Client reads this key directly to compute the cache-hit share — the\n * exact same data the chat stats line below the input box shows, same formula\n * — instead of the Host mirroring it inside `redlineTimeline`. Absent until a\n * provider reports usage.\n */\nexport interface TokenUsage {\n /** Billed prompt tokens that missed the provider cache. */\n uncachedInputTokens: number\n /** Billed output tokens (reasoning included). */\n outputTokens: number\n /** Billed prompt tokens served from the provider cache. */\n cacheReadTokens: number\n /** Billed prompt tokens written into the provider cache. */\n cacheWriteTokens: number\n}\n\n/**\n * Cumulative billed-token totals for one pricing bucket of the session-cost\n * estimate (host-folded, never trimmed — running totals over the COMPLETE\n * session log, immune to the request/event retention bounds).\n */\nexport interface CostBucketTotals {\n uncached: number\n cacheRead: number\n cacheWrite: number\n output: number\n}\n\n/**\n * One completed tool name's whole-session call tally behind the timing\n * card's top-tools ranking (running totals, never trimmed).\n */\nexport interface ToolTimingTotals {\n calls: number\n ms: number\n}\n\n/**\n * Whole-session timing totals, host-folded from the durable `step/start` /\n * `step/end` / `tool/call` / `tool/result` lifecycle plus the model call's\n * first token (running totals over the COMPLETE session log — the same\n * never-trimmed framing as `cost`). The first token comes from the call's\n * own embedded stream (`assistant/message.data.stream` /\n * `assistant/attempt.data.stream`), matching the harness's own\n * session-stats fold. Durations are wall-clock milliseconds: `wallMs` sums\n * whole steps, `ttftMs` the step-start → first-token slice (the model wait)\n * and `genMs` the first-token → assistant-message slice (the generation) —\n * both only over calls whose stream carried a token delta, `toolsMs` the sum\n * of per-call tool durations (parallel calls each count, so it can overlap).\n * Absent until the first step lifecycle completes in the log.\n *\n * The generation window itself splits by WHAT was being decoded, off the\n * stream's `block-start` framing (`blockType`): `reasoningMs` (the model's\n * thinking), `textMs` (the answer text), and `toolArgMs` (the tool-call\n * arguments). Each marker owns the interval up to the next one (the last one\n * up to the assistant message), so the three tile the marker span and together\n * account for essentially all of `genMs` — the span opens at the first marker,\n * which can sit marginally before the first token, so it is not an exact\n * partition. They are ADDITIVE-OPTIONAL: cached projection rows written before\n * the split carry `genMs` without them, so the card falls back to the\n * un-split shape instead of the cache row being discarded (the\n * stateVersion-15 rationale in host/timeline.ts).\n */\nexport interface TimingTotals {\n /** Summed wall time of completed steps (the session's active time). */\n wallMs: number\n /** Summed step-start → first-token time (the model wait, TTFT). */\n ttftMs: number\n /** Summed first-token → assistant-message time (the generation). */\n genMs: number\n /** Reasoning-decode slice of `genMs` (the model's thinking). */\n reasoningMs?: number\n /** Counted reasoning-decode blocks (the Thinking slice's tally). */\n reasoningBlocks?: number\n /** Answer-text decode slice of `genMs`. */\n textMs?: number\n /** Counted answer-text decode blocks (the Answer slice's tally). */\n textBlocks?: number\n /** Tool-call-argument decode slice of `genMs`. */\n toolArgMs?: number\n /**\n * Counted tool-call-argument decode blocks — one per tool call whose\n * arguments the stream decoded (the Tool args slice's tally). The counts are\n * ADDITIVE-OPTIONAL like their spans: a row cached before they existed (or a\n * call whose stream framed no blocks) carries none, and the card qualifies\n * only what was actually counted.\n */\n toolArgBlocks?: number\n /**\n * The decode-throughput seat, paired exactly as the harness's own\n * session-stats fold pairs them: `speedTokens` sums provider-reported\n * output tokens and `speedMs` the first-token → assistant-message\n * windows, over the calls that carried BOTH a first-token stamp and a\n * usage report — a subset of `genMs`, which counts every token-stamped\n * call regardless of usage. Additive-optional: cached rows written before\n * the seat existed lack them, and the card falls back to no chip.\n */\n speedTokens?: number\n speedMs?: number\n /** Completed model calls (assistant messages folded). */\n calls: number\n /** Summed per-call durations of completed tool calls. */\n toolsMs: number\n /** Completed tool calls (call/result pairs folded). */\n toolCalls: number\n /** Per-tool-name tallies behind the timing card's ranking (bounded). */\n tools: Record<string, ToolTimingTotals>\n}\n\n/**\n * One billed model's cumulative totals split by pricing period. Providers\n * without period-based pricing book everything under `peak` (the list-price\n * period); DeepSeek splits at fold time — peak windows bill at list price,\n * off-peak (all other hours) at half.\n */\nexport interface CostModelUsage {\n peak?: CostBucketTotals\n off?: CostBucketTotals\n}\n\n/**\n * The session-cost estimate's raw material: cumulative provider-reported\n * billed-token totals, keyed by the request envelope's DSH provider id (''\n * when a log carries none) and then by its model id — the exact (provider,\n * model) faces the Client's model-price book resolves (the models.dev\n * registry, client/modelPrices.ts). Running totals per key; absent until a\n * request with a known model reports usage.\n */\nexport interface SessionCostUsage {\n [provider: string]: { [model: string]: CostModelUsage }\n}\n\n/** One model-visible message on the surface, with its heuristic token price. */\nexport interface SurfaceNode {\n seq: number\n time?: number\n cat: Category\n tokens: number\n /** Image blocks inside this node's message (absent when zero). */\n imgs?: number\n /**\n * Removal marker, present only on `archive` entries: the seq of the\n * replacement surface event that shadowed this node (compaction/prune).\n * The node is part of the assembled context of every request with\n * seq > this node.seq and seq < gone.\n */\n gone?: number\n form?: string\n /**\n * The producer identity the matching inject event names (host pricing.ts\n * `injectionSourceName`: the plugin id, the reconciled instruction files,\n * or the durable kind). Stamped on injection nodes alongside the event, so\n * the browser rows label them the way the events card does; absent when the\n * source carries no readable identity or the node predates the stamp.\n */\n name?: string\n text?: string\n tool?: string\n err?: boolean\n skill?: string\n calls?: string[]\n}\n\n/** One answered model call (a step); consecutive records of one turn form it. */\nexport interface RequestRecord {\n turn?: number\n step?: number\n time: number\n seq: number\n system: number\n tools: number\n user: number\n inject: number\n assistant: number\n tool: number\n total: number\n prompt?: number\n /**\n * Skill-machinery tokens of this request (the `skill` composition\n * category — catalog digests, invocation instructions, `skill`-tool\n * loads). Always written by the current fold; absent on rows folded\n * before the category existed (read as 0).\n */\n skill?: number\n /**\n * Billed cache-read (served) prompt tokens of this request — the\n * hit-rate numerator against `prompt` (input + cacheRead + cacheWrite).\n * Absent on older hosts / usage-less requests; zero is a real value.\n */\n cacheRead?: number\n output?: number\n /**\n * Turn-mode aggregate marker, set by the Client's aggregateByTurn (one bar\n * per turn shows its LAST step's record). The Host never sets it.\n */\n stepCount?: number\n /**\n * Delta-mode signed net change, set by the Client's deltaOf (only present\n * on the delta-transformed records the TrendChart plots). The Host never\n * sets it.\n */\n net?: number\n}\n\n/** A notable context event (compaction, prune, injection, model switch). */\nexport interface ContextEventRecord {\n seq: number\n time: number\n kind: 'compaction' | 'prune' | 'inject' | 'model' | 'mode'\n form?: string\n tokens?: number\n count?: number\n sub?: string\n name?: string\n /** One-line producer account (notice-form summary), shown after the name. */\n detail?: string\n from?: string\n to?: string\n /** Turn/step of the request logged right BEFORE the event (host-stamped). */\n fromTurn?: number\n fromStep?: number\n /** Turn/step of the request this event contributed to (host-stamped). */\n turn?: number\n step?: number\n}\n\n/**\n * Sentinel `HeaderTool.plugin` value marking a tool whose provider could not\n * be attributed: it was already registered in the harness tool service when\n * this plugin's runtime attribution hook installed (boot-time third-party\n * tools — e.g. local-link plugins that apply before dsh-context-redline). The client\n * renders a localized \"unknown plugin\" tag with an explanatory tooltip. No\n * real plugin name can collide (it is not a valid package identifier).\n */\nexport const UNKNOWN_TOOL_SOURCE = '<unknown-plugin>'\n\n/** One tool of a request-header epoch, with its display price. */\nexport interface HeaderTool {\n name: string\n tokens: number\n /**\n * The registering plugin's label, when attribution is known: the host's\n * best-effort attribution (`mcp:<server>` for MCP tools, or the pinned\n * first-party package map), or a `plugin` field carried by the raw header\n * entry — no supported-baseline harness path writes one, but the read\n * stays defensive for foreign/newer producers. `UNKNOWN_TOOL_SOURCE` marks\n * a tool whose provider predates the attribution hook; absent means\n * nothing is known and the browser shows no tag.\n */\n plugin?: string\n}\n\n/**\n * One request-header epoch's METADATA: the epoch boundaries and token prices\n * in force from this event's seq until the next epoch. The epoch CONTENT\n * (full system prompt text, tool descriptions/schemas) is not projected —\n * every session.list row, control baseline, push frame, and projection-cache\n * checkpoint would otherwise carry it per session × epoch. The client\n * fetches one epoch's content on demand (a seq-anchored history read off\n * `seq`) as a {@link HeaderEpochContent}.\n */\nexport interface HeaderRecord {\n seq: number\n time: number\n /** The epoch's estimated system-prompt tokens; absent when it logged no system prompt. */\n systemTokens?: number\n tools: HeaderTool[]\n}\n\n/** The `redlineHeaders` projection value: the bounded epoch list (newest last). */\nexport interface ContextHeaders {\n headers: HeaderRecord[]\n}\n\n/**\n * The fetched CONTENT of one request-header epoch — the full system prompt\n * text and per-tool descriptions/schemas, mapped client-side off the raw\n * durable event (see historyPage.ts). Tool identity joins the epoch metadata\n * by `name`; absent description/schema means the raw entry carried none.\n */\nexport interface HeaderEpochContent {\n system?: string\n tools: Array<{\n name: string\n description?: string\n /** The raw JSON schema object the model received (plain JSON). */\n schema?: unknown\n }>\n}\n\n/** One currency's DeepSeek open-platform balance figures. */\nexport interface PlatformBalanceEntry {\n /** The ISO code the platform reported (`CNY` / `USD`). */\n currency: string\n /** Total available funds: `granted` + `toppedUp`. Derived here rather than read\n * from the platform's own `total_balance`, which rounds independently of its\n * parts and can land a cent away from what the breakdown beside it shows. */\n total: number\n /** The not-expired granted (gift) balance. */\n granted: number\n /** The topped-up balance. */\n toppedUp: number\n}\n\n/**\n * The DeepSeek open-platform balance, served by the plugin's\n * `/api/dsh-context-redline/balance` fetch route (host/balance.ts). `null` on the\n * wire — and nothing rendered client-side — whenever the platform is not\n * configured or the read fails: the capsule only ever shows a live figure.\n */\nexport interface PlatformBalance {\n /** Whether the platform reports the balance sufficient for API calls. */\n isAvailable: boolean\n /** One entry per currency the account holds; at least one. */\n balances: PlatformBalanceEntry[]\n}\n","/**\n * Per-step context assembly — the pure reconstruction behind the Context\n * browser card.\n *\n * A request record R was snapshotted by the Host exactly as dispatched:\n * header in force + the model-visible surface BEFORE the response landed.\n * Given the timeline's live `nodes` (newest tail) and `archive` (removed\n * nodes stamped with `gone`), the surface assembled into R is:\n *\n * every node with seq < R.seq AND (gone undefined OR gone > R.seq)\n *\n * For the LIVE view (the next request's context) it is simply the current\n * live nodes. Coverage is honest: when the served window cannot contain the\n * full answer (older live nodes dropped, or removals older than the archive\n * retention), the result carries the flags the UI turns into notices.\n */\n\nimport type { ContextHeaders, ContextTimeline, HeaderRecord, SurfaceNode, SystemPromptNode } from '../shared/types'\n\nexport interface Assembled {\n /** True when browsing the live surface (the next request's context). */\n live: boolean\n /** The header epoch in force (null = headers projection absent or none yet). */\n header: HeaderRecord | null\n /**\n * The system prompt in force at the shown step (null = none), resolved from\n * the timeline's live `systems` nodes; on rows folded before that field\n * existed the header epoch's own envelope figure stands in.\n */\n system: SystemPromptNode | null\n /** The assembled surface messages, in seq order. */\n nodes: SurfaceNode[]\n /** Live nodes outside the served window that are also part of the context. */\n missingLive: number\n /** True when removals this step depends on may exceed archive retention. */\n approximate: boolean\n}\n\n/** The header epoch in force at `seq` (last logged before it), or the newest. */\nexport function headerAt(headers: ContextHeaders | null, seq: number | null): HeaderRecord | null {\n if (headers === null || headers.headers.length === 0) return null\n if (seq === null) return headers.headers[headers.headers.length - 1]\n for (let i = headers.headers.length - 1; i >= 0; i--) {\n if (headers.headers[i].seq < seq) return headers.headers[i]\n }\n return null\n}\n\n/**\n * The system prompt in force at `seq` (null = none) — the LAST live system\n * node at or before it carrying tokens, which is exactly the host fold's\n * \"last nonempty surviving system\" rule and therefore agrees with the\n * per-step `system` figure the fold recorded. Rows folded before `systems`\n * existed carry none; the header epoch's own figure stands in for them (the\n * legacy wire shape older plugin builds served — current epochs fold\n * metadata-only, so the fallback only ever fires on those cached rows).\n */\nexport function systemAt(\n data: ContextTimeline,\n header: HeaderRecord | null,\n seq: number | null,\n): SystemPromptNode | null {\n const systems = data.systems\n if (systems !== undefined && systems.length > 0) {\n for (let i = systems.length - 1; i >= 0; i--) {\n const node = systems[i]\n if (node.tokens <= 0) continue\n if (seq === null || node.seq < seq) return node\n }\n return null\n }\n return header !== null && header.systemTokens !== undefined\n ? { seq: header.seq, time: header.time, tokens: header.systemTokens }\n : null\n}\n\nexport function assemble(data: ContextTimeline, headers: ContextHeaders | null, seq: number | null): Assembled {\n const live = seq === null\n let nodes: SurfaceNode[]\n if (live) {\n nodes = data.nodes.slice()\n } else {\n const picked: SurfaceNode[] = []\n for (const n of data.nodes) {\n if (n.seq < seq) picked.push(n)\n }\n for (const n of data.archive) {\n if (n.seq < seq && n.gone !== undefined && n.gone > seq) picked.push(n)\n }\n nodes = picked\n }\n nodes.sort((a, b) => a.seq - b.seq)\n\n let missingLive = 0\n if (data.droppedNodes > 0) {\n // Live: every dropped live node is part of the current context. A past\n // step: the dropped slice sits at or below `surfaceFloor`, so a step\n // after it contains them all (an older step's unknown subset is left\n // unflagged rather than overstated).\n if (live || (data.surfaceFloor !== undefined && seq > data.surfaceFloor)) {\n missingLive = data.droppedNodes\n }\n }\n const approximate = !live\n && data.archiveFloor !== undefined\n && seq < data.archiveFloor\n\n const header = headerAt(headers, seq)\n return { live, header, system: systemAt(data, header, seq), nodes, missingLive, approximate }\n}\n\n/** 「当前这一步」的读数:统计卡那 3 格 + `本步可见 N 条 · ≈X tokens`(`docs/10` M4-07)。 */\nexport interface StepStats {\n /** 该步列表里的条目总数(demo 的 `本步可见 N 条`)。 */\n readonly listed: number\n /** 模型可见条目 = 列表里**没有** `gone` 的那些。 */\n readonly visible: number\n /** 列表里**已失效**的原文条数(demo 那句「另 N 条被遮蔽」)。 */\n readonly shadowed: number\n /** 可见条目里的用户消息条数。 */\n readonly user: number\n /** 可见条目里的注入内容条数。 */\n readonly inject: number\n /** 整张列表的估算 token 合计(`≈` 前缀由界面加)。 */\n readonly tokens: number\n /**\n * 列表里**没有** `tokens` 的条数(`docs/00` S1.1:缺失时显示 `—`,不得用 0 冒充)。\n * 线上 schema 里 `tokens` 是 **optional**(`z.number().optional()`),而 TS 类型写成必填 ——\n * 也就是这种情况**真的会发生**(丑陋的类型/契约错位,先按\"数出来、说清楚\"处理,见下)。\n * 求和那格没法显示 `—`,所以单列出来,界面据此说明「另有 N 条未计入」。\n */\n readonly missingTokens: number\n}\n\n/**\n * The three cells the demo defines (user ruling 2026-10-06, `docs/10` M4-07).\n *\n * 口径**完全取自 `assemble()` 已经算好的那张列表**,不再自己定边界:\n * `assemble()` 对\"某一步\"返回的 `nodes` 里既有仍然有效的条目,也有**在那一步还活着、\n * 如今已被接替**的原文(判据 `n.gone !== undefined`,因为原文在那一步尚未被替换)。\n * 所以:\n * · `visible` = 列表里没有 `gone` 的;\n * · `shadowed` = 列表里有 `gone` 的(界面把它渲染成\"已被接替\"那一行);\n * · 两个分类计数只数**可见**的(demo 同样从 `vis` 里筛);\n * · `tokens` = 整张列表的合计(对得上 `本步可见 N 条 · ≈X tokens` 里那个 N)。\n * 按 seq 去重:早期那次把同一条替换体渲染两遍、面板列 5 项却报 7 项(2026-10-02 用户截图抓到的 #1600 重复计数)。\n */\nexport function stepStatsOf(assembly: { readonly nodes: readonly SurfaceNode[] }): StepStats {\n const seen = new Set<number>()\n let listed = 0\n let visible = 0\n let shadowed = 0\n let user = 0\n let inject = 0\n let tokens = 0\n let missingTokens = 0\n for (const n of assembly.nodes) {\n if (seen.has(n.seq)) continue\n seen.add(n.seq)\n listed += 1\n if (typeof n.tokens === 'number') tokens += n.tokens\n else missingTokens += 1\n if (n.gone === undefined) {\n visible += 1\n if (n.cat === 'user') user += 1\n else if (n.cat === 'inject') inject += 1\n } else {\n shadowed += 1\n }\n }\n return { listed, visible, shadowed, user, inject, tokens, missingTokens }\n}\n","/**\n * The browser's DNA mode: decompose an assembled context into ONE band per\n * item (the system prompt, every tool schema, every surface message) and\n * lay them out in the order the model actually reads them — the context's\n * \"fingerprint\" strip behind the composition bar's `dna` toggle.\n *\n * The order is PROMPT order, which is also the order items joined the\n * context: the system prompt and tool schemas prefix every request, so they\n * lead the strip; the message flow follows in seq (chronological) order.\n * The system band rides the timeline's own `systems` nodes (the prompt's real\n * surface positions), the tool bands their header epoch. The header epoch's\n * own seq is NOT usable as an ordering key: dsh appends `request/header` at\n * dispatch time of the first request that uses a header (agent.ts —\n * 'initial'/'resume'/'change'/'series'), a bookkeeping snapshot that lands\n * AFTER every message already in context. A mid-session refresh would\n * otherwise park the tools bands in the middle of the strip, behind the very\n * tool results those schemas describe. A refreshed epoch REPLACES the prefix\n * in place — the strip reflects that by keeping the current epoch's bands at\n * the front (the band's tooltip carries the epoch's time).\n */\n\nimport type { Category, SurfaceNode } from '../shared/types'\nimport type { Assembled } from './assemble'\n\n/**\n * One band of the DNA strip. Header bands carry their tokens only; message\n * bands hand the node through so the label builder reads tool/form/skill\n * straight off it (the union discriminates on `cat` — no defensive guards).\n */\nexport type DnaItem =\n | { key: string; cat: 'system' | 'tools'; tokens: number; time?: number }\n | { key: string; cat: Category; tokens: number; time?: number; node: SurfaceNode }\n\nexport function dnaOf(view: Assembled): DnaItem[] {\n const items: DnaItem[] = []\n if (view.system !== null) {\n items.push({ key: 'sys', cat: 'system', tokens: view.system.tokens, time: view.system.time })\n }\n if (view.header !== null) {\n for (const tool of view.header.tools) {\n items.push({ key: 'tool:' + tool.name, cat: 'tools', tokens: tool.tokens })\n }\n }\n // `assemble` guarantees seq order; zero-token items keep their band (the\n // bar drops zero widths, the reading order stays truthful).\n for (const n of view.nodes) {\n items.push({\n key: 'n' + String(n.seq),\n cat: n.cat,\n tokens: n.tokens,\n node: n,\n ...(n.time !== undefined ? { time: n.time } : {}),\n })\n }\n return items\n}\n","/**\n * The file-operation parser — the ONE derivation of \"what the agent did to\n * files\" from a settled file-tool call. Shared by both halves: the host fold\n * books the op log from the durable tool lifecycle (tool/call +\n * tool/result + tool/ptc-dispatch), and the client's INLINE-generation\n * fallback re-derives ops from the conversation-window join when an older\n * host serves no `fileOps`.\n *\n * Tool coverage matches the harness's built-ins on every supported baseline\n * (0.1.5-rc.1): read / read_image / write / edit (tool-fs) and grep / glob\n * (tool-fs-search), plus the Anthropic-style `str_replace_editor` (view\n * reads, every other command writes). Line deltas are estimates read off the\n * call ARGUMENTS (an edit's old/new strings, a write's content), never off\n * result payloads. A search resolves further when its result's bounded\n * presentation meta names the matched files — the ops then row per real\n * file with the match count, and only a capped (`truncated`) or malformed\n * meta falls back to the call's own target (the narrowing path, else the\n * searched pattern itself).\n */\n\nimport type { FileOpRecord } from './types'\n\n/** Parse a call's raw JSON arguments; non-string/malformed/non-record inputs yield null. */\nexport function parseCallArgs(raw: unknown): Record<string, unknown> | null {\n if (typeof raw !== 'string' || raw === '') return null\n try {\n const parsed: unknown = JSON.parse(raw)\n return parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)\n ? parsed as Record<string, unknown>\n : null\n } catch {\n return null\n }\n}\n\nconst KIND_BY_TOOL: Record<string, FileOpRecord['kind']> = {\n read: 'read',\n read_image: 'read',\n write: 'write',\n edit: 'write',\n grep: 'search',\n glob: 'search',\n}\n\n/** The file purpose of a tool, or null for non-file tools (bash, web_search…). */\nexport function kindOfTool(tool: string | undefined): FileOpRecord['kind'] | null {\n if (tool === undefined) return null\n return KIND_BY_TOOL[tool] ?? null\n}\n\n/**\n * The file purpose of one executed call. Like {@link kindOfTool} except for\n * the one file tool whose purpose follows its arguments: `str_replace_editor`\n * reads on `view` and writes on every other command (create / str_replace /\n * insert — an unknown command writes too; the call failed and the row keeps\n * its error flag).\n */\nexport function kindOfCall(tool: string, args: Record<string, unknown> | null): FileOpRecord['kind'] | null {\n if (tool === 'str_replace_editor') return args !== null && args.command === 'view' ? 'read' : 'write'\n return kindOfTool(tool)\n}\n\n/**\n * Whether a settled call's arguments can yield an op at all: the file tools\n * plus `str_replace_editor`, whose purpose follows its `command`. The public\n * face of the gate {@link opsOfCall} short-circuits on — callers that decide\n * whether to parse or to KEEP a call's raw arguments ask here instead of\n * restating the tool list.\n */\nexport function opBearingTool(tool: string): boolean {\n return tool === 'str_replace_editor' || kindOfTool(tool) !== null\n}\n\n/**\n * Whether a call's raw arguments must ride the fold state\n * (TimelineState.callNames): every op-bearing tool, plus `run_code`, whose\n * `description` labels the ops its nested dispatches book at flush time.\n */\nexport function rawArgsNeeded(tool: string): boolean {\n return opBearingTool(tool) || tool === 'run_code'\n}\n\n/**\n * The operation's target path: the path-ish argument of read/write tools;\n * for searches the narrowing `path`, else the pattern itself (a pathless\n * grep/glob's target IS the pattern — the workspace-wide search text).\n */\nexport function pathOfArgs(tool: string, args: Record<string, unknown> | null): string | null {\n if (args === null) return null\n if (tool === 'grep' || tool === 'glob') {\n const p = args.path\n if (typeof p === 'string' && p !== '') return p\n const pattern = args.pattern\n return typeof pattern === 'string' && pattern !== '' ? pattern : null\n }\n for (const k of ['file_path', 'filePath', 'path']) {\n const v = args[k]\n if (typeof v === 'string' && v !== '') return v\n }\n return null\n}\n\n/** Rendered line count: '' is 0, a trailing newline closes its own line. */\nexport function linesOf(s: string): number {\n if (s === '') return 0\n let n = 0\n for (let i = 0; i < s.length; i++) if (s[i] === '\\n') n++\n return s.endsWith('\\n') ? n : n + 1\n}\n\n/** The added/removed pair of one content-bearing argument set, or zeros. */\nfunction pairOf(added: unknown, removed: unknown): { added: number; removed: number } {\n return {\n added: typeof added === 'string' ? linesOf(added) : 0,\n removed: typeof removed === 'string' ? linesOf(removed) : 0,\n }\n}\n\n/**\n * The signed line footprint of one call: an edit removes its old string and\n * adds its new one; a write adds its content (the pre-existing body, if any,\n * is unknowable from the arguments — the estimate stays honest about that);\n * `str_replace_editor` splits the same shapes across its commands. Callers\n * reach here only with parsed args (a null parse yields no path).\n */\nfunction deltaOf(tool: string, args: Record<string, unknown>): { added: number; removed: number } {\n if (tool === 'edit') return pairOf(args.new_string, args.old_string)\n if (tool === 'write') return pairOf(args.content, undefined)\n if (tool === 'str_replace_editor') {\n if (args.command === 'str_replace') return pairOf(args.new_str, args.old_str)\n if (args.command === 'insert') return pairOf(args.new_str, undefined)\n if (args.command === 'create') return pairOf(args.file_text, undefined)\n }\n return { added: 0, removed: 0 }\n}\n\n/** The exact window a read's result meta reports: `offset` plus the retained\n * `lines` array (the same bounded payload the read card renders from). Null\n * for a foreign or malformed meta. */\nfunction readWindowOf(meta: unknown): { start: number; count: number } | null {\n if (meta === null || typeof meta !== 'object') return null\n const m = meta as { path?: unknown; offset?: unknown; lines?: unknown }\n if (typeof m.path !== 'string' || m.path === '') return null\n if (typeof m.offset !== 'number' || !Number.isFinite(m.offset) || m.offset < 1) return null\n if (!Array.isArray(m.lines) || m.lines.length === 0) return null\n return { start: m.offset, count: m.lines.length }\n}\n\n/** The limit estimate: the tool reads up to `limit` lines from `offset`;\n * absent when the call reads unbounded. */\nfunction readEstimateOf(args: Record<string, unknown>): { count: number; est: true } | undefined {\n const limit = args.limit\n return typeof limit === 'number' && Number.isFinite(limit) && limit > 0\n ? { count: Math.floor(limit), est: true }\n : undefined\n}\n\n/** What a read op shows: the exact window off the result meta, else the\n * limit estimate, else nothing (an unbounded read names no footprint). */\nfunction readOf(meta: unknown, args: Record<string, unknown>): { start: number; count: number } | { count: number; est: true } | undefined {\n const win = readWindowOf(meta)\n if (win !== null) return { start: win.start, count: win.count }\n return readEstimateOf(args)\n}\n\n/**\n * A search op's detail: the pattern, with the include filter appended when\n * one narrowed the call. A patternless (malformed) search has no detail.\n */\nfunction searchDetailOf(args: Record<string, unknown> | null): string | undefined {\n const pattern = args?.pattern\n if (typeof pattern !== 'string' || pattern === '') return undefined\n const include = args?.include\n return typeof include === 'string' && include !== '' ? `${pattern} (${include})` : pattern\n}\n\n/**\n * The files a search demonstrably reached, read off the result's bounded\n * presentation meta (grep groups matched lines by file; glob lists paths).\n * Only the COMPLETE list attributes: a capped search (`truncated`) names a\n * partial file set, and a malformed meta names none — both fall back to the\n * call's own target. Each entry carries the reported match count.\n */\nfunction searchFilesOf(meta: unknown): { path: string; hits: number }[] | null {\n if (meta === null || typeof meta !== 'object') return null\n const m = meta as { shape?: unknown; truncated?: unknown; files?: unknown; paths?: unknown }\n if (m.truncated !== false) return null\n const files: { path: string; hits: number }[] = []\n if (m.shape === 'matches' && Array.isArray(m.files)) {\n for (const f of m.files) {\n if (f === null || typeof f !== 'object') continue\n const group = f as { path?: unknown; matches?: unknown }\n if (typeof group.path === 'string' && group.path !== '' && Array.isArray(group.matches)) {\n files.push({ path: group.path, hits: group.matches.length })\n }\n }\n } else if (m.shape === 'paths' && Array.isArray(m.paths)) {\n for (const p of m.paths) {\n if (typeof p === 'string' && p !== '') files.push({ path: p, hits: 0 })\n }\n }\n return files.length > 0 ? files : null\n}\n\n/**\n * The one-shot per-call op assembly, uniform across every producer: the\n * host's call/result pairing (args off the armed call, meta off the\n * result), the nested Code-Mode settle (no meta exists on a dispatch — the\n * read window and per-file search attribution degrade to the argument-only\n * forms), and the client's inline-generation join fallback. Returns zero to\n * N records: a search with the complete matched-file meta rows per file;\n * any other file call rows once; a non-file tool (or a call whose arguments\n * resolve no target) rows nothing.\n */\nexport function opsOfCall(input: {\n seq: number\n tool: string\n argsRaw?: unknown\n meta?: unknown\n err?: boolean\n time?: number\n gone?: number\n parent?: number\n program?: string\n}): FileOpRecord[] {\n // A non-op-bearing tool never rows one — skip its arguments parse entirely\n // (a call's arguments are its largest payload, and the fold may hand a large\n // bash/pwsh call here).\n const args = opBearingTool(input.tool) ? parseCallArgs(input.argsRaw) : null\n const kind = kindOfCall(input.tool, args)\n if (kind === null) return []\n const stamp: FileOpRecord = {\n seq: input.seq,\n kind,\n tool: input.tool,\n err: input.err === true,\n added: 0,\n removed: 0,\n path: '',\n ...(input.time !== undefined ? { time: input.time } : {}),\n ...(input.gone !== undefined ? { gone: input.gone } : {}),\n ...(input.parent !== undefined ? { parent: input.parent } : {}),\n ...(input.program !== undefined ? { program: input.program } : {}),\n }\n // A search whose result meta carries the COMPLETE matched-file list rows\n // its ops per real file — even when the call's own arguments failed to\n // parse (the detail line just drops out). The call's own target (the\n // searched path, or the pattern for a workspace-wide search) rows TOO —\n // \"what was searched\" and \"what got hit\" both count; only the degenerate\n // single-file search (the target IS the sole matched file) skips the\n // duplicate target row.\n if (kind === 'search') {\n const files = searchFilesOf(input.meta)\n if (files !== null) {\n const detail = searchDetailOf(args)\n const target = args !== null ? pathOfArgs(input.tool, args) : null\n const narrowed = args !== null && typeof args.path === 'string' && args.path !== ''\n const targetOps: FileOpRecord[] = target !== null && !files.some(f => f.path === target)\n ? [{\n ...stamp,\n path: target,\n ...(narrowed && detail !== undefined ? { detail } : {}),\n ...(narrowed ? {} : { pattern: true as const }),\n }]\n : []\n return [\n ...targetOps,\n ...files.map(f => ({\n ...stamp,\n path: f.path,\n ...(detail !== undefined ? { detail } : {}),\n ...(f.hits > 0 ? { hits: f.hits } : {}),\n })),\n ]\n }\n }\n if (args === null) return []\n const path = pathOfArgs(input.tool, args)\n if (path === null) return []\n const { added, removed } = deltaOf(input.tool, args)\n const narrowed = typeof args.path === 'string' && args.path !== ''\n const detail = kind === 'search' && narrowed ? searchDetailOf(args) : undefined\n const read = kind === 'read' ? readOf(input.meta, args) : undefined\n return [{\n ...stamp,\n path,\n added,\n removed,\n ...(detail !== undefined ? { detail } : {}),\n ...(read !== undefined ? { read } : {}),\n ...(kind === 'search' && !narrowed ? { pattern: true as const } : {}),\n }]\n}\n","/**\n * Tool-call argument summaries — shared between the Context browser (row\n * previews) and the step brief (input chips / reply enrichment). A call's\n * preview is its bash-style `description`, or the target path\n * (`file_path`/`path`/`filePath`) for edit/read/write tools.\n */\n\nimport type { ConversationNodeLike } from './services'\n// The argument parser lives in the shared layer (shared/fileOps.ts) since the\n// op-log generation — the host fold parses the same raw strings there.\nimport { parseCallArgs } from '../shared/fileOps'\n\nexport { parseCallArgs }\n\nexport function summaryInArgs(args: Record<string, unknown> | null): string | null {\n if (args === null) return null\n for (const k of ['description', 'file_path', 'path', 'filePath']) {\n const v = args[k]\n if (typeof v === 'string' && v !== '') return v\n }\n return null\n}\n\nexport function callSummaryOf(conv: ConversationNodeLike | undefined): string | null {\n return summaryInArgs(parseCallArgs(conv?.call?.argsRaw))\n}\n\nexport function blockSummaryOf(conv: ConversationNodeLike | undefined): string | null {\n if (conv === undefined || !Array.isArray(conv.blocks)) return null\n for (const b of conv.blocks) {\n const blk = b !== null && typeof b === 'object' ? b as { kind?: string; argsRaw?: unknown } : null\n if (blk === null || blk.kind !== 'tool-call') continue\n const s = summaryInArgs(parseCallArgs(blk.argsRaw))\n if (s !== null) return s\n }\n return null\n}\n\n/**\n * All tool-call names in an assistant conversation node, in order. The fold's surface node keeps `calls` only for TEXT-LESS replies,\n * so a reply carrying both text and calls recovers its call breadcrumb here through the conversation join.\n */\nexport function callNamesOf(conv: ConversationNodeLike | undefined): string[] {\n if (conv === undefined || !Array.isArray(conv.blocks)) return []\n const names: string[] = []\n for (const b of conv.blocks) {\n const blk = b !== null && typeof b === 'object' ? b as { kind?: string; name?: unknown } : null\n if (blk !== null && blk.kind === 'tool-call' && typeof blk.name === 'string') names.push(blk.name)\n }\n return names\n}\n","/**\n * The detail collections' pending/failed note — the split generation's\n * visible loading story (timelineSource.ts): while the first detail read is\n * in flight the detail-driven cards show this strip instead of a misleading\n * empty state, and a settled-without-data read arms the retry button (never\n * a spinner that never resolves, never a silent empty chart). Callers guard\n * the failed state on a retry callback being wired (an unwired failure keeps\n * the plain text).\n */\n\nimport { type ReactElement } from 'react'\nimport type { ViewKit } from '../viewkit'\n\nexport function makeDetailNote(kit: ViewKit): (props: {\n /** The pending kind: the first read in flight, or settled without data. */\n state: 'loading' | 'failed'\n /** The retry affordance for the failed read; absent = the note renders inert text. */\n onRetry?: () => void\n /** The container's style class: cards use the shared empty well, the browser its inline note strip. */\n className?: string\n}) => ReactElement {\n const { t } = kit\n return function DetailNote(props: {\n state: 'loading' | 'failed'\n onRetry?: () => void\n className?: string\n }): ReactElement {\n const cls = props.className ?? 'redline-empty'\n if (props.state === 'loading') return <div className={cls}>{t('detail.loading')}</div>\n return (\n <div className={cls}>\n {props.onRetry !== undefined\n ? <button type=\"button\" className=\"redline-br-retry hover:brightness-[1.15]\" onClick={props.onRetry}>{t('detail.loadFailed')}</button>\n : t('detail.loadFailed')}\n </div>\n )\n }\n}\n","/**\n * Capability judgement — WHICH action a row gets, decided by the UNDERLYING EVENT\n * TYPE, never by the display category (`AGENTS.md` §2.3.1, `docs/01` F7/F7.2,\n * `docs/05` A17).\n *\n * Why it must be by event type: the category is a presentation grouping (injected\n * content and skill injection are both `user/message` underneath), while the\n * platform's rewrite rules are stated per event type. Judging by category is how\n * the earlier attempt shipped an assistant-rewrite branch that could only fail at\n * runtime — the UI must never offer a button that is guaranteed to error.\n *\n * The four \"no action, with a reason\" cases, and the one that matters most:\n * · `system/message` / tool definitions — the host protects node 0 → `inert`\n * (no action BAR at all, not an empty one);\n * · `assistant/message` — replace requires `sourceEventSeqs` covering the\n * shadowed node, but an assistant message is FORBIDDEN to carry it. The two\n * rules are mutually exclusive, so there is no working write at all;\n * · a shadowed original — no longer a surface node, so it cannot be a target;\n * · a compacted-away row — out of reach.\n *\n * And the rule that makes repeat editing work: the REPLACEMENT body is a current\n * surface node, so it stays editable. `shadowed` therefore means \"superseded by a\n * later replacement\", not \"is a replacement\".\n *\n * ── Why this lives in `src/shared/**` and not in `src/redline/**` ──────────\n * The BROWSER needs this rule too (it decides which action a row renders), and the\n * client bundle must not import `src/redline/**` — that is the bundle-purity gate\n * (`docs/02` §4, `docs/05` A13), enforced mechanically by\n * `scripts/namespace-contract.mjs` face 9 and by the tsdown client-bundle purity\n * plugin. Proved by reverse verification: a temporary `import { ability } from\n * '../redline/eligibility'` in `src/client/services.ts` reddens face 9 immediately.\n * `src/shared/**` is the documented home for logic BOTH halves run, so the rule\n * lives here once — never duplicated per half (a duplicated button rule is exactly\n * how the earlier attempt shipped an assistant-rewrite branch that could only fail).\n *\n * Purity: no `node:*`, no DOM, no React.\n */\n\n/** The seven row classes the panel groups by (`docs/03` §2). */\nexport type RowClass = 'system' | 'tools' | 'user' | 'inject' | 'skill' | 'assistant' | 'tool'\n\n/**\n * The stable reason keys. The client maps each to the sentence of `docs/03` R4.7 —\n * the host never ships user-facing prose for a refusal.\n */\nexport type BlockReason = 'system-head' | 'shadowed' | 'assistant-immutable' | 'compacted'\n\n/** One row, as far as capability judgement is concerned. */\nexport interface SurfaceRow {\n readonly seq: number\n /** The durable event type (`user/message`, `assistant/message`, `tool/result`, `system/message`…). */\n readonly type: string\n readonly cat: RowClass\n /** Superseded by a later replacement → no longer on the surface. */\n readonly shadowed: boolean\n /** Is itself a replacement body (a current surface node). */\n readonly isReplacement: boolean\n /** Buried by compaction. */\n readonly compacted: boolean\n}\n\n/** The judgement for one row. */\nexport interface Ability {\n /** May this row's content be rewritten at all? */\n readonly canRewrite: boolean\n /** Host-protected: render NO action area (`docs/03` R2.1). */\n readonly inert: boolean\n readonly shadowed: boolean\n readonly isReplacement: boolean\n /** 被压缩埋掉(够不到,既不能编辑也不能作废)。 */\n readonly compacted: boolean\n /** The \"advanced\" class: `Edit` is hidden behind the advanced switch (`docs/03` R2.5). */\n readonly advancedOnly: boolean\n /**\n * 能不能把这一条标为「不要」(`docs/11` D65,用户 2026-10-08 选 A)。\n * 判据与\"能不能编辑\"**不同**:助手消息**改不了但可以作废** —— 那正是它唯一的处置手段。\n * 宿主保护的两类、已被接替的、被压缩埋掉的:不给(与\"不能编辑\"同一批)。\n */\n readonly canExclude: boolean\n /** Present exactly when `canRewrite` is false — including inert rows, which still need a reason line. */\n readonly blockReason?: BlockReason\n}\n\n/**\n * One row's actions.\n * · `drop` —— 丢弃这一条的本地改动(有改动时才出现);\n * · `exclude` —— 标为「不要」(作废,开启子会话时逐字声明);\n * · `unexclude` —— 取消作废标记。\n * `exclude` 与 `edit` **互斥**(同一条记录只有一份,标了就清掉改动)。\n */\nexport type RowAction = 'edit' | 'drop' | 'exclude' | 'unexclude'\n\nexport function ability(row: SurfaceRow): Ability {\n const inert = row.cat === 'system' || row.cat === 'tools'\n // New carriers are zero-history sessions: editing assistant text changes only the migration copy, never the old log.\n const canRewrite = !inert && !row.shadowed && !row.compacted\n const canExclude = !inert && !row.shadowed && !row.compacted\n return {\n canRewrite,\n canExclude,\n inert,\n compacted: row.compacted,\n shadowed: row.shadowed,\n isReplacement: row.isReplacement,\n advancedOnly: row.cat === 'tool',\n // docs/11 实施共识 §6: when two reasons apply, the assistant rule wins (the\n // sentences differ, the action set does not). Inert rows keep a reason too —\n // \"no action bar\" is the layout, and the reason is the explanation the row\n // still owes the reader.\n ...(canRewrite\n ? {}\n : {\n blockReason: inert ? 'system-head' : row.shadowed ? 'shadowed' : 'compacted',\n }),\n }\n}\n\n/**\n * Which durable types each presentation bucket can hold, per the host fold\n * (`src/host/fold.ts` `categoryOf` + the header-epoch rows for `system`/`tools`).\n *\n * WHY a bucket needs a list rather than one type: `skill` holds BOTH a skill\n * injection (`user/message`) and a skill LOAD, which the fold reclassifies into\n * the skill bucket \"but stays a tool result\". So the bucket cannot name one type.\n *\n * WHY that is still safe for the BUTTON SET: the action rule is invariant across\n * every type a bucket can hold (proved by `tests/edit/ability-buckets.spec.ts`:\n * for each bucket, all its listed types yield the same `canRewrite` / `inert` /\n * `advancedOnly` / `blockReason`). The row's category therefore decides the\n * actions, and the ONLY thing that needs the exact type — the editor's fields\n * (`docs/03` R3.2: a tool result edits result-text + `isError`, a user message\n * edits 正文 + thinking text) — is taken from `node.read`, which answers the real\n * durable type when the editor opens. No guessing anywhere.\n */\nexport const TYPES_BY_BUCKET: Readonly<Record<RowClass, readonly string[]>> = {\n system: ['system/message'],\n tools: ['request/header'],\n user: ['user/message'],\n inject: ['user/message'],\n skill: ['user/message', 'tool/result'],\n assistant: ['assistant/message'],\n tool: ['tool/result'],\n}\n\n/**\n * The representative durable type of a bucket — for callers that need SOMETHING\n * to feed {@link ability} when the exact type is not at hand. It is safe to use\n * for the action set (the buckets are action-invariant) and **unfit for the\n * editor's fields** — use the type `node.read` returns for that.\n */\nexport function durableTypeOf(cat: RowClass): string {\n return TYPES_BY_BUCKET[cat][0] ?? 'user/message'\n}\n\n/**\n * The actions a row offers.\n *\n * ⚠️ 2026-10-09(`docs/03` R4.8):**删除与编辑不再互斥** —— 旧口径\"标了就清掉改动 /\n * 改了就把标记清掉\"已作废,删除标记与编辑正文是两个独立字段。\n * 删除态仍给「丢弃这条改动」:那对应「已删除编辑稿 ──丢弃这条改动──▶ 已删除原文」\n * (只清正文、保持删除态),所以它只属于**可编辑且有改稿**的行。\n */\nexport function rowActions(a: Ability, hasLocalEdit: boolean, deleted = false): readonly RowAction[] {\n if (a.inert) return []\n if (deleted) {\n const kept: RowAction[] = ['unexclude']\n if (a.canRewrite && hasLocalEdit) kept.push('drop')\n return kept\n }\n if (a.shadowed || a.compacted) return []\n const actions: RowAction[] = []\n if (a.canRewrite) actions.push('edit')\n if (a.canExclude) actions.push('exclude')\n // 「丢弃这条改动」只属于**可编辑**的行(不能编辑的行根本不该有本地改动;这里有防守意义)。\n if (a.canRewrite && hasLocalEdit) actions.push('drop')\n return actions\n}\n","/**\n * The editing UI the demo fixes: a row's action bar, and the editor that expands\n * **under that row** (never a modal — the user is comparing against the context,\n * `docs/03` R3.1).\n *\n * The contract these two components keep, straight from `docs/03`'s current-demo\n * sections and `docs/11` D15/D16/D17/D19:\n *\n * · Row actions are **only** `编辑` (plus `丢弃这条改动` while a local edit exists).\n * Host-protected rows render **no action area at all**; rows that cannot be\n * rewritten render **one sentence** and no action (`R2.1`/`R2.3`).\n * · The marker `已改(本地)` appears **once**, beside the seq (`R4.1`, D20).\n * · Fields are keyed off the **durable type** `node.read` answered (`R3.2`): a tool\n * result edits result-text + `isError`; everything else edits 正文 + a thinking\n * text folded under 高级.\n * · The editor is prefilled with the FULL text — and, after a save, with the saved\n * version (`effectiveText`), because that is the version in effect (D16).\n * · Saving writes only the plugin's local store, and the field carries the\n * destination marker so nobody mistakes it for \"the model can see this\" (`R3.3`).\n * · `Esc` cancels, `Cmd/Ctrl+Enter` submits; a refusal keeps the input and shows\n * the reason (`R3.5`).\n */\n\nimport { useEffect, useRef, useState, type ReactElement, type ChangeEvent, type KeyboardEvent } from 'react'\nimport type { ViewKit } from '../viewkit'\nimport { rowActions, type Ability } from '../../shared/redline-ability'\n\n/** Why a row has no action — mapped to a sentence by the caller's dictionary. */\nconst REASON_KEY: Record<string, string> = {\n 'assistant-immutable': 'redline.reason.assistant',\n 'system-head': 'redline.reason.system',\n 'shadowed': 'redline.reason.shadowed',\n 'compacted': 'redline.reason.compacted',\n}\n\n/** The editor's submission. */\nexport interface RedlineSubmit {\n readonly text: string\n readonly reasoning: string\n readonly isError: boolean\n}\n\n/**\n * A row's action bar.\n *\n * @returns `null` for a host-protected row: the area is not rendered at all\n * (an empty action strip would look like a missing feature, `docs/03` R2.1).\n */\nexport function makeRedlineActions(kit: ViewKit): (props: {\n seq: number\n ability: Ability\n hasLocalEdit: boolean\n /** 这一条是否已被删除(`docs/03` R4.8)。与 `hasLocalEdit` **不**互斥:删除后仍可带改稿。 */\n deleted: boolean\n /** The advanced switch, only meaningful for `advancedOnly` rows (`R2.5`). */\n advanced: boolean\n busy: boolean\n onEdit: () => void\n onDrop: () => void\n /** 标为「不要」/ 取消标记。 */\n onExclude: () => void\n onUnexclude: () => void\n /**\n * 这一行**最近一次动作被拒**的稳定码(`redline/*`)。\n * ⚠️ 真机踩到:`删除` 没有编辑器可依附,若只把错误丢给编辑器,拒绝就被吞掉了\n * (`docs/03` R3.5 要求\"拒绝必须说出来\")。所以动作条自己也要能报。\n */\n errorCode: string | null\n}) => ReactElement | null {\n const { t } = kit\n return function RedlineActions(props): ReactElement | null {\n const { ability } = props\n if (ability.inert) return null\n const actions = rowActions(ability, props.hasLocalEdit, props.deleted)\n const hiddenAsAdvanced = ability.advancedOnly && !props.advanced && (actions.includes('edit') || actions.includes('exclude'))\n /**\n * 改不了时的\"为什么\"徽章:助手消息要它(说明为什么没有「编辑」),\n * 但**已标为「不要」的行不要**(那时行上已经有「已标为不要」了,再来一句原因就是噪音)。\n */\n const reasonKey = REASON_KEY[ability.blockReason ?? ''] ?? 'redline.reason.other'\n const reasonChip = actions.includes('unexclude')\n ? null\n : <span className=\"redline-chip-soft\" title={t(reasonKey)}>{t(reasonKey)}</span>\n return (\n <div className=\"redline-act\" data-rowactions={props.seq}>\n <span className=\"redline-act-seq\">{'#' + String(props.seq)}</span>\n {props.hasLocalEdit\n ? <span className=\"redline-chip-local\" title={t('redline.local.tip')}>{t('redline.local')}</span>\n : null}\n {props.deleted\n ? <span className=\"redline-chip-excluded\" title={t('redline.excluded.tip')}>{t('redline.excluded')}</span>\n : null}\n {hiddenAsAdvanced\n ? <span className=\"redline-chip-soft\" title={t('redline.advanced.tip')}>{t('redline.advanced')}</span>\n : actions.includes('edit')\n ? <button type=\"button\" className=\"redline-btn\" disabled={props.busy} onClick={props.onEdit}>{t('redline.edit')}</button>\n : reasonChip}\n {actions.includes('exclude') && !hiddenAsAdvanced\n ? <button type=\"button\" className=\"redline-btn redline-btn-quiet\" title={t('redline.exclude.tip')} disabled={props.busy} onClick={props.onExclude}>{t('redline.exclude')}</button>\n : null}\n {actions.includes('unexclude') && !hiddenAsAdvanced\n ? <button type=\"button\" className=\"redline-btn redline-btn-quiet\" title={t('redline.unexclude.tip')} disabled={props.busy} onClick={props.onUnexclude}>{t('redline.unexclude')}</button>\n : null}\n {actions.includes('drop')\n ? <button type=\"button\" className=\"redline-btn redline-btn-quiet\" disabled={props.busy} onClick={props.onDrop}>{t('redline.drop')}</button>\n : null}\n {props.errorCode === null\n ? null\n : <span className=\"redline-act-err\" role=\"alert\">{t('redline.err.' + props.errorCode.replace('redline/', ''))}</span>}\n </div>\n )\n }\n}\n\n/**\n * The inline editor. Mounted by the row when it is the open editor, so its local\n * state lives exactly as long as the row is being edited.\n */\nexport function makeRedlineEditor(kit: ViewKit): (props: {\n seq: number\n /** The durable type `node.read` answered — this is what picks the fields. */\n type: string\n /** The version in effect (the original, or your saved edit). */\n initial: RedlineSubmit\n busy: boolean\n /**\n * Set when editing is not allowed at all right now: the demo's own gate\n * (`turnOpen || !live`) disables `保存` and shows the sentence, rather than\n * letting the click fail.\n */\n blocked: 'turn-open' | 'not-live' | null\n /** The stable refusal code to display, if the last attempt failed. */\n errorCode: string | null\n onSubmit: (edit: RedlineSubmit) => void\n onCancel: () => void\n}) => ReactElement {\n const { t } = kit\n return function RedlineEditor(props): ReactElement {\n const [text, setText] = useState(props.initial.text)\n const [reasoning, setReasoning] = useState(props.initial.reasoning)\n const [isError, setIsError] = useState(props.initial.isError)\n const areaRef = useRef<HTMLTextAreaElement | null>(null)\n // A different row's values must never leak into this editor's state.\n useEffect(() => {\n setText(props.initial.text)\n setReasoning(props.initial.reasoning)\n setIsError(props.initial.isError)\n }, [props.seq])\n useEffect(() => { areaRef.current?.focus() }, [])\n\n const isToolResult = props.type === 'tool/result'\n const multiParagraph = props.initial.text.includes('\\n')\n const submit = (): void => { props.onSubmit({ text, reasoning: isToolResult ? '' : reasoning, isError }) }\n const onKey = (ev: KeyboardEvent<HTMLDivElement>): void => {\n if (ev.key === 'Escape') { ev.preventDefault(); props.onCancel(); return }\n if (ev.key === 'Enter' && (ev.metaKey || ev.ctrlKey)) { ev.preventDefault(); submit() }\n }\n const errKey = props.errorCode === null ? null : `redline.err.${props.errorCode.replace('redline/', '')}`\n const blockedKey = props.blocked === 'turn-open'\n ? 'redline.blocked.turnOpen'\n : props.blocked === 'not-live' ? 'redline.blocked.notLive' : null\n\n return (\n <div className=\"redline-editor\" onKeyDown={onKey}>\n {multiParagraph ? <div className=\"redline-editor-note\">{t('redline.multiParagraph')}</div> : null}\n <label className=\"redline-editor-label\" htmlFor={`redline-ed-${String(props.seq)}`}>\n {isToolResult ? t('redline.field.result') : t('redline.field.body')}\n <span className=\"redline-dest\">{t('redline.dest.local')}</span>\n </label>\n <textarea\n id={`redline-ed-${String(props.seq)}`}\n ref={areaRef}\n className=\"redline-editor-text\"\n value={text}\n rows={6}\n onChange={(ev: ChangeEvent<HTMLTextAreaElement>) => { setText(ev.target.value) }}\n />\n {isToolResult\n ? (\n <label className=\"redline-editor-check\">\n <input type=\"checkbox\" checked={isError} onChange={(ev: ChangeEvent<HTMLInputElement>) => { setIsError(ev.target.checked) }} />\n {t('redline.field.isError')}\n <span className=\"redline-dest\">{t('redline.dest.local')}</span>\n </label>\n )\n : (\n <details className=\"redline-editor-adv\">\n <summary>{t('redline.field.advanced')}</summary>\n <label className=\"redline-editor-label\" htmlFor={`redline-edr-${String(props.seq)}`}>\n {t('redline.field.thinking')}\n <span className=\"redline-dest\">{t('redline.dest.local')}</span>\n </label>\n <textarea\n id={`redline-edr-${String(props.seq)}`}\n className=\"redline-editor-text\"\n value={reasoning}\n rows={3}\n onChange={(ev: ChangeEvent<HTMLTextAreaElement>) => { setReasoning(ev.target.value) }}\n />\n </details>\n )}\n {blockedKey !== null ? <div className=\"redline-editor-blocked\">{t(blockedKey)}</div> : null}\n {errKey !== null ? <div className=\"redline-editor-err\" role=\"alert\">{t(errKey)}</div> : null}\n {/* 动作区**没有浮标**(用户 2026-10-06 红框截图:那个「?」压在「高级:思考文本」上)。\n 它当初是给**批注**动作做说明的角标(`docs/10` M05-40),批注已整批删除;\n 剩下的说明改挂按钮自身的 `title` —— 不占版面,鼠标停上去照样看得到。 */}\n <div className=\"redline-editor-actions\">\n <button\n type=\"button\"\n className=\"redline-btn\"\n title={t('redline.save.tip')}\n disabled={props.busy || blockedKey !== null}\n onClick={submit}\n >{t('redline.save')}</button>\n <button type=\"button\" className=\"redline-btn redline-btn-quiet\" onClick={props.onCancel}>{t('redline.cancel')}</button>\n </div>\n </div>\n )\n }\n}\n","/**\n * The stable error-code table shared by BOTH halves — the plugin's outward\n * contract.\n *\n * Why a frozen table instead of ad-hoc strings: the client maps a code to the\n * localized human wording, and the tests assert the code (never the\n * message). A code that changes shape silently turns \"这一条改不了,因为…\" into\n * a raw provider error, which is exactly the failure this project exists to\n * avoid.\n *\n * The `redline/` prefix keeps these out of any host or upstream namespace.\n */\n\n/** Every code the channel can answer with. */\nexport const REDLINE_ERROR = {\n /** The body was not JSON, or lacked a usable `op`/`sessionId`. */\n badRequest: 'redline/bad-request',\n /** The op is not in the channel's table (an older client, or a typo). */\n unknownOp: 'redline/unknown-op',\n /** The target session has no live Agent in this process (`docs/01` F9). */\n notLive: 'redline/not-live',\n /** The session has an open turn: edits must land on a turn boundary (`docs/01` F8). */\n turnOpen: 'redline/turn-open',\n /** No local draft exists for that seq. */\n noDraft: 'redline/no-draft',\n /** The draft is identical to the version already in effect. */\n noChange: 'redline/no-change',\n /** The draft empties both the visible text and the thinking text. */\n emptyContent: 'redline/empty-content',\n /** 首条任务是人写的,空的不能开子会话(M5-04:不产生任何 AI 生成内容)。 */\n emptyTask: 'redline/empty-task',\n /** 这台运行时没有可用的子会话服务:别装作能开,如实说\"只能人工搬运\"。 */\n noSubagents: 'redline/no-subagents',\n /** A child provider returned without the child identity required to prove creation. */\n childStartUnconfirmed: 'redline/child-start-unconfirmed',\n /** Official and bare child creation both failed; no child was reported as started. */\n childStartFailed: 'redline/child-start-failed',\n /** Drafts changed after the user reviewed the confirmation; they must review again. */\n draftsChanged: 'redline/drafts-changed',\n /** `assistant/message` cannot be rewritten on this platform (`docs/01` F7.2). */\n assistantImmutable: 'redline/assistant-immutable',\n /** The target is no longer a surface node (it was replaced) (`docs/01` F7). */\n shadowed: 'redline/shadowed',\n /**\n * The target seq is not in this session's log at all (stale client, trimmed\n * window, wrong session). ⚠️ Distinct from {@link shadowed}: the log keeps a\n * replaced original, so \"not found\" and \"superseded\" are different facts and\n * used to be reported as the same one (Code Review P1-1).\n */\n notFound: 'redline/not-found',\n /** The draft file on disk is not readable as our format (E13: loud, never silently empty). */\n draftCorrupt: 'redline/draft-corrupt',\n /** The draft file's `schemaVersion` is not one this build understands. */\n draftSchema: 'redline/draft-schema',\n /** The origin ledger file is unreadable (deleted/corrupt/hand-edited). */\n originCorrupt: 'redline/origin-corrupt',\n /** The origin ledger's `schemaVersion` is not one this build understands. */\n originSchema: 'redline/origin-schema',\n /** A range argument was half-given or reversed. */\n badRange: 'redline/bad-range',\n /** The full text of that version cannot be read back on this platform. */\n historyUnavailable: 'redline/history-unavailable',\n /** The underlying event type has no rewrite path at all. */\n unsupportedType: 'redline/unsupported-type',\n /** An op handler threw. Never a platform code — the message carries that. */\n internal: 'redline/internal',\n /** CLIENT-SIDE: the call never produced a valid answer (offline, HTTP error, bad body). */\n transport: 'redline/transport',\n} as const\n\nexport type RedlineErrorCode = (typeof REDLINE_ERROR)[keyof typeof REDLINE_ERROR]\n\n/**\n * Short English wire text per code. Deliberately NOT the user-facing sentence:\n * the client owns the localized wording (`docs/03` R4.7), and a wire message\n * that reads like UI copy is how two different sentences for one condition get\n * shipped.\n */\nexport const REDLINE_ERROR_MESSAGE: Readonly<Record<RedlineErrorCode, string>> = {\n [REDLINE_ERROR.badRequest]: 'body is not a valid redline call',\n [REDLINE_ERROR.unknownOp]: 'unknown redline op',\n [REDLINE_ERROR.notLive]: 'session is not live in this process',\n [REDLINE_ERROR.turnOpen]: 'the session has an open turn',\n [REDLINE_ERROR.noDraft]: 'no local draft for that seq',\n [REDLINE_ERROR.noChange]: 'the draft does not change the effective text',\n [REDLINE_ERROR.emptyContent]: 'the draft has no content at all',\n [REDLINE_ERROR.emptyTask]: 'the first task must be written by the human',\n [REDLINE_ERROR.noSubagents]: 'this runtime exposes no subagents service',\n [REDLINE_ERROR.childStartUnconfirmed]: 'the child provider did not return a child identity',\n [REDLINE_ERROR.childStartFailed]: 'the child could not be created by either available provider',\n [REDLINE_ERROR.draftsChanged]: 'the local edits changed after confirmation was prepared',\n [REDLINE_ERROR.assistantImmutable]: 'assistant/message cannot be rewritten',\n [REDLINE_ERROR.shadowed]: 'that seq is no longer a surface node',\n [REDLINE_ERROR.notFound]: 'that seq is not in this session log',\n [REDLINE_ERROR.draftCorrupt]: 'the local draft file is not readable',\n [REDLINE_ERROR.draftSchema]: 'the local draft file has an unsupported schema version',\n [REDLINE_ERROR.originCorrupt]: 'the local origin ledger is not readable',\n [REDLINE_ERROR.originSchema]: 'the local origin ledger has an unsupported schema version',\n [REDLINE_ERROR.badRange]: 'bad void range',\n [REDLINE_ERROR.historyUnavailable]: 'the full text of that version is not readable',\n [REDLINE_ERROR.unsupportedType]: 'this event type has no rewrite path',\n [REDLINE_ERROR.internal]: 'the op handler failed',\n [REDLINE_ERROR.transport]: 'the request did not reach the host',\n}\n\n/** Whether `code` is one of ours (used by the client to pick the R4.7 wording). */\nexport function isRedlineErrorCode(code: string): code is RedlineErrorCode {\n return Object.values(REDLINE_ERROR).includes(code as RedlineErrorCode)\n}\n","/**\n * Local edits — the plugin's own store, and the WHOLE of what a \"save\" does\n * (`docs/11` D15, `AGENTS.md` §1: every save is temporary).\n *\n * The hard constraint, in one sentence: pressing save writes a JSON file under\n * our data directory and **nothing else** — the session log is untouched, so the\n * current session's model sees exactly what it saw before. The one and only write\n * point is opening a child session (M5), which carries these edits verbatim into\n * the new session's first message.\n *\n * Facts this module owns:\n * · ONE local edit per row. Saving again OVERWRITES it (never stacks), and the\n * latest version is the one that would be carried forward.\n * · The version in effect is what the row DISPLAYS, what the editor PREFILLS and\n * what the \"no substantive change\" check compares against (`docs/11` D16).\n * That is why editing again after a save shows your saved text, and why\n * editing back to the original counts as a change.\n * · A corrupt file is an explicit error, never a silently empty table (E13).\n *\n * ── Why this lives in `src/shared/**` and not in `src/redline/**` ──────────\n * The BROWSER needs these rules too: it DISPLAYS the version in effect, PREFILLS\n * the editor from it, and labels a row `已改(本地)` — all three must use the same\n * answer the host uses when it decides \"no substantive change\". Two copies of\n * \"what is in effect\" is precisely how a UI starts disagreeing with the gate that\n * refuses the save.\n *\n * The bundle-purity gate (`docs/02` §4, `docs/05` A13, `namespace-contract` face 9,\n * plus tsdown's client-bundle purity plugin) forbids `src/client/**` from importing\n * `src/redline/**` at runtime — reverse-verified, same as `redline-ability.ts`.\n *\n * Purity: no `node:*` — the host half owns the file system and passes text in/out.\n */\n\nimport { REDLINE_ERROR } from './redline-errors'\nimport { REDLINE_DATA_DIR_NAME } from './redline-paths'\n\n/** Our on-disk format version. Only bumped with a migration; there is none yet. */\nexport const REDLINE_DRAFT_SCHEMA_VERSION = 1\n\n/** One row's local edit. `text` is the complete replacement body (never a preview). */\nexport interface LocalEdit {\n readonly seq: number\n readonly text: string\n readonly reasoning: string\n readonly isError: boolean\n /** When this version was saved (ISO-8601). The client formats it. */\n readonly updatedAt: string\n /** Display context: the row's category and tool/file name, when known. */\n readonly cat?: string\n readonly name?: string\n /**\n * 「删除」标记(`docs/03` R4.8 / `docs/13` §7):这一条**不写进新会话**。\n *\n * ⚠️ 与编辑正文**独立存储** —— 删一条**不清空**它的编辑稿,取消删除要能原样恢复整条记录。\n * 旧实现(`excluded`)是\"整条覆盖 + 清空正文\",那种互斥语义**已作废**。\n */\n readonly deleted?: boolean\n /**\n * 旧名字的**兼容镜像**:与 `deleted` 同写同清(历史草稿与尚未改名的调用方仍按这个字段名过滤)。\n * ⚠️ 不是\"废弃 API\"的注解写法 —— 命名空间契约的 lint 禁止仓库内**使用**被标 `@deprecated` 的成员,\n * 而这个镜像在被调用方改名(归 C3/C6)之前必须在本文件里读写。退役时把两处一起删。\n */\n readonly excluded?: boolean\n /**\n * 旧实现**先清空正文**再写删除标记 ⟹ 那条\"删除前的编辑\"已经不可能恢复。\n * 迁移时如实置位,让界面能说\"这条旧标记无法恢复删除前的编辑\"(R4.8 硬要求 5),\n * 而不是伪造一份正文、也不是静默丢掉标记。用户重新编辑后此位清除。\n */\n readonly legacyBodyLost?: true\n}\n\n/** All local edits of one session, keyed by `String(seq)`. */\nexport type DraftTable = Readonly<Record<string, LocalEdit>>\n\n/** The minimal surface row this module needs: the FULL text plus its error mark. */\nexport interface SurfaceRowText {\n readonly seq: number\n readonly text: string\n readonly reasoning?: string\n readonly isError?: boolean\n}\n\n/**\n * Why a save was refused. Derived from the ONE code table (`redline-errors.ts`)\n * rather than re-spelled here: a second spelling of a wire code is how the client\n * ends up with a case it cannot map.\n */\n/**\n * 一条记录是否**带编辑正文**。\n *\n * 判据用\"正文或思考文本非空\",而不是另加一个布尔字段:保存路径的 `checkChange` 会拒绝\n * `text === '' && reasoning === ''`(`empty-content`),所以**能存下来的编辑一定有正文**,\n * 而\"空正文\"只能来自删除墓碑。这样\"已删除原文 / 已删除编辑稿\"两态天然可分。\n */\nexport function hasEditBody(edit: LocalEdit): boolean {\n return edit.text !== '' || edit.reasoning !== ''\n}\n\n/** 按固定字段顺序重建一条记录(保证序列化与 revision 稳定,不带上游对象的键序)。 */\nfunction withMarks(entry: LocalEdit, deleted: boolean, legacyBodyLost: boolean): LocalEdit {\n return {\n seq: entry.seq,\n text: entry.text,\n reasoning: entry.reasoning,\n isError: entry.isError,\n updatedAt: entry.updatedAt,\n ...entry.cat === undefined ? {} : { cat: entry.cat },\n ...entry.name === undefined ? {} : { name: entry.name },\n ...deleted ? { deleted: true, excluded: true } : {},\n ...legacyBodyLost ? { legacyBodyLost: true } : {},\n }\n}\n\n/**\n * 把某一行标为**删除**:这一条不写进新会话(`docs/03` R4.8 / `docs/13` §7)。\n *\n * ⚠️ **保留**该行已有的编辑正文与显示元数据 —— 取消删除要能原样恢复整条记录。\n * 只写我们自己这份表;当前会话一个字都不写(硬约束,`docs/11` D15)。\n */\nexport function putDeleted(table: DraftTable, seq: number, updatedAt: string): DraftTable {\n const key = String(seq)\n // `Readonly<Record<string, LocalEdit>>` 把索引类型成 `LocalEdit`(不是 `| undefined`)⟹ 只能\n // 用 `Object.hasOwn` 问\"到底有没有这条\",`=== undefined` 会既骗读者又被 lint 抓(同 dropEdit 的口径)。\n const existing: LocalEdit | undefined = Object.hasOwn(table, key) ? table[key] : undefined\n const base: LocalEdit = existing ?? { seq, text: '', reasoning: '', isError: false, updatedAt }\n return { ...table, [key]: withMarks(base, true, existing?.legacyBodyLost === true) }\n}\n\n/**\n * 取消删除:**回到删除之前的状态**(R4.8 关键转换)。\n * 有编辑正文 ⟹ 回到\"已编辑\"(正文原样);没有正文 ⟹ 回到\"原文\"(整条记录去掉)。\n */\nexport function unmarkDeleted(table: DraftTable, seq: number): DraftTable {\n const key = String(seq)\n if (!Object.hasOwn(table, key)) return table\n const existing = table[key]\n if (!hasEditBody(existing)) {\n // 没有正文可留 ⟹ 就是\"原文\"。\n return Object.fromEntries(Object.entries(table).filter(([k]) => k !== key))\n }\n return { ...table, [key]: withMarks(existing, false, false) }\n}\n\n/** 被删除的 seq,升序。 */\nexport function deletedSeqsOf(table: DraftTable): number[] {\n return Object.values(table).filter(entry => isDeleted(table, entry.seq)).map(entry => entry.seq).sort((a, b) => a - b)\n}\n\n/** Whether a row carries the delete mark (`deleted`, or the compat mirror `excluded`). */\nexport function isDeleted(table: DraftTable, seq: number): boolean {\n const key = String(seq)\n if (!Object.hasOwn(table, key)) return false\n const entry = table[key]\n return entry.deleted === true || entry.excluded === true\n}\n\n/**\n * 旧名字(`putExcluded`)。语义**已改变**:不再清空正文(R4.8 硬要求 3 作废了互斥)。\n * 委托给 `putDeleted`;调用方改名归 C3/C6。\n * ⚠️ 不写 `@deprecated` 注解:lint 会因此拒绝任何**使用**它的调用方,而唯一剩下的使用者是\n * 尚未获准改动的那几个文件。退役时连名字一起删。\n */\nexport function putExcluded(table: DraftTable, seq: number, updatedAt: string): DraftTable {\n return putDeleted(table, seq, updatedAt)\n}\n\n/** 旧名字(`deletedSeqsOf`)——同一口径的委托;宿主已改用新名字,退役归 C3/C6。 */\nexport function excludedSeqsOf(table: DraftTable): number[] {\n return deletedSeqsOf(table)\n}\n\nexport type ChangeRefusal = typeof REDLINE_ERROR.emptyContent | typeof REDLINE_ERROR.noChange\n\nexport type ChangeVerdict = { readonly ok: true } | { readonly ok: false; readonly code: ChangeRefusal }\n\nexport function emptyDrafts(): DraftTable {\n return {}\n}\n\n/**\n * A session id → a file-name-safe key.\n *\n * ⚠️ 只做百分号编码是不够的(Code Review P2):\n * · macOS 默认**大小写不敏感** ⟹ `Session-A` 与 `session-a` 会落到同一个文件(串档);\n * · 超长 id 会撞 255 字节的文件名上限 ⟹ `ENAMETOOLONG` ⟹ 保存直接失败。\n * 所以先做一次稳定的短哈希(FNV-1a 32 位,纯函数、无 `node:*`:宿主半边与测试都能用),\n * 再把可读前缀拼上 —— 既不会串档,也绝不会超长。可读前缀只为排障时认得出是哪个会话。\n */\nexport function stableKeyOf(sessionId: string): string {\n let hash = 0x811c9dc5\n for (let i = 0; i < sessionId.length; i += 1) {\n hash ^= sessionId.charCodeAt(i)\n // FNV 质数 16777619,用移位避免大整数精度问题。\n hash = (hash + ((hash << 1) + (hash << 4) + (hash << 7) + (hash << 8) + (hash << 24))) >>> 0\n }\n return hash.toString(16).padStart(8, '0')\n}\n\n/** The on-disk name of one session's draft file. */\nexport function draftFileName(sessionId: string): string {\n const readable = sessionId.replace(/[^A-Za-z0-9_-]/g, '_').slice(0, 40)\n return `redline-drafts-${readable}-${stableKeyOf(sessionId)}.json`\n}\n\n/** Our data directory's name, re-exported so the host has one source for it. */\nexport { REDLINE_DATA_DIR_NAME }\n\n/** The edit for a row, if any. */\nexport function editOf(table: DraftTable, seq: number): LocalEdit | undefined {\n const entry = Object.values(table).find(candidate => candidate.seq === seq)\n // ⚠️ 判据是\"**有没有编辑正文**\",不是\"有没有删除标记\"(`docs/03` R4.8):\n // · 删除墓碑(没有正文)不是编辑 —— 若当成编辑返回,`effectiveText` 会给出空串,行渲染成空白;\n // · 「已删除编辑稿」(有正文 + 有删除标记)**是**编辑 —— 取消删除后要原样恢复它。\n return entry === undefined || !hasEditBody(entry) ? undefined : entry\n}\n\n/**\n * 旧名字(`isDeleted`)——同一口径,含 `deleted` 与兼容镜像字段。\n * 客户端 `browser.tsx` 还在用它(那个文件不在本卡允许改清单里)⟹ 退役归 C3/C6。\n */\nexport function isExcluded(table: DraftTable, seq: number): boolean {\n return isDeleted(table, seq)\n}\n\n/** Whether a row carries a local edit. */\nexport function hasLocalEdit(table: DraftTable, seq: number): boolean {\n return editOf(table, seq) !== undefined\n}\n\n/**\n * Insert or OVERWRITE the edit for one row. One row, one edit — never two.\n *\n * ⚠️ 覆盖**不解除删除标记**(`docs/03` R4.8 硬要求 3:互斥已作废)⟹ 编辑一条已删除的行\n * 得到的仍是\"已删除编辑稿\"。同时清掉 `legacyBodyLost`:用户给了新正文,那条\"旧编辑已丢失\"\n * 的提示不再适用(继续显示会说假话)。\n */\nexport function putEdit(table: DraftTable, edit: LocalEdit): DraftTable {\n const key = String(edit.seq)\n if (!Object.hasOwn(table, key) || !isDeleted(table, edit.seq)) {\n return { ...table, [key]: edit }\n }\n return { ...table, [key]: withMarks(edit, true, false) }\n}\n\n/** Forget one row's edit — but a **deleted** row keeps its tombstone (R4.8). */\nexport function dropEdit(table: DraftTable, seq: number): DraftTable {\n const key = String(seq)\n // Existence, not value: a `Record<string, T>` indexes as `T`, so `=== undefined`\n // is both a lie to the reader and a lint error. `Object.hasOwn` is the honest check.\n if (!Object.hasOwn(table, key)) return table\n const existing = table[key]\n if (isDeleted(table, seq)) {\n // 「已删除编辑稿 ──丢弃这条改动──▶ 已删除原文」:只清正文,**保持删除态**。\n return { ...table, [key]: withMarks({ ...existing, text: '', reasoning: '', isError: false }, true, false) }\n }\n // Built immutably (no `delete` on a computed key), so callers can diff by identity.\n return Object.fromEntries(Object.entries(table).filter(([k]) => k !== key))\n}\n\n/** The text in effect for a row: the local edit if there is one, else the original. */\nexport function effectiveText(row: SurfaceRowText, table: DraftTable): string {\n const edit = editOf(table, row.seq)\n return edit === undefined ? row.text : edit.text\n}\n\n/** The thinking text in effect (an edit that empties it stays empty). */\nexport function effectiveReasoning(row: SurfaceRowText, table: DraftTable): string {\n const edit = editOf(table, row.seq)\n return edit === undefined ? (row.reasoning ?? '') : edit.reasoning\n}\n\n/** The error mark in effect. */\nexport function effectiveIsError(row: SurfaceRowText, table: DraftTable): boolean {\n const edit = editOf(table, row.seq)\n return edit === undefined ? (row.isError ?? false) : edit.isError\n}\n\n/**\n * Decide whether a proposed edit is a substantive change — the demo's rule\n * (`demo/demo.js` `submitEditor`), locked by the `drafts` spec:\n * · both the visible text and the thinking text empty → `empty-content`;\n * · identical to the version IN EFFECT (text, thinking text and error mark all\n * equal) → `no-change`;\n * · otherwise it is a change — including \"change it back to the original\",\n * because after a save the version in effect IS the saved one.\n */\nexport function checkChange(\n row: SurfaceRowText,\n table: DraftTable,\n next: { readonly text: string; readonly reasoning: string; readonly isError: boolean },\n): ChangeVerdict {\n if (next.text === '' && next.reasoning === '') return { ok: false, code: REDLINE_ERROR.emptyContent }\n if (\n next.text === effectiveText(row, table)\n && next.reasoning === effectiveReasoning(row, table)\n && next.isError === effectiveIsError(row, table)\n ) {\n return { ok: false, code: REDLINE_ERROR.noChange }\n }\n return { ok: true }\n}\n\n/** The wire form of one draft file. */\nexport interface DraftFile {\n readonly schemaVersion: number\n readonly sessionId: string\n readonly edits: readonly LocalEdit[]\n}\n\n/** Serialize a table for disk: deterministic (sorted by seq), newline-terminated. */\nexport function serializeDrafts(sessionId: string, table: DraftTable): string {\n const edits = Object.values(table).sort((a, b) => a.seq - b.seq)\n const file: DraftFile = { schemaVersion: REDLINE_DRAFT_SCHEMA_VERSION, sessionId, edits }\n return `${JSON.stringify(file, null, 2)}\\n`\n}\n\n/**\n * A deterministic version token for the exact draft set a child-confirmation dialog\n * reviewed. It is a stale-confirmation guard, not an authorization mechanism: the\n * route remains authenticated by the harness. The canonical serialization means\n * record order cannot change the version, while any carried field can.\n */\nexport function draftRevisionOf(sessionId: string, table: DraftTable): string {\n const source = serializeDrafts(sessionId, table)\n let hash = 0x811c9dc5\n for (let i = 0; i < source.length; i += 1) {\n hash ^= source.charCodeAt(i)\n hash = (hash + ((hash << 1) + (hash << 4) + (hash << 7) + (hash << 8) + (hash << 24))) >>> 0\n }\n return `d1-${hash.toString(16).padStart(8, '0')}`\n}\n\nexport type ParseResult =\n | { readonly ok: true; readonly table: DraftTable }\n | { readonly ok: false; readonly code: string; readonly message: string }\n\n/** A missing/empty file is an empty table; anything unreadable is a loud refusal. */\nexport function parseDrafts(raw: string | null | undefined, expectedSessionId?: string): ParseResult {\n if (raw === null || raw === undefined || raw.trim() === '') return { ok: true, table: {} }\n let parsed: unknown\n try {\n parsed = JSON.parse(raw)\n } catch {\n return { ok: false, code: REDLINE_ERROR.draftCorrupt, message: 'the draft file is not valid JSON' }\n }\n if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {\n return { ok: false, code: REDLINE_ERROR.draftCorrupt, message: 'the draft file is not an object' }\n }\n const file = parsed as Partial<DraftFile>\n // 串档防线(Code Review P2):文件里记着它是哪个会话的草稿。文件名被改过、或\n // 两个会话的 id 在文件系统上收敛到同一个名字时,这里必须**拒绝**而不是当成本会话的草稿。\n if (expectedSessionId !== undefined && file.sessionId !== expectedSessionId) {\n return {\n ok: false,\n code: REDLINE_ERROR.draftCorrupt,\n message: `the draft file belongs to another session (${String(file.sessionId)})`,\n }\n }\n if (file.schemaVersion !== REDLINE_DRAFT_SCHEMA_VERSION) {\n return {\n ok: false,\n code: REDLINE_ERROR.draftSchema,\n message: `unsupported draft schemaVersion: ${String(file.schemaVersion)}`,\n }\n }\n if (!Array.isArray(file.edits)) {\n return { ok: false, code: REDLINE_ERROR.draftCorrupt, message: 'the draft file has no edits array' }\n }\n const table: Record<string, LocalEdit> = {}\n for (const entry of file.edits) {\n if (entry === null || typeof entry !== 'object') {\n return { ok: false, code: REDLINE_ERROR.draftCorrupt, message: 'a draft entry is not an object' }\n }\n const edit = entry as Partial<LocalEdit>\n if (typeof edit.seq !== 'number' || !Number.isInteger(edit.seq) || edit.seq < 0) {\n return { ok: false, code: REDLINE_ERROR.draftCorrupt, message: 'a draft entry has no usable seq' }\n }\n if (typeof edit.text !== 'string' || typeof edit.reasoning !== 'string' || typeof edit.isError !== 'boolean') {\n return { ok: false, code: REDLINE_ERROR.draftCorrupt, message: `draft #${edit.seq} has ill-typed fields` }\n }\n if (edit.excluded !== undefined && typeof edit.excluded !== 'boolean') {\n return { ok: false, code: REDLINE_ERROR.draftCorrupt, message: `draft #${edit.seq} has a non-boolean excluded` }\n }\n if (edit.deleted !== undefined && typeof edit.deleted !== 'boolean') {\n return { ok: false, code: REDLINE_ERROR.draftCorrupt, message: `draft #${edit.seq} has a non-boolean deleted` }\n }\n // 旧实现**先清空正文**才写 `excluded`(没有 `deleted` 字段)⟹ 那条\"删除前的编辑\"已经不可能恢复。\n // 迁移到 `deleted` 的同时如实置 `legacyBodyLost`:标记不丢、也不伪造正文(R4.8 硬要求 5)。\n const legacyOnly = edit.deleted === undefined && edit.excluded === true\n const deleted = edit.deleted === true || edit.excluded === true\n const body = { seq: edit.seq, text: edit.text, reasoning: edit.reasoning, isError: edit.isError }\n table[String(edit.seq)] = withMarks(\n {\n ...body,\n updatedAt: typeof edit.updatedAt === 'string' ? edit.updatedAt : '',\n ...(typeof edit.cat === 'string' ? { cat: edit.cat } : {}),\n ...(typeof edit.name === 'string' ? { name: edit.name } : {}),\n },\n deleted,\n legacyOnly && !hasEditBody({ ...body, updatedAt: '', seq: edit.seq }),\n )\n }\n return { ok: true, table }\n}\n","/** The one-line label cascade shared by the Context browser's element rows. */\n\nimport type { SurfaceNode } from '../../shared/types'\nimport type { ViewKit } from '../viewkit'\n\nexport function makeNodeText(kit: ViewKit): (n: SurfaceNode) => string {\n const { t } = kit\n return function nodeText(n: SurfaceNode): string {\n if (n.cat === 'tool') {\n return t('node.toolResult') + (n.tool ? ' ← ' + n.tool : '') + (n.err ? ' ⚠' : '')\n }\n if (n.skill) return 'Skill: ' + n.skill\n if (n.calls) return t('node.calls') + n.calls.join(', ')\n if (n.text) return n.form === 'snapshot' ? t('node.snapshot') + n.text : n.text\n if (n.cat === 'assistant') return t('node.empty')\n if (n.cat === 'inject' || n.cat === 'skill') return t('form.' + (n.form || 'context'))\n return t('node.nonText')\n }\n}\n","/**\n * Stop a horizontal scroller's overscroll from reaching the browser's history navigation — the trackpad\n * swipe-back (left edge) and swipe-forward (right edge) gestures. The spec answer is `overscroll-behavior-x:\n * contain`, the harness's own idiom for its horizontal scrollers and what the sheets beside this module's\n * callers already set; it covers Chromium and Firefox, but WebKit still navigates on horizontal overscroll with\n * the property set (bug 240183), where a canceled wheel is the only lever. Without either, one swipe past the\n * edge of the trend chart or the agent graph leaves the whole app for another page in the tab's history.\n */\n\n/**\n * Cancel the horizontal-dominant wheel gestures a scroller cannot consume — the ones the browser would\n * otherwise read as a history swipe. Vertical-dominant gestures are left alone: they belong to the page's own\n * scrolling, and the scrollers this guards only overflow horizontally.\n * @param el - the horizontal scroll container (the listener must be non-passive, so it cannot ride React's passive wheel seat).\n * @returns the disposer removing the listener.\n */\nexport function containHorizontalOverscroll(el: HTMLElement): () => void {\n const onWheel = (e: WheelEvent): void => {\n if (Math.abs(e.deltaX) <= Math.abs(e.deltaY)) return\n const atStart = e.deltaX < 0 && el.scrollLeft <= 0\n // 1px tolerance: fractional device-pixel scroll offsets land just short of the exact end.\n const atEnd = e.deltaX > 0 && el.scrollLeft + el.clientWidth >= el.scrollWidth - 1\n if (atStart || atEnd) e.preventDefault()\n }\n el.addEventListener('wheel', onWheel, { passive: false })\n return () => { el.removeEventListener('wheel', onWheel) }\n}\n","/**\n * Bespoke per-request history chart — no shared data-viz primitive — styled through the shared `--dsw-alias-*` tokens; helpers\n * aggregateByTurn/attachMarkers are shared with ContextView. On mount each bar rises from its baseline,\n * staggered left to right with the cascade capped for long logs (trendChart.css, `--redline-i` slots below).\n */\n\nimport { memo, useLayoutEffect, useMemo, useRef, useState, type CSSProperties, type ReactElement, type UIEvent } from 'react'\nimport type { Category, ContextEventRecord, RequestRecord } from '../../shared/types'\nimport { CATS } from '../categories'\nimport { containHorizontalOverscroll } from '../overscroll'\nimport type { ViewKit } from '../viewkit'\n\nexport interface TrendChartProps {\n requests: RequestRecord[]\n markers: (ContextEventRecord | undefined)[]\n selectedSeq: number | null\n hoveredSeq: number | null\n activeTurn: number | null\n granularity: 'step' | 'turn'\n mode: 'total' | 'delta'\n focusTurn: number | null\n /** Mirrored category hover (shared with the overview and the browser): lights that category's segment in every bar. */\n hoverCat: string | null\n /**\n * The browser's open category: every bar plots only that category's fold figure, with the axis rescaled\n * to its own max. Null plots every category; an unrecognized key (a stale or hostile state) degrades to the\n * unfocused chart.\n */\n focusCat?: string | null\n /**\n * Adaptive scale (the trend card's title-adjacent toggle): the axis is recomputed from the bars currently\n * VISIBLE in the scroller and follows the scroll, so a spike far outside the window cannot flatten the bars\n * on screen. Off = the whole retained log scales the axis, the historical behavior.\n */\n adaptive?: boolean\n onSelect: (seq: number | null) => void\n onHover: (seq: number | null) => void\n onHoverTurn: (turn: number | null) => void\n onPickTurn: (turn: number) => void\n onFocusTurnHandled: () => void\n}\n\n/**\n * Collapse per-step requests into one bar per turn — each turn is represented by its LAST step's record, tagged `stepCount` for the bar's\n * column width; the log keeps one turn's requests consecutive, so a run of equal turns collapses to its final record.\n */\nexport function aggregateByTurn(requests: RequestRecord[]): RequestRecord[] {\n const out: RequestRecord[] = []\n let runSteps = 0\n for (const req of requests) {\n const last = out.length > 0 ? out[out.length - 1] : null\n if (last !== null && (last.turn ?? 0) === (req.turn ?? 0)) {\n runSteps++\n out[out.length - 1] = { ...req, stepCount: runSteps }\n } else {\n runSteps = 1\n out.push({ ...req, stepCount: 1 })\n }\n }\n return out\n}\n\n/**\n * The per-turn step tallies the step-granularity labels lean on (\"第 s 步 (共 n 步)\") — the same count a\n * turn-mode bar's `stepCount` carries. Records without a turn stamp pool under 0, the key the labels'\n * `turn ?? 0` fallback reads; the getter answers 1 for a turn outside the list so a caller can never miss.\n */\nexport function turnStepsOf(requests: RequestRecord[]): (turn: number | undefined) => number {\n const counts = new Map<number, number>()\n for (const req of requests) {\n const turn = req.turn ?? 0\n counts.set(turn, (counts.get(turn) ?? 0) + 1)\n }\n return turn => counts.get(turn ?? 0) ?? 1\n}\n\n/**\n * Attach each boundary event (compaction/prune) to the first request logged after it — one entry per index, for the ✂ marker and the detail\n * chip; shared with the detail panel so both show the SAME event.\n */\nexport function attachMarkers(requests: RequestRecord[], events: ContextEventRecord[]): (ContextEventRecord | undefined)[] {\n const markers: (ContextEventRecord | undefined)[] = new Array<ContextEventRecord | undefined>(requests.length)\n for (const ev of events) {\n if (ev.kind !== 'compaction' && ev.kind !== 'prune') continue\n for (let r = 0; r < requests.length; r++) {\n if (requests[r].seq >= ev.seq) {\n if (markers[r] === undefined) markers[r] = ev\n break\n }\n }\n }\n return markers\n}\n\n/**\n * The chat→Context jump's target: the turn bar whose closing reply the user clicked — the relayed seq is a turn's LAST step, exactly the\n * aggregate's record — or, when that turn has aged out of the host's retained window, the oldest retained bar. Resolved against turn\n * aggregates, since the jump pins in turn granularity. Null only on an empty history.\n */\nexport function jumpTargetOf(requests: RequestRecord[], seq: number): RequestRecord | null {\n for (const req of requests) if (req.seq === seq) return req\n return requests.length > 0 ? requests[0] : null\n}\n\nexport function makeTrendChart(kit: ViewKit): (props: TrendChartProps) => ReactElement {\n const { t, fmt, eventLabel, eventAt, catLabel } = kit\n\n const CHART_H = 112\n // Quarter-mark label tops for the axis (mirrored to .redline-axis-q1/.redline-axis-q3 in trendChart.css): chart top 18\n // plus a quarter/three-quarters of the 112px bar area, minus half the 11px label box (font-size 11, line-height 1).\n const Q3_TOP = 41\n const Q1_TOP = 97\n // Delta axis ticks are signed: '+' only on positives — fmt already carries the minus for negatives.\n const fmtSigned = (v: number): string => (v > 0 ? '+' : '') + fmt(v)\n // Constant bar width: sparse histories don't stretch bars, dense ones scroll instead of compressing; the turn strip below mirrors the\n // same column grid.\n const BAR_W = 14\n const BAR_GAP = 2\n // Entrance stagger cap: long logs render thousands of bars, so the grow-in cascade stops widening after\n // this many columns and late bars simply join within the cap (trendChart.css delays by `--redline-i`).\n const STAGGER_CAP = 20\n // Step flags: every 5th step bar plants one at its left edge, labeled with its cumulative step number\n // (5, 10, 15, …) — the chart's only position landmark in step granularity (the turn strip numbers turns).\n const STEP_FLAG_EVERY = 5\n // Neutral zebra, deliberately DISJOINT from the category palette — the strip must read as a partition layer, not a bottom segment of the\n // composition bars.\n const TURN_FILLS = [\n 'color-mix(in srgb, var(--redline-color-neutral-500) 12%, transparent)',\n 'color-mix(in srgb, var(--redline-color-neutral-500) 26%, transparent)',\n ]\n // Turn labels render at natural width (a 2-digit \"12\" is wider than a 14px turn bar) and overflow their block.\n // Every label must stay on the single line, so the strip shrinks ALL labels to one font size — the largest at\n // which the tightest adjacent pair still clears the gap (analytic widths below, no measurement) — and the\n // measured chain in updateTurnLabels stays only as the last-resort guard past the floor. OVERHANG bounds how\n // far a label can reach beyond its block (a generous read of \"9999\" at 10px) for the viewport-participation\n // test; GAP is the breathing room between adjacent labels' boxes.\n const LABEL_OVERHANG = 48\n const LABEL_GAP = 2\n // Label font sizing (the 10px base mirrors .redline-turn in trendChart.css): conservative upper-bound glyph width\n // at the base size (6.5px per digit at 10px semibold), floored at 6px.\n const LABEL_FONT = 10\n const LABEL_FONT_MIN = 6\n const estTurnLabel = (turn: number): number => 6.5 * String(turn).length\n\n /**\n * Focus a bar on one category (the browser's open category): the kept bucket carries its fold figure, the other\n * buckets zero, and `total` IS the plotted figure — the downstream stack/tooltip math reads the derived record\n * unchanged. The raw fold figures are plotted as-is: a per-request rescale against the provider prompt would drift\n * with the heuristic's ratio error and fake growth into constant categories (a never-changing system prompt must\n * plot flat).\n */\n const focusOf = (req: RequestRecord, cat: string): RequestRecord => {\n const key = cat as Category | 'system' | 'tools'\n const out: RequestRecord = { ...req }\n const v = req[key] || 0\n out.total = v\n for (const c of CATS) out[c.key] = c.key === key ? v : 0\n return out\n }\n\n /**\n * Delta mode: each category keeps the SIGNED change vs the previous record so bars can diverge\n * above/below the zero line; `total` is the churn (summed magnitude), `net` the signed change\n * for the tooltip; the first request starts from zero so the scale is change-driven, and per-request\n * provider prompt/output are dropped (they are not deltas).\n */\n const deltaOf = (req: RequestRecord, prev: RequestRecord | null): RequestRecord => {\n const { prompt: _prompt, output: _output, ...out } = req\n let churn = 0\n let net = 0\n for (const c of CATS) {\n const d = prev !== null ? (req[c.key] || 0) - (prev[c.key] || 0) : 0\n out[c.key] = d\n churn += Math.abs(d)\n net += d\n }\n out.total = churn\n out.net = net\n return out\n }\n\n /** The visible window's own maxima (adaptive scale): the total-mode peak, and the delta arms' up/down sums. */\n interface VisibleMax {\n total: number\n up: number\n down: number\n }\n\n interface ChartBarProps {\n req: RequestRecord\n marker: ContextEventRecord | undefined\n selected: boolean\n hovered: boolean\n inTurn: boolean\n maxTotal: number\n /**\n * Delta mode geometry: zero-line offsets in px (up from the top / down from the bottom of the bar area)\n * and the uniform px-per-token scale — identical above and below the zero line, so a +n segment and a\n * −n segment always draw the same height. All three absent in total mode; passed as PRIMITIVES so the\n * memoized bar keeps its shallow-compare bailout.\n */\n upPx?: number\n downPx?: number\n deltaScale?: number\n /** Bar index in the render order: the entrance grow-in stagger slot (capped inside, so a long log's cascade stays snappy). */\n enterIndex: number\n /** The step flag's label (the bar's cumulative step number), or null to plant none. */\n flag: number | null\n onSelect: (seq: number | null) => void\n onHover: (seq: number | null) => void\n }\n\n // Memoized so a hover/selection change re-renders only the bars whose flags flipped — the retained log renders in full (thousands of\n // nodes on long sessions); `req`/`marker` keep stable identities because the parent memoizes its aggregation, so the default shallow\n // compare suffices.\n const ChartBar = memo(function ChartBar(props: ChartBarProps): ReactElement {\n const { req, marker } = props\n const markerAt = marker !== undefined ? eventAt(marker) : null\n // Delta mode: diverging stacks — positive category deltas pile UP from the zero line, negative ones\n // hang DOWN from it, both in category colors (direction carries the sign, color the category).\n const diverge = props.upPx !== undefined && props.downPx !== undefined && props.deltaScale !== undefined\n // Rise stagger slot, shared by the total stack and both delta arms (trendChart.css scaleY-opens them).\n const enterStyle = { '--redline-i': Math.min(props.enterIndex, STAGGER_CAP) } as CSSProperties\n return (\n <div\n className={'redline-bar hover:bg-(--dsw-alias-bg-layer-2)'\n + (props.selected ? ' redline-bar-selected' : '')\n + (props.hovered ? ' redline-bar-hovered' : '')\n + (props.inTurn ? ' redline-bar-in-turn' : '')}\n data-redline-seq={req.seq}\n style={{ width: `${BAR_W}px` }}\n onClick={() => { props.onSelect(props.selected ? null : req.seq) }}\n onMouseEnter={() => { props.onHover(req.seq) }}\n >\n {props.flag !== null ? (\n // Painted UNDER the ✂ marker (it follows in DOM order): on a rare same-bar collision the event\n // glyph keeps precedence over the landmark.\n <span className=\"redline-step-flag\" aria-hidden=\"true\"><span className=\"redline-step-flag-label\">{props.flag}</span></span>\n ) : null}\n {marker !== undefined ? (\n <span\n className=\"redline-bar-marker\"\n title={'✂ ' + (markerAt !== null ? markerAt + ' — ' : '') + eventLabel(marker)}\n >{'✂'}</span>\n ) : null}\n {diverge ? (\n <>\n <div className=\"redline-bar-up animate-redline-bar-in motion-reduce:animate-none\" style={{ bottom: `${props.downPx}px`, ...enterStyle }}>\n {CATS.map((c) => {\n const d = req[c.key] || 0\n if (d <= 0) return null\n return <div key={c.key} data-redline-cat={c.key} className=\"redline-cat-seg\" style={{ height: `${Math.max(1, Math.round(d * (props.deltaScale as number)))}px`, background: c.color }} />\n })}\n </div>\n <div className=\"redline-bar-down animate-redline-bar-in motion-reduce:animate-none\" style={{ top: `${props.upPx}px`, ...enterStyle }}>\n {CATS.map((c) => {\n const d = req[c.key] || 0\n if (d >= 0) return null\n return <div key={c.key} data-redline-cat={c.key} className=\"redline-cat-seg\" style={{ height: `${Math.max(1, Math.round(-d * (props.deltaScale as number)))}px`, background: c.color }} />\n })}\n </div>\n </>\n ) : (\n <div className=\"redline-bar-stack animate-redline-bar-in motion-reduce:animate-none\" style={enterStyle}>\n {CATS.map((c) => {\n const v = req[c.key] || 0\n if (!v) return null\n // px (not %) heights: the stack is content-driven, so percentage heights would collapse against an indefinite base.\n return <div key={c.key} data-redline-cat={c.key} className=\"redline-cat-seg\" style={{ height: `${Math.max(1, Math.round(v / props.maxTotal * CHART_H))}px`, background: c.color }} />\n })}\n </div>\n )}\n </div>\n )\n })\n\n return function TrendChart(props: TrendChartProps): ReactElement {\n const delta = props.mode === 'delta'\n // An unrecognized focus key degrades to the unfocused chart instead of plotting an empty axis.\n const focus = props.focusCat !== null && props.focusCat !== undefined && CATS.some(c => c.key === props.focusCat)\n ? props.focusCat\n : null\n const requests = useMemo(\n () => {\n const base = focus !== null ? props.requests.map(req => focusOf(req, focus)) : props.requests\n return delta ? base.map((req, i) => deltaOf(req, i > 0 ? base[i - 1] : null)) : base\n },\n [props.requests, delta, focus],\n )\n const markers = props.markers\n // Adaptive scale: the maxima over the bars currently on screen. Null until the first measure, which falls\n // back to the whole-log scale, so the first paint never draws an empty axis; the field-wise comparison means\n // scrolling inside a window whose maxima do not move re-renders nothing.\n const adaptive = props.adaptive === true\n const [visMax, setVisMax] = useState<VisibleMax | null>(null)\n const measureVisible = (el: HTMLDivElement): void => {\n if (!adaptive) return\n const n = requests.length\n // Nothing measurable: an empty history, or a zero-width viewport (a hidden pane, an unlaid-out test DOM).\n // Keeping the previous scale degrades the chart to the whole-log axis instead of flattening every bar.\n if (n === 0 || el.clientWidth <= 0) return\n const pitch = BAR_W + BAR_GAP\n const sl = el.scrollLeft\n const vr = sl + el.clientWidth\n let total = 0\n let up = 0\n let down = 0\n // The column holding the left edge through the one holding the right edge; the per-column test then drops\n // the neighbour whose column falls in the 2px gap just outside the viewport.\n const from = Math.max(0, Math.floor(sl / pitch))\n const to = Math.min(n - 1, Math.max(from, Math.floor((vr - 1) / pitch)))\n for (let i = from; i <= to; i++) {\n const col = i * pitch\n if (col >= vr || col + BAR_W <= sl) continue\n const req = requests[i]\n if (delta) {\n // Per-bar arms, then the window maximum — the same figures the whole-log loop takes.\n let bu = 0\n let bd = 0\n for (const c of CATS) {\n const d = req[c.key] || 0\n if (d > 0) bu += d\n else bd -= d\n }\n if (bu > up) up = bu\n if (bd > down) down = bd\n } else if (req.total > total) {\n total = req.total\n }\n }\n setVisMax(prev => prev !== null && prev.total === total && prev.up === up && prev.down === down\n ? prev\n : { total, up, down })\n }\n // Whole-log maxima: the axis when adaptive is off, and the fallback for a delta window with no change at all\n // (it carries no scale of its own).\n let maxTotal = 1\n let maxUp = 0\n let maxDown = 0\n if (delta) {\n for (const req of requests) {\n let up = 0\n let down = 0\n for (const c of CATS) {\n const d = req[c.key] || 0\n if (d > 0) up += d\n else down -= d\n }\n if (up > maxUp) maxUp = up\n if (down > maxDown) maxDown = down\n }\n } else {\n for (const req of requests) {\n if (req.total > maxTotal) maxTotal = req.total\n }\n }\n if (adaptive && visMax !== null) {\n if (delta) {\n if (visMax.up + visMax.down > 0) {\n maxUp = visMax.up\n maxDown = visMax.down\n }\n } else {\n maxTotal = Math.max(1, visMax.total)\n }\n }\n // The zero line splits the bar area PROPORTIONALLY to the larger side, so the px-per-token scale\n // is identical above and below it — a compaction's downward bar reads honestly against a growth bar.\n const span = Math.max(1, maxUp + maxDown)\n const deltaScale = CHART_H / span\n const upPx = Math.round(maxUp * deltaScale)\n const downPx = CHART_H - upPx\n // A delta quarter mark (axis label + its dashed guide) yields ENTIRELY when its 11px label box would\n // overlap the zero label (top 13+upPx) — the zero line is the reading reference. Total-mode marks never\n // collide and always render.\n const q3Clear = Math.abs(Q3_TOP - 13 - upPx) >= 11\n const q1Clear = Math.abs(Q1_TOP - 13 - upPx) >= 11\n\n // Consecutive same-turn requests collapse into one labeled range; `span` counts the STEP columns the group covers (step records count\n // one each), so strip blocks align with the bars in both granularities.\n const groups: { turn: number; count: number; span: number; agg: boolean }[] = []\n for (const req of requests) {\n let grp = groups.length > 0 ? groups[groups.length - 1] : null\n if (grp === null || grp.turn !== (req.turn ?? 0)) {\n grp = { turn: req.turn ?? 0, count: 0, span: 0, agg: req.stepCount !== undefined }\n groups.push(grp)\n }\n grp.count++\n grp.span += req.stepCount ?? 1\n }\n\n // Strip offsets/widths are computed in content px so the scroll handler can re-center labels analytically and measures only the handful\n // of labels on screen.\n const turnOffsets: number[] = []\n const turnWidths: number[] = []\n {\n let x = 0\n for (const grp of groups) {\n const w = grp.agg ? BAR_W : grp.span * (BAR_W + BAR_GAP) - BAR_GAP\n turnOffsets.push(x)\n turnWidths.push(w)\n x += w + BAR_GAP\n }\n }\n\n // One font size for the whole strip: the largest at which the TIGHTEST adjacent pair of labels still clears\n // the gap between their block centers (center distance = half each block + the gap between blocks), so every\n // turn label stays shown on the single line instead of thinning out. Uniform (not per-label) so sizes never\n // mix, and computed from the groups alone so it is stable while scrolling.\n let labelFont = ''\n {\n let scale = 1\n for (let i = 0; i + 1 < groups.length; i++) {\n const avail = (turnWidths[i] + turnWidths[i + 1]) / 2 + BAR_GAP\n const need = (estTurnLabel(groups[i].turn) + estTurnLabel(groups[i + 1].turn)) / 2 + LABEL_GAP\n if (need > avail) scale = Math.min(scale, avail / need)\n }\n if (scale < 1) labelFont = `${Math.max(LABEL_FONT_MIN, Math.floor(LABEL_FONT * scale))}px`\n }\n\n // Default anchor: newest bars at the RIGHT edge; the first layout after mount scrolls unconditionally, a GRANULARITY SWITCH re-anchors\n // the same way (step mode must not inherit the turn chart's stale left edge), otherwise stick to the end only while already near it;\n // useLayoutEffect avoids a first-paint flash.\n const scrollRef = useRef<HTMLDivElement | null>(null)\n const scrolledOnce = useRef(false)\n const lastGranRef = useRef(props.granularity)\n // The newest bar's seq (or 0 when the log is empty): the layout effect only re-runs when the right edge genuinely\n // moves (new bar appended, granularity switched, focus turn set) — hover/select changes keep their scroll position\n // so the chart does not flash with every keystroke.\n const lastSeqRef = useRef(0)\n // The scrollWidth measured during the PREVIOUS effect pass. The \"was the reader near the right edge?\" check\n // has to compare against the width as it was BEFORE the new bar landed — by the time the layout effect runs,\n // `el.scrollWidth` is already the new (wider) value, so a near-edge check against it would miss the auto-follow.\n const prevScrollWidthRef = useRef(0)\n /**\n * Keep each turn label centered within its block's VISIBLE slice, then thin colliding labels: a label wider\n * than its block overflows it, so consecutive narrow turns would smear into each other — walking left→right\n * in content coordinates, a label whose box reaches the previous KEPT one drops to visibility:hidden. The\n * render-time font shrink (labelFont) already sizes every label to clear its tightest neighbour, so this\n * chain only fires past the 6px floor or on viewport-edge shifts. Blocks that cannot reach the viewport even\n * overhung by a label skip their reads/writes entirely (their transform/visibility just reset); reads\n * (offsetWidth) batch before the writes to avoid layout thrash, and unchanged styles write nothing.\n */\n const updateTurnLabels = (el: HTMLDivElement): void => {\n const labels = el.querySelectorAll<HTMLElement>('.redline-turn-label')\n const n = Math.min(labels.length, turnOffsets.length)\n const sl = el.scrollLeft\n const vr = sl + el.clientWidth\n const writes: [HTMLElement, string, string][] = []\n // Right edge (content px) of the last kept label's box plus the gap; -Infinity opens the chain.\n let chainR = -Infinity\n for (let i = 0; i < n; i++) {\n const off = turnOffsets[i]\n const w = turnWidths[i]\n let dx = 0\n let vis = ''\n if (off + w + LABEL_OVERHANG > sl && off - LABEL_OVERHANG < vr) {\n const lw = labels[i].offsetWidth\n const visL = Math.max(off, sl)\n const visR = Math.min(off + w, vr)\n if (visR > visL && lw < w) {\n const center = (visL + visR) / 2 - off\n dx = Math.min(Math.max(center, lw / 2), w - lw / 2) - w / 2\n }\n const left = off + w / 2 + dx - lw / 2\n if (left < chainR) vis = 'hidden'\n else chainR = left + lw + LABEL_GAP\n }\n const next = dx !== 0 ? `translateX(${dx}px)` : ''\n if (labels[i].style.transform !== next || labels[i].style.visibility !== vis) writes.push([labels[i], next, vis])\n }\n for (const [label, next, vis] of writes) {\n label.style.transform = next\n label.style.visibility = vis\n }\n }\n useLayoutEffect(() => {\n const el = scrollRef.current\n /* v8 ignore next 1 -- the scroll div renders unconditionally and React\n attaches refs before layout effects run; el is never null here. */\n if (el === null) return\n const newestSeq = requests.length === 0 ? 0 : requests[requests.length - 1].seq\n const grew = newestSeq !== lastSeqRef.current\n const widthBeforeAppend = prevScrollWidthRef.current\n if (props.granularity !== lastGranRef.current) {\n lastGranRef.current = props.granularity\n scrolledOnce.current = false\n }\n // A strip-clicked focus turn centers its bar instead of the newest anchor, consumed once via onFocusTurnHandled — also when\n // granularity was already 'turn' (no re-anchor happens that render).\n if (props.focusTurn !== null) {\n const gi = groups.findIndex(g => g.turn === props.focusTurn)\n if (gi >= 0) {\n scrolledOnce.current = true\n el.scrollLeft = Math.max(0, gi * (BAR_W + BAR_GAP) + BAR_W / 2 - el.clientWidth / 2)\n }\n props.onFocusTurnHandled()\n } else if (!scrolledOnce.current) {\n scrolledOnce.current = true\n el.scrollLeft = el.scrollWidth\n } else if (grew && el.scrollLeft + el.clientWidth >= widthBeforeAppend - 24) {\n // Only follow the latest bar when the right edge actually moved AND the reader was already near it\n // BEFORE the new bar landed — comparing against the new scrollWidth would silently drop the stick for a\n // mid-chart reader whose viewport just slid past the near-end threshold.\n el.scrollLeft = el.scrollWidth\n }\n lastSeqRef.current = newestSeq\n prevScrollWidthRef.current = el.scrollWidth\n updateTurnLabels(el)\n syncTip(el)\n measureVisible(el)\n }, [props.granularity, props.focusTurn, requests, adaptive])\n\n // The observer callback needs the LATEST measure closure (it captures `requests`/`delta`); a ref keeps it fresh\n // without tearing the observer down on every commit.\n const measureRef = useRef(measureVisible)\n useLayoutEffect(() => { measureRef.current = measureVisible })\n // A pane resize (sidebar collapse/drag, window resize) changes the visible window without any render, so the\n // observer re-measures. jsdom exposes no ResizeObserver — the commit/scroll measures cover those paths.\n useLayoutEffect(() => {\n const el = scrollRef.current\n /* v8 ignore next 1 -- the scroll div renders unconditionally and React\n attaches refs before layout effects run; el is never null here. */\n if (el === null) return\n if (typeof ResizeObserver !== 'function') return\n const observer = new ResizeObserver(() => { measureRef.current(el) })\n observer.observe(el)\n return () => { observer.disconnect() }\n }, [])\n // A horizontal swipe running off the chart's edge must not chain into the browser's history navigation\n // (overscroll.ts): the sheet's overscroll-behavior-x covers Chromium/Firefox, this covers WebKit.\n useLayoutEffect(() => {\n const el = scrollRef.current\n /* v8 ignore next 1 -- the scroll div renders unconditionally and React\n attaches refs before layout effects run; el is never null here. */\n if (el === null) return\n return containHorizontalOverscroll(el)\n }, [])\n\n // Compact 2-row hover tooltip, shown instantly by the custom `.redline-chart-tip` (the native title is delayed):\n // identity and the bar's total — the SAME value the bar height and axis are scaled against (the fold's\n // heuristic figure, matching every other card). Identity phrasing follows the granularity —\n // turn bars always speak TURN (the aggregate's step count, singular for a 1-step turn; a record missing\n // stepCount degrades to that too), step bars carry the step index plus the turn's step total. Delta swaps\n // the metric row for the net.\n const stepsOf = useMemo(() => turnStepsOf(props.requests), [props.requests])\n const tipRowsOf = (req: RequestRecord): [string, string] => {\n const n = req.stepCount ?? 1\n const head = props.granularity === 'turn'\n ? (n > 1 ? t('tip.turn', { t: req.turn ?? 0, n }) : t('tip.turn1', { t: req.turn ?? 0 }))\n : t('tip.step', { t: req.turn ?? 0, s: req.step ?? 0, n: stepsOf(req.turn) })\n if (delta) {\n /* v8 ignore next 1 -- delta mode only receives records from\n deltaOf, which always assigns net; the fallback is defensive. */\n const n = req.net ?? 0\n return [head, t('tip.delta', { n: (n > 0 ? '+' : '') + fmt(n) })]\n }\n // Focused: the metric row IS the focused category's figure, so the tip names it instead of claiming a total.\n return [head, focus !== null\n ? t('tip.cat', { cat: catLabel(focus), n: fmt(req.total) })\n : t('tip.total', { n: fmt(req.total) })]\n }\n const hoveredIdx = props.hoveredSeq !== null ? requests.findIndex(r => r.seq === props.hoveredSeq) : -1\n const hoveredReq = hoveredIdx >= 0 ? requests[hoveredIdx] : null\n\n // Column center (content px) of the currently hovered bar, for syncTip reads outside the render pass.\n const tipColRef = useRef(0)\n\n /**\n * Glue the hover tip to its bar's VISIBLE slice. The tip deliberately does NOT live inside the scrolling\n * content: an absolutely-positioned child of a scroller contributes to its scrollable overflow, so a wide\n * reply preview on a right-edge bar used to inflate scrollWidth on every hover and flap the horizontal\n * scrollbar open/closed — jumping the whole card. Reads (offsetWidth/clientWidth) batch before the single\n * style write; unchanged transforms write nothing.\n */\n const syncTip = (el: HTMLDivElement): void => {\n /* v8 ignore next 1 -- the scroll div renders unconditionally while mounted, so its parent exists. */\n const tip = (el.parentElement ?? document.body).querySelector<HTMLElement>('.redline-chart-tip')\n // No hover, nothing to place.\n if (tip === null) return\n const lw = tip.offsetWidth\n const cw = el.clientWidth\n // Center over the bar's visible slice, clamped so the tip never hangs past either edge nor gets cut off; a tip\n // wider than the viewport centers over it instead of picking a bogus side on an inverted clamp window.\n const half = Math.min(lw / 2, cw / 2)\n const cx = Math.min(Math.max(tipColRef.current - el.scrollLeft, half), cw - half)\n const next = `translate(${Math.round(cx - lw / 2)}px, 0)`\n if (tip.style.transform !== next) tip.style.transform = next\n }\n\n // Position (and re-position after EVERY commit — the tip mounts on hover changes, which touch no other\n // effect dependency here) from the committed hovered column before paint.\n useLayoutEffect(() => {\n /* v8 ignore next 1 -- the scroll div renders unconditionally and React attaches refs before\n layout effects run; el is never null here. */\n if (scrollRef.current === null) return\n tipColRef.current = hoveredIdx >= 0 ? hoveredIdx * (BAR_W + BAR_GAP) + BAR_W / 2 : 0\n syncTip(scrollRef.current)\n })\n\n return (\n <div className=\"redline-chartrow\">\n <div className=\"redline-axis\">\n {delta ? (\n <>\n <span className=\"redline-axis-top\">{fmtSigned(maxUp)}</span>\n {/* Axis quartile marks on the uniform px-per-token scale (the value at each fixed height); a mark\n whose 11px label box would overlap the zero label drops itself — the zero line is the reading\n reference and keeps its place. */}\n {q3Clear\n ? <span className=\"redline-axis-q3\">{fmtSigned(Math.round(maxUp - span / 4))}</span>\n : null}\n {/* The 0 label rides the zero line (chart top padding 18px, half the 11px line-height up). */}\n <span className=\"redline-axis-mid\" style={{ top: `${13 + upPx}px` }}>{'0'}</span>\n {q1Clear\n ? <span className=\"redline-axis-q1\">{fmtSigned(Math.round(maxUp - 3 * span / 4))}</span>\n : null}\n <span className=\"redline-axis-bot\">{fmtSigned(-maxDown)}</span>\n </>\n ) : (\n <>\n <span className=\"redline-axis-top\">{fmt(maxTotal)}</span>\n <span className=\"redline-axis-q3\">{fmt(Math.round(maxTotal * 3 / 4))}</span>\n <span className=\"redline-axis-mid\">{fmt(Math.round(maxTotal / 2))}</span>\n <span className=\"redline-axis-q1\">{fmt(Math.round(maxTotal / 4))}</span>\n <span className=\"redline-axis-bot\">{'0'}</span>\n </>\n )}\n </div>\n {/* Only the scrolling CONTENT lives under .redline-chart-scroll; the hover tip sits beside it inside the\n positioned wrapper instead of inside the scroller — absolutely-positioned children of a scroller\n contribute to its scrollable overflow AND translate away with the content on scroll. */}\n <div className=\"redline-chart-wrap\">\n <div\n className={'redline-chart-scroll' + (props.activeTurn !== null ? ' redline-chart-dim' : '')}\n ref={scrollRef}\n onScroll={(e: UIEvent<HTMLDivElement>) => {\n updateTurnLabels(e.currentTarget)\n syncTip(e.currentTarget)\n measureVisible(e.currentTarget)\n }}\n >\n <div\n className=\"redline-chart\"\n // The shared category hover rides a plain attribute: the CSS lights that key's segment in EVERY bar\n // and recedes the rest, so the memoized bars never re-render on a cross-card hover change.\n data-redline-catdim={props.hoverCat ?? undefined}\n onMouseLeave={() => { props.onHover(null) }}\n >\n <div className=\"redline-grid redline-grid-top\" />\n {/* Dashed guides aligning the bars with the axis quarter marks (fixed heights, both modes); a delta\n mark that yielded to the zero label drops its guide too, and a coinciding guide sits under the\n solid zero line painted after it. */}\n {(!delta || q3Clear) ? <div className=\"redline-grid redline-grid-q3\" /> : null}\n {(!delta || q1Clear) ? <div className=\"redline-grid redline-grid-q1\" /> : null}\n {!delta ? <div className=\"redline-grid redline-grid-mid\" /> : null}\n {/* The SOLID zero baseline — the reading reference in both modes: inline-positioned off the up-arm\n in delta mode, the chart floor (CSS default) under the '0' label in total mode. */}\n <div className=\"redline-grid redline-grid-zero\" style={delta ? { top: `${18 + upPx}px` } : undefined} />\n {requests.map((req, i) => (\n <ChartBar\n // Granularity belongs in the key: a turn aggregate IS its last step's record (the same\n // seq), so a step ↔ turn switch would otherwise REUSE that bar's DOM node and its finished\n // entrance rise would not replay — every turn's last step bar would pop in unanimated.\n key={`${req.seq}:${props.granularity}`}\n req={req}\n marker={markers[i]}\n selected={props.selectedSeq === req.seq}\n hovered={props.hoveredSeq === req.seq}\n inTurn={props.activeTurn !== null && (req.turn ?? 0) === props.activeTurn}\n // Turn bars skip the flag: the turn strip below already numbers that grid.\n flag={props.granularity === 'step' && (i + 1) % STEP_FLAG_EVERY === 0 ? i + 1 : null}\n maxTotal={maxTotal}\n upPx={delta ? upPx : undefined}\n downPx={delta ? downPx : undefined}\n deltaScale={delta ? deltaScale : undefined}\n enterIndex={i}\n onSelect={props.onSelect}\n onHover={props.onHover}\n />\n ))}\n </div>\n {/* Turn strip: one COLOR BLOCK per turn spanning exactly its bars' columns, so the partition reads at a glance and lines\n up with the steps; hovering a block highlights that turn's bars and vice versa — one shared hover-only state.\n */}\n <div className=\"redline-turns\" style={labelFont !== '' ? { fontSize: labelFont } : undefined} onMouseLeave={() => { props.onHoverTurn(null) }}>\n {groups.map((grp, gi) => {\n const on = props.activeTurn === grp.turn\n return (\n <span\n key={`turn-${gi}`}\n className={'redline-turn' + (on ? ' redline-turn-on' : '')}\n style={{\n width: `${turnWidths[gi]}px`,\n background: TURN_FILLS[gi % TURN_FILLS.length],\n }}\n title={`T${grp.turn}`}\n onMouseEnter={() => { props.onHoverTurn(grp.turn) }}\n onClick={() => { props.onPickTurn(grp.turn) }}\n ><span className=\"redline-turn-label\">{`${grp.turn}`}</span></span>\n )\n })}\n </div>\n </div>\n {/* Compact 2-row hover tooltip (identity / bar total), shown instantly by the custom `.redline-chart-tip`\n (the native title is delayed); the per-category breakdown lives in the detail panel below. It floats\n ABOVE the plot (CSS bottom anchoring) so it never covers the bars, is capped at the wrapper's width\n and wrapped, and is positioned imperatively over its bar's visible slice (syncTip) so scrolling keeps\n it glued without ever widening the scrollable area. */}\n {hoveredReq !== null ? (\n <div className=\"redline-chart-tip\">{tipRowsOf(hoveredReq).map((row, i) => <span key={i}>{row}</span>)}</div>\n ) : null}\n </div>\n </div>\n )\n }\n}\n","/**\n * The fetch-on-miss state machine behind the Context browser's two on-demand\n * reads (a row's full message content and a header epoch's prompt/schemas):\n * one targeted history read per key the local data missed, with a visible\n * terminal state for every outcome — `absent` when the durable log does not\n * hold the key, `failed` arming the retry button, never an unhandled\n * rejection or a spinner that never resolves. Landed values cache by key:\n * history is immutable, so a resolved key never refetches.\n */\n\nimport { useEffect, useState, type ReactNode } from 'react'\nimport type { Translate } from '../i18n'\n\nexport type FetchMissState = 'idle' | 'loading' | 'absent' | 'failed'\n\nexport interface FetchOnMiss<T> {\n /** Resolved values by key (immutable history — a landed value never refetches). */\n values: Map<number, T>\n state: FetchMissState\n /** Re-arm the read after a failure (the retry button). */\n retry: () => void\n}\n\n/**\n * Run one fetch for `key` when it is set and not yet cached. `key` null (no\n * target open) or `fetcher` undefined (older host without the history face)\n * leaves the machine idle; the caller renders the matching note either way.\n */\nexport function useFetchOnMiss<T>(\n key: number | null,\n fetcher: ((key: number) => Promise<T | null>) | undefined,\n warn: string,\n): FetchOnMiss<T> {\n const [values, setValues] = useState<Map<number, T>>(() => new Map())\n const [state, setState] = useState<FetchMissState>('idle')\n const [attempt, setAttempt] = useState(0)\n useEffect(() => {\n if (key === null || fetcher === undefined || values.has(key)) return\n let live = true\n setState('loading')\n fetcher(key).then((value) => {\n if (!live) return\n if (value === null) {\n setState('absent')\n return\n }\n setValues((prev) => {\n const next = new Map(prev)\n next.set(key, value)\n return next\n })\n setState('idle')\n }, (error: unknown) => {\n console.warn(warn, error)\n if (live) setState('failed')\n })\n return () => { live = false }\n }, [key, fetcher, attempt, values])\n return { values, state, retry: () => { setAttempt(a => a + 1) } }\n}\n\n/**\n * The note a not-yet-loaded fetch target shows — one expression for both\n * on-demand reads: the legacy static hint (`emptyKey`) when no fetcher is\n * composed, `loading` while the read is in flight (and on the first frame\n * before the effect fires), `notInLog` when the durable log does not hold\n * the key, and a retry button after a failed read.\n */\nexport function fetchMissNote(\n t: Translate,\n fetcher: unknown,\n state: FetchMissState,\n onRetry: () => void,\n emptyKey: 'browser.noContent' | 'browser.headerMetaOnly',\n): ReactNode {\n if (fetcher === undefined) return t(emptyKey)\n if (state === 'absent') return t('browser.notInLog')\n if (state === 'failed') {\n return (\n <button type=\"button\" className=\"redline-br-retry hover:brightness-[1.15]\" onClick={onRetry}>\n {t('browser.loadFailed')}\n </button>\n )\n }\n return t('browser.loading')\n}\n","/**\n * Generation-proof named imports from the ui-primitives platform module.\n *\n * The icon vocabulary renamed across the supported range — `Icon*Outline16` /\n * `Icon*Outline14` through 0.1.5, `Icon*OutlineRegular` / `Icon*OutlineMedium`\n * from 0.1.6 — and a renamed export arrives as `undefined` at runtime (the\n * pinned devDep's types cannot see the other generation), which rendered as\n * React error #130 inside the Context tab. Each icon here resolves through\n * BOTH spellings at module load, modern first; a render-nothing fallback keeps\n * a future rename a missing glyph instead of a crashed tab.\n */\n\nimport type { ReactElement } from 'react'\nimport * as primitives from '@deepseek-ai/dsh-client-ui-primitives'\nimport type { IconProps } from '@deepseek-ai/dsh-client-ui-primitives'\n\n/** One platform icon component, as the call sites render it. */\nexport type IconComponent = (props: IconProps) => ReactElement | null\n\n/** The platform module's export surface, read by name (the two vocabularies meet here). */\nconst ns = primitives as unknown as Record<string, unknown>\n\n/**\n * Read one export through a bounded catch: partial module mocks (and any\n * hostile namespace) may throw on the property access itself, which must\n * degrade to \"not this spelling\", never crash the importer.\n */\nfunction read(source: Record<string, unknown>, key: string): unknown {\n try {\n return source[key]\n } catch {\n return undefined\n }\n}\n\n/**\n * Resolve one icon across the range's two spellings: the modern\n * `…OutlineRegular`/`…OutlineMedium` name first, then the legacy\n * `…Outline16`/`…Outline14` one; neither present (or not a component)\n * renders nothing. `source` overrides the platform namespace for tests.\n */\nexport function resolveIcon(modern: string, legacy: string, source: Record<string, unknown> = ns): IconComponent {\n const found = read(source, modern) ?? read(source, legacy)\n return typeof found === 'function' ? found as IconComponent : () => null\n}\n\nexport const IconBranch = resolveIcon('IconBranchOutlineRegular', 'IconBranchOutline16')\nexport const IconPlus = resolveIcon('IconPlusOutlineRegular', 'IconPlusOutline16')\nexport const IconCheck = resolveIcon('IconCheckOutlineRegular', 'IconCheckOutline16')\nexport const IconCopy = resolveIcon('IconCopyOutlineRegular', 'IconCopyOutline16')\nexport const IconClose = resolveIcon('IconCloseOutlineRegular', 'IconCloseOutline16')\nexport const IconSettings = resolveIcon('IconSettingsOutlineMedium', 'IconSettingsOutline14')\nexport const IconChevronDown = resolveIcon('IconChevronDownOutlineMedium', 'IconChevronDownOutline14')\n","/** `fmt`: the k/M/B suffix style shared by bars/details/stats; `fmtTime`: local HH:MM:SS. */\n\nexport function fmt(n: number | null | undefined): string {\n if (n === undefined || n === null || isNaN(n)) return '—'\n const sign = n < 0 ? '-' : ''\n const a = Math.abs(n)\n if (a >= 1e9) return sign + (a / 1e9).toFixed(1) + 'B'\n if (a >= 1e6) return sign + (a / 1e6).toFixed(1) + 'M'\n if (a >= 1000) return sign + (a / 1000).toFixed(1) + 'k'\n return sign + String(Math.round(a))\n}\n\n/** Byte sizes for attachment metadata (1 kB = 1000 B, matching the k/M style of `fmt`). */\nexport function fmtBytes(n: number | null | undefined): string {\n if (n === undefined || n === null || isNaN(n) || n < 0) return '—'\n if (n >= 1e6) return (n / 1e6).toFixed(1) + ' MB'\n if (n >= 1000) return (n / 1000).toFixed(1) + ' kB'\n return String(Math.round(n)) + ' B'\n}\n\n/**\n * Cache-hit share of billed prompt-side input (`reads` over `billed`),\n * TRUNCATED to `decimals` places (cut, not round) — same formula as the\n * harness chat stats line's '缓存命中' figure and the stats board's cell\n * (which shows two decimals). Null when nothing was billed. The 1e-9 epsilon\n * absorbs only float noise (integer token counts never sit that close to a\n * boundary).\n */\nexport function cacheHitPercent(reads: number, billed: number, decimals = 2): string | null {\n if (!(billed > 0)) return null\n const factor = 10 ** decimals\n const scaled = Math.trunc((reads / billed) * 100 * factor + 1e-9)\n return `${Math.floor(scaled / factor)}.${String(scaled % factor).padStart(decimals, '0')}`\n}\n\nexport function fmtTime(t: number): string {\n // en-GB 24-hour clock zero-pads HH:MM:SS without a helper; invalid dates must show '—' (toLocaleTimeString throws RangeError).\n const d = new Date(t)\n if (isNaN(d.getTime())) return '—'\n return d.toLocaleTimeString('en-GB', { hour12: false })\n}\n\n/**\n * Share of a whole as a compact leading percentage for the slice rows:\n * '—' when nothing totals, '0.0%' for empty slices, '<0.1%' for non-zero\n * crumbs a 0.1%-precision figure would erase. One decimal everywhere; shares\n * cap at 100% (parallel tool time can over-run the wall it belongs to).\n */\nexport function fmtShare(part: number, total: number): string {\n if (!Number.isFinite(part) || !Number.isFinite(total) || total <= 0) return '—'\n if (part <= 0) return '0.0%'\n const pct = Math.min(1, part / total) * 100\n if (pct < 0.1) return '<0.1%'\n return `${pct.toFixed(1)}%`\n}\n\n/**\n * Whole-session durations for the timing card, locale-free compact units: raw\n * ms under a second, one-decimal seconds under a minute, then m/s and h/m.\n * Non-finite or non-positive input shows the dash (callers render their empty\n * state anyway).\n */\nexport function fmtDuration(ms: number): string {\n if (!Number.isFinite(ms) || ms <= 0) return '—'\n if (ms < 1000) return `${Math.round(ms)}ms`\n if (ms < 60_000) return `${(ms / 1000).toFixed(1)}s`\n const totalSec = Math.floor(ms / 1000)\n const m = Math.floor(totalSec / 60)\n const s = totalSec % 60\n if (ms < 3_600_000) return `${m}m${s}s`\n return `${Math.floor(m / 60)}h${m % 60}m`\n}\n","/**\n * Per-image token estimate for DeepSeek's vision model — a faithful port of\n * the official \"图片 Token 计算器\" (Image Token Calculator) shipped on the\n * DeepSeek API docs (https://api-docs.deepseek.com/zh-cn/quick_start/token_usage),\n * which implements the provider's own image→token conversion:\n *\n * - every image is aspect-preserved rescaled before entering the model:\n * below ~384×384 total pixels it is enlarged, above it is shrunk;\n * - tokens follow the patch grid (patch 14px, downsample 3), so every\n * image costs at least 117 and at most ~384 tokens (the documented cap).\n *\n * Verified against the docs calculator itself: 2048×1365→313, 800×600→341,\n * 2048×2048→349, 512×512→201, 100×100→117, 1920×1080→369, 400×900→249.\n * The DSH request pipeline's own 640k-pixel pre-resize does not change the\n * result (the provider formula rescales to the same patch grid), so the\n * durable attachment dimensions can be fed in directly.\n *\n * Pure math shared by the Host fold (message pricing) and the Client\n * (attachment card token badges) — no dependencies, never mutates.\n */\n\nconst PATCH_SIZE = 14\nconst DOWNSAMPLE_RATIO = 3\n/** Documented per-image token cap ( DeepSeek vision guide ). */\nconst MAX_TOKENS = 384\nconst COMPRESS_PAD_TO = 4\nconst MAX_WH_RATIO = 8\n/** ~384×384 total pixels: smaller images are enlarged before patching. */\nconst MIN_PIXELS = 147456\n\nconst floorDiv = (a: number, b: number): number => Math.floor(a / b)\nconst ceilDiv = (a: number, b: number): number => Math.floor((a + b - 1) / b)\n\nfunction gridTokens(rows: number, cols: number): number {\n let n = rows * (cols + 1) + 2\n if (rows % 2 === 1) n += cols + 1\n n += (ceilDiv(rows, 2) * (cols + 1) % 2) * 2\n return n\n}\n\ninterface ResizeSolution {\n nLlmH: number\n nLlmW: number\n bestHeight: number\n bestWidth: number\n numTokens: number\n}\n\n/** Solve the largest in-grid resize whose token count fits `budget`. */\nfunction solveResizeRatio(height: number, width: number, budget: number): ResizeSolution {\n const ratio = height / width\n const gridW = Math.sqrt((budget - 2) / ratio + 0.25) - 0.5\n const gridH = gridW * ratio\n const unit = PATCH_SIZE * DOWNSAMPLE_RATIO\n let bestHeight: number\n let bestWidth: number\n if (gridW < 1) {\n // Tall image: width collapses to one unit, height takes the budget.\n let rows = floorDiv(budget - 2, 2)\n /* v8 ignore else -- budget enters at 381 and the tall solve always fits\n (never decrements), so rows is always odd here; parity-defensive. */\n if (rows % 2 === 1) rows -= 1\n bestWidth = unit\n bestHeight = rows * unit\n /* v8 ignore start -- unreachable: the MAX_WH_RATIO clamp in\n calcResizeInner keeps height/width ≥ 1/8, so gridH = gridW × ratio\n can never fall below 2 (500k-dimension fuzz: wide = 0 hits); the arm\n is kept verbatim from the official calculator port. */\n } else if (gridH < 2) {\n // Wide image: height collapses to two units, width takes the budget.\n const cols = floorDiv(budget - 2, 2) - 1\n if (cols <= 1) throw new Error('image tokens: budget too small to solve')\n bestHeight = 2 * unit\n bestWidth = cols * unit\n /* v8 ignore stop */\n } else {\n const cols = Math.trunc(gridW)\n // The row grid carries the pairing constraint: odd counts round down.\n let rows = Math.trunc(gridH)\n if (rows % 2 === 1) rows -= 1\n const scale = Math.min(cols * unit / width, rows * unit / height)\n bestWidth = Math.trunc(width * scale / PATCH_SIZE) * PATCH_SIZE\n bestHeight = Math.trunc(height * scale / PATCH_SIZE) * PATCH_SIZE\n }\n const nLlmH = ceilDiv(floorDiv(bestHeight, PATCH_SIZE), DOWNSAMPLE_RATIO)\n const nLlmW = ceilDiv(floorDiv(bestWidth, PATCH_SIZE), DOWNSAMPLE_RATIO)\n return { nLlmH, nLlmW, bestHeight, bestWidth, numTokens: gridTokens(nLlmH, nLlmW) }\n}\n\n/** Resize so the patch grid fits the cap, then re-add the pad reserve. */\nfunction safeResize(height: number, width: number, paddedHeight: number, paddedWidth: number): ResizeSolution {\n const nLlmH = ceilDiv(floorDiv(paddedHeight, PATCH_SIZE), DOWNSAMPLE_RATIO)\n const nLlmW = ceilDiv(floorDiv(paddedWidth, PATCH_SIZE), DOWNSAMPLE_RATIO)\n const pad = COMPRESS_PAD_TO - 1\n const budget = MAX_TOKENS - pad\n let result: ResizeSolution = {\n nLlmH, nLlmW, bestHeight: paddedHeight, bestWidth: paddedWidth,\n numTokens: gridTokens(nLlmH, nLlmW),\n }\n if (result.numTokens > budget) {\n result = solveResizeRatio(height, width, budget)\n let nextBudget = budget\n while (result.numTokens > budget) {\n nextBudget -= 1\n result = solveResizeRatio(height, width, nextBudget)\n }\n }\n result.numTokens += pad\n return result\n}\n\nfunction calcResizeInner(width: number, height: number): ResizeSolution {\n let w = width\n let h = height\n if (w > h * MAX_WH_RATIO) w = h * MAX_WH_RATIO\n const pixels = w * h\n if (pixels < MIN_PIXELS && pixels > 0) {\n const scale = Math.sqrt(MIN_PIXELS / pixels)\n w = Math.trunc(w * scale)\n h = Math.trunc(h * scale)\n }\n const paddedWidth = ceilDiv(w, PATCH_SIZE) * PATCH_SIZE\n const paddedHeight = ceilDiv(h, PATCH_SIZE) * PATCH_SIZE\n return safeResize(h, w, paddedHeight, paddedWidth)\n}\n\n/**\n * Estimate the tokens one image consumes in a DeepSeek vision request from its pixel dimensions. Returns null for non-positive/non-finite\n * dimensions or when the official iteration fails to converge — callers fall back to the generic structural price.\n */\nexport function estimateImageTokens(width: number, height: number): number | null {\n if (!Number.isFinite(width) || !Number.isFinite(height) || width <= 0 || height <= 0) return null\n try {\n let result = calcResizeInner(width, height)\n for (let i = 1; i < 10; i++) {\n const next = calcResizeInner(result.bestWidth, result.bestHeight)\n if (next.nLlmH === result.nLlmH && next.nLlmW === result.nLlmW\n && next.bestHeight === result.bestHeight && next.bestWidth === result.bestWidth\n && next.numTokens === result.numTokens) return result.numTokens\n result = next\n }\n return null\n } catch {\n /* v8 ignore next -- the only throw site is the clamped-away budget guard\n above; the catch keeps a hostile dimension from ever breaking the fold. */\n return null\n }\n}\n","/**\n * dsh's multimodal pipeline stores only a normalized reference per image (never inline bytes); the block carries everything the card needs\n * except the display URL, which comes from the harness `uiConversation` service's `imageUrl` (the same loader the chat history rides on),\n * handed down as `load`; absent loader or failed load degrades to the metadata row alone — the card never throws.\n */\n\nimport { useCallback, useEffect, useRef, useState, type ReactElement } from 'react'\nimport { createPortal } from 'react-dom'\nimport { IconClose } from '../primitives'\nimport { fmtBytes } from '../format'\nimport type { ImageLoader, ImageRefLike } from '../services'\nimport { estimateImageTokens } from '../../shared/imageTokens'\nimport type { ViewKit } from '../viewkit'\n\nexport interface ImageKit {\n Card: (props: { attachment: ImageRefLike; load?: ImageLoader }) => ReactElement\n load?: ImageLoader\n}\n\n/**\n * Narrow an unknown content block to a durable image ref: accepts both raw message blocks (`{ type: 'image', attachment }`) and the\n * snapshot's assistant blocks (`{ kind: 'image', attachment }`); everything else null. Lenient on the optional facts — imageUrl reads\n * only attachmentId.\n */\nexport function imageRefOf(block: unknown): ImageRefLike | null {\n if (block === null || typeof block !== 'object') return null\n const b = block as { type?: unknown; kind?: unknown; attachment?: unknown }\n if (b.type !== 'image' && b.kind !== 'image') return null\n const a = b.attachment\n if (a === null || typeof a !== 'object') return null\n const r = a as Record<string, unknown>\n if (typeof r.attachmentId !== 'string' || r.attachmentId === '') return null\n const num = (v: unknown): number | undefined =>\n typeof v === 'number' && Number.isFinite(v) && v > 0 ? v : undefined\n const orig = r.originalDimensions !== null && typeof r.originalDimensions === 'object'\n ? r.originalDimensions as Record<string, unknown>\n : undefined\n const origDims = orig !== undefined && num(orig.width) !== undefined && num(orig.height) !== undefined\n ? { width: num(orig.width) as number, height: num(orig.height) as number }\n : undefined\n return {\n attachmentId: r.attachmentId,\n ...(typeof r.name === 'string' && r.name !== '' ? { name: r.name } : {}),\n ...(num(r.bytes) !== undefined ? { bytes: num(r.bytes) } : {}),\n ...(num(r.width) !== undefined ? { width: num(r.width) } : {}),\n ...(num(r.height) !== undefined ? { height: num(r.height) } : {}),\n ...(origDims !== undefined ? { originalDimensions: origDims } : {}),\n }\n}\n\n/**\n * Document-level original-image preview — the chat history's ImageLightbox recipe (dsh ui-attachment, which the browser module table does\n * not seed) ported onto the plugin's redline-* classes: body portal (a transformed/filtered ancestor cannot trap the fixed\n * backdrop), blurred\n * mask, contain-fit image, circular close, Escape/mask close, focus restored to the opener.\n */\nfunction AttachmentLightbox(props: {\n src: string\n alt: string\n labels: { dialog: string; close: string }\n onClose: () => void\n}): ReactElement {\n const { src, alt, labels, onClose } = props\n const closeRef = useRef<HTMLButtonElement | null>(null)\n const restoreRef = useRef<HTMLElement | null>(null)\n\n useEffect(() => {\n restoreRef.current = document.activeElement instanceof HTMLElement ? document.activeElement : null\n closeRef.current?.focus()\n const onKeyDown = (event: KeyboardEvent): void => {\n if (event.key === 'Escape') onClose()\n }\n window.addEventListener('keydown', onKeyDown)\n return () => {\n window.removeEventListener('keydown', onKeyDown)\n restoreRef.current?.focus()\n }\n }, [onClose])\n\n return createPortal(\n <div className=\"redline-att-lightbox\" role=\"dialog\" aria-modal=\"true\" aria-label={labels.dialog}>\n <div className=\"redline-att-lightbox-mask\" aria-hidden=\"true\" onMouseDown={onClose} />\n <img className=\"redline-att-lightbox-img\" src={src} alt={alt} />\n <button ref={closeRef} type=\"button\" className=\"redline-att-lightbox-close\" aria-label={labels.close} onClick={onClose}>\n <IconClose size={16} />\n </button>\n </div>,\n document.body,\n )\n}\n\n/**\n * One attachment card, the WHOLE card the click target: 64px cover tile + metadata column — Raw (the pre-normalization raster dsh records\n * when normalization reduced the image), Sent (the normalized raster the model receives, with byte size), estimated provider-billed tokens.\n * Click opens the chat-style lightbox; load failures retry on click; unknown facts leave no row.\n */\nexport function makeImageCard(kit: ViewKit): ImageKit['Card'] {\n const { t, fmt } = kit\n return function ImageCard(props: { attachment: ImageRefLike; load?: ImageLoader }): ReactElement {\n const { attachment, load } = props\n const [src, setSrc] = useState<string | null>(null)\n const [error, setError] = useState(false)\n const [attempt, setAttempt] = useState(0)\n const [preview, setPreview] = useState(false)\n const closePreview = useCallback(() => { setPreview(false) }, [])\n\n useEffect(() => {\n if (load === undefined) return\n let live = true\n setError(false)\n setSrc(null)\n void load(attachment).then((url) => { if (live) setSrc(url) }).catch(() => { if (live) setError(true) })\n return () => { live = false }\n }, [attachment, load, attempt])\n\n const name = attachment.name ?? t('attach.image')\n const dimsOf = (w: number | undefined, h: number | undefined): string | null =>\n w !== undefined && h !== undefined ? `${w}×${h}` : null\n const rows: Array<{ label: string; value: string; tip?: string }> = []\n // No byte size is stored for the raw raster — dims only.\n const raw = attachment.originalDimensions !== undefined\n ? dimsOf(attachment.originalDimensions.width, attachment.originalDimensions.height)\n : null\n if (raw !== null) rows.push({ label: t('attach.raw'), value: raw })\n const sent = dimsOf(attachment.width, attachment.height)\n if (sent !== null) {\n rows.push({\n label: t('attach.sent'),\n value: attachment.bytes !== undefined ? `${sent} · ${fmtBytes(attachment.bytes)}` : sent,\n })\n }\n // Estimated provider-billed tokens (shared/imageTokens — the official docs calculator on the stored dimensions; 117–384 per the vision\n // guide's cap), shown whenever normalized dimensions are known.\n const tokens = attachment.width !== undefined && attachment.height !== undefined\n ? estimateImageTokens(attachment.width, attachment.height)\n : null\n if (tokens !== null) rows.push({ label: t('attach.token'), value: `≈${fmt(tokens)}`, tip: t('attach.tokensTip') })\n\n const activate = (): void => {\n if (error) { setAttempt(a => a + 1); return }\n if (src !== null) setPreview(true)\n }\n return (\n <>\n <button\n type=\"button\"\n className=\"redline-att-item hover:border-(--dsw-alias-label-dimmed) hover:bg-[var(--dsw-alias-interactive-bg-hover,var(--dsw-alias-bg-layer-2))]\"\n title={error ? t('attach.loadFailed') : t('attach.open')}\n onClick={activate}\n >\n <span className=\"redline-att-thumb\">\n {src !== null\n ? <img src={src} alt={name} />\n : (\n <span className={error ? 'redline-att-err' : 'redline-att-ph'}>\n {error ? '⚠' : load === undefined ? '🖼' : t('attach.loading')}\n </span>\n )}\n </span>\n <span className=\"redline-att-meta\">\n <span className=\"redline-att-name\" title={name}>{name}</span>\n {rows.map(r => (\n <span key={r.label} className=\"redline-att-row\" title={r.tip}>\n <b className=\"redline-att-row-label\">{r.label}</b>{r.value}\n </span>\n ))}\n </span>\n </button>\n {preview && src !== null && (\n <AttachmentLightbox\n src={src}\n alt={name}\n labels={{ dialog: t('attach.preview'), close: t('attach.close') }}\n onClose={closePreview}\n />\n )}\n </>\n )\n }\n}\n","/**\n * RichText — the raw/markdown body for the Context browser's detail sections. Markdown renders via the harness's shared MarkdownText (GFM,\n * sanitized, resolved from the platform module table — zero plugin-side markdown dependency); raw is a line-numbered `<pre>`. The Raw/MD\n * switch sits at a section head's right edge (RichSwitch; per-card mode via useRichMode), with the copy-raw control (RichCopy) beside it.\n */\n\nimport { useCallback, useMemo, useState, type ReactElement } from 'react'\nimport { MarkdownText, writeClipboard } from '@deepseek-ai/dsh-client-ui-primitives'\nimport { IconCheck, IconCopy } from '../primitives'\nimport type { ViewKit } from '../viewkit'\n\nexport type RichMode = 'raw' | 'md'\n\n/**\n * The Markdown chrome the harness primitives serve as a required `labels`\n * prop. Typed locally so the plugin typechecks without a primitives\n * dependency.\n */\ninterface MarkdownChrome {\n code: { copyLabel: string; copiedLabel: string }\n footnotes: string\n}\n\nconst Markdown = MarkdownText as (props: { text: string; labels?: MarkdownChrome }) => ReactElement\n\nexport interface RichKit {\n RichText: (props: { text: string; mode: RichMode }) => ReactElement\n RichSwitch: (props: { mode: RichMode; onPick: (mode: RichMode) => void }) => ReactElement\n RichCopy: (props: { text: string }) => ReactElement\n useRichMode: () => [RichMode, (mode: RichMode) => void]\n}\n\nexport function makeRichText(kit: ViewKit): RichKit {\n const { t } = kit\n\n function useRichMode(): [RichMode, (mode: RichMode) => void] {\n // Markdown is the default view: the detail cards hold prose (prompts,\n // descriptions, messages), which reads better rendered; raw stays one\n // click away for exact source inspection.\n const [mode, setMode] = useState<RichMode>('md')\n return [mode, setMode]\n }\n\n function RichSwitch(props: { mode: RichMode; onPick: (mode: RichMode) => void }): ReactElement {\n const seg = (m: RichMode, label: string, tip: string) => (\n <button\n type=\"button\"\n className={'redline-rich-seg-btn' + (props.mode === m ? ' redline-rich-seg-on' : '')}\n title={tip}\n onClick={() => { props.onPick(m) }}\n >{label}</button>\n )\n return (\n <span className=\"redline-rich-seg\">\n {seg('raw', t('rich.raw'), t('rich.toRaw'))}\n {seg('md', t('rich.md'), t('rich.toMd'))}\n </span>\n )\n }\n\n // One block per source line: the number is a counter-fed ::before glued to\n // its own line across soft wraps, and pseudo content never reaches the\n // clipboard, so selecting the body still copies the exact source text.\n function RawText(props: { text: string }): ReactElement {\n const lines = useMemo(() => {\n const parts = props.text.split('\\n')\n return parts.length > 1 && parts[parts.length - 1] === '' ? parts.slice(0, -1) : parts\n }, [props.text])\n return (\n <pre className=\"redline-ts-desc-body redline-ts-lines\">\n {lines.map((line, index) => (\n <span key={index} className=\"redline-ts-line\">{line}</span>\n ))}\n </pre>\n )\n }\n\n // Icon-only copy of the section's exact source (always the raw text, never\n // the rendered markdown). The write and its transient confirmation follow\n // the harness's own code-block control: a rejected host write claims no\n // success, a second click during the window is a no-op, and the glyph\n // resets after a beat.\n function RichCopy(props: { text: string }): ReactElement {\n const [copied, setCopied] = useState(false)\n const onCopy = useCallback(() => {\n if (copied) return\n void writeClipboard(props.text).then((ok) => {\n if (!ok) return\n setCopied(true)\n window.setTimeout(() => { setCopied(false) }, 1200)\n })\n }, [copied, props.text])\n const label = copied ? t('rich.copied') : t('rich.copy')\n return (\n <button\n type=\"button\"\n className={'redline-rich-copy' + (copied ? ' redline-rich-copy-on' : '')}\n title={label}\n aria-label={label}\n onClick={onCopy}\n >\n {copied ? <IconCheck size={13} /> : <IconCopy size={13} />}\n </button>\n )\n }\n\n function RichText(props: { text: string; mode: RichMode }): ReactElement {\n // Reference-stable per locale: a fresh object identity would discard the\n // renderer's cached elements on every render (0.1.2+ faces).\n const mdLabels = useMemo<MarkdownChrome>(() => ({\n code: { copyLabel: t('rich.md.copy'), copiedLabel: t('rich.md.copied') },\n footnotes: t('rich.md.footnotes'),\n }), [t])\n if (props.mode === 'md') {\n return <div className=\"redline-ts-desc-md\"><Markdown text={props.text} labels={mdLabels} /></div>\n }\n return <RawText text={props.text} />\n }\n\n return { RichText, RichSwitch, RichCopy, useRichMode }\n}\n","import { useEffect, useId, useLayoutEffect, useMemo, useRef, useState, type ChangeEvent, type ReactElement, type ReactNode } from 'react'\nimport { UNKNOWN_TOOL_SOURCE, type Category, type ContextHeaders, type ContextTimeline, type HeaderTool, type RequestRecord, type SurfaceNode } from '../../shared/types'\nimport { assemble } from '../assemble'\nimport type { Assembled } from '../assemble'\nimport { CATS, CAT_COLOR, partsOf } from '../categories'\nimport { dnaOf } from '../dna'\nimport type { DnaItem } from '../dna'\nimport type { ContentFetcher, ConversationNodeLike, HeaderFetcher } from '../services'\nimport type { ContextSettings, DefaultToolSort } from '../settings'\nimport type { ViewKit } from '../viewkit'\nimport { blockSummaryOf, callSummaryOf, parseCallArgs } from '../callSummary'\nimport type { DetailState } from '../timelineSource'\nimport { makeDetailNote } from './detailNote'\nimport { makeRedlineActions, makeRedlineEditor, type RedlineSubmit } from './redlineEdit'\nimport { ability, durableTypeOf, type Ability } from '../../shared/redline-ability'\nimport { effectiveIsError, effectiveReasoning, effectiveText, hasLocalEdit, isDeleted } from '../../shared/redline-drafts'\nimport type { RedlineRow } from '../redlineChannel'\nimport type { RedlineDraftController } from '../redlineDrafts'\nimport { makeNodeText } from './nodes'\nimport { turnStepsOf } from './trendChart'\nimport { fetchMissNote, useFetchOnMiss } from './fetchOnMiss'\nimport { imageRefOf, makeImageCard } from './images'\nimport type { ImageKit } from './images'\nimport { makeRichText } from './richText'\nimport type { RichKit } from './richText'\nimport type { StackedBarProps } from './stackedBar'\nimport type { ImageLoader, ImageRefLike } from '../services'\n\nexport interface ContextBrowserProps {\n data: ContextTimeline\n headers: ContextHeaders | null\n /**\n * The conversation-window nodes, resolved by the caller from the `useChat`\n * seat — the browser itself stays seat-free so the hook order lives in\n * exactly one place.\n */\n convNodes?: readonly ConversationNodeLike[]\n /**\n * Targeted full-content fetch for nodes outside the conversation window:\n * one seq-anchored history read per expanded row (absent on older hosts —\n * those keep the preview-plus-hint degradation).\n */\n fetchContent?: ContentFetcher\n /**\n * On-demand CONTENT fetch for the selected step's `redlineHeaders` epoch\n * (system prompt text, tool descriptions/schemas) — one seq-anchored\n * history read per epoch, cached per session (absent on older hosts —\n * those keep the metadata-only degradation).\n */\n fetchHeader?: HeaderFetcher\n /** Preview-seq: hover transiently previews that step; the picker's own selection resumes when the pointer leaves the chart. */\n previewSeq?: number | null\n /** Pin-seq: a pin selects that step; pinSeq null returns the browser to the live surface. */\n pinSeq?: number | null\n /**\n * One-shot reveal request from the step brief: select the step, open the category and the node element, scroll it into view;\n * handed back via `onNodeFocusHandled` so the same row can fire again.\n */\n nodeFocus?: { step: number | 'live'; seq: number; cat: Category } | null\n onNodeFocusHandled?: () => void\n /**\n * The local-edit controller (`redlineDrafts.ts`): a row's `编辑` reads the FULL\n * text through it and its `保存` writes the plugin's own store — never the\n * session (the hard constraint, `docs/11` D15).\n */\n redline: RedlineDraftController\n hoverKey?: string | null\n onHoverKey?: (key: string | null) => void\n /**\n * Reports the open category (null once none opens): the Context tab focuses the trend chart's bars on it.\n * Absent (the /redline modal) — the accordion stays purely internal.\n */\n onOpenCat?: (cat: string | null) => void\n loadImage?: ImageLoader\n /**\n * The timeline source's detail state (split generation): while the first\n * detail read is pending or settled without data, a note strip names the\n * state (the picker/sections otherwise show a misleading empty surface).\n */\n detailState?: DetailState\n onDetailRetry?: () => void\n}\n\ninterface ParamSchema {\n type?: unknown\n description?: unknown\n enum?: unknown\n items?: unknown\n anyOf?: unknown\n oneOf?: unknown\n}\n\nfunction unionTypesOf(p: ParamSchema): string | null {\n const branches: unknown[] = []\n if (Array.isArray(p.anyOf)) branches.push(...p.anyOf as unknown[])\n if (Array.isArray(p.oneOf)) branches.push(...p.oneOf as unknown[])\n if (branches.length === 0) return null\n const parts: string[] = []\n for (const b of branches) {\n if (b !== null && typeof b === 'object') parts.push(typeOf(b))\n }\n return parts.length > 0 ? parts.join(' | ') : null\n}\n\nfunction typeOf(p: ParamSchema): string {\n const u = unionTypesOf(p)\n if (u !== null) return u\n const t = p.type\n if (t === 'array') {\n const items = p.items\n if (items !== null && typeof items === 'object') {\n const inner = typeOf(items)\n return 'array<' + inner + '>'\n }\n return 'array'\n }\n if (typeof t === 'string') {\n if (t === 'object') {\n const props = (p as { properties?: unknown }).properties\n if (props !== null && typeof props === 'object' && Object.keys(props).length > 0) {\n return `object{${Object.keys(props).length}}`\n }\n }\n if (Array.isArray(p.enum) && p.enum.length > 0) {\n return t + ' (enum)'\n }\n return t\n }\n if (Array.isArray(p.enum) && p.enum.length > 0) return '(enum)'\n return 'unknown'\n}\n\n/**\n * Tool schemas nest parameters under `parameters`, `input_schema`, or `inputSchema` (producer-dependent), or bare when `type === 'object'`\n * — `{type:'object', properties}` at the root is itself the parameter object.\n */\nfunction paramsOf(schema: unknown): ParamSchema | null {\n if (schema === null || typeof schema !== 'object') return null\n const s = schema as Record<string, unknown>\n const candidate = (v: unknown): ParamSchema | null =>\n v !== null && typeof v === 'object' ? v : null\n const nested = candidate(s.parameters) ?? candidate(s.input_schema)\n ?? candidate(s.inputSchema)\n if (nested !== null) return nested\n if (s.type === 'object' && s.properties !== undefined && typeof s.properties === 'object') {\n return s\n }\n return null\n}\n\nfunction ParamRow(props: {\n name: string\n schema: ParamSchema\n required: boolean\n}): ReactElement {\n const typeLabel = typeOf(props.schema)\n const desc = props.schema.description\n return (\n <div className=\"redline-ts-param-row\">\n <span className=\"redline-ts-param-name\">{props.name}</span>\n <span className=\"redline-ts-param-type\">{typeLabel}</span>\n <span className={props.required ? 'redline-ts-param-req' : 'redline-ts-param-req-off'}>\n {props.required ? '✓' : '·'}\n </span>\n {typeof desc === 'string' && desc !== ''\n ? <span className=\"redline-ts-param-desc\">{desc}</span>\n : null}\n </div>\n )\n}\n\n/**\n * Section — the ONE detail chrome of the browser: every expanded element is a stack of these (labeled head + body), so the reader scans one\n * repeating anatomy per content kind.\n */\nfunction Section(props: {\n label: string\n labelClass?: string\n /** Fold the head's trailing group onto a second line under width pressure (rich-text heads; the call-name head must stay one-line). */\n foldHead?: boolean\n count?: number\n actions?: ReactNode\n meta?: ReactNode\n children: ReactNode\n}): ReactElement {\n const right = props.actions !== undefined || props.meta !== undefined\n return (\n <div className=\"redline-ts-card\">\n <div className={'redline-ts-card-head' + (props.foldHead === true ? ' redline-ts-card-head-wrap' : '')}>\n {/* The title recovers an ellipsized label: long mono call names truncate under width pressure. */}\n <b className={props.labelClass} title={props.label}>{props.label}</b>\n {right ? <span className=\"redline-ts-card-right\">{props.meta}{props.actions}</span> : null}\n {props.count !== undefined ? <span className=\"redline-ts-card-count\">{props.count}</span> : null}\n </div>\n {props.children}\n </div>\n )\n}\n\nfunction lineCountOf(text: string): number {\n // Count logical lines for LF, CRLF, and lone CR output alike.\n return text.split(/\\r\\n|\\r|\\n/).length\n}\n\nfunction TextSection(props: {\n label: string\n text: string\n rich: RichKit\n lines: (n: number) => string\n}): ReactElement {\n const { rich } = props\n const [mode, setMode] = rich.useRichMode()\n const lineCount = useMemo(() => lineCountOf(props.text), [props.text])\n return (\n <Section\n label={props.label}\n foldHead\n actions={<>\n <rich.RichSwitch mode={mode} onPick={setMode} />\n <rich.RichCopy text={props.text} />\n </>}\n meta={<span className=\"redline-ts-card-meta\">{props.lines(lineCount)}</span>}\n >\n <rich.RichText text={props.text} mode={mode} />\n </Section>\n )\n}\n\nfunction RawSection(props: { label: string; text: string }): ReactElement {\n return (\n <Section label={props.label}>\n <pre className=\"redline-ts-desc-body redline-br-dim\">{props.text}</pre>\n </Section>\n )\n}\n\n/**\n * The search text of one tool's raw schema. The schema is log data this view\n * does not own — a hostile value (cyclic, throwing getters) degrades to no\n * matchable text instead of taking the row, or the browser, down.\n */\nfunction schemaTextOf(schema: unknown): string {\n try {\n return JSON.stringify(schema ?? '')\n } catch {\n return ''\n }\n}\n\n/**\n * The shared row-filter toolbar of a category body: a text input plus an\n * optional trailing control group (the tools' size/name sort). Stays mounted\n * on an empty match so the filter can always be cleared from the UI.\n */\nfunction RowToolbar(props: {\n value: string\n placeholder: string\n tip?: string\n onChange: (v: string) => void\n children?: ReactNode\n}): ReactElement {\n return (\n <div className=\"redline-br-toolctl\">\n <input\n className=\"redline-br-tool-search focus:border-(--dsw-alias-label-dimmed)\"\n value={props.value}\n placeholder={props.placeholder}\n onChange={(ev: ChangeEvent<HTMLInputElement>) => { props.onChange(ev.target.value) }}\n />\n {props.children !== undefined\n ? <span className=\"redline-gran\" role=\"group\" title={props.tip}>{props.children}</span>\n : null}\n </div>\n )\n}\n\n\n\n/**\n * Full tool-row body: description, parsed parameter table (when the schema carries one), raw JSON behind a per-row toggle — the JSON open\n * state is per-row so two expanded tools stay independent.\n */\nfunction ToolSchema(props: {\n description: string | undefined\n schema: unknown\n rich: RichKit\n lines: (n: number) => string\n labels: {\n desc: string\n title: string\n empty: string\n show: string\n hide: string\n }\n}): ReactElement {\n const { rich } = props\n const [jsonOpen, setJsonOpen] = useState(false)\n const params = useMemo(() => paramsOf(props.schema), [props.schema])\n const rows = useMemo<{ name: string; schema: ParamSchema; required: boolean }[]>(() => {\n if (params === null) return []\n const props = (params as { properties?: unknown }).properties\n if (props === null || typeof props !== 'object') return []\n const req = Array.isArray((params as { required?: unknown }).required)\n ? new Set(((params as { required: unknown[] }).required)\n .filter((x): x is string => typeof x === 'string'))\n : new Set<string>()\n const out: { name: string; schema: ParamSchema; required: boolean }[] = []\n for (const k of Object.keys(props)) {\n const v = (props as Record<string, unknown>)[k]\n if (v === null || typeof v !== 'object') continue\n out.push({ name: k, schema: v, required: req.has(k) })\n }\n return out\n }, [params])\n // Pretty-printed only while the row's JSON is open: a tools section lists\n // dozens of schemas, and eager stringification of every collapsed row\n // dominated the section's render cost.\n const schemaJson = useMemo(\n () => jsonOpen ? JSON.stringify(props.schema, null, 2) : '',\n [props.schema, jsonOpen],\n )\n return (\n <>\n {props.description !== undefined ? (\n <TextSection label={props.labels.desc} text={props.description} rich={rich} lines={props.lines} />\n ) : null}\n {params !== null && rows.length > 0 ? (\n <Section label={props.labels.title} count={rows.length}>\n {rows.map(r => <ParamRow key={r.name} name={r.name} schema={r.schema} required={r.required} />)}\n </Section>\n ) : params !== null ? (\n <div className=\"redline-ts-params-empty\">{props.labels.empty}</div>\n ) : null}\n <div className=\"redline-ts-json\">\n <button\n type=\"button\"\n className=\"redline-ts-json-toggle hover:text-(--dsw-alias-label-primary) hover:underline\"\n onClick={() => { setJsonOpen(o => !o) }}\n >{(jsonOpen ? '▾ ' : '▸ ') + (jsonOpen ? props.labels.hide : props.labels.show)}</button>\n {jsonOpen ? <pre className=\"redline-ts-desc-body redline-br-dim\">{schemaJson}</pre> : null}\n </div>\n </>\n )\n}\n\ninterface DetailLabels {\n thinking: string\n answer: string\n content: string\n result: string\n summary: string\n images: string\n other: string\n lines: (n: number) => string\n callState: (err: boolean, exit: number | null) => ReactNode\n}\n\n/**\n * Both block vocabularies normalize here — raw durable blocks (`type`: text/reasoning/tool-call/tool-result/image) and snapshot assistant\n * blocks (`kind`: text/reasoning/tool-call/image, argsRaw). Consecutive images group into one grid; every\n * rich text block carries the Raw/MD switch + line count; nested tool-result blocks flatten into the same flow.\n */\nfunction BlocksBody(props: {\n blocks: readonly unknown[]\n richable: boolean\n textLabel: string\n rich: RichKit\n img: ImageKit\n labels: DetailLabels\n}): ReactElement {\n const { rich, img, labels } = props\n const out: ReactNode[] = []\n let images: ImageRefLike[] = []\n const flushImages = (): void => {\n if (images.length === 0) return\n const group = images\n images = []\n out.push(\n <Section key={'img' + String(out.length)} label={labels.images} count={group.length}>\n <div className=\"redline-att-grid\">\n {group.map((a, i) => <img.Card key={`${a.attachmentId}:${i}`} attachment={a} load={img.load} />)}\n </div>\n </Section>,\n )\n }\n for (const b of props.blocks) {\n const image = imageRefOf(b)\n if (image !== null) { images.push(image); continue }\n flushImages()\n const blk = b !== null && typeof b === 'object'\n ? b as { type?: unknown; kind?: unknown; text?: unknown; name?: unknown; argsRaw?: unknown; arguments?: unknown; content?: unknown }\n : null\n const blockKind = blk !== null\n ? typeof blk.type === 'string' ? blk.type : typeof blk.kind === 'string' ? blk.kind : ''\n : ''\n if ((blockKind === 'text' || blockKind === 'reasoning') && typeof blk?.text === 'string') {\n const label = blockKind === 'reasoning' ? labels.thinking : props.textLabel\n out.push(<TextSection\n key={out.length}\n label={label}\n text={blk.text}\n rich={rich}\n lines={labels.lines}\n />)\n continue\n }\n if (blockKind === 'tool-call') {\n out.push(<ToolCallCard\n key={out.length}\n name={typeof blk?.name === 'string' ? blk.name : '?'}\n argsRaw={blk?.argsRaw ?? blk?.arguments}\n />)\n continue\n }\n if (blockKind === 'tool-result' && Array.isArray(blk?.content)) {\n out.push(<BlocksBody\n key={out.length}\n blocks={blk.content as unknown[]}\n richable={false}\n textLabel={labels.result}\n rich={rich}\n img={img}\n labels={labels}\n />)\n continue\n }\n out.push(<RawSection key={out.length} label={labels.other} text={JSON.stringify(b, null, 2)} />)\n }\n flushImages()\n return <>{out}</>\n}\n\n/**\n * The trailing status markers dsh shell tools append at the END of a result's text while `isError` stays false\n * (the status is result data, per tool-bash's render: \"non-zero exits are reported, not errored\"):\n * - one-shot bash/pwsh: `[exit code: N]` (non-zero only), `[killed by signal: X]`\n * - persistent shells: `[shell killed by signal: X]`, `[shell exited: code N]` — riding LAST, after the\n * `[exit code: N]` of the command whose failure killed the shell, so the command marker is re-checked\n * on the preceding text\n * - job_output: `[status: killed]` / `[status: failed, detail]` — the tool-jobs status line always terminates\n * the read; a killed/failed background job settles with `isError` false, so only the line flags the loss\n * End-anchored like dsh's own parseExitStatus, so marker text quoted inside the output (e.g. a cat'ed log)\n * is not a failure. A clean shell exit (code 0 or code-less) or a live/completed job status is a notice,\n * not a failure.\n * The parsed exit code feeds the FAILED run-state pill.\n */\nfunction tailStatusOf(conv: ConversationNodeLike | undefined): { fail: boolean; exit: number | null } {\n if (conv === undefined || !Array.isArray(conv.content)) return { fail: false, exit: null }\n for (const b of conv.content) {\n const text = (b as { text?: unknown } | null)?.text\n if (typeof text !== 'string') continue\n const tail = text.trimEnd()\n const shell = /\\[(shell killed by signal: [^\\]\\n]+|shell exited(?:: code \\d+)?)\\]$/.exec(tail)\n if (shell !== null) {\n const cmdExit = /\\[exit code:\\s*(\\d+)\\]\\s*$/.exec(tail.slice(0, shell.index))\n if (cmdExit !== null) return { fail: true, exit: Number(cmdExit[1]) }\n const code = /: code (\\d+)$/.exec(shell[1])\n if (code !== null) return { fail: code[1] !== '0', exit: code[1] === '0' ? null : Number(code[1]) }\n return { fail: shell[1].startsWith('shell killed'), exit: null }\n }\n const exit = /\\[exit code:\\s*(\\d+)\\]$/.exec(tail)\n if (exit !== null) return { fail: true, exit: Number(exit[1]) }\n if (/\\[killed by signal: [^\\]\\n]+\\]$/.test(tail)) return { fail: true, exit: null }\n if (/\\[status: (?:killed|failed)(?:, [^\\]\\n]*)?\\]$/.test(tail)) return { fail: true, exit: null }\n }\n return { fail: false, exit: null }\n}\n\n/**\n * A tool result's failure: the fold-stamped `err` or the snapshot's `isError` (infrastructure failures — dsh stamps\n * those) OR a trailing status marker (see tailStatusOf). dsh settles a failing COMMAND as a completed call, so the\n * marker is the only failure signal — mirroring the chat row's terminalFailed. A timeout stays a notice, as in the chat.\n */\nfunction toolErrOf(node: SurfaceNode, conv: ConversationNodeLike | undefined): { err: boolean; exit: number | null } {\n const tail = tailStatusOf(conv)\n const err = node.err === true || conv?.isError === true || tail.fail\n return { err, exit: tail.exit }\n}\n\nfunction ToolCallCard(props: {\n name: string\n argsRaw: unknown\n arrow?: string\n status?: ReactNode\n}): ReactElement {\n const args = useMemo(() => parseCallArgs(props.argsRaw), [props.argsRaw])\n return (\n <Section\n label={(props.arrow ?? '→') + ' ' + props.name}\n labelClass=\"redline-ts-call-name\"\n meta={props.status}\n >\n {args !== null\n ? Object.keys(args).map(k => <CallArgRow key={k} name={k} value={args[k]} />)\n : typeof props.argsRaw === 'string' && props.argsRaw !== ''\n ? <pre className=\"redline-ts-desc-body redline-br-dim\">{props.argsRaw}</pre>\n : null}\n </Section>\n )\n}\n\nfunction CallArgRow(props: { name: string; value: unknown }): ReactElement {\n const v = props.value\n /* v8 ignore next 2 -- the only caller maps Object.keys of a JSON.parse'd\n object, which never holds undefined values; defensive. */\n const text = typeof v === 'string' ? v\n : v === undefined ? ''\n : JSON.stringify(v)\n return (\n <div className=\"redline-ts-arg-row\">\n <span className=\"redline-ts-param-name\">{props.name}</span>\n <span className=\"redline-ts-arg-val\">{text}</span>\n </div>\n )\n}\n\nfunction NodeContent(props: {\n node: SurfaceNode\n conv: ConversationNodeLike | undefined\n hint: ReactNode\n rich: RichKit\n img: ImageKit\n labels: DetailLabels\n}): ReactElement {\n const { node, conv, rich, img, labels } = props\n if (conv === undefined) {\n // The join missed (node outside the loaded window): the 80-char preview\n // still shows as a plain content section, with the fetch-state note below.\n if (node.text === undefined || node.text === '') {\n return <div className=\"redline-br-note\">{props.hint}</div>\n }\n return (\n <>\n <TextSection label={labels.content} text={node.text} rich={rich} lines={labels.lines} />\n <div className=\"redline-br-note\">{props.hint}</div>\n </>\n )\n }\n if (conv.kind === 'assistant' && Array.isArray(conv.blocks)) {\n return <BlocksBody blocks={conv.blocks} richable textLabel={labels.answer} rich={rich} img={img} labels={labels} />\n }\n if (conv.kind === 'tool-result') {\n const { err, exit } = toolErrOf(node, conv)\n return (\n <>\n {conv.call != null\n ? <ToolCallCard\n arrow=\"←\"\n name={conv.call.name}\n argsRaw={conv.call.argsRaw}\n status={labels.callState(err, exit)}\n />\n : null}\n {Array.isArray(conv.content)\n ? <BlocksBody blocks={conv.content} richable={false} textLabel={labels.result} rich={rich} img={img} labels={labels} />\n : null}\n </>\n )\n }\n if (conv.kind === 'compaction') {\n return typeof conv.summary === 'string' && conv.summary !== ''\n ? <TextSection label={labels.summary} text={conv.summary} rich={rich} lines={labels.lines} />\n : <></>\n }\n if (Array.isArray(conv.content)) {\n return <BlocksBody blocks={conv.content} richable textLabel={labels.content} rich={rich} img={img} labels={labels} />\n }\n return <div className=\"redline-br-note\">{props.hint}</div>\n}\n\nfunction byCatOf(asm: Assembled): Partial<Record<Category, SurfaceNode[]>> {\n const m: Partial<Record<Category, SurfaceNode[]>> = {}\n for (const n of asm.nodes) (m[n.cat] ??= []).push(n)\n return m\n}\n\n/**\n * The producer identity a fold-stamped injection node carries\n * (shared/types.ts SurfaceNode.name): '' when absent or drift-typed — the\n * delivered payload is untrusted, so rows re-prove it before rendering.\n */\nfunction nodeNameOf(n: SurfaceNode): string {\n return typeof n.name === 'string' ? n.name : ''\n}\n\nfunction countOf(asm: Assembled, byCat: Partial<Record<Category, SurfaceNode[]>>, c: string): number {\n if (c === 'system') return asm.system !== null ? 1 : 0\n if (c === 'tools') return asm.header !== null ? asm.header.tools.length : 0\n return byCat[c as Category]?.length ?? 0\n}\n\nfunction lastOfTurn(requests: RequestRecord[], turn: number): RequestRecord | null {\n for (let i = requests.length - 1; i >= 0; i--) if ((requests[i].turn ?? 0) === turn) return requests[i]\n return null\n}\n\n/**\n * DNA bands keep at least this share of the occupied region, so a tiny item (a 25-token user message in a 40k\n * context) stays a hoverable/clickable filament instead of a sub-pixel sliver. Tooltips still report true shares.\n */\nconst DNA_MIN_BAND = 0.35\n\nexport function makeContextBrowser(\n kit: ViewKit,\n StackedBar: (props: StackedBarProps) => ReactElement,\n settings: ContextSettings,\n): (props: ContextBrowserProps) => ReactElement {\n const { t, fmt, fmtTime, catLabel } = kit\n const DetailNote = makeDetailNote(kit)\n const nodeText = makeNodeText(kit)\n const rich = makeRichText(kit)\n const ImageCard = makeImageCard(kit)\n const RedlineActions = makeRedlineActions(kit)\n const RedlineEditor = makeRedlineEditor(kit)\n // All rich text sections share the same line-count label; hoist it once so tool\n // descriptions, system text, and message bodies stay in sync.\n const lineLabel = (n: number): string => t(n === 1 ? 'block.line' : 'block.lines', { n })\n\n return function ContextBrowser(props: ContextBrowserProps): ReactElement {\n const { data, headers } = props\n // 'live' = the current surface (the NEXT request's context); number = a retained step's seq.\n // 面板在 `placement:'all'` 下会**同时挂在 tab 与右侧栏**(两个实例)⟹ 写死的 id\n // 会在同一个文档里重复(Code Review P2)。`useId()` 给出每个实例唯一的后缀。\n const uid = useId()\n const [sel, setSel] = useState<'live' | number>('live')\n /**\n * The δ baseline (`docs/03` R1.13, copied verbatim from the reference plugin's\n * 0.60.0 `browser.base.*`): `turn` compares against the PREVIOUS TURN's last\n * step (one stable unit whatever step is shown), `step` against the immediately\n * preceding record. Default `turn`, like the demo.\n */\n const [base, setBase] = useState<'step' | 'turn'>('turn')\n const [openCat, setOpenCat] = useState<string | null>(null)\n const [openElem, setOpenElem] = useState<string | null>(null)\n // The open category's row-filter text plus the tools' row order. The\n // filter is a lens on the OPEN category: opening a different one resets\n // it, while step picks (setOpenCat(null) below) keep it so the same lens\n // compares epochs.\n const [rowQuery, setRowQuery] = useState('')\n // Mount-time default from the plugin settings card; in-toolbar toggling\n // stays mount-local and never writes back.\n const [toolSort, setToolSort] = useState<DefaultToolSort>(() => settings.defaultToolSort())\n // DNA mode: the composition bar redraws as ONE band per context item in prompt order (dna.ts), hovered/clicked per item.\n const [dna, setDna] = useState(false)\n const [dnaKey, setDnaKey] = useState<string | null>(null)\n // Every open-category change (toggle, step pick, pin, brief reveal) reports outward so the Context tab\n // can focus the trend chart on the open category.\n const onOpenCat = props.onOpenCat\n const setCat = (c: string | null): void => {\n setOpenCat(c)\n if (onOpenCat !== undefined) onOpenCat(c)\n }\n\n // Full message content: the conversation-window join first (zero cost),\n // plus nodes fetched on demand for seqs outside the window (node arrays\n // are stable references per snapshot; the map memoizes over them).\n const convNodes = props.convNodes\n const convBySeq = useMemo(() => {\n const m = new Map<number, ConversationNodeLike>()\n for (const n of convNodes ?? []) m.set(n.seq, n)\n return m\n }, [convNodes])\n\n // The open element's surface-node seq ('sys'/'tool:*' keys never join).\n const openSeq = openElem !== null && openElem.startsWith('n')\n ? Number(openElem.slice(1))\n : null\n // Fetch-on-miss: one targeted history read per expanded row whose seq the\n // join missed (fetchOnMiss.tsx; landed values cache by seq — history is\n // immutable). `failed` arms the retry button; `absent` means the page\n // came back without the seq — it is not in the durable log.\n const fetchContent = props.fetchContent\n const miss = useFetchOnMiss(\n openSeq !== null && !convBySeq.has(openSeq) ? openSeq : null,\n fetchContent,\n 'dsh-context-redline: targeted history read failed',\n )\n const bySeq = useMemo(() => {\n if (miss.values.size === 0) return convBySeq\n const m = new Map(convBySeq)\n for (const [seq, n] of miss.values) if (!m.has(seq)) m.set(seq, n)\n return m\n }, [convBySeq, miss.values])\n // Pin linkage: a pinned bar selects its step (same accordion reset as a manual pick); unpin returns to live — a manual pick here is\n // overridden only when a NEW pin lands.\n const pinSeq = props.pinSeq\n useEffect(() => {\n setSel(pinSeq === null || pinSeq === undefined ? 'live' : pinSeq)\n setCat(null)\n setOpenElem(null)\n }, [pinSeq, onOpenCat])\n // Step-brief reveal: select the owning step, open the node's category + element (the pagination effect above already pulls older\n // history for a missing join), then arm a one-shot scroll consumed by the layout effect once the row renders.\n const rootRef = useRef<HTMLDivElement | null>(null)\n const focusScrollRef = useRef(false)\n const nodeFocus = props.nodeFocus\n useEffect(() => {\n if (nodeFocus === null || nodeFocus === undefined) return\n setSel(nodeFocus.step)\n setCat(nodeFocus.cat)\n setOpenElem('n' + String(nodeFocus.seq))\n focusScrollRef.current = true\n if (props.onNodeFocusHandled !== undefined) props.onNodeFocusHandled()\n }, [nodeFocus, props.onNodeFocusHandled, onOpenCat])\n useLayoutEffect(() => {\n if (!focusScrollRef.current) return\n focusScrollRef.current = false\n rootRef.current?.querySelector('.redline-br-elem-on')?.scrollIntoView({ block: 'nearest' })\n })\n // The note an un-joined open row shows, per fetch state (fetchOnMiss.tsx).\n const missNote = fetchMissNote(t, fetchContent, miss.state, miss.retry, 'browser.noContent')\n\n const requests = data.requests\n const stepsOf = useMemo(() => turnStepsOf(requests), [requests])\n const hoverReq = props.previewSeq !== null && props.previewSeq !== undefined\n ? requests.find(r => r.seq === props.previewSeq) ?? null\n : null\n const req = hoverReq ?? (sel === 'live' ? null : requests.find(r => r.seq === sel) ?? null)\n // The actual-prompt figure follows the shown step; the live surface pairs its next-request\n // estimate with the freshest actual the log holds (highest seq — wire order is not trusted).\n const actual = req ?? requests.reduce<RequestRecord | null>((a, r) => (a === null || r.seq > a.seq ? r : a), null)\n // A pinned step trimmed out of retention falls back to live.\n const seq = req !== null ? req.seq : null\n // The browser joins the shared composition hover ONLY while it shows the LIVE step — a pinned/previewed step has a different\n // composition, so its hover must not light the overview (and vice versa); the mirror filter drops the overview's 'free' key, which has\n // no segment in this bar.\n const linked = req === null && props.onHoverKey !== undefined\n const linkKey = linked && props.hoverKey !== null && props.hoverKey !== 'free'\n ? props.hoverKey\n : null\n const view = assemble(data, headers, seq)\n\n // Header/tool epoch CONTENT (tool descriptions/schemas) and the system\n // prompt TEXT: the projections carry metadata only, so the selected step's\n // sources are fetched on demand — one seq-anchored history read per open\n // section. The system prompt rides the timeline's own `systems` nodes (a\n // `system/message` event), the tools the header epoch; both map through\n // the same fetcher. Content caches per seq — history is immutable.\n const fetchHeader = props.fetchHeader\n const headerSeq = view.header !== null ? view.header.seq : null\n const systemSeq = view.system !== null ? view.system.seq : null\n const contentSeq = openCat === 'system' ? systemSeq : openCat === 'tools' ? headerSeq : null\n const epoch = useFetchOnMiss(\n contentSeq,\n fetchHeader,\n 'dsh-context-redline: header content fetch failed',\n )\n const headerContent = epoch.values\n // The note a not-yet-loaded epoch section shows, per fetch state (fetchOnMiss.tsx).\n const headerNote = fetchMissNote(t, fetchHeader, epoch.state, epoch.retry, 'browser.headerMetaOnly')\n\n const breakdown = req !== null ? req : data.current\n const parts = partsOf(breakdown)\n const total = breakdown.total\n // The open category stays lit in the composition bar (category mode: its segment; DNA mode: its bands' group) even\n // without pointer hover — a pointer hover overrides the pin, the pin resumes on leave. Dropped when the shown\n // step's composition holds nothing for the category, so the bar never reads all-dimmed with nothing lit.\n const pinKey = openCat !== null && (breakdown[openCat as Category | 'system' | 'tools'] || 0) > 0 ? openCat : null\n const pick = (v: string) => {\n setSel(v === 'live' ? 'live' : Number(v))\n setCat(null)\n setOpenElem(null)\n }\n\n // The two-level picker's own facts: the turn list, which turn is shown, and that\n // turn's steps. Live (or a seq retained away) falls back to the LAST turn — the\n // live surface belongs to the turn that is still running.\n const turns = useMemo(() => [...new Set(requests.map(r => r.turn ?? 1))].sort((a, b) => a - b), [requests])\n const lastTurn = turns.length > 0 ? turns[turns.length - 1] ?? 1 : 1\n const selTurn = req !== null && req.turn !== undefined && turns.includes(req.turn) ? req.turn : lastTurn\n const requestsOfTurn = useMemo(() => requests.filter(r => (r.turn ?? 1) === selTurn), [requests, selTurn])\n\n // δ baseline, the demo's `deltaRefReq` verbatim (which is the reference plugin's\n // 0.60.0 rule): live surface → 比前步 reads the LAST request, 比前轮 its previous\n // turn's last step; a shown step → 比前轮 its previous turn's last step,\n // 比前步 the immediately preceding record. The first turn has NO baseline, so\n // everything counts as a change there (the upstream `zeroBase` behaviour).\n const lastReq = requests.length > 0 ? requests[requests.length - 1] ?? null : null\n const turnBaseOf = (r: RequestRecord): RequestRecord | null =>\n (r.turn ?? 1) > 1 ? lastOfTurn(requests, (r.turn ?? 1) - 1) : null\n const refReq = req === null\n ? (base === 'step' ? lastReq : lastReq !== null ? turnBaseOf(lastReq) : null)\n : base === 'turn'\n ? turnBaseOf(req)\n : (() => {\n const gi = requests.findIndex(r => r.seq === req.seq)\n return gi <= 0 ? null : requests[gi - 1] ?? null\n })()\n const prevView = refReq !== null ? assemble(data, headers, refReq.seq) : null\n const prevByCat = prevView !== null ? byCatOf(prevView) : null\n\n const byCat = byCatOf(view)\n\n // Per-tool call-hit tally over the shown step's assembled surface: one\n // tool-result node (the fold stamps `tool` on a paired result) is one\n // completed call — the same accounting as the stats' toolCalls. A\n // `skill`-tool load reclassifies its node into the `skill` bucket but\n // keeps the tool stamp, so those calls still count here.\n const toolHits = new Map<string, number>()\n for (const n of view.nodes) {\n if ((n.cat === 'tool' || n.cat === 'skill') && n.tool !== undefined) toolHits.set(n.tool, (toolHits.get(n.tool) ?? 0) + 1)\n }\n const toolHitsOf = (tool: HeaderTool): number => toolHits.get(tool.name) ?? 0\n\n // DNA mode: per-item bands in prompt order (dna.ts). The band label names the item the way its accordion row would\n // (skill name, tool name, injection form, else the category label), with the item's time appended.\n const dnaLabel = (it: DnaItem): string => {\n let base: string\n if (!('node' in it)) {\n base = it.cat === 'system' ? catLabel('system') : it.key.slice('tool:'.length)\n } else {\n const n = it.node\n // 工具名认不出来时**不要渲染「?」**(用户 2026-10-06 对界面上任何 `?` 都反感)——\n // 退回分类名「工具结果」,它至少是句人话。(真机实测:未配对的工具结果会走到这里。)\n base = n.skill !== undefined ? t('node.skillTag', { name: n.skill })\n : n.cat === 'tool' ? (n.tool ?? catLabel(n.cat))\n : n.cat === 'inject' ? t('form.' + (n.form || 'context'))\n : catLabel(n.cat)\n }\n return it.time !== undefined ? base + ' · ' + fmtTime(it.time) : base\n }\n const dnaItems = dna ? dnaOf(view) : null\n const dnaByKey = new Map(dnaItems?.map(it => [it.key, it] as const) ?? [])\n const dnaParts = dnaItems?.map(it => ({\n key: it.key,\n color: CAT_COLOR[it.cat],\n value: it.tokens,\n label: dnaLabel(it),\n group: it.cat,\n })) ?? null\n // A band hover is honored only while its key names a RENDERED band: a push can drop the band under a resting\n // pointer (compaction, tail slide) without a mouseleave, and a dead key exact-matches nothing — the bar would\n // sit all-dimmed with nothing lit (the same invariant the pin's `breakdown` gate keeps).\n const liveDnaKey = dnaKey !== null && dnaByKey.has(dnaKey) ? dnaKey : null\n // A band click opens its category + element row below (the same reveal the step brief uses) and scrolls it into view.\n const pickDna = (key: string): void => {\n const it = dnaByKey.get(key)\n /* v8 ignore next 1 -- the bar only reports keys of the parts it was handed; defensive. */\n if (it === undefined) return\n setCat(it.cat)\n setRowQuery('')\n setOpenElem(key)\n focusScrollRef.current = true\n }\n\n const toolCount = (c: string): number => countOf(view, byCat, c)\n\n // A category holding exactly one item opens that row with the category, so\n // one click lands on the content directly (the lone prompt / tool schema /\n // surface node).\n const singleKeyOf = (c: string): string | null => {\n if (c === 'system') return view.system !== null ? 'sys' : null\n if (c === 'tools') {\n const tools = view.header?.tools\n return tools !== undefined && tools.length === 1 ? 'tool:' + tools[0].name : null\n }\n /* v8 ignore next 1 -- reached only through toggleCat's openable guard\n (count > 0 ⟺ byCat[c] exists); the fallback is defensive. */\n const nodes = byCat[c as Category] ?? []\n return nodes.length === 1 ? 'n' + String(nodes[0].seq) : null\n }\n\n const toggleCat = (c: string) => {\n // Empty cats stay shut — except system/tools with no header epoch, which open to explain the degradation note.\n const openable = toolCount(c) > 0\n || ((c === 'system' || c === 'tools') && view.header === null)\n if (!openable) return\n if (openCat === c) {\n setCat(null)\n setOpenElem(null)\n return\n }\n setCat(c)\n // A different category opens unfiltered — the lens belongs to the open one.\n setRowQuery('')\n setOpenElem(singleKeyOf(c))\n }\n const toggleElem = (key: string) => { setOpenElem(openElem === key ? null : key) }\n\n /**\n * Expandable element row; `err` rows carry the red run-state dot right after the chevron (the chat's failed-tool marker) so a failed\n * result scans while collapsed.\n */\n const elemRow = (\n key: string, tag: ReactNode | null, preview: string,\n tokens: number, time: number | undefined, body: ReactNode,\n err = false, trailing: ReactNode = null, actions: ReactNode = null, editor: ReactNode = null,\n deleted = false,\n ) => {\n const open = openElem === key\n return (\n <div key={key} className={'redline-br-elem' + (open ? ' redline-br-elem-on' : '') + (deleted ? ' redline-br-elem-deleted' : '')}>\n <button type=\"button\" className=\"redline-br-elem-row hover:bg-(--dsw-alias-interactive-bg-hover)\" onClick={() => { toggleElem(key) }}>\n <span className={'redline-br-chev' + (open ? ' redline-br-chev-on' : '')} />\n {err ? <span className=\"redline-br-err-dot\" title={t('node.failed')} /> : null}\n {tag !== null ? <span className=\"redline-br-tag\">{tag}</span> : null}\n <span className=\"redline-br-preview\">{preview}</span>\n {trailing !== null ? trailing : null}\n {time !== undefined ? <span className=\"redline-br-time\">{fmtTime(time)}</span> : null}\n <span className=\"redline-br-tokens\">{'≈' + fmt(tokens)}</span>\n </button>\n {open ? <div className=\"redline-br-content\">{body}</div> : null}\n {actions}\n {editor}\n </div>\n )\n }\n\n // ── local editing (docs/03 §2–§3) ─────────────────────────────────────────\n // The advanced switch only gates the `编辑` button on tool results (R2.5); it\n // changes no data.\n const [advanced, setAdvanced] = useState(false)\n const [editingSeq, setEditingSeq] = useState<number | null>(null)\n const [editorRow, setEditorRow] = useState<RedlineRow | null>(null)\n const [editorError, setEditorError] = useState<string | null>(null)\n // Mirrors `editingSeq` for the async loads: a `node.read` that lands after the\n // user left that row must not reopen it.\n const editingSeqRef = useRef<number | null>(null)\n\n /**\n * The row's action set. The BUCKET decides it — provably action-invariant\n * across the bucket's durable types (`tests/edit/ability-buckets.spec.ts`);\n * the exact type is only needed for the editor's fields, and that comes from\n * `node.read` when the editor opens.\n */\n const abilityOfNode = (n: SurfaceNode): Ability => ability({\n seq: n.seq,\n type: durableTypeOf(n.cat),\n cat: n.cat,\n // `gone` marks an archived (superseded) node — no longer a surface node.\n shadowed: n.gone !== undefined,\n isReplacement: n.gone === undefined,\n compacted: false,\n })\n\n /** Open the editor on one row: read the FULL text first (`docs/01` F35). */\n const openEditor = (seq: number): void => {\n editingSeqRef.current = seq\n setEditingSeq(seq)\n setEditorRow(null)\n setEditorError(null)\n void (async () => {\n const result = await props.redline.loadRow(seq)\n setEditorRow((current) => {\n // Ignore a late answer for a row the user already left.\n if (editingSeqRef.current !== seq) return current\n return result.ok ? result.value : null\n })\n if (!result.ok) setEditorError(result.code)\n })()\n }\n\n const closeEditor = (): void => {\n editingSeqRef.current = null\n setEditingSeq(null)\n setEditorRow(null)\n setEditorError(null)\n props.redline.clearError()\n }\n\n /** The action bar for one row (`docs/03` R2.1–R2.5). */\n const rowActionsFor = (n: SurfaceNode): ReactNode => {\n const a = abilityOfNode(n)\n return (\n <RedlineActions\n seq={n.seq}\n ability={a}\n hasLocalEdit={hasLocalEdit(props.redline.table, n.seq)}\n deleted={isDeleted(props.redline.table, n.seq)}\n advanced={advanced}\n busy={props.redline.busySeq === n.seq}\n onEdit={() => { openEditor(n.seq) }}\n errorCode={props.redline.rowError?.seq === n.seq ? props.redline.rowError.code : null}\n onExclude={() => { void props.redline.exclude(n.seq, true) }}\n onUnexclude={() => { void props.redline.exclude(n.seq, false) }}\n onDrop={() => {\n void (async () => {\n const ok = await props.redline.drop(n.seq)\n // `docs/11` D17: discarding collapses the editor on that row.\n if (ok && editingSeqRef.current === n.seq) closeEditor()\n })()\n }}\n />\n )\n }\n\n /** The inline editor for one row, when it is the open one. */\n const rowEditorFor = (n: SurfaceNode): ReactNode => {\n if (editingSeq !== n.seq) return null\n if (editorRow === null) {\n return (\n <div className=\"redline-editor\">\n <div className=\"redline-editor-label\">\n {editorError === null ? t('detail.loading') : t(`redline.err.${editorError.replace('redline/', '')}`)}\n </div>\n </div>\n )\n }\n const row = { seq: n.seq, text: editorRow.text, reasoning: editorRow.reasoning, isError: editorRow.isError }\n const initial: RedlineSubmit = {\n // The version in effect — after a save this is YOUR saved text (`docs/11` D16).\n text: effectiveText(row, props.redline.table),\n reasoning: effectiveReasoning(row, props.redline.table),\n isError: effectiveIsError(row, props.redline.table),\n }\n return (\n <RedlineEditor\n seq={n.seq}\n type={editorRow.type}\n initial={initial}\n busy={props.redline.busySeq === n.seq}\n blocked={!props.redline.turn.known ? 'not-live' : props.redline.turn.open ? 'turn-open' : null}\n errorCode={props.redline.rowError?.seq === n.seq ? props.redline.rowError.code : editorError}\n onSubmit={(edit: RedlineSubmit) => {\n void (async () => {\n const ok = await props.redline.save(n.seq, edit)\n if (ok) closeEditor()\n })()\n }}\n onCancel={closeEditor}\n />\n )\n }\n\n const catBody = (c: string): ReactNode => {\n if (c === 'system') {\n // No prompt in force at this step. The category only opens without one\n // when there is no header epoch at all (the openable guard above), so\n // the note names the missing PROJECTION — no headers service versus\n // headers that carried no epoch yet.\n const sys = view.system\n if (sys === null) {\n return <div className=\"redline-br-note\">{t(headers === null ? 'browser.noHeader' : 'browser.noEpoch')}</div>\n }\n const content = headerContent.get(sys.seq)\n // Metadata-only until the prompt's event resolves (fetched when the\n // section opens; the note names the state).\n if (content === undefined) return <div className=\"redline-br-note\">{headerNote}</div>\n if (content.system === undefined) return <div className=\"redline-br-note\">{t('browser.noSystem')}</div>\n return elemRow('sys', null, content.system.replace(/\\s+/g, ' ').trim().slice(0, 80), breakdown.system, undefined,\n <TextSection label={catLabel('system')} text={content.system} rich={rich} lines={lineLabel} />)\n }\n if (c === 'tools') {\n if (view.header === null) return <div className=\"redline-br-note\">{t(headers === null ? 'browser.noHeader' : 'browser.noEpoch')}</div>\n const labels = {\n desc: t('tool.desc'),\n title: t('tool.params'),\n empty: t('tool.paramsEmpty'),\n show: t('tool.jsonToggle'),\n hide: t('tool.jsonHide'),\n }\n // The epoch's fetched content, joined onto the metadata rows by tool\n // name (the open row's body renders description/params/JSON from it).\n const content = headerContent.get(view.header.seq)\n const contentByName = new Map(content?.tools.map(t => [t.name, t]) ?? [])\n // The text filter scans everything the rows can say: the name, the\n // producer description, the plugin chip, and the raw parameter JSON —\n // the latter two only once the epoch's content is loaded.\n const q = rowQuery.trim().toLowerCase()\n const shown = view.header.tools\n .filter((tool: HeaderTool) => {\n if (q === '') return true\n if (tool.name.toLowerCase().includes(q)) return true\n if ((tool.plugin ?? '').toLowerCase().includes(q)) return true\n const row = contentByName.get(tool.name)\n if (row === undefined) return false\n return (row.description ?? '').toLowerCase().includes(q)\n || schemaTextOf(row.schema).toLowerCase().includes(q)\n })\n // Size order mirrors the overview's Top chips — the producer's header\n // order is not meaningful; count order ranks by the call-hit tally of\n // the shown step's surface (ties break by name); name order gives\n // lookup instead of ranking (names are unique keys, so a two-way\n // comparison orders them fully).\n .sort((a, b) => toolSort === 'count'\n ? (toolHitsOf(b) - toolHitsOf(a) || (a.name < b.name ? -1 : 1))\n : toolSort === 'size'\n ? b.tokens - a.tokens\n : (a.name < b.name ? -1 : 1))\n // The toolbar stays mounted on an empty match, or the filter could\n // never be cleared from the UI.\n const toolctl = (\n <RowToolbar value={rowQuery} placeholder={t('tool.search')} tip={t('tool.sortTip')} onChange={setRowQuery}>\n {(['size', 'count', 'name'] as const).map(k => (\n <button\n key={k}\n type=\"button\"\n className={'redline-gran-btn' + (toolSort === k ? ' redline-gran-on' : '')}\n onClick={() => { setToolSort(k) }}\n >\n {t('tool.sort.' + k)}\n </button>\n ))}\n </RowToolbar>\n )\n if (shown.length === 0) {\n return (\n <div>\n {toolctl}\n <div className=\"redline-br-note\">{t('tool.noMatch')}</div>\n </div>\n )\n }\n // The open row's body: the fetched content's description, parameter\n // table, and raw JSON — or the epoch's fetch-state note.\n const toolBody = (tool: HeaderTool): ReactNode => {\n if (content === undefined) return <div className=\"redline-br-note\">{headerNote}</div>\n const row = contentByName.get(tool.name)\n return row === undefined\n ? <div className=\"redline-br-note\">{t('browser.notInLog')}</div>\n : <ToolSchema description={row.description} schema={row.schema} rich={rich} lines={lineLabel} labels={labels} />\n }\n return (\n <div>\n {toolctl}\n {shown.map((tool: HeaderTool) => {\n // The registering plugin (best-effort host attribution — see\n // toolSources.ts) trails the tool name as a standalone chip, so it\n // needs no extra frame around it. A tool whose provider predates\n // the attribution hook arrives with the UNKNOWN_TOOL_SOURCE\n // sentinel and renders a localized \"unknown plugin\" tag whose\n // tooltip explains why no provider is shown. The hit tally always\n // trails — a zero names a definition the shown step never called.\n const trailing = (\n <>\n {tool.plugin !== undefined\n ? <span className=\"redline-br-tag redline-br-tool-plugin\" title={tool.plugin === UNKNOWN_TOOL_SOURCE ? t('tool.unknownTitle') : t('tool.plugin')}>\n {tool.plugin === UNKNOWN_TOOL_SOURCE ? t('tool.unknown') : tool.plugin}\n </span>\n : null}\n <span className=\"redline-br-hits\" title={t('tool.hitsTip')}>{'×' + fmt(toolHitsOf(tool))}</span>\n </>\n )\n return elemRow('tool:' + tool.name, null, tool.name, tool.tokens, undefined,\n toolBody(tool),\n false, trailing)\n })}\n </div>\n )\n }\n // List surface nodes newest first (the live surface's reading order).\n /* v8 ignore next 1 -- the body renders only when the category is open,\n which requires count > 0 ⟺ byCat[c] exists; defensive. */\n const nodes = (byCat[c as Category] ?? []).slice().reverse()\n // Derive each row's display facts first so the text filter scans exactly\n // what the rows show (tag + preview) at zero extra derivation cost; the\n // survivors render unchanged. Identity-labeled injection rows keep their\n // folded content out of the preview, so the filter scans `text` too.\n const rows = nodes.map((n) => {\n const conv = bySeq.get(n.seq)\n // A `skill`-tool load reclassifies into the `skill` bucket (issue #66)\n // but stays a tool result — its failure marking follows the same rule.\n const rowErr = (n.cat === 'tool' || n.cat === 'skill') && toolErrOf(n, conv).err\n // Tag carries the compact fact (tool name, injection form) — one shared subtle chip style; the preview line carries the text — each\n // fact shown once.\n let tag: string | null = null\n let preview = nodeText(n)\n const id = nodeNameOf(n)\n if (n.cat === 'tool') {\n // ⚠️ 工具名认不出来时**不挂标签**(原来是 `'?'`):那行本来就写着「工具结果」当预览,\n // 再挂一个 `?` 只是噪音(用户 2026-10-06 对界面上任何 `?` 都反感)。`null` = 这一格不渲染。\n tag = n.tool ?? null\n preview = callSummaryOf(conv) ?? t('node.toolResult')\n } else if (n.cat === 'skill') {\n // Skill content (issue #66): a load/invocation names itself, and a\n // text-less row (an unjoined load) falls back to the call summary;\n // the catalog digest carries no name — its form label tags it and\n // the stamped source identity (e.g. `skill-catalog`) previews.\n tag = n.skill !== undefined ? t('node.skillTag', { name: n.skill }) : t('form.' + (n.form || 'context'))\n preview = (n.skill === undefined && id !== '' ? id : null)\n ?? (n.text !== undefined && n.text !== '' ? n.text : null)\n ?? callSummaryOf(conv) ?? preview\n } else if (n.cat === 'assistant' && Array.isArray(n.calls) && n.calls.length > 0) {\n // Call targets join as a breadcrumb (`bash › write`); the preview carries the reply text, else the first call's own summary for a\n // text-less turn.\n tag = n.calls.join(' › ')\n preview = (n.text !== undefined && n.text !== '' ? n.text : null)\n ?? blockSummaryOf(conv)\n ?? t('node.empty')\n } else if (n.cat === 'assistant' && (n.text === undefined || n.text === '')) {\n // A text-less turn can still preview a self-summarizing call from the join even when the node carries no call list.\n preview = blockSummaryOf(conv) ?? preview\n } else if (n.cat === 'user') {\n // User messages with image uploads gain an Image chip on the collapsed row (detected via the conversation join, like the expanded\n // body); expanded, the grid shows anyway.\n const imgCount = conv !== undefined && Array.isArray(conv.content)\n ? conv.content.filter(b => imageRefOf(b) !== null).length\n : 0\n if (imgCount > 0 && openElem !== `n${n.seq}`) {\n tag = t('attach.image') + (imgCount > 1 ? ' ×' + String(imgCount) : '')\n }\n } else if (n.cat === 'inject') {\n tag = t('form.' + (n.form || 'context'))\n if (id !== '') {\n // The source identity the events card names (plugin id, reconciled\n // instruction files, durable kind) — more scannable than the raw\n // content, which stays one expand away.\n preview = id\n } else if (n.text !== undefined && n.text !== '') {\n preview = n.form === 'snapshot' ? t('node.snapshot') + n.text : n.text\n }\n }\n return { n, conv, rowErr, tag, preview }\n })\n const q = rowQuery.trim().toLowerCase()\n const shown = q === '' ? rows : rows.filter(r =>\n (r.tag ?? '').toLowerCase().includes(q) || r.preview.toLowerCase().includes(q)\n || (typeof r.n.text === 'string' && r.n.text.toLowerCase().includes(q)))\n // The toolbar stays mounted on an empty match, or the filter could\n // never be cleared from the UI.\n const rowctl = <RowToolbar value={rowQuery} placeholder={t('browser.search.' + c)} onChange={setRowQuery} />\n if (shown.length === 0) {\n return <div>{rowctl}<div className=\"redline-br-note\">{t('browser.rowNoMatch')}</div></div>\n }\n return (\n <div>\n {rowctl}\n {shown.map(({ n, conv, rowErr, tag, preview }) => elemRow(`n${n.seq}`, tag, preview, n.tokens, n.time,\n <NodeContent\n node={n}\n conv={conv}\n rich={rich}\n img={{ Card: ImageCard, load: props.loadImage }}\n // Localized section titles handed in by the parent so the body stays a pure function of props.\n labels={{\n thinking: t('block.thinking'),\n answer: t('block.answer'),\n content: t('block.content'),\n result: t('block.result'),\n summary: t('block.summary'),\n images: t('attach.images'),\n other: t('attach.other'),\n lines: lineLabel,\n callState: (err: boolean, exit: number | null) => (\n <span className={'redline-ts-call-state ' + (err ? 'redline-ts-call-err' : 'redline-ts-call-ok')}>\n <i />\n {err\n ? t('call.fail') + (exit !== null ? ' · ' + t('call.exit', { n: exit }) : '')\n : t('call.ok')}\n </span>\n ),\n }}\n // Only the open row's body renders, so the miss note is exactly THIS join's fetch state; a joined-but-empty row keeps the\n // static hint.\n hint={conv === undefined ? missNote : t('browser.noContent')}\n />,\n rowErr, null, rowActionsFor(n), rowEditorFor(n), isDeleted(props.redline.table, n.seq)))}\n </div>\n )\n }\n\n return (\n <div className=\"redline-card\" ref={rootRef}>\n <div className=\"redline-card-title\">\n <span className=\"redline-card-title-text\">{t('browser.title')}</span>\n {/* 高级编辑开关(docs/03 R2.5):默认关,只影响工具结果的「编辑」是否可见,不改任何数据 */}\n <button\n type=\"button\"\n className={'redline-gran-btn' + (advanced ? ' redline-gran-on' : '')}\n aria-pressed={advanced}\n title={t('redline.advancedToggle.tip')}\n onClick={() => { setAdvanced(v => !v) }}\n >{t('redline.advancedToggle')}</button>\n <span className=\"redline-gran redline-br-dna-ctl\" role=\"group\" title={t('browser.dnaTip')}>\n <button\n type=\"button\"\n className={'redline-gran-btn' + (dna ? ' redline-gran-on' : '')}\n onClick={() => { setDna(on => !on) }}\n >\n {t('browser.dna')}\n </button>\n </span>\n {/* 对比基线:两个按钮逐字照参考插件 0.60.0 的 `lc-gran` + `browser.base.tip`(`docs/03` R1.13) */}\n <span className=\"redline-gran\" id={`redline-base-${uid}`} data-redline-base-group role=\"group\" title={t('browser.base.tip')}>\n <button\n type=\"button\"\n className={'redline-gran-btn' + (base === 'step' ? ' redline-gran-on' : '')}\n aria-pressed={base === 'step'}\n onClick={() => { setBase('step') }}\n >{t('browser.base.step')}</button>\n <button\n type=\"button\"\n className={'redline-gran-btn' + (base === 'turn' ? ' redline-gran-on' : '')}\n aria-pressed={base === 'turn'}\n onClick={() => { setBase('turn') }}\n >{t('browser.base.turn')}</button>\n </span>\n {/* 两级选择器(轮 → 步):列表规模从 N(整段历史)降到 T + S。\n `docs/05` §1.5 的量级保护(实测单下拉 4,000 项 75.0ms vs 两级 9.2ms),\n 这是本插件**有意偏离上游**的那一处。 */}\n <select\n className=\"redline-br-pick\"\n id={`redline-turn-${uid}`}\n data-redline-turn-pick\n value={String(selTurn)}\n onChange={(e) => {\n const turn = Number(e.target.value)\n const last = lastOfTurn(requests, turn)\n if (last !== null) pick(String(last.seq))\n }}\n >\n {turns.map(turn => (\n <option\n key={turn}\n value={String(turn)}\n data-turn={String(turn)}\n data-last-seq={String(lastOfTurn(requests, turn)?.seq ?? '')}\n >\n {t('browser.turnPick', { t: turn, n: stepsOf(turn) })}\n </option>\n ))}\n </select>\n <select\n className=\"redline-br-pick\"\n id={`redline-step-${uid}`}\n data-redline-step-pick\n value={seq === null ? 'live' : String(seq)}\n onChange={(e) => { pick(e.target.value) }}\n >\n {requestsOfTurn.map(r => (\n <option key={r.seq} value={String(r.seq)} data-redline-seq={String(r.seq)}>\n {t('browser.stepPick', { s: r.step ?? 0, n: stepsOf(r.turn) }) + ' · ' + fmtTime(r.time)}\n </option>\n ))}\n {/* 「当前(下一次请求)」只出现在**末轮**(`docs/03` R1.13) */}\n {selTurn === lastTurn ? <option value=\"live\">{t('browser.live')}</option> : null}\n </select>\n </div>\n\n <div className=\"redline-br-meta\">\n <b>{req !== null\n ? t('detail.step', { t: req.turn ?? 0, s: req.step ?? 0, n: stepsOf(req.turn) })\n : t('browser.liveNow')}</b>\n {req !== null ? <span>{fmtTime(req.time)}</span> : null}\n <span className=\"redline-est\">{t('detail.estTotal', { n: fmt(total) })}</span>\n {actual !== null && actual.prompt !== undefined\n ? <span>{t('detail.actual', { n: fmt(actual.prompt) })}</span>\n : null}\n </div>\n\n <div className={'redline-br-bar' + (dna ? ' redline-br-bar-dna' : '')}>\n <StackedBar\n parts={dnaParts ?? parts}\n height={10}\n // Highlight precedence: pointer hover (local in DNA mode, the shared link otherwise) over the open-category pin.\n // The mirrored link (see `linked` above) works while the browser shows the live surface; it is ONE-WAY in DNA\n // mode — an incoming category key lights that category's BANDS (the parts' `group`), while band hovers stay\n // on the bar and never report upward (the overview keeps showing the live category composition). Tip stays\n // off in category mode: a cross-card hover must not float a second tooltip over a bar the pointer does not\n // rest on — and the group-keyed pin never exact-matches a DNA band, so the pinned highlight floats no tip.\n hoverKey={dna ? liveDnaKey ?? linkKey ?? pinKey : linkKey ?? pinKey}\n onHoverKey={dna ? setDnaKey : linked ? props.onHoverKey : undefined}\n tip={dna}\n onPickKey={dna ? pickDna : undefined}\n minBand={dna ? DNA_MIN_BAND : undefined}\n />\n </div>\n\n {view.missingLive > 0\n ? <div className=\"redline-br-note\">{t('browser.missingLive', { n: view.missingLive })}</div>\n : null}\n {view.approximate\n ? <div className=\"redline-br-note\">{t('browser.approx')}</div>\n : null}\n {props.detailState === 'loading'\n ? <DetailNote state=\"loading\" className=\"redline-br-note\" />\n : null}\n {props.detailState === 'failed' && props.onDetailRetry !== undefined\n ? <DetailNote state=\"failed\" onRetry={props.onDetailRetry} className=\"redline-br-note\" />\n : null}\n\n <div className=\"redline-br-cats\">\n {CATS.map((c) => {\n const count = toolCount(c.key)\n const v = breakdown[c.key] || 0\n const prevCount = prevView !== null && prevByCat !== null ? countOf(prevView, prevByCat, c.key) : null\n const countDelta = prevCount !== null ? count - prevCount : null\n const prevTokens = refReq !== null ? (refReq[c.key] || 0) : null\n const tokenDelta = prevTokens !== null ? v - prevTokens : null\n const openable = count > 0\n || ((c.key === 'system' || c.key === 'tools') && view.header === null)\n const open = openCat === c.key && openable\n return (\n <div key={c.key} className={'redline-br-cat' + (openable ? '' : ' redline-br-cat-empty')}>\n <button\n type=\"button\"\n className={'redline-br-cat-row hover:bg-(--dsw-alias-interactive-bg-hover)'\n + (open ? ' redline-br-cat-open' : '')\n + (linked && props.hoverKey === c.key ? ' redline-br-cat-on' : '')}\n /* v8 ignore start -- the handlers exist only when linked,\n and linked already requires onHoverKey defined (above). */\n onMouseEnter={linked ? () => { if (props.onHoverKey !== undefined) props.onHoverKey(c.key) } : undefined}\n onMouseLeave={linked ? () => { if (props.onHoverKey !== undefined) props.onHoverKey(null) } : undefined}\n /* v8 ignore stop */\n onClick={() => { toggleCat(c.key) }}\n >\n <span className={'redline-br-chev' + (open ? ' redline-br-chev-on' : '')} />\n <i style={{ background: c.color }} />\n <span className=\"redline-br-cat-label\">{catLabel(c.key)}</span>\n {/* Count + Δ pill sit as one attached group (tight inner gap),\n the group absorbs the row's free space so tokens/percent\n stay right-aligned. */}\n <span className=\"redline-br-count-grp\">\n <span className=\"redline-br-cat-count\">{t('browser.items', { n: count })}</span>\n {countDelta !== null && countDelta !== 0 ? (\n <span className={'redline-br-delta redline-br-delta-' + (countDelta > 0 ? 'up' : 'down')}>\n {`${countDelta > 0 ? '+' : ''}${countDelta}`}\n </span>\n ) : null}\n </span>\n <span className=\"redline-br-tokens-grp\">\n {tokenDelta !== null && tokenDelta !== 0 ? (\n <span className={'redline-br-tdelta redline-br-tdelta-' + (tokenDelta > 0 ? 'up' : 'down')}>\n {(tokenDelta > 0 ? '+' : '') + fmt(tokenDelta)}\n </span>\n ) : null}\n <span className=\"redline-br-tokens\">{'≈' + fmt(v)}</span>\n </span>\n <span className=\"redline-br-pct\">{total > 0 ? `${Math.round(v / total * 100)}%` : ''}</span>\n </button>\n {open ? <div className=\"redline-br-body\">{catBody(c.key)}</div> : null}\n </div>\n )\n })}\n </div>\n </div>\n )\n }\n}\n","/**\n * Composition bar + legend; the shared hover-link tooltip is bespoke — no shared primitive reproduces the cross-segment/legend linkage —\n * styled through the shared `--dsw-alias-*` tokens. On mount the segments and the free track grow open\n * left to right (stackedBar.css, staggered by the capped per-piece `--redline-i` slots below, so a long DNA\n * band list settles fast); the reserve band stays unanimated.\n */\n\nimport { useState, type CSSProperties, type ReactElement } from 'react'\nimport type { PartsPart } from '../categories'\nimport type { ViewKit } from '../viewkit'\n\n/**\n * Mirror of dsh-compaction-basic's default `thresholdRatio` (0.8): it compacts at step boundaries once `floor(contextWindow × ratio)` is\n * reached; DSH does not publish the configured ratio to plugins/clients, so the reserve band mirrors the default — deployments tuning\n * `thresholdRatio`/`modelPolicies` should adjust it to match.\n */\nexport const AUTO_COMPACT_RATIO = 0.8\n\n/**\n * Entrance stagger cap: the browser's DNA bands can list dozens of items, so the grow-in cascade stops\n * widening after this many slots and late bands simply join within the cap (stackedBar.css delays by\n * `--redline-i`); the composition bar's few category segments never reach it.\n */\nconst STAGGER_CAP = 8\n\nexport interface StackedBarProps {\n parts: PartsPart[]\n max?: number\n height?: number\n hoverKey?: string | null\n onHoverKey?: (key: string | null) => void\n /** Segment click (the browser's DNA mode opens the band's accordion row): segments gain the pick cursor and report their key. */\n onPickKey?: (key: string) => void\n /**\n * Minimum width each segment keeps, as a share of the OCCUPIED region (the browser's DNA bands: a tiny item must\n * stay a hoverable filament instead of rendering sub-pixel). Bands below the floor pin to it and the rest rescale\n * proportionally; the floor caps at the equal split (100/N), where the strip degrades to uniform bands. Tooltips\n * keep reporting TRUE shares — only widths are floored.\n */\n minBand?: number\n /**\n * Render the hover tooltip (default true); a bar that only MIRRORS another card's hover turns it off, so the tooltip floats only over the\n * surface the pointer actually rests on.\n */\n tip?: boolean\n /**\n * Optional auto-compaction reserve band: the rightmost (1−ratio) of the window, striped 'headroom' — the region the session normally\n * avoids filling because automatic compaction triggers past the threshold; rendered only when `max` (the window) is positive.\n */\n reserve?: { ratio: number; label: string }\n}\n\nexport function makeStackedBar(kit: ViewKit): (props: StackedBarProps) => ReactElement {\n const { t, fmt, catLabel } = kit\n return function StackedBar(props: StackedBarProps): ReactElement {\n // The reserve-hover flag lives here so the single tooltip slot serves both the segments and the band.\n const [reserveOn, setReserveOn] = useState(false)\n let total = 0\n for (const p of props.parts) total += p.value\n const scale = props.max !== undefined && props.max > total ? props.max : total\n const free = props.max !== undefined && props.max > total ? props.max - total : 0\n // Segment WIDTHS lay out against the full window (scale), but legend/tooltip percentages are shares of the OCCUPIED total — on hover a\n // solid box frames the occupied region (width = used/scale) to make that reference frame visible; only when a free track exists.\n const usedPct = scale > 0 ? total / scale * 100 : 0\n const hovering = props.hoverKey !== null && props.hoverKey !== undefined\n const showBox = free > 0 && hovering\n const pickKey = props.onPickKey\n const minBand = props.minBand !== undefined && props.minBand > 0 ? props.minBand : 0\n\n // The renderable segments (zero-value parts skip) with their BAR-unit widths, floored at `minBand` in occupied\n // units: pinned bands take the floor, the rest rescale into the remaining room so the strip still sums to the\n // occupied region exactly. At least one band always stays unpinned (the shares sum to 100, the floor ≤ 100/N),\n // so restRaw never divides by zero.\n const visible = total > 0 ? props.parts.filter(p => p.value > 0) : []\n const widths = ((): number[] => {\n if (minBand === 0 || visible.length < 2) return visible.map(p => p.value / scale * 100)\n const shares = visible.map(p => p.value / total * 100)\n const floor = Math.min(minBand, 100 / visible.length)\n let pinned = 0\n let pinnedRaw = 0\n for (const s of shares) {\n if (s < floor) { pinned += 1; pinnedRaw += s }\n }\n if (pinned === 0) return visible.map(p => p.value / scale * 100)\n const restRoom = 100 - pinned * floor\n const restRaw = 100 - pinnedRaw\n return shares.map(s => (s < floor ? floor : s * restRoom / restRaw) * total / scale)\n })()\n\n // The band lays out in WINDOW units (`ratio × max` → `max`) scaled onto whatever total the bar spans, so it stays the same physical\n // slice with or without a free track (once used exceeds the window, the stripes sit over the outermost segments).\n const reserve = props.reserve !== undefined && props.max !== undefined && props.max > 0\n ? { ...props.reserve, max: props.max }\n : null\n const reserveLeft = reserve !== null ? Math.round(reserve.max * reserve.ratio / scale * 1000) / 10 : 0\n const reserveWidth = reserve !== null ? Math.round((1 - reserve.ratio) * reserve.max / scale * 1000) / 10 : 0\n\n // The tooltip is DERIVED from the shared hover key, so a segment and its legend chip light the same segment with the same tooltip\n // (centered by %, no measuring); the wrapper keeps it outside the clipped stack; the reserve band overrides the slot with its own\n // label.\n let tip: { text: string; leftPct: number } | null = null\n if (reserveOn && reserve !== null) {\n tip = {\n text: reserve.label,\n leftPct: Math.max(12, Math.min(reserveLeft + reserveWidth / 2, 88)),\n }\n } else if (props.hoverKey !== null && props.hoverKey !== undefined) {\n if (props.hoverKey === 'free' && free > 0) {\n const pct = scale > 0 ? free / scale * 100 : 0\n tip = {\n text: `${t('overview.free')} ${fmt(free)} (${Math.round(pct)}%)`,\n leftPct: Math.max(12, Math.min((total / scale * 100) + pct / 2, 88)),\n }\n } else {\n let acc = 0\n // Counts come from the part's heuristic `raw` figure (the ring\n // panel's rows); widths ride the floored `widths` so the tooltip centers on the RENDERED segment.\n let rawTotal = 0\n for (const p of props.parts) rawTotal += p.raw ?? p.value\n for (let i = 0; i < visible.length; i++) {\n const p = visible[i]\n if (p.key === props.hoverKey) {\n const count = p.raw ?? p.value\n tip = {\n text: `${p.label ?? catLabel(p.key)} ≈${fmt(count)} (${rawTotal > 0 ? Math.round(count / rawTotal * 100) : 0}%) `\n + t('overview.ofUsed'),\n leftPct: Math.max(12, Math.min(acc + widths[i] / 2, 88)),\n }\n break\n }\n acc += widths[i]\n }\n }\n }\n\n return (\n <div className=\"redline-stacked-wrap\">\n <div\n className={'redline-stacked' + (hovering ? ' redline-stacked-dim' : '')}\n style={{ height: `${props.height || 14}px` }}\n onMouseLeave={() => {\n if (props.onHoverKey !== undefined) props.onHoverKey(null)\n setReserveOn(false)\n }}\n >\n {visible.map((p, i) => {\n // Exact-key hover lights the one segment; a part's `group` answers a mirrored CATEGORY hover (DNA bands light per category).\n const on = props.hoverKey !== undefined\n && (props.hoverKey === p.key || (p.group !== undefined && props.hoverKey === p.group))\n return (\n <div\n key={p.key}\n className={'redline-stacked-seg animate-redline-stacked-in motion-reduce:animate-none' + (on ? ' redline-stacked-seg-on' : '') + (pickKey !== undefined ? ' redline-stacked-seg-pick' : '')}\n // Grow-in stagger slot (the animate-redline-stacked-in token's delay): each segment scaleX-opens\n // from the left edge in turn, capped so a long DNA band list settles fast.\n style={{ width: `${widths[i]}%`, backgroundColor: p.color, '--redline-i': Math.min(i, STAGGER_CAP) } as CSSProperties}\n onMouseEnter={() => { if (props.onHoverKey !== undefined) props.onHoverKey(p.key) }}\n onClick={pickKey !== undefined ? () => { pickKey(p.key) } : undefined}\n />\n )\n })}\n {free > 0 ? (\n <div\n key=\"free\"\n className={'redline-stacked-free animate-redline-stacked-in motion-reduce:animate-none' + (props.hoverKey === 'free' ? ' redline-stacked-free-on' : '')}\n // The free track opens right after the last occupied segment (past the stagger cap it joins\n // one slot after the capped segments).\n style={{ width: `${free / scale * 100}%`, '--redline-i': Math.min(visible.length, STAGGER_CAP + 1) } as CSSProperties}\n onMouseEnter={() => { if (props.onHoverKey !== undefined) props.onHoverKey('free') }}\n />\n ) : null}\n {/* Painted above the track/segments so the stripes overlay them; owns the pointer so its own explanation shows — and clears the\n segment hover link while exploring it.\n */}\n {reserve !== null ? (\n <div\n className=\"redline-reserve\"\n style={{ left: `${reserveLeft}%`, width: `${reserveWidth}%` }}\n onMouseEnter={() => {\n setReserveOn(true)\n if (props.onHoverKey !== undefined) props.onHoverKey(null)\n }}\n onMouseLeave={() => { setReserveOn(false) }}\n />\n ) : null}\n {/* The occupied-region frame: painted last so its border stays above the segments; always mounted\n (`.redline-occupied-box-on` toggles opacity) so it fades out on leave instead of unmounting instantly.\n */}\n <div\n className={'redline-occupied-box' + (showBox ? ' redline-occupied-box-on' : '')}\n style={{ width: `${usedPct}%` }}\n />\n </div>\n {/* The hover tooltip is always mounted too (opacity via `.redline-bar-tip-on`) so it fades in and out; hidden it holds\n no pointer events and no width of its own.\n */}\n {props.tip !== false\n ? (\n <div\n className={'redline-tip redline-bar-tip' + (tip ? ' redline-bar-tip-on' : '')}\n style={{ left: tip ? `${tip.leftPct}%` : '50%' }}\n >{tip ? tip.text : ''}</div>\n )\n : null}\n </div>\n )\n }\n}\n\nexport function makeLegend(kit: ViewKit): (props: {\n parts: PartsPart[]\n hoverKey?: string | null\n onHoverKey?: (key: string | null) => void\n}) => ReactElement {\n const { t, fmt, catLabel } = kit\n return function Legend(props: {\n parts: PartsPart[]\n hoverKey?: string | null\n onHoverKey?: (key: string | null) => void\n }): ReactElement {\n let total = 0\n for (const p of props.parts) total += p.raw ?? p.value\n return (\n <div className=\"redline-legend\">\n {props.parts.map((p) => {\n const count = p.raw ?? p.value\n const on = props.hoverKey !== undefined && props.hoverKey === p.key\n return (\n <span\n key={p.key}\n className={'redline-chip' + (on ? ' redline-chip-on' : '')}\n title={t('overview.ofUsed')}\n onMouseEnter={() => { if (props.onHoverKey !== undefined) props.onHoverKey(p.key) }}\n onMouseLeave={() => { if (props.onHoverKey !== undefined) props.onHoverKey(null) }}\n >\n <i style={{ background: p.color }} />\n <span className=\"redline-chip-label\">{catLabel(p.key)}</span>\n <span className=\"redline-chip-nums\">\n {'≈' + fmt(count)}\n {total > 0 ? <em>{`${Math.round(count / total * 100)}%`}</em> : null}\n </span>\n </span>\n )\n })}\n </div>\n )\n }\n}\n","import { type ReactElement } from 'react'\nimport type { PartsPart } from '../categories'\nimport type { Headline } from '../headline'\nimport type { ViewKit } from '../viewkit'\nimport { AUTO_COMPACT_RATIO } from './stackedBar'\nimport type { StackedBarProps } from './stackedBar'\n\ntype LegendFn = (props: {\n parts: PartsPart[]\n hoverKey?: string | null\n onHoverKey?: (key: string | null) => void\n}) => ReactElement\n\nexport interface CurrentCompositionProps {\n head: Headline\n subtitle?: string\n hoverKey?: string | null\n onHoverKey?: (key: string | null) => void\n}\n\nexport function makeCurrentComposition(\n kit: ViewKit,\n StackedBar: (props: StackedBarProps) => ReactElement,\n Legend: LegendFn,\n): (props: CurrentCompositionProps) => ReactElement {\n const { t, fmt } = kit\n return function CurrentComposition(props: CurrentCompositionProps): ReactElement {\n const head = props.head\n const reserve = head.window != null && head.window > 0\n ? { ratio: AUTO_COMPACT_RATIO, label: t('overview.compactReserve', { pct: Math.round(AUTO_COMPACT_RATIO * 100) }) }\n : undefined\n return (\n <div className=\"redline-card\" data-redline-current>\n <div className=\"redline-card-title\">\n <span className=\"redline-card-title-text\">{t('overview.title')}</span>\n {props.subtitle !== undefined && props.subtitle !== ''\n ? <span className=\"redline-card-sub\">{props.subtitle}</span>\n : null}\n </div>\n <div className=\"redline-overview-num\">\n <b>{fmt(head.tokens)}</b>\n <span>\n {head.window\n ? ' / ' + fmt(head.window) + ' tokens'\n : ' ' + t('overview.estimate')}\n </span>\n {head.pct !== null ? (\n <span className=\"redline-overview-pct\">\n <b>{`${head.pct}%`}</b>\n {t('overview.used')}\n </span>\n ) : null}\n </div>\n <StackedBar\n parts={head.parts}\n height={16}\n max={head.window}\n hoverKey={props.hoverKey}\n onHoverKey={props.onHoverKey}\n reserve={reserve}\n />\n <Legend parts={head.parts} hoverKey={props.hoverKey} onHoverKey={props.onHoverKey} />\n </div>\n )\n }\n}\n","/**\n * ErrorBoundary — the tab's no-white-screen guarantee: a render error in the subtree degrades to a styled error card instead of\n * propagating\n * into the harness's slot renderer and unmounting the conversation view. Class component: the only React primitive that can catch a\n * subtree's render errors (no hook-based boundary in React 18); Retry resets the boundary and a healthy value resumes.\n */\n\nimport { Component, type ComponentType, type ReactNode } from 'react'\nimport type { Translate } from '../i18n'\n\nexport function makeErrorBoundary(t: Translate): ComponentType<{ children?: ReactNode }> {\n return class ErrorBoundary extends Component<{ children?: ReactNode }, { error: Error | null }> {\n constructor(props: { children?: ReactNode }) {\n super(props)\n this.state = { error: null }\n }\n\n static getDerivedStateFromError(error: unknown): { error: Error | null } {\n return { error: error instanceof Error ? error : new Error(String(error)) }\n }\n\n render(): ReactNode {\n const error = this.state.error\n if (error === null) return this.props.children\n return (\n <div className=\"redline-root\">\n <div className=\"redline-empty redline-error\">\n <span>{t('error')}</span>\n <code className=\"redline-error-msg\">{error.message}</code>\n <button\n type=\"button\"\n className=\"redline-error-retry hover:border-(--dsw-alias-label-primary)\"\n onClick={() => { this.setState({ error: null }) }}\n >{t('error.retry')}</button>\n </div>\n </div>\n )\n }\n }\n}\n","/**\n * The shared Escape-to-close contract of the plugin's overlays (the /redline\n * modal and the baseline-gate dialog): capture-phase keydown on window, so\n * the composer's own key handling never swallows Escape first; on close, focus\n * returns to the element that held it when the overlay opened (skipped when\n * that element left the document).\n */\n\nimport { useEffect, useRef } from 'react'\n\n/**\n * Close on Escape while `active`; restores the pre-open focus on cleanup.\n * `onClose` rides a latest-ref so the subscription lives on the `active`\n * transitions alone: every caller passes a render-fresh closure, and a\n * per-render resubscribe would rerun the cleanup's focus restore — yanking\n * focus out of the overlay's own inputs on every keystroke.\n */\nexport function useEscapeClose(active: boolean, onClose: () => void): void {\n const close = useRef(onClose)\n close.current = onClose\n useEffect(() => {\n if (!active) return undefined\n const previous = document.activeElement instanceof HTMLElement ? document.activeElement : null\n const onKey = (ev: KeyboardEvent): void => {\n if (ev.key !== 'Escape') return\n ev.preventDefault()\n ev.stopPropagation()\n close.current()\n }\n window.addEventListener('keydown', onKey, true)\n return () => {\n window.removeEventListener('keydown', onKey, true)\n if (previous !== null && document.contains(previous)) previous.focus()\n }\n }, [active])\n}\n","/**\n * The panel's transport to OUR route (`REDLINE_CHANNEL_ROUTE`) — the only way the\n * browser half talks to the editing layer.\n *\n * Two contracts this file exists to keep:\n *\n * 1. **One path, shared with the host.** The URL is `REDLINE_CHANNEL_ROUTE` from\n * `src/shared/redline-route.ts`, never a literal. A hand-written path on either\n * side is how \"前缀/形状不成对\" turns into a silent 404 (`docs/01` F1,\n * `docs/05` A12) — the `channel` lane asserts the host REGISTERS that constant,\n * and `tests/client-logic/redline-channel.spec.ts` asserts the client POSTS it.\n *\n * 2. **Failures are values, never exceptions.** Every outcome is either\n * `{ok:true, value}` or `{ok:false, code, message}` with a STABLE code, because\n * the editor must show the reason while keeping the user's input\n * (`docs/03` R3.5). An exception escaping here would blank the row instead.\n *\n * Reads the FULL text: `node.read` answers the durable event's complete body, not\n * the list preview (`docs/01` F35) — the editor prefills from exactly this.\n */\n\nimport { REDLINE_ERROR } from '../shared/redline-errors'\nimport { REDLINE_CHANNEL_ROUTE, type RedlineEnvelope } from '../shared/redline-route'\nimport type { ChildCapacity } from '../shared/redline-capacity'\nimport type { OriginRecord } from '../shared/redline-origins'\nimport type { DraftTable } from '../shared/redline-drafts'\nimport type { TurnState } from '../shared/redline-turn'\n\n/** One row's complete content, as `node.read` answers it. */\nexport interface RedlineRow {\n readonly seq: number\n /** The durable event type (`docs/03` R3.2 keys the editor fields off it). */\n readonly type: string\n readonly text: string\n readonly reasoning: string\n readonly isError: boolean\n}\n\n/** The edit the editor submits. `reasoning`/`isError` are only meaningful per type. */\nexport interface DraftEdit {\n readonly text: string\n readonly reasoning: string\n readonly isError: boolean\n}\n\n/** The transport's outcome: a value, or a stable code the UI turns into a sentence. */\nexport type RedlineResult<T> =\n | { readonly ok: true; readonly value: T }\n | { readonly ok: false; readonly code: string; readonly message: string }\n\n/** Narrow an untrusted body to our envelope. */\nfunction envelopeOf(body: unknown): RedlineEnvelope<unknown> | null {\n if (body === null || typeof body !== 'object' || Array.isArray(body)) return null\n const bag = body as { ok?: unknown; value?: unknown; error?: unknown }\n if (bag.ok === true) return { ok: true, value: bag.value }\n if (bag.ok === false) {\n const error = bag.error\n if (error === null || typeof error !== 'object') return null\n const { code, message } = error as { code?: unknown; message?: unknown }\n if (typeof code !== 'string') return null\n return { ok: false, error: { code, message: typeof message === 'string' ? message : code } }\n }\n return null\n}\n\n/** POST one op and normalize every possible outcome into a {@link RedlineResult}. */\nasync function call<T>(body: Record<string, unknown>): Promise<RedlineResult<T>> {\n let response: Response\n try {\n response = await fetch(REDLINE_CHANNEL_ROUTE, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n // The route is `no-store` on the host side too; a cached refusal would be a\n // lie the user cannot get rid of by saving again.\n cache: 'no-store',\n body: JSON.stringify(body),\n })\n } catch (error) {\n return { ok: false, code: REDLINE_ERROR.transport, message: error instanceof Error ? error.message : String(error) }\n }\n let parsed: unknown\n try {\n parsed = await response.json()\n } catch (error) {\n return {\n ok: false,\n code: REDLINE_ERROR.transport,\n message: `${REDLINE_ERROR.transport}: HTTP ${String(response.status)} ${error instanceof Error ? error.message : ''}`.trim(),\n }\n }\n const envelope = envelopeOf(parsed)\n if (envelope === null) {\n return { ok: false, code: REDLINE_ERROR.transport, message: `${REDLINE_ERROR.transport}: HTTP ${String(response.status)}` }\n }\n if (!envelope.ok) return { ok: false, code: envelope.error.code, message: envelope.error.message }\n return { ok: true, value: envelope.value as T }\n}\n\n/** One row's COMPLETE content — the editor's only prefill source. */\nexport async function readRow(sessionId: string, seq: number): Promise<RedlineResult<RedlineRow>> {\n return await call<RedlineRow>({ op: 'node.read', sessionId, seq })\n}\n\n/**\n * Whether this session can be edited right now (`docs/03` R4.3). Asked BEFORE the\n * editor opens, because the demo blocks editing entirely mid-turn / on a session\n * this process does not host — a save button that fails after the click is a\n * worse experience than one that is disabled with the reason beside it.\n */\nexport async function readTurnState(sessionId: string): Promise<RedlineResult<TurnState>> {\n return await call<TurnState>({ op: 'turnState', sessionId })\n}\n\n/** Every local edit of this session (the row markers and the prefill read this). */\nexport async function listDrafts(sessionId: string): Promise<RedlineResult<DraftTable>> {\n return await call<DraftTable>({ op: 'draft.list', sessionId })\n}\n\n/**\n * Save one row's local edit. Refusals are expected values: `redline/no-change`\n * (identical to the version in effect) and `redline/empty-content`.\n */\nexport async function saveDraft(sessionId: string, seq: number, edit: DraftEdit): Promise<RedlineResult<DraftTable>> {\n return await call<DraftTable>({ op: 'draft.update', sessionId, seq, edit })\n}\n\n/** Forget one row's local edit (the row goes back to its original). */\n/**\n * 标为「不要」(`excluded: true`)或取消标记(`false`)。**只写插件本地** ——\n * 当前会话一个字都不写;开启子会话时由首条任务逐字声明这几条作废(`docs/11` D65)。\n */\nexport async function excludeDraft(sessionId: string, seq: number, excluded: boolean): Promise<RedlineResult<DraftTable>> {\n return await call<DraftTable>({ op: 'draft.exclude', sessionId, seq, excluded })\n}\n\nexport async function dropDraft(sessionId: string, seq: number): Promise<RedlineResult<DraftTable>> {\n return await call<DraftTable>({ op: 'draft.drop', sessionId, seq })\n}\n\n/** 确认框五项 + 组装好的首条任务(开子会话**之前**能问的全部事实;只读)。 */\nexport interface ChildPlan {\n /** 恰好五项:从哪儿开始 / 会带上的改动 / 第一句话由人写 / 会带什么不带什么 / 取消。 */\n items: readonly { label: string; text: string }[]\n /** 会逐字带过去的本地改动(按 seq)。 */\n carriedSeqs: readonly number[]\n /** 已删除、不会写进普通新会话的 seq。 */\n excludedSeqs: readonly number[]\n /** Opaque confirmation token: exact operation + draft + source + manifest versions. */\n draftRevision: string\n /** 组装好的最终发送全文;被拒绝时为 `null`。用户可在确认框直接编辑。 */\n prompt: string | null\n /** 默认冻结配置;修改只作用于即将创建的普通新会话。 */\n config?: { agentPreset: string; provider: string; model: string; reasoningEffort?: string }\n /** 首条任务的读数(M2-20):UTF-8 字节 / 行 / 带了几条改动;被拒绝时为 `null`。 */\n metrics: { bytes: number; lines: number; edits: number } | null\n /** 被拒绝时给一句人话(例如\"第一句话必须你自己写\")。 */\n refusal: { code: string; message: string } | null\n}\n\n/** 开子会话之前问事实(只读,绝不写任何东西)。 */\nexport async function planChild(sessionId: string, humanTask: string): Promise<RedlineResult<ChildPlan>> {\n return await call<ChildPlan>({ op: 'carrier.plan', sessionId, humanTask })\n}\n\nexport interface CarrierModelOption {\n readonly provider: string\n readonly providerName: string\n readonly model: string\n readonly modelName: string\n readonly efforts: readonly { readonly id: string; readonly name: string }[]\n readonly defaultEffort?: string\n}\n\nexport async function readCarrierModels(): Promise<RedlineResult<{ models: readonly CarrierModelOption[] }>> {\n return await call<{ models: readonly CarrierModelOption[] }>({ op: 'carrier.models' })\n}\n\n/** 开子会话成功后的回执。 */\nexport interface ChildStarted {\n /**\n * 走的是哪条路:`'official-member'`(官方团队成员)/ `'bare-child'`(裸子会话)。\n * 界面必须如实标出来 —— 两者的可管理性完全不同(官方那份能在官方团队视图里看到)。\n */\n via?: string\n label: string\n prompt: string\n carriedSeqs: readonly number[]\n /** 平台给的子会话回执(`childId` / `messageId`)。 */\n started: unknown\n}\n\n/**\n * **开子会话** —— 全插件唯一的写入点。\n *\n * 只在人**明确点了确认**之后调用;`humanTask` 是人写的第一句话(空着会被宿主拒绝)。\n * 拒绝一律以稳定的 code + 一句人话回来(transport 从不抛),界面照它显示就行。\n */\nexport async function startChild(\n sessionId: string,\n humanTask: string,\n confirmationToken: string,\n finalText?: string,\n config?: { provider: string; model: string; reasoningEffort?: string },\n): Promise<RedlineResult<ChildStarted>> {\n return await call<ChildStarted>({ op: 'carrier.start', sessionId, humanTask, confirmationToken, finalText, config })\n}\n\nexport interface CarrierListRow {\n readonly id: string\n readonly label: string\n readonly mode: 'continuable'\n readonly createdAt: number\n readonly via: 'ordinary-session'\n}\n\nexport async function readCarriers(sessionId: string): Promise<RedlineResult<{ rows: readonly CarrierListRow[] }>> {\n return await call<{ rows: readonly CarrierListRow[] }>({ op: 'carrier.list', sessionId })\n}\n\n/** `child.origins` 的回答:`records: null` = 我们那本台账**读不出来**(界面必须说\"来源未知\")。 */\nexport interface OriginAnswer {\n readonly records: readonly OriginRecord[] | null\n readonly error?: string\n}\n\n/**\n * M5-12 的来源台账:问宿主\"这些子会话里,哪些**是在这个面板里**开的\"。\n * 只读;`records: null` 表示**读不出来**(与\"空台账\"是两件事,界面话术不同)。\n */\nexport async function readOrigins(sessionId: string): Promise<RedlineResult<OriginAnswer>> {\n return await call<OriginAnswer>({ op: 'child.origins', sessionId })\n}\n\n/**\n * M5-13 的分母:问宿主\"这台机器允许几个团队成员\"。\n * 只读;形状不可信 ⟹ 调用方要用 `capacityOf()` re-prove 一遍再进渲染。\n */\nexport async function readCapacity(): Promise<RedlineResult<ChildCapacity>> {\n return await call<ChildCapacity>({ op: 'child.capacity' })\n}\n","/**\n * The panel's local-edit state: one loaded `DraftTable` per session, plus the\n * save/discard calls the rows make.\n *\n * Three rules this hook exists to keep, all from the hard constraint of\n * `docs/11` D15 (\"every save is temporary\"):\n *\n * 1. **A save only ever writes our own store.** Nothing here touches the session\n * log; the only call it makes is `draft.update` on our channel, and the host\n * answers with the new table — which this hook then adopts as the truth. No\n * optimistic merge of our own construction: a refusal (`redline/no-change`,\n * `redline/empty-content`) must leave the stored table exactly as it was.\n * 2. **A refusal is shown, never swallowed** (`docs/03` R3.5): the failing row\n * keeps the user's input and displays the reason, mapped from the STABLE code\n * by the component (`redline.err.<code>`).\n * 3. **One request at a time per row**, so a double click cannot interleave two\n * saves of the same row.\n */\n\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react'\nimport type { DraftTable } from '../shared/redline-drafts'\nimport { dropDraft, excludeDraft, listDrafts, readRow, readTurnState, saveDraft, type DraftEdit, type RedlineResult, type RedlineRow } from './redlineChannel'\nimport type { TurnState } from '../shared/redline-turn'\n\n/** The per-row failure the editor shows, keyed by the row it belongs to. */\nexport interface RedlineRowError {\n readonly seq: number\n /** A stable code (`redline/*`), or `redline/transport`. */\n readonly code: string\n}\n\nexport interface RedlineDraftController {\n /** The local edits in effect (the row markers and the prefill read this). */\n readonly table: DraftTable\n /**\n * Whether editing is allowed at all right now. `known:false` = view only;\n * `open:true` = the turn has not closed. The panel disables `保存` on both and\n * says why (`docs/03` R4.3) — before any round trip, like the demo does.\n */\n readonly turn: TurnState\n /** False until the first load settles — the panel shows nothing edited before that. */\n readonly ready: boolean\n /** The row currently saving/dropping, so its buttons can disable. */\n readonly busySeq: number | null\n /** The last refusal/failure for the editor to display. */\n readonly rowError: RedlineRowError | null\n /** One row's COMPLETE content — what the editor prefills from (`docs/01` F35). */\n loadRow(seq: number): Promise<RedlineResult<RedlineRow>>\n /** Resolves true only when the save was accepted (so the editor knows to close). */\n save(seq: number, edit: DraftEdit): Promise<boolean>\n /** Resolves true only when the discard was accepted. */\n drop(seq: number): Promise<boolean>\n /** 标为「不要」/ 取消标记(`docs/11` D65)。解析为 true 表示宿主接受了。 */\n exclude(seq: number, on: boolean): Promise<boolean>\n /** Forget a row's error (the next open starts clean). */\n clearError(): void\n}\n\n/**\n * Load and mutate one session's local edits.\n *\n * @param sessionId - the session whose rows are shown; `undefined` keeps it idle\n * (a slot can mount before the framework hands a session over).\n */\nexport function useRedlineDrafts(sessionId: string | undefined): RedlineDraftController {\n const [table, setTable] = useState<DraftTable>({})\n const [ready, setReady] = useState(false)\n const [busySeq, setBusySeq] = useState<number | null>(null)\n const [rowError, setRowError] = useState<RedlineRowError | null>(null)\n const [turn, setTurn] = useState<TurnState>({ known: true, open: false })\n // A late answer from a previous session must not overwrite the current one.\n const generation = useRef(0)\n\n useEffect(() => {\n generation.current += 1\n const mine = generation.current\n setTable({})\n setReady(false)\n setRowError(null)\n setTurn({ known: true, open: false })\n if (sessionId === undefined || sessionId === '') return\n void (async () => {\n const [drafts, state] = await Promise.all([listDrafts(sessionId), readTurnState(sessionId)])\n if (generation.current !== mine) return\n if (drafts.ok) setTable(drafts.value)\n else setRowError({ seq: -1, code: drafts.code })\n // A failed state read must not silently look \"editable\": `known:false` is the\n // honest answer (view only), and the panel says so.\n setTurn(state.ok ? state.value : { known: false, open: false })\n setReady(true)\n })()\n }, [sessionId])\n\n const save = useCallback(async (seq: number, edit: DraftEdit): Promise<boolean> => {\n if (sessionId === undefined || sessionId === '') return false\n setBusySeq(seq)\n setRowError(null)\n const result = await saveDraft(sessionId, seq, edit)\n setBusySeq(current => (current === seq ? null : current))\n if (!result.ok) { setRowError({ seq, code: result.code }); return false }\n setTable(result.value)\n return true\n }, [sessionId])\n\n const exclude = useCallback(async (seq: number, on: boolean): Promise<boolean> => {\n if (sessionId === undefined || sessionId === '') return false\n setBusySeq(seq)\n setRowError(null)\n const result = await excludeDraft(sessionId, seq, on)\n setBusySeq(current => (current === seq ? null : current))\n if (!result.ok) { setRowError({ seq, code: result.code }); return false }\n setTable(result.value)\n return true\n }, [sessionId])\n\n const drop = useCallback(async (seq: number): Promise<boolean> => {\n if (sessionId === undefined || sessionId === '') return false\n setBusySeq(seq)\n setRowError(null)\n const result = await dropDraft(sessionId, seq)\n setBusySeq(current => (current === seq ? null : current))\n if (!result.ok) { setRowError({ seq, code: result.code }); return false }\n setTable(result.value)\n return true\n }, [sessionId])\n\n const loadRow = useCallback(async (seq: number): Promise<RedlineResult<RedlineRow>> => {\n if (sessionId === undefined || sessionId === '') {\n return { ok: false, code: 'redline/not-live', message: 'no session' }\n }\n return await readRow(sessionId, seq)\n }, [sessionId])\n\n const clearError = useCallback(() => { setRowError(null) }, [])\n\n return useMemo(\n () => ({ table, turn, ready, busySeq, rowError, loadRow, save, drop, exclude, clearError }),\n [table, turn, ready, busySeq, rowError, loadRow, save, drop, exclude, clearError],\n )\n}\n","/**\n * The /redline command's centered dialog — the same data as the Context tab (the pushed `redlineTimeline` projection) distilled to the\n * current-composition overview and the shared Context browser; rendered from the `conversation.input.overlay` slot and opened/closed\n * through the per-session modal store, so the trigger flips it and no message ever enters session history.\n */\n\nimport { createElement as h, useCallback, useLayoutEffect, useMemo, useRef, useState, type ReactElement } from 'react'\nimport { measureDock } from '../dockMeasure'\nimport { headlineOf } from '../headline'\nimport { modalStoreOf, takePendingConsume } from '../modalStore'\nimport type { ClientCtx, SessionStandardProps, SessionsFace } from '../services'\nimport type { ContextSettings } from '../settings'\nimport { contextBreakdownOf, contextPressureOf, conversationNodesOf, headersOf, imageLoaderOf, projectionOf } from '../services'\nimport { makeContentFetcher, makeHeaderFetcher, useHistoryFace } from '../historyPage'\nimport { useTimelineSource } from '../timelineSource'\nimport type { ViewKit } from '../viewkit'\nimport { makeContextBrowser } from './browser'\nimport { makeCurrentComposition } from './currentComposition'\nimport { makeErrorBoundary } from './errorBoundary'\nimport { useEscapeClose } from './escapeClose'\nimport { makeLegend, makeStackedBar } from './stackedBar'\nimport { useRedlineDrafts } from '../redlineDrafts'\n\nexport interface ContextModalProps extends SessionStandardProps {\n /** Bound selector hook over the per-session open flag (hooks compartment). */\n useContextModal?: (sel: (open: boolean) => boolean) => boolean\n}\n\nexport function makeContextModal(\n ctx: ClientCtx,\n kit: ViewKit,\n settings: ContextSettings,\n): (props: ContextModalProps) => ReactElement | null {\n const { t } = kit\n const StackedBar = makeStackedBar(kit)\n const Legend = makeLegend(kit)\n const CurrentComposition = makeCurrentComposition(kit, StackedBar, Legend)\n const ContextBrowser = makeContextBrowser(kit, StackedBar, settings)\n const ErrorBoundary = makeErrorBoundary(t)\n\n function ContextModalBody(props: ContextModalProps): ReactElement | null {\n const sessionId = typeof props.sessionId === 'string' ? props.sessionId : ''\n const redline = useRedlineDrafts(sessionId !== '' ? sessionId : undefined)\n const open = typeof props.useContextModal === 'function' ? props.useContextModal(s => s) : false\n // The timeline source (timelineSource.ts) — shares the tab's per-session\n // detail store, so an open tab's detail serves the modal with no refetch.\n const source = useTimelineSource(ctx, props)\n const data = source.data\n const pressure = projectionOf(props, 'contextPressure', contextPressureOf)\n const breakdown = projectionOf(props, 'contextBreakdown', contextBreakdownOf)\n const headers = projectionOf(props, 'redlineHeaders', headersOf)\n // Conversation-window join for the browser (the seat is a real hook —\n // read unconditionally here, before the closed early return, so the hook\n // order stays stable across open/close).\n const convNodes = conversationNodesOf(props)\n const [hoverCat, setHoverCat] = useState<string | null>(null)\n // Dock the mask beside the shell sidebar: 0 until the frame measure lands\n // (the layout effect below resolves it before first paint).\n const [dockLeft, setDockLeft] = useState(0)\n const backdropRef = useRef<HTMLDivElement | null>(null)\n // Session-authorized durable-image loader for the browser's attachment cards, resolved through the harness `uiConversation` service\n // (`imageUrl`); absent service/session degrades the cards to metadata-only, never an error. Same parity as the Context tab.\n const loadImage = useMemo(\n () => imageLoaderOf(ctx, sessionId !== '' ? sessionId : undefined),\n [ctx, sessionId],\n )\n\n // The gateway page face, as a React seat: the first render can race the declared inject (a watch rebuild remounts this overlay before\n // the fiber re-fires), and both fetchers below must rebuild — not stick to the static degradation — when the face lands or is revoked.\n const historyFace = useHistoryFace()\n\n // Same targeted content fetch the Context tab wires (one seq-anchored history read per expanded row), plus the on-demand header\n // epoch content read for the browser's system/tools sections.\n const fetchContent = useMemo(\n () => (sessionId !== '' && historyFace !== undefined ? makeContentFetcher(sessionId) : undefined),\n [sessionId, historyFace],\n )\n const fetchHeader = useMemo(\n () => (sessionId !== '' && historyFace !== undefined ? makeHeaderFetcher(sessionId) : undefined),\n [sessionId, historyFace],\n )\n\n const close = useCallback(() => {\n if (sessionId === '') return\n modalStoreOf(sessionId).set(false)\n // Consume the `/redline` token now (it stayed in the composer while the modal was open) via the scoped input event — a stale guard\n // (the user typed meanwhile) fails soft inside the shell and leaves the draft untouched. The sessions service is read at CLOSE time:\n // capturing it at apply would race the finer module composition (`ctx.get` is the inject-free reflect read — undefined, never a\n // throw, when the service is not composed).\n const guard = takePendingConsume(sessionId)\n const sessions = ctx.get('sessions') as SessionsFace | undefined\n if (guard === undefined || sessions === undefined) return\n const scope = sessions.scope(sessionId)\n if (scope !== undefined) scope.bail(scope, 'slash/input-consume-token', { guard })\n }, [ctx, sessionId])\n\n // Capture-phase Escape close + focus restore (the shared overlay contract).\n useEscapeClose(open, close)\n\n // Dock the mask to the main column: measure the sidebar track once before\n // first paint, then follow the frame's inline template while open (sidebar\n // drags, collapse toggles and narrow-viewport re-solves all rewrite it).\n // An unresolved frame keeps the full-viewport mask.\n useLayoutEffect(() => {\n if (!open) return undefined\n const dock = measureDock(backdropRef.current)\n setDockLeft(dock.left)\n if (dock.frame === null) return undefined\n const observer = new MutationObserver(() => {\n setDockLeft(measureDock(backdropRef.current).left)\n })\n observer.observe(dock.frame, { attributes: true, attributeFilter: ['style'] })\n return () => { observer.disconnect() }\n }, [open])\n\n if (!open) return null\n\n const head = data !== null ? headlineOf(data, pressure, breakdown) : null\n const subtitle = data !== null ? (data.model ? data.model : '') + (data.provider ? ' · ' + data.provider : '') : ''\n\n return (\n <div ref={backdropRef} className=\"redline-modal-backdrop\" style={{ left: dockLeft }} onClick={close}>\n <div className=\"redline-modal-card\" onClick={(ev) => { ev.stopPropagation() }}>\n <div className=\"redline-modal-head\">\n <span className=\"redline-modal-title\">{t('tab')}</span>\n <button className=\"redline-modal-close hover:text-(--dsw-alias-label-primary) hover:bg-(--dsw-alias-bg-layer-2)\" aria-label={t('cmd.close')} onClick={close}>×</button>\n </div>\n\n {data === null || head === null ? (\n <div className=\"redline-empty\">{t('loading')}</div>\n ) : (\n <div>\n <CurrentComposition\n head={head}\n subtitle={subtitle}\n hoverKey={hoverCat}\n onHoverKey={setHoverCat}\n />\n <ContextBrowser\n redline={redline}\n data={data}\n headers={headers}\n convNodes={convNodes}\n fetchContent={fetchContent}\n fetchHeader={fetchHeader}\n loadImage={loadImage}\n hoverKey={hoverCat}\n onHoverKey={setHoverCat}\n detailState={source.detailState}\n onDetailRetry={source.retryDetail}\n />\n </div>\n )}\n </div>\n </div>\n )\n }\n\n return function ContextModal(props: ContextModalProps): ReactElement | null {\n return h(ErrorBoundary, null, h(ContextModalBody, props))\n }\n}\n","/**\n * Best-effort jump to this plugin's preferences. Two generations of chrome:\n * - dsh 0.1.7+ (Config-form generation): the preferences live on the\n * bundle's page of the Plugins main panel — the jump clicks the panel's\n * sidebar entry (its shipped aria-label), then follows the page with a\n * bounded poll for the bundle card's open control, found by the shipped,\n * locale-independent `data-plugin-package` list identity: the card lists\n * once the page's package load settles, and inside it the one button\n * that is not the enable switch is the title that opens the page. A\n * poll that never finds the card (still loading, plugin absent, or the\n * page already open on the detail view — the list unmounts there)\n * degrades to the card list, and every step stays silent.\n * - older lines: Settings → Plugins → Plugin configuration — the settings\n * panel keeps its open state inside the shell component (no plugin-facing\n * open face exists), so the jump drives the real chrome: click the\n * sidebar's settings trigger, then the Plugins section nav row, both\n * found by their shipped attributes and labels.\n * The last leg — the card itself — is ours: the module also carries a\n * short-lived in-bundle expand request that the settings-section card\n * consumes on mount, so that jump lands on the configuration already open.\n * EVERY step is individually guarded: a shell that doesn't match (different\n * layout, missing sidebar) degrades the whole jump to a silent no-op — this\n * path must never throw into the caller's render.\n */\n\nlet requestedAt = 0\n\n/** Raise a short-lived request for the plugin's settings card to mount expanded. */\nexport function requestCardExpand(now: number = Date.now()): void {\n requestedAt = now\n}\n\n/** Consume the request once; true only while it is still fresh (younger than maxAgeMs). */\nexport function consumeCardExpand(now: number = Date.now(), maxAgeMs = 5000): boolean {\n const fresh = requestedAt > 0 && now - requestedAt < maxAgeMs\n requestedAt = 0\n return fresh\n}\n\n/**\n * The shipped Plugins label in both locales — the main-panel entry's\n * aria-label and the settings section's nav row text are the same word.\n */\nconst PLUGIN_LABELS = new Set(['Plugins', '插件'])\n\n/** The bundle card's shipped list identity (locale-independent). */\nconst PACKAGE_KEY = 'dsh-context-redline'\n\n/** How long the card poll follows the panel: 40 ticks at the 100ms tick, enough for the page's package load. */\nconst POLL_TICKS = 40\n\n/** Buttons the jump may operate on, in document order. */\nfunction buttonsOf(doc: Document): HTMLButtonElement[] {\n return [...doc.querySelectorAll<HTMLButtonElement>('button')]\n}\n\n/** The Plugins main-panel entry, matched by its shipped aria-label. */\nfunction findPanelEntry(doc: Document): HTMLButtonElement | undefined {\n return buttonsOf(doc).find(b => PLUGIN_LABELS.has(b.getAttribute('aria-label') ?? ''))\n}\n\n/**\n * The bundle card's open control: the one button inside the card that is not\n * the enable switch (the primitives switch carries `role=\"switch\"`); the\n * title button's own aria-label is localized.\n */\nfunction findCardOpenControl(doc: Document): HTMLButtonElement | undefined {\n const card = doc.querySelector(`[data-plugin-package=\"${PACKAGE_KEY}\"]`)\n if (card === null) return undefined\n const open = [...card.querySelectorAll<HTMLButtonElement>('button')].filter(b => b.getAttribute('role') !== 'switch')\n return open.length === 1 ? open[0] : undefined\n}\n\n/** The sidebar's settings triggers: dialog semantics plus an expanded flag. */\nfunction findTriggers(doc: Document): HTMLButtonElement[] {\n return buttonsOf(doc)\n .filter(b => b.getAttribute('aria-haspopup') === 'dialog' && b.hasAttribute('aria-expanded'))\n}\n\n/** The Plugins section's nav row, matched by its shipped label text. */\nfunction findSectionRow(doc: Document): HTMLButtonElement | undefined {\n return buttonsOf(doc).find(b => PLUGIN_LABELS.has(b.textContent.trim()))\n}\n\nexport function openPluginSettings(\n doc: Document = document,\n schedule: (run: () => void, ms: number) => void = (run, ms) => { window.setTimeout(run, ms) },\n): void {\n try {\n // Config-form generation first: the panel entry is the one seat both\n // locales ship. The follow-up poll rides the same scheduler contract as\n // the legacy leg, so tests drive every tick.\n const panel = findPanelEntry(doc)\n if (panel !== undefined) {\n panel.click()\n const poll = (left: number): void => {\n try {\n const open = findCardOpenControl(doc)\n if (open !== undefined) {\n open.click()\n return\n }\n } catch { /* a hostile card: stay on the card list */ }\n if (left > 0) schedule(() => { poll(left - 1) }, 100)\n }\n schedule(() => { poll(POLL_TICKS) }, 200)\n return\n }\n const triggers = findTriggers(doc)\n const open = triggers.find(b => b.getAttribute('aria-expanded') === 'true')\n // No dialog trigger at all: this shell has no settings panel — no-op.\n if (open === undefined && triggers.length === 0) return\n // A collapsed trigger opens the panel; an already-open one is left alone.\n triggers.find(b => b.getAttribute('aria-expanded') !== 'true')?.click()\n // Only a chrome with a settings dialog raises the expand request, and\n // only once the trigger click survived — a degraded jump leaves no\n // stale signal behind.\n requestCardExpand()\n schedule(() => {\n try {\n findSectionRow(doc)?.click()\n } catch { /* no Plugins row on this host: stay on the opened section */ }\n }, 80)\n } catch { /* the settings surface doesn't match: silent no-op */ }\n}\n","/**\n * The dsh-context-redline preference cards — two seats over the same six rows. The\n * settings-section card (`settings.plugin.item`, the older harness lines)\n * renders a collapsible list item in Settings → Plugins → Plugin\n * configuration; the Plugins-page card (`plugins.bundle.config`, the\n * Config-form generation) renders the rows flat inside the section chrome the\n * Plugins page draws for the bundle. Both are keyed on the Host-served\n * `dsh-context-redline` namespace and render nothing while it is unavailable (a\n * deployment without the Host half, or a remote browser, shows no trace).\n * The settings-section card mounts expanded when the Plugin Info card's\n * \"Open plugin settings\" jump left a fresh expand request (settingsJump.ts),\n * scrolling itself into view.\n */\n\nimport { useEffect, useRef, useState, type ReactElement } from 'react'\nimport { Menu } from '@deepseek-ai/dsh-client-ui-primitives'\nimport { IconChevronDown } from '../primitives'\nimport { consumeCardExpand } from '../settingsJump'\nimport type { SettingsField, SettingsState } from '../settings'\nimport type { ViewKit } from '../viewkit'\n\nexport interface SettingsCardProps {\n useContextSettings?: <T>(selector: (state: SettingsState) => T) => T\n set?: (field: SettingsField, value: string) => void\n}\n\ninterface PrefRowProps {\n label: string\n value: string\n options: ReadonlyArray<{ id: string; label: string }>\n disabled: boolean\n onPick: (id: string) => void\n}\n\nfunction PrefRow(props: PrefRowProps): ReactElement {\n const [open, setOpen] = useState(false)\n const active = props.options.find(o => o.id === props.value)?.label ?? props.value\n return (\n <div className=\"redline-settings-row\">\n <span className=\"redline-settings-label\">{props.label}</span>\n <Menu\n open={open}\n onClose={() => { setOpen(false) }}\n items={props.options}\n selectedId={props.value}\n onSelect={(id) => { setOpen(false); props.onPick(id) }}\n align=\"end\"\n portal\n anchor={(\n <button\n type=\"button\"\n className=\"redline-settings-select hover:enabled:bg-(--dsw-alias-interactive-bg-hover) disabled:opacity-50 disabled:cursor-default\"\n disabled={props.disabled}\n aria-haspopup=\"menu\"\n aria-expanded={open}\n onClick={() => { setOpen(v => !v) }}\n >\n {active}\n <IconChevronDown />\n </button>\n )}\n />\n </div>\n )\n}\n\n/** Translate over the plugin's dictionary, as the view kit binds it. */\ntype Translate = ViewKit['t']\n\n/** The six preference rows shared by both seats. */\nfunction PreferenceRows(props: { t: Translate; state: SettingsState; set?: SettingsCardProps['set'] }): ReactElement {\n const { t, state, set } = props\n const disabled = state.status !== 'ready' || !state.writable\n return (\n <>\n <PrefRow\n label={t('settings.placement')}\n value={state.placement}\n disabled={disabled}\n options={[\n { id: 'all', label: t('placement.all') },\n { id: 'tab', label: t('placement.tab') },\n { id: 'sidebar', label: t('placement.sidebar') },\n ]}\n onPick={(id) => { set?.('defaultPlacement', id) }}\n />\n {/* 「洞察入口」那个开关随洞察面一起删掉了(2026-10-05 用户选二)—— 不留\"按了没反应\"的开关。 */}\n <PrefRow\n label={t('settings.gran')}\n value={state.granularity}\n disabled={disabled}\n options={[\n { id: 'step', label: t('gran.step') },\n { id: 'turn', label: t('gran.turn') },\n ]}\n onPick={(id) => { set?.('defaultGranularity', id) }}\n />\n <PrefRow\n label={t('settings.mode')}\n value={state.mode}\n disabled={disabled}\n options={[\n { id: 'total', label: t('gran.total') },\n { id: 'delta', label: t('gran.delta') },\n ]}\n onPick={(id) => { set?.('defaultTrendMode', id) }}\n />\n <PrefRow\n label={t('settings.toolSort')}\n value={state.toolSort}\n disabled={disabled}\n options={[\n { id: 'size', label: t('tool.sort.size') },\n { id: 'count', label: t('tool.sort.count') },\n { id: 'name', label: t('tool.sort.name') },\n ]}\n onPick={(id) => { set?.('defaultToolSort', id) }}\n />\n <PrefRow\n label={t('settings.fileSort')}\n value={state.fileSort}\n disabled={disabled}\n options={[\n { id: 'count', label: t('files.sort.count') },\n { id: 'latest', label: t('files.sort.latest') },\n { id: 'path', label: t('files.sort.path') },\n ]}\n onPick={(id) => { set?.('defaultFileSort', id) }}\n />\n </>\n )\n}\n\nexport function makeSettingsCard(kit: ViewKit): (props: SettingsCardProps) => ReactElement | null {\n const { t } = kit\n return function SettingsCard(props: SettingsCardProps): ReactElement | null {\n const [open, setOpen] = useState(false)\n const itemRef = useRef<HTMLLIElement | null>(null)\n // \"Open plugin settings\" jump: consume its fresh expand request once on\n // mount and land open; every guard stays local so no host quirk can surface.\n useEffect(() => {\n if (!consumeCardExpand()) return\n setOpen(true)\n try {\n itemRef.current?.scrollIntoView({ block: 'nearest' })\n } catch { /* hosts without scrollIntoView: expanded but unscrolled */ }\n }, [])\n const state = typeof props.useContextSettings === 'function' ? props.useContextSettings(s => s) : undefined\n if (state === undefined || state.status === 'unavailable') return null\n return (\n <li ref={itemRef} className={'redline-settings-card' + (open ? ' redline-settings-open' : '')}>\n <button\n type=\"button\"\n className=\"redline-settings-head\"\n aria-expanded={open}\n aria-label={`${t(open ? 'settings.collapse' : 'settings.expand')}: ${t('settings.title')}`}\n onClick={() => { setOpen(!open) }}\n >\n <span className=\"redline-settings-headtext\">\n <span className=\"redline-settings-name\">{t('settings.title')}</span>\n <span className=\"redline-settings-desc\">{t('settings.desc')}</span>\n </span>\n <IconChevronDown className=\"redline-settings-chevron\" />\n </button>\n {open\n ? (\n <div className=\"redline-settings-body\">\n {!state.writable && state.status === 'ready'\n ? <p className=\"redline-settings-note\" role=\"status\">{t('settings.readOnly')}</p>\n : null}\n <PreferenceRows t={t} state={state} set={props.set} />\n </div>\n )\n : null}\n </li>\n )\n }\n}\n\n/**\n * The Plugins-page card (the Config-form generation's `plugins.bundle.config`\n * seat, `view: 'page'`): the page owns the bundle's page and section chrome,\n * so the rows render flat. Same unserved/absent degradation as the\n * settings-section card.\n */\nexport function makePluginConfigCard(kit: ViewKit): (props: SettingsCardProps) => ReactElement | null {\n const { t } = kit\n return function PluginConfigCard(props: SettingsCardProps): ReactElement | null {\n const state = typeof props.useContextSettings === 'function' ? props.useContextSettings(s => s) : undefined\n if (state === undefined || state.status === 'unavailable') return null\n return (\n <div className=\"redline-settings-prefs\">\n {!state.writable && state.status === 'ready'\n ? <p className=\"redline-settings-note\" role=\"status\">{t('settings.readOnly')}</p>\n : null}\n <PreferenceRows t={t} state={state} set={props.set} />\n </div>\n )\n }\n}\n","/**\n * The plugin's user-settings binding (browser half). The Host-served\n * `dsh-context-redline` namespace carries per-user display preferences; the Context\n * tab reads them at mount, and the Plugin configuration card (Settings →\n * Plugins) writes them through the settings scope. Both degrade to the\n * schema defaults when the settings surface is absent (older host) or\n * read-only (remote browser in memory mode).\n *\n * The scope faces are minimally re-typed here (the services.ts discipline):\n * the runtime service comes from the user's harness, and type-only imports\n * of the contract package would still be erased — spelling the consumed\n * members keeps the dependency graph honest.\n */\n\nimport type { DefaultFileSort, DefaultGranularity, DefaultPlacement, DefaultToolSort, DefaultTrendMode, SettingsField } from '../shared/types'\n\n// The preference vocabulary is declared once in shared/types.ts; re-exported\n// here so client-side consumers keep their canonical import path.\nexport type { DefaultFileSort, DefaultGranularity, DefaultPlacement, DefaultToolSort, DefaultTrendMode, SettingsField } from '../shared/types'\n\n/** The bound settings scope (ctx.settingsScope.bind result), as consumed. */\nexport interface SettingsScopeLike {\n getSnapshot(): { status: string; value: unknown; writable: boolean }\n subscribe(listener: () => void): () => void\n set(field: string, value: unknown): Promise<void>\n}\n\n/** The ctx.settingsScope binder face, as consumed. */\nexport interface SettingsScopeBinderFace {\n bind(spec: { namespace: string }): SettingsScopeLike\n}\n\n/**\n * The ctx.configForms service face (the Config-form generation's settings\n * transport), as consumed: forms bind per namespace, and `whileServed` keeps\n * a registration alive while the Host serves any of them. The bound form\n * satisfies {@link SettingsScopeLike} (same snapshot/subscribe/set shape).\n */\nexport interface ConfigFormsFace {\n get(namespace: string): SettingsScopeLike\n whileServed(namespaces: readonly string[], register: () => () => void): () => void\n}\n\n/** The preference snapshot the card renders and the view reads at mount. */\nexport interface SettingsState {\n /** Scope sync: loading until the first Host section, unavailable when unserved. */\n status: 'loading' | 'ready' | 'unavailable'\n placement: DefaultPlacement\n granularity: DefaultGranularity\n mode: DefaultTrendMode\n toolSort: DefaultToolSort\n fileSort: DefaultFileSort\n writable: boolean\n}\n\nexport interface ContextSettings {\n /** Observable snapshot store, bound onto card props as `useContextSettings`. */\n store: { subscribe(listener: () => void): () => void; getSnapshot(): SettingsState }\n defaultPlacement(): DefaultPlacement\n defaultGranularity(): DefaultGranularity\n defaultTrendMode(): DefaultTrendMode\n defaultToolSort(): DefaultToolSort\n defaultFileSort(): DefaultFileSort\n attach(scope: SettingsScopeLike): () => void\n /** Persist one preference choice (local echo, then the fenced scope write). */\n set(field: SettingsField, value: string): void\n}\n\ntype Prefs = {\n placement?: DefaultPlacement\n granularity?: DefaultGranularity\n mode?: DefaultTrendMode\n toolSort?: DefaultToolSort\n fileSort?: DefaultFileSort\n}\n\nfunction prefsOf(value: unknown): Prefs {\n if (value === null || typeof value !== 'object') return {}\n const v = value as Record<string, unknown>\n return {\n ...(v.defaultPlacement === 'all' || v.defaultPlacement === 'tab' || v.defaultPlacement === 'sidebar' ? { placement: v.defaultPlacement } : {}),\n ...(v.defaultGranularity === 'step' || v.defaultGranularity === 'turn' ? { granularity: v.defaultGranularity } : {}),\n ...(v.defaultTrendMode === 'total' || v.defaultTrendMode === 'delta' ? { mode: v.defaultTrendMode } : {}),\n ...(v.defaultToolSort === 'size' || v.defaultToolSort === 'count' || v.defaultToolSort === 'name' ? { toolSort: v.defaultToolSort } : {}),\n ...(v.defaultFileSort === 'count' || v.defaultFileSort === 'latest' || v.defaultFileSort === 'path' ? { fileSort: v.defaultFileSort } : {}),\n }\n}\n\nexport function createContextSettings(): ContextSettings {\n let state: SettingsState = { status: 'loading', placement: 'all', granularity: 'turn', mode: 'total', toolSort: 'count', fileSort: 'count', writable: false }\n let scope: SettingsScopeLike | undefined\n const listeners = new Set<() => void>()\n const publish = (next: SettingsState): void => {\n if (next.status === state.status && next.placement === state.placement && next.granularity === state.granularity\n && next.mode === state.mode && next.toolSort === state.toolSort && next.fileSort === state.fileSort\n && next.writable === state.writable) return\n state = next\n for (const listener of listeners) listener()\n }\n // Republish from the bound scope's current snapshot; the attach sync and\n // the failed-write rollback share this one read. Returns the scope's valid\n // placement and insights entry, if it carries them.\n const sync = (bound: SettingsScopeLike): { placement?: DefaultPlacement } => {\n const snap = bound.getSnapshot()\n const prefs = prefsOf(snap.value)\n // Fail open: a config problem must never leave an entry hidden. A valid\n // value wins; one the plugin cannot understand degrades to the field's\n // default; a section without the field (older Host half) keeps the\n // current state.\n const raw = snap.value !== null && typeof snap.value === 'object'\n ? snap.value as Record<string, unknown>\n : undefined\n publish({\n status: snap.status === 'ready' || snap.status === 'unavailable' ? snap.status : 'loading',\n placement: prefs.placement ?? (raw?.defaultPlacement === undefined ? state.placement : 'all'),\n granularity: prefs.granularity ?? state.granularity,\n mode: prefs.mode ?? state.mode,\n toolSort: prefs.toolSort ?? state.toolSort,\n fileSort: prefs.fileSort ?? state.fileSort,\n writable: snap.writable,\n })\n return { placement: prefs.placement }\n }\n return {\n store: {\n subscribe(listener) {\n listeners.add(listener)\n return () => { listeners.delete(listener) }\n },\n getSnapshot: () => state,\n },\n defaultPlacement: () => state.placement,\n defaultGranularity: () => state.granularity,\n defaultTrendMode: () => state.mode,\n defaultToolSort: () => state.toolSort,\n defaultFileSort: () => state.fileSort,\n attach(bound) {\n scope = bound\n sync(bound)\n return bound.subscribe(() => { sync(bound) })\n },\n set(field, value) {\n publish({ ...state, ...prefsOf({ [field]: value }) })\n // The scope write settles asynchronously and its promise REJECTS on a\n // transport failure (dsh keeps only its internal queue tail fulfilled)\n // — never let it float unhandled. Roll the optimistic echo back to the\n // scope's truth; a refused (non-2xx) write needs nothing here, the\n // scope's own recovery re-reads the Host and republishes via subscribe.\n const bound = scope\n if (bound === undefined) return\n void bound.set(field, value).catch(() => {\n const truth = sync(bound)\n // A visibility gate that failed to persist must not keep an entry\n // hidden on an unpersisted echo: with no valid value in the scope's\n // truth, degrade each gate to its default.\n if (field === 'defaultPlacement' && truth.placement === undefined) {\n publish({ ...state, placement: 'all' })\n }\n })\n },\n }\n}\n","/**\n * Step brief — the semantic identity of one history bar (\"what this step was\n * about\"), derived CLIENT-SIDE from the timeline's served nodes; no host or\n * wire additions. A request record's seq IS its response's surface seq (the\n * fold logs both on the same assistant/message event), so:\n *\n * response node = the node at exactly req.seq\n * step inputs = nodes with (previous bar's seq) < seq < req.seq\n * turn opener = the newest user message before this turn's first bar\n *\n * Coverage degrades silently: steps older than the nodes/archive retention\n * window simply yield no rows.\n */\n\nimport type { ContextTimeline, RequestRecord, SurfaceNode } from '../shared/types'\n\nexport interface StepBrief {\n /** The user message that opened this turn (absent when outside retention). */\n opener?: SurfaceNode\n /** Nodes that entered the context since the previous bar (mid-turn steps only). */\n inputs: SurfaceNode[]\n /** This bar's own response node. */\n response?: SurfaceNode\n}\n\n/** Every served node (live tail + removed archive copies), seq-sorted. */\nexport function briefNodes(data: ContextTimeline): SurfaceNode[] {\n return [...data.nodes, ...data.archive].sort((a, b) => a.seq - b.seq)\n}\n\n/** First index whose node seq is >= `seq` (lower bound over the sorted list). */\nfunction lowerBound(nodes: SurfaceNode[], seq: number): number {\n let lo = 0\n let hi = nodes.length\n while (lo < hi) {\n const mid = (lo + hi) >> 1\n if (nodes[mid].seq < seq) lo = mid + 1\n else hi = mid\n }\n return lo\n}\n\n/**\n * Derive the brief for `requests[idx]` (the DISPLAY list — step records or\n * turn aggregates; a turn aggregate is always a turn start, so its inputs row\n * stays hidden and the opener/response carry the narrative).\n */\nexport function briefOf(nodes: SurfaceNode[], requests: RequestRecord[], idx: number): StepBrief | null {\n if (idx < 0 || idx >= requests.length) return null\n const req = requests[idx]\n const ri = lowerBound(nodes, req.seq)\n const hit = ri < nodes.length && nodes[ri].seq === req.seq ? nodes[ri] : undefined\n const response = hit !== undefined && hit.cat === 'assistant' ? hit : undefined\n\n const turnStart = idx === 0 || (requests[idx - 1].turn ?? 0) !== (req.turn ?? 0)\n\n // Opener: the newest user message in (previous turn's last bar seq, this\n // turn's first bar seq) — user messages only land at turn starts.\n let firstIdx = idx\n while (firstIdx > 0 && (requests[firstIdx - 1].turn ?? 0) === (req.turn ?? 0)) firstIdx--\n const upper = requests[firstIdx].seq\n const lower = firstIdx > 0 ? requests[firstIdx - 1].seq : -1\n let opener: SurfaceNode | undefined\n for (let i = lowerBound(nodes, upper) - 1; i >= 0; i--) {\n const n = nodes[i]\n if (n.seq <= lower) break\n if (n.cat === 'user') { opener = n; break }\n }\n\n const inputs: SurfaceNode[] = []\n if (!turnStart) {\n // idx > 0 here (a first bar is always a turn start): collect everything that landed since the previous bar.\n const prevSeq = requests[idx - 1].seq\n for (let i = lowerBound(nodes, prevSeq + 1); i < nodes.length && nodes[i].seq < req.seq; i++) {\n inputs.push(nodes[i])\n }\n }\n return { opener, inputs, response }\n}\n","/**\n * 「这条子会话是不是**在这个面板里**开的」—— 我们自己的一本台账(`docs/10` **M5-12**)。\n *\n * 为什么必须自己记,而不是从平台读:\n * 官方 `subagentCatalog` 投影的条目里**只有** `childId` / `childCreatedAt` / `version` /\n * `mode` / `label` —— **没有来源字段**(2026-10-07 安装树实测,`docs/01` **F59**)。\n * 所以\"本项目发起 / 来自 Agent Teams\"这件事,平台侧答不出来。\n *\n * 三种**诚实**态(界面按这三态说话,不许含糊):\n * ① 台账里有这条 ⟹ **本项目发起**,并写明走的是\"官方成员\"还是\"裸子会话\"(那是我们真知道的,\n * 因为 `child.start` 的返回里就带着 `via`);\n * ② 台账里没有这条 ⟹ **不是在这儿开的**(**不猜**是谁开的:可能是官方团队自己的工具、\n * 也可能是别的会话 —— 我们不去读官方名册,那块界面已按用户裁定撤下);\n * ③ 台账**读不出来** ⟹ **来源未知**并**大声**报错(`redline/origin-corrupt` /\n * `redline/origin-schema`),绝不假装成\"没有记录\"(那会把②说成一个我们没证据的结论)。\n *\n * 只写我们自己的数据目录;**不写任何会话**(`AGENTS.md` §1)。\n */\n\nimport { REDLINE_ERROR } from './redline-errors'\nimport { stableKeyOf } from './redline-drafts'\n\n/** 这条子会话是走哪条路开的(`child.start` 的返回里那个 `via`)。 */\nexport type OriginVia = 'official-member' | 'bare-child'\n\n/** 一条台账记录。`childId` 对官方成员就是 `TeamMemberView.id`(类型是 `SessionId`)。 */\nexport interface OriginRecord {\n readonly childId: string\n readonly via: OriginVia\n readonly at: number\n}\n\n/** 台账文件形状(带自己的 schemaVersion,串档/旧版要认得出)。 */\nexport interface OriginFile {\n readonly schemaVersion: number\n readonly sessionId: string\n readonly records: readonly OriginRecord[]\n}\n\n/** 台账文件的 schema 版本。 */\nexport const ORIGIN_LEDGER_SCHEMA_VERSION = 1\n\n/** 一本台账最多留多少条(老的先丢;子会话数量远小于这个数)。 */\nexport const ORIGIN_LEDGER_CAP = 200\n\n/** 一条会话的台账文件名(与草稿同一套命名:可读前缀 + 稳定短哈希)。 */\nexport function originsFileName(sessionId: string): string {\n const readable = sessionId.replace(/[^A-Za-z0-9_-]/g, '_').slice(0, 40)\n return `redline-origins-${readable}-${stableKeyOf(sessionId)}.json`\n}\n\n/** 解析结果:`ok:false` 一定带一个**稳定错误码**,界面就按它说人话。 */\nexport type OriginParseResult =\n | { readonly ok: true; readonly records: readonly OriginRecord[] }\n | { readonly ok: false; readonly code: string; readonly message: string }\n\nconst VIA_VALUES: readonly string[] = ['official-member', 'bare-child']\n\nfunction recordOf(raw: unknown): OriginRecord | null {\n if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return null\n const row = raw as Record<string, unknown>\n const childId = row.childId\n const via = row.via\n if (typeof childId !== 'string' || childId === '') return null\n if (typeof via !== 'string' || !VIA_VALUES.includes(via)) return null\n const at = typeof row.at === 'number' && Number.isFinite(row.at) ? row.at : 0\n return { childId, via: via as OriginVia, at }\n}\n\n/**\n * 缺文件 = 空台账(我们确实没在这条会话里开过子会话);\n * 文件在但读不出来 = **大声拒绝**(不许把③说成②)。\n *\n * @param raw - 文件内容(`null` = 文件不存在)。\n * @param expectedSessionId - 给了就校验串档(台账上写的会话必须就是这条)。\n */\nexport function parseOrigins(raw: string | null | undefined, expectedSessionId?: string): OriginParseResult {\n if (raw === null || raw === undefined || raw.trim() === '') return { ok: true, records: [] }\n let parsed: unknown\n try {\n parsed = JSON.parse(raw)\n } catch {\n return { ok: false, code: REDLINE_ERROR.originCorrupt, message: 'the origin ledger is not valid JSON' }\n }\n if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {\n return { ok: false, code: REDLINE_ERROR.originCorrupt, message: 'the origin ledger is not an object' }\n }\n const file = parsed as Record<string, unknown>\n if (file.schemaVersion !== ORIGIN_LEDGER_SCHEMA_VERSION) {\n return { ok: false, code: REDLINE_ERROR.originSchema, message: 'the origin ledger has an unsupported schema version' }\n }\n if (typeof file.sessionId !== 'string' || file.sessionId === '') {\n return { ok: false, code: REDLINE_ERROR.originCorrupt, message: 'the origin ledger has no session id' }\n }\n if (expectedSessionId !== undefined && file.sessionId !== expectedSessionId) {\n return { ok: false, code: REDLINE_ERROR.originCorrupt, message: 'the origin ledger belongs to another session' }\n }\n if (!Array.isArray(file.records)) {\n return { ok: false, code: REDLINE_ERROR.originCorrupt, message: 'the origin ledger has no records array' }\n }\n const records: OriginRecord[] = []\n for (const entry of file.records) {\n const record = recordOf(entry)\n // 坏条目**丢**(不是整份拒绝):一条垃圾不该让整本台账变成\"来源未知\"。\n if (record !== null && !records.some(one => one.childId === record.childId)) records.push(record)\n }\n return { ok: true, records }\n}\n\n/** 写盘用的确定性序列化(新的在前)。 */\nexport function serializeOrigins(sessionId: string, records: readonly OriginRecord[]): string {\n const file: OriginFile = { schemaVersion: ORIGIN_LEDGER_SCHEMA_VERSION, sessionId, records }\n return `${JSON.stringify(file, null, 2)}\\n`\n}\n\n/** 记一条(按 `childId` 幂等:同一条子会话只留最新那次),超出上限丢最老的。 */\nexport function putOrigin(records: readonly OriginRecord[], record: OriginRecord): OriginRecord[] {\n const next = [record, ...records.filter(one => one.childId !== record.childId)]\n return next.length > ORIGIN_LEDGER_CAP ? next.slice(0, ORIGIN_LEDGER_CAP) : next\n}\n\n/** 这条子会话是不是在这儿开的;是就顺带说清走的是哪条路。 */\nexport function viaOf(records: readonly OriginRecord[], childId: string): OriginVia | null {\n return records.find(one => one.childId === childId)?.via ?? null\n}\n","/**\n * 「这台机器允许多少个团队成员」—— `docs/10` **M5-13** 标题里那个分母的来源。\n *\n * 为什么这里不是一句常量(三件事决定的):\n *\n * ① **分母不是库默认值**:官方 `maxMembers` 的**库默认是 16**,而本机由\n * `…/@deepseek-ai/dsh-experimental-agent-team-profile/cordis.patch.yml` 配成 **8**\n * (`docs/01` **F31** 实测)⟹ 写死任何一个数都会在另一种部署上变成假话;\n * ② **读它是一次\"可能读不到\"的动作**:服务可能没启用(团队未装配)、字段可能改名\n * (TS 的 `private readonly config` 在运行时只是普通属性 `this.config`,**不是** JS `#private`,\n * 所以能读,但没有任何契约保证它一直在)⟹ **读不到就必须说\"不知道\"**,\n * 界面那时只写 `活跃 N`,**绝不编一个分母**;\n * ③ 通道来的值进渲染前要 **re-prove 形状**(`docs/11` D54 的教训:喂错形状曾把面板渲染炸掉)。\n *\n * 两边都用它:宿主用它读活服务({@link capacityFromService}),客户端用它验通道回答\n * ({@link capacityOf})—— 一个口径只有一处实现。\n */\n\n/** 上限的两种状态:知道(`max` 是正整数)或不知道(`max` 为 null)。 */\nexport interface ChildCapacity {\n readonly known: boolean\n readonly max: number | null\n}\n\n/** 唯一的\"不知道\"取值(冻结:调用方不许就地改它)。 */\nexport const UNKNOWN_CAPACITY: ChildCapacity = Object.freeze({ known: false, max: null })\n\n/** 只接受**正整数**:0 / 负数 / 小数 / `NaN` / 字符串一律算\"读不到\"。 */\nfunction positiveIntOf(value: unknown): number | null {\n return typeof value === 'number' && Number.isInteger(value) && value > 0 ? value : null\n}\n\n/**\n * 从**活服务对象**上防御性读 `config.maxMembers`。\n *\n * @param service - `ctx.get('agentTeams')` 拿到的那个对象(可能是 `undefined`)。\n * @returns 读到正规正整数就是 `{known:true,max}`,其余一律 {@link UNKNOWN_CAPACITY}。\n */\nexport function capacityFromService(service: unknown): ChildCapacity {\n if (service === null || typeof service !== 'object') return UNKNOWN_CAPACITY\n const config = (service as { config?: unknown }).config\n if (config === null || typeof config !== 'object') return UNKNOWN_CAPACITY\n const max = positiveIntOf((config as { maxMembers?: unknown }).maxMembers)\n return max === null ? UNKNOWN_CAPACITY : { known: true, max }\n}\n\n/**\n * Re-prove 一个从通道读来的值(`child.capacity` 的回答)。\n *\n * @param raw - 通道回答里的 `value`,形状不可信。\n * @returns 形状对得上才是那个上限,否则 {@link UNKNOWN_CAPACITY}。\n */\nexport function capacityOf(raw: unknown): ChildCapacity {\n if (raw === null || typeof raw !== 'object') return UNKNOWN_CAPACITY\n const value = raw as { known?: unknown; max?: unknown }\n if (value.known !== true) return UNKNOWN_CAPACITY\n const max = positiveIntOf(value.max)\n return max === null ? UNKNOWN_CAPACITY : { known: true, max }\n}\n","/**\n * The child-session half of the panel: the parent's **index of children**\n * (`subagentCatalog`) plus the two calls that open a new one (`child.plan` →\n * `child.start`).\n *\n * Three things this module deliberately does NOT do, all from `docs/03` R5.1.1:\n *\n * 1. **It does not draw a conversation.** The index lists identity + state and\n * nothing else; the full view is the official UI's job (the runtime's own\n * subagent package owns the tree picker in the parent header). R5.1.1 spells\n * out why: copying a tree/dialog view would fight the official surface and\n * drag a consistency problem we do not need.\n * 2. **It does not offer a jump.** The current demo only states the child's\n * state (\"open it = the panel switches to its context\"); the actual jump is\n * a later stage (`docs/10` M5-06 / M7-02).\n * 3. **It never guesses a state.** A child's \"running / idle / not in this\n * process\" is read from the SAME `turnState` op the editor uses — one\n * read-only call per child — so the row's sentence matches what pressing\n * `编辑` there would actually do. Unknown stays unknown (`null`), and the\n * row says so instead of claiming 空闲.\n */\n\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react'\nimport { planChild, readCapacity, readCarrierModels, readCarriers, readOrigins, readTurnState, startChild, type CarrierModelOption, type ChildPlan, type ChildStarted, type RedlineResult } from './redlineChannel'\nimport { viaOf, type OriginRecord, type OriginVia } from '../shared/redline-origins'\nimport { REDLINE_ERROR as ERR } from '../shared/redline-errors'\nimport { UNKNOWN_CAPACITY, capacityOf, type ChildCapacity } from '../shared/redline-capacity'\n\n/** One row of the index. */\nexport interface ChildRow {\n readonly id: string\n /** The tail of the id, the way the official surface shows it. */\n readonly short: string\n readonly label: string\n /** `one-shot` / `continuable` / `unknown` — straight from the catalog entry. */\n readonly mode: 'one-shot' | 'continuable' | 'unknown'\n readonly createdAt: number\n /** `true` = this process hosts a live agent for it; `null` = not read yet. */\n readonly live: boolean | null\n /** `true` = its turn has not closed yet (writes are refused there too). */\n readonly open: boolean | null\n /** Carrier rows declare their source directly; legacy rows fill this from the old origin ledger. */\n readonly via?: OriginVia | 'ordinary-session' | null\n}\n\ninterface CatalogEntryLike {\n readonly id?: unknown\n readonly label?: unknown\n readonly mode?: unknown\n readonly createdAt?: unknown\n}\n\n/**\n * Parse the `subagentCatalog` projection into rows.\n *\n * Pure and total on purpose: the projection is host data, so a malformed entry\n * must degrade to a row that says `unknown`, never throw inside render.\n *\n * @param raw - the projection value as it arrived (any shape).\n * @returns one row per usable entry, newest first (the fold appends).\n */\nexport function childRowsOf(raw: unknown): ChildRow[] {\n if (!Array.isArray(raw)) return []\n const rows: ChildRow[] = []\n for (const item of raw as unknown[]) {\n if (item === null || typeof item !== 'object') continue\n const entry = item as CatalogEntryLike\n const id = typeof entry.id === 'string' ? entry.id : null\n if (id === null) continue\n const mode = entry.mode === 'one-shot' || entry.mode === 'continuable' || entry.mode === 'unknown' ? entry.mode : 'unknown'\n rows.push({\n id,\n short: id.length > 8 && id.includes('-') ? id.slice(-8) : id,\n label: typeof entry.label === 'string' ? entry.label : '',\n mode,\n createdAt: typeof entry.createdAt === 'number' ? entry.createdAt : 0,\n live: null,\n open: null,\n })\n }\n return rows.reverse()\n}\n\n/** 索引行 + \"在这儿开的吗\"(台账)。 */\nexport interface ChildIndexRow extends ChildRow {\n /** 在这儿开的:走的是官方成员还是裸子会话;`null`/缺省 = 台账里没有这条(不猜是谁开的)。 */\n readonly via?: OriginVia | 'ordinary-session' | null\n}\n\nexport interface ChildController {\n /** The index rows; `live`/`open` fill in as the per-child probes answer. */\n readonly rows: readonly ChildRow[]\n /**\n * 这台机器允许几个团队成员(M5-13 标题里的分母)。**读不到就是\"不知道\"**\n * (`known:false`)⟹ 界面那时只写 `活跃 N`,不编一个分母。\n */\n readonly capacity: ChildCapacity\n /**\n * 我们那本来源台账**读得出来吗**(M5-12)。`false` = 读不出来 ⟹ 界面必须说\"来源未知\",\n * **不许**说成\"不是在这儿开的\"(那是把一个我们没证据的结论说成事实)。\n */\n readonly originsKnown: boolean\n /**\n * 台账**为什么**读不出来(错误码);\\`null\\` = 没有这件事。\n * 界面要把它说出来 —— 只说\"来源未知\"等于把原因吞掉(`docs/11` D54 的教训)。\n */\n readonly originsError: string | null\n /** Live selectable models; reading them never changes this or the source session. */\n readonly models: readonly CarrierModelOption[]\n /** Open the confirm box: the host builds exact default bytes/config for this task. */\n readonly plan: (humanTask: string) => Promise<RedlineResult<ChildPlan>>\n /** The only call in this whole panel that writes a session (`docs/11` D15). */\n readonly start: (\n humanTask: string,\n confirmationToken: string,\n finalText?: string,\n config?: { provider: string; model: string; reasoningEffort?: string },\n ) => Promise<RedlineResult<ChildStarted>>\n}\n\n/**\n * Probe one row's state through the same read-only op the editor's gate uses.\n *\n * @param sessionId - the child's own session id.\n * @returns `live`/`open`, or `null`s when the read failed (never a guess).\n */\nexport function carrierModelsOf(raw: unknown): CarrierModelOption[] {\n if (!Array.isArray(raw)) return []\n const models: CarrierModelOption[] = []\n for (const item of raw) {\n if (item === null || typeof item !== 'object' || Array.isArray(item)) continue\n const model = item as Record<string, unknown>\n if (typeof model.provider !== 'string' || model.provider === '' || typeof model.providerName !== 'string'\n || typeof model.model !== 'string' || model.model === '' || typeof model.modelName !== 'string'\n || !Array.isArray(model.efforts)) continue\n const efforts: { id: string; name: string }[] = []\n for (const rawEffort of model.efforts) {\n if (rawEffort === null || typeof rawEffort !== 'object' || Array.isArray(rawEffort)) continue\n const effort = rawEffort as Record<string, unknown>\n if (typeof effort.id === 'string' && effort.id !== '' && typeof effort.name === 'string') {\n efforts.push({ id: effort.id, name: effort.name })\n }\n }\n models.push({\n provider: model.provider,\n providerName: model.providerName,\n model: model.model,\n modelName: model.modelName,\n efforts,\n ...(typeof model.defaultEffort === 'string' ? { defaultEffort: model.defaultEffort } : {}),\n })\n }\n return models\n}\n\nasync function probeChild(sessionId: string): Promise<{ live: boolean; open: boolean } | null> {\n const state = await readTurnState(sessionId)\n if (!state.ok) return null\n return { live: state.value.known, open: state.value.open }\n}\n\n/**\n * Wire the index + the two child calls for one session.\n *\n * @param sessionId - the session the panel is showing (the would-be parent).\n * @param catalog - the raw `subagentCatalog` projection value.\n */\nexport function useChildSessions(\n sessionId: string | undefined,\n catalog: unknown,\n): ChildController {\n const legacy = useMemo(() => childRowsOf(catalog), [catalog])\n const [carriers, setCarriers] = useState<ChildIndexRow[]>([])\n const carrierGeneration = useRef(0)\n const refreshCarriers = useCallback(async (): Promise<void> => {\n carrierGeneration.current += 1\n const mine = carrierGeneration.current\n setCarriers([])\n if (sessionId === undefined || sessionId === '') return\n const answer = await readCarriers(sessionId)\n if (carrierGeneration.current !== mine || !answer.ok) return\n const payload: unknown = answer.value\n const rows = payload !== null && typeof payload === 'object' && Array.isArray((payload as { rows?: unknown }).rows)\n ? (payload as { rows: { id?: unknown; label?: unknown; mode?: unknown; createdAt?: unknown; via?: unknown }[] }).rows\n : []\n setCarriers(rows.flatMap((row) => {\n if (typeof row.id !== 'string' || row.id === '') return []\n return [{\n id: row.id,\n short: row.id.length > 8 ? row.id.slice(-8) : row.id,\n label: typeof row.label === 'string' ? row.label : '',\n mode: 'continuable' as const,\n createdAt: typeof row.createdAt === 'number' ? row.createdAt : 0,\n via: 'ordinary-session' as const,\n live: null,\n open: null,\n }]\n }))\n }, [sessionId])\n useEffect(() => { void refreshCarriers() }, [refreshCarriers])\n const base = useMemo(() => {\n const carrierIds = new Set(carriers.map(row => row.id))\n return [...carriers, ...legacy.filter(row => !carrierIds.has(row.id))]\n }, [carriers, legacy])\n const [states, setStates] = useState<Record<string, { live: boolean; open: boolean }>>({})\n const generation = useRef(0)\n\n useEffect(() => {\n generation.current += 1\n const mine = generation.current\n setStates({})\n if (base.length === 0) return\n // A handful of read-only calls; a child that answers after the panel moved on\n // must not write into the new session's index (same guard as the draft hook).\n void (async () => {\n const entries = await Promise.all(base.map(async row => [row.id, await probeChild(row.id)] as const))\n if (generation.current !== mine) return\n const next: Record<string, { live: boolean; open: boolean }> = {}\n for (const [id, state] of entries) if (state !== null) next[id] = state\n setStates(next)\n })()\n }, [base])\n\n // 来源台账:跟着会话取一次;`known:false` 的初值意味着\"在回答到达之前不冒充知道\"。\n // 与上面的索引探测同一个惯用法:用\"第几代\"而不是 `let cancelled`(后者会被\n // `no-unnecessary-condition` 判成恒假 —— 规则看不见闭包里的赋值)。\n interface OriginsState { known: boolean; records: readonly OriginRecord[]; error: string | null }\n const EMPTY_ORIGINS: OriginsState = { known: false, records: [], error: null }\n const [origins, setOrigins] = useState<OriginsState>(EMPTY_ORIGINS)\n const originsGeneration = useRef(0)\n useEffect(() => {\n originsGeneration.current += 1\n const mine = originsGeneration.current\n setOrigins(EMPTY_ORIGINS)\n if (sessionId === undefined || sessionId === '') return\n void (async () => {\n const answer = await readOrigins(sessionId)\n if (originsGeneration.current !== mine) return\n // ⚠️ 用**宿主回答里的错误码**,别硬套 transport 那句 ——\n // 旧宿主没有这个 op 时答的是 \\`redline/unknown-op\\`,对应的人话是\"刷新页面再试\",\n // 而 transport 那句是\"保存没有送到宿主\",用在这里是**误导**。\n if (!answer.ok) { setOrigins({ known: false, records: [], error: answer.code === '' ? ERR.transport : answer.code }); return }\n setOrigins(answer.value.records === null\n ? { known: false, records: [], error: answer.value.error ?? ERR.originCorrupt }\n : { known: true, records: answer.value.records, error: null })\n })()\n }, [sessionId])\n\n const rows = useMemo(\n () => base.map(row => ({\n ...row,\n ...(states[row.id] ?? { live: null, open: null }),\n via: row.via === 'ordinary-session' ? row.via : viaOf(origins.records, row.id),\n })),\n [base, states, origins],\n )\n\n // 分母只问一次(与选哪个会话无关:它是这台机器的配置,不是某条日志的性质)。\n // 回答的形状不可信 ⟹ 先 `capacityOf()` re-prove 再进渲染(`docs/11` D54 的教训)。\n const [capacity, setCapacity] = useState<ChildCapacity>(UNKNOWN_CAPACITY)\n // 与上面那个索引探测同一个惯用法:用\"第几代\"而不是 `let alive`\n // (`let alive` 会被 `no-unnecessary-condition` 判成恒假 —— 那是规则对闭包赋值看不见,\n // 但**改成代次计数器既绕开它、又和本文件既有写法一致**)。\n const capGeneration = useRef(0)\n useEffect(() => {\n capGeneration.current += 1\n const mine = capGeneration.current\n void (async () => {\n const answer = await readCapacity()\n if (capGeneration.current !== mine || !answer.ok) return\n setCapacity(capacityOf(answer.value))\n })()\n }, [])\n\n const [models, setModels] = useState<readonly CarrierModelOption[]>([])\n useEffect(() => {\n void (async () => {\n const answer = await readCarrierModels()\n if (!answer.ok) return\n setModels(carrierModelsOf((answer.value as { models?: unknown }).models))\n })()\n }, [])\n\n const plan = useCallback(async (humanTask: string): Promise<RedlineResult<ChildPlan>> => {\n if (sessionId === undefined || sessionId === '') {\n return { ok: false, code: 'redline/not-live', message: 'no session' }\n }\n return await planChild(sessionId, humanTask)\n }, [sessionId])\n\n const start = useCallback(async (\n humanTask: string,\n confirmationToken: string,\n finalText?: string,\n config?: { provider: string; model: string; reasoningEffort?: string },\n ): Promise<RedlineResult<ChildStarted>> => {\n if (sessionId === undefined || sessionId === '') {\n return { ok: false, code: 'redline/not-live', message: 'no session' }\n }\n const answer = await startChild(sessionId, humanTask, confirmationToken, finalText, config)\n if (answer.ok) await refreshCarriers()\n return answer\n }, [refreshCarriers, sessionId])\n\n return useMemo(\n () => ({ rows, capacity, originsKnown: origins.known, originsError: origins.error, models, plan, start }),\n [rows, capacity, origins.known, origins.error, models, plan, start],\n )\n}\n","/**\n * The child-session card: the always-here 「开子会话」 entry, the read-only index of\n * children, and the small confirm box the entry opens.\n *\n * The contract (all of it from `docs/03` R5.1 / R5.1.1 / R5.1.3 and `docs/11` D15):\n *\n * · **Two blocks only** — 开子会话 + 子会话索引. No freeze record, no dispatch, no official\n * task board, no compaction, no interrupt: those are later stages (`docs/11` D10).\n * · **The index never draws a conversation** and offers no jump; it states identity + state and\n * says in words what the state means for editing. The official surface owns the tree and the\n * full view.\n * · **The button is gated exactly like `保存`**: a parent whose turn has not closed, or that is\n * not live in this process, would be refused by the host (`redline/turn-open` /\n * `redline/not-live`) — so it is disabled here first and says why, rather than letting the\n * click fail.\n * · **The confirm box is the host's own five items** (`child.plan`), and the first message is\n * written by the human only: the plugin never invents a word (`docs/11` D15, hard constraint).\n * An empty task makes the plan itself refuse; the confirm button is then disabled. The refusal stays\n * observable (`data-redline-refusal` on the task block), but its sentence is NOT printed any more —\n * the user asked to drop it (2026-10-08).\n */\n\nimport { createElement as h, useCallback, useEffect, useLayoutEffect, useRef, useState, type ChangeEvent, type CSSProperties, type ReactElement } from 'react'\nimport { createPortal } from 'react-dom'\nimport type { ViewKit } from '../viewkit'\nimport type { ChildIndexRow, ChildRow } from '../childSessions'\nimport type { ChildCapacity } from '../../shared/redline-capacity'\nimport type { CarrierModelOption, ChildPlan, ChildStarted, RedlineResult } from '../redlineChannel'\n\nexport interface ChildCardProps {\n /** The parent session the panel is showing. */\n readonly sessionId?: string\n /** The index, already probed (`childSessions.ts`). */\n readonly rows: readonly ChildIndexRow[]\n /** 我们那本来源台账读得出来吗(缺省按\"读得出来\"处理,独立渲染时行为可预期)。 */\n readonly originsKnown?: boolean\n /** 读不出来时的**原因**(错误码);界面要把它说成人话,不许只写\"来源未知\"。 */\n readonly originsError?: string | null\n /** 这台机器允许几个团队成员(M5-13 的分母);缺省 = 不知道。 */\n readonly capacity?: ChildCapacity\n /** Live model catalog; choosing one only configures the new carrier. */\n readonly models?: readonly CarrierModelOption[]\n /** The parent is live in this process (`turnState.known`). */\n readonly live: boolean\n /** The parent's turn has not closed yet. */\n readonly turnOpen: boolean\n /** How many local edits the confirm box will carry (0 → the sentence says \"no edits\"). */\n readonly carriedCount: number\n /** `child.plan` — read-only, builds the five items for this exact task text. */\n readonly plan: (humanTask: string) => Promise<RedlineResult<ChildPlan>>\n /** `child.start` — the ONLY session write the panel can perform. */\n readonly start: (\n humanTask: string,\n confirmationToken: string,\n finalText?: string,\n config?: { provider: string; model: string; reasoningEffort?: string },\n ) => Promise<RedlineResult<ChildStarted>>\n}\n\ninterface CarrierSelectionBarProps {\n readonly models: readonly CarrierModelOption[]\n readonly selectedRoute: string\n readonly selectedEffort: string\n readonly onRoute: (route: string) => void\n readonly onEffort: (effort: string) => void\n readonly t: ViewKit['t']\n}\n\nfunction CarrierSelectionBar(props: CarrierSelectionBarProps): ReactElement {\n const [open, setOpen] = useState<'model' | 'effort' | null>(null)\n const modelRef = useRef<HTMLButtonElement | null>(null)\n const effortRef = useRef<HTMLButtonElement | null>(null)\n const menuRef = useRef<HTMLDivElement | null>(null)\n const [menuStyle, setMenuStyle] = useState<CSSProperties>({ visibility: 'hidden' })\n const selected = props.models.find(model => JSON.stringify([model.provider, model.model]) === props.selectedRoute)\n const effortLabel = props.selectedEffort === ''\n ? props.t('child.confirm.effortDefault')\n : selected?.efforts.find(level => level.id === props.selectedEffort)?.name ?? props.selectedEffort\n\n useLayoutEffect(() => {\n if (open === null) return\n const trigger = open === 'model' ? modelRef.current : effortRef.current\n if (trigger === null) return\n const rect = trigger.getBoundingClientRect()\n const width = Math.min(Math.max(open === 'model' ? 300 : 220, rect.width), window.innerWidth - 32)\n const left = Math.min(Math.max(16, rect.left), window.innerWidth - width - 16)\n setMenuStyle({ left, width, bottom: window.innerHeight - rect.top + 6, maxHeight: Math.max(120, rect.top - 22) })\n }, [open])\n\n useEffect(() => {\n if (open === null) return\n const dismiss = (event: MouseEvent): void => {\n const node = event.target\n if (!(node instanceof Node) || menuRef.current?.contains(node) === true\n || modelRef.current?.contains(node) === true || effortRef.current?.contains(node) === true) return\n setOpen(null)\n }\n const escape = (event: KeyboardEvent): void => { if (event.key === 'Escape') setOpen(null) }\n document.addEventListener('mousedown', dismiss)\n document.addEventListener('keydown', escape)\n return () => {\n document.removeEventListener('mousedown', dismiss)\n document.removeEventListener('keydown', escape)\n }\n }, [open])\n\n const toggle = (pane: 'model' | 'effort'): void => { setOpen(current => current === pane ? null : pane) }\n const groups = new Map<string, { name: string; models: CarrierModelOption[] }>()\n for (const model of props.models) {\n const group = groups.get(model.provider) ?? { name: model.providerName, models: [] }\n group.models.push(model)\n groups.set(model.provider, group)\n }\n const menu = open === null ? null : createPortal(h('div', {\n ref: menuRef,\n className: 'redline-picker-menu scrollable',\n style: menuStyle,\n role: 'menu',\n 'data-redline-picker-menu': open,\n }, open === 'model'\n ? [...groups.entries()].map(([provider, group]) => h('section', { key: provider, className: 'redline-picker-group' },\n h('div', { className: 'redline-picker-group-label' }, group.name),\n group.models.map((model) => {\n const route = JSON.stringify([model.provider, model.model])\n const active = route === props.selectedRoute\n return h('button', {\n type: 'button', role: 'menuitemradio', 'aria-checked': active,\n className: 'redline-picker-option' + (active ? ' is-selected' : ''),\n key: route,\n onClick: () => { props.onRoute(route); setOpen(null) },\n }, h('span', null, model.modelName), h('span', { className: 'redline-picker-check' }, active ? '✓' : ''))\n })))\n : h('div', null,\n [{ id: '', name: props.t('child.confirm.effortDefault') }, ...(selected?.efforts ?? [])].map((level) => {\n const active = level.id === props.selectedEffort\n return h('button', {\n type: 'button', role: 'menuitemradio', 'aria-checked': active,\n className: 'redline-picker-option' + (active ? ' is-selected' : ''),\n key: level.id || 'default',\n onClick: () => { props.onEffort(level.id); setOpen(null) },\n }, h('span', null, level.name), h('span', { className: 'redline-picker-check' }, active ? '✓' : ''))\n }))), document.body)\n\n return h('div', { className: 'redline-picker-bar', 'data-redline-picker': '1' },\n h('button', {\n ref: modelRef, type: 'button', className: 'redline-picker-trigger',\n 'data-redline-model': '1', 'aria-haspopup': 'menu', 'aria-expanded': open === 'model',\n onClick: () => { toggle('model') },\n }, h('span', { className: 'redline-picker-value' }, selected?.modelName ?? props.t('child.confirm.modelLabel')),\n h('span', { className: 'redline-picker-chevron' + (open === 'model' ? ' redline-picker-chevron-open' : '') }, '⌄')),\n h('span', { className: 'redline-picker-divider' }),\n h('button', {\n ref: effortRef, type: 'button', className: 'redline-picker-trigger',\n 'data-redline-effort': '1', 'aria-haspopup': 'menu', 'aria-expanded': open === 'effort',\n disabled: selected === undefined,\n onClick: () => { toggle('effort') },\n }, h('span', { className: 'redline-picker-value redline-picker-effort-value' }, effortLabel),\n h('span', { className: 'redline-picker-chevron' + (open === 'effort' ? ' redline-picker-chevron-open' : '') }, '⌄')),\n menu,\n )\n}\n\n/** The state dot + word a row shows, from the probed `turnState`. */\nfunction stateOf(row: ChildRow): { tone: string; key: string; hint: string } {\n if (row.live === null) return { tone: 'unknown', key: 'child.state.unknown', hint: 'child.hint.unknown' }\n if (!row.live) return row.via === 'ordinary-session'\n ? { tone: 'gone', key: 'child.state.unloaded', hint: 'child.hint.unloaded' }\n : { tone: 'gone', key: 'child.state.gone', hint: 'child.hint.gone' }\n if (row.open === true) return { tone: 'run', key: 'child.state.running', hint: 'child.hint.running' }\n return row.via === 'ordinary-session'\n ? { tone: 'idle', key: 'child.state.idle', hint: 'child.hint.carrierIdle' }\n : { tone: 'idle', key: 'child.state.idle', hint: 'child.hint.idle' }\n}\n\n/** `HH:MM` for a `createdAt` timestamp; an unreadable stamp shows nothing. */\nfunction clockOf(createdAt: number): string | null {\n if (!Number.isFinite(createdAt) || createdAt <= 0) return null\n const date = new Date(createdAt)\n const pad = (n: number): string => String(n).padStart(2, '0')\n return `${pad(date.getHours())}:${pad(date.getMinutes())}`\n}\n\nexport function makeChildCard(kit: ViewKit): (props: ChildCardProps) => ReactElement {\n const { t } = kit\n\n return function ChildCard(props): ReactElement {\n const [open, setOpen] = useState(false)\n const [task, setTask] = useState('')\n const [plan, setPlan] = useState<ChildPlan | null>(null)\n const [finalText, setFinalText] = useState('')\n const [selectedRoute, setSelectedRoute] = useState('')\n const [selectedEffort, setSelectedEffort] = useState('')\n const [busy, setBusy] = useState(false)\n const [error, setError] = useState<{ code: string; message: string } | null>(null)\n // Late plan/start answers for an older task or selected session must not overwrite the new view.\n const generation = useRef(0)\n const startGeneration = useRef(0)\n\n const blockedKey = !props.live\n ? 'redline.blocked.notLive'\n : props.turnOpen ? 'redline.blocked.turnOpen' : null\n\n const close = useCallback(() => {\n setOpen(false)\n setPlan(null)\n setError(null)\n }, [])\n\n useEffect(() => {\n generation.current += 1\n startGeneration.current += 1\n setOpen(false)\n setTask('')\n setPlan(null)\n setFinalText('')\n setSelectedRoute('')\n setSelectedEffort('')\n setBusy(false)\n setError(null)\n }, [props.sessionId])\n\n // The confirm box's five items come from the host and depend on the task text\n // (item 3 IS that text, and the refusal fires on an empty one), so refetch on change —\n // debounced, because every keystroke would otherwise be a round trip.\n useEffect(() => {\n if (!open) return\n generation.current += 1\n const mine = generation.current\n const timer = setTimeout(() => {\n void (async () => {\n const answer = await props.plan(task)\n if (generation.current !== mine) return\n if (!answer.ok) { setError({ code: answer.code, message: answer.message }); setPlan(null); return }\n setError(null)\n setPlan(answer.value)\n setFinalText(answer.value.prompt ?? '')\n const config = answer.value.config\n setSelectedRoute(config === undefined ? '' : JSON.stringify([config.provider, config.model]))\n // Start from the selected model's own default; never carry an explicit source effort by accident.\n setSelectedEffort('')\n })()\n }, 220)\n return () => { clearTimeout(timer) }\n }, [open, task, props.plan])\n\n const catalog = props.models ?? []\n const currentConfig = plan?.config\n const hasCurrent = currentConfig !== undefined && catalog.some(model =>\n model.provider === currentConfig.provider && model.model === currentConfig.model)\n const availableModels = currentConfig !== undefined && !hasCurrent\n ? [{\n provider: currentConfig.provider, providerName: currentConfig.provider,\n model: currentConfig.model, modelName: currentConfig.model, efforts: [],\n }, ...catalog]\n : catalog\n const selectedModel = availableModels.find(model => JSON.stringify([model.provider, model.model]) === selectedRoute)\n const legacyPlan = plan !== null && plan.config === undefined\n const finalBytes = new TextEncoder().encode(finalText).byteLength\n const refused = plan !== null && (plan.refusal !== null || finalText.trim() === '' || (!legacyPlan && selectedModel === undefined))\n const confirm = useCallback(() => {\n if (busy || plan === null || refused) return\n setBusy(true)\n setError(null)\n startGeneration.current += 1\n const mine = startGeneration.current\n void (async () => {\n if (!legacyPlan && selectedModel === undefined) return\n const selectedConfig = selectedModel === undefined ? undefined : {\n provider: selectedModel.provider,\n model: selectedModel.model,\n ...(selectedEffort === '' ? {} : { reasoningEffort: selectedEffort }),\n }\n const answer = legacyPlan\n ? await props.start(task, plan.draftRevision)\n : await props.start(task, plan.draftRevision, finalText, selectedConfig)\n if (startGeneration.current !== mine) return\n setBusy(false)\n if (!answer.ok) { setError({ code: answer.code, message: answer.message }); return }\n // The child is visible in the card's live index; do not replace the\n // confirmation with a second success screen that hides that outcome.\n close()\n })()\n }, [busy, close, finalText, legacyPlan, plan, refused, selectedEffort, selectedModel, props.start, task])\n\n // ⚠️ 口径跟 demo(`renderOrch()` 的 `state === 'running' || state === 'idle'`):\n // 「活跃」= **在场的子会话**(运行中 + 空闲),**不是**\"只有正在跑的\" ——\n // 2026-10-07 真机读数时发现我们原先少算了一半(只在 `open` 为真时计数)。\n const active = props.rows.filter(row => row.live === true).length\n // Ordinary carrier sessions are root sessions and do not consume Agent Team member capacity.\n const scale = t('child.bmeta', { a: active, n: props.rows.length })\n const errKey = error === null ? null : `redline.err.${error.code.replace('redline/', '')}`\n const errText = error === null ? null : error.code === 'redline/internal' && error.message !== ''\n ? `${t(errKey ?? 'redline.err.internal')}:${error.message}`\n : t(errKey ?? 'redline.err.internal')\n\n return h('div', { className: 'redline-card', 'data-redline-card': 'child' },\n h('div', { className: 'redline-card-title' },\n h('div', { className: 'redline-orch-titles' },\n h('div', { className: 'redline-orch-title-row' },\n h('span', { className: 'redline-card-title-text' }, t('child.title')),\n ),\n ),\n h('div', { className: 'redline-orch-metrics' },\n h('span', { className: 'redline-card-scale redline-orch-metric' }, scale),\n ),\n ),\n\n h('section', { className: 'redline-orch-launch', 'data-redline-block': 'spawn' },\n h('div', { className: 'redline-orch-copy' },\n h('div', { className: 'redline-orch-launch-row' },\n h('h3', { className: 'redline-orch-launch-title' }, t('child.spawn.head')),\n h('span', { className: 'redline-orch-launch-hint' }, t('child.spawn.hint')),\n ),\n h('p', { className: 'redline-orch-launch-note' }, t('child.spawn.note')),\n blockedKey !== null ? h('p', { className: 'redline-orch-launch-note' }, t(blockedKey)) : null,\n ),\n h('button', {\n type: 'button',\n className: 'redline-orch-open',\n 'data-redline-spawn': '1',\n disabled: blockedKey !== null,\n onClick: () => { setTask(''); setOpen(true) },\n }, t('child.spawn.button')),\n ),\n\n h('section', { 'data-redline-block': 'children' },\n h('div', { className: 'redline-orch-listhead' },\n h('span', null, t('child.list.head')),\n h('span', null, t('child.list.hint'))),\n props.originsError === undefined || props.originsError === null\n ? null\n : h('div', { className: 'redline-cap', 'data-redline-origins-error': props.originsError },\n t('redline.err.' + props.originsError.replace('redline/', ''))),\n props.rows.length === 0\n ? h('div', { className: 'redline-orch-empty' }, t('child.empty'))\n : h('div', { className: 'redline-orch-list' }, props.rows.map((row) => {\n const state = stateOf(row)\n const clock = clockOf(row.createdAt)\n return h('div', { className: 'redline-orch-row', key: row.id, 'data-redline-child': row.id },\n h('div', { className: 'redline-orch-main' },\n // 方形图标位(v0 的 `.sessionCardAvatar`):纯装饰,不承载文案。\n h('span', { className: 'redline-orch-avatar', 'aria-hidden': 'true' }, '↗'),\n h('div', { className: 'redline-orch-content' },\n h('div', { className: 'redline-orch-id' },\n h('span', { className: 'redline-snapid' }, row.short),\n h('span', { className: 'redline-chip-soft' }, t('child.mode.' + row.mode)),\n // 来源(M5-12):三态各自一句 —— 台账里有说是哪条路;没有说\"不是在这儿开的\";\n // 台账读不出来说\"来源未知\"。**不猜**(官方目录里没有来源字段,docs/01 F59)。\n (() => {\n const known = row.via === 'ordinary-session' || props.originsKnown !== false\n const tone = !known ? 'unknown' : row.via == null ? 'other' : 'own'\n const key = !known\n ? 'child.src.unknown'\n : row.via === 'ordinary-session' ? 'child.src.own.carrier'\n : row.via === 'official-member' ? 'child.src.own.official'\n : row.via === 'bare-child' ? 'child.src.own.bare' : 'child.src.other'\n return h('span', { className: 'redline-src redline-src-' + tone, 'data-redline-src': tone, title: t('child.src.tip') }, t(key))\n })(),\n clock === null ? null : h('span', { className: 'redline-orch-clock' }, clock),\n ),\n row.label === '' ? null : h('p', { className: 'redline-orch-note' }, row.label),\n h('span', { className: 'redline-orch-subnote' }, t(state.hint)),\n ),\n ),\n // 状态胶囊靠右(v0 的 `.sessionStatus`)。\n h('span', { className: 'redline-badge-state' + (state.tone === 'run' ? ' redline-badge-state-run' : '') },\n h('i', { className: 'redline-mstat redline-mstat-' + state.tone }),\n t(state.key)),\n )\n })),\n ),\n\n open\n ? h('div', {\n className: 'redline-modal-backdrop',\n onMouseDown: (event: { target: unknown; currentTarget: unknown }) => {\n if (event.target === event.currentTarget) close()\n },\n }, h('div', { className: 'redline-modal-card', role: 'dialog', 'aria-modal': 'true', 'data-redline-confirm': '1' },\n // 结构照抄 v0 定稿:固定标题栏 → 只有中间可滚 → 固定底栏。\n h('div', { className: 'redline-modal-head' },\n h('h2', { className: 'redline-modal-title' }, t('child.confirm.title')),\n h('button', { type: 'button', className: 'redline-modal-close', onClick: close }, '×'),\n ),\n h('div', { className: 'redline-confirm-body' },\n h('p', { className: 'redline-confirm-intro' }, t('child.confirm.intro')),\n plan === null\n ? h('div', { className: 'redline-cap' }, t('child.confirm.preparing'))\n : h('div', { className: 'redline-confirm-summary' },\n plan.items.filter(item => item.label !== '新会话配置与回程').map(item => h('div', { key: item.label },\n h('strong', null, item.label + ':'),\n h('span', null, item.text))),\n plan.metrics === null || typeof plan.metrics.bytes !== 'number'\n ? null\n : h('div', { 'data-redline-first-task': String(finalBytes) },\n t('child.confirm.metrics', { bytes: finalBytes, edits: plan.metrics.edits }))),\n // 空任务时宿主会拒绝(`redline/empty-task`):按钮禁用即可,**不再把那句拒绝话术打在弹窗里**\n // (用户 2026-10-08:「子会话的第一句话必须由你自己写……可以去掉」)。\n // 拒绝这件事仍然可观测(`data-redline-refusal` 挂在任务块上),只是不再占版面。\n h('label', {\n className: 'redline-confirm-task',\n ...(plan !== null && plan.refusal !== null ? { 'data-redline-refusal': plan.refusal.code } : {}),\n },\n h('span', { className: 'redline-confirm-task-label' }, t('child.confirm.taskLabel')),\n h('span', { className: 'redline-confirm-task-hint' }, t('child.confirm.taskHint')),\n h('textarea', {\n rows: 3,\n 'data-redline-task': '1',\n placeholder: t('child.confirm.taskPlaceholder'),\n value: task,\n onChange: (event: ChangeEvent<HTMLTextAreaElement>) => {\n generation.current += 1\n setTask(event.target.value)\n setPlan(null)\n setFinalText('')\n setSelectedRoute('')\n setSelectedEffort('')\n setError(null)\n },\n })),\n h(CarrierSelectionBar, {\n models: availableModels,\n selectedRoute,\n selectedEffort,\n t,\n onRoute: (route: string) => {\n setSelectedRoute(route)\n setSelectedEffort('')\n },\n onEffort: (effort: string) => { setSelectedEffort(effort) },\n }),\n h('label', { className: 'redline-confirm-task redline-confirm-final' },\n h('span', { className: 'redline-confirm-task-label' }, t('child.confirm.finalLabel')),\n h('span', { className: 'redline-confirm-task-hint' }, t('child.confirm.finalHint')),\n h('textarea', {\n rows: 6,\n 'data-redline-final': '1',\n value: finalText,\n onChange: (event: ChangeEvent<HTMLTextAreaElement>) => { setFinalText(event.target.value) },\n })),\n errText !== null ? h('div', { className: 'redline-editor-err', role: 'alert' }, errText) : null,\n ),\n h('div', { className: 'redline-modal-foot' },\n h('button', { type: 'button', className: 'redline-confirm-btn redline-confirm-btn-cancel', onClick: close }, t('child.confirm.cancel')),\n h('button', {\n type: 'button',\n className: 'redline-confirm-btn redline-confirm-btn-ok',\n 'data-redline-confirm-ok': '1',\n disabled: busy || plan === null || refused,\n onClick: confirm,\n }, t('child.confirm.ok')),\n ),\n ))\n : null,\n\n )\n }\n}\n","/**\n * Glyphs: inject/model-switch reuse the harness's shared icon set (`@deepseek-ai/dsh-client-ui-primitives`, a platform seed word);\n * compaction/prune keep the ✂ marker — no shared glyph exists for it.\n */\n\nimport { useEffect, useLayoutEffect, useRef, type ReactElement } from 'react'\nimport type { ContextEventRecord } from '../../shared/types'\nimport { IconBranch, IconPlus } from '../primitives'\nimport type { Translate } from '../i18n'\nimport type { DetailState } from '../timelineSource'\nimport type { ViewKit } from '../viewkit'\nimport { makeDetailNote } from './detailNote'\n\nconst EVENT_ICONS: Record<string, string> = { compaction: '✂', prune: '✂', inject: '+', model: '⇄', mode: '⇄' }\n\nexport interface EventListProps {\n events: ContextEventRecord[]\n /**\n * The timeline source's detail state (split generation): with no events to\n * list, `loading`/`failed` replace the empty claim with the pending note /\n * retry button — an un-fetched list is not an empty one.\n */\n state?: DetailState\n onRetry?: () => void\n}\n\nexport function makeEventText(t: Translate): {\n eventLabel: (ev: ContextEventRecord) => string\n eventAt: (ev: ContextEventRecord) => string | null\n} {\n function eventLabel(ev: ContextEventRecord): string {\n if (ev.kind === 'compaction') return t('ev.compaction', { n: ev.count || 0 })\n if (ev.kind === 'prune') return t('ev.prune')\n if (ev.kind === 'model') return t('ev.model', { a: ev.from || '?', b: ev.to || '?' })\n if (ev.kind === 'mode') return t('ev.mode.' + (ev.name || '?'))\n // The kind union narrows to 'inject' here; a future kind breaks the\n // compile (ev.sub ev.form ev.name are inject-only), forcing a label.\n if (ev.sub === 'skill') return t('ev.skill', { name: ev.name || '?' })\n const base = t('form.' + (ev.form || 'context'))\n let label = ev.name ? base + ' · ' + ev.name : base\n if (ev.detail) label += ' · ' + ev.detail\n return label\n }\n\n /**\n * Where this event sits in the timeline: boundary events (compaction/prune) label the GAP they sit in — same-turn 'Turn 2 · Step 3→4',\n * cross-turn 'Turn 50 · Step 8 → Turn 51 · Step 1'; other kinds keep their single point; no turn/step (in flight) → null.\n */\n function eventAt(ev: ContextEventRecord): string | null {\n if (ev.kind === 'compaction' || ev.kind === 'prune') {\n if (typeof ev.turn === 'number' && typeof ev.step === 'number') {\n if (typeof ev.fromTurn === 'number' && typeof ev.fromStep === 'number') {\n if (ev.fromTurn === ev.turn) return t('events.range', { t: ev.turn, a: ev.fromStep, b: ev.step })\n return t('events.rangeTo', { a: ev.fromTurn, as: ev.fromStep, b: ev.turn, bs: ev.step })\n }\n return t('events.at', { t: ev.turn, s: ev.step })\n }\n return null\n }\n if (typeof ev.turn === 'number' && typeof ev.step === 'number') {\n return t('events.at', { t: ev.turn, s: ev.step })\n }\n return null\n }\n\n return { eventLabel, eventAt }\n}\n\n/**\n * Set the native `title` on every label whose text overflows its box (the styled tips cover cards, but a plain\n * ellipsis row still needs the native fallback); reads (scrollWidth/clientWidth) and writes (title) stay separate\n * from layout-affecting work, and callers gate WHEN this runs so it never becomes a per-render forced layout.\n */\nfunction syncTitles(root: HTMLElement): void {\n for (const el of root.querySelectorAll<HTMLElement>('.redline-event-label')) {\n el.title = el.scrollWidth > el.clientWidth ? el.textContent || '' : ''\n }\n}\n\nexport function makeEventList(kit: ViewKit): (props: EventListProps) => ReactElement {\n const { t, fmt, fmtTime, eventLabel, eventAt } = kit\n const DetailNote = makeDetailNote(kit)\n return function EventList(props: EventListProps): ReactElement {\n // Hooks stay unconditional (Rules of Hooks): events going empty ->\n // non-empty in one mounted instance must not grow the hook count — an\n // early return above these hooks is a React #310 class bug (issue #12).\n const rootRef = useRef<HTMLDivElement | null>(null)\n // Truncation titles ride a resize-only listener plus an events-driven resync: the effect MUST NOT run\n // on every render — a plain re-render (hover/select elsewhere in the view) would re-read scrollWidth /\n // clientWidth for every label, one forced synchronous layout per row, and rebind the listener.\n useLayoutEffect(() => {\n const root = rootRef.current\n if (!root) return\n syncTitles(root)\n }, [props.events])\n useEffect(() => {\n const onResize = (): void => {\n const root = rootRef.current\n if (root !== null) syncTitles(root)\n }\n window.addEventListener('resize', onResize)\n return () => { window.removeEventListener('resize', onResize) }\n }, [])\n if (props.events.length === 0) {\n if (props.state === 'loading') return <DetailNote state=\"loading\" />\n if (props.state === 'failed' && props.onRetry !== undefined) {\n return <DetailNote state=\"failed\" onRetry={props.onRetry} />\n }\n return <div className=\"redline-empty\">{t('events.empty')}</div>\n }\n const sorted = props.events.slice().reverse()\n return (\n <div className=\"redline-events\" ref={rootRef}>\n {sorted.map((ev) => {\n const label = eventLabel(ev)\n const at = eventAt(ev)\n const glyph = ev.kind === 'inject' ? <IconPlus />\n : ev.kind === 'model' ? <IconBranch />\n : EVENT_ICONS[ev.kind] || '•'\n // Key on the durable seq alone: the list renders newest-first, so a fresh event lands at index 0\n // and an index-bearing key would shift EVERY existing row's key — a full-list remount on every push.\n // Narrow cards (phone panes): the single-line row would crush the label and push the meta\n // tail into a scrollbar, so the row wraps — the label's near-full-width basis keeps line 1\n // to icon + kind + label, and the meta tail folds onto line 2. The 92px basis reservation\n // covers icon + gap + the widest kind chip (both locales) + gap.\n return (\n <div key={ev.seq} className=\"redline-event @max-[380px]/redline-card:flex-wrap\">\n <span className={'redline-event-icon redline-event-' + ev.kind}>{glyph}</span>\n <span className={'redline-kind redline-kind-' + ev.kind}>{t('kind.' + ev.kind)}</span>\n <span className=\"redline-event-label flex-1 @max-[380px]/redline-card:basis-[calc(100%-92px)]\">{label}</span>\n {at !== null ? <span className=\"redline-event-at\">{at}</span> : null}\n {ev.tokens ? (\n <span className={'redline-event-tokens' + (ev.kind === 'inject' ? ' redline-up' : ' redline-down')}>\n {(ev.kind === 'inject' ? '+' : '−') + fmt(ev.tokens)}\n </span>\n ) : null}\n <span className=\"redline-event-time\">{fmtTime(ev.time)}</span>\n </div>\n )\n })}\n </div>\n )\n }\n}\n","/**\n * The baseline-gate modal: when the host reports the running harness below\n * the supported baseline (the `unsupported` record on the pushed\n * `redlineTimeline` value — see host/fallback.ts), the Context tab keeps\n * rendering its (zeroed) cards and this centered dialog names the detected\n * harness version against the required minimum and urges the upgrade.\n *\n * Dismissal is remembered per session in a module-level ledger: tab remounts\n * do not re-pop it, while a fresh app launch does — the gate stays visible\n * until the harness is actually updated.\n */\n\nimport { useCallback, useState, type ReactElement } from 'react'\nimport type { ViewKit } from '../viewkit'\nimport { useEscapeClose } from './escapeClose'\n\n/** Sessions whose gate the user already dismissed this browser session. */\nconst dismissed = new Set<string>()\n\nexport interface UpgradeGateProps {\n sessionId?: string\n /** The detected harness version (displayed verbatim, already re-proved). */\n current: string\n /** The plugin's minimum supported baseline. */\n minimum: string\n}\n\nexport function makeUpgradeGate(kit: ViewKit): (props: UpgradeGateProps) => ReactElement | null {\n const { t } = kit\n return function UpgradeGate(props: UpgradeGateProps): ReactElement | null {\n const sessionId = typeof props.sessionId === 'string' ? props.sessionId : ''\n // `closedFor` re-renders on dismiss within one mount; the ledger covers\n // remounts and in-place session switches.\n const [closedFor, setClosedFor] = useState<string | null>(null)\n const closed = closedFor === sessionId || dismissed.has(sessionId)\n const close = useCallback(() => {\n dismissed.add(sessionId)\n setClosedFor(sessionId)\n }, [sessionId])\n\n // Same overlay contract as the /redline modal (escapeClose.ts):\n // capture-phase Escape, and focus returns to the pre-open element.\n useEscapeClose(!closed, close)\n\n if (closed) return null\n\n return (\n <div className=\"redline-modal-backdrop\" onClick={close}>\n <div className=\"redline-modal-card redline-gate-card\" onClick={(ev) => { ev.stopPropagation() }}>\n <div className=\"redline-modal-head\">\n <span className=\"redline-modal-title\">{t('gate.title')}</span>\n <button className=\"redline-modal-close hover:text-(--dsw-alias-label-primary) hover:bg-(--dsw-alias-bg-layer-2)\" aria-label={t('cmd.close')} onClick={close}>×</button>\n </div>\n <div className=\"redline-gate-body\">{t('gate.body', { minimum: props.minimum })}</div>\n <div className=\"redline-gate-versions\">\n <span className=\"redline-gate-version\">\n <span className=\"redline-gate-version-label\">{t('gate.current')}</span>\n <span className=\"redline-gate-version-value\">v{props.current}</span>\n </span>\n <span className=\"redline-gate-version\">\n <span className=\"redline-gate-version-label\">{t('gate.minimum')}</span>\n <span className=\"redline-gate-version-value\">\n v{props.minimum}\n <span className=\"redline-gate-or-newer\">{t('gate.orNewer')}</span>\n </span>\n </span>\n </div>\n <div className=\"redline-gate-actions\">\n <button type=\"button\" className=\"redline-gate-ok hover:brightness-110\" onClick={close}>{t('gate.ok')}</button>\n </div>\n </div>\n </div>\n )\n }\n}\n","import { memo, type ComponentType, type MouseEvent, type ReactElement, type ReactNode } from 'react'\nimport type { ContextEventRecord, RequestRecord, SurfaceNode } from '../../shared/types'\nimport { partsOf, CATS } from '../categories'\nimport { cacheHitPercent } from '../format'\nimport type { StepBrief } from '../brief'\nimport { blockSummaryOf, callNamesOf, callSummaryOf } from '../callSummary'\nimport type { ConversationNodeLike } from '../services'\nimport type { StackedBarProps } from './stackedBar'\nimport type { ViewKit } from '../viewkit'\n\nexport interface RequestDetailProps {\n request: RequestRecord | null\n /**\n * Delta mode: the record displayed just before this one (null on the first\n * bar). Its PRESENCE switches the panel from cumulative makeup to the signed\n * change against that previous record — the same pairing the chart's\n * deltaOf plots.\n */\n prev?: RequestRecord | null\n marker?: ContextEventRecord | null\n /** The step's semantic identity (turn opener / inputs / reply) — see brief.ts; null renders an empty reserved lane. */\n brief?: StepBrief | null\n /** Conversation-snapshot join for call-argument enrichment; absent join = names only, never an error. */\n convOf?: (seq: number) => ConversationNodeLike | undefined\n /**\n * Per-turn step totals (the parent's `turnStepsOf` over the served requests) behind the head's\n * step-of-total figure; absent = a 1-step turn.\n */\n stepsOf?: (turn: number | undefined) => number\n /** Reveal a brief row's node in the Context browser; absent = rows render inert. */\n onLocate?: (node: SurfaceNode, isResponse: boolean) => void\n /**\n * Mirrored category hover (shared with the overview/browser): lights the composition bar's matching\n * segment; the bar never reports hovers back.\n */\n hoverKey?: string | null\n}\n\nexport function makeRequestDetail(\n kit: ViewKit,\n StackedBar: (props: StackedBarProps) => ReactElement,\n): ComponentType<RequestDetailProps> {\n const { t, fmt, fmtTime, catLabel, eventLabel, eventAt } = kit\n\n /**\n * One brief row: a fixed-width kind tag plus one glanceable line. The tag carries a styled, instant explanation bubble (the\n * shared `.redline-tip` chrome); the content span keeps the native title (preview + locate hint), so the two never stack.\n * Clickable when the browser linkage is wired AND the row carries a node (the always-present In row's empty state stays inert).\n */\n function BriefRow(props: {\n tag: string\n tagTip: string\n /** Absent only on the empty-state In row — a row without a node cannot be located. */\n node?: SurfaceNode\n isResponse: boolean\n onLocate?: (node: SurfaceNode, isResponse: boolean) => void\n children: ReactNode\n }): ReactElement {\n const inner = (\n <>\n <span className=\"redline-brief-tag group/tip\">\n {props.tag}\n <span className=\"redline-tip redline-brief-tip group-hover/tip:opacity-100\" role=\"tooltip\">{props.tagTip}</span>\n </span>\n {props.children}\n </>\n )\n if (props.node === undefined || props.onLocate === undefined) return <div className=\"redline-brief-row\">{inner}</div>\n const node = props.node\n const onLocate = props.onLocate\n const locate = (): void => { onLocate(node, props.isResponse) }\n return (\n <button type=\"button\" className=\"redline-brief-row redline-brief-row-link hover:bg-(--dsw-alias-interactive-bg-hover)\" onClick={locate}>\n {inner}\n </button>\n )\n }\n\n /**\n * One line's anatomy — a compact FACT tag plus the preview text, mirroring the Context browser's element rows so a\n * brief line reads exactly like the browser row its click reveals: tool results tag the tool name, skill content\n * the skill name, assistant replies the call breadcrumb, injections the form, user messages image attachments.\n * The branches cover the Category union; a hostile cat degrades into the\n * user tail — a plain text row, never a throw.\n */\n function chipParts(n: SurfaceNode, conv: ConversationNodeLike | undefined): { tag: string | null; text: string } {\n if (n.cat === 'tool') {\n const summary = callSummaryOf(conv)\n if (n.tool !== undefined) return { tag: n.tool, text: summary ?? '' }\n return { tag: null, text: summary ?? t('node.toolResult') }\n }\n if (n.cat === 'skill') {\n // Skill content (issue #66): a load/invocation tags its NAME, the\n // catalog digest its form label ('目录更新'). A text-less row (the\n // `skill`-tool load — its content rode the tool result) previews the\n // call summary, like the tool rows do.\n return {\n tag: n.skill !== undefined ? t('node.skillTag', { name: n.skill }) : t('form.' + (n.form ?? 'context')),\n text: n.text ?? callSummaryOf(conv) ?? '',\n }\n }\n if (n.cat === 'assistant') {\n // The fold's surface node keeps `calls` only for TEXT-LESS replies; a reply carrying both text and calls recovers\n // its call breadcrumb through the conversation join.\n const names = n.calls !== undefined && n.calls.length > 0 ? n.calls : callNamesOf(conv)\n const own = n.text !== undefined && n.text !== '' ? n.text : blockSummaryOf(conv) ?? ''\n return {\n tag: names.length > 0 ? names.join(' › ') : null,\n text: own !== '' ? own : (names.length > 0 ? '' : t('node.empty')),\n }\n }\n if (n.cat === 'inject') {\n const text = n.text !== undefined && n.text !== ''\n ? (n.form === 'snapshot' ? t('node.snapshot') + n.text : n.text)\n : ''\n return { tag: t('form.' + (n.form ?? 'context')), text }\n }\n // The user tail (or a hostile cat): image uploads gain an Image chip.\n const imgs = n.imgs ?? 0\n return {\n tag: imgs > 0 ? t('attach.image') + (imgs > 1 ? ' ×' + String(imgs) : '') : null,\n text: n.text ?? '',\n }\n }\n\n /** The native-title line for a fact+text pair: 'tag · text', degrading to whichever half exists. */\n function factTitle(tag: string | null, text: string): string {\n return tag !== null ? (text !== '' ? tag + ' · ' + text : tag) : text\n }\n\n /**\n * The brief's container ALWAYS renders — a fixed three-row lane (`.redline-brief`'s min-height) so scrubbing the chart never\n * changes the panel's height; unknown or empty steps just leave parts of the lane blank instead of collapsing it.\n */\n function BriefSection(props: {\n brief: StepBrief | null | undefined\n convOf?: (seq: number) => ConversationNodeLike | undefined\n onLocate?: (node: SurfaceNode, isResponse: boolean) => void\n }): ReactElement {\n const { opener, inputs, response } = props.brief ?? { inputs: [] }\n const convOf = props.convOf ?? (() => undefined)\n // The content span's native title: full preview, plus the locate hint when the row is clickable.\n const hint = props.onLocate !== undefined ? ' — ' + t('brief.locate') : ''\n // Chip click: locate THIS chip's node; stopPropagation keeps it from also firing the row's own locate.\n const locateChip = props.onLocate === undefined ? undefined : (n: SurfaceNode) =>\n (e?: MouseEvent) => { e?.stopPropagation(); props.onLocate?.(n, false) }\n const MAX_CHIPS = 3\n /**\n * The ONE content unit of the brief — inputs and the reply share the same chip anatomy (error dot, fact tag,\n * preview text). Input chips are compact and individually clickable (each locates its own node); the reply is a\n * single chip grown to the row's width, left inert because the row button already locates it.\n */\n const nodeChip = (n: SurfaceNode, onClick?: (e?: MouseEvent) => void, grow = false): ReactElement => {\n const { tag, text } = chipParts(n, convOf(n.seq))\n return (\n <span\n key={n.seq}\n className={'redline-brief-chip' + (grow ? ' redline-brief-chip-grow' : '') + (onClick !== undefined ? ' redline-brief-chip-link hover:bg-(--dsw-alias-interactive-bg-hover)' : '')}\n title={factTitle(tag, text) + hint}\n onClick={onClick}\n >\n {n.err === true ? <span className=\"redline-br-err-dot\" /> : null}\n {tag !== null ? <span className=\"redline-brief-chip-tag\">{tag}</span> : null}\n {text !== '' ? <span className=\"redline-brief-chip-text\">{text}</span> : null}\n </span>\n )\n }\n const openerParts = opener !== undefined ? chipParts(opener, convOf(opener.seq)) : null\n return (\n <div className=\"redline-brief\">\n {opener !== undefined && openerParts !== null ? (\n <BriefRow tag={t('brief.turn')} tagTip={t('brief.turnTip')} node={opener} isResponse={false} onLocate={props.onLocate}>\n {openerParts.tag !== null ? <span className=\"redline-brief-fact\">{openerParts.tag}</span> : null}\n {openerParts.text !== '' ? (\n <span className=\"redline-brief-text\" title={factTitle(openerParts.tag, openerParts.text) + hint}>{openerParts.text}</span>\n ) : null}\n </BriefRow>\n ) : null}\n {/* The In row ALWAYS renders (empty state included): a turn's opening step has no inputs, and a constant row\n count keeps the panel height steady while the chart scrubs. Without a node the row renders inert. */}\n <BriefRow tag={t('brief.input')} tagTip={t('brief.inputTip')} node={inputs[0]} isResponse={false} onLocate={props.onLocate}>\n {inputs.length > 0 ? (\n <>\n {/* Whole-row clickable like the other rows (locates the FIRST input); each chip still locates its own node —\n stopPropagation keeps a chip click from also firing the row's. */}\n {inputs.slice(0, MAX_CHIPS).map(n => nodeChip(n, locateChip?.(n)))}\n {inputs.length > MAX_CHIPS ? <span className=\"redline-brief-more\">{t('brief.more', { n: inputs.length - MAX_CHIPS })}</span> : null}\n </>\n ) : (\n <span className=\"redline-brief-empty\">{t('brief.noInputs')}</span>\n )}\n </BriefRow>\n {response !== undefined ? (\n <BriefRow tag={t('brief.reply')} tagTip={t('brief.replyTip')} node={response} isResponse onLocate={props.onLocate}>\n {nodeChip(response, undefined, true)}\n </BriefRow>\n ) : null}\n </div>\n )\n }\n\n // Memoized at the factory level: the parent hands reference-stable request/prev/marker/brief/convOf/onLocate\n // across hover/select renders (see contextView), so the panel skips reconciliation when the active bar did not move.\n return memo(function RequestDetail(props: RequestDetailProps): ReactElement | null {\n const req = props.request\n if (!req) return null\n const isTurn = req.stepCount !== undefined && req.stepCount > 1\n const head = isTurn\n ? t('detail.turn', {\n t: req.turn ?? 0,\n /* v8 ignore next -- isTurn already guarantees stepCount !== undefined;\n the fallback is defensive. */\n n: req.stepCount ?? 0,\n })\n : t('detail.step', { t: req.turn ?? 0, s: req.step ?? 0, n: props.stepsOf?.(req.turn) ?? 1 })\n // When this bar carries a boundary event (compaction/prune), the header\n // also shows WHERE the event happened: the gap between the request\n // before and the request after (e.g. \"✂ Turn 49 · Step 2→3\").\n const marker = props.marker ?? null\n const markerAt = marker !== null ? eventAt(marker) : null\n // Delta mode: per-category SIGNED change vs the previous record (the chart stacks them diverging\n // above/below its zero line); provider usage chips drop out — prompt/output/cacheRead are\n // per-request figures, not deltas.\n const delta = props.prev !== undefined\n const prev = props.prev ?? null\n const deltas = CATS.map(c => delta ? (req[c.key] || 0) - (prev !== null ? prev[c.key] || 0 : 0) : 0)\n let net = 0\n let maxAbs = 0\n if (delta) {\n for (const d of deltas) {\n net += d\n if (Math.abs(d) > maxAbs) maxAbs = Math.abs(d)\n }\n }\n const parts = delta\n ? CATS.map((c, i) => ({ key: c.key, color: c.color, value: Math.abs(deltas[i]) }))\n : partsOf(req)\n return (\n <div className=\"redline-detail\">\n <div className=\"redline-detail-head\">\n <b>{head}</b>\n {marker !== null && markerAt !== null\n ? <span className=\"redline-detail-marker\" title={eventLabel(marker)}>{'✂ ' + markerAt}</span>\n : null}\n {isTurn ? <span className=\"redline-detail-tag\">{t('detail.lastStep')}</span> : null}\n {delta ? <span className=\"redline-detail-tag\">{t('gran.delta')}</span> : null}\n <span className=\"redline-detail-time\">{fmtTime(req.time)}</span>\n {/* Metric chips: one neutral pill per provider figure; the cache figure drops out on hosts\n that do not fold `cacheRead` (and on usage-less requests). */}\n {delta ? (\n <span className={'redline-detail-metric' + (net > 0 ? ' redline-detail-metric-up' : net < 0 ? ' redline-detail-metric-down' : '')}>\n {t('tip.delta', { n: (net > 0 ? '+' : '') + fmt(net) })}\n </span>\n ) : null}\n {!delta && req.prompt !== undefined\n ? <span className=\"redline-detail-metric\">{t('detail.actual', { n: fmt(req.prompt) })}</span>\n : null}\n {!delta && req.output !== undefined\n ? <span className=\"redline-detail-metric\">{t('detail.output', { n: fmt(req.output) })}</span>\n : null}\n {!delta && req.prompt !== undefined && req.cacheRead !== undefined\n ? <span className=\"redline-detail-metric\">{t('detail.cache', { n: cacheHitPercent(req.cacheRead, req.prompt) ?? '—' })}</span>\n : null}\n </div>\n <BriefSection brief={props.brief} convOf={props.convOf} onLocate={props.onLocate} />\n {/* Mirrors the shared category hover with the tip off — a cross-card hover must not float a second tooltip\n over a bar the pointer does not rest on (same rule as the browser's own bar). */}\n <StackedBar parts={parts} height={10} hoverKey={props.hoverKey} tip={false} />\n <div className=\"redline-detail-rows\">\n {CATS.map((c, i) => {\n const v = delta ? deltas[i] : req[c.key] || 0\n const mag = Math.abs(v)\n return (\n <div key={c.key} className={'redline-detail-row' + (props.hoverKey === c.key ? ' redline-detail-row-on' : '')}>\n <i style={{ background: c.color }} />\n <span className=\"redline-detail-label\">{catLabel(c.key)}</span>\n <span className=\"redline-bar-track\">\n {delta ? (\n <>\n {/* Mini diverging bar echoing the chart: zero at the middle, growth fills right,\n shrinkage fills left, one shared scale across the rows. */}\n <span className=\"redline-bar-zero\" />\n {v !== 0 ? (\n <span\n className={'redline-bar-fill ' + (v > 0 ? 'redline-bar-fill-up' : 'redline-bar-fill-down')}\n style={{ width: `${mag / maxAbs * 50}%`, background: c.color }}\n />\n ) : null}\n </>\n ) : (\n <span className=\"redline-bar-fill\" style={{ width: `${req.total > 0 ? v / req.total * 100 : 0}%`, background: c.color }} />\n )}\n </span>\n {delta ? (\n <span className={'redline-detail-num' + (v > 0 ? ' redline-detail-num-up' : v < 0 ? ' redline-detail-num-down' : '')}>\n {(v > 0 ? '+' : '') + fmt(v)}\n </span>\n ) : (\n <span className=\"redline-detail-num\">{'≈' + fmt(v)}</span>\n )}\n <span className=\"redline-detail-pct\">{!delta && req.total > 0 ? `${Math.round(v / req.total * 100)}%` : ''}</span>\n </div>\n )\n })}\n </div>\n </div>\n )\n })\n}\n","/**\n * The Context card: what the session's context IS and how it evolved — a\n * seven-cell grid of the session's shape (turns / steps / human inputs /\n * live tool calls), the whole-session cache-hit rate, and the cost estimate\n * at two scopes: the family total (the current agent plus every subagent\n * session) and the subagents' own share.\n * Count figures only: nothing here is part of a spendable whole, so no pie —\n * proportions live in the composition card, and the context-event tallies\n * live on the events card's kind filters (contextView.tsx). The cache-hit\n * cell reads the official `tokenUsage` projection — the same source and\n * formula as the harness chat stats line under the composer, shown with one\n * decimal — and dashes until a provider reports usage. The cost cells price\n * the host-folded cumulative billed totals (complete session logs, never\n * trimmed; the subagents' usage folds out of the session-list snapshot,\n * `makeSubagentCost` below) from the models.dev price book (modelPrices.ts)\n * in the locale's currency; their hover bubbles (a '?' marker + styled DOM\n * tip) explain each scope and list the per-1M-token rates of the models the\n * family actually billed, straight from the same book (cost.ts), so printed\n * rates can never drift from the math. A book that has not loaded (or\n * failed) dashes the cells and notes the outage.\n *\n * The counts arrive precomputed: the split-generation wire head carries them\n * (shared/types.ts `TimelineCounts` — computed over the retained records),\n * and the caller derives them from the collections on the inline generation\n * (`countsOfRecords`). The card itself never touches the collections.\n */\n\nimport type { ReactElement } from 'react'\nimport type { ContextEventRecord, RequestRecord, TimelineCounts } from '../../shared/types'\nimport { type StepStats } from '../assemble'\nimport type { ViewKit } from '../viewkit'\n\n\n/**\n * The inline generation's counter derivation — the exact tally the card ran\n * over the served collections before the split (distinct turn values, record\n * count, per-kind event tallies). The host's split-generation counts match\n * it by construction (fold.ts buildTimelineHead).\n */\nexport function countsOfRecords(requests: readonly RequestRecord[], events: readonly ContextEventRecord[]): TimelineCounts {\n const turns = new Set<number>()\n for (const req of requests) turns.add(req.turn ?? 0)\n let injects = 0\n let compactions = 0\n let prunes = 0\n for (const ev of events) {\n if (ev.kind === 'inject') injects++\n else if (ev.kind === 'compaction') compactions++\n else if (ev.kind === 'prune') prunes++\n }\n return { turns: turns.size, steps: requests.length, injects, compactions, prunes }\n}\n\n/**\n * 上下文统计卡 —— **3 格,跟 demo**(`docs/10` M4-07:用户 2026-10-06 裁定)。\n *\n * 卡片上只有 demo 确认过的那三格 + 标题里的当前视图与 `本步可见 N 条 · ≈X tokens`:\n * ① 模型可见条目(另 N 条被遮蔽)② 用户消息 ③ 注入内容。\n * 三个数字的口径由 `stepStatsOf()`(`src/client/assemble.ts`,纯函数 + 单测)从\n * **`assemble()` 已经算好的那一步列表**里直接数出来 —— 卡片不做任何二次判断。\n *\n * ⚠️ 与基线(上游 `dsh-context`)的**有意差异**:不再有 `轮次 / 步数 / 工具调用 / 缓存命中 / 费用 / 子 Agent 费用`\n * 六格读数。会话指认改由趋势卡标题 `按轮次(共 N 轮)` + 浏览器 meta `第 t 轮 · 第 s 步` 承担(`docs/10` M4-03);\n * 费用与缓存属于\"上下文洞察\"那套能力,不是本产品(批改台)的目标。\n * 费用/价格模块(`cost.ts` / `modelPrices.ts` / 本文件的 `makeSubagentCost`)**保留未删**,只是本卡不再引用。\n */\nexport function makeStatsContext(\n kit: ViewKit,\n): (props: {\n /** 该步的读数(`stepStatsOf` 的结果)。 */\n stats: StepStats\n /** 当前视图的轮次与步(live 时是最后一步)。 */\n turn?: number\n step?: number\n /** 正在看\"当前(下一次请求)\"而不是某条历史记录。 */\n live: boolean\n /**\n * 该步的列表数据到了没有(`timelineSource` 的 `detailState === 'ready'`)。\n * 没到就显示 `—`:三个数字都来自**该步的节点列表**,那是 detail 通道的产物,\n * 而 slim head 里只有 token 合计、没有条目数 —— 假装成 0 会等于在骗人。\n */\n ready: boolean\n}) => ReactElement {\n const { t, fmt } = kit\n return function StatsContext(props: {\n stats: StepStats\n turn?: number\n step?: number\n live: boolean\n ready: boolean\n }): ReactElement {\n const cell = (label: string, value: string | number): ReactElement => (\n <div className=\"redline-stat\">\n <span className=\"redline-stat-value\">{value}</span>\n <span className=\"redline-stat-label\">{label}</span>\n </div>\n )\n const { stats, ready } = props\n // 被遮蔽的条数只在真的有时才写出来(与 demo 的条件一致)。\n const shadowNote = ready && stats.shadowed > 0 ? t('stats.shadowedNote', { n: fmt(stats.shadowed) }) : ''\n const value = (n: number): string => (ready ? fmt(n) : '—')\n return (\n <div className=\"redline-card redline-col-stats\">\n <div className=\"redline-card-title\">\n <span className=\"redline-card-title-text\">{t('stats.title')}</span>\n <span className=\"redline-stat-hint\">\n {t('stats.viewHint', { t: props.turn ?? 0, s: props.step ?? 0 }) + (props.live ? t('stats.viewLive') : '')}\n </span>\n {ready\n ? <span className=\"redline-bmeta\">{t('stats.bmeta', { n: fmt(stats.listed), k: fmt(stats.tokens) })}</span>\n : null}\n {ready && stats.missingTokens > 0\n // S1.1:缺 token 时不许把 `≈N` 说成完整数字(那一格显示不了 `—`,就把缺的条数说出来)。\n ? <span className=\"redline-stat-hint\" data-redline-missing-tokens={String(stats.missingTokens)}>{t('stats.missing', { m: fmt(stats.missingTokens) })}</span>\n : null}\n </div>\n <div className=\"redline-stats\">\n {cell(t('stats.visibleItems') + shadowNote, value(stats.visible))}\n {cell(t('stats.userMsgs'), value(stats.user))}\n {cell(t('stats.injectItems'), value(stats.inject))}\n </div>\n </div>\n )\n }\n}\n","/**\n * The right Sidebar's Context tab (dsh 0.1.5-rc.1+).\n *\n * The tab reuses the Context conversation-view component VERBATIM: the\n * `sidebar.right.pane.tab` seat is session-scoped and delivers the same\n * framework standard kit (`sessionId`, `useProjection`, `useChat`, the locale\n * `t` seat) the `conversation.view` seat does, so the panel and the tab are\n * one component with one data path. The tab type contributes a guide entry, so\n * the sidebar's guide page offers \"Context\" and picking it opens the panel —\n * the product's own path, exactly as the shipped Files type does: a capsule of\n * glyph, title, and description line, plus the chip-title seat that puts the\n * same glyph beside the label once the tab is open (`icon.tsx`).\n *\n * OPTIONAL BY CONTRACT. `ctx.sidebarRightTabs` and the seat ship only on the\n * 0.1.5 line (0.1.5-rc.1+ supported); the registration therefore rides a\n * DEFERRED inject (the plugin's hard injects stay `slots` + `locale`), so on\n * every older supported line the callback never fires, the plugin fiber never\n * pends, and nothing is registered. The registry is re-proved structurally and\n * the whole registration is guarded: a foreign or hostile registry (a throwing\n * `register`, a taken id/kind) leaves the sidebar without the tab instead of\n * taking the browser down.\n *\n * @module dsh-context-redline/client/sidebar\n */\n\nimport { ContextIcon, makeContextTabTitle } from './icon'\nimport type { ClientCtx, ContextViewProps, SidebarTabsFace } from './services'\nimport type { Translate } from './i18n'\n\n/** The tab type's identity in the sidebar's tab system (also its body-seat key). */\nexport const SIDEBAR_CONTEXT_ID = 'dsh-context-redline'\n\n/**\n * The kind `openTab` names. Namespaced rather than the bare `context`: the\n * registry THROWS when a kind collides with another registration in a\n * non-coexisting band, and a foreign plugin may well own `context`.\n */\nexport const SIDEBAR_CONTEXT_KIND = 'dsh-context-redline'\n\n/** The guide capsule's position: after the shipped Files entry (order 10). */\nconst GUIDE_ORDER = 20\n\n/**\n * Register the Context tab type, its body, and its chip title on the right\n * Sidebar, if — and only if — this harness serves the sidebar tab registry.\n * @param ctx - client root context carrying `slots` and the locale service.\n * @param view - the Context view component factory result (the same one the\n * conversation tab mounts).\n * @param t - the plugin-namespace translate; the label thunks read the active\n * locale at call time, so a language switch relabels the guide entry.\n * @param ns - the plugin's locale namespace, put on the body registration so\n * the framework synthesizes the `t` seat for the panel too.\n * @returns the deferred inject's disposer (placement toggling calls it to\n * take the mount down; a no-op on faces that return no handle).\n */\nexport function watchSidebarContextTab(\n ctx: ClientCtx,\n view: (props: ContextViewProps) => unknown,\n t: Translate,\n ns: string,\n): () => void {\n // Deferred: a harness without the right Sidebar never fires this, and the\n // plugin is simply a conversation tab there — no pending fiber, no error.\n const fiber = ctx.inject(['sidebarRightTabs'], (raw) => {\n const injected = raw as unknown as ClientCtx & { sidebarRightTabs?: SidebarTabsFace }\n // Every registration that already landed, so a partial failure below\n // unwinds exactly what this callback owns.\n const disposers: (() => void)[] = []\n const own = (result: unknown): void => {\n if (typeof result === 'function') disposers.push(result as () => void)\n }\n try {\n const tabs = injected.sidebarRightTabs\n if (tabs === undefined || typeof tabs.register !== 'function') return\n own(tabs.register({\n id: SIDEBAR_CONTEXT_ID,\n kind: SIDEBAR_CONTEXT_KIND,\n title: () => t('tab'),\n guide: [{\n order: GUIDE_ORDER,\n title: () => t('tab'),\n description: () => t('sidebar.guideDescription'),\n icon: ContextIcon,\n }],\n }))\n own(injected.slots.inject('sidebar.right.pane.tab', () => injected.slots.register(\n { name: 'sidebar.right.pane.tab', key: SIDEBAR_CONTEXT_ID, locale: ns },\n (props: { sessionId?: string } & Record<string, unknown>) => view({ ...props, host: 'sidebar' }),\n )))\n // The chip title seat (0.1.5-rc.1+): the emblem beside the label, the\n // files type's own idiom. Registered under the type id so the kit\n // dispatches it for this type's tabs only.\n own(injected.slots.inject('sidebar.right.pane.tab.title', () => injected.slots.register(\n { name: 'sidebar.right.pane.tab.title', key: SIDEBAR_CONTEXT_ID },\n makeContextTabTitle(t),\n )))\n } catch {\n // A foreign registry that throws on register leaves the sidebar without\n // this tab; the conversation tab and every other seat keep working.\n for (const dispose of disposers) dispose()\n return undefined\n }\n // The inject callback's own disposer owns every registration: cordis\n // unloads them with the injected fiber (plugin stop, HMR reload).\n return () => {\n for (const dispose of disposers) dispose()\n }\n })\n // The cordis inject handle disposes the callback's fiber; re-proved at\n // runtime because a harness face may return no handle at all.\n const handle = fiber as { dispose?: () => unknown } | undefined\n return () => { void handle?.dispose?.() }\n}\n","/**\n * Chat → Context jump relay. The assistant-message action records the clicked\n * reply's request seq here and opens the Context view — the right Sidebar's\n * tab when this harness serves one, else the conversation tab; the view\n * consumes the one-shot focus once its projection data is in. Module-level\n * per-session map — the same life pattern as the modal open-state stores.\n */\n\nimport { asRecord, type ClientCtx } from './services'\nimport { SIDEBAR_CONTEXT_KIND } from './sidebar'\n\nconst pendingFocus = new Map<string, number>()\n\n/** The mounted Context views re-pinning on later records (repeat jumps). */\nconst focusListeners = new Set<() => void>()\n\n/**\n * Record the Context step (request seq) to reveal for `sessionId` — replaces\n * any unconsumed request and wakes the mounted views.\n */\nexport function requestContextFocus(sessionId: string, seq: number): void {\n pendingFocus.set(sessionId, seq)\n for (const listener of focusListeners) listener()\n}\n\n/**\n * Wake on every record while subscribed: a Context view that is already\n * mounted (the sidebar landing keeps it mounted across jumps) re-pins when a\n * record lands — the listener takes its OWN session's entry, so other\n * sessions' records leave their entries pending for their views.\n */\nexport function subscribeContextFocus(listener: () => void): () => void {\n focusListeners.add(listener)\n return () => { focusListeners.delete(listener) }\n}\n\n/** Take the pending focus request, if any — one-shot, the map entry is consumed. */\nexport function takeContextFocus(sessionId: string): number | null {\n const seq = pendingFocus.get(sessionId)\n if (seq === undefined) return null\n pendingFocus.delete(sessionId)\n return seq\n}\n\n/**\n * Open the Context tab on the right Sidebar over `ctx.sidebarRight.openTab`\n * (the column expands in the same step). OPTIONAL seam, re-proved at call\n * time: a harness without the service (every line older than 0.1.5-rc.1), a\n * placement that registered no tab type, no mounted session surface, or a\n * hostile face all report false so the caller keeps its conversation-tab\n * fallback.\n */\nexport function openContextSidebar(ctx: ClientCtx): boolean {\n try {\n const face = asRecord(ctx.get('sidebarRight'))\n if (face === null || typeof face.openTab !== 'function') return false\n ;(face.openTab as (kind: string) => void).call(face, SIDEBAR_CONTEXT_KIND)\n return true\n } catch {\n return false\n }\n}\n\n/**\n * Activate the Context tab by clicking its own tab-bar button (the semantic\n * `button[role=\"tab\"]` chrome the conversation shell renders for every view).\n * The harness hands `openView` only to the ACTIVE view entry, so a nested\n * chat action cannot call it — this rides the same button a user click would.\n * Already-active is a no-op that still reports success; no matching tab (any\n * dsh layout without the tab bar) reports failure and nothing happens.\n */\nexport function activateContextTab(label: string): boolean {\n const tabs = document.querySelectorAll<HTMLButtonElement>('button[role=\"tab\"]')\n for (const tab of tabs) {\n if (tab.textContent.trim() !== label) continue\n if (tab.getAttribute('aria-selected') !== 'true') tab.click()\n return true\n }\n return false\n}\n","/**\n * 我们的面板\"现在真的可见吗\"—— 决定那两条**改宿主元素**的 CSS 规则能不能生效\n * (`base.css` 里用 `[data-redline-active=\"1\"]` 限定;Code Review P1-2)。\n *\n * 为什么不能只看\"挂载了\":宿主今天\"切走即卸载\",所以 `.redline-root` 存在≈我们的\n * tab 被选中;但若宿主改成\"常驻只隐藏\",`.redline-root` 会在别的 tab(包括上游\n * 插件的 tab)里继续存在,那两条规则就会把**宿主的输入框/宽度拖柄**藏掉。\n * IntersectionObserver 给的是真实的可见性,正好对上这个判据。\n *\n * 退化:没有 `IntersectionObserver`(jsdom、老引擎)时按\"挂载即活跃\"处理 ——\n * 保住既有行为,不让功能因为缺一个观察器而消失。\n */\n\nimport { useEffect, type RefObject } from 'react'\n\n/** 我们自己控制的标记属性;CSS 侧只认它。 */\nexport const REDLINE_ACTIVE_ATTR = 'data-redline-active'\n\n/** 按元素真实可见性维护 `data-redline-active`(卸载时清掉)。 */\nexport function useSurfaceVisibility(ref: RefObject<Element | null>): void {\n useEffect(() => {\n const element = ref.current\n if (element === null) return\n const set = (on: boolean): void => {\n if (on) element.setAttribute(REDLINE_ACTIVE_ATTR, '1')\n else element.removeAttribute(REDLINE_ACTIVE_ATTR)\n }\n if (typeof IntersectionObserver === 'undefined') {\n set(true)\n return () => { set(false) }\n }\n const observer = new IntersectionObserver((entries) => {\n set(entries.some(entry => entry.isIntersecting))\n })\n observer.observe(element)\n return () => {\n observer.disconnect()\n set(false)\n }\n }, [ref])\n}\n","/**\n * Scroll an element's nearest scrollable ancestor so the element tops that\n * scrollport. The jump's landing reveal needs this host-agnostic: the\n * conversation tab scrolls the shared `[data-conversation-scroll]` container\n * while the right Sidebar's scroller differs per generation (dockkit's pane\n * body — a CSS-module class with no stable attribute — on the 0.1.5 line, the\n * tab root itself on the 0.1.7 line), so the walk takes whichever ancestor\n * actually scrolls — the rect delta lands the anchor flush regardless of the\n * container's current position. `document.body` ends the walk: the page\n * itself never scrolls. False — never a throw — when no ancestor scrolls (the\n * layout already shows the element) or the chain turns hostile.\n *\n * @module dsh-context-redline/client/revealScroll\n */\n\nexport function revealInScrollParent(anchor: Element): boolean {\n try {\n for (let el = anchor.parentElement; el !== null && el !== document.body; el = el.parentElement) {\n const oy = window.getComputedStyle(el).overflowY\n if (oy === 'auto' || oy === 'scroll') {\n el.scrollTop += anchor.getBoundingClientRect().top - el.getBoundingClientRect().top\n return true\n }\n }\n } catch { /* hostile chain: the reveal degrades to nothing */ }\n return false\n}\n","/**\n * Context tab root: renders the `redlineTimeline` projection and composes stats, composition, history, events and messages.\n * The data plane is the harness's projection pipeline end to end; the one addition is the split generation's on-demand\n * detail read (timelineSource.ts) — the pushed wire value is the slim head, and the heavy collections arrive from the\n * host's detail endpoint only while the tab (or modal) is open.\n */\n\nimport { createElement as h, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactElement } from 'react'\nimport type { ContextEventRecord, RequestRecord, SurfaceNode } from '../../shared/types'\nimport { briefNodes, briefOf } from '../brief'\nimport type { ContextViewProps } from '../services'\nimport { conversationNodesOf, headersOf, imageLoaderOf, projectionOf, unsupportedOf } from '../services'\nimport type { ClientCtx, ConversationNodeLike } from '../services'\nimport { makeContentFetcher, makeHeaderFetcher, useHistoryFace } from '../historyPage'\nimport { useTimelineSource } from '../timelineSource'\nimport { makeDetailNote } from './detailNote'\nimport type { ContextSettings } from '../settings'\nimport type { ViewKit } from '../viewkit'\nimport { makeContextBrowser } from './browser'\nimport { useRedlineDrafts } from '../redlineDrafts'\nimport { useChildSessions } from '../childSessions'\nimport { makeChildCard } from './childCard'\nimport { makeEventList } from './events'\nimport { makeUpgradeGate } from './upgradeGate'\nimport { makeRequestDetail } from './requestDetail'\nimport { countsOfRecords, makeStatsContext } from './statsContext'\nimport { assemble, stepStatsOf } from '../assemble'\nimport { makeStackedBar } from './stackedBar'\nimport { aggregateByTurn, attachMarkers, jumpTargetOf, makeTrendChart, turnStepsOf } from './trendChart'\n\nimport { subscribeContextFocus, takeContextFocus } from '../viewFocus'\nimport { useSurfaceVisibility } from '../surfaceVisibility'\nimport { revealInScrollParent } from '../revealScroll'\nimport { makeErrorBoundary } from './errorBoundary'\n\n// The context page scrolls inside the conversation's shared `[data-conversation-scroll]` container, which the chat bottom-anchors — mirror\n// the chat's chatScroll pattern: a module-level per-session position ledger (survives tab remounts), restored once content renders; first\n// visits start at the top.\nconst viewScroll = new Map<string, number>()\n\nconst EVENT_KINDS = ['inject', 'compaction', 'prune', 'model', 'mode'] as const\n\nexport function makeContextView(\n ctx: ClientCtx,\n kit: ViewKit,\n settings: ContextSettings,\n): (props: ContextViewProps) => ReactElement {\n const { t } = kit\n const StackedBar = makeStackedBar(kit)\n const TrendChart = makeTrendChart(kit)\n const RequestDetail = makeRequestDetail(kit, StackedBar)\n const EventList = makeEventList(kit)\n // One page-scope cold-head cache serves both subagent-data readers: the\n const StatsContext = makeStatsContext(kit)\n const UpgradeGate = makeUpgradeGate(kit)\n const DetailNote = makeDetailNote(kit)\n const ContextBrowser = makeContextBrowser(kit, StackedBar, settings)\n const ErrorBoundary = makeErrorBoundary(t)\n\n // The body renders under the error boundary: a corrupt projection value (past the timelineOf shape guard) degrades to a styled error\n // card, not a white screen; the boundary itself has NO hooks, so the body's hook order and loading/data flow stay unchanged.\n function ContextViewBody(props: ContextViewProps): ReactElement {\n const sessionId = props.sessionId\n // The right Sidebar's panel is a narrow column: it drops the two head cards\n // that only pay off on the full-width tab (context stats, plugin info).\n const inSidebar = props.host === 'sidebar'\n // The timeline source (timelineSource.ts): the pushed value on the inline\n // generation, or the slim head merged with the on-demand detail on the\n // split generation. `detailState`/`retryDetail` drive the detail cards'\n // loading/failed notes.\n const source = useTimelineSource(ctx, props)\n const data = source.data\n // Official token-meter `contextPressure` projection — the same key the chat's context ring reads; token-meter owns estimation, the Host\n // no longer mirrors it. Absent → derived fallback.\n // Official token-meter `contextBreakdown` projection — the exact rows the chat ring's click-open panel shows, so the overview legend\n // reads identically by construction; absent → the fold's own same-estimator sums inside headlineOf.\n // Legacy fork rows remain readable from the platform catalog; ordinary carrier rows come from `carrier.list`.\n const childCatalog = projectionOf(props, 'subagentCatalog', raw => (Array.isArray(raw) ? raw : null))\n // `redlineHeaders` companion projection (full system prompt + tool schemas) for the Context browser; absent key = older Host half →\n // those sections degrade to tokens-only with a note.\n const headers = projectionOf(props, 'redlineHeaders', headersOf)\n const [selectedSeq, setSelectedSeq] = useState<number | null>(null)\n const [hoveredSeq, setHoveredSeq] = useState<number | null>(null)\n const [hoverTurn, setHoverTurn] = useState<number | null>(null)\n // Mount-time default from the plugin settings card; in-chart toggling stays mount-local and never writes back.\n const [granularity, setGranularity] = useState<'step' | 'turn'>(() => settings.defaultGranularity())\n // 'total' plots each request's cumulative composition, 'delta' its incremental change vs the previous one;\n // like granularity, the default is read at mount and in-chart toggling never writes back.\n const [trendMode, setTrendMode] = useState<'total' | 'delta'>(() => settings.defaultTrendMode())\n // Adaptive scale (the title-adjacent toggle): the trend bars rescale to the visible window; like the two\n // toggles above, mount-local and never written back.\n const [adaptive, setAdaptive] = useState(false)\n // Strip-clicked turn: chart switches to turn granularity and scroll-centers that turn's bar, then clears via onFocusTurnHandled.\n const [focusTurn, setFocusTurn] = useState<number | null>(null)\n // Chat → Context jump: the assistant-action relay's one-shot request, held until the projection data is in, then resolved into a\n // turn-level pin below (mirrors the strip-click's consume-once focus flow).\n const [jumpSeq, setJumpSeq] = useState<number | null>(null)\n const [hoverCat, setHoverCat] = useState<string | null>(null)\n // The browser's open category: the trend card focuses its bars on it (collapsing the category restores all).\n const [focusCat, setFocusCat] = useState<string | null>(null)\n const [pickedKinds, setPickedKinds] = useState<string[]>([...EVENT_KINDS])\n const toggleKind = (k: string) => {\n setPickedKinds((p) => {\n if (p.length === EVENT_KINDS.length) return [k]\n if (!p.includes(k)) return [...p, k]\n return p.length === 1 ? [...EVENT_KINDS] : p.filter(x => x !== k)\n })\n }\n // Step-brief → browser reveal bridge: one-shot focus request consumed by the Context browser.\n const [nodeFocus, setNodeFocus] = useState<{ step: number | 'live'; seq: number; cat: SurfaceNode['cat'] } | null>(null)\n const clearNodeFocus = useCallback(() => { setNodeFocus(null) }, [])\n\n // Session-authorized durable-image loader for the browser's attachment cards, resolved through the harness `uiConversation` service\n // (`imageUrl`); absent service/session degrades the cards to metadata-only, never an error.\n const loadImage = useMemo(\n () => imageLoaderOf(ctx, typeof sessionId === 'string' ? sessionId : undefined),\n [ctx, sessionId],\n )\n\n // The gateway page face, as a React seat: the first render can race the\n // declared inject (a watch rebuild remounts this view before the fiber\n // re-fires), and both fetchers below must rebuild — not stick to the\n // static degradation — when the face lands or is revoked.\n const historyFace = useHistoryFace()\n\n // Targeted full-content fetch for browser nodes outside the conversation window (one seq-anchored history read per expanded row);\n // absent face/session degrades to the static hint — never an error.\n const fetchContent = useMemo(\n () => (typeof sessionId === 'string' && sessionId !== '' && historyFace !== undefined\n ? makeContentFetcher(sessionId)\n : undefined),\n [sessionId, historyFace],\n )\n // On-demand header epoch content (system prompt text, tool schemas) for the Context browser — one seq-anchored history read per\n // opened epoch; the `redlineHeaders` projection carries metadata only. Same degradation shape as fetchContent.\n const fetchHeader = useMemo(\n () => (typeof sessionId === 'string' && sessionId !== '' && historyFace !== undefined\n ? makeHeaderFetcher(sessionId)\n : undefined),\n [sessionId, historyFace],\n )\n\n const rootRef = useRef<HTMLDivElement | null>(null)\n const scrollerRef = useRef<HTMLElement | null>(null)\n // The session whose position was already applied this mount — re-applying on re-renders would yank the reader's scroll.\n const restoredRef = useRef<string | null>(null)\n\n // 只在面板真的可见时,让那两条改**宿主**元素的 CSS 生效(见 surfaceVisibility.ts)。\n useSurfaceVisibility(rootRef)\n\n // Restore the saved position (or the top on first visit) in a layout effect, so the chat's bottom-anchored position never flashes in\n // first.\n useLayoutEffect(() => {\n if (typeof sessionId !== 'string' || sessionId === '' || data === null) return\n if (restoredRef.current === sessionId) return\n restoredRef.current = sessionId\n /* v8 ignore next 3 -- a layout effect body only runs while mounted and\n both render paths attach rootRef, so the null arm cannot fire. */\n const scroller = rootRef.current !== null\n ? rootRef.current.closest('[data-conversation-scroll]')\n : null\n if (scroller === null) return\n scrollerRef.current = scroller as HTMLElement\n scroller.scrollTop = viewScroll.get(sessionId) ?? 0\n }, [sessionId, data])\n\n // Save the position on unmount/session change — a layout-effect cleanup, so it fires before the incoming view's own layout effects\n // re-scroll the shared container.\n useLayoutEffect(() => {\n return () => {\n if (typeof sessionId !== 'string' || sessionId === '') return\n const scroller = scrollerRef.current\n if (scroller === null) return\n viewScroll.set(sessionId, scroller.scrollTop)\n }\n }, [sessionId])\n\n // No locale subscription here: the harness slot outlet subscribes the\n // LocaleFace revision and re-renders every entry on a locale switch, and\n // the kit's bound `t` reads the active locale at call time.\n\n // Hooks stay unconditional (Rules of Hooks): the projection value can arrive AFTER a loading first render, and an early return above\n // these useMemos would grow the hook count between renders (React #310); fall back to empty collections and keep the loading return\n // below the last hook.\n const requests = data ? data.requests : []\n const events = data ? data.events : []\n // The stats board's count figures — the split head's precomputed tallies, or\n // the collections' own derivation on the inline generation. Shared by the\n // stats card's shape cells and the events card's kind-filter counts.\n const counts = data?.counts ?? countsOfRecords(requests, events)\n // The per-kind tallies that ride the filter buttons: only the three priced\n // kinds the host counts (model/mode switches carry no tally, hence undefined).\n const kindCounts: Record<string, number | undefined> = { inject: counts.injects, compaction: counts.compactions, prune: counts.prunes }\n const shownEvents = pickedKinds.length === EVENT_KINDS.length ? events : events.filter(e => pickedKinds.includes(e.kind))\n // Per-step bars, or one per turn (each turn's LAST step's record); memoized so hover-driven re-renders keep bar props identity-stable —\n // the chart's memoized bars then skip reconciliation (turn-mode aggregation allocates).\n const displayRequests = useMemo(\n () => (granularity === 'turn' ? aggregateByTurn(requests) : requests),\n [requests, granularity],\n )\n // The scale readout's turn count: the LAST request's turn — the demo's own\n // `REQUESTS[last].turn` (`docs/03` R1.5).\n const lastTurn = displayRequests.length > 0 ? displayRequests[displayRequests.length - 1]?.turn ?? 1 : 0\n // The step labels' per-turn totals (\"第 s 步 (共 n 步)\"), tallied over the RAW step records — turn-mode\n // aggregates read their own stepCount instead.\n const stepsOf = useMemo(() => turnStepsOf(requests), [requests])\n const markers = useMemo(() => attachMarkers(displayRequests, events), [displayRequests, events])\n\n // Chat → Context jump, leg 1: pick up the assistant-action relay's request for this session —\n // once per mount, and again on every later record (the sidebar landing keeps this view mounted\n // while the user jumps between replies).\n useEffect(() => {\n if (typeof sessionId !== 'string' || sessionId === '') return\n const take = (): void => {\n const seq = takeContextFocus(sessionId)\n if (seq !== null) setJumpSeq(seq)\n }\n take()\n return subscribeContextFocus(take)\n }, [sessionId])\n\n // Leg 2: the action row belongs to the reply that CLOSED a turn, so the jump is turn-level — flip the chart to turn bars, pin that\n // turn's aggregate (the relayed seq is the turn's last request, exactly the aggregate's record), and center it: the same flow as a\n // turn-strip click. An aged-out turn clamps to the oldest retained bar. The landing then reveals the Current Composition card, so\n // the card and the pinned turn's trend chart share the scrollport (revealScroll.ts; no scrollable ancestor → a quiet no-op).\n // The split generation waits for the detail read first: the relayed seq resolves against the served request records, so the\n // one-shot request must not be consumed while the collections are still pending (it re-fires when they land).\n const detailReady = source.detailState === 'ready' || source.detailState === 'legacy'\n useEffect(() => {\n if (jumpSeq === null || data === null || !detailReady) return\n setJumpSeq(null)\n const target = jumpTargetOf(aggregateByTurn(requests), jumpSeq)\n if (target === null) return\n setGranularity('turn')\n setSelectedSeq(target.seq)\n setFocusTurn(target.turn ?? 0)\n // The restore layout effect already applied the saved position on this same data render\n // (layout effects precede this one); the reveal overrides it wherever it landed.\n /* v8 ignore next 2 -- the effect only fires while mounted, and both render paths attach\n rootRef and render the composition card. */\n const anchor = rootRef.current?.querySelector('[data-redline-current]') ?? null\n if (anchor !== null) revealInScrollParent(anchor)\n }, [jumpSeq, data, requests, detailReady])\n\n // Step-brief raw material: every served node seq-sorted (live tail + archive), and the conversation-snapshot\n // join the brief uses for call-argument enrichment (same join the Context browser builds).\n const briefList = useMemo(() => (data ? briefNodes(data) : []), [data])\n // The conversation-window join, from the `useChat` seat. The seat is a\n // real hook — invoked unconditionally per render (stable order);\n // undefined join = render without it, never an error.\n const convNodes = conversationNodesOf(props)\n const bySeq = useMemo(() => {\n const m = new Map<number, ConversationNodeLike>()\n for (const n of convNodes ?? []) m.set(n.seq, n)\n return m\n }, [convNodes])\n\n // Active bar / pin lookup — derived BEFORE the loading-return so the hooks below stay unconditional (React #310).\n let pinnedIdx = -1\n for (let i = 0; i < displayRequests.length; i++) if (displayRequests[i].seq === selectedSeq) pinnedIdx = i\n const pinnedReq = pinnedIdx >= 0 ? displayRequests[pinnedIdx] : null\n let activeIdx = -1\n if (hoveredSeq !== null) {\n for (let i = 0; i < displayRequests.length; i++) if (displayRequests[i].seq === hoveredSeq) { activeIdx = i; break }\n }\n if (activeIdx < 0) activeIdx = pinnedIdx\n if (activeIdx < 0 && displayRequests.length > 0) activeIdx = displayRequests.length - 1\n const activeReq = activeIdx >= 0 ? displayRequests[activeIdx] : null\n // The active bar's semantic identity (\"what this step was about\"); pure derivation over the served nodes, null when nothing is known.\n const brief = useMemo(\n () => (activeReq !== null ? briefOf(briefList, displayRequests, activeIdx) : null),\n [activeReq, briefList, displayRequests, activeIdx],\n )\n const convOf = useCallback((seq: number): ConversationNodeLike | undefined => bySeq.get(seq), [bySeq])\n\n // File activity follows the same active bar: the op-log generation reads the fold-derived records (full\n // session-log coverage); older hosts keep the conversation-window derivation. Recomputed when the brief\n // source, the conversation join, or the upper bound moves — hover/select elsewhere (composition chips,\n // kind filters) leaves every input reference untouched, so the walk is skipped on those renders.\n // The session's workspace root — './'-relative row paths when known; read per\n // render (an observable snapshot), so the next projection push re-renders with it.\n // The system-opener affordance rides the same ctx; both resolve before the early return.\n // The capability is an RPC answer now (the synchronous host-description fact is gone),\n // so it lands in state once the probe settles — inert file names until then; the\n // effect's cleanup drops an answer that arrives after the view unmounted.\n // The right-Sidebar preview opener (the same optional column the Context\n // tab itself registers into): resolved off `ctx` at mount, the face\n // re-proved per call, so an HMR reload's revocation never leaves a stale\n // opener. Absent face = no `onPreview` at all, and the card keeps its\n // system-open affordance untouched.\n // A brief row's reveal target: inputs/opener live in the picked step's OWN assembled surface; the response node (seq === the\n // request's) first appears in the NEXT step's surface — or the live surface when the last bar is picked.\n const locateNode = useCallback((node: SurfaceNode, isResponse: boolean): void => {\n /* v8 ignore next 1 -- locateNode is only wired to brief rows, and\n brief !== null guarantees activeReq !== null in the same closure. */\n if (activeReq === null) return\n const next = isResponse && activeIdx + 1 < displayRequests.length ? displayRequests[activeIdx + 1] : null\n const step: number | 'live' = isResponse ? (next !== null ? next.seq : 'live') : activeReq.seq\n setNodeFocus({ step, seq: node.seq, cat: node.cat })\n }, [activeReq, activeIdx, displayRequests])\n\n // Hooks must remain above the loading return: one mounted view may move from undefined projection to ready data.\n const redline = useRedlineDrafts(typeof sessionId === 'string' && sessionId !== '' ? sessionId : undefined)\n const children = useChildSessions(\n typeof sessionId === 'string' && sessionId !== '' ? sessionId : undefined,\n childCatalog,\n )\n\n if (!data) {\n return <div className=\"redline-root\" ref={rootRef}><div className=\"redline-empty\">{t('loading')}</div></div>\n }\n\n const markerOf = (req: RequestRecord): ContextEventRecord | undefined => {\n const i = displayRequests.indexOf(req)\n /* v8 ignore next 1 -- the only caller passes displayRequests[activeIdx],\n an element of the very array indexOf scans. */\n return i >= 0 ? markers[i] : undefined\n }\n\n // Provider-anchored CURRENT occupancy (contextPressure.projectedTokens): the headline, because the fixed 4-chars/token heuristic\n // undercounts CJK by ~10–15% — proportions stay heuristic but are anchored to the real billed total. Shared with the /redline popup\n // (headline.ts); composition rides the official `contextBreakdown` rows.\n\n // Turn highlight is hover-only: the turn strip hover wins, then the hovered bar's turn — no fallback, so a pinned or default selection\n // never keeps a turn glowing.\n let activeTurn: number | null = hoverTurn\n if (activeTurn === null && hoveredSeq !== null) {\n for (const req of displayRequests) if (req.seq === hoveredSeq) { activeTurn = req.turn ?? null; break }\n }\n\n // The trend card mirrors the SAME shared category hover the browser's live link uses: the overview's 'free' key drops\n // (no segment in the chart or the detail bar), and every bar + the detail bar light that category's segment.\n const trendHoverCat = hoverCat !== null && hoverCat !== 'free' ? hoverCat : null\n\n // The cost cell prices in the active locale (zh → CNY, else USD), read at render time — the locale subscription above already\n // The host's baseline gate (host/fallback.ts): the cards below render\n // the fallback's zeroed data while the modal names both versions and\n // urges the upgrade. Absent record = a supported harness, no gate.\n const gate = unsupportedOf(data.unsupported)\n\n // The three main-row cards, built once and laid out by the shared\n // arrangement below (every host uses the same row).\n const trendCard = (\n <div className=\"redline-card\">\n <div className=\"redline-card-title\">\n <span className=\"redline-card-title-text\">{t('trend.title')}</span>\n {/* 规模读数(`docs/03` R1.5,与 demo 的 `granLabel` 同一句):`按轮次(共 N 轮)` / `按步骤(共 N 次请求)`。\n 单独一个 class:`.redline-card-sub` 是**聚焦**那一行,两者语义不同(混用会让\"没聚焦⇒没有副标题\"的契约失真)。 */}\n <span className=\"redline-card-scale\">\n {t(granularity === 'turn' ? 'trend.gran.turn' : 'trend.gran.step', { n: granularity === 'turn' ? lastTurn : displayRequests.length })}\n </span>\n {/* The adaptive switch rides the title's right (the browser card's DNA toggle idiom): bars rescale\n to the bars currently on screen instead of the whole retained log. */}\n <span className=\"redline-gran redline-trend-adaptive\" role=\"group\" title={t('trend.adaptiveHint')}>\n <button\n type=\"button\"\n className={'redline-gran-btn' + (adaptive ? ' redline-gran-on' : '')}\n onClick={() => { setAdaptive(on => !on) }}\n >{t('trend.adaptive')}</button>\n </span>\n {focusCat !== null\n ? <span className=\"redline-card-sub\">{t('trend.focus', { cat: kit.catLabel(focusCat) })}</span>\n : null}\n <div className=\"redline-trend-ctl\">\n <div className=\"redline-gran\">\n <button\n className={'redline-gran-btn' + (granularity === 'step' ? ' redline-gran-on' : '')}\n onClick={() => { setGranularity('step') }}\n >{t('gran.step')}</button>\n <button\n className={'redline-gran-btn' + (granularity === 'turn' ? ' redline-gran-on' : '')}\n onClick={() => { setGranularity('turn') }}\n >{t('gran.turn')}</button>\n </div>\n <div className=\"redline-gran\" title={t('gran.modeHint')}>\n <button\n className={'redline-gran-btn' + (trendMode === 'total' ? ' redline-gran-on' : '')}\n onClick={() => { setTrendMode('total') }}\n >{t('gran.total')}</button>\n <button\n className={'redline-gran-btn' + (trendMode === 'delta' ? ' redline-gran-on' : '')}\n onClick={() => { setTrendMode('delta') }}\n >{t('gran.delta')}</button>\n </div>\n </div>\n </div>\n {displayRequests.length === 0\n // Split generation, first detail read pending or failed: say\n // so instead of claiming the session has no history.\n ? (detailReady\n ? <div className=\"redline-empty\">{t('trend.empty')}</div>\n : <DetailNote state={source.detailState === 'failed' ? 'failed' : 'loading'} onRetry={source.retryDetail} />)\n : (\n <div>\n <TrendChart\n // Remount per session: switching sessions re-anchors the chart at the newest bars instead of inheriting stale scroll\n // state.\n key={sessionId}\n // Render ALL retained requests (bounded by the host's maxKeptTurns/maxRequestSteps config) so earlier turns/steps\n // stay reachable via horizontal scroll.\n requests={displayRequests}\n markers={markers}\n selectedSeq={pinnedReq ? pinnedReq.seq : null}\n hoveredSeq={hoveredSeq}\n activeTurn={activeTurn}\n granularity={granularity}\n mode={trendMode}\n focusTurn={focusTurn}\n hoverCat={trendHoverCat}\n focusCat={focusCat}\n adaptive={adaptive}\n onSelect={setSelectedSeq}\n onHover={setHoveredSeq}\n onHoverTurn={setHoverTurn}\n onPickTurn={(turn) => { setGranularity('turn'); setFocusTurn(turn) }}\n onFocusTurnHandled={() => { setFocusTurn(null) }}\n />\n <RequestDetail\n request={activeReq}\n // Delta mode pairs the detail with the SAME previous record the chart diffs against (first bar: null).\n prev={trendMode === 'delta' && activeIdx >= 0 ? (activeIdx > 0 ? displayRequests[activeIdx - 1] : null) : undefined}\n /* v8 ignore next 1 -- RequestDetail renders only when\n displayRequests.length > 0, which forces activeReq\n non-null via the activeIdx fallback above. */\n marker={activeReq !== null ? markerOf(activeReq) : undefined}\n brief={brief}\n convOf={convOf}\n stepsOf={stepsOf}\n onLocate={locateNode}\n hoverKey={trendHoverCat}\n />\n </div>\n )}\n </div>\n )\n const browserCard = (\n <ContextBrowser\n redline={redline}\n data={data}\n headers={headers}\n convNodes={convNodes}\n fetchContent={fetchContent}\n fetchHeader={fetchHeader}\n previewSeq={hoveredSeq}\n pinSeq={pinnedReq !== null ? pinnedReq.seq : null}\n hoverKey={hoverCat}\n onHoverKey={setHoverCat}\n onOpenCat={setFocusCat}\n nodeFocus={nodeFocus}\n onNodeFocusHandled={clearNodeFocus}\n loadImage={loadImage}\n detailState={source.detailState}\n onDetailRetry={source.retryDetail}\n />\n )\n\n // 统计卡那 3 格的数据:`assemble()` 给出\"这一步的列表\"(含在那一步还活着、如今已被接替的原文),\n // 三个数字由纯函数 `stepStatsOf()` 从同一张列表里数出来 —— 与浏览器卡片列出的行**同一个来源**。\n const stepStats = stepStatsOf(assemble(data, headers, activeReq !== null ? activeReq.seq : null))\n return (\n <div className=\"redline-root\" ref={rootRef}>\n\n {/* 两列各自从顶部向下排:左边看趋势/发生了什么,右边看上下文/改完后开子会话。\n 不把另一列的高度带进定位,避免传统行式布局造成的顶部空洞;窄处自动成一列。\n 统计卡是**左列第一张卡**(demo 的顺序),不再是顶部整宽横幅 —— 整宽时它的三格\n 会被拉成三大行,既不像 demo 也浪费首屏。右侧栏面板(窄列)不放它(`docs/03` R5.1)。 */}\n <div className=\"redline-masonry\">\n <div className=\"redline-masonry-col\">\n {inSidebar ? null : (\n <StatsContext stats={stepStats} turn={activeReq?.turn} step={activeReq?.step}\n live={activeReq === null} ready={source.detailState === 'ready' || source.detailState === 'legacy'} />\n )}\n {trendCard}\n <div className=\"redline-card\">\n <div className=\"redline-card-title\">\n <span className=\"redline-card-title-text\">{t('events.title')}</span>\n <div className=\"redline-kinds @max-[380px]/redline-card:flex-wrap\">\n {EVENT_KINDS.map((k) => {\n const n = kindCounts[k]\n return (\n <button\n key={k}\n data-redline-kind={k}\n className={'redline-gran-btn' + (pickedKinds.includes(k) ? ' redline-gran-on redline-kind-' + k : '')}\n onClick={() => { toggleKind(k) }}\n >\n {t('kind.' + k)}\n {n !== undefined ? <span className=\"redline-kind-n\">{kit.fmt(n)}</span> : null}\n </button>\n )\n })}\n </div>\n </div>\n <EventList events={shownEvents} state={source.detailState} onRetry={source.retryDetail} />\n </div>\n </div>\n\n <div className=\"redline-masonry-col\">\n {browserCard}\n {/* 第 5 张卡(`docs/10` M3-16/17,随 M5 落地):子会话索引 + 开子会话。\n 它是**本面板唯一会写会话的入口**,所以按钮的门禁与 `保存` 完全一致(`live` / `turnOpen`)。 */}\n <ChildCard\n sessionId={sessionId}\n rows={children.rows}\n capacity={children.capacity}\n originsKnown={children.originsKnown}\n originsError={children.originsError}\n models={children.models}\n live={redline.turn.known}\n turnOpen={redline.turn.open}\n carriedCount={Object.keys(redline.table).length}\n plan={children.plan}\n start={children.start}\n />\n </div>\n </div>\n\n\n <div className=\"redline-foot\">{t('footer')}</div>\n\n {gate !== null && (\n <UpgradeGate sessionId={sessionId} current={gate.current} minimum={gate.minimum} />\n )}\n </div>\n )\n }\n\n const ChildCard = makeChildCard(kit)\n\n return function ContextView(props: ContextViewProps): ReactElement {\n return h(ErrorBoundary, null, h(ContextViewBody, props))\n }\n}\n","/**\n * The assistant-message action that opens the Context view at this reply's\n * turn. Registered on the harness `conversation.chat.assistant-actions` seat\n * (the icon row beside copy/branch), it receives the finalized reply's durable\n * message id, resolves the matching assistant node's seq off the `useChat`\n * node seat AT RENDER TIME (the seat is a real React hook — render-only; a\n * click-time read throws the dispatcher guard and the jump would land\n * unpinned), records it in the viewFocus relay on click, and opens the\n * Context tab on the right Sidebar — where the jump pins the reply's TURN\n * (see contextView's leg 2). A harness or placement without the sidebar tab\n * falls back to the conversation tab; an unresolvable seq still opens the\n * view, just without a pin; a message id that is not a plain string renders\n * nothing at all.\n */\n\nimport { type ReactElement } from 'react'\nimport { Tooltip } from '@deepseek-ai/dsh-client-ui-primitives'\nimport type { ClientCtx, ConversationNodeLike, UseChatLike } from '../services'\nimport { conversationNodesOf } from '../services'\nimport { activateContextTab, openContextSidebar, requestContextFocus } from '../viewFocus'\nimport type { ViewKit } from '../viewkit'\n\n/** The assistant-action seat's currency, as far as this button consumes it. */\nexport interface ContextJumpProps {\n messageId?: unknown\n sessionId?: unknown\n useChat?: UseChatLike\n}\n\n/**\n * The reply's request seq by its durable message id, or null when no served node proves the pair. Join/log nodes are untrusted input: each\n * element is isolated, so one hostile object that throws on property access is skipped — the jump keeps its pin, never its click.\n */\nexport function seqOfMessageId(nodes: readonly ConversationNodeLike[] | undefined, messageId: string): number | null {\n for (const node of nodes ?? []) {\n try {\n if (node.kind !== 'assistant' || node.messageId !== messageId) continue\n return typeof node.seq === 'number' && Number.isFinite(node.seq) ? node.seq : null\n } catch {\n continue\n }\n }\n return null\n}\n\n/** The jump glyph: the plugin's mini stacked composition bars, same 16px outline family as the shipped row icons. */\nfunction JumpIcon(): ReactElement {\n return (\n <svg width=\"16\" height=\"16\" viewBox=\"0 0 16 16\" className=\"redline-jump fill-none\" aria-hidden=\"true\">\n <rect x=\"2\" y=\"3\" width=\"12\" height=\"2\" rx=\"1\" className=\"fill-current\" />\n <rect x=\"2\" y=\"7\" width=\"8.5\" height=\"2\" rx=\"1\" className=\"fill-current\" />\n <rect x=\"2\" y=\"11\" width=\"5.5\" height=\"2\" rx=\"1\" className=\"fill-current\" />\n </svg>\n )\n}\n\nexport function makeContextJumpButton(ctx: ClientCtx, kit: ViewKit): (props: ContextJumpProps) => ReactElement | null {\n const { t } = kit\n return function ContextJump(props: ContextJumpProps): ReactElement | null {\n // The seat is read HERE — unconditionally and first, so the early return\n // below keeps hook order — and the click consumes the captured pair.\n const nodes = conversationNodesOf(props)\n const messageId = props.messageId\n // Interruption-frozen partials address no durable message — the owner\n // already withholds them, and anything else non-string is ignored.\n if (typeof messageId !== 'string' || messageId === '') return null\n const seq = seqOfMessageId(nodes, messageId)\n const jump = (): void => {\n const sessionId = props.sessionId\n if (seq !== null && typeof sessionId === 'string' && sessionId !== '') {\n requestContextFocus(sessionId, seq)\n }\n // The sidebar expands over the chat, keeping the clicked reply in view;\n // a harness or placement without that tab keeps the tab activation.\n if (!openContextSidebar(ctx)) activateContextTab(t('tab'))\n }\n return (\n <Tooltip label={t('jump.title')} side=\"bottom\">\n <button type=\"button\" className=\"redline-jump hover:bg-(--dsw-alias-interactive-bg-hover) hover:text-(--dsw-alias-label-secondary)\" aria-label={t('jump.title')} onClick={jump}>\n <JumpIcon />\n </button>\n </Tooltip>\n )\n }\n}\n","/**\n * Placement gating for the Context view: the per-user `defaultPlacement`\n * preference (the settings namespace's `defaultPlacement` field) picks which\n * registrations carry it — the conversation tab, the right Sidebar panel, or\n * both.\n *\n * Each mount is a factory returning its own disposer, so a preference flip\n * takes down only what the new value drops and mounts only what it adds; the\n * underlying `slots.inject` / deferred-inject disposers are the harness's own\n * dynamic-mount idiom. A mount landing no disposer (a harness face that\n * returns nothing) simply has nothing to unwind.\n *\n * @module dsh-context-redline/client/placement\n */\n\nimport type { ContextSettings } from './settings'\nimport type { DefaultPlacement } from '../shared/types'\n\n/** One registration factory per placement; each returns its mount's disposer. */\nexport interface PlacementMounts {\n tab(): unknown\n sidebar(): unknown\n}\n\n/**\n * Mount per the current preference and keep the registrations glued to it\n * until the returned disposer runs.\n */\nexport function watchPlacement(settings: ContextSettings, mounts: PlacementMounts): () => void {\n let tab: (() => void) | undefined\n let sidebar: (() => void) | undefined\n const own = (result: unknown): (() => void) | undefined =>\n typeof result === 'function' ? result as () => void : undefined\n const mount = (placement: DefaultPlacement): void => {\n const wantTab = placement !== 'sidebar'\n const wantSidebar = placement !== 'tab'\n if (wantTab && tab === undefined) tab = own(mounts.tab())\n if (!wantTab && tab !== undefined) { tab(); tab = undefined }\n if (wantSidebar && sidebar === undefined) sidebar = own(mounts.sidebar())\n if (!wantSidebar && sidebar !== undefined) { sidebar(); sidebar = undefined }\n }\n mount(settings.defaultPlacement())\n const unsubscribe = settings.store.subscribe(() => { mount(settings.defaultPlacement()) })\n return () => {\n unsubscribe()\n tab?.()\n sidebar?.()\n tab = undefined\n sidebar = undefined\n }\n}\n","/** Shared dependency bag for component factories, built once per plugin apply (t, formatters, catLabel, event-text helpers). */\n\nimport type { ContextEventRecord } from '../shared/types'\nimport { fmt, fmtDuration, fmtShare, fmtTime } from './format'\nimport { makeEventText } from './components/events'\nimport type { Translate } from './i18n'\n\nexport interface ViewKit {\n t: Translate\n fmt: typeof fmt\n fmtTime: typeof fmtTime\n fmtDuration: typeof fmtDuration\n fmtShare: typeof fmtShare\n catLabel: (key: string) => string\n eventLabel: (ev: ContextEventRecord) => string\n eventAt: (ev: ContextEventRecord) => string | null\n}\n\nexport function makeViewKit(t: Translate): ViewKit {\n const { eventLabel, eventAt } = makeEventText(t)\n return {\n t,\n fmt,\n fmtTime,\n fmtDuration,\n fmtShare,\n catLabel: (key: string) => t('cat.' + key),\n eventLabel,\n eventAt,\n }\n}\n","/**\n * dsh-context-redline — Client half (installed package bundle entry).\n *\n * Registers a \"上下文/Context\" tab in the conversation view ring\n * (`conversation.view` slot, beside Chat/Trajectory) and renders the\n * context-composition timeline: current makeup, per-request stacked-bar\n * history, context events, and the live message list.\n *\n * Since v0.9 the tab rides the harness's session-projection pipeline\n * (`redlineTimeline` projection key), read from the framework standard kit\n * (`useProjection('redlineTimeline')`, a standard prop on every session-scope\n * slot component). The wire value is the split generation's slim head; the\n * heavy collections arrive on demand from the host's detail endpoint, one\n * read per viewing client (timelineSource.ts). No polling, no stale-while-\n * revalidate cache.\n *\n * This module is the body of the package's `./client` bundle: tsdown\n * (tsdown.config.ts) bundles it (external `react` — the browser module table\n * supplies it via the injected `require`) into the web boot handoff\n * (`window.__ModuleLoader__.load({id, factory})`). All imports from other\n * client modules are inlined by the bundler; everything here is zero-runtime\n * beyond the bundled source.\n */\n\nimport { createElement as h } from 'react'\nimport { DICT_EN, DICT_ZH } from './i18n'\nimport { registerContextCommand } from './command'\nimport { makeContextModal } from './components/contextModal'\nimport { makeSettingsCard, makePluginConfigCard } from './components/settingsCard'\nimport { modalStoreOf } from './modalStore'\nimport type { ClientCtx } from './services'\nimport { createContextSettings, type ConfigFormsFace, type SettingsField, type SettingsScopeBinderFace } from './settings'\nimport { makeContextView } from './components/contextView'\nimport { makeContextJumpButton } from './components/contextJump'\nimport { watchHistoryFaces } from './historyPage'\nimport { watchPlacement } from './placement'\nimport { watchSidebarContextTab } from './sidebar'\nimport { makeViewKit } from './viewkit'\n\n// Theme-native styles: the bundle's global-CSS channel injects each sheet as\n// a plugin-owned <style data-plugin> tag at factory execution (the web boot\n// loader and the HMR receiver claim tags carrying data-plugin). Import order\n// IS cascade order across same-specificity rules: the Tailwind utilities\n// first (the sibling sheets keep winning same-specificity ties), then base,\n// then the per-component sheets in their original section order.\nimport './styles/tailwind.css'\nimport './styles/base.css'\nimport './styles/stats.css'\nimport './styles/jump.css'\nimport './styles/settings.css'\nimport './styles/stackedBar.css'\nimport './styles/trendChart.css'\nimport './styles/requestDetail.css'\nimport './styles/events.css'\n// fileCard.css 已随孤岛 B(已删的上游五卡)删除(docs/10 M6-17)\nimport './styles/modal.css'\nimport './styles/browser.css'\nimport './styles/childCard.css'\nimport './styles/detailSections.css'\nimport './styles/attachments.css'\n// agentGraph.css 已随孤岛 A(Agent 网络卡 + 费用/子 agent 模块)删除(docs/10 M6-17)\n// overview.css 已随洞察面删除(用户 2026-10-05 选二):96 个类全无引用\n\nconst NS = 'dsh-context-redline'\n\nfunction apply(ctx: ClientCtx): void {\n // Bilingual dictionaries, registered via ctx.effect so a stop or HMR reload\n // disposes them; the tab label thunk and all UI text follow the active\n // locale through the bound translate — missing keys resolve through the\n // harness chain (en fallback, then the key).\n ctx.effect(() => {\n return ctx.locale.register(NS, { zh: DICT_ZH, en: DICT_EN })\n }, 'dsh-context-redline: dictionaries')\n const t = ctx.locale.bind(NS)\n\n const kit = makeViewKit(t)\n // History face of the harness gateway remotes, resolved through the\n // DECLARED inject — a non-declared read of the traced `remote.session`\n // proxy throws (\"cannot get property … without inject\") and would take\n // the browser down with the view. Injection waits for the service; a\n // harness that never composes the namespace never fires the callback and\n // the targeted fetches simply stay absent.\n watchHistoryFaces(ctx)\n const settings = createContextSettings()\n const ContextView = makeContextView(ctx, kit, settings)\n\n // Placement: the per-user `defaultPlacement` preference picks which\n // registration carries the view — the conversation tab, the right Sidebar\n // (dsh 0.1.5-rc.1+, optional by contract), or both (the default). Each\n // mount owns its disposer so the watcher takes down exactly what a\n // preference flip drops (see placement.ts).\n ctx.effect(() => watchPlacement(settings, {\n tab: () => ctx.slots.inject('conversation.view', () => {\n return ctx.slots.register(\n // order 20 renders right of Chat (0) and Trajectory (10); the locale\n // namespace put the framework `t` seat on the component's props too.\n { name: 'conversation.view', id: 'redline', order: 20, locale: NS, label: () => t('tab') },\n props => h(ContextView, props),\n )\n }),\n sidebar: () => watchSidebarContextTab(ctx, ContextView, t, NS),\n }), 'dsh-context-redline: placement')\n\n // Chat → Context jump: an icon in each finalized reply's action row that\n // opens the Context tab on the right Sidebar pinned to that reply's turn —\n // falling back to the conversation tab wherever the sidebar serves no tab\n // (see contextJump.tsx; the relay and view activation live in viewFocus.ts).\n const ContextJump = makeContextJumpButton(ctx, kit)\n ctx.slots.inject('conversation.chat.assistant-actions', () => {\n return ctx.slots.register(\n // After the shipped feedback entry (10), still inside the icon row.\n { name: 'conversation.chat.assistant-actions', id: 'redline-jump', order: 20, locale: NS },\n props => h(ContextJump, props),\n )\n })\n\n // `/redline` slash command: opens the context modal (see command.ts for\n // the trigger source). The modal itself renders from the input overlay\n // slot, opened per session through the hooks-compartment store.\n registerContextCommand(ctx, kit)\n const ContextModal = makeContextModal(ctx, kit, settings)\n ctx.slots.inject('conversation.input.overlay', () => {\n return ctx.slots.register(\n { name: 'conversation.input.overlay', id: 'redline-modal', order: 10, locale: NS,\n inject: (sessionId = '') => ({ hooks: { contextModal: modalStoreOf(sessionId) } }) },\n props => h(ContextModal, props),\n )\n })\n\n // The Context Dashboard (see components/overviewPanel.tsx): the cross-session\n // insight surface. ⚠️ **The sidebar-foot ENTRY was removed on 2026-10-05** ——\n // the user said 「左侧抽屉的底部,我们不需要上下文批改的这个提示。可以去掉」\n // (the footer chip sat directly above Settings in the left drawer)。\n // The overlay below stays registered: it is the panel itself, and the open flag\n // still rides `overviewStore.ts`, so wiring a different opener later needs no\n // panel work. NOTE: with no opener registered today the overlay is unreachable\n // — flagged in `docs/10` M3-35 as a decision (keep for later wiring / remove).\n // ⚠️ **整块\"洞察面\"已按用户要求删除**(2026-10-05:「我推荐选二」—— 它是参考插件 dsh-context 的功能,\n // 我们的 demo 里没有;入口在更早一轮按同一要求拆掉)。删的是我们自己包里的那份复制品:\n // overviewPanel / overviewButton / overviewCard / overviewTokens / overviewUsage / heatmap / balanceCapsule\n // + overviewStore + 这处 `shell.overlay` 注册。**共用件一律保留**(`overview.ts` 是全仓核心装配、\n // `donut` / `pluginInfo` / `agentTree` / `statsTokens·Timing` / `sliceList` / `currentComposition` 我们的面板在用)。\n // 界线上不碰任何**别人的**插件与其样式。\n\n /** The injected face both preference cards ride: the settings store as the\n * framework's hooks-compartment `useContextSettings` seat, plus the set verb. */\n const cardFace = (): {\n hooks: { contextSettings: typeof settings.store }\n set: (field: SettingsField, value: string) => void\n } => ({\n hooks: { contextSettings: settings.store },\n set: (field, value) => { settings.set(field, value) },\n })\n\n // Per-user display preferences. Two generations, two transports and seats,\n // switched by SERVICE PRESENCE (each deferred inject fires on exactly one\n // side; a host without its service never runs the callback):\n // - the settingsScope generation registers the card on the keyed\n // `settings.plugin.item` slot (Settings → Plugins → Plugin\n // configuration), binding the Host-served `dsh-context-redline` namespace;\n // - the Config-form generation (dsh 0.1.7+) retired that pair — there the\n // card rides the configForms transport and the Plugins page's keyed\n // `plugins.bundle.config` seat, alive only while the Host serves the\n // namespace (the entry Config's volatile preference fields).\n ctx.inject(['settingsScope'], (raw) => {\n const c = raw as ClientCtx & { settingsScope?: SettingsScopeBinderFace }\n const binder = c.settingsScope\n if (binder === undefined) return\n c.effect(() => settings.attach(binder.bind({ namespace: NS })), 'dsh-context-redline: settings scope')\n const SettingsCard = makeSettingsCard(kit)\n c.slots.inject('settings.plugin.item', () => {\n return c.slots.register(\n { name: 'settings.plugin.item', key: NS, locale: NS, inject: cardFace },\n // Root-scope keyed slot: no sessionId on these props — the face\n // (hooks + set) arrives through the registration's inject.\n props => h(SettingsCard, props as unknown as Parameters<typeof SettingsCard>[0]),\n )\n })\n })\n ctx.inject(['configForms'], (raw) => {\n const c = raw as ClientCtx & { configForms?: ConfigFormsFace }\n const forms = c.configForms\n if (forms === undefined || typeof forms.get !== 'function' || typeof forms.whileServed !== 'function') return\n c.effect(() => settings.attach(forms.get(NS)), 'dsh-context-redline: config forms')\n const PluginConfigCard = makePluginConfigCard(kit)\n c.effect(() => forms.whileServed([NS], () => {\n // slots.inject's disposer is the registration's disposer (the typed\n // local face reads unknown; the harness contract returns a disposer).\n return c.slots.inject('plugins.bundle.config', () => {\n return c.slots.register(\n { name: 'plugins.bundle.config', key: NS, locale: NS, inject: cardFace },\n props => h(PluginConfigCard, props as unknown as Parameters<typeof PluginConfigCard>[0]),\n )\n }) as () => void\n }), 'dsh-context-redline: plugins-page card')\n })\n}\n\nmodule.exports = {\n name: 'dsh-context-redline',\n inject: ['slots', 'locale'],\n apply,\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAOA,MAAa,UAAkC;GAC7C,OAAO;GACP,4BAA4B;GAC5B,cAAc;GAAS,aAAa;GAAQ,YAAY;GACxD,cAAc;GAAQ,aAAa;GAAQ,iBAAiB;GAAQ,YAAY;GAChF,kBAAkB;GAClB,qBAAqB;GACrB,iBAAiB;GACjB,iBAAiB;GACjB,mBAAmB;GACnB,2BAA2B;GAC3B,eAAe;GACf,kBAAkB;GAClB,kBAAkB;GAClB,eAAe;GAEf,iBAAiB;GACjB,sBAAsB;GACtB,sBAAsB;GACtB,kBAAkB;GAClB,qBAAqB;GACrB,kBAAkB;GAClB,cAAc;GACd,eAAe;GACf,aAAa;GAAM,aAAa;GAEhC,mBAAmB;GACnB,mBAAmB;GACnB,kBAAkB;GAAO,iBAAiB;GAC1C,sBAAsB;GACtB,iBAAiB;GAAO,qBAAqB;GAAO,iBAAiB;GACr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AAA,cAAAA,CAAE,cAAc,KAAsD,CACjF;IACF,CAAC;GACH,CAAC;GACD,IAAI,OAAO,CAAC,aAAa,IAAI,QAAQ;IACnC,MAAM,IAAI;IACV,MAAM,QAAQ,EAAE;IAChB,IAAI,UAAU,KAAA,KAAa,OAAO,MAAM,QAAQ,cAAc,OAAO,MAAM,gBAAgB,YAAY;IACvG,EAAE,aAAa,SAAS,OAAO,MAAM,IAAI,EAAE,CAAC,GAAG,mCAAmC;IAClF,MAAM,mBAAmB,qBAAqB,GAAG;IACjD,EAAE,aAAa,MAAM,YAAY,CAAC,EAAE,SAAS;KAG3C,OAAO,EAAE,MAAM,OAAO,+BAA+B;MACnD,OAAO,EAAE,MAAM,SACb;OAAE,MAAM;OAAyB,KAAK;OAAI,QAAQ;OAAI,QAAQ;MAAS,IACvE,WAAA,GAASA,MAAAA,cAAAA,CAAE,kBAAkB,KAA0D,CACzF;KACF,CAAC;IACH,CAAC,GAAG,wCAAwC;GAC9C,CAAC;EACH;EAEA,OAAO,UAAU;GACf,MAAM;GACN,QAAQ,CAAC,SAAS,QAAQ;GAC1B;EACF"}
|
|
1
|
+
{"version":3,"file":"client.js","names":["sheetMarkup","stores","useSyncExternalStore","useMemo","useSyncExternalStore","useState","useRef","memo","useMemo","useState","useRef","useState","primitives","useRef","createPortal","useState","useCallback","MarkdownText","useState","useMemo","useCallback","writeClipboard","useMemo","useState","useId","useRef","useState","Component","useRef","useState","useRef","useCallback","useMemo","useState","useRef","useMemo","useCallback","h","useState","Menu","useRef","useMemo","useState","useRef","useCallback","ERR","useState","useRef","createPortal","h","useCallback","useRef","useState","useCallback","memo","useState","useCallback","useMemo","useRef","h","Tooltip","h"],"sources":["../src/client/i18n.ts","../icon.svg?raw","../src/client/icon.tsx","../src/client/modalStore.ts","../src/client/command.ts","../src/client/dockMeasure.ts","../src/client/categories.ts","../src/client/headline.ts","../src/shared/estimate.ts","../src/client/services.ts","../src/client/historyPage.ts","../src/shared/redline-route.ts","../src/client/timelineSource.ts","../src/shared/types.ts","../src/client/assemble.ts","../src/client/dna.ts","../src/shared/fileOps.ts","../src/client/callSummary.ts","../src/client/components/detailNote.tsx","../src/shared/redline-ability.ts","../src/client/components/redlineEdit.tsx","../src/shared/redline-errors.ts","../src/shared/redline-drafts.ts","../src/client/components/nodes.tsx","../src/client/overscroll.ts","../src/client/components/trendChart.tsx","../src/client/components/fetchOnMiss.tsx","../src/client/primitives.ts","../src/client/format.ts","../src/shared/imageTokens.ts","../src/client/components/images.tsx","../src/client/components/richText.tsx","../src/client/components/browser.tsx","../src/client/components/stackedBar.tsx","../src/client/components/currentComposition.tsx","../src/client/components/errorBoundary.tsx","../src/client/components/escapeClose.ts","../src/client/redlineChannel.ts","../src/client/redlineDrafts.ts","../src/client/components/contextModal.tsx","../src/client/settingsJump.ts","../src/client/components/settingsCard.tsx","../src/client/settings.ts","../src/client/brief.ts","../src/shared/redline-origins.ts","../src/shared/redline-capacity.ts","../src/client/childSessions.ts","../src/client/components/childCard.tsx","../src/client/components/events.tsx","../src/client/components/upgradeGate.tsx","../src/client/components/requestDetail.tsx","../src/client/components/statsContext.tsx","../src/client/sidebar.ts","../src/client/viewFocus.ts","../src/client/surfaceVisibility.ts","../src/client/revealScroll.ts","../src/client/components/contextView.tsx","../src/client/components/contextJump.tsx","../src/client/placement.ts","../src/client/viewkit.ts","../src/client/index.ts"],"sourcesContent":["/**\n * Bilingual dictionaries (zh/en) for every UI string; missing keys resolve\n * through the harness locale service (active → en → common → the key itself).\n */\n\nexport type Translate = (key: string, params?: Record<string, string | number>) => string\n\nexport const DICT_ZH: Record<string, string> = {\n 'tab': '上下文批改',\n 'sidebar.guideDescription': '查看上下文的构成、统计、演变。',\n 'cat.system': '系统提示词', 'cat.tools': '工具定义', 'cat.user': '用户消息',\n 'cat.inject': '注入内容', 'cat.skill': '技能注入', 'cat.assistant': '助手消息', 'cat.tool': '工具结果',\n 'overview.title': '当前上下文',\n 'overview.estimate': 'tokens(估算)',\n 'overview.free': '剩余窗口',\n 'overview.used': '上下文已用',\n 'overview.ofUsed': '占已用上下文',\n 'overview.compactReserve': '自动压缩预留:占用达 {pct}% 窗口时触发压缩,此区域一般不实际占用',\n 'stats.title': '上下文统计',\n 'stats.viewHint': '(当前视图:第 {t} 轮 · 第 {s} 步',\n 'stats.viewLive': ' · 当前)',\n 'stats.bmeta': '本步可见 {n} 条 · ≈{k} tokens',\n // S1.1:缺 token 的条数要说出来(不许把 ≈ 说成完整数字)。\n 'stats.missing': '(另有 {m} 条无 token,未计入)',\n 'stats.visibleItems': '模型可见条目',\n 'stats.shadowedNote': '(另 {n} 条被遮蔽)',\n 'stats.userMsgs': '用户消息',\n 'stats.injectItems': '注入内容',\n 'stats.cacheHit': '缓存命中',\n 'stats.cost': '费用',\n 'trend.title': '上下文趋势',\n 'gran.step': '步骤', 'gran.turn': '轮次',\n // 规模读数(docs/03 R1.5,与 demo 的 granLabel 同一句)\n 'trend.gran.turn': '按轮次(共 {n} 轮)',\n 'trend.gran.step': '按步骤(共 {n} 次请求)',\n 'settings.title': '上下文', 'settings.desc': 'dsh-context-redline 插件中上下文面板的偏好设置',\n 'settings.placement': '入口位置',\n 'placement.tab': '标签页', 'placement.sidebar': '侧边栏', 'placement.all': '全部',\n 'settings.gran': '趋势图 · 默认粒度',\n 'settings.mode': '趋势图 · 默认展示方式',\n 'settings.toolSort': '工具定义 · 默认排序',\n 'settings.fileSort': '文件活动 · 默认排序',\n 'settings.expand': '展开', 'settings.collapse': '收起',\n 'settings.readOnly': '当前环境的设置为只读',\n 'gran.total': '全量', 'gran.delta': '增量',\n 'gran.modeHint': '全量:累计构成;增量:相对上一条请求的变化量',\n 'trend.focus': '仅展示 {cat}',\n 'trend.adaptive': '自适应',\n 'trend.adaptiveHint': '按当前可视范围内的柱子重新缩放高度,滚动时随之变化',\n 'trend.empty': '发起一轮对话后,这里会展示每次模型请求的上下文构成',\n 'detail.step': '第 {t} 轮 · 第 {s} 步 (共 {n} 步)',\n 'detail.turn': '第 {t} 轮 · 共 {n} 步',\n 'detail.lastStep': '末步',\n 'detail.estTotal': '估算合计 ≈ {n}',\n 'detail.actual': '实际 {n}',\n 'detail.output': '输出 {n}',\n 'detail.cache': '缓存 {n}%',\n 'brief.turn': '本轮',\n 'brief.input': '输入',\n 'brief.reply': '回复',\n 'brief.more': '+{n}',\n 'brief.noInputs': '(无新增)',\n 'brief.locate': '在上下文浏览器中查看',\n 'jump.title': '在上下文视图中查看此轮',\n 'brief.turnTip': '这一轮开场时用户发送的消息;回合内的每一步都会回显同一条',\n 'brief.inputTip': '上一步回复之后、本次请求发出前新进入上下文的内容——通常是上一步所调工具的结果;每轮的第一步无新增',\n 'brief.replyTip': '这一步模型返回的内容(文本回复或工具调用);此步发起的调用,其结果会出现在下一柱的「输入」行',\n 'events.title': '上下文事件',\n 'events.empty': '暂无上下文事件(压缩、注入、模型切换会出现在这里)',\n 'events.at': '第 {t} 轮 · 第 {s} 步',\n 'events.range': '第 {t} 轮 · 第 {a}→{b} 步',\n 'events.rangeTo': '第 {a} 轮 · 第 {as} 步 → 第 {b} 轮 · 第 {bs} 步',\n 'kind.inject': '注入', 'kind.compaction': '压缩', 'kind.prune': '剪枝', 'kind.model': '切换', 'kind.mode': '模式',\n 'files.title': '文件活动',\n 'files.sort.count': '按次数', 'files.sort.latest': '按最新', 'files.sort.path': '按路径',\n 'loading': '正在读取会话日志…',\n 'detail.loading': '正在加载历史数据…',\n 'detail.loadFailed': '历史数据加载失败,点击重试',\n 'error': '上下文数据读取失败:',\n 'error.retry': '重试',\n 'gate.title': '请更新 DeepSeek Harness 版本',\n 'gate.body': 'dsh-context-redline 插件支持 DeepSeek Harness v{minimum} 或更新版本。',\n 'gate.current': '当前版本',\n 'gate.minimum': '最低要求',\n 'gate.orNewer': '及更新的版本',\n 'gate.ok': '知道了',\n 'footer': 'Token 数量统计:「估算」与 DeepSeek Harness 内置 tokenMeter 相同的固定密度启发式(约 4 字符 ≈ 1 token);「实际」为供应商上报用量。',\n 'tip.step': '第 {t} 轮 · 第 {s} 步 (共 {n} 步)',\n 'tip.turn': '第 {t} 轮 · 共 {n} 步',\n 'tip.turn1': '第 {t} 轮 · 共 1 步',\n 'tip.total': '合计 ≈ {n}',\n 'tip.cat': '{cat} ≈ {n}',\n 'tip.delta': 'Δ {n}',\n 'ev.compaction': '压缩上下文(摘要替换 {n} 条消息)',\n 'ev.prune': '剪枝工具输出',\n 'ev.skill': 'Skill 注入({name})',\n 'ev.model': '模型切换:{a} → {b}',\n 'ev.mode.plan.on': '进入计划模式', 'ev.mode.plan.off': '退出计划模式',\n 'form.instructions': '指令注入', 'form.catalog': '目录更新', 'form.snapshot': '状态快照',\n 'form.notice': '通知', 'form.relay': '代理转发', 'form.recall': '历史召回', 'form.context': '上下文注入',\n 'node.toolResult': '工具结果',\n 'node.calls': '调用 ',\n 'node.empty': '(空回复)',\n 'node.nonText': '(非文本消息)',\n 'node.snapshot': '快照: ',\n 'node.skillTag': '技能 · {name}',\n 'cmd.label': '上下文',\n 'cmd.section': '上下文',\n 'cmd.desc': '查看当前上下文构成,浏览各步骤组成',\n 'cmd.close': '关闭',\n 'browser.title': '上下文浏览器',\n // ── 编辑(当前 demo 的契约:docs/03 §2–§4 + docs/11 D15/D16/D17/D19/D20)──\n 'redline.edit': '编辑',\n 'redline.drop': '丢弃这条改动',\n // 「删除」(`docs/03` R4.8):这一条**不写进新会话**。只记在插件本地,当前会话一个字都不写。\n 'redline.exclude': '删除',\n 'redline.exclude.tip': '把这一条删掉:只记在插件本地,当前会话不受影响;开启新会话时,被删的条目不会出现在里面。你之前对它的修改会原样留着 —— 取消删除就能拿回来。',\n 'redline.unexclude': '取消删除',\n 'redline.unexclude.tip': '取消删除:这一条重新参与投递;如果你之前改过它,改后的正文会原样回来。',\n 'redline.excluded': '已删除',\n 'redline.excluded.tip': '这一条已被删除:它不会被写进新会话。取消删除可原样恢复(含你改过的正文)。',\n 'redline.local': '已改(本地)',\n 'redline.local.tip': '已保存在插件本地:当前会话的模型看不到。确认开启普通新会话时,改后的正文会逐字写进第一句话。',\n 'redline.advanced': '高级编辑',\n 'redline.advanced.tip': '工具结果的「编辑」属于高级编辑:打开顶部的「高级编辑」开关即可看到(避免几十条工具结果把常用动作淹掉)。',\n 'redline.reason.assistant': '旧日志不改;迁移副本可编辑',\n 'redline.reason.system': '宿主保护:改不了',\n 'redline.reason.shadowed': '已被接替',\n 'redline.reason.compacted': '被压缩埋掉了',\n 'redline.reason.other': '这一条改不了',\n 'redline.field.body': '正文',\n 'redline.field.thinking': '思考文本',\n 'redline.field.result': '结果文本',\n 'redline.field.isError': '标记为错误(isError)',\n 'redline.field.advanced': '高级:思考文本',\n 'redline.dest.local': '只写本地 · 确认开新会话时才带进去',\n 'redline.multiParagraph': '这条消息有多个文本段落;改写后会合并为一段。',\n 'redline.save': '保存',\n 'redline.save.tip': '只写插件本地(当前会话的模型看不到、会话日志不动)。同一行再次保存会覆盖这一条;确认开启普通新会话时才逐字带进第一句话。',\n 'redline.cancel': '取消(Esc)',\n 'child.title': '承载会话',\n 'child.bmeta': '活跃 {a} · 共 {n} 个',\n // 来源(M5-12):三态各自一句 —— 台账里有 / 没有 / 台账读不出来。**不猜**。\n 'child.src.own.carrier': '本项目发起 · 普通会话',\n 'child.src.own.official': '历史 · 官方成员',\n 'child.src.own.bare': '本项目发起 · 裸子会话',\n 'child.src.other': '不是在这儿开的',\n 'child.src.unknown': '来源未知',\n 'child.src.tip': '来源来自我们自己记的台账:官方那本子会话目录里只有 mode / label,没有来源字段(docs/01 F59)。「不是在这儿开的」只说明不是这个面板建的 —— 不猜是谁建的。',\n // 分母只在真读到上限时才写(M5-13);读不到就退回上一条,不编数字。\n 'child.spawn.head': '开新会话执行',\n 'child.spawn.hint': '批改后的上下文只会写进这个新会话',\n 'child.spawn.button': '开启新会话',\n 'child.spawn.note': '在当前工作区左侧新开一个零历史普通会话,只带你确认保留或修改的内容;删除项不会进去,任务结果会自动回到当前会话。',\n 'child.list.head': '承载会话',\n 'child.list.hint': '这个面板开启的普通会话 · 看状态与来源',\n 'child.empty': '(还没有承载会话)',\n 'child.mode.one-shot': '一次性',\n 'child.mode.continuable': '多轮',\n 'child.mode.unknown': '模式未知',\n 'child.state.running': '运行中',\n 'child.state.idle': '空闲',\n 'child.state.gone': '已结束',\n 'child.state.unloaded': '未加载',\n 'child.state.unknown': '状态未知',\n 'child.hint.running': '运行中:轮次闭合前只能看,不能改(要改就先等它空闲,或打断它)。',\n 'child.hint.idle': '空闲:用父会话页头右侧的「N 个子智能体」目录打开旧子会话。',\n 'child.hint.carrierIdle': '空闲:从左侧会话列表打开它,就能查看和继续批改它自己的上下文。',\n 'child.hint.gone': '这个历史子会话当前不在本进程里,只能查看。',\n 'child.hint.unloaded': '普通会话当前未加载;从左侧会话列表打开即可恢复。',\n 'child.hint.unknown': '读不到它的状态 —— 打开它之前先按\"只能查看\"打算。',\n 'child.confirm.metrics': '约 {bytes} 字节(UTF-8,含 {edits} 条本地改动)',\n 'child.confirm.title': '开启普通新会话',\n 'child.confirm.intro': '确认后会在当前工作区新开一个零历史普通会话,只写入下面逐字列出的迁移内容;删除项不进入。任务结束后,结果会原样自动回到当前会话。',\n 'child.confirm.preparing': '正在准备……',\n 'child.confirm.taskLabel': '首条任务',\n 'child.confirm.taskHint': '会成为普通新会话的第一句话;新会话模型可见,当前会话模型不可见。',\n 'child.confirm.taskPlaceholder': '一句话说清这次要它干什么。',\n 'child.confirm.modelLabel': '执行模型',\n 'child.confirm.effortDefault': '使用模型默认值',\n 'child.confirm.finalLabel': '最终发送全文',\n 'child.confirm.finalHint': '下面就是实际写入新会话的完整第一句话。可直接删段、改字或重排;确认后逐字冻结。',\n 'child.confirm.ok': '确认创建',\n 'child.confirm.cancel': '取消',\n 'redline.blocked.turnOpen': '当前轮次还没结束 —— 改动只能在轮次边界提交。',\n 'redline.blocked.notLive': '这个会话不在本进程里,只能查看,不能编辑。',\n 'redline.err.turn-open': '当前轮次还没结束 —— 改动只能在轮次边界提交',\n 'redline.err.no-change': '没有实质改动 —— 内容和上次保存的一模一样',\n 'redline.err.empty-content': '正文与思考文本不能同时为空',\n 'redline.err.not-live': '这个会话不在本进程里,只能查看,不能编辑',\n 'redline.err.transport': '保存没有送到宿主(网络或服务问题),你的输入还在',\n 'redline.err.bad-request': '这条改动的参数不合法(这是缺陷,请把这条报出来)',\n 'redline.err.internal': '宿主保存失败,你的输入还在',\n 'redline.err.unknown-op': '这一条请求宿主不认(多半是页面版本比插件旧):刷新页面再试',\n // 来源台账(M5-12):读不出来时要说**原因**,不许只写\"来源未知\"(错误码 → 人话)。\n 'redline.err.origin-corrupt': '本地那份「来源」台账读不出来(可能被手改过或写坏过)—— 删掉它就能重建;这只影响界面显示的来源,不影响任何会话',\n 'redline.err.origin-schema': '本地那份「来源」台账来自另一个版本的插件 —— 删掉它就能重建;不影响任何会话',\n 'redline.err.no-draft': '这一条还没有本地改动可丢',\n 'redline.err.empty-task': '子会话的第一句话必须由你自己写 —— 它要做什么不能替你决定',\n 'redline.err.no-subagents': '这台运行时没有可用的子会话服务:只能把改好的正文手动带过去',\n 'redline.err.child-start-unconfirmed': '子会话服务没有返回可核对的会话身份,所以没有把它说成已开启',\n 'redline.err.child-start-failed': '子会话没有创建成功(官方成员与备用路径都没能完成)—— 你的本地改动还在',\n 'redline.err.drafts-changed': '本地改动在确认后变了:请重新打开确认框,核对将要带入的新版本',\n 'redline.err.assistant-immutable': '助手消息在平台上无法改写(两条规则互斥):这一条不能作为目标',\n 'redline.err.unsupported-type': '这一类内容(系统提示词 / 工具定义等)由宿主保护,本插件不能改',\n 'redline.err.shadowed': '这一条已被后来的一条接替,已不在模型可见内容里',\n 'redline.err.not-found': '按这个位置找不到这一条(可能来自旧页面,或已被裁出窗口)',\n 'redline.err.draft-corrupt': '本地改动文件读不出来:它已损坏。可以丢弃本地改动后重试',\n 'redline.err.draft-schema': '本地改动文件的格式版本不认识(多半是升级/降级造成的)',\n 'redline.err.bad-range': '范围参数不完整或顺序反了',\n 'redline.err.history-unavailable': '这一版的历史原文在这台运行时上读不回来',\n 'redline.advancedToggle': '高级编辑',\n 'redline.advancedToggle.tip': '打开后,工具结果的「编辑」会出现(默认收起,避免几十条工具结果把常用动作淹掉)。',\n 'browser.live': '当前(下一次请求)',\n 'browser.liveNow': '当前 · 下一次请求',\n 'browser.items': '{n} 项',\n 'browser.missingLive': '… 另有 {n} 条更早的消息也在上下文中(超出展示窗口)',\n 'browser.approx': '该步骤涉及的部分已移除消息超出保留范围,以下为近似构成',\n // 对比基线(照参考插件 0.60.0 的 browser.base.* 逐字)与两级选择器(docs/03 R1.13)\n 'browser.base.step': '比前步',\n 'browser.base.turn': '比前轮',\n 'browser.base.tip': '变动对比的基线:比前步=与上一步对比;比前轮=与上一轮最后一步对比(首轮无基线,全部计为变动)',\n 'browser.turnPick': '第 {t} 轮(共 {n} 步)',\n 'browser.stepPick': '第 {s} 步(共 {n} 步)',\n 'browser.dna': 'DNA 模式',\n 'browser.dnaTip': '按模型读取上下文的次序逐条展示每一项:系统提示词、工具定义,然后是按时间排列的消息;悬停查看条目,点击定位到下方列表',\n 'browser.noHeader': '此数据来自旧版插件:仅提供 token 估算,无实际内容',\n 'browser.noEpoch': '该步骤的头部内容(系统提示词 / 工具定义)不在保留范围内',\n 'browser.headerMetaOnly': '此环境不支持按需读取头部内容,仅显示 token 估算',\n 'browser.noSystem': '该请求头部未包含系统提示词',\n 'browser.noContent': '完整内容不在当前加载的消息窗口内(在聊天页加载更早历史后可查看)',\n 'browser.search.user': '按消息内容过滤…',\n 'browser.search.inject': '按注入内容过滤…',\n 'browser.search.skill': '按技能过滤…',\n 'browser.search.assistant': '按回复或调用过滤…',\n 'browser.search.tool': '按工具或参数过滤…',\n 'browser.rowNoMatch': '没有匹配当前过滤条件的行',\n 'browser.loading': '正在从更早的会话历史加载完整内容…',\n 'browser.notInLog': '会话日志中未找到该条目的完整内容(可能已被压缩或清理)',\n 'browser.loadFailed': '内容加载失败,点击重试',\n 'tool.desc': '描述',\n 'tool.params': '参数',\n 'tool.paramsEmpty': '(无参数)',\n 'tool.plugin': '该工具的注册插件(仅供参考)',\n 'tool.unknown': '未知插件',\n 'tool.unknownTitle': '因早于上下文插件加载或原插件已卸载,无法查询该工具的提供者',\n 'tool.jsonToggle': '查看原始 JSON',\n 'tool.jsonHide': '收起',\n 'tool.search': '按名称、描述或参数过滤…',\n 'tool.sort.size': '按大小', 'tool.sort.count': '按次数', 'tool.sort.name': '按名称',\n 'tool.sortTip': '工具排序:按当前步骤中的调用次数(默认)、token 大小或名称',\n 'tool.hitsTip': '当前展示步骤的上下文中,该工具被调用并返回结果的次数',\n 'tool.noMatch': '没有匹配当前过滤条件的工具',\n 'rich.raw': '原文',\n 'rich.md': 'Markdown',\n 'rich.toMd': '按 Markdown 渲染查看',\n 'rich.toRaw': '查看原始文本',\n 'rich.copy': '复制原文', 'rich.copied': '已复制',\n 'rich.md.copy': '复制', 'rich.md.copied': '已复制',\n 'rich.md.footnotes': '脚注',\n 'block.thinking': '思考',\n 'block.answer': '回答',\n 'block.content': '内容', 'block.result': '结果', 'block.summary': '摘要',\n // Line-count chip on a tool-result's payload card (the singular/plural\n // split is a no-op in zh, where the measure word never inflects).\n 'block.line': '{n} 行', 'block.lines': '{n} 行',\n 'call.ok': '正常', 'call.fail': '失败', 'call.exit': 'exit {n}',\n 'node.failed': '工具执行失败',\n 'attach.images': '图片附件',\n 'attach.other': '其他内容',\n 'attach.image': '图片',\n 'attach.open': '查看原图',\n 'attach.preview': '图片预览',\n 'attach.close': '关闭',\n 'attach.loading': '…',\n 'attach.loadFailed': '加载失败 · 点击重试',\n 'attach.raw': '原图',\n 'attach.sent': '发送',\n 'attach.token': 'Token',\n 'attach.tokensTip': '按 DeepSeek 官方图片尺寸换算(单图上限 384 tokens)估算的 token 消耗',\n 'ov.entry': '上下文批改 · 洞察',\n 'ov.title': '上下文批改 · 洞察',\n}\n\nexport const DICT_EN: Record<string, string> = {\n 'tab': 'Context Redline',\n 'sidebar.guideDescription': 'Inspect context composition, stats, and evolution.',\n 'cat.system': 'System Prompt', 'cat.tools': 'Tool Schemas', 'cat.user': 'User Messages',\n 'cat.inject': 'Injected Context', 'cat.skill': 'Skill Injections', 'cat.assistant': 'Assistant Messages', 'cat.tool': 'Tool Results',\n 'overview.title': 'Current Context',\n 'overview.estimate': 'tokens (estimated)',\n 'overview.free': 'Free Window',\n 'overview.used': 'of context used',\n 'overview.ofUsed': 'of used context',\n 'overview.compactReserve': 'Auto-compaction reserve: auto-compaction triggers at {pct}% of the window — this area is normally kept as headroom, not actually used',\n 'stats.title': 'Context Stats',\n 'stats.viewHint': '(showing turn {t} · step {s}',\n 'stats.viewLive': ' · live)',\n 'stats.bmeta': '{n} items visible in this step · ≈{k} tokens',\n 'stats.missing': '({m} more have no token and are not counted)',\n 'stats.visibleItems': 'Model-visible items',\n 'stats.shadowedNote': ' ({n} more superseded)',\n 'stats.userMsgs': 'User messages',\n 'stats.injectItems': 'Injected items',\n 'stats.cacheHit': 'Cache Hit',\n 'stats.cost': 'Cost',\n 'trend.title': 'Context Trend',\n 'gran.step': 'Step', 'gran.turn': 'Turn',\n 'trend.gran.turn': 'By turn ({n} turns)',\n 'trend.gran.step': 'By step ({n} requests)',\n 'settings.title': 'Context', 'settings.desc': 'Preferences for Context panel in dsh-context-redline plugin',\n 'settings.placement': 'Entry Options',\n 'placement.tab': 'Tab', 'placement.sidebar': 'Sidebar', 'placement.all': 'All',\n 'settings.gran': 'Trend Chart · Default granularity',\n 'settings.mode': 'Trend Chart · Default display',\n 'settings.toolSort': 'Tool Schemas · Default sort',\n 'settings.fileSort': 'File Activity · Default sort',\n 'settings.expand': 'Expand', 'settings.collapse': 'Collapse',\n 'settings.readOnly': 'Settings are read-only in this environment',\n 'gran.total': 'Total', 'gran.delta': 'Delta',\n 'gran.modeHint': 'Total: cumulative makeup; Delta: change vs the previous request',\n 'trend.focus': 'Showing {cat} only',\n 'trend.adaptive': 'Adaptive',\n 'trend.adaptiveHint': 'Rescale bar heights to the visible range, following the scroll',\n 'trend.empty': 'Send a message and each model request’s context makeup shows up here',\n 'detail.step': 'Turn {t} · Step {s} of {n}',\n 'detail.turn': 'Turn {t} · {n} steps',\n 'detail.lastStep': 'Last Step',\n 'detail.estTotal': 'Estimated ≈ {n}',\n 'detail.actual': 'Actual {n}',\n 'detail.output': 'Output {n}',\n 'detail.cache': 'Cache {n}%',\n 'brief.turn': 'User',\n 'brief.input': 'In',\n 'brief.reply': 'Response',\n 'brief.more': '+{n}',\n 'brief.noInputs': '(nothing new)',\n 'brief.locate': 'Reveal in Context Browser',\n 'jump.title': 'View this turn in the Context view',\n 'brief.turnTip': 'The user message that opened this turn — every step of the turn recalls it',\n 'brief.inputTip': 'What entered after the previous reply and before this request went out — usually the previous tool-call results; a turn opener has nothing new',\n 'brief.replyTip': 'What the model returned on this step (a text reply or tool calls) — results of calls made here appear in the In row of the next bar',\n 'events.title': 'Context Events',\n 'events.empty': 'No context events yet (compaction, injections, model switches appear here)',\n 'events.at': 'Turn {t} · Step {s}',\n 'events.range': 'Turn {t} · Step {a}→{b}',\n 'events.rangeTo': 'Turn {a} · Step {as} → Turn {b} · Step {bs}',\n 'kind.inject': 'Inject', 'kind.compaction': 'Compact', 'kind.prune': 'Prune', 'kind.model': 'Switch', 'kind.mode': 'Mode',\n 'files.title': 'File Activity',\n 'files.sort.count': 'Most active', 'files.sort.latest': 'Latest', 'files.sort.path': 'By path',\n 'loading': 'Reading the session log…',\n 'detail.loading': 'Loading history…',\n 'detail.loadFailed': 'History failed to load — click to retry',\n 'error': 'Failed to read context data: ',\n 'error.retry': 'Retry',\n 'gate.title': 'Update DeepSeek Harness',\n 'gate.body': 'dsh-context-redline supports DeepSeek Harness v{minimum} or newer.',\n 'gate.current': 'Current',\n 'gate.minimum': 'Minimum required',\n 'gate.orNewer': 'or newer',\n 'gate.ok': 'Got it',\n 'footer': 'Token amount: “Estimated” uses the same fixed-density heuristic as DeepSeek Harness’s built-in tokenMeter (~4 chars ≈ 1 token); “Actual” is provider-reported usage.',\n 'tip.step': 'Turn {t} · Step {s} of {n}',\n 'tip.turn': 'Turn {t} · {n} steps',\n 'tip.turn1': 'Turn {t} · 1 step',\n 'tip.total': 'Total ≈ {n}',\n 'tip.cat': '{cat} ≈ {n}',\n 'tip.delta': 'Δ {n}',\n 'ev.compaction': 'Context compacted (summary replaced {n} messages)',\n 'ev.prune': 'Tool output pruned',\n 'ev.skill': 'Skill injected ({name})',\n 'ev.model': 'Model switched: {a} → {b}',\n 'ev.mode.plan.on': 'Plan mode on', 'ev.mode.plan.off': 'Plan mode off',\n 'form.instructions': 'Instructions', 'form.catalog': 'Catalog Update', 'form.snapshot': 'State Snapshot',\n 'form.notice': 'Notice', 'form.relay': 'Agent Relay', 'form.recall': 'Recall', 'form.context': 'Context Injection',\n 'node.toolResult': 'Tool Result',\n 'node.calls': 'Calls ',\n 'node.empty': '(empty reply)',\n 'node.nonText': '(non-text message)',\n 'node.snapshot': 'Snapshot: ',\n 'node.skillTag': 'Skill · {name}',\n 'cmd.label': 'Context',\n 'cmd.section': 'Context',\n 'cmd.desc': 'View current context makeup, browse per-step composition',\n 'cmd.close': 'Close',\n 'browser.title': 'Context Browser',\n 'redline.edit': 'Edit',\n 'redline.drop': 'Discard this change',\n 'redline.exclude': 'Delete',\n 'redline.exclude.tip': 'Delete this item: recorded in the plugin only, this session is unaffected; when you open the new session, deleted items are not in it. Any edit you made is kept — cancel the delete to get it back.',\n 'redline.unexclude': 'Cancel delete',\n 'redline.unexclude.tip': 'Cancel the delete: this item is carried again; if you had edited it, your edited text comes back exactly as it was.',\n 'redline.excluded': 'Deleted',\n 'redline.excluded.tip': 'This item is deleted: it will not be written into the new session. Cancel the delete to restore it exactly (including your edited text).',\n 'redline.local': 'Edited (local)',\n 'redline.local.tip': 'Saved in the plugin only: this session\\'s model cannot see it. Confirmation carries the edited text verbatim into the ordinary new session\\'s first message.',\n 'redline.advanced': 'Advanced editing',\n 'redline.advanced.tip': 'Editing a tool result is an advanced action: turn on the Advanced editing switch at the top to see it (dozens of tool results would otherwise bury the common actions).',\n 'redline.reason.assistant': 'Old log stays unchanged; the migration copy is editable',\n 'redline.reason.system': 'Host-protected',\n 'redline.reason.shadowed': 'Superseded',\n 'redline.reason.compacted': 'Buried by compaction',\n 'redline.reason.other': 'Cannot be edited',\n 'redline.field.body': 'Body',\n 'redline.field.thinking': 'Thinking text',\n 'redline.field.result': 'Result text',\n 'redline.field.isError': 'Mark as an error (isError)',\n 'redline.field.advanced': 'Advanced: thinking text',\n 'redline.dest.local': 'Local only · carried after you confirm a new session',\n 'redline.multiParagraph': 'This message has several text paragraphs; a rewrite merges them into one.',\n 'redline.save': 'Save',\n 'redline.save.tip': 'Writes the plugin\\'s local store only (this session\\'s model cannot see it, the log is untouched). Saving again overwrites that row; confirmation carries it verbatim into the ordinary new session\\'s first message.',\n 'redline.cancel': 'Cancel (Esc)',\n 'child.title': 'Carrier sessions',\n 'child.bmeta': '{a} active · {n} total',\n 'child.src.own.carrier': 'Started here · ordinary session',\n 'child.src.own.official': 'Legacy · official member',\n 'child.src.own.bare': 'Started here · bare child',\n 'child.src.other': 'Not started here',\n 'child.src.unknown': 'Origin unknown',\n 'child.src.tip': 'Origin comes from our own ledger: the official child catalog carries only mode / label and no origin field (docs/01 F59). \"Not started here\" only means this panel did not create it - we do not guess who did.',\n 'child.spawn.head': 'Run in a new session',\n 'child.spawn.hint': 'Only the confirmed redlined context is written there',\n 'child.spawn.button': 'Open new session',\n 'child.spawn.note': 'Open a zero-history ordinary session in this workspace, carrying only content you kept or edited. Deleted items stay out, and the final result returns here automatically.',\n 'child.list.head': 'Carrier sessions',\n 'child.list.hint': 'Ordinary sessions opened by this panel · state and source',\n 'child.empty': '(no carrier sessions yet)',\n 'child.mode.one-shot': 'one-shot',\n 'child.mode.continuable': 'continuable',\n 'child.mode.unknown': 'mode unknown',\n 'child.state.running': 'running',\n 'child.state.idle': 'idle',\n 'child.state.gone': 'finished',\n 'child.state.unloaded': 'not loaded',\n 'child.state.unknown': 'state unknown',\n 'child.hint.running': 'Running: you can look until its turn closes, but not edit (wait for it to go idle, or interrupt it).',\n 'child.hint.idle': 'Idle: open a legacy child from the parent header\\'s “N subagents” directory.',\n 'child.hint.carrierIdle': 'Idle: open this ordinary session from the left session list to inspect or redline its context.',\n 'child.hint.gone': 'This legacy child session is not live in this process: view only.',\n 'child.hint.unloaded': 'This ordinary session is not loaded; open it from the left session list to resume it.',\n 'child.hint.unknown': 'Its state could not be read — assume view only until you open it.',\n 'child.confirm.metrics': 'about {bytes} bytes (UTF-8, carrying {edits} local edits)',\n 'child.confirm.title': 'Open an ordinary new session',\n 'child.confirm.preparing': 'Preparing…',\n 'child.confirm.intro': 'Confirmation opens a zero-history ordinary session in this workspace. Only the migration content listed below is written there; deleted items stay out. The final result returns here verbatim.',\n 'child.confirm.taskLabel': 'First task',\n 'child.confirm.taskHint': 'It becomes the ordinary new session\\'s first message; that model sees it, this session\\'s model does not.',\n 'child.confirm.taskPlaceholder': 'One sentence saying what this session should do.',\n 'child.confirm.modelLabel': 'Execution model',\n 'child.confirm.effortDefault': 'Use model default',\n 'child.confirm.finalLabel': 'Final message to send',\n 'child.confirm.finalHint': 'This is the exact first user message written to the new session. Delete, edit, or reorder freely; confirmation freezes these bytes.',\n 'child.confirm.ok': 'Create it',\n 'child.confirm.cancel': 'Cancel',\n 'redline.blocked.turnOpen': 'This turn has not finished — edits can only be committed on a turn boundary.',\n 'redline.blocked.notLive': 'This session is not live in this process: view only, no editing.',\n 'redline.err.turn-open': 'This turn has not finished — edits can only be committed on a turn boundary',\n 'redline.err.no-change': 'Nothing substantive changed — this is identical to what is already in effect',\n 'redline.err.empty-content': 'The body and the thinking text cannot both be empty',\n 'redline.err.not-live': 'This session is not live in this process: view only, no editing',\n 'redline.err.transport': 'The save did not reach the host (network or service): your input is kept',\n 'redline.err.bad-request': 'The save arguments were invalid (this is a defect — please report it)',\n 'redline.err.internal': 'The host failed to save; your input is kept',\n 'redline.err.unknown-op': 'The host does not know this request (the page is probably older than the plugin): reload and retry',\n 'redline.err.origin-corrupt': 'The local origin ledger cannot be read (hand-edited or written badly) - deleting it rebuilds it; this only affects the origin shown in the UI, never a session',\n 'redline.err.origin-schema': 'The local origin ledger comes from another plugin version - deleting it rebuilds it; no session is affected',\n 'redline.err.no-draft': 'There is no local edit on this row to discard',\n 'redline.err.empty-task': 'The first task must be written by you — the plugin cannot decide what the child does',\n 'redline.err.no-subagents': 'This runtime exposes no child-session service: carry the edited text over by hand',\n 'redline.err.child-start-unconfirmed': 'The child-session service returned no verifiable session identity, so it is not reported as started',\n 'redline.err.child-start-failed': 'The child session was not created (neither the official-member nor fallback path completed); your local edits remain',\n 'redline.err.drafts-changed': 'Local edits changed after this confirmation was prepared: reopen it and review the current version',\n 'redline.err.assistant-immutable': 'An assistant message cannot be rewritten on this platform (two rules are mutually exclusive)',\n 'redline.err.unsupported-type': 'This kind of content (system prompt / tool definitions) is host-protected and cannot be edited here',\n 'redline.err.shadowed': 'A later item superseded this one, so it is no longer part of what the model sees',\n 'redline.err.not-found': 'Nothing is at that position (an older page, or the row fell out of the window)',\n 'redline.err.draft-corrupt': 'The local edit file cannot be read: it is corrupt. Discard the local edits and retry',\n 'redline.err.draft-schema': 'The local edit file has a format version this build does not know',\n 'redline.err.bad-range': 'The range arguments were incomplete or reversed',\n 'redline.err.history-unavailable': 'The full text of that version cannot be read back on this runtime',\n 'redline.advancedToggle': 'Advanced editing',\n 'redline.advancedToggle.tip': 'Turn on to reveal Edit on tool results (hidden by default so dozens of tool results cannot bury the common actions).',\n 'browser.live': 'Live (Next Request)',\n 'browser.liveNow': 'Live · Next Request',\n 'browser.items': '{n} Items',\n 'browser.missingLive': '… {n} earlier messages are also part of the context (outside the served window)',\n 'browser.approx': 'Some removed messages of this step exceed retention — the makeup below is approximate',\n 'browser.base.step': 'vs. previous step',\n 'browser.base.turn': 'vs. previous turn',\n 'browser.base.tip': 'Baseline for the change markers: vs. previous step (what this step added or dropped) or vs. the previous turn\\'s last step (how this turn moved as a whole). The first turn has no baseline, so everything counts as a change.',\n 'browser.turnPick': 'Turn {t} ({n} steps)',\n 'browser.stepPick': 'Step {s} of {n}',\n 'browser.dna': 'DNA Mode',\n 'browser.dnaTip': 'One band per item in the order the model reads the context — system prompt, tool schemas, then messages chronologically; hover for details, click to open its row below',\n 'browser.noHeader': 'Served by an older plugin build: token estimates only, no content',\n 'browser.noEpoch': 'The header content (System Prompt / Tool Schemas) of this step is outside retention',\n 'browser.headerMetaOnly': 'This environment cannot fetch header content on demand; token estimates only',\n 'browser.noSystem': 'This request header carried no system prompt',\n 'browser.noContent': 'Full content is outside the loaded message window (load older history in Chat to view)',\n 'browser.search.user': 'Filter by message text…',\n 'browser.search.inject': 'Filter injected context…',\n 'browser.search.skill': 'Filter skills…',\n 'browser.search.assistant': 'Filter by reply or calls…',\n 'browser.search.tool': 'Filter by tool or arguments…',\n 'browser.rowNoMatch': 'No rows match the current filter',\n 'browser.loading': 'Loading full content from older session history…',\n 'browser.notInLog': 'This item is not in the session log anymore (it may have been compacted away or cleared)',\n 'browser.loadFailed': 'Load failed — click to retry',\n 'tool.desc': 'Description',\n 'tool.params': 'Parameters',\n 'tool.paramsEmpty': '(no parameters)',\n 'tool.plugin': 'The registering plugin of this tool (for reference)',\n 'tool.unknown': 'Unknown plugin',\n 'tool.unknownTitle': 'The tool was registered before the context plugin loaded, or its plugin has been unloaded, so its provider cannot be determined',\n 'tool.jsonToggle': 'View Raw JSON',\n 'tool.jsonHide': 'Collapse',\n 'tool.search': 'Filter by name, description, or parameters…',\n 'tool.sort.size': 'By size', 'tool.sort.count': 'By calls', 'tool.sort.name': 'By name',\n 'tool.sortTip': 'Sort tools by call count in the shown step (default), token size, or name',\n 'tool.hitsTip': 'Times this tool was called and answered within the shown step’s context',\n 'tool.noMatch': 'No tools match the current filter',\n 'rich.raw': 'Raw',\n 'rich.md': 'Markdown',\n 'rich.toMd': 'View as Markdown',\n 'rich.toRaw': 'View Raw Text',\n 'rich.copy': 'Copy Raw Text', 'rich.copied': 'Copied',\n 'rich.md.copy': 'Copy', 'rich.md.copied': 'Copied',\n 'rich.md.footnotes': 'Footnotes',\n 'block.thinking': 'Reasoning',\n 'block.answer': 'Response',\n 'block.content': 'Content', 'block.result': 'Result', 'block.summary': 'Summary',\n 'block.line': '1 line', 'block.lines': '{n} lines',\n 'call.ok': 'OK', 'call.fail': 'Failed', 'call.exit': 'exit {n}',\n 'node.failed': 'Tool execution failed',\n 'attach.images': 'Images',\n 'attach.other': 'Other content',\n 'attach.image': 'Image',\n 'attach.open': 'Open full image',\n 'attach.preview': 'Image preview',\n 'attach.close': 'Close',\n 'attach.loading': '…',\n 'attach.loadFailed': 'Load failed · click to retry',\n 'attach.raw': 'Raw',\n 'attach.sent': 'Sent',\n 'attach.token': 'Token',\n 'attach.tokensTip': 'Estimated token cost via DeepSeek\\'s official image-size conversion (384-token cap per image)',\n 'ov.entry': 'Context Redline · Insights',\n 'ov.title': 'Context Redline · Insights',\n}\n","export default \"<svg xmlns=\\\"http://www.w3.org/2000/svg\\\" viewBox=\\\"0 0 1024 1024\\\"><!-- Original artwork for dsh-context-redline (MIT). Not derived from the dsh-context icon: this is a redline-on-context-rows motif drawn for this fork. -->\\n <path d=\\\"M109 168H109A13 13 0 0 1 122 181V843A13 13 0 0 1 109 856H109A13 13 0 0 1 96 843V181A13 13 0 0 1 109 168Z\\\" fill=\\\"#7C5CD6\\\"/>\\n <path d=\\\"M206 168H898A30 30 0 0 1 928 198V230A30 30 0 0 1 898 260H206A30 30 0 0 1 176 230V198A30 30 0 0 1 206 168Z\\\" fill=\\\"#5B6478\\\"/>\\n <path d=\\\"M206 300H746A30 30 0 0 1 776 330V362A30 30 0 0 1 746 392H206A30 30 0 0 1 176 362V330A30 30 0 0 1 206 300Z\\\" fill=\\\"#4F63C8\\\"/>\\n <path d=\\\"M206 432H850A30 30 0 0 1 880 462V494A30 30 0 0 1 850 524H206A30 30 0 0 1 176 494V462A30 30 0 0 1 206 432Z\\\" fill=\\\"#E0A32E\\\"/>\\n <path d=\\\"M206 564H666A30 30 0 0 1 696 594V626A30 30 0 0 1 666 656H206A30 30 0 0 1 176 626V594A30 30 0 0 1 206 564Z\\\" fill=\\\"#2FA3A0\\\"/>\\n <path d=\\\"M206 696H818A30 30 0 0 1 848 726V758A30 30 0 0 1 818 788H206A30 30 0 0 1 176 758V726A30 30 0 0 1 206 696Z\\\" fill=\\\"#D0342C\\\"/>\\n <path d=\\\"M206 828H506A30 30 0 0 1 536 858V890A30 30 0 0 1 506 920H206A30 30 0 0 1 176 890V858A30 30 0 0 1 206 828Z\\\" fill=\\\"#5B6478\\\"/>\\n <path d=\\\"M225 877L871 372L899 375L899 375L895 403L249 908L221 905L221 905Z\\\" fill=\\\"#D0342C\\\"/>\\n <path d=\\\"M794 372H824A24 24 0 0 1 848 396V426A24 24 0 0 1 824 450H794A24 24 0 0 1 770 426V396A24 24 0 0 1 794 372Z\\\" fill=\\\"#D0342C\\\"/>\\n <path d=\\\"M250 974a46 46 0 1 0 92 0 46 46 0 1 0-92 0Z\\\" fill=\\\"#7C5CD6\\\"/>\\n</svg>\\n\"","/**\n * The Context emblem: the colourful document sheet, bundled rather than read\n * off the harness primitives so the plugin's identity is self-contained.\n *\n * The single graphic source is the package-root `icon.svg` — the same file\n * package.json `icon` hands to the Host's package-meta reader, which serves\n * it to the Plugins page's package cards. The client bundle inlines the\n * file's markup at build time (the `?raw` channel in tsdown.config.ts) and\n * re-renders it at every requested size. Fixed fills, never `currentColor` —\n * the sheet is deliberately polychrome on both light and dark chrome.\n */\n\nimport sheetMarkup from '../../icon.svg?raw'\nimport type { ReactElement } from 'react'\nimport type { Translate } from './i18n'\n\n/** Everything between the file's `<svg>` tags: the sheet's strokes in paint order, whitespace-folded. */\nconst SHEET_MARKUP = sheetMarkup\n .slice(sheetMarkup.indexOf('>') + 1, sheetMarkup.lastIndexOf('</svg>'))\n .trim()\n .replace(/>\\s+</g, '><')\n\n/** The emblem's props, matching the harness `IconProps` the guide capsule hands it. */\nexport interface ContextIconProps {\n /** Square edge in px. */\n size?: number\n /** Extra class for layout placement. */\n className?: string\n}\n\n/** The colourful document sheet at the requested square edge. */\nexport function ContextIcon({ size = 20, className }: ContextIconProps): ReactElement {\n return (\n <svg\n width={size}\n height={size}\n viewBox=\"0 0 1024 1024\"\n className={className}\n aria-hidden=\"true\"\n xmlns=\"http://www.w3.org/2000/svg\"\n dangerouslySetInnerHTML={{ __html: SHEET_MARKUP }}\n />\n )\n}\n\n/**\n * The tab chip's title seat (`sidebar.right.pane.tab.title`): the emblem before\n * the label, so the chip reads as the files chip does. The label comes from the\n * plugin's own bound translate — read at render, so the chip follows the active\n * locale — rather than the tab-information hook, which a foreign or\n * not-yet-committed tab record can throw on. It carries a trailing gutter\n * (`.redline-title-label`) so the active chip's fade lands past the text, never on\n * the last glyphs.\n * @param t - the plugin-namespace translate bound in `apply`.\n * @returns the title component to register under the tab type's id.\n */\nexport function makeContextTabTitle(t: Translate): () => ReactElement {\n return function ContextTabTitle(): ReactElement {\n return (\n <>\n <ContextIcon size={16} className=\"redline-title-icon\" />\n <span className=\"redline-title-label\">{t('tab')}</span>\n </>\n )\n }\n}\n","/**\n * Per-session open-state stores for the /redline modal, plus the deferred\n * token-consume guards. Module-level so the state survives overlay remounts;\n * the trigger source (pick/enter) opens it, the overlay component subscribes\n * and renders. Implements the ObservableSnapshot pair the slot `hooks`\n * compartment binds as a `useContextModal` selector hook.\n */\n\nimport type { TokenSpan } from './services'\n\nexport interface ModalStore {\n subscribe(listener: () => void): () => void\n getSnapshot(): boolean\n set(open: boolean): void\n}\n\nconst stores = new Map<string, ModalStore>()\n\nexport function modalStoreOf(sessionId: string): ModalStore {\n const existing = stores.get(sessionId)\n if (existing !== undefined) return existing\n let open = false\n const listeners = new Set<() => void>()\n const store: ModalStore = {\n subscribe(listener) {\n listeners.add(listener)\n return () => { listeners.delete(listener) }\n },\n getSnapshot: () => open,\n set(next) {\n if (next === open) return\n open = next\n for (const listener of listeners) listener()\n },\n }\n stores.set(sessionId, store)\n return store\n}\n\n// ---- deferred token consumption -------------------------------------------\n// The `/redline` token stays in the composer while the modal is open and is\n// consumed only when the modal closes. Each open path records the guard the\n// input shell understands (span CAS for menu picks, bare-token equality for\n// enter); the close path takes it and dispatches the scoped\n// `slash/input-consume-token` event. A stale guard (the user typed meanwhile)\n// fails soft inside the shell — the draft is left untouched.\n\nexport type ConsumeGuard =\n | { kind: 'span'; span: TokenSpan }\n | { kind: 'bare-token'; token: string }\n\nconst pendingConsume = new Map<string, ConsumeGuard>()\n\nexport function setPendingConsume(sessionId: string, guard: ConsumeGuard): void {\n pendingConsume.set(sessionId, guard)\n}\n\nexport function takePendingConsume(sessionId: string): ConsumeGuard | undefined {\n const guard = pendingConsume.get(sessionId)\n if (guard !== undefined) pendingConsume.delete(sessionId)\n return guard\n}\n","/**\n * `/redline` — a client-owned slash command that opens the context modal\n * (current composition + recent trend) in the center of the page.\n *\n * Implemented as the plugin's own '/' trigger source instead of a host\n * command: nothing is dispatched to the host, no session log records are\n * written, and nothing becomes model-visible — the invocation never enters\n * the message history. Both paths answer `'handled'` and open the modal,\n * leaving the `/redline` token in the composer while it is open; the modal's\n * close path consumes the token then (see modalStore.ts).\n */\n\nimport { ContextIcon } from './icon'\nimport { modalStoreOf, setPendingConsume } from './modalStore'\nimport type { ClientCtx, InputTriggersFace } from './services'\nimport type { ViewKit } from './viewkit'\n\nconst COMMAND = 'redline'\nconst LINE = '/' + COMMAND\n\nexport function registerContextCommand(ctx: ClientCtx, kit: ViewKit): void {\n // Wait for the SERVICE, not for module arrival order: dsh composes\n // the client from finer modules, so `inputTriggers` may not be provided\n // yet when this plugin applies. A harness without the service never fires\n // the callback — the tab keeps working and only the command is absent.\n ctx.inject(['inputTriggers'], (ictx) => {\n const inputTriggers = (ictx as ClientCtx).get('inputTriggers') as InputTriggersFace | undefined\n if (inputTriggers === undefined || typeof inputTriggers.registerSource !== 'function') return\n ictx.effect(() => inputTriggers.registerSource({\n trigger: '/',\n name: COMMAND,\n order: 1,\n candidates: (_session, req) => {\n if (req.position !== 'leading') return Promise.resolve([])\n const query = req.query.trim().toLowerCase()\n if (query !== '' && !COMMAND.startsWith(query)) return Promise.resolve([])\n // A sectioned candidate replaces the menu's source-title row, which\n // otherwise renders the raw, unlocalizable source name (`context` is\n // not a key of the harness's own slash.menu dictionary). Label and\n // glyph are pure display data: builds that predate their rendering\n // keep showing the bare name.\n return Promise.resolve([{\n name: COMMAND,\n label: kit.t('cmd.label'),\n icon: ContextIcon,\n section: kit.t('cmd.section'),\n description: kit.t('cmd.desc'),\n }])\n },\n onPick: (pick) => {\n // Open and remember the token span: the modal's close path consumes\n // it (span CAS — a draft changed meanwhile is left untouched).\n setPendingConsume(pick.session.sessionId, { kind: 'span', span: pick.span })\n modalStoreOf(pick.session.sessionId).set(true)\n return 'handled'\n },\n matchEnter: (session, line) => {\n if (line !== LINE) return Promise.resolve(undefined)\n setPendingConsume(session.sessionId, { kind: 'bare-token', token: LINE })\n modalStoreOf(session.sessionId).set(true)\n return Promise.resolve<'handled'>('handled')\n },\n }), 'dsh-context-redline: /redline command')\n })\n}\n","/**\n * The /redline modal's dock inset: the width of the shell's sidebar track, so the fixed backdrop can start at the sidebar's right edge and\n * center the dialog over the main column instead of the whole viewport. The only host anchor is the app frame's inline grid template\n * (`<sidebar>px …` — the sidebar-leading px track is the one contract every\n * supported baseline shares; the center/right tracks' spellings differ per\n * generation) found by walking up from the backdrop. Anything unresolved — no\n * frame, unparsable template, a hostile node in the chain —\n * degrades to a 0 inset, the full-viewport mask.\n */\n\n/** The dock measure for one backdrop position: the mask inset and the frame to observe for template rewrites. */\nexport interface DockMeasure {\n /** Mask inset from the viewport's left edge, in px (0 = full-viewport mask). */\n left: number\n /** The element owning the inline grid template; null when unresolved (nothing to observe). */\n frame: HTMLElement | null\n}\n\nconst LEADING_PX_TRACK = /^(\\d+(?:\\.\\d+)?)px/\n\n/** Measure the sidebar track width from the backdrop's ancestor chain, or resolve to the full-viewport mask. */\nexport function measureDock(start: HTMLElement | null): DockMeasure {\n try {\n for (let el = start?.parentElement ?? null; el !== null; el = el.parentElement) {\n const template = el.style.gridTemplateColumns\n if (template === '') continue\n const track = LEADING_PX_TRACK.exec(template.trim())\n if (track === null) return { left: 0, frame: null }\n return { left: Number(track[1]), frame: el }\n }\n } catch { /* a hostile node in the chain degrades to the full-viewport mask */ }\n return { left: 0, frame: null }\n}\n","/**\n * Category presentation config: the seven priced buckets (system, tool\n * schemas, and the five surface categories) with their chart colors, plus\n * the part builders behind the composition card.\n *\n * Two figures ride on every part, mirroring the official chat context\n * meter's own split: `raw` is the heuristic count (the meter panel's `~`\n * rows — identical to the ring panel by construction when the official\n * `contextBreakdown` projection feeds it), while `value` is the\n * provider-anchored bar width (the ring's fill proportioned by the\n * heuristic ratios). Without a provider anchor the two are equal.\n */\n\nimport type { Category, ContextBreakdown, RequestRecord, Snapshot, TokenUsage } from '../shared/types'\n\nexport interface PartsPart {\n key: string\n color: string\n /** Bar-width figure (provider-anchored when an anchor applies). */\n value: number\n /** Heuristic count shown by the legend and tooltips (defaults to value). */\n raw?: number\n /** Tooltip display name (defaults to the category label of `key`) — DNA mode names individual items. */\n label?: string\n /** Shared-hover group: an incoming hover key equal to a part's group lights it (DNA bands light per category). */\n group?: string\n}\n\nexport const CATS: { key: Category | 'system' | 'tools'; color: string }[] = [\n { key: 'system', color: 'var(--redline-color-indigo-500)' },\n { key: 'tools', color: 'var(--redline-color-amber-500)' },\n { key: 'user', color: 'var(--redline-color-green-500)' },\n { key: 'inject', color: 'var(--redline-color-purple-500)' },\n { key: 'skill', color: 'var(--redline-color-orange-500)' },\n { key: 'assistant', color: 'var(--redline-color-blue-500)' },\n { key: 'tool', color: 'var(--redline-color-teal-500)' },\n]\n\n/** Category key → bar color, for per-item bands (the browser's DNA mode) that bypass the CATS-order part builders. */\nexport const CAT_COLOR = Object.fromEntries(CATS.map(c => [c.key, c.color])) as Record<Category | 'system' | 'tools', string>\n\nconst MESSAGE_CATS: readonly (Category | 'system' | 'tools')[] = ['user', 'inject', 'skill', 'assistant', 'tool']\n\nexport function partsOf(breakdown: Snapshot['current'] | RequestRecord): PartsPart[] {\n return CATS.map((c) => {\n return { key: c.key, color: c.color, value: breakdown[c.key] || 0 }\n })\n}\n\n/**\n * Build the pie-consistent raw parts: system/tools/messages take the\n * OFFICIAL `contextBreakdown` figures when delivered (the exact counts the\n * chat ring's panel shows), with the message bucket subdivided into the\n * four surface categories by the fold's per-category ratios (rounding\n * residue lands on the largest category, so the four always sum exactly to\n * the official message figure). Absent the projection, the fold's own sums\n * serve — the same fixed estimator, so identical on image-free sessions.\n */\nexport function officialParts(\n current: Snapshot['current'],\n breakdown: ContextBreakdown | null,\n): PartsPart[] {\n const foldSurface = current.user + current.inject + current.skill + current.assistant + current.tool\n const system = breakdown?.systemTokens ?? current.system\n const tools = breakdown?.toolsTokens ?? current.tools\n const messages = breakdown?.messageTokens ?? foldSurface\n const shares: Record<string, number> = { system, tools }\n if (foldSurface > 0) {\n let assigned = 0\n let largest: Category = 'user'\n for (const cat of MESSAGE_CATS) {\n const count = Math.round(messages * (current[cat as Category] / foldSurface))\n shares[cat] = count\n assigned += count\n if (current[cat as Category] > current[largest]) largest = cat as Category\n }\n // Rounding residue lands on the largest category; clamp so a tiny\n // message bucket with several rounded-up shares never goes negative.\n shares[largest] = Math.max(0, shares[largest] + messages - assigned)\n } else {\n for (const cat of MESSAGE_CATS) shares[cat] = 0\n }\n return CATS.map(c => ({\n key: c.key,\n color: c.color,\n /* v8 ignore next 1 -- `shares` is initialized with system/tools and both\n foldSurface arms assign every MESSAGE_CATS key, so each key is always\n defined; the fallback is defensive. */\n value: shares[c.key] ?? 0,\n }))\n}\n\n/**\n * Reproportion heuristic parts so they sum to a provider-anchored target —\n * the same trick the official ContextMeter uses: the heuristic breakdown\n * supplies the composition RATIOS, the provider sample the total. The\n * anchored figure rides `value` (bar widths); the heuristic count stays on\n * `raw` for the legend and tooltips. Returns the parts unchanged when no\n * anchor applies.\n */\nexport function anchoredParts(parts: PartsPart[], target: number | null): PartsPart[] {\n const sourced = parts.map(p => ({ ...p, raw: p.raw ?? p.value }))\n if (target === null || target <= 0) return sourced\n let total = 0\n for (const p of sourced) total += p.raw\n if (total <= 0) return sourced\n if (total === target) return sourced.map(p => ({ ...p, value: p.raw }))\n const scale = target / total\n return sourced.map(p => ({ ...p, value: Math.round(p.raw * scale) }))\n}\n\n/**\n * The Token card's billed split, by WHAT the tokens are rather than by how\n * the provider cached them: the six composition categories share the\n * provider-reported prompt-side total (uncached + cache read + cache write —\n * the chat stats line's billed input) by the composition card's own\n * estimated ratios, and the provider's exact output count closes the ring as\n * the seventh part. Only the per-category split is estimated — every\n * category's sum and the output figure are provider-reported, so the parts\n * total equals the chat line's whole-session token count by construction. A\n * zero/negative prompt total (or a hostile negative output) never invents a\n * split: the prompt parts zero out / the output clamps at 0.\n */\nexport function billedParts(\n current: Snapshot['current'],\n breakdown: ContextBreakdown | null,\n usage: TokenUsage,\n): PartsPart[] {\n const input = usage.uncachedInputTokens + usage.cacheReadTokens + usage.cacheWriteTokens\n const estimated = officialParts(current, breakdown)\n const prompt = input > 0\n ? anchoredParts(estimated, input)\n : estimated.map(p => ({ ...p, value: 0 }))\n return [...prompt, { key: 'output', color: 'var(--redline-color-pink-500)', value: Math.max(0, usage.outputTokens) }]\n}\n","/**\n * Provider-anchored headline derivation, shared by the Context tab and the\n * /redline popup: the best-known occupancy of the next request, the route\n * capacity it scales against, and the composition parts anchored to that\n * total (heuristic ratios, provider-anchored sum).\n *\n * Two official token-meter projections feed it, the same keys the chat's\n * composer ring reads: `contextPressure` supplies the anchored total (the\n * ring's percentage), and `contextBreakdown` supplies the composition\n * counts (the ring panel's system/tools/messages `~` rows) so the legend\n * figures stay identical to the panel's by construction. Either key absent\n * (older harness, meter not composed) degrades to the fold's own sums —\n * the same fixed estimator.\n */\n\nimport type { ContextBreakdown, ContextPressure, ContextTimeline } from '../shared/types'\nimport { anchoredParts, officialParts, type PartsPart } from './categories'\n\nexport interface Headline {\n /** Best-known occupancy of the next request (projected ?? derived ?? heuristic total). */\n tokens: number\n window?: number\n /** tokens / window, clamped to 100; null without a window. */\n pct: number | null\n /**\n * Composition parts: `value` is the provider-anchored bar width (the\n * ring's fill), `raw` the official heuristic count (the ring panel's\n * rows) shown by the legend and tooltips.\n */\n parts: PartsPart[]\n}\n\nexport function headlineOf(\n data: ContextTimeline,\n pressure: ContextPressure | null = null,\n breakdown: ContextBreakdown | null = null,\n): Headline {\n const current = data.current\n // The official projection's whole value is the newest usage sample carried\n // forward by the heuristic surface movement since it was taken — the same\n // formula the chat ring displays. Fields are last-wins; absent until a\n // provider reports usage.\n const projected = pressure !== null && typeof pressure.projectedTokens === 'number'\n ? pressure.projectedTokens\n : undefined\n // Fallback anchor: the newest request's provider prompt plus the heuristic\n // surface movement since it was logged (same shape as the projection, one\n // request behind). The split-generation wire head carries that record's\n // billing summary as `last` (the request records ride the detail channel);\n // the inline generation reads its newest record directly.\n const last = data.last\n const requests = data.requests\n const lastReq = requests.length > 0 ? requests[requests.length - 1] : null\n const anchor = last !== undefined ? last : lastReq\n const derived = anchor !== null && typeof anchor.prompt === 'number'\n ? anchor.prompt + (current.total - anchor.total)\n : undefined\n const occupancyTokens = projected ?? derived ?? null\n const window = pressure !== null && typeof pressure.contextWindow === 'number'\n ? pressure.contextWindow\n : data.contextWindow\n const tokens = occupancyTokens ?? current.total\n const pct = window !== undefined && window > 0 ? Math.min(100, Math.round(tokens / window * 100)) : null\n const parts = anchoredParts(\n officialParts(current, breakdown),\n occupancyTokens !== null && tokens > 0 ? tokens : null,\n )\n return { tokens, window, pct, parts }\n}\n","/**\n * Token heuristics shared by the host fold and the client boundary — the\n * harness token-meter's own fixed-density figure (dsh-token-meter/estimate.ts:\n * ~4 chars ≈ 1 token, +4 role framing). Priced identically on both sides so a\n * legacy value normalized at the client boundary matches what the host view\n * would have served.\n */\n\nconst CHARS_PER_TOKEN = 4\nconst ROLE_OVERHEAD = 4\n\n/** Price rendered system-prompt text; 0 for absent/empty/non-string input. */\nexport function estimateSystemTokens(text: unknown): number {\n if (typeof text !== 'string' || text.length === 0) return 0\n return Math.ceil(text.length / CHARS_PER_TOKEN) + ROLE_OVERHEAD\n}\n\n/**\n * Price a `system/message` payload's content exactly like the harness's\n * token-meter (`estimateSystemMessage`): text density over EVERY text block\n * plus role framing, with no per-block overhead — an adapter serializes the\n * prompt as plain text, so a text block costs its characters alone. Any other\n * block (or a hostile element) falls back to its JSON length. 0 for empty\n * content, which the harness reads as \"no system prompt\".\n */\nexport function estimateSystemContent(blocks: unknown): number {\n if (!Array.isArray(blocks) || blocks.length === 0) return 0\n let characters = 0\n for (const block of blocks) {\n const text = block !== null && typeof block === 'object' && (block as { type?: unknown }).type === 'text'\n ? (block as { text?: unknown }).text\n : undefined\n if (typeof text === 'string') {\n characters += text.length\n continue\n }\n try {\n const json: unknown = JSON.stringify(block)\n if (typeof json === 'string') characters += json.length\n } catch {\n // A cyclic/hostile block contributes no characters instead of throwing the fold.\n }\n }\n return Math.ceil(characters / CHARS_PER_TOKEN) + ROLE_OVERHEAD\n}\n","/**\n * Client-side harness boundary — the exact API surface this plugin consumes\n * from the harness web half, plus the sanitizers that re-prove every\n * delivered value at that boundary.\n *\n * The plugin bundles its own code but relies on the reader to deliver the\n * framework standard kit to slot components (`sessionId`, `useChat`,\n * `useProjection`, `t` …); only the small faces below are referenced across\n * modules. The INTERFACES are type-only (the runtime services come from the\n * user's harness); the `*Of` functions are the runtime guards the\n * no-white-screen guarantee rides on. Data arrives as pushed session\n * projections (`useProjection` standard seat); the ONE exception is the\n * gateway history page read (`remote.session.page`, see historyPage.ts) that\n * fetches a request-header epoch's content on demand.\n */\n\nimport type { Context } from '@deepseek-ai/cordis'\nimport type { ComponentType } from 'react'\nimport { estimateSystemTokens } from '../shared/estimate'\nimport type { ActivityDay, ContextActivity, ContextBreakdown, ContextHeaders, ContextPressure, ContextTimeline, CostModelUsage, HeaderEpochContent, SystemPromptNode, TimingTotals, TokenUsage, ToolTimingTotals } from '../shared/types'\n\nexport interface LocaleService {\n register(ns: string, dicts: Record<string, Record<string, string>>): () => void\n bind(ns: string): (key: string, params?: Record<string, string | number>) => string\n getLocale?(): { active: string }\n}\n\nexport interface SlotRegistration {\n name: string\n /** List slots dispatch on id + order. */\n id?: string\n order?: number\n /** Keyed slots (e.g. settings.plugin.item) dispatch on the entry key. */\n key?: string\n /** optional dictionary namespace; the framework then synthesizes the `t` seat. */\n locale?: string\n label?: () => string\n /** optional business face factory; a `hooks` compartment binds selector hooks onto props. */\n inject?: (sessionId?: string) => unknown\n}\n\nexport interface SlotsService {\n inject(name: string, callback: () => unknown): unknown\n register(\n registration: SlotRegistration,\n component: (props: { sessionId?: string } & Record<string, unknown>) => unknown,\n ): unknown\n}\n\n/**\n * One guide-page capsule a right-Sidebar tab type contributes (dsh\n * 0.1.5-rc.1+): the glyph, the title, and the optional one-line description,\n * exactly the fields `SidebarRightGuideEntry` carries.\n */\nexport interface SidebarGuideEntryLike {\n /** Ascending position among every registered type's entries. */\n order: number\n title: () => string\n /**\n * One line under the title on what picking the capsule opens; the guide\n * renders it only while it lists few enough entries. Optional, so a line\n * whose guide body ignores it simply goes without.\n */\n description?: () => string\n icon?: ComponentType<{ size?: number }>\n}\n\n/** One right-Sidebar tab type registration (the fields this plugin uses). */\nexport interface SidebarTabDefinitionLike {\n /** This implementation's identity, unique across every registration. */\n id: string\n /** What `openTab` names; also the page address's discriminator. */\n kind: string\n /** The tab chip's text, captured when the tab opens. */\n title: () => string\n /** Entry capsules for the guide page (omitted = the type stays off it). */\n guide?: readonly SidebarGuideEntryLike[]\n}\n\n/**\n * The right Sidebar's tab-type registry (`ctx.sidebarRightTabs`), as far as\n * this plugin consumes it. OPTIONAL by contract: the service ships only on the\n * 0.1.5 line (0.1.5-rc.1+ supported), so the plugin reaches it through a\n * deferred inject and stays fully functional (no pending fiber, no throw)\n * without it.\n */\nexport interface SidebarTabsFace {\n register(definition: SidebarTabDefinitionLike): () => void\n}\n\n/**\n * The right Sidebar's navigation face (`ctx.sidebarRight`), as far as this\n * plugin consumes it: `openResource` claims a `dsh-resource://file/…` address\n * through the shipped preview type and reveals the column in the same step.\n * The same optional generation as {@link SidebarTabsFace}; the caller re-proves\n * the verb at runtime and falls back to the system opener when it is absent or\n * refuses the address.\n */\nexport interface SidebarResourceFace {\n openResource(address: string): void\n}\n\n/**\n * The conversation node, as far as the Context browser consumes it: the\n * framework's finalized chat nodes carry the source surface event's `seq`\n * plus the full content — the browser joins its surface nodes on `seq` to\n * show actual content without carrying it through the projection.\n */\nexport interface ConversationNodeLike {\n kind: string\n seq: number\n /**\n * The durable message id (assistant nodes on the harness chat nodes; absent\n * on synthetic/interrupted replies) — the key the chat's assistant-action\n * seat addresses a finalized reply by.\n */\n messageId?: unknown\n content?: readonly unknown[]\n blocks?: readonly unknown[]\n call?: { name: string; argsRaw: string } | null\n isError?: boolean\n summary?: string | null\n /**\n * Nested Code-Mode call tree (dsh's recursive ToolCallBlock[]) on a tool\n * result whose call ran sub-dispatches — a PTC `run_code` program. Consumed\n * structurally only (fileActivity): every block is re-proved at runtime and\n * malformed shapes drop out instead of throwing.\n */\n subCalls?: readonly unknown[]\n /** The tool result's bounded presentation meta (a search's matched files), as the join delivers it. */\n meta?: unknown\n}\n\n/**\n * A durable image attachment reference, as far as this plugin consumes it\n * (dsh's `ImageAttachmentRef`, minimally re-typed so the plugin stays free\n * of an attachment-package dependency). The durable log holds only this ref\n * — never inline bytes. On every supported line the width/height/bytes\n * describe the NORMALIZED raster under a deployment-resolvable policy\n * (defaults: total-pixel budget 2048×2048, long edge capped at 8192px);\n * `originalDimensions` carries the pre-normalization size when normalization\n * reduced the image.\n */\nexport interface ImageRefLike {\n attachmentId: string\n name?: string\n bytes?: number\n width?: number\n height?: number\n originalDimensions?: { width: number; height: number }\n}\n\n/** Loads a session-authorized display URL for one durable image reference. */\nexport type ImageLoader = (attachment: ImageRefLike) => Promise<string>\n\n/**\n * The harness conversation client service, minimally typed for image\n * resolution — the same call the chat view's own message images ride on\n * (`ctx.uiConversation.imageUrl`).\n */\nexport interface UiConversationFace {\n imageUrl?(sessionId: string, attachment: ImageRefLike): Promise<string>\n}\n\n/**\n * A session-authorized durable-image loader over the harness conversation\n * face (`uiConversation.imageUrl`), or undefined when the service is not\n * composed — the caller degrades to metadata-only cards. Hostile snapshots\n * and throwing service reads are caught: this helper can never take a\n * render down.\n */\nexport function imageLoaderOf(\n ctx: ClientCtx,\n sessionId: string | undefined,\n): ImageLoader | undefined {\n if (typeof sessionId !== 'string' || sessionId === '') return undefined\n try {\n const conversation = ctx.get('uiConversation') as UiConversationFace | undefined\n if (conversation !== undefined && typeof conversation.imageUrl === 'function') {\n const imageUrl = conversation.imageUrl.bind(conversation)\n return attachment => imageUrl(sessionId, attachment)\n }\n } catch { /* absent or hostile service — metadata-only cards */ }\n return undefined\n}\n\n/**\n * The `useChat` standard seat (the finalized chat nodes live on a per-view\n * `ChatSnapshot` whose `legacy` slice keeps the plain `ConversationNode[]`).\n * Minimally typed: the selector receives the harness snapshot (untrusted —\n * re-proved outside), and the slice it returns must be reference-stable so\n * the framework's selector-hook equality can gate re-renders.\n */\nexport type UseChatLike = <T>(selector: (snapshot: unknown) => T) => T\n\n/**\n * The conversation-window nodes this plugin joins on, from the `useChat`\n * seat (`ChatSnapshot.legacy.nodes`). Returns undefined when the seat does\n * not deliver a real array (absent seat, foreign harness, hostile snapshot)\n * — callers render without the join, never an error.\n */\nexport function conversationNodesOf(props: {\n useChat?: UseChatLike\n}): readonly ConversationNodeLike[] | undefined {\n const useChat: unknown = props.useChat\n if (typeof useChat !== 'function') return undefined\n try {\n // `s.legacy` is a stable object; the array is read outside the selector.\n const slice = (useChat as UseChatLike)((s: unknown) =>\n s !== null && typeof s === 'object' ? (s as { legacy?: unknown }).legacy : undefined)\n const nodes = slice !== null && typeof slice === 'object' ? (slice as { nodes?: unknown }).nodes : undefined\n return Array.isArray(nodes) ? nodes as readonly ConversationNodeLike[] : undefined\n } catch { /* hostile seat — the join degrades to nothing */ }\n return undefined\n}\n\n/**\n * The framework standard kit of a session-scope slot component, as far as\n * this plugin consumes it: the resolve session id and the key-addressed\n * projection reader that delivers the `redlineTimeline` value (undefined =\n * the host unit is absent or no value has arrived yet).\n */\nexport interface SessionStandardProps {\n sessionId?: string\n useProjection?: (key: string) => unknown\n /** The chat-view snapshot seat (see {@link UseChatLike}). */\n useChat?: UseChatLike\n}\n\n/**\n * The Context view's props: the framework standard kit plus this plugin's own\n * host marker. The right Sidebar's panel registration sets `host`, so the SAME\n * view drops the head cards a narrow column cannot serve.\n */\nexport interface ContextViewProps extends SessionStandardProps {\n /** Set only by the right-Sidebar registration; absent in the conversation tab and the /redline modal. */\n host?: 'sidebar'\n}\n\n/**\n * Read one projection key through the standard seat, narrowed at the\n * boundary: null when the seat is absent (a harness without the projection\n * pipeline) or the delivered value fails the narrow. The seat is a real\n * hook — call this unconditionally at the top of the component, one call\n * per key, in a stable order.\n */\nexport function projectionOf<T>(props: SessionStandardProps, key: string, narrow: (value: unknown) => T | null): T | null {\n if (typeof props.useProjection !== 'function') return null\n return narrow(props.useProjection(key))\n}\n\nexport type ClientCtx = Context & {\n locale: LocaleService\n slots: SlotsService\n}\n\n/**\n * Narrow an unknown projection value to a string-keyed record, or null when\n * it is not one. The boundary type is Record<string, unknown> on purpose:\n * every field read below must re-prove itself (the no-white-screen\n * guarantee), so no field may borrow the wire type before its check.\n * Shared by every sanitizer here and by the agent-tree derivation\n * (agentTree.ts) — the ONE record guard for the whole client half.\n */\nexport function asRecord(value: unknown): Record<string, unknown> | null {\n if (value === null || value === undefined || typeof value !== 'object') return null\n return value as Record<string, unknown>\n}\n\n/**\n * Safe finite-number read: a missing/non-numeric/NaN field degrades to 0\n * instead of leaking into the UI as NaN percentages or broken arithmetic.\n */\nexport function numOf(value: unknown): number {\n return typeof value === 'number' && Number.isFinite(value) ? value : 0\n}\n\n/** Shared per-item collection guard: drop non-object entries, keep the rest. */\nexport function objectsOf<T>(value: unknown): T[] {\n if (!Array.isArray(value)) return []\n return value.filter((v): v is T => v !== null && typeof v === 'object')\n}\n\n/**\n * The fast path's collection check: a real array whose entries are ALL\n * records. A null/primitive entry would pass a bare Array.isArray yet throw\n * on the first property read downstream (`req.seq` on null), so it sends the\n * value down the sanitizing slow path, where `objectsOf` drops it.\n */\nfunction recordsOnly(value: unknown): boolean {\n return Array.isArray(value) && value.every(e => e !== null && typeof e === 'object')\n}\n\n/**\n * Narrow a delivered `unsupported` gate record (the host's baseline gate —\n * see host/fallback.ts): both version strings re-proved, anything else\n * degrades to null (no gate shown) instead of rendering garbage.\n */\nexport function unsupportedOf(value: unknown): { current: string; minimum: string } | null {\n const data = asRecord(value)\n if (data === null) return null\n if (typeof data.current !== 'string' || typeof data.minimum !== 'string') return null\n return { current: data.current, minimum: data.minimum }\n}\n\n/**\n * The session-cost raw material, re-proved per provider/model/period/bucket\n * (the shape the client's cost.ts prices): a branch, model, or period that\n * is not a plain record drops whole — never a half-proved row — and bucket\n * fields zero out via numOf, so garbage can only price as zero, never as\n * NaN. Absent stays absent.\n */\nfunction costOf(value: unknown): ContextTimeline['cost'] | undefined {\n const data = asRecord(value)\n if (data === null || Array.isArray(data)) return undefined\n const out: NonNullable<ContextTimeline['cost']> = {}\n for (const provider of Object.keys(data)) {\n const models = asRecord(data[provider])\n if (models === null || Array.isArray(models)) continue\n const branch: Record<string, CostModelUsage> = {}\n for (const model of Object.keys(models)) {\n const periods = asRecord(models[model])\n if (periods === null || Array.isArray(periods)) continue\n const copy: CostModelUsage = {}\n for (const period of ['peak', 'off'] as const) {\n const b = asRecord(periods[period])\n if (b === null || Array.isArray(b)) continue\n copy[period] = {\n uncached: numOf(b.uncached),\n cacheRead: numOf(b.cacheRead),\n cacheWrite: numOf(b.cacheWrite),\n output: numOf(b.output),\n }\n }\n branch[model] = copy\n }\n out[provider] = branch\n }\n return out\n}\n\n/** The fast-path structural check for `cost`: every branch is a plain record (bucket fields re-prove in costOf/cost.ts). */\nfunction costFastOk(value: unknown): boolean {\n if (value === undefined) return true\n const data = asRecord(value)\n if (data === null || Array.isArray(data)) return false\n return Object.keys(data).every((provider) => {\n const models = asRecord(data[provider])\n return models !== null && !Array.isArray(models)\n })\n}\n\n/**\n * Narrow a delivered projection value to a RENDER-SAFE context timeline —\n * the client's no-white-screen guarantee against backend/parse failures.\n *\n * A value that is not a record at all (capability absent, nothing delivered\n * yet) stays `null` and callers show the loading screen. A record that fails\n * the wire shape (corrupt checkpoint restore, a failed/older host payload,\n * plugin drift) is SANITIZED instead of rejected: every collection becomes\n * an array, non-object entries are dropped, `current` becomes a numeric\n * breakdown, and wrong-typed scalars are dropped or zeroed — so the whole\n * tab still renders with every usable piece of data instead of throwing\n * during render and unmounting the conversation view.\n */\nexport function timelineOf(value: unknown): ContextTimeline | null {\n const data = asRecord(value)\n if (data === null) return null\n const current = data.current\n // The wire shape check for the cheap pass-through path: `current` must be\n // a full numeric breakdown (the host always sends all seven fields), and\n // every collection must be a real list. Anything else takes the slow path\n // and is rebuilt into the safe shape below.\n const numericBreakdown = current !== null && typeof current === 'object'\n && ['system', 'tools', 'user', 'inject', 'skill', 'assistant', 'tool', 'total']\n .every(k => typeof (current as Record<string, unknown>)[k] === 'number')\n if (numericBreakdown\n && recordsOnly(data.requests)\n && recordsOnly(data.events)\n && recordsOnly(data.nodes)\n && recordsOnly(data.archive)\n && systemsFastOk(data.systems)\n && timingFastOk(data.timing)\n && costFastOk(data.cost)) {\n // Well-formed: pass the delivered value through untouched (cheap, and reference-stable so plain re-renders stay zero-copy).\n return data as unknown as ContextTimeline\n }\n const safeCurrent: Record<string, unknown> = current !== null && typeof current === 'object' ? current as Record<string, unknown> : {}\n const cost = costOf(data.cost)\n const timing = timingOf(data.timing)\n // The baseline-gate record survives sanitizing: a fallback payload that\n // somehow fails the fast path must still pop the gate modal.\n const unsupported = unsupportedOf(data.unsupported)\n // The split-generation head fields survive sanitizing too.\n const counts = countsOf(data.counts)\n const last = lastOf(data.last)\n const safe: ContextTimeline = {\n ok: true,\n ...(unsupported !== null ? { unsupported } : {}),\n ...(typeof data.model === 'string' ? { model: data.model } : {}),\n ...(typeof data.provider === 'string' ? { provider: data.provider } : {}),\n ...(typeof data.contextWindow === 'number' ? { contextWindow: data.contextWindow } : {}),\n current: {\n system: numOf(safeCurrent.system),\n tools: numOf(safeCurrent.tools),\n user: numOf(safeCurrent.user),\n inject: numOf(safeCurrent.inject),\n skill: numOf(safeCurrent.skill),\n assistant: numOf(safeCurrent.assistant),\n tool: numOf(safeCurrent.tool),\n total: numOf(safeCurrent.total),\n },\n requests: objectsOf(data.requests),\n events: objectsOf(data.events),\n nodes: objectsOf(data.nodes),\n droppedNodes: numOf(data.droppedNodes),\n ...(typeof data.images === 'number' ? { images: data.images } : {}),\n ...(typeof data.toolCalls === 'number' ? { toolCalls: data.toolCalls } : {}),\n ...(typeof data.humanInputs === 'number' ? { humanInputs: data.humanInputs } : {}),\n ...(typeof data.lastUser === 'string' && data.lastUser !== '' ? { lastUser: data.lastUser.slice(0, 200) } : {}),\n archive: objectsOf(data.archive),\n ...(counts !== undefined ? { counts } : {}),\n ...(last !== undefined ? { last } : {}),\n ...(typeof data.detailRev === 'number' && Number.isFinite(data.detailRev) ? { detailRev: data.detailRev } : {}),\n ...(cost !== undefined ? { cost } : {}),\n ...(timing !== null ? { timing } : {}),\n ...(data.systems !== undefined ? { systems: systemsOf(data.systems) } : {}),\n ...(typeof data.surfaceFloor === 'number' ? { surfaceFloor: data.surfaceFloor } : {}),\n ...(typeof data.archiveFloor === 'number' ? { archiveFloor: data.archiveFloor } : {}),\n ...(data.fileOps !== undefined ? { fileOps: objectsOf(data.fileOps) } : {}),\n ...(typeof data.fileOpsFloor === 'number' ? { fileOpsFloor: data.fileOpsFloor } : {}),\n }\n return safe\n}\n\n/**\n * The live system-prompt nodes, re-proved per entry and sorted by seq: an\n * entry missing a finite seq/time/tokens drops out (the browser then falls\n * back to the header epoch), so a hostile collection can never produce a NaN\n * prompt figure or an unfetchable seq. Absent or empty stays absent.\n */\nfunction systemsOf(value: unknown): ContextTimeline['systems'] {\n const list = objectsOf<Record<string, unknown>>(value)\n const out: SystemPromptNode[] = []\n for (const entry of list) {\n const { seq, time, tokens } = entry\n if (typeof seq !== 'number' || !Number.isFinite(seq)) continue\n if (typeof time !== 'number' || !Number.isFinite(time)) continue\n if (typeof tokens !== 'number' || !Number.isFinite(tokens)) continue\n out.push({ seq, time, tokens })\n }\n return out.sort((a, b) => a.seq - b.seq)\n}\n\n/**\n * The fast path's check for the live system-prompt nodes: every entry must\n * carry the three finite numbers the browser reads — `seq` for the per-step\n * resolution, `time` for the DNA band, `tokens` for its width. A primitive\n * entry, or one whose fields are not numbers, sends the payload down the\n * sanitizing slow path (`systemsOf` drops it) instead of leaking `undefined`\n * into the bar math. An absent list is fine.\n */\nfunction systemsFastOk(value: unknown): boolean {\n if (value === undefined) return true\n if (!Array.isArray(value)) return false\n return value.every((entry) => {\n if (entry === null || typeof entry !== 'object') return false\n const { seq, time, tokens } = entry as Record<string, unknown>\n return typeof seq === 'number' && Number.isFinite(seq)\n && typeof time === 'number' && Number.isFinite(time)\n && typeof tokens === 'number' && Number.isFinite(tokens)\n })\n}\n\n/**\n * The split head's count figures, re-proved field by field: a present-but-\n * partial record zeroes its unreadable fields (the stats board's no-NaN\n * guarantee), an absent or non-record value stays absent (legacy generation\n * — callers derive the counts from the collections instead).\n */\nfunction countsOf(value: unknown): ContextTimeline['counts'] {\n const data = asRecord(value)\n if (data === null) return undefined\n return {\n turns: numOf(data.turns),\n steps: numOf(data.steps),\n injects: numOf(data.injects),\n compactions: numOf(data.compactions),\n prunes: numOf(data.prunes),\n }\n}\n\n/** The split head's newest-request summary; absent or shapeless stays absent. */\nfunction lastOf(value: unknown): ContextTimeline['last'] {\n const data = asRecord(value)\n if (data === null) return undefined\n if (typeof data.seq !== 'number' || !Number.isFinite(data.seq)) return undefined\n if (typeof data.total !== 'number' || !Number.isFinite(data.total)) return undefined\n return {\n seq: data.seq,\n total: data.total,\n ...(typeof data.prompt === 'number' && Number.isFinite(data.prompt) ? { prompt: data.prompt } : {}),\n }\n}\n\n/**\n * Narrow a delivered projection value to the official token-meter\n * `contextPressure` projection (provider-anchored occupancy of the next\n * request). Absent key or value = the meter's projection is not composed\n * (e.g. a harness without the session-projection registry) — callers fall\n * back to their derived anchor, so the UI degrades gracefully. The three\n * fields are independent last-wins records on the wire (dsh's strict wire\n * schema), so each is re-proved on its own: a wrong-typed field drops out,\n * the readable ones survive.\n */\nexport function contextPressureOf(value: unknown): ContextPressure | null {\n const data = asRecord(value)\n if (data === null) return null\n const out: ContextPressure = {}\n if (typeof data.pressureTokens === 'number' && Number.isFinite(data.pressureTokens)) out.pressureTokens = data.pressureTokens\n if (typeof data.projectedTokens === 'number' && Number.isFinite(data.projectedTokens)) out.projectedTokens = data.projectedTokens\n if (typeof data.contextWindow === 'number' && Number.isFinite(data.contextWindow)) out.contextWindow = data.contextWindow\n return out\n}\n\n/**\n * Narrow a delivered projection value to the official token-meter\n * `contextBreakdown` projection (the heuristic composition rows of the chat\n * ring's panel). Every figure must be a finite number — a partial/corrupt\n * value degrades to null so the composition card falls back to the fold's\n * own sums instead of mixing sources.\n */\nexport function contextBreakdownOf(value: unknown): ContextBreakdown | null {\n const data = asRecord(value)\n if (data === null) return null\n const { systemTokens, toolsTokens, messageTokens } = data\n if (typeof systemTokens !== 'number' || !Number.isFinite(systemTokens)) return null\n if (typeof toolsTokens !== 'number' || !Number.isFinite(toolsTokens)) return null\n if (typeof messageTokens !== 'number' || !Number.isFinite(messageTokens)) return null\n return { systemTokens, toolsTokens, messageTokens }\n}\n\n/**\n * Narrow a delivered projection value to the official token-meter\n * `tokenUsage` projection (durable cumulative provider usage). Absent key or\n * value = the meter's projection is not composed (or no request has reported\n * usage yet) — callers drop the cache-hit cell to a dash. The wire schema is\n * strict with all four buckets REQUIRED (dsh token-meter's projectionSchema),\n * so a partial/corrupt value degrades the whole value to null instead of\n * undercounting the billed total.\n */\nexport function tokenUsageOf(value: unknown): TokenUsage | null {\n const data = asRecord(value)\n if (data === null) return null\n const { uncachedInputTokens, outputTokens, cacheReadTokens, cacheWriteTokens } = data\n if (typeof uncachedInputTokens !== 'number' || !Number.isFinite(uncachedInputTokens)) return null\n if (typeof outputTokens !== 'number' || !Number.isFinite(outputTokens)) return null\n if (typeof cacheReadTokens !== 'number' || !Number.isFinite(cacheReadTokens)) return null\n if (typeof cacheWriteTokens !== 'number' || !Number.isFinite(cacheWriteTokens)) return null\n return { uncachedInputTokens, outputTokens, cacheReadTokens, cacheWriteTokens }\n}\n\n/**\n * A non-negative finite number (the timing totals' every field): NaN or a\n * negative degrades to 0 instead of leaking into donut shares.\n */\nfunction msNumOf(value: unknown): number {\n return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : 0\n}\n\n/**\n * The OPTIONAL timing scalars (the generation split's spans and block counts):\n * a real non-negative number passes, anything else — including absence — reads\n * as undefined so the field stays absent on the narrowed value (see\n * `timingOf`).\n */\nfunction optNumOf(value: unknown): number | undefined {\n return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : undefined\n}\n\n/**\n * Cheap whole-value check for the pass-through path of `timelineOf`: absent\n * timing passes; present timing must already be well-formed (every scalar\n * numeric, every per-name row shaped) — anything else sends the payload down\n * the sanitizing slow path.\n */\nfunction timingFastOk(value: unknown): boolean {\n if (value === undefined) return true\n if (value === null || typeof value !== 'object' || Array.isArray(value)) return false\n const t = value as Record<string, unknown>\n for (const k of ['wallMs', 'ttftMs', 'genMs', 'calls', 'toolsMs', 'toolCalls']) {\n if (typeof t[k] !== 'number') return false\n }\n // The generation split and the block counts are optional but, when present,\n // must be finite non-negative numbers — the same gate the slow path applies,\n // so a hostile bucket cannot slip through the fast path (see `timingOf`).\n for (const k of ['reasoningMs', 'textMs', 'toolArgMs', 'reasoningBlocks', 'textBlocks', 'toolArgBlocks']) {\n const v = t[k]\n if (v !== undefined && (typeof v !== 'number' || !Number.isFinite(v) || v < 0)) return false\n }\n const tools = t.tools\n if (tools === null || typeof tools !== 'object' || Array.isArray(tools)) return false\n for (const k in tools) {\n const row = (tools as Record<string, unknown>)[k]\n if (row === null || typeof row !== 'object') return false\n if (typeof (row as Record<string, unknown>).calls !== 'number') return false\n if (typeof (row as Record<string, unknown>).ms !== 'number') return false\n }\n return true\n}\n\n/**\n * Narrow a delivered timing totals value (see TimingTotals) to a RENDER-SAFE\n * shape — the timing card's no-white-screen guarantee. A value that is not a\n * record stays null (the card renders its empty state); wrong-typed scalars\n * zero out and per-name rows failing the shape drop individually, so one\n * hostile row never blanks the ranking.\n */\nexport function timingOf(value: unknown): TimingTotals | null {\n const data = asRecord(value)\n if (data === null) return null\n const tools: Record<string, ToolTimingTotals> = {}\n const rawTools = data.tools\n if (rawTools !== null && typeof rawTools === 'object' && !Array.isArray(rawTools)) {\n for (const k in rawTools) {\n // A JSON-delivered record can carry an own '__proto__' key; assigning it\n // would set the prototype instead of a row — skip it.\n if (k === '__proto__' || !Object.hasOwn(rawTools, k)) continue\n const row = (rawTools as Record<string, unknown>)[k]\n if (row === null || typeof row !== 'object') continue\n const calls = (row as Record<string, unknown>).calls\n const ms = (row as Record<string, unknown>).ms\n if (typeof calls !== 'number' || !(calls >= 0) || typeof ms !== 'number' || !(ms >= 0)) continue\n tools[k] = { calls, ms }\n }\n }\n const totals: TimingTotals = {\n wallMs: msNumOf(data.wallMs),\n ttftMs: msNumOf(data.ttftMs),\n genMs: msNumOf(data.genMs),\n calls: msNumOf(data.calls),\n toolsMs: msNumOf(data.toolsMs),\n toolCalls: msNumOf(data.toolCalls),\n tools,\n }\n // The optional scalars stay ABSENT when the host did not serve them (a row\n // cached before the split / the counts) or served a non-number: the card\n // renders the un-split shape / no qualifier instead of meaningless zeros.\n const reasoning = optNumOf(data.reasoningMs)\n if (reasoning !== undefined) totals.reasoningMs = reasoning\n const reasoningBlocks = optNumOf(data.reasoningBlocks)\n if (reasoningBlocks !== undefined) totals.reasoningBlocks = reasoningBlocks\n const textMs = optNumOf(data.textMs)\n if (textMs !== undefined) totals.textMs = textMs\n const textBlocks = optNumOf(data.textBlocks)\n if (textBlocks !== undefined) totals.textBlocks = textBlocks\n const toolArgMs = optNumOf(data.toolArgMs)\n if (toolArgMs !== undefined) totals.toolArgMs = toolArgMs\n const toolArgBlocks = optNumOf(data.toolArgBlocks)\n if (toolArgBlocks !== undefined) totals.toolArgBlocks = toolArgBlocks\n return totals\n}\n\n/**\n * Narrow a delivered projection value to the plugin's `redlineHeaders`\n * (request-header epoch METADATA — boundaries, token prices, attribution).\n * Absent key = an older Host half without the companion unit — the Context\n * browser degrades its system/tools sections to a metadata-only note.\n *\n * Entry-level shape is checked too: a malformed epoch (corrupt payload with\n * a missing tools list, a wrong-typed systemTokens, or a tool row whose\n * name/tokens the browser reads blindly — `tool.name.toLowerCase()` and\n * `b.tokens - a.tokens` throw on junk) would crash the browser's\n * tools/sections reads, so the WHOLE projection degrades to null and the\n * card falls back to its metadata-only note. The epoch CONTENT is\n * not part of this value — the browser fetches it per epoch on demand.\n *\n * The pre-#37 wire generation carries the system TEXT instead of its token\n * price (a host still running the old view — stale watch build, an app not\n * restarted since the upgrade — serves it from its cache verbatim), so the\n * two generations are normalized to the metadata shape here: unpriced legacy\n * entries get the shared meter heuristic applied, priced ones and\n * new-shape values pass through untouched.\n */\nexport function headersOf(value: unknown): ContextHeaders | null {\n const headers = asRecord(value)\n if (headers === null || !Array.isArray(headers.headers)) return null\n for (const h of headers.headers as unknown[]) {\n if (h === null || typeof h !== 'object') return null\n const entry = h as { tools?: unknown; systemTokens?: unknown }\n if (!Array.isArray(entry.tools)) return null\n if (entry.systemTokens !== undefined && (typeof entry.systemTokens !== 'number' || !Number.isFinite(entry.systemTokens))) return null\n for (const t of entry.tools as unknown[]) {\n if (t === null || typeof t !== 'object') return null\n const tool = t as { name?: unknown; tokens?: unknown; plugin?: unknown }\n if (typeof tool.name !== 'string') return null\n if (typeof tool.tokens !== 'number' || !Number.isFinite(tool.tokens)) return null\n if (tool.plugin !== undefined && typeof tool.plugin !== 'string') return null\n }\n }\n let legacy = false\n for (const entry of headers.headers as { systemTokens?: unknown; system?: unknown }[]) {\n if (entry.systemTokens === undefined && typeof entry.system === 'string' && entry.system !== '') {\n legacy = true\n break\n }\n }\n if (!legacy) return headers as unknown as ContextHeaders\n return {\n headers: (headers.headers as { systemTokens?: number; system?: unknown }[]).map((entry) => {\n if (entry.systemTokens !== undefined) return entry\n return { ...entry, systemTokens: estimateSystemTokens(entry.system) || undefined }\n }),\n } as unknown as ContextHeaders\n}\n\n/**\n * Narrow a delivered `redlineActivity` value (the per-day ledger the Context\n * Overview's heatmap and usage chart read off each session-list row) to a\n * render-safe shape. Absent or non-record stays null (an older host serves no\n * such key — the heatmap renders its empty note). Per-day re-proved: a\n * malformed key or a wrong-typed figure drops just that entry, a malformed\n * pricing record drops just the fee (the day's tokens survive), a hostile day\n * record can never produce a NaN cell, and a well-formed payload passes\n * through untouched (reference-stable for the selector equality).\n */\nexport function activityOf(value: unknown): ContextActivity | null {\n const data = asRecord(value)\n if (data === null) return null\n const rawDays = asRecord(data.days)\n if (rawDays === null || Array.isArray(rawDays)) return null\n const days: Record<string, ActivityDay> = {}\n let dirty = false\n for (const key of Object.keys(rawDays)) {\n const entry = asRecord(rawDays[key])\n const tokens = entry?.tokens\n const requests = entry?.requests\n if (!/^\\d{4}-\\d{2}-\\d{2}$/.test(key)\n || entry === null || Array.isArray(entry)\n || typeof tokens !== 'number' || !Number.isFinite(tokens) || tokens < 0\n || typeof requests !== 'number' || !Number.isFinite(requests) || requests < 0) {\n dirty = true\n continue\n }\n // The day's pricing record (additive-optional): re-proved by the SAME\n // sanitizer the timeline's session-cost rides. Absent stays absent; a\n // record with no readable branch drops whole (empty ≠ zero — a truly\n // metered day always carries a branch), keeping the day's own figures.\n const proved = costOf(entry.cost)\n const cost = proved !== undefined && Object.keys(proved).length > 0 ? proved : undefined\n if (entry.cost !== undefined && cost === undefined) dirty = true\n days[key] = { tokens, requests, ...(cost !== undefined ? { cost } : {}) }\n }\n // Fully well-formed: pass the delivered value through untouched (cheap, and\n // reference-stable for the selector equality); otherwise the sanitized copy.\n return dirty ? { days } : data as unknown as ContextActivity\n}\n\nexport interface TriggerCandidate {\n name: string\n /** Display title; the name itself when absent (a differing title renders the name as a trailing alias). */\n label?: string\n /** Visual heading of this candidate's group; its presence suppresses the menu's source-title row. */\n section?: string\n description?: string\n /** Row glyph, rendered at a 16px edge. */\n icon?: ComponentType<{ size?: number }>\n}\n\n/** Pick-moment snapshot of the trigger token span (draftRev CAS). */\nexport interface TokenSpan {\n start: number\n end: number\n draftRev: number\n}\n\nexport interface TriggerPick {\n candidate: TriggerCandidate\n session: { sessionId: string }\n position: string\n via: string\n span: TokenSpan\n}\n\nexport type SourcePickOutcome = 'handled' | undefined\n\n/**\n * The harness input-trigger service (`ctx.inputTriggers`), as far as this\n * plugin consumes it: registering one '/' source whose candidates, picks,\n * and enter adjudication all stay on the client.\n */\nexport interface InputTriggersFace {\n registerSource(src: {\n trigger: '/'\n name: string\n order?: number\n candidates(\n session: { sessionId: string },\n req: { query: string; position: string; signal: AbortSignal },\n ): Promise<readonly TriggerCandidate[]>\n onPick(pick: TriggerPick): SourcePickOutcome\n matchEnter?(\n session: { sessionId: string },\n line: string,\n signal: AbortSignal,\n ): Promise<SourcePickOutcome>\n }): () => void\n}\n\n/** The session scope (`ctx.sessions.scope`), used to dispatch the scoped consume-token event. */\nexport interface SessionScopeFace {\n bail(subject: unknown, event: string, payload: unknown): unknown\n}\n\nexport interface SessionsFace {\n scope(id: string): SessionScopeFace | undefined\n /**\n * Select a listed session as current — the retired selection spelling,\n * still served through the 0.1.5 line and gone since the 0.1.6 selection\n * refactor (issue #90: the verb's home is now the view owner). Re-proved at\n * the call site via {@link openSessionVia}, which prefers the newer face.\n */\n open?(id: string): void\n /**\n * Re-pull the session-list baseline (the rows' projection column included).\n * The overview rides it on open so host-side backfill rows (backfill.ts)\n * reach a long-connected browser without a reload.\n */\n refresh?(): Promise<unknown>\n}\n\n/** One history page row: the raw event plus the optional host-computed view. */\nexport interface HistoryEntryLike {\n event?: unknown\n}\n\n/**\n * The seq-anchored history page verb of the harness gateway remotes: the\n * session namespace mounts as a traced cordis service literally named\n * `remote.session`. The plugin resolves it through the DECLARED inject\n * (`watchHistoryFaces` in historyPage.ts — a non-declared read of the\n * traced proxy throws), so reads are undefined on harnesses that never\n * mount it rather than crashing. `throughSeq` is the inclusive log cut (a\n * seq that must exist in the log), `beforeSeq` the exclusive upper bound,\n * and the response wraps the rows in a `ClientResult`-style envelope. Rows\n * are `SessionHistoryRecord`s — `{type:'event', event}` entries plus packed\n * `{type:'chunks', …}` runs the mapper skips (every event the fold needs —\n * user/assistant messages, tool calls/results, compaction summaries — is\n * always served verbatim; only streaming deltas pack).\n */\nexport interface SessionPageFace {\n page(request: {\n address: { kind: 'session'; sessionId: string }\n throughSeq: number\n beforeSeq?: number\n maxMessages?: number\n }, signal?: AbortSignal): Promise<unknown>\n}\n\n/**\n * The connection service face, as far as this plugin consumes it: the\n * generic Connection RPC caller (the harness's unary channel transport)\n * plus the loopback fact the harness's own open affordances gate on.\n */\nexport interface ConnectionFace {\n /** Whether the page reaches the Host on the operator's own machine. */\n isLoopback?: boolean\n rpc?: {\n call?(channel: string, endpoint: string, payload: unknown, signal?: AbortSignal): Promise<unknown>\n }\n}\n\n/** The session-namespace workspace-opener remotes, ridden through the generic '/api' channel. */\nconst OPEN_CHANNEL = '/api'\nconst CAN_OPEN_ENDPOINT = 'session/canOpenWorkspacePath'\nconst OPEN_ENDPOINT = 'session/openWorkspacePath'\n\n/**\n * The connection's bound generic-RPC caller, or undefined when the service\n * is absent or hostile — every read is guarded, so this can never throw.\n */\nexport function rpcCallOf(ctx: ClientCtx): ((channel: string, endpoint: string, payload: unknown) => Promise<unknown>) | undefined {\n try {\n const rpc = asRecord((ctx.get('connection') as ConnectionFace | undefined)?.rpc)\n const fn = rpc?.call\n if (rpc !== null && typeof fn === 'function') {\n return (fn as (channel: string, endpoint: string, payload: unknown) => Promise<unknown>).bind(rpc)\n }\n } catch { /* absent or hostile connection — the caller degrades off */ }\n return undefined\n}\n\n/**\n * The SESSION's workspace root — the `cwd` its session-list row carries (the\n * host session canon, not the host process's own launch directory) — or\n * undefined when the face is absent, the snapshot is malformed, or the row\n * names no cwd. Every field is re-proved — the no-white-screen guarantee.\n */\nexport function workspaceOf(ctx: ClientCtx, sessionId: string | undefined): string | undefined {\n if (typeof sessionId !== 'string' || sessionId === '') return undefined\n // The snapshot and its rows are host data — a hostile object may throw on\n // the call or on property access, and the card must never blank over it.\n try {\n const sessions = ctx.get('sessions') as { list?: { getSnapshot(): unknown } } | undefined\n const snapshot = typeof sessions?.list?.getSnapshot === 'function' ? sessions.list.getSnapshot() : undefined\n const byId = snapshot !== null && typeof snapshot === 'object' ? (snapshot as { byId?: unknown }).byId : undefined\n const row: unknown = byId !== null && typeof byId === 'object' ? (byId as Record<string, unknown>)[sessionId] : undefined\n const cwd = row !== null && typeof row === 'object' ? (row as { cwd?: unknown }).cwd : undefined\n return typeof cwd === 'string' && cwd !== '' ? cwd : undefined\n } catch {\n return undefined\n }\n}\n\n/**\n * Whether this deployment can hand a path to the user's native desktop: the\n * page must reach the Host on the operator's own machine (`isLoopback`, the\n * harness's own gate) AND the session controller's opener capability remote\n * must answer true. The capability is an RPC round-trip now (the synchronous\n * host-description fact is gone), so the answer is asynchronous; every\n * absence, hostility, or transport failure resolves false — never a rejection.\n */\nexport async function canOpenPathsOf(ctx: ClientCtx): Promise<boolean> {\n const call = rpcCallOf(ctx)\n if (call === undefined) return false\n try {\n const connection = ctx.get('connection') as ConnectionFace | undefined\n if (connection?.isLoopback !== true) return false\n const result = await call(OPEN_CHANNEL, CAN_OPEN_ENDPOINT, { args: {} })\n const r = asRecord(result)\n return r !== null && r.ok === true && r.value === true\n } catch {\n return false\n }\n}\n\n/**\n * The system path opener over the session controller's open remote, or\n * undefined when the connection carries no RPC caller. Fire-and-forget:\n * rejections (unknown path, no desktop, offline) swallow — the affordance\n * is best-effort by nature.\n */\nexport function openPathVia(ctx: ClientCtx): ((path: string) => void) | undefined {\n const call = rpcCallOf(ctx)\n if (call === undefined) return undefined\n return (path: string): void => {\n try {\n // `args` is a plain object keyed by the remote's declared parameter\n // names (the gateway's wire contract — an array is rejected host-side).\n void call(OPEN_CHANNEL, OPEN_ENDPOINT, { args: { request: { path } } })\n .catch(() => { /* the open is best-effort; a failure stays silent */ })\n } catch { /* same contract, for a synchronously throwing transport */ }\n }\n}\n\n/**\n * The right Sidebar's resource opener over `ctx.sidebarRight`, or undefined\n * when this harness serves no such column (every line older than 0.1.5-rc.1) or\n * the face is hostile — the caller then keeps its system-open degradation.\n * Synchronous, and it reports whether the column took the address: `openResource`\n * throws for a no-type-claims address or with no session surface mounted, and an\n * unwired preview must fall back rather than become an inert click. The face is\n * re-proved at call time (the service can land or be revoked across an HMR\n * reload), so the returned closure reads it per open.\n */\nexport function openResourceVia(ctx: ClientCtx): ((address: string) => boolean) | undefined {\n // The face is untrusted at the boundary, so the raw service is re-proved as a\n // record with a callable `openResource` (never trusted off the cast).\n const faceOf = (): SidebarResourceFace | undefined => {\n try {\n const face = asRecord(ctx.get('sidebarRight'))\n return face !== null && typeof face.openResource === 'function'\n ? face as unknown as SidebarResourceFace\n : undefined\n } catch {\n return undefined\n }\n }\n if (faceOf() === undefined) return undefined\n return (address: string): boolean => {\n const face = faceOf()\n if (face === undefined) return false\n try {\n face.openResource(address)\n return true\n } catch {\n // No preview type claims it, or no session surface is mounted: the caller\n // falls back instead of showing an inert affordance.\n return false\n }\n }\n}\n\n/**\n * Jump to one session — the harness's own session-selection verb (issue #90).\n * Every supported line selects through the view owner (`uiWorkspace`\n * .openSession, the sidebar row click's own verb); the sessions service's own\n * `open` is the retired spelling (still served through the 0.1.5 line, gone\n * since the 0.1.6 selection refactor) and stays as the degradation path for a\n * composition without the workspace module. Both faces are re-proved per call\n * (a service can land or be revoked across an HMR reload) and the verb is\n * invoked bound (the service instance reads its own state); a generation\n * serving neither, or a hostile face, swallows — the jump is best-effort by\n * nature.\n */\nexport function openSessionVia(ctx: ClientCtx, id: string): void {\n try {\n const workspace = asRecord(ctx.get('uiWorkspace'))\n const open = workspace?.openSession\n if (typeof open === 'function') {\n open.call(workspace, id)\n return\n }\n const sessions = asRecord(ctx.get('sessions'))\n const legacy = sessions?.open\n if (typeof legacy === 'function') legacy.call(sessions, id)\n } catch { /* absent or hostile face — the jump is best-effort */ }\n}\n\n/**\n * On-demand full content for one surface-node seq: resolves the joined\n * conversation node, `null` when the durable log does not hold the seq,\n * rejects on transport/RPC failure (the caller distinguishes the three).\n */\nexport type ContentFetcher = (seq: number) => Promise<ConversationNodeLike | null>\n\n/**\n * On-demand CONTENT for one `redlineHeaders` epoch seq: the fetched system\n * prompt and tool schemas (see historyPage.ts), `null` when the durable log\n * does not hold the epoch, rejects on transport/RPC failure (the caller\n * distinguishes the three).\n */\nexport type HeaderFetcher = (seq: number) => Promise<HeaderEpochContent | null>\n","/**\n * Targeted full-content fetch for the Context browser — the fallback that\n * replaces blind tail paging. When a surface node's seq is outside the\n * conversation window, ONE seq-anchored history read returns the page\n * containing that event: the host cuts pages on whole append-origin message\n * boundaries, so the newest group on the page covers `seq` whenever the\n * durable log still holds it. The read rides the harness gateway remotes\n * (`remote.session.page`, with the inclusive cut `throughSeq` pinned to the\n * target seq) and the raw events map into the same conversation-node shapes\n * the window join delivers (a thin display subset of dsh's own fold).\n * Fetched nodes cache per session — history is immutable, so a seq never\n * needs fetching twice.\n *\n * The remote face is resolved through the DECLARED inject\n * (`watchHistoryFaces`): this plugin's module inject lists only slots/\n * locale, and NONDECLARED reads of the traced service proxy throw \"cannot\n * get property … without inject\" and can take a view down. The injection\n * callback runs under a fiber that declares both `remote` and\n * `remote.session` (the dsh idiom), so the property path resolves there and\n * nowhere else; the resolved face is re-proved and a hostile read leaves\n * the slot unset instead of ever throwing.\n */\n\nimport { useSyncExternalStore } from 'react'\nimport type {\n ClientCtx, ContentFetcher, ConversationNodeLike, HeaderFetcher,\n HistoryEntryLike, SessionPageFace,\n} from './services'\nimport type { HeaderEpochContent } from '../shared/types'\n\n/** Narrow one served row to a validated durable event envelope, or null. */\nfunction eventOf(entry: unknown): { type: string; seq: number; data: Record<string, unknown> } | null {\n if (entry === null || typeof entry !== 'object') return null\n // History records wrap the envelope in an `event` field\n // (`{type:'event'|'chunks', event}`); a bare envelope passes too, so shape\n // drift degrades instead of breaking the page. Packed chunk-row records\n // flow through as unknown types and project to nothing downstream — only\n // final events matter here.\n const inner = (entry as HistoryEntryLike).event ?? entry\n if (typeof inner !== 'object') return null\n const e = inner as { type?: unknown; seq?: unknown; data?: unknown }\n if (typeof e.type !== 'string' || typeof e.seq !== 'number' || !Number.isFinite(e.seq)) return null\n const data = e.data !== null && typeof e.data === 'object' ? e.data as Record<string, unknown> : {}\n return { type: e.type, seq: e.seq, data }\n}\n\n/** All string texts of an event's message-content shape joined (compaction summaries). */\nfunction textOf(blocks: unknown): string | null {\n if (!Array.isArray(blocks)) return null\n let out = ''\n for (const b of blocks) {\n const text = b !== null && typeof b === 'object' ? (b as { type?: unknown; text?: unknown }).text : undefined\n if (typeof text === 'string') out += text\n }\n return out.trim() === '' ? null : out\n}\n\n/**\n * The system prompt's exact rendered text — every text block joined with NO\n * normalization: a whitespace-only prompt is still the prompt the model\n * received (the host prices it as text), so it must render rather than read\n * as absent. Null when the content carries no text block at all.\n */\nfunction systemTextOf(blocks: unknown): string | null {\n if (!Array.isArray(blocks)) return null\n let out = ''\n let seen = false\n for (const b of blocks) {\n const text = b !== null && typeof b === 'object' ? (b as { type?: unknown; text?: unknown }).text : undefined\n if (typeof text === 'string') {\n out += text\n seen = true\n }\n }\n return seen ? out : null\n}\n\n/**\n * One assistant content block → the snapshot block vocabulary the browser\n * already renders (`kind`: text/reasoning/image/tool-call); unmappable\n * blocks pass through raw and degrade to the generic JSON section.\n */\nfunction assistantBlockOf(block: unknown): Record<string, unknown> {\n const b = block !== null && typeof block === 'object' ? block as { type?: unknown; text?: unknown; attachment?: unknown; name?: unknown; arguments?: unknown } : null\n switch (b?.type) {\n case 'text': case 'reasoning':\n return { kind: b.type, ...(typeof b.text === 'string' ? { text: b.text } : {}) }\n case 'image':\n return { kind: 'image', ...(b.attachment !== undefined ? { attachment: b.attachment } : {}) }\n case 'tool-call':\n return {\n kind: 'tool-call',\n name: typeof b.name === 'string' ? b.name : '?',\n argsRaw: b.arguments,\n }\n default:\n return block !== null && typeof block === 'object' ? block as Record<string, unknown> : { value: block }\n }\n}\n\n/**\n * Map one history page into joined conversation nodes keyed by their event\n * seq — the display subset of the browser's join: user messages, assistant\n * blocks, tool results paired with their in-page call head, and compaction\n * checkpoints paired with their summary event. Everything else (headers,\n * boundaries, chunks, bare calls) projects to nothing.\n */\nexport function pageNodesOf(entries: readonly unknown[]): Map<number, ConversationNodeLike> {\n const nodes = new Map<number, ConversationNodeLike>()\n const calls = new Map<string, { name: string; argsRaw: string }>()\n const summaries = new Map<string, string>()\n for (const entry of entries) {\n const ev = eventOf(entry)\n if (ev === null) continue\n const { type, seq, data } = ev\n if (type === 'tool/call') {\n if (typeof data.callId === 'string') {\n calls.set(data.callId, {\n name: typeof data.name === 'string' ? data.name : '?',\n // The durable envelope stores arguments as a raw JSON string.\n argsRaw: typeof data.arguments === 'string' ? data.arguments : '',\n })\n }\n continue\n }\n if (type === 'compaction/summary') {\n if (typeof data.compactionId === 'string') {\n const summary = textOf(data.summary)\n if (summary !== null) summaries.set(data.compactionId, summary)\n }\n continue\n }\n if (type === 'user/message') {\n const source = data.source !== null && typeof data.source === 'object' ? data.source as Record<string, unknown> : null\n const compactionId = source !== null\n && source.kind === 'plugin' && typeof source.compactionId === 'string'\n ? source.compactionId\n : null\n if (compactionId !== null) {\n // A compaction checkpoint: the model-visible envelope never renders —\n // the marker shows its summary instead (null when the page cut left\n // the summary event outside).\n nodes.set(seq, { kind: 'compaction', seq, summary: summaries.get(compactionId) ?? null })\n continue\n }\n nodes.set(seq, {\n kind: 'user',\n seq,\n content: Array.isArray(data.content) ? data.content as readonly unknown[] : [],\n })\n continue\n }\n if (type === 'assistant/message') {\n const message = data.message !== null && typeof data.message === 'object' ? data.message as Record<string, unknown> : null\n const content = message !== null && Array.isArray(message.content) ? message.content : []\n nodes.set(seq, {\n kind: 'assistant',\n seq,\n blocks: (content as unknown[]).map(assistantBlockOf),\n })\n continue\n }\n if (type === 'tool/result') {\n const message = data.message !== null && typeof data.message === 'object' ? data.message as Record<string, unknown> : null\n const source = message?.source !== null && typeof message?.source === 'object' ? message.source as Record<string, unknown> : null\n const first = Array.isArray(message?.content) ? (message.content as unknown[])[0] : undefined\n const block = first !== null && typeof first === 'object' ? first as Record<string, unknown> : null\n const callId = typeof source?.callId === 'string' ? source.callId\n : typeof message?.toolCallId === 'string' ? message.toolCallId\n : typeof block?.toolCallId === 'string' ? block.toolCallId\n : null\n const call = callId !== null ? calls.get(callId) ?? null : null\n nodes.set(seq, {\n kind: 'tool-result',\n seq,\n call,\n // Current DSH stores tool output directly on the message. Historical\n // logs may still wrap it in one tool-result block; preserve both.\n content: message?.role === 'tool'\n ? Array.isArray(message.content) ? message.content as readonly unknown[] : []\n : block !== null && Array.isArray(block.content) ? block.content as readonly unknown[]\n : Array.isArray(message?.content) ? message.content as readonly unknown[] : [],\n isError: message?.isError === true || block?.isError === true || data.error === true\n || (data.error !== null && typeof data.error === 'object'),\n })\n continue\n }\n }\n return nodes\n}\n\n/** The `page` verb of a history face, re-proved and bound to its owner.\n * Hostile objects (any accessor backed by host state can throw) degrade to\n * undefined instead of escaping the read. */\nfunction readPageOf(face: unknown): SessionPageFace['page'] | undefined {\n if (face === null || typeof face !== 'object') return undefined\n try {\n const fn = (face as Record<string, unknown>).page\n return typeof fn === 'function' ? (fn as SessionPageFace['page']).bind(face) : undefined\n } catch {\n return undefined\n }\n}\n\n/**\n * The gateway history page verb, resolved through the DECLARED inject\n * (see {@link watchHistoryFaces}) and bound up front: a method extracted\n * unbound loses `this`, and the traced `remote` proxy that hands it out\n * requires the inject to resolve at all.\n */\nlet declaredPage: SessionPageFace['page'] | undefined\n\nconst faceListeners = new Set<() => void>()\n\nfunction setPageFace(page: SessionPageFace['page'] | undefined): void {\n declaredPage = page\n for (const listener of [...faceListeners]) listener()\n}\n\n/** The page face resolved so far, for non-React readers (the fetcher builders). */\nexport function historyFace(): SessionPageFace['page'] | undefined {\n return declaredPage\n}\n\n/** Subscribe to face resolution and revocation (plugin reload/HMR). */\nexport function subscribeHistoryFace(listener: () => void): () => void {\n faceListeners.add(listener)\n return () => { faceListeners.delete(listener) }\n}\n\n/** The store snapshot both useSyncExternalStore seats read (client and hydration). */\nfunction faceSnapshot(): SessionPageFace['page'] | undefined {\n return declaredPage\n}\n\n/**\n * The React seat over the resolved page face. A mount can RACE the declared\n * inject — a watch rebuild (patchReload) remounts the slot components before\n * the injected fiber re-fires — so the first render may legitimately see no\n * face. Subscribing keeps that transient state from sticking: the fetchers\n * derived downstream rebuild when the face lands (or is revoked), instead of\n * degrading to the static note for the mount's whole lifetime.\n */\nexport function useHistoryFace(): SessionPageFace['page'] | undefined {\n return useSyncExternalStore(subscribeHistoryFace, faceSnapshot, faceSnapshot)\n}\n\n/**\n * Register the plugin's history face with the harness through the DECLARED\n * inject — both `remote` AND `remote.session` (the ui-chat idiom) must be in\n * one fiber's requirement list, because the traced `remote` proxy resolves\n * `.session` through the context and each name needs the other's\n * declaration; an undeclared read of the traced proxy throws instead of\n * resolving. The callback re-runs on every unload/remount, so it owns the\n * slot's lifetime. The face itself is re-proven: a never-fired invocation\n * or a hostile property read leaves the slot unset — nothing here can throw.\n */\nexport function watchHistoryFaces(ctx: ClientCtx): void {\n ctx.inject(['remote', 'remote.session'], (c) => {\n try {\n const session = (c as ClientCtx & { remote?: { session?: SessionPageFace } }).remote?.session\n setPageFace(session !== undefined ? readPageOf(session) : undefined)\n } catch {\n setPageFace(undefined)\n }\n return () => { setPageFace(undefined) }\n })\n}\n\n/** The rows array of a successful history page, under the served envelope. */\nfunction rowsOf(response: unknown): readonly unknown[] {\n // Envelope unwrapping: the remote resolves to the ClientResult itself\n // ({ok, value}). A bare {records} payload passes too. Anything else\n // rejects so the caller can offer a retry instead of claiming absence.\n let payload: unknown = response\n if (payload !== null && typeof payload === 'object' && 'ok' in payload) {\n const r = payload as { ok?: unknown; value?: unknown }\n if (r.ok !== true || r.value === null || typeof r.value !== 'object') {\n throw new Error('history rpc failed')\n }\n payload = r.value\n }\n if (payload === null || typeof payload !== 'object') throw new Error('history rpc failed')\n const rows = (payload as { records?: unknown }).records\n if (!Array.isArray(rows)) throw new Error('history rpc failed')\n return rows\n}\n\n/**\n * The session's history reader over the gateway remotes (`remote.session.page`),\n * from the declared-inject slot. The page cuts message-aligned pages, so the\n * returned read covers `seq` whenever the durable log still holds it: the\n * inclusive cut is pinned to the seq itself, the exclusive bound one past\n * it. Undefined when the slot holds no face (the inject never fired or\n * served no usable page verb) — callers keep their static degradation.\n */\nfunction pageReaderOf(sessionId: string): ((seq: number) => Promise<unknown>) | undefined {\n // The face resolved at build time: absent face = the caller's static\n // degradation, a resolved face stays bound for the fetcher's lifetime.\n const page = declaredPage\n if (page === undefined) return undefined\n return (seq) => {\n // The inclusive log cut pinned to the target seq, the exclusive bound\n // one past it.\n return page({\n address: { kind: 'session' as const, sessionId },\n throughSeq: seq,\n beforeSeq: seq + 1,\n }, new AbortController().signal)\n }\n}\n\n/**\n * Build the browser's per-session fetcher over the gateway history face\n * (`remote.session.page`): message-aligned pages whose inclusive cut pinned\n * to `seq` (exclusive bound one past it) cover the seq whenever the durable\n * log still holds it. Undefined when no face was resolved at build time —\n * the caller keeps its static preview-plus-hint degradation. Found nodes\n * cache in the closure: one mount re-reading a row never re-fetches.\n */\nexport function makeContentFetcher(sessionId: string): ContentFetcher | undefined {\n const read = pageReaderOf(sessionId)\n if (read === undefined) return undefined\n // Fetched nodes cache in the closure: history is immutable, so one mount\n // re-reading a row never re-fetches.\n const cache = new Map<number, ConversationNodeLike>()\n return async (seq) => {\n const hit = cache.get(seq)\n if (hit !== undefined) return hit\n // The whole envelope is re-proven (no-white-screen guarantee): a failed or\n // malformed read rejects so the browser offers a retry instead of guessing.\n const node = pageNodesOf(rowsOf(await read(seq))).get(seq) ?? null\n if (node !== null) cache.set(seq, node)\n return node\n }\n}\n\n/**\n * Map one raw durable event into the epoch content the browser renders. A\n * `request/header` yields each tool's producer description and raw schema; a\n * `system/message` yields the prompt text alone (its tools live in the\n * request header). Both mirror the host fold's per-entry guards — a null or\n * primitive tool entry degrades to an unnamed row instead of throwing the\n * read. Null when the event carries neither.\n */\nfunction headerContentOf(event: { type: string; data: Record<string, unknown> }): HeaderEpochContent | null {\n const { type, data } = event\n if (type === 'system/message') {\n const message = data.message !== null && typeof data.message === 'object'\n ? data.message as Record<string, unknown>\n : null\n const system = systemTextOf(message?.content)\n return system === null ? null : { system, tools: [] }\n }\n const rawHeader = data.header !== null && typeof data.header === 'object'\n ? data.header as Record<string, unknown>\n : null\n if (rawHeader === null) return null\n const toolsRaw = Array.isArray(rawHeader.tools) ? rawHeader.tools : []\n const tools: HeaderEpochContent['tools'] = []\n for (const t of toolsRaw) {\n const tool = t !== null && typeof t === 'object' ? t as Record<string, unknown> : null\n tools.push({\n name: tool !== null && typeof tool.name === 'string' ? tool.name : '?',\n ...(tool !== null && typeof tool.description === 'string' && tool.description !== ''\n ? { description: tool.description }\n : {}),\n schema: t,\n })\n }\n return { tools }\n}\n\n/**\n * The on-demand CONTENT fetch for the browser's System and Tools sections —\n * the lazy counterpart of the node fetcher above. One seq-anchored history\n * read off the requested seq returns the page holding that event (non-message\n * events ride the page verbatim); a `request/header` maps to the epoch's\n * tools, a `system/message` to the prompt's text. Landed content caches per\n * seq (history is immutable), and OLDER\n * epochs sharing the page cache for free — stepping back through epochs walks\n * the same pages. Undefined when no history face exists — the browser keeps a\n * metadata-only degradation instead.\n */\nexport function makeHeaderFetcher(sessionId: string): HeaderFetcher | undefined {\n const read = pageReaderOf(sessionId)\n if (read === undefined) return undefined\n const cache = new Map<number, HeaderEpochContent>()\n return async (seq) => {\n const hit = cache.get(seq)\n if (hit !== undefined) return hit\n // Same re-prove contract as the node fetcher: a failed or malformed read\n // rejects so the browser offers a retry instead of guessing.\n const rows = rowsOf(await read(seq))\n let picked: HeaderEpochContent | null = null\n for (const entry of rows) {\n const ev = eventOf(entry)\n if (ev === null || (ev.type !== 'request/header' && ev.type !== 'system/message')) continue\n const content = headerContentOf(ev)\n if (content === null) continue\n // The page's exclusive bound is seq + 1, so every content event on it\n // is the picked one or an OLDER one — cache them all.\n cache.set(ev.seq, content)\n if (ev.seq === seq) picked = content\n }\n return picked\n }\n}\n","/**\n * The 上下文批改 RPC surface shared by BOTH halves — the single source of truth\n * for the route path, request/response envelope, and operation vocabulary.\n * This is the only place allowed to spell the path: duplicating it risks a\n * silent Client/Host drift into 404s.\n *\n * Namespacing is a HARD constraint, not a preference: the connection registry\n * THROWS on a duplicate exact path (`exact Fetch route \"…\" is already\n * registered`), and the panel coexists with `dsh-context@0.60.0`, which owns\n * `/api/dsh-context/*` (`docs/01` F1, `UPSTREAM.md` §3.1 row 1).\n */\n\n/** Our authenticated `/api` prefix. Everything below hangs off it. */\nexport const REDLINE_API_PREFIX = '/api/dsh-context-redline'\n\n/**\n * The edit-surface channel: ONE endpoint with an `op` discriminator\n * (`docs/02` §5.2), so adding an op never adds a route.\n */\nexport const REDLINE_CHANNEL_ROUTE = `${REDLINE_API_PREFIX}/redline`\n\n/** Upstream's on-demand timeline detail route, renamed (M1-04). */\nexport const REDLINE_DETAIL_ROUTE = `${REDLINE_API_PREFIX}/detail`\n\n/** Upstream's platform-balance route, renamed (M1-04). */\nexport const REDLINE_BALANCE_ROUTE = `${REDLINE_API_PREFIX}/balance`\n\n/** Upstream's cold-history warm-up route, renamed (M1-04). */\nexport const REDLINE_BACKFILL_ROUTE = `${REDLINE_API_PREFIX}/backfill`\n\n/** Every route this plugin registers, for the namespace contract and tests. */\nexport const REDLINE_ROUTES: readonly string[] = [\n REDLINE_CHANNEL_ROUTE,\n REDLINE_DETAIL_ROUTE,\n REDLINE_BALANCE_ROUTE,\n REDLINE_BACKFILL_ROUTE,\n]\n\n/** Success envelope (`docs/02` §5.1). */\nexport interface RedlineOk<T> {\n readonly ok: true\n readonly value: T\n}\n\n/** Failure envelope: a STABLE machine code plus a short wire message. */\nexport interface RedlineFailure {\n readonly ok: false\n readonly error: {\n /** One of `REDLINE_ERROR` (`src/shared/redline-errors.ts`). */\n readonly code: string\n /** Short English wire text. The user-facing wording is the client's i18n. */\n readonly message: string\n }\n}\n\nexport type RedlineEnvelope<T> = RedlineOk<T> | RedlineFailure\n\n/**\n * One call on the channel. `op` is the discriminator; every other field is\n * op-specific. The vocabulary itself is declared with its handlers in\n * `src/host/redline-channel.ts` (M2 fills the table).\n */\nexport interface RedlineCall {\n readonly op: string\n readonly sessionId?: string\n readonly [field: string]: unknown\n}\n\n/** The success half of the envelope. */\nexport function redlineOk<T>(value: T): RedlineOk<T> {\n return { ok: true, value }\n}\n\n/** The failure half of the envelope. */\nexport function redlineFailure(code: string, message: string): RedlineFailure {\n return { ok: false, error: { code, message } }\n}\n\n/**\n * Narrow an untrusted JSON body to a {@link RedlineCall}. Returns null for\n * anything that is not an object with a non-empty string `op`.\n */\nexport function asRedlineCall(body: unknown): RedlineCall | null {\n if (body === null || typeof body !== 'object' || Array.isArray(body)) return null\n const op = (body as { op?: unknown }).op\n if (typeof op !== 'string' || op === '') return null\n return body as RedlineCall\n}\n","/**\n * The timeline source behind the Context tab and the /redline modal —\n * reconciles the two `redlineTimeline` wire generations into the single\n * value the cards have always rendered.\n *\n * Generations (the marker is `detailRev` on the delivered value):\n * - INLINE (older hosts, channel-less deployments, the baseline-gate\n * fallback): the wire value carries the collections in place. It passes\n * through untouched — no fetch ever happens.\n * - SPLIT (current host with the detail route live): the wire value is the\n * slim head (~1KB — every session.list row, control baseline, and push\n * frame carries it whole). The collections arrive from the plugin's\n * `/api/dsh-context-redline/detail` fetch route (host/detail.ts): one targeted read\n * when the tab/modal first opens, then a debounced refetch whenever the\n * pushed `detailRev` outruns the served detail. Closed tabs fetch nothing.\n *\n * The no-stale-content guarantees: the store is per session and shared by\n * the tab and the modal; a refetch is single-flight with a trailing edge\n * (a rev bumped mid-flight re-reads after settle); responses race-safe by\n * revision (latest wins, with the refold exception — a host that refolded\n * restarts the revision, and a response matching the requested rev is\n * accepted regardless of order); a transport failure keeps the last good\n * detail and backs off; an absent answer (the session left the live set)\n * stops the trailing until the head moves again. With no detail at all,\n * failure surfaces as a retryable note on the detail cards instead of an\n * empty chart.\n */\n\nimport { useEffect, useMemo, useSyncExternalStore } from 'react'\nimport type { ContextTimeline, ContextTimelineDetail } from '../shared/types'\nimport type { ClientCtx, SessionStandardProps } from './services'\nimport { asRecord, numOf, objectsOf, projectionOf, timelineOf } from './services'\nimport { REDLINE_DETAIL_ROUTE } from '../shared/redline-route'\n\n// The detail route of host/detail.ts — re-declared here: the client bundle\n// inlines every import, and the host module must never reach it. Same-origin\n// POST under the harness's authenticated `/api` fence.\nconst DETAIL_ROUTE = REDLINE_DETAIL_ROUTE\n\n/**\n * Narrow the detail endpoint's payload to a render-safe value (the same\n * boundary rigor as `timelineOf`): collections re-proved per item, scalars\n * zeroed, a missing/NaN revision rejects the whole payload (the caller then\n * shows the retryable failure note instead of half-merged data).\n */\nexport function detailOf(value: unknown): ContextTimelineDetail | null {\n const data = asRecord(value)\n if (data === null) return null\n if (typeof data.rev !== 'number' || !Number.isFinite(data.rev) || data.rev < 0) return null\n // The slim head rides the payload for the Agent network's cold-node ring\n // fetch; a missing or malformed head only degrades that composition (the\n // detail cards never read it), so it drops out instead of rejecting the\n // payload the cards consume.\n const head = timelineOf(data.head)\n return {\n rev: data.rev,\n ...(head !== null ? { head } : {}),\n requests: objectsOf(data.requests),\n events: objectsOf(data.events),\n nodes: objectsOf(data.nodes),\n droppedNodes: numOf(data.droppedNodes),\n archive: objectsOf(data.archive),\n ...(typeof data.surfaceFloor === 'number' ? { surfaceFloor: data.surfaceFloor } : {}),\n ...(typeof data.archiveFloor === 'number' ? { archiveFloor: data.archiveFloor } : {}),\n ...(data.fileOps !== undefined ? { fileOps: objectsOf(data.fileOps) } : {}),\n ...(typeof data.fileOpsFloor === 'number' ? { fileOpsFloor: data.fileOpsFloor } : {}),\n }\n}\n\n/**\n * The detail reader over the plugin's own `/api` fetch route (host/detail.ts).\n * Same-origin POST through the harness's authenticated fence; the returned\n * thunk resolves the session's current detail, `null` when the session is not\n * live anymore, and rejects on transport failure or a malformed payload (the\n * store turns the two into the retryable state).\n */\nexport function makeDetailFetcher(\n ctx: ClientCtx,\n sessionId: string,\n): (() => Promise<ContextTimelineDetail | null>) | undefined {\n void ctx\n if (sessionId === '') return undefined\n return async () => {\n const response = await fetch(DETAIL_ROUTE, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ sessionId }),\n })\n if (!response.ok) throw new Error(`dsh-context-redline: detail route HTTP ${response.status}`)\n const r = asRecord(await response.json())\n if (r === null || r.ok !== true) throw new Error('dsh-context-redline: detail read failed')\n if (r.value === null) return null\n const detail = detailOf(r.value)\n if (detail === null) throw new Error('dsh-context-redline: detail read malformed')\n return detail\n }\n}\n\n/** The store's observable snapshot, rebuilt on every transition (identity-gated for useSyncExternalStore). */\nexport interface DetailSnap {\n /** The newest accepted detail (kept while a refetch is in flight — the cards never flicker back to loading). */\n detail: ContextTimelineDetail | null\n /** The last read settled without data (transport failure or absence) and there is no detail to show. */\n failed: boolean\n /** A read is scheduled or in flight. */\n pending: boolean\n}\n\nconst EMPTY_SNAP: DetailSnap = { detail: null, failed: false, pending: false }\n\n/** The fetch debounce base; each consecutive failure doubles the wait, capped at 3 doublings. */\nconst DETAIL_DEBOUNCE_MS = 300\n\n/**\n * One session's detail ledger. Exported for tests (a zero debounce makes the\n * machine synchronous-ish); the app reaches it through `detailStoreOf`.\n */\nexport class DetailStore {\n private detail: ContextTimelineDetail | null = null\n /** The revision of `detail` (latest-wins cursor); -1 before the first landing. */\n private acceptedRev = -1\n /** The newest revision the head has asked for. */\n private wantedRev = -1\n /** The head rev the IN-FLIGHT (or scheduled) read targets — the refold exception's acceptance key. */\n private targetRev = -1\n /** The head rev seen last — a DECREASE means the host refolded (revisions restart). */\n private lastHeadRev = -1\n private failed = false\n private inFlight = false\n private timer: ReturnType<typeof setTimeout> | null = null\n private failures = 0\n private readonly listeners = new Set<() => void>()\n private snap: DetailSnap = EMPTY_SNAP\n\n constructor(\n private readonly fetcher: (() => Promise<ContextTimelineDetail | null>) | undefined,\n private readonly baseDelay: number = DETAIL_DEBOUNCE_MS,\n ) {}\n\n readonly subscribe = (fn: () => void): (() => void) => {\n this.listeners.add(fn)\n return () => this.listeners.delete(fn)\n }\n\n readonly getSnapshot = (): DetailSnap => this.snap\n\n /**\n * The head's current revision arrived: schedule the trailing-edge read\n * when it outruns the served detail. A rev DECREASE means the host\n * refolded the session (a discarded checkpoint, a restart): revisions are\n * no longer comparable, so the ledger resets and refetches.\n */\n request(rev: number): void {\n if (rev < this.lastHeadRev) {\n this.acceptedRev = -1\n this.wantedRev = -1\n this.detail = null\n this.failed = false\n }\n this.lastHeadRev = rev\n if (rev <= this.acceptedRev || rev <= this.wantedRev) return\n this.wantedRev = rev\n this.schedule()\n }\n\n /** Re-arm after a failure (the cards' retry note): immediate, backoff reset. */\n readonly retry = (): void => {\n this.failures = 0\n if (this.detail !== null) return\n if (this.timer !== null) {\n clearTimeout(this.timer)\n this.timer = null\n }\n if (!this.inFlight) void this.fire()\n }\n\n private schedule(): void {\n if (this.timer !== null) return\n this.timer = setTimeout(() => {\n this.timer = null\n void this.fire()\n }, this.baseDelay * 2 ** Math.min(this.failures, 3))\n this.emit()\n }\n\n private async fire(): Promise<void> {\n // A trailing timer fired while an earlier read is still in flight — that\n // read's settle re-arms when the wanted rev still outruns the served one.\n if (this.inFlight) return\n if (this.fetcher === undefined) {\n // No session id to read for: the typed failure arms the cards' note.\n // (The slim head is only served when the host route went live, so this\n // is the exotic path.)\n this.failed = true\n this.emit()\n return\n }\n this.inFlight = true\n this.targetRev = this.wantedRev\n this.emit()\n try {\n const d = await this.fetcher()\n if (d !== null) {\n // Latest-wins, with the refold exception: a response matching the\n // requested rev is the current truth even when its number trails a\n // pre-refold landing.\n if (d.rev >= this.acceptedRev || d.rev === this.targetRev) {\n this.detail = d\n this.acceptedRev = d.rev\n }\n this.failures = 0\n this.failed = false\n } else {\n // Absent (the session left the live set): keep the last detail, stop\n // the trailing until the head moves again (a disposed session's rev\n // never does), and arm the note only when nothing is showable.\n this.wantedRev = this.acceptedRev\n this.failed = this.detail === null\n this.failures++\n }\n } catch {\n this.failed = this.detail === null\n this.failures++\n }\n this.inFlight = false\n // The head moved while the read settled (or an earlier read lost the\n // race): trail once more, debounced.\n if (this.wantedRev > this.acceptedRev) this.schedule()\n this.emit()\n }\n\n private emit(): void {\n const pending = this.timer !== null || this.inFlight\n const next: DetailSnap = { detail: this.detail, failed: this.failed, pending }\n if (next.detail === this.snap.detail && next.failed === this.snap.failed && next.pending === this.snap.pending) return\n this.snap = next\n for (const fn of this.listeners) fn()\n }\n}\n\n/** Page-lifetime per-session stores (the tab and the modal share one). */\nconst stores = new Map<string, DetailStore>()\n\nexport function detailStoreOf(ctx: ClientCtx, sessionId: string): DetailStore {\n let store = stores.get(sessionId)\n if (store === undefined) {\n store = new DetailStore(makeDetailFetcher(ctx, sessionId))\n stores.set(sessionId, store)\n }\n return store\n}\n\n/** Test isolation: drop every cached store. */\nexport function resetTimelineDetailStores(): void {\n stores.clear()\n}\n\nexport type DetailState = 'legacy' | 'loading' | 'ready' | 'failed'\n\nexport interface TimelineSource {\n /**\n * The value the cards render — the inline generation's value untouched, or\n * the slim head merged with the fetched detail collections (empty while\n * the first read is in flight; `detailState` names that).\n */\n data: ContextTimeline | null\n detailState: DetailState\n retryDetail: () => void\n}\n\nconst noopSubscribe = (): (() => void) => () => {}\nconst noopRetry = (): void => {}\n\n/**\n * The view's one read of the timeline (see the module header for the\n * generation rules). Hook-order safe: every hook runs unconditionally, the\n * branches below only shape the returned record.\n */\nexport function useTimelineSource(ctx: ClientCtx, props: SessionStandardProps): TimelineSource {\n const head = projectionOf(props, 'redlineTimeline', timelineOf)\n const sessionId = typeof props.sessionId === 'string' ? props.sessionId : ''\n // The split marker: the slim head carries the detail revision; anything\n // else (the inline value, the gate fallback, a corrupt payload) is the\n // inline generation — `headRev` null means no detail channel work at all.\n const headRev = head !== null && typeof head.detailRev === 'number' ? head.detailRev : null\n const slim = headRev !== null\n const store = useMemo(\n () => (slim ? detailStoreOf(ctx, sessionId) : null),\n [ctx, sessionId, slim],\n )\n const snap = useSyncExternalStore(\n store !== null ? store.subscribe : noopSubscribe,\n store !== null ? store.getSnapshot : () => EMPTY_SNAP,\n )\n useEffect(() => {\n if (store !== null && headRev !== null) store.request(headRev)\n }, [store, headRev])\n\n return useMemo<TimelineSource>(() => {\n if (head === null) return { data: null, detailState: 'loading', retryDetail: noopRetry }\n if (!slim || store === null) return { data: head, detailState: 'legacy', retryDetail: noopRetry }\n const detail = snap.detail\n const data: ContextTimeline = detail === null\n ? head\n : {\n ...head,\n requests: detail.requests,\n events: detail.events,\n nodes: detail.nodes,\n droppedNodes: detail.droppedNodes,\n archive: detail.archive,\n // Slim heads serve no floors; the detail's pair lands whole here.\n ...(detail.surfaceFloor !== undefined ? { surfaceFloor: detail.surfaceFloor } : {}),\n ...(detail.archiveFloor !== undefined ? { archiveFloor: detail.archiveFloor } : {}),\n ...(detail.fileOps !== undefined ? { fileOps: detail.fileOps } : {}),\n ...(detail.fileOpsFloor !== undefined ? { fileOpsFloor: detail.fileOpsFloor } : {}),\n }\n const detailState: DetailState = detail !== null ? 'ready' : snap.failed ? 'failed' : 'loading'\n return { data, detailState, retryDetail: store.retry }\n }, [head, slim, store, snap])\n}\n","/**\n * Shared wire contract — the snapshot model exchanged between the Host and Client halves. Delivered as the `view()` payload of the\n * `redlineTimeline`/`redlineHeaders` session projections (registered on `ctx.sessionProjections`; the registry pushes finished views as\n * `session/projection` frames — see host/timeline.ts). TYPE-ONLY host-side module: both halves import these as `import type`, so nothing\n * from here ever reaches the runtime bundles.\n */\n\nimport type { ActivityState } from '../host/activity'\nimport type { HeadersState } from '../host/headers'\nimport type { TimelineState } from '../host/fold'\n// The registry package ROOT carries the `@deepseek-ai/cordis` Context\n// augmentation (`sessionProjections` service); the `/types` subpath below\n// only declares the merge-extensible maps.\nimport type {} from '@deepseek-ai/dsh-session-projection'\nimport type {} from '@deepseek-ai/dsh-session-projection/types'\n\ndeclare module '@deepseek-ai/dsh-session-projection/types' {\n // Both maps take the plugin keys: `SessionProjectionMap` names the\n // client-visible wire values, `SessionProjectionStateMap` constrains the\n // unit `key`s and their fold-state types (the split arrived with\n // dsh 0.1.1 — the definition's K constraint moved to the state map).\n interface SessionProjectionMap {\n /**\n * The plugin's context timeline: current composition, counters, and the\n * headline anchor. Since the split generation the wire value is the SLIM\n * head (every delivery channel — session.list rows, control baselines,\n * push frames — carries it whole); the per-request history, context\n * events, and the surface/archive collections ride the on-demand detail\n * channel ({@link ContextTimelineDetail}, host/detail.ts). Channel-less\n * hosts keep the inline generation (the collections stay in the value).\n * Key absence = the plugin's host half is not composed.\n */\n redlineTimeline: ContextTimeline\n /**\n * The request-header CONTENT epochs (full system prompt + tool schemas)\n * behind the timeline's envelope figures. A separate unit so the hot\n * `redlineTimeline` value stays lean: headers change rarely, so this\n * value (and its pushes) change only when a `request/header` lands.\n * The Context browser card reads it to show the actual prompt/schema\n * content of a picked step (key absence = older host: tokens only).\n */\n redlineHeaders: ContextHeaders\n /**\n * The per-day activity ledger (billed tokens + completed requests keyed\n * by local day) behind the Context Dashboard's heatmap — the timeline's\n * \"current snapshot\" cannot draw a per-day chart, so the overview reads\n * this off every session-list row's projection column. Tiny (one small\n * record per day, retention-capped), so riding every list row costs\n * nothing next to the timeline head. Key absence = older host: the\n * heatmap degrades to its empty note.\n */\n redlineActivity: ContextActivity\n }\n interface SessionProjectionStateMap {\n redlineTimeline: TimelineState\n redlineHeaders: HeadersState\n redlineActivity: ActivityState\n }\n}\n\n/**\n * The priced surface buckets. `skill` carries every skill-machinery content\n * the harness injects (issue #66): the `<available_skills>` catalog digest,\n * a user-explicit `/name` invocation's instructions message, and the content\n * a `skill`-tool load returns (modeled as a tool result by the harness).\n */\nexport type Category = 'user' | 'inject' | 'skill' | 'assistant' | 'tool'\n\n/**\n * One live system-prompt node (Snapshot.systems) — the harness models the\n * system prompt as a surface node, so its TEXT is fetched on demand from the\n * `system/message` event at `seq`. `tokens` is the node's heuristic\n * price (0 for a dormant empty node, which the harness reads as \"no system\n * prompt\"); the effective figure is the LAST node with `tokens > 0`.\n */\nexport interface SystemPromptNode {\n seq: number\n time: number\n tokens: number\n}\n\n/**\n * The stats board's count figures, precomputed host-side over the RETAINED\n * request/event records (the same set the detail payload serves). Carried by\n * the split-generation wire head so the board — and the Agent card's\n * per-session request tally — never need the collections themselves.\n * `steps` doubles as the retained request-record count.\n */\nexport interface TimelineCounts {\n turns: number\n steps: number\n injects: number\n compactions: number\n prunes: number\n}\n\n/**\n * The newest retained request record's billing summary — the headline's\n * derived-occupancy anchor (`prompt + surface movement since`), carried by\n * the split-generation wire head so the headline never needs the request\n * records themselves.\n */\nexport interface TimelineLast {\n seq: number\n total: number\n prompt?: number\n}\n\n/** One day's ledger entry in the `redlineActivity` projection. */\nexport interface ActivityDay {\n /**\n * Billed tokens folded from provider-reported usage that day (prompt-side\n * input + cache read/write + output). Requests without a usage settlement\n * count only toward `requests` — a fabricated 0 never understates the day.\n */\n tokens: number\n /** Completed model calls (assistant settlements) that day. */\n requests: number\n /**\n * The day's billed buckets keyed provider → model → pricing period — the\n * same SessionCostUsage raw material the timeline's session-cost totals\n * carry, scoped to the day the requests INITIATED in, so the client prices\n * each day off the same model-price book as the KPI band. ADDITIVE-OPTIONAL:\n * absent on rows folded before the field existed (older plugin builds), on\n * days whose settlements predate any model header, and on settlements the\n * provider left unmetered — the usage chart degrades to tokens-only bars.\n */\n cost?: SessionCostUsage\n}\n\n/**\n * The per-session daily activity ledger (`redlineActivity` wire value):\n * day key (`YYYY-MM-DD`, host-local — see shared/days.ts) → that day's\n * billed volume, retention-capped by the fold. The Context Dashboard merges\n * every listed session's ledger into its activity heatmap.\n */\nexport interface ContextActivity {\n days: Record<string, ActivityDay>\n}\n\n/**\n * The per-user display-preference vocabulary of the `dsh-context-redline` settings\n * namespace — the ONE declaration both halves share: the Host registers the\n * namespace schema against it (host/settings.ts), the Client binds the scope\n * and edits fields by name (client/settings.ts). Type-only, so both bundles\n * erase it.\n */\nexport type DefaultGranularity = 'step' | 'turn'\n\nexport type DefaultTrendMode = 'total' | 'delta'\n\n/** File Activity row order: most operations first, most-recently-touched first, or path ascending. */\nexport type DefaultFileSort = 'count' | 'latest' | 'path'\n\n/** Tool-definition row order: largest schema first, most call hits first, or name ascending. */\nexport type DefaultToolSort = 'size' | 'count' | 'name'\n\n/** Where the Context view is offered: the conversation tab, the right Sidebar, or both. */\nexport type DefaultPlacement = 'all' | 'tab' | 'sidebar'\n\n/** Whether the Context Insights panel's sidebar entry is offered at all. */\n\nexport interface PluginSettings {\n defaultPlacement: DefaultPlacement\n defaultGranularity: DefaultGranularity\n defaultTrendMode: DefaultTrendMode\n defaultToolSort: DefaultToolSort\n defaultFileSort: DefaultFileSort\n}\n\n/** The section fields the settings card edits, as the Host schema names them. */\nexport type SettingsField = keyof PluginSettings\n\nexport interface Snapshot {\n ok: boolean\n /**\n * The host's baseline-gate record, present ONLY when the running harness\n * is below the plugin's supported baseline: the host then folds nothing\n * and every figure in this snapshot is zero/empty. The client keeps\n * rendering the (blank) cards and pops the upgrade gate modal naming\n * `current` (the detected harness version) and `minimum` (the baseline).\n */\n unsupported?: {\n current: string\n minimum: string\n }\n model?: string\n provider?: string\n contextWindow?: number\n current: {\n system: number\n tools: number\n user: number\n inject: number\n skill: number\n assistant: number\n tool: number\n total: number\n }\n /**\n * Image blocks live in the CURRENT context (user uploads plus tool-result\n * images, nested blocks included) — the sum over the live surface nodes'\n * `imgs`, so compaction/prune shrink it. Absent from older hosts; clients\n * treat absence as zero.\n */\n images?: number\n /**\n * Tool calls whose result is live in the CURRENT context (one `tool/result`\n * folds to one `tool` surface node). Calls still in flight and results\n * compacted/pruned out of the surface are not counted. Absent from older\n * hosts; clients treat absence as zero.\n */\n toolCalls?: number\n /**\n * Whole-session human-input tally: every non-injection `user/message`\n * (the user's own messages) plus every answered `ask_user_question`\n * result (one per answer submission). A running total over the COMPLETE\n * log — turns the retained window no longer holds still count. Absent\n * from older hosts; clients treat absence as zero.\n */\n humanInputs?: number\n /**\n * The user's newest own message as a one-line bounded preview (first text\n * block, whitespace collapsed, ~80 chars): the session cards' footer line.\n * Additive-optional — absent from rows folded before the field existed\n * (older hosts, idle sessions' cached rows); clients hide the line then.\n */\n lastUser?: string\n /**\n * Split-generation head fields — present exactly when the host serves the\n * SLIM head (the heavy collections moved to the on-demand detail channel,\n * host/detail.ts) and absent on the inline generation (older or\n * channel-less hosts serve the collections in place). `detailRev` is the\n * detail's revision marker: it bumps whenever the detail collections\n * change, so an open tab refetches on the push alone.\n */\n counts?: TimelineCounts\n last?: TimelineLast\n detailRev?: number\n /**\n * The per-request history / context-event collections. On the split\n * generation these stay ABSENT from the wire value (every session.list row,\n * control baseline, and push frame would carry them whole otherwise); the\n * client fills them from the detail channel ({@link ContextTimelineDetail}).\n */\n requests: RequestRecord[]\n events: ContextEventRecord[]\n /**\n * Cumulative session-cost raw material (per-provider, per-model billed\n * token totals — see SessionCostUsage). Absent until a request with a\n * known model reports usage.\n */\n cost?: SessionCostUsage\n /**\n * Whole-session timing totals (see TimingTotals). Absent until the first\n * step lifecycle completes in the log (older plugin builds never folded\n * one — clients treat absence as an empty timing card).\n */\n timing?: TimingTotals\n /**\n * The live system-prompt nodes, oldest first — the browser's per-step source\n * for the System section. Absent on rows folded before this field existed\n * (older plugin builds; the client then falls back to the header epoch's\n * own `systemTokens`, the legacy wire shape those builds served).\n */\n systems?: SystemPromptNode[]\n /**\n * The served live surface: the newest `maxNodes` tail PLUS every live inject node older than the tail (injections land first and are\n * few,\n * so they are pinned). Seq-ordered, oldest first.\n */\n nodes: SurfaceNode[]\n /** Live nodes not served (the overflow beyond `maxNodes`, minus pinned injects — see `nodes`). */\n droppedNodes: number\n /**\n * Recently REMOVED surface nodes (compaction/prune shadows), each stamped\n * with `gone` (the replacing event's seq). Together with `nodes` this lets\n * the Context browser reconstruct the assembled surface of any retained\n * step: alive at request R = seq < R.seq && (gone undefined || gone > R.seq).\n */\n archive: SurfaceNode[]\n /**\n * Coverage floor of the served live `nodes`: the newest seq among the\n * `droppedNodes` live nodes not served. Present only when droppedNodes > 0.\n */\n surfaceFloor?: number\n /**\n * Coverage floor of `archive`: the newest `gone` among archive entries the\n * retention bounds dropped. Steps with seq < archiveFloor may miss removed\n * nodes (the browser shows the reconstruction as approximate).\n */\n archiveFloor?: number\n /**\n * The fold-derived file-operation log and its trim floor — present on the\n * INLINE wire value (channel-less hosts) and on the detail payload\n * (ContextTimelineDetail), absent from the slim head (they ride the detail\n * channel there).\n */\n fileOps?: FileOpRecord[]\n fileOpsFloor?: number\n}\n\n/**\n * The on-demand DETAIL payload of the split `redlineTimeline` generation —\n * the heavy collections (per-request records, context events, the served\n * surface window, and the removed-node archive) that the slim wire head no\n * longer carries through every delivery channel. The host serves it off the\n * live fold state at the `/dsh-context-redline` `detail` endpoint (host/detail.ts);\n * `rev` mirrors the head's `detailRev` at build time and acts as the\n * client's latest-wins cursor.\n */\nexport interface ContextTimelineDetail {\n rev: number\n /**\n * The slim wire head at the SAME fold cut as the collections: the\n * composition scalars (`current`), the window/model envelope, and the\n * precomputed counts. Sessions listed cold (never attached since the\n * requesting unit last changed) carry no `redlineTimeline` projection row\n * for the browser's list reads, so the Agent network card fetches this\n * head per node to render their composition rings. The host always serves\n * it; optional so a payload missing it still serves the collections (the\n * detail cards) and only the ring composition degrades.\n */\n head?: ContextTimeline\n requests: RequestRecord[]\n events: ContextEventRecord[]\n nodes: SurfaceNode[]\n droppedNodes: number\n archive: SurfaceNode[]\n surfaceFloor?: number\n archiveFloor?: number\n /**\n * The fold-derived file-operation log (shared/fileOps.ts): one record per\n * executed file op, newest-retained, covering the full log (never\n * window-bound like the client-side join derivation it replaces on this\n * generation). Code-Mode nested dispatches book ops located on their\n * parent run_code result (`parent`).\n */\n fileOps?: FileOpRecord[]\n /** The newest dropped op's seq when the op log trimmed (coverage honesty, same family as archiveFloor). */\n fileOpsFloor?: number\n}\n\n/**\n * One executed file operation (a settled file-tool call with a resolved\n * target), folded host-side from the durable tool lifecycle: the call's\n * name+arguments (`tool/call`), the result's presentation meta and error\n * (`tool/result`), or a nested Code-Mode settle (`tool/ptc-dispatch`,\n * located on its parent run_code result via `parent` + `program`).\n *\n * `gone` is NOT host-stamped: the client joins it from the detail's archive\n * at render time (the op's result node leaving the live surface marks where\n * its content is still viewable). Line deltas are estimates read off the\n * call ARGUMENTS (an edit's old/new strings, a write's content), never off\n * result payloads.\n */\nexport interface FileOpRecord {\n seq: number\n /** The op's file; for a pathless search the searched PATTERN (`pattern: true`). */\n path: string\n kind: 'read' | 'write' | 'search'\n tool: string\n time?: number\n err: boolean\n added: number\n removed: number\n /** What was searched for, when a search named both a path and a pattern. */\n detail?: string\n /** Meta-attributed search op only: matched lines the result reported for this file. */\n hits?: number\n /** Read ops only: the exact 1-based window the result meta reported, else the `limit`-argument estimate (`est: true`). */\n read?: { start: number; count: number } | { count: number; est: true }\n /** Nested Code-Mode op only: the run_code result node the op ran under (the locate target). */\n parent?: number\n /** Nested Code-Mode op only: the run_code program's model-authored description. */\n program?: string\n /** The searched-pattern marker: `path` is a pattern, not a file — display must not relativize it. */\n pattern?: true\n /** Client-joined archive stamp (see the type note); absent on the wire. */\n gone?: number\n}\n\n/**\n * The `redlineTimeline` projection's whole value — the same snapshot the Client has always rendered. `ok` is always `true` here (a\n * delivered projection is by definition available); kept for wire compatibility with the snapshot shape.\n */\nexport type ContextTimeline = Snapshot\n\n/**\n * The official token-meter `contextPressure` projection (registered by\n * `@deepseek-ai/dsh-token-meter` on the same `SessionProjectionMap`): the\n * provider-anchored occupancy of the NEXT request. The Client reads this key\n * directly instead of the Host mirroring it inside `redlineTimeline`\n * (token-meter owns estimation and replay — the docs' stated division of\n * labor). Fields are independent last-wins records; absent until a provider\n * reports usage. Absent key/value = the registry (or the meter) is not\n * composed — the Client falls back to its derived anchor.\n */\nexport interface ContextPressure {\n /** Provider-reported prompt size of the most recent request (input + cache). */\n pressureTokens?: number\n /** pressureTokens + heuristic surface movement since the sample (clamped ≥ 0). */\n projectedTokens?: number\n /** Newest recorded route capacity (last-wins). */\n contextWindow?: number\n}\n\n/**\n * The official token-meter `contextBreakdown` projection: the heuristic\n * composition rows the chat ring's click-open panel shows (system prompt,\n * tool schemas, conversation). The Client reads this key directly so the\n * composition card's proportions AND counts stay identical to the panel's\n * by construction; the message bucket is subdivided into the plugin's four\n * surface categories by the fold's per-category ratios. Absent key/value =\n * an older harness without the meter's projection units — callers fall back\n * to the fold's own sums (identical estimator, minus the image correction).\n */\nexport interface ContextBreakdown {\n systemTokens: number\n toolsTokens: number\n messageTokens: number\n}\n\n/**\n * The official token-meter `tokenUsage` projection (registered by\n * `@deepseek-ai/dsh-token-meter` on the same `SessionProjectionMap`): durable\n * cumulative provider-reported usage across the COMPLETE session log. The four\n * buckets are disjoint (reasoning tokens are already inside `outputTokens`).\n * The Client reads this key directly to compute the cache-hit share — the\n * exact same data the chat stats line below the input box shows, same formula\n * — instead of the Host mirroring it inside `redlineTimeline`. Absent until a\n * provider reports usage.\n */\nexport interface TokenUsage {\n /** Billed prompt tokens that missed the provider cache. */\n uncachedInputTokens: number\n /** Billed output tokens (reasoning included). */\n outputTokens: number\n /** Billed prompt tokens served from the provider cache. */\n cacheReadTokens: number\n /** Billed prompt tokens written into the provider cache. */\n cacheWriteTokens: number\n}\n\n/**\n * Cumulative billed-token totals for one pricing bucket of the session-cost\n * estimate (host-folded, never trimmed — running totals over the COMPLETE\n * session log, immune to the request/event retention bounds).\n */\nexport interface CostBucketTotals {\n uncached: number\n cacheRead: number\n cacheWrite: number\n output: number\n}\n\n/**\n * One completed tool name's whole-session call tally behind the timing\n * card's top-tools ranking (running totals, never trimmed).\n */\nexport interface ToolTimingTotals {\n calls: number\n ms: number\n}\n\n/**\n * Whole-session timing totals, host-folded from the durable `step/start` /\n * `step/end` / `tool/call` / `tool/result` lifecycle plus the model call's\n * first token (running totals over the COMPLETE session log — the same\n * never-trimmed framing as `cost`). The first token comes from the call's\n * own embedded stream (`assistant/message.data.stream` /\n * `assistant/attempt.data.stream`), matching the harness's own\n * session-stats fold. Durations are wall-clock milliseconds: `wallMs` sums\n * whole steps, `ttftMs` the step-start → first-token slice (the model wait)\n * and `genMs` the first-token → assistant-message slice (the generation) —\n * both only over calls whose stream carried a token delta, `toolsMs` the sum\n * of per-call tool durations (parallel calls each count, so it can overlap).\n * Absent until the first step lifecycle completes in the log.\n *\n * The generation window itself splits by WHAT was being decoded, off the\n * stream's `block-start` framing (`blockType`): `reasoningMs` (the model's\n * thinking), `textMs` (the answer text), and `toolArgMs` (the tool-call\n * arguments). Each marker owns the interval up to the next one (the last one\n * up to the assistant message), so the three tile the marker span and together\n * account for essentially all of `genMs` — the span opens at the first marker,\n * which can sit marginally before the first token, so it is not an exact\n * partition. They are ADDITIVE-OPTIONAL: cached projection rows written before\n * the split carry `genMs` without them, so the card falls back to the\n * un-split shape instead of the cache row being discarded (the\n * stateVersion-15 rationale in host/timeline.ts).\n */\nexport interface TimingTotals {\n /** Summed wall time of completed steps (the session's active time). */\n wallMs: number\n /** Summed step-start → first-token time (the model wait, TTFT). */\n ttftMs: number\n /** Summed first-token → assistant-message time (the generation). */\n genMs: number\n /** Reasoning-decode slice of `genMs` (the model's thinking). */\n reasoningMs?: number\n /** Counted reasoning-decode blocks (the Thinking slice's tally). */\n reasoningBlocks?: number\n /** Answer-text decode slice of `genMs`. */\n textMs?: number\n /** Counted answer-text decode blocks (the Answer slice's tally). */\n textBlocks?: number\n /** Tool-call-argument decode slice of `genMs`. */\n toolArgMs?: number\n /**\n * Counted tool-call-argument decode blocks — one per tool call whose\n * arguments the stream decoded (the Tool args slice's tally). The counts are\n * ADDITIVE-OPTIONAL like their spans: a row cached before they existed (or a\n * call whose stream framed no blocks) carries none, and the card qualifies\n * only what was actually counted.\n */\n toolArgBlocks?: number\n /**\n * The decode-throughput seat, paired exactly as the harness's own\n * session-stats fold pairs them: `speedTokens` sums provider-reported\n * output tokens and `speedMs` the first-token → assistant-message\n * windows, over the calls that carried BOTH a first-token stamp and a\n * usage report — a subset of `genMs`, which counts every token-stamped\n * call regardless of usage. Additive-optional: cached rows written before\n * the seat existed lack them, and the card falls back to no chip.\n */\n speedTokens?: number\n speedMs?: number\n /** Completed model calls (assistant messages folded). */\n calls: number\n /** Summed per-call durations of completed tool calls. */\n toolsMs: number\n /** Completed tool calls (call/result pairs folded). */\n toolCalls: number\n /** Per-tool-name tallies behind the timing card's ranking (bounded). */\n tools: Record<string, ToolTimingTotals>\n}\n\n/**\n * One billed model's cumulative totals split by pricing period. Providers\n * without period-based pricing book everything under `peak` (the list-price\n * period); DeepSeek splits at fold time — peak windows bill at list price,\n * off-peak (all other hours) at half.\n */\nexport interface CostModelUsage {\n peak?: CostBucketTotals\n off?: CostBucketTotals\n}\n\n/**\n * The session-cost estimate's raw material: cumulative provider-reported\n * billed-token totals, keyed by the request envelope's DSH provider id (''\n * when a log carries none) and then by its model id — the exact (provider,\n * model) faces the Client's model-price book resolves (the models.dev\n * registry, client/modelPrices.ts). Running totals per key; absent until a\n * request with a known model reports usage.\n */\nexport interface SessionCostUsage {\n [provider: string]: { [model: string]: CostModelUsage }\n}\n\n/** One model-visible message on the surface, with its heuristic token price. */\nexport interface SurfaceNode {\n seq: number\n time?: number\n cat: Category\n tokens: number\n /** Image blocks inside this node's message (absent when zero). */\n imgs?: number\n /**\n * Removal marker, present only on `archive` entries: the seq of the\n * replacement surface event that shadowed this node (compaction/prune).\n * The node is part of the assembled context of every request with\n * seq > this node.seq and seq < gone.\n */\n gone?: number\n form?: string\n /**\n * The producer identity the matching inject event names (host pricing.ts\n * `injectionSourceName`: the plugin id, the reconciled instruction files,\n * or the durable kind). Stamped on injection nodes alongside the event, so\n * the browser rows label them the way the events card does; absent when the\n * source carries no readable identity or the node predates the stamp.\n */\n name?: string\n text?: string\n tool?: string\n err?: boolean\n skill?: string\n calls?: string[]\n}\n\n/** One answered model call (a step); consecutive records of one turn form it. */\nexport interface RequestRecord {\n turn?: number\n step?: number\n time: number\n seq: number\n system: number\n tools: number\n user: number\n inject: number\n assistant: number\n tool: number\n total: number\n prompt?: number\n /**\n * Skill-machinery tokens of this request (the `skill` composition\n * category — catalog digests, invocation instructions, `skill`-tool\n * loads). Always written by the current fold; absent on rows folded\n * before the category existed (read as 0).\n */\n skill?: number\n /**\n * Billed cache-read (served) prompt tokens of this request — the\n * hit-rate numerator against `prompt` (input + cacheRead + cacheWrite).\n * Absent on older hosts / usage-less requests; zero is a real value.\n */\n cacheRead?: number\n output?: number\n /**\n * Turn-mode aggregate marker, set by the Client's aggregateByTurn (one bar\n * per turn shows its LAST step's record). The Host never sets it.\n */\n stepCount?: number\n /**\n * Delta-mode signed net change, set by the Client's deltaOf (only present\n * on the delta-transformed records the TrendChart plots). The Host never\n * sets it.\n */\n net?: number\n}\n\n/** A notable context event (compaction, prune, injection, model switch). */\nexport interface ContextEventRecord {\n seq: number\n time: number\n kind: 'compaction' | 'prune' | 'inject' | 'model' | 'mode'\n form?: string\n tokens?: number\n count?: number\n sub?: string\n name?: string\n /** One-line producer account (notice-form summary), shown after the name. */\n detail?: string\n from?: string\n to?: string\n /** Turn/step of the request logged right BEFORE the event (host-stamped). */\n fromTurn?: number\n fromStep?: number\n /** Turn/step of the request this event contributed to (host-stamped). */\n turn?: number\n step?: number\n}\n\n/**\n * Sentinel `HeaderTool.plugin` value marking a tool whose provider could not\n * be attributed: it was already registered in the harness tool service when\n * this plugin's runtime attribution hook installed (boot-time third-party\n * tools — e.g. local-link plugins that apply before dsh-context-redline). The client\n * renders a localized \"unknown plugin\" tag with an explanatory tooltip. No\n * real plugin name can collide (it is not a valid package identifier).\n */\nexport const UNKNOWN_TOOL_SOURCE = '<unknown-plugin>'\n\n/** One tool of a request-header epoch, with its display price. */\nexport interface HeaderTool {\n name: string\n tokens: number\n /**\n * The registering plugin's label, when attribution is known: the host's\n * best-effort attribution (`mcp:<server>` for MCP tools, or the pinned\n * first-party package map), or a `plugin` field carried by the raw header\n * entry — no supported-baseline harness path writes one, but the read\n * stays defensive for foreign/newer producers. `UNKNOWN_TOOL_SOURCE` marks\n * a tool whose provider predates the attribution hook; absent means\n * nothing is known and the browser shows no tag.\n */\n plugin?: string\n}\n\n/**\n * One request-header epoch's METADATA: the epoch boundaries and token prices\n * in force from this event's seq until the next epoch. The epoch CONTENT\n * (full system prompt text, tool descriptions/schemas) is not projected —\n * every session.list row, control baseline, push frame, and projection-cache\n * checkpoint would otherwise carry it per session × epoch. The client\n * fetches one epoch's content on demand (a seq-anchored history read off\n * `seq`) as a {@link HeaderEpochContent}.\n */\nexport interface HeaderRecord {\n seq: number\n time: number\n /** The epoch's estimated system-prompt tokens; absent when it logged no system prompt. */\n systemTokens?: number\n tools: HeaderTool[]\n}\n\n/** The `redlineHeaders` projection value: the bounded epoch list (newest last). */\nexport interface ContextHeaders {\n headers: HeaderRecord[]\n}\n\n/**\n * The fetched CONTENT of one request-header epoch — the full system prompt\n * text and per-tool descriptions/schemas, mapped client-side off the raw\n * durable event (see historyPage.ts). Tool identity joins the epoch metadata\n * by `name`; absent description/schema means the raw entry carried none.\n */\nexport interface HeaderEpochContent {\n system?: string\n tools: Array<{\n name: string\n description?: string\n /** The raw JSON schema object the model received (plain JSON). */\n schema?: unknown\n }>\n}\n\n/** One currency's DeepSeek open-platform balance figures. */\nexport interface PlatformBalanceEntry {\n /** The ISO code the platform reported (`CNY` / `USD`). */\n currency: string\n /** Total available funds: `granted` + `toppedUp`. Derived here rather than read\n * from the platform's own `total_balance`, which rounds independently of its\n * parts and can land a cent away from what the breakdown beside it shows. */\n total: number\n /** The not-expired granted (gift) balance. */\n granted: number\n /** The topped-up balance. */\n toppedUp: number\n}\n\n/**\n * The DeepSeek open-platform balance, served by the plugin's\n * `/api/dsh-context-redline/balance` fetch route (host/balance.ts). `null` on the\n * wire — and nothing rendered client-side — whenever the platform is not\n * configured or the read fails: the capsule only ever shows a live figure.\n */\nexport interface PlatformBalance {\n /** Whether the platform reports the balance sufficient for API calls. */\n isAvailable: boolean\n /** One entry per currency the account holds; at least one. */\n balances: PlatformBalanceEntry[]\n}\n","/**\n * Per-step context assembly — the pure reconstruction behind the Context\n * browser card.\n *\n * A request record R was snapshotted by the Host exactly as dispatched:\n * header in force + the model-visible surface BEFORE the response landed.\n * Given the timeline's live `nodes` (newest tail) and `archive` (removed\n * nodes stamped with `gone`), the surface assembled into R is:\n *\n * every node with seq < R.seq AND (gone undefined OR gone > R.seq)\n *\n * For the LIVE view (the next request's context) it is simply the current\n * live nodes. Coverage is honest: when the served window cannot contain the\n * full answer (older live nodes dropped, or removals older than the archive\n * retention), the result carries the flags the UI turns into notices.\n */\n\nimport type { ContextHeaders, ContextTimeline, HeaderRecord, SurfaceNode, SystemPromptNode } from '../shared/types'\n\nexport interface Assembled {\n /** True when browsing the live surface (the next request's context). */\n live: boolean\n /** The header epoch in force (null = headers projection absent or none yet). */\n header: HeaderRecord | null\n /**\n * The system prompt in force at the shown step (null = none), resolved from\n * the timeline's live `systems` nodes; on rows folded before that field\n * existed the header epoch's own envelope figure stands in.\n */\n system: SystemPromptNode | null\n /** The assembled surface messages, in seq order. */\n nodes: SurfaceNode[]\n /** Live nodes outside the served window that are also part of the context. */\n missingLive: number\n /** True when removals this step depends on may exceed archive retention. */\n approximate: boolean\n}\n\n/** The header epoch in force at `seq` (last logged before it), or the newest. */\nexport function headerAt(headers: ContextHeaders | null, seq: number | null): HeaderRecord | null {\n if (headers === null || headers.headers.length === 0) return null\n if (seq === null) return headers.headers[headers.headers.length - 1]\n for (let i = headers.headers.length - 1; i >= 0; i--) {\n if (headers.headers[i].seq < seq) return headers.headers[i]\n }\n return null\n}\n\n/**\n * The system prompt in force at `seq` (null = none) — the LAST live system\n * node at or before it carrying tokens, which is exactly the host fold's\n * \"last nonempty surviving system\" rule and therefore agrees with the\n * per-step `system` figure the fold recorded. Rows folded before `systems`\n * existed carry none; the header epoch's own figure stands in for them (the\n * legacy wire shape older plugin builds served — current epochs fold\n * metadata-only, so the fallback only ever fires on those cached rows).\n */\nexport function systemAt(\n data: ContextTimeline,\n header: HeaderRecord | null,\n seq: number | null,\n): SystemPromptNode | null {\n const systems = data.systems\n if (systems !== undefined && systems.length > 0) {\n for (let i = systems.length - 1; i >= 0; i--) {\n const node = systems[i]\n if (node.tokens <= 0) continue\n if (seq === null || node.seq < seq) return node\n }\n return null\n }\n return header !== null && header.systemTokens !== undefined\n ? { seq: header.seq, time: header.time, tokens: header.systemTokens }\n : null\n}\n\nexport function assemble(data: ContextTimeline, headers: ContextHeaders | null, seq: number | null): Assembled {\n const live = seq === null\n let nodes: SurfaceNode[]\n if (live) {\n nodes = data.nodes.slice()\n } else {\n const picked: SurfaceNode[] = []\n for (const n of data.nodes) {\n if (n.seq < seq) picked.push(n)\n }\n for (const n of data.archive) {\n if (n.seq < seq && n.gone !== undefined && n.gone > seq) picked.push(n)\n }\n nodes = picked\n }\n nodes.sort((a, b) => a.seq - b.seq)\n\n let missingLive = 0\n if (data.droppedNodes > 0) {\n // Live: every dropped live node is part of the current context. A past\n // step: the dropped slice sits at or below `surfaceFloor`, so a step\n // after it contains them all (an older step's unknown subset is left\n // unflagged rather than overstated).\n if (live || (data.surfaceFloor !== undefined && seq > data.surfaceFloor)) {\n missingLive = data.droppedNodes\n }\n }\n const approximate = !live\n && data.archiveFloor !== undefined\n && seq < data.archiveFloor\n\n const header = headerAt(headers, seq)\n return { live, header, system: systemAt(data, header, seq), nodes, missingLive, approximate }\n}\n\n/** 「当前这一步」的读数:统计卡那 3 格 + `本步可见 N 条 · ≈X tokens`(`docs/10` M4-07)。 */\nexport interface StepStats {\n /** 该步列表里的条目总数(demo 的 `本步可见 N 条`)。 */\n readonly listed: number\n /** 模型可见条目 = 列表里**没有** `gone` 的那些。 */\n readonly visible: number\n /** 列表里**已失效**的原文条数(demo 那句「另 N 条被遮蔽」)。 */\n readonly shadowed: number\n /** 可见条目里的用户消息条数。 */\n readonly user: number\n /** 可见条目里的注入内容条数。 */\n readonly inject: number\n /** 整张列表的估算 token 合计(`≈` 前缀由界面加)。 */\n readonly tokens: number\n /**\n * 列表里**没有** `tokens` 的条数(`docs/00` S1.1:缺失时显示 `—`,不得用 0 冒充)。\n * 线上 schema 里 `tokens` 是 **optional**(`z.number().optional()`),而 TS 类型写成必填 ——\n * 也就是这种情况**真的会发生**(丑陋的类型/契约错位,先按\"数出来、说清楚\"处理,见下)。\n * 求和那格没法显示 `—`,所以单列出来,界面据此说明「另有 N 条未计入」。\n */\n readonly missingTokens: number\n}\n\n/**\n * The three cells the demo defines (user ruling 2026-10-06, `docs/10` M4-07).\n *\n * 口径**完全取自 `assemble()` 已经算好的那张列表**,不再自己定边界:\n * `assemble()` 对\"某一步\"返回的 `nodes` 里既有仍然有效的条目,也有**在那一步还活着、\n * 如今已被接替**的原文(判据 `n.gone !== undefined`,因为原文在那一步尚未被替换)。\n * 所以:\n * · `visible` = 列表里没有 `gone` 的;\n * · `shadowed` = 列表里有 `gone` 的(界面把它渲染成\"已被接替\"那一行);\n * · 两个分类计数只数**可见**的(demo 同样从 `vis` 里筛);\n * · `tokens` = 整张列表的合计(对得上 `本步可见 N 条 · ≈X tokens` 里那个 N)。\n * 按 seq 去重:早期那次把同一条替换体渲染两遍、面板列 5 项却报 7 项(2026-10-02 用户截图抓到的 #1600 重复计数)。\n */\nexport function stepStatsOf(assembly: { readonly nodes: readonly SurfaceNode[] }): StepStats {\n const seen = new Set<number>()\n let listed = 0\n let visible = 0\n let shadowed = 0\n let user = 0\n let inject = 0\n let tokens = 0\n let missingTokens = 0\n for (const n of assembly.nodes) {\n if (seen.has(n.seq)) continue\n seen.add(n.seq)\n listed += 1\n if (typeof n.tokens === 'number') tokens += n.tokens\n else missingTokens += 1\n if (n.gone === undefined) {\n visible += 1\n if (n.cat === 'user') user += 1\n else if (n.cat === 'inject') inject += 1\n } else {\n shadowed += 1\n }\n }\n return { listed, visible, shadowed, user, inject, tokens, missingTokens }\n}\n","/**\n * The browser's DNA mode: decompose an assembled context into ONE band per\n * item (the system prompt, every tool schema, every surface message) and\n * lay them out in the order the model actually reads them — the context's\n * \"fingerprint\" strip behind the composition bar's `dna` toggle.\n *\n * The order is PROMPT order, which is also the order items joined the\n * context: the system prompt and tool schemas prefix every request, so they\n * lead the strip; the message flow follows in seq (chronological) order.\n * The system band rides the timeline's own `systems` nodes (the prompt's real\n * surface positions), the tool bands their header epoch. The header epoch's\n * own seq is NOT usable as an ordering key: dsh appends `request/header` at\n * dispatch time of the first request that uses a header (agent.ts —\n * 'initial'/'resume'/'change'/'series'), a bookkeeping snapshot that lands\n * AFTER every message already in context. A mid-session refresh would\n * otherwise park the tools bands in the middle of the strip, behind the very\n * tool results those schemas describe. A refreshed epoch REPLACES the prefix\n * in place — the strip reflects that by keeping the current epoch's bands at\n * the front (the band's tooltip carries the epoch's time).\n */\n\nimport type { Category, SurfaceNode } from '../shared/types'\nimport type { Assembled } from './assemble'\n\n/**\n * One band of the DNA strip. Header bands carry their tokens only; message\n * bands hand the node through so the label builder reads tool/form/skill\n * straight off it (the union discriminates on `cat` — no defensive guards).\n */\nexport type DnaItem =\n | { key: string; cat: 'system' | 'tools'; tokens: number; time?: number }\n | { key: string; cat: Category; tokens: number; time?: number; node: SurfaceNode }\n\nexport function dnaOf(view: Assembled): DnaItem[] {\n const items: DnaItem[] = []\n if (view.system !== null) {\n items.push({ key: 'sys', cat: 'system', tokens: view.system.tokens, time: view.system.time })\n }\n if (view.header !== null) {\n for (const tool of view.header.tools) {\n items.push({ key: 'tool:' + tool.name, cat: 'tools', tokens: tool.tokens })\n }\n }\n // `assemble` guarantees seq order; zero-token items keep their band (the\n // bar drops zero widths, the reading order stays truthful).\n for (const n of view.nodes) {\n items.push({\n key: 'n' + String(n.seq),\n cat: n.cat,\n tokens: n.tokens,\n node: n,\n ...(n.time !== undefined ? { time: n.time } : {}),\n })\n }\n return items\n}\n","/**\n * The file-operation parser — the ONE derivation of \"what the agent did to\n * files\" from a settled file-tool call. Shared by both halves: the host fold\n * books the op log from the durable tool lifecycle (tool/call +\n * tool/result + tool/ptc-dispatch), and the client's INLINE-generation\n * fallback re-derives ops from the conversation-window join when an older\n * host serves no `fileOps`.\n *\n * Tool coverage matches the harness's built-ins on every supported baseline\n * (0.1.5-rc.1): read / read_image / write / edit (tool-fs) and grep / glob\n * (tool-fs-search), plus the Anthropic-style `str_replace_editor` (view\n * reads, every other command writes). Line deltas are estimates read off the\n * call ARGUMENTS (an edit's old/new strings, a write's content), never off\n * result payloads. A search resolves further when its result's bounded\n * presentation meta names the matched files — the ops then row per real\n * file with the match count, and only a capped (`truncated`) or malformed\n * meta falls back to the call's own target (the narrowing path, else the\n * searched pattern itself).\n */\n\nimport type { FileOpRecord } from './types'\n\n/** Parse a call's raw JSON arguments; non-string/malformed/non-record inputs yield null. */\nexport function parseCallArgs(raw: unknown): Record<string, unknown> | null {\n if (typeof raw !== 'string' || raw === '') return null\n try {\n const parsed: unknown = JSON.parse(raw)\n return parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)\n ? parsed as Record<string, unknown>\n : null\n } catch {\n return null\n }\n}\n\nconst KIND_BY_TOOL: Record<string, FileOpRecord['kind']> = {\n read: 'read',\n read_image: 'read',\n write: 'write',\n edit: 'write',\n grep: 'search',\n glob: 'search',\n}\n\n/** The file purpose of a tool, or null for non-file tools (bash, web_search…). */\nexport function kindOfTool(tool: string | undefined): FileOpRecord['kind'] | null {\n if (tool === undefined) return null\n return KIND_BY_TOOL[tool] ?? null\n}\n\n/**\n * The file purpose of one executed call. Like {@link kindOfTool} except for\n * the one file tool whose purpose follows its arguments: `str_replace_editor`\n * reads on `view` and writes on every other command (create / str_replace /\n * insert — an unknown command writes too; the call failed and the row keeps\n * its error flag).\n */\nexport function kindOfCall(tool: string, args: Record<string, unknown> | null): FileOpRecord['kind'] | null {\n if (tool === 'str_replace_editor') return args !== null && args.command === 'view' ? 'read' : 'write'\n return kindOfTool(tool)\n}\n\n/**\n * Whether a settled call's arguments can yield an op at all: the file tools\n * plus `str_replace_editor`, whose purpose follows its `command`. The public\n * face of the gate {@link opsOfCall} short-circuits on — callers that decide\n * whether to parse or to KEEP a call's raw arguments ask here instead of\n * restating the tool list.\n */\nexport function opBearingTool(tool: string): boolean {\n return tool === 'str_replace_editor' || kindOfTool(tool) !== null\n}\n\n/**\n * Whether a call's raw arguments must ride the fold state\n * (TimelineState.callNames): every op-bearing tool, plus `run_code`, whose\n * `description` labels the ops its nested dispatches book at flush time.\n */\nexport function rawArgsNeeded(tool: string): boolean {\n return opBearingTool(tool) || tool === 'run_code'\n}\n\n/**\n * The operation's target path: the path-ish argument of read/write tools;\n * for searches the narrowing `path`, else the pattern itself (a pathless\n * grep/glob's target IS the pattern — the workspace-wide search text).\n */\nexport function pathOfArgs(tool: string, args: Record<string, unknown> | null): string | null {\n if (args === null) return null\n if (tool === 'grep' || tool === 'glob') {\n const p = args.path\n if (typeof p === 'string' && p !== '') return p\n const pattern = args.pattern\n return typeof pattern === 'string' && pattern !== '' ? pattern : null\n }\n for (const k of ['file_path', 'filePath', 'path']) {\n const v = args[k]\n if (typeof v === 'string' && v !== '') return v\n }\n return null\n}\n\n/** Rendered line count: '' is 0, a trailing newline closes its own line. */\nexport function linesOf(s: string): number {\n if (s === '') return 0\n let n = 0\n for (let i = 0; i < s.length; i++) if (s[i] === '\\n') n++\n return s.endsWith('\\n') ? n : n + 1\n}\n\n/** The added/removed pair of one content-bearing argument set, or zeros. */\nfunction pairOf(added: unknown, removed: unknown): { added: number; removed: number } {\n return {\n added: typeof added === 'string' ? linesOf(added) : 0,\n removed: typeof removed === 'string' ? linesOf(removed) : 0,\n }\n}\n\n/**\n * The signed line footprint of one call: an edit removes its old string and\n * adds its new one; a write adds its content (the pre-existing body, if any,\n * is unknowable from the arguments — the estimate stays honest about that);\n * `str_replace_editor` splits the same shapes across its commands. Callers\n * reach here only with parsed args (a null parse yields no path).\n */\nfunction deltaOf(tool: string, args: Record<string, unknown>): { added: number; removed: number } {\n if (tool === 'edit') return pairOf(args.new_string, args.old_string)\n if (tool === 'write') return pairOf(args.content, undefined)\n if (tool === 'str_replace_editor') {\n if (args.command === 'str_replace') return pairOf(args.new_str, args.old_str)\n if (args.command === 'insert') return pairOf(args.new_str, undefined)\n if (args.command === 'create') return pairOf(args.file_text, undefined)\n }\n return { added: 0, removed: 0 }\n}\n\n/** The exact window a read's result meta reports: `offset` plus the retained\n * `lines` array (the same bounded payload the read card renders from). Null\n * for a foreign or malformed meta. */\nfunction readWindowOf(meta: unknown): { start: number; count: number } | null {\n if (meta === null || typeof meta !== 'object') return null\n const m = meta as { path?: unknown; offset?: unknown; lines?: unknown }\n if (typeof m.path !== 'string' || m.path === '') return null\n if (typeof m.offset !== 'number' || !Number.isFinite(m.offset) || m.offset < 1) return null\n if (!Array.isArray(m.lines) || m.lines.length === 0) return null\n return { start: m.offset, count: m.lines.length }\n}\n\n/** The limit estimate: the tool reads up to `limit` lines from `offset`;\n * absent when the call reads unbounded. */\nfunction readEstimateOf(args: Record<string, unknown>): { count: number; est: true } | undefined {\n const limit = args.limit\n return typeof limit === 'number' && Number.isFinite(limit) && limit > 0\n ? { count: Math.floor(limit), est: true }\n : undefined\n}\n\n/** What a read op shows: the exact window off the result meta, else the\n * limit estimate, else nothing (an unbounded read names no footprint). */\nfunction readOf(meta: unknown, args: Record<string, unknown>): { start: number; count: number } | { count: number; est: true } | undefined {\n const win = readWindowOf(meta)\n if (win !== null) return { start: win.start, count: win.count }\n return readEstimateOf(args)\n}\n\n/**\n * A search op's detail: the pattern, with the include filter appended when\n * one narrowed the call. A patternless (malformed) search has no detail.\n */\nfunction searchDetailOf(args: Record<string, unknown> | null): string | undefined {\n const pattern = args?.pattern\n if (typeof pattern !== 'string' || pattern === '') return undefined\n const include = args?.include\n return typeof include === 'string' && include !== '' ? `${pattern} (${include})` : pattern\n}\n\n/**\n * The files a search demonstrably reached, read off the result's bounded\n * presentation meta (grep groups matched lines by file; glob lists paths).\n * Only the COMPLETE list attributes: a capped search (`truncated`) names a\n * partial file set, and a malformed meta names none — both fall back to the\n * call's own target. Each entry carries the reported match count.\n */\nfunction searchFilesOf(meta: unknown): { path: string; hits: number }[] | null {\n if (meta === null || typeof meta !== 'object') return null\n const m = meta as { shape?: unknown; truncated?: unknown; files?: unknown; paths?: unknown }\n if (m.truncated !== false) return null\n const files: { path: string; hits: number }[] = []\n if (m.shape === 'matches' && Array.isArray(m.files)) {\n for (const f of m.files) {\n if (f === null || typeof f !== 'object') continue\n const group = f as { path?: unknown; matches?: unknown }\n if (typeof group.path === 'string' && group.path !== '' && Array.isArray(group.matches)) {\n files.push({ path: group.path, hits: group.matches.length })\n }\n }\n } else if (m.shape === 'paths' && Array.isArray(m.paths)) {\n for (const p of m.paths) {\n if (typeof p === 'string' && p !== '') files.push({ path: p, hits: 0 })\n }\n }\n return files.length > 0 ? files : null\n}\n\n/**\n * The one-shot per-call op assembly, uniform across every producer: the\n * host's call/result pairing (args off the armed call, meta off the\n * result), the nested Code-Mode settle (no meta exists on a dispatch — the\n * read window and per-file search attribution degrade to the argument-only\n * forms), and the client's inline-generation join fallback. Returns zero to\n * N records: a search with the complete matched-file meta rows per file;\n * any other file call rows once; a non-file tool (or a call whose arguments\n * resolve no target) rows nothing.\n */\nexport function opsOfCall(input: {\n seq: number\n tool: string\n argsRaw?: unknown\n meta?: unknown\n err?: boolean\n time?: number\n gone?: number\n parent?: number\n program?: string\n}): FileOpRecord[] {\n // A non-op-bearing tool never rows one — skip its arguments parse entirely\n // (a call's arguments are its largest payload, and the fold may hand a large\n // bash/pwsh call here).\n const args = opBearingTool(input.tool) ? parseCallArgs(input.argsRaw) : null\n const kind = kindOfCall(input.tool, args)\n if (kind === null) return []\n const stamp: FileOpRecord = {\n seq: input.seq,\n kind,\n tool: input.tool,\n err: input.err === true,\n added: 0,\n removed: 0,\n path: '',\n ...(input.time !== undefined ? { time: input.time } : {}),\n ...(input.gone !== undefined ? { gone: input.gone } : {}),\n ...(input.parent !== undefined ? { parent: input.parent } : {}),\n ...(input.program !== undefined ? { program: input.program } : {}),\n }\n // A search whose result meta carries the COMPLETE matched-file list rows\n // its ops per real file — even when the call's own arguments failed to\n // parse (the detail line just drops out). The call's own target (the\n // searched path, or the pattern for a workspace-wide search) rows TOO —\n // \"what was searched\" and \"what got hit\" both count; only the degenerate\n // single-file search (the target IS the sole matched file) skips the\n // duplicate target row.\n if (kind === 'search') {\n const files = searchFilesOf(input.meta)\n if (files !== null) {\n const detail = searchDetailOf(args)\n const target = args !== null ? pathOfArgs(input.tool, args) : null\n const narrowed = args !== null && typeof args.path === 'string' && args.path !== ''\n const targetOps: FileOpRecord[] = target !== null && !files.some(f => f.path === target)\n ? [{\n ...stamp,\n path: target,\n ...(narrowed && detail !== undefined ? { detail } : {}),\n ...(narrowed ? {} : { pattern: true as const }),\n }]\n : []\n return [\n ...targetOps,\n ...files.map(f => ({\n ...stamp,\n path: f.path,\n ...(detail !== undefined ? { detail } : {}),\n ...(f.hits > 0 ? { hits: f.hits } : {}),\n })),\n ]\n }\n }\n if (args === null) return []\n const path = pathOfArgs(input.tool, args)\n if (path === null) return []\n const { added, removed } = deltaOf(input.tool, args)\n const narrowed = typeof args.path === 'string' && args.path !== ''\n const detail = kind === 'search' && narrowed ? searchDetailOf(args) : undefined\n const read = kind === 'read' ? readOf(input.meta, args) : undefined\n return [{\n ...stamp,\n path,\n added,\n removed,\n ...(detail !== undefined ? { detail } : {}),\n ...(read !== undefined ? { read } : {}),\n ...(kind === 'search' && !narrowed ? { pattern: true as const } : {}),\n }]\n}\n","/**\n * Tool-call argument summaries — shared between the Context browser (row\n * previews) and the step brief (input chips / reply enrichment). A call's\n * preview is its bash-style `description`, or the target path\n * (`file_path`/`path`/`filePath`) for edit/read/write tools.\n */\n\nimport type { ConversationNodeLike } from './services'\n// The argument parser lives in the shared layer (shared/fileOps.ts) since the\n// op-log generation — the host fold parses the same raw strings there.\nimport { parseCallArgs } from '../shared/fileOps'\n\nexport { parseCallArgs }\n\nexport function summaryInArgs(args: Record<string, unknown> | null): string | null {\n if (args === null) return null\n for (const k of ['description', 'file_path', 'path', 'filePath']) {\n const v = args[k]\n if (typeof v === 'string' && v !== '') return v\n }\n return null\n}\n\nexport function callSummaryOf(conv: ConversationNodeLike | undefined): string | null {\n return summaryInArgs(parseCallArgs(conv?.call?.argsRaw))\n}\n\nexport function blockSummaryOf(conv: ConversationNodeLike | undefined): string | null {\n if (conv === undefined || !Array.isArray(conv.blocks)) return null\n for (const b of conv.blocks) {\n const blk = b !== null && typeof b === 'object' ? b as { kind?: string; argsRaw?: unknown } : null\n if (blk === null || blk.kind !== 'tool-call') continue\n const s = summaryInArgs(parseCallArgs(blk.argsRaw))\n if (s !== null) return s\n }\n return null\n}\n\n/**\n * All tool-call names in an assistant conversation node, in order. The fold's surface node keeps `calls` only for TEXT-LESS replies,\n * so a reply carrying both text and calls recovers its call breadcrumb here through the conversation join.\n */\nexport function callNamesOf(conv: ConversationNodeLike | undefined): string[] {\n if (conv === undefined || !Array.isArray(conv.blocks)) return []\n const names: string[] = []\n for (const b of conv.blocks) {\n const blk = b !== null && typeof b === 'object' ? b as { kind?: string; name?: unknown } : null\n if (blk !== null && blk.kind === 'tool-call' && typeof blk.name === 'string') names.push(blk.name)\n }\n return names\n}\n","/**\n * The detail collections' pending/failed note — the split generation's\n * visible loading story (timelineSource.ts): while the first detail read is\n * in flight the detail-driven cards show this strip instead of a misleading\n * empty state, and a settled-without-data read arms the retry button (never\n * a spinner that never resolves, never a silent empty chart). Callers guard\n * the failed state on a retry callback being wired (an unwired failure keeps\n * the plain text).\n */\n\nimport { type ReactElement } from 'react'\nimport type { ViewKit } from '../viewkit'\n\nexport function makeDetailNote(kit: ViewKit): (props: {\n /** The pending kind: the first read in flight, or settled without data. */\n state: 'loading' | 'failed'\n /** The retry affordance for the failed read; absent = the note renders inert text. */\n onRetry?: () => void\n /** The container's style class: cards use the shared empty well, the browser its inline note strip. */\n className?: string\n}) => ReactElement {\n const { t } = kit\n return function DetailNote(props: {\n state: 'loading' | 'failed'\n onRetry?: () => void\n className?: string\n }): ReactElement {\n const cls = props.className ?? 'redline-empty'\n if (props.state === 'loading') return <div className={cls}>{t('detail.loading')}</div>\n return (\n <div className={cls}>\n {props.onRetry !== undefined\n ? <button type=\"button\" className=\"redline-br-retry hover:brightness-[1.15]\" onClick={props.onRetry}>{t('detail.loadFailed')}</button>\n : t('detail.loadFailed')}\n </div>\n )\n }\n}\n","/**\n * Capability judgement — WHICH action a row gets, decided by the UNDERLYING EVENT\n * TYPE, never by the display category (`AGENTS.md` §2.3.1, `docs/01` F7/F7.2,\n * `docs/05` A17).\n *\n * Why it must be by event type: the category is a presentation grouping (injected\n * content and skill injection are both `user/message` underneath), while the\n * platform's rewrite rules are stated per event type. Judging by category is how\n * the earlier attempt shipped an assistant-rewrite branch that could only fail at\n * runtime — the UI must never offer a button that is guaranteed to error.\n *\n * The four \"no action, with a reason\" cases, and the one that matters most:\n * · `system/message` / tool definitions — the host protects node 0 → `inert`\n * (no action BAR at all, not an empty one);\n * · `assistant/message` — replace requires `sourceEventSeqs` covering the\n * shadowed node, but an assistant message is FORBIDDEN to carry it. The two\n * rules are mutually exclusive, so there is no working write at all;\n * · a shadowed original — no longer a surface node, so it cannot be a target;\n * · a compacted-away row — out of reach.\n *\n * And the rule that makes repeat editing work: the REPLACEMENT body is a current\n * surface node, so it stays editable. `shadowed` therefore means \"superseded by a\n * later replacement\", not \"is a replacement\".\n *\n * ── Why this lives in `src/shared/**` and not in `src/redline/**` ──────────\n * The BROWSER needs this rule too (it decides which action a row renders), and the\n * client bundle must not import `src/redline/**` — that is the bundle-purity gate\n * (`docs/02` §4, `docs/05` A13), enforced mechanically by\n * `scripts/namespace-contract.mjs` face 9 and by the tsdown client-bundle purity\n * plugin. Proved by reverse verification: a temporary `import { ability } from\n * '../redline/eligibility'` in `src/client/services.ts` reddens face 9 immediately.\n * `src/shared/**` is the documented home for logic BOTH halves run, so the rule\n * lives here once — never duplicated per half (a duplicated button rule is exactly\n * how the earlier attempt shipped an assistant-rewrite branch that could only fail).\n *\n * Purity: no `node:*`, no DOM, no React.\n */\n\n/** The seven row classes the panel groups by (`docs/03` §2). */\nexport type RowClass = 'system' | 'tools' | 'user' | 'inject' | 'skill' | 'assistant' | 'tool'\n\n/**\n * The stable reason keys. The client maps each to the sentence of `docs/03` R4.7 —\n * the host never ships user-facing prose for a refusal.\n */\nexport type BlockReason = 'system-head' | 'shadowed' | 'assistant-immutable' | 'compacted'\n\n/** One row, as far as capability judgement is concerned. */\nexport interface SurfaceRow {\n readonly seq: number\n /** The durable event type (`user/message`, `assistant/message`, `tool/result`, `system/message`…). */\n readonly type: string\n readonly cat: RowClass\n /** Superseded by a later replacement → no longer on the surface. */\n readonly shadowed: boolean\n /** Is itself a replacement body (a current surface node). */\n readonly isReplacement: boolean\n /** Buried by compaction. */\n readonly compacted: boolean\n}\n\n/** The judgement for one row. */\nexport interface Ability {\n /** May this row's content be rewritten at all? */\n readonly canRewrite: boolean\n /** Host-protected: render NO action area (`docs/03` R2.1). */\n readonly inert: boolean\n readonly shadowed: boolean\n readonly isReplacement: boolean\n /** 被压缩埋掉(够不到,既不能编辑也不能作废)。 */\n readonly compacted: boolean\n /** The \"advanced\" class: `Edit` is hidden behind the advanced switch (`docs/03` R2.5). */\n readonly advancedOnly: boolean\n /**\n * 能不能把这一条标为「不要」(`docs/11` D65,用户 2026-10-08 选 A)。\n * 判据与\"能不能编辑\"**不同**:助手消息**改不了但可以作废** —— 那正是它唯一的处置手段。\n * 宿主保护的两类、已被接替的、被压缩埋掉的:不给(与\"不能编辑\"同一批)。\n */\n readonly canExclude: boolean\n /** Present exactly when `canRewrite` is false — including inert rows, which still need a reason line. */\n readonly blockReason?: BlockReason\n}\n\n/**\n * One row's actions.\n * · `drop` —— 丢弃这一条的本地改动(有改动时才出现);\n * · `exclude` —— 标为「不要」(作废,开启子会话时逐字声明);\n * · `unexclude` —— 取消作废标记。\n * `exclude` 与 `edit` **互斥**(同一条记录只有一份,标了就清掉改动)。\n */\nexport type RowAction = 'edit' | 'drop' | 'exclude' | 'unexclude'\n\nexport function ability(row: SurfaceRow): Ability {\n const inert = row.cat === 'system' || row.cat === 'tools'\n // New carriers are zero-history sessions: editing assistant text changes only the migration copy, never the old log.\n const canRewrite = !inert && !row.shadowed && !row.compacted\n const canExclude = !inert && !row.shadowed && !row.compacted\n return {\n canRewrite,\n canExclude,\n inert,\n compacted: row.compacted,\n shadowed: row.shadowed,\n isReplacement: row.isReplacement,\n advancedOnly: row.cat === 'tool',\n // docs/11 实施共识 §6: when two reasons apply, the assistant rule wins (the\n // sentences differ, the action set does not). Inert rows keep a reason too —\n // \"no action bar\" is the layout, and the reason is the explanation the row\n // still owes the reader.\n ...(canRewrite\n ? {}\n : {\n blockReason: inert ? 'system-head' : row.shadowed ? 'shadowed' : 'compacted',\n }),\n }\n}\n\n/**\n * Which durable types each presentation bucket can hold, per the host fold\n * (`src/host/fold.ts` `categoryOf` + the header-epoch rows for `system`/`tools`).\n *\n * WHY a bucket needs a list rather than one type: `skill` holds BOTH a skill\n * injection (`user/message`) and a skill LOAD, which the fold reclassifies into\n * the skill bucket \"but stays a tool result\". So the bucket cannot name one type.\n *\n * WHY that is still safe for the BUTTON SET: the action rule is invariant across\n * every type a bucket can hold (proved by `tests/edit/ability-buckets.spec.ts`:\n * for each bucket, all its listed types yield the same `canRewrite` / `inert` /\n * `advancedOnly` / `blockReason`). The row's category therefore decides the\n * actions, and the ONLY thing that needs the exact type — the editor's fields\n * (`docs/03` R3.2: a tool result edits result-text + `isError`, a user message\n * edits 正文 + thinking text) — is taken from `node.read`, which answers the real\n * durable type when the editor opens. No guessing anywhere.\n */\nexport const TYPES_BY_BUCKET: Readonly<Record<RowClass, readonly string[]>> = {\n system: ['system/message'],\n tools: ['request/header'],\n user: ['user/message'],\n inject: ['user/message'],\n skill: ['user/message', 'tool/result'],\n assistant: ['assistant/message'],\n tool: ['tool/result'],\n}\n\n/**\n * The representative durable type of a bucket — for callers that need SOMETHING\n * to feed {@link ability} when the exact type is not at hand. It is safe to use\n * for the action set (the buckets are action-invariant) and **unfit for the\n * editor's fields** — use the type `node.read` returns for that.\n */\nexport function durableTypeOf(cat: RowClass): string {\n return TYPES_BY_BUCKET[cat][0] ?? 'user/message'\n}\n\n/**\n * The actions a row offers.\n *\n * ⚠️ 2026-10-09(`docs/03` R4.8):**删除与编辑不再互斥** —— 旧口径\"标了就清掉改动 /\n * 改了就把标记清掉\"已作废,删除标记与编辑正文是两个独立字段。\n * 删除态仍给「丢弃这条改动」:那对应「已删除编辑稿 ──丢弃这条改动──▶ 已删除原文」\n * (只清正文、保持删除态),所以它只属于**可编辑且有改稿**的行。\n */\nexport function rowActions(a: Ability, hasLocalEdit: boolean, deleted = false): readonly RowAction[] {\n if (a.inert) return []\n if (deleted) {\n const kept: RowAction[] = ['unexclude']\n if (a.canRewrite && hasLocalEdit) kept.push('drop')\n return kept\n }\n if (a.shadowed || a.compacted) return []\n const actions: RowAction[] = []\n if (a.canRewrite) actions.push('edit')\n if (a.canExclude) actions.push('exclude')\n // 「丢弃这条改动」只属于**可编辑**的行(不能编辑的行根本不该有本地改动;这里有防守意义)。\n if (a.canRewrite && hasLocalEdit) actions.push('drop')\n return actions\n}\n","/**\n * The editing UI the demo fixes: a row's action bar, and the editor that expands\n * **under that row** (never a modal — the user is comparing against the context,\n * `docs/03` R3.1).\n *\n * The contract these two components keep, straight from `docs/03`'s current-demo\n * sections and `docs/11` D15/D16/D17/D19:\n *\n * · Row actions are **only** `编辑` (plus `丢弃这条改动` while a local edit exists).\n * Host-protected rows render **no action area at all**; rows that cannot be\n * rewritten render **one sentence** and no action (`R2.1`/`R2.3`).\n * · The marker `已改(本地)` appears **once**, beside the seq (`R4.1`, D20).\n * · Fields are keyed off the **durable type** `node.read` answered (`R3.2`): a tool\n * result edits result-text + `isError`; everything else edits 正文 + a thinking\n * text folded under 高级.\n * · The editor is prefilled with the FULL text — and, after a save, with the saved\n * version (`effectiveText`), because that is the version in effect (D16).\n * · Saving writes only the plugin's local store, and the field carries the\n * destination marker so nobody mistakes it for \"the model can see this\" (`R3.3`).\n * · `Esc` cancels, `Cmd/Ctrl+Enter` submits; a refusal keeps the input and shows\n * the reason (`R3.5`).\n */\n\nimport { useEffect, useRef, useState, type ReactElement, type ChangeEvent, type KeyboardEvent } from 'react'\nimport type { ViewKit } from '../viewkit'\nimport { rowActions, type Ability } from '../../shared/redline-ability'\n\n/** Why a row has no action — mapped to a sentence by the caller's dictionary. */\nconst REASON_KEY: Record<string, string> = {\n 'assistant-immutable': 'redline.reason.assistant',\n 'system-head': 'redline.reason.system',\n 'shadowed': 'redline.reason.shadowed',\n 'compacted': 'redline.reason.compacted',\n}\n\n/** The editor's submission. */\nexport interface RedlineSubmit {\n readonly text: string\n readonly reasoning: string\n readonly isError: boolean\n}\n\n/**\n * A row's action bar.\n *\n * @returns `null` for a host-protected row: the area is not rendered at all\n * (an empty action strip would look like a missing feature, `docs/03` R2.1).\n */\nexport function makeRedlineActions(kit: ViewKit): (props: {\n seq: number\n ability: Ability\n hasLocalEdit: boolean\n /** 这一条是否已被删除(`docs/03` R4.8)。与 `hasLocalEdit` **不**互斥:删除后仍可带改稿。 */\n deleted: boolean\n /** The advanced switch, only meaningful for `advancedOnly` rows (`R2.5`). */\n advanced: boolean\n busy: boolean\n onEdit: () => void\n onDrop: () => void\n /** 标为「不要」/ 取消标记。 */\n onExclude: () => void\n onUnexclude: () => void\n /**\n * 这一行**最近一次动作被拒**的稳定码(`redline/*`)。\n * ⚠️ 真机踩到:`删除` 没有编辑器可依附,若只把错误丢给编辑器,拒绝就被吞掉了\n * (`docs/03` R3.5 要求\"拒绝必须说出来\")。所以动作条自己也要能报。\n */\n errorCode: string | null\n}) => ReactElement | null {\n const { t } = kit\n return function RedlineActions(props): ReactElement | null {\n const { ability } = props\n if (ability.inert) return null\n const actions = rowActions(ability, props.hasLocalEdit, props.deleted)\n const hiddenAsAdvanced = ability.advancedOnly && !props.advanced && (actions.includes('edit') || actions.includes('exclude'))\n /**\n * 改不了时的\"为什么\"徽章:助手消息要它(说明为什么没有「编辑」),\n * 但**已标为「不要」的行不要**(那时行上已经有「已标为不要」了,再来一句原因就是噪音)。\n */\n const reasonKey = REASON_KEY[ability.blockReason ?? ''] ?? 'redline.reason.other'\n const reasonChip = actions.includes('unexclude')\n ? null\n : <span className=\"redline-chip-soft\" title={t(reasonKey)}>{t(reasonKey)}</span>\n return (\n <div className=\"redline-act\" data-rowactions={props.seq}>\n <span className=\"redline-act-seq\">{'#' + String(props.seq)}</span>\n {props.hasLocalEdit\n ? <span className=\"redline-chip-local\" title={t('redline.local.tip')}>{t('redline.local')}</span>\n : null}\n {props.deleted\n ? <span className=\"redline-chip-excluded\" title={t('redline.excluded.tip')}>{t('redline.excluded')}</span>\n : null}\n {hiddenAsAdvanced\n ? <span className=\"redline-chip-soft\" title={t('redline.advanced.tip')}>{t('redline.advanced')}</span>\n : actions.includes('edit')\n ? <button type=\"button\" className=\"redline-btn\" disabled={props.busy} onClick={props.onEdit}>{t('redline.edit')}</button>\n : reasonChip}\n {actions.includes('exclude') && !hiddenAsAdvanced\n ? <button type=\"button\" className=\"redline-btn redline-btn-quiet\" title={t('redline.exclude.tip')} disabled={props.busy} onClick={props.onExclude}>{t('redline.exclude')}</button>\n : null}\n {actions.includes('unexclude') && !hiddenAsAdvanced\n ? <button type=\"button\" className=\"redline-btn redline-btn-quiet\" title={t('redline.unexclude.tip')} disabled={props.busy} onClick={props.onUnexclude}>{t('redline.unexclude')}</button>\n : null}\n {actions.includes('drop')\n ? <button type=\"button\" className=\"redline-btn redline-btn-quiet\" disabled={props.busy} onClick={props.onDrop}>{t('redline.drop')}</button>\n : null}\n {props.errorCode === null\n ? null\n : <span className=\"redline-act-err\" role=\"alert\">{t('redline.err.' + props.errorCode.replace('redline/', ''))}</span>}\n </div>\n )\n }\n}\n\n/**\n * The inline editor. Mounted by the row when it is the open editor, so its local\n * state lives exactly as long as the row is being edited.\n */\nexport function makeRedlineEditor(kit: ViewKit): (props: {\n seq: number\n /** The durable type `node.read` answered — this is what picks the fields. */\n type: string\n /** The version in effect (the original, or your saved edit). */\n initial: RedlineSubmit\n busy: boolean\n /**\n * Set when editing is not allowed at all right now: the demo's own gate\n * (`turnOpen || !live`) disables `保存` and shows the sentence, rather than\n * letting the click fail.\n */\n blocked: 'turn-open' | 'not-live' | null\n /** The stable refusal code to display, if the last attempt failed. */\n errorCode: string | null\n onSubmit: (edit: RedlineSubmit) => void\n onCancel: () => void\n}) => ReactElement {\n const { t } = kit\n return function RedlineEditor(props): ReactElement {\n const [text, setText] = useState(props.initial.text)\n const [reasoning, setReasoning] = useState(props.initial.reasoning)\n const [isError, setIsError] = useState(props.initial.isError)\n const areaRef = useRef<HTMLTextAreaElement | null>(null)\n // A different row's values must never leak into this editor's state.\n useEffect(() => {\n setText(props.initial.text)\n setReasoning(props.initial.reasoning)\n setIsError(props.initial.isError)\n }, [props.seq])\n useEffect(() => { areaRef.current?.focus() }, [])\n\n const isToolResult = props.type === 'tool/result'\n const multiParagraph = props.initial.text.includes('\\n')\n const submit = (): void => { props.onSubmit({ text, reasoning: isToolResult ? '' : reasoning, isError }) }\n const onKey = (ev: KeyboardEvent<HTMLDivElement>): void => {\n if (ev.key === 'Escape') { ev.preventDefault(); props.onCancel(); return }\n if (ev.key === 'Enter' && (ev.metaKey || ev.ctrlKey)) { ev.preventDefault(); submit() }\n }\n const errKey = props.errorCode === null ? null : `redline.err.${props.errorCode.replace('redline/', '')}`\n const blockedKey = props.blocked === 'turn-open'\n ? 'redline.blocked.turnOpen'\n : props.blocked === 'not-live' ? 'redline.blocked.notLive' : null\n\n return (\n <div className=\"redline-editor\" onKeyDown={onKey}>\n {multiParagraph ? <div className=\"redline-editor-note\">{t('redline.multiParagraph')}</div> : null}\n <label className=\"redline-editor-label\" htmlFor={`redline-ed-${String(props.seq)}`}>\n {isToolResult ? t('redline.field.result') : t('redline.field.body')}\n <span className=\"redline-dest\">{t('redline.dest.local')}</span>\n </label>\n <textarea\n id={`redline-ed-${String(props.seq)}`}\n ref={areaRef}\n className=\"redline-editor-text\"\n value={text}\n rows={6}\n onChange={(ev: ChangeEvent<HTMLTextAreaElement>) => { setText(ev.target.value) }}\n />\n {isToolResult\n ? (\n <label className=\"redline-editor-check\">\n <input type=\"checkbox\" checked={isError} onChange={(ev: ChangeEvent<HTMLInputElement>) => { setIsError(ev.target.checked) }} />\n {t('redline.field.isError')}\n <span className=\"redline-dest\">{t('redline.dest.local')}</span>\n </label>\n )\n : (\n <details className=\"redline-editor-adv\">\n <summary>{t('redline.field.advanced')}</summary>\n <label className=\"redline-editor-label\" htmlFor={`redline-edr-${String(props.seq)}`}>\n {t('redline.field.thinking')}\n <span className=\"redline-dest\">{t('redline.dest.local')}</span>\n </label>\n <textarea\n id={`redline-edr-${String(props.seq)}`}\n className=\"redline-editor-text\"\n value={reasoning}\n rows={3}\n onChange={(ev: ChangeEvent<HTMLTextAreaElement>) => { setReasoning(ev.target.value) }}\n />\n </details>\n )}\n {blockedKey !== null ? <div className=\"redline-editor-blocked\">{t(blockedKey)}</div> : null}\n {errKey !== null ? <div className=\"redline-editor-err\" role=\"alert\">{t(errKey)}</div> : null}\n {/* 动作区**没有浮标**(用户 2026-10-06 红框截图:那个「?」压在「高级:思考文本」上)。\n 它当初是给**批注**动作做说明的角标(`docs/10` M05-40),批注已整批删除;\n 剩下的说明改挂按钮自身的 `title` —— 不占版面,鼠标停上去照样看得到。 */}\n <div className=\"redline-editor-actions\">\n <button\n type=\"button\"\n className=\"redline-btn\"\n title={t('redline.save.tip')}\n disabled={props.busy || blockedKey !== null}\n onClick={submit}\n >{t('redline.save')}</button>\n <button type=\"button\" className=\"redline-btn redline-btn-quiet\" onClick={props.onCancel}>{t('redline.cancel')}</button>\n </div>\n </div>\n )\n }\n}\n","/**\n * The stable error-code table shared by BOTH halves — the plugin's outward\n * contract.\n *\n * Why a frozen table instead of ad-hoc strings: the client maps a code to the\n * localized human wording, and the tests assert the code (never the\n * message). A code that changes shape silently turns \"这一条改不了,因为…\" into\n * a raw provider error, which is exactly the failure this project exists to\n * avoid.\n *\n * The `redline/` prefix keeps these out of any host or upstream namespace.\n */\n\n/** Every code the channel can answer with. */\nexport const REDLINE_ERROR = {\n /** The body was not JSON, or lacked a usable `op`/`sessionId`. */\n badRequest: 'redline/bad-request',\n /** The op is not in the channel's table (an older client, or a typo). */\n unknownOp: 'redline/unknown-op',\n /** The target session has no live Agent in this process (`docs/01` F9). */\n notLive: 'redline/not-live',\n /** The session has an open turn: edits must land on a turn boundary (`docs/01` F8). */\n turnOpen: 'redline/turn-open',\n /** No local draft exists for that seq. */\n noDraft: 'redline/no-draft',\n /** The draft is identical to the version already in effect. */\n noChange: 'redline/no-change',\n /** The draft empties both the visible text and the thinking text. */\n emptyContent: 'redline/empty-content',\n /** 首条任务是人写的,空的不能开子会话(M5-04:不产生任何 AI 生成内容)。 */\n emptyTask: 'redline/empty-task',\n /** 这台运行时没有可用的子会话服务:别装作能开,如实说\"只能人工搬运\"。 */\n noSubagents: 'redline/no-subagents',\n /** A child provider returned without the child identity required to prove creation. */\n childStartUnconfirmed: 'redline/child-start-unconfirmed',\n /** Official and bare child creation both failed; no child was reported as started. */\n childStartFailed: 'redline/child-start-failed',\n /** Drafts changed after the user reviewed the confirmation; they must review again. */\n draftsChanged: 'redline/drafts-changed',\n /** `assistant/message` cannot be rewritten on this platform (`docs/01` F7.2). */\n assistantImmutable: 'redline/assistant-immutable',\n /** The target is no longer a surface node (it was replaced) (`docs/01` F7). */\n shadowed: 'redline/shadowed',\n /**\n * The target seq is not in this session's log at all (stale client, trimmed\n * window, wrong session). ⚠️ Distinct from {@link shadowed}: the log keeps a\n * replaced original, so \"not found\" and \"superseded\" are different facts and\n * used to be reported as the same one (Code Review P1-1).\n */\n notFound: 'redline/not-found',\n /** The draft file on disk is not readable as our format (E13: loud, never silently empty). */\n draftCorrupt: 'redline/draft-corrupt',\n /** The draft file's `schemaVersion` is not one this build understands. */\n draftSchema: 'redline/draft-schema',\n /** The origin ledger file is unreadable (deleted/corrupt/hand-edited). */\n originCorrupt: 'redline/origin-corrupt',\n /** The origin ledger's `schemaVersion` is not one this build understands. */\n originSchema: 'redline/origin-schema',\n /** A range argument was half-given or reversed. */\n badRange: 'redline/bad-range',\n /** The full text of that version cannot be read back on this platform. */\n historyUnavailable: 'redline/history-unavailable',\n /** The underlying event type has no rewrite path at all. */\n unsupportedType: 'redline/unsupported-type',\n /** An op handler threw. Never a platform code — the message carries that. */\n internal: 'redline/internal',\n /** CLIENT-SIDE: the call never produced a valid answer (offline, HTTP error, bad body). */\n transport: 'redline/transport',\n} as const\n\nexport type RedlineErrorCode = (typeof REDLINE_ERROR)[keyof typeof REDLINE_ERROR]\n\n/**\n * Short English wire text per code. Deliberately NOT the user-facing sentence:\n * the client owns the localized wording (`docs/03` R4.7), and a wire message\n * that reads like UI copy is how two different sentences for one condition get\n * shipped.\n */\nexport const REDLINE_ERROR_MESSAGE: Readonly<Record<RedlineErrorCode, string>> = {\n [REDLINE_ERROR.badRequest]: 'body is not a valid redline call',\n [REDLINE_ERROR.unknownOp]: 'unknown redline op',\n [REDLINE_ERROR.notLive]: 'session is not live in this process',\n [REDLINE_ERROR.turnOpen]: 'the session has an open turn',\n [REDLINE_ERROR.noDraft]: 'no local draft for that seq',\n [REDLINE_ERROR.noChange]: 'the draft does not change the effective text',\n [REDLINE_ERROR.emptyContent]: 'the draft has no content at all',\n [REDLINE_ERROR.emptyTask]: 'the first task must be written by the human',\n [REDLINE_ERROR.noSubagents]: 'this runtime exposes no subagents service',\n [REDLINE_ERROR.childStartUnconfirmed]: 'the child provider did not return a child identity',\n [REDLINE_ERROR.childStartFailed]: 'the child could not be created by either available provider',\n [REDLINE_ERROR.draftsChanged]: 'the local edits changed after confirmation was prepared',\n [REDLINE_ERROR.assistantImmutable]: 'assistant/message cannot be rewritten',\n [REDLINE_ERROR.shadowed]: 'that seq is no longer a surface node',\n [REDLINE_ERROR.notFound]: 'that seq is not in this session log',\n [REDLINE_ERROR.draftCorrupt]: 'the local draft file is not readable',\n [REDLINE_ERROR.draftSchema]: 'the local draft file has an unsupported schema version',\n [REDLINE_ERROR.originCorrupt]: 'the local origin ledger is not readable',\n [REDLINE_ERROR.originSchema]: 'the local origin ledger has an unsupported schema version',\n [REDLINE_ERROR.badRange]: 'bad void range',\n [REDLINE_ERROR.historyUnavailable]: 'the full text of that version is not readable',\n [REDLINE_ERROR.unsupportedType]: 'this event type has no rewrite path',\n [REDLINE_ERROR.internal]: 'the op handler failed',\n [REDLINE_ERROR.transport]: 'the request did not reach the host',\n}\n\n/** Whether `code` is one of ours (used by the client to pick the R4.7 wording). */\nexport function isRedlineErrorCode(code: string): code is RedlineErrorCode {\n return Object.values(REDLINE_ERROR).includes(code as RedlineErrorCode)\n}\n","/**\n * Local edits — the plugin's own store, and the WHOLE of what a \"save\" does\n * (`docs/11` D15, `AGENTS.md` §1: every save is temporary).\n *\n * The hard constraint, in one sentence: pressing save writes a JSON file under\n * our data directory and **nothing else** — the session log is untouched, so the\n * current session's model sees exactly what it saw before. The one and only write\n * point is opening a child session (M5), which carries these edits verbatim into\n * the new session's first message.\n *\n * Facts this module owns:\n * · ONE local edit per row. Saving again OVERWRITES it (never stacks), and the\n * latest version is the one that would be carried forward.\n * · The version in effect is what the row DISPLAYS, what the editor PREFILLS and\n * what the \"no substantive change\" check compares against (`docs/11` D16).\n * That is why editing again after a save shows your saved text, and why\n * editing back to the original counts as a change.\n * · A corrupt file is an explicit error, never a silently empty table (E13).\n *\n * ── Why this lives in `src/shared/**` and not in `src/redline/**` ──────────\n * The BROWSER needs these rules too: it DISPLAYS the version in effect, PREFILLS\n * the editor from it, and labels a row `已改(本地)` — all three must use the same\n * answer the host uses when it decides \"no substantive change\". Two copies of\n * \"what is in effect\" is precisely how a UI starts disagreeing with the gate that\n * refuses the save.\n *\n * The bundle-purity gate (`docs/02` §4, `docs/05` A13, `namespace-contract` face 9,\n * plus tsdown's client-bundle purity plugin) forbids `src/client/**` from importing\n * `src/redline/**` at runtime — reverse-verified, same as `redline-ability.ts`.\n *\n * Purity: no `node:*` — the host half owns the file system and passes text in/out.\n */\n\nimport { REDLINE_ERROR } from './redline-errors'\nimport { REDLINE_DATA_DIR_NAME } from './redline-paths'\n\n/** Our on-disk format version. Only bumped with a migration; there is none yet. */\nexport const REDLINE_DRAFT_SCHEMA_VERSION = 1\n\n/** One row's local edit. `text` is the complete replacement body (never a preview). */\nexport interface LocalEdit {\n readonly seq: number\n readonly text: string\n readonly reasoning: string\n readonly isError: boolean\n /** When this version was saved (ISO-8601). The client formats it. */\n readonly updatedAt: string\n /** Display context: the row's category and tool/file name, when known. */\n readonly cat?: string\n readonly name?: string\n /**\n * 「删除」标记(`docs/03` R4.8 / `docs/13` §7):这一条**不写进新会话**。\n *\n * ⚠️ 与编辑正文**独立存储** —— 删一条**不清空**它的编辑稿,取消删除要能原样恢复整条记录。\n * 旧实现(`excluded`)是\"整条覆盖 + 清空正文\",那种互斥语义**已作废**。\n */\n readonly deleted?: boolean\n /**\n * 旧名字的**兼容镜像**:与 `deleted` 同写同清(历史草稿与尚未改名的调用方仍按这个字段名过滤)。\n * ⚠️ 不是\"废弃 API\"的注解写法 —— 命名空间契约的 lint 禁止仓库内**使用**被标 `@deprecated` 的成员,\n * 而这个镜像在被调用方改名(归 C3/C6)之前必须在本文件里读写。退役时把两处一起删。\n */\n readonly excluded?: boolean\n /**\n * 旧实现**先清空正文**再写删除标记 ⟹ 那条\"删除前的编辑\"已经不可能恢复。\n * 迁移时如实置位,让界面能说\"这条旧标记无法恢复删除前的编辑\"(R4.8 硬要求 5),\n * 而不是伪造一份正文、也不是静默丢掉标记。用户重新编辑后此位清除。\n */\n readonly legacyBodyLost?: true\n}\n\n/** All local edits of one session, keyed by `String(seq)`. */\nexport type DraftTable = Readonly<Record<string, LocalEdit>>\n\n/** The minimal surface row this module needs: the FULL text plus its error mark. */\nexport interface SurfaceRowText {\n readonly seq: number\n readonly text: string\n readonly reasoning?: string\n readonly isError?: boolean\n}\n\n/**\n * Why a save was refused. Derived from the ONE code table (`redline-errors.ts`)\n * rather than re-spelled here: a second spelling of a wire code is how the client\n * ends up with a case it cannot map.\n */\n/**\n * 一条记录是否**带编辑正文**。\n *\n * 判据用\"正文或思考文本非空\",而不是另加一个布尔字段:保存路径的 `checkChange` 会拒绝\n * `text === '' && reasoning === ''`(`empty-content`),所以**能存下来的编辑一定有正文**,\n * 而\"空正文\"只能来自删除墓碑。这样\"已删除原文 / 已删除编辑稿\"两态天然可分。\n */\nexport function hasEditBody(edit: LocalEdit): boolean {\n return edit.text !== '' || edit.reasoning !== ''\n}\n\n/** 按固定字段顺序重建一条记录(保证序列化与 revision 稳定,不带上游对象的键序)。 */\nfunction withMarks(entry: LocalEdit, deleted: boolean, legacyBodyLost: boolean): LocalEdit {\n return {\n seq: entry.seq,\n text: entry.text,\n reasoning: entry.reasoning,\n isError: entry.isError,\n updatedAt: entry.updatedAt,\n ...entry.cat === undefined ? {} : { cat: entry.cat },\n ...entry.name === undefined ? {} : { name: entry.name },\n ...deleted ? { deleted: true, excluded: true } : {},\n ...legacyBodyLost ? { legacyBodyLost: true } : {},\n }\n}\n\n/**\n * 把某一行标为**删除**:这一条不写进新会话(`docs/03` R4.8 / `docs/13` §7)。\n *\n * ⚠️ **保留**该行已有的编辑正文与显示元数据 —— 取消删除要能原样恢复整条记录。\n * 只写我们自己这份表;当前会话一个字都不写(硬约束,`docs/11` D15)。\n */\nexport function putDeleted(table: DraftTable, seq: number, updatedAt: string): DraftTable {\n const key = String(seq)\n // `Readonly<Record<string, LocalEdit>>` 把索引类型成 `LocalEdit`(不是 `| undefined`)⟹ 只能\n // 用 `Object.hasOwn` 问\"到底有没有这条\",`=== undefined` 会既骗读者又被 lint 抓(同 dropEdit 的口径)。\n const existing: LocalEdit | undefined = Object.hasOwn(table, key) ? table[key] : undefined\n const base: LocalEdit = existing ?? { seq, text: '', reasoning: '', isError: false, updatedAt }\n return { ...table, [key]: withMarks(base, true, existing?.legacyBodyLost === true) }\n}\n\n/**\n * 取消删除:**回到删除之前的状态**(R4.8 关键转换)。\n * 有编辑正文 ⟹ 回到\"已编辑\"(正文原样);没有正文 ⟹ 回到\"原文\"(整条记录去掉)。\n */\nexport function unmarkDeleted(table: DraftTable, seq: number): DraftTable {\n const key = String(seq)\n if (!Object.hasOwn(table, key)) return table\n const existing = table[key]\n if (!hasEditBody(existing)) {\n // 没有正文可留 ⟹ 就是\"原文\"。\n return Object.fromEntries(Object.entries(table).filter(([k]) => k !== key))\n }\n return { ...table, [key]: withMarks(existing, false, false) }\n}\n\n/** 被删除的 seq,升序。 */\nexport function deletedSeqsOf(table: DraftTable): number[] {\n return Object.values(table).filter(entry => isDeleted(table, entry.seq)).map(entry => entry.seq).sort((a, b) => a - b)\n}\n\n/** Whether a row carries the delete mark (`deleted`, or the compat mirror `excluded`). */\nexport function isDeleted(table: DraftTable, seq: number): boolean {\n const key = String(seq)\n if (!Object.hasOwn(table, key)) return false\n const entry = table[key]\n return entry.deleted === true || entry.excluded === true\n}\n\n/**\n * 旧名字(`putExcluded`)。语义**已改变**:不再清空正文(R4.8 硬要求 3 作废了互斥)。\n * 委托给 `putDeleted`;调用方改名归 C3/C6。\n * ⚠️ 不写 `@deprecated` 注解:lint 会因此拒绝任何**使用**它的调用方,而唯一剩下的使用者是\n * 尚未获准改动的那几个文件。退役时连名字一起删。\n */\nexport function putExcluded(table: DraftTable, seq: number, updatedAt: string): DraftTable {\n return putDeleted(table, seq, updatedAt)\n}\n\n/** 旧名字(`deletedSeqsOf`)——同一口径的委托;宿主已改用新名字,退役归 C3/C6。 */\nexport function excludedSeqsOf(table: DraftTable): number[] {\n return deletedSeqsOf(table)\n}\n\nexport type ChangeRefusal = typeof REDLINE_ERROR.emptyContent | typeof REDLINE_ERROR.noChange\n\nexport type ChangeVerdict = { readonly ok: true } | { readonly ok: false; readonly code: ChangeRefusal }\n\nexport function emptyDrafts(): DraftTable {\n return {}\n}\n\n/**\n * A session id → a file-name-safe key.\n *\n * ⚠️ 只做百分号编码是不够的(Code Review P2):\n * · macOS 默认**大小写不敏感** ⟹ `Session-A` 与 `session-a` 会落到同一个文件(串档);\n * · 超长 id 会撞 255 字节的文件名上限 ⟹ `ENAMETOOLONG` ⟹ 保存直接失败。\n * 所以先做一次稳定的短哈希(FNV-1a 32 位,纯函数、无 `node:*`:宿主半边与测试都能用),\n * 再把可读前缀拼上 —— 既不会串档,也绝不会超长。可读前缀只为排障时认得出是哪个会话。\n */\nexport function stableKeyOf(sessionId: string): string {\n let hash = 0x811c9dc5\n for (let i = 0; i < sessionId.length; i += 1) {\n hash ^= sessionId.charCodeAt(i)\n // FNV 质数 16777619,用移位避免大整数精度问题。\n hash = (hash + ((hash << 1) + (hash << 4) + (hash << 7) + (hash << 8) + (hash << 24))) >>> 0\n }\n return hash.toString(16).padStart(8, '0')\n}\n\n/** The on-disk name of one session's draft file. */\nexport function draftFileName(sessionId: string): string {\n const readable = sessionId.replace(/[^A-Za-z0-9_-]/g, '_').slice(0, 40)\n return `redline-drafts-${readable}-${stableKeyOf(sessionId)}.json`\n}\n\n/** Our data directory's name, re-exported so the host has one source for it. */\nexport { REDLINE_DATA_DIR_NAME }\n\n/** The edit for a row, if any. */\nexport function editOf(table: DraftTable, seq: number): LocalEdit | undefined {\n const entry = Object.values(table).find(candidate => candidate.seq === seq)\n // ⚠️ 判据是\"**有没有编辑正文**\",不是\"有没有删除标记\"(`docs/03` R4.8):\n // · 删除墓碑(没有正文)不是编辑 —— 若当成编辑返回,`effectiveText` 会给出空串,行渲染成空白;\n // · 「已删除编辑稿」(有正文 + 有删除标记)**是**编辑 —— 取消删除后要原样恢复它。\n return entry === undefined || !hasEditBody(entry) ? undefined : entry\n}\n\n/**\n * 旧名字(`isDeleted`)——同一口径,含 `deleted` 与兼容镜像字段。\n * 客户端 `browser.tsx` 还在用它(那个文件不在本卡允许改清单里)⟹ 退役归 C3/C6。\n */\nexport function isExcluded(table: DraftTable, seq: number): boolean {\n return isDeleted(table, seq)\n}\n\n/** Whether a row carries a local edit. */\nexport function hasLocalEdit(table: DraftTable, seq: number): boolean {\n return editOf(table, seq) !== undefined\n}\n\n/**\n * Insert or OVERWRITE the edit for one row. One row, one edit — never two.\n *\n * ⚠️ 覆盖**不解除删除标记**(`docs/03` R4.8 硬要求 3:互斥已作废)⟹ 编辑一条已删除的行\n * 得到的仍是\"已删除编辑稿\"。同时清掉 `legacyBodyLost`:用户给了新正文,那条\"旧编辑已丢失\"\n * 的提示不再适用(继续显示会说假话)。\n */\nexport function putEdit(table: DraftTable, edit: LocalEdit): DraftTable {\n const key = String(edit.seq)\n if (!Object.hasOwn(table, key) || !isDeleted(table, edit.seq)) {\n return { ...table, [key]: edit }\n }\n return { ...table, [key]: withMarks(edit, true, false) }\n}\n\n/** Forget one row's edit — but a **deleted** row keeps its tombstone (R4.8). */\nexport function dropEdit(table: DraftTable, seq: number): DraftTable {\n const key = String(seq)\n // Existence, not value: a `Record<string, T>` indexes as `T`, so `=== undefined`\n // is both a lie to the reader and a lint error. `Object.hasOwn` is the honest check.\n if (!Object.hasOwn(table, key)) return table\n const existing = table[key]\n if (isDeleted(table, seq)) {\n // 「已删除编辑稿 ──丢弃这条改动──▶ 已删除原文」:只清正文,**保持删除态**。\n return { ...table, [key]: withMarks({ ...existing, text: '', reasoning: '', isError: false }, true, false) }\n }\n // Built immutably (no `delete` on a computed key), so callers can diff by identity.\n return Object.fromEntries(Object.entries(table).filter(([k]) => k !== key))\n}\n\n/** The text in effect for a row: the local edit if there is one, else the original. */\nexport function effectiveText(row: SurfaceRowText, table: DraftTable): string {\n const edit = editOf(table, row.seq)\n return edit === undefined ? row.text : edit.text\n}\n\n/** The thinking text in effect (an edit that empties it stays empty). */\nexport function effectiveReasoning(row: SurfaceRowText, table: DraftTable): string {\n const edit = editOf(table, row.seq)\n return edit === undefined ? (row.reasoning ?? '') : edit.reasoning\n}\n\n/** The error mark in effect. */\nexport function effectiveIsError(row: SurfaceRowText, table: DraftTable): boolean {\n const edit = editOf(table, row.seq)\n return edit === undefined ? (row.isError ?? false) : edit.isError\n}\n\n/**\n * Decide whether a proposed edit is a substantive change — the demo's rule\n * (`demo/demo.js` `submitEditor`), locked by the `drafts` spec:\n * · both the visible text and the thinking text empty → `empty-content`;\n * · identical to the version IN EFFECT (text, thinking text and error mark all\n * equal) → `no-change`;\n * · otherwise it is a change — including \"change it back to the original\",\n * because after a save the version in effect IS the saved one.\n */\nexport function checkChange(\n row: SurfaceRowText,\n table: DraftTable,\n next: { readonly text: string; readonly reasoning: string; readonly isError: boolean },\n): ChangeVerdict {\n if (next.text === '' && next.reasoning === '') return { ok: false, code: REDLINE_ERROR.emptyContent }\n if (\n next.text === effectiveText(row, table)\n && next.reasoning === effectiveReasoning(row, table)\n && next.isError === effectiveIsError(row, table)\n ) {\n return { ok: false, code: REDLINE_ERROR.noChange }\n }\n return { ok: true }\n}\n\n/** The wire form of one draft file. */\nexport interface DraftFile {\n readonly schemaVersion: number\n readonly sessionId: string\n readonly edits: readonly LocalEdit[]\n}\n\n/** Serialize a table for disk: deterministic (sorted by seq), newline-terminated. */\nexport function serializeDrafts(sessionId: string, table: DraftTable): string {\n const edits = Object.values(table).sort((a, b) => a.seq - b.seq)\n const file: DraftFile = { schemaVersion: REDLINE_DRAFT_SCHEMA_VERSION, sessionId, edits }\n return `${JSON.stringify(file, null, 2)}\\n`\n}\n\n/**\n * A deterministic version token for the exact draft set a child-confirmation dialog\n * reviewed. It is a stale-confirmation guard, not an authorization mechanism: the\n * route remains authenticated by the harness. The canonical serialization means\n * record order cannot change the version, while any carried field can.\n */\nexport function draftRevisionOf(sessionId: string, table: DraftTable): string {\n const source = serializeDrafts(sessionId, table)\n let hash = 0x811c9dc5\n for (let i = 0; i < source.length; i += 1) {\n hash ^= source.charCodeAt(i)\n hash = (hash + ((hash << 1) + (hash << 4) + (hash << 7) + (hash << 8) + (hash << 24))) >>> 0\n }\n return `d1-${hash.toString(16).padStart(8, '0')}`\n}\n\nexport type ParseResult =\n | { readonly ok: true; readonly table: DraftTable }\n | { readonly ok: false; readonly code: string; readonly message: string }\n\n/** A missing/empty file is an empty table; anything unreadable is a loud refusal. */\nexport function parseDrafts(raw: string | null | undefined, expectedSessionId?: string): ParseResult {\n if (raw === null || raw === undefined || raw.trim() === '') return { ok: true, table: {} }\n let parsed: unknown\n try {\n parsed = JSON.parse(raw)\n } catch {\n return { ok: false, code: REDLINE_ERROR.draftCorrupt, message: 'the draft file is not valid JSON' }\n }\n if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {\n return { ok: false, code: REDLINE_ERROR.draftCorrupt, message: 'the draft file is not an object' }\n }\n const file = parsed as Partial<DraftFile>\n // 串档防线(Code Review P2):文件里记着它是哪个会话的草稿。文件名被改过、或\n // 两个会话的 id 在文件系统上收敛到同一个名字时,这里必须**拒绝**而不是当成本会话的草稿。\n if (expectedSessionId !== undefined && file.sessionId !== expectedSessionId) {\n return {\n ok: false,\n code: REDLINE_ERROR.draftCorrupt,\n message: `the draft file belongs to another session (${String(file.sessionId)})`,\n }\n }\n if (file.schemaVersion !== REDLINE_DRAFT_SCHEMA_VERSION) {\n return {\n ok: false,\n code: REDLINE_ERROR.draftSchema,\n message: `unsupported draft schemaVersion: ${String(file.schemaVersion)}`,\n }\n }\n if (!Array.isArray(file.edits)) {\n return { ok: false, code: REDLINE_ERROR.draftCorrupt, message: 'the draft file has no edits array' }\n }\n const table: Record<string, LocalEdit> = {}\n for (const entry of file.edits) {\n if (entry === null || typeof entry !== 'object') {\n return { ok: false, code: REDLINE_ERROR.draftCorrupt, message: 'a draft entry is not an object' }\n }\n const edit = entry as Partial<LocalEdit>\n if (typeof edit.seq !== 'number' || !Number.isInteger(edit.seq) || edit.seq < 0) {\n return { ok: false, code: REDLINE_ERROR.draftCorrupt, message: 'a draft entry has no usable seq' }\n }\n if (typeof edit.text !== 'string' || typeof edit.reasoning !== 'string' || typeof edit.isError !== 'boolean') {\n return { ok: false, code: REDLINE_ERROR.draftCorrupt, message: `draft #${edit.seq} has ill-typed fields` }\n }\n if (edit.excluded !== undefined && typeof edit.excluded !== 'boolean') {\n return { ok: false, code: REDLINE_ERROR.draftCorrupt, message: `draft #${edit.seq} has a non-boolean excluded` }\n }\n if (edit.deleted !== undefined && typeof edit.deleted !== 'boolean') {\n return { ok: false, code: REDLINE_ERROR.draftCorrupt, message: `draft #${edit.seq} has a non-boolean deleted` }\n }\n // 旧实现**先清空正文**才写 `excluded`(没有 `deleted` 字段)⟹ 那条\"删除前的编辑\"已经不可能恢复。\n // 迁移到 `deleted` 的同时如实置 `legacyBodyLost`:标记不丢、也不伪造正文(R4.8 硬要求 5)。\n const legacyOnly = edit.deleted === undefined && edit.excluded === true\n const deleted = edit.deleted === true || edit.excluded === true\n const body = { seq: edit.seq, text: edit.text, reasoning: edit.reasoning, isError: edit.isError }\n table[String(edit.seq)] = withMarks(\n {\n ...body,\n updatedAt: typeof edit.updatedAt === 'string' ? edit.updatedAt : '',\n ...(typeof edit.cat === 'string' ? { cat: edit.cat } : {}),\n ...(typeof edit.name === 'string' ? { name: edit.name } : {}),\n },\n deleted,\n legacyOnly && !hasEditBody({ ...body, updatedAt: '', seq: edit.seq }),\n )\n }\n return { ok: true, table }\n}\n","/** The one-line label cascade shared by the Context browser's element rows. */\n\nimport type { SurfaceNode } from '../../shared/types'\nimport type { ViewKit } from '../viewkit'\n\nexport function makeNodeText(kit: ViewKit): (n: SurfaceNode) => string {\n const { t } = kit\n return function nodeText(n: SurfaceNode): string {\n if (n.cat === 'tool') {\n return t('node.toolResult') + (n.tool ? ' ← ' + n.tool : '') + (n.err ? ' ⚠' : '')\n }\n if (n.skill) return 'Skill: ' + n.skill\n if (n.calls) return t('node.calls') + n.calls.join(', ')\n if (n.text) return n.form === 'snapshot' ? t('node.snapshot') + n.text : n.text\n if (n.cat === 'assistant') return t('node.empty')\n if (n.cat === 'inject' || n.cat === 'skill') return t('form.' + (n.form || 'context'))\n return t('node.nonText')\n }\n}\n","/**\n * Stop a horizontal scroller's overscroll from reaching the browser's history navigation — the trackpad\n * swipe-back (left edge) and swipe-forward (right edge) gestures. The spec answer is `overscroll-behavior-x:\n * contain`, the harness's own idiom for its horizontal scrollers and what the sheets beside this module's\n * callers already set; it covers Chromium and Firefox, but WebKit still navigates on horizontal overscroll with\n * the property set (bug 240183), where a canceled wheel is the only lever. Without either, one swipe past the\n * edge of the trend chart or the agent graph leaves the whole app for another page in the tab's history.\n */\n\n/**\n * Cancel the horizontal-dominant wheel gestures a scroller cannot consume — the ones the browser would\n * otherwise read as a history swipe. Vertical-dominant gestures are left alone: they belong to the page's own\n * scrolling, and the scrollers this guards only overflow horizontally.\n * @param el - the horizontal scroll container (the listener must be non-passive, so it cannot ride React's passive wheel seat).\n * @returns the disposer removing the listener.\n */\nexport function containHorizontalOverscroll(el: HTMLElement): () => void {\n const onWheel = (e: WheelEvent): void => {\n if (Math.abs(e.deltaX) <= Math.abs(e.deltaY)) return\n const atStart = e.deltaX < 0 && el.scrollLeft <= 0\n // 1px tolerance: fractional device-pixel scroll offsets land just short of the exact end.\n const atEnd = e.deltaX > 0 && el.scrollLeft + el.clientWidth >= el.scrollWidth - 1\n if (atStart || atEnd) e.preventDefault()\n }\n el.addEventListener('wheel', onWheel, { passive: false })\n return () => { el.removeEventListener('wheel', onWheel) }\n}\n","/**\n * Bespoke per-request history chart — no shared data-viz primitive — styled through the shared `--dsw-alias-*` tokens; helpers\n * aggregateByTurn/attachMarkers are shared with ContextView. On mount each bar rises from its baseline,\n * staggered left to right with the cascade capped for long logs (trendChart.css, `--redline-i` slots below).\n */\n\nimport { memo, useLayoutEffect, useMemo, useRef, useState, type CSSProperties, type ReactElement, type UIEvent } from 'react'\nimport type { Category, ContextEventRecord, RequestRecord } from '../../shared/types'\nimport { CATS } from '../categories'\nimport { containHorizontalOverscroll } from '../overscroll'\nimport type { ViewKit } from '../viewkit'\n\nexport interface TrendChartProps {\n requests: RequestRecord[]\n markers: (ContextEventRecord | undefined)[]\n selectedSeq: number | null\n hoveredSeq: number | null\n activeTurn: number | null\n granularity: 'step' | 'turn'\n mode: 'total' | 'delta'\n focusTurn: number | null\n /** Mirrored category hover (shared with the overview and the browser): lights that category's segment in every bar. */\n hoverCat: string | null\n /**\n * The browser's open category: every bar plots only that category's fold figure, with the axis rescaled\n * to its own max. Null plots every category; an unrecognized key (a stale or hostile state) degrades to the\n * unfocused chart.\n */\n focusCat?: string | null\n /**\n * Adaptive scale (the trend card's title-adjacent toggle): the axis is recomputed from the bars currently\n * VISIBLE in the scroller and follows the scroll, so a spike far outside the window cannot flatten the bars\n * on screen. Off = the whole retained log scales the axis, the historical behavior.\n */\n adaptive?: boolean\n onSelect: (seq: number | null) => void\n onHover: (seq: number | null) => void\n onHoverTurn: (turn: number | null) => void\n onPickTurn: (turn: number) => void\n onFocusTurnHandled: () => void\n}\n\n/**\n * Collapse per-step requests into one bar per turn — each turn is represented by its LAST step's record, tagged `stepCount` for the bar's\n * column width; the log keeps one turn's requests consecutive, so a run of equal turns collapses to its final record.\n */\nexport function aggregateByTurn(requests: RequestRecord[]): RequestRecord[] {\n const out: RequestRecord[] = []\n let runSteps = 0\n for (const req of requests) {\n const last = out.length > 0 ? out[out.length - 1] : null\n if (last !== null && (last.turn ?? 0) === (req.turn ?? 0)) {\n runSteps++\n out[out.length - 1] = { ...req, stepCount: runSteps }\n } else {\n runSteps = 1\n out.push({ ...req, stepCount: 1 })\n }\n }\n return out\n}\n\n/**\n * The per-turn step tallies the step-granularity labels lean on (\"第 s 步 (共 n 步)\") — the same count a\n * turn-mode bar's `stepCount` carries. Records without a turn stamp pool under 0, the key the labels'\n * `turn ?? 0` fallback reads; the getter answers 1 for a turn outside the list so a caller can never miss.\n */\nexport function turnStepsOf(requests: RequestRecord[]): (turn: number | undefined) => number {\n const counts = new Map<number, number>()\n for (const req of requests) {\n const turn = req.turn ?? 0\n counts.set(turn, (counts.get(turn) ?? 0) + 1)\n }\n return turn => counts.get(turn ?? 0) ?? 1\n}\n\n/**\n * Attach each boundary event (compaction/prune) to the first request logged after it — one entry per index, for the ✂ marker and the detail\n * chip; shared with the detail panel so both show the SAME event.\n */\nexport function attachMarkers(requests: RequestRecord[], events: ContextEventRecord[]): (ContextEventRecord | undefined)[] {\n const markers: (ContextEventRecord | undefined)[] = new Array<ContextEventRecord | undefined>(requests.length)\n for (const ev of events) {\n if (ev.kind !== 'compaction' && ev.kind !== 'prune') continue\n for (let r = 0; r < requests.length; r++) {\n if (requests[r].seq >= ev.seq) {\n if (markers[r] === undefined) markers[r] = ev\n break\n }\n }\n }\n return markers\n}\n\n/**\n * The chat→Context jump's target: the turn bar whose closing reply the user clicked — the relayed seq is a turn's LAST step, exactly the\n * aggregate's record — or, when that turn has aged out of the host's retained window, the oldest retained bar. Resolved against turn\n * aggregates, since the jump pins in turn granularity. Null only on an empty history.\n */\nexport function jumpTargetOf(requests: RequestRecord[], seq: number): RequestRecord | null {\n for (const req of requests) if (req.seq === seq) return req\n return requests.length > 0 ? requests[0] : null\n}\n\nexport function makeTrendChart(kit: ViewKit): (props: TrendChartProps) => ReactElement {\n const { t, fmt, eventLabel, eventAt, catLabel } = kit\n\n const CHART_H = 112\n // Quarter-mark label tops for the axis (mirrored to .redline-axis-q1/.redline-axis-q3 in trendChart.css): chart top 18\n // plus a quarter/three-quarters of the 112px bar area, minus half the 11px label box (font-size 11, line-height 1).\n const Q3_TOP = 41\n const Q1_TOP = 97\n // Delta axis ticks are signed: '+' only on positives — fmt already carries the minus for negatives.\n const fmtSigned = (v: number): string => (v > 0 ? '+' : '') + fmt(v)\n // Constant bar width: sparse histories don't stretch bars, dense ones scroll instead of compressing; the turn strip below mirrors the\n // same column grid.\n const BAR_W = 14\n const BAR_GAP = 2\n // Entrance stagger cap: long logs render thousands of bars, so the grow-in cascade stops widening after\n // this many columns and late bars simply join within the cap (trendChart.css delays by `--redline-i`).\n const STAGGER_CAP = 20\n // Step flags: every 5th step bar plants one at its left edge, labeled with its cumulative step number\n // (5, 10, 15, …) — the chart's only position landmark in step granularity (the turn strip numbers turns).\n const STEP_FLAG_EVERY = 5\n // Neutral zebra, deliberately DISJOINT from the category palette — the strip must read as a partition layer, not a bottom segment of the\n // composition bars.\n const TURN_FILLS = [\n 'color-mix(in srgb, var(--redline-color-neutral-500) 12%, transparent)',\n 'color-mix(in srgb, var(--redline-color-neutral-500) 26%, transparent)',\n ]\n // Turn labels render at natural width (a 2-digit \"12\" is wider than a 14px turn bar) and overflow their block.\n // Every label must stay on the single line, so the strip shrinks ALL labels to one font size — the largest at\n // which the tightest adjacent pair still clears the gap (analytic widths below, no measurement) — and the\n // measured chain in updateTurnLabels stays only as the last-resort guard past the floor. OVERHANG bounds how\n // far a label can reach beyond its block (a generous read of \"9999\" at 10px) for the viewport-participation\n // test; GAP is the breathing room between adjacent labels' boxes.\n const LABEL_OVERHANG = 48\n const LABEL_GAP = 2\n // Label font sizing (the 10px base mirrors .redline-turn in trendChart.css): conservative upper-bound glyph width\n // at the base size (6.5px per digit at 10px semibold), floored at 6px.\n const LABEL_FONT = 10\n const LABEL_FONT_MIN = 6\n const estTurnLabel = (turn: number): number => 6.5 * String(turn).length\n\n /**\n * Focus a bar on one category (the browser's open category): the kept bucket carries its fold figure, the other\n * buckets zero, and `total` IS the plotted figure — the downstream stack/tooltip math reads the derived record\n * unchanged. The raw fold figures are plotted as-is: a per-request rescale against the provider prompt would drift\n * with the heuristic's ratio error and fake growth into constant categories (a never-changing system prompt must\n * plot flat).\n */\n const focusOf = (req: RequestRecord, cat: string): RequestRecord => {\n const key = cat as Category | 'system' | 'tools'\n const out: RequestRecord = { ...req }\n const v = req[key] || 0\n out.total = v\n for (const c of CATS) out[c.key] = c.key === key ? v : 0\n return out\n }\n\n /**\n * Delta mode: each category keeps the SIGNED change vs the previous record so bars can diverge\n * above/below the zero line; `total` is the churn (summed magnitude), `net` the signed change\n * for the tooltip; the first request starts from zero so the scale is change-driven, and per-request\n * provider prompt/output are dropped (they are not deltas).\n */\n const deltaOf = (req: RequestRecord, prev: RequestRecord | null): RequestRecord => {\n const { prompt: _prompt, output: _output, ...out } = req\n let churn = 0\n let net = 0\n for (const c of CATS) {\n const d = prev !== null ? (req[c.key] || 0) - (prev[c.key] || 0) : 0\n out[c.key] = d\n churn += Math.abs(d)\n net += d\n }\n out.total = churn\n out.net = net\n return out\n }\n\n /** The visible window's own maxima (adaptive scale): the total-mode peak, and the delta arms' up/down sums. */\n interface VisibleMax {\n total: number\n up: number\n down: number\n }\n\n interface ChartBarProps {\n req: RequestRecord\n marker: ContextEventRecord | undefined\n selected: boolean\n hovered: boolean\n inTurn: boolean\n maxTotal: number\n /**\n * Delta mode geometry: zero-line offsets in px (up from the top / down from the bottom of the bar area)\n * and the uniform px-per-token scale — identical above and below the zero line, so a +n segment and a\n * −n segment always draw the same height. All three absent in total mode; passed as PRIMITIVES so the\n * memoized bar keeps its shallow-compare bailout.\n */\n upPx?: number\n downPx?: number\n deltaScale?: number\n /** Bar index in the render order: the entrance grow-in stagger slot (capped inside, so a long log's cascade stays snappy). */\n enterIndex: number\n /** The step flag's label (the bar's cumulative step number), or null to plant none. */\n flag: number | null\n onSelect: (seq: number | null) => void\n onHover: (seq: number | null) => void\n }\n\n // Memoized so a hover/selection change re-renders only the bars whose flags flipped — the retained log renders in full (thousands of\n // nodes on long sessions); `req`/`marker` keep stable identities because the parent memoizes its aggregation, so the default shallow\n // compare suffices.\n const ChartBar = memo(function ChartBar(props: ChartBarProps): ReactElement {\n const { req, marker } = props\n const markerAt = marker !== undefined ? eventAt(marker) : null\n // Delta mode: diverging stacks — positive category deltas pile UP from the zero line, negative ones\n // hang DOWN from it, both in category colors (direction carries the sign, color the category).\n const diverge = props.upPx !== undefined && props.downPx !== undefined && props.deltaScale !== undefined\n // Rise stagger slot, shared by the total stack and both delta arms (trendChart.css scaleY-opens them).\n const enterStyle = { '--redline-i': Math.min(props.enterIndex, STAGGER_CAP) } as CSSProperties\n return (\n <div\n className={'redline-bar hover:bg-(--dsw-alias-bg-layer-2)'\n + (props.selected ? ' redline-bar-selected' : '')\n + (props.hovered ? ' redline-bar-hovered' : '')\n + (props.inTurn ? ' redline-bar-in-turn' : '')}\n data-redline-seq={req.seq}\n style={{ width: `${BAR_W}px` }}\n onClick={() => { props.onSelect(props.selected ? null : req.seq) }}\n onMouseEnter={() => { props.onHover(req.seq) }}\n >\n {props.flag !== null ? (\n // Painted UNDER the ✂ marker (it follows in DOM order): on a rare same-bar collision the event\n // glyph keeps precedence over the landmark.\n <span className=\"redline-step-flag\" aria-hidden=\"true\"><span className=\"redline-step-flag-label\">{props.flag}</span></span>\n ) : null}\n {marker !== undefined ? (\n <span\n className=\"redline-bar-marker\"\n title={'✂ ' + (markerAt !== null ? markerAt + ' — ' : '') + eventLabel(marker)}\n >{'✂'}</span>\n ) : null}\n {diverge ? (\n <>\n <div className=\"redline-bar-up animate-redline-bar-in motion-reduce:animate-none\" style={{ bottom: `${props.downPx}px`, ...enterStyle }}>\n {CATS.map((c) => {\n const d = req[c.key] || 0\n if (d <= 0) return null\n return <div key={c.key} data-redline-cat={c.key} className=\"redline-cat-seg\" style={{ height: `${Math.max(1, Math.round(d * (props.deltaScale as number)))}px`, background: c.color }} />\n })}\n </div>\n <div className=\"redline-bar-down animate-redline-bar-in motion-reduce:animate-none\" style={{ top: `${props.upPx}px`, ...enterStyle }}>\n {CATS.map((c) => {\n const d = req[c.key] || 0\n if (d >= 0) return null\n return <div key={c.key} data-redline-cat={c.key} className=\"redline-cat-seg\" style={{ height: `${Math.max(1, Math.round(-d * (props.deltaScale as number)))}px`, background: c.color }} />\n })}\n </div>\n </>\n ) : (\n <div className=\"redline-bar-stack animate-redline-bar-in motion-reduce:animate-none\" style={enterStyle}>\n {CATS.map((c) => {\n const v = req[c.key] || 0\n if (!v) return null\n // px (not %) heights: the stack is content-driven, so percentage heights would collapse against an indefinite base.\n return <div key={c.key} data-redline-cat={c.key} className=\"redline-cat-seg\" style={{ height: `${Math.max(1, Math.round(v / props.maxTotal * CHART_H))}px`, background: c.color }} />\n })}\n </div>\n )}\n </div>\n )\n })\n\n return function TrendChart(props: TrendChartProps): ReactElement {\n const delta = props.mode === 'delta'\n // An unrecognized focus key degrades to the unfocused chart instead of plotting an empty axis.\n const focus = props.focusCat !== null && props.focusCat !== undefined && CATS.some(c => c.key === props.focusCat)\n ? props.focusCat\n : null\n const requests = useMemo(\n () => {\n const base = focus !== null ? props.requests.map(req => focusOf(req, focus)) : props.requests\n return delta ? base.map((req, i) => deltaOf(req, i > 0 ? base[i - 1] : null)) : base\n },\n [props.requests, delta, focus],\n )\n const markers = props.markers\n // Adaptive scale: the maxima over the bars currently on screen. Null until the first measure, which falls\n // back to the whole-log scale, so the first paint never draws an empty axis; the field-wise comparison means\n // scrolling inside a window whose maxima do not move re-renders nothing.\n const adaptive = props.adaptive === true\n const [visMax, setVisMax] = useState<VisibleMax | null>(null)\n const measureVisible = (el: HTMLDivElement): void => {\n if (!adaptive) return\n const n = requests.length\n // Nothing measurable: an empty history, or a zero-width viewport (a hidden pane, an unlaid-out test DOM).\n // Keeping the previous scale degrades the chart to the whole-log axis instead of flattening every bar.\n if (n === 0 || el.clientWidth <= 0) return\n const pitch = BAR_W + BAR_GAP\n const sl = el.scrollLeft\n const vr = sl + el.clientWidth\n let total = 0\n let up = 0\n let down = 0\n // The column holding the left edge through the one holding the right edge; the per-column test then drops\n // the neighbour whose column falls in the 2px gap just outside the viewport.\n const from = Math.max(0, Math.floor(sl / pitch))\n const to = Math.min(n - 1, Math.max(from, Math.floor((vr - 1) / pitch)))\n for (let i = from; i <= to; i++) {\n const col = i * pitch\n if (col >= vr || col + BAR_W <= sl) continue\n const req = requests[i]\n if (delta) {\n // Per-bar arms, then the window maximum — the same figures the whole-log loop takes.\n let bu = 0\n let bd = 0\n for (const c of CATS) {\n const d = req[c.key] || 0\n if (d > 0) bu += d\n else bd -= d\n }\n if (bu > up) up = bu\n if (bd > down) down = bd\n } else if (req.total > total) {\n total = req.total\n }\n }\n setVisMax(prev => prev !== null && prev.total === total && prev.up === up && prev.down === down\n ? prev\n : { total, up, down })\n }\n // Whole-log maxima: the axis when adaptive is off, and the fallback for a delta window with no change at all\n // (it carries no scale of its own).\n let maxTotal = 1\n let maxUp = 0\n let maxDown = 0\n if (delta) {\n for (const req of requests) {\n let up = 0\n let down = 0\n for (const c of CATS) {\n const d = req[c.key] || 0\n if (d > 0) up += d\n else down -= d\n }\n if (up > maxUp) maxUp = up\n if (down > maxDown) maxDown = down\n }\n } else {\n for (const req of requests) {\n if (req.total > maxTotal) maxTotal = req.total\n }\n }\n if (adaptive && visMax !== null) {\n if (delta) {\n if (visMax.up + visMax.down > 0) {\n maxUp = visMax.up\n maxDown = visMax.down\n }\n } else {\n maxTotal = Math.max(1, visMax.total)\n }\n }\n // The zero line splits the bar area PROPORTIONALLY to the larger side, so the px-per-token scale\n // is identical above and below it — a compaction's downward bar reads honestly against a growth bar.\n const span = Math.max(1, maxUp + maxDown)\n const deltaScale = CHART_H / span\n const upPx = Math.round(maxUp * deltaScale)\n const downPx = CHART_H - upPx\n // A delta quarter mark (axis label + its dashed guide) yields ENTIRELY when its 11px label box would\n // overlap the zero label (top 13+upPx) — the zero line is the reading reference. Total-mode marks never\n // collide and always render.\n const q3Clear = Math.abs(Q3_TOP - 13 - upPx) >= 11\n const q1Clear = Math.abs(Q1_TOP - 13 - upPx) >= 11\n\n // Consecutive same-turn requests collapse into one labeled range; `span` counts the STEP columns the group covers (step records count\n // one each), so strip blocks align with the bars in both granularities.\n const groups: { turn: number; count: number; span: number; agg: boolean }[] = []\n for (const req of requests) {\n let grp = groups.length > 0 ? groups[groups.length - 1] : null\n if (grp === null || grp.turn !== (req.turn ?? 0)) {\n grp = { turn: req.turn ?? 0, count: 0, span: 0, agg: req.stepCount !== undefined }\n groups.push(grp)\n }\n grp.count++\n grp.span += req.stepCount ?? 1\n }\n\n // Strip offsets/widths are computed in content px so the scroll handler can re-center labels analytically and measures only the handful\n // of labels on screen.\n const turnOffsets: number[] = []\n const turnWidths: number[] = []\n {\n let x = 0\n for (const grp of groups) {\n const w = grp.agg ? BAR_W : grp.span * (BAR_W + BAR_GAP) - BAR_GAP\n turnOffsets.push(x)\n turnWidths.push(w)\n x += w + BAR_GAP\n }\n }\n\n // One font size for the whole strip: the largest at which the TIGHTEST adjacent pair of labels still clears\n // the gap between their block centers (center distance = half each block + the gap between blocks), so every\n // turn label stays shown on the single line instead of thinning out. Uniform (not per-label) so sizes never\n // mix, and computed from the groups alone so it is stable while scrolling.\n let labelFont = ''\n {\n let scale = 1\n for (let i = 0; i + 1 < groups.length; i++) {\n const avail = (turnWidths[i] + turnWidths[i + 1]) / 2 + BAR_GAP\n const need = (estTurnLabel(groups[i].turn) + estTurnLabel(groups[i + 1].turn)) / 2 + LABEL_GAP\n if (need > avail) scale = Math.min(scale, avail / need)\n }\n if (scale < 1) labelFont = `${Math.max(LABEL_FONT_MIN, Math.floor(LABEL_FONT * scale))}px`\n }\n\n // Default anchor: newest bars at the RIGHT edge; the first layout after mount scrolls unconditionally, a GRANULARITY SWITCH re-anchors\n // the same way (step mode must not inherit the turn chart's stale left edge), otherwise stick to the end only while already near it;\n // useLayoutEffect avoids a first-paint flash.\n const scrollRef = useRef<HTMLDivElement | null>(null)\n const scrolledOnce = useRef(false)\n const lastGranRef = useRef(props.granularity)\n // The newest bar's seq (or 0 when the log is empty): the layout effect only re-runs when the right edge genuinely\n // moves (new bar appended, granularity switched, focus turn set) — hover/select changes keep their scroll position\n // so the chart does not flash with every keystroke.\n const lastSeqRef = useRef(0)\n // The scrollWidth measured during the PREVIOUS effect pass. The \"was the reader near the right edge?\" check\n // has to compare against the width as it was BEFORE the new bar landed — by the time the layout effect runs,\n // `el.scrollWidth` is already the new (wider) value, so a near-edge check against it would miss the auto-follow.\n const prevScrollWidthRef = useRef(0)\n /**\n * Keep each turn label centered within its block's VISIBLE slice, then thin colliding labels: a label wider\n * than its block overflows it, so consecutive narrow turns would smear into each other — walking left→right\n * in content coordinates, a label whose box reaches the previous KEPT one drops to visibility:hidden. The\n * render-time font shrink (labelFont) already sizes every label to clear its tightest neighbour, so this\n * chain only fires past the 6px floor or on viewport-edge shifts. Blocks that cannot reach the viewport even\n * overhung by a label skip their reads/writes entirely (their transform/visibility just reset); reads\n * (offsetWidth) batch before the writes to avoid layout thrash, and unchanged styles write nothing.\n */\n const updateTurnLabels = (el: HTMLDivElement): void => {\n const labels = el.querySelectorAll<HTMLElement>('.redline-turn-label')\n const n = Math.min(labels.length, turnOffsets.length)\n const sl = el.scrollLeft\n const vr = sl + el.clientWidth\n const writes: [HTMLElement, string, string][] = []\n // Right edge (content px) of the last kept label's box plus the gap; -Infinity opens the chain.\n let chainR = -Infinity\n for (let i = 0; i < n; i++) {\n const off = turnOffsets[i]\n const w = turnWidths[i]\n let dx = 0\n let vis = ''\n if (off + w + LABEL_OVERHANG > sl && off - LABEL_OVERHANG < vr) {\n const lw = labels[i].offsetWidth\n const visL = Math.max(off, sl)\n const visR = Math.min(off + w, vr)\n if (visR > visL && lw < w) {\n const center = (visL + visR) / 2 - off\n dx = Math.min(Math.max(center, lw / 2), w - lw / 2) - w / 2\n }\n const left = off + w / 2 + dx - lw / 2\n if (left < chainR) vis = 'hidden'\n else chainR = left + lw + LABEL_GAP\n }\n const next = dx !== 0 ? `translateX(${dx}px)` : ''\n if (labels[i].style.transform !== next || labels[i].style.visibility !== vis) writes.push([labels[i], next, vis])\n }\n for (const [label, next, vis] of writes) {\n label.style.transform = next\n label.style.visibility = vis\n }\n }\n useLayoutEffect(() => {\n const el = scrollRef.current\n /* v8 ignore next 1 -- the scroll div renders unconditionally and React\n attaches refs before layout effects run; el is never null here. */\n if (el === null) return\n const newestSeq = requests.length === 0 ? 0 : requests[requests.length - 1].seq\n const grew = newestSeq !== lastSeqRef.current\n const widthBeforeAppend = prevScrollWidthRef.current\n if (props.granularity !== lastGranRef.current) {\n lastGranRef.current = props.granularity\n scrolledOnce.current = false\n }\n // A strip-clicked focus turn centers its bar instead of the newest anchor, consumed once via onFocusTurnHandled — also when\n // granularity was already 'turn' (no re-anchor happens that render).\n if (props.focusTurn !== null) {\n const gi = groups.findIndex(g => g.turn === props.focusTurn)\n if (gi >= 0) {\n scrolledOnce.current = true\n el.scrollLeft = Math.max(0, gi * (BAR_W + BAR_GAP) + BAR_W / 2 - el.clientWidth / 2)\n }\n props.onFocusTurnHandled()\n } else if (!scrolledOnce.current) {\n scrolledOnce.current = true\n el.scrollLeft = el.scrollWidth\n } else if (grew && el.scrollLeft + el.clientWidth >= widthBeforeAppend - 24) {\n // Only follow the latest bar when the right edge actually moved AND the reader was already near it\n // BEFORE the new bar landed — comparing against the new scrollWidth would silently drop the stick for a\n // mid-chart reader whose viewport just slid past the near-end threshold.\n el.scrollLeft = el.scrollWidth\n }\n lastSeqRef.current = newestSeq\n prevScrollWidthRef.current = el.scrollWidth\n updateTurnLabels(el)\n syncTip(el)\n measureVisible(el)\n }, [props.granularity, props.focusTurn, requests, adaptive])\n\n // The observer callback needs the LATEST measure closure (it captures `requests`/`delta`); a ref keeps it fresh\n // without tearing the observer down on every commit.\n const measureRef = useRef(measureVisible)\n useLayoutEffect(() => { measureRef.current = measureVisible })\n // A pane resize (sidebar collapse/drag, window resize) changes the visible window without any render, so the\n // observer re-measures. jsdom exposes no ResizeObserver — the commit/scroll measures cover those paths.\n useLayoutEffect(() => {\n const el = scrollRef.current\n /* v8 ignore next 1 -- the scroll div renders unconditionally and React\n attaches refs before layout effects run; el is never null here. */\n if (el === null) return\n if (typeof ResizeObserver !== 'function') return\n const observer = new ResizeObserver(() => { measureRef.current(el) })\n observer.observe(el)\n return () => { observer.disconnect() }\n }, [])\n // A horizontal swipe running off the chart's edge must not chain into the browser's history navigation\n // (overscroll.ts): the sheet's overscroll-behavior-x covers Chromium/Firefox, this covers WebKit.\n useLayoutEffect(() => {\n const el = scrollRef.current\n /* v8 ignore next 1 -- the scroll div renders unconditionally and React\n attaches refs before layout effects run; el is never null here. */\n if (el === null) return\n return containHorizontalOverscroll(el)\n }, [])\n\n // Compact 2-row hover tooltip, shown instantly by the custom `.redline-chart-tip` (the native title is delayed):\n // identity and the bar's total — the SAME value the bar height and axis are scaled against (the fold's\n // heuristic figure, matching every other card). Identity phrasing follows the granularity —\n // turn bars always speak TURN (the aggregate's step count, singular for a 1-step turn; a record missing\n // stepCount degrades to that too), step bars carry the step index plus the turn's step total. Delta swaps\n // the metric row for the net.\n const stepsOf = useMemo(() => turnStepsOf(props.requests), [props.requests])\n const tipRowsOf = (req: RequestRecord): [string, string] => {\n const n = req.stepCount ?? 1\n const head = props.granularity === 'turn'\n ? (n > 1 ? t('tip.turn', { t: req.turn ?? 0, n }) : t('tip.turn1', { t: req.turn ?? 0 }))\n : t('tip.step', { t: req.turn ?? 0, s: req.step ?? 0, n: stepsOf(req.turn) })\n if (delta) {\n /* v8 ignore next 1 -- delta mode only receives records from\n deltaOf, which always assigns net; the fallback is defensive. */\n const n = req.net ?? 0\n return [head, t('tip.delta', { n: (n > 0 ? '+' : '') + fmt(n) })]\n }\n // Focused: the metric row IS the focused category's figure, so the tip names it instead of claiming a total.\n return [head, focus !== null\n ? t('tip.cat', { cat: catLabel(focus), n: fmt(req.total) })\n : t('tip.total', { n: fmt(req.total) })]\n }\n const hoveredIdx = props.hoveredSeq !== null ? requests.findIndex(r => r.seq === props.hoveredSeq) : -1\n const hoveredReq = hoveredIdx >= 0 ? requests[hoveredIdx] : null\n\n // Column center (content px) of the currently hovered bar, for syncTip reads outside the render pass.\n const tipColRef = useRef(0)\n\n /**\n * Glue the hover tip to its bar's VISIBLE slice. The tip deliberately does NOT live inside the scrolling\n * content: an absolutely-positioned child of a scroller contributes to its scrollable overflow, so a wide\n * reply preview on a right-edge bar used to inflate scrollWidth on every hover and flap the horizontal\n * scrollbar open/closed — jumping the whole card. Reads (offsetWidth/clientWidth) batch before the single\n * style write; unchanged transforms write nothing.\n */\n const syncTip = (el: HTMLDivElement): void => {\n /* v8 ignore next 1 -- the scroll div renders unconditionally while mounted, so its parent exists. */\n const tip = (el.parentElement ?? document.body).querySelector<HTMLElement>('.redline-chart-tip')\n // No hover, nothing to place.\n if (tip === null) return\n const lw = tip.offsetWidth\n const cw = el.clientWidth\n // Center over the bar's visible slice, clamped so the tip never hangs past either edge nor gets cut off; a tip\n // wider than the viewport centers over it instead of picking a bogus side on an inverted clamp window.\n const half = Math.min(lw / 2, cw / 2)\n const cx = Math.min(Math.max(tipColRef.current - el.scrollLeft, half), cw - half)\n const next = `translate(${Math.round(cx - lw / 2)}px, 0)`\n if (tip.style.transform !== next) tip.style.transform = next\n }\n\n // Position (and re-position after EVERY commit — the tip mounts on hover changes, which touch no other\n // effect dependency here) from the committed hovered column before paint.\n useLayoutEffect(() => {\n /* v8 ignore next 1 -- the scroll div renders unconditionally and React attaches refs before\n layout effects run; el is never null here. */\n if (scrollRef.current === null) return\n tipColRef.current = hoveredIdx >= 0 ? hoveredIdx * (BAR_W + BAR_GAP) + BAR_W / 2 : 0\n syncTip(scrollRef.current)\n })\n\n return (\n <div className=\"redline-chartrow\">\n <div className=\"redline-axis\">\n {delta ? (\n <>\n <span className=\"redline-axis-top\">{fmtSigned(maxUp)}</span>\n {/* Axis quartile marks on the uniform px-per-token scale (the value at each fixed height); a mark\n whose 11px label box would overlap the zero label drops itself — the zero line is the reading\n reference and keeps its place. */}\n {q3Clear\n ? <span className=\"redline-axis-q3\">{fmtSigned(Math.round(maxUp - span / 4))}</span>\n : null}\n {/* The 0 label rides the zero line (chart top padding 18px, half the 11px line-height up). */}\n <span className=\"redline-axis-mid\" style={{ top: `${13 + upPx}px` }}>{'0'}</span>\n {q1Clear\n ? <span className=\"redline-axis-q1\">{fmtSigned(Math.round(maxUp - 3 * span / 4))}</span>\n : null}\n <span className=\"redline-axis-bot\">{fmtSigned(-maxDown)}</span>\n </>\n ) : (\n <>\n <span className=\"redline-axis-top\">{fmt(maxTotal)}</span>\n <span className=\"redline-axis-q3\">{fmt(Math.round(maxTotal * 3 / 4))}</span>\n <span className=\"redline-axis-mid\">{fmt(Math.round(maxTotal / 2))}</span>\n <span className=\"redline-axis-q1\">{fmt(Math.round(maxTotal / 4))}</span>\n <span className=\"redline-axis-bot\">{'0'}</span>\n </>\n )}\n </div>\n {/* Only the scrolling CONTENT lives under .redline-chart-scroll; the hover tip sits beside it inside the\n positioned wrapper instead of inside the scroller — absolutely-positioned children of a scroller\n contribute to its scrollable overflow AND translate away with the content on scroll. */}\n <div className=\"redline-chart-wrap\">\n <div\n className={'redline-chart-scroll' + (props.activeTurn !== null ? ' redline-chart-dim' : '')}\n ref={scrollRef}\n onScroll={(e: UIEvent<HTMLDivElement>) => {\n updateTurnLabels(e.currentTarget)\n syncTip(e.currentTarget)\n measureVisible(e.currentTarget)\n }}\n >\n <div\n className=\"redline-chart\"\n // The shared category hover rides a plain attribute: the CSS lights that key's segment in EVERY bar\n // and recedes the rest, so the memoized bars never re-render on a cross-card hover change.\n data-redline-catdim={props.hoverCat ?? undefined}\n onMouseLeave={() => { props.onHover(null) }}\n >\n <div className=\"redline-grid redline-grid-top\" />\n {/* Dashed guides aligning the bars with the axis quarter marks (fixed heights, both modes); a delta\n mark that yielded to the zero label drops its guide too, and a coinciding guide sits under the\n solid zero line painted after it. */}\n {(!delta || q3Clear) ? <div className=\"redline-grid redline-grid-q3\" /> : null}\n {(!delta || q1Clear) ? <div className=\"redline-grid redline-grid-q1\" /> : null}\n {!delta ? <div className=\"redline-grid redline-grid-mid\" /> : null}\n {/* The SOLID zero baseline — the reading reference in both modes: inline-positioned off the up-arm\n in delta mode, the chart floor (CSS default) under the '0' label in total mode. */}\n <div className=\"redline-grid redline-grid-zero\" style={delta ? { top: `${18 + upPx}px` } : undefined} />\n {requests.map((req, i) => (\n <ChartBar\n // Granularity belongs in the key: a turn aggregate IS its last step's record (the same\n // seq), so a step ↔ turn switch would otherwise REUSE that bar's DOM node and its finished\n // entrance rise would not replay — every turn's last step bar would pop in unanimated.\n key={`${req.seq}:${props.granularity}`}\n req={req}\n marker={markers[i]}\n selected={props.selectedSeq === req.seq}\n hovered={props.hoveredSeq === req.seq}\n inTurn={props.activeTurn !== null && (req.turn ?? 0) === props.activeTurn}\n // Turn bars skip the flag: the turn strip below already numbers that grid.\n flag={props.granularity === 'step' && (i + 1) % STEP_FLAG_EVERY === 0 ? i + 1 : null}\n maxTotal={maxTotal}\n upPx={delta ? upPx : undefined}\n downPx={delta ? downPx : undefined}\n deltaScale={delta ? deltaScale : undefined}\n enterIndex={i}\n onSelect={props.onSelect}\n onHover={props.onHover}\n />\n ))}\n </div>\n {/* Turn strip: one COLOR BLOCK per turn spanning exactly its bars' columns, so the partition reads at a glance and lines\n up with the steps; hovering a block highlights that turn's bars and vice versa — one shared hover-only state.\n */}\n <div className=\"redline-turns\" style={labelFont !== '' ? { fontSize: labelFont } : undefined} onMouseLeave={() => { props.onHoverTurn(null) }}>\n {groups.map((grp, gi) => {\n const on = props.activeTurn === grp.turn\n return (\n <span\n key={`turn-${gi}`}\n className={'redline-turn' + (on ? ' redline-turn-on' : '')}\n style={{\n width: `${turnWidths[gi]}px`,\n background: TURN_FILLS[gi % TURN_FILLS.length],\n }}\n title={`T${grp.turn}`}\n onMouseEnter={() => { props.onHoverTurn(grp.turn) }}\n onClick={() => { props.onPickTurn(grp.turn) }}\n ><span className=\"redline-turn-label\">{`${grp.turn}`}</span></span>\n )\n })}\n </div>\n </div>\n {/* Compact 2-row hover tooltip (identity / bar total), shown instantly by the custom `.redline-chart-tip`\n (the native title is delayed); the per-category breakdown lives in the detail panel below. It floats\n ABOVE the plot (CSS bottom anchoring) so it never covers the bars, is capped at the wrapper's width\n and wrapped, and is positioned imperatively over its bar's visible slice (syncTip) so scrolling keeps\n it glued without ever widening the scrollable area. */}\n {hoveredReq !== null ? (\n <div className=\"redline-chart-tip\">{tipRowsOf(hoveredReq).map((row, i) => <span key={i}>{row}</span>)}</div>\n ) : null}\n </div>\n </div>\n )\n }\n}\n","/**\n * The fetch-on-miss state machine behind the Context browser's two on-demand\n * reads (a row's full message content and a header epoch's prompt/schemas):\n * one targeted history read per key the local data missed, with a visible\n * terminal state for every outcome — `absent` when the durable log does not\n * hold the key, `failed` arming the retry button, never an unhandled\n * rejection or a spinner that never resolves. Landed values cache by key:\n * history is immutable, so a resolved key never refetches.\n */\n\nimport { useEffect, useState, type ReactNode } from 'react'\nimport type { Translate } from '../i18n'\n\nexport type FetchMissState = 'idle' | 'loading' | 'absent' | 'failed'\n\nexport interface FetchOnMiss<T> {\n /** Resolved values by key (immutable history — a landed value never refetches). */\n values: Map<number, T>\n state: FetchMissState\n /** Re-arm the read after a failure (the retry button). */\n retry: () => void\n}\n\n/**\n * Run one fetch for `key` when it is set and not yet cached. `key` null (no\n * target open) or `fetcher` undefined (older host without the history face)\n * leaves the machine idle; the caller renders the matching note either way.\n */\nexport function useFetchOnMiss<T>(\n key: number | null,\n fetcher: ((key: number) => Promise<T | null>) | undefined,\n warn: string,\n): FetchOnMiss<T> {\n const [values, setValues] = useState<Map<number, T>>(() => new Map())\n const [state, setState] = useState<FetchMissState>('idle')\n const [attempt, setAttempt] = useState(0)\n useEffect(() => {\n if (key === null || fetcher === undefined || values.has(key)) return\n let live = true\n setState('loading')\n fetcher(key).then((value) => {\n if (!live) return\n if (value === null) {\n setState('absent')\n return\n }\n setValues((prev) => {\n const next = new Map(prev)\n next.set(key, value)\n return next\n })\n setState('idle')\n }, (error: unknown) => {\n console.warn(warn, error)\n if (live) setState('failed')\n })\n return () => { live = false }\n }, [key, fetcher, attempt, values])\n return { values, state, retry: () => { setAttempt(a => a + 1) } }\n}\n\n/**\n * The note a not-yet-loaded fetch target shows — one expression for both\n * on-demand reads: the legacy static hint (`emptyKey`) when no fetcher is\n * composed, `loading` while the read is in flight (and on the first frame\n * before the effect fires), `notInLog` when the durable log does not hold\n * the key, and a retry button after a failed read.\n */\nexport function fetchMissNote(\n t: Translate,\n fetcher: unknown,\n state: FetchMissState,\n onRetry: () => void,\n emptyKey: 'browser.noContent' | 'browser.headerMetaOnly',\n): ReactNode {\n if (fetcher === undefined) return t(emptyKey)\n if (state === 'absent') return t('browser.notInLog')\n if (state === 'failed') {\n return (\n <button type=\"button\" className=\"redline-br-retry hover:brightness-[1.15]\" onClick={onRetry}>\n {t('browser.loadFailed')}\n </button>\n )\n }\n return t('browser.loading')\n}\n","/**\n * Generation-proof named imports from the ui-primitives platform module.\n *\n * The icon vocabulary renamed across the supported range — `Icon*Outline16` /\n * `Icon*Outline14` through 0.1.5, `Icon*OutlineRegular` / `Icon*OutlineMedium`\n * from 0.1.6 — and a renamed export arrives as `undefined` at runtime (the\n * pinned devDep's types cannot see the other generation), which rendered as\n * React error #130 inside the Context tab. Each icon here resolves through\n * BOTH spellings at module load, modern first; a render-nothing fallback keeps\n * a future rename a missing glyph instead of a crashed tab.\n */\n\nimport type { ReactElement } from 'react'\nimport * as primitives from '@deepseek-ai/dsh-client-ui-primitives'\nimport type { IconProps } from '@deepseek-ai/dsh-client-ui-primitives'\n\n/** One platform icon component, as the call sites render it. */\nexport type IconComponent = (props: IconProps) => ReactElement | null\n\n/** The platform module's export surface, read by name (the two vocabularies meet here). */\nconst ns = primitives as unknown as Record<string, unknown>\n\n/**\n * Read one export through a bounded catch: partial module mocks (and any\n * hostile namespace) may throw on the property access itself, which must\n * degrade to \"not this spelling\", never crash the importer.\n */\nfunction read(source: Record<string, unknown>, key: string): unknown {\n try {\n return source[key]\n } catch {\n return undefined\n }\n}\n\n/**\n * Resolve one icon across the range's two spellings: the modern\n * `…OutlineRegular`/`…OutlineMedium` name first, then the legacy\n * `…Outline16`/`…Outline14` one; neither present (or not a component)\n * renders nothing. `source` overrides the platform namespace for tests.\n */\nexport function resolveIcon(modern: string, legacy: string, source: Record<string, unknown> = ns): IconComponent {\n const found = read(source, modern) ?? read(source, legacy)\n return typeof found === 'function' ? found as IconComponent : () => null\n}\n\nexport const IconBranch = resolveIcon('IconBranchOutlineRegular', 'IconBranchOutline16')\nexport const IconPlus = resolveIcon('IconPlusOutlineRegular', 'IconPlusOutline16')\nexport const IconCheck = resolveIcon('IconCheckOutlineRegular', 'IconCheckOutline16')\nexport const IconCopy = resolveIcon('IconCopyOutlineRegular', 'IconCopyOutline16')\nexport const IconClose = resolveIcon('IconCloseOutlineRegular', 'IconCloseOutline16')\nexport const IconSettings = resolveIcon('IconSettingsOutlineMedium', 'IconSettingsOutline14')\nexport const IconChevronDown = resolveIcon('IconChevronDownOutlineMedium', 'IconChevronDownOutline14')\n","/** `fmt`: the k/M/B suffix style shared by bars/details/stats; `fmtTime`: local HH:MM:SS. */\n\nexport function fmt(n: number | null | undefined): string {\n if (n === undefined || n === null || isNaN(n)) return '—'\n const sign = n < 0 ? '-' : ''\n const a = Math.abs(n)\n if (a >= 1e9) return sign + (a / 1e9).toFixed(1) + 'B'\n if (a >= 1e6) return sign + (a / 1e6).toFixed(1) + 'M'\n if (a >= 1000) return sign + (a / 1000).toFixed(1) + 'k'\n return sign + String(Math.round(a))\n}\n\n/** Byte sizes for attachment metadata (1 kB = 1000 B, matching the k/M style of `fmt`). */\nexport function fmtBytes(n: number | null | undefined): string {\n if (n === undefined || n === null || isNaN(n) || n < 0) return '—'\n if (n >= 1e6) return (n / 1e6).toFixed(1) + ' MB'\n if (n >= 1000) return (n / 1000).toFixed(1) + ' kB'\n return String(Math.round(n)) + ' B'\n}\n\n/**\n * Cache-hit share of billed prompt-side input (`reads` over `billed`),\n * TRUNCATED to `decimals` places (cut, not round) — same formula as the\n * harness chat stats line's '缓存命中' figure and the stats board's cell\n * (which shows two decimals). Null when nothing was billed. The 1e-9 epsilon\n * absorbs only float noise (integer token counts never sit that close to a\n * boundary).\n */\nexport function cacheHitPercent(reads: number, billed: number, decimals = 2): string | null {\n if (!(billed > 0)) return null\n const factor = 10 ** decimals\n const scaled = Math.trunc((reads / billed) * 100 * factor + 1e-9)\n return `${Math.floor(scaled / factor)}.${String(scaled % factor).padStart(decimals, '0')}`\n}\n\nexport function fmtTime(t: number): string {\n // en-GB 24-hour clock zero-pads HH:MM:SS without a helper; invalid dates must show '—' (toLocaleTimeString throws RangeError).\n const d = new Date(t)\n if (isNaN(d.getTime())) return '—'\n return d.toLocaleTimeString('en-GB', { hour12: false })\n}\n\n/**\n * Share of a whole as a compact leading percentage for the slice rows:\n * '—' when nothing totals, '0.0%' for empty slices, '<0.1%' for non-zero\n * crumbs a 0.1%-precision figure would erase. One decimal everywhere; shares\n * cap at 100% (parallel tool time can over-run the wall it belongs to).\n */\nexport function fmtShare(part: number, total: number): string {\n if (!Number.isFinite(part) || !Number.isFinite(total) || total <= 0) return '—'\n if (part <= 0) return '0.0%'\n const pct = Math.min(1, part / total) * 100\n if (pct < 0.1) return '<0.1%'\n return `${pct.toFixed(1)}%`\n}\n\n/**\n * Whole-session durations for the timing card, locale-free compact units: raw\n * ms under a second, one-decimal seconds under a minute, then m/s and h/m.\n * Non-finite or non-positive input shows the dash (callers render their empty\n * state anyway).\n */\nexport function fmtDuration(ms: number): string {\n if (!Number.isFinite(ms) || ms <= 0) return '—'\n if (ms < 1000) return `${Math.round(ms)}ms`\n if (ms < 60_000) return `${(ms / 1000).toFixed(1)}s`\n const totalSec = Math.floor(ms / 1000)\n const m = Math.floor(totalSec / 60)\n const s = totalSec % 60\n if (ms < 3_600_000) return `${m}m${s}s`\n return `${Math.floor(m / 60)}h${m % 60}m`\n}\n","/**\n * Per-image token estimate for DeepSeek's vision model — a faithful port of\n * the official \"图片 Token 计算器\" (Image Token Calculator) shipped on the\n * DeepSeek API docs (https://api-docs.deepseek.com/zh-cn/quick_start/token_usage),\n * which implements the provider's own image→token conversion:\n *\n * - every image is aspect-preserved rescaled before entering the model:\n * below ~384×384 total pixels it is enlarged, above it is shrunk;\n * - tokens follow the patch grid (patch 14px, downsample 3), so every\n * image costs at least 117 and at most ~384 tokens (the documented cap).\n *\n * Verified against the docs calculator itself: 2048×1365→313, 800×600→341,\n * 2048×2048→349, 512×512→201, 100×100→117, 1920×1080→369, 400×900→249.\n * The DSH request pipeline's own 640k-pixel pre-resize does not change the\n * result (the provider formula rescales to the same patch grid), so the\n * durable attachment dimensions can be fed in directly.\n *\n * Pure math shared by the Host fold (message pricing) and the Client\n * (attachment card token badges) — no dependencies, never mutates.\n */\n\nconst PATCH_SIZE = 14\nconst DOWNSAMPLE_RATIO = 3\n/** Documented per-image token cap ( DeepSeek vision guide ). */\nconst MAX_TOKENS = 384\nconst COMPRESS_PAD_TO = 4\nconst MAX_WH_RATIO = 8\n/** ~384×384 total pixels: smaller images are enlarged before patching. */\nconst MIN_PIXELS = 147456\n\nconst floorDiv = (a: number, b: number): number => Math.floor(a / b)\nconst ceilDiv = (a: number, b: number): number => Math.floor((a + b - 1) / b)\n\nfunction gridTokens(rows: number, cols: number): number {\n let n = rows * (cols + 1) + 2\n if (rows % 2 === 1) n += cols + 1\n n += (ceilDiv(rows, 2) * (cols + 1) % 2) * 2\n return n\n}\n\ninterface ResizeSolution {\n nLlmH: number\n nLlmW: number\n bestHeight: number\n bestWidth: number\n numTokens: number\n}\n\n/** Solve the largest in-grid resize whose token count fits `budget`. */\nfunction solveResizeRatio(height: number, width: number, budget: number): ResizeSolution {\n const ratio = height / width\n const gridW = Math.sqrt((budget - 2) / ratio + 0.25) - 0.5\n const gridH = gridW * ratio\n const unit = PATCH_SIZE * DOWNSAMPLE_RATIO\n let bestHeight: number\n let bestWidth: number\n if (gridW < 1) {\n // Tall image: width collapses to one unit, height takes the budget.\n let rows = floorDiv(budget - 2, 2)\n /* v8 ignore else -- budget enters at 381 and the tall solve always fits\n (never decrements), so rows is always odd here; parity-defensive. */\n if (rows % 2 === 1) rows -= 1\n bestWidth = unit\n bestHeight = rows * unit\n /* v8 ignore start -- unreachable: the MAX_WH_RATIO clamp in\n calcResizeInner keeps height/width ≥ 1/8, so gridH = gridW × ratio\n can never fall below 2 (500k-dimension fuzz: wide = 0 hits); the arm\n is kept verbatim from the official calculator port. */\n } else if (gridH < 2) {\n // Wide image: height collapses to two units, width takes the budget.\n const cols = floorDiv(budget - 2, 2) - 1\n if (cols <= 1) throw new Error('image tokens: budget too small to solve')\n bestHeight = 2 * unit\n bestWidth = cols * unit\n /* v8 ignore stop */\n } else {\n const cols = Math.trunc(gridW)\n // The row grid carries the pairing constraint: odd counts round down.\n let rows = Math.trunc(gridH)\n if (rows % 2 === 1) rows -= 1\n const scale = Math.min(cols * unit / width, rows * unit / height)\n bestWidth = Math.trunc(width * scale / PATCH_SIZE) * PATCH_SIZE\n bestHeight = Math.trunc(height * scale / PATCH_SIZE) * PATCH_SIZE\n }\n const nLlmH = ceilDiv(floorDiv(bestHeight, PATCH_SIZE), DOWNSAMPLE_RATIO)\n const nLlmW = ceilDiv(floorDiv(bestWidth, PATCH_SIZE), DOWNSAMPLE_RATIO)\n return { nLlmH, nLlmW, bestHeight, bestWidth, numTokens: gridTokens(nLlmH, nLlmW) }\n}\n\n/** Resize so the patch grid fits the cap, then re-add the pad reserve. */\nfunction safeResize(height: number, width: number, paddedHeight: number, paddedWidth: number): ResizeSolution {\n const nLlmH = ceilDiv(floorDiv(paddedHeight, PATCH_SIZE), DOWNSAMPLE_RATIO)\n const nLlmW = ceilDiv(floorDiv(paddedWidth, PATCH_SIZE), DOWNSAMPLE_RATIO)\n const pad = COMPRESS_PAD_TO - 1\n const budget = MAX_TOKENS - pad\n let result: ResizeSolution = {\n nLlmH, nLlmW, bestHeight: paddedHeight, bestWidth: paddedWidth,\n numTokens: gridTokens(nLlmH, nLlmW),\n }\n if (result.numTokens > budget) {\n result = solveResizeRatio(height, width, budget)\n let nextBudget = budget\n while (result.numTokens > budget) {\n nextBudget -= 1\n result = solveResizeRatio(height, width, nextBudget)\n }\n }\n result.numTokens += pad\n return result\n}\n\nfunction calcResizeInner(width: number, height: number): ResizeSolution {\n let w = width\n let h = height\n if (w > h * MAX_WH_RATIO) w = h * MAX_WH_RATIO\n const pixels = w * h\n if (pixels < MIN_PIXELS && pixels > 0) {\n const scale = Math.sqrt(MIN_PIXELS / pixels)\n w = Math.trunc(w * scale)\n h = Math.trunc(h * scale)\n }\n const paddedWidth = ceilDiv(w, PATCH_SIZE) * PATCH_SIZE\n const paddedHeight = ceilDiv(h, PATCH_SIZE) * PATCH_SIZE\n return safeResize(h, w, paddedHeight, paddedWidth)\n}\n\n/**\n * Estimate the tokens one image consumes in a DeepSeek vision request from its pixel dimensions. Returns null for non-positive/non-finite\n * dimensions or when the official iteration fails to converge — callers fall back to the generic structural price.\n */\nexport function estimateImageTokens(width: number, height: number): number | null {\n if (!Number.isFinite(width) || !Number.isFinite(height) || width <= 0 || height <= 0) return null\n try {\n let result = calcResizeInner(width, height)\n for (let i = 1; i < 10; i++) {\n const next = calcResizeInner(result.bestWidth, result.bestHeight)\n if (next.nLlmH === result.nLlmH && next.nLlmW === result.nLlmW\n && next.bestHeight === result.bestHeight && next.bestWidth === result.bestWidth\n && next.numTokens === result.numTokens) return result.numTokens\n result = next\n }\n return null\n } catch {\n /* v8 ignore next -- the only throw site is the clamped-away budget guard\n above; the catch keeps a hostile dimension from ever breaking the fold. */\n return null\n }\n}\n","/**\n * dsh's multimodal pipeline stores only a normalized reference per image (never inline bytes); the block carries everything the card needs\n * except the display URL, which comes from the harness `uiConversation` service's `imageUrl` (the same loader the chat history rides on),\n * handed down as `load`; absent loader or failed load degrades to the metadata row alone — the card never throws.\n */\n\nimport { useCallback, useEffect, useRef, useState, type ReactElement } from 'react'\nimport { createPortal } from 'react-dom'\nimport { IconClose } from '../primitives'\nimport { fmtBytes } from '../format'\nimport type { ImageLoader, ImageRefLike } from '../services'\nimport { estimateImageTokens } from '../../shared/imageTokens'\nimport type { ViewKit } from '../viewkit'\n\nexport interface ImageKit {\n Card: (props: { attachment: ImageRefLike; load?: ImageLoader }) => ReactElement\n load?: ImageLoader\n}\n\n/**\n * Narrow an unknown content block to a durable image ref: accepts both raw message blocks (`{ type: 'image', attachment }`) and the\n * snapshot's assistant blocks (`{ kind: 'image', attachment }`); everything else null. Lenient on the optional facts — imageUrl reads\n * only attachmentId.\n */\nexport function imageRefOf(block: unknown): ImageRefLike | null {\n if (block === null || typeof block !== 'object') return null\n const b = block as { type?: unknown; kind?: unknown; attachment?: unknown }\n if (b.type !== 'image' && b.kind !== 'image') return null\n const a = b.attachment\n if (a === null || typeof a !== 'object') return null\n const r = a as Record<string, unknown>\n if (typeof r.attachmentId !== 'string' || r.attachmentId === '') return null\n const num = (v: unknown): number | undefined =>\n typeof v === 'number' && Number.isFinite(v) && v > 0 ? v : undefined\n const orig = r.originalDimensions !== null && typeof r.originalDimensions === 'object'\n ? r.originalDimensions as Record<string, unknown>\n : undefined\n const origDims = orig !== undefined && num(orig.width) !== undefined && num(orig.height) !== undefined\n ? { width: num(orig.width) as number, height: num(orig.height) as number }\n : undefined\n return {\n attachmentId: r.attachmentId,\n ...(typeof r.name === 'string' && r.name !== '' ? { name: r.name } : {}),\n ...(num(r.bytes) !== undefined ? { bytes: num(r.bytes) } : {}),\n ...(num(r.width) !== undefined ? { width: num(r.width) } : {}),\n ...(num(r.height) !== undefined ? { height: num(r.height) } : {}),\n ...(origDims !== undefined ? { originalDimensions: origDims } : {}),\n }\n}\n\n/**\n * Document-level original-image preview — the chat history's ImageLightbox recipe (dsh ui-attachment, which the browser module table does\n * not seed) ported onto the plugin's redline-* classes: body portal (a transformed/filtered ancestor cannot trap the fixed\n * backdrop), blurred\n * mask, contain-fit image, circular close, Escape/mask close, focus restored to the opener.\n */\nfunction AttachmentLightbox(props: {\n src: string\n alt: string\n labels: { dialog: string; close: string }\n onClose: () => void\n}): ReactElement {\n const { src, alt, labels, onClose } = props\n const closeRef = useRef<HTMLButtonElement | null>(null)\n const restoreRef = useRef<HTMLElement | null>(null)\n\n useEffect(() => {\n restoreRef.current = document.activeElement instanceof HTMLElement ? document.activeElement : null\n closeRef.current?.focus()\n const onKeyDown = (event: KeyboardEvent): void => {\n if (event.key === 'Escape') onClose()\n }\n window.addEventListener('keydown', onKeyDown)\n return () => {\n window.removeEventListener('keydown', onKeyDown)\n restoreRef.current?.focus()\n }\n }, [onClose])\n\n return createPortal(\n <div className=\"redline-att-lightbox\" role=\"dialog\" aria-modal=\"true\" aria-label={labels.dialog}>\n <div className=\"redline-att-lightbox-mask\" aria-hidden=\"true\" onMouseDown={onClose} />\n <img className=\"redline-att-lightbox-img\" src={src} alt={alt} />\n <button ref={closeRef} type=\"button\" className=\"redline-att-lightbox-close\" aria-label={labels.close} onClick={onClose}>\n <IconClose size={16} />\n </button>\n </div>,\n document.body,\n )\n}\n\n/**\n * One attachment card, the WHOLE card the click target: 64px cover tile + metadata column — Raw (the pre-normalization raster dsh records\n * when normalization reduced the image), Sent (the normalized raster the model receives, with byte size), estimated provider-billed tokens.\n * Click opens the chat-style lightbox; load failures retry on click; unknown facts leave no row.\n */\nexport function makeImageCard(kit: ViewKit): ImageKit['Card'] {\n const { t, fmt } = kit\n return function ImageCard(props: { attachment: ImageRefLike; load?: ImageLoader }): ReactElement {\n const { attachment, load } = props\n const [src, setSrc] = useState<string | null>(null)\n const [error, setError] = useState(false)\n const [attempt, setAttempt] = useState(0)\n const [preview, setPreview] = useState(false)\n const closePreview = useCallback(() => { setPreview(false) }, [])\n\n useEffect(() => {\n if (load === undefined) return\n let live = true\n setError(false)\n setSrc(null)\n void load(attachment).then((url) => { if (live) setSrc(url) }).catch(() => { if (live) setError(true) })\n return () => { live = false }\n }, [attachment, load, attempt])\n\n const name = attachment.name ?? t('attach.image')\n const dimsOf = (w: number | undefined, h: number | undefined): string | null =>\n w !== undefined && h !== undefined ? `${w}×${h}` : null\n const rows: Array<{ label: string; value: string; tip?: string }> = []\n // No byte size is stored for the raw raster — dims only.\n const raw = attachment.originalDimensions !== undefined\n ? dimsOf(attachment.originalDimensions.width, attachment.originalDimensions.height)\n : null\n if (raw !== null) rows.push({ label: t('attach.raw'), value: raw })\n const sent = dimsOf(attachment.width, attachment.height)\n if (sent !== null) {\n rows.push({\n label: t('attach.sent'),\n value: attachment.bytes !== undefined ? `${sent} · ${fmtBytes(attachment.bytes)}` : sent,\n })\n }\n // Estimated provider-billed tokens (shared/imageTokens — the official docs calculator on the stored dimensions; 117–384 per the vision\n // guide's cap), shown whenever normalized dimensions are known.\n const tokens = attachment.width !== undefined && attachment.height !== undefined\n ? estimateImageTokens(attachment.width, attachment.height)\n : null\n if (tokens !== null) rows.push({ label: t('attach.token'), value: `≈${fmt(tokens)}`, tip: t('attach.tokensTip') })\n\n const activate = (): void => {\n if (error) { setAttempt(a => a + 1); return }\n if (src !== null) setPreview(true)\n }\n return (\n <>\n <button\n type=\"button\"\n className=\"redline-att-item hover:border-(--dsw-alias-label-dimmed) hover:bg-[var(--dsw-alias-interactive-bg-hover,var(--dsw-alias-bg-layer-2))]\"\n title={error ? t('attach.loadFailed') : t('attach.open')}\n onClick={activate}\n >\n <span className=\"redline-att-thumb\">\n {src !== null\n ? <img src={src} alt={name} />\n : (\n <span className={error ? 'redline-att-err' : 'redline-att-ph'}>\n {error ? '⚠' : load === undefined ? '🖼' : t('attach.loading')}\n </span>\n )}\n </span>\n <span className=\"redline-att-meta\">\n <span className=\"redline-att-name\" title={name}>{name}</span>\n {rows.map(r => (\n <span key={r.label} className=\"redline-att-row\" title={r.tip}>\n <b className=\"redline-att-row-label\">{r.label}</b>{r.value}\n </span>\n ))}\n </span>\n </button>\n {preview && src !== null && (\n <AttachmentLightbox\n src={src}\n alt={name}\n labels={{ dialog: t('attach.preview'), close: t('attach.close') }}\n onClose={closePreview}\n />\n )}\n </>\n )\n }\n}\n","/**\n * RichText — the raw/markdown body for the Context browser's detail sections. Markdown renders via the harness's shared MarkdownText (GFM,\n * sanitized, resolved from the platform module table — zero plugin-side markdown dependency); raw is a line-numbered `<pre>`. The Raw/MD\n * switch sits at a section head's right edge (RichSwitch; per-card mode via useRichMode), with the copy-raw control (RichCopy) beside it.\n */\n\nimport { useCallback, useMemo, useState, type ReactElement } from 'react'\nimport { MarkdownText, writeClipboard } from '@deepseek-ai/dsh-client-ui-primitives'\nimport { IconCheck, IconCopy } from '../primitives'\nimport type { ViewKit } from '../viewkit'\n\nexport type RichMode = 'raw' | 'md'\n\n/**\n * The Markdown chrome the harness primitives serve as a required `labels`\n * prop. Typed locally so the plugin typechecks without a primitives\n * dependency.\n */\ninterface MarkdownChrome {\n code: { copyLabel: string; copiedLabel: string }\n footnotes: string\n}\n\nconst Markdown = MarkdownText as (props: { text: string; labels?: MarkdownChrome }) => ReactElement\n\nexport interface RichKit {\n RichText: (props: { text: string; mode: RichMode }) => ReactElement\n RichSwitch: (props: { mode: RichMode; onPick: (mode: RichMode) => void }) => ReactElement\n RichCopy: (props: { text: string }) => ReactElement\n useRichMode: () => [RichMode, (mode: RichMode) => void]\n}\n\nexport function makeRichText(kit: ViewKit): RichKit {\n const { t } = kit\n\n function useRichMode(): [RichMode, (mode: RichMode) => void] {\n // Markdown is the default view: the detail cards hold prose (prompts,\n // descriptions, messages), which reads better rendered; raw stays one\n // click away for exact source inspection.\n const [mode, setMode] = useState<RichMode>('md')\n return [mode, setMode]\n }\n\n function RichSwitch(props: { mode: RichMode; onPick: (mode: RichMode) => void }): ReactElement {\n const seg = (m: RichMode, label: string, tip: string) => (\n <button\n type=\"button\"\n className={'redline-rich-seg-btn' + (props.mode === m ? ' redline-rich-seg-on' : '')}\n title={tip}\n onClick={() => { props.onPick(m) }}\n >{label}</button>\n )\n return (\n <span className=\"redline-rich-seg\">\n {seg('raw', t('rich.raw'), t('rich.toRaw'))}\n {seg('md', t('rich.md'), t('rich.toMd'))}\n </span>\n )\n }\n\n // One block per source line: the number is a counter-fed ::before glued to\n // its own line across soft wraps, and pseudo content never reaches the\n // clipboard, so selecting the body still copies the exact source text.\n function RawText(props: { text: string }): ReactElement {\n const lines = useMemo(() => {\n const parts = props.text.split('\\n')\n return parts.length > 1 && parts[parts.length - 1] === '' ? parts.slice(0, -1) : parts\n }, [props.text])\n return (\n <pre className=\"redline-ts-desc-body redline-ts-lines\">\n {lines.map((line, index) => (\n <span key={index} className=\"redline-ts-line\">{line}</span>\n ))}\n </pre>\n )\n }\n\n // Icon-only copy of the section's exact source (always the raw text, never\n // the rendered markdown). The write and its transient confirmation follow\n // the harness's own code-block control: a rejected host write claims no\n // success, a second click during the window is a no-op, and the glyph\n // resets after a beat.\n function RichCopy(props: { text: string }): ReactElement {\n const [copied, setCopied] = useState(false)\n const onCopy = useCallback(() => {\n if (copied) return\n void writeClipboard(props.text).then((ok) => {\n if (!ok) return\n setCopied(true)\n window.setTimeout(() => { setCopied(false) }, 1200)\n })\n }, [copied, props.text])\n const label = copied ? t('rich.copied') : t('rich.copy')\n return (\n <button\n type=\"button\"\n className={'redline-rich-copy' + (copied ? ' redline-rich-copy-on' : '')}\n title={label}\n aria-label={label}\n onClick={onCopy}\n >\n {copied ? <IconCheck size={13} /> : <IconCopy size={13} />}\n </button>\n )\n }\n\n function RichText(props: { text: string; mode: RichMode }): ReactElement {\n // Reference-stable per locale: a fresh object identity would discard the\n // renderer's cached elements on every render (0.1.2+ faces).\n const mdLabels = useMemo<MarkdownChrome>(() => ({\n code: { copyLabel: t('rich.md.copy'), copiedLabel: t('rich.md.copied') },\n footnotes: t('rich.md.footnotes'),\n }), [t])\n if (props.mode === 'md') {\n return <div className=\"redline-ts-desc-md\"><Markdown text={props.text} labels={mdLabels} /></div>\n }\n return <RawText text={props.text} />\n }\n\n return { RichText, RichSwitch, RichCopy, useRichMode }\n}\n","import { useEffect, useId, useLayoutEffect, useMemo, useRef, useState, type ChangeEvent, type ReactElement, type ReactNode } from 'react'\nimport { UNKNOWN_TOOL_SOURCE, type Category, type ContextHeaders, type ContextTimeline, type HeaderTool, type RequestRecord, type SurfaceNode } from '../../shared/types'\nimport { assemble } from '../assemble'\nimport type { Assembled } from '../assemble'\nimport { CATS, CAT_COLOR, partsOf } from '../categories'\nimport { dnaOf } from '../dna'\nimport type { DnaItem } from '../dna'\nimport type { ContentFetcher, ConversationNodeLike, HeaderFetcher } from '../services'\nimport type { ContextSettings, DefaultToolSort } from '../settings'\nimport type { ViewKit } from '../viewkit'\nimport { blockSummaryOf, callSummaryOf, parseCallArgs } from '../callSummary'\nimport type { DetailState } from '../timelineSource'\nimport { makeDetailNote } from './detailNote'\nimport { makeRedlineActions, makeRedlineEditor, type RedlineSubmit } from './redlineEdit'\nimport { ability, durableTypeOf, type Ability } from '../../shared/redline-ability'\nimport { effectiveIsError, effectiveReasoning, effectiveText, hasLocalEdit, isDeleted } from '../../shared/redline-drafts'\nimport type { RedlineRow } from '../redlineChannel'\nimport type { RedlineDraftController } from '../redlineDrafts'\nimport { makeNodeText } from './nodes'\nimport { turnStepsOf } from './trendChart'\nimport { fetchMissNote, useFetchOnMiss } from './fetchOnMiss'\nimport { imageRefOf, makeImageCard } from './images'\nimport type { ImageKit } from './images'\nimport { makeRichText } from './richText'\nimport type { RichKit } from './richText'\nimport type { StackedBarProps } from './stackedBar'\nimport type { ImageLoader, ImageRefLike } from '../services'\n\nexport interface ContextBrowserProps {\n data: ContextTimeline\n headers: ContextHeaders | null\n /**\n * The conversation-window nodes, resolved by the caller from the `useChat`\n * seat — the browser itself stays seat-free so the hook order lives in\n * exactly one place.\n */\n convNodes?: readonly ConversationNodeLike[]\n /**\n * Targeted full-content fetch for nodes outside the conversation window:\n * one seq-anchored history read per expanded row (absent on older hosts —\n * those keep the preview-plus-hint degradation).\n */\n fetchContent?: ContentFetcher\n /**\n * On-demand CONTENT fetch for the selected step's `redlineHeaders` epoch\n * (system prompt text, tool descriptions/schemas) — one seq-anchored\n * history read per epoch, cached per session (absent on older hosts —\n * those keep the metadata-only degradation).\n */\n fetchHeader?: HeaderFetcher\n /** Preview-seq: hover transiently previews that step; the picker's own selection resumes when the pointer leaves the chart. */\n previewSeq?: number | null\n /** Pin-seq: a pin selects that step; pinSeq null returns the browser to the live surface. */\n pinSeq?: number | null\n /**\n * One-shot reveal request from the step brief: select the step, open the category and the node element, scroll it into view;\n * handed back via `onNodeFocusHandled` so the same row can fire again.\n */\n nodeFocus?: { step: number | 'live'; seq: number; cat: Category } | null\n onNodeFocusHandled?: () => void\n /**\n * The local-edit controller (`redlineDrafts.ts`): a row's `编辑` reads the FULL\n * text through it and its `保存` writes the plugin's own store — never the\n * session (the hard constraint, `docs/11` D15).\n */\n redline: RedlineDraftController\n hoverKey?: string | null\n onHoverKey?: (key: string | null) => void\n /**\n * Reports the open category (null once none opens): the Context tab focuses the trend chart's bars on it.\n * Absent (the /redline modal) — the accordion stays purely internal.\n */\n onOpenCat?: (cat: string | null) => void\n loadImage?: ImageLoader\n /**\n * The timeline source's detail state (split generation): while the first\n * detail read is pending or settled without data, a note strip names the\n * state (the picker/sections otherwise show a misleading empty surface).\n */\n detailState?: DetailState\n onDetailRetry?: () => void\n}\n\ninterface ParamSchema {\n type?: unknown\n description?: unknown\n enum?: unknown\n items?: unknown\n anyOf?: unknown\n oneOf?: unknown\n}\n\nfunction unionTypesOf(p: ParamSchema): string | null {\n const branches: unknown[] = []\n if (Array.isArray(p.anyOf)) branches.push(...p.anyOf as unknown[])\n if (Array.isArray(p.oneOf)) branches.push(...p.oneOf as unknown[])\n if (branches.length === 0) return null\n const parts: string[] = []\n for (const b of branches) {\n if (b !== null && typeof b === 'object') parts.push(typeOf(b))\n }\n return parts.length > 0 ? parts.join(' | ') : null\n}\n\nfunction typeOf(p: ParamSchema): string {\n const u = unionTypesOf(p)\n if (u !== null) return u\n const t = p.type\n if (t === 'array') {\n const items = p.items\n if (items !== null && typeof items === 'object') {\n const inner = typeOf(items)\n return 'array<' + inner + '>'\n }\n return 'array'\n }\n if (typeof t === 'string') {\n if (t === 'object') {\n const props = (p as { properties?: unknown }).properties\n if (props !== null && typeof props === 'object' && Object.keys(props).length > 0) {\n return `object{${Object.keys(props).length}}`\n }\n }\n if (Array.isArray(p.enum) && p.enum.length > 0) {\n return t + ' (enum)'\n }\n return t\n }\n if (Array.isArray(p.enum) && p.enum.length > 0) return '(enum)'\n return 'unknown'\n}\n\n/**\n * Tool schemas nest parameters under `parameters`, `input_schema`, or `inputSchema` (producer-dependent), or bare when `type === 'object'`\n * — `{type:'object', properties}` at the root is itself the parameter object.\n */\nfunction paramsOf(schema: unknown): ParamSchema | null {\n if (schema === null || typeof schema !== 'object') return null\n const s = schema as Record<string, unknown>\n const candidate = (v: unknown): ParamSchema | null =>\n v !== null && typeof v === 'object' ? v : null\n const nested = candidate(s.parameters) ?? candidate(s.input_schema)\n ?? candidate(s.inputSchema)\n if (nested !== null) return nested\n if (s.type === 'object' && s.properties !== undefined && typeof s.properties === 'object') {\n return s\n }\n return null\n}\n\nfunction ParamRow(props: {\n name: string\n schema: ParamSchema\n required: boolean\n}): ReactElement {\n const typeLabel = typeOf(props.schema)\n const desc = props.schema.description\n return (\n <div className=\"redline-ts-param-row\">\n <span className=\"redline-ts-param-name\">{props.name}</span>\n <span className=\"redline-ts-param-type\">{typeLabel}</span>\n <span className={props.required ? 'redline-ts-param-req' : 'redline-ts-param-req-off'}>\n {props.required ? '✓' : '·'}\n </span>\n {typeof desc === 'string' && desc !== ''\n ? <span className=\"redline-ts-param-desc\">{desc}</span>\n : null}\n </div>\n )\n}\n\n/**\n * Section — the ONE detail chrome of the browser: every expanded element is a stack of these (labeled head + body), so the reader scans one\n * repeating anatomy per content kind.\n */\nfunction Section(props: {\n label: string\n labelClass?: string\n /** Fold the head's trailing group onto a second line under width pressure (rich-text heads; the call-name head must stay one-line). */\n foldHead?: boolean\n count?: number\n actions?: ReactNode\n meta?: ReactNode\n children: ReactNode\n}): ReactElement {\n const right = props.actions !== undefined || props.meta !== undefined\n return (\n <div className=\"redline-ts-card\">\n <div className={'redline-ts-card-head' + (props.foldHead === true ? ' redline-ts-card-head-wrap' : '')}>\n {/* The title recovers an ellipsized label: long mono call names truncate under width pressure. */}\n <b className={props.labelClass} title={props.label}>{props.label}</b>\n {right ? <span className=\"redline-ts-card-right\">{props.meta}{props.actions}</span> : null}\n {props.count !== undefined ? <span className=\"redline-ts-card-count\">{props.count}</span> : null}\n </div>\n {props.children}\n </div>\n )\n}\n\nfunction lineCountOf(text: string): number {\n // Count logical lines for LF, CRLF, and lone CR output alike.\n return text.split(/\\r\\n|\\r|\\n/).length\n}\n\nfunction TextSection(props: {\n label: string\n text: string\n rich: RichKit\n lines: (n: number) => string\n}): ReactElement {\n const { rich } = props\n const [mode, setMode] = rich.useRichMode()\n const lineCount = useMemo(() => lineCountOf(props.text), [props.text])\n return (\n <Section\n label={props.label}\n foldHead\n actions={<>\n <rich.RichSwitch mode={mode} onPick={setMode} />\n <rich.RichCopy text={props.text} />\n </>}\n meta={<span className=\"redline-ts-card-meta\">{props.lines(lineCount)}</span>}\n >\n <rich.RichText text={props.text} mode={mode} />\n </Section>\n )\n}\n\nfunction RawSection(props: { label: string; text: string }): ReactElement {\n return (\n <Section label={props.label}>\n <pre className=\"redline-ts-desc-body redline-br-dim\">{props.text}</pre>\n </Section>\n )\n}\n\n/**\n * The search text of one tool's raw schema. The schema is log data this view\n * does not own — a hostile value (cyclic, throwing getters) degrades to no\n * matchable text instead of taking the row, or the browser, down.\n */\nfunction schemaTextOf(schema: unknown): string {\n try {\n return JSON.stringify(schema ?? '')\n } catch {\n return ''\n }\n}\n\n/**\n * The shared row-filter toolbar of a category body: a text input plus an\n * optional trailing control group (the tools' size/name sort). Stays mounted\n * on an empty match so the filter can always be cleared from the UI.\n */\nfunction RowToolbar(props: {\n value: string\n placeholder: string\n tip?: string\n onChange: (v: string) => void\n children?: ReactNode\n}): ReactElement {\n return (\n <div className=\"redline-br-toolctl\">\n <input\n className=\"redline-br-tool-search focus:border-(--dsw-alias-label-dimmed)\"\n value={props.value}\n placeholder={props.placeholder}\n onChange={(ev: ChangeEvent<HTMLInputElement>) => { props.onChange(ev.target.value) }}\n />\n {props.children !== undefined\n ? <span className=\"redline-gran\" role=\"group\" title={props.tip}>{props.children}</span>\n : null}\n </div>\n )\n}\n\n\n\n/**\n * Full tool-row body: description, parsed parameter table (when the schema carries one), raw JSON behind a per-row toggle — the JSON open\n * state is per-row so two expanded tools stay independent.\n */\nfunction ToolSchema(props: {\n description: string | undefined\n schema: unknown\n rich: RichKit\n lines: (n: number) => string\n labels: {\n desc: string\n title: string\n empty: string\n show: string\n hide: string\n }\n}): ReactElement {\n const { rich } = props\n const [jsonOpen, setJsonOpen] = useState(false)\n const params = useMemo(() => paramsOf(props.schema), [props.schema])\n const rows = useMemo<{ name: string; schema: ParamSchema; required: boolean }[]>(() => {\n if (params === null) return []\n const props = (params as { properties?: unknown }).properties\n if (props === null || typeof props !== 'object') return []\n const req = Array.isArray((params as { required?: unknown }).required)\n ? new Set(((params as { required: unknown[] }).required)\n .filter((x): x is string => typeof x === 'string'))\n : new Set<string>()\n const out: { name: string; schema: ParamSchema; required: boolean }[] = []\n for (const k of Object.keys(props)) {\n const v = (props as Record<string, unknown>)[k]\n if (v === null || typeof v !== 'object') continue\n out.push({ name: k, schema: v, required: req.has(k) })\n }\n return out\n }, [params])\n // Pretty-printed only while the row's JSON is open: a tools section lists\n // dozens of schemas, and eager stringification of every collapsed row\n // dominated the section's render cost.\n const schemaJson = useMemo(\n () => jsonOpen ? JSON.stringify(props.schema, null, 2) : '',\n [props.schema, jsonOpen],\n )\n return (\n <>\n {props.description !== undefined ? (\n <TextSection label={props.labels.desc} text={props.description} rich={rich} lines={props.lines} />\n ) : null}\n {params !== null && rows.length > 0 ? (\n <Section label={props.labels.title} count={rows.length}>\n {rows.map(r => <ParamRow key={r.name} name={r.name} schema={r.schema} required={r.required} />)}\n </Section>\n ) : params !== null ? (\n <div className=\"redline-ts-params-empty\">{props.labels.empty}</div>\n ) : null}\n <div className=\"redline-ts-json\">\n <button\n type=\"button\"\n className=\"redline-ts-json-toggle hover:text-(--dsw-alias-label-primary) hover:underline\"\n onClick={() => { setJsonOpen(o => !o) }}\n >{(jsonOpen ? '▾ ' : '▸ ') + (jsonOpen ? props.labels.hide : props.labels.show)}</button>\n {jsonOpen ? <pre className=\"redline-ts-desc-body redline-br-dim\">{schemaJson}</pre> : null}\n </div>\n </>\n )\n}\n\ninterface DetailLabels {\n thinking: string\n answer: string\n content: string\n result: string\n summary: string\n images: string\n other: string\n lines: (n: number) => string\n callState: (err: boolean, exit: number | null) => ReactNode\n}\n\n/**\n * Both block vocabularies normalize here — raw durable blocks (`type`: text/reasoning/tool-call/tool-result/image) and snapshot assistant\n * blocks (`kind`: text/reasoning/tool-call/image, argsRaw). Consecutive images group into one grid; every\n * rich text block carries the Raw/MD switch + line count; nested tool-result blocks flatten into the same flow.\n */\nfunction BlocksBody(props: {\n blocks: readonly unknown[]\n richable: boolean\n textLabel: string\n rich: RichKit\n img: ImageKit\n labels: DetailLabels\n}): ReactElement {\n const { rich, img, labels } = props\n const out: ReactNode[] = []\n let images: ImageRefLike[] = []\n const flushImages = (): void => {\n if (images.length === 0) return\n const group = images\n images = []\n out.push(\n <Section key={'img' + String(out.length)} label={labels.images} count={group.length}>\n <div className=\"redline-att-grid\">\n {group.map((a, i) => <img.Card key={`${a.attachmentId}:${i}`} attachment={a} load={img.load} />)}\n </div>\n </Section>,\n )\n }\n for (const b of props.blocks) {\n const image = imageRefOf(b)\n if (image !== null) { images.push(image); continue }\n flushImages()\n const blk = b !== null && typeof b === 'object'\n ? b as { type?: unknown; kind?: unknown; text?: unknown; name?: unknown; argsRaw?: unknown; arguments?: unknown; content?: unknown }\n : null\n const blockKind = blk !== null\n ? typeof blk.type === 'string' ? blk.type : typeof blk.kind === 'string' ? blk.kind : ''\n : ''\n if ((blockKind === 'text' || blockKind === 'reasoning') && typeof blk?.text === 'string') {\n const label = blockKind === 'reasoning' ? labels.thinking : props.textLabel\n out.push(<TextSection\n key={out.length}\n label={label}\n text={blk.text}\n rich={rich}\n lines={labels.lines}\n />)\n continue\n }\n if (blockKind === 'tool-call') {\n out.push(<ToolCallCard\n key={out.length}\n name={typeof blk?.name === 'string' ? blk.name : '?'}\n argsRaw={blk?.argsRaw ?? blk?.arguments}\n />)\n continue\n }\n if (blockKind === 'tool-result' && Array.isArray(blk?.content)) {\n out.push(<BlocksBody\n key={out.length}\n blocks={blk.content as unknown[]}\n richable={false}\n textLabel={labels.result}\n rich={rich}\n img={img}\n labels={labels}\n />)\n continue\n }\n out.push(<RawSection key={out.length} label={labels.other} text={JSON.stringify(b, null, 2)} />)\n }\n flushImages()\n return <>{out}</>\n}\n\n/**\n * The trailing status markers dsh shell tools append at the END of a result's text while `isError` stays false\n * (the status is result data, per tool-bash's render: \"non-zero exits are reported, not errored\"):\n * - one-shot bash/pwsh: `[exit code: N]` (non-zero only), `[killed by signal: X]`\n * - persistent shells: `[shell killed by signal: X]`, `[shell exited: code N]` — riding LAST, after the\n * `[exit code: N]` of the command whose failure killed the shell, so the command marker is re-checked\n * on the preceding text\n * - job_output: `[status: killed]` / `[status: failed, detail]` — the tool-jobs status line always terminates\n * the read; a killed/failed background job settles with `isError` false, so only the line flags the loss\n * End-anchored like dsh's own parseExitStatus, so marker text quoted inside the output (e.g. a cat'ed log)\n * is not a failure. A clean shell exit (code 0 or code-less) or a live/completed job status is a notice,\n * not a failure.\n * The parsed exit code feeds the FAILED run-state pill.\n */\nfunction tailStatusOf(conv: ConversationNodeLike | undefined): { fail: boolean; exit: number | null } {\n if (conv === undefined || !Array.isArray(conv.content)) return { fail: false, exit: null }\n for (const b of conv.content) {\n const text = (b as { text?: unknown } | null)?.text\n if (typeof text !== 'string') continue\n const tail = text.trimEnd()\n const shell = /\\[(shell killed by signal: [^\\]\\n]+|shell exited(?:: code \\d+)?)\\]$/.exec(tail)\n if (shell !== null) {\n const cmdExit = /\\[exit code:\\s*(\\d+)\\]\\s*$/.exec(tail.slice(0, shell.index))\n if (cmdExit !== null) return { fail: true, exit: Number(cmdExit[1]) }\n const code = /: code (\\d+)$/.exec(shell[1])\n if (code !== null) return { fail: code[1] !== '0', exit: code[1] === '0' ? null : Number(code[1]) }\n return { fail: shell[1].startsWith('shell killed'), exit: null }\n }\n const exit = /\\[exit code:\\s*(\\d+)\\]$/.exec(tail)\n if (exit !== null) return { fail: true, exit: Number(exit[1]) }\n if (/\\[killed by signal: [^\\]\\n]+\\]$/.test(tail)) return { fail: true, exit: null }\n if (/\\[status: (?:killed|failed)(?:, [^\\]\\n]*)?\\]$/.test(tail)) return { fail: true, exit: null }\n }\n return { fail: false, exit: null }\n}\n\n/**\n * A tool result's failure: the fold-stamped `err` or the snapshot's `isError` (infrastructure failures — dsh stamps\n * those) OR a trailing status marker (see tailStatusOf). dsh settles a failing COMMAND as a completed call, so the\n * marker is the only failure signal — mirroring the chat row's terminalFailed. A timeout stays a notice, as in the chat.\n */\nfunction toolErrOf(node: SurfaceNode, conv: ConversationNodeLike | undefined): { err: boolean; exit: number | null } {\n const tail = tailStatusOf(conv)\n const err = node.err === true || conv?.isError === true || tail.fail\n return { err, exit: tail.exit }\n}\n\nfunction ToolCallCard(props: {\n name: string\n argsRaw: unknown\n arrow?: string\n status?: ReactNode\n}): ReactElement {\n const args = useMemo(() => parseCallArgs(props.argsRaw), [props.argsRaw])\n return (\n <Section\n label={(props.arrow ?? '→') + ' ' + props.name}\n labelClass=\"redline-ts-call-name\"\n meta={props.status}\n >\n {args !== null\n ? Object.keys(args).map(k => <CallArgRow key={k} name={k} value={args[k]} />)\n : typeof props.argsRaw === 'string' && props.argsRaw !== ''\n ? <pre className=\"redline-ts-desc-body redline-br-dim\">{props.argsRaw}</pre>\n : null}\n </Section>\n )\n}\n\nfunction CallArgRow(props: { name: string; value: unknown }): ReactElement {\n const v = props.value\n /* v8 ignore next 2 -- the only caller maps Object.keys of a JSON.parse'd\n object, which never holds undefined values; defensive. */\n const text = typeof v === 'string' ? v\n : v === undefined ? ''\n : JSON.stringify(v)\n return (\n <div className=\"redline-ts-arg-row\">\n <span className=\"redline-ts-param-name\">{props.name}</span>\n <span className=\"redline-ts-arg-val\">{text}</span>\n </div>\n )\n}\n\nfunction NodeContent(props: {\n node: SurfaceNode\n conv: ConversationNodeLike | undefined\n hint: ReactNode\n rich: RichKit\n img: ImageKit\n labels: DetailLabels\n}): ReactElement {\n const { node, conv, rich, img, labels } = props\n if (conv === undefined) {\n // The join missed (node outside the loaded window): the 80-char preview\n // still shows as a plain content section, with the fetch-state note below.\n if (node.text === undefined || node.text === '') {\n return <div className=\"redline-br-note\">{props.hint}</div>\n }\n return (\n <>\n <TextSection label={labels.content} text={node.text} rich={rich} lines={labels.lines} />\n <div className=\"redline-br-note\">{props.hint}</div>\n </>\n )\n }\n if (conv.kind === 'assistant' && Array.isArray(conv.blocks)) {\n return <BlocksBody blocks={conv.blocks} richable textLabel={labels.answer} rich={rich} img={img} labels={labels} />\n }\n if (conv.kind === 'tool-result') {\n const { err, exit } = toolErrOf(node, conv)\n return (\n <>\n {conv.call != null\n ? <ToolCallCard\n arrow=\"←\"\n name={conv.call.name}\n argsRaw={conv.call.argsRaw}\n status={labels.callState(err, exit)}\n />\n : null}\n {Array.isArray(conv.content)\n ? <BlocksBody blocks={conv.content} richable={false} textLabel={labels.result} rich={rich} img={img} labels={labels} />\n : null}\n </>\n )\n }\n if (conv.kind === 'compaction') {\n return typeof conv.summary === 'string' && conv.summary !== ''\n ? <TextSection label={labels.summary} text={conv.summary} rich={rich} lines={labels.lines} />\n : <></>\n }\n if (Array.isArray(conv.content)) {\n return <BlocksBody blocks={conv.content} richable textLabel={labels.content} rich={rich} img={img} labels={labels} />\n }\n return <div className=\"redline-br-note\">{props.hint}</div>\n}\n\nfunction byCatOf(asm: Assembled): Partial<Record<Category, SurfaceNode[]>> {\n const m: Partial<Record<Category, SurfaceNode[]>> = {}\n for (const n of asm.nodes) (m[n.cat] ??= []).push(n)\n return m\n}\n\n/**\n * The producer identity a fold-stamped injection node carries\n * (shared/types.ts SurfaceNode.name): '' when absent or drift-typed — the\n * delivered payload is untrusted, so rows re-prove it before rendering.\n */\nfunction nodeNameOf(n: SurfaceNode): string {\n return typeof n.name === 'string' ? n.name : ''\n}\n\nfunction countOf(asm: Assembled, byCat: Partial<Record<Category, SurfaceNode[]>>, c: string): number {\n if (c === 'system') return asm.system !== null ? 1 : 0\n if (c === 'tools') return asm.header !== null ? asm.header.tools.length : 0\n return byCat[c as Category]?.length ?? 0\n}\n\nfunction lastOfTurn(requests: RequestRecord[], turn: number): RequestRecord | null {\n for (let i = requests.length - 1; i >= 0; i--) if ((requests[i].turn ?? 0) === turn) return requests[i]\n return null\n}\n\n/**\n * DNA bands keep at least this share of the occupied region, so a tiny item (a 25-token user message in a 40k\n * context) stays a hoverable/clickable filament instead of a sub-pixel sliver. Tooltips still report true shares.\n */\nconst DNA_MIN_BAND = 0.35\n\nexport function makeContextBrowser(\n kit: ViewKit,\n StackedBar: (props: StackedBarProps) => ReactElement,\n settings: ContextSettings,\n): (props: ContextBrowserProps) => ReactElement {\n const { t, fmt, fmtTime, catLabel } = kit\n const DetailNote = makeDetailNote(kit)\n const nodeText = makeNodeText(kit)\n const rich = makeRichText(kit)\n const ImageCard = makeImageCard(kit)\n const RedlineActions = makeRedlineActions(kit)\n const RedlineEditor = makeRedlineEditor(kit)\n // All rich text sections share the same line-count label; hoist it once so tool\n // descriptions, system text, and message bodies stay in sync.\n const lineLabel = (n: number): string => t(n === 1 ? 'block.line' : 'block.lines', { n })\n\n return function ContextBrowser(props: ContextBrowserProps): ReactElement {\n const { data, headers } = props\n // 'live' = the current surface (the NEXT request's context); number = a retained step's seq.\n // 面板在 `placement:'all'` 下会**同时挂在 tab 与右侧栏**(两个实例)⟹ 写死的 id\n // 会在同一个文档里重复(Code Review P2)。`useId()` 给出每个实例唯一的后缀。\n const uid = useId()\n const [sel, setSel] = useState<'live' | number>('live')\n /**\n * The δ baseline (`docs/03` R1.13, copied verbatim from the reference plugin's\n * 0.60.0 `browser.base.*`): `turn` compares against the PREVIOUS TURN's last\n * step (one stable unit whatever step is shown), `step` against the immediately\n * preceding record. Default `turn`, like the demo.\n */\n const [base, setBase] = useState<'step' | 'turn'>('turn')\n const [openCat, setOpenCat] = useState<string | null>(null)\n const [openElem, setOpenElem] = useState<string | null>(null)\n // The open category's row-filter text plus the tools' row order. The\n // filter is a lens on the OPEN category: opening a different one resets\n // it, while step picks (setOpenCat(null) below) keep it so the same lens\n // compares epochs.\n const [rowQuery, setRowQuery] = useState('')\n // Mount-time default from the plugin settings card; in-toolbar toggling\n // stays mount-local and never writes back.\n const [toolSort, setToolSort] = useState<DefaultToolSort>(() => settings.defaultToolSort())\n // DNA mode: the composition bar redraws as ONE band per context item in prompt order (dna.ts), hovered/clicked per item.\n const [dna, setDna] = useState(false)\n const [dnaKey, setDnaKey] = useState<string | null>(null)\n // Every open-category change (toggle, step pick, pin, brief reveal) reports outward so the Context tab\n // can focus the trend chart on the open category.\n const onOpenCat = props.onOpenCat\n const setCat = (c: string | null): void => {\n setOpenCat(c)\n if (onOpenCat !== undefined) onOpenCat(c)\n }\n\n // Full message content: the conversation-window join first (zero cost),\n // plus nodes fetched on demand for seqs outside the window (node arrays\n // are stable references per snapshot; the map memoizes over them).\n const convNodes = props.convNodes\n const convBySeq = useMemo(() => {\n const m = new Map<number, ConversationNodeLike>()\n for (const n of convNodes ?? []) m.set(n.seq, n)\n return m\n }, [convNodes])\n\n // The open element's surface-node seq ('sys'/'tool:*' keys never join).\n const openSeq = openElem !== null && openElem.startsWith('n')\n ? Number(openElem.slice(1))\n : null\n // Fetch-on-miss: one targeted history read per expanded row whose seq the\n // join missed (fetchOnMiss.tsx; landed values cache by seq — history is\n // immutable). `failed` arms the retry button; `absent` means the page\n // came back without the seq — it is not in the durable log.\n const fetchContent = props.fetchContent\n const miss = useFetchOnMiss(\n openSeq !== null && !convBySeq.has(openSeq) ? openSeq : null,\n fetchContent,\n 'dsh-context-redline: targeted history read failed',\n )\n const bySeq = useMemo(() => {\n if (miss.values.size === 0) return convBySeq\n const m = new Map(convBySeq)\n for (const [seq, n] of miss.values) if (!m.has(seq)) m.set(seq, n)\n return m\n }, [convBySeq, miss.values])\n // Pin linkage: a pinned bar selects its step (same accordion reset as a manual pick); unpin returns to live — a manual pick here is\n // overridden only when a NEW pin lands.\n const pinSeq = props.pinSeq\n useEffect(() => {\n setSel(pinSeq === null || pinSeq === undefined ? 'live' : pinSeq)\n setCat(null)\n setOpenElem(null)\n }, [pinSeq, onOpenCat])\n // Step-brief reveal: select the owning step, open the node's category + element (the pagination effect above already pulls older\n // history for a missing join), then arm a one-shot scroll consumed by the layout effect once the row renders.\n const rootRef = useRef<HTMLDivElement | null>(null)\n const focusScrollRef = useRef(false)\n const nodeFocus = props.nodeFocus\n useEffect(() => {\n if (nodeFocus === null || nodeFocus === undefined) return\n setSel(nodeFocus.step)\n setCat(nodeFocus.cat)\n setOpenElem('n' + String(nodeFocus.seq))\n focusScrollRef.current = true\n if (props.onNodeFocusHandled !== undefined) props.onNodeFocusHandled()\n }, [nodeFocus, props.onNodeFocusHandled, onOpenCat])\n useLayoutEffect(() => {\n if (!focusScrollRef.current) return\n focusScrollRef.current = false\n rootRef.current?.querySelector('.redline-br-elem-on')?.scrollIntoView({ block: 'nearest' })\n })\n // The note an un-joined open row shows, per fetch state (fetchOnMiss.tsx).\n const missNote = fetchMissNote(t, fetchContent, miss.state, miss.retry, 'browser.noContent')\n\n const requests = data.requests\n const stepsOf = useMemo(() => turnStepsOf(requests), [requests])\n const hoverReq = props.previewSeq !== null && props.previewSeq !== undefined\n ? requests.find(r => r.seq === props.previewSeq) ?? null\n : null\n const req = hoverReq ?? (sel === 'live' ? null : requests.find(r => r.seq === sel) ?? null)\n // The actual-prompt figure follows the shown step; the live surface pairs its next-request\n // estimate with the freshest actual the log holds (highest seq — wire order is not trusted).\n const actual = req ?? requests.reduce<RequestRecord | null>((a, r) => (a === null || r.seq > a.seq ? r : a), null)\n // A pinned step trimmed out of retention falls back to live.\n const seq = req !== null ? req.seq : null\n // The browser joins the shared composition hover ONLY while it shows the LIVE step — a pinned/previewed step has a different\n // composition, so its hover must not light the overview (and vice versa); the mirror filter drops the overview's 'free' key, which has\n // no segment in this bar.\n const linked = req === null && props.onHoverKey !== undefined\n const linkKey = linked && props.hoverKey !== null && props.hoverKey !== 'free'\n ? props.hoverKey\n : null\n const view = assemble(data, headers, seq)\n\n // Header/tool epoch CONTENT (tool descriptions/schemas) and the system\n // prompt TEXT: the projections carry metadata only, so the selected step's\n // sources are fetched on demand — one seq-anchored history read per open\n // section. The system prompt rides the timeline's own `systems` nodes (a\n // `system/message` event), the tools the header epoch; both map through\n // the same fetcher. Content caches per seq — history is immutable.\n const fetchHeader = props.fetchHeader\n const headerSeq = view.header !== null ? view.header.seq : null\n const systemSeq = view.system !== null ? view.system.seq : null\n const contentSeq = openCat === 'system' ? systemSeq : openCat === 'tools' ? headerSeq : null\n const epoch = useFetchOnMiss(\n contentSeq,\n fetchHeader,\n 'dsh-context-redline: header content fetch failed',\n )\n const headerContent = epoch.values\n // The note a not-yet-loaded epoch section shows, per fetch state (fetchOnMiss.tsx).\n const headerNote = fetchMissNote(t, fetchHeader, epoch.state, epoch.retry, 'browser.headerMetaOnly')\n\n const breakdown = req !== null ? req : data.current\n const parts = partsOf(breakdown)\n const total = breakdown.total\n // The open category stays lit in the composition bar (category mode: its segment; DNA mode: its bands' group) even\n // without pointer hover — a pointer hover overrides the pin, the pin resumes on leave. Dropped when the shown\n // step's composition holds nothing for the category, so the bar never reads all-dimmed with nothing lit.\n const pinKey = openCat !== null && (breakdown[openCat as Category | 'system' | 'tools'] || 0) > 0 ? openCat : null\n const pick = (v: string) => {\n setSel(v === 'live' ? 'live' : Number(v))\n setCat(null)\n setOpenElem(null)\n }\n\n // The two-level picker's own facts: the turn list, which turn is shown, and that\n // turn's steps. Live (or a seq retained away) falls back to the LAST turn — the\n // live surface belongs to the turn that is still running.\n const turns = useMemo(() => [...new Set(requests.map(r => r.turn ?? 1))].sort((a, b) => a - b), [requests])\n const lastTurn = turns.length > 0 ? turns[turns.length - 1] ?? 1 : 1\n const selTurn = req !== null && req.turn !== undefined && turns.includes(req.turn) ? req.turn : lastTurn\n const requestsOfTurn = useMemo(() => requests.filter(r => (r.turn ?? 1) === selTurn), [requests, selTurn])\n\n // δ baseline, the demo's `deltaRefReq` verbatim (which is the reference plugin's\n // 0.60.0 rule): live surface → 比前步 reads the LAST request, 比前轮 its previous\n // turn's last step; a shown step → 比前轮 its previous turn's last step,\n // 比前步 the immediately preceding record. The first turn has NO baseline, so\n // everything counts as a change there (the upstream `zeroBase` behaviour).\n const lastReq = requests.length > 0 ? requests[requests.length - 1] ?? null : null\n const turnBaseOf = (r: RequestRecord): RequestRecord | null =>\n (r.turn ?? 1) > 1 ? lastOfTurn(requests, (r.turn ?? 1) - 1) : null\n const refReq = req === null\n ? (base === 'step' ? lastReq : lastReq !== null ? turnBaseOf(lastReq) : null)\n : base === 'turn'\n ? turnBaseOf(req)\n : (() => {\n const gi = requests.findIndex(r => r.seq === req.seq)\n return gi <= 0 ? null : requests[gi - 1] ?? null\n })()\n const prevView = refReq !== null ? assemble(data, headers, refReq.seq) : null\n const prevByCat = prevView !== null ? byCatOf(prevView) : null\n\n const byCat = byCatOf(view)\n\n // Per-tool call-hit tally over the shown step's assembled surface: one\n // tool-result node (the fold stamps `tool` on a paired result) is one\n // completed call — the same accounting as the stats' toolCalls. A\n // `skill`-tool load reclassifies its node into the `skill` bucket but\n // keeps the tool stamp, so those calls still count here.\n const toolHits = new Map<string, number>()\n for (const n of view.nodes) {\n if ((n.cat === 'tool' || n.cat === 'skill') && n.tool !== undefined) toolHits.set(n.tool, (toolHits.get(n.tool) ?? 0) + 1)\n }\n const toolHitsOf = (tool: HeaderTool): number => toolHits.get(tool.name) ?? 0\n\n // DNA mode: per-item bands in prompt order (dna.ts). The band label names the item the way its accordion row would\n // (skill name, tool name, injection form, else the category label), with the item's time appended.\n const dnaLabel = (it: DnaItem): string => {\n let base: string\n if (!('node' in it)) {\n base = it.cat === 'system' ? catLabel('system') : it.key.slice('tool:'.length)\n } else {\n const n = it.node\n // 工具名认不出来时**不要渲染「?」**(用户 2026-10-06 对界面上任何 `?` 都反感)——\n // 退回分类名「工具结果」,它至少是句人话。(真机实测:未配对的工具结果会走到这里。)\n base = n.skill !== undefined ? t('node.skillTag', { name: n.skill })\n : n.cat === 'tool' ? (n.tool ?? catLabel(n.cat))\n : n.cat === 'inject' ? t('form.' + (n.form || 'context'))\n : catLabel(n.cat)\n }\n return it.time !== undefined ? base + ' · ' + fmtTime(it.time) : base\n }\n const dnaItems = dna ? dnaOf(view) : null\n const dnaByKey = new Map(dnaItems?.map(it => [it.key, it] as const) ?? [])\n const dnaParts = dnaItems?.map(it => ({\n key: it.key,\n color: CAT_COLOR[it.cat],\n value: it.tokens,\n label: dnaLabel(it),\n group: it.cat,\n })) ?? null\n // A band hover is honored only while its key names a RENDERED band: a push can drop the band under a resting\n // pointer (compaction, tail slide) without a mouseleave, and a dead key exact-matches nothing — the bar would\n // sit all-dimmed with nothing lit (the same invariant the pin's `breakdown` gate keeps).\n const liveDnaKey = dnaKey !== null && dnaByKey.has(dnaKey) ? dnaKey : null\n // A band click opens its category + element row below (the same reveal the step brief uses) and scrolls it into view.\n const pickDna = (key: string): void => {\n const it = dnaByKey.get(key)\n /* v8 ignore next 1 -- the bar only reports keys of the parts it was handed; defensive. */\n if (it === undefined) return\n setCat(it.cat)\n setRowQuery('')\n setOpenElem(key)\n focusScrollRef.current = true\n }\n\n const toolCount = (c: string): number => countOf(view, byCat, c)\n\n // A category holding exactly one item opens that row with the category, so\n // one click lands on the content directly (the lone prompt / tool schema /\n // surface node).\n const singleKeyOf = (c: string): string | null => {\n if (c === 'system') return view.system !== null ? 'sys' : null\n if (c === 'tools') {\n const tools = view.header?.tools\n return tools !== undefined && tools.length === 1 ? 'tool:' + tools[0].name : null\n }\n /* v8 ignore next 1 -- reached only through toggleCat's openable guard\n (count > 0 ⟺ byCat[c] exists); the fallback is defensive. */\n const nodes = byCat[c as Category] ?? []\n return nodes.length === 1 ? 'n' + String(nodes[0].seq) : null\n }\n\n const toggleCat = (c: string) => {\n // Empty cats stay shut — except system/tools with no header epoch, which open to explain the degradation note.\n const openable = toolCount(c) > 0\n || ((c === 'system' || c === 'tools') && view.header === null)\n if (!openable) return\n if (openCat === c) {\n setCat(null)\n setOpenElem(null)\n return\n }\n setCat(c)\n // A different category opens unfiltered — the lens belongs to the open one.\n setRowQuery('')\n setOpenElem(singleKeyOf(c))\n }\n const toggleElem = (key: string) => { setOpenElem(openElem === key ? null : key) }\n\n /**\n * Expandable element row; `err` rows carry the red run-state dot right after the chevron (the chat's failed-tool marker) so a failed\n * result scans while collapsed.\n */\n const elemRow = (\n key: string, tag: ReactNode | null, preview: string,\n tokens: number, time: number | undefined, body: ReactNode,\n err = false, trailing: ReactNode = null, actions: ReactNode = null, editor: ReactNode = null,\n deleted = false,\n ) => {\n const open = openElem === key\n return (\n <div key={key} className={'redline-br-elem' + (open ? ' redline-br-elem-on' : '') + (deleted ? ' redline-br-elem-deleted' : '')}>\n <button type=\"button\" className=\"redline-br-elem-row hover:bg-(--dsw-alias-interactive-bg-hover)\" onClick={() => { toggleElem(key) }}>\n <span className={'redline-br-chev' + (open ? ' redline-br-chev-on' : '')} />\n {err ? <span className=\"redline-br-err-dot\" title={t('node.failed')} /> : null}\n {tag !== null ? <span className=\"redline-br-tag\">{tag}</span> : null}\n <span className=\"redline-br-preview\">{preview}</span>\n {trailing !== null ? trailing : null}\n {time !== undefined ? <span className=\"redline-br-time\">{fmtTime(time)}</span> : null}\n <span className=\"redline-br-tokens\">{'≈' + fmt(tokens)}</span>\n </button>\n {open ? <div className=\"redline-br-content\">{body}</div> : null}\n {actions}\n {editor}\n </div>\n )\n }\n\n // ── local editing (docs/03 §2–§3) ─────────────────────────────────────────\n // The advanced switch only gates the `编辑` button on tool results (R2.5); it\n // changes no data.\n const [advanced, setAdvanced] = useState(false)\n const [editingSeq, setEditingSeq] = useState<number | null>(null)\n const [editorRow, setEditorRow] = useState<RedlineRow | null>(null)\n const [editorError, setEditorError] = useState<string | null>(null)\n // Mirrors `editingSeq` for the async loads: a `node.read` that lands after the\n // user left that row must not reopen it.\n const editingSeqRef = useRef<number | null>(null)\n\n /**\n * The row's action set. The BUCKET decides it — provably action-invariant\n * across the bucket's durable types (`tests/edit/ability-buckets.spec.ts`);\n * the exact type is only needed for the editor's fields, and that comes from\n * `node.read` when the editor opens.\n */\n const abilityOfNode = (n: SurfaceNode): Ability => ability({\n seq: n.seq,\n type: durableTypeOf(n.cat),\n cat: n.cat,\n // `gone` marks an archived (superseded) node — no longer a surface node.\n shadowed: n.gone !== undefined,\n isReplacement: n.gone === undefined,\n compacted: false,\n })\n\n /** Open the editor on one row: read the FULL text first (`docs/01` F35). */\n const openEditor = (seq: number): void => {\n editingSeqRef.current = seq\n setEditingSeq(seq)\n setEditorRow(null)\n setEditorError(null)\n void (async () => {\n const result = await props.redline.loadRow(seq)\n setEditorRow((current) => {\n // Ignore a late answer for a row the user already left.\n if (editingSeqRef.current !== seq) return current\n return result.ok ? result.value : null\n })\n if (!result.ok) setEditorError(result.code)\n })()\n }\n\n const closeEditor = (): void => {\n editingSeqRef.current = null\n setEditingSeq(null)\n setEditorRow(null)\n setEditorError(null)\n props.redline.clearError()\n }\n\n /** The action bar for one row (`docs/03` R2.1–R2.5). */\n const rowActionsFor = (n: SurfaceNode): ReactNode => {\n const a = abilityOfNode(n)\n return (\n <RedlineActions\n seq={n.seq}\n ability={a}\n hasLocalEdit={hasLocalEdit(props.redline.table, n.seq)}\n deleted={isDeleted(props.redline.table, n.seq)}\n advanced={advanced}\n busy={props.redline.busySeq === n.seq}\n onEdit={() => { openEditor(n.seq) }}\n errorCode={props.redline.rowError?.seq === n.seq ? props.redline.rowError.code : null}\n onExclude={() => { void props.redline.exclude(n.seq, true) }}\n onUnexclude={() => { void props.redline.exclude(n.seq, false) }}\n onDrop={() => {\n void (async () => {\n const ok = await props.redline.drop(n.seq)\n // `docs/11` D17: discarding collapses the editor on that row.\n if (ok && editingSeqRef.current === n.seq) closeEditor()\n })()\n }}\n />\n )\n }\n\n /** The inline editor for one row, when it is the open one. */\n const rowEditorFor = (n: SurfaceNode): ReactNode => {\n if (editingSeq !== n.seq) return null\n if (editorRow === null) {\n return (\n <div className=\"redline-editor\">\n <div className=\"redline-editor-label\">\n {editorError === null ? t('detail.loading') : t(`redline.err.${editorError.replace('redline/', '')}`)}\n </div>\n </div>\n )\n }\n const row = { seq: n.seq, text: editorRow.text, reasoning: editorRow.reasoning, isError: editorRow.isError }\n const initial: RedlineSubmit = {\n // The version in effect — after a save this is YOUR saved text (`docs/11` D16).\n text: effectiveText(row, props.redline.table),\n reasoning: effectiveReasoning(row, props.redline.table),\n isError: effectiveIsError(row, props.redline.table),\n }\n return (\n <RedlineEditor\n seq={n.seq}\n type={editorRow.type}\n initial={initial}\n busy={props.redline.busySeq === n.seq}\n blocked={!props.redline.turn.known ? 'not-live' : props.redline.turn.open ? 'turn-open' : null}\n errorCode={props.redline.rowError?.seq === n.seq ? props.redline.rowError.code : editorError}\n onSubmit={(edit: RedlineSubmit) => {\n void (async () => {\n const ok = await props.redline.save(n.seq, edit)\n if (ok) closeEditor()\n })()\n }}\n onCancel={closeEditor}\n />\n )\n }\n\n const catBody = (c: string): ReactNode => {\n if (c === 'system') {\n // No prompt in force at this step. The category only opens without one\n // when there is no header epoch at all (the openable guard above), so\n // the note names the missing PROJECTION — no headers service versus\n // headers that carried no epoch yet.\n const sys = view.system\n if (sys === null) {\n return <div className=\"redline-br-note\">{t(headers === null ? 'browser.noHeader' : 'browser.noEpoch')}</div>\n }\n const content = headerContent.get(sys.seq)\n // Metadata-only until the prompt's event resolves (fetched when the\n // section opens; the note names the state).\n if (content === undefined) return <div className=\"redline-br-note\">{headerNote}</div>\n if (content.system === undefined) return <div className=\"redline-br-note\">{t('browser.noSystem')}</div>\n return elemRow('sys', null, content.system.replace(/\\s+/g, ' ').trim().slice(0, 80), breakdown.system, undefined,\n <TextSection label={catLabel('system')} text={content.system} rich={rich} lines={lineLabel} />)\n }\n if (c === 'tools') {\n if (view.header === null) return <div className=\"redline-br-note\">{t(headers === null ? 'browser.noHeader' : 'browser.noEpoch')}</div>\n const labels = {\n desc: t('tool.desc'),\n title: t('tool.params'),\n empty: t('tool.paramsEmpty'),\n show: t('tool.jsonToggle'),\n hide: t('tool.jsonHide'),\n }\n // The epoch's fetched content, joined onto the metadata rows by tool\n // name (the open row's body renders description/params/JSON from it).\n const content = headerContent.get(view.header.seq)\n const contentByName = new Map(content?.tools.map(t => [t.name, t]) ?? [])\n // The text filter scans everything the rows can say: the name, the\n // producer description, the plugin chip, and the raw parameter JSON —\n // the latter two only once the epoch's content is loaded.\n const q = rowQuery.trim().toLowerCase()\n const shown = view.header.tools\n .filter((tool: HeaderTool) => {\n if (q === '') return true\n if (tool.name.toLowerCase().includes(q)) return true\n if ((tool.plugin ?? '').toLowerCase().includes(q)) return true\n const row = contentByName.get(tool.name)\n if (row === undefined) return false\n return (row.description ?? '').toLowerCase().includes(q)\n || schemaTextOf(row.schema).toLowerCase().includes(q)\n })\n // Size order mirrors the overview's Top chips — the producer's header\n // order is not meaningful; count order ranks by the call-hit tally of\n // the shown step's surface (ties break by name); name order gives\n // lookup instead of ranking (names are unique keys, so a two-way\n // comparison orders them fully).\n .sort((a, b) => toolSort === 'count'\n ? (toolHitsOf(b) - toolHitsOf(a) || (a.name < b.name ? -1 : 1))\n : toolSort === 'size'\n ? b.tokens - a.tokens\n : (a.name < b.name ? -1 : 1))\n // The toolbar stays mounted on an empty match, or the filter could\n // never be cleared from the UI.\n const toolctl = (\n <RowToolbar value={rowQuery} placeholder={t('tool.search')} tip={t('tool.sortTip')} onChange={setRowQuery}>\n {(['size', 'count', 'name'] as const).map(k => (\n <button\n key={k}\n type=\"button\"\n className={'redline-gran-btn' + (toolSort === k ? ' redline-gran-on' : '')}\n onClick={() => { setToolSort(k) }}\n >\n {t('tool.sort.' + k)}\n </button>\n ))}\n </RowToolbar>\n )\n if (shown.length === 0) {\n return (\n <div>\n {toolctl}\n <div className=\"redline-br-note\">{t('tool.noMatch')}</div>\n </div>\n )\n }\n // The open row's body: the fetched content's description, parameter\n // table, and raw JSON — or the epoch's fetch-state note.\n const toolBody = (tool: HeaderTool): ReactNode => {\n if (content === undefined) return <div className=\"redline-br-note\">{headerNote}</div>\n const row = contentByName.get(tool.name)\n return row === undefined\n ? <div className=\"redline-br-note\">{t('browser.notInLog')}</div>\n : <ToolSchema description={row.description} schema={row.schema} rich={rich} lines={lineLabel} labels={labels} />\n }\n return (\n <div>\n {toolctl}\n {shown.map((tool: HeaderTool) => {\n // The registering plugin (best-effort host attribution — see\n // toolSources.ts) trails the tool name as a standalone chip, so it\n // needs no extra frame around it. A tool whose provider predates\n // the attribution hook arrives with the UNKNOWN_TOOL_SOURCE\n // sentinel and renders a localized \"unknown plugin\" tag whose\n // tooltip explains why no provider is shown. The hit tally always\n // trails — a zero names a definition the shown step never called.\n const trailing = (\n <>\n {tool.plugin !== undefined\n ? <span className=\"redline-br-tag redline-br-tool-plugin\" title={tool.plugin === UNKNOWN_TOOL_SOURCE ? t('tool.unknownTitle') : t('tool.plugin')}>\n {tool.plugin === UNKNOWN_TOOL_SOURCE ? t('tool.unknown') : tool.plugin}\n </span>\n : null}\n <span className=\"redline-br-hits\" title={t('tool.hitsTip')}>{'×' + fmt(toolHitsOf(tool))}</span>\n </>\n )\n return elemRow('tool:' + tool.name, null, tool.name, tool.tokens, undefined,\n toolBody(tool),\n false, trailing)\n })}\n </div>\n )\n }\n // List surface nodes newest first (the live surface's reading order).\n /* v8 ignore next 1 -- the body renders only when the category is open,\n which requires count > 0 ⟺ byCat[c] exists; defensive. */\n const nodes = (byCat[c as Category] ?? []).slice().reverse()\n // Derive each row's display facts first so the text filter scans exactly\n // what the rows show (tag + preview) at zero extra derivation cost; the\n // survivors render unchanged. Identity-labeled injection rows keep their\n // folded content out of the preview, so the filter scans `text` too.\n const rows = nodes.map((n) => {\n const conv = bySeq.get(n.seq)\n // A `skill`-tool load reclassifies into the `skill` bucket (issue #66)\n // but stays a tool result — its failure marking follows the same rule.\n const rowErr = (n.cat === 'tool' || n.cat === 'skill') && toolErrOf(n, conv).err\n // Tag carries the compact fact (tool name, injection form) — one shared subtle chip style; the preview line carries the text — each\n // fact shown once.\n let tag: string | null = null\n let preview = nodeText(n)\n const id = nodeNameOf(n)\n if (n.cat === 'tool') {\n // ⚠️ 工具名认不出来时**不挂标签**(原来是 `'?'`):那行本来就写着「工具结果」当预览,\n // 再挂一个 `?` 只是噪音(用户 2026-10-06 对界面上任何 `?` 都反感)。`null` = 这一格不渲染。\n tag = n.tool ?? null\n preview = callSummaryOf(conv) ?? t('node.toolResult')\n } else if (n.cat === 'skill') {\n // Skill content (issue #66): a load/invocation names itself, and a\n // text-less row (an unjoined load) falls back to the call summary;\n // the catalog digest carries no name — its form label tags it and\n // the stamped source identity (e.g. `skill-catalog`) previews.\n tag = n.skill !== undefined ? t('node.skillTag', { name: n.skill }) : t('form.' + (n.form || 'context'))\n preview = (n.skill === undefined && id !== '' ? id : null)\n ?? (n.text !== undefined && n.text !== '' ? n.text : null)\n ?? callSummaryOf(conv) ?? preview\n } else if (n.cat === 'assistant' && Array.isArray(n.calls) && n.calls.length > 0) {\n // Call targets join as a breadcrumb (`bash › write`); the preview carries the reply text, else the first call's own summary for a\n // text-less turn.\n tag = n.calls.join(' › ')\n preview = (n.text !== undefined && n.text !== '' ? n.text : null)\n ?? blockSummaryOf(conv)\n ?? t('node.empty')\n } else if (n.cat === 'assistant' && (n.text === undefined || n.text === '')) {\n // A text-less turn can still preview a self-summarizing call from the join even when the node carries no call list.\n preview = blockSummaryOf(conv) ?? preview\n } else if (n.cat === 'user') {\n // User messages with image uploads gain an Image chip on the collapsed row (detected via the conversation join, like the expanded\n // body); expanded, the grid shows anyway.\n const imgCount = conv !== undefined && Array.isArray(conv.content)\n ? conv.content.filter(b => imageRefOf(b) !== null).length\n : 0\n if (imgCount > 0 && openElem !== `n${n.seq}`) {\n tag = t('attach.image') + (imgCount > 1 ? ' ×' + String(imgCount) : '')\n }\n } else if (n.cat === 'inject') {\n tag = t('form.' + (n.form || 'context'))\n if (id !== '') {\n // The source identity the events card names (plugin id, reconciled\n // instruction files, durable kind) — more scannable than the raw\n // content, which stays one expand away.\n preview = id\n } else if (n.text !== undefined && n.text !== '') {\n preview = n.form === 'snapshot' ? t('node.snapshot') + n.text : n.text\n }\n }\n return { n, conv, rowErr, tag, preview }\n })\n const q = rowQuery.trim().toLowerCase()\n const shown = q === '' ? rows : rows.filter(r =>\n (r.tag ?? '').toLowerCase().includes(q) || r.preview.toLowerCase().includes(q)\n || (typeof r.n.text === 'string' && r.n.text.toLowerCase().includes(q)))\n // The toolbar stays mounted on an empty match, or the filter could\n // never be cleared from the UI.\n const rowctl = <RowToolbar value={rowQuery} placeholder={t('browser.search.' + c)} onChange={setRowQuery} />\n if (shown.length === 0) {\n return <div>{rowctl}<div className=\"redline-br-note\">{t('browser.rowNoMatch')}</div></div>\n }\n return (\n <div>\n {rowctl}\n {shown.map(({ n, conv, rowErr, tag, preview }) => elemRow(`n${n.seq}`, tag, preview, n.tokens, n.time,\n <NodeContent\n node={n}\n conv={conv}\n rich={rich}\n img={{ Card: ImageCard, load: props.loadImage }}\n // Localized section titles handed in by the parent so the body stays a pure function of props.\n labels={{\n thinking: t('block.thinking'),\n answer: t('block.answer'),\n content: t('block.content'),\n result: t('block.result'),\n summary: t('block.summary'),\n images: t('attach.images'),\n other: t('attach.other'),\n lines: lineLabel,\n callState: (err: boolean, exit: number | null) => (\n <span className={'redline-ts-call-state ' + (err ? 'redline-ts-call-err' : 'redline-ts-call-ok')}>\n <i />\n {err\n ? t('call.fail') + (exit !== null ? ' · ' + t('call.exit', { n: exit }) : '')\n : t('call.ok')}\n </span>\n ),\n }}\n // Only the open row's body renders, so the miss note is exactly THIS join's fetch state; a joined-but-empty row keeps the\n // static hint.\n hint={conv === undefined ? missNote : t('browser.noContent')}\n />,\n rowErr, null, rowActionsFor(n), rowEditorFor(n), isDeleted(props.redline.table, n.seq)))}\n </div>\n )\n }\n\n return (\n <div className=\"redline-card\" ref={rootRef}>\n <div className=\"redline-card-title\">\n <span className=\"redline-card-title-text\">{t('browser.title')}</span>\n {/* 高级编辑开关(docs/03 R2.5):默认关,只影响工具结果的「编辑」是否可见,不改任何数据 */}\n <button\n type=\"button\"\n className={'redline-gran-btn' + (advanced ? ' redline-gran-on' : '')}\n aria-pressed={advanced}\n title={t('redline.advancedToggle.tip')}\n onClick={() => { setAdvanced(v => !v) }}\n >{t('redline.advancedToggle')}</button>\n <span className=\"redline-gran redline-br-dna-ctl\" role=\"group\" title={t('browser.dnaTip')}>\n <button\n type=\"button\"\n className={'redline-gran-btn' + (dna ? ' redline-gran-on' : '')}\n onClick={() => { setDna(on => !on) }}\n >\n {t('browser.dna')}\n </button>\n </span>\n {/* 对比基线:两个按钮逐字照参考插件 0.60.0 的 `lc-gran` + `browser.base.tip`(`docs/03` R1.13) */}\n <span className=\"redline-gran\" id={`redline-base-${uid}`} data-redline-base-group role=\"group\" title={t('browser.base.tip')}>\n <button\n type=\"button\"\n className={'redline-gran-btn' + (base === 'step' ? ' redline-gran-on' : '')}\n aria-pressed={base === 'step'}\n onClick={() => { setBase('step') }}\n >{t('browser.base.step')}</button>\n <button\n type=\"button\"\n className={'redline-gran-btn' + (base === 'turn' ? ' redline-gran-on' : '')}\n aria-pressed={base === 'turn'}\n onClick={() => { setBase('turn') }}\n >{t('browser.base.turn')}</button>\n </span>\n {/* 两级选择器(轮 → 步):列表规模从 N(整段历史)降到 T + S。\n `docs/05` §1.5 的量级保护(实测单下拉 4,000 项 75.0ms vs 两级 9.2ms),\n 这是本插件**有意偏离上游**的那一处。 */}\n <select\n className=\"redline-br-pick\"\n id={`redline-turn-${uid}`}\n data-redline-turn-pick\n value={String(selTurn)}\n onChange={(e) => {\n const turn = Number(e.target.value)\n const last = lastOfTurn(requests, turn)\n if (last !== null) pick(String(last.seq))\n }}\n >\n {turns.map(turn => (\n <option\n key={turn}\n value={String(turn)}\n data-turn={String(turn)}\n data-last-seq={String(lastOfTurn(requests, turn)?.seq ?? '')}\n >\n {t('browser.turnPick', { t: turn, n: stepsOf(turn) })}\n </option>\n ))}\n </select>\n <select\n className=\"redline-br-pick\"\n id={`redline-step-${uid}`}\n data-redline-step-pick\n value={seq === null ? 'live' : String(seq)}\n onChange={(e) => { pick(e.target.value) }}\n >\n {requestsOfTurn.map(r => (\n <option key={r.seq} value={String(r.seq)} data-redline-seq={String(r.seq)}>\n {t('browser.stepPick', { s: r.step ?? 0, n: stepsOf(r.turn) }) + ' · ' + fmtTime(r.time)}\n </option>\n ))}\n {/* 「当前(下一次请求)」只出现在**末轮**(`docs/03` R1.13) */}\n {selTurn === lastTurn ? <option value=\"live\">{t('browser.live')}</option> : null}\n </select>\n </div>\n\n <div className=\"redline-br-meta\">\n <b>{req !== null\n ? t('detail.step', { t: req.turn ?? 0, s: req.step ?? 0, n: stepsOf(req.turn) })\n : t('browser.liveNow')}</b>\n {req !== null ? <span>{fmtTime(req.time)}</span> : null}\n <span className=\"redline-est\">{t('detail.estTotal', { n: fmt(total) })}</span>\n {actual !== null && actual.prompt !== undefined\n ? <span>{t('detail.actual', { n: fmt(actual.prompt) })}</span>\n : null}\n </div>\n\n <div className={'redline-br-bar' + (dna ? ' redline-br-bar-dna' : '')}>\n <StackedBar\n parts={dnaParts ?? parts}\n height={10}\n // Highlight precedence: pointer hover (local in DNA mode, the shared link otherwise) over the open-category pin.\n // The mirrored link (see `linked` above) works while the browser shows the live surface; it is ONE-WAY in DNA\n // mode — an incoming category key lights that category's BANDS (the parts' `group`), while band hovers stay\n // on the bar and never report upward (the overview keeps showing the live category composition). Tip stays\n // off in category mode: a cross-card hover must not float a second tooltip over a bar the pointer does not\n // rest on — and the group-keyed pin never exact-matches a DNA band, so the pinned highlight floats no tip.\n hoverKey={dna ? liveDnaKey ?? linkKey ?? pinKey : linkKey ?? pinKey}\n onHoverKey={dna ? setDnaKey : linked ? props.onHoverKey : undefined}\n tip={dna}\n onPickKey={dna ? pickDna : undefined}\n minBand={dna ? DNA_MIN_BAND : undefined}\n />\n </div>\n\n {view.missingLive > 0\n ? <div className=\"redline-br-note\">{t('browser.missingLive', { n: view.missingLive })}</div>\n : null}\n {view.approximate\n ? <div className=\"redline-br-note\">{t('browser.approx')}</div>\n : null}\n {props.detailState === 'loading'\n ? <DetailNote state=\"loading\" className=\"redline-br-note\" />\n : null}\n {props.detailState === 'failed' && props.onDetailRetry !== undefined\n ? <DetailNote state=\"failed\" onRetry={props.onDetailRetry} className=\"redline-br-note\" />\n : null}\n\n <div className=\"redline-br-cats\">\n {CATS.map((c) => {\n const count = toolCount(c.key)\n const v = breakdown[c.key] || 0\n const prevCount = prevView !== null && prevByCat !== null ? countOf(prevView, prevByCat, c.key) : null\n const countDelta = prevCount !== null ? count - prevCount : null\n const prevTokens = refReq !== null ? (refReq[c.key] || 0) : null\n const tokenDelta = prevTokens !== null ? v - prevTokens : null\n const openable = count > 0\n || ((c.key === 'system' || c.key === 'tools') && view.header === null)\n const open = openCat === c.key && openable\n return (\n <div key={c.key} className={'redline-br-cat' + (openable ? '' : ' redline-br-cat-empty')}>\n <button\n type=\"button\"\n className={'redline-br-cat-row hover:bg-(--dsw-alias-interactive-bg-hover)'\n + (open ? ' redline-br-cat-open' : '')\n + (linked && props.hoverKey === c.key ? ' redline-br-cat-on' : '')}\n /* v8 ignore start -- the handlers exist only when linked,\n and linked already requires onHoverKey defined (above). */\n onMouseEnter={linked ? () => { if (props.onHoverKey !== undefined) props.onHoverKey(c.key) } : undefined}\n onMouseLeave={linked ? () => { if (props.onHoverKey !== undefined) props.onHoverKey(null) } : undefined}\n /* v8 ignore stop */\n onClick={() => { toggleCat(c.key) }}\n >\n <span className={'redline-br-chev' + (open ? ' redline-br-chev-on' : '')} />\n <i style={{ background: c.color }} />\n <span className=\"redline-br-cat-label\">{catLabel(c.key)}</span>\n {/* Count + Δ pill sit as one attached group (tight inner gap),\n the group absorbs the row's free space so tokens/percent\n stay right-aligned. */}\n <span className=\"redline-br-count-grp\">\n <span className=\"redline-br-cat-count\">{t('browser.items', { n: count })}</span>\n {countDelta !== null && countDelta !== 0 ? (\n <span className={'redline-br-delta redline-br-delta-' + (countDelta > 0 ? 'up' : 'down')}>\n {`${countDelta > 0 ? '+' : ''}${countDelta}`}\n </span>\n ) : null}\n </span>\n <span className=\"redline-br-tokens-grp\">\n {tokenDelta !== null && tokenDelta !== 0 ? (\n <span className={'redline-br-tdelta redline-br-tdelta-' + (tokenDelta > 0 ? 'up' : 'down')}>\n {(tokenDelta > 0 ? '+' : '') + fmt(tokenDelta)}\n </span>\n ) : null}\n <span className=\"redline-br-tokens\">{'≈' + fmt(v)}</span>\n </span>\n <span className=\"redline-br-pct\">{total > 0 ? `${Math.round(v / total * 100)}%` : ''}</span>\n </button>\n {open ? <div className=\"redline-br-body\">{catBody(c.key)}</div> : null}\n </div>\n )\n })}\n </div>\n </div>\n )\n }\n}\n","/**\n * Composition bar + legend; the shared hover-link tooltip is bespoke — no shared primitive reproduces the cross-segment/legend linkage —\n * styled through the shared `--dsw-alias-*` tokens. On mount the segments and the free track grow open\n * left to right (stackedBar.css, staggered by the capped per-piece `--redline-i` slots below, so a long DNA\n * band list settles fast); the reserve band stays unanimated.\n */\n\nimport { useState, type CSSProperties, type ReactElement } from 'react'\nimport type { PartsPart } from '../categories'\nimport type { ViewKit } from '../viewkit'\n\n/**\n * Mirror of dsh-compaction-basic's default `thresholdRatio` (0.8): it compacts at step boundaries once `floor(contextWindow × ratio)` is\n * reached; DSH does not publish the configured ratio to plugins/clients, so the reserve band mirrors the default — deployments tuning\n * `thresholdRatio`/`modelPolicies` should adjust it to match.\n */\nexport const AUTO_COMPACT_RATIO = 0.8\n\n/**\n * Entrance stagger cap: the browser's DNA bands can list dozens of items, so the grow-in cascade stops\n * widening after this many slots and late bands simply join within the cap (stackedBar.css delays by\n * `--redline-i`); the composition bar's few category segments never reach it.\n */\nconst STAGGER_CAP = 8\n\nexport interface StackedBarProps {\n parts: PartsPart[]\n max?: number\n height?: number\n hoverKey?: string | null\n onHoverKey?: (key: string | null) => void\n /** Segment click (the browser's DNA mode opens the band's accordion row): segments gain the pick cursor and report their key. */\n onPickKey?: (key: string) => void\n /**\n * Minimum width each segment keeps, as a share of the OCCUPIED region (the browser's DNA bands: a tiny item must\n * stay a hoverable filament instead of rendering sub-pixel). Bands below the floor pin to it and the rest rescale\n * proportionally; the floor caps at the equal split (100/N), where the strip degrades to uniform bands. Tooltips\n * keep reporting TRUE shares — only widths are floored.\n */\n minBand?: number\n /**\n * Render the hover tooltip (default true); a bar that only MIRRORS another card's hover turns it off, so the tooltip floats only over the\n * surface the pointer actually rests on.\n */\n tip?: boolean\n /**\n * Optional auto-compaction reserve band: the rightmost (1−ratio) of the window, striped 'headroom' — the region the session normally\n * avoids filling because automatic compaction triggers past the threshold; rendered only when `max` (the window) is positive.\n */\n reserve?: { ratio: number; label: string }\n}\n\nexport function makeStackedBar(kit: ViewKit): (props: StackedBarProps) => ReactElement {\n const { t, fmt, catLabel } = kit\n return function StackedBar(props: StackedBarProps): ReactElement {\n // The reserve-hover flag lives here so the single tooltip slot serves both the segments and the band.\n const [reserveOn, setReserveOn] = useState(false)\n let total = 0\n for (const p of props.parts) total += p.value\n const scale = props.max !== undefined && props.max > total ? props.max : total\n const free = props.max !== undefined && props.max > total ? props.max - total : 0\n // Segment WIDTHS lay out against the full window (scale), but legend/tooltip percentages are shares of the OCCUPIED total — on hover a\n // solid box frames the occupied region (width = used/scale) to make that reference frame visible; only when a free track exists.\n const usedPct = scale > 0 ? total / scale * 100 : 0\n const hovering = props.hoverKey !== null && props.hoverKey !== undefined\n const showBox = free > 0 && hovering\n const pickKey = props.onPickKey\n const minBand = props.minBand !== undefined && props.minBand > 0 ? props.minBand : 0\n\n // The renderable segments (zero-value parts skip) with their BAR-unit widths, floored at `minBand` in occupied\n // units: pinned bands take the floor, the rest rescale into the remaining room so the strip still sums to the\n // occupied region exactly. At least one band always stays unpinned (the shares sum to 100, the floor ≤ 100/N),\n // so restRaw never divides by zero.\n const visible = total > 0 ? props.parts.filter(p => p.value > 0) : []\n const widths = ((): number[] => {\n if (minBand === 0 || visible.length < 2) return visible.map(p => p.value / scale * 100)\n const shares = visible.map(p => p.value / total * 100)\n const floor = Math.min(minBand, 100 / visible.length)\n let pinned = 0\n let pinnedRaw = 0\n for (const s of shares) {\n if (s < floor) { pinned += 1; pinnedRaw += s }\n }\n if (pinned === 0) return visible.map(p => p.value / scale * 100)\n const restRoom = 100 - pinned * floor\n const restRaw = 100 - pinnedRaw\n return shares.map(s => (s < floor ? floor : s * restRoom / restRaw) * total / scale)\n })()\n\n // The band lays out in WINDOW units (`ratio × max` → `max`) scaled onto whatever total the bar spans, so it stays the same physical\n // slice with or without a free track (once used exceeds the window, the stripes sit over the outermost segments).\n const reserve = props.reserve !== undefined && props.max !== undefined && props.max > 0\n ? { ...props.reserve, max: props.max }\n : null\n const reserveLeft = reserve !== null ? Math.round(reserve.max * reserve.ratio / scale * 1000) / 10 : 0\n const reserveWidth = reserve !== null ? Math.round((1 - reserve.ratio) * reserve.max / scale * 1000) / 10 : 0\n\n // The tooltip is DERIVED from the shared hover key, so a segment and its legend chip light the same segment with the same tooltip\n // (centered by %, no measuring); the wrapper keeps it outside the clipped stack; the reserve band overrides the slot with its own\n // label.\n let tip: { text: string; leftPct: number } | null = null\n if (reserveOn && reserve !== null) {\n tip = {\n text: reserve.label,\n leftPct: Math.max(12, Math.min(reserveLeft + reserveWidth / 2, 88)),\n }\n } else if (props.hoverKey !== null && props.hoverKey !== undefined) {\n if (props.hoverKey === 'free' && free > 0) {\n const pct = scale > 0 ? free / scale * 100 : 0\n tip = {\n text: `${t('overview.free')} ${fmt(free)} (${Math.round(pct)}%)`,\n leftPct: Math.max(12, Math.min((total / scale * 100) + pct / 2, 88)),\n }\n } else {\n let acc = 0\n // Counts come from the part's heuristic `raw` figure (the ring\n // panel's rows); widths ride the floored `widths` so the tooltip centers on the RENDERED segment.\n let rawTotal = 0\n for (const p of props.parts) rawTotal += p.raw ?? p.value\n for (let i = 0; i < visible.length; i++) {\n const p = visible[i]\n if (p.key === props.hoverKey) {\n const count = p.raw ?? p.value\n tip = {\n text: `${p.label ?? catLabel(p.key)} ≈${fmt(count)} (${rawTotal > 0 ? Math.round(count / rawTotal * 100) : 0}%) `\n + t('overview.ofUsed'),\n leftPct: Math.max(12, Math.min(acc + widths[i] / 2, 88)),\n }\n break\n }\n acc += widths[i]\n }\n }\n }\n\n return (\n <div className=\"redline-stacked-wrap\">\n <div\n className={'redline-stacked' + (hovering ? ' redline-stacked-dim' : '')}\n style={{ height: `${props.height || 14}px` }}\n onMouseLeave={() => {\n if (props.onHoverKey !== undefined) props.onHoverKey(null)\n setReserveOn(false)\n }}\n >\n {visible.map((p, i) => {\n // Exact-key hover lights the one segment; a part's `group` answers a mirrored CATEGORY hover (DNA bands light per category).\n const on = props.hoverKey !== undefined\n && (props.hoverKey === p.key || (p.group !== undefined && props.hoverKey === p.group))\n return (\n <div\n key={p.key}\n className={'redline-stacked-seg animate-redline-stacked-in motion-reduce:animate-none' + (on ? ' redline-stacked-seg-on' : '') + (pickKey !== undefined ? ' redline-stacked-seg-pick' : '')}\n // Grow-in stagger slot (the animate-redline-stacked-in token's delay): each segment scaleX-opens\n // from the left edge in turn, capped so a long DNA band list settles fast.\n style={{ width: `${widths[i]}%`, backgroundColor: p.color, '--redline-i': Math.min(i, STAGGER_CAP) } as CSSProperties}\n onMouseEnter={() => { if (props.onHoverKey !== undefined) props.onHoverKey(p.key) }}\n onClick={pickKey !== undefined ? () => { pickKey(p.key) } : undefined}\n />\n )\n })}\n {free > 0 ? (\n <div\n key=\"free\"\n className={'redline-stacked-free animate-redline-stacked-in motion-reduce:animate-none' + (props.hoverKey === 'free' ? ' redline-stacked-free-on' : '')}\n // The free track opens right after the last occupied segment (past the stagger cap it joins\n // one slot after the capped segments).\n style={{ width: `${free / scale * 100}%`, '--redline-i': Math.min(visible.length, STAGGER_CAP + 1) } as CSSProperties}\n onMouseEnter={() => { if (props.onHoverKey !== undefined) props.onHoverKey('free') }}\n />\n ) : null}\n {/* Painted above the track/segments so the stripes overlay them; owns the pointer so its own explanation shows — and clears the\n segment hover link while exploring it.\n */}\n {reserve !== null ? (\n <div\n className=\"redline-reserve\"\n style={{ left: `${reserveLeft}%`, width: `${reserveWidth}%` }}\n onMouseEnter={() => {\n setReserveOn(true)\n if (props.onHoverKey !== undefined) props.onHoverKey(null)\n }}\n onMouseLeave={() => { setReserveOn(false) }}\n />\n ) : null}\n {/* The occupied-region frame: painted last so its border stays above the segments; always mounted\n (`.redline-occupied-box-on` toggles opacity) so it fades out on leave instead of unmounting instantly.\n */}\n <div\n className={'redline-occupied-box' + (showBox ? ' redline-occupied-box-on' : '')}\n style={{ width: `${usedPct}%` }}\n />\n </div>\n {/* The hover tooltip is always mounted too (opacity via `.redline-bar-tip-on`) so it fades in and out; hidden it holds\n no pointer events and no width of its own.\n */}\n {props.tip !== false\n ? (\n <div\n className={'redline-tip redline-bar-tip' + (tip ? ' redline-bar-tip-on' : '')}\n style={{ left: tip ? `${tip.leftPct}%` : '50%' }}\n >{tip ? tip.text : ''}</div>\n )\n : null}\n </div>\n )\n }\n}\n\nexport function makeLegend(kit: ViewKit): (props: {\n parts: PartsPart[]\n hoverKey?: string | null\n onHoverKey?: (key: string | null) => void\n}) => ReactElement {\n const { t, fmt, catLabel } = kit\n return function Legend(props: {\n parts: PartsPart[]\n hoverKey?: string | null\n onHoverKey?: (key: string | null) => void\n }): ReactElement {\n let total = 0\n for (const p of props.parts) total += p.raw ?? p.value\n return (\n <div className=\"redline-legend\">\n {props.parts.map((p) => {\n const count = p.raw ?? p.value\n const on = props.hoverKey !== undefined && props.hoverKey === p.key\n return (\n <span\n key={p.key}\n className={'redline-chip' + (on ? ' redline-chip-on' : '')}\n title={t('overview.ofUsed')}\n onMouseEnter={() => { if (props.onHoverKey !== undefined) props.onHoverKey(p.key) }}\n onMouseLeave={() => { if (props.onHoverKey !== undefined) props.onHoverKey(null) }}\n >\n <i style={{ background: p.color }} />\n <span className=\"redline-chip-label\">{catLabel(p.key)}</span>\n <span className=\"redline-chip-nums\">\n {'≈' + fmt(count)}\n {total > 0 ? <em>{`${Math.round(count / total * 100)}%`}</em> : null}\n </span>\n </span>\n )\n })}\n </div>\n )\n }\n}\n","import { type ReactElement } from 'react'\nimport type { PartsPart } from '../categories'\nimport type { Headline } from '../headline'\nimport type { ViewKit } from '../viewkit'\nimport { AUTO_COMPACT_RATIO } from './stackedBar'\nimport type { StackedBarProps } from './stackedBar'\n\ntype LegendFn = (props: {\n parts: PartsPart[]\n hoverKey?: string | null\n onHoverKey?: (key: string | null) => void\n}) => ReactElement\n\nexport interface CurrentCompositionProps {\n head: Headline\n subtitle?: string\n hoverKey?: string | null\n onHoverKey?: (key: string | null) => void\n}\n\nexport function makeCurrentComposition(\n kit: ViewKit,\n StackedBar: (props: StackedBarProps) => ReactElement,\n Legend: LegendFn,\n): (props: CurrentCompositionProps) => ReactElement {\n const { t, fmt } = kit\n return function CurrentComposition(props: CurrentCompositionProps): ReactElement {\n const head = props.head\n const reserve = head.window != null && head.window > 0\n ? { ratio: AUTO_COMPACT_RATIO, label: t('overview.compactReserve', { pct: Math.round(AUTO_COMPACT_RATIO * 100) }) }\n : undefined\n return (\n <div className=\"redline-card\" data-redline-current>\n <div className=\"redline-card-title\">\n <span className=\"redline-card-title-text\">{t('overview.title')}</span>\n {props.subtitle !== undefined && props.subtitle !== ''\n ? <span className=\"redline-card-sub\">{props.subtitle}</span>\n : null}\n </div>\n <div className=\"redline-overview-num\">\n <b>{fmt(head.tokens)}</b>\n <span>\n {head.window\n ? ' / ' + fmt(head.window) + ' tokens'\n : ' ' + t('overview.estimate')}\n </span>\n {head.pct !== null ? (\n <span className=\"redline-overview-pct\">\n <b>{`${head.pct}%`}</b>\n {t('overview.used')}\n </span>\n ) : null}\n </div>\n <StackedBar\n parts={head.parts}\n height={16}\n max={head.window}\n hoverKey={props.hoverKey}\n onHoverKey={props.onHoverKey}\n reserve={reserve}\n />\n <Legend parts={head.parts} hoverKey={props.hoverKey} onHoverKey={props.onHoverKey} />\n </div>\n )\n }\n}\n","/**\n * ErrorBoundary — the tab's no-white-screen guarantee: a render error in the subtree degrades to a styled error card instead of\n * propagating\n * into the harness's slot renderer and unmounting the conversation view. Class component: the only React primitive that can catch a\n * subtree's render errors (no hook-based boundary in React 18); Retry resets the boundary and a healthy value resumes.\n */\n\nimport { Component, type ComponentType, type ReactNode } from 'react'\nimport type { Translate } from '../i18n'\n\nexport function makeErrorBoundary(t: Translate): ComponentType<{ children?: ReactNode }> {\n return class ErrorBoundary extends Component<{ children?: ReactNode }, { error: Error | null }> {\n constructor(props: { children?: ReactNode }) {\n super(props)\n this.state = { error: null }\n }\n\n static getDerivedStateFromError(error: unknown): { error: Error | null } {\n return { error: error instanceof Error ? error : new Error(String(error)) }\n }\n\n render(): ReactNode {\n const error = this.state.error\n if (error === null) return this.props.children\n return (\n <div className=\"redline-root\">\n <div className=\"redline-empty redline-error\">\n <span>{t('error')}</span>\n <code className=\"redline-error-msg\">{error.message}</code>\n <button\n type=\"button\"\n className=\"redline-error-retry hover:border-(--dsw-alias-label-primary)\"\n onClick={() => { this.setState({ error: null }) }}\n >{t('error.retry')}</button>\n </div>\n </div>\n )\n }\n }\n}\n","/**\n * The shared Escape-to-close contract of the plugin's overlays (the /redline\n * modal and the baseline-gate dialog): capture-phase keydown on window, so\n * the composer's own key handling never swallows Escape first; on close, focus\n * returns to the element that held it when the overlay opened (skipped when\n * that element left the document).\n */\n\nimport { useEffect, useRef } from 'react'\n\n/**\n * Close on Escape while `active`; restores the pre-open focus on cleanup.\n * `onClose` rides a latest-ref so the subscription lives on the `active`\n * transitions alone: every caller passes a render-fresh closure, and a\n * per-render resubscribe would rerun the cleanup's focus restore — yanking\n * focus out of the overlay's own inputs on every keystroke.\n */\nexport function useEscapeClose(active: boolean, onClose: () => void): void {\n const close = useRef(onClose)\n close.current = onClose\n useEffect(() => {\n if (!active) return undefined\n const previous = document.activeElement instanceof HTMLElement ? document.activeElement : null\n const onKey = (ev: KeyboardEvent): void => {\n if (ev.key !== 'Escape') return\n ev.preventDefault()\n ev.stopPropagation()\n close.current()\n }\n window.addEventListener('keydown', onKey, true)\n return () => {\n window.removeEventListener('keydown', onKey, true)\n if (previous !== null && document.contains(previous)) previous.focus()\n }\n }, [active])\n}\n","/**\n * The panel's transport to OUR route (`REDLINE_CHANNEL_ROUTE`) — the only way the\n * browser half talks to the editing layer.\n *\n * Two contracts this file exists to keep:\n *\n * 1. **One path, shared with the host.** The URL is `REDLINE_CHANNEL_ROUTE` from\n * `src/shared/redline-route.ts`, never a literal. A hand-written path on either\n * side is how \"前缀/形状不成对\" turns into a silent 404 (`docs/01` F1,\n * `docs/05` A12) — the `channel` lane asserts the host REGISTERS that constant,\n * and `tests/client-logic/redline-channel.spec.ts` asserts the client POSTS it.\n *\n * 2. **Failures are values, never exceptions.** Every outcome is either\n * `{ok:true, value}` or `{ok:false, code, message}` with a STABLE code, because\n * the editor must show the reason while keeping the user's input\n * (`docs/03` R3.5). An exception escaping here would blank the row instead.\n *\n * Reads the FULL text: `node.read` answers the durable event's complete body, not\n * the list preview (`docs/01` F35) — the editor prefills from exactly this.\n */\n\nimport { REDLINE_ERROR } from '../shared/redline-errors'\nimport { REDLINE_CHANNEL_ROUTE, type RedlineEnvelope } from '../shared/redline-route'\nimport type { ChildCapacity } from '../shared/redline-capacity'\nimport type { OriginRecord } from '../shared/redline-origins'\nimport type { DraftTable } from '../shared/redline-drafts'\nimport type { TurnState } from '../shared/redline-turn'\n\n/** One row's complete content, as `node.read` answers it. */\nexport interface RedlineRow {\n readonly seq: number\n /** The durable event type (`docs/03` R3.2 keys the editor fields off it). */\n readonly type: string\n readonly text: string\n readonly reasoning: string\n readonly isError: boolean\n}\n\n/** The edit the editor submits. `reasoning`/`isError` are only meaningful per type. */\nexport interface DraftEdit {\n readonly text: string\n readonly reasoning: string\n readonly isError: boolean\n}\n\n/** The transport's outcome: a value, or a stable code the UI turns into a sentence. */\nexport type RedlineResult<T> =\n | { readonly ok: true; readonly value: T }\n | { readonly ok: false; readonly code: string; readonly message: string }\n\n/** Narrow an untrusted body to our envelope. */\nfunction envelopeOf(body: unknown): RedlineEnvelope<unknown> | null {\n if (body === null || typeof body !== 'object' || Array.isArray(body)) return null\n const bag = body as { ok?: unknown; value?: unknown; error?: unknown }\n if (bag.ok === true) return { ok: true, value: bag.value }\n if (bag.ok === false) {\n const error = bag.error\n if (error === null || typeof error !== 'object') return null\n const { code, message } = error as { code?: unknown; message?: unknown }\n if (typeof code !== 'string') return null\n return { ok: false, error: { code, message: typeof message === 'string' ? message : code } }\n }\n return null\n}\n\n/** POST one op and normalize every possible outcome into a {@link RedlineResult}. */\nasync function call<T>(body: Record<string, unknown>): Promise<RedlineResult<T>> {\n let response: Response\n try {\n response = await fetch(REDLINE_CHANNEL_ROUTE, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n // The route is `no-store` on the host side too; a cached refusal would be a\n // lie the user cannot get rid of by saving again.\n cache: 'no-store',\n body: JSON.stringify(body),\n })\n } catch (error) {\n return { ok: false, code: REDLINE_ERROR.transport, message: error instanceof Error ? error.message : String(error) }\n }\n let parsed: unknown\n try {\n parsed = await response.json()\n } catch (error) {\n return {\n ok: false,\n code: REDLINE_ERROR.transport,\n message: `${REDLINE_ERROR.transport}: HTTP ${String(response.status)} ${error instanceof Error ? error.message : ''}`.trim(),\n }\n }\n const envelope = envelopeOf(parsed)\n if (envelope === null) {\n return { ok: false, code: REDLINE_ERROR.transport, message: `${REDLINE_ERROR.transport}: HTTP ${String(response.status)}` }\n }\n if (!envelope.ok) return { ok: false, code: envelope.error.code, message: envelope.error.message }\n return { ok: true, value: envelope.value as T }\n}\n\n/** One row's COMPLETE content — the editor's only prefill source. */\nexport async function readRow(sessionId: string, seq: number): Promise<RedlineResult<RedlineRow>> {\n return await call<RedlineRow>({ op: 'node.read', sessionId, seq })\n}\n\n/**\n * Whether this session can be edited right now (`docs/03` R4.3). Asked BEFORE the\n * editor opens, because the demo blocks editing entirely mid-turn / on a session\n * this process does not host — a save button that fails after the click is a\n * worse experience than one that is disabled with the reason beside it.\n */\nexport async function readTurnState(sessionId: string): Promise<RedlineResult<TurnState>> {\n return await call<TurnState>({ op: 'turnState', sessionId })\n}\n\n/** Every local edit of this session (the row markers and the prefill read this). */\nexport async function listDrafts(sessionId: string): Promise<RedlineResult<DraftTable>> {\n return await call<DraftTable>({ op: 'draft.list', sessionId })\n}\n\n/**\n * Save one row's local edit. Refusals are expected values: `redline/no-change`\n * (identical to the version in effect) and `redline/empty-content`.\n */\nexport async function saveDraft(sessionId: string, seq: number, edit: DraftEdit): Promise<RedlineResult<DraftTable>> {\n return await call<DraftTable>({ op: 'draft.update', sessionId, seq, edit })\n}\n\n/** Forget one row's local edit (the row goes back to its original). */\n/**\n * 标为「不要」(`excluded: true`)或取消标记(`false`)。**只写插件本地** ——\n * 当前会话一个字都不写;开启子会话时由首条任务逐字声明这几条作废(`docs/11` D65)。\n */\nexport async function excludeDraft(sessionId: string, seq: number, excluded: boolean): Promise<RedlineResult<DraftTable>> {\n return await call<DraftTable>({ op: 'draft.exclude', sessionId, seq, excluded })\n}\n\nexport async function dropDraft(sessionId: string, seq: number): Promise<RedlineResult<DraftTable>> {\n return await call<DraftTable>({ op: 'draft.drop', sessionId, seq })\n}\n\n/** 确认框五项 + 组装好的首条任务(开子会话**之前**能问的全部事实;只读)。 */\nexport interface ChildPlan {\n /** 恰好五项:从哪儿开始 / 会带上的改动 / 第一句话由人写 / 会带什么不带什么 / 取消。 */\n items: readonly { label: string; text: string }[]\n /** 会逐字带过去的本地改动(按 seq)。 */\n carriedSeqs: readonly number[]\n /** 已删除、不会写进普通新会话的 seq。 */\n excludedSeqs: readonly number[]\n /** Opaque confirmation token: exact operation + draft + source + manifest versions. */\n draftRevision: string\n /** 组装好的最终发送全文;被拒绝时为 `null`。用户可在确认框直接编辑。 */\n prompt: string | null\n /** 默认冻结配置;修改只作用于即将创建的普通新会话。 */\n config?: { agentPreset: string; provider: string; model: string; reasoningEffort?: string }\n /** 首条任务的读数(M2-20):UTF-8 字节 / 行 / 带了几条改动;被拒绝时为 `null`。 */\n metrics: { bytes: number; lines: number; edits: number } | null\n /** 被拒绝时给一句人话(例如\"第一句话必须你自己写\")。 */\n refusal: { code: string; message: string } | null\n}\n\n/** 开子会话之前问事实(只读,绝不写任何东西)。 */\nexport async function planChild(sessionId: string, humanTask: string): Promise<RedlineResult<ChildPlan>> {\n return await call<ChildPlan>({ op: 'carrier.plan', sessionId, humanTask })\n}\n\nexport interface CarrierModelOption {\n readonly provider: string\n readonly providerName: string\n readonly model: string\n readonly modelName: string\n readonly efforts: readonly { readonly id: string; readonly name: string }[]\n readonly defaultEffort?: string\n}\n\nexport async function readCarrierModels(): Promise<RedlineResult<{ models: readonly CarrierModelOption[] }>> {\n return await call<{ models: readonly CarrierModelOption[] }>({ op: 'carrier.models' })\n}\n\n/** 开子会话成功后的回执。 */\nexport interface ChildStarted {\n /**\n * 走的是哪条路:`'official-member'`(官方团队成员)/ `'bare-child'`(裸子会话)。\n * 界面必须如实标出来 —— 两者的可管理性完全不同(官方那份能在官方团队视图里看到)。\n */\n via?: string\n label: string\n prompt: string\n carriedSeqs: readonly number[]\n /** 平台给的子会话回执(`childId` / `messageId`)。 */\n started: unknown\n}\n\n/**\n * **开子会话** —— 全插件唯一的写入点。\n *\n * 只在人**明确点了确认**之后调用;`humanTask` 是人写的第一句话(空着会被宿主拒绝)。\n * 拒绝一律以稳定的 code + 一句人话回来(transport 从不抛),界面照它显示就行。\n */\nexport async function startChild(\n sessionId: string,\n humanTask: string,\n confirmationToken: string,\n finalText?: string,\n config?: { provider: string; model: string; reasoningEffort?: string },\n): Promise<RedlineResult<ChildStarted>> {\n return await call<ChildStarted>({ op: 'carrier.start', sessionId, humanTask, confirmationToken, finalText, config })\n}\n\nexport interface CarrierListRow {\n readonly id: string\n readonly label: string\n readonly mode: 'continuable'\n readonly createdAt: number\n readonly via: 'ordinary-session'\n}\n\nexport async function readCarriers(sessionId: string): Promise<RedlineResult<{ rows: readonly CarrierListRow[] }>> {\n return await call<{ rows: readonly CarrierListRow[] }>({ op: 'carrier.list', sessionId })\n}\n\n/** `child.origins` 的回答:`records: null` = 我们那本台账**读不出来**(界面必须说\"来源未知\")。 */\nexport interface OriginAnswer {\n readonly records: readonly OriginRecord[] | null\n readonly error?: string\n}\n\n/**\n * M5-12 的来源台账:问宿主\"这些子会话里,哪些**是在这个面板里**开的\"。\n * 只读;`records: null` 表示**读不出来**(与\"空台账\"是两件事,界面话术不同)。\n */\nexport async function readOrigins(sessionId: string): Promise<RedlineResult<OriginAnswer>> {\n return await call<OriginAnswer>({ op: 'child.origins', sessionId })\n}\n\n/**\n * M5-13 的分母:问宿主\"这台机器允许几个团队成员\"。\n * 只读;形状不可信 ⟹ 调用方要用 `capacityOf()` re-prove 一遍再进渲染。\n */\nexport async function readCapacity(): Promise<RedlineResult<ChildCapacity>> {\n return await call<ChildCapacity>({ op: 'child.capacity' })\n}\n","/**\n * The panel's local-edit state: one loaded `DraftTable` per session, plus the\n * save/discard calls the rows make.\n *\n * Three rules this hook exists to keep, all from the hard constraint of\n * `docs/11` D15 (\"every save is temporary\"):\n *\n * 1. **A save only ever writes our own store.** Nothing here touches the session\n * log; the only call it makes is `draft.update` on our channel, and the host\n * answers with the new table — which this hook then adopts as the truth. No\n * optimistic merge of our own construction: a refusal (`redline/no-change`,\n * `redline/empty-content`) must leave the stored table exactly as it was.\n * 2. **A refusal is shown, never swallowed** (`docs/03` R3.5): the failing row\n * keeps the user's input and displays the reason, mapped from the STABLE code\n * by the component (`redline.err.<code>`).\n * 3. **One request at a time per row**, so a double click cannot interleave two\n * saves of the same row.\n */\n\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react'\nimport type { DraftTable } from '../shared/redline-drafts'\nimport { dropDraft, excludeDraft, listDrafts, readRow, readTurnState, saveDraft, type DraftEdit, type RedlineResult, type RedlineRow } from './redlineChannel'\nimport type { TurnState } from '../shared/redline-turn'\n\n/** The per-row failure the editor shows, keyed by the row it belongs to. */\nexport interface RedlineRowError {\n readonly seq: number\n /** A stable code (`redline/*`), or `redline/transport`. */\n readonly code: string\n}\n\nexport interface RedlineDraftController {\n /** The local edits in effect (the row markers and the prefill read this). */\n readonly table: DraftTable\n /**\n * Whether editing is allowed at all right now. `known:false` = view only;\n * `open:true` = the turn has not closed. The panel disables `保存` on both and\n * says why (`docs/03` R4.3) — before any round trip, like the demo does.\n */\n readonly turn: TurnState\n /** False until the first load settles — the panel shows nothing edited before that. */\n readonly ready: boolean\n /** The row currently saving/dropping, so its buttons can disable. */\n readonly busySeq: number | null\n /** The last refusal/failure for the editor to display. */\n readonly rowError: RedlineRowError | null\n /** One row's COMPLETE content — what the editor prefills from (`docs/01` F35). */\n loadRow(seq: number): Promise<RedlineResult<RedlineRow>>\n /** Resolves true only when the save was accepted (so the editor knows to close). */\n save(seq: number, edit: DraftEdit): Promise<boolean>\n /** Resolves true only when the discard was accepted. */\n drop(seq: number): Promise<boolean>\n /** 标为「不要」/ 取消标记(`docs/11` D65)。解析为 true 表示宿主接受了。 */\n exclude(seq: number, on: boolean): Promise<boolean>\n /** Forget a row's error (the next open starts clean). */\n clearError(): void\n}\n\n/**\n * Load and mutate one session's local edits.\n *\n * @param sessionId - the session whose rows are shown; `undefined` keeps it idle\n * (a slot can mount before the framework hands a session over).\n */\nexport function useRedlineDrafts(sessionId: string | undefined): RedlineDraftController {\n const [table, setTable] = useState<DraftTable>({})\n const [ready, setReady] = useState(false)\n const [busySeq, setBusySeq] = useState<number | null>(null)\n const [rowError, setRowError] = useState<RedlineRowError | null>(null)\n const [turn, setTurn] = useState<TurnState>({ known: true, open: false })\n // A late answer from a previous session must not overwrite the current one.\n const generation = useRef(0)\n\n useEffect(() => {\n generation.current += 1\n const mine = generation.current\n setTable({})\n setReady(false)\n setRowError(null)\n setTurn({ known: true, open: false })\n if (sessionId === undefined || sessionId === '') return\n void (async () => {\n const [drafts, state] = await Promise.all([listDrafts(sessionId), readTurnState(sessionId)])\n if (generation.current !== mine) return\n if (drafts.ok) setTable(drafts.value)\n else setRowError({ seq: -1, code: drafts.code })\n // A failed state read must not silently look \"editable\": `known:false` is the\n // honest answer (view only), and the panel says so.\n setTurn(state.ok ? state.value : { known: false, open: false })\n setReady(true)\n })()\n }, [sessionId])\n\n const save = useCallback(async (seq: number, edit: DraftEdit): Promise<boolean> => {\n if (sessionId === undefined || sessionId === '') return false\n setBusySeq(seq)\n setRowError(null)\n const result = await saveDraft(sessionId, seq, edit)\n setBusySeq(current => (current === seq ? null : current))\n if (!result.ok) { setRowError({ seq, code: result.code }); return false }\n setTable(result.value)\n return true\n }, [sessionId])\n\n const exclude = useCallback(async (seq: number, on: boolean): Promise<boolean> => {\n if (sessionId === undefined || sessionId === '') return false\n setBusySeq(seq)\n setRowError(null)\n const result = await excludeDraft(sessionId, seq, on)\n setBusySeq(current => (current === seq ? null : current))\n if (!result.ok) { setRowError({ seq, code: result.code }); return false }\n setTable(result.value)\n return true\n }, [sessionId])\n\n const drop = useCallback(async (seq: number): Promise<boolean> => {\n if (sessionId === undefined || sessionId === '') return false\n setBusySeq(seq)\n setRowError(null)\n const result = await dropDraft(sessionId, seq)\n setBusySeq(current => (current === seq ? null : current))\n if (!result.ok) { setRowError({ seq, code: result.code }); return false }\n setTable(result.value)\n return true\n }, [sessionId])\n\n const loadRow = useCallback(async (seq: number): Promise<RedlineResult<RedlineRow>> => {\n if (sessionId === undefined || sessionId === '') {\n return { ok: false, code: 'redline/not-live', message: 'no session' }\n }\n return await readRow(sessionId, seq)\n }, [sessionId])\n\n const clearError = useCallback(() => { setRowError(null) }, [])\n\n return useMemo(\n () => ({ table, turn, ready, busySeq, rowError, loadRow, save, drop, exclude, clearError }),\n [table, turn, ready, busySeq, rowError, loadRow, save, drop, exclude, clearError],\n )\n}\n","/**\n * The /redline command's centered dialog — the same data as the Context tab (the pushed `redlineTimeline` projection) distilled to the\n * current-composition overview and the shared Context browser; rendered from the `conversation.input.overlay` slot and opened/closed\n * through the per-session modal store, so the trigger flips it and no message ever enters session history.\n */\n\nimport { createElement as h, useCallback, useLayoutEffect, useMemo, useRef, useState, type ReactElement } from 'react'\nimport { measureDock } from '../dockMeasure'\nimport { headlineOf } from '../headline'\nimport { modalStoreOf, takePendingConsume } from '../modalStore'\nimport type { ClientCtx, SessionStandardProps, SessionsFace } from '../services'\nimport type { ContextSettings } from '../settings'\nimport { contextBreakdownOf, contextPressureOf, conversationNodesOf, headersOf, imageLoaderOf, projectionOf } from '../services'\nimport { makeContentFetcher, makeHeaderFetcher, useHistoryFace } from '../historyPage'\nimport { useTimelineSource } from '../timelineSource'\nimport type { ViewKit } from '../viewkit'\nimport { makeContextBrowser } from './browser'\nimport { makeCurrentComposition } from './currentComposition'\nimport { makeErrorBoundary } from './errorBoundary'\nimport { useEscapeClose } from './escapeClose'\nimport { makeLegend, makeStackedBar } from './stackedBar'\nimport { useRedlineDrafts } from '../redlineDrafts'\n\nexport interface ContextModalProps extends SessionStandardProps {\n /** Bound selector hook over the per-session open flag (hooks compartment). */\n useContextModal?: (sel: (open: boolean) => boolean) => boolean\n}\n\nexport function makeContextModal(\n ctx: ClientCtx,\n kit: ViewKit,\n settings: ContextSettings,\n): (props: ContextModalProps) => ReactElement | null {\n const { t } = kit\n const StackedBar = makeStackedBar(kit)\n const Legend = makeLegend(kit)\n const CurrentComposition = makeCurrentComposition(kit, StackedBar, Legend)\n const ContextBrowser = makeContextBrowser(kit, StackedBar, settings)\n const ErrorBoundary = makeErrorBoundary(t)\n\n function ContextModalBody(props: ContextModalProps): ReactElement | null {\n const sessionId = typeof props.sessionId === 'string' ? props.sessionId : ''\n const redline = useRedlineDrafts(sessionId !== '' ? sessionId : undefined)\n const open = typeof props.useContextModal === 'function' ? props.useContextModal(s => s) : false\n // The timeline source (timelineSource.ts) — shares the tab's per-session\n // detail store, so an open tab's detail serves the modal with no refetch.\n const source = useTimelineSource(ctx, props)\n const data = source.data\n const pressure = projectionOf(props, 'contextPressure', contextPressureOf)\n const breakdown = projectionOf(props, 'contextBreakdown', contextBreakdownOf)\n const headers = projectionOf(props, 'redlineHeaders', headersOf)\n // Conversation-window join for the browser (the seat is a real hook —\n // read unconditionally here, before the closed early return, so the hook\n // order stays stable across open/close).\n const convNodes = conversationNodesOf(props)\n const [hoverCat, setHoverCat] = useState<string | null>(null)\n // Dock the mask beside the shell sidebar: 0 until the frame measure lands\n // (the layout effect below resolves it before first paint).\n const [dockLeft, setDockLeft] = useState(0)\n const backdropRef = useRef<HTMLDivElement | null>(null)\n // Session-authorized durable-image loader for the browser's attachment cards, resolved through the harness `uiConversation` service\n // (`imageUrl`); absent service/session degrades the cards to metadata-only, never an error. Same parity as the Context tab.\n const loadImage = useMemo(\n () => imageLoaderOf(ctx, sessionId !== '' ? sessionId : undefined),\n [ctx, sessionId],\n )\n\n // The gateway page face, as a React seat: the first render can race the declared inject (a watch rebuild remounts this overlay before\n // the fiber re-fires), and both fetchers below must rebuild — not stick to the static degradation — when the face lands or is revoked.\n const historyFace = useHistoryFace()\n\n // Same targeted content fetch the Context tab wires (one seq-anchored history read per expanded row), plus the on-demand header\n // epoch content read for the browser's system/tools sections.\n const fetchContent = useMemo(\n () => (sessionId !== '' && historyFace !== undefined ? makeContentFetcher(sessionId) : undefined),\n [sessionId, historyFace],\n )\n const fetchHeader = useMemo(\n () => (sessionId !== '' && historyFace !== undefined ? makeHeaderFetcher(sessionId) : undefined),\n [sessionId, historyFace],\n )\n\n const close = useCallback(() => {\n if (sessionId === '') return\n modalStoreOf(sessionId).set(false)\n // Consume the `/redline` token now (it stayed in the composer while the modal was open) via the scoped input event — a stale guard\n // (the user typed meanwhile) fails soft inside the shell and leaves the draft untouched. The sessions service is read at CLOSE time:\n // capturing it at apply would race the finer module composition (`ctx.get` is the inject-free reflect read — undefined, never a\n // throw, when the service is not composed).\n const guard = takePendingConsume(sessionId)\n const sessions = ctx.get('sessions') as SessionsFace | undefined\n if (guard === undefined || sessions === undefined) return\n const scope = sessions.scope(sessionId)\n if (scope !== undefined) scope.bail(scope, 'slash/input-consume-token', { guard })\n }, [ctx, sessionId])\n\n // Capture-phase Escape close + focus restore (the shared overlay contract).\n useEscapeClose(open, close)\n\n // Dock the mask to the main column: measure the sidebar track once before\n // first paint, then follow the frame's inline template while open (sidebar\n // drags, collapse toggles and narrow-viewport re-solves all rewrite it).\n // An unresolved frame keeps the full-viewport mask.\n useLayoutEffect(() => {\n if (!open) return undefined\n const dock = measureDock(backdropRef.current)\n setDockLeft(dock.left)\n if (dock.frame === null) return undefined\n const observer = new MutationObserver(() => {\n setDockLeft(measureDock(backdropRef.current).left)\n })\n observer.observe(dock.frame, { attributes: true, attributeFilter: ['style'] })\n return () => { observer.disconnect() }\n }, [open])\n\n if (!open) return null\n\n const head = data !== null ? headlineOf(data, pressure, breakdown) : null\n const subtitle = data !== null ? (data.model ? data.model : '') + (data.provider ? ' · ' + data.provider : '') : ''\n\n return (\n <div ref={backdropRef} className=\"redline-modal-backdrop\" style={{ left: dockLeft }} onClick={close}>\n <div className=\"redline-modal-card\" onClick={(ev) => { ev.stopPropagation() }}>\n <div className=\"redline-modal-head\">\n <span className=\"redline-modal-title\">{t('tab')}</span>\n <button className=\"redline-modal-close hover:text-(--dsw-alias-label-primary) hover:bg-(--dsw-alias-bg-layer-2)\" aria-label={t('cmd.close')} onClick={close}>×</button>\n </div>\n\n {data === null || head === null ? (\n <div className=\"redline-empty\">{t('loading')}</div>\n ) : (\n <div>\n <CurrentComposition\n head={head}\n subtitle={subtitle}\n hoverKey={hoverCat}\n onHoverKey={setHoverCat}\n />\n <ContextBrowser\n redline={redline}\n data={data}\n headers={headers}\n convNodes={convNodes}\n fetchContent={fetchContent}\n fetchHeader={fetchHeader}\n loadImage={loadImage}\n hoverKey={hoverCat}\n onHoverKey={setHoverCat}\n detailState={source.detailState}\n onDetailRetry={source.retryDetail}\n />\n </div>\n )}\n </div>\n </div>\n )\n }\n\n return function ContextModal(props: ContextModalProps): ReactElement | null {\n return h(ErrorBoundary, null, h(ContextModalBody, props))\n }\n}\n","/**\n * Best-effort jump to this plugin's preferences. Two generations of chrome:\n * - dsh 0.1.7+ (Config-form generation): the preferences live on the\n * bundle's page of the Plugins main panel — the jump clicks the panel's\n * sidebar entry (its shipped aria-label), then follows the page with a\n * bounded poll for the bundle card's open control, found by the shipped,\n * locale-independent `data-plugin-package` list identity: the card lists\n * once the page's package load settles, and inside it the one button\n * that is not the enable switch is the title that opens the page. A\n * poll that never finds the card (still loading, plugin absent, or the\n * page already open on the detail view — the list unmounts there)\n * degrades to the card list, and every step stays silent.\n * - older lines: Settings → Plugins → Plugin configuration — the settings\n * panel keeps its open state inside the shell component (no plugin-facing\n * open face exists), so the jump drives the real chrome: click the\n * sidebar's settings trigger, then the Plugins section nav row, both\n * found by their shipped attributes and labels.\n * The last leg — the card itself — is ours: the module also carries a\n * short-lived in-bundle expand request that the settings-section card\n * consumes on mount, so that jump lands on the configuration already open.\n * EVERY step is individually guarded: a shell that doesn't match (different\n * layout, missing sidebar) degrades the whole jump to a silent no-op — this\n * path must never throw into the caller's render.\n */\n\nlet requestedAt = 0\n\n/** Raise a short-lived request for the plugin's settings card to mount expanded. */\nexport function requestCardExpand(now: number = Date.now()): void {\n requestedAt = now\n}\n\n/** Consume the request once; true only while it is still fresh (younger than maxAgeMs). */\nexport function consumeCardExpand(now: number = Date.now(), maxAgeMs = 5000): boolean {\n const fresh = requestedAt > 0 && now - requestedAt < maxAgeMs\n requestedAt = 0\n return fresh\n}\n\n/**\n * The shipped Plugins label in both locales — the main-panel entry's\n * aria-label and the settings section's nav row text are the same word.\n */\nconst PLUGIN_LABELS = new Set(['Plugins', '插件'])\n\n/** The bundle card's shipped list identity (locale-independent). */\nconst PACKAGE_KEY = 'dsh-context-redline'\n\n/** How long the card poll follows the panel: 40 ticks at the 100ms tick, enough for the page's package load. */\nconst POLL_TICKS = 40\n\n/** Buttons the jump may operate on, in document order. */\nfunction buttonsOf(doc: Document): HTMLButtonElement[] {\n return [...doc.querySelectorAll<HTMLButtonElement>('button')]\n}\n\n/** The Plugins main-panel entry, matched by its shipped aria-label. */\nfunction findPanelEntry(doc: Document): HTMLButtonElement | undefined {\n return buttonsOf(doc).find(b => PLUGIN_LABELS.has(b.getAttribute('aria-label') ?? ''))\n}\n\n/**\n * The bundle card's open control: the one button inside the card that is not\n * the enable switch (the primitives switch carries `role=\"switch\"`); the\n * title button's own aria-label is localized.\n */\nfunction findCardOpenControl(doc: Document): HTMLButtonElement | undefined {\n const card = doc.querySelector(`[data-plugin-package=\"${PACKAGE_KEY}\"]`)\n if (card === null) return undefined\n const open = [...card.querySelectorAll<HTMLButtonElement>('button')].filter(b => b.getAttribute('role') !== 'switch')\n return open.length === 1 ? open[0] : undefined\n}\n\n/** The sidebar's settings triggers: dialog semantics plus an expanded flag. */\nfunction findTriggers(doc: Document): HTMLButtonElement[] {\n return buttonsOf(doc)\n .filter(b => b.getAttribute('aria-haspopup') === 'dialog' && b.hasAttribute('aria-expanded'))\n}\n\n/** The Plugins section's nav row, matched by its shipped label text. */\nfunction findSectionRow(doc: Document): HTMLButtonElement | undefined {\n return buttonsOf(doc).find(b => PLUGIN_LABELS.has(b.textContent.trim()))\n}\n\nexport function openPluginSettings(\n doc: Document = document,\n schedule: (run: () => void, ms: number) => void = (run, ms) => { window.setTimeout(run, ms) },\n): void {\n try {\n // Config-form generation first: the panel entry is the one seat both\n // locales ship. The follow-up poll rides the same scheduler contract as\n // the legacy leg, so tests drive every tick.\n const panel = findPanelEntry(doc)\n if (panel !== undefined) {\n panel.click()\n const poll = (left: number): void => {\n try {\n const open = findCardOpenControl(doc)\n if (open !== undefined) {\n open.click()\n return\n }\n } catch { /* a hostile card: stay on the card list */ }\n if (left > 0) schedule(() => { poll(left - 1) }, 100)\n }\n schedule(() => { poll(POLL_TICKS) }, 200)\n return\n }\n const triggers = findTriggers(doc)\n const open = triggers.find(b => b.getAttribute('aria-expanded') === 'true')\n // No dialog trigger at all: this shell has no settings panel — no-op.\n if (open === undefined && triggers.length === 0) return\n // A collapsed trigger opens the panel; an already-open one is left alone.\n triggers.find(b => b.getAttribute('aria-expanded') !== 'true')?.click()\n // Only a chrome with a settings dialog raises the expand request, and\n // only once the trigger click survived — a degraded jump leaves no\n // stale signal behind.\n requestCardExpand()\n schedule(() => {\n try {\n findSectionRow(doc)?.click()\n } catch { /* no Plugins row on this host: stay on the opened section */ }\n }, 80)\n } catch { /* the settings surface doesn't match: silent no-op */ }\n}\n","/**\n * The dsh-context-redline preference cards — two seats over the same six rows. The\n * settings-section card (`settings.plugin.item`, the older harness lines)\n * renders a collapsible list item in Settings → Plugins → Plugin\n * configuration; the Plugins-page card (`plugins.bundle.config`, the\n * Config-form generation) renders the rows flat inside the section chrome the\n * Plugins page draws for the bundle. Both are keyed on the Host-served\n * `dsh-context-redline` namespace and render nothing while it is unavailable (a\n * deployment without the Host half, or a remote browser, shows no trace).\n * The settings-section card mounts expanded when the Plugin Info card's\n * \"Open plugin settings\" jump left a fresh expand request (settingsJump.ts),\n * scrolling itself into view.\n */\n\nimport { useEffect, useRef, useState, type ReactElement } from 'react'\nimport { Menu } from '@deepseek-ai/dsh-client-ui-primitives'\nimport { IconChevronDown } from '../primitives'\nimport { consumeCardExpand } from '../settingsJump'\nimport type { SettingsField, SettingsState } from '../settings'\nimport type { ViewKit } from '../viewkit'\n\nexport interface SettingsCardProps {\n useContextSettings?: <T>(selector: (state: SettingsState) => T) => T\n set?: (field: SettingsField, value: string) => void\n}\n\ninterface PrefRowProps {\n label: string\n value: string\n options: ReadonlyArray<{ id: string; label: string }>\n disabled: boolean\n onPick: (id: string) => void\n}\n\nfunction PrefRow(props: PrefRowProps): ReactElement {\n const [open, setOpen] = useState(false)\n const active = props.options.find(o => o.id === props.value)?.label ?? props.value\n return (\n <div className=\"redline-settings-row\">\n <span className=\"redline-settings-label\">{props.label}</span>\n <Menu\n open={open}\n onClose={() => { setOpen(false) }}\n items={props.options}\n selectedId={props.value}\n onSelect={(id) => { setOpen(false); props.onPick(id) }}\n align=\"end\"\n portal\n anchor={(\n <button\n type=\"button\"\n className=\"redline-settings-select hover:enabled:bg-(--dsw-alias-interactive-bg-hover) disabled:opacity-50 disabled:cursor-default\"\n disabled={props.disabled}\n aria-haspopup=\"menu\"\n aria-expanded={open}\n onClick={() => { setOpen(v => !v) }}\n >\n {active}\n <IconChevronDown />\n </button>\n )}\n />\n </div>\n )\n}\n\n/** Translate over the plugin's dictionary, as the view kit binds it. */\ntype Translate = ViewKit['t']\n\n/** The six preference rows shared by both seats. */\nfunction PreferenceRows(props: { t: Translate; state: SettingsState; set?: SettingsCardProps['set'] }): ReactElement {\n const { t, state, set } = props\n const disabled = state.status !== 'ready' || !state.writable\n return (\n <>\n <PrefRow\n label={t('settings.placement')}\n value={state.placement}\n disabled={disabled}\n options={[\n { id: 'all', label: t('placement.all') },\n { id: 'tab', label: t('placement.tab') },\n { id: 'sidebar', label: t('placement.sidebar') },\n ]}\n onPick={(id) => { set?.('defaultPlacement', id) }}\n />\n {/* 「洞察入口」那个开关随洞察面一起删掉了(2026-10-05 用户选二)—— 不留\"按了没反应\"的开关。 */}\n <PrefRow\n label={t('settings.gran')}\n value={state.granularity}\n disabled={disabled}\n options={[\n { id: 'step', label: t('gran.step') },\n { id: 'turn', label: t('gran.turn') },\n ]}\n onPick={(id) => { set?.('defaultGranularity', id) }}\n />\n <PrefRow\n label={t('settings.mode')}\n value={state.mode}\n disabled={disabled}\n options={[\n { id: 'total', label: t('gran.total') },\n { id: 'delta', label: t('gran.delta') },\n ]}\n onPick={(id) => { set?.('defaultTrendMode', id) }}\n />\n <PrefRow\n label={t('settings.toolSort')}\n value={state.toolSort}\n disabled={disabled}\n options={[\n { id: 'size', label: t('tool.sort.size') },\n { id: 'count', label: t('tool.sort.count') },\n { id: 'name', label: t('tool.sort.name') },\n ]}\n onPick={(id) => { set?.('defaultToolSort', id) }}\n />\n <PrefRow\n label={t('settings.fileSort')}\n value={state.fileSort}\n disabled={disabled}\n options={[\n { id: 'count', label: t('files.sort.count') },\n { id: 'latest', label: t('files.sort.latest') },\n { id: 'path', label: t('files.sort.path') },\n ]}\n onPick={(id) => { set?.('defaultFileSort', id) }}\n />\n </>\n )\n}\n\nexport function makeSettingsCard(kit: ViewKit): (props: SettingsCardProps) => ReactElement | null {\n const { t } = kit\n return function SettingsCard(props: SettingsCardProps): ReactElement | null {\n const [open, setOpen] = useState(false)\n const itemRef = useRef<HTMLLIElement | null>(null)\n // \"Open plugin settings\" jump: consume its fresh expand request once on\n // mount and land open; every guard stays local so no host quirk can surface.\n useEffect(() => {\n if (!consumeCardExpand()) return\n setOpen(true)\n try {\n itemRef.current?.scrollIntoView({ block: 'nearest' })\n } catch { /* hosts without scrollIntoView: expanded but unscrolled */ }\n }, [])\n const state = typeof props.useContextSettings === 'function' ? props.useContextSettings(s => s) : undefined\n if (state === undefined || state.status === 'unavailable') return null\n return (\n <li ref={itemRef} className={'redline-settings-card' + (open ? ' redline-settings-open' : '')}>\n <button\n type=\"button\"\n className=\"redline-settings-head\"\n aria-expanded={open}\n aria-label={`${t(open ? 'settings.collapse' : 'settings.expand')}: ${t('settings.title')}`}\n onClick={() => { setOpen(!open) }}\n >\n <span className=\"redline-settings-headtext\">\n <span className=\"redline-settings-name\">{t('settings.title')}</span>\n <span className=\"redline-settings-desc\">{t('settings.desc')}</span>\n </span>\n <IconChevronDown className=\"redline-settings-chevron\" />\n </button>\n {open\n ? (\n <div className=\"redline-settings-body\">\n {!state.writable && state.status === 'ready'\n ? <p className=\"redline-settings-note\" role=\"status\">{t('settings.readOnly')}</p>\n : null}\n <PreferenceRows t={t} state={state} set={props.set} />\n </div>\n )\n : null}\n </li>\n )\n }\n}\n\n/**\n * The Plugins-page card (the Config-form generation's `plugins.bundle.config`\n * seat, `view: 'page'`): the page owns the bundle's page and section chrome,\n * so the rows render flat. Same unserved/absent degradation as the\n * settings-section card.\n */\nexport function makePluginConfigCard(kit: ViewKit): (props: SettingsCardProps) => ReactElement | null {\n const { t } = kit\n return function PluginConfigCard(props: SettingsCardProps): ReactElement | null {\n const state = typeof props.useContextSettings === 'function' ? props.useContextSettings(s => s) : undefined\n if (state === undefined || state.status === 'unavailable') return null\n return (\n <div className=\"redline-settings-prefs\">\n {!state.writable && state.status === 'ready'\n ? <p className=\"redline-settings-note\" role=\"status\">{t('settings.readOnly')}</p>\n : null}\n <PreferenceRows t={t} state={state} set={props.set} />\n </div>\n )\n }\n}\n","/**\n * The plugin's user-settings binding (browser half). The Host-served\n * `dsh-context-redline` namespace carries per-user display preferences; the Context\n * tab reads them at mount, and the Plugin configuration card (Settings →\n * Plugins) writes them through the settings scope. Both degrade to the\n * schema defaults when the settings surface is absent (older host) or\n * read-only (remote browser in memory mode).\n *\n * The scope faces are minimally re-typed here (the services.ts discipline):\n * the runtime service comes from the user's harness, and type-only imports\n * of the contract package would still be erased — spelling the consumed\n * members keeps the dependency graph honest.\n */\n\nimport type { DefaultFileSort, DefaultGranularity, DefaultPlacement, DefaultToolSort, DefaultTrendMode, SettingsField } from '../shared/types'\n\n// The preference vocabulary is declared once in shared/types.ts; re-exported\n// here so client-side consumers keep their canonical import path.\nexport type { DefaultFileSort, DefaultGranularity, DefaultPlacement, DefaultToolSort, DefaultTrendMode, SettingsField } from '../shared/types'\n\n/** The bound settings scope (ctx.settingsScope.bind result), as consumed. */\nexport interface SettingsScopeLike {\n getSnapshot(): { status: string; value: unknown; writable: boolean }\n subscribe(listener: () => void): () => void\n set(field: string, value: unknown): Promise<void>\n}\n\n/** The ctx.settingsScope binder face, as consumed. */\nexport interface SettingsScopeBinderFace {\n bind(spec: { namespace: string }): SettingsScopeLike\n}\n\n/**\n * The ctx.configForms service face (the Config-form generation's settings\n * transport), as consumed: forms bind per namespace, and `whileServed` keeps\n * a registration alive while the Host serves any of them. The bound form\n * satisfies {@link SettingsScopeLike} (same snapshot/subscribe/set shape).\n */\nexport interface ConfigFormsFace {\n get(namespace: string): SettingsScopeLike\n whileServed(namespaces: readonly string[], register: () => () => void): () => void\n}\n\n/** The preference snapshot the card renders and the view reads at mount. */\nexport interface SettingsState {\n /** Scope sync: loading until the first Host section, unavailable when unserved. */\n status: 'loading' | 'ready' | 'unavailable'\n placement: DefaultPlacement\n granularity: DefaultGranularity\n mode: DefaultTrendMode\n toolSort: DefaultToolSort\n fileSort: DefaultFileSort\n writable: boolean\n}\n\nexport interface ContextSettings {\n /** Observable snapshot store, bound onto card props as `useContextSettings`. */\n store: { subscribe(listener: () => void): () => void; getSnapshot(): SettingsState }\n defaultPlacement(): DefaultPlacement\n defaultGranularity(): DefaultGranularity\n defaultTrendMode(): DefaultTrendMode\n defaultToolSort(): DefaultToolSort\n defaultFileSort(): DefaultFileSort\n attach(scope: SettingsScopeLike): () => void\n /** Persist one preference choice (local echo, then the fenced scope write). */\n set(field: SettingsField, value: string): void\n}\n\ntype Prefs = {\n placement?: DefaultPlacement\n granularity?: DefaultGranularity\n mode?: DefaultTrendMode\n toolSort?: DefaultToolSort\n fileSort?: DefaultFileSort\n}\n\nfunction prefsOf(value: unknown): Prefs {\n if (value === null || typeof value !== 'object') return {}\n const v = value as Record<string, unknown>\n return {\n ...(v.defaultPlacement === 'all' || v.defaultPlacement === 'tab' || v.defaultPlacement === 'sidebar' ? { placement: v.defaultPlacement } : {}),\n ...(v.defaultGranularity === 'step' || v.defaultGranularity === 'turn' ? { granularity: v.defaultGranularity } : {}),\n ...(v.defaultTrendMode === 'total' || v.defaultTrendMode === 'delta' ? { mode: v.defaultTrendMode } : {}),\n ...(v.defaultToolSort === 'size' || v.defaultToolSort === 'count' || v.defaultToolSort === 'name' ? { toolSort: v.defaultToolSort } : {}),\n ...(v.defaultFileSort === 'count' || v.defaultFileSort === 'latest' || v.defaultFileSort === 'path' ? { fileSort: v.defaultFileSort } : {}),\n }\n}\n\nexport function createContextSettings(): ContextSettings {\n let state: SettingsState = { status: 'loading', placement: 'all', granularity: 'turn', mode: 'total', toolSort: 'count', fileSort: 'count', writable: false }\n let scope: SettingsScopeLike | undefined\n const listeners = new Set<() => void>()\n const publish = (next: SettingsState): void => {\n if (next.status === state.status && next.placement === state.placement && next.granularity === state.granularity\n && next.mode === state.mode && next.toolSort === state.toolSort && next.fileSort === state.fileSort\n && next.writable === state.writable) return\n state = next\n for (const listener of listeners) listener()\n }\n // Republish from the bound scope's current snapshot; the attach sync and\n // the failed-write rollback share this one read. Returns the scope's valid\n // placement and insights entry, if it carries them.\n const sync = (bound: SettingsScopeLike): { placement?: DefaultPlacement } => {\n const snap = bound.getSnapshot()\n const prefs = prefsOf(snap.value)\n // Fail open: a config problem must never leave an entry hidden. A valid\n // value wins; one the plugin cannot understand degrades to the field's\n // default; a section without the field (older Host half) keeps the\n // current state.\n const raw = snap.value !== null && typeof snap.value === 'object'\n ? snap.value as Record<string, unknown>\n : undefined\n publish({\n status: snap.status === 'ready' || snap.status === 'unavailable' ? snap.status : 'loading',\n placement: prefs.placement ?? (raw?.defaultPlacement === undefined ? state.placement : 'all'),\n granularity: prefs.granularity ?? state.granularity,\n mode: prefs.mode ?? state.mode,\n toolSort: prefs.toolSort ?? state.toolSort,\n fileSort: prefs.fileSort ?? state.fileSort,\n writable: snap.writable,\n })\n return { placement: prefs.placement }\n }\n return {\n store: {\n subscribe(listener) {\n listeners.add(listener)\n return () => { listeners.delete(listener) }\n },\n getSnapshot: () => state,\n },\n defaultPlacement: () => state.placement,\n defaultGranularity: () => state.granularity,\n defaultTrendMode: () => state.mode,\n defaultToolSort: () => state.toolSort,\n defaultFileSort: () => state.fileSort,\n attach(bound) {\n scope = bound\n sync(bound)\n return bound.subscribe(() => { sync(bound) })\n },\n set(field, value) {\n publish({ ...state, ...prefsOf({ [field]: value }) })\n // The scope write settles asynchronously and its promise REJECTS on a\n // transport failure (dsh keeps only its internal queue tail fulfilled)\n // — never let it float unhandled. Roll the optimistic echo back to the\n // scope's truth; a refused (non-2xx) write needs nothing here, the\n // scope's own recovery re-reads the Host and republishes via subscribe.\n const bound = scope\n if (bound === undefined) return\n void bound.set(field, value).catch(() => {\n const truth = sync(bound)\n // A visibility gate that failed to persist must not keep an entry\n // hidden on an unpersisted echo: with no valid value in the scope's\n // truth, degrade each gate to its default.\n if (field === 'defaultPlacement' && truth.placement === undefined) {\n publish({ ...state, placement: 'all' })\n }\n })\n },\n }\n}\n","/**\n * Step brief — the semantic identity of one history bar (\"what this step was\n * about\"), derived CLIENT-SIDE from the timeline's served nodes; no host or\n * wire additions. A request record's seq IS its response's surface seq (the\n * fold logs both on the same assistant/message event), so:\n *\n * response node = the node at exactly req.seq\n * step inputs = nodes with (previous bar's seq) < seq < req.seq\n * turn opener = the newest user message before this turn's first bar\n *\n * Coverage degrades silently: steps older than the nodes/archive retention\n * window simply yield no rows.\n */\n\nimport type { ContextTimeline, RequestRecord, SurfaceNode } from '../shared/types'\n\nexport interface StepBrief {\n /** The user message that opened this turn (absent when outside retention). */\n opener?: SurfaceNode\n /** Nodes that entered the context since the previous bar (mid-turn steps only). */\n inputs: SurfaceNode[]\n /** This bar's own response node. */\n response?: SurfaceNode\n}\n\n/** Every served node (live tail + removed archive copies), seq-sorted. */\nexport function briefNodes(data: ContextTimeline): SurfaceNode[] {\n return [...data.nodes, ...data.archive].sort((a, b) => a.seq - b.seq)\n}\n\n/** First index whose node seq is >= `seq` (lower bound over the sorted list). */\nfunction lowerBound(nodes: SurfaceNode[], seq: number): number {\n let lo = 0\n let hi = nodes.length\n while (lo < hi) {\n const mid = (lo + hi) >> 1\n if (nodes[mid].seq < seq) lo = mid + 1\n else hi = mid\n }\n return lo\n}\n\n/**\n * Derive the brief for `requests[idx]` (the DISPLAY list — step records or\n * turn aggregates; a turn aggregate is always a turn start, so its inputs row\n * stays hidden and the opener/response carry the narrative).\n */\nexport function briefOf(nodes: SurfaceNode[], requests: RequestRecord[], idx: number): StepBrief | null {\n if (idx < 0 || idx >= requests.length) return null\n const req = requests[idx]\n const ri = lowerBound(nodes, req.seq)\n const hit = ri < nodes.length && nodes[ri].seq === req.seq ? nodes[ri] : undefined\n const response = hit !== undefined && hit.cat === 'assistant' ? hit : undefined\n\n const turnStart = idx === 0 || (requests[idx - 1].turn ?? 0) !== (req.turn ?? 0)\n\n // Opener: the newest user message in (previous turn's last bar seq, this\n // turn's first bar seq) — user messages only land at turn starts.\n let firstIdx = idx\n while (firstIdx > 0 && (requests[firstIdx - 1].turn ?? 0) === (req.turn ?? 0)) firstIdx--\n const upper = requests[firstIdx].seq\n const lower = firstIdx > 0 ? requests[firstIdx - 1].seq : -1\n let opener: SurfaceNode | undefined\n for (let i = lowerBound(nodes, upper) - 1; i >= 0; i--) {\n const n = nodes[i]\n if (n.seq <= lower) break\n if (n.cat === 'user') { opener = n; break }\n }\n\n const inputs: SurfaceNode[] = []\n if (!turnStart) {\n // idx > 0 here (a first bar is always a turn start): collect everything that landed since the previous bar.\n const prevSeq = requests[idx - 1].seq\n for (let i = lowerBound(nodes, prevSeq + 1); i < nodes.length && nodes[i].seq < req.seq; i++) {\n inputs.push(nodes[i])\n }\n }\n return { opener, inputs, response }\n}\n","/**\n * 「这条子会话是不是**在这个面板里**开的」—— 我们自己的一本台账(`docs/10` **M5-12**)。\n *\n * 为什么必须自己记,而不是从平台读:\n * 官方 `subagentCatalog` 投影的条目里**只有** `childId` / `childCreatedAt` / `version` /\n * `mode` / `label` —— **没有来源字段**(2026-10-07 安装树实测,`docs/01` **F59**)。\n * 所以\"本项目发起 / 来自 Agent Teams\"这件事,平台侧答不出来。\n *\n * 三种**诚实**态(界面按这三态说话,不许含糊):\n * ① 台账里有这条 ⟹ **本项目发起**,并写明走的是\"官方成员\"还是\"裸子会话\"(那是我们真知道的,\n * 因为 `child.start` 的返回里就带着 `via`);\n * ② 台账里没有这条 ⟹ **不是在这儿开的**(**不猜**是谁开的:可能是官方团队自己的工具、\n * 也可能是别的会话 —— 我们不去读官方名册,那块界面已按用户裁定撤下);\n * ③ 台账**读不出来** ⟹ **来源未知**并**大声**报错(`redline/origin-corrupt` /\n * `redline/origin-schema`),绝不假装成\"没有记录\"(那会把②说成一个我们没证据的结论)。\n *\n * 只写我们自己的数据目录;**不写任何会话**(`AGENTS.md` §1)。\n */\n\nimport { REDLINE_ERROR } from './redline-errors'\nimport { stableKeyOf } from './redline-drafts'\n\n/** 这条子会话是走哪条路开的(`child.start` 的返回里那个 `via`)。 */\nexport type OriginVia = 'official-member' | 'bare-child'\n\n/** 一条台账记录。`childId` 对官方成员就是 `TeamMemberView.id`(类型是 `SessionId`)。 */\nexport interface OriginRecord {\n readonly childId: string\n readonly via: OriginVia\n readonly at: number\n}\n\n/** 台账文件形状(带自己的 schemaVersion,串档/旧版要认得出)。 */\nexport interface OriginFile {\n readonly schemaVersion: number\n readonly sessionId: string\n readonly records: readonly OriginRecord[]\n}\n\n/** 台账文件的 schema 版本。 */\nexport const ORIGIN_LEDGER_SCHEMA_VERSION = 1\n\n/** 一本台账最多留多少条(老的先丢;子会话数量远小于这个数)。 */\nexport const ORIGIN_LEDGER_CAP = 200\n\n/** 一条会话的台账文件名(与草稿同一套命名:可读前缀 + 稳定短哈希)。 */\nexport function originsFileName(sessionId: string): string {\n const readable = sessionId.replace(/[^A-Za-z0-9_-]/g, '_').slice(0, 40)\n return `redline-origins-${readable}-${stableKeyOf(sessionId)}.json`\n}\n\n/** 解析结果:`ok:false` 一定带一个**稳定错误码**,界面就按它说人话。 */\nexport type OriginParseResult =\n | { readonly ok: true; readonly records: readonly OriginRecord[] }\n | { readonly ok: false; readonly code: string; readonly message: string }\n\nconst VIA_VALUES: readonly string[] = ['official-member', 'bare-child']\n\nfunction recordOf(raw: unknown): OriginRecord | null {\n if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return null\n const row = raw as Record<string, unknown>\n const childId = row.childId\n const via = row.via\n if (typeof childId !== 'string' || childId === '') return null\n if (typeof via !== 'string' || !VIA_VALUES.includes(via)) return null\n const at = typeof row.at === 'number' && Number.isFinite(row.at) ? row.at : 0\n return { childId, via: via as OriginVia, at }\n}\n\n/**\n * 缺文件 = 空台账(我们确实没在这条会话里开过子会话);\n * 文件在但读不出来 = **大声拒绝**(不许把③说成②)。\n *\n * @param raw - 文件内容(`null` = 文件不存在)。\n * @param expectedSessionId - 给了就校验串档(台账上写的会话必须就是这条)。\n */\nexport function parseOrigins(raw: string | null | undefined, expectedSessionId?: string): OriginParseResult {\n if (raw === null || raw === undefined || raw.trim() === '') return { ok: true, records: [] }\n let parsed: unknown\n try {\n parsed = JSON.parse(raw)\n } catch {\n return { ok: false, code: REDLINE_ERROR.originCorrupt, message: 'the origin ledger is not valid JSON' }\n }\n if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {\n return { ok: false, code: REDLINE_ERROR.originCorrupt, message: 'the origin ledger is not an object' }\n }\n const file = parsed as Record<string, unknown>\n if (file.schemaVersion !== ORIGIN_LEDGER_SCHEMA_VERSION) {\n return { ok: false, code: REDLINE_ERROR.originSchema, message: 'the origin ledger has an unsupported schema version' }\n }\n if (typeof file.sessionId !== 'string' || file.sessionId === '') {\n return { ok: false, code: REDLINE_ERROR.originCorrupt, message: 'the origin ledger has no session id' }\n }\n if (expectedSessionId !== undefined && file.sessionId !== expectedSessionId) {\n return { ok: false, code: REDLINE_ERROR.originCorrupt, message: 'the origin ledger belongs to another session' }\n }\n if (!Array.isArray(file.records)) {\n return { ok: false, code: REDLINE_ERROR.originCorrupt, message: 'the origin ledger has no records array' }\n }\n const records: OriginRecord[] = []\n for (const entry of file.records) {\n const record = recordOf(entry)\n // 坏条目**丢**(不是整份拒绝):一条垃圾不该让整本台账变成\"来源未知\"。\n if (record !== null && !records.some(one => one.childId === record.childId)) records.push(record)\n }\n return { ok: true, records }\n}\n\n/** 写盘用的确定性序列化(新的在前)。 */\nexport function serializeOrigins(sessionId: string, records: readonly OriginRecord[]): string {\n const file: OriginFile = { schemaVersion: ORIGIN_LEDGER_SCHEMA_VERSION, sessionId, records }\n return `${JSON.stringify(file, null, 2)}\\n`\n}\n\n/** 记一条(按 `childId` 幂等:同一条子会话只留最新那次),超出上限丢最老的。 */\nexport function putOrigin(records: readonly OriginRecord[], record: OriginRecord): OriginRecord[] {\n const next = [record, ...records.filter(one => one.childId !== record.childId)]\n return next.length > ORIGIN_LEDGER_CAP ? next.slice(0, ORIGIN_LEDGER_CAP) : next\n}\n\n/** 这条子会话是不是在这儿开的;是就顺带说清走的是哪条路。 */\nexport function viaOf(records: readonly OriginRecord[], childId: string): OriginVia | null {\n return records.find(one => one.childId === childId)?.via ?? null\n}\n","/**\n * 「这台机器允许多少个团队成员」—— `docs/10` **M5-13** 标题里那个分母的来源。\n *\n * 为什么这里不是一句常量(三件事决定的):\n *\n * ① **分母不是库默认值**:官方 `maxMembers` 的**库默认是 16**,而本机由\n * `…/@deepseek-ai/dsh-experimental-agent-team-profile/cordis.patch.yml` 配成 **8**\n * (`docs/01` **F31** 实测)⟹ 写死任何一个数都会在另一种部署上变成假话;\n * ② **读它是一次\"可能读不到\"的动作**:服务可能没启用(团队未装配)、字段可能改名\n * (TS 的 `private readonly config` 在运行时只是普通属性 `this.config`,**不是** JS `#private`,\n * 所以能读,但没有任何契约保证它一直在)⟹ **读不到就必须说\"不知道\"**,\n * 界面那时只写 `活跃 N`,**绝不编一个分母**;\n * ③ 通道来的值进渲染前要 **re-prove 形状**(`docs/11` D54 的教训:喂错形状曾把面板渲染炸掉)。\n *\n * 两边都用它:宿主用它读活服务({@link capacityFromService}),客户端用它验通道回答\n * ({@link capacityOf})—— 一个口径只有一处实现。\n */\n\n/** 上限的两种状态:知道(`max` 是正整数)或不知道(`max` 为 null)。 */\nexport interface ChildCapacity {\n readonly known: boolean\n readonly max: number | null\n}\n\n/** 唯一的\"不知道\"取值(冻结:调用方不许就地改它)。 */\nexport const UNKNOWN_CAPACITY: ChildCapacity = Object.freeze({ known: false, max: null })\n\n/** 只接受**正整数**:0 / 负数 / 小数 / `NaN` / 字符串一律算\"读不到\"。 */\nfunction positiveIntOf(value: unknown): number | null {\n return typeof value === 'number' && Number.isInteger(value) && value > 0 ? value : null\n}\n\n/**\n * 从**活服务对象**上防御性读 `config.maxMembers`。\n *\n * @param service - `ctx.get('agentTeams')` 拿到的那个对象(可能是 `undefined`)。\n * @returns 读到正规正整数就是 `{known:true,max}`,其余一律 {@link UNKNOWN_CAPACITY}。\n */\nexport function capacityFromService(service: unknown): ChildCapacity {\n if (service === null || typeof service !== 'object') return UNKNOWN_CAPACITY\n const config = (service as { config?: unknown }).config\n if (config === null || typeof config !== 'object') return UNKNOWN_CAPACITY\n const max = positiveIntOf((config as { maxMembers?: unknown }).maxMembers)\n return max === null ? UNKNOWN_CAPACITY : { known: true, max }\n}\n\n/**\n * Re-prove 一个从通道读来的值(`child.capacity` 的回答)。\n *\n * @param raw - 通道回答里的 `value`,形状不可信。\n * @returns 形状对得上才是那个上限,否则 {@link UNKNOWN_CAPACITY}。\n */\nexport function capacityOf(raw: unknown): ChildCapacity {\n if (raw === null || typeof raw !== 'object') return UNKNOWN_CAPACITY\n const value = raw as { known?: unknown; max?: unknown }\n if (value.known !== true) return UNKNOWN_CAPACITY\n const max = positiveIntOf(value.max)\n return max === null ? UNKNOWN_CAPACITY : { known: true, max }\n}\n","/**\n * The child-session half of the panel: the parent's **index of children**\n * (`subagentCatalog`) plus the two calls that open a new one (`child.plan` →\n * `child.start`).\n *\n * Three things this module deliberately does NOT do, all from `docs/03` R5.1.1:\n *\n * 1. **It does not draw a conversation.** The index lists identity + state and\n * nothing else; the full view is the official UI's job (the runtime's own\n * subagent package owns the tree picker in the parent header). R5.1.1 spells\n * out why: copying a tree/dialog view would fight the official surface and\n * drag a consistency problem we do not need.\n * 2. **It does not offer a jump.** The current demo only states the child's\n * state (\"open it = the panel switches to its context\"); the actual jump is\n * a later stage (`docs/10` M5-06 / M7-02).\n * 3. **It never guesses a state.** A child's \"running / idle / not in this\n * process\" is read from the SAME `turnState` op the editor uses — one\n * read-only call per child — so the row's sentence matches what pressing\n * `编辑` there would actually do. Unknown stays unknown (`null`), and the\n * row says so instead of claiming 空闲.\n */\n\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react'\nimport { planChild, readCapacity, readCarrierModels, readCarriers, readOrigins, readTurnState, startChild, type CarrierModelOption, type ChildPlan, type ChildStarted, type RedlineResult } from './redlineChannel'\nimport { viaOf, type OriginRecord, type OriginVia } from '../shared/redline-origins'\nimport { REDLINE_ERROR as ERR } from '../shared/redline-errors'\nimport { UNKNOWN_CAPACITY, capacityOf, type ChildCapacity } from '../shared/redline-capacity'\n\n/** One row of the index. */\nexport interface ChildRow {\n readonly id: string\n /** The tail of the id, the way the official surface shows it. */\n readonly short: string\n readonly label: string\n /** `one-shot` / `continuable` / `unknown` — straight from the catalog entry. */\n readonly mode: 'one-shot' | 'continuable' | 'unknown'\n readonly createdAt: number\n /** `true` = this process hosts a live agent for it; `null` = not read yet. */\n readonly live: boolean | null\n /** `true` = its turn has not closed yet (writes are refused there too). */\n readonly open: boolean | null\n /** Carrier rows declare their source directly; legacy rows fill this from the old origin ledger. */\n readonly via?: OriginVia | 'ordinary-session' | null\n}\n\ninterface CatalogEntryLike {\n readonly id?: unknown\n readonly label?: unknown\n readonly mode?: unknown\n readonly createdAt?: unknown\n}\n\n/**\n * Parse the `subagentCatalog` projection into rows.\n *\n * Pure and total on purpose: the projection is host data, so a malformed entry\n * must degrade to a row that says `unknown`, never throw inside render.\n *\n * @param raw - the projection value as it arrived (any shape).\n * @returns one row per usable entry, newest first (the fold appends).\n */\nexport function childRowsOf(raw: unknown): ChildRow[] {\n if (!Array.isArray(raw)) return []\n const rows: ChildRow[] = []\n for (const item of raw as unknown[]) {\n if (item === null || typeof item !== 'object') continue\n const entry = item as CatalogEntryLike\n const id = typeof entry.id === 'string' ? entry.id : null\n if (id === null) continue\n const mode = entry.mode === 'one-shot' || entry.mode === 'continuable' || entry.mode === 'unknown' ? entry.mode : 'unknown'\n rows.push({\n id,\n short: id.length > 8 && id.includes('-') ? id.slice(-8) : id,\n label: typeof entry.label === 'string' ? entry.label : '',\n mode,\n createdAt: typeof entry.createdAt === 'number' ? entry.createdAt : 0,\n live: null,\n open: null,\n })\n }\n return rows.reverse()\n}\n\n/** 索引行 + \"在这儿开的吗\"(台账)。 */\nexport interface ChildIndexRow extends ChildRow {\n /** 在这儿开的:走的是官方成员还是裸子会话;`null`/缺省 = 台账里没有这条(不猜是谁开的)。 */\n readonly via?: OriginVia | 'ordinary-session' | null\n}\n\nexport interface ChildController {\n /** The index rows; `live`/`open` fill in as the per-child probes answer. */\n readonly rows: readonly ChildRow[]\n /**\n * 这台机器允许几个团队成员(M5-13 标题里的分母)。**读不到就是\"不知道\"**\n * (`known:false`)⟹ 界面那时只写 `活跃 N`,不编一个分母。\n */\n readonly capacity: ChildCapacity\n /**\n * 我们那本来源台账**读得出来吗**(M5-12)。`false` = 读不出来 ⟹ 界面必须说\"来源未知\",\n * **不许**说成\"不是在这儿开的\"(那是把一个我们没证据的结论说成事实)。\n */\n readonly originsKnown: boolean\n /**\n * 台账**为什么**读不出来(错误码);\\`null\\` = 没有这件事。\n * 界面要把它说出来 —— 只说\"来源未知\"等于把原因吞掉(`docs/11` D54 的教训)。\n */\n readonly originsError: string | null\n /** Live selectable models; reading them never changes this or the source session. */\n readonly models: readonly CarrierModelOption[]\n /** Open the confirm box: the host builds exact default bytes/config for this task. */\n readonly plan: (humanTask: string) => Promise<RedlineResult<ChildPlan>>\n /** The only call in this whole panel that writes a session (`docs/11` D15). */\n readonly start: (\n humanTask: string,\n confirmationToken: string,\n finalText?: string,\n config?: { provider: string; model: string; reasoningEffort?: string },\n ) => Promise<RedlineResult<ChildStarted>>\n}\n\n/**\n * Probe one row's state through the same read-only op the editor's gate uses.\n *\n * @param sessionId - the child's own session id.\n * @returns `live`/`open`, or `null`s when the read failed (never a guess).\n */\nexport function carrierModelsOf(raw: unknown): CarrierModelOption[] {\n if (!Array.isArray(raw)) return []\n const models: CarrierModelOption[] = []\n for (const item of raw) {\n if (item === null || typeof item !== 'object' || Array.isArray(item)) continue\n const model = item as Record<string, unknown>\n if (typeof model.provider !== 'string' || model.provider === '' || typeof model.providerName !== 'string'\n || typeof model.model !== 'string' || model.model === '' || typeof model.modelName !== 'string'\n || !Array.isArray(model.efforts)) continue\n const efforts: { id: string; name: string }[] = []\n for (const rawEffort of model.efforts) {\n if (rawEffort === null || typeof rawEffort !== 'object' || Array.isArray(rawEffort)) continue\n const effort = rawEffort as Record<string, unknown>\n if (typeof effort.id === 'string' && effort.id !== '' && typeof effort.name === 'string') {\n efforts.push({ id: effort.id, name: effort.name })\n }\n }\n models.push({\n provider: model.provider,\n providerName: model.providerName,\n model: model.model,\n modelName: model.modelName,\n efforts,\n ...(typeof model.defaultEffort === 'string' ? { defaultEffort: model.defaultEffort } : {}),\n })\n }\n return models\n}\n\nasync function probeChild(sessionId: string): Promise<{ live: boolean; open: boolean } | null> {\n const state = await readTurnState(sessionId)\n if (!state.ok) return null\n return { live: state.value.known, open: state.value.open }\n}\n\n/**\n * Wire the index + the two child calls for one session.\n *\n * @param sessionId - the session the panel is showing (the would-be parent).\n * @param catalog - the raw `subagentCatalog` projection value.\n */\nexport function useChildSessions(\n sessionId: string | undefined,\n catalog: unknown,\n): ChildController {\n const legacy = useMemo(() => childRowsOf(catalog), [catalog])\n const [carriers, setCarriers] = useState<ChildIndexRow[]>([])\n const carrierGeneration = useRef(0)\n const refreshCarriers = useCallback(async (): Promise<void> => {\n carrierGeneration.current += 1\n const mine = carrierGeneration.current\n setCarriers([])\n if (sessionId === undefined || sessionId === '') return\n const answer = await readCarriers(sessionId)\n if (carrierGeneration.current !== mine || !answer.ok) return\n const payload: unknown = answer.value\n const rows = payload !== null && typeof payload === 'object' && Array.isArray((payload as { rows?: unknown }).rows)\n ? (payload as { rows: { id?: unknown; label?: unknown; mode?: unknown; createdAt?: unknown; via?: unknown }[] }).rows\n : []\n setCarriers(rows.flatMap((row) => {\n if (typeof row.id !== 'string' || row.id === '') return []\n return [{\n id: row.id,\n short: row.id.length > 8 ? row.id.slice(-8) : row.id,\n label: typeof row.label === 'string' ? row.label : '',\n mode: 'continuable' as const,\n createdAt: typeof row.createdAt === 'number' ? row.createdAt : 0,\n via: 'ordinary-session' as const,\n live: null,\n open: null,\n }]\n }))\n }, [sessionId])\n useEffect(() => { void refreshCarriers() }, [refreshCarriers])\n const base = useMemo(() => {\n const carrierIds = new Set(carriers.map(row => row.id))\n return [...carriers, ...legacy.filter(row => !carrierIds.has(row.id))]\n }, [carriers, legacy])\n const [states, setStates] = useState<Record<string, { live: boolean; open: boolean }>>({})\n const generation = useRef(0)\n\n useEffect(() => {\n generation.current += 1\n const mine = generation.current\n setStates({})\n if (base.length === 0) return\n // A handful of read-only calls; a child that answers after the panel moved on\n // must not write into the new session's index (same guard as the draft hook).\n void (async () => {\n const entries = await Promise.all(base.map(async row => [row.id, await probeChild(row.id)] as const))\n if (generation.current !== mine) return\n const next: Record<string, { live: boolean; open: boolean }> = {}\n for (const [id, state] of entries) if (state !== null) next[id] = state\n setStates(next)\n })()\n }, [base])\n\n // 来源台账:跟着会话取一次;`known:false` 的初值意味着\"在回答到达之前不冒充知道\"。\n // 与上面的索引探测同一个惯用法:用\"第几代\"而不是 `let cancelled`(后者会被\n // `no-unnecessary-condition` 判成恒假 —— 规则看不见闭包里的赋值)。\n interface OriginsState { known: boolean; records: readonly OriginRecord[]; error: string | null }\n const EMPTY_ORIGINS: OriginsState = { known: false, records: [], error: null }\n const [origins, setOrigins] = useState<OriginsState>(EMPTY_ORIGINS)\n const originsGeneration = useRef(0)\n useEffect(() => {\n originsGeneration.current += 1\n const mine = originsGeneration.current\n setOrigins(EMPTY_ORIGINS)\n if (sessionId === undefined || sessionId === '') return\n void (async () => {\n const answer = await readOrigins(sessionId)\n if (originsGeneration.current !== mine) return\n // ⚠️ 用**宿主回答里的错误码**,别硬套 transport 那句 ——\n // 旧宿主没有这个 op 时答的是 \\`redline/unknown-op\\`,对应的人话是\"刷新页面再试\",\n // 而 transport 那句是\"保存没有送到宿主\",用在这里是**误导**。\n if (!answer.ok) { setOrigins({ known: false, records: [], error: answer.code === '' ? ERR.transport : answer.code }); return }\n setOrigins(answer.value.records === null\n ? { known: false, records: [], error: answer.value.error ?? ERR.originCorrupt }\n : { known: true, records: answer.value.records, error: null })\n })()\n }, [sessionId])\n\n const rows = useMemo(\n () => base.map(row => ({\n ...row,\n ...(states[row.id] ?? { live: null, open: null }),\n via: row.via === 'ordinary-session' ? row.via : viaOf(origins.records, row.id),\n })),\n [base, states, origins],\n )\n\n // 分母只问一次(与选哪个会话无关:它是这台机器的配置,不是某条日志的性质)。\n // 回答的形状不可信 ⟹ 先 `capacityOf()` re-prove 再进渲染(`docs/11` D54 的教训)。\n const [capacity, setCapacity] = useState<ChildCapacity>(UNKNOWN_CAPACITY)\n // 与上面那个索引探测同一个惯用法:用\"第几代\"而不是 `let alive`\n // (`let alive` 会被 `no-unnecessary-condition` 判成恒假 —— 那是规则对闭包赋值看不见,\n // 但**改成代次计数器既绕开它、又和本文件既有写法一致**)。\n const capGeneration = useRef(0)\n useEffect(() => {\n capGeneration.current += 1\n const mine = capGeneration.current\n void (async () => {\n const answer = await readCapacity()\n if (capGeneration.current !== mine || !answer.ok) return\n setCapacity(capacityOf(answer.value))\n })()\n }, [])\n\n const [models, setModels] = useState<readonly CarrierModelOption[]>([])\n useEffect(() => {\n void (async () => {\n const answer = await readCarrierModels()\n if (!answer.ok) return\n setModels(carrierModelsOf((answer.value as { models?: unknown }).models))\n })()\n }, [])\n\n const plan = useCallback(async (humanTask: string): Promise<RedlineResult<ChildPlan>> => {\n if (sessionId === undefined || sessionId === '') {\n return { ok: false, code: 'redline/not-live', message: 'no session' }\n }\n return await planChild(sessionId, humanTask)\n }, [sessionId])\n\n const start = useCallback(async (\n humanTask: string,\n confirmationToken: string,\n finalText?: string,\n config?: { provider: string; model: string; reasoningEffort?: string },\n ): Promise<RedlineResult<ChildStarted>> => {\n if (sessionId === undefined || sessionId === '') {\n return { ok: false, code: 'redline/not-live', message: 'no session' }\n }\n const answer = await startChild(sessionId, humanTask, confirmationToken, finalText, config)\n if (answer.ok) await refreshCarriers()\n return answer\n }, [refreshCarriers, sessionId])\n\n return useMemo(\n () => ({ rows, capacity, originsKnown: origins.known, originsError: origins.error, models, plan, start }),\n [rows, capacity, origins.known, origins.error, models, plan, start],\n )\n}\n","/**\n * The child-session card: the always-here 「开子会话」 entry, the read-only index of\n * children, and the small confirm box the entry opens.\n *\n * The contract (all of it from `docs/03` R5.1 / R5.1.1 / R5.1.3 and `docs/11` D15):\n *\n * · **Two blocks only** — 开子会话 + 子会话索引. No freeze record, no dispatch, no official\n * task board, no compaction, no interrupt: those are later stages (`docs/11` D10).\n * · **The index never draws a conversation** and offers no jump; it states identity + state and\n * says in words what the state means for editing. The official surface owns the tree and the\n * full view.\n * · **The button is gated exactly like `保存`**: a parent whose turn has not closed, or that is\n * not live in this process, would be refused by the host (`redline/turn-open` /\n * `redline/not-live`) — so it is disabled here first and says why, rather than letting the\n * click fail.\n * · **The confirm box is the host's own five items** (`child.plan`), and the first message is\n * written by the human only: the plugin never invents a word (`docs/11` D15, hard constraint).\n * An empty task makes the plan itself refuse; the confirm button is then disabled. The refusal stays\n * observable (`data-redline-refusal` on the task block), but its sentence is NOT printed any more —\n * the user asked to drop it (2026-10-08).\n */\n\nimport { createElement as h, useCallback, useEffect, useLayoutEffect, useRef, useState, type ChangeEvent, type CSSProperties, type ReactElement } from 'react'\nimport { createPortal } from 'react-dom'\nimport type { ViewKit } from '../viewkit'\nimport type { ChildIndexRow, ChildRow } from '../childSessions'\nimport type { ChildCapacity } from '../../shared/redline-capacity'\nimport type { CarrierModelOption, ChildPlan, ChildStarted, RedlineResult } from '../redlineChannel'\n\nexport interface ChildCardProps {\n /** The parent session the panel is showing. */\n readonly sessionId?: string\n /** The index, already probed (`childSessions.ts`). */\n readonly rows: readonly ChildIndexRow[]\n /** 我们那本来源台账读得出来吗(缺省按\"读得出来\"处理,独立渲染时行为可预期)。 */\n readonly originsKnown?: boolean\n /** 读不出来时的**原因**(错误码);界面要把它说成人话,不许只写\"来源未知\"。 */\n readonly originsError?: string | null\n /** 这台机器允许几个团队成员(M5-13 的分母);缺省 = 不知道。 */\n readonly capacity?: ChildCapacity\n /** Live model catalog; choosing one only configures the new carrier. */\n readonly models?: readonly CarrierModelOption[]\n /** The parent is live in this process (`turnState.known`). */\n readonly live: boolean\n /** The parent's turn has not closed yet. */\n readonly turnOpen: boolean\n /** How many local edits the confirm box will carry (0 → the sentence says \"no edits\"). */\n readonly carriedCount: number\n /** `child.plan` — read-only, builds the five items for this exact task text. */\n readonly plan: (humanTask: string) => Promise<RedlineResult<ChildPlan>>\n /** `child.start` — the ONLY session write the panel can perform. */\n readonly start: (\n humanTask: string,\n confirmationToken: string,\n finalText?: string,\n config?: { provider: string; model: string; reasoningEffort?: string },\n ) => Promise<RedlineResult<ChildStarted>>\n}\n\ninterface CarrierSelectionBarProps {\n readonly models: readonly CarrierModelOption[]\n readonly selectedRoute: string\n readonly selectedEffort: string\n readonly onRoute: (route: string) => void\n readonly onEffort: (effort: string) => void\n readonly t: ViewKit['t']\n}\n\nfunction CarrierSelectionBar(props: CarrierSelectionBarProps): ReactElement {\n const [open, setOpen] = useState<'model' | 'effort' | null>(null)\n const modelRef = useRef<HTMLButtonElement | null>(null)\n const effortRef = useRef<HTMLButtonElement | null>(null)\n const menuRef = useRef<HTMLDivElement | null>(null)\n const [menuStyle, setMenuStyle] = useState<CSSProperties>({ visibility: 'hidden' })\n const selected = props.models.find(model => JSON.stringify([model.provider, model.model]) === props.selectedRoute)\n const effortLabel = props.selectedEffort === ''\n ? props.t('child.confirm.effortDefault')\n : selected?.efforts.find(level => level.id === props.selectedEffort)?.name ?? props.selectedEffort\n\n useLayoutEffect(() => {\n if (open === null) return\n const trigger = open === 'model' ? modelRef.current : effortRef.current\n if (trigger === null) return\n const rect = trigger.getBoundingClientRect()\n const width = Math.min(Math.max(open === 'model' ? 300 : 220, rect.width), window.innerWidth - 32)\n const left = Math.min(Math.max(16, rect.left), window.innerWidth - width - 16)\n setMenuStyle({ left, width, bottom: window.innerHeight - rect.top + 6, maxHeight: Math.max(120, rect.top - 22) })\n }, [open])\n\n useEffect(() => {\n if (open === null) return\n const dismiss = (event: MouseEvent): void => {\n const node = event.target\n if (!(node instanceof Node) || menuRef.current?.contains(node) === true\n || modelRef.current?.contains(node) === true || effortRef.current?.contains(node) === true) return\n setOpen(null)\n }\n const escape = (event: KeyboardEvent): void => { if (event.key === 'Escape') setOpen(null) }\n document.addEventListener('mousedown', dismiss)\n document.addEventListener('keydown', escape)\n return () => {\n document.removeEventListener('mousedown', dismiss)\n document.removeEventListener('keydown', escape)\n }\n }, [open])\n\n const toggle = (pane: 'model' | 'effort'): void => { setOpen(current => current === pane ? null : pane) }\n const groups = new Map<string, { name: string; models: CarrierModelOption[] }>()\n for (const model of props.models) {\n const group = groups.get(model.provider) ?? { name: model.providerName, models: [] }\n group.models.push(model)\n groups.set(model.provider, group)\n }\n const menu = open === null ? null : createPortal(h('div', {\n ref: menuRef,\n className: 'redline-picker-menu scrollable',\n style: menuStyle,\n role: 'menu',\n 'data-redline-picker-menu': open,\n }, open === 'model'\n ? [...groups.entries()].map(([provider, group]) => h('section', { key: provider, className: 'redline-picker-group' },\n h('div', { className: 'redline-picker-group-label' }, group.name),\n group.models.map((model) => {\n const route = JSON.stringify([model.provider, model.model])\n const active = route === props.selectedRoute\n return h('button', {\n type: 'button', role: 'menuitemradio', 'aria-checked': active,\n className: 'redline-picker-option' + (active ? ' is-selected' : ''),\n key: route,\n onClick: () => { props.onRoute(route); setOpen(null) },\n }, h('span', null, model.modelName), h('span', { className: 'redline-picker-check' }, active ? '✓' : ''))\n })))\n : h('div', null,\n [{ id: '', name: props.t('child.confirm.effortDefault') }, ...(selected?.efforts ?? [])].map((level) => {\n const active = level.id === props.selectedEffort\n return h('button', {\n type: 'button', role: 'menuitemradio', 'aria-checked': active,\n className: 'redline-picker-option' + (active ? ' is-selected' : ''),\n key: level.id || 'default',\n onClick: () => { props.onEffort(level.id); setOpen(null) },\n }, h('span', null, level.name), h('span', { className: 'redline-picker-check' }, active ? '✓' : ''))\n }))), document.body)\n\n return h('div', { className: 'redline-picker-bar', 'data-redline-picker': '1' },\n h('button', {\n ref: modelRef, type: 'button', className: 'redline-picker-trigger',\n 'data-redline-model': '1', 'aria-haspopup': 'menu', 'aria-expanded': open === 'model',\n onClick: () => { toggle('model') },\n }, h('span', { className: 'redline-picker-value' }, selected?.modelName ?? props.t('child.confirm.modelLabel')),\n h('span', { className: 'redline-picker-chevron' + (open === 'model' ? ' redline-picker-chevron-open' : '') }, '⌄')),\n h('span', { className: 'redline-picker-divider' }),\n h('button', {\n ref: effortRef, type: 'button', className: 'redline-picker-trigger',\n 'data-redline-effort': '1', 'aria-haspopup': 'menu', 'aria-expanded': open === 'effort',\n disabled: selected === undefined,\n onClick: () => { toggle('effort') },\n }, h('span', { className: 'redline-picker-value redline-picker-effort-value' }, effortLabel),\n h('span', { className: 'redline-picker-chevron' + (open === 'effort' ? ' redline-picker-chevron-open' : '') }, '⌄')),\n menu,\n )\n}\n\n/** The state dot + word a row shows, from the probed `turnState`. */\nfunction stateOf(row: ChildRow): { tone: string; key: string; hint: string } {\n if (row.live === null) return { tone: 'unknown', key: 'child.state.unknown', hint: 'child.hint.unknown' }\n if (!row.live) return row.via === 'ordinary-session'\n ? { tone: 'gone', key: 'child.state.unloaded', hint: 'child.hint.unloaded' }\n : { tone: 'gone', key: 'child.state.gone', hint: 'child.hint.gone' }\n if (row.open === true) return { tone: 'run', key: 'child.state.running', hint: 'child.hint.running' }\n return row.via === 'ordinary-session'\n ? { tone: 'idle', key: 'child.state.idle', hint: 'child.hint.carrierIdle' }\n : { tone: 'idle', key: 'child.state.idle', hint: 'child.hint.idle' }\n}\n\n/** `HH:MM` for a `createdAt` timestamp; an unreadable stamp shows nothing. */\nfunction clockOf(createdAt: number): string | null {\n if (!Number.isFinite(createdAt) || createdAt <= 0) return null\n const date = new Date(createdAt)\n const pad = (n: number): string => String(n).padStart(2, '0')\n return `${pad(date.getHours())}:${pad(date.getMinutes())}`\n}\n\nexport function makeChildCard(kit: ViewKit): (props: ChildCardProps) => ReactElement {\n const { t } = kit\n\n return function ChildCard(props): ReactElement {\n const [open, setOpen] = useState(false)\n const [task, setTask] = useState('')\n const [plan, setPlan] = useState<ChildPlan | null>(null)\n const [finalText, setFinalText] = useState('')\n const [selectedRoute, setSelectedRoute] = useState('')\n const [selectedEffort, setSelectedEffort] = useState('')\n const [busy, setBusy] = useState(false)\n const [error, setError] = useState<{ code: string; message: string } | null>(null)\n // Late plan/start answers for an older task or selected session must not overwrite the new view.\n const generation = useRef(0)\n const startGeneration = useRef(0)\n\n const blockedKey = !props.live\n ? 'redline.blocked.notLive'\n : props.turnOpen ? 'redline.blocked.turnOpen' : null\n\n const close = useCallback(() => {\n setOpen(false)\n setPlan(null)\n setError(null)\n }, [])\n\n useEffect(() => {\n generation.current += 1\n startGeneration.current += 1\n setOpen(false)\n setTask('')\n setPlan(null)\n setFinalText('')\n setSelectedRoute('')\n setSelectedEffort('')\n setBusy(false)\n setError(null)\n }, [props.sessionId])\n\n // The confirm box's five items come from the host and depend on the task text\n // (item 3 IS that text, and the refusal fires on an empty one), so refetch on change —\n // debounced, because every keystroke would otherwise be a round trip.\n useEffect(() => {\n if (!open) return\n generation.current += 1\n const mine = generation.current\n const timer = setTimeout(() => {\n void (async () => {\n const answer = await props.plan(task)\n if (generation.current !== mine) return\n if (!answer.ok) { setError({ code: answer.code, message: answer.message }); setPlan(null); return }\n setError(null)\n setPlan(answer.value)\n setFinalText(answer.value.prompt ?? '')\n const config = answer.value.config\n setSelectedRoute(config === undefined ? '' : JSON.stringify([config.provider, config.model]))\n // Start from the selected model's own default; never carry an explicit source effort by accident.\n setSelectedEffort('')\n })()\n }, 220)\n return () => { clearTimeout(timer) }\n }, [open, task, props.plan])\n\n const catalog = props.models ?? []\n const currentConfig = plan?.config\n const hasCurrent = currentConfig !== undefined && catalog.some(model =>\n model.provider === currentConfig.provider && model.model === currentConfig.model)\n const availableModels = currentConfig !== undefined && !hasCurrent\n ? [{\n provider: currentConfig.provider, providerName: currentConfig.provider,\n model: currentConfig.model, modelName: currentConfig.model, efforts: [],\n }, ...catalog]\n : catalog\n const selectedModel = availableModels.find(model => JSON.stringify([model.provider, model.model]) === selectedRoute)\n const legacyPlan = plan !== null && plan.config === undefined\n const finalBytes = new TextEncoder().encode(finalText).byteLength\n const refused = plan !== null && (plan.refusal !== null || finalText.trim() === '' || (!legacyPlan && selectedModel === undefined))\n const confirm = useCallback(() => {\n if (busy || plan === null || refused) return\n setBusy(true)\n setError(null)\n startGeneration.current += 1\n const mine = startGeneration.current\n void (async () => {\n if (!legacyPlan && selectedModel === undefined) return\n const selectedConfig = selectedModel === undefined ? undefined : {\n provider: selectedModel.provider,\n model: selectedModel.model,\n ...(selectedEffort === '' ? {} : { reasoningEffort: selectedEffort }),\n }\n const answer = legacyPlan\n ? await props.start(task, plan.draftRevision)\n : await props.start(task, plan.draftRevision, finalText, selectedConfig)\n if (startGeneration.current !== mine) return\n setBusy(false)\n if (!answer.ok) { setError({ code: answer.code, message: answer.message }); return }\n // The child is visible in the card's live index; do not replace the\n // confirmation with a second success screen that hides that outcome.\n close()\n })()\n }, [busy, close, finalText, legacyPlan, plan, refused, selectedEffort, selectedModel, props.start, task])\n\n // ⚠️ 口径跟 demo(`renderOrch()` 的 `state === 'running' || state === 'idle'`):\n // 「活跃」= **在场的子会话**(运行中 + 空闲),**不是**\"只有正在跑的\" ——\n // 2026-10-07 真机读数时发现我们原先少算了一半(只在 `open` 为真时计数)。\n const active = props.rows.filter(row => row.live === true).length\n // Ordinary carrier sessions are root sessions and do not consume Agent Team member capacity.\n const scale = t('child.bmeta', { a: active, n: props.rows.length })\n const errKey = error === null ? null : `redline.err.${error.code.replace('redline/', '')}`\n const errText = error === null ? null : error.code === 'redline/internal' && error.message !== ''\n ? `${t(errKey ?? 'redline.err.internal')}:${error.message}`\n : t(errKey ?? 'redline.err.internal')\n\n return h('div', { className: 'redline-card', 'data-redline-card': 'child' },\n h('div', { className: 'redline-card-title' },\n h('div', { className: 'redline-orch-titles' },\n h('div', { className: 'redline-orch-title-row' },\n h('span', { className: 'redline-card-title-text' }, t('child.title')),\n ),\n ),\n h('div', { className: 'redline-orch-metrics' },\n h('span', { className: 'redline-card-scale redline-orch-metric' }, scale),\n ),\n ),\n\n h('section', { className: 'redline-orch-launch', 'data-redline-block': 'spawn' },\n h('div', { className: 'redline-orch-copy' },\n h('div', { className: 'redline-orch-launch-row' },\n h('h3', { className: 'redline-orch-launch-title' }, t('child.spawn.head')),\n h('span', { className: 'redline-orch-launch-hint' }, t('child.spawn.hint')),\n ),\n h('p', { className: 'redline-orch-launch-note' }, t('child.spawn.note')),\n blockedKey !== null ? h('p', { className: 'redline-orch-launch-note' }, t(blockedKey)) : null,\n ),\n h('button', {\n type: 'button',\n className: 'redline-orch-open',\n 'data-redline-spawn': '1',\n disabled: blockedKey !== null,\n onClick: () => { setTask(''); setOpen(true) },\n }, t('child.spawn.button')),\n ),\n\n h('section', { 'data-redline-block': 'children' },\n h('div', { className: 'redline-orch-listhead' },\n h('span', null, t('child.list.head')),\n h('span', null, t('child.list.hint'))),\n props.originsError === undefined || props.originsError === null\n ? null\n : h('div', { className: 'redline-cap', 'data-redline-origins-error': props.originsError },\n t('redline.err.' + props.originsError.replace('redline/', ''))),\n props.rows.length === 0\n ? h('div', { className: 'redline-orch-empty' }, t('child.empty'))\n : h('div', { className: 'redline-orch-list' }, props.rows.map((row) => {\n const state = stateOf(row)\n const clock = clockOf(row.createdAt)\n return h('div', { className: 'redline-orch-row', key: row.id, 'data-redline-child': row.id },\n h('div', { className: 'redline-orch-main' },\n // 方形图标位(v0 的 `.sessionCardAvatar`):纯装饰,不承载文案。\n h('span', { className: 'redline-orch-avatar', 'aria-hidden': 'true' }, '↗'),\n h('div', { className: 'redline-orch-content' },\n h('div', { className: 'redline-orch-id' },\n h('span', { className: 'redline-snapid' }, row.short),\n h('span', { className: 'redline-chip-soft' }, t('child.mode.' + row.mode)),\n // 来源(M5-12):三态各自一句 —— 台账里有说是哪条路;没有说\"不是在这儿开的\";\n // 台账读不出来说\"来源未知\"。**不猜**(官方目录里没有来源字段,docs/01 F59)。\n (() => {\n const known = row.via === 'ordinary-session' || props.originsKnown !== false\n const tone = !known ? 'unknown' : row.via == null ? 'other' : 'own'\n const key = !known\n ? 'child.src.unknown'\n : row.via === 'ordinary-session' ? 'child.src.own.carrier'\n : row.via === 'official-member' ? 'child.src.own.official'\n : row.via === 'bare-child' ? 'child.src.own.bare' : 'child.src.other'\n return h('span', { className: 'redline-src redline-src-' + tone, 'data-redline-src': tone, title: t('child.src.tip') }, t(key))\n })(),\n clock === null ? null : h('span', { className: 'redline-orch-clock' }, clock),\n ),\n row.label === '' ? null : h('p', { className: 'redline-orch-note' }, row.label),\n h('span', { className: 'redline-orch-subnote' }, t(state.hint)),\n ),\n ),\n // 状态胶囊靠右(v0 的 `.sessionStatus`)。\n h('span', { className: 'redline-badge-state' + (state.tone === 'run' ? ' redline-badge-state-run' : '') },\n h('i', { className: 'redline-mstat redline-mstat-' + state.tone }),\n t(state.key)),\n )\n })),\n ),\n\n open\n ? h('div', {\n className: 'redline-modal-backdrop',\n onMouseDown: (event: { target: unknown; currentTarget: unknown }) => {\n if (event.target === event.currentTarget) close()\n },\n }, h('div', { className: 'redline-modal-card', role: 'dialog', 'aria-modal': 'true', 'data-redline-confirm': '1' },\n // 结构照抄 v0 定稿:固定标题栏 → 只有中间可滚 → 固定底栏。\n h('div', { className: 'redline-modal-head' },\n h('h2', { className: 'redline-modal-title' }, t('child.confirm.title')),\n h('button', { type: 'button', className: 'redline-modal-close', onClick: close }, '×'),\n ),\n h('div', { className: 'redline-confirm-body' },\n h('p', { className: 'redline-confirm-intro' }, t('child.confirm.intro')),\n plan === null\n ? h('div', { className: 'redline-cap' }, t('child.confirm.preparing'))\n : h('div', { className: 'redline-confirm-summary' },\n plan.items.filter(item => item.label !== '新会话配置与回程').map(item => h('div', { key: item.label },\n h('strong', null, item.label + ':'),\n h('span', null, item.text))),\n plan.metrics === null || typeof plan.metrics.bytes !== 'number'\n ? null\n : h('div', { 'data-redline-first-task': String(finalBytes) },\n t('child.confirm.metrics', { bytes: finalBytes, edits: plan.metrics.edits }))),\n // 空任务时宿主会拒绝(`redline/empty-task`):按钮禁用即可,**不再把那句拒绝话术打在弹窗里**\n // (用户 2026-10-08:「子会话的第一句话必须由你自己写……可以去掉」)。\n // 拒绝这件事仍然可观测(`data-redline-refusal` 挂在任务块上),只是不再占版面。\n h('label', {\n className: 'redline-confirm-task',\n ...(plan !== null && plan.refusal !== null ? { 'data-redline-refusal': plan.refusal.code } : {}),\n },\n h('span', { className: 'redline-confirm-task-label' }, t('child.confirm.taskLabel')),\n h('span', { className: 'redline-confirm-task-hint' }, t('child.confirm.taskHint')),\n h('textarea', {\n rows: 3,\n 'data-redline-task': '1',\n placeholder: t('child.confirm.taskPlaceholder'),\n value: task,\n onChange: (event: ChangeEvent<HTMLTextAreaElement>) => {\n generation.current += 1\n setTask(event.target.value)\n setPlan(null)\n setFinalText('')\n setSelectedRoute('')\n setSelectedEffort('')\n setError(null)\n },\n })),\n h(CarrierSelectionBar, {\n models: availableModels,\n selectedRoute,\n selectedEffort,\n t,\n onRoute: (route: string) => {\n setSelectedRoute(route)\n setSelectedEffort('')\n },\n onEffort: (effort: string) => { setSelectedEffort(effort) },\n }),\n h('label', { className: 'redline-confirm-task redline-confirm-final' },\n h('span', { className: 'redline-confirm-task-label' }, t('child.confirm.finalLabel')),\n h('span', { className: 'redline-confirm-task-hint' }, t('child.confirm.finalHint')),\n h('textarea', {\n rows: 6,\n 'data-redline-final': '1',\n value: finalText,\n onChange: (event: ChangeEvent<HTMLTextAreaElement>) => { setFinalText(event.target.value) },\n })),\n errText !== null ? h('div', { className: 'redline-editor-err', role: 'alert' }, errText) : null,\n ),\n h('div', { className: 'redline-modal-foot' },\n h('button', { type: 'button', className: 'redline-confirm-btn redline-confirm-btn-cancel', onClick: close }, t('child.confirm.cancel')),\n h('button', {\n type: 'button',\n className: 'redline-confirm-btn redline-confirm-btn-ok',\n 'data-redline-confirm-ok': '1',\n disabled: busy || plan === null || refused,\n onClick: confirm,\n }, t('child.confirm.ok')),\n ),\n ))\n : null,\n\n )\n }\n}\n","/**\n * Glyphs: inject/model-switch reuse the harness's shared icon set (`@deepseek-ai/dsh-client-ui-primitives`, a platform seed word);\n * compaction/prune keep the ✂ marker — no shared glyph exists for it.\n */\n\nimport { useEffect, useLayoutEffect, useRef, type ReactElement } from 'react'\nimport type { ContextEventRecord } from '../../shared/types'\nimport { IconBranch, IconPlus } from '../primitives'\nimport type { Translate } from '../i18n'\nimport type { DetailState } from '../timelineSource'\nimport type { ViewKit } from '../viewkit'\nimport { makeDetailNote } from './detailNote'\n\nconst EVENT_ICONS: Record<string, string> = { compaction: '✂', prune: '✂', inject: '+', model: '⇄', mode: '⇄' }\n\nexport interface EventListProps {\n events: ContextEventRecord[]\n /**\n * The timeline source's detail state (split generation): with no events to\n * list, `loading`/`failed` replace the empty claim with the pending note /\n * retry button — an un-fetched list is not an empty one.\n */\n state?: DetailState\n onRetry?: () => void\n}\n\nexport function makeEventText(t: Translate): {\n eventLabel: (ev: ContextEventRecord) => string\n eventAt: (ev: ContextEventRecord) => string | null\n} {\n function eventLabel(ev: ContextEventRecord): string {\n if (ev.kind === 'compaction') return t('ev.compaction', { n: ev.count || 0 })\n if (ev.kind === 'prune') return t('ev.prune')\n if (ev.kind === 'model') return t('ev.model', { a: ev.from || '?', b: ev.to || '?' })\n if (ev.kind === 'mode') return t('ev.mode.' + (ev.name || '?'))\n // The kind union narrows to 'inject' here; a future kind breaks the\n // compile (ev.sub ev.form ev.name are inject-only), forcing a label.\n if (ev.sub === 'skill') return t('ev.skill', { name: ev.name || '?' })\n const base = t('form.' + (ev.form || 'context'))\n let label = ev.name ? base + ' · ' + ev.name : base\n if (ev.detail) label += ' · ' + ev.detail\n return label\n }\n\n /**\n * Where this event sits in the timeline: boundary events (compaction/prune) label the GAP they sit in — same-turn 'Turn 2 · Step 3→4',\n * cross-turn 'Turn 50 · Step 8 → Turn 51 · Step 1'; other kinds keep their single point; no turn/step (in flight) → null.\n */\n function eventAt(ev: ContextEventRecord): string | null {\n if (ev.kind === 'compaction' || ev.kind === 'prune') {\n if (typeof ev.turn === 'number' && typeof ev.step === 'number') {\n if (typeof ev.fromTurn === 'number' && typeof ev.fromStep === 'number') {\n if (ev.fromTurn === ev.turn) return t('events.range', { t: ev.turn, a: ev.fromStep, b: ev.step })\n return t('events.rangeTo', { a: ev.fromTurn, as: ev.fromStep, b: ev.turn, bs: ev.step })\n }\n return t('events.at', { t: ev.turn, s: ev.step })\n }\n return null\n }\n if (typeof ev.turn === 'number' && typeof ev.step === 'number') {\n return t('events.at', { t: ev.turn, s: ev.step })\n }\n return null\n }\n\n return { eventLabel, eventAt }\n}\n\n/**\n * Set the native `title` on every label whose text overflows its box (the styled tips cover cards, but a plain\n * ellipsis row still needs the native fallback); reads (scrollWidth/clientWidth) and writes (title) stay separate\n * from layout-affecting work, and callers gate WHEN this runs so it never becomes a per-render forced layout.\n */\nfunction syncTitles(root: HTMLElement): void {\n for (const el of root.querySelectorAll<HTMLElement>('.redline-event-label')) {\n el.title = el.scrollWidth > el.clientWidth ? el.textContent || '' : ''\n }\n}\n\nexport function makeEventList(kit: ViewKit): (props: EventListProps) => ReactElement {\n const { t, fmt, fmtTime, eventLabel, eventAt } = kit\n const DetailNote = makeDetailNote(kit)\n return function EventList(props: EventListProps): ReactElement {\n // Hooks stay unconditional (Rules of Hooks): events going empty ->\n // non-empty in one mounted instance must not grow the hook count — an\n // early return above these hooks is a React #310 class bug (issue #12).\n const rootRef = useRef<HTMLDivElement | null>(null)\n // Truncation titles ride a resize-only listener plus an events-driven resync: the effect MUST NOT run\n // on every render — a plain re-render (hover/select elsewhere in the view) would re-read scrollWidth /\n // clientWidth for every label, one forced synchronous layout per row, and rebind the listener.\n useLayoutEffect(() => {\n const root = rootRef.current\n if (!root) return\n syncTitles(root)\n }, [props.events])\n useEffect(() => {\n const onResize = (): void => {\n const root = rootRef.current\n if (root !== null) syncTitles(root)\n }\n window.addEventListener('resize', onResize)\n return () => { window.removeEventListener('resize', onResize) }\n }, [])\n if (props.events.length === 0) {\n if (props.state === 'loading') return <DetailNote state=\"loading\" />\n if (props.state === 'failed' && props.onRetry !== undefined) {\n return <DetailNote state=\"failed\" onRetry={props.onRetry} />\n }\n return <div className=\"redline-empty\">{t('events.empty')}</div>\n }\n const sorted = props.events.slice().reverse()\n return (\n <div className=\"redline-events\" ref={rootRef}>\n {sorted.map((ev) => {\n const label = eventLabel(ev)\n const at = eventAt(ev)\n const glyph = ev.kind === 'inject' ? <IconPlus />\n : ev.kind === 'model' ? <IconBranch />\n : EVENT_ICONS[ev.kind] || '•'\n // Key on the durable seq alone: the list renders newest-first, so a fresh event lands at index 0\n // and an index-bearing key would shift EVERY existing row's key — a full-list remount on every push.\n // Narrow cards (phone panes): the single-line row would crush the label and push the meta\n // tail into a scrollbar, so the row wraps — the label's near-full-width basis keeps line 1\n // to icon + kind + label, and the meta tail folds onto line 2. The 92px basis reservation\n // covers icon + gap + the widest kind chip (both locales) + gap.\n return (\n <div key={ev.seq} className=\"redline-event @max-[380px]/redline-card:flex-wrap\">\n <span className={'redline-event-icon redline-event-' + ev.kind}>{glyph}</span>\n <span className={'redline-kind redline-kind-' + ev.kind}>{t('kind.' + ev.kind)}</span>\n <span className=\"redline-event-label flex-1 @max-[380px]/redline-card:basis-[calc(100%-92px)]\">{label}</span>\n {at !== null ? <span className=\"redline-event-at\">{at}</span> : null}\n {ev.tokens ? (\n <span className={'redline-event-tokens' + (ev.kind === 'inject' ? ' redline-up' : ' redline-down')}>\n {(ev.kind === 'inject' ? '+' : '−') + fmt(ev.tokens)}\n </span>\n ) : null}\n <span className=\"redline-event-time\">{fmtTime(ev.time)}</span>\n </div>\n )\n })}\n </div>\n )\n }\n}\n","/**\n * The baseline-gate modal: when the host reports the running harness below\n * the supported baseline (the `unsupported` record on the pushed\n * `redlineTimeline` value — see host/fallback.ts), the Context tab keeps\n * rendering its (zeroed) cards and this centered dialog names the detected\n * harness version against the required minimum and urges the upgrade.\n *\n * Dismissal is remembered per session in a module-level ledger: tab remounts\n * do not re-pop it, while a fresh app launch does — the gate stays visible\n * until the harness is actually updated.\n */\n\nimport { useCallback, useState, type ReactElement } from 'react'\nimport type { ViewKit } from '../viewkit'\nimport { useEscapeClose } from './escapeClose'\n\n/** Sessions whose gate the user already dismissed this browser session. */\nconst dismissed = new Set<string>()\n\nexport interface UpgradeGateProps {\n sessionId?: string\n /** The detected harness version (displayed verbatim, already re-proved). */\n current: string\n /** The plugin's minimum supported baseline. */\n minimum: string\n}\n\nexport function makeUpgradeGate(kit: ViewKit): (props: UpgradeGateProps) => ReactElement | null {\n const { t } = kit\n return function UpgradeGate(props: UpgradeGateProps): ReactElement | null {\n const sessionId = typeof props.sessionId === 'string' ? props.sessionId : ''\n // `closedFor` re-renders on dismiss within one mount; the ledger covers\n // remounts and in-place session switches.\n const [closedFor, setClosedFor] = useState<string | null>(null)\n const closed = closedFor === sessionId || dismissed.has(sessionId)\n const close = useCallback(() => {\n dismissed.add(sessionId)\n setClosedFor(sessionId)\n }, [sessionId])\n\n // Same overlay contract as the /redline modal (escapeClose.ts):\n // capture-phase Escape, and focus returns to the pre-open element.\n useEscapeClose(!closed, close)\n\n if (closed) return null\n\n return (\n <div className=\"redline-modal-backdrop\" onClick={close}>\n <div className=\"redline-modal-card redline-gate-card\" onClick={(ev) => { ev.stopPropagation() }}>\n <div className=\"redline-modal-head\">\n <span className=\"redline-modal-title\">{t('gate.title')}</span>\n <button className=\"redline-modal-close hover:text-(--dsw-alias-label-primary) hover:bg-(--dsw-alias-bg-layer-2)\" aria-label={t('cmd.close')} onClick={close}>×</button>\n </div>\n <div className=\"redline-gate-body\">{t('gate.body', { minimum: props.minimum })}</div>\n <div className=\"redline-gate-versions\">\n <span className=\"redline-gate-version\">\n <span className=\"redline-gate-version-label\">{t('gate.current')}</span>\n <span className=\"redline-gate-version-value\">v{props.current}</span>\n </span>\n <span className=\"redline-gate-version\">\n <span className=\"redline-gate-version-label\">{t('gate.minimum')}</span>\n <span className=\"redline-gate-version-value\">\n v{props.minimum}\n <span className=\"redline-gate-or-newer\">{t('gate.orNewer')}</span>\n </span>\n </span>\n </div>\n <div className=\"redline-gate-actions\">\n <button type=\"button\" className=\"redline-gate-ok hover:brightness-110\" onClick={close}>{t('gate.ok')}</button>\n </div>\n </div>\n </div>\n )\n }\n}\n","import { memo, type ComponentType, type MouseEvent, type ReactElement, type ReactNode } from 'react'\nimport type { ContextEventRecord, RequestRecord, SurfaceNode } from '../../shared/types'\nimport { partsOf, CATS } from '../categories'\nimport { cacheHitPercent } from '../format'\nimport type { StepBrief } from '../brief'\nimport { blockSummaryOf, callNamesOf, callSummaryOf } from '../callSummary'\nimport type { ConversationNodeLike } from '../services'\nimport type { StackedBarProps } from './stackedBar'\nimport type { ViewKit } from '../viewkit'\n\nexport interface RequestDetailProps {\n request: RequestRecord | null\n /**\n * Delta mode: the record displayed just before this one (null on the first\n * bar). Its PRESENCE switches the panel from cumulative makeup to the signed\n * change against that previous record — the same pairing the chart's\n * deltaOf plots.\n */\n prev?: RequestRecord | null\n marker?: ContextEventRecord | null\n /** The step's semantic identity (turn opener / inputs / reply) — see brief.ts; null renders an empty reserved lane. */\n brief?: StepBrief | null\n /** Conversation-snapshot join for call-argument enrichment; absent join = names only, never an error. */\n convOf?: (seq: number) => ConversationNodeLike | undefined\n /**\n * Per-turn step totals (the parent's `turnStepsOf` over the served requests) behind the head's\n * step-of-total figure; absent = a 1-step turn.\n */\n stepsOf?: (turn: number | undefined) => number\n /** Reveal a brief row's node in the Context browser; absent = rows render inert. */\n onLocate?: (node: SurfaceNode, isResponse: boolean) => void\n /**\n * Mirrored category hover (shared with the overview/browser): lights the composition bar's matching\n * segment; the bar never reports hovers back.\n */\n hoverKey?: string | null\n}\n\nexport function makeRequestDetail(\n kit: ViewKit,\n StackedBar: (props: StackedBarProps) => ReactElement,\n): ComponentType<RequestDetailProps> {\n const { t, fmt, fmtTime, catLabel, eventLabel, eventAt } = kit\n\n /**\n * One brief row: a fixed-width kind tag plus one glanceable line. The tag carries a styled, instant explanation bubble (the\n * shared `.redline-tip` chrome); the content span keeps the native title (preview + locate hint), so the two never stack.\n * Clickable when the browser linkage is wired AND the row carries a node (the always-present In row's empty state stays inert).\n */\n function BriefRow(props: {\n tag: string\n tagTip: string\n /** Absent only on the empty-state In row — a row without a node cannot be located. */\n node?: SurfaceNode\n isResponse: boolean\n onLocate?: (node: SurfaceNode, isResponse: boolean) => void\n children: ReactNode\n }): ReactElement {\n const inner = (\n <>\n <span className=\"redline-brief-tag group/tip\">\n {props.tag}\n <span className=\"redline-tip redline-brief-tip group-hover/tip:opacity-100\" role=\"tooltip\">{props.tagTip}</span>\n </span>\n {props.children}\n </>\n )\n if (props.node === undefined || props.onLocate === undefined) return <div className=\"redline-brief-row\">{inner}</div>\n const node = props.node\n const onLocate = props.onLocate\n const locate = (): void => { onLocate(node, props.isResponse) }\n return (\n <button type=\"button\" className=\"redline-brief-row redline-brief-row-link hover:bg-(--dsw-alias-interactive-bg-hover)\" onClick={locate}>\n {inner}\n </button>\n )\n }\n\n /**\n * One line's anatomy — a compact FACT tag plus the preview text, mirroring the Context browser's element rows so a\n * brief line reads exactly like the browser row its click reveals: tool results tag the tool name, skill content\n * the skill name, assistant replies the call breadcrumb, injections the form, user messages image attachments.\n * The branches cover the Category union; a hostile cat degrades into the\n * user tail — a plain text row, never a throw.\n */\n function chipParts(n: SurfaceNode, conv: ConversationNodeLike | undefined): { tag: string | null; text: string } {\n if (n.cat === 'tool') {\n const summary = callSummaryOf(conv)\n if (n.tool !== undefined) return { tag: n.tool, text: summary ?? '' }\n return { tag: null, text: summary ?? t('node.toolResult') }\n }\n if (n.cat === 'skill') {\n // Skill content (issue #66): a load/invocation tags its NAME, the\n // catalog digest its form label ('目录更新'). A text-less row (the\n // `skill`-tool load — its content rode the tool result) previews the\n // call summary, like the tool rows do.\n return {\n tag: n.skill !== undefined ? t('node.skillTag', { name: n.skill }) : t('form.' + (n.form ?? 'context')),\n text: n.text ?? callSummaryOf(conv) ?? '',\n }\n }\n if (n.cat === 'assistant') {\n // The fold's surface node keeps `calls` only for TEXT-LESS replies; a reply carrying both text and calls recovers\n // its call breadcrumb through the conversation join.\n const names = n.calls !== undefined && n.calls.length > 0 ? n.calls : callNamesOf(conv)\n const own = n.text !== undefined && n.text !== '' ? n.text : blockSummaryOf(conv) ?? ''\n return {\n tag: names.length > 0 ? names.join(' › ') : null,\n text: own !== '' ? own : (names.length > 0 ? '' : t('node.empty')),\n }\n }\n if (n.cat === 'inject') {\n const text = n.text !== undefined && n.text !== ''\n ? (n.form === 'snapshot' ? t('node.snapshot') + n.text : n.text)\n : ''\n return { tag: t('form.' + (n.form ?? 'context')), text }\n }\n // The user tail (or a hostile cat): image uploads gain an Image chip.\n const imgs = n.imgs ?? 0\n return {\n tag: imgs > 0 ? t('attach.image') + (imgs > 1 ? ' ×' + String(imgs) : '') : null,\n text: n.text ?? '',\n }\n }\n\n /** The native-title line for a fact+text pair: 'tag · text', degrading to whichever half exists. */\n function factTitle(tag: string | null, text: string): string {\n return tag !== null ? (text !== '' ? tag + ' · ' + text : tag) : text\n }\n\n /**\n * The brief's container ALWAYS renders — a fixed three-row lane (`.redline-brief`'s min-height) so scrubbing the chart never\n * changes the panel's height; unknown or empty steps just leave parts of the lane blank instead of collapsing it.\n */\n function BriefSection(props: {\n brief: StepBrief | null | undefined\n convOf?: (seq: number) => ConversationNodeLike | undefined\n onLocate?: (node: SurfaceNode, isResponse: boolean) => void\n }): ReactElement {\n const { opener, inputs, response } = props.brief ?? { inputs: [] }\n const convOf = props.convOf ?? (() => undefined)\n // The content span's native title: full preview, plus the locate hint when the row is clickable.\n const hint = props.onLocate !== undefined ? ' — ' + t('brief.locate') : ''\n // Chip click: locate THIS chip's node; stopPropagation keeps it from also firing the row's own locate.\n const locateChip = props.onLocate === undefined ? undefined : (n: SurfaceNode) =>\n (e?: MouseEvent) => { e?.stopPropagation(); props.onLocate?.(n, false) }\n const MAX_CHIPS = 3\n /**\n * The ONE content unit of the brief — inputs and the reply share the same chip anatomy (error dot, fact tag,\n * preview text). Input chips are compact and individually clickable (each locates its own node); the reply is a\n * single chip grown to the row's width, left inert because the row button already locates it.\n */\n const nodeChip = (n: SurfaceNode, onClick?: (e?: MouseEvent) => void, grow = false): ReactElement => {\n const { tag, text } = chipParts(n, convOf(n.seq))\n return (\n <span\n key={n.seq}\n className={'redline-brief-chip' + (grow ? ' redline-brief-chip-grow' : '') + (onClick !== undefined ? ' redline-brief-chip-link hover:bg-(--dsw-alias-interactive-bg-hover)' : '')}\n title={factTitle(tag, text) + hint}\n onClick={onClick}\n >\n {n.err === true ? <span className=\"redline-br-err-dot\" /> : null}\n {tag !== null ? <span className=\"redline-brief-chip-tag\">{tag}</span> : null}\n {text !== '' ? <span className=\"redline-brief-chip-text\">{text}</span> : null}\n </span>\n )\n }\n const openerParts = opener !== undefined ? chipParts(opener, convOf(opener.seq)) : null\n return (\n <div className=\"redline-brief\">\n {opener !== undefined && openerParts !== null ? (\n <BriefRow tag={t('brief.turn')} tagTip={t('brief.turnTip')} node={opener} isResponse={false} onLocate={props.onLocate}>\n {openerParts.tag !== null ? <span className=\"redline-brief-fact\">{openerParts.tag}</span> : null}\n {openerParts.text !== '' ? (\n <span className=\"redline-brief-text\" title={factTitle(openerParts.tag, openerParts.text) + hint}>{openerParts.text}</span>\n ) : null}\n </BriefRow>\n ) : null}\n {/* The In row ALWAYS renders (empty state included): a turn's opening step has no inputs, and a constant row\n count keeps the panel height steady while the chart scrubs. Without a node the row renders inert. */}\n <BriefRow tag={t('brief.input')} tagTip={t('brief.inputTip')} node={inputs[0]} isResponse={false} onLocate={props.onLocate}>\n {inputs.length > 0 ? (\n <>\n {/* Whole-row clickable like the other rows (locates the FIRST input); each chip still locates its own node —\n stopPropagation keeps a chip click from also firing the row's. */}\n {inputs.slice(0, MAX_CHIPS).map(n => nodeChip(n, locateChip?.(n)))}\n {inputs.length > MAX_CHIPS ? <span className=\"redline-brief-more\">{t('brief.more', { n: inputs.length - MAX_CHIPS })}</span> : null}\n </>\n ) : (\n <span className=\"redline-brief-empty\">{t('brief.noInputs')}</span>\n )}\n </BriefRow>\n {response !== undefined ? (\n <BriefRow tag={t('brief.reply')} tagTip={t('brief.replyTip')} node={response} isResponse onLocate={props.onLocate}>\n {nodeChip(response, undefined, true)}\n </BriefRow>\n ) : null}\n </div>\n )\n }\n\n // Memoized at the factory level: the parent hands reference-stable request/prev/marker/brief/convOf/onLocate\n // across hover/select renders (see contextView), so the panel skips reconciliation when the active bar did not move.\n return memo(function RequestDetail(props: RequestDetailProps): ReactElement | null {\n const req = props.request\n if (!req) return null\n const isTurn = req.stepCount !== undefined && req.stepCount > 1\n const head = isTurn\n ? t('detail.turn', {\n t: req.turn ?? 0,\n /* v8 ignore next -- isTurn already guarantees stepCount !== undefined;\n the fallback is defensive. */\n n: req.stepCount ?? 0,\n })\n : t('detail.step', { t: req.turn ?? 0, s: req.step ?? 0, n: props.stepsOf?.(req.turn) ?? 1 })\n // When this bar carries a boundary event (compaction/prune), the header\n // also shows WHERE the event happened: the gap between the request\n // before and the request after (e.g. \"✂ Turn 49 · Step 2→3\").\n const marker = props.marker ?? null\n const markerAt = marker !== null ? eventAt(marker) : null\n // Delta mode: per-category SIGNED change vs the previous record (the chart stacks them diverging\n // above/below its zero line); provider usage chips drop out — prompt/output/cacheRead are\n // per-request figures, not deltas.\n const delta = props.prev !== undefined\n const prev = props.prev ?? null\n const deltas = CATS.map(c => delta ? (req[c.key] || 0) - (prev !== null ? prev[c.key] || 0 : 0) : 0)\n let net = 0\n let maxAbs = 0\n if (delta) {\n for (const d of deltas) {\n net += d\n if (Math.abs(d) > maxAbs) maxAbs = Math.abs(d)\n }\n }\n const parts = delta\n ? CATS.map((c, i) => ({ key: c.key, color: c.color, value: Math.abs(deltas[i]) }))\n : partsOf(req)\n return (\n <div className=\"redline-detail\">\n <div className=\"redline-detail-head\">\n <b>{head}</b>\n {marker !== null && markerAt !== null\n ? <span className=\"redline-detail-marker\" title={eventLabel(marker)}>{'✂ ' + markerAt}</span>\n : null}\n {isTurn ? <span className=\"redline-detail-tag\">{t('detail.lastStep')}</span> : null}\n {delta ? <span className=\"redline-detail-tag\">{t('gran.delta')}</span> : null}\n <span className=\"redline-detail-time\">{fmtTime(req.time)}</span>\n {/* Metric chips: one neutral pill per provider figure; the cache figure drops out on hosts\n that do not fold `cacheRead` (and on usage-less requests). */}\n {delta ? (\n <span className={'redline-detail-metric' + (net > 0 ? ' redline-detail-metric-up' : net < 0 ? ' redline-detail-metric-down' : '')}>\n {t('tip.delta', { n: (net > 0 ? '+' : '') + fmt(net) })}\n </span>\n ) : null}\n {!delta && req.prompt !== undefined\n ? <span className=\"redline-detail-metric\">{t('detail.actual', { n: fmt(req.prompt) })}</span>\n : null}\n {!delta && req.output !== undefined\n ? <span className=\"redline-detail-metric\">{t('detail.output', { n: fmt(req.output) })}</span>\n : null}\n {!delta && req.prompt !== undefined && req.cacheRead !== undefined\n ? <span className=\"redline-detail-metric\">{t('detail.cache', { n: cacheHitPercent(req.cacheRead, req.prompt) ?? '—' })}</span>\n : null}\n </div>\n <BriefSection brief={props.brief} convOf={props.convOf} onLocate={props.onLocate} />\n {/* Mirrors the shared category hover with the tip off — a cross-card hover must not float a second tooltip\n over a bar the pointer does not rest on (same rule as the browser's own bar). */}\n <StackedBar parts={parts} height={10} hoverKey={props.hoverKey} tip={false} />\n <div className=\"redline-detail-rows\">\n {CATS.map((c, i) => {\n const v = delta ? deltas[i] : req[c.key] || 0\n const mag = Math.abs(v)\n return (\n <div key={c.key} className={'redline-detail-row' + (props.hoverKey === c.key ? ' redline-detail-row-on' : '')}>\n <i style={{ background: c.color }} />\n <span className=\"redline-detail-label\">{catLabel(c.key)}</span>\n <span className=\"redline-bar-track\">\n {delta ? (\n <>\n {/* Mini diverging bar echoing the chart: zero at the middle, growth fills right,\n shrinkage fills left, one shared scale across the rows. */}\n <span className=\"redline-bar-zero\" />\n {v !== 0 ? (\n <span\n className={'redline-bar-fill ' + (v > 0 ? 'redline-bar-fill-up' : 'redline-bar-fill-down')}\n style={{ width: `${mag / maxAbs * 50}%`, background: c.color }}\n />\n ) : null}\n </>\n ) : (\n <span className=\"redline-bar-fill\" style={{ width: `${req.total > 0 ? v / req.total * 100 : 0}%`, background: c.color }} />\n )}\n </span>\n {delta ? (\n <span className={'redline-detail-num' + (v > 0 ? ' redline-detail-num-up' : v < 0 ? ' redline-detail-num-down' : '')}>\n {(v > 0 ? '+' : '') + fmt(v)}\n </span>\n ) : (\n <span className=\"redline-detail-num\">{'≈' + fmt(v)}</span>\n )}\n <span className=\"redline-detail-pct\">{!delta && req.total > 0 ? `${Math.round(v / req.total * 100)}%` : ''}</span>\n </div>\n )\n })}\n </div>\n </div>\n )\n })\n}\n","/**\n * The Context card: what the session's context IS and how it evolved — a\n * seven-cell grid of the session's shape (turns / steps / human inputs /\n * live tool calls), the whole-session cache-hit rate, and the cost estimate\n * at two scopes: the family total (the current agent plus every subagent\n * session) and the subagents' own share.\n * Count figures only: nothing here is part of a spendable whole, so no pie —\n * proportions live in the composition card, and the context-event tallies\n * live on the events card's kind filters (contextView.tsx). The cache-hit\n * cell reads the official `tokenUsage` projection — the same source and\n * formula as the harness chat stats line under the composer, shown with one\n * decimal — and dashes until a provider reports usage. The cost cells price\n * the host-folded cumulative billed totals (complete session logs, never\n * trimmed; the subagents' usage folds out of the session-list snapshot,\n * `makeSubagentCost` below) from the models.dev price book (modelPrices.ts)\n * in the locale's currency; their hover bubbles (a '?' marker + styled DOM\n * tip) explain each scope and list the per-1M-token rates of the models the\n * family actually billed, straight from the same book (cost.ts), so printed\n * rates can never drift from the math. A book that has not loaded (or\n * failed) dashes the cells and notes the outage.\n *\n * The counts arrive precomputed: the split-generation wire head carries them\n * (shared/types.ts `TimelineCounts` — computed over the retained records),\n * and the caller derives them from the collections on the inline generation\n * (`countsOfRecords`). The card itself never touches the collections.\n */\n\nimport type { ReactElement } from 'react'\nimport type { ContextEventRecord, RequestRecord, TimelineCounts } from '../../shared/types'\nimport { type StepStats } from '../assemble'\nimport type { ViewKit } from '../viewkit'\n\n\n/**\n * The inline generation's counter derivation — the exact tally the card ran\n * over the served collections before the split (distinct turn values, record\n * count, per-kind event tallies). The host's split-generation counts match\n * it by construction (fold.ts buildTimelineHead).\n */\nexport function countsOfRecords(requests: readonly RequestRecord[], events: readonly ContextEventRecord[]): TimelineCounts {\n const turns = new Set<number>()\n for (const req of requests) turns.add(req.turn ?? 0)\n let injects = 0\n let compactions = 0\n let prunes = 0\n for (const ev of events) {\n if (ev.kind === 'inject') injects++\n else if (ev.kind === 'compaction') compactions++\n else if (ev.kind === 'prune') prunes++\n }\n return { turns: turns.size, steps: requests.length, injects, compactions, prunes }\n}\n\n/**\n * 上下文统计卡 —— **3 格,跟 demo**(`docs/10` M4-07:用户 2026-10-06 裁定)。\n *\n * 卡片上只有 demo 确认过的那三格 + 标题里的当前视图与 `本步可见 N 条 · ≈X tokens`:\n * ① 模型可见条目(另 N 条被遮蔽)② 用户消息 ③ 注入内容。\n * 三个数字的口径由 `stepStatsOf()`(`src/client/assemble.ts`,纯函数 + 单测)从\n * **`assemble()` 已经算好的那一步列表**里直接数出来 —— 卡片不做任何二次判断。\n *\n * ⚠️ 与基线(上游 `dsh-context`)的**有意差异**:不再有 `轮次 / 步数 / 工具调用 / 缓存命中 / 费用 / 子 Agent 费用`\n * 六格读数。会话指认改由趋势卡标题 `按轮次(共 N 轮)` + 浏览器 meta `第 t 轮 · 第 s 步` 承担(`docs/10` M4-03);\n * 费用与缓存属于\"上下文洞察\"那套能力,不是本产品(批改台)的目标。\n * 费用/价格模块(`cost.ts` / `modelPrices.ts` / 本文件的 `makeSubagentCost`)**保留未删**,只是本卡不再引用。\n */\nexport function makeStatsContext(\n kit: ViewKit,\n): (props: {\n /** 该步的读数(`stepStatsOf` 的结果)。 */\n stats: StepStats\n /** 当前视图的轮次与步(live 时是最后一步)。 */\n turn?: number\n step?: number\n /** 正在看\"当前(下一次请求)\"而不是某条历史记录。 */\n live: boolean\n /**\n * 该步的列表数据到了没有(`timelineSource` 的 `detailState === 'ready'`)。\n * 没到就显示 `—`:三个数字都来自**该步的节点列表**,那是 detail 通道的产物,\n * 而 slim head 里只有 token 合计、没有条目数 —— 假装成 0 会等于在骗人。\n */\n ready: boolean\n}) => ReactElement {\n const { t, fmt } = kit\n return function StatsContext(props: {\n stats: StepStats\n turn?: number\n step?: number\n live: boolean\n ready: boolean\n }): ReactElement {\n const cell = (label: string, value: string | number): ReactElement => (\n <div className=\"redline-stat\">\n <span className=\"redline-stat-value\">{value}</span>\n <span className=\"redline-stat-label\">{label}</span>\n </div>\n )\n const { stats, ready } = props\n // 被遮蔽的条数只在真的有时才写出来(与 demo 的条件一致)。\n const shadowNote = ready && stats.shadowed > 0 ? t('stats.shadowedNote', { n: fmt(stats.shadowed) }) : ''\n const value = (n: number): string => (ready ? fmt(n) : '—')\n return (\n <div className=\"redline-card redline-col-stats\">\n <div className=\"redline-card-title\">\n <span className=\"redline-card-title-text\">{t('stats.title')}</span>\n <span className=\"redline-stat-hint\">\n {t('stats.viewHint', { t: props.turn ?? 0, s: props.step ?? 0 }) + (props.live ? t('stats.viewLive') : '')}\n </span>\n {ready\n ? <span className=\"redline-bmeta\">{t('stats.bmeta', { n: fmt(stats.listed), k: fmt(stats.tokens) })}</span>\n : null}\n {ready && stats.missingTokens > 0\n // S1.1:缺 token 时不许把 `≈N` 说成完整数字(那一格显示不了 `—`,就把缺的条数说出来)。\n ? <span className=\"redline-stat-hint\" data-redline-missing-tokens={String(stats.missingTokens)}>{t('stats.missing', { m: fmt(stats.missingTokens) })}</span>\n : null}\n </div>\n <div className=\"redline-stats\">\n {cell(t('stats.visibleItems') + shadowNote, value(stats.visible))}\n {cell(t('stats.userMsgs'), value(stats.user))}\n {cell(t('stats.injectItems'), value(stats.inject))}\n </div>\n </div>\n )\n }\n}\n","/**\n * The right Sidebar's Context tab (dsh 0.1.5-rc.1+).\n *\n * The tab reuses the Context conversation-view component VERBATIM: the\n * `sidebar.right.pane.tab` seat is session-scoped and delivers the same\n * framework standard kit (`sessionId`, `useProjection`, `useChat`, the locale\n * `t` seat) the `conversation.view` seat does, so the panel and the tab are\n * one component with one data path. The tab type contributes a guide entry, so\n * the sidebar's guide page offers \"Context\" and picking it opens the panel —\n * the product's own path, exactly as the shipped Files type does: a capsule of\n * glyph, title, and description line, plus the chip-title seat that puts the\n * same glyph beside the label once the tab is open (`icon.tsx`).\n *\n * OPTIONAL BY CONTRACT. `ctx.sidebarRightTabs` and the seat ship only on the\n * 0.1.5 line (0.1.5-rc.1+ supported); the registration therefore rides a\n * DEFERRED inject (the plugin's hard injects stay `slots` + `locale`), so on\n * every older supported line the callback never fires, the plugin fiber never\n * pends, and nothing is registered. The registry is re-proved structurally and\n * the whole registration is guarded: a foreign or hostile registry (a throwing\n * `register`, a taken id/kind) leaves the sidebar without the tab instead of\n * taking the browser down.\n *\n * @module dsh-context-redline/client/sidebar\n */\n\nimport { ContextIcon, makeContextTabTitle } from './icon'\nimport type { ClientCtx, ContextViewProps, SidebarTabsFace } from './services'\nimport type { Translate } from './i18n'\n\n/** The tab type's identity in the sidebar's tab system (also its body-seat key). */\nexport const SIDEBAR_CONTEXT_ID = 'dsh-context-redline'\n\n/**\n * The kind `openTab` names. Namespaced rather than the bare `context`: the\n * registry THROWS when a kind collides with another registration in a\n * non-coexisting band, and a foreign plugin may well own `context`.\n */\nexport const SIDEBAR_CONTEXT_KIND = 'dsh-context-redline'\n\n/** The guide capsule's position: after the shipped Files entry (order 10). */\nconst GUIDE_ORDER = 20\n\n/**\n * Register the Context tab type, its body, and its chip title on the right\n * Sidebar, if — and only if — this harness serves the sidebar tab registry.\n * @param ctx - client root context carrying `slots` and the locale service.\n * @param view - the Context view component factory result (the same one the\n * conversation tab mounts).\n * @param t - the plugin-namespace translate; the label thunks read the active\n * locale at call time, so a language switch relabels the guide entry.\n * @param ns - the plugin's locale namespace, put on the body registration so\n * the framework synthesizes the `t` seat for the panel too.\n * @returns the deferred inject's disposer (placement toggling calls it to\n * take the mount down; a no-op on faces that return no handle).\n */\nexport function watchSidebarContextTab(\n ctx: ClientCtx,\n view: (props: ContextViewProps) => unknown,\n t: Translate,\n ns: string,\n): () => void {\n // Deferred: a harness without the right Sidebar never fires this, and the\n // plugin is simply a conversation tab there — no pending fiber, no error.\n const fiber = ctx.inject(['sidebarRightTabs'], (raw) => {\n const injected = raw as unknown as ClientCtx & { sidebarRightTabs?: SidebarTabsFace }\n // Every registration that already landed, so a partial failure below\n // unwinds exactly what this callback owns.\n const disposers: (() => void)[] = []\n const own = (result: unknown): void => {\n if (typeof result === 'function') disposers.push(result as () => void)\n }\n try {\n const tabs = injected.sidebarRightTabs\n if (tabs === undefined || typeof tabs.register !== 'function') return\n own(tabs.register({\n id: SIDEBAR_CONTEXT_ID,\n kind: SIDEBAR_CONTEXT_KIND,\n title: () => t('tab'),\n guide: [{\n order: GUIDE_ORDER,\n title: () => t('tab'),\n description: () => t('sidebar.guideDescription'),\n icon: ContextIcon,\n }],\n }))\n own(injected.slots.inject('sidebar.right.pane.tab', () => injected.slots.register(\n { name: 'sidebar.right.pane.tab', key: SIDEBAR_CONTEXT_ID, locale: ns },\n (props: { sessionId?: string } & Record<string, unknown>) => view({ ...props, host: 'sidebar' }),\n )))\n // The chip title seat (0.1.5-rc.1+): the emblem beside the label, the\n // files type's own idiom. Registered under the type id so the kit\n // dispatches it for this type's tabs only.\n own(injected.slots.inject('sidebar.right.pane.tab.title', () => injected.slots.register(\n { name: 'sidebar.right.pane.tab.title', key: SIDEBAR_CONTEXT_ID },\n makeContextTabTitle(t),\n )))\n } catch {\n // A foreign registry that throws on register leaves the sidebar without\n // this tab; the conversation tab and every other seat keep working.\n for (const dispose of disposers) dispose()\n return undefined\n }\n // The inject callback's own disposer owns every registration: cordis\n // unloads them with the injected fiber (plugin stop, HMR reload).\n return () => {\n for (const dispose of disposers) dispose()\n }\n })\n // The cordis inject handle disposes the callback's fiber; re-proved at\n // runtime because a harness face may return no handle at all.\n const handle = fiber as { dispose?: () => unknown } | undefined\n return () => { void handle?.dispose?.() }\n}\n","/**\n * Chat → Context jump relay. The assistant-message action records the clicked\n * reply's request seq here and opens the Context view — the right Sidebar's\n * tab when this harness serves one, else the conversation tab; the view\n * consumes the one-shot focus once its projection data is in. Module-level\n * per-session map — the same life pattern as the modal open-state stores.\n */\n\nimport { asRecord, type ClientCtx } from './services'\nimport { SIDEBAR_CONTEXT_KIND } from './sidebar'\n\nconst pendingFocus = new Map<string, number>()\n\n/** The mounted Context views re-pinning on later records (repeat jumps). */\nconst focusListeners = new Set<() => void>()\n\n/**\n * Record the Context step (request seq) to reveal for `sessionId` — replaces\n * any unconsumed request and wakes the mounted views.\n */\nexport function requestContextFocus(sessionId: string, seq: number): void {\n pendingFocus.set(sessionId, seq)\n for (const listener of focusListeners) listener()\n}\n\n/**\n * Wake on every record while subscribed: a Context view that is already\n * mounted (the sidebar landing keeps it mounted across jumps) re-pins when a\n * record lands — the listener takes its OWN session's entry, so other\n * sessions' records leave their entries pending for their views.\n */\nexport function subscribeContextFocus(listener: () => void): () => void {\n focusListeners.add(listener)\n return () => { focusListeners.delete(listener) }\n}\n\n/** Take the pending focus request, if any — one-shot, the map entry is consumed. */\nexport function takeContextFocus(sessionId: string): number | null {\n const seq = pendingFocus.get(sessionId)\n if (seq === undefined) return null\n pendingFocus.delete(sessionId)\n return seq\n}\n\n/**\n * Open the Context tab on the right Sidebar over `ctx.sidebarRight.openTab`\n * (the column expands in the same step). OPTIONAL seam, re-proved at call\n * time: a harness without the service (every line older than 0.1.5-rc.1), a\n * placement that registered no tab type, no mounted session surface, or a\n * hostile face all report false so the caller keeps its conversation-tab\n * fallback.\n */\nexport function openContextSidebar(ctx: ClientCtx): boolean {\n try {\n const face = asRecord(ctx.get('sidebarRight'))\n if (face === null || typeof face.openTab !== 'function') return false\n ;(face.openTab as (kind: string) => void).call(face, SIDEBAR_CONTEXT_KIND)\n return true\n } catch {\n return false\n }\n}\n\n/**\n * Activate the Context tab by clicking its own tab-bar button (the semantic\n * `button[role=\"tab\"]` chrome the conversation shell renders for every view).\n * The harness hands `openView` only to the ACTIVE view entry, so a nested\n * chat action cannot call it — this rides the same button a user click would.\n * Already-active is a no-op that still reports success; no matching tab (any\n * dsh layout without the tab bar) reports failure and nothing happens.\n */\nexport function activateContextTab(label: string): boolean {\n const tabs = document.querySelectorAll<HTMLButtonElement>('button[role=\"tab\"]')\n for (const tab of tabs) {\n if (tab.textContent.trim() !== label) continue\n if (tab.getAttribute('aria-selected') !== 'true') tab.click()\n return true\n }\n return false\n}\n","/**\n * 我们的面板\"现在真的可见吗\"—— 决定那两条**改宿主元素**的 CSS 规则能不能生效\n * (`base.css` 里用 `[data-redline-active=\"1\"]` 限定;Code Review P1-2)。\n *\n * 为什么不能只看\"挂载了\":宿主今天\"切走即卸载\",所以 `.redline-root` 存在≈我们的\n * tab 被选中;但若宿主改成\"常驻只隐藏\",`.redline-root` 会在别的 tab(包括上游\n * 插件的 tab)里继续存在,那两条规则就会把**宿主的输入框/宽度拖柄**藏掉。\n * IntersectionObserver 给的是真实的可见性,正好对上这个判据。\n *\n * 退化:没有 `IntersectionObserver`(jsdom、老引擎)时按\"挂载即活跃\"处理 ——\n * 保住既有行为,不让功能因为缺一个观察器而消失。\n */\n\nimport { useEffect, type RefObject } from 'react'\n\n/** 我们自己控制的标记属性;CSS 侧只认它。 */\nexport const REDLINE_ACTIVE_ATTR = 'data-redline-active'\n\n/** 按元素真实可见性维护 `data-redline-active`(卸载时清掉)。 */\nexport function useSurfaceVisibility(ref: RefObject<Element | null>): void {\n useEffect(() => {\n const element = ref.current\n if (element === null) return\n const set = (on: boolean): void => {\n if (on) element.setAttribute(REDLINE_ACTIVE_ATTR, '1')\n else element.removeAttribute(REDLINE_ACTIVE_ATTR)\n }\n if (typeof IntersectionObserver === 'undefined') {\n set(true)\n return () => { set(false) }\n }\n const observer = new IntersectionObserver((entries) => {\n set(entries.some(entry => entry.isIntersecting))\n })\n observer.observe(element)\n return () => {\n observer.disconnect()\n set(false)\n }\n }, [ref])\n}\n","/**\n * Scroll an element's nearest scrollable ancestor so the element tops that\n * scrollport. The jump's landing reveal needs this host-agnostic: the\n * conversation tab scrolls the shared `[data-conversation-scroll]` container\n * while the right Sidebar's scroller differs per generation (dockkit's pane\n * body — a CSS-module class with no stable attribute — on the 0.1.5 line, the\n * tab root itself on the 0.1.7 line), so the walk takes whichever ancestor\n * actually scrolls — the rect delta lands the anchor flush regardless of the\n * container's current position. `document.body` ends the walk: the page\n * itself never scrolls. False — never a throw — when no ancestor scrolls (the\n * layout already shows the element) or the chain turns hostile.\n *\n * @module dsh-context-redline/client/revealScroll\n */\n\nexport function revealInScrollParent(anchor: Element): boolean {\n try {\n for (let el = anchor.parentElement; el !== null && el !== document.body; el = el.parentElement) {\n const oy = window.getComputedStyle(el).overflowY\n if (oy === 'auto' || oy === 'scroll') {\n el.scrollTop += anchor.getBoundingClientRect().top - el.getBoundingClientRect().top\n return true\n }\n }\n } catch { /* hostile chain: the reveal degrades to nothing */ }\n return false\n}\n","/**\n * Context tab root: renders the `redlineTimeline` projection and composes stats, composition, history, events and messages.\n * The data plane is the harness's projection pipeline end to end; the one addition is the split generation's on-demand\n * detail read (timelineSource.ts) — the pushed wire value is the slim head, and the heavy collections arrive from the\n * host's detail endpoint only while the tab (or modal) is open.\n */\n\nimport { createElement as h, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactElement } from 'react'\nimport type { ContextEventRecord, RequestRecord, SurfaceNode } from '../../shared/types'\nimport { briefNodes, briefOf } from '../brief'\nimport type { ContextViewProps } from '../services'\nimport { conversationNodesOf, headersOf, imageLoaderOf, projectionOf, unsupportedOf } from '../services'\nimport type { ClientCtx, ConversationNodeLike } from '../services'\nimport { makeContentFetcher, makeHeaderFetcher, useHistoryFace } from '../historyPage'\nimport { useTimelineSource } from '../timelineSource'\nimport { makeDetailNote } from './detailNote'\nimport type { ContextSettings } from '../settings'\nimport type { ViewKit } from '../viewkit'\nimport { makeContextBrowser } from './browser'\nimport { useRedlineDrafts } from '../redlineDrafts'\nimport { useChildSessions } from '../childSessions'\nimport { makeChildCard } from './childCard'\nimport { makeEventList } from './events'\nimport { makeUpgradeGate } from './upgradeGate'\nimport { makeRequestDetail } from './requestDetail'\nimport { countsOfRecords, makeStatsContext } from './statsContext'\nimport { assemble, stepStatsOf } from '../assemble'\nimport { makeStackedBar } from './stackedBar'\nimport { aggregateByTurn, attachMarkers, jumpTargetOf, makeTrendChart, turnStepsOf } from './trendChart'\n\nimport { subscribeContextFocus, takeContextFocus } from '../viewFocus'\nimport { useSurfaceVisibility } from '../surfaceVisibility'\nimport { revealInScrollParent } from '../revealScroll'\nimport { makeErrorBoundary } from './errorBoundary'\n\n// The context page scrolls inside the conversation's shared `[data-conversation-scroll]` container, which the chat bottom-anchors — mirror\n// the chat's chatScroll pattern: a module-level per-session position ledger (survives tab remounts), restored once content renders; first\n// visits start at the top.\nconst viewScroll = new Map<string, number>()\n\nconst EVENT_KINDS = ['inject', 'compaction', 'prune', 'model', 'mode'] as const\n\nexport function makeContextView(\n ctx: ClientCtx,\n kit: ViewKit,\n settings: ContextSettings,\n): (props: ContextViewProps) => ReactElement {\n const { t } = kit\n const StackedBar = makeStackedBar(kit)\n const TrendChart = makeTrendChart(kit)\n const RequestDetail = makeRequestDetail(kit, StackedBar)\n const EventList = makeEventList(kit)\n // One page-scope cold-head cache serves both subagent-data readers: the\n const StatsContext = makeStatsContext(kit)\n const UpgradeGate = makeUpgradeGate(kit)\n const DetailNote = makeDetailNote(kit)\n const ContextBrowser = makeContextBrowser(kit, StackedBar, settings)\n const ErrorBoundary = makeErrorBoundary(t)\n\n // The body renders under the error boundary: a corrupt projection value (past the timelineOf shape guard) degrades to a styled error\n // card, not a white screen; the boundary itself has NO hooks, so the body's hook order and loading/data flow stay unchanged.\n function ContextViewBody(props: ContextViewProps): ReactElement {\n const sessionId = props.sessionId\n // The right Sidebar's panel is a narrow column: it drops the two head cards\n // that only pay off on the full-width tab (context stats, plugin info).\n const inSidebar = props.host === 'sidebar'\n // The timeline source (timelineSource.ts): the pushed value on the inline\n // generation, or the slim head merged with the on-demand detail on the\n // split generation. `detailState`/`retryDetail` drive the detail cards'\n // loading/failed notes.\n const source = useTimelineSource(ctx, props)\n const data = source.data\n // Official token-meter `contextPressure` projection — the same key the chat's context ring reads; token-meter owns estimation, the Host\n // no longer mirrors it. Absent → derived fallback.\n // Official token-meter `contextBreakdown` projection — the exact rows the chat ring's click-open panel shows, so the overview legend\n // reads identically by construction; absent → the fold's own same-estimator sums inside headlineOf.\n // Legacy fork rows remain readable from the platform catalog; ordinary carrier rows come from `carrier.list`.\n const childCatalog = projectionOf(props, 'subagentCatalog', raw => (Array.isArray(raw) ? raw : null))\n // `redlineHeaders` companion projection (full system prompt + tool schemas) for the Context browser; absent key = older Host half →\n // those sections degrade to tokens-only with a note.\n const headers = projectionOf(props, 'redlineHeaders', headersOf)\n const [selectedSeq, setSelectedSeq] = useState<number | null>(null)\n const [hoveredSeq, setHoveredSeq] = useState<number | null>(null)\n const [hoverTurn, setHoverTurn] = useState<number | null>(null)\n // Mount-time default from the plugin settings card; in-chart toggling stays mount-local and never writes back.\n const [granularity, setGranularity] = useState<'step' | 'turn'>(() => settings.defaultGranularity())\n // 'total' plots each request's cumulative composition, 'delta' its incremental change vs the previous one;\n // like granularity, the default is read at mount and in-chart toggling never writes back.\n const [trendMode, setTrendMode] = useState<'total' | 'delta'>(() => settings.defaultTrendMode())\n // Adaptive scale (the title-adjacent toggle): the trend bars rescale to the visible window; like the two\n // toggles above, mount-local and never written back.\n const [adaptive, setAdaptive] = useState(false)\n // Strip-clicked turn: chart switches to turn granularity and scroll-centers that turn's bar, then clears via onFocusTurnHandled.\n const [focusTurn, setFocusTurn] = useState<number | null>(null)\n // Chat → Context jump: the assistant-action relay's one-shot request, held until the projection data is in, then resolved into a\n // turn-level pin below (mirrors the strip-click's consume-once focus flow).\n const [jumpSeq, setJumpSeq] = useState<number | null>(null)\n const [hoverCat, setHoverCat] = useState<string | null>(null)\n // The browser's open category: the trend card focuses its bars on it (collapsing the category restores all).\n const [focusCat, setFocusCat] = useState<string | null>(null)\n const [pickedKinds, setPickedKinds] = useState<string[]>([...EVENT_KINDS])\n const toggleKind = (k: string) => {\n setPickedKinds((p) => {\n if (p.length === EVENT_KINDS.length) return [k]\n if (!p.includes(k)) return [...p, k]\n return p.length === 1 ? [...EVENT_KINDS] : p.filter(x => x !== k)\n })\n }\n // Step-brief → browser reveal bridge: one-shot focus request consumed by the Context browser.\n const [nodeFocus, setNodeFocus] = useState<{ step: number | 'live'; seq: number; cat: SurfaceNode['cat'] } | null>(null)\n const clearNodeFocus = useCallback(() => { setNodeFocus(null) }, [])\n\n // Session-authorized durable-image loader for the browser's attachment cards, resolved through the harness `uiConversation` service\n // (`imageUrl`); absent service/session degrades the cards to metadata-only, never an error.\n const loadImage = useMemo(\n () => imageLoaderOf(ctx, typeof sessionId === 'string' ? sessionId : undefined),\n [ctx, sessionId],\n )\n\n // The gateway page face, as a React seat: the first render can race the\n // declared inject (a watch rebuild remounts this view before the fiber\n // re-fires), and both fetchers below must rebuild — not stick to the\n // static degradation — when the face lands or is revoked.\n const historyFace = useHistoryFace()\n\n // Targeted full-content fetch for browser nodes outside the conversation window (one seq-anchored history read per expanded row);\n // absent face/session degrades to the static hint — never an error.\n const fetchContent = useMemo(\n () => (typeof sessionId === 'string' && sessionId !== '' && historyFace !== undefined\n ? makeContentFetcher(sessionId)\n : undefined),\n [sessionId, historyFace],\n )\n // On-demand header epoch content (system prompt text, tool schemas) for the Context browser — one seq-anchored history read per\n // opened epoch; the `redlineHeaders` projection carries metadata only. Same degradation shape as fetchContent.\n const fetchHeader = useMemo(\n () => (typeof sessionId === 'string' && sessionId !== '' && historyFace !== undefined\n ? makeHeaderFetcher(sessionId)\n : undefined),\n [sessionId, historyFace],\n )\n\n const rootRef = useRef<HTMLDivElement | null>(null)\n const scrollerRef = useRef<HTMLElement | null>(null)\n // The session whose position was already applied this mount — re-applying on re-renders would yank the reader's scroll.\n const restoredRef = useRef<string | null>(null)\n\n // 只在面板真的可见时,让那两条改**宿主**元素的 CSS 生效(见 surfaceVisibility.ts)。\n useSurfaceVisibility(rootRef)\n\n // Restore the saved position (or the top on first visit) in a layout effect, so the chat's bottom-anchored position never flashes in\n // first.\n useLayoutEffect(() => {\n if (typeof sessionId !== 'string' || sessionId === '' || data === null) return\n if (restoredRef.current === sessionId) return\n restoredRef.current = sessionId\n /* v8 ignore next 3 -- a layout effect body only runs while mounted and\n both render paths attach rootRef, so the null arm cannot fire. */\n const scroller = rootRef.current !== null\n ? rootRef.current.closest('[data-conversation-scroll]')\n : null\n if (scroller === null) return\n scrollerRef.current = scroller as HTMLElement\n scroller.scrollTop = viewScroll.get(sessionId) ?? 0\n }, [sessionId, data])\n\n // Save the position on unmount/session change — a layout-effect cleanup, so it fires before the incoming view's own layout effects\n // re-scroll the shared container.\n useLayoutEffect(() => {\n return () => {\n if (typeof sessionId !== 'string' || sessionId === '') return\n const scroller = scrollerRef.current\n if (scroller === null) return\n viewScroll.set(sessionId, scroller.scrollTop)\n }\n }, [sessionId])\n\n // No locale subscription here: the harness slot outlet subscribes the\n // LocaleFace revision and re-renders every entry on a locale switch, and\n // the kit's bound `t` reads the active locale at call time.\n\n // Hooks stay unconditional (Rules of Hooks): the projection value can arrive AFTER a loading first render, and an early return above\n // these useMemos would grow the hook count between renders (React #310); fall back to empty collections and keep the loading return\n // below the last hook.\n const requests = data ? data.requests : []\n const events = data ? data.events : []\n // The stats board's count figures — the split head's precomputed tallies, or\n // the collections' own derivation on the inline generation. Shared by the\n // stats card's shape cells and the events card's kind-filter counts.\n const counts = data?.counts ?? countsOfRecords(requests, events)\n // The per-kind tallies that ride the filter buttons: only the three priced\n // kinds the host counts (model/mode switches carry no tally, hence undefined).\n const kindCounts: Record<string, number | undefined> = { inject: counts.injects, compaction: counts.compactions, prune: counts.prunes }\n const shownEvents = pickedKinds.length === EVENT_KINDS.length ? events : events.filter(e => pickedKinds.includes(e.kind))\n // Per-step bars, or one per turn (each turn's LAST step's record); memoized so hover-driven re-renders keep bar props identity-stable —\n // the chart's memoized bars then skip reconciliation (turn-mode aggregation allocates).\n const displayRequests = useMemo(\n () => (granularity === 'turn' ? aggregateByTurn(requests) : requests),\n [requests, granularity],\n )\n // The scale readout's turn count: the LAST request's turn — the demo's own\n // `REQUESTS[last].turn` (`docs/03` R1.5).\n const lastTurn = displayRequests.length > 0 ? displayRequests[displayRequests.length - 1]?.turn ?? 1 : 0\n // The step labels' per-turn totals (\"第 s 步 (共 n 步)\"), tallied over the RAW step records — turn-mode\n // aggregates read their own stepCount instead.\n const stepsOf = useMemo(() => turnStepsOf(requests), [requests])\n const markers = useMemo(() => attachMarkers(displayRequests, events), [displayRequests, events])\n\n // Chat → Context jump, leg 1: pick up the assistant-action relay's request for this session —\n // once per mount, and again on every later record (the sidebar landing keeps this view mounted\n // while the user jumps between replies).\n useEffect(() => {\n if (typeof sessionId !== 'string' || sessionId === '') return\n const take = (): void => {\n const seq = takeContextFocus(sessionId)\n if (seq !== null) setJumpSeq(seq)\n }\n take()\n return subscribeContextFocus(take)\n }, [sessionId])\n\n // Leg 2: the action row belongs to the reply that CLOSED a turn, so the jump is turn-level — flip the chart to turn bars, pin that\n // turn's aggregate (the relayed seq is the turn's last request, exactly the aggregate's record), and center it: the same flow as a\n // turn-strip click. An aged-out turn clamps to the oldest retained bar. The landing then reveals the Current Composition card, so\n // the card and the pinned turn's trend chart share the scrollport (revealScroll.ts; no scrollable ancestor → a quiet no-op).\n // The split generation waits for the detail read first: the relayed seq resolves against the served request records, so the\n // one-shot request must not be consumed while the collections are still pending (it re-fires when they land).\n const detailReady = source.detailState === 'ready' || source.detailState === 'legacy'\n useEffect(() => {\n if (jumpSeq === null || data === null || !detailReady) return\n setJumpSeq(null)\n const target = jumpTargetOf(aggregateByTurn(requests), jumpSeq)\n if (target === null) return\n setGranularity('turn')\n setSelectedSeq(target.seq)\n setFocusTurn(target.turn ?? 0)\n // The restore layout effect already applied the saved position on this same data render\n // (layout effects precede this one); the reveal overrides it wherever it landed.\n /* v8 ignore next 2 -- the effect only fires while mounted, and both render paths attach\n rootRef and render the composition card. */\n const anchor = rootRef.current?.querySelector('[data-redline-current]') ?? null\n if (anchor !== null) revealInScrollParent(anchor)\n }, [jumpSeq, data, requests, detailReady])\n\n // Step-brief raw material: every served node seq-sorted (live tail + archive), and the conversation-snapshot\n // join the brief uses for call-argument enrichment (same join the Context browser builds).\n const briefList = useMemo(() => (data ? briefNodes(data) : []), [data])\n // The conversation-window join, from the `useChat` seat. The seat is a\n // real hook — invoked unconditionally per render (stable order);\n // undefined join = render without it, never an error.\n const convNodes = conversationNodesOf(props)\n const bySeq = useMemo(() => {\n const m = new Map<number, ConversationNodeLike>()\n for (const n of convNodes ?? []) m.set(n.seq, n)\n return m\n }, [convNodes])\n\n // Active bar / pin lookup — derived BEFORE the loading-return so the hooks below stay unconditional (React #310).\n let pinnedIdx = -1\n for (let i = 0; i < displayRequests.length; i++) if (displayRequests[i].seq === selectedSeq) pinnedIdx = i\n const pinnedReq = pinnedIdx >= 0 ? displayRequests[pinnedIdx] : null\n let activeIdx = -1\n if (hoveredSeq !== null) {\n for (let i = 0; i < displayRequests.length; i++) if (displayRequests[i].seq === hoveredSeq) { activeIdx = i; break }\n }\n if (activeIdx < 0) activeIdx = pinnedIdx\n if (activeIdx < 0 && displayRequests.length > 0) activeIdx = displayRequests.length - 1\n const activeReq = activeIdx >= 0 ? displayRequests[activeIdx] : null\n // The active bar's semantic identity (\"what this step was about\"); pure derivation over the served nodes, null when nothing is known.\n const brief = useMemo(\n () => (activeReq !== null ? briefOf(briefList, displayRequests, activeIdx) : null),\n [activeReq, briefList, displayRequests, activeIdx],\n )\n const convOf = useCallback((seq: number): ConversationNodeLike | undefined => bySeq.get(seq), [bySeq])\n\n // File activity follows the same active bar: the op-log generation reads the fold-derived records (full\n // session-log coverage); older hosts keep the conversation-window derivation. Recomputed when the brief\n // source, the conversation join, or the upper bound moves — hover/select elsewhere (composition chips,\n // kind filters) leaves every input reference untouched, so the walk is skipped on those renders.\n // The session's workspace root — './'-relative row paths when known; read per\n // render (an observable snapshot), so the next projection push re-renders with it.\n // The system-opener affordance rides the same ctx; both resolve before the early return.\n // The capability is an RPC answer now (the synchronous host-description fact is gone),\n // so it lands in state once the probe settles — inert file names until then; the\n // effect's cleanup drops an answer that arrives after the view unmounted.\n // The right-Sidebar preview opener (the same optional column the Context\n // tab itself registers into): resolved off `ctx` at mount, the face\n // re-proved per call, so an HMR reload's revocation never leaves a stale\n // opener. Absent face = no `onPreview` at all, and the card keeps its\n // system-open affordance untouched.\n // A brief row's reveal target: inputs/opener live in the picked step's OWN assembled surface; the response node (seq === the\n // request's) first appears in the NEXT step's surface — or the live surface when the last bar is picked.\n const locateNode = useCallback((node: SurfaceNode, isResponse: boolean): void => {\n /* v8 ignore next 1 -- locateNode is only wired to brief rows, and\n brief !== null guarantees activeReq !== null in the same closure. */\n if (activeReq === null) return\n const next = isResponse && activeIdx + 1 < displayRequests.length ? displayRequests[activeIdx + 1] : null\n const step: number | 'live' = isResponse ? (next !== null ? next.seq : 'live') : activeReq.seq\n setNodeFocus({ step, seq: node.seq, cat: node.cat })\n }, [activeReq, activeIdx, displayRequests])\n\n // Hooks must remain above the loading return: one mounted view may move from undefined projection to ready data.\n const redline = useRedlineDrafts(typeof sessionId === 'string' && sessionId !== '' ? sessionId : undefined)\n const children = useChildSessions(\n typeof sessionId === 'string' && sessionId !== '' ? sessionId : undefined,\n childCatalog,\n )\n\n if (!data) {\n return <div className=\"redline-root\" ref={rootRef}><div className=\"redline-empty\">{t('loading')}</div></div>\n }\n\n const markerOf = (req: RequestRecord): ContextEventRecord | undefined => {\n const i = displayRequests.indexOf(req)\n /* v8 ignore next 1 -- the only caller passes displayRequests[activeIdx],\n an element of the very array indexOf scans. */\n return i >= 0 ? markers[i] : undefined\n }\n\n // Provider-anchored CURRENT occupancy (contextPressure.projectedTokens): the headline, because the fixed 4-chars/token heuristic\n // undercounts CJK by ~10–15% — proportions stay heuristic but are anchored to the real billed total. Shared with the /redline popup\n // (headline.ts); composition rides the official `contextBreakdown` rows.\n\n // Turn highlight is hover-only: the turn strip hover wins, then the hovered bar's turn — no fallback, so a pinned or default selection\n // never keeps a turn glowing.\n let activeTurn: number | null = hoverTurn\n if (activeTurn === null && hoveredSeq !== null) {\n for (const req of displayRequests) if (req.seq === hoveredSeq) { activeTurn = req.turn ?? null; break }\n }\n\n // The trend card mirrors the SAME shared category hover the browser's live link uses: the overview's 'free' key drops\n // (no segment in the chart or the detail bar), and every bar + the detail bar light that category's segment.\n const trendHoverCat = hoverCat !== null && hoverCat !== 'free' ? hoverCat : null\n\n // The cost cell prices in the active locale (zh → CNY, else USD), read at render time — the locale subscription above already\n // The host's baseline gate (host/fallback.ts): the cards below render\n // the fallback's zeroed data while the modal names both versions and\n // urges the upgrade. Absent record = a supported harness, no gate.\n const gate = unsupportedOf(data.unsupported)\n\n // The three main-row cards, built once and laid out by the shared\n // arrangement below (every host uses the same row).\n const trendCard = (\n <div className=\"redline-card\">\n <div className=\"redline-card-title\">\n <span className=\"redline-card-title-text\">{t('trend.title')}</span>\n {/* 规模读数(`docs/03` R1.5,与 demo 的 `granLabel` 同一句):`按轮次(共 N 轮)` / `按步骤(共 N 次请求)`。\n 单独一个 class:`.redline-card-sub` 是**聚焦**那一行,两者语义不同(混用会让\"没聚焦⇒没有副标题\"的契约失真)。 */}\n <span className=\"redline-card-scale\">\n {t(granularity === 'turn' ? 'trend.gran.turn' : 'trend.gran.step', { n: granularity === 'turn' ? lastTurn : displayRequests.length })}\n </span>\n {/* The adaptive switch rides the title's right (the browser card's DNA toggle idiom): bars rescale\n to the bars currently on screen instead of the whole retained log. */}\n <span className=\"redline-gran redline-trend-adaptive\" role=\"group\" title={t('trend.adaptiveHint')}>\n <button\n type=\"button\"\n className={'redline-gran-btn' + (adaptive ? ' redline-gran-on' : '')}\n onClick={() => { setAdaptive(on => !on) }}\n >{t('trend.adaptive')}</button>\n </span>\n {focusCat !== null\n ? <span className=\"redline-card-sub\">{t('trend.focus', { cat: kit.catLabel(focusCat) })}</span>\n : null}\n <div className=\"redline-trend-ctl\">\n <div className=\"redline-gran\">\n <button\n className={'redline-gran-btn' + (granularity === 'step' ? ' redline-gran-on' : '')}\n onClick={() => { setGranularity('step') }}\n >{t('gran.step')}</button>\n <button\n className={'redline-gran-btn' + (granularity === 'turn' ? ' redline-gran-on' : '')}\n onClick={() => { setGranularity('turn') }}\n >{t('gran.turn')}</button>\n </div>\n <div className=\"redline-gran\" title={t('gran.modeHint')}>\n <button\n className={'redline-gran-btn' + (trendMode === 'total' ? ' redline-gran-on' : '')}\n onClick={() => { setTrendMode('total') }}\n >{t('gran.total')}</button>\n <button\n className={'redline-gran-btn' + (trendMode === 'delta' ? ' redline-gran-on' : '')}\n onClick={() => { setTrendMode('delta') }}\n >{t('gran.delta')}</button>\n </div>\n </div>\n </div>\n {displayRequests.length === 0\n // Split generation, first detail read pending or failed: say\n // so instead of claiming the session has no history.\n ? (detailReady\n ? <div className=\"redline-empty\">{t('trend.empty')}</div>\n : <DetailNote state={source.detailState === 'failed' ? 'failed' : 'loading'} onRetry={source.retryDetail} />)\n : (\n <div>\n <TrendChart\n // Remount per session: switching sessions re-anchors the chart at the newest bars instead of inheriting stale scroll\n // state.\n key={sessionId}\n // Render ALL retained requests (bounded by the host's maxKeptTurns/maxRequestSteps config) so earlier turns/steps\n // stay reachable via horizontal scroll.\n requests={displayRequests}\n markers={markers}\n selectedSeq={pinnedReq ? pinnedReq.seq : null}\n hoveredSeq={hoveredSeq}\n activeTurn={activeTurn}\n granularity={granularity}\n mode={trendMode}\n focusTurn={focusTurn}\n hoverCat={trendHoverCat}\n focusCat={focusCat}\n adaptive={adaptive}\n onSelect={setSelectedSeq}\n onHover={setHoveredSeq}\n onHoverTurn={setHoverTurn}\n onPickTurn={(turn) => { setGranularity('turn'); setFocusTurn(turn) }}\n onFocusTurnHandled={() => { setFocusTurn(null) }}\n />\n <RequestDetail\n request={activeReq}\n // Delta mode pairs the detail with the SAME previous record the chart diffs against (first bar: null).\n prev={trendMode === 'delta' && activeIdx >= 0 ? (activeIdx > 0 ? displayRequests[activeIdx - 1] : null) : undefined}\n /* v8 ignore next 1 -- RequestDetail renders only when\n displayRequests.length > 0, which forces activeReq\n non-null via the activeIdx fallback above. */\n marker={activeReq !== null ? markerOf(activeReq) : undefined}\n brief={brief}\n convOf={convOf}\n stepsOf={stepsOf}\n onLocate={locateNode}\n hoverKey={trendHoverCat}\n />\n </div>\n )}\n </div>\n )\n const browserCard = (\n <ContextBrowser\n redline={redline}\n data={data}\n headers={headers}\n convNodes={convNodes}\n fetchContent={fetchContent}\n fetchHeader={fetchHeader}\n previewSeq={hoveredSeq}\n pinSeq={pinnedReq !== null ? pinnedReq.seq : null}\n hoverKey={hoverCat}\n onHoverKey={setHoverCat}\n onOpenCat={setFocusCat}\n nodeFocus={nodeFocus}\n onNodeFocusHandled={clearNodeFocus}\n loadImage={loadImage}\n detailState={source.detailState}\n onDetailRetry={source.retryDetail}\n />\n )\n\n // 统计卡那 3 格的数据:`assemble()` 给出\"这一步的列表\"(含在那一步还活着、如今已被接替的原文),\n // 三个数字由纯函数 `stepStatsOf()` 从同一张列表里数出来 —— 与浏览器卡片列出的行**同一个来源**。\n const stepStats = stepStatsOf(assemble(data, headers, activeReq !== null ? activeReq.seq : null))\n return (\n <div className=\"redline-root\" ref={rootRef}>\n\n {/* 两列各自从顶部向下排:左边看趋势/发生了什么,右边看上下文/改完后开子会话。\n 不把另一列的高度带进定位,避免传统行式布局造成的顶部空洞;窄处自动成一列。\n 统计卡是**左列第一张卡**(demo 的顺序),不再是顶部整宽横幅 —— 整宽时它的三格\n 会被拉成三大行,既不像 demo 也浪费首屏。右侧栏面板(窄列)不放它(`docs/03` R5.1)。 */}\n <div className=\"redline-masonry\">\n <div className=\"redline-masonry-col\">\n {inSidebar ? null : (\n <StatsContext stats={stepStats} turn={activeReq?.turn} step={activeReq?.step}\n live={activeReq === null} ready={source.detailState === 'ready' || source.detailState === 'legacy'} />\n )}\n {trendCard}\n <div className=\"redline-card\">\n <div className=\"redline-card-title\">\n <span className=\"redline-card-title-text\">{t('events.title')}</span>\n <div className=\"redline-kinds @max-[380px]/redline-card:flex-wrap\">\n {EVENT_KINDS.map((k) => {\n const n = kindCounts[k]\n return (\n <button\n key={k}\n data-redline-kind={k}\n className={'redline-gran-btn' + (pickedKinds.includes(k) ? ' redline-gran-on redline-kind-' + k : '')}\n onClick={() => { toggleKind(k) }}\n >\n {t('kind.' + k)}\n {n !== undefined ? <span className=\"redline-kind-n\">{kit.fmt(n)}</span> : null}\n </button>\n )\n })}\n </div>\n </div>\n <EventList events={shownEvents} state={source.detailState} onRetry={source.retryDetail} />\n </div>\n </div>\n\n <div className=\"redline-masonry-col\">\n {browserCard}\n {/* 第 5 张卡(`docs/10` M3-16/17,随 M5 落地):子会话索引 + 开子会话。\n 它是**本面板唯一会写会话的入口**,所以按钮的门禁与 `保存` 完全一致(`live` / `turnOpen`)。 */}\n <ChildCard\n sessionId={sessionId}\n rows={children.rows}\n capacity={children.capacity}\n originsKnown={children.originsKnown}\n originsError={children.originsError}\n models={children.models}\n live={redline.turn.known}\n turnOpen={redline.turn.open}\n carriedCount={Object.keys(redline.table).length}\n plan={children.plan}\n start={children.start}\n />\n </div>\n </div>\n\n\n <div className=\"redline-foot\">{t('footer')}</div>\n\n {gate !== null && (\n <UpgradeGate sessionId={sessionId} current={gate.current} minimum={gate.minimum} />\n )}\n </div>\n )\n }\n\n const ChildCard = makeChildCard(kit)\n\n return function ContextView(props: ContextViewProps): ReactElement {\n return h(ErrorBoundary, null, h(ContextViewBody, props))\n }\n}\n","/**\n * The assistant-message action that opens the Context view at this reply's\n * turn. Registered on the harness `conversation.chat.assistant-actions` seat\n * (the icon row beside copy/branch), it receives the finalized reply's durable\n * message id, resolves the matching assistant node's seq off the `useChat`\n * node seat AT RENDER TIME (the seat is a real React hook — render-only; a\n * click-time read throws the dispatcher guard and the jump would land\n * unpinned), records it in the viewFocus relay on click, and opens the\n * Context tab on the right Sidebar — where the jump pins the reply's TURN\n * (see contextView's leg 2). A harness or placement without the sidebar tab\n * falls back to the conversation tab; an unresolvable seq still opens the\n * view, just without a pin; a message id that is not a plain string renders\n * nothing at all.\n */\n\nimport { type ReactElement } from 'react'\nimport { Tooltip } from '@deepseek-ai/dsh-client-ui-primitives'\nimport type { ClientCtx, ConversationNodeLike, UseChatLike } from '../services'\nimport { conversationNodesOf } from '../services'\nimport { activateContextTab, openContextSidebar, requestContextFocus } from '../viewFocus'\nimport type { ViewKit } from '../viewkit'\n\n/** The assistant-action seat's currency, as far as this button consumes it. */\nexport interface ContextJumpProps {\n messageId?: unknown\n sessionId?: unknown\n useChat?: UseChatLike\n}\n\n/**\n * The reply's request seq by its durable message id, or null when no served node proves the pair. Join/log nodes are untrusted input: each\n * element is isolated, so one hostile object that throws on property access is skipped — the jump keeps its pin, never its click.\n */\nexport function seqOfMessageId(nodes: readonly ConversationNodeLike[] | undefined, messageId: string): number | null {\n for (const node of nodes ?? []) {\n try {\n if (node.kind !== 'assistant' || node.messageId !== messageId) continue\n return typeof node.seq === 'number' && Number.isFinite(node.seq) ? node.seq : null\n } catch {\n continue\n }\n }\n return null\n}\n\n/** The jump glyph: the plugin's mini stacked composition bars, same 16px outline family as the shipped row icons. */\nfunction JumpIcon(): ReactElement {\n return (\n <svg width=\"16\" height=\"16\" viewBox=\"0 0 16 16\" className=\"redline-jump fill-none\" aria-hidden=\"true\">\n <rect x=\"2\" y=\"3\" width=\"12\" height=\"2\" rx=\"1\" className=\"fill-current\" />\n <rect x=\"2\" y=\"7\" width=\"8.5\" height=\"2\" rx=\"1\" className=\"fill-current\" />\n <rect x=\"2\" y=\"11\" width=\"5.5\" height=\"2\" rx=\"1\" className=\"fill-current\" />\n </svg>\n )\n}\n\nexport function makeContextJumpButton(ctx: ClientCtx, kit: ViewKit): (props: ContextJumpProps) => ReactElement | null {\n const { t } = kit\n return function ContextJump(props: ContextJumpProps): ReactElement | null {\n // The seat is read HERE — unconditionally and first, so the early return\n // below keeps hook order — and the click consumes the captured pair.\n const nodes = conversationNodesOf(props)\n const messageId = props.messageId\n // Interruption-frozen partials address no durable message — the owner\n // already withholds them, and anything else non-string is ignored.\n if (typeof messageId !== 'string' || messageId === '') return null\n const seq = seqOfMessageId(nodes, messageId)\n const jump = (): void => {\n const sessionId = props.sessionId\n if (seq !== null && typeof sessionId === 'string' && sessionId !== '') {\n requestContextFocus(sessionId, seq)\n }\n // The sidebar expands over the chat, keeping the clicked reply in view;\n // a harness or placement without that tab keeps the tab activation.\n if (!openContextSidebar(ctx)) activateContextTab(t('tab'))\n }\n return (\n <Tooltip label={t('jump.title')} side=\"bottom\">\n <button type=\"button\" className=\"redline-jump hover:bg-(--dsw-alias-interactive-bg-hover) hover:text-(--dsw-alias-label-secondary)\" aria-label={t('jump.title')} onClick={jump}>\n <JumpIcon />\n </button>\n </Tooltip>\n )\n }\n}\n","/**\n * Placement gating for the Context view: the per-user `defaultPlacement`\n * preference (the settings namespace's `defaultPlacement` field) picks which\n * registrations carry it — the conversation tab, the right Sidebar panel, or\n * both.\n *\n * Each mount is a factory returning its own disposer, so a preference flip\n * takes down only what the new value drops and mounts only what it adds; the\n * underlying `slots.inject` / deferred-inject disposers are the harness's own\n * dynamic-mount idiom. A mount landing no disposer (a harness face that\n * returns nothing) simply has nothing to unwind.\n *\n * @module dsh-context-redline/client/placement\n */\n\nimport type { ContextSettings } from './settings'\nimport type { DefaultPlacement } from '../shared/types'\n\n/** One registration factory per placement; each returns its mount's disposer. */\nexport interface PlacementMounts {\n tab(): unknown\n sidebar(): unknown\n}\n\n/**\n * Mount per the current preference and keep the registrations glued to it\n * until the returned disposer runs.\n */\nexport function watchPlacement(settings: ContextSettings, mounts: PlacementMounts): () => void {\n let tab: (() => void) | undefined\n let sidebar: (() => void) | undefined\n const own = (result: unknown): (() => void) | undefined =>\n typeof result === 'function' ? result as () => void : undefined\n const mount = (placement: DefaultPlacement): void => {\n const wantTab = placement !== 'sidebar'\n const wantSidebar = placement !== 'tab'\n if (wantTab && tab === undefined) tab = own(mounts.tab())\n if (!wantTab && tab !== undefined) { tab(); tab = undefined }\n if (wantSidebar && sidebar === undefined) sidebar = own(mounts.sidebar())\n if (!wantSidebar && sidebar !== undefined) { sidebar(); sidebar = undefined }\n }\n mount(settings.defaultPlacement())\n const unsubscribe = settings.store.subscribe(() => { mount(settings.defaultPlacement()) })\n return () => {\n unsubscribe()\n tab?.()\n sidebar?.()\n tab = undefined\n sidebar = undefined\n }\n}\n","/** Shared dependency bag for component factories, built once per plugin apply (t, formatters, catLabel, event-text helpers). */\n\nimport type { ContextEventRecord } from '../shared/types'\nimport { fmt, fmtDuration, fmtShare, fmtTime } from './format'\nimport { makeEventText } from './components/events'\nimport type { Translate } from './i18n'\n\nexport interface ViewKit {\n t: Translate\n fmt: typeof fmt\n fmtTime: typeof fmtTime\n fmtDuration: typeof fmtDuration\n fmtShare: typeof fmtShare\n catLabel: (key: string) => string\n eventLabel: (ev: ContextEventRecord) => string\n eventAt: (ev: ContextEventRecord) => string | null\n}\n\nexport function makeViewKit(t: Translate): ViewKit {\n const { eventLabel, eventAt } = makeEventText(t)\n return {\n t,\n fmt,\n fmtTime,\n fmtDuration,\n fmtShare,\n catLabel: (key: string) => t('cat.' + key),\n eventLabel,\n eventAt,\n }\n}\n","/**\n * dsh-context-redline — Client half (installed package bundle entry).\n *\n * Registers a \"上下文/Context\" tab in the conversation view ring\n * (`conversation.view` slot, beside Chat/Trajectory) and renders the\n * context-composition timeline: current makeup, per-request stacked-bar\n * history, context events, and the live message list.\n *\n * Since v0.9 the tab rides the harness's session-projection pipeline\n * (`redlineTimeline` projection key), read from the framework standard kit\n * (`useProjection('redlineTimeline')`, a standard prop on every session-scope\n * slot component). The wire value is the split generation's slim head; the\n * heavy collections arrive on demand from the host's detail endpoint, one\n * read per viewing client (timelineSource.ts). No polling, no stale-while-\n * revalidate cache.\n *\n * This module is the body of the package's `./client` bundle: tsdown\n * (tsdown.config.ts) bundles it (external `react` — the browser module table\n * supplies it via the injected `require`) into the web boot handoff\n * (`window.__ModuleLoader__.load({id, factory})`). All imports from other\n * client modules are inlined by the bundler; everything here is zero-runtime\n * beyond the bundled source.\n */\n\nimport { createElement as h } from 'react'\nimport { DICT_EN, DICT_ZH } from './i18n'\nimport { registerContextCommand } from './command'\nimport { makeContextModal } from './components/contextModal'\nimport { makeSettingsCard, makePluginConfigCard } from './components/settingsCard'\nimport { modalStoreOf } from './modalStore'\nimport type { ClientCtx } from './services'\nimport { createContextSettings, type ConfigFormsFace, type SettingsField, type SettingsScopeBinderFace } from './settings'\nimport { makeContextView } from './components/contextView'\nimport { makeContextJumpButton } from './components/contextJump'\nimport { watchHistoryFaces } from './historyPage'\nimport { watchPlacement } from './placement'\nimport { watchSidebarContextTab } from './sidebar'\nimport { makeViewKit } from './viewkit'\n\n// Theme-native styles: the bundle's global-CSS channel injects each sheet as\n// a plugin-owned <style data-plugin> tag at factory execution (the web boot\n// loader and the HMR receiver claim tags carrying data-plugin). Import order\n// IS cascade order across same-specificity rules: the Tailwind utilities\n// first (the sibling sheets keep winning same-specificity ties), then base,\n// then the per-component sheets in their original section order.\nimport './styles/tailwind.css'\nimport './styles/base.css'\nimport './styles/stats.css'\nimport './styles/jump.css'\nimport './styles/settings.css'\nimport './styles/stackedBar.css'\nimport './styles/trendChart.css'\nimport './styles/requestDetail.css'\nimport './styles/events.css'\n// fileCard.css 已随孤岛 B(已删的上游五卡)删除(docs/10 M6-17)\nimport './styles/modal.css'\nimport './styles/browser.css'\nimport './styles/childCard.css'\nimport './styles/detailSections.css'\nimport './styles/attachments.css'\n// agentGraph.css 已随孤岛 A(Agent 网络卡 + 费用/子 agent 模块)删除(docs/10 M6-17)\n// overview.css 已随洞察面删除(用户 2026-10-05 选二):96 个类全无引用\n\nconst NS = 'dsh-context-redline'\n\nfunction apply(ctx: ClientCtx): void {\n // Bilingual dictionaries, registered via ctx.effect so a stop or HMR reload\n // disposes them; the tab label thunk and all UI text follow the active\n // locale through the bound translate — missing keys resolve through the\n // harness chain (en fallback, then the key).\n ctx.effect(() => {\n return ctx.locale.register(NS, { zh: DICT_ZH, en: DICT_EN })\n }, 'dsh-context-redline: dictionaries')\n const t = ctx.locale.bind(NS)\n\n const kit = makeViewKit(t)\n // History face of the harness gateway remotes, resolved through the\n // DECLARED inject — a non-declared read of the traced `remote.session`\n // proxy throws (\"cannot get property … without inject\") and would take\n // the browser down with the view. Injection waits for the service; a\n // harness that never composes the namespace never fires the callback and\n // the targeted fetches simply stay absent.\n watchHistoryFaces(ctx)\n const settings = createContextSettings()\n const ContextView = makeContextView(ctx, kit, settings)\n\n // Placement: the per-user `defaultPlacement` preference picks which\n // registration carries the view — the conversation tab, the right Sidebar\n // (dsh 0.1.5-rc.1+, optional by contract), or both (the default). Each\n // mount owns its disposer so the watcher takes down exactly what a\n // preference flip drops (see placement.ts).\n ctx.effect(() => watchPlacement(settings, {\n tab: () => ctx.slots.inject('conversation.view', () => {\n return ctx.slots.register(\n // order 20 renders right of Chat (0) and Trajectory (10); the locale\n // namespace put the framework `t` seat on the component's props too.\n { name: 'conversation.view', id: 'redline', order: 20, locale: NS, label: () => t('tab') },\n props => h(ContextView, props),\n )\n }),\n sidebar: () => watchSidebarContextTab(ctx, ContextView, t, NS),\n }), 'dsh-context-redline: placement')\n\n // Chat → Context jump: an icon in each finalized reply's action row that\n // opens the Context tab on the right Sidebar pinned to that reply's turn —\n // falling back to the conversation tab wherever the sidebar serves no tab\n // (see contextJump.tsx; the relay and view activation live in viewFocus.ts).\n const ContextJump = makeContextJumpButton(ctx, kit)\n ctx.slots.inject('conversation.chat.assistant-actions', () => {\n return ctx.slots.register(\n // After the shipped feedback entry (10), still inside the icon row.\n { name: 'conversation.chat.assistant-actions', id: 'redline-jump', order: 20, locale: NS },\n props => h(ContextJump, props),\n )\n })\n\n // `/redline` slash command: opens the context modal (see command.ts for\n // the trigger source). The modal itself renders from the input overlay\n // slot, opened per session through the hooks-compartment store.\n registerContextCommand(ctx, kit)\n const ContextModal = makeContextModal(ctx, kit, settings)\n ctx.slots.inject('conversation.input.overlay', () => {\n return ctx.slots.register(\n { name: 'conversation.input.overlay', id: 'redline-modal', order: 10, locale: NS,\n inject: (sessionId = '') => ({ hooks: { contextModal: modalStoreOf(sessionId) } }) },\n props => h(ContextModal, props),\n )\n })\n\n // The Context Dashboard (see components/overviewPanel.tsx): the cross-session\n // insight surface. ⚠️ **The sidebar-foot ENTRY was removed on 2026-10-05** ——\n // the user said 「左侧抽屉的底部,我们不需要上下文批改的这个提示。可以去掉」\n // (the footer chip sat directly above Settings in the left drawer)。\n // The overlay below stays registered: it is the panel itself, and the open flag\n // still rides `overviewStore.ts`, so wiring a different opener later needs no\n // panel work. NOTE: with no opener registered today the overlay is unreachable\n // — flagged in `docs/10` M3-35 as a decision (keep for later wiring / remove).\n // ⚠️ **整块\"洞察面\"已按用户要求删除**(2026-10-05:「我推荐选二」—— 它是参考插件 dsh-context 的功能,\n // 我们的 demo 里没有;入口在更早一轮按同一要求拆掉)。删的是我们自己包里的那份复制品:\n // overviewPanel / overviewButton / overviewCard / overviewTokens / overviewUsage / heatmap / balanceCapsule\n // + overviewStore + 这处 `shell.overlay` 注册。**共用件一律保留**(`overview.ts` 是全仓核心装配、\n // `donut` / `pluginInfo` / `agentTree` / `statsTokens·Timing` / `sliceList` / `currentComposition` 我们的面板在用)。\n // 界线上不碰任何**别人的**插件与其样式。\n\n /** The injected face both preference cards ride: the settings store as the\n * framework's hooks-compartment `useContextSettings` seat, plus the set verb. */\n const cardFace = (): {\n hooks: { contextSettings: typeof settings.store }\n set: (field: SettingsField, value: string) => void\n } => ({\n hooks: { contextSettings: settings.store },\n set: (field, value) => { settings.set(field, value) },\n })\n\n // Per-user display preferences. Two generations, two transports and seats,\n // switched by SERVICE PRESENCE (each deferred inject fires on exactly one\n // side; a host without its service never runs the callback):\n // - the settingsScope generation registers the card on the keyed\n // `settings.plugin.item` slot (Settings → Plugins → Plugin\n // configuration), binding the Host-served `dsh-context-redline` namespace;\n // - the Config-form generation (dsh 0.1.7+) retired that pair — there the\n // card rides the configForms transport and the Plugins page's keyed\n // `plugins.bundle.config` seat, alive only while the Host serves the\n // namespace (the entry Config's volatile preference fields).\n ctx.inject(['settingsScope'], (raw) => {\n const c = raw as ClientCtx & { settingsScope?: SettingsScopeBinderFace }\n const binder = c.settingsScope\n if (binder === undefined) return\n c.effect(() => settings.attach(binder.bind({ namespace: NS })), 'dsh-context-redline: settings scope')\n const SettingsCard = makeSettingsCard(kit)\n c.slots.inject('settings.plugin.item', () => {\n return c.slots.register(\n { name: 'settings.plugin.item', key: NS, locale: NS, inject: cardFace },\n // Root-scope keyed slot: no sessionId on these props — the face\n // (hooks + set) arrives through the registration's inject.\n props => h(SettingsCard, props as unknown as Parameters<typeof SettingsCard>[0]),\n )\n })\n })\n ctx.inject(['configForms'], (raw) => {\n const c = raw as ClientCtx & { configForms?: ConfigFormsFace }\n const forms = c.configForms\n if (forms === undefined || typeof forms.get !== 'function' || typeof forms.whileServed !== 'function') return\n c.effect(() => settings.attach(forms.get(NS)), 'dsh-context-redline: config forms')\n const PluginConfigCard = makePluginConfigCard(kit)\n c.effect(() => forms.whileServed([NS], () => {\n // slots.inject's disposer is the registration's disposer (the typed\n // local face reads unknown; the harness contract returns a disposer).\n return c.slots.inject('plugins.bundle.config', () => {\n return c.slots.register(\n { name: 'plugins.bundle.config', key: NS, locale: NS, inject: cardFace },\n props => h(PluginConfigCard, props as unknown as Parameters<typeof PluginConfigCard>[0]),\n )\n }) as () => void\n }), 'dsh-context-redline: plugins-page card')\n })\n}\n\nmodule.exports = {\n name: 'dsh-context-redline',\n inject: ['slots', 'locale'],\n apply,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