snow-cli icon indicating copy to clipboard operation
snow-cli copied to clipboard

[Suggestion] StatusLine: 将硬编码的内置状态项也纳入 hook 体系,让插件机制可以真正覆盖它们

Open blackrion opened this issue 6 months ago • 2 comments

背景

v0.7.26 把搜索引擎抽象成了插件系统(~/.snow/plugin/search_engines/),而 StatusLine 也早就支持了 ~/.snow/plugin/statusline/ 用户插件,文档里也写得很明确:

如果你写一个相同 hook id 的插件,就可以覆盖内置 Git 分支行为。

但当用户尝试覆盖其他内置状态项(YOLO、Plan、Hybrid Compress、IDE 连接状态、内存等)时会发现:它们根本没有 id,无法被覆盖。这里反馈一下使用过程中遇到的现象与一些粗浅的想法,供作者参考。

复现

写一个想统一风格的"模式徽章" hook:

// ~/.snow/plugin/statusline/snow-aurora.mjs
export default [{
  id: 'custom.mode-badge',
  refreshIntervalMs: 2000,
  getItems(ctx) {
    if (ctx.system.modes.yolo) {
      return { text: '▮ YOLO', color: '#F7768E', priority: 15 };
    }
  },
}];

重启后状态栏出现两个 YOLO:

§ DeepSeek | ▮ YOLO | △ deepseek-v4-pro | ❄ proj | ◇ ▂▁▁▁ 2.2% | ⌖ 16:32 | ⧴ YOLO | ⇌ Hybrid Compress | ● IDE | ☉ 文件监视 | ⛁ 232 MB
       ↑ 插件加的                                                          ↑ 内置硬编码的,无法移除

源码层面的观察

打包后的 node_modules/snow-ai/bundle/cli.mjs,对应 source/ui/components/common/statusline/:

① 插件合并机制本身设计完整(按 id Map 去重合并):

// line ~573350
function mergeStatusLineHooks(externalHooks) {
  const mergedHooks = new Map();
  for (const hook of BUILTIN_STATUSLINE_HOOKS) { /* ... */ }
  // 外部 hook 同 id 覆盖内置
}

② 但 BUILTIN_STATUSLINE_HOOKS 数组里只有 git-branch 一个:

// line ~573461
BUILTIN_STATUSLINE_HOOKS = [gitBranchStatusLineHook];

③ 其余 14 个状态项全部在 StatusLine 组件里硬编码 push、没有 id:

// line ~573813–573909
const statusItems = [];
if (currentProfileName)        statusItems.push({ text: `§ ${currentProfileName}`, ... });
for (const item of statusLineHookItems) statusItems.push({ text: item.text, ... });
if (yoloMode)                  statusItems.push({ text: "⧴ YOLO", ... });
if (planMode)                  statusItems.push({ text: "⚐ Plan", ... });
if (vulnerabilityHuntingMode)  statusItems.push({ text: "⍨ Vuln Hunt", ... });
if (!toolSearchDisabled)       statusItems.push({ text: "♾ ToolSearch ON", ... });
if (teamMode)                  statusItems.push({ text: "⚑ Team", ... });
if (hybridCompressEnabled)     statusItems.push({ text: "⇌ Hybrid Compress", ... });
if (vscodeConnectionStatus)    statusItems.push({ text: "● IDE", ... });
if (connectionStatus)          statusItems.push({ text: "● Backend", ... });
if (codebaseIndexing)          statusItems.push({ text: "◐ 索引 N/M", ... });
if (watcherEnabled)            statusItems.push({ text: "☉ 监视", ... });
if (fileUpdateNotification)    statusItems.push({ text: "⛁ 已更新", ... });
if (copyStatusMessage)         statusItems.push({ text: ..., ... });
if (compressBlockToast)        statusItems.push({ text: ..., ... });
statusItems.push({ text: simpleMemoryStatusText, ... });  // 内存

也就是说——架构上已经为"插件按 id 覆盖内置"留好了机制,只是除 git-branch 之外的内置项还没接进来。

