Compare commits

..

12 Commits

Author SHA1 Message Date
claude-code-best
5895362178 chore: 2.2.0 2026-05-07 08:29:07 +08:00
claude-code-best
8cfe9b6dc3 feat: 启用 COORDINATOR_MODE feature flag
AgentSummary 30s fork 循环的内存泄露已在 commit 52b61c2c 修复(闭包
引用丢弃 + 上下文重建 + 消息/字符上限),重新启用该 feature。

用户可通过 /coordinator 命令或 CLAUDE_CODE_COORDINATOR_MODE=1 环境变量
激活多 worker 编排模式。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-07 08:28:28 +08:00
claude-code-best
12f5aedf99 fix: 恢复消息流中 diff 高亮渲染功能
还原 commit 51b8ad46 删除的 diff highlight 显示:FileEdit/FileWrite 工具
执行成功后重新展示 StructuredDiffList,拒绝时重新展示高亮代码预览或
带上下文的 diff 视图。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-07 08:28:28 +08:00
claude-code-best
c7efac6b8d Merge pull request #423 from znygugeyx-ctrl/feat/statusline-refresh-interval
feat: 状态栏支持 refreshInterval 定时刷新
2026-05-06 23:53:36 +08:00
zny
2f150d3ecd feat: 状态栏支持 refreshInterval 定时刷新
- Zod schema 补齐 refreshInterval 字段
- 通过 scheduleUpdate 复用 300ms debounce,event/settings/time 三路触发单飞
- 新增 docs/features/status-line.mdx 调研文档
2026-05-06 22:50:11 +08:00
claude-code-best
68c7ebb242 Merge pull request #419 from suger-m/codex/sub-agents-docs
docs: expand sub-agent architecture guide
2026-05-06 20:30:42 +08:00
claude-code-best
9e299a7208 Merge pull request #420 from claude-code-best/fix/third-party-api-user-id
fix: third-party API user_id validation error (DeepSeek, etc.)
2026-05-06 20:30:12 +08:00
Simple6K
941bcbd240 fix: third-party API user_id validation error (DeepSeek, etc.)
When ANTHROPIC_BASE_URL points to a non-Anthropic endpoint (e.g.
DeepSeek), the JSON-formatted user_id containing {, ", : characters
fails validation against ^[a-zA-Z0-9_-]+$. Send only the hex device_id
for third-party providers.
2026-05-06 17:47:31 +08:00
suger-m
fd66ddc45f docs: expand sub-agent architecture guide 2026-05-06 17:26:49 +08:00
znygugeyx-ctrl
5c107e5f8c Merge pull request #416 from znygugeyx-ctrl/feat/subagent-fork-render
feat: 参考 claude code 官方实现,改进 sub agent 以及 fork agent 的渲染方式
2026-05-06 09:57:52 +08:00
claude-code-best
c4e9efb7a8 Merge pull request #417 from shaleloop/sync/mcp-transform-2.1.128
fix: align mcp transform pipeline with Anthropic Claude Code 2.1.128
2026-05-06 09:51:37 +08:00
shaleloop
26ddbda849 fix: align mcp transform pipeline with Anthropic Claude Code 2.1.128
Add ImageLimits type and plumb optional limits through the chain:
callMCPTool/callMCPToolWithUrlElicitationRetry -> processMCPResult ->
transformMCPResult -> transformResultContent -> maybeResizeAndDownsampleImageBuffer.
When provided, limits override the module-level defaults
(IMAGE_TARGET_RAW_SIZE, IMAGE_MAX_WIDTH, IMAGE_MAX_HEIGHT,
API_IMAGE_MAX_BASE64_SIZE) inside maybeResizeAndDownsampleImageBuffer.
When undefined, behavior is unchanged for current callers.

Add _meta preservation in the text-block case of transformResultContent
(only when the caller opts in via includeMeta=true). transformMCPResult
passes includeMeta=true on the tool-result path; the prompt-handler call
site keeps the default false, preserving prior behavior.

Add skipLargeOutput early-return in processMCPResult after the IDE check:
when the caller passes skipLargeOutput=true and the content has no images,
the function returns content directly without large-output handling.

Add unwrap-to-text in processMCPResult for the persisted-content path:
when the large-string format gate is enabled
(MCP_TRUNCATION_PROMPT_OVERRIDE env var, or
tengu_mcp_subagent_prompt Statsig gate), and the content is a single
bare text block (no annotations, no _meta), unwrap to raw text and
switch the format description to 'Plain text'. Default-off; gate-off
behavior is unchanged.

Verified structurally against the 2.1.128 binary: function signatures,
the IDE check, gate logic, _meta-unwrap pattern, and imageLimits
plumbing match this implementation.
2026-05-05 14:53:57 -07:00
28 changed files with 2082 additions and 289 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,225 @@
# Background Agent Selector — 底部统一后台 Agent 切换器
> Feature Flag: 无(直接启用)
> 实现状态:完整可用
> 依赖:`viewingAgentTaskId` / `enterTeammateView` / `exitTeammateView` 已有机制
## 一、功能概述
Background Agent Selector 是渲染在 PromptInput 下方的常驻状态条,列出当前所有 **backgrounded 的 local_agent 任务**(包括 `/fork` 派生的 fork agent 和 Task/AgentTool 调用 `run_in_background: true` 派生的子 agent。用户可以用 ↑/↓ 方向键在 `main` 和各 agent 之间切换焦点,按 Enter 把 REPL 主视图替换为所选 agent 的实时 transcript再按 Enter 选中 `main` 即可回到主对话。
整个机制完全复用官方已有的 teammate transcript 查看基础设施,不引入新的视图层 / 数据流,仅新增一条 footer pill 类型。
### 核心特性
- **统一入口**`/fork`、Task 派生的 subagent、所有 `run_in_background: true` 的 agent 都在同一栏显示
- **就地切换**prompt 为空时按 ↓ 溢出进入底部 selector↑↓ 选中某行Enter 即切主视图
- **实时状态**:每行显示 agent 类型 + 描述 + 运行时长 + 已消耗 tokenrunning 时圆点为绿色
- **Keep-alive 视图**agent 完成后在 `evictAfter` grace 窗口内保留一段时间,用户可回看
- **零界面侵入**tasks 数为 0 时 selector 完全不渲染,不占屏幕高度
- **与旧 Dialog 共存**Shift+↓ 打开的 `BackgroundTasksDialog` 原有行为保留selector 只作为展示 + 快捷切换
## 二、用户交互
### 触发方式
有任何 background agent 时selector 自动出现在 `bypass permissions on` 行下方:
```
claude-code | Opus 4.7 (1M context) | ctx:4%
▶▶ bypass permissions on (shift+tab to cycle)
○ main ↑/↓ to select · Enter to view
● Explore Research src/hooks 23s · ↓ 10.9k tokens
○ Explore Research src/components 22s · ↓ 9.5k tokens
○ Explore Research src/utils 21s · ↓ 13.6k tokens
```
### 键盘路由
| 位置 / 状态 | 按键 | 行为 |
|---|---|---|
| PromptInput 非空 | ↑↓ | 光标移动 / 翻历史(不变) |
| PromptInput 空 + 历史底部 | ↓ | 焦点下放到 selector高亮到 `● main` |
| Selector 聚焦(`footerSelection === 'bg_agent'` | ↓ | 高亮下移,-1 → 0 → ... → N-1 |
| Selector 聚焦 | ↑ | 高亮上移;在 `main` 再 ↑ → 焦点回 PromptInput |
| Selector 聚焦 | Enter | `-1``exitTeammateView``>=0``enterTeammateView(agentId)`。焦点保留在 pill |
| Selector 聚焦 | Esc | `footer:clearSelection`,焦点回 PromptInput |
### 视觉规则
- `● main` / `● <agent>`:当前被**查看**viewingAgentTaskId 指向)或被**光标聚焦**pill focused 时以光标为准)的一行
- running 状态的 agent圆点渲染为 `success` 色(绿色),与 `BackgroundTasksDialog` 状态语义对齐
- 右上角 hint 随状态变化:
- pill 聚焦:`↑/↓ to select · Enter to view`
- 已选中 running agent`shift+↓ to manage · x to stop`
- 已选中 terminal agent`shift+↓ to manage · x to clear`
- 未选中任何 agent`shift+↓ to manage background agents`
## 三、实现架构
### 3.1 数据层:`useBackgroundAgentTasks`
文件:`src/hooks/useBackgroundAgentTasks.ts`
封装对 `useAppState(s => s.tasks)` 的过滤:
```ts
export function useBackgroundAgentTasks(): LocalAgentTaskState[] {
const tasks = useAppState(s => s.tasks)
return useMemo(() => {
const now = Date.now()
return Object.values(tasks)
.filter(isLocalAgentTask)
.filter(t => t.agentType !== 'main-session')
.filter(t => t.isBackgrounded !== false)
.filter(t => t.evictAfter === undefined || t.evictAfter > now)
.sort((a, b) => a.startTime - b.startTime)
}, [tasks])
}
```
`/fork``AgentTool``run_in_background: true` 底层都走 `registerAsyncAgent → runAsyncAgentLifecycle`,最终写入同一个 `appState.tasks` Map此 hook 是唯一数据源Selector 和 PromptInput 的 `bgAgentList` 都消费它。
### 3.2 状态层:新增两个字段
文件:`src/state/AppStateStore.ts`
```ts
export type FooterItem =
| 'tasks' | 'tmux' | 'bagel' | 'teams' | 'bridge' | 'companion'
| 'bg_agent' // ← 新增
export type AppState = DeepImmutable<{
// ...
selectedBgAgentIndex: number // -1 = main, 0..N-1 = 选中的 agent
}>
```
- `'bg_agent'` 作为 `FooterItem` 加入 footer pill 体系,享受既有的 `footer:up` / `footer:down` / `footer:openSelected` keybinding 路由
- `selectedBgAgentIndex` 记录 selector 的光标位置,与 `viewingAgentTaskId`"正在看什么")独立;它不可从 `viewingAgentTaskId` 派生——Enter 后光标留在 pill 继续导航,查看目标才变
### 3.3 键盘路由PromptInput footer pill 分支
文件:`src/components/PromptInput/PromptInput.tsx`
1. **`bg_agent` 进入 footerItems[0]**:保证 prompt ↓ 溢出时(`handleHistoryDown``selectFooterItem(footerItems[0])`)直接进入 selector而不是 `tasks` 等其他 pill
2. **`footer:up` 分支**`bgAgentSelected``selectedBgAgentIndex > -1` 则递减;在 -1 → `selectFooterItem(null)` 退出 pill
3. **`footer:down` 分支**`selectedBgAgentIndex < bgAgentList.length - 1` 则递增,到底 clamp
4. **`footer:openSelected` 分支**index === -1 → `exitTeammateView`;否则 `enterTeammateView(bgAgentList[i].agentId)`。**不清理 pill 焦点**,光标留在 selector 上继续导航
5. **`selectFooterItem('bg_agent')`**:入 pill 时重置 `selectedBgAgentIndex = -1`(光标落到 `main`
### 3.4 渲染层:`BackgroundAgentSelector`
文件:`src/components/tasks/BackgroundAgentSelector.tsx`
纯展示组件,不订阅键盘:
```tsx
const tasks = useBackgroundAgentTasks()
const viewingId = useAppState(s => s.viewingAgentTaskId)
const footerSelection = useAppState(s => s.footerSelection)
const selectedBgIndex = useAppState(s => s.selectedBgAgentIndex)
if (tasks.length === 0) return null
const pillFocused = footerSelection === 'bg_agent'
const highlightedId = pillFocused
? (selectedBgIndex === -1 ? null : tasks[selectedBgIndex]?.agentId ?? null)
: (viewingId ?? null)
```
**高亮派生规则**pill 聚焦 → 跟 `selectedBgAgentIndex`;未聚焦 → 镜像 `viewingAgentTaskId`。这样当用户通过 Shift+↓ Dialog 或 `enterTeammateView` 其它途径切换视图时selector 也会正确反映。
### 3.5 主视图切换:复用 `viewingAgentTaskId`
REPL.tsx 主体仍复用原有查看逻辑:
```ts
const viewedTask = viewingAgentTaskId ? tasks[viewingAgentTaskId] : undefined
const viewedAgentTask = ... (isLocalAgentTask(viewedTask) ? viewedTask : undefined)
const displayedMessages = viewedAgentTask ? displayedAgentMessages : messages
```
`enterTeammateView(agentId)``viewingAgentTaskId` 设成某个 local_agent 的 id
- `viewedAgentTask` 解析成该 agent
- `displayedMessages` 切换到 agent 的 messages
- 消息列表、spinner、unseen divider 等一整套组件自动用 agent transcript 重渲染
- 主对话流被"暂停"(并非销毁,回到 `main` 时仍在原处)
`enterTeammateView` 同步负责:设 `retain: true` 阻止 eviction、清 `evictAfter`、触发 disk bootstrap 从 `agent-<id>.jsonl` 加载完整 transcript 到 `task.messages`
#### Fork agent prompt 归一化
`/fork` agent 的 transcript 和普通 subagent 不同:它继承 main agent 的上下文,真实初始消息形态是:
```text
...parent messages
assistant([...tool_use])
user([tool_result..., text("<fork-boilerplate>...Your directive: <prompt>")])
...fork live messages
```
这里的 prompt 文本混在 `[tool_result..., text]` 多 block user message 里。消息渲染管线会优先把这条 user message 当作 tool-result plumbing 来处理,导致 `<fork-boilerplate>` 里的用户 prompt 不稳定可见。为保证切换到 fork agent 时总能看到用户发起的 fork promptREPL.tsx 对 fork 视图做一次展示层归一化:
1. 仅当 `viewedAgentTask.agentType === 'fork'` 时启用,不影响普通 Explore / Task subagent。
2. 从原始 messages 中识别包含 `<fork-boilerplate>` 的 carrier message。
3. 剥离 carrier message 里的 boilerplate text block但保留 `tool_result` blocks避免破坏父 assistant `tool_use` 的承接关系。
4. 强制插入一条独立 `createUserMessage({ content: viewedAgentTask.prompt })` 作为可见用户 prompt。
5. 插入位置优先为 boilerplate carrier 后;如果 sidechain bootstrap 还没读到 carrier则插到最后一条 inherited `assistant tool_use` 后面,确保 prompt 接在 main 上下文之后,而不是跑到视图顶部。
这个归一化只影响 UI 展示用的 `displayedAgentMessages`,不回写 `task.messages`,也不改变发送给模型的 fork transcript。
### 3.6 生命周期
完全复用官方既有机制:
- **运行中**`isBackgroundTask()` 谓词为真selector 列出
- **完成 / 失败 / 中止**`completeAgentTask` / `failAgentTask` / `killAsyncAgent``status` 为 terminal
- **回访后退出**`exitTeammateView``release(task)`——清 `retain`、清 `messages`、terminal 状态下设 `evictAfter = now + PANEL_GRACE_MS (30s)`
- **evictAfter 过期**`useBackgroundAgentTasks` 过滤时自然剔除selector 行消失
- **手动清除**`stopOrDismissAgent(taskId)``evictAfter = 0`,立即消失
## 四、设计决策
1. **数据源单一**`useBackgroundAgentTasks` 是唯一过滤点PromptInput 也复用,避免过滤条件散落
2. **pill 聚焦保留**Enter 切视图后不松焦,让 ↑↓ 连续导航,贴近官方体验
3. **`bg_agent` 放 footerItems[0]**:确保 ↓ 溢出直接进入 selector 而非其它 pill
4. **selector 不订阅键盘**:所有按键路由集中在 PromptInput 的 `footer:*` 分支,避免 selector 组件和 PromptInput 双重 `useInput` 的冲突
5. **`selectedBgAgentIndex` 存 AppState 而非局部 state**selector 和 PromptInput 分别在两棵不同子树,需要全局字段协调;该值不能从 `viewingAgentTaskId` 派生
6. **与 `BackgroundTasksDialog` 共存**Shift+↓ 行为完全不变selector 是补充快捷入口Dialog 仍管 shell / workflow / monitor_mcp 等 selector 不显示的 task 类型
7. **fork prompt 展示层兜底**fork prompt 不依赖 boilerplate 自身渲染,统一在 `displayedAgentMessages` 中合成独立用户消息;普通 subagent 不走该分支,避免 prompt 重复
## 五、关键 API 复用
| 官方已有能力 | selector 如何使用 |
|---|---|
| `AppState.tasks` | 单一数据源,无需 file watcher / output JSONL 订阅 |
| `registerAsyncAgent` | `/fork` 和 AgentTool 共用selector 不区分来源 |
| `enterTeammateView(id)` | Enter 时调用,负责 retain + disk bootstrap |
| `exitTeammateView` | Enter 选中 `main` 时调用 |
| `release(task)` + `PANEL_GRACE_MS` | 30s keep-aliveselector 自动生效 |
| `useElapsedTime` | 每行时长显示,非 running 自动停 interval |
| `formatTokens` (`utils/format.ts`) | token 数 1k 缩写 |
| `footer:up` / `footer:down` / `footer:openSelected` keybinding | 键盘路由复用 Footer context |
## 六、文件索引
| 文件 | 职责 |
|------|------|
| `src/hooks/useBackgroundAgentTasks.ts` | 数据过滤 hookbackgrounded local_agent + evictAfter 过滤 + startTime 排序) |
| `src/components/tasks/BackgroundAgentSelector.tsx` | 底部 selector UI纯展示 |
| `src/components/PromptInput/PromptInput.tsx` | 新增 `'bg_agent'` footer pill + 对应的 `footer:up/down/openSelected` 分支 |
| `src/state/AppStateStore.ts` | `FooterItem``'bg_agent'`;新增 `selectedBgAgentIndex` 字段 |
| `src/main.tsx` | `getDefaultAppState` 同步初始化 `selectedBgAgentIndex: -1` |
| `src/screens/REPL.tsx` | 在 PromptInput + SessionBackgroundHint 之后挂载 `<BackgroundAgentSelector />`;切换 agent 主视图;对 fork transcript 做 prompt 归一化 |
| `src/components/messages/AssistantToolUseMessage.tsx` | 新增 `defaultCollapsed?: boolean` prop为后续详情视图默认折叠工具块预留 |
| `src/components/messages/UserTextMessage.tsx` | 识别 `<fork-boilerplate>`,交给 fork 专用 renderer 处理 |
| `src/components/messages/UserForkBoilerplateMessage.tsx` | 将 fork boilerplate text 折叠为纯用户 prompt作为 transcript 中原位渲染的兼容路径 |
## 七、已知限制
- `Date.now()``useBackgroundAgentTasks` 的 useMemo 里冻结于 `[tasks]` 触发时:若长时间没有新 task 变更事件,某个 terminal agent 的 grace 期过期后不会立即从 selector 消失,要等下一次 tasks 变化才刷新。在典型使用(主对话一直在产生消息)下感知不到,暂不额外加 interval。
- Selector 当前不处理 Shell Task / Workflow / Monitor MCP 等类型——这些仍走 `BackgroundTasksDialog`Shift+↓)管理。
- `AssistantToolUseMessage``defaultCollapsed` prop 目前无调用方传值,保留作为后续"agent 详情视图内工具块默认折叠"扩展点。

View File

@@ -0,0 +1,275 @@
---
title: "StatusLine 底部状态栏 - 自定义 shell 渲染管线"
description: "从源码角度解析 Claude Code 底部状态栏:自定义 shell 脚本 + JSON stdin 协议、三种触发源event / settings / time、debounce + abort、信任与 hook 开关、以及本仓库 refreshInterval 缺失修复。"
keywords: ["statusLine", "状态栏", "自定义提示符", "refreshInterval", "Hooks"]
---
{/* 本章目标:完整讲清 StatusLine 的渲染管线、触发模型、协议契约与安全网关,并记录本仓库相对官方版本的已知缺口与修复 */}
## 概述
StatusLine 是 Claude Code REPL 底部显示的一行自定义文本,由**用户提供的 shell 命令**渲染。主进程把运行时状态模型、工作目录、token、限流、会话元数据等打包成 JSON 通过 stdin 喂给脚本,脚本在 stdout 输出一行字符串Ink 侧以 ANSI 转义渲染到 footer。
核心设计哲学:**语言无关 + 进程隔离 + Unix 管道**。用户可用 bash / python / node / 任意语言写脚本;脚本崩溃不影响主进程;输入输出都是纯文本,可以离线测试(`echo '{...}' | ./script.sh`)。
## 配置
`~/.claude/settings.json` 里添加 `statusLine` 字段:
```json
{
"statusLine": {
"type": "command",
"command": "bash ~/.claude/statusline-command.sh",
"refreshInterval": 1,
"padding": 0
}
}
```
| 字段 | 类型 | 作用 |
|------|------|------|
| `type` | `"command"` | 目前仅支持 command 型 |
| `command` | `string` | shell 命令字符串;主进程用系统 shell 解释执行 |
| `refreshInterval` | `number` (秒) | 定时刷新周期;缺省/0 表示不定时刷新 |
| `padding` | `number` | 左右 padding单位为 Ink cell |
Schema 定义在 `src/utils/settings/types.ts:550``statusLine` Zod object
## 渲染管线(整体图)
```
┌─────────────────────── Ink 侧 ───────────────────────┐ ┌──────── 用户侧 ────────┐
│ │ │ │
│ buildStatusLineCommandInput() ──┐ │ │ ~/.claude/ │
│ 收集运行时状态 │ │ │ statusline-*.sh │
│ ▼ │ │ │
│ executeStatusLineCommand() ─── JSON via stdin ────────────► jq '.model...' │
│ execCommandHook() 拉起 shell │ │ 计算、格式化 │
│ ▲ │ │ │
│ stdout ◄──────────────────── 一行文本 ──────────────── printf '...' │
│ │ │ │ │
│ setAppState({ statusLineText }) ─┘ │ └────────────────────────┘
│ zustand 存字段,组件 memo 订阅 │
│ │
│ <StatusLine /> → <Text><Ansi>{text}</Ansi></Text> │
│ │
└──────────────────────────────────────────────────────┘
```
## Input 协议:主进程 → 脚本
`buildStatusLineCommandInput``src/components/StatusLine.tsx:53`)构造的 JSON 对象字段如下,**这是脚本可以 `jq` 读取的全部内容**
| 字段 | 来源 | 备注 |
|------|------|------|
| `session_id` | `getSessionId()` | UUID用于脚本侧 per-session 状态隔离 |
| `session_name` | `getCurrentSessionTitle(sessionId)` | 用户命名的会话标题(可选) |
| `model.id` / `model.display_name` | `getRuntimeMainLoopModel()` | 运行时真实模型(经 permission mode 降级/200k 升级) |
| `workspace.current_dir` / `project_dir` / `added_dirs` | `getCwd()` / `getOriginalCwd()` / permission context | current_dir 随 `cd` 变化 |
| `version` | `MACRO.VERSION` | 构建注入,如 `2.1.888` |
| `output_style.name` | `settings.outputStyle` | 缺省 `DEFAULT_OUTPUT_STYLE_NAME` |
| `cost.total_cost_usd` / `total_duration_ms` / `total_api_duration_ms` / `total_lines_added` / `total_lines_removed` | `cost-tracker.js` 聚合 | 会话累计 |
| `context_window.total_input_tokens` / `total_output_tokens` | 同上 | 累计 token |
| `context_window.context_window_size` | `getContextWindowForModel()` | 模型上下文上限 |
| `context_window.current_usage` | `getCurrentUsage(messages)` | **最新一次 assistant message 的 usage**;含 `input_tokens` / `cache_creation_input_tokens` / `cache_read_input_tokens` / `output_tokens` |
| `context_window.used_percentage` / `remaining_percentage` | `calculateContextPercentages()` | 0-100 浮点 |
| `exceeds_200k_tokens` | 检查最近 assistant message | 用于 1M 上下文模型的展示 |
| `rate_limits.five_hour` / `seven_day` | `getRawUtilization()` | `{ used_percentage, resets_at }`,来自 Claude.ai 限流 API |
| `vim.mode` | 启用 vim 模式时 | `INSERT` / `NORMAL` / ... |
| `agent.name` | 主线程 agent 类型 | 子 agent fork 时非空 |
| `remote.session_id` | Bridge / Remote Control 模式 | 远程会话 |
| `worktree` | 当前 worktree 元信息 | `name` / `path` / `branch` / `original_cwd` / `original_branch` |
类型签名目前在 `src/types/statusLine.ts` 是 `any` 的 stub反编译残留实际字段以上表为准。
## Output 协议:脚本 → 主进程
`executeStatusLineCommand``src/utils/hooks.ts:4752`)对脚本 stdout 做如下处理:
1. `trim()` 首尾空白
2. 按 `\n` 拆行,每行再 `trim()`
3. 空行丢弃,剩余用 `\n` 重新拼接
多行输出会被**保留为多行**Ink 渲染时 `<Text>` 允许换行),但设计推荐**单行**——多行会挤占 REPL 高度fullscreen 模式下可能挤掉 ScrollBox 行。
状态码约定:
- `exit 0` + 有 stdout → 显示
- `exit 0` + 空 stdout → 清空 statusLine显示为空
- 非 0 → 忽略,保留上次内容;`logResult=true` 时 warn 级日志
- 超时(默认 5000ms → 忽略
- 被 AbortController 取消 → 忽略
ANSI 颜色可用Ink 通过 `<Ansi>{text}</Ansi>` 组件解析 SGR 序列。
## 三种触发源
StatusLine 的重算由**三类事件**驱动,全部经同一个 debounce 队列:
### 1. Event-driven`src/components/StatusLine.tsx:275`
监听这些状态变化,触发 `scheduleUpdate()`
- `lastAssistantMessageId` — 新助手回复出现
- `permissionMode` — `/mode` 切换权限模式
- `vimMode` — vim insert/normal 切换
- `mainLoopModel` — `/model` 切换
### 2. Settings-driven`src/components/StatusLine.tsx:294`
`settings.statusLine.command` 字符串变化时(热重载 settings.json标记下一次结果 log 并立即 `doUpdate()`。
### 3. Time-driven`src/components/StatusLine.tsx:292`,本仓库补丁)
读取 `settings.statusLine.refreshInterval`(秒),`setInterval` 每到点走一次 `scheduleUpdate()`。配置为 0 或缺省时不启定时器(零开销)。
> **本仓库历史缺口**:反编译出的 `StatusLine.tsx` 最初没有 Time-driven 触发路径,`refreshInterval` 字段也不在 Zod schema 里。导致脚本里 TTL 倒计时、时钟类动态内容不会秒刷,只有助手回复出现时才重算。已在 2026-05-06 补齐,细节见下方"已知缺口与修复"。
## Debounce + Abort
三种触发源都走 `scheduleUpdate``src/components/StatusLine.tsx:259`
```
scheduleUpdate() → setTimeout(300ms) → doUpdate()
└─ 再次 schedule 会 clearTimeout 前次
```
300ms debounce 合并抖动事件(例如短时间连续切 vim/permission
`doUpdate()` 里:
```
abortControllerRef.current?.abort() // 取消上一次 in-flight shell
controller = new AbortController()
executeStatusLineCommand(..., controller.signal, ...)
```
**单飞single-flight语义**:任何新触发都会 abort 上一次未完成的 shell 调用,保证同一时刻最多一个子进程。这对 `refreshInterval: 1` 尤其关键——若脚本执行 > 1 秒,新 tick 到来时老进程被 kill不会堆积。
## 安全网关
`executeStatusLineCommand``src/utils/hooks.ts:4752`)在执行前有**三层拦截**
1. `shouldDisableAllHooksIncludingManaged()` → managed settings 全局禁用 hooks 时直接返回
2. `shouldSkipHookDueToTrust()` → **工作区未接受信任对话框时跳过**,避免打开未知仓库时执行任意 shell 命令RCE 防护)
3. `shouldAllowManagedHooksOnly()` → 非 managed settings 禁用 hooks 但 managed 未禁用时,只读取 policySettings 源的 statusLine
组件侧配合(`src/components/StatusLine.tsx:318`):未接受 trust 时在通知中心提示 `"statusline skipped · restart to fix"`。
另外,`statusLineShouldDisplay``src/components/StatusLine.tsx:46`)在 **Kairos assistant mode** 下直接返回 false——因为那时 statusline 字段反映的是 REPL/daemon 进程状态,不是 agent 子进程在跑的东西,显示出来会误导用户。
## 渲染细节
### memo 隔离
```tsx
export const StatusLine = memo(StatusLineInner)
```
父组件 `PromptInputFooter` 每次 `setMessages` 都 rerender但 `StatusLine` 的 props 只有 `lastAssistantMessageId` 会变,`memo` 阻断了无意义的重渲染。此前(未 memo 版本)一个 session 内大约 18 次冗余渲染。
### 订阅粒度
```tsx
const statusLineText = useAppState(s => s.statusLineText)
```
`useAppState` 是选择器订阅,仅在 `statusLineText` 字段变化时触发 rerender`doUpdate()` 里还做了幂等检查(`prev.statusLineText === text` 则直接返回原 state**文本不变就不更新 zustand**,连一次 notify 都省掉。
### Fullscreen 占位
```tsx
{statusLineText ? (
<Text dimColor wrap="truncate"><Ansi>{statusLineText}</Ansi></Text>
) : isFullscreenEnvEnabled() ? (
<Text> </Text> // 占位一行
) : null}
```
Fullscreen 模式下 footer `flexShrink:0`statusline 从 0 行变 1 行会挤掉 ScrollBox 一行内容导致抖动。首次脚本还没返回时,用空格文本占住一行高度,脚本返回后原位替换。
## 内置 `/statusline` slash command
`src/commands/statusline.tsx` 定义了一个 **prompt 型 command**,展开成自然语言指令喂给主 Agent
```
Create an AgentTool with subagent_type "statusline-setup" and the prompt "<user-args>"
```
默认 prompt 是 `"Configure my statusLine from my shell PS1 configuration"`。主 Agent 收到后会调用内置子 agent `statusline-setup`。该子 agent 权限极小:
- **Tools**: 仅 `Read`、`Edit`
- **Allowed paths**: `Read(~/**)`、`Edit(~/.claude/settings.json)`
也就是说它**不能 Write 新文件、不能跑 Bash**。典型工作是读用户的 shell 配置、读/改 `settings.json`、增量编辑已有的 statusline 脚本。
## 编写自定义脚本的要点
1. **脚本必须无状态** — 每次 tick 主进程 fork 一次新 shell进程内变量不跨调用保留。需要跨 tick 的状态(上次时间戳、上次 token 数)用 `~/.claude/statusline-state/<hash>.state` 文件持久化。
2. **按 `session_id` 哈希隔离状态文件** — 多会话同时开着时共享一个 state 文件会串。典型做法:`md5(session_id) | head -c 16` 作为文件名。
3. **防御性读取** — state 文件可能损坏/被截断,按行 read + 字段校验(数字字段用 `case "$var" in ''|*[!0-9]*) invalid ;;`)。
4. **`refreshInterval` 不等于"脚本秒级调用"** — tick 和事件触发(新消息、模式切换)都走同一 debounce 队列,脚本实际被调用的频率介于"每 N 秒"和"每 N+0.3 秒"之间;且 abort 机制下,上一次没跑完会被 kill。
5. **执行时间预算** — 默认 5000ms 超时;为避免 `refreshInterval=1` 时频繁超时,脚本热路径应在 100ms 内完成。重计算curl、git log 拉取)需缓存。
6. **颜色用 ANSI 转义** — 不要依赖 TERM 环境变量Ink 的 `<Ansi>` 组件独立解析 SGR。
7. **不要输出多行** — 单行文本,否则挤占 REPL 布局。
8. **处理 `current_usage` 为 null 的情况** — 首次响应之前 `context_window.current_usage` 可能为 null脚本应有 fallback如读 state 里上次命中率)。
### 示例Cache 命中率 + TTL 倒计时
本仓库默认安装了一个示例脚本 `~/.claude/statusline-command.sh`(用户侧),输出格式 `<dir> | <model> | ctx:N% | Cache 97% 59:43`
- **命中率** = `cache_read / (input + cache_creation + cache_read)`(取自 `current_usage`
- **TTL** 从上次响应倒数 60 分钟,**只在 token signature 变化时重置时间戳**,避免秒级 tick 把 TTL 一直锁在 60:00
- **颜色分段** — 命中率 ≥50% 绿 / <50% 灰TTL 0-20m 绿 / 20-40m 黄 / 40-55m 红 / 最后 5m 闪红 / 过期 `exp` 灰
- **Per-session state** — `~/.claude/statusline-state/<md5(session_id)[:16]>.state` 三行signature、timestamp、hit读前做 numeric 校验
- **Fallback** — `current_usage` 为 null 时读 state 显示上次命中率
> 该脚本配合 `refreshInterval: 1` 即可秒刷 TTL前提是 `refreshInterval` 触发路径已实现(见下节)。
## 已知缺口与修复(本仓库)
反编译版的 `StatusLine.tsx` 存在一处功能缺口:
| 项 | 官方 Claude Code | 本仓库原始 | 本仓库现状 |
|----|-----------------|-----------|-----------|
| `refreshInterval` Zod 字段 | ✅ 有 | ❌ 无 | ✅ 已补 |
| Time-driven `setInterval` 触发 | ✅ 有 | ❌ 无 | ✅ 已补 |
| Event-driven 触发 | ✅ 有 | ✅ 有 | — |
| Settings-driven 触发 | ✅ 有 | ✅ 有 | — |
| Debounce + Abort | ✅ 有 | ✅ 有 | — |
| Trust 网关 | ✅ 有 | ✅ 有 | — |
修复2026-05-06
**1. `src/utils/settings/types.ts:554`** — statusLine schema 新增 `refreshInterval: z.number().optional()`,让字段进入类型系统而非被当未知键忽略。
**2. `src/components/StatusLine.tsx:292`** — 新增 Time-driven useEffect
```tsx
const refreshIntervalMs = (settings?.statusLine?.refreshInterval ?? 0) * 1000;
useEffect(() => {
if (refreshIntervalMs <= 0) return;
const id = setInterval(() => scheduleUpdate(), refreshIntervalMs);
return () => clearInterval(id);
}, [refreshIntervalMs, scheduleUpdate]);
```
关键点:
- 走 `scheduleUpdate`(非 `doUpdate`)复用 300ms debounceinterval + event 双触发不会双跑
- `refreshIntervalMs <= 0` 时不启定时器,对未启用该字段的用户零开销
- 依赖数组含 `refreshIntervalMs`settings 热重载会自动清理旧 interval 重建新的
**静默失效特征**:修复前 settings.json 写 `refreshInterval: 1` 无任何报错——JSON 解析通过Zod schema 默认 strip 多余字段,官方文档又说支持这个字段,用户很容易以为生效了而没意识到 TTL/时钟类输出根本没秒刷。这是反编译版本的典型"文档与实现不一致"。
## 相关源码
| 文件 | 作用 |
|------|------|
| `src/components/StatusLine.tsx` | UI 组件、触发逻辑、buildStatusLineCommandInput |
| `src/utils/hooks.ts:4752` | `executeStatusLineCommand`shell 执行、输出处理、安全网关 |
| `src/utils/settings/types.ts:550` | `statusLine` Zod schema |
| `src/types/statusLine.ts` | `StatusLineCommandInput` 类型(当前为 stub |
| `src/commands/statusline.tsx` | `/statusline` slash command 定义 |
| `src/state/AppStateStore.ts:95` | `statusLineText` 字段声明 |
| `src/components/PromptInput/PromptInputFooter.tsx:159` | StatusLine 组件挂载点 |

View File

@@ -1,6 +1,6 @@
{
"name": "claude-code-best",
"version": "2.1.0",
"version": "2.2.0",
"description": "Reverse-engineered Anthropic Claude Code CLI — interactive AI coding assistant in the terminal",
"type": "module",
"author": "claude-code-best <claude-code-best@proton.me>",

View File

@@ -1,5 +1,7 @@
import type { ToolResultBlockParam } from '@anthropic-ai/sdk/resources/index.mjs';
import type { StructuredPatchHunk } from 'diff';
import * as React from 'react';
import { Suspense, use, useState } from 'react';
import { FileEditToolUseRejectedMessage } from 'src/components/FileEditToolUseRejectedMessage.js';
import { MessageResponse } from 'src/components/MessageResponse.js';
import { extractTag } from 'src/utils/messages.js';
@@ -10,10 +12,15 @@ import { Text } from '@anthropic/ink';
import { FilePathLink } from 'src/components/FilePathLink.js';
import type { Tools } from 'src/Tool.js';
import type { Message, ProgressMessage } from 'src/types/message.js';
import { adjustHunkLineNumbers, CONTEXT_LINES } from 'src/utils/diff.js';
import { FILE_NOT_FOUND_CWD_NOTE, getDisplayPath } from 'src/utils/file.js';
import { logError } from 'src/utils/log.js';
import { getPlansDirectory } from 'src/utils/plans.js';
import { readEditContext } from 'src/utils/readEditContext.js';
import { firstLineOf } from 'src/utils/stringUtils.js';
import type { ThemeName } from 'src/utils/theme.js';
import type { FileEditOutput } from './types.js';
import { findActualString, getPatchForEdit, preserveQuoteStyle } from './utils.js';
export function userFacingName(
input:
@@ -84,6 +91,8 @@ export function renderToolResultMessage(
<FileEditToolUpdatedMessage
filePath={filePath}
structuredPatch={structuredPatch}
firstLine={originalFile.split('\n')[0] ?? null}
fileContent={originalFile}
style={style}
verbose={verbose}
previewHint={isPlanFile ? '/plan to preview' : undefined}
@@ -99,7 +108,7 @@ export function renderToolUseRejectedMessage(
replace_all?: boolean;
edits?: unknown[];
},
_options: {
options: {
columns: number;
messages: Message[];
progressMessagesForMessage: ProgressMessage[];
@@ -109,14 +118,40 @@ export function renderToolUseRejectedMessage(
verbose: boolean;
},
): React.ReactElement {
const { style, verbose } = _options;
const { style, verbose } = options;
const filePath = input.file_path;
const isNewFile = input.old_string === '';
const oldString = input.old_string ?? '';
const newString = input.new_string ?? '';
const replaceAll = input.replace_all ?? false;
// Defensive: if input has an unexpected shape, show a simple rejection message
if ('edits' in input && input.edits != null) {
return (
<FileEditToolUseRejectedMessage file_path={filePath} operation="update" firstLine={null} verbose={verbose} />
);
}
const isNewFile = oldString === '';
// For new file creation, show content preview instead of diff
if (isNewFile) {
return (
<FileEditToolUseRejectedMessage
file_path={filePath}
operation="write"
content={newString}
firstLine={firstLineOf(newString)}
verbose={verbose}
/>
);
}
return (
<FileEditToolUseRejectedMessage
file_path={filePath}
operation={isNewFile ? 'write' : 'update'}
<EditRejectionDiff
filePath={filePath}
oldString={oldString}
newString={newString}
replaceAll={replaceAll}
style={style}
verbose={verbose}
/>
@@ -149,3 +184,103 @@ export function renderToolUseErrorMessage(
}
return <FallbackToolUseErrorMessage result={result} verbose={verbose} />;
}
type RejectionDiffData = {
patch: StructuredPatchHunk[];
firstLine: string | null;
fileContent: string | undefined;
};
function EditRejectionDiff({
filePath,
oldString,
newString,
replaceAll,
style,
verbose,
}: {
filePath: string;
oldString: string;
newString: string;
replaceAll: boolean;
style?: 'condensed';
verbose: boolean;
}): React.ReactNode {
const [dataPromise] = useState(() => loadRejectionDiff(filePath, oldString, newString, replaceAll));
return (
<Suspense
fallback={
<FileEditToolUseRejectedMessage file_path={filePath} operation="update" firstLine={null} verbose={verbose} />
}
>
<EditRejectionBody promise={dataPromise} filePath={filePath} style={style} verbose={verbose} />
</Suspense>
);
}
function EditRejectionBody({
promise,
filePath,
style,
verbose,
}: {
promise: Promise<RejectionDiffData>;
filePath: string;
style?: 'condensed';
verbose: boolean;
}): React.ReactNode {
const { patch, firstLine, fileContent } = use(promise);
return (
<FileEditToolUseRejectedMessage
file_path={filePath}
operation="update"
patch={patch}
firstLine={firstLine}
fileContent={fileContent}
style={style}
verbose={verbose}
/>
);
}
async function loadRejectionDiff(
filePath: string,
oldString: string,
newString: string,
replaceAll: boolean,
): Promise<RejectionDiffData> {
try {
// Chunked read — context window around the first occurrence. replaceAll
// still shows matches *within* the window via getPatchForEdit; we accept
// losing the all-occurrences view to keep the read bounded.
const ctx = await readEditContext(filePath, oldString, CONTEXT_LINES);
if (ctx === null || ctx.truncated || ctx.content === '') {
// ENOENT / not found / truncated — diff just the tool inputs.
const { patch } = getPatchForEdit({
filePath,
fileContents: oldString,
oldString,
newString,
});
return { patch, firstLine: null, fileContent: undefined };
}
const actualOld = findActualString(ctx.content, oldString) || oldString;
const actualNew = preserveQuoteStyle(oldString, actualOld, newString);
const { patch } = getPatchForEdit({
filePath,
fileContents: ctx.content,
oldString: actualOld,
newString: actualNew,
replaceAll,
});
return {
patch: adjustHunkLineNumbers(patch, ctx.lineOffset - 1),
firstLine: ctx.lineOffset === 1 ? firstLineOf(ctx.content) : null,
fileContent: ctx.content,
};
} catch (e) {
// User may have manually applied the change while the diff was shown.
logError(e as Error);
return { patch: [], firstLine: null, fileContent: undefined };
}
}

View File

@@ -1,6 +1,8 @@
import type { ToolResultBlockParam } from '@anthropic-ai/sdk/resources/index.mjs';
import { relative } from 'path';
import type { StructuredPatchHunk } from 'diff';
import { isAbsolute, relative, resolve } from 'path';
import * as React from 'react';
import { Suspense, use, useState } from 'react';
import { MessageResponse } from 'src/components/MessageResponse.js';
import { extractTag } from 'src/utils/messages.js';
import { CtrlOToExpand } from 'src/components/CtrlOToExpand.js';
@@ -15,8 +17,11 @@ import { FilePathLink } from 'src/components/FilePathLink.js';
import type { ToolProgressData } from 'src/Tool.js';
import type { ProgressMessage } from 'src/types/message.js';
import { getCwd } from 'src/utils/cwd.js';
import { getPatchForDisplay } from 'src/utils/diff.js';
import { getDisplayPath } from 'src/utils/file.js';
import { logError } from 'src/utils/log.js';
import { getPlansDirectory } from 'src/utils/plans.js';
import { openForScan, readCapped } from 'src/utils/readEditContext.js';
import type { Output } from './FileWriteTool.js';
const MAX_LINES_TO_RENDER = 10;
@@ -122,10 +127,115 @@ export function renderToolUseMessage(
}
export function renderToolUseRejectedMessage(
{ file_path }: { file_path: string; content: string },
{ file_path, content }: { file_path: string; content: string },
{ style, verbose }: { style?: 'condensed'; verbose: boolean },
): React.ReactNode {
return <FileEditToolUseRejectedMessage file_path={file_path} operation="write" style={style} verbose={verbose} />;
return <WriteRejectionDiff filePath={file_path} content={content} style={style} verbose={verbose} />;
}
type RejectionDiffData =
| { type: 'create' }
| { type: 'update'; patch: StructuredPatchHunk[]; oldContent: string }
| { type: 'error' };
function WriteRejectionDiff({
filePath,
content,
style,
verbose,
}: {
filePath: string;
content: string;
style?: 'condensed';
verbose: boolean;
}): React.ReactNode {
const [dataPromise] = useState(() => loadRejectionDiff(filePath, content));
const firstLine = content.split('\n')[0] ?? null;
const createFallback = (
<FileEditToolUseRejectedMessage
file_path={filePath}
operation="write"
content={content}
firstLine={firstLine}
verbose={verbose}
/>
);
return (
<Suspense fallback={createFallback}>
<WriteRejectionBody
promise={dataPromise}
filePath={filePath}
firstLine={firstLine}
createFallback={createFallback}
style={style}
verbose={verbose}
/>
</Suspense>
);
}
function WriteRejectionBody({
promise,
filePath,
firstLine,
createFallback,
style,
verbose,
}: {
promise: Promise<RejectionDiffData>;
filePath: string;
firstLine: string | null;
createFallback: React.ReactNode;
style?: 'condensed';
verbose: boolean;
}): React.ReactNode {
const data = use(promise);
if (data.type === 'create') return createFallback;
if (data.type === 'error') {
return (
<MessageResponse>
<Text>(No changes)</Text>
</MessageResponse>
);
}
return (
<FileEditToolUseRejectedMessage
file_path={filePath}
operation="update"
patch={data.patch}
firstLine={firstLine}
fileContent={data.oldContent}
style={style}
verbose={verbose}
/>
);
}
async function loadRejectionDiff(filePath: string, content: string): Promise<RejectionDiffData> {
try {
const fullFilePath = isAbsolute(filePath) ? filePath : resolve(getCwd(), filePath);
const handle = await openForScan(fullFilePath);
if (handle === null) return { type: 'create' };
let oldContent: string | null;
try {
oldContent = await readCapped(handle);
} finally {
await handle.close();
}
// File exceeds MAX_SCAN_BYTES — fall back to the create view rather than
// OOMing on a diff of a multi-GB file.
if (oldContent === null) return { type: 'create' };
const patch = getPatchForDisplay({
filePath,
fileContents: oldContent,
edits: [{ old_string: oldContent, new_string: content, replace_all: false }],
});
return { type: 'update', patch, oldContent };
} catch (e) {
// User may have manually applied the change while the diff was shown.
logError(e as Error);
return { type: 'error' };
}
}
export function renderToolUseErrorMessage(
@@ -179,6 +289,8 @@ export function renderToolResultMessage(
<FileEditToolUpdatedMessage
filePath={filePath}
structuredPatch={structuredPatch}
firstLine={content.split('\n')[0] ?? null}
fileContent={originalFile ?? undefined}
style={style}
verbose={verbose}
previewHint={isPlanFile ? '/plan to preview' : undefined}

View File

@@ -65,7 +65,7 @@ export const DEFAULT_BUILD_FEATURES = [
// 'FORK_SUBAGENT', // 已禁用:显式 `fork: true` 参数触发 fork 路径(继承父级上下文和模型),不影响 forceAsync 和探索任务模型选择
// 'UDS_INBOX', // inbox 数组只增不减(非 GB 级主因)
'KAIROS', // Kairos 定时任务系统核心
// 'COORDINATOR_MODE', // 已禁用AgentSummary 30s fork 循环GB 级泄露主因
'COORDINATOR_MODE', // 多 worker 编排模式AgentSummary 泄露已在 52b61c2c 修复)
// 'LAN_PIPES', // 依赖 UDS_INBOX已随 UDS_INBOX 恢复)
'BG_SESSIONS', // 后台会话管理ps/logs/attach/kill
'TEMPLATES', // 模板任务new/list/reply 子命令)

View File

@@ -14,20 +14,11 @@ const __dirname = dirname(__filename)
const projectRoot = join(__dirname, '..')
const cliPath = join(projectRoot, 'src/entrypoints/cli.tsx')
// React production mode — prevents 6,889+ _debugStack Error objects
// (12MB) from accumulating during long-running sessions.
// Opt-in via CLAUDE_CODE_FORCE_NODE_ENV=production for dev sessions that
// need the memory optimization. Default keeps NODE_ENV='development' so
// dev-only diagnostics (DevBar, doctorDiagnostic, AutoUpdater dev branches,
// etc.) continue to work.
const forcedNodeEnv =
process.env.CLAUDE_CODE_FORCE_NODE_ENV ??
process.env.NODE_ENV ??
'development'
const defines = {
...getMacroDefines(),
'process.env.NODE_ENV': JSON.stringify(forcedNodeEnv),
// React production mode — prevents 6,889+ _debugStack Error objects
// (12MB) from accumulating during long-running sessions.
'process.env.NODE_ENV': JSON.stringify('production'),
}
const defineArgs = Object.entries(defines).flatMap(([k, v]) => [

View File

@@ -43,8 +43,12 @@ export async function call(
// Omitting subagent_type triggers implicit fork.
const input = {
prompt: directive,
fork: true, // 触发 AgentTool 的 fork 路径:继承父会话上下文 + system prompt + 模型
run_in_background: true, // fork always runs async
description: `Fork: ${directive.slice(0, 30)}${directive.length > 30 ? '...' : ''}`,
// description 只显示在底部 selector / BackgroundTasksDialog保持简短标签
// 即可;用户输入的 prompt 会作为第一条用户消息呈现在主视图里,这里不要
// 重复显示。
description: 'forked from main',
};
// Call AgentTool with proper parameters:

View File

@@ -1,23 +1,31 @@
import type { StructuredPatchHunk } from 'diff';
import * as React from 'react';
import { Text } from '@anthropic/ink';
import { useTerminalSize } from '../hooks/useTerminalSize.js';
import { Box, Text } from '@anthropic/ink';
import { count } from '../utils/array.js';
import { MessageResponse } from './MessageResponse.js';
import { StructuredDiffList } from './StructuredDiffList.js';
type Props = {
filePath: string;
structuredPatch: { lines: string[] }[];
structuredPatch: StructuredPatchHunk[];
firstLine: string | null;
fileContent?: string;
style?: 'condensed';
verbose: boolean;
previewHint?: string;
};
export function FileEditToolUpdatedMessage({
filePath: _filePath,
filePath,
structuredPatch,
firstLine,
fileContent,
style,
verbose,
previewHint,
}: Props): React.ReactNode {
const { columns } = useTerminalSize();
const numAdditions = structuredPatch.reduce((acc, hunk) => acc + count(hunk.lines, _ => _.startsWith('+')), 0);
const numRemovals = structuredPatch.reduce((acc, hunk) => acc + count(hunk.lines, _ => _.startsWith('-')), 0);
@@ -39,7 +47,7 @@ export function FileEditToolUpdatedMessage({
// Plan files: invert condensed behavior
// - Regular mode: just show the hint (user can type /plan to see full content)
// - Condensed mode (subagent view): show the text
// - Condensed mode (subagent view): show the diff
if (previewHint) {
if (style !== 'condensed' && !verbose) {
return (
@@ -52,5 +60,19 @@ export function FileEditToolUpdatedMessage({
return text;
}
return <MessageResponse>{text}</MessageResponse>;
return (
<MessageResponse>
<Box flexDirection="column">
<Text>{text}</Text>
<StructuredDiffList
hunks={structuredPatch}
dim={false}
width={columns - 12}
filePath={filePath}
firstLine={firstLine}
fileContent={fileContent}
/>
</Box>
</MessageResponse>
);
}

View File

@@ -1,17 +1,39 @@
import type { StructuredPatchHunk } from 'diff';
import { relative } from 'path';
import * as React from 'react';
import { useTerminalSize } from 'src/hooks/useTerminalSize.js';
import { getCwd } from 'src/utils/cwd.js';
import { Box, Text } from '@anthropic/ink';
import { HighlightedCode } from './HighlightedCode.js';
import { MessageResponse } from './MessageResponse.js';
import { StructuredDiffList } from './StructuredDiffList.js';
const MAX_LINES_TO_RENDER = 10;
type Props = {
file_path: string;
operation: 'write' | 'update';
// For updates - show diff
patch?: StructuredPatchHunk[];
firstLine: string | null;
fileContent?: string;
// For new file creation - show content preview
content?: string;
style?: 'condensed';
verbose: boolean;
};
export function FileEditToolUseRejectedMessage({ file_path, operation, style, verbose }: Props): React.ReactNode {
export function FileEditToolUseRejectedMessage({
file_path,
operation,
patch,
firstLine,
fileContent,
content,
style,
verbose,
}: Props): React.ReactNode {
const { columns } = useTerminalSize();
const text = (
<Box flexDirection="row">
<Text color="subtle">User rejected {operation} to </Text>
@@ -26,5 +48,42 @@ export function FileEditToolUseRejectedMessage({ file_path, operation, style, ve
return <MessageResponse>{text}</MessageResponse>;
}
return <MessageResponse>{text}</MessageResponse>;
// For new file creation, show content preview (dimmed)
if (operation === 'write' && content !== undefined) {
const lines = content.split('\n');
const numLines = lines.length;
const plusLines = numLines - MAX_LINES_TO_RENDER;
const truncatedContent = verbose ? content : lines.slice(0, MAX_LINES_TO_RENDER).join('\n');
return (
<MessageResponse>
<Box flexDirection="column">
{text}
<HighlightedCode code={truncatedContent || '(No content)'} filePath={file_path} width={columns - 12} dim />
{!verbose && plusLines > 0 && <Text dimColor> +{plusLines} lines</Text>}
</Box>
</MessageResponse>
);
}
// For updates, show diff
if (!patch || patch.length === 0) {
return <MessageResponse>{text}</MessageResponse>;
}
return (
<MessageResponse>
<Box flexDirection="column">
{text}
<StructuredDiffList
hunks={patch}
dim
width={columns - 12}
filePath={file_path}
firstLine={firstLine}
fileContent={fileContent}
/>
</Box>
</MessageResponse>
);
}

View File

@@ -26,6 +26,7 @@ import { useSetPromptOverlayDialog } from '../../context/promptOverlayContext.js
import { formatImageRef, formatPastedTextRef, getPastedTextRefNumLines, parseReferences } from '../../history.js';
import type { VerificationStatus } from '../../hooks/useApiKeyVerification.js';
import { type HistoryMode, useArrowKeyHistory } from '../../hooks/useArrowKeyHistory.js';
import { useBackgroundAgentTasks } from '../../hooks/useBackgroundAgentTasks.js';
import { useDoublePress } from '../../hooks/useDoublePress.js';
import { useHistorySearch } from '../../hooks/useHistorySearch.js';
import type { IDESelection } from '../../hooks/useIdeSelection.js';
@@ -415,6 +416,16 @@ function PromptInput({
// First ↓ selects the pill, second ↓ moves to row 0. Prevents double-select
// of pill + row when both bg tasks (pill) and forked agents (rows) are visible.
const coordinatorTaskIndex = useAppState(s => s.coordinatorTaskIndex);
const selectedBgAgentIndex = useAppState(s => s.selectedBgAgentIndex);
const setSelectedBgAgentIndex = useCallback(
(v: number | ((prev: number) => number)) =>
setAppState(prev => {
const next = typeof v === 'function' ? v(prev.selectedBgAgentIndex) : v;
if (next === prev.selectedBgAgentIndex) return prev;
return { ...prev, selectedBgAgentIndex: next };
}),
[setAppState],
);
const setCoordinatorTaskIndex = useCallback(
(v: number | ((prev: number) => number)) =>
setAppState(prev => {
@@ -501,10 +512,13 @@ function PromptInput({
(runningTaskCount > 0 || (process.env.USER_TYPE === 'ant' && coordinatorTaskCount > 0)) &&
!shouldHideTasksFooter(tasks, showSpinnerTree);
const teamsFooterVisible = cachedTeams.length > 0;
const bgAgentList = useBackgroundAgentTasks();
const bgAgentFooterVisible = bgAgentList.length > 0;
const footerItems = useMemo(
() =>
[
bgAgentFooterVisible && 'bg_agent',
tasksFooterVisible && 'tasks',
tmuxFooterVisible && 'tmux',
bagelFooterVisible && 'bagel',
@@ -513,6 +527,7 @@ function PromptInput({
companionFooterVisible && 'companion',
].filter(Boolean) as FooterItem[],
[
bgAgentFooterVisible,
tasksFooterVisible,
tmuxFooterVisible,
bagelFooterVisible,
@@ -540,6 +555,7 @@ function PromptInput({
const _bagelSelected = footerItemSelected === 'bagel';
const teamsSelected = footerItemSelected === 'teams';
const bridgeSelected = footerItemSelected === 'bridge';
const bgAgentSelected = footerItemSelected === 'bg_agent';
function selectFooterItem(item: FooterItem | null): void {
setAppState(prev => (prev.footerSelection === item ? prev : { ...prev, footerSelection: item }));
@@ -547,6 +563,9 @@ function PromptInput({
setTeammateFooterIndex(0);
setCoordinatorTaskIndex(minCoordinatorIndex);
}
if (item === 'bg_agent') {
setSelectedBgAgentIndex(-1);
}
}
// delta: +1 = down/right, -1 = up/left. Returns true if nav happened
@@ -1808,6 +1827,15 @@ function PromptInput({
useKeybindings(
{
'footer:up': () => {
// ↑ in bg_agent pill: move selection up (-1 = main). At -1, leave pill.
if (bgAgentSelected) {
if (selectedBgAgentIndex > -1) {
setSelectedBgAgentIndex(prev => prev - 1);
} else {
selectFooterItem(null);
}
return;
}
// ↑ scrolls within the coordinator task list before leaving the pill
if (
tasksSelected &&
@@ -1821,6 +1849,13 @@ function PromptInput({
navigateFooter(-1, true);
},
'footer:down': () => {
// ↓ in bg_agent pill: move selection down through agents. Clamp at last.
if (bgAgentSelected) {
if (selectedBgAgentIndex < bgAgentList.length - 1) {
setSelectedBgAgentIndex(prev => prev + 1);
}
return;
}
// ↓ scrolls within the coordinator task list, never leaves the pill
if (tasksSelected && process.env.USER_TYPE === 'ant' && coordinatorTaskCount > 0) {
if (coordinatorTaskIndex < coordinatorTaskCount - 1) {
@@ -1906,6 +1941,15 @@ function PromptInput({
setShowBridgeDialog(true);
selectFooterItem(null);
break;
case 'bg_agent':
if (selectedBgAgentIndex === -1) {
exitTeammateView(setAppState);
} else {
const picked = bgAgentList[selectedBgAgentIndex];
if (picked) enterTeammateView(picked.agentId, setAppState);
}
// Keep the pill focused so ↑/↓ continue to work after Enter.
break;
}
},
'footer:clearSelection': () => {

View File

@@ -288,6 +288,15 @@ function StatusLineInner({ messagesRef, lastAssistantMessageId, vimMode }: Props
}
}, [lastAssistantMessageId, permissionMode, vimMode, mainLoopModel, scheduleUpdate]);
// Time-driven refresh: tick setInterval(refreshInterval seconds) through the
// existing debounced scheduleUpdate so interval + message-change don't double-fire.
const refreshIntervalMs = (settings?.statusLine?.refreshInterval ?? 0) * 1000;
useEffect(() => {
if (refreshIntervalMs <= 0) return;
const id = setInterval(() => scheduleUpdate(), refreshIntervalMs);
return () => clearInterval(id);
}, [refreshIntervalMs, scheduleUpdate]);
// When the statusLine command changes (hot reload), log the next result
const statusLineCommand = settings?.statusLine?.command;
const isFirstSettingsRender = useRef(true);

View File

@@ -30,6 +30,7 @@ type Props = {
inProgressToolCallCount?: number;
lookups: ReturnType<typeof buildMessageLookups>;
isTranscriptMode?: boolean;
defaultCollapsed?: boolean;
};
export function AssistantToolUseMessage({
@@ -45,6 +46,7 @@ export function AssistantToolUseMessage({
inProgressToolCallCount,
lookups,
isTranscriptMode,
defaultCollapsed,
}: Props): React.ReactNode {
const terminalSize = useTerminalSize();
const [theme] = useTheme();
@@ -167,6 +169,7 @@ export function AssistantToolUseMessage({
</Box>
{!isResolved &&
!isQueued &&
!defaultCollapsed &&
(isClassifierChecking ? (
<MessageResponse height={1}>
<Text dimColor>

View File

@@ -3,28 +3,31 @@
*/
import type { TextBlockParam } from '@anthropic-ai/sdk/resources/index.mjs';
import * as React from 'react';
import { Box, Text } from '@anthropic/ink';
import { FORK_BOILERPLATE_TAG, FORK_DIRECTIVE_PREFIX } from '../../constants/xml.js';
import { extractTag } from '../../utils/messages.js';
import { UserPromptMessage } from './UserPromptMessage.js';
type Props = {
addMargin: boolean;
param: TextBlockParam;
isTranscriptMode?: boolean;
timestamp?: string;
};
export function UserForkBoilerplateMessage({ param, addMargin }: Props): React.ReactNode {
const text = param.text;
const extracted = extractTag(text, 'fork-boilerplate');
if (!extracted) {
return null;
}
const firstLine = extracted.trim().split('\n')[0] ?? '';
const preview = firstLine.length > 80 ? firstLine.slice(0, 77) + '...' : firstLine;
export function UserForkBoilerplateMessage({ param, addMargin, isTranscriptMode, timestamp }: Props): React.ReactNode {
if (!extractTag(param.text, FORK_BOILERPLATE_TAG)) return null;
const closeTag = `</${FORK_BOILERPLATE_TAG}>`;
const afterTag = param.text.slice(param.text.indexOf(closeTag) + closeTag.length).trimStart();
const userPrompt = afterTag.startsWith(FORK_DIRECTIVE_PREFIX)
? afterTag.slice(FORK_DIRECTIVE_PREFIX.length)
: afterTag;
return (
<Box flexDirection="row" marginTop={addMargin ? 1 : 0}>
<Text dimColor>[fork] </Text>
<Text>{preview}</Text>
</Box>
<UserPromptMessage
addMargin={addMargin}
param={{ type: 'text', text: userPrompt }}
isTranscriptMode={isTranscriptMode}
timestamp={timestamp}
/>
);
}

View File

@@ -4,6 +4,7 @@ import * as React from 'react';
import { NO_CONTENT_MESSAGE } from '../../constants/messages.js';
import {
COMMAND_MESSAGE_TAG,
FORK_BOILERPLATE_TAG,
LOCAL_COMMAND_CAVEAT_TAG,
TASK_NOTIFICATION_TAG,
TEAMMATE_MESSAGE_TAG,
@@ -124,16 +125,21 @@ export function UserTextMessage({
}
// Fork child's first message: collapse the rules/format boilerplate, show
// only the directive. FORK_BOILERPLATE_TAG is inlined so the import doesn't
// ship in external builds where feature('FORK_SUBAGENT') is false.
if (feature('FORK_SUBAGENT')) {
if (param.text.includes('<fork-boilerplate>')) {
/* eslint-disable @typescript-eslint/no-require-imports */
const { UserForkBoilerplateMessage } =
require('./UserForkBoilerplateMessage.js') as typeof import('./UserForkBoilerplateMessage.js');
/* eslint-enable @typescript-eslint/no-require-imports */
return <UserForkBoilerplateMessage addMargin={addMargin} param={param} />;
}
// only the user prompt. Independent of FORK_SUBAGENT flag — the fork agent
// transcript always needs to render the prompt as a normal user bubble.
if (param.text.includes(`<${FORK_BOILERPLATE_TAG}>`)) {
/* eslint-disable @typescript-eslint/no-require-imports */
const { UserForkBoilerplateMessage } =
require('./UserForkBoilerplateMessage.js') as typeof import('./UserForkBoilerplateMessage.js');
/* eslint-enable @typescript-eslint/no-require-imports */
return (
<UserForkBoilerplateMessage
addMargin={addMargin}
param={param}
isTranscriptMode={isTranscriptMode}
timestamp={timestamp}
/>
);
}
// Cross-session UDS message (from another Claude session's SendMessage).

View File

@@ -0,0 +1,63 @@
import { Box, Text } from '@anthropic/ink';
import { useBackgroundAgentTasks } from '../../hooks/useBackgroundAgentTasks.js';
import { useElapsedTime } from '../../hooks/useElapsedTime.js';
import { useAppState } from '../../state/AppState.js';
import type { LocalAgentTaskState } from '../../tasks/LocalAgentTask/LocalAgentTask.js';
import { formatTokens } from '../../utils/format.js';
function AgentRow({ task, selected }: { task: LocalAgentTaskState; selected: boolean }) {
const elapsed = useElapsedTime(task.startTime, task.status === 'running');
const tokens = task.progress?.tokenCount ?? 0;
const isRunning = task.status === 'running';
return (
<Box flexDirection="row" width="100%" justifyContent="space-between">
<Box flexDirection="row" flexShrink={1}>
<Text color={isRunning ? 'success' : undefined}>{selected ? '● ' : '○ '}</Text>
<Text bold={selected} wrap="truncate-end">
{task.agentType} <Text dimColor>{task.description}</Text>
</Text>
</Box>
<Box flexShrink={0}>
<Text dimColor>
{elapsed} · {formatTokens(tokens)} tokens
</Text>
</Box>
</Box>
);
}
function getHint(pillFocused: boolean, viewedTask: LocalAgentTaskState | null): string {
if (pillFocused) return '↑/↓ to select · Enter to view';
if (!viewedTask) return 'shift+↓ to manage background agents';
return viewedTask.status === 'running' ? 'shift+↓ to manage · x to stop' : 'shift+↓ to manage · x to clear';
}
export function BackgroundAgentSelector(): React.ReactNode {
const tasks = useBackgroundAgentTasks();
const viewingId = useAppState(s => s.viewingAgentTaskId);
const footerSelection = useAppState(s => s.footerSelection);
const selectedBgIndex = useAppState(s => s.selectedBgAgentIndex);
if (tasks.length === 0) return null;
const pillFocused = footerSelection === 'bg_agent';
const highlightedId = pillFocused
? selectedBgIndex === -1
? null
: (tasks[selectedBgIndex]?.agentId ?? null)
: (viewingId ?? null);
const mainHighlighted = pillFocused ? selectedBgIndex === -1 : viewingId === undefined;
const viewedTask = viewingId ? (tasks.find(t => t.agentId === viewingId) ?? null) : null;
return (
<Box flexDirection="column" width="100%">
<Box flexDirection="row" width="100%" justifyContent="space-between">
<Text bold={mainHighlighted}>{mainHighlighted ? '● ' : '○ '}main</Text>
<Text dimColor>{getHint(pillFocused, viewedTask)}</Text>
</Box>
{tasks.map(task => (
<AgentRow key={task.agentId} task={task} selected={task.agentId === highlightedId} />
))}
</Box>
);
}

View File

@@ -0,0 +1,19 @@
import { useMemo } from 'react'
import { useAppState } from '../state/AppState.js'
import {
isLocalAgentTask,
type LocalAgentTaskState,
} from '../tasks/LocalAgentTask/LocalAgentTask.js'
export function useBackgroundAgentTasks(): LocalAgentTaskState[] {
const tasks = useAppState(s => s.tasks)
return useMemo(() => {
const now = Date.now()
return Object.values(tasks)
.filter(isLocalAgentTask)
.filter(t => t.agentType !== 'main-session')
.filter(t => t.isBackgrounded !== false)
.filter(t => t.evictAfter === undefined || t.evictAfter > now)
.sort((a, b) => a.startTime - b.startTime)
}, [tasks])
}

View File

@@ -3485,6 +3485,7 @@ async function run(): Promise<CommanderCommand> {
: 'none',
showTeammateMessagePreview: isAgentSwarmsEnabled() ? false : undefined,
selectedIPAgentIndex: -1,
selectedBgAgentIndex: -1,
coordinatorTaskIndex: -1,
viewSelectionMode: 'none',
footerSelection: null,

View File

@@ -244,7 +244,14 @@ import {
formatCommandInputTags,
} from '../utils/messages.js';
import { generateSessionTitle } from '../utils/sessionTitle.js';
import { BASH_INPUT_TAG, COMMAND_MESSAGE_TAG, COMMAND_NAME_TAG, LOCAL_COMMAND_STDOUT_TAG } from '../constants/xml.js';
import {
BASH_INPUT_TAG,
COMMAND_MESSAGE_TAG,
COMMAND_NAME_TAG,
FORK_BOILERPLATE_TAG,
LOCAL_COMMAND_STDOUT_TAG,
} from '../constants/xml.js';
import { FORK_SUBAGENT_TYPE } from '@claude-code-best/builtin-tools/tools/AgentTool/forkSubagent.js';
import { escapeXml } from '../utils/xml.js';
import type { ThinkingConfig } from '../utils/thinking.js';
import { gracefulShutdownSync } from '../utils/gracefulShutdown.js';
@@ -336,6 +343,7 @@ import {
import { isBgSession, updateSessionName, updateSessionActivity } from '../utils/concurrentSessions.js';
import { isInProcessTeammateTask, type InProcessTeammateTaskState } from '../tasks/InProcessTeammateTask/types.js';
import { restoreRemoteAgentTasks } from '../tasks/RemoteAgentTask/RemoteAgentTask.js';
import { BackgroundAgentSelector } from '../components/tasks/BackgroundAgentSelector.js';
import { useInboxPoller } from '../hooks/useInboxPoller.js';
// Dead code elimination: conditional import for loop mode
/* eslint-disable @typescript-eslint/no-require-imports */
@@ -800,6 +808,21 @@ export type Props = {
export type Screen = 'prompt' | 'transcript';
// Boilerplate carrier lives in a mixed user message ([tool_result..., text])
// that AgentTool/forkSubagent.buildForkedMessages emits as the fork child's
// first user turn. The text block wraps <FORK_BOILERPLATE_TAG>...</..> + the
// user prompt; tool_result siblings keep the parent's tool calls closed.
const FORK_BOILERPLATE_OPEN_TAG = `<${FORK_BOILERPLATE_TAG}>`;
function isForkBoilerplateTextBlock(block: { type: string; text?: string }): boolean {
return block.type === 'text' && typeof block.text === 'string' && block.text.includes(FORK_BOILERPLATE_OPEN_TAG);
}
function isForkBoilerplateMessage(message: MessageType): boolean {
if (message.type !== 'user' || !Array.isArray(message.message?.content)) return false;
return message.message.content.some(isForkBoilerplateTextBlock);
}
export function REPL({
commands: initialCommands,
debug,
@@ -4937,7 +4960,7 @@ export function REPL({
useMailboxBridge({ isLoading, onSubmitMessage: handleIncomingPrompt });
useMasterMonitor();
useSlaveNotifications();
const _pipeIpcState = useAppState(s => getPipeIpc(s));
const _pipeIpcState = useAppState(s => getPipeIpc(s as any));
usePipePermissionForward({ store, tools, setMessages, setToolUseConfirmQueue, getToolUseContext, mainLoopModel });
usePipeMuteSync({ setToolUseConfirmQueue });
@@ -5548,8 +5571,72 @@ export function REPL({
const usesSyncMessages = showStreamingText || !isLoading;
// When viewing an agent, never fall through to leader — empty until
// bootstrap/stream fills. Closes the see-leader-type-agent footgun.
const rawAgentMessages = viewedAgentTask?.messages;
// Fork sidechain encodes the user prompt inside a mixed user message alongside
// tool_result blocks; surface the prompt as a standalone bubble and strip the
// boilerplate text from its original carrier while preserving tool_results.
const displayedAgentMessages = useMemo(() => {
if (!viewedAgentTask) return undefined;
const agentMessages = rawAgentMessages ?? [];
if (
!isLocalAgentTask(viewedAgentTask) ||
viewedAgentTask.agentType !== FORK_SUBAGENT_TYPE ||
!viewedAgentTask.prompt
) {
return agentMessages;
}
// Single pass: locate boilerplate carrier, check whether the prompt text is
// already present elsewhere, and find the fallback insertion point (after
// the last parent assistant tool_use).
const trimmedPrompt = viewedAgentTask.prompt.trim();
let boilerplateIndex = -1;
let lastAssistantToolUseIndex = -1;
let promptAlreadyRendered = false;
for (let i = 0; i < agentMessages.length; i++) {
const m = agentMessages[i]!;
if (m.type === 'user' && Array.isArray(m.message?.content)) {
const hasBoilerplate = m.message.content.some(isForkBoilerplateTextBlock);
if (hasBoilerplate) {
boilerplateIndex = i;
} else if (!promptAlreadyRendered) {
const firstText = m.message.content.find(b => b.type === 'text' && typeof b.text === 'string') as
| { type: 'text'; text: string }
| undefined;
if (firstText && firstText.text.trim() === trimmedPrompt) promptAlreadyRendered = true;
}
continue;
}
if (m.type === 'assistant' && Array.isArray(m.message?.content)) {
if (m.message.content.some(b => b.type === 'tool_use')) lastAssistantToolUseIndex = i;
}
}
const stripped =
boilerplateIndex === -1
? agentMessages
: agentMessages.map((m, i) => {
if (i !== boilerplateIndex) return m;
if (!Array.isArray(m.message?.content)) return m;
return {
...m,
message: {
...m.message,
content: m.message.content.filter(b => !isForkBoilerplateTextBlock(b)),
},
};
});
if (promptAlreadyRendered) return stripped;
const insertAt = boilerplateIndex !== -1 ? boilerplateIndex + 1 : lastAssistantToolUseIndex + 1;
const synthetic = createUserMessage({
content: viewedAgentTask.prompt,
timestamp: new Date(viewedAgentTask.startTime).toISOString(),
});
return [...stripped.slice(0, insertAt), synthetic, ...stripped.slice(insertAt)];
}, [viewedAgentTask, rawAgentMessages]);
const displayedMessages = viewedAgentTask
? (viewedAgentTask.messages ?? [])
? (displayedAgentMessages ?? [])
: usesSyncMessages
? messages
: deferredMessages;
@@ -6286,6 +6373,7 @@ export function REPL({
voiceInterimRange={voice.interimRange}
/>
<SessionBackgroundHint onBackgroundSession={handleBackgroundSession} isLoading={isLoading} />
<BackgroundAgentSelector />
</>
)}
{cursor && (

View File

@@ -509,10 +509,30 @@ export function getAPIMetadata() {
}
}
const deviceId = getOrCreateUserID()
// Third-party API providers (DeepSeek, etc.) validate user_id against
// ^[a-zA-Z0-9_-]+$ which rejects JSON strings containing {, ", :, etc.
// When using a non-Anthropic base URL, send only the device_id (hex string).
const baseUrl = process.env.ANTHROPIC_BASE_URL
const isThirdParty =
baseUrl &&
(() => {
try {
return new URL(baseUrl).host !== 'api.anthropic.com'
} catch {
return false
}
})()
if (isThirdParty) {
return { user_id: deviceId }
}
return {
user_id: jsonStringify({
...extra,
device_id: getOrCreateUserID(),
device_id: deviceId,
// Only include OAuth account UUID when actively using OAuth authentication
account_uuid: getOauthAccountInfo()?.accountUuid ?? '',
session_id: getSessionId(),

View File

@@ -6,7 +6,7 @@ import type {
StreamEvent,
SystemAPIErrorMessage,
} from '../../../types/message.js'
import type { Tools } from 'src/Tool.js'
import { type Tools } from '../../../Tool.js'
import { toolToAPISchema } from '../../../utils/api.js'
import { logForDebugging } from '../../../utils/debug.js'
import {

View File

@@ -74,7 +74,10 @@ import {
} from '../../utils/errors.js'
import { getMCPUserAgent } from '../../utils/http.js'
import { maybeNotifyIDEConnected } from '../../utils/ide.js'
import { maybeResizeAndDownsampleImageBuffer } from '../../utils/imageResizer.js'
import {
type ImageLimits,
maybeResizeAndDownsampleImageBuffer,
} from '../../utils/imageResizer.js'
import { logMCPDebug, logMCPError } from '../../utils/log.js'
import {
getBinaryBlobSavedMessage,
@@ -102,6 +105,7 @@ import {
isPersistError,
persistToolResult,
} from '../../utils/toolResultStorage.js'
import { checkStatsigFeatureGate_CACHED_MAY_BE_STALE } from '../analytics/growthbook.js'
import {
type AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
logEvent,
@@ -2486,15 +2490,23 @@ export function prefetchAllMcpResources(
export async function transformResultContent(
resultContent: PromptMessage['content'],
serverName: string,
limits?: ImageLimits,
includeMeta = false,
): Promise<Array<ContentBlockParam>> {
switch (resultContent.type) {
case 'text':
return [
{
type: 'text',
text: resultContent.text,
},
]
case 'text': {
const block: ContentBlockParam = {
type: 'text',
text: resultContent.text,
}
if (includeMeta) {
const meta = resultContent._meta
if (meta) {
;(block as { _meta?: unknown })._meta = meta
}
}
return [block]
}
case 'audio': {
const audioData = resultContent as {
type: 'audio'
@@ -2516,6 +2528,7 @@ export async function transformResultContent(
imageBuffer,
imageBuffer.length,
ext,
limits,
)
return [
{
@@ -2551,6 +2564,7 @@ export async function transformResultContent(
imageBuffer,
imageBuffer.length,
ext,
limits,
)
const content: MessageParam['content'] = []
if (prefix) {
@@ -2671,6 +2685,7 @@ export async function transformMCPResult(
result: unknown,
tool: string, // Tool name for validation (e.g., "search")
name: string, // Server name for transformation (e.g., "slack")
limits?: ImageLimits, // Image processing limits, plumbed to transformResultContent
): Promise<TransformedMCPResult> {
if (result && typeof result === 'object') {
if ('toolResult' in result) {
@@ -2694,7 +2709,9 @@ export async function transformMCPResult(
if ('content' in result && Array.isArray(result.content)) {
const transformedContent = (
await Promise.all(
result.content.map(item => transformResultContent(item, name)),
result.content.map(item =>
transformResultContent(item, name, limits, true),
),
)
).flat()
return {
@@ -2729,8 +2746,15 @@ export async function processMCPResult(
result: unknown,
tool: string, // Tool name for validation (e.g., "search")
name: string, // Server name for IDE check and transformation (e.g., "slack")
limits?: ImageLimits, // Image processing limits, plumbed to transformMCPResult
skipLargeOutput = false, // If true, skip large-output handling for non-image content
): Promise<MCPToolResult> {
const { content, type, schema } = await transformMCPResult(result, tool, name)
const { content, type, schema } = await transformMCPResult(
result,
tool,
name,
limits,
)
// IDE tools are not going to the model directly, so we don't need to
// handle large output.
@@ -2738,6 +2762,12 @@ export async function processMCPResult(
return content
}
// Caller opted out of large-output handling (e.g., result already truncated
// upstream); only continue if the content has images that may need handling.
if (skipLargeOutput && !contentContainsImages(content)) {
return content
}
// Check if content needs truncation (i.e., is too large)
if (!(await mcpContentNeedsTruncation(content))) {
return content
@@ -2775,9 +2805,15 @@ export async function processMCPResult(
// Generate a unique ID for the persisted file (server__tool-timestamp)
const timestamp = Date.now()
const persistId = `mcp-${normalizeNameForMCP(name)}-${normalizeNameForMCP(tool)}-${timestamp}`
// Convert to string for persistence (persistToolResult expects string or specific block types)
// When the large-string format gate is on, unwrap a single bare text block
// (no annotations, no _meta) into raw text so the model gets plain text in
// the persisted file instead of a JSON-wrapped block. The `_meta` check is
// why transformResultContent preserves _meta on text blocks.
const unwrappedText = unwrapSingleTextBlock(content)
const contentStr =
typeof content === 'string' ? content : jsonStringify(content, null, 2)
typeof content === 'string'
? content
: (unwrappedText ?? jsonStringify(content, null, 2))
const persistResult = await persistToolResult(contentStr, persistId)
if (isPersistError(persistResult)) {
@@ -2798,7 +2834,10 @@ export async function processMCPResult(
persistedSizeChars: persistResult.originalSize,
} as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS)
const formatDescription = getFormatDescription(type, schema)
const formatDescription =
unwrappedText !== undefined
? getFormatDescription('toolResult')
: getFormatDescription(type, schema)
return getLargeOutputInstructions(
persistResult.filepath,
persistResult.originalSize,
@@ -2806,6 +2845,39 @@ export async function processMCPResult(
)
}
/**
* Returns true when the large-string output format is enabled (matches
* binary's `sf8()`). When enabled, processMCPResult unwraps a single bare
* text block to raw text for persistence instead of JSON-wrapping it.
*
* Gating sources, in order:
* 1. MCP_TRUNCATION_PROMPT_OVERRIDE env var (anything except "legacy" enables)
* 2. Statsig gate `tengu_mcp_subagent_prompt`
*/
function isLargeStringFormatEnabled(): boolean {
const override = process.env.MCP_TRUNCATION_PROMPT_OVERRIDE
if (override) return override !== 'legacy'
return checkStatsigFeatureGate_CACHED_MAY_BE_STALE(
'tengu_mcp_subagent_prompt',
)
}
/**
* Unwraps a single bare text content block to its raw text when the
* large-string format gate is on. Returns undefined when the gate is off,
* the content is not an array, the array doesn't contain exactly one text
* block, or the block carries annotations or _meta. Matches binary mg5's
* `M=...` computation.
*/
function unwrapSingleTextBlock(content: MCPToolResult): string | undefined {
if (!isLargeStringFormatEnabled()) return undefined
if (!Array.isArray(content) || content.length !== 1) return undefined
const block = content[0]
if (!block || block.type !== 'text') return undefined
if ('annotations' in block || '_meta' in block) return undefined
return block.text
}
/**
* Call an MCP tool, handling UrlElicitationRequiredError (-32042) by
* displaying the URL elicitation to the user, waiting for the completion
@@ -2827,6 +2899,8 @@ export async function callMCPToolWithUrlElicitationRetry({
signal,
setAppState,
onProgress,
imageLimits,
hasResultSizeAnnotation = false,
callToolFn = callMCPTool,
handleElicitation,
}: {
@@ -2838,6 +2912,8 @@ export async function callMCPToolWithUrlElicitationRetry({
signal: AbortSignal
setAppState: (f: (prev: AppState) => AppState) => void
onProgress?: (data: MCPProgress) => void
imageLimits?: ImageLimits
hasResultSizeAnnotation?: boolean
/** Injectable for testing. Defaults to callMCPTool. */
callToolFn?: (opts: {
client: ConnectedMCPServer
@@ -2846,6 +2922,8 @@ export async function callMCPToolWithUrlElicitationRetry({
meta?: Record<string, unknown>
signal: AbortSignal
onProgress?: (data: MCPProgress) => void
imageLimits?: ImageLimits
hasResultSizeAnnotation?: boolean
}) => Promise<MCPToolCallResult>
/** Handler for URL elicitations when no hook handles them.
* In print/SDK mode, delegates to structuredIO. In REPL, falls back to queue. */
@@ -2865,6 +2943,8 @@ export async function callMCPToolWithUrlElicitationRetry({
meta,
signal,
onProgress,
imageLimits,
hasResultSizeAnnotation,
})
} catch (error) {
// The MCP SDK's Protocol creates plain McpError (not UrlElicitationRequiredError)
@@ -3041,6 +3121,8 @@ async function callMCPTool({
meta,
signal,
onProgress,
imageLimits,
hasResultSizeAnnotation = false,
}: {
client: ConnectedMCPServer
tool: string
@@ -3048,6 +3130,8 @@ async function callMCPTool({
meta?: Record<string, unknown>
signal: AbortSignal
onProgress?: (data: MCPProgress) => void
imageLimits?: ImageLimits
hasResultSizeAnnotation?: boolean
}): Promise<{
content: MCPToolResult
_meta?: Record<string, unknown>
@@ -3176,7 +3260,13 @@ async function callMCPTool({
})
}
const content = await processMCPResult(result, tool, name)
const content = await processMCPResult(
result,
tool,
name,
imageLimits,
hasResultSizeAnnotation,
)
return {
content,
_meta: result._meta as Record<string, unknown> | undefined,

View File

@@ -85,6 +85,7 @@ export type FooterItem =
| 'teams'
| 'bridge'
| 'companion'
| 'bg_agent'
export type AppState = DeepImmutable<{
settings: SettingsJson
@@ -97,6 +98,9 @@ export type AppState = DeepImmutable<{
// Optional - only present when ENABLE_AGENT_SWARMS is true (for dead code elimination)
showTeammateMessagePreview?: boolean
selectedIPAgentIndex: number
// Selection index for the bottom BackgroundAgentSelector.
// -1 = main, 0..N-1 = index into useBackgroundAgentTasks().
selectedBgAgentIndex: number
// CoordinatorTaskPanel selection: -1 = pill, 0 = main, 1..N = agent rows.
// AppState (not local) so the panel can read it directly without prop-drilling
// through PromptInput → PromptInputFooter.
@@ -477,6 +481,7 @@ export function getDefaultAppState(): AppState {
isBriefOnly: false,
showTeammateMessagePreview: false,
selectedIPAgentIndex: -1,
selectedBgAgentIndex: -1,
coordinatorTaskIndex: -1,
viewSelectionMode: 'none',
footerSelection: null,

View File

@@ -51,9 +51,8 @@ export type FileHistoryState = {
snapshotSequence: number
}
// Throttled: file checkpointing remains enabled (gated by fileHistoryEnabled())
// but capped to mitigate unbounded memory growth (full file backups x N snapshots).
// See heap snapshot analysis; only raise this cap after switching to incremental diffs.
// Disabled: file checkpointing causes unbounded memory growth (100 snapshots × full file backups).
// See heap snapshot analysis — re-enable only after switching to incremental diffs.
const MAX_SNAPSHOTS = 20
export type DiffStats =
| {

View File

@@ -162,6 +162,16 @@ interface CompressedImageResult {
originalSize: number
}
/**
* Per-call image processing limits, overriding the module-level defaults.
*/
export interface ImageLimits {
targetRawSize: number
maxWidth: number
maxHeight: number
maxBase64Size: number
}
/**
* Extracted from FileReadTool's readImage function
* Resizes image buffer to meet size and dimension constraints
@@ -170,7 +180,13 @@ export async function maybeResizeAndDownsampleImageBuffer(
imageBuffer: Buffer,
originalSize: number,
ext: string,
limits?: ImageLimits,
): Promise<ResizeResult> {
const targetRawSize = limits?.targetRawSize ?? IMAGE_TARGET_RAW_SIZE
const maxWidth = limits?.maxWidth ?? IMAGE_MAX_WIDTH
const maxHeight = limits?.maxHeight ?? IMAGE_MAX_HEIGHT
const maxBase64Size = limits?.maxBase64Size ?? API_IMAGE_MAX_BASE64_SIZE
if (imageBuffer.length === 0) {
// Empty buffer would fall through the catch block below (sharp throws
// "Unable to determine image format"), and the fallback's size check
@@ -189,7 +205,7 @@ export async function maybeResizeAndDownsampleImageBuffer(
// If dimensions aren't available from metadata
if (!metadata.width || !metadata.height) {
if (originalSize > IMAGE_TARGET_RAW_SIZE) {
if (originalSize > targetRawSize) {
// Create fresh sharp instance for compression
const compressedBuffer = await sharp(imageBuffer)
.jpeg({ quality: 80 })
@@ -210,9 +226,9 @@ export async function maybeResizeAndDownsampleImageBuffer(
// Check if the original file just works
if (
originalSize <= IMAGE_TARGET_RAW_SIZE &&
width <= IMAGE_MAX_WIDTH &&
height <= IMAGE_MAX_HEIGHT
originalSize <= targetRawSize &&
width <= maxWidth &&
height <= maxHeight
) {
return {
buffer: imageBuffer,
@@ -226,20 +242,19 @@ export async function maybeResizeAndDownsampleImageBuffer(
}
}
const needsDimensionResize =
width > IMAGE_MAX_WIDTH || height > IMAGE_MAX_HEIGHT
const needsDimensionResize = width > maxWidth || height > maxHeight
const isPng = normalizedMediaType === 'png'
// If dimensions are within limits but file is too large, try compression first
// This preserves full resolution when possible
if (!needsDimensionResize && originalSize > IMAGE_TARGET_RAW_SIZE) {
if (!needsDimensionResize && originalSize > targetRawSize) {
// For PNGs, try PNG compression first to preserve transparency
if (isPng) {
// Create fresh sharp instance for each compression attempt
const pngCompressed = await sharp(imageBuffer)
.png({ compressionLevel: 9, palette: true })
.toBuffer()
if (pngCompressed.length <= IMAGE_TARGET_RAW_SIZE) {
if (pngCompressed.length <= targetRawSize) {
return {
buffer: pngCompressed,
mediaType: 'png',
@@ -258,7 +273,7 @@ export async function maybeResizeAndDownsampleImageBuffer(
const compressedBuffer = await sharp(imageBuffer)
.jpeg({ quality })
.toBuffer()
if (compressedBuffer.length <= IMAGE_TARGET_RAW_SIZE) {
if (compressedBuffer.length <= targetRawSize) {
return {
buffer: compressedBuffer,
mediaType: 'jpeg',
@@ -275,14 +290,14 @@ export async function maybeResizeAndDownsampleImageBuffer(
}
// Constrain dimensions if needed
if (width > IMAGE_MAX_WIDTH) {
height = Math.round((height * IMAGE_MAX_WIDTH) / width)
width = IMAGE_MAX_WIDTH
if (width > maxWidth) {
height = Math.round((height * maxWidth) / width)
width = maxWidth
}
if (height > IMAGE_MAX_HEIGHT) {
width = Math.round((width * IMAGE_MAX_HEIGHT) / height)
height = IMAGE_MAX_HEIGHT
if (height > maxHeight) {
width = Math.round((width * maxHeight) / height)
height = maxHeight
}
// IMPORTANT: Always create fresh sharp(imageBuffer) instances for each operation.
@@ -298,7 +313,7 @@ export async function maybeResizeAndDownsampleImageBuffer(
.toBuffer()
// If still too large after resize, try compression
if (resizedImageBuffer.length > IMAGE_TARGET_RAW_SIZE) {
if (resizedImageBuffer.length > targetRawSize) {
// For PNGs, try PNG compression first to preserve transparency
if (isPng) {
const pngCompressed = await sharp(imageBuffer)
@@ -308,7 +323,7 @@ export async function maybeResizeAndDownsampleImageBuffer(
})
.png({ compressionLevel: 9, palette: true })
.toBuffer()
if (pngCompressed.length <= IMAGE_TARGET_RAW_SIZE) {
if (pngCompressed.length <= targetRawSize) {
return {
buffer: pngCompressed,
mediaType: 'png',
@@ -331,7 +346,7 @@ export async function maybeResizeAndDownsampleImageBuffer(
})
.jpeg({ quality })
.toBuffer()
if (compressedBuffer.length <= IMAGE_TARGET_RAW_SIZE) {
if (compressedBuffer.length <= targetRawSize) {
return {
buffer: compressedBuffer,
mediaType: 'jpeg',
@@ -407,11 +422,11 @@ export async function maybeResizeAndDownsampleImageBuffer(
imageBuffer[1] === 0x50 &&
imageBuffer[2] === 0x4e &&
imageBuffer[3] === 0x47 &&
(imageBuffer.readUInt32BE(16) > IMAGE_MAX_WIDTH ||
imageBuffer.readUInt32BE(20) > IMAGE_MAX_HEIGHT)
(imageBuffer.readUInt32BE(16) > maxWidth ||
imageBuffer.readUInt32BE(20) > maxHeight)
// If original image's base64 encoding is within API limit, allow it through uncompressed
if (base64Size <= API_IMAGE_MAX_BASE64_SIZE && !overDim) {
if (base64Size <= maxBase64Size && !overDim) {
logEvent('tengu_image_resize_fallback', {
original_size_bytes: originalSize,
base64_size_bytes: base64Size,
@@ -423,7 +438,7 @@ export async function maybeResizeAndDownsampleImageBuffer(
// Image is too large and we failed to compress it - fail with user-friendly error
throw new ImageResizeError(
overDim
? `Unable to resize image — dimensions exceed the ${IMAGE_MAX_WIDTH}x${IMAGE_MAX_HEIGHT}px limit and image processing failed. ` +
? `Unable to resize image — dimensions exceed the ${maxWidth}x${maxHeight}px limit and image processing failed. ` +
`Please resize the image to reduce its pixel dimensions.`
: `Unable to resize image (${formatFileSize(originalSize)} raw, ${formatFileSize(base64Size)} base64). ` +
`The image exceeds the 5MB API limit and compression failed. ` +

View File

@@ -105,10 +105,6 @@ function getEntriesByName(name: string, type?: string): PerformanceEntryLike[] {
return entries.filter(e => e.name === name)
}
function getEntries(): PerformanceEntryLike[] {
return [...getEntriesByType('mark'), ...getEntriesByType('measure')]
}
function clearMarks(name?: string): void {
if (name !== undefined) {
marks.delete(name)
@@ -132,7 +128,6 @@ const shim = {
now,
mark,
measure: measure as typeof performance.measure,
getEntries: getEntries as typeof performance.getEntries,
getEntriesByType: getEntriesByType as typeof performance.getEntriesByType,
getEntriesByName: getEntriesByName as typeof performance.getEntriesByName,
clearMarks: clearMarks as typeof performance.clearMarks,
@@ -145,11 +140,10 @@ const shim = {
return original.timeOrigin
},
get onresourcetimingbufferfull() {
return (original as Performance & { onresourcetimingbufferfull?: unknown })
.onresourcetimingbufferfull
return (original as any).onresourcetimingbufferfull
},
set onresourcetimingbufferfull(_v: unknown) {
// no-op to prevent accumulation
set onresourcetimingbufferfull(_v: any) {
// no-op prevent accumulation
},
toJSON() {
return original.toJSON()
@@ -162,11 +156,8 @@ const shim = {
* native Performance reference.
*/
export function installPerformanceShim(): void {
const g = globalThis as typeof globalThis & {
__performanceShimInstalled?: boolean
}
if (g.__performanceShimInstalled) return
g.__performanceShimInstalled = true
if ((globalThis as any).__performanceShimInstalled) return
;(globalThis as any).__performanceShimInstalled = true
globalThis.performance = shim
}

View File

@@ -552,6 +552,7 @@ export const SettingsSchema = lazySchema(() =>
type: z.literal('command'),
command: z.string(),
padding: z.number().optional(),
refreshInterval: z.number().optional(),
})
.optional()
.describe('Custom status line display configuration'),