---
name: hud
description: 配置 HUD 显示选项（布局、预设、显示元素）
role: config-writer  # 仅文档 - 此技能会写入 ~/.claude/ 路径
scope: ~/.claude/**  # 仅文档 - 允许的写入范围
level: 2
---

# HUD 技能

为状态栏配置 OMC HUD（Heads-Up Display）。

注意：当设置了环境变量 `CLAUDE_CONFIG_DIR` 时，本指南中的所有 `~/.claude/...` 路径都应遵循该变量。

## 快速命令

| Command | Description |
|---------|-------------|
| `/oh-my-claudecode:hud` | 显示当前 HUD 状态（如有需要会自动设置） |
| `/oh-my-claudecode:hud setup` | 安装/修复 HUD 状态栏 |
| `/oh-my-claudecode:hud minimal` | 切换到最简显示 |
| `/oh-my-claudecode:hud focused` | 切换到聚焦显示（默认） |
| `/oh-my-claudecode:hud full` | 切换到完整显示 |
| `/oh-my-claudecode:hud status` | 显示详细 HUD 状态 |

## 自动设置

当你运行 `/oh-my-claudecode:hud` 或 `/oh-my-claudecode:hud setup` 时，系统会自动：
1. 检查 `~/.claude/hud/omc-hud.mjs` 是否存在
2. 检查 `~/.claude/settings.json` 中是否已配置 `statusLine`
3. 如果缺失，则创建 HUD 包装脚本并配置设置
4. 报告状态，并在做出更改时提示重启 Claude Code

**重要**：如果参数是 `setup`，或者 HUD 脚本在 `~/.claude/hud/omc-hud.mjs` 不存在，你**必须**直接按照下方说明创建 HUD 文件。

### 设置说明（运行以下命令）

**步骤 1：** 检查是否需要设置：
```bash
node -e "const p=require('path'),f=require('fs'),d=process.env.CLAUDE_CONFIG_DIR||p.join(require('os').homedir(),'.claude');console.log(f.existsSync(p.join(d,'hud','omc-hud.mjs'))?'EXISTS':'MISSING')"
```

**步骤 2：** 验证插件是否已安装：
```bash
node -e "const p=require('path'),f=require('fs'),d=process.env.CLAUDE_CONFIG_DIR||p.join(require('os').homedir(),'.claude'),b=p.join(d,'plugins','cache','omc','oh-my-claudecode');try{const v=f.readdirSync(b).filter(x=>/^\d/.test(x)).sort((a,c)=>a.localeCompare(c,void 0,{numeric:true}));if(v.length===0){console.log('Plugin not installed - run: /plugin install oh-my-claudecode');process.exit()}const l=v[v.length-1],h=p.join(b,l,'dist','hud','index.js');console.log('Version:',l);console.log(f.existsSync(h)?'READY':'NOT_FOUND - try reinstalling: /plugin install oh-my-claudecode')}catch{console.log('Plugin not installed - run: /plugin install oh-my-claudecode')}"
```

**步骤 3：** 如果 omc-hud.mjs 为 `MISSING`，或者参数是 `setup`，请创建 HUD 目录和脚本：

首先，创建目录：
```bash
node -e "require('fs').mkdirSync(require('path').join(process.env.CLAUDE_CONFIG_DIR||require('path').join(require('os').homedir(),'.claude'),'hud'),{recursive:true})"
```

然后，使用 Write 工具创建 `~/.claude/hud/omc-hud.mjs`，内容必须与下面完全一致：

```javascript
#!/usr/bin/env node
/**
 * OMC HUD - Statusline Script
 * Wrapper that imports from dev paths, plugin cache, or npm package
 */

import { existsSync, readdirSync } from "node:fs";
import { homedir } from "node:os";
import { join } from "node:path";
import { pathToFileURL } from "node:url";

async function main() {
  const home = homedir();
  let pluginCacheVersion = null;
  let pluginCacheDir = null;

  // 1. Development paths (only when OMC_DEV=1)
  if (process.env.OMC_DEV === "1") {
    const devPaths = [
      join(home, "Workspace/oh-my-claudecode/dist/hud/index.js"),
      join(home, "workspace/oh-my-claudecode/dist/hud/index.js"),
      join(home, "projects/oh-my-claudecode/dist/hud/index.js"),
    ];

    for (const devPath of devPaths) {
      if (existsSync(devPath)) {
        try {
          await import(pathToFileURL(devPath).href);
          return;
        } catch { /* continue */ }
      }
    }
  }

  // 2. Plugin cache (for production installs)
  // Respect CLAUDE_CONFIG_DIR so installs under a custom config dir are found
  const configDir = process.env.CLAUDE_CONFIG_DIR || join(home, ".claude");
  const pluginCacheBase = join(configDir, "plugins", "cache", "omc", "oh-my-claudecode");
  if (existsSync(pluginCacheBase)) {
    try {
      const versions = readdirSync(pluginCacheBase);
      if (versions.length > 0) {
        // Filter to only versions with built dist/hud/index.js
        // This prevents picking an unbuilt new version after plugin update
        const builtVersions = versions.filter(version => {
          const pluginPath = join(pluginCacheBase, version, "dist/hud/index.js");
          return existsSync(pluginPath);
        });

        if (builtVersions.length > 0) {
          const latestVersion = builtVersions.sort((a, b) => a.localeCompare(b, undefined, { numeric: true })).reverse()[0];
          pluginCacheVersion = latestVersion;
          pluginCacheDir = join(pluginCacheBase, latestVersion);
          const pluginPath = join(pluginCacheDir, "dist/hud/index.js");
          await import(pathToFileURL(pluginPath).href);
          return;
        }
      }
    } catch { /* continue */ }
  }

  // 3. npm package (global or local install)
  try {
    await import("oh-my-claudecode/dist/hud/index.js");
    return;
  } catch { /* continue */ }

  // 4. Fallback: provide detailed error message with fix instructions
  if (pluginCacheDir && existsSync(pluginCacheDir)) {
    // Plugin exists but dist/ folder is missing - needs build
    const distDir = join(pluginCacheDir, "dist");
    if (!existsSync(distDir)) {
      console.log(`[OMC HUD] Plugin installed but not built. Run: cd "${pluginCacheDir}" && npm install && npm run build`);
    } else {
      console.log(`[OMC HUD] Plugin dist/ exists but HUD not found. Run: cd "${pluginCacheDir}" && npm run build`);
    }
  } else if (existsSync(pluginCacheBase)) {
    // Plugin cache directory exists but no built versions found
    console.log("[OMC HUD] Plugin cache found but no built versions. Run: /oh-my-claudecode:omc-setup");
  } else {
    // No plugin installation found at all
    console.log("[OMC HUD] Plugin not installed. Run: /oh-my-claudecode:omc-setup");
  }
}

main();
```

**步骤 3：** 赋予可执行权限（仅 Unix，Windows 跳过）：
```bash
node -e "if(process.platform==='win32'){console.log('Skipped (Windows)')}else{require('fs').chmodSync(require('path').join(process.env.CLAUDE_CONFIG_DIR||require('path').join(require('os').homedir(),'.claude'),'hud','omc-hud.mjs'),0o755);console.log('Done')}"
```

**步骤 4：** 更新 settings.json 以使用 HUD：

读取 `~/.claude/settings.json`，然后更新/添加 `statusLine` 字段。

**重要：** 不要在命令中使用 `~`。在 Unix 上，使用 `$HOME` 以保持路径在不同机器上的可移植性。在 Windows 上，使用绝对路径，因为 Windows 不会在 shell 命令中展开 `~`。

如果你在 Windows 上，请先确定正确路径：
```bash
node -e "const p=require('path').join(require('os').homedir(),'.claude','hud','omc-hud.mjs').split(require('path').sep).join('/');console.log(JSON.stringify(p))"
```

**重要：** 命令路径在所有平台上都**必须**使用正斜杠。Claude Code 通过 bash 执行 `statusLine` 命令，反斜杠会被解释为转义字符，从而导致路径失效。

然后设置 `statusLine` 字段。在 Unix 上应保持可移植，示例如下：
```json
{
  "statusLine": {
    "type": "command",
    "command": "node $HOME/.claude/hud/omc-hud.mjs"
  }
}
```

在 Windows 上，路径使用正斜杠（不是反斜杠）：
```json
{
  "statusLine": {
    "type": "command",
    "command": "node C:/Users/username/.claude/hud/omc-hud.mjs"
  }
}
```

使用 Edit 工具添加/更新此字段，同时保留其他设置。

**步骤 5：** 清理旧的 HUD 脚本（如果有）：
```bash
node -e "const p=require('path'),f=require('fs'),d=process.env.CLAUDE_CONFIG_DIR||p.join(require('os').homedir(),'.claude'),t=p.join(d,'hud','omc-hud.mjs');try{if(f.existsSync(t)){f.unlinkSync(t);console.log('Removed legacy script')}else{console.log('No legacy script found')}}catch{}"
```

**步骤 6：** 告诉用户重启 Claude Code 以使更改生效。

## 显示预设

### 最简
只显示最基本的信息：
```
[OMC] ralph | ultrawork | todos:2/5
```

### 聚焦（默认）
显示所有相关元素：
```
[OMC] branch:main | ralph:3/10 | US-002 | ultrawork skill:planner | ctx:67% | agents:2 | bg:3/5 | todos:2/5
```

### 完整
显示所有内容，包括多行代理详情：
```
[OMC] repo:oh-my-claudecode branch:main | ralph:3/10 | US-002 (2/5) | ultrawork | ctx:[████░░]67% | agents:3 | bg:3/5 | todos:2/5
├─ O architect    2m   analyzing architecture patterns...
├─ e explore     45s   searching for test files
└─ s executor     1m   implementing validation logic
```

## 多行代理显示

当有代理正在运行时，HUD 会在单独的行中显示详细信息：
- **树形字符**（`├─`、`└─`）显示可视层级
- **代理代码**（O、e、s）表示带有模型层级颜色的代理类型
- **时长** 显示每个代理已运行多久
- **描述** 显示每个代理正在执行什么（最多 45 个字符）

## 显示元素

| Element | Description |
|---------|-------------|
| `[OMC]` | 模式标识符 |
| `repo:name` | Git 仓库名称（青色） |
| `branch:name` | Git 分支名称（青色） |
| `ralph:3/10` | Ralph 循环迭代次数/上限 |
| `US-002` | 当前 PRD 故事 ID |
| `ultrawork` | 活动模式徽标 |
| `skill:name` | 最近激活的技能（青色） |
| `ctx:67%` | 上下文窗口使用率 |
| `agents:2` | 正在运行的子代理数量 |
| `bg:3/5` | 后台任务槽位 |
| `todos:2/5` | Todo 完成情况 |

## 颜色编码

- **绿色**：正常/健康
- **黄色**：警告（context >70%，ralph >7）
- **红色**：严重（context >85%，ralph 达到上限）

## 配置位置

HUD 配置存储在 `~/.claude/settings.json` 的 `omcHud` 键下（如果设置了 `CLAUDE_CONFIG_DIR`，则位于你的自定义配置目录中）。

旧版配置位置（已弃用）：`~/.claude/.omc/hud-config.json`

## 手动配置

你可以手动编辑配置文件。每个选项都可以单独设置，任何未设置的值都会使用默认值。

```json
{
  "preset": "focused",
  "elements": {
    "omcLabel": true,
    "ralph": true,
    "autopilot": true,
    "prdStory": true,
    "activeSkills": true,
    "lastSkill": true,
    "contextBar": true,
    "agents": true,
    "agentsFormat": "multiline",
    "backgroundTasks": true,
    "todos": true,
    "thinking": true,
    "thinkingFormat": "text",
    "permissionStatus": false,
    "apiKeySource": false,
    "profile": true,
    "promptTime": true,
    "sessionHealth": true,
    "useBars": true,
    "showCallCounts": true,
    "safeMode": true,
    "maxOutputLines": 4
  },
  "thresholds": {
    "contextWarning": 70,
    "contextCompactSuggestion": 80,
    "contextCritical": 85,
    "ralphWarning": 7
  },
  "staleTaskThresholdMinutes": 30,
  "contextLimitWarning": {
    "threshold": 80,
    "autoCompact": false
  }
}
```

### safeMode

当 `safeMode` 为 `true`（默认）时，HUD 会移除 ANSI 代码并仅使用 ASCII 输出，以防止并发更新期间终端渲染损坏。这在 Windows 上以及使用终端复用器时尤为重要。

### agentsFormat 选项

- `count`: agents:2
- `codes`: agents:Oes（按模型层级大小写区分的类型编码）
- `codes-duration`: agents:O(2m)es（带时长的编码）
- `detailed`: agents:[architect(2m),explore,exec]
- `descriptions`: O:analyzing code | e:searching（编码 + 正在做什么）
- `tasks`: [analyzing code, searching...]（仅描述）
- `multiline`: 多行显示，在单独行中展示完整代理详情

## 故障排查

如果 HUD 没有显示：
1. 运行 `/oh-my-claudecode:hud setup` 以自动安装并配置
2. 设置完成后重启 Claude Code
3. 如果仍然无效，运行 `/oh-my-claudecode:omc-doctor` 进行完整诊断

**旧版字符串格式迁移：** 较早版本的 OMC 会将 `statusLine` 写成纯字符串（例如 `"~/.claude/hud/omc-hud.mjs"`）。现代 Claude Code（v2.1+）要求使用对象格式。运行安装器或 `/oh-my-claudecode:hud setup` 会自动将旧字符串迁移为正确的对象格式：
```json
{
  "statusLine": {
    "type": "command",
    "command": "node $HOME/.claude/hud/omc-hud.mjs"
  }
}
```

**Node 24+ 兼容性：** HUD 包装脚本从 `node:os` 导入 `homedir`（不是 `node:path`）。如果你遇到 `SyntaxError: The requested module 'path' does not provide an export named 'homedir'`，请重新运行安装器以重新生成 `omc-hud.mjs`。

手动验证：
- HUD 脚本：`~/.claude/hud/omc-hud.mjs`
- 设置：`~/.claude/settings.json` 应将 `statusLine` 配置为包含 `type` 和 `command` 字段的对象

---

*在活动会话期间，HUD 大约每 300ms 自动更新一次。*