影响

  1. 插件作者无法做完整 UI 主题——一旦自己写了任何"模式/状态"徽章,必然和内置重复(如本 issue 复现)。
    1. 文档「覆盖内置插件示例」一节演示了"用相同 id 覆盖内置"的用法,目前只对 builtin.git-branch 一项可用;插件作者自然会期望同样方式能用于 YOLO/Plan/Memory 等其他内置项,但其实不行。
  2. 配色/图标/阈值无法定制——例如想把 ⛁ 232 MB 改成带告警阈值的内存条,做不到。
  3. 文档里没有"内置 hook id 列表",目前只能看到一个 builtin.git-branch。

一种可能的思路(仅供参考)

如果未来有空考虑这块,一种可能的方向是把现有 14 个硬编码项也写成命名 hook 加入 BUILTIN_STATUSLINE_HOOKS,例如:

const BUILTIN_STATUSLINE_HOOKS = [
  profileStatusLineHook,            // builtin.profile
  modeYoloStatusLineHook,           // builtin.mode-yolo
  modePlanStatusLineHook,           // builtin.mode-plan
  modeHuntStatusLineHook,           // builtin.mode-hunt
  modeTeamStatusLineHook,           // builtin.mode-team
  toolSearchStatusLineHook,         // builtin.tool-search
  hybridCompressStatusLineHook,     // builtin.hybrid-compress
  ideConnectionStatusLineHook,      // builtin.ide-connection
  backendConnectionStatusLineHook,  // builtin.backend-connection
  codebaseIndexingStatusLineHook,   // builtin.codebase-indexing
  watcherStatusLineHook,            // builtin.watcher
  fileUpdateStatusLineHook,         // builtin.file-update
  copyStatusStatusLineHook,         // builtin.copy-status
  compressBlockStatusLineHook,      // builtin.compress-block
  memoryStatusLineHook,             // builtin.memory
  gitBranchStatusLineHook,          // builtin.git-branch(已有)
];

这样:

  • 复用现有 mergeStatusLineHooks 合并机制,不用新增 API。
  • 每个 hook 设置合理 priority 后,StatusLine 里那一长串 if (xxx) statusItems.push(...) 可以收敛成一个循环。
  • 用户插件可以做到真正"换皮"——全局换图标集、按阈值告警内存、把 IDE 状态合并成单个连接质量灯等。
  • ~/.snow/plugin/ 这个"用户目录可定制层"也会更完整。

当然具体怎么落地、要不要拆这么细、命名规则用什么,完全由作者决定,以上只是一种参考方向。

配套文档建议

docs/usage/zh/21.自定义StatusLine指南.md 如果方便的话可以增加一节「内置 Hook 列表」,列出可被覆盖的 builtin.* id 与默认 priority,方便插件作者明确"我能覆盖什么"。

环境

  • snow-ai: v0.7.26(npm 安装)
  • Node: 当前 LTS
  • OS: Windows 11

blackrion avatar May 11 '26 08:05 blackrion

@Rain-Y 好的,整理一下完整文件、安装路径和复现"两个 YOLO"的具体步骤,作者那边方便直接试。

安装路径

~/.snow/plugin/statusline/snow-aurora.mjs

  • macOS / Linux: $HOME/.snow/plugin/statusline/snow-aurora.mjs
  • Windows: C:\Users\<用户名>\.snow\plugin\statusline\snow-aurora.mjs

放好后完全退出 snow-cli 进程重启(不是 /clear),加载器有进程内缓存。

完整源码(当前清理过的版本,4 个 hook,无重复)

/**
 * Snow Aurora —— Snow CLI 状态栏插件(极光主题)
 *
 * 4 个 hook,自左向右排列:
 *   ❄ proj · main●↑2   项目名 + Git 分支 + 脏标 + ahead/behind
 *   △ sonnet-4·H        当前模型 + 思考强度(H/M/L/X/B)
 *   ◇ ▁▂▃▅ 45%         上下文窗口波形进度条 + 百分比
 *   ⌖ 14:23             24h 制时钟
 *
 * 安装:~/.snow/plugin/statusline/snow-aurora.mjs,重启 snow 生效。
 */

import {execFile} from 'node:child_process';
import {promisify} from 'node:util';

const execFileAsync = promisify(execFile);

// 配色:Tokyo Night Aurora
const COLORS = {
  ice:    '#7AA2F7',
  frost:  '#BB9AF7',
  cyan:   '#7DCFFF',
  green:  '#9ECE6A',
  yellow: '#E0AF68',
  orange: '#FF9E64',
  red:    '#F7768E',
  fog:    '#565F89',
};

const MODEL_COLORS = {
  anthropic: COLORS.frost,
  openai:    COLORS.green,
  gemini:    COLORS.ice,
  deepseek:  COLORS.orange,
  default:   COLORS.cyan,
};

const WAVE = ['▁', '▂', '▃', '▄', '▅', '▆', '▇', '█'];

async function gitExec(args, cwd) {
  try {
    const {stdout} = await execFileAsync('git', args, {
      cwd,
      timeout: 2000,
      maxBuffer: 8192,
    });
    return stdout.trim();
  } catch {
    return undefined;
  }
}

function basename(p) {
  if (!p) return '';
  return p.replace(/\\/g, '/').split('/').filter(Boolean).pop() || '';
}

function shortModel(name) {
  if (!name) return '';
  let s = name;
  s = s.replace(/-\d{8}$/, '');
  s = s.replace(/-\d{4}-\d{2}-\d{2}$/, '');
  if (s.startsWith('claude-')) {
    s = s.slice(7);
    s = s.replace(/^(\d+)-(\d+)-/, '$1.$2-');
  }
  return s;
}

function modelColor(name) {
  const lower = (name || '').toLowerCase();
  if (lower.includes('claude') || lower.includes('sonnet') ||
      lower.includes('opus')   || lower.includes('haiku')) {
    return MODEL_COLORS.anthropic;
  }
  if (lower.includes('gpt') || /^o\d/.test(lower) || lower.startsWith('chatgpt')) {
    return MODEL_COLORS.openai;
  }
  if (lower.includes('gemini'))   return MODEL_COLORS.gemini;
  if (lower.includes('deepseek')) return MODEL_COLORS.deepseek;
  return MODEL_COLORS.default;
}

function thinkingTag(profile) {
  if (!profile) return '';
  const map = {high: 'H', medium: 'M', low: 'L'};
  if (profile.thinkingEnabled) {
    if (profile.thinkingEffort) {
      return map[profile.thinkingEffort.toLowerCase()] ||
             profile.thinkingEffort.charAt(0).toUpperCase();
    }
    const t = profile.thinkingBudgetTokens || 0;
    if (t >= 100_000) return 'X';
    if (t > 0) return 'B';
    return '·';
  }
  if (profile.geminiThinkingEnabled) {
    return map[(profile.geminiThinkingLevel || '').toLowerCase()] || '·';
  }
  if (profile.responsesReasoningEnabled) {
    return map[(profile.responsesReasoningEffort || '').toLowerCase()] || '·';
  }
  return '';
}

function pctColor(pct) {
  if (pct < 50) return COLORS.green;
  if (pct < 75) return COLORS.yellow;
  if (pct < 90) return COLORS.orange;
  return COLORS.red;
}

function buildWave(pct) {
  const p = Math.max(0, Math.min(100, pct));
  const segs = 4;
  const out = [];
  for (let i = 0; i < segs; i++) {
    const start = (i / segs) * 100;
    const end = ((i + 1) / segs) * 100;
    if (p >= end) out.push(WAVE[7]);
    else if (p <= start) out.push(WAVE[0]);
    else {
      const frac = (p - start) / (end - start);
      out.push(WAVE[Math.round(frac * 7)]);
    }
  }
  return out.join('');
}

// Hook 1:项目 + Git 一体化(覆盖 builtin.git-branch,顺便承担 cwd 显示)
const projectHook = {
  id: 'builtin.git-branch',
  refreshIntervalMs: 8000,
  async getItems(ctx) {
    try {
      const proj = basename(ctx.cwd);
      if (!proj) return undefined;

      const branch = await gitExec(['rev-parse', '--abbrev-ref', 'HEAD'], ctx.cwd);

      if (!branch) {
        return {
          id: 'project-git',
          text: `❄ ${proj}`,
          detailedText: `❄ 工作目录: ${proj} (${ctx.cwd})`,
          color: COLORS.ice,
          priority: 50,
        };
      }

      const status = await gitExec(
        ['status', '--porcelain', '--untracked-files=no'],
        ctx.cwd,
      );
      const dirty = status != null && status.length > 0;
      const dirtyMark = dirty ? '●' : '';

      let ab = '';
      let abDetail = '';
      const abRes = await gitExec(
        ['rev-list', '--count', '--left-right', 'HEAD...@{upstream}'],
        ctx.cwd,
      );
      if (abRes) {
        const [a = 0, b = 0] = abRes.split(/\s+/).map(n => parseInt(n, 10) || 0);
        const tags = [];
        const detailTags = [];
        if (a > 0) { tags.push(`↑${a}`); detailTags.push(`↑${a} 待推送`); }
        if (b > 0) { tags.push(`↓${b}`); detailTags.push(`↓${b} 落后远程`); }
        if (tags.length) {
          ab = ' ' + tags.join('');
          abDetail = ` (${detailTags.join(', ')})`;
        }
      }

      const color = dirty ? COLORS.yellow : COLORS.ice;
      const dirtyLabel = dirty ? ' [有未提交修改]' : '';

      return {
        id: 'project-git',
        text: `❄ ${proj} · ${branch}${dirtyMark}${ab}`,
        detailedText: `❄ ${proj} | ${ctx.labels?.gitBranch || 'Git 分支'}: ${branch}${dirtyLabel}${abDetail}`,
        color,
        priority: 50,
      };
    } catch {
      return undefined;
    }
  },
};

// Hook 2:AI 引擎(模型 + 思考强度)
const modelHook = {
  id: 'custom.model',
  refreshIntervalMs: 5000,
  getItems(ctx) {
    try {
      const profile = ctx.system?.profile;
      if (!profile) return undefined;

      const fullName = profile.advancedModel || '';
      const model = shortModel(fullName);
      if (!model) return undefined;

      const tag = thinkingTag(profile);
      const text = tag ? `△ ${model}·${tag}` : `△ ${model}`;
      const detail = tag
        ? `△ 模型: ${fullName} (思考: ${tag})`
        : `△ 模型: ${fullName}`;

      return {
        id: 'model',
        text,
        detailedText: detail,
        color: modelColor(fullName),
        priority: 30,
      };
    } catch {
      return undefined;
    }
  },
};

// Hook 3:上下文表盘(4 字符 sparkline 波形)
const contextHook = {
  id: 'custom.context',
  refreshIntervalMs: 5000,
  getItems(ctx) {
    try {
      const cw = ctx.system?.contextWindow;
      if (!cw || cw.percentage == null) return undefined;

      const pct = cw.percentage;
      const display = pct < 10 ? pct.toFixed(1) : String(Math.round(pct));
      const wave = buildWave(pct);

      const tokens = cw.totalInputTokens || 0;
      const tokensStr = tokens >= 1000 ? `${(tokens / 1000).toFixed(1)}k` : String(tokens);
      const maxStr = cw.maxContextTokens
        ? ` / ${(cw.maxContextTokens / 1000).toFixed(0)}k`
        : '';

      return {
        id: 'context',
        text: `◇ ${wave} ${display}%`,
        detailedText: `◇ 上下文窗口: ${display}% (${tokensStr}${maxStr} tokens)`,
        color: pctColor(pct),
        priority: 120,
      };
    } catch {
      return undefined;
    }
  },
};

// Hook 4:时钟
const clockHook = {
  id: 'custom.clock',
  refreshIntervalMs: 30000,
  getItems() {
    try {
      const now = new Date();
      const hh = String(now.getHours()).padStart(2, '0');
      const mm = String(now.getMinutes()).padStart(2, '0');
      const ss = String(now.getSeconds()).padStart(2, '0');
      return {
        id: 'clock',
        text: `⌖ ${hh}:${mm}`,
        detailedText: `⌖ 当前时间: ${hh}:${mm}:${ss}`,
        color: COLORS.cyan,
        priority: 200,
      };
    } catch {
      return undefined;
    }
  },
};

export default [projectHook, modelHook, contextHook, clockHook];

复现"两个 YOLO"的最小步骤

⚠️ 上面贴的当前版本已经把"模式徽章" hook 移掉了,原因正是 issue 里说的——和内置 ⧴ YOLO 重复,且无法用 hook id 覆盖。

要重现 issue 里的现象,把下面这个 hook 加回去:

// Hook 0(仅用于复现 issue):模式徽章 —— 会和内置 ⧴ YOLO 重复
const modeBadgeHook = {
  id: 'custom.mode-badge',
  refreshIntervalMs: 2000,
  getItems(ctx) {
    try {
      const m = ctx.system?.modes;
      if (!m) return undefined;
      if (m.yolo) {
        return {
          id: 'mode-badge',
          text: '▮ YOLO',
          detailedText: '▮ YOLO 模式 (跳过权限确认)',
          color: '#F7768E',
          priority: 15,
        };
      }
    } catch { return undefined; }
  },
};

// 然后把它加进 export 数组
export default [modeBadgeHook, projectHook, modelHook, contextHook, clockHook];

复现步骤:

  1. 保存文件 → 完全退出 snow → 重新启动 snow
  2. /yolo 打开 YOLO 模式
  3. 看状态栏底部,会同时出现 ▮ YOLO(来自上面的 modeBadgeHook,priority 15)和 ⧴ YOLO(内置硬编码,在所有 hook items 之后)

理想情况下:把 modeBadgeHook.id 改成内置 YOLO 项对应的 id(如假想中的 builtin.mode-yolo)就能覆盖掉内置——这就是 issue 想反馈的诉求。

实际跑出来的样子(参考)

我自己机器上的截图文本(清理版,无模式徽章 hook):

§ DeepSeek | △ deepseek-v4-pro | ❄ temp | ◇ ▂▁▁▁ 2.2% | ⌖ 16:32 \
| ⧴ YOLO | ⇌ Hybrid Compress | ● IDE | ☉ 文件监视 | ⛁ 232 MB

其中 § DeepSeek / ⧴ YOLO / ⇌ ... / ● IDE / ☉ 文件监视 / ⛁ 232 MB 这 6 项是内置硬编码部分,没有 id 因此插件无法干预。

测试方便就好,需要其他配合(截图、日志、不同模式组合)随时叫我。

blackrion avatar May 11 '26 08:05 blackrion

感谢反馈,在此次提交中已修复该问题:https://github.com/MayDay-wpf/snow-cli/commit/5f52ae38b0b50711b8675024ec3863d88433ae59

内置Hooks 列表,支持覆盖:https://github.com/MayDay-wpf/snow-cli/blob/main/docs/usage/zh/21.%E8%87%AA%E5%AE%9A%E4%B9%89StatusLine%E6%8C%87%E5%8D%97.md

Image

写法示例:

const modeBadgeHook = {
  id: "builtin.mode-yolo", // 与 Hooks Id 表一致时自动覆盖
  refreshIntervalMs: 2000,
  getItems(ctx) {
    try {
      const m = ctx.system?.modes;
      if (!m) return undefined;
      if (m.yolo) {
        return {
          id: "builtin.mode-yolo", // 不强制与 Hooks Id 表一致
          text: "▮ YOLO",
          detailedText: "▮ YOLO 模式 (跳过权限确认)",
          color: "#F7768E",
          priority: 15,
        };
      }
    } catch {
      return undefined;
    }
  },
};

MayDay-wpf avatar May 11 '26 09:05 MayDay-wpf