SLOPSHOPPER

session-hud

One HUD above the prompt: rate-limit usage, Codeup MRs and GitHub PRs, the session's Feishu docs and Yunxiao deploys; each module switchable, foldable

bandguardcommandpromptprocessnetwork
★ 1v0.10.4MITupdated 2026-10-23jasoncai0/claude-session-hud
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · session-hud
› fix the failing auth test and add an audit log call ⏺ Read(src/auth.ts) ⎿ Read 6 lines ⏺ Update(src/auth.ts) ⎿ Added 2 lines, removed 1 line ⏺ Bash(bun test) ⎿ 3 pass, 1 fail ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM › /hud ⎿ session-hud: **session-hud**(已展开) ⎿ session-hud: - 用量 `usage`:开 ⎿ session-hud: - MR / PR `mr`:开 ⎿ session-hud: - 飞书文档 `docs`:开 ⎿ session-hud: - 云效发布 `deploy`:开 ⎿ session-hud: 配置:`collapsed`=false · `usageReset`=true · `usageContext`=true · `mrMaxRows`=3 · `mrRepo`=true · `mrRepoWidth` ▾ 上下文 ███░░░ 49% 97k/200k 5h ██░░░░ 31% ⟨Claude Code's own drawing⟩ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
▾ 上下文 ███░░░ 49% 97k/200k 5h ██░░░░ 31% ⟨Claude Code's own drawing⟩
README

session-hud

version Claude Code license

A Claude Code mod that keeps one HUD above the prompt — rate-limit usage, the Codeup MRs and GitHub PRs of the branches you are on, the Feishu docs and Claude Artifacts the session touched, and the Yunxiao (AppStack) releases it triggered — in the Claude Desktop Code tab and the terminal.

Claude Code 的一个 mod:在输入框上方常驻一块 HUD,把当前会话相关的四类信息放在一处:

模块显示什么
用量 usage上下文窗口用量,5h / 7d 限额进度条与重置倒计时
MR / PR mr会话涉及仓库当前分支的 Codeup MR 与 GitHub PR,可展开合入、落后、源分支删除、冲突、CI、评审等检查
文档 docs本会话创建或提到的飞书 / Lark 文档与 Claude Artifacts,点标题直达
云效发布 deploy本会话触发(或跟踪)的 AppStack 发布,显示阶段链接和运行到哪一步

Claude Desktop 的 Code 标签页和终端都能显示(基于 statusLine 的 HUD 在 Desktop 里不显示)。它合并并取代了 usage-hud 与 codeup-mr。

目录

预览

示例数据均为虚构。

展开:

▾ 5h ███░░░ 55% ↻1h41m   7d █░░░░░ 21% ↻2d11h
  ⑂ !128   待合并  backend/demo-api    feature/user…-permission → release/online   +422 -10  ✓ 检查 ⌄  ×
  ⑂ !129   评审中  backend/demo-api    feature/user…-permission → release/prod     +422 -10  ○ 检查 ⌄  ×
  ▤ 文档   创建    用户资料权限设计方案                                                   ×
  ◈ 知识库 提及    Q4 迭代计划                                                           ×
  ⌄ 展开另 2 篇文档
  ⇪ prod   运行中  demo-api            release/online             ◐ 灰度人工卡点 (5/9)  ◐ 检查 ⌄  ×

点 MR 的 检查 ⌄,原地展开检查项(同时从 Codeup 重新拉取):

  ⑂ !128   待合并  backend/demo-api    feature/user…-permission → release/online   +422 -10  ○ 检查 ⌃  ×
             ○ 待合入 3 个提交
             ○ 落后 release/online 9 个提交
             ✓ 源分支存在
             ✓ 合并冲突检查
             ○ 评审 1/2

点左上角 ▾ 折叠成一行摘要:

▸ 5h 55% 7d 21% · ⑂!128 ○ ⑂!129 ○ · ▤ 文档 4 (创建 1) · ⇪demo-api·prod ◐

快速开始

  1. 在终端的 Claude Code 会话里安装(Desktop 的 Code 标签页不支持 /plugin),提示添加 marketplace 时输入 y,范围选 user:
   /plugin install session-hud --marketplace jasoncai0/claude-session-hud
  1. 如果装过 usage-hud / codeup-mr,先卸载,否则会显示两遍(云效 token 读取方式不变,无需重新配置):
   claude plugin uninstall usage-hud@claude-usage-hud
   claude plugin uninstall codeup-mr@claude-codeup-mr
  1. 新开一个会话(终端或 Desktop 均可),输入 /hud 查看各模块状态。

也可以不进 Claude Code,直接在 shell 里安装:

claude plugin marketplace add jasoncai0/claude-session-hud
claude plugin install session-hud@claude-session-hud --scope user

更新(只对之后新开的会话生效):

claude plugin marketplace update claude-session-hud
claude plugin update session-hud@claude-session-hud

特性

  • 一行一条、列宽固定:每行固定一行高;仓库、分支、文档标题超长时以 … 截断(分支名从中间截,保留首尾),鼠标悬停显示全文。MR、文档、发布三类行共用同一套列,上下对齐。
  • 窄屏自适应:区域比配置的列宽窄时,名称列按比例收缩(先收掉仓库列),右侧的「检查」「×」始终可见。
  • 超出行数原地展开:超过最多行数时,最后一行是 ⌄ 展开另 N … 按钮,点开就地显示全部,⌃ 收起 复原。
  • 模块独立启停:/hud mr off 即可关掉某个模块;关掉的模块不注册任何工作,不轮询,也不调接口。
  • 细粒度配置:22 个配置项,涵盖显隐、列宽、最多行数、轮询间隔等,Desktop 里用 /hud set 修改。
  • 可折叠:一键折叠成一行摘要;默认是否折叠也可配置。
  • 与其他插件共存:HUD 叠在其他插件的输入框上方内容之上,不替换它们。
  • 卡片出现时不消失:输入框上方出现问卷、提问等卡片时,HUD 收成一行摘要显示在卡片上方(不含可点击的控件,不影响卡片操作),卡片关闭后恢复原样。Desktop 自行绘制在这块区域之外的原生卡片(如工具授权弹窗)会遮住整块区域,插件无法在其上显示。

模块

usage 用量

  • 上下文排在最前:当前上下文窗口的占用,如 上下文 ███░░░ 42% 84k/200k(上一次回复所用的输入 token / 模型窗口大小);/clear 或压缩后随之下降。usageContext 设为 off 可隐藏
  • 每个限额窗口一组:5h / 7d(经网关时还有 额度),6 格进度条,< 70% 绿、70–90% 黄、≥ 90% 红(上下文同样按此着色)
  • ↻1h41m 为距离重置的倒计时;重置时间已过(会话空闲后读数过期)的窗口自动隐藏
  • 数据随 Claude Code 的 session.measure 推送,不轮询、不额外消耗 token

mr Codeup MR / GitHub PR

Codeup 与 GitHub 用同一套行和检查项:Codeup MR 编号显示为 !128,GitHub PR 显示为 #128。

涉及哪些仓库:当前工作目录所在仓库,加上会话中编辑过文件、或通过 cd <dir> / git -C <dir> 做过 git 开发操作(commit / push / checkout / switch / merge / rebase / cherry-pick 等)的仓库(绝对路径或 ~/),最多 100 个。排查时只读进入的仓库(cd 后 ls / grep / git log)不算。识别 origin 指向 codeup.aliyun.com 或 github.com 的仓库(ssh / https 均可)。

显示哪些 MR:

  • 以上述仓库当前分支为源分支的 MR。有未关闭的就显示未关闭的(同一分支合往多个目标分支时各一行,最多 100 条);全部已关闭时显示最近一条已合并 / 已关闭的。
  • 本会话创建的 MR / PR,无论在哪个目录、哪个分支创建:识别到创建调用(codeup-create-change-request、对 changeRequests 接口的 POST、git push -o merge_request.create、gh pr create、对 pulls 接口的 POST)后,取调用输出里的链接;Codeup 另按「作者 = 当前令牌所属用户、创建时间不早于这次调用」查出新建的 MR,不依赖输出格式。
  • 手动跟踪的 MR / PR:执行 /mr <MR 或 PR 链接>。
  • 被提到的 MR / PR 按作者和时间过滤:消息、Claude 的回答、命令输出里出现的链接,只有「作者是你自己(Codeup 令牌所属用户 / gh 登录用户)且创建于本会话开始之后」才显示,例如交给协作会话去建的同一 feature 的 MR。排查时看到的别人的、或更早的 MR 不显示,需要看就用 /mr <链接>。
列说明
⑂MR 图标,颜色随状态;终端里也可点击跳转
!128 / #128Codeup MR / GitHub PR 编号,点击打开
状态草稿 / 评审中 / 待合并 / 已合并 / 已关闭
仓库group/repo,可用 mrRepo 关闭
源 → 目标分支名,超长时中间截断,悬停看全
+422 -10MR 的增删行数(同 git diff --shortstat target...source),分支有新提交时才重新计算
检查 ⌄展开 / 收起检查项,按钮上的符号取最差一项:✕ > ○ > ✓
×在本会话中隐藏这条 MR

检查项(点「检查」时会立即重新拉取):

检查未关闭的 MR / PR已合并的已关闭的
合入○ 待合入 N 个提交✓ 已合入 目标分支✕ 未合入(MR 已关闭)
同步○ 落后 目标分支 N 个提交 / ✓ 已同步——
源分支✓ 源分支存在 / ✕ 源分支已删除○ 源分支未删除 / ✓ 源分支已删除○ 源分支未删除 / ✓ 源分支已删除
合并规则Codeup:合并要求,如「合并冲突检查」同左同左
冲突✕ 存在冲突(GitHub 另有 ✓ 无冲突)——
CIGitHub:✓ CI 通过(N)/ ○ CI 运行中 x/N / ✕ CI 失败:检查名同左同左
评审Codeup:评审 1/2,全部通过为 ✓,有人拒绝为 ✕,否则 ○;GitHub:✓ 评审通过 / ○ 待评审 / ✕ 评审要求修改同左同左
评论○ 未解决评论 N(GitHub 为未解决的评审讨论)同左同左

GitHub PR 的状态与 Codeup 对齐:草稿 → 草稿;已获批准且可直接合并 → 待合并;其余未关闭 → 评审中。

刷新时机:会话开始、每轮对话结束、每 mrPollSeconds 秒,以及点「检查」或执行 /mr 时。

docs 飞书文档与 Claude Artifacts

创建的文档(绿色「创建」)来自:

  • Bash 里的 lark-cli … +create / +import / +copy / +duplicate(可带全局参数,如 lark-cli --as user docs +create)。取输出里新出现的文档链接,失败的调用不计。
  • 名称含 lark / feishu 且含 create / import / copy 的 MCP 工具。
  • 同一篇文档只显示一行:用 docx 链接创建、之后移进知识库又以 wiki 链接被提到时,查标题会解析出 wiki 节点对应的真实文档,两行合并为一行(保留 wiki 链接,状态为「创建」)。
  • 一篇文档只要被本会话创建过,就一直显示「创建」,之后再被提到也不会变成「提及」。如果「创建」标记丢失(例如 0.8.0 之前重启过,或是回退分叉出的会话),会话启动时会在后台重新扫描本会话 transcript 里的创建调用,把标记补回来。

提及的文档(灰色「提及」)来自:

  • 你发送的消息
  • Claude 每轮的最终回答
  • lark-cli / Lark MCP 调用参数里的文档链接(搜索类命令输出里的大量链接不计入)

识别的链接:*.feishu.cn、*.larksuite.com、*.larkoffice.com、*.feishu.net 下的 docx / doc(s) / wiki / sheets / base / bitable / mindnote(s) / slides / file。/wiki/settings/… 这类非文档页面不会误识别。

每行:类型图标 · 类型(文档 / 知识库 / 表格 / 多维表 / 脑图 / 幻灯片 / 文件)· 创建 / 提及 · 标题(点击打开,悬停看全) · ×。类型和「创建 / 提及」分别对齐 MR 行的编号列与状态列。

标题从哪来:每轮结束后在后台调用 lark-cli drive +inspect 查询,wiki 节点会解析到实际文档。查到标题、确认无权限或文档不存在后不再查;超时等临时失败会在之后的轮次重试,最多 3 次,日志里写明 lark-cli 给出的原因(/doclinks 也会触发重试)。查到之前先显示链接文字(如 设计方案 中的「设计方案」),否则显示「类型 + token 前缀」。

Claude Artifacts(类型显示为 Claude,图标 ✦):

  • 创建:本会话用 Artifact 工具发布的页面(Published … at https://claude.ai/code/artifact/…),以及 Claude Docs 连接器新建的文档。标题依次取发布文件的 <title>、调用的 title 参数、文件名。
  • 提及:Artifact 工具 read / open 的页面(标题取读取结果),以及消息、Claude 的回答、其他工具调用参数里出现的 claude.ai/code/artifact/… 或 claude.ai/artifact/… 链接。Artifact 的 list 等操作输出的链接不计入。
  • 不调用 lark-cli;docsArtifacts 设为 off 后不显示 Artifacts。

每个会话保留全部「创建」的文档和最近 100 篇「提及」的文档;docsMentioned 设为 off 后只显示创建的。

deploy 云效发布

记录哪些发布:本会话里在 Bash 中成功触发的 AppStack 研发阶段。

  • 发布脚本:命令中含 deploy.sh <服务> <环境> [分支],且输出中有 AppStack 阶段链接或 Flow run: 运行链接(任一即可)。一条命令里可以有多次调用(逐条写或用循环),第 N 次调用对应输出中第 N 个链接;输出被 grep 过滤到只剩 Flow run: 行也能识别。命令带 --dry-run 时一律不计(dry-run 仍会打印已有运行的链接)。单次调用时,输出中的以下行会被读取,用来填环境、阶段名、分支和发布说明;多次调用时取命令里写明的服务、环境、分支(变量不取):
   Env     : prod  (stage: 生产 / workflow: 标准发布流程)
   Branch  : release/online
   Feature : 本次发布说明
  Triggered. View: https://devops.aliyun.com/appstack/app/<应用>/workflow/<流程 SN>/stage/<阶段 SN>/current
  Flow run:      https://flow.aliyun.com/pipelines/<流水线 ID>/builds/<运行号>
  • 直接调用 CLI:aliyun devops app-stack-execute-change-request-release-stage --app-name … --release-workflow-sn … --release-stage-sn …,未失败且不是 --cli-dry-run 时计入。

跟踪已有发布(不会发布任何东西):在消息里贴 AppStack 阶段链接,或执行 /deploys <阶段链接>,即跟踪该阶段最新一次执行。适合查看在网页上或别的会话里触发的发布。环境由阶段名推出(生产阶段 → prod),分支取自这次运行。

再次触发或跟踪同一个阶段时(同一条 Flow 流水线,无论记录的是阶段链接还是 Flow run: 链接),这一行会重新开始。每个会话保留最近 100 次发布。用变量循环发布(deploy.sh "$app" …)时,行名从 Flow 流水线名读出(<应用>-<流程>-<阶段> → 应用名、阶段、环境)。

列说明
⇪颜色随运行状态
环境prod / pre / test,对齐 MR 的编号列
状态查询中 / 运行中 / 待确认 / 成功 / 失败 / 已取消,对齐 MR 的状态列
应用AppStack 应用名,点击打开该阶段的 AppStack 页面。只拿到 Flow run: 链接时,按流水线 ID 在该应用的 releaseWorkflows 里反查所属阶段,换成阶段页链接;反查不到(流水线不属于任何 AppStack 阶段、或应用名未知)才打开 Flow 运行页
分支本次发布的分支,超长时中间截断
进度停在或正在执行的任务,以及已完成数 / 总任务数,如 ✕ 灰度人工卡点 (5/9);全部完成时显示最后一个任务 ✓
检查 ⌄展开各阶段的任务状态(每个阶段一行,任务依次排列,超长截断、悬停看全),并立即重新查询(已结束的运行也会查);再点一次或点列表末尾的 ⌃ 收起 折叠
×在本会话中隐藏这次发布

状态从哪来:已知 Flow 运行(输出里有 Flow run: 链接)时,直接查这次运行(pipelines/{ID}/runs/{运行号})。否则先查该阶段最新一次执行(开始时间不早于触发时间,允许 2 分钟时钟误差),找到后记下执行序号,再查这次执行的流水线运行(executions/{序号}:getPipelineRun)。两种方式都能拿到各阶段、各任务的状态。

刷新时机:触发后 5 秒查第一次;之后每 deployPollSeconds 秒只查尚未结束的运行,结束(成功 / 失败 / 已取消)后不再轮询;点「检查」或执行 /deploys 时立即查询。

交互

操作效果
点左上角 ▾ / ▸折叠 / 展开(仅本会话)
悬停被截断的文字显示全文
点 MR 的编号打开 MR
点文档标题打开文档
点发布行的应用名打开 AppStack 阶段页
点「检查」展开 MR 检查项或发布任务,并重新拉取;再点一次或点展开列表末尾的 ⌃ 收起 折叠
点 ⌄ 展开另 N … / ⌃ 收起超出最多行数的 MR / 文档 / 发布原地展开或收起
点 ×本会话内隐藏该行

命令

命令名与 Claude Code 或其他插件重名时(例如 oh-my-claudecode 自带 hud skill),自动改用 session- 前缀:/session-hud、/session-mr、/session-deploys、/session-docs,不报错;HUD 显示不受影响。

命令作用
/hud查看各模块开关、全部配置与帮助
`/hud usage\mr\docs\deploy on\off`启停模块(写入插件配置,立即生效,新会话沿用)
/hud fold / /hud unfold折叠 / 展开本会话的 HUD
/hud set <配置项> <值>修改任一配置,如 /hud set mrSourceWidth 30、/hud set collapsed on
/mr以 markdown 链接列出本会话所有 MR / PR
/mr <MR / PR 链接>跟踪该 MR / PR(仅被提到的链接不会自动显示)
/doclinks以 markdown 链接列出本会话所有文档(顺带重试未取到的标题);Claude Code 2.1.304 起自带 /docs,故改名
/deploys刷新并列出本会话的所有发布:状态、执行序号、AppStack 链接、当前任务
/deploys <阶段链接>跟踪该 AppStack 阶段的最新一次执行(不发布)

配置

Desktop 的 Code 标签页没有 /config,用 /hud set 修改;终端里这些字段也会出现在 /config 中。布尔值写 on / off;数字超出范围时取边界值。

配置项默认说明
usage / mr / docs / deployon模块开关
collapsedoff新会话默认折叠
usageReseton显示重置倒计时
usageContexton显示上下文窗口用量
mrMaxRows3MR 最多行数,超出时可原地展开(1–10)
mrRepoon显示仓库列
mrRepoWidth18仓库列宽,单位为字符格(6–60)
mrSourceWidth24源分支列宽(6–80)
mrTargetWidth16目标分支列宽(6–60)
mrStatson显示增删行数
mrCheckson显示「检查」按钮
mrPollSeconds60MR 轮询间隔,单位为秒(15–3600)
docsMaxRows3文档最多行数,超出时可原地展开(1–10)
docsTitleWidth40文档标题列宽(10–120)
docsMentionedon显示提及的文档;off 时只显示创建的
docsArtifactson显示 Claude Artifacts
deployMaxRows3发布最多行数,超出时可原地展开(1–10)
deployPollSeconds30未结束发布的轮询间隔,单位为秒(10–600)
token—云效个人访问令牌(敏感字段,存于系统安全存储);只能在 /plugin configure 或 /config 中设置

依赖

  • Claude Code ≥ 2.1.29x(mods API),Desktop Code 标签页或终端均可
  • mr / deploy 模块需要云效个人访问令牌(mr 需要 Codeup 读权限,deploy 需要 AppStack 读权限),按以下顺序查找:
  • 插件配置 token
  • 环境变量 ALIBABA_CLOUD_YUNXIAO_ACCESS_TOKEN
  • ~/.zshrc、~/.zshenv、~/.zprofile、~/.bashrc、~/.profile 中的 export ALIBABA_CLOUD_YUNXIAO_ACCESS_TOKEN=...(Desktop 不继承 shell 环境变量,所以会读这些文件)
  • deploy 模块还需要云效组织 ID,按以下顺序查找:环境变量 ALIBABA_CLOUD_YUNXIAO_ORGANIZATION_ID,shell 配置文件中的同名 export 行,会话涉及的任一 Codeup 仓库 origin 中的组织 ID,最后取令牌所属用户最近使用的组织(platform/user 的 lastOrganization,会话不在任何仓库里时用到)。找不到时不缓存,下次轮询重试
  • GitHub PR 通过本机的 gh 查询(使用 gh auth login 的登录态,需要 repo 权限),会在 PATH、/opt/homebrew/bin、/usr/local/bin 中查找;不需要云效令牌
  • docs 模块显示链接无需额外依赖;显示标题需要已登录的 lark-cli,会在 PATH、/opt/homebrew/bin、/usr/local/bin 中查找

网络与隐私

  • Codeup / AppStack / Flow:只调用 openapi-rdc.aliyuncs.com 上的只读接口。Codeup 部分包括仓库、MR 列表(按仓库,或按作者查本会话新建的)、MR 详情、对比、分支;AppStack 部分包括阶段列表、阶段执行列表、流水线运行;Flow 部分是流水线运行;另外会查一次令牌所属用户的 ID。插件不会触发、取消或推进任何发布。token 只放在请求头里。
  • GitHub:通过本机 gh 只读查询(一次 GraphQL 取 PR 信息,未关闭的 PR 另调一次 compare 取落后提交数),使用你自己的 gh 登录态。
  • 飞书:插件本身不发网络请求,标题查询通过本机的 lark-cli 完成,使用你自己的登录态。
  • 不上报任何数据。每个会话的状态(涉及的仓库目录、钉选的 MR / PR、文档、发布、隐藏项、折叠)按会话 ID 保存在本机:插件自己的 store 文件,位于 Claude Code 配置目录下。会话恢复时(Desktop 升级重启、闲置后进程被回收、--resume)据此还原,MR 状态和用量会重新拉取。Desktop 里回退或编辑历史消息会以新会话 ID 分叉继续,插件按会话首条消息的 uuid 找到原会话的存档并合并过来。最多保留最近 30 个会话,超过 30 天的自动清理;在 Desktop 里归档的会话,其存档会在下一个会话启动时删除(读取 Desktop 本地的会话元数据判断是否已归档)。

排错

现象原因与处理
看不到 HUD当前会话启动于安装之前,新开一个会话;再用 /hud 确认模块已开启
每行出现两遍旧的 usage-hud / codeup-mr 没卸载,见快速开始第 2 步
GitHub 仓库显示「未找到 gh CLI」或报错安装 gh 并执行 gh auth login;私有仓库需要 repo 权限
显示「未找到云效 token」按依赖配置 token
没有 MR 行仓库 origin 不在 Codeup 上;当前分支没有 MR;或该 MR 不在仓库最新的 100 条之内。在别处创建的 MR,可以在消息里贴它的链接
文档只显示「文档 xxxxxxxx…」未安装或未登录 lark-cli(终端执行 lark-cli auth login),或无该文档权限;临时失败会自动重试,也可执行 /doclinks 立即重试
发布行一直是「等待运行开始」该阶段还没有新的执行(触发被排队或失败),点「检查」重查;或触发时间与执行开始时间相差超过 2 分钟
MR / 发布下方出现一行报错格式为「GitHub PR / Codeup MR · 仓库 · 原因」,鼠标悬停看原始报错。网络超时、限流、服务端 5xx 属临时失败:保留上次结果,下次轮询自动重试;「无权限」「未登录或凭证失效」「不存在或无权限」需检查 token / gh auth status
发布行显示「查询失败」令牌没有 AppStack 读权限,或组织 ID 不对,见依赖;临时网络失败时继续显示上次读到的进度
用量行不显示还没有新的限额读数,发一条消息后就会出现
会话恢复后 HUD 内容为空0.8.0 起会话状态会存到本机并在恢复时还原,0.9.1 起回退 / 编辑消息产生的分叉会话也能继承;0.8.0 之前产生的会话没有存档,无法找回

插件内部出错时会记录一行 session-hud <模块>: <原因>,可在 claude --debug 的日志里查到。

已知限制

  • Codeup 的 MR 列表接口不支持按源分支过滤,因此每个仓库只扫描最新的 100 条 MR
  • 不显示 Codeup 提交上的流水线(CI)状态:只有流水线把状态回写到提交上时,接口才会提供
  • Desktop 中 MR 图标是 Svg,宿主不允许把 Svg 放进链接,所以要点编号跳转
  • 发布模块只跟踪 AppStack 研发阶段;不经 AppStack 的纯 Flow 流水线发布暂不显示
  • 发布模块只读:人工卡点需要到 AppStack 页面推进
  • 旧版 codeup-mr 0.2 / 0.3 写进会话标题的 MR 徽标,本插件不再清理

开发

.claude-plugin/plugin.json   清单、userConfig(全部配置项)
types/index.d.ts             $.state 契约
hooks/register.tsx           入口:唯一调用 $ 的文件(引擎要求),事件分发、数据拉取、绘制组装
hooks/settings.ts            配置解析与默认值
hooks/hud.tsx                折叠条与 /hud 命令解析
hooks/ui.tsx                 共用列宽、定宽截断单元格(悬停显示全文)、原地展开
hooks/text.ts                按显示宽度截断(中文按 2 格计)
hooks/usage/                 用量格式化与绘制
hooks/mr/                    Codeup 解析、检查项、列宽自适应、绘制
hooks/docs/                  链接识别、去重合并、lark-cli 标题查询、绘制
hooks/deploy/                发布触发识别、执行匹配、运行状态映射、绘制
claude plugin validate .
claude plugin test .

本地调试用 claude --plugin-dir <本仓库目录> 启动,或把目录加入 CLAUDE_CODE_PLUGIN_DIRS,保存后自动热重载。测试数据全部为虚构:不要在测试、示例或提交信息里写入真实的组织 ID、仓库、应用、文档链接或 token。

发布流程:

  1. 在 .claude-plugin/plugin.json 中提升 version
  2. 推送到 main
  3. 使用方执行快速开始中「更新」的两条命令

更新记录

  • 0.10.4:文档标题查询遇到「文档不存在」(已删除、链接写错)不再重试,也不再打日志;其他失败的日志改为显示 lark-cli 给出的原因,而不是 JSON 末尾的 }
  • 0.10.3:修复文档重复显示:docx 创建后移入知识库、再以 wiki 链接被提到时出现两行;查标题时解析 wiki 节点的真实文档 token,同一文档合并为一行(已有的 wiki 行会补查一次)
  • 0.10.2:修复 0.10.0 把旧版本钉选的、本会话实际创建的 MR 一并隐藏;被提到的 MR 改为「作者是自己且创建于本会话开始之后」才显示(协作会话为本 feature 建的 MR 也能显示,排查时引用的别人的 MR 不显示);修复同一 MR 从「提及」升级为「创建 / 跟踪」不生效
  • 0.10.1:命令重名时自动改用 session- 前缀(/hud 与 oh-my-claudecode 的 hud skill 重名时为 /session-hud),不再每次启动打出「refused」报错
  • 0.10.0:MR / PR 只显示本会话开发的分支、本会话创建的、以及 /mr <链接> 手动跟踪的;消息 / 回答 / 命令输出里只是被提到的链接不再自动显示(0.10.2 调整为按作者和时间过滤),排查时只读进入的仓库也不再算入。/docs 改名 /doclinks(Claude Code 2.1.304 自带 /docs,同名注册会被拒绝并导致启动钩子被跳过);命令改为逐个注册,一个失败不影响其余
  • 0.9.2:文档「创建 / 提及」更准:会话启动时在后台从 transcript 补回丢失的「创建」标记(重启或分叉后被误标为「提及」的文档);合并分叉存档时,任一方是「创建」就保留「创建」
  • 0.9.1:修复 Desktop 中回退 / 编辑历史消息后 HUD 内容丢失:这类操作以新会话 ID 分叉继续,存档改为同时记录会话首条消息 uuid(分叉后不变),恢复时合并同一谱系的存档并迁移到新 ID
  • 0.9.0:用量模块新增上下文窗口用量(上下文 ███░░░ 42% 84k/200k),新增配置 usageContext
  • 0.8.1:Desktop 中已归档会话的 HUD 存档在下一个会话启动时自动删除,避免 store 膨胀
  • 0.8.0:修复会话恢复后 HUD 内容被清空(Desktop 升级、长时间闲置后进程被回收):会话状态按会话 ID 存入插件 store,每轮结束、会话结束及每 30 秒检查一次,有变化才写入;新进程恢复会话时先还原再刷新,热重载不受影响
  • 0.7.6:报错显示优化:MR 报错按来源标「GitHub PR / Codeup MR」,原因归类为网络超时、限流、无权限等简短中文,悬停看原始报错;临时失败保留上次的 MR 行和发布进度,下次轮询自动重试
  • 0.7.5:发布行链接优先用 AppStack 阶段页:只有 Flow run: 链接的发布,按流水线 ID 反查应用的发布阶段(每个应用只查一次)
  • 0.7.4:MR(仓库、每分支 MR、提到的 MR / PR)、文档、发布的保留条数统一提到 100;超出 *MaxRows 的照常折叠,点 ⌄ 展开另 N … 查看
  • 0.7.3:修复会话不在 Codeup 仓库里时发布行「查询失败:未找到云效组织 ID」(新增令牌所属用户的组织兜底,查不到不再永久缓存);每会话保留的发布从 10 次增到 30 次;同一 Flow 流水线不再重复成行;变量循环发布的行用流水线名命名
  • 0.7.2:发布的「检查」展开改为每个阶段一行(高度从逐任务一行缩到阶段数),MR 与发布的展开列表末尾都加 ⌃ 收起,即使提示栏滚动、行首按钮不可见也能折叠
  • 0.7.1:输入框上方出现卡片时,HUD 不再整体隐藏,改为在卡片上方显示一行摘要
  • 0.7.0:文档模块支持 Claude Artifacts:本会话发布的页面(创建)、读取或提到的页面(提及),标题取发布文件的 <title>;新增 docsArtifacts 开关
  • 0.6.0:MR 模块支持 GitHub PR:origin 在 GitHub 的仓库显示当前分支的 PR,消息、回答和命令输出里的 PR 链接(含 gh pr create 的输出)会被固定显示;检查项与 Codeup 一致,另含 CI 汇总;通过本机 gh 查询
  • 0.5.0:发布识别支持一条命令多次 deploy.sh、输出只剩 Flow run: 行(直接查 Flow 运行状态),并排除 --dry-run;MR 模块显示本会话创建的 MR(按作者与创建时间查找,不依赖目录和分支)和消息、回答、命令输出里出现的 MR 链接
  • 0.4.3:README 重写(目录、快速开始、虚构示例数据),测试数据脱敏
  • 0.4.2:超出最多行数时改为原地「⌄ 展开另 N … / ⌃ 收起」按钮(MR、文档、发布通用);文档标题查询遇到超时等临时失败会重试
  • 0.4.1:发布模块支持跟踪已有发布:在消息里贴 AppStack 阶段链接或执行 /deploys <链接>
  • 0.4.0:新增云效发布模块:AppStack 阶段链接、运行到哪个任务、未结束时自动轮询、「检查」展开全部任务并立即刷新;新增 /deploys
  • 0.3.0:「检查」新增合入状态、落后目标分支的提交数、源分支是否已删除;点「检查」时立即重新拉取
  • 0.2.0:去掉行尾的「打开」链接,MR 通过编号跳转、文档通过标题跳转;文档行与 MR 行列对齐
  • 0.1.0:合并 usage-hud 与 codeup-mr,新增飞书文档模块、定宽单行布局、模块独立启停、细粒度配置与折叠

许可证

MIT

Source 21 files
hooks/register.tsx 930 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { DeployRun, DocLink, DocOrigin, MrView, RepoView, SessionView, Usage } from '../types'
5import { addRun, envOfStage, findStageTargets, isSettled, isUnnamed, pickExecution, pipelineLabel, runOf, stageOfPipeline, stageUrl, triggersOf } from './deploy/parse'
6import type { ApiPipelineRun } from './deploy/parse'
7import { deployList, deploySection } from './deploy/view'
8import { artifactsOfCall, findAllDocs, findDocs, foldSameDoc, htmlTitle, isCreation, isLarkTool, mergeDocs } from './docs/links'
9import type { FoundDoc } from './docs/links'
10import { CREATION_LINES_RE, createdInTranscript } from './docs/backfill'
11import { LARK_CLI, inspectArgv, isMissingProgram, lookupOf } from './docs/lookup'
12import type { Lookup } from './docs/lookup'
13import { docList, docsLayout, docsSection, visibleDocs } from './docs/view'
14import { band, parseHud, status } from './hud'
15import { API_BASE, addPins, createdSince, isMention, isOwnSince, diffStat, exportFromProfile, findMrLinks, isMrCreation, isOpen, parseRemote, pickMrs, repoLabel, stateOf, toView, tokenFromProfile } from './mr/codeup'
16import type { ApiChangeRequest, ApiCompare, ApiDetail, MrPin, Repo } from './mr/codeup'
17import { mrKey } from './mr/session'
18import { compareRange, findPrLinks, parseGithubRemote, pickPrs, prQuery, prView, prsOf } from './mr/github'
19import type { ApiPr, GhRepo } from './mr/github'
20import { dirsOf, keepLastMrs, mrList, rememberDirs } from './mr/session'
21import { mrLayout, mrSection } from './mr/view'
22import { SNAPSHOT_PREFIX, archivedIdsOf, isEmpty, lineageOf, snapshotOf, staleKeys } from './persist'
23import type { Saved } from './persist'
24import { LIST_MAX, MODULE_IDS, PLUGIN, settingsOf } from './settings'
25import type { Settings } from './settings'
26import { isBlank } from './tree'
27import type { Fold, Section } from './ui'
28import { usageSection } from './usage/view'
29
30const usage = atom({ plugin: 'session-hud', key: 'usage' } as const, null)
31const mrView = atom({ plugin: 'session-hud', key: 'mrView' } as const, null)
32const mrDirs = atom({ plugin: 'session-hud', key: 'mrDirs' } as const, [])
33const mrExpanded = atom({ plugin: 'session-hud', key: 'mrExpanded' } as const, null)
34const mrDismissed = atom({ plugin: 'session-hud', key: 'mrDismissed' } as const, [])
35const mrPinned = atom({ plugin: 'session-hud', key: 'mrPinned' } as const, [])
36const docs = atom({ plugin: 'session-hud', key: 'docs' } as const, [])
37const docsDismissed = atom({ plugin: 'session-hud', key: 'docsDismissed' } as const, [])
38const collapsed = atom({ plugin: 'session-hud', key: 'collapsed' } as const, null)
39const deploys = atom({ plugin: 'session-hud', key: 'deploys' } as const, [])
40const deployExpanded = atom({ plugin: 'session-hud', key: 'deployExpanded' } as const, null)
41const deployDismissed = atom({ plugin: 'session-hud', key: 'deployDismissed' } as const, [])
42const expandedLists = atom({ plugin: 'session-hud', key: 'expandedLists' } as const, [])
43
44const PAGE_SIZE = 100
45/** An author's newest MRs read after a create call: more than one call opens. */
46const AUTHOR_PAGE = 10
47/** How much earlier than the create call an MR may be stamped and still be its (clock skew). */
48const CREATE_SLACK_MS = 60_000
49const HTTP_NOT_FOUND = 404
50const GIT_TIMEOUT_MS = 5_000
51const LARK_TIMEOUT_MS = 8_000
52/** Exit status of a command that was not found. */
53const NOT_FOUND = 127
54/** Title lookups per turn: each is one lark-cli call. */
55const LOOKUPS_PER_TURN = 5
56/** Retryable lookup failures per document before its title is given up. */
57const MAX_LOOKUP_TRIES = 3
58const PROFILES = ['.zshrc', '.zshenv', '.zprofile', '.bashrc', '.profile']
59/** The Desktop app does not inherit the shell's PATH: gh is also looked for in the usual install folders. */
60const GH_CLI = ['gh', '/opt/homebrew/bin/gh', '/usr/local/bin/gh'] as const
61const GH_TIMEOUT_MS = 15_000
62const NO_GH = '未找到 gh CLI(安装后执行 gh auth login)'
63const NO_TOKEN = '未找到云效 token(设置 ALIBABA_CLOUD_YUNXIAO_ACCESS_TOKEN)'
64const NO_ORG = '未找到云效组织 ID(设置 ALIBABA_CLOUD_YUNXIAO_ORGANIZATION_ID)'
65const ORG_VAR = 'ALIBABA_CLOUD_YUNXIAO_ORGANIZATION_ID'
66const APPSTACK_BASE = 'https://openapi-rdc.aliyuncs.com/oapi/v1/appstack/organizations'
67const FLOW_BASE = 'https://openapi-rdc.aliyuncs.com/oapi/v1/flow/organizations'
68const PLATFORM_USER = 'https://openapi-rdc.aliyuncs.com/oapi/v1/platform/user'
69/** A just-triggered stage needs a moment before its execution is listed. */
70const DEPLOY_FIRST_CHECK_MS = 5_000
71
72const listOf = <T,>(v: unknown): T[] => (Array.isArray(v) ? (v as T[]) : [])
73
74// ponytail: module-level caches; reset on reload, which is fine
75const repoIds = new Map<string, number>()
76const roots = new Map<string, string>()
77/** +/- per `${repo}!${id}@${head sha}`: the diff is fetched again only when the branch moves. */
78const stats = new Map<string, { additions: number; deletions: number }>()
79let tokenCache: { value: string | undefined } | null = null
80/** Kept once found; until then each call looks again, so a session that starts outside a Codeup repo still finds it. */
81let orgCache: string | undefined
82/** The token owner, read once: their id (to find the MRs they create) and the org they last used. */
83let platformUser: { id?: string; lastOrganization?: string } | undefined
84/** Flow pipeline names by id, read once: they name a run whose call did not (a loop over `$app`). */
85const pipelineNames = new Map<string, string>()
86/** Each app's `releaseWorkflows` answer, read once: it maps a Flow pipeline to its AppStack release stage. */
87const appWorkflows = new Map<string, unknown>()
88/** The gh that ran; null once none was found. */
89let ghCli: string | null | undefined
90/** Release-stage names per `${app}/${workflowSn}`, read once: they name a tracked run's env. */
91const stageNames = new Map<string, Map<string, string>>()
92/** Run keys being fetched, so a press during a poll does not fetch twice. */
93const deployFetching = new Set<string>()
94/** The lark-cli that ran; null once none was found. */
95let larkCli: string | null | undefined
96/** Tokens whose title lookup is running, so overlapping turns (subagents, fast prompts) never look one up twice. */
97const lookingUp = new Set<string>()
98
99/** Runs one module's step: a failure neither stops the other modules nor the event, and is logged. */
100async function guard($: EngineInterface, id: string, step: () => Promise<unknown>): Promise<void> {
101  try {
102    await step()
103  } catch (err) {
104    $.ui.log(`${PLUGIN} ${id}: ${err instanceof Error ? err.message : String(err)}`)
105  }
106}
107
108// ── usage ───────────────────────────────────────────────────────────────────────────────────────────────────────────
109
110async function refreshUsage($: EngineInterface) {
111  const u = await $.session.usage()
112  // A host without a live window (a stub, an older engine) sends none: the context meter is then left out.
113  const c = u.context as Usage['context'] | undefined
114  const context = c?.window ? { window: c.window, ...(c.tokens === undefined ? {} : { tokens: c.tokens }), ...(c.percent === undefined ? {} : { percent: c.percent }) } : undefined
115  const next: Usage = { rateLimits: u.rateLimits, ...(context ? { context } : {}) }
116  await update($, usage, () => next)
117}
118
119// ── Codeup MR ───────────────────────────────────────────────────────────────────────────────────────────────────────
120
121async function git($: EngineInterface, dir: string, ...args: string[]): Promise<string> {
122  const { exitCode, stdout } = await $.process.run(['git', '-C', dir, ...args], { timeoutMs: GIT_TIMEOUT_MS }).catch(() => ({ exitCode: 1, stdout: '' }))
123  return exitCode === 0 ? stdout.trim() : ''
124}
125
126async function resolveToken($: EngineInterface, configured: string | undefined): Promise<string | undefined> {
127  if (configured) return configured
128  const fromEnv = await $.env.get('ALIBABA_CLOUD_YUNXIAO_ACCESS_TOKEN')
129  if (fromEnv) return fromEnv
130  const home = await $.env.get('HOME')
131  for (const name of PROFILES) {
132    const token = tokenFromProfile(await $.fs.read(`${home}/${name}`).catch(() => ''))
133    if (token) return token
134  }
135  return undefined
136}
137
138async function getJson<T>($: EngineInterface, token: string, url: string, what: string): Promise<T> {
139  const res = await $.http.fetch(url, { headers: { 'x-yunxiao-token': token } })
140  if (!res.ok) throw new Error(`${what} ${res.status}: ${res.text.slice(0, 120)}`)
141  return JSON.parse(res.text) as T
142}
143
144const api = <T,>($: EngineInterface, token: string, path: string): Promise<T> => getJson<T>($, token, `${API_BASE}/${path}`, 'Codeup')
145
146async function cachedToken($: EngineInterface, settings: Settings): Promise<string | undefined> {
147  tokenCache ??= { value: await resolveToken($, settings.token) }
148  return tokenCache.value
149}
150
151/** Whether the branch still exists on Codeup: 404 is deleted; any other failure is unknown, so no check is shown. */
152async function isBranchAlive($: EngineInterface, token: string, base: string, branch: string): Promise<boolean | undefined> {
153  const res = await $.http.fetch(`${API_BASE}/${base}/branches/${encodeURIComponent(branch)}`, { headers: { 'x-yunxiao-token': token } }).catch(() => null)
154  if (!res) return undefined
155  return res.ok ? true : res.status === HTTP_NOT_FOUND ? false : undefined
156}
157
158async function repoIdOf($: EngineInterface, token: string, repo: Repo): Promise<number> {
159  const known = repoIds.get(repo.path)
160  if (known !== undefined) return known
161  const id = (await api<{ id: number }>($, token, `${repo.org}/repositories/${encodeURIComponent(repo.path)}`)).id
162  repoIds.set(repo.path, id)
163  return id
164}
165
166/** A repo's newest MRs. ponytail: Codeup ignores sourceBranch filtering, so scan the newest 100; page further if old branches matter */
167async function repoMrs($: EngineInterface, token: string, repo: Repo): Promise<{ base: string; list: ApiChangeRequest[] }> {
168  const repoId = await repoIdOf($, token, repo)
169  const list = await api<ApiChangeRequest[]>($, token, `${repo.org}/changeRequests?projectIds=${repoId}&state=all&perPage=${PAGE_SIZE}`)
170  return { base: `${repo.org}/repositories/${repoId}`, list }
171}
172
173/**
174 * Rows for `crs`: detail checks, +/- stats (fetched again only when `versionOf` changes) and whether each source branch
175 * still exists (one lookup per branch).
176 */
177async function mrViews($: EngineInterface, token: string, repo: Repo, base: string, crs: readonly ApiChangeRequest[], versionOf: (cr: ApiChangeRequest) => string): Promise<MrView[]> {
178  const branches = [...new Set(crs.map(cr => cr.sourceBranch))]
179  const alive = new Map(await Promise.all(branches.map(async b => [b, await isBranchAlive($, token, base, b)] as const)))
180  // ponytail: the stats key ignores the target branch moving; add its sha if merged-in target commits must show
181  return Promise.all(crs.map(async cr => {
182    const key = `${repo.path}!${cr.localId}@${versionOf(cr)}`
183    const [detail, stat] = await Promise.all([
184      api<ApiDetail>($, token, `${base}/changeRequests/${cr.localId}`).catch(() => undefined),
185      !isOpen(cr) ? undefined : stats.get(key) ?? api<ApiCompare>($, token, `${base}/compares?from=${encodeURIComponent(cr.targetBranch)}&to=${encodeURIComponent(cr.sourceBranch)}`)
186        .then(diffStat)
187        .then(s => (stats.set(key, s), s))
188        .catch(() => undefined),
189    ])
190    return toView(cr, repo.path, detail, stat, alive.get(cr.sourceBranch))
191  }))
192}
193
194async function fetchMrs($: EngineInterface, token: string, repo: Repo, branch: string, head: string): Promise<MrView[]> {
195  const { base, list } = await repoMrs($, token, repo)
196  return mrViews($, token, repo, base, pickMrs(list, branch), () => head)
197}
198
199/**
200 * `gh <args>` parsed as JSON, through gh's own login. gh exits non-zero when a GraphQL answer carries errors next to
201 * its data (a pinned number that is no PR), so stdout is read whatever the exit; only no JSON at all is a failure.
202 */
203async function ghJson($: EngineInterface, args: readonly string[]): Promise<unknown> {
204  const candidates = ghCli === undefined ? GH_CLI : ghCli ? [ghCli] : []
205  for (const bin of candidates) {
206    const run = await $.process.run([bin, ...args], { timeoutMs: GH_TIMEOUT_MS }).catch((err: unknown) => (isMissingProgram(err) ? null : Promise.reject(err)))
207    if (run === null || run.exitCode === NOT_FOUND) continue
208    ghCli = bin
209    try {
210      return JSON.parse(run.stdout)
211    } catch {
212      throw new Error((run.stderr || run.stdout).trim().split('\n').slice(-1)[0]?.slice(0, 160) || `gh exit ${run.exitCode}`)
213    }
214  }
215  if (candidates.length) ghCli = null
216  throw new Error(NO_GH)
217}
218
219/** The PRs of `branch` (picked as for Codeup) and the PRs pinned by number, as rows, in one GraphQL call. */
220async function githubPrs($: EngineInterface, repo: GhRepo, branch: string | undefined, numbers: readonly number[], keep: (pr: ApiPr, viewer?: string) => boolean = () => true): Promise<MrView[]> {
221  const { branch: ofBranch, pinned, viewer } = prsOf(await ghJson($, ['api', 'graphql', '-f', `query=${prQuery(repo, branch, numbers)}`]))
222  const prs = [...pickPrs(ofBranch), ...pinned.filter(p => !ofBranch.some(b => b.number === p.number) && keep(p, viewer))]
223  return Promise.all(prs.map(async (pr: ApiPr) => {
224    const behind = pr.state === 'OPEN'
225      ? await ghJson($, ['api', `repos/${repo.owner}/${repo.name}/compare/${compareRange(pr)}`, '--jq', '{behind_by}'])
226        .then(c => (c as { behind_by?: number }).behind_by)
227        .catch(() => undefined)
228      : undefined
229    return prView(pr, repo, behind)
230  }))
231}
232
233/** Rows for the pinned MRs not already shown, one group per repo; a repo that fails says so in its group. */
234async function pinnedViews($: EngineInterface, token: string | undefined, pins: readonly MrPin[], shown: ReadonlySet<string>): Promise<RepoView[]> {
235  // A mention shows only when it is the user's own MR opened since the session began (unknown start: none shows).
236  const since = await $.session.usage().then(u => u.startedAt - CREATE_SLACK_MS, () => Number.POSITIVE_INFINITY)
237  const mentioned = new Set(pins.filter(isMention).map(p => `${p.forge ?? 'codeup'}:${p.repoPath}!${p.localId}`))
238  const ghPins = pins.filter(p => p.forge === 'github' && !shown.has(`${p.repoPath}#${p.localId}`))
239  const ghByRepo = new Map<string, number[]>()
240  for (const p of ghPins) ghByRepo.set(p.repoPath, [...(ghByRepo.get(p.repoPath) ?? []), p.localId])
241  const github = await Promise.all([...ghByRepo].map(async ([path, ids]): Promise<RepoView> => {
242    const [owner = '', name = ''] = path.split('/')
243    const keep = (pr: ApiPr, viewer?: string) => !mentioned.has(`github:${path}!${pr.number}`) || isOwnSince(pr.author?.login, viewer, pr.createdAt, since)
244    return githubPrs($, { owner, name }, undefined, ids, keep)
245      .then((mrs): RepoView => ({ root: '', repo: path, branch: '', mrs, forge: 'github' }))
246      .catch((err: Error): RepoView => ({ root: '', repo: path, branch: '', mrs: [], error: err.message, forge: 'github' }))
247  }))
248  if (!token) return github
249  const me = await userOf($, token).then(u => u.id, () => undefined)
250  const byRepo = new Map<string, number[]>()
251  for (const p of pins) if (p.forge !== 'github' && !shown.has(`${repoLabel(p.repoPath)}!${p.localId}`)) byRepo.set(p.repoPath, [...(byRepo.get(p.repoPath) ?? []), p.localId])
252  const codeup = await Promise.all([...byRepo].map(async ([path, ids]): Promise<RepoView> => {
253    const repo: Repo = { org: path.split('/')[0] ?? '', path }
254    const name = repoLabel(path)
255    try {
256      const { base, list } = await repoMrs($, token, repo)
257      const crs = list.filter(cr => ids.includes(cr.localId) && (!mentioned.has(`codeup:${path}!${cr.localId}`) || isOwnSince(cr.author?.userId, me, cr.createdAt, since)))
258      // A pinned MR has no checkout to read a head from: its last update stands in, so new pushes refetch the stats.
259      return { root: '', repo: name, branch: '', mrs: await mrViews($, token, repo, base, crs, cr => cr.updatedAt ?? '') }
260    } catch (err) {
261      return { root: '', repo: name, branch: '', mrs: [], error: err instanceof Error ? err.message : String(err) }
262    }
263  }))
264  return [...github, ...codeup]
265}
266
267/** Git roots of the session's cwd and of every directory it touched, cwd first, deduped. */
268async function sessionRoots($: EngineInterface): Promise<string[]> {
269  const touched = listOf<string>(await read($, mrDirs))
270  const candidates = [await $.session.cwd(), ...[...touched].reverse()]
271  const found: string[] = []
272  for (const dir of candidates) {
273    if (!roots.has(dir)) roots.set(dir, await git($, dir, 'rev-parse', '--show-toplevel'))
274    const root = roots.get(dir)
275    if (root && !found.includes(root)) found.push(root)
276    if (found.length >= LIST_MAX) break
277  }
278  return found
279}
280
281async function repoView($: EngineInterface, token: string | undefined, root: string): Promise<RepoView | null> {
282  const [remote, branch, upstream, local] = await Promise.all([
283    git($, root, 'remote', 'get-url', 'origin'),
284    git($, root, 'branch', '--show-current'),
285    git($, root, 'rev-parse', '@{u}'),
286    git($, root, 'rev-parse', 'HEAD'),
287  ])
288  const gh = parseGithubRemote(remote)
289  if (gh && branch) {
290    const label = `${gh.owner}/${gh.name}`
291    return githubPrs($, gh, branch, [])
292      .then((mrs): RepoView => ({ root, repo: label, branch, mrs, forge: 'github' }))
293      .catch((err: Error): RepoView => ({ root, repo: label, branch, mrs: [], error: err.message, forge: 'github' }))
294  }
295  if (!token) return null
296  const repo = parseRemote(remote)
297  if (!repo || !branch) return null
298  const name = repoLabel(repo.path)
299  return fetchMrs($, token, repo, branch, upstream || local)
300    .then(mrs => ({ root, repo: name, branch, mrs }))
301    .catch((err: Error) => ({ root, repo: name, branch, mrs: [], error: err.message }))
302}
303
304/** How many of `roots` are Codeup checkouts: the ones a missing Yunxiao token leaves out. */
305async function codeupRootCount($: EngineInterface, roots: readonly string[]): Promise<number> {
306  const remotes = await Promise.all(roots.map(root => git($, root, 'remote', 'get-url', 'origin')))
307  return remotes.filter(r => parseRemote(r) !== null).length
308}
309
310async function refreshMrs($: EngineInterface, settings: Settings) {
311  const found = await sessionRoots($)
312  const pins = listOf<MrPin>(await read($, mrPinned))
313  if (!found.length && !pins.length) {
314    await update($, mrView, () => null)
315    return
316  }
317  // GitHub repos need no Yunxiao token (gh has its own login); Codeup ones are left out without it, and say so.
318  const token = await cachedToken($, settings)
319  const repos = (await Promise.all(found.map(root => repoView($, token, root)))).filter((r): r is RepoView => r !== null)
320  const shown = new Set(repos.flatMap(r => r.mrs.map(mrKey)))
321  const pinned = pins.length ? await pinnedViews($, token, pins, shown) : []
322  const all = keepLastMrs((await read($, mrView))?.repos ?? [], [...repos, ...pinned])
323  const needsToken = !token && (pins.some(p => p.forge !== 'github') || (await codeupRootCount($, found)) > 0)
324  await update($, mrView, (): SessionView => (needsToken ? { repos: all, error: NO_TOKEN } : { repos: all }))
325}
326
327async function pinMrs($: EngineInterface, settings: Settings, added: readonly MrPin[]) {
328  if (!added.length) return
329  const known = listOf<MrPin>(await read($, mrPinned))
330  const next = addPins(known, added)
331  // A new pin, or one whose reason grew (a mention now made / asked for): anything else changes nothing.
332  if (JSON.stringify(next) === JSON.stringify(known)) return
333  await update($, mrPinned, () => next)
334  await refreshMrs($, settings)
335}
336
337/**
338 * The MRs a create call just opened: the token owner's newest MRs created since the call started. Read by author and
339 * time, not from the call's output, so it works however the call printed (or hid) what it made.
340 */
341/** Every MR / PR linked in `text`, pinned as a mention. */
342const mentionsOf = (text: string): MrPin[] => [...findMrLinks(text), ...findPrLinks(text)].map(p => ({ ...p, via: 'mentioned' as const }))
343
344/** A create call that opens a GitHub PR: its link is in its output, and there is no Codeup author list to read. */
345const isGithubOnly = (input: Readonly<Record<string, unknown>>): boolean => typeof input.command === 'string' && /\bgh\s+pr\s+create\b|\/pulls\b/.test(input.command)
346
347async function pinCreatedMrs($: EngineInterface, settings: Settings, since: number) {
348  const token = await cachedToken($, settings)
349  const org = token ? await cachedOrg($, token) : undefined
350  if (!token || !org) return
351  const userId = (await userOf($, token)).id
352  if (!userId) return
353  const list = await api<ApiChangeRequest[]>($, token, `${org}/changeRequests?authorIds=${userId}&state=all&perPage=${AUTHOR_PAGE}&orderBy=created_at&sort=desc`)
354  await pinMrs($, settings, createdSince(list, since - CREATE_SLACK_MS).map(p => ({ ...p, via: 'created' as const })))
355}
356
357async function rememberMrDirs($: EngineInterface, tool: string, input: Readonly<Record<string, unknown>>) {
358  const added = dirsOf(tool, input, (await $.env.get('HOME')) ?? '')
359  if (added.length) await update($, mrDirs, known => rememberDirs(listOf<string>(known), added))
360}
361
362// ── Feishu docs ─────────────────────────────────────────────────────────────────────────────────────────────────────
363
364async function rememberDocs($: EngineInterface, found: readonly FoundDoc[], origin: DocOrigin, settings: Settings) {
365  if (!found.length || (origin === 'mentioned' && !settings.docsMentioned)) return
366  const now = await $.clock.now()
367  await update($, docs, list => mergeDocs(listOf<DocLink>(list), found, origin, now))
368}
369
370/** The `<title>` of the page an Artifact publish sent, read from its file; undefined when unreadable or untitled. */
371async function publishedTitle($: EngineInterface, tool: string, input: Readonly<Record<string, unknown>>): Promise<string | undefined> {
372  const path = input.file_path
373  if (tool !== 'Artifact' || typeof path !== 'string' || !/\.html?$/i.test(path)) return undefined
374  return htmlTitle(await $.fs.read(path).catch(() => ''))
375}
376
377/** The Claude Artifacts a call published (created) or worked on (mentioned). */
378async function rememberToolArtifacts($: EngineInterface, tool: string, input: Readonly<Record<string, unknown>>, output: string, settings: Settings) {
379  if (!settings.docsArtifacts) return
380  const { made, mentioned } = artifactsOfCall(tool, { ...input }, output, await publishedTitle($, tool, input))
381  await rememberDocs($, mentioned, 'mentioned', settings)
382  await rememberDocs($, made, 'created', settings)
383}
384
385/** A Lark call's input names the docs it works on (mentions); only a create call's output counts, as what it made. */
386async function rememberToolDocs($: EngineInterface, tool: string, input: Readonly<Record<string, unknown>>, output: string, settings: Settings) {
387  await rememberToolArtifacts($, tool, input, output, settings)
388  if (!isLarkTool(tool, input)) return
389  const mentioned = findDocs(JSON.stringify(input))
390  const asked = new Set(mentioned.map(d => d.token))
391  const made = isCreation(tool, input) ? findDocs(output).filter(d => !asked.has(d.token)) : []
392  // Mentions first, so what the call made lands newest: a +copy lists the copy above its source.
393  await rememberDocs($, mentioned, 'mentioned', settings)
394  await rememberDocs($, made, 'created', settings)
395}
396
397/** Prints the session transcript's lines that matter for documents (pattern `$3`); nothing without a transcript. */
398const TRANSCRIPT_GREP = `f=$(ls "$1"/projects/*/"$2".jsonl 2>/dev/null | head -n 1); [ -n "$f" ] && grep -E -i -- "$3" "$f"; exit 0`
399const BACKFILL_TIMEOUT_MS = 20_000
400
401/**
402 * Marks 创建 the documents this session's own calls made, from its transcript, where a lost mark left them 提及 (a
403 * restart before the mark was saved, a fork that met them again). Once per process, off the session's path.
404 */
405async function backfillCreated($: EngineInterface) {
406  if (!listOf<DocLink>(await read($, docs)).some(d => d.origin === 'mentioned')) return
407  const dir = (await $.env.get('CLAUDE_CONFIG_DIR')) || `${(await $.env.get('HOME')) ?? ''}/.claude`
408  const run = await $.process.run(['/bin/sh', '-c', TRANSCRIPT_GREP, 'sh', dir, await $.session.id(), CREATION_LINES_RE], { timeoutMs: BACKFILL_TIMEOUT_MS })
409  const made = createdInTranscript(run.stdout)
410  if (!made.size) return
411  await update($, docs, list => listOf<DocLink>(list).map(d => (d.origin === 'mentioned' && made.has(d.token) ? { ...d, origin: 'created' as const } : d)))
412}
413
414/**
415 * The document's title through lark-cli. Only a missing program moves on to the next install folder, and only when
416 * none of them exists are lookups given up for the session; a timeout or other failure is retried on a later turn.
417 */
418async function lookupTitle($: EngineInterface, url: string): Promise<Lookup> {
419  const candidates = larkCli === undefined ? LARK_CLI : larkCli ? [larkCli] : []
420  for (const bin of candidates) {
421    const run = await $.process.run(inspectArgv(bin, url), { timeoutMs: LARK_TIMEOUT_MS }).then(
422      r => (r.exitCode === NOT_FOUND ? null : r),
423      (err: unknown) => (isMissingProgram(err) ? null : { failed: err instanceof Error ? err.message : String(err) }),
424    )
425    if (run === null) continue
426    if (!('failed' in run)) larkCli = bin
427    return lookupOf(run)
428  }
429  if (candidates.length) larkCli = null
430  return { final: '未找到 lark-cli' }
431}
432
433/** Looks up the titles still missing, a few per turn; a document is retried a few times, then given up. */
434async function lookupTitles($: EngineInterface) {
435  const pending = listOf<DocLink>(await read($, docs))
436    // A wiki node is looked up until it is unwrapped, even with a title: that is how a moved doc's two links meet.
437    .filter(d => ((!d.title && !d.isLookedUp) || (d.kind === 'wiki' && !d.docToken)) && (d.lookupTries ?? 0) < MAX_LOOKUP_TRIES && !lookingUp.has(d.token))
438    .slice(0, LOOKUPS_PER_TURN)
439  if (!pending.length) return
440  pending.forEach(d => lookingUp.add(d.token))
441  const results = new Map(await Promise.all(pending.map(async d => [d.token, await lookupTitle($, d.url)] as const)))
442  pending.forEach(d => lookingUp.delete(d.token))
443  results.forEach((r, token) => {
444    if ('retry' in r) $.ui.log(`${PLUGIN} docs: 标题查询失败(将重试)${token.slice(0, 8)}…: ${r.retry}`)
445  })
446  await update($, docs, list => foldSameDoc(listOf<DocLink>(list).map(d => {
447    const r = results.get(d.token)
448    if (!r) return d
449    // A wiki node keeps its unwrapped token (its own when none came back, so it is not asked again).
450    const unwrapped = d.kind === 'wiki' ? { docToken: ('title' in r ? r.token : undefined) ?? d.token } : {}
451    if ('title' in r) return { ...d, title: r.title, isLookedUp: true, ...unwrapped }
452    if ('final' in r) return { ...d, isLookedUp: true, ...unwrapped }
453    return { ...d, lookupTries: (d.lookupTries ?? 0) + 1 }
454  })))
455}
456
457// ── Yunxiao deploys ─────────────────────────────────────────────────────────────────────────────────────────────
458
459async function userOf($: EngineInterface, token: string): Promise<{ id?: string; lastOrganization?: string }> {
460  platformUser ??= await getJson<{ id?: string; lastOrganization?: string }>($, token, PLATFORM_USER, 'Yunxiao')
461  return platformUser
462}
463
464async function cachedOrg($: EngineInterface, token: string): Promise<string | undefined> {
465  orgCache ??= await resolveOrg($, token)
466  return orgCache
467}
468
469/**
470 * The Yunxiao organization: $ALIBABA_CLOUD_YUNXIAO_ORGANIZATION_ID, its export line in a shell profile, the org of any
471 * Codeup repo the session works in, else the org the token's owner last used (a session outside any repo).
472 */
473async function resolveOrg($: EngineInterface, token: string): Promise<string | undefined> {
474  const fromEnv = await $.env.get('ALIBABA_CLOUD_YUNXIAO_ORGANIZATION_ID')
475  if (fromEnv) return fromEnv
476  const home = await $.env.get('HOME')
477  for (const name of PROFILES) {
478    const org = exportFromProfile(await $.fs.read(`${home}/${name}`).catch(() => ''), ORG_VAR)
479    if (org) return org
480  }
481  for (const root of await sessionRoots($)) {
482    const org = parseRemote(await git($, root, 'remote', 'get-url', 'origin'))?.org
483    if (org) return org
484  }
485  return (await userOf($, token).catch(() => undefined))?.lastOrganization || undefined
486}
487
488/** What the Flow pipeline's name says about an unnamed run: its app, stage and env. */
489async function pipelineOf($: EngineInterface, token: string, org: string, r: DeployRun): Promise<Partial<DeployRun>> {
490  const id = r.flowPipelineId
491  if (!id || !isUnnamed(r)) return {}
492  if (!pipelineNames.has(id)) {
493    const { name } = await getJson<{ name?: unknown }>($, token, `${FLOW_BASE}/${org}/pipelines/${id}`, 'Flow')
494    if (typeof name === 'string' && name) pipelineNames.set(id, name)
495  }
496  const name = pipelineNames.get(id)
497  if (!name) return {}
498  const label = pipelineLabel(name)
499  return { app: label.app, ...(r.stageName || !label.stageName ? {} : { stageName: label.stageName }), ...(r.env || !label.env ? {} : { env: label.env }) }
500}
501
502/** The AppStack release stage a Flow-only run belongs to, so its row links the stage page rather than the Flow run. */
503async function appStageOf($: EngineInterface, token: string, org: string, app: string, r: DeployRun): Promise<Partial<DeployRun>> {
504  const id = r.flowPipelineId
505  if (r.stageSn || !id || isUnnamed({ app, flowPipelineId: id })) return {}
506  if (!appWorkflows.has(app)) appWorkflows.set(app, await getJson<unknown>($, token, `${APPSTACK_BASE}/${org}/apps/${encodeURIComponent(app)}/releaseWorkflows`, 'AppStack'))
507  const stage = stageOfPipeline(appWorkflows.get(app), id)
508  if (!stage) return {}
509  return { workflowSn: stage.workflowSn, stageSn: stage.stageSn, url: stageUrl(app, stage.workflowSn, stage.stageSn), ...(r.stageName || !stage.stageName ? {} : { stageName: stage.stageName }) }
510}
511
512/** The stage's name and env, for a run whose trigger did not print them (a tracked link, a direct API call). */
513async function stageOf($: EngineInterface, token: string, org: string, r: DeployRun): Promise<Partial<DeployRun>> {
514  if (r.stageName || !r.stageSn) return {}
515  const key = `${r.app}/${r.workflowSn}`
516  if (!stageNames.has(key)) {
517    const briefs = await getJson<{ sn?: unknown; name?: unknown }[]>($, token, `${APPSTACK_BASE}/${org}/apps/${encodeURIComponent(r.app)}/releaseWorkflow/${r.workflowSn}/releaseStageBriefs`, 'AppStack')
518    stageNames.set(key, new Map((Array.isArray(briefs) ? briefs : []).flatMap(b => (typeof b.sn === 'string' && typeof b.name === 'string' ? [[b.sn, b.name] as const] : []))))
519  }
520  const name = stageNames.get(key)?.get(r.stageSn)
521  return name ? { stageName: name, ...(r.env ? {} : { env: envOfStage(name) }) } : {}
522}
523
524/**
525 * The run's stages' jobs as Yunxiao has them now. A run whose Flow run is known is read from it directly; otherwise its
526 * stage execution is found once (the latest that started after the trigger) and pinned.
527 */
528async function fetchRun($: EngineInterface, token: string, org: string, r: DeployRun): Promise<Partial<DeployRun>> {
529  if (r.flowPipelineId && r.flowRunId) {
530    const named = await pipelineOf($, token, org, r).catch((): Partial<DeployRun> => ({}))
531    const appStage = await appStageOf($, token, org, named.app ?? r.app, r).catch(() => ({}))
532    const stage = { ...(await stageOf($, token, org, r).catch(() => ({}))), ...named, ...appStage }
533    const flowRun = await getJson<ApiPipelineRun['pipelineRun']>($, token, `${FLOW_BASE}/${org}/pipelines/${r.flowPipelineId}/runs/${r.flowRunId}`, 'Flow')
534    const { branch, ...run } = runOf({ pipelineRun: flowRun })
535    return { ...stage, number: r.flowRunId, ...run, ...(r.branch || !branch ? {} : { branch }) }
536  }
537  const base = `${APPSTACK_BASE}/${org}/apps/${encodeURIComponent(r.app)}/releaseWorkflows/${r.workflowSn}/releaseStages/${r.stageSn}/executions`
538  const stage = await stageOf($, token, org, r).catch(() => ({}))
539  const latest = r.number === undefined ? (await getJson<{ data?: { number?: unknown; startTime?: unknown }[] }>($, token, `${base}?perPage=1&page=1`, 'AppStack')).data?.[0] : undefined
540  const number = r.number ?? pickExecution(latest, r.isTracked ? 0 : r.triggeredAt)
541  if (number === undefined) return stage
542  const { branch, ...run } = runOf(await getJson<ApiPipelineRun>($, token, `${base}/${number}:getPipelineRun`, 'AppStack'))
543  return { ...stage, number, ...run, ...(r.branch || !branch ? {} : { branch }) }
544}
545
546/** Refreshes `key`'s run, or every run still going; a failure is kept on its run and shown in its row. */
547async function refreshDeploys($: EngineInterface, settings: Settings, key?: string) {
548  const due = listOf<DeployRun>(await read($, deploys)).filter(r => (key ? r.key === key : !isSettled(r)) && !deployFetching.has(r.key))
549  if (!due.length) return
550  const token = await cachedToken($, settings)
551  const org = token ? await cachedOrg($, token) : undefined
552  due.forEach(r => deployFetching.add(r.key))
553  const patches = await Promise.all(due.map(async r => {
554    if (!token || !org) return [r.key, { error: token ? NO_ORG : NO_TOKEN }] as const
555    const patch = await fetchRun($, token, org, r).then(
556      (p): Partial<DeployRun> => ({ ...p, error: undefined }),
557      (err: Error): Partial<DeployRun> => ({ error: err.message }),
558    )
559    return [r.key, patch] as const
560  }))
561  due.forEach(r => deployFetching.delete(r.key))
562  const byKey = new Map(patches)
563  await update($, deploys, list => listOf<DeployRun>(list).map(r => {
564    const patch = byKey.get(r.key)
565    if (!patch) return r
566    const { error, ...rest } = { ...r, ...patch }
567    return error ? { ...rest, error } : rest
568  }))
569}
570
571async function rememberDeploy($: EngineInterface, tool: string, input: Readonly<Record<string, unknown>>, output: string, isError: boolean, settings: Settings) {
572  const triggered = triggersOf(tool, input, output, isError)
573  if (!triggered.length) return
574  const now = await $.clock.now()
575  await update($, deploys, list => triggered.reduceRight((runs, t) => addRun(runs, t, now), listOf<DeployRun>(list)))
576  for (const t of triggered) $.clock.after(DEPLOY_FIRST_CHECK_MS, () => void guard($, 'deploy', () => refreshDeploys($, settings, t.key)))
577}
578
579/** Tracks the AppStack stages linked in `text` without deploying anything: each shows its latest run. */
580async function trackDeploys($: EngineInterface, text: string, settings: Settings): Promise<number> {
581  const targets = findStageTargets(text)
582  if (!targets.length) return 0
583  const now = await $.clock.now()
584  await update($, deploys, list => targets.reduce((runs, t) => addRun(runs, t, now, true), listOf<DeployRun>(list)))
585  await Promise.all(targets.map(t => refreshDeploys($, settings, t.key)))
586  return targets.length
587}
588
589// ── /hud ────────────────────────────────────────────────────────────────────────────────────────────────────────────
590
591async function runHud($: EngineInterface, args: string, settings: Settings): Promise<string> {
592  const cmd = parseHud(args)
593  if (cmd.kind === 'reply') return cmd.text
594  if (cmd.kind === 'status') return status(settings, (await read($, collapsed)) ?? settings.collapsed)
595  if (cmd.kind === 'fold') {
596    await update($, collapsed, () => cmd.isCollapsed)
597    return cmd.isCollapsed ? '已折叠' : '已展开'
598  }
599  const { deny } = await $.config.set({ key: `${PLUGIN}.${cmd.key}`, value: cmd.value })
600  return deny ? `未能修改 ${cmd.key}:${deny}` : `已设置 ${cmd.key} = ${String(cmd.value)}`
601}
602
603// ── commands ────────────────────────────────────────────────────────────────────────────────────────────────────
604
605/**
606 * Registers `/<name>`, or `/session-<name>` (or `fallback`) when the name is taken (Claude Code's own /docs, another
607 * plugin's /hud skill). Logged only when neither could be had.
608 */
609async function registerCommand($: EngineInterface, name: string, spec: { description: string; argumentHint?: string }, fallback = `session-${name}`) {
610  for (const candidate of [name, fallback]) {
611    const isRegistered = await $.command.register({ name: candidate, ...spec }).then(() => true, () => false)
612    if (isRegistered) return
613  }
614  $.ui.log(`${PLUGIN}: /${name} 与 /${fallback} 都已被占用,命令未注册(HUD 显示不受影响)`)
615}
616
617async function runMr($: EngineInterface, args: string, settings: Settings): Promise<string> {
618  if (!settings.mr) return 'MR / PR 模块已关闭:/hud mr on'
619  // `/mr <link>`: track an MR / PR this session did not open (one linked while investigating is not shown by itself).
620  const asked = [...findMrLinks(args), ...findPrLinks(args)].map(p => ({ ...p, via: 'tracked' as const }))
621  if (asked.length) await pinMrs($, settings, asked)
622  await refreshMrs($, settings)
623  const v = await read($, mrView)
624  return v?.error ?? mrList(v?.repos ?? [], state => stateOf(state).label)
625}
626
627async function runDeploys($: EngineInterface, args: string, settings: Settings): Promise<string> {
628  if (!settings.deploy) return '云效发布模块已关闭:/hud deploy on'
629  // `/deploys <stage link>…` tracks those stages; bare `/deploys` refreshes and lists.
630  if (!(await trackDeploys($, args, settings))) await refreshDeploys($, settings)
631  return deployList(listOf<DeployRun>(await read($, deploys)))
632}
633
634async function runDocs($: EngineInterface, settings: Settings): Promise<string> {
635  if (!settings.docs) return '飞书文档模块已关闭:/hud docs on'
636  await guard($, 'docs', () => lookupTitles($))
637  return docList(listOf<DocLink>(await read($, docs)))
638}
639
640// ── persistence ─────────────────────────────────────────────────────────────────────────────────────────────────
641
642/** How often the session's snapshot is compared and, when it changed, written. */
643const SAVE_EVERY_MS = 30_000
644/** The last snapshot written, so an unchanged one is not written again. */
645let lastSaved = ''
646/** Snapshots of the same lineage folded into this session's on restore: dropped once this one is written. */
647let foldedKeys: string[] = []
648/** The session's root (its first transcript row's uuid), per session id: a /clear goes on under another. */
649let rootCache: { id: string; root: string } | null = null
650/** Finds the session's transcript and prints its first row's uuid; nothing before the first row is written. */
651const ROOT_SCRIPT = `f=$(ls "$1"/projects/*/"$2".jsonl 2>/dev/null | head -n 1); [ -n "$f" ] && grep -m 1 -o '"uuid":"[0-9a-f-]*"' "$f"; exit 0`
652const ROOT_TIMEOUT_MS = 5_000
653
654/** The uuid of session `id`'s first transcript row: shared by every fork of it (a rewind or an edit in the desktop app). */
655async function readRoot($: EngineInterface, id: string): Promise<string | undefined> {
656  const dir = (await $.env.get('CLAUDE_CONFIG_DIR')) || `${(await $.env.get('HOME')) ?? ''}/.claude`
657  const run = await $.process.run(['/bin/sh', '-c', ROOT_SCRIPT, 'sh', dir, id], { timeoutMs: ROOT_TIMEOUT_MS })
658  return run.stdout.match(/"uuid":"([0-9a-f-]+)"/)?.[1]
659}
660
661async function rootOf($: EngineInterface, id: string): Promise<string | undefined> {
662  if (rootCache?.id === id) return rootCache.root
663  const root = await readRoot($, id)
664  if (root) rootCache = { id, root }
665  return root
666}
667
668async function savedOf($: EngineInterface): Promise<Saved> {
669  return {
670    mrDirs: listOf<string>(await read($, mrDirs)),
671    mrPinned: listOf<MrPin>(await read($, mrPinned)),
672    mrDismissed: listOf<string>(await read($, mrDismissed)),
673    docs: listOf<DocLink>(await read($, docs)),
674    docsDismissed: listOf<string>(await read($, docsDismissed)),
675    deploys: listOf<DeployRun>(await read($, deploys)),
676    deployDismissed: listOf<string>(await read($, deployDismissed)),
677    collapsed: (await read($, collapsed)) ?? null,
678  }
679}
680
681/** Where the desktop app keeps a JSON file per session, `isArchived` and `cliSessionId` among its fields. */
682const DESKTOP_SESSIONS = 'Library/Application Support/Claude/claude-code-sessions'
683/** Prints the `cliSessionId` line of each archived session's file; nothing where the app is not installed. */
684const ARCHIVED_SCRIPT = `grep -rl --include='local_*.json' '"isArchived":true' "$1" 2>/dev/null | while IFS= read -r f; do grep -o '"cliSessionId":"[^"]*"' "$f"; done; exit 0`
685const ARCHIVED_TIMEOUT_MS = 10_000
686
687/**
688 * The sessions archived in the desktop app. The app tells a plugin nothing when a session is archived (its process just
689 * ends), so its own session files are read. ponytail: reads the app's internal metadata; if its layout changes this
690 * finds nothing and the 30-session / 30-day cap still bounds the store.
691 */
692async function archivedSessions($: EngineInterface): Promise<Set<string>> {
693  const home = await $.env.get('HOME')
694  if (!home) return new Set()
695  const run = await $.process.run(['/bin/sh', '-c', ARCHIVED_SCRIPT, 'sh', `${home}/${DESKTOP_SESSIONS}`], { timeoutMs: ARCHIVED_TIMEOUT_MS })
696  return archivedIdsOf(run.stdout)
697}
698
699/** Drops archived sessions' snapshots and those past the newest kept or a month old; `isFull` keeps fewer, to make room. */
700async function pruneStore($: EngineInterface, isFull = false) {
701  const keys = (await $.store.keys()).filter(k => k.startsWith(SNAPSHOT_PREFIX))
702  if (!keys.length) return
703  const saved = await Promise.all(keys.map(async key => ({ key, savedAt: snapshotOf(await $.store.get(key))?.savedAt ?? 0 })))
704  const archived = await archivedSessions($).catch(() => new Set<string>())
705  for (const key of staleKeys(saved, await $.clock.now(), isFull, archived)) await $.store.delete(key)
706}
707
708/** Writes the session's snapshot when it changed since the last write; a full store is pruned harder once. */
709async function saveSession($: EngineInterface) {
710  const state = await savedOf($)
711  const text = JSON.stringify(state)
712  if (text === lastSaved || (isEmpty(state) && !lastSaved)) return
713  const id = await $.session.id()
714  const key = `${SNAPSHOT_PREFIX}${id}`
715  const root = await rootOf($, id).catch(() => undefined)
716  const snapshot = { savedAt: await $.clock.now(), ...(root ? { root } : {}), state }
717  await $.store.set(key, snapshot).catch(async () => {
718    await pruneStore($, true)
719    await $.store.set(key, snapshot)
720  })
721  lastSaved = text
722  // What this session took over from the session it forked from now lives under its own key.
723  for (const old of foldedKeys.filter(k => k !== key)) await $.store.delete(old)
724  foldedKeys = []
725}
726
727/**
728 * Puts the session's snapshot back when the host holds nothing for it: a fresh process resuming the session. A hot
729 * reload finds the host's values and keeps them. A fork (a rewind or an edit in the desktop app goes on under a new
730 * session id) finds the snapshots of the session it came from by their shared root, and takes them over.
731 */
732async function restoreSession($: EngineInterface) {
733  const now = await savedOf($)
734  if (!isEmpty(now)) {
735    lastSaved = JSON.stringify(now)
736    return
737  }
738  const id = await $.session.id()
739  const ownKey = `${SNAPSHOT_PREFIX}${id}`
740  const root = await rootOf($, id).catch(() => undefined)
741  const keys = (await $.store.keys()).filter(k => k.startsWith(SNAPSHOT_PREFIX))
742  // A snapshot written before roots were recorded has its root read from its own transcript.
743  const entries = (await Promise.all(keys.map(async key => {
744    const snap = snapshotOf(await $.store.get(key))
745    if (!snap || snap.root || !root) return snap ? [{ key, snap }] : []
746    const its = await readRoot($, key.slice(SNAPSHOT_PREFIX.length)).catch(() => undefined)
747    return [{ key, snap: its ? { ...snap, root: its } : snap }]
748  }))).flat()
749  const lineage = lineageOf(entries, ownKey, root)
750  if (!lineage) return
751  const s = lineage.state
752  await update($, mrDirs, () => s.mrDirs)
753  await update($, mrPinned, () => s.mrPinned)
754  await update($, mrDismissed, () => s.mrDismissed)
755  await update($, docs, () => s.docs)
756  await update($, docsDismissed, () => s.docsDismissed)
757  await update($, deploys, () => s.deploys)
758  await update($, deployDismissed, () => s.deployDismissed)
759  await update($, collapsed, () => s.collapsed)
760  // Taken over from another session: written under this one's key at the next save, which drops the others.
761  const isOwnOnly = lineage.keys.length === 1 && lineage.keys[0] === ownKey
762  lastSaved = isOwnOnly ? JSON.stringify(s) : ''
763  foldedKeys = isOwnOnly ? [] : lineage.keys
764}
765
766// ── wiring ──────────────────────────────────────────────────────────────────────────────────────────────────────────
767
768export const register: Register = (on, options) => {
769  const settings = settingsOf(options)
770  const isAnyOn = MODULE_IDS.some(id => settings[id])
771
772  on('session.start', async ($, e, next) => {
773    const result = await next(e)
774    // Before any refresh: the pins, dirs and runs it reads may come back from the store.
775    if (isAnyOn) {
776      await guard($, 'persist', () => restoreSession($))
777      if (settings.docs) $.clock.after(0, () => void guard($, 'docs', () => backfillCreated($)))
778      void guard($, 'persist', () => pruneStore($))
779      $.clock.every(SAVE_EVERY_MS, () => void guard($, 'persist', () => saveSession($)))
780    }
781    // Each on its own, with a `session-` name to fall back to: a name Claude Code or another plugin already has is
782    // refused, and that must neither stop the rest of the start nor print an error every session.
783    await registerCommand($, 'hud', { description: 'session-hud:查看 / 启停模块、折叠、修改配置', argumentHint: '[usage|mr|docs|deploy on|off | fold | unfold | set <key> <value>]' })
784    if (settings.mr) await registerCommand($, 'mr', { description: '列出本会话的 MR / PR;带 MR / PR 链接则跟踪它', argumentHint: '[MR / PR 链接]' })
785    // Not `docs`: Claude Code ships a /docs of its own.
786    if (settings.docs) await registerCommand($, 'doclinks', { description: '列出本会话创建或提到的飞书文档 / Artifacts 及链接' }, 'session-docs')
787    if (settings.deploy) await registerCommand($, 'deploys', { description: '列出本会话的云效发布;带 AppStack 阶段链接则跟踪该阶段', argumentHint: '[AppStack 阶段链接]' })
788    if (settings.usage) await guard($, 'usage', () => refreshUsage($))
789    if (settings.mr) {
790      void guard($, 'mr', () => refreshMrs($, settings))
791      $.clock.every(settings.mrPollSeconds * 1_000, () => void guard($, 'mr', () => refreshMrs($, settings)))
792    }
793    if (settings.deploy) {
794      // Only runs still going are fetched; with none, a tick reads the state and stops.
795      void guard($, 'deploy', () => refreshDeploys($, settings))
796      $.clock.every(settings.deployPollSeconds * 1_000, () => void guard($, 'deploy', () => refreshDeploys($, settings)))
797    }
798    return result
799  })
800
801  // Pushed with every measurement: no polling, no extra tokens.
802  on('session.measure', async ($, e, next) => {
803    if (settings.usage) await guard($, 'usage', () => refreshUsage($))
804    return next(e)
805  })
806
807  on('prompt.submit', async ($, e, next) => {
808    if (settings.docs) await guard($, 'docs', () => rememberDocs($, findAllDocs(e.text, settings.docsArtifacts), 'mentioned', settings))
809    if (settings.deploy) await guard($, 'deploy', () => trackDeploys($, e.text, settings))
810    if (settings.mr) await guard($, 'mr', () => pinMrs($, settings, mentionsOf(e.text)))
811    return next(e)
812  })
813
814  on('tool.call', async ($, e, next) => {
815    const { tool, ...input } = e
816    // An MR-opening call is timed from before it runs: what it opened is then found by author and creation time.
817    const mrCreateStart = settings.mr && isMrCreation(tool, input as { command?: unknown }) ? await $.clock.now() : undefined
818    const ran = await next(e)
819    // A failed call's error text is no output: nothing it names was made.
820    const output = !ran.isError && 'text' in ran && typeof ran.text === 'string' ? ran.text : ''
821    if (settings.mr) {
822      await guard($, 'mr', () => rememberMrDirs($, tool, input))
823      // What a create call made shows as made; anything else a call names is a mention, shown only when it is the user's
824      // own MR opened during the session (a helper session's, say), never one met while investigating.
825      await guard($, 'mr', () => pinMrs($, settings, mentionsOf(`${JSON.stringify(input)}\n${output}`)))
826      if (mrCreateStart !== undefined && !ran.isError) {
827        const made = [...findMrLinks(output), ...findPrLinks(output)].map(p => ({ ...p, via: 'created' as const }))
828        await guard($, 'mr', () => pinMrs($, settings, made))
829        if (!isGithubOnly(input)) await guard($, 'mr', () => pinCreatedMrs($, settings, mrCreateStart))
830      }
831    }
832    if (settings.docs) await guard($, 'docs', () => rememberToolDocs($, tool, input, output, settings))
833    if (settings.deploy) await guard($, 'deploy', () => rememberDeploy($, tool, input, 'text' in ran && typeof ran.text === 'string' ? ran.text : '', Boolean(ran.isError), settings))
834    return ran
835  })
836
837  on('turn.complete', async ($, e, next) => {
838    const result = await next(e)
839    // A subagent's turn ends inside the main one: its answer reaches the main answer, and the refreshes wait for it.
840    if (e.agentId) return result
841    const answer = 'answer' in e && typeof e.answer === 'string' ? e.answer : ''
842    await Promise.all([
843      settings.mr && guard($, 'mr', async () => {
844        await pinMrs($, settings, mentionsOf(answer))
845        await refreshMrs($, settings)
846      }),
847      settings.docs && guard($, 'docs', () => rememberDocs($, findAllDocs(answer, settings.docsArtifacts), 'mentioned', settings)),
848    ])
849    // Title lookups run lark-cli (seconds each): off the turn's path, on a timer.
850    if (settings.docs) $.clock.after(0, () => void guard($, 'docs', () => lookupTitles($)))
851    if (isAnyOn) await guard($, 'persist', () => saveSession($))
852    return result
853  })
854
855  on('session.end', async ($, e, next) => {
856    if (isAnyOn) await guard($, 'persist', () => saveSession($))
857    return next(e)
858  })
859
860  // Each command answers under its own name and under the `session-` one it falls back to when the name is taken.
861  on('command.run', { command: 'hud' }, async ($, e) => ({ text: await runHud($, e.args, settings) }))
862  on('command.run', { command: 'session-hud' }, async ($, e) => ({ text: await runHud($, e.args, settings) }))
863  on('command.run', { command: 'mr' }, async ($, e) => ({ text: await runMr($, e.args, settings) }))
864  on('command.run', { command: 'session-mr' }, async ($, e) => ({ text: await runMr($, e.args, settings) }))
865  on('command.run', { command: 'deploys' }, async ($, e) => ({ text: await runDeploys($, e.args, settings) }))
866  on('command.run', { command: 'session-deploys' }, async ($, e) => ({ text: await runDeploys($, e.args, settings) }))
867  on('command.run', { command: 'doclinks' }, async $ => ({ text: await runDocs($, settings) }))
868  on('command.run', { command: 'session-docs' }, async $ => ({ text: await runDocs($, settings) }))
869
870  // The band above the prompt is one site shared by every plugin: draw on top of whatever the plugins beneath drew
871  // (next), never instead of it, and step aside entirely while a survey holds it.
872  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
873    if (!isAnyOn) return next(e)
874    // A card (a survey, a question) holds the band: stay as one line above it, with nothing in it to press.
875    const isCardUp = e.props.hasSurvey
876    const ui = $.ui.resolve(e)
877    const unfolded = listOf<string>(await read($, expandedLists))
878    const foldOf = (list: string): Fold => ({
879      isExpanded: unfolded.includes(list),
880      toggle: () => void update($, expandedLists, cur => {
881        const known = listOf<string>(cur)
882        return known.includes(list) ? known.filter(l => l !== list) : [...known, list]
883      }),
884    })
885    const drawn: (Section | null)[] = []
886    if (settings.usage) drawn.push(usageSection(ui, await read($, usage), await $.clock.now(), settings))
887    if (settings.mr) {
888      const mrState = { view: await read($, mrView), dismissed: listOf<string>(await read($, mrDismissed)), expanded: await read($, mrExpanded) }
889      drawn.push(mrSection(ui, mrState, mrLayout(settings, e.props.bodyColumns), {
890        // Unfolding the checks also fetches them afresh: merge state, branch, conflicts as Codeup has them now.
891        toggleChecks: key => {
892          void update($, mrExpanded, cur => (cur === key ? null : key))
893          void guard($, 'mr', () => refreshMrs($, settings))
894        },
895        dismiss: key => void update($, mrDismissed, list => [...listOf<string>(list), key]),
896      }, foldOf('mr')))
897    }
898    if (settings.docs) {
899      const shown = visibleDocs(listOf<DocLink>(await read($, docs)), listOf<string>(await read($, docsDismissed)), settings)
900      drawn.push(docsSection(ui, shown, docsLayout(settings, e.props.bodyColumns), token => void update($, docsDismissed, list => [...listOf<string>(list), token]), foldOf('docs')))
901    }
902    if (settings.deploy) {
903      const deployState = { runs: listOf<DeployRun>(await read($, deploys)), dismissed: listOf<string>(await read($, deployDismissed)), expanded: await read($, deployExpanded) }
904      drawn.push(deploySection(ui, deployState, mrLayout(settings, e.props.bodyColumns), {
905        // Unfolding a run's stages also fetches them afresh, finished or not.
906        toggle: key => {
907          void update($, deployExpanded, cur => (cur === key ? null : key))
908          void guard($, 'deploy', () => refreshDeploys($, settings, key))
909        },
910        dismiss: key => void update($, deployDismissed, list => [...listOf<string>(list), key]),
911      }, foldOf('deploy')))
912    }
913    const sections = drawn.filter((s): s is Section => s !== null)
914    if (!sections.length) return next(e)
915
916    const isCollapsed = (await read($, collapsed)) ?? settings.collapsed
917    const below = await next(e)
918    const mine = isCardUp
919      ? band(ui, sections, true)
920      : band(ui, sections, isCollapsed, () => void update($, collapsed, cur => !(cur ?? settings.collapsed)))
921    if (isBlank(below)) return mine
922    return (
923      <ui.Box flexDirection="column">
924        {mine}
925        {below}
926      </ui.Box>
927    )
928  })
929}
930
hooks/deploy/parse.ts 216 lines
1import type { DeployRun, DeployStage } from '../../types'
2import { shortError } from '../errors'
3import { LIST_MAX } from '../settings'
4
5const STAGE_URL_RE = /https:\/\/devops\.aliyun\.com\/appstack\/app\/([\w.-]+)\/workflow\/([0-9a-f]{32})\/stage\/([0-9a-f]{32})/
6const STAGE_URLS_RE = new RegExp(STAGE_URL_RE.source, 'g')
7/** One `deploy.sh <service> <env> [branch]` call; the words may be quoted or shell variables. */
8const DEPLOY_SH_RE = /\bdeploy\.sh\s+(\S+)\s+(\S+)(?:\s+([^\s-]\S*))?/g
9const FLOW_RUN_RE = /https:\/\/flow\.aliyun\.com\/pipelines\/(\d+)\/builds\/(\d+)/g
10const DRY_RUN_RE = /\s--(?:dry-run|cli-dry-run)\b/
11const EXECUTE_RE = /\bapp-stack-execute-change-request-release-stage\b/
12/** An AppStack-made Flow pipeline's name: `<app>-<workflow>-<stage>`, e.g. `demo-api-标准发布流程-生产阶段`. */
13const PIPELINE_NAME_RE = /^(.+)-([^-]+)-([^-]+阶段[^-]*)$/
14/** How much earlier than the trigger an execution may start and still be its run (clock skew). */
15const START_SLACK_MS = 2 * 60_000
16
17/** What a trigger names: the stage, and what deploy.sh printed about it. */
18export type DeployTarget = Omit<DeployRun, 'triggeredAt' | 'number' | 'status' | 'stages' | 'error'>
19
20const flagOf = (cmd: string, flag: string): string | undefined => cmd.match(new RegExp(`--${flag}[=\\s]+['"]?([\\w.-]+)`))?.[1]
21const lineOf = (out: string, label: string): string | undefined => out.match(new RegExp(`^\\s*${label}\\s*:\\s*(.+?)\\s*$`, 'm'))?.[1]
22
23/** The AppStack page of a release stage's current run. */
24export const stageUrl = (app: string, workflowSn: string, stageSn: string): string =>
25  `https://devops.aliyun.com/appstack/app/${app}/workflow/${workflowSn}/stage/${stageSn}/current`
26
27const target = (app: string, workflowSn: string, stageSn: string, extra: Partial<DeployTarget>): DeployTarget => ({
28  key: `${app}/${stageSn}`,
29  app,
30  workflowSn,
31  stageSn,
32  url: stageUrl(app, workflowSn, stageSn),
33  ...Object.fromEntries(Object.entries(extra).filter(([, v]) => v)),
34})
35
36/** A word of the command as written: quotes dropped; a shell variable or substitution is not a value. */
37const literal = (word: string | undefined): string | undefined => {
38  const w = word?.replace(/^(['"])(.*)\1$/, '$2')
39  return w && !/[$`(){}]/.test(w) ? w : undefined
40}
41
42/** A Flow run page: what a release is when deploy.sh's output was cut down to its `Flow run:` line. */
43const unnamed = (pipelineId: string): string => `流水线 ${pipelineId}`
44
45/** A Flow-only run whose call named no app (a loop over `$app`): its row is named from the pipeline once read. */
46export const isUnnamed = (r: Pick<DeployRun, 'app' | 'flowPipelineId'>): boolean => Boolean(r.flowPipelineId) && r.app === unnamed(r.flowPipelineId ?? '')
47
48/** What a Flow pipeline's name says about its run: the app, and the stage and env when AppStack named it. */
49export function pipelineLabel(name: string): Pick<DeployRun, 'app' | 'stageName' | 'env'> {
50  const m = name.match(PIPELINE_NAME_RE)
51  return m?.[1] && m[3] ? { app: m[1], stageName: m[3], env: envOfStage(m[3]) } : { app: name }
52}
53
54const flowTarget = (pipelineId: string, runId: string, extra: Partial<DeployTarget>): DeployTarget => ({
55  key: `flow/${pipelineId}`,
56  app: extra.app ?? unnamed(pipelineId),
57  workflowSn: '',
58  stageSn: '',
59  url: `https://flow.aliyun.com/pipelines/${pipelineId}/builds/${runId}`,
60  ...Object.fromEntries(Object.entries(extra).filter(([, v]) => v)),
61  flowPipelineId: pipelineId,
62  flowRunId: runId,
63})
64
65/**
66 * Every AppStack release a finished Bash call triggered, in the order it ran them. A command may run deploy.sh several
67 * times (a loop, one call per region) and cut its output down (`| grep "Flow run"`): the n-th `deploy.sh` call is
68 * paired with the n-th stage page and the n-th `Flow run:` link in the output, and either link is enough. The env and
69 * branch come from the call's words, or from its `Env:` / `Branch:` lines when it ran alone. A dry run (which still
70 * prints links to existing runs) and a failed call never count. A direct
71 * `app-stack-execute-change-request-release-stage` call counts by its flags.
72 */
73export function triggersOf(tool: string, input: { command?: unknown }, output: string, isError: boolean): DeployTarget[] {
74  const cmd = typeof input.command === 'string' ? input.command : ''
75  if (tool !== 'Bash' || isError || !cmd || DRY_RUN_RE.test(cmd)) return []
76  const calls = [...cmd.matchAll(DEPLOY_SH_RE)]
77  if (calls.length) {
78    const stages = [...output.matchAll(STAGE_URLS_RE)]
79    const flows = [...output.matchAll(FLOW_RUN_RE)]
80    // A loop runs one call many times: then the links, not the calls, say how many releases there were.
81    const count = Math.max(stages.length, flows.length)
82    const isSingle = count === 1
83    return Array.from({ length: count }, (_, i) => {
84      // Past the last call, a loop is running it again: its literal words hold for every run, its variables for none.
85      const call = calls[Math.min(i, calls.length - 1)]
86      const envLine = isSingle ? lineOf(output, 'Env') ?? '' : ''
87      const branchLine = isSingle ? lineOf(output, 'Branch') : undefined
88      const extra: Partial<DeployTarget> = {
89        env: envLine.split(/\s+/)[0] || literal(call?.[2]),
90        stageName: envLine.match(/\(stage:\s*([^/)]+?)\s*(?:\/|\))/)?.[1],
91        branch: (branchLine && !branchLine.startsWith('<') ? branchLine : undefined) ?? literal(call?.[3]),
92        feature: isSingle ? lineOf(output, 'Labelled') ?? lineOf(output, 'Feature')?.replace(/^<none.*$/, '') : undefined,
93      }
94      const stage = stages[i]
95      const flow = flows[i]
96      const flowIds = flow?.[1] && flow[2] ? { flowPipelineId: flow[1], flowRunId: flow[2] } : {}
97      if (stage?.[1] && stage[2] && stage[3]) return { ...target(stage[1], stage[2], stage[3], extra), ...flowIds }
98      return flow?.[1] && flow[2] ? flowTarget(flow[1], flow[2], { ...extra, app: literal(call?.[1]) }) : null
99    }).filter((t): t is DeployTarget => t !== null)
100  }
101  if (!EXECUTE_RE.test(cmd)) return []
102  const app = flagOf(cmd, 'app-name')
103  const wf = flagOf(cmd, 'release-workflow-sn')
104  const stage = flagOf(cmd, 'release-stage-sn')
105  return app && wf && stage ? [target(app, wf, stage, {})] : []
106}
107
108/** Every AppStack stage page linked in `text`, deduped: what a pasted link asks to track. */
109export function findStageTargets(text: string): DeployTarget[] {
110  const found = new Map<string, DeployTarget>()
111  for (const [, app, wf, stage] of text.matchAll(STAGE_URLS_RE)) {
112    if (app && wf && stage && !found.has(`${app}/${stage}`)) found.set(`${app}/${stage}`, target(app, wf, stage, {}))
113  }
114  return [...found.values()]
115}
116
117type ApiWorkflow = { sn?: unknown; releaseStages?: { sn?: unknown; name?: unknown; pipeline?: { id?: unknown } | null }[] }
118
119/** The release stage whose Flow pipeline is `pipelineId`, from an app's `releaseWorkflows` answer. */
120export function stageOfPipeline(workflows: unknown, pipelineId: string): Pick<DeployRun, 'workflowSn' | 'stageSn' | 'stageName'> | undefined {
121  for (const w of Array.isArray(workflows) ? (workflows as ApiWorkflow[]) : []) {
122    const s = (w.releaseStages ?? []).find(st => String(st.pipeline?.id ?? '') === pipelineId)
123    if (s && typeof w.sn === 'string' && typeof s.sn === 'string') {
124      return { workflowSn: w.sn, stageSn: s.sn, ...(typeof s.name === 'string' ? { stageName: s.name } : {}) }
125    }
126  }
127  return undefined
128}
129
130/**
131 * Adds a run, newest first; triggering (or tracking) a stage again starts its entry over. The same Flow pipeline is the
132 * same stage however it was recorded (stage page or `Flow run:` link), and an unnamed one keeps the name it had.
133 */
134export function addRun(known: readonly DeployRun[], t: DeployTarget, now: number, isTracked = false): DeployRun[] {
135  const isSame = (r: DeployRun) => r.key === t.key || (t.flowPipelineId !== undefined && r.flowPipelineId === t.flowPipelineId)
136  const prior = known.find(r => isSame(r) && !isUnnamed(r))
137  const named = isUnnamed(t) && prior ? { ...t, app: prior.app, ...(prior.stageName && !t.stageName ? { stageName: prior.stageName } : {}) } : t
138  const run: DeployRun = isTracked ? { ...named, triggeredAt: now, isTracked } : { ...named, triggeredAt: now }
139  return [run, ...known.filter(r => !isSame(r))].slice(0, LIST_MAX)
140}
141
142const ENV_KEYWORDS: readonly (readonly [string, RegExp])[] = [['prod', /生产|线上|正式|prod/i], ['pre', /预发|灰度|staging|pre/i], ['test', /测试|日常|daily|test/i]]
143
144/** A release stage's name as the env it deploys to: 生产阶段 → prod, 预发阶段 → pre; else the name without 阶段. */
145export function envOfStage(name: string): string {
146  return ENV_KEYWORDS.find(([, re]) => re.test(name))?.[0] ?? name.replace(/阶段$/, '')
147}
148
149const TERMINAL = new Set(['SUCCESS', 'FAIL', 'FAILED', 'CANCELED', 'CANCELLED'])
150
151/** Finished runs are not polled; an unpinned run (its execution not found yet) still is. */
152export const isSettled = (r: DeployRun) => r.number !== undefined && r.status !== undefined && TERMINAL.has(r.status)
153
154/** The stage execution that is this run: the latest one, unless it started before the trigger (0: any). */
155export function pickExecution(latest: { number?: unknown; startTime?: unknown } | undefined, triggeredAt: number): string | undefined {
156  if (!latest || (typeof latest.number !== 'string' && typeof latest.number !== 'number')) return undefined
157  const started = typeof latest.startTime === 'string' ? Date.parse(latest.startTime) : NaN
158  return Number.isNaN(started) || started >= triggeredAt - START_SLACK_MS ? String(latest.number) : undefined
159}
160
161type ApiJob = { name?: unknown; status?: unknown }
162type ApiStage = { name?: unknown; stageInfo?: { name?: unknown; status?: unknown; jobs?: ApiJob[] } }
163export type ApiPipelineRun = { pipelineRun?: { status?: unknown; stages?: ApiStage[]; sources?: { data?: { branch?: unknown } }[] } }
164
165const str = (v: unknown, fallback: string) => (typeof v === 'string' && v ? v : fallback)
166
167/** A getPipelineRun answer as the run's status, its stages' jobs and the branch it built. */
168export function runOf(api: ApiPipelineRun): { status: string; stages: DeployStage[]; branch?: string } {
169  const run = api.pipelineRun ?? {}
170  const stages = (run.stages ?? []).map((s): DeployStage => ({
171    name: str(s.name ?? s.stageInfo?.name, '阶段'),
172    status: str(s.stageInfo?.status, 'INIT'),
173    jobs: (s.stageInfo?.jobs ?? []).map(j => ({ name: str(j.name, '任务'), status: str(j.status, 'INIT') })),
174  }))
175  const branch = run.sources?.[0]?.data?.branch
176  return { status: str(run.status, 'RUNNING'), stages, ...(typeof branch === 'string' && branch ? { branch } : {}) }
177}
178
179export type Tone = 'success' | 'error' | 'warning' | 'inactive' | 'suggestion'
180
181const STATES: Record<string, { label: string; glyph: string; tone: Tone }> = {
182  SUCCESS: { label: '成功', glyph: '✓', tone: 'success' },
183  FAIL: { label: '失败', glyph: '✕', tone: 'error' },
184  FAILED: { label: '失败', glyph: '✕', tone: 'error' },
185  RUNNING: { label: '运行中', glyph: '◐', tone: 'suggestion' },
186  WAITING: { label: '待确认', glyph: '◷', tone: 'warning' },
187  SWITCH_MANUAL: { label: '待确认', glyph: '◷', tone: 'warning' },
188  CANCELED: { label: '已取消', glyph: '⊘', tone: 'inactive' },
189  CANCELLED: { label: '已取消', glyph: '⊘', tone: 'inactive' },
190  SKIPPED: { label: '已跳过', glyph: '–', tone: 'inactive' },
191  INIT: { label: '未开始', glyph: '○', tone: 'inactive' },
192  QUEUED: { label: '排队中', glyph: '○', tone: 'inactive' },
193}
194
195export function stateOf(status: string | undefined): { label: string; glyph: string; tone: Tone } {
196  if (status === undefined) return { label: '查询中', glyph: '…', tone: 'inactive' }
197  return STATES[status] ?? { label: status, glyph: '?', tone: 'inactive' }
198}
199
200/**
201 * Where the run stands, as one line: the job it stopped at or is on (the first that is not done), else the last job.
202 * `✕ 灰度人工卡点`, `◐ 预热发布`, `✓ 全量发布`.
203 */
204export function progressOf(r: DeployRun): string {
205  const jobs = (r.stages ?? []).flatMap(s => s.jobs)
206  if (r.error) {
207    const e = shortError(r.error)
208    // A blip with stages already read: show them; the next poll tries again.
209    if (!(e.isTransient && jobs.length)) return `查询失败:${e.reason}${e.isTransient ? ',稍后重试' : ''}`
210  }
211  if (!jobs.length) return r.number ? `#${r.number}` : '等待运行开始'
212  const current = jobs.find(j => j.status !== 'SUCCESS' && j.status !== 'SKIPPED') ?? jobs[jobs.length - 1]
213  const done = jobs.filter(j => j.status === 'SUCCESS').length
214  return current ? `${stateOf(current.status).glyph} ${current.name} (${done}/${jobs.length})` : ''
215}
216
hooks/deploy/view.tsx 118 lines
1import type { RenderElement } from 'claude-code'
2
3import type { DeployRun } from '../../types'
4import type { Settings } from '../settings'
5import { ICON_W, ID_W, STATE_W, capRows, cell, foldButton } from '../ui'
6import type { Fold, Section, Ui } from '../ui'
7import { progressOf, stateOf } from './parse'
8
9/** The 检查 button's column, as wide as the MR rows' so the two line up at the right. */
10const CHECKS_W = 12
11/** The progress column spans the MR rows' `→ target` columns: the arrow, its gap and the target. */
12const ARROW_AND_GAP = 2
13const SUMMARY_MAX = 3
14
15export type DeployActions = {
16  toggle: (key: string) => void
17  dismiss: (key: string) => void
18}
19
20export type DeployState = { runs: readonly DeployRun[]; dismissed: readonly string[]; expanded: string | null }
21
22/** A stage's name column in the unfolded list (构建, 部署). */
23const STAGE_NAME_W = 6
24
25/**
26 * A run unfolded: one line per stage, its glyph and name, then its jobs inline (`✓ 预热发布 · ✕ 灰度人工卡点`), cut to
27 * the row's width and whole on hover; the release note first, a `⌃ 收起` last. Kept short so the band rarely scrolls.
28 */
29function jobList(ui: Ui, r: DeployRun, settings: Settings, act: DeployActions): RenderElement {
30  const { Box, Text } = ui
31  const stages = r.stages ?? []
32  // From the state column to the end of the progress column: the same span the row's name columns take.
33  const span = STATE_W + (settings.mrRepo ? settings.mrRepoWidth + 1 : 0) + settings.mrSourceWidth + 1 + settings.mrTargetWidth + ARROW_AND_GAP + 1
34  const jobsW = Math.max(10, span - STAGE_NAME_W - 4)
35  return (
36    <Box key={`deploy-jobs-${r.key}`} flexDirection="column" paddingLeft={ICON_W + ID_W + 2}>
37      {r.feature ? (
38        <Box key={`deploy-feature-${r.key}`} height={1} overflow="hidden">
39          <Text dimColor wrap="truncate-end">发布说明:{r.feature}</Text>
40        </Box>
41      ) : null}
42      {stages.length ? stages.map((st, i) => {
43        const s = stateOf(st.status)
44        const jobs = st.jobs.map(j => `${stateOf(j.status).glyph} ${j.name}`).join(' · ')
45        return (
46          <Box key={`deploy-stage-${r.key}-${i}`} height={1} columnGap={1} flexWrap="nowrap" overflow="hidden">
47            <Text color={s.tone}>{s.glyph}</Text>
48            {cell(ui, { key: `deploy-stage-name-${r.key}-${i}`, text: st.name, width: STAGE_NAME_W, dimColor: true })}
49            {cell(ui, { key: `deploy-stage-jobs-${r.key}-${i}`, text: jobs || s.label, width: jobsW })}
50          </Box>
51        )
52      }) : <Text key={`deploy-nojobs-${r.key}`} dimColor>{progressOf(r)}</Text>}
53      {foldButton(ui, `deploy-fold-${r.key}`, () => act.toggle(r.key))}
54    </Box>
55  )
56}
57
58/** One release on the MR rows' grid: env under `!id`, the run's state under the MR state, app (the link), branch, progress. */
59function row(ui: Ui, r: DeployRun, settings: Settings, isOpen: boolean, act: DeployActions): RenderElement {
60  const { Box, Button, Text } = ui
61  const s = stateOf(r.error ? undefined : r.status)
62  const sum = r.error ? { glyph: '!', tone: 'warning' } : s
63  return (
64    <Box key={`deploy-${r.key}`} flexDirection="column">
65      <Box height={1} flexWrap="nowrap" overflow="hidden" columnGap={1} alignItems="center">
66        <Box width={ICON_W} flexShrink={0}><Text color={s.tone}>⇪</Text></Box>
67        {cell(ui, { key: `deploy-env-${r.key}`, text: r.env ?? r.stageName ?? '发布', width: ID_W, dimColor: true })}
68        {cell(ui, { key: `deploy-state-${r.key}`, text: s.label, width: STATE_W, color: s.tone })}
69        {cell(ui, { key: `deploy-app-${r.key}`, text: r.app, width: settings.mrRepoWidth, href: r.url })}
70        {cell(ui, { key: `deploy-branch-${r.key}`, text: r.branch ?? r.stageName ?? '', width: settings.mrSourceWidth, mode: 'middle', dimColor: true })}
71        {cell(ui, { key: `deploy-progress-${r.key}`, text: progressOf(r), width: settings.mrTargetWidth + ARROW_AND_GAP, color: r.error ? 'warning' : undefined, dimColor: !r.error })}
72        <Box flexGrow={1} />
73        <Box key={`deploy-checks-${r.key}`} minWidth={CHECKS_W} flexShrink={0}>
74          <Button key={`deploy-check-${r.key}`} onPress={() => act.toggle(r.key)}>
75            <Text color={sum.tone}>{sum.glyph}</Text> 检查 {isOpen ? '⌃' : '⌄'}
76          </Button>
77        </Box>
78        <Button key={`deploy-dismiss-${r.key}`} role="dismiss" plain label="×" dimColor onPress={() => act.dismiss(r.key)} />
79      </Box>
80      {isOpen ? jobList(ui, r, settings, act) : null}
81    </Box>
82  )
83}
84
85/** `/deploys` output: one markdown line per release, linked. */
86export function deployList(runs: readonly DeployRun[]): string {
87  const lines = runs.map(r => {
88    const s = stateOf(r.status)
89    const where = [r.env, r.branch && `\`${r.branch}\``].filter(Boolean).join(' · ')
90    return `- ${s.glyph} **${r.app}**${r.isTracked ? '(跟踪)' : ''} ${where} · ${s.label}${r.number ? ` #${r.number}` : ''} · [AppStack](${r.url}) · ${progressOf(r)}`
91  })
92  return lines.length ? lines.join('\n') : '本会话还没有触发或跟踪云效发布。跟踪已有发布:`/deploys <AppStack 阶段链接>`,或在消息里贴该链接。'
93}
94
95/** One row per release the session triggered, newest first; null with none. */
96export function deploySection(ui: Ui, state: DeployState, settings: Settings, act: DeployActions, fold: Fold): Section | null {
97  const runs = state.runs.filter(r => !state.dismissed.includes(r.key))
98  if (!runs.length) return null
99  const { Box, Text } = ui
100  const rows = runs.map(r => row(ui, r, settings, state.expanded === r.key, act))
101  const shown = runs.slice(0, SUMMARY_MAX)
102  return {
103    rows: capRows(ui, 'deploy', rows, settings.deployMaxRows, '次发布', fold),
104    summary: [
105      ...shown.map(r => {
106        const s = stateOf(r.status)
107        return (
108          <Box key={`deploy-sum-${r.key}`} columnGap={1} flexShrink={0}>
109            <Text color={s.tone}>⇪{r.app}{r.env ? `·${r.env}` : ''}</Text>
110            <Text color={s.tone}>{s.glyph}</Text>
111          </Box>
112        )
113      }),
114      ...(runs.length > shown.length ? [<Text key="deploy-sum-more" dimColor>+{runs.length - shown.length}</Text>] : []),
115    ],
116  }
117}
118
hooks/docs/links.ts 170 lines
1import type { DocLink, DocOrigin } from '../../types'
2import { LIST_MAX } from '../settings'
3
4const HOSTS = String.raw`[\w-]+(?:\.[\w-]+)*\.(?:feishu\.cn|larksuite\.com|larkoffice\.com|feishu\.net)`
5const KINDS = 'docx|docs|doc|wiki|sheets|sheet|base|bitable|mindnotes|mindnote|slides|file'
6// The token must end the path segment: `/wiki/settings/123` is a page, not the document `settings`.
7const URL_RE = new RegExp(String.raw`https?://(${HOSTS})/(${KINDS})/([A-Za-z0-9]{8,})(?![\w/-])`, 'gi')
8const MD_LINK_RE = /\[([^\]\n]{1,200})\]\((https?:\/\/[^)\s]+)\)/g
9const CREATE_RE = /\blark-cli\b[^\n;&|]*?\s\+(?:create|import|copy|duplicate)\b/
10/** Mentions kept per session; created documents are always kept. */
11
12export type FoundDoc = { token: string; url: string; kind: string; label?: string; title?: string }
13
14export const KIND_LABELS: Record<string, string> = {
15  docx: '文档', docs: '文档', doc: '文档', wiki: '知识库', sheets: '表格', sheet: '表格',
16  base: '多维表', bitable: '多维表', mindnotes: '脑图', mindnote: '脑图', slides: '幻灯片', file: '文件',
17  artifact: 'Claude',
18}
19
20/** The kind a Claude Artifact (a page published to claude.ai) is filed under. */
21export const ARTIFACT = 'artifact'
22/** claude.ai/code/artifact/<uuid> or claude.ai/artifact/<id>: the id is the dedupe key. */
23const ARTIFACT_RE = /https:\/\/claude\.ai\/(?:code\/)?artifact\/([A-Za-z0-9][A-Za-z0-9-]{7,})/g
24/** The head of an Artifact `read` result: `[Artifact <id> "<title>" — …`. */
25const ARTIFACT_READ_RE = /^\[Artifact ([A-Za-z0-9-]+) "([^"\n]{1,300})"/
26/** Artifact actions whose links name the artifact being worked on; `list` and the rest print other links. */
27const ARTIFACT_NAMING = new Set(['publish', 'read', 'open'])
28
29/** Every Feishu / Lark document link in `text`, deduped by token; a markdown link's text is its label. */
30export function findDocs(text: string): FoundDoc[] {
31  const labels = new Map<string, string>()
32  for (const [, label, url] of text.matchAll(MD_LINK_RE)) {
33    const token = [...(url ?? '').matchAll(URL_RE)][0]?.[3]
34    const shown = label?.trim()
35    if (token && shown && !/^https?:\/\//i.test(shown)) labels.set(token, shown)
36  }
37  const found = new Map<string, FoundDoc>()
38  for (const [, host, kind, token] of text.matchAll(URL_RE)) {
39    if (!host || !kind || !token || found.has(token)) continue
40    const label = labels.get(token)
41    const k = kind.toLowerCase()
42    found.set(token, { token, kind: k, url: `https://${host.toLowerCase()}/${k}/${token}`, ...(label ? { label } : {}) })
43  }
44  return [...found.values()]
45}
46
47/** Every Claude Artifact linked in `text`, deduped by id; a markdown link's text is its label. */
48export function findArtifacts(text: string): FoundDoc[] {
49  const labels = new Map<string, string>()
50  for (const [, label, url] of text.matchAll(MD_LINK_RE)) {
51    const id = [...(url ?? '').matchAll(ARTIFACT_RE)][0]?.[1]
52    const shown = label?.trim()
53    if (id && shown && !/^https?:\/\//i.test(shown)) labels.set(id, shown)
54  }
55  const found = new Map<string, FoundDoc>()
56  for (const [url, id] of text.matchAll(ARTIFACT_RE)) {
57    if (!id || found.has(id)) continue
58    const label = labels.get(id)
59    found.set(id, { token: id, kind: ARTIFACT, url, ...(label ? { label } : {}) })
60  }
61  return [...found.values()]
62}
63
64/** Feishu / Lark documents and Claude Artifacts linked in `text`. */
65export const findAllDocs = (text: string, withArtifacts: boolean): FoundDoc[] => [...findDocs(text), ...(withArtifacts ? findArtifacts(text) : [])]
66
67/** The title an HTML page names in its `<title>`, entities left as written. */
68export const htmlTitle = (html: string): string | undefined => html.match(/<title[^>]*>\s*([^<]{1,300}?)\s*<\/title>/i)?.[1]
69
70/**
71 * What an Artifact call made or named. A publish made the page its output links (`Published … at <url>`), titled by its
72 * file's `<title>` (`pageTitle`), the call's `title`, else the file's name; a read or open names the artifact it was given, titled by the
73 * read's header. Other actions (`list`, `delete`, …) count for nothing. A Claude Docs connector call that creates
74 * (`container.create` in its input) made the artifacts its output links.
75 */
76export function artifactsOfCall(tool: string, input: Record<string, unknown>, output: string, pageTitle?: string): { made: FoundDoc[]; mentioned: FoundDoc[] } {
77  if (tool === 'Artifact') {
78    const action = typeof input.action === 'string' ? input.action : 'publish'
79    if (!ARTIFACT_NAMING.has(action) || input.asset === true) return { made: [], mentioned: [] }
80    if (action === 'publish') {
81      const fileName = typeof input.file_path === 'string' ? input.file_path.split('/').at(-1)?.replace(/\.[^.]+$/, '') : undefined
82      const title = pageTitle ?? (typeof input.title === 'string' && input.title ? input.title : undefined) ?? (fileName || undefined)
83      return { made: findArtifacts(output).slice(0, 1).map(d => (title ? { ...d, title } : d)), mentioned: [] }
84    }
85    const header = output.match(ARTIFACT_READ_RE)
86    const named = findArtifacts(JSON.stringify(input)).map(d => (header?.[2] && d.token === header[1] ? { ...d, title: header[2] } : d))
87    return { made: [], mentioned: named }
88  }
89  const isDocsCreate = tool.startsWith('mcp__') && /"create"\s*:/.test(JSON.stringify(input))
90  return isDocsCreate ? { made: findArtifacts(output), mentioned: [] } : { made: [], mentioned: findArtifacts(JSON.stringify(input)) }
91}
92
93/** A tool call that makes a document: `lark-cli [flags] <domain> +create|+import|+copy`, or a Lark MCP tool named so. */
94export function isCreation(tool: string, input: { command?: unknown }): boolean {
95  if (tool === 'Bash') return typeof input.command === 'string' && CREATE_RE.test(input.command)
96  return /lark|feishu/i.test(tool) && /create|import|copy|duplicate/i.test(tool)
97}
98
99/** A tool call worth scanning for links: lark-cli in Bash, or a Lark / Feishu MCP tool. */
100export function isLarkTool(tool: string, input: { command?: unknown }): boolean {
101  if (tool === 'Bash') return typeof input.command === 'string' && /\blark-cli\b/.test(input.command)
102  return /lark|feishu/i.test(tool)
103}
104
105/**
106 * Adds what was found, newest first: `created` outranks `mentioned`, a looked-up title is never replaced, and only
107 * mentions are dropped past the cap.
108 */
109/** Every token a row answers to: its link's, its document's own, and the links folded into it. */
110const namesOf = (d: DocLink): string[] => [d.token, ...(d.docToken ? [d.docToken] : []), ...(d.aliases ?? [])]
111
112/**
113 * One row per document: rows that share a token (a docx link and the wiki node it was moved under, once the lookup
114 * unwrapped the node) become one, where the first of them stood. The wiki link is kept (where the doc lives now), made
115 * if either was made, with every other token as an alias so a later mention or a dismissal of either finds it.
116 * ponytail: O(n²) over the session's docs (a hundred or so).
117 */
118export function foldSameDoc(list: readonly DocLink[]): DocLink[] {
119  const groups: DocLink[][] = []
120  for (const d of list) {
121    const names = new Set(namesOf(d))
122    const group = groups.find(g => g.some(o => namesOf(o).some(n => names.has(n))))
123    if (group) group.push(d)
124    else groups.push([d])
125  }
126  return groups.map(g => {
127    if (g.length === 1) return g[0] as DocLink
128    const base = g.find(d => d.kind === 'wiki') ?? (g[0] as DocLink)
129    const aliases = [...new Set(g.flatMap(namesOf))].filter(n => n !== base.token && n !== base.docToken)
130    const title = base.title ?? g.find(d => d.title)?.title
131    const label = base.label ?? g.find(d => d.label)?.label
132    const docToken = base.docToken ?? g.find(d => d.docToken)?.docToken
133    return {
134      ...base,
135      origin: g.some(d => d.origin === 'created') ? 'created' : base.origin,
136      at: Math.max(...g.map(d => d.at)),
137      ...(title ? { title } : {}),
138      ...(label ? { label } : {}),
139      ...(docToken ? { docToken } : {}),
140      ...(g.some(d => d.isLookedUp) ? { isLookedUp: true } : {}),
141      ...(aliases.length ? { aliases } : {}),
142    }
143  })
144}
145
146export function mergeDocs(known: readonly DocLink[], found: readonly FoundDoc[], origin: DocOrigin, now: number): DocLink[] {
147  const byToken = new Map(known.map(d => [d.token, d]))
148  const fresh = found.map((f): DocLink => {
149    const old = byToken.get(f.token)
150    const label = f.label ?? old?.label
151    const title = f.title ?? old?.title
152    return {
153      ...old,
154      token: f.token,
155      url: old?.url ?? f.url,
156      kind: f.kind,
157      origin: old?.origin === 'created' || origin === 'created' ? 'created' : 'mentioned',
158      at: now,
159      ...(label ? { label } : {}),
160      ...(title ? { title } : {}),
161      // An artifact's title comes with it or not at all: there is nothing to look it up with.
162      ...(f.kind === ARTIFACT ? { isLookedUp: true } : {}),
163    }
164  })
165  const tokens = new Set(fresh.map(d => d.token))
166  const all = foldSameDoc([...fresh, ...known.filter(d => !tokens.has(d.token))])
167  const keptMentions = new Set(all.filter(d => d.origin === 'mentioned').slice(0, LIST_MAX).map(d => d.token))
168  return all.filter(d => d.origin === 'created' || keptMentions.has(d.token))
169}
170
hooks/docs/backfill.ts 48 lines
1import { artifactsOfCall, findDocs, isCreation } from './links'
2
3/**
4 * What picks a session's transcript lines worth reading for documents it made: a document or artifact link, a create
5 * call, or a Lark / Artifact tool. Everything else (most of the transcript) is left to grep.
6 */
7export const CREATION_LINES_RE = String.raw`feishu\.cn|larksuite\.com|larkoffice\.com|feishu\.net|claude\.ai/(code/)?artifact|\+(create|import|copy|duplicate)|"name":"[^"]*(lark|feishu|Artifact)[^"]*"`
8
9type ToolUse = { name: string; input: Record<string, unknown> }
10type Block = { type?: string; id?: string; name?: string; input?: unknown; tool_use_id?: string; content?: unknown; is_error?: boolean; text?: string }
11
12const textOf = (content: unknown): string =>
13  typeof content === 'string' ? content
14    : Array.isArray(content) ? content.map(c => (typeof (c as Block).text === 'string' ? (c as Block).text : JSON.stringify(c))).join('\n')
15      : JSON.stringify(content ?? '')
16
17const blocksOf = (line: string): Block[] => {
18  try {
19    const content = (JSON.parse(line) as { message?: { content?: unknown } }).message?.content
20    return Array.isArray(content) ? (content as Block[]) : []
21  } catch {
22    return []
23  }
24}
25
26/**
27 * The documents a session's own calls made, read back from its transcript lines: a create call's output links that its
28 * input did not name, and the Artifacts it published. What the live hooks would have marked 创建, for a session whose
29 * marks were lost (a restart before they were saved, a fork that started over).
30 */
31export function createdInTranscript(lines: string): Set<string> {
32  const uses = new Map<string, ToolUse>()
33  const made = new Set<string>()
34  for (const line of lines.split('\n')) {
35    for (const b of blocksOf(line)) {
36      if (b.type === 'tool_use' && b.id && b.name) uses.set(b.id, { name: b.name, input: (b.input ?? {}) as Record<string, unknown> })
37      if (b.type !== 'tool_result' || b.is_error || !b.tool_use_id) continue
38      const use = uses.get(b.tool_use_id)
39      if (!use) continue
40      const output = textOf(b.content)
41      const asked = new Set(findDocs(JSON.stringify(use.input)).map(d => d.token))
42      const lark = isCreation(use.name, use.input as { command?: unknown }) ? findDocs(output).filter(d => !asked.has(d.token)) : []
43      for (const d of [...lark, ...artifactsOfCall(use.name, use.input, output).made]) made.add(d.token)
44    }
45  }
46  return made
47}
48
hooks/docs/lookup.ts 77 lines
1/** The Desktop app does not inherit the shell's PATH, so the usual install folders are tried after the bare name. */
2export const LARK_CLI = ['lark-cli', '/opt/homebrew/bin/lark-cli', '/usr/local/bin/lark-cli'] as const
3
4/** URL path kinds `+inspect` spells differently from the links people share. */
5const INSPECT_KINDS: Record<string, string> = { mindnotes: 'mindnote', docs: 'doc' }
6
7/** The argv that prints a document's type, title and canonical token as JSON (wiki nodes unwrapped). */
8export function inspectArgv(bin: string, url: string): string[] {
9  const fixed = url.replace(/\/(mindnotes|docs)\//, (_m, kind: string) => `/${INSPECT_KINDS[kind] ?? kind}/`)
10  return [bin, 'drive', '+inspect', '--url', fixed, '--format', 'json']
11}
12
13/** A spawn failure that means "no such program here", so the next install folder is worth trying. */
14export const isMissingProgram = (err: unknown): boolean => /ENOENT|not found|no such file/i.test(err instanceof Error ? err.message : String(err))
15
16/** What one lookup came to: a title; a final no (no access, no such doc); or a failure worth trying again later. */
17export type Lookup = { title: string; token?: string } | { final: string } | { retry: string }
18
19type CliError = { type?: string; subtype?: string; code?: number; message?: string }
20
21/** The `error` of the JSON a failed run printed (after any progress lines, on stdout or stderr); undefined without one. */
22export function cliErrorOf(text: string): CliError | undefined {
23  const start = text.indexOf('{')
24  if (start < 0) return undefined
25  try {
26    const error = (JSON.parse(text.slice(start)) as { error?: unknown }).error
27    return error && typeof error === 'object' ? (error as CliError) : undefined
28  } catch {
29    return undefined
30  }
31}
32
33const NOT_FOUND_RE = /not[_ ]?found/i
34const MAX_REASON = 160
35
36/**
37 * Reads one `lark-cli drive +inspect` run. A success without a title, no access, and no such document (a deleted doc,
38 * a made-up link) are final; any other failure (a timeout, a network error, a CLI that could not start) is tried again
39 * later, with the CLI's own message as the reason.
40 */
41export function lookupOf(run: { exitCode: number; stdout: string; stderr: string } | { failed: string }): Lookup {
42  if ('failed' in run) return { retry: run.failed }
43  if (run.exitCode === 0) {
44    const title = titleOf(run.stdout)
45    const token = tokenOf(run.stdout)
46    return title ? { title, ...(token ? { token } : {}) } : { final: '无标题' }
47  }
48  const error = cliErrorOf(run.stdout) ?? cliErrorOf(run.stderr)
49  const text = `${run.stderr}\n${run.stdout}`
50  if (error?.type === 'authorization' || /permission/i.test(error?.subtype ?? '') || (!error && /"type"\s*:\s*"authorization"|permission/i.test(text))) return { final: '无权限' }
51  if (NOT_FOUND_RE.test(error?.subtype ?? '') || NOT_FOUND_RE.test(error?.message ?? '')) return { final: '不存在' }
52  const lastLine = text.split('\n').map(l => l.trim()).filter(l => l && !/^[{}\]],?$/.test(l)).at(-1) ?? ''
53  const reason = error?.message ?? lastLine
54  return { retry: `lark-cli exit ${run.exitCode}: ${reason.slice(0, MAX_REASON)}` }
55}
56
57/** Pulls `data.token` (the document's own, a wiki node unwrapped) out of `lark-cli drive +inspect` JSON. */
58export function tokenOf(stdout: string): string | undefined {
59  try {
60    const token = (JSON.parse(stdout) as { data?: { token?: unknown } }).data?.token
61    return typeof token === 'string' && token ? token : undefined
62  } catch {
63    return undefined
64  }
65}
66
67/** Pulls `data.title` out of `lark-cli drive +inspect` JSON; undefined when the call failed or has none. */
68export function titleOf(stdout: string): string | undefined {
69  try {
70    const parsed = JSON.parse(stdout) as { ok?: boolean; data?: { title?: unknown } }
71    const title = parsed.ok === false ? undefined : parsed.data?.title
72    return typeof title === 'string' && title.trim() ? title.trim() : undefined
73  } catch {
74    return undefined
75  }
76}
77
hooks/docs/view.tsx 79 lines
1import type { RenderElement } from 'claude-code'
2
3import type { DocLink, DocOrigin } from '../../types'
4import type { Settings } from '../settings'
5import { DISMISS_W, ICON_W, ID_W, STATE_W, TOGGLE_W, capRows, cell } from '../ui'
6import type { Fold, Section, Ui } from '../ui'
7import { KIND_LABELS } from './links'
8
9const TOKEN_SHOWN = 8
10
11/** The document's state chip: what the session made stands out, what it only mentioned is dim. */
12const ORIGINS: Record<DocOrigin, { label: string; tone?: string; isDim?: boolean }> = {
13  created: { label: '创建', tone: 'success' },
14  mentioned: { label: '提及', isDim: true },
15}
16
17const GLYPHS: Record<string, string> = { artifact: '✦', wiki: '◈', sheets: '▦', sheet: '▦', base: '▥', bitable: '▥', slides: '▭', mindnotes: '◎', mindnote: '◎', file: '▢' }
18
19const kindLabel = (kind: string) => KIND_LABELS[kind] ?? kind
20
21/** The title; until it is known, the link text it was seen with, else the kind and the token's head. */
22export const docTitle = (d: DocLink) => d.title ?? d.label ?? `${kindLabel(d.kind)} ${d.token.slice(0, TOKEN_SHOWN)}…`
23
24/** Cells a doc row takes besides its title: glyph, kind, origin, ×, the five gaps between, and the fold toggle. */
25const ROW_OVERHEAD = ICON_W + ID_W + STATE_W + DISMISS_W + 5 + TOGGLE_W
26const MIN_TITLE_W = 10
27
28/** The settings with the title column narrowed to what `bodyColumns` leaves, so the row's controls stay on screen. */
29export const docsLayout = (settings: Settings, bodyColumns: number): Settings => ({
30  ...settings,
31  docsTitleWidth: Math.max(MIN_TITLE_W, Math.min(settings.docsTitleWidth, bodyColumns - ROW_OVERHEAD)),
32})
33
34/** The documents the band shows: not dismissed, and mentions only while `docsMentioned` is on. */
35export const visibleDocs = (list: readonly DocLink[], dismissed: readonly string[], settings: Settings): DocLink[] =>
36  list.filter(d => !dismissed.includes(d.token) && !(d.aliases ?? []).some(a => dismissed.includes(a)) && (settings.docsMentioned || d.origin === 'created'))
37
38/** `/doclinks` output: one markdown line per document, linked. */
39export function docList(list: readonly DocLink[]): string {
40  const lines = list.map(d => `- ${ORIGINS[d.origin].label} · ${kindLabel(d.kind)} · [${docTitle(d)}](${d.url})`)
41  return lines.length ? lines.join('\n') : '本会话还没有创建或提到飞书文档。'
42}
43
44/**
45 * One document on the MR rows' grid: glyph, kind under `!id`, 创建 / 提及 under the MR state, then the title, which is
46 * the link (cut to its column, whole on hover).
47 */
48function row(ui: Ui, d: DocLink, settings: Settings, dismiss: (token: string) => void): RenderElement {
49  const { Box, Button, Text } = ui
50  const o = ORIGINS[d.origin]
51  return (
52    <Box key={`doc-${d.token}`} height={1} flexWrap="nowrap" overflow="hidden" columnGap={1} alignItems="center">
53      <Box width={ICON_W} flexShrink={0}><Text color="suggestion">{GLYPHS[d.kind] ?? '▤'}</Text></Box>
54      {cell(ui, { key: `doc-kind-${d.token}`, text: kindLabel(d.kind), width: ID_W, dimColor: true })}
55      {cell(ui, { key: `doc-origin-${d.token}`, text: o.label, width: STATE_W, color: o.tone, dimColor: o.isDim })}
56      {cell(ui, { key: `doc-title-${d.token}`, text: docTitle(d), width: settings.docsTitleWidth, href: d.url })}
57      <Box flexGrow={1} />
58      <Button key={`doc-dismiss-${d.token}`} role="dismiss" plain label="×" dimColor onPress={() => dismiss(d.token)} />
59    </Box>
60  )
61}
62
63/** One row per document, newest first, capped at `docsMaxRows`; null with none. */
64export function docsSection(ui: Ui, list: readonly DocLink[], settings: Settings, dismiss: (token: string) => void, fold: Fold): Section | null {
65  if (!list.length) return null
66  const { Box, Text } = ui
67  const created = list.filter(d => d.origin === 'created').length
68  return {
69    rows: capRows(ui, 'docs', list.map(d => row(ui, d, settings, dismiss)), settings.docsMaxRows, '篇文档', fold),
70    summary: [
71      <Box key="docs-sum" columnGap={1} flexShrink={0}>
72        <Text color="suggestion">▤</Text>
73        <Text>文档 {list.length}</Text>
74        {created ? <Text dimColor>(创建 {created})</Text> : null}
75      </Box>,
76    ],
77  }
78}
79
hooks/hud.tsx 78 lines
1import type { RenderElement } from 'claude-code'
2
3import { DEFAULTS, MODULE_IDS, isSettingKey, parseSetting } from './settings'
4import type { SettingKey, Settings } from './settings'
5import { TOGGLE_W, gap } from './ui'
6import type { Section, Ui } from './ui'
7
8const MODULE_NAMES: Record<string, string> = { usage: '用量', mr: 'MR / PR', docs: '飞书文档', deploy: '云效发布' }
9
10export const HELP = [
11  '用法(`/hud` 与其他插件重名时为 `/session-hud`,其余命令同理:`/session-mr` 等):',
12  '- `/hud` 查看各模块开关与配置',
13  '- `/hud usage|mr|docs|deploy on|off` 启停模块(写入插件配置,立即生效)',
14  '- `/hud fold` / `/hud unfold` 折叠 / 展开本会话的 HUD(默认值:`/hud set collapsed on|off`)',
15  '- `/hud set <配置项> <值>` 改任一配置,如 `/hud set mrSourceWidth 30`',
16].join('\n')
17
18/** `/hud` with no arguments: each module's switch, then every other setting. */
19export function status(settings: Settings, isCollapsed: boolean): string {
20  const modules = MODULE_IDS.map(id => `- ${MODULE_NAMES[id]} \`${id}\`:${settings[id] ? '开' : '关'}`)
21  const rest = (Object.keys(DEFAULTS) as SettingKey[])
22    .filter(k => !(MODULE_IDS as readonly string[]).includes(k))
23    .map(k => `\`${k}\`=${String(settings[k])}`)
24  return [`**session-hud**(${isCollapsed ? '已折叠' : '已展开'})`, ...modules, `配置:${rest.join(' · ')}`, '', HELP].join('\n')
25}
26
27export type HudCommand =
28  | { kind: 'status' }
29  | { kind: 'fold'; isCollapsed: boolean }
30  | { kind: 'set'; key: SettingKey; value: boolean | number }
31  | { kind: 'reply'; text: string }
32
33/** `/hud` arguments → what to do. */
34export function parseHud(args: string): HudCommand {
35  const [first = '', second = '', third = ''] = args.trim().split(/\s+/)
36  if (!first) return { kind: 'status' }
37  if (first === 'fold' || first === 'unfold') return { kind: 'fold', isCollapsed: first === 'fold' }
38  const [key, text] = first === 'set' ? [second, third] : [first, second]
39  const isModule = (MODULE_IDS as readonly string[]).includes(first)
40  if (!isModule && first !== 'set') return { kind: 'reply', text: HELP }
41  if (!isSettingKey(key)) return { kind: 'reply', text: `没有配置项 \`${key}\`\n\n${HELP}` }
42  const parsed = parseSetting(key, text)
43  return 'error' in parsed ? { kind: 'reply', text: parsed.error } : { kind: 'set', key, value: parsed.value }
44}
45
46/**
47 * The band: every enabled module's rows under one fold toggle, or folded, one summary row. Without `onToggle` it is the
48 * summary alone with no control in it: what shows above a card holding the band, which owns the keys and clicks there.
49 */
50export function band(ui: Ui, sections: readonly Section[], isCollapsed: boolean, onToggle?: () => void): RenderElement {
51  const { Box, Button, Text } = ui
52  const toggle = onToggle ? (
53    <Box key="hud-toggle" width={TOGGLE_W} flexShrink={0}>
54      <Button key="hud-fold" plain dimColor label={isCollapsed ? '▸' : '▾'} onPress={onToggle} />
55    </Box>
56  ) : gap(ui, 'hud-toggle', TOGGLE_W)
57  if (isCollapsed) {
58    const parts = sections.flatMap((s, i) => (i === 0 ? s.summary : [<Text key={`hud-sep-${i}`} dimColor>·</Text>, ...s.summary]))
59    return (
60      <Box key="hud" height={1} flexWrap="nowrap" overflow="hidden" columnGap={1}>
61        {toggle}
62        {parts}
63      </Box>
64    )
65  }
66  const rows = sections.flatMap(s => s.rows)
67  return (
68    <Box key="hud" flexDirection="column">
69      {rows.map((r, i) => (
70        <Box key={`hud-row-${i}`} flexDirection="row">
71          {i === 0 ? toggle : gap(ui, `hud-pad-${i}`, TOGGLE_W)}
72          <Box flexGrow={1} flexDirection="column">{r}</Box>
73        </Box>
74      ))}
75    </Box>
76  )
77}
78
hooks/mr/codeup.ts 228 lines
1import type { Check, CheckStatus, MrView } from '../../types'
2import { LIST_MAX } from '../settings'
3
4export const API_BASE = 'https://openapi-rdc.aliyuncs.com/oapi/v1/codeup/organizations'
5export const TOKEN_VAR = 'ALIBABA_CLOUD_YUNXIAO_ACCESS_TOKEN'
6const CLOSED_STATES = new Set(['MERGED', 'CLOSED'])
7
8export type Repo = { org: string; path: string }
9
10/** git@codeup.aliyun.com:ORG/group/repo.git | https://[user@]codeup.aliyun.com/ORG/group/repo(.git) */
11export function parseRemote(url: string): Repo | null {
12  const m = url.trim().match(/^(?:git@codeup\.aliyun\.com:|(?:ssh|https?):\/\/(?:[^@/]+@)?codeup\.aliyun\.com(?::\d+)?\/)(.+?)(?:\.git)?\/?$/)
13  const path = m?.[1]
14  const org = path?.split('/')[0]
15  return path && org && path.includes('/') ? { org, path } : null
16}
17
18/** Value of the last `export ALIBABA_CLOUD_YUNXIAO_ACCESS_TOKEN=...` line in a shell profile. */
19export function tokenFromProfile(text: string): string | undefined {
20  return exportFromProfile(text, TOKEN_VAR)
21}
22
23/** Value of the last `export <name>=...` line in a shell profile, quotes and trailing comment stripped. */
24export function exportFromProfile(text: string, name: string): string | undefined {
25  const lines = text.split('\n').filter(l => new RegExp(`^\\s*export\\s+${name}=`).test(l))
26  const raw = lines.at(-1)?.replace(/^[^=]*=/, '').replace(/\s+#.*$/, '').trim()
27  const value = raw?.replace(/^(['"])(.*)\1$/, '$2')
28  return value || undefined
29}
30
31type ApiReviewer = { reviewOpinionStatus?: string }
32export type ApiChangeRequest = {
33  localId: number
34  /** `userId` is the platform user id (`platform/user`'s `id`). */
35  author?: { userId?: string }
36  createdAt?: string
37  updatedAt?: string
38  detailUrl: string
39  title: string
40  sourceBranch: string
41  targetBranch: string
42  state: string
43  hasConflict?: boolean
44  reviewers?: ApiReviewer[]
45  unResolvedCommentCount?: number
46}
47type ApiCheckItem = { itemType: string; pass?: boolean }
48export type ApiDetail = {
49  checkList?: { requirementRuleItems?: ApiCheckItem[]; needAttentionItems?: ApiCheckItem[] }
50  /** Source commits the target does not have yet. */
51  ahead?: number
52  /** Target commits the source does not have: how far the branch is behind. */
53  behind?: number
54}
55export type ApiCompare = { diffs?: { diff?: string }[] }
56
57export const isOpen = (cr: ApiChangeRequest) => !CLOSED_STATES.has(cr.state)
58
59/** An MR the session made or named, pinned to the band whatever branch its checkout is on. */
60/**
61 * An MR shown whatever branch is checked out: one the session opened (`created`), one asked for with `/mr <link>`
62 * (`tracked`), or one it came across (`mentioned`: a link in a message, an answer, a command's output; a pin without
63 * `via` is an older version's, read the same). A mentioned one shows only when it is the user's own and opened since
64 * the session began: the work of this feature, a helper session's included, not an MR looked at while investigating.
65 */
66export type MrPin = { repoPath: string; localId: number; forge?: 'github'; via?: PinVia }
67export type PinVia = 'created' | 'tracked' | 'mentioned'
68
69const MR_URL_RE = /https?:\/\/codeup\.aliyun\.com\/((?:[\w.-]+\/)+[\w.-]+?)\/change\/(\d+)/g
70/** A call that opens an MR: the devops CLI, a POST to the changeRequests API, or a push option asking Codeup to. */
71const MR_CREATE_RE = /\bcodeup-create-change-request\b|\bmerge_request\.create\b|\/changeRequests\b[^\n]*(?:-X\s*POST|--request\s+POST)|(?:-X\s*POST|--request\s+POST)[^\n]*\/changeRequests\b|\bgh\s+pr\s+create\b|\/pulls\b[^\n]*(?:-X\s*POST|--method\s+POST)/
72
73/** Every Codeup MR page linked in `text`, deduped. */
74export function findMrLinks(text: string): MrPin[] {
75  const found = new Map<string, MrPin>()
76  for (const [, repoPath, id] of text.matchAll(MR_URL_RE)) {
77    if (repoPath && id && repoPath.includes('/')) found.set(`${repoPath}!${id}`, { repoPath, localId: Number(id) })
78  }
79  return [...found.values()]
80}
81
82/** A tool call that opens an MR / PR, however it is spelled: a Codeup one is then looked up by author and time. */
83export function isMrCreation(tool: string, input: { command?: unknown }): boolean {
84  if (tool === 'Bash') return typeof input.command === 'string' && MR_CREATE_RE.test(input.command)
85  return /codeup/i.test(tool) && /create/i.test(tool) && /change|merge/i.test(tool)
86}
87
88/** The MRs in an author's newest-first list created at or after `since` (epoch ms): what one call just opened. */
89export function createdSince(list: readonly ApiChangeRequest[], since: number): MrPin[] {
90  return list.flatMap(cr => {
91    const at = Date.parse(cr.createdAt ?? '')
92    const pin = findMrLinks(cr.detailUrl)[0]
93    return pin && !Number.isNaN(at) && at >= since ? [pin] : []
94  })
95}
96
97/** Pins added, deduped, newest last. */
98/** Whether a pin shows only when it is the user's own MR, opened since the session began. */
99export const isMention = (p: MrPin): boolean => p.via !== 'created' && p.via !== 'tracked'
100
101/** The user's own MR, opened at or after `since` (epoch ms): what a mention must be to show. */
102export const isOwnSince = (author: string | undefined, me: string | undefined, createdAt: string | undefined, since: number): boolean =>
103  Boolean(author && me && author === me) && Date.parse(createdAt ?? '') >= since
104
105/** Pins added, deduped, newest last; a stronger reason (made, asked for) replaces a mention of the same MR. */
106export const addPins = (known: readonly MrPin[], added: readonly MrPin[]): MrPin[] => {
107  const key = (p: MrPin) => `${p.forge ?? 'codeup'}:${p.repoPath}!${p.localId}`
108  const upgraded = known.map(k => {
109    const better = added.find(a => key(a) === key(k) && isMention(k) && !isMention(a))
110    return better ? { ...k, via: better.via } : k
111  })
112  const fresh = added.filter(p => !known.some(k => key(k) === key(p)))
113  return [...upgraded, ...fresh].slice(-LIST_MAX)
114}
115
116/** Open MRs of the branch (newest first, capped); none open → the latest closed/merged one. */
117export function pickMrs<T extends ApiChangeRequest>(list: readonly T[], branch: string): T[] {
118  const mine = list.filter(cr => cr.sourceBranch === branch)
119  const open = mine.filter(isOpen)
120  return open.length ? open.slice(0, LIST_MAX) : mine.slice(0, 1)
121}
122
123/** +/- line counts of a Codeup compare, same as `git diff --shortstat target...source`. */
124export function diffStat(compare: ApiCompare): { additions: number; deletions: number } {
125  const lines = (compare.diffs ?? []).flatMap(d => (d.diff ?? '').split('\n'))
126  return {
127    additions: lines.filter(l => l.startsWith('+') && !l.startsWith('+++')).length,
128    deletions: lines.filter(l => l.startsWith('-') && !l.startsWith('---')).length,
129  }
130}
131
132const CHECK_LABELS: Record<string, string> = { MERGE_CONFLICT_CHECK: '合并冲突检查' }
133
134/** Merge requirements, conflict, reviews and unresolved comments as one checks list (the CI dropdown). */
135/**
136 * Where the branch stands: merged or how much is left to merge, how far it is behind its target, and whether the source
137 * branch still exists (kept while open; worth deleting once merged). `isBranchAlive` undefined: not known, not shown.
138 */
139export function branchChecks(cr: ApiChangeRequest, detail: ApiDetail | undefined, isBranchAlive: boolean | undefined): Check[] {
140  const isMerged = cr.state === 'MERGED'
141  const merge: Check = isMerged
142    ? { label: `已合入 ${cr.targetBranch}`, status: 'pass' }
143    : !isOpen(cr)
144      ? { label: '未合入(MR 已关闭)', status: 'fail' }
145      : { label: detail?.ahead === undefined ? '待合入' : `待合入 ${detail.ahead} 个提交`, status: 'pending' }
146  const behind = detail?.behind
147  const sync: Check[] = !isOpen(cr) || behind === undefined ? []
148    : [behind > 0 ? { label: `落后 ${cr.targetBranch} ${behind} 个提交`, status: 'pending' } : { label: `已同步 ${cr.targetBranch}`, status: 'pass' }]
149  const branch: Check[] = isBranchAlive === undefined ? []
150    : isOpen(cr)
151      ? [isBranchAlive ? { label: '源分支存在', status: 'pass' } : { label: '源分支已删除', status: 'fail' }]
152      : [isBranchAlive ? { label: '源分支未删除', status: 'pending' } : { label: '源分支已删除', status: 'pass' }]
153  return [merge, ...sync, ...branch]
154}
155
156export function checksOf(cr: ApiChangeRequest, detail: ApiDetail | undefined, isBranchAlive?: boolean): Check[] {
157  const rules = (detail?.checkList?.requirementRuleItems ?? []).map((it): Check => ({
158    label: CHECK_LABELS[it.itemType] ?? it.itemType,
159    status: it.pass ? 'pass' : 'fail',
160  }))
161  const attention = (detail?.checkList?.needAttentionItems ?? []).map((it): Check => ({ label: CHECK_LABELS[it.itemType] ?? it.itemType, status: 'fail' }))
162  const reviewers = cr.reviewers ?? []
163  const approved = reviewers.filter(r => r.reviewOpinionStatus === 'PASS').length
164  const reviewStatus: CheckStatus = reviewers.some(r => r.reviewOpinionStatus === 'NOT_PASS') ? 'fail' : approved === reviewers.length ? 'pass' : 'pending'
165  const reviews: Check[] = reviewers.length ? [{ label: `评审 ${approved}/${reviewers.length}`, status: reviewStatus }] : []
166  const conflict: Check[] = cr.hasConflict && !rules.some(r => r.label === CHECK_LABELS.MERGE_CONFLICT_CHECK) ? [{ label: '存在冲突', status: 'fail' }] : []
167  const unresolved = cr.unResolvedCommentCount ?? 0
168  const comments: Check[] = unresolved ? [{ label: `未解决评论 ${unresolved}`, status: 'pending' }] : []
169  return [...branchChecks(cr, detail, isBranchAlive), ...rules, ...attention, ...conflict, ...reviews, ...comments]
170}
171
172export function summarize(checks: readonly Check[]): CheckStatus | 'none' {
173  if (!checks.length) return 'none'
174  if (checks.some(c => c.status === 'fail')) return 'fail'
175  return checks.some(c => c.status === 'pending') ? 'pending' : 'pass'
176}
177
178export function toView(cr: ApiChangeRequest, repoPath: string, detail?: ApiDetail, stats?: { additions: number; deletions: number }, isBranchAlive?: boolean): MrView {
179  return {
180    id: cr.localId,
181    url: cr.detailUrl,
182    title: cr.title,
183    repo: repoLabel(repoPath),
184    source: cr.sourceBranch,
185    target: cr.targetBranch,
186    state: cr.state,
187    ...stats,
188    checks: checksOf(cr, detail, isBranchAlive),
189  }
190}
191
192/** `org/frontend/web-app` → `frontend/web-app`: group and name, without the org id. */
193export function repoLabel(path: string): string {
194  return path.split('/').slice(1).slice(-2).join('/') || path
195}
196
197/** 39230 → `39,230` */
198export function thousands(n: number): string {
199  return String(n).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
200}
201
202
203export type Tone = 'success' | 'warning' | 'error' | 'merged' | 'inactive'
204
205const STATES: Record<string, { label: string; tone: Tone; hex: string }> = {
206  UNDER_DEV: { label: '草稿', tone: 'inactive', hex: '#8c959f' },
207  UNDER_REVIEW: { label: '评审中', tone: 'success', hex: '#1a7f37' },
208  TO_BE_MERGED: { label: '待合并', tone: 'success', hex: '#1a7f37' },
209  MERGED: { label: '已合并', tone: 'merged', hex: '#8250df' },
210  CLOSED: { label: '已关闭', tone: 'error', hex: '#cf222e' },
211}
212
213export function stateOf(state: string): { label: string; tone: Tone; hex: string } {
214  return STATES[state] ?? { label: state, tone: 'inactive', hex: '#8c959f' }
215}
216
217export const CHECK_GLYPH: Record<CheckStatus | 'none', { glyph: string; tone: Tone | undefined }> = {
218  pass: { glyph: '✓', tone: 'success' },
219  fail: { glyph: '✕', tone: 'error' },
220  pending: { glyph: '○', tone: 'warning' },
221  none: { glyph: '○', tone: undefined },
222}
223
224/** The pull-request glyph, stroked in the state's color. */
225export function prIcon(hex: string): string {
226  return `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="${hex}" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="4" cy="3.5" r="1.75"/><circle cx="4" cy="12.5" r="1.75"/><circle cx="12" cy="12.5" r="1.75"/><path d="M4 5.25v5.5M12 10.75V6.5a2 2 0 0 0-2-2H7.5M9 3 7.5 4.5 9 6"/></svg>`
227}
228
hooks/mr/session.ts 53 lines
1import type { MrView, RepoView } from '../../types'
2import { LIST_MAX } from '../settings'
3
4const MERGE = '🔀'
5
6/** How the forge numbers it: GitHub `#191`, Codeup `!191`. */
7export const mrRef = (mr: Pick<MrView, 'id' | 'forge'>) => `${mr.forge === 'github' ? '#' : '!'}${mr.id}`
8
9export const mrKey = (mr: Pick<MrView, 'repo' | 'id' | 'forge'>) => `${mr.repo}${mrRef(mr)}`
10
11/** Directories a tool call works in: an edited file's folder, a Bash `cd X` or `git -C X`. */
12/** Git work on a branch: what makes a repo the session's own, beside editing its files. Reading one (log, diff, grep) does not. */
13const GIT_WORK_RE = /\bgit\b(?:\s+-C\s+\S+)?\s+(?:commit|push|checkout|switch|merge|rebase|cherry-pick|am|apply|reset|worktree\s+add)\b|\bgh\s+pr\s+create\b/
14
15/**
16 * The directories a call worked in: a file it wrote or edited, or the `cd` / `git -C` dirs of a command that does git
17 * work there. A repo only looked into while investigating (cd, ls, git log) is not the session's: its MRs stay out.
18 */
19export function dirsOf(tool: string, input: { file_path?: unknown; notebook_path?: unknown; command?: unknown }, home: string): string[] {
20  const file = typeof input.file_path === 'string' ? input.file_path : typeof input.notebook_path === 'string' ? input.notebook_path : undefined
21  if (file && tool !== 'Read') return [file.slice(0, file.lastIndexOf('/')) || '/']
22  if (tool !== 'Bash' || typeof input.command !== 'string' || !GIT_WORK_RE.test(input.command)) return []
23  const found = [...input.command.matchAll(/(?:^|[\s;&|(])(?:cd|git\s+-C)\s+("[^"]+"|'[^']+'|[^\s;&|)]+)/g)]
24  return found
25    .map(m => (m[1] ?? '').replace(/^(['"])(.*)\1$/, '$2').replace(/^~(?=\/|$)/, home))
26    .filter(d => d.startsWith('/'))
27}
28
29/** Adds dirs, deduped, newest last, capped. */
30export function rememberDirs(known: readonly string[], added: readonly string[]): string[] {
31  const merged = [...known.filter(d => !added.includes(d)), ...added]
32  return merged.slice(-LIST_MAX)
33}
34
35/** `/mr` output: one markdown line per MR, linked. */
36export function mrList(repos: readonly RepoView[], label: (state: string) => string): string {
37  const lines = repos.flatMap(r => r.mrs.map(mr =>
38    `- ${MERGE} **${r.repo}** [${mrRef(mr)} ${mr.title}](${mr.url}) · ${label(mr.state)} · \`${mr.source}\` → \`${mr.target}\``,
39  ))
40  return lines.length ? lines.join('\n') : '当前会话涉及的 Codeup 仓库分支没有 MR。'
41}
42
43const viewKey = (r: RepoView) => `${r.forge ?? 'codeup'}:${r.repo}@${r.branch}`
44
45/** A repo whose fetch failed keeps the rows it had (marked stale), so a network blip does not empty the band. */
46export function keepLastMrs(prev: readonly RepoView[], next: readonly RepoView[]): RepoView[] {
47  const last = new Map(prev.filter(r => r.mrs.length).map(r => [viewKey(r), r.mrs] as const))
48  return next.map(r => {
49    const mrs = r.error && !r.mrs.length ? last.get(viewKey(r)) : undefined
50    return mrs ? { ...r, mrs, isStale: true } : r
51  })
52}
53
hooks/mr/github.ts 166 lines
1import type { Check, CheckStatus, MrView } from '../../types'
2import { LIST_MAX } from '../settings'
3import type { MrPin } from './codeup'
4
5/** A GitHub repository: owner and name. */
6export type GhRepo = { owner: string; name: string }
7
8const CI_NAMES_SHOWN = 2
9const PR_URL_RE = /https?:\/\/github\.com\/([\w.-]+)\/([\w.-]+)\/pull\/(\d+)/g
10const CI_FAILED = new Set(['FAILURE', 'ERROR', 'TIMED_OUT', 'CANCELLED', 'ACTION_REQUIRED', 'STARTUP_FAILURE'])
11const CI_PASSED = new Set(['SUCCESS', 'NEUTRAL', 'SKIPPED'])
12/** Merge states in which an approved PR can be merged now. */
13const MERGEABLE_NOW = new Set(['CLEAN', 'HAS_HOOKS', 'UNSTABLE'])
14
15/** git@github.com:o/r.git | ssh://git@github.com/o/r | https://github.com/o/r(.git) */
16export function parseGithubRemote(url: string): GhRepo | null {
17  const m = url.trim().match(/^(?:git@github\.com:|(?:ssh|https?):\/\/(?:[^@/]+@)?github\.com(?::\d+)?\/)([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/)
18  return m?.[1] && m[2] ? { owner: m[1], name: m[2] } : null
19}
20
21/** Every GitHub PR page linked in `text`, deduped, pinned as `forge: 'github'`. */
22export function findPrLinks(text: string): MrPin[] {
23  const found = new Map<string, MrPin>()
24  for (const [, owner, name, n] of text.matchAll(PR_URL_RE)) {
25    if (owner && name && n) found.set(`${owner}/${name}#${n}`, { repoPath: `${owner}/${name}`, localId: Number(n), forge: 'github' })
26  }
27  return [...found.values()]
28}
29
30const FIELDS = `fragment F on PullRequest {
31  number url title state isDraft merged createdAt additions deletions author { login }
32  headRefName baseRefName headRef { name } headRepositoryOwner { login }
33  mergeable mergeStateStatus reviewDecision
34  commits(last: 1) { totalCount nodes { commit { statusCheckRollup { state contexts(first: 50) { nodes {
35    __typename ... on CheckRun { name status conclusion } ... on StatusContext { context state }
36  } } } } } }
37  reviewThreads(first: 100) { nodes { isResolved } }
38}`
39
40/**
41 * One query for a repo: the PRs from `branch` (newest first) and the PRs pinned by number, each aliased `n<number>`.
42 * Names reach the query as JSON strings, which GraphQL reads as its own string literals.
43 */
44export function prQuery(repo: GhRepo, branch: string | undefined, numbers: readonly number[]): string {
45  const byBranch = branch
46    ? `branch: pullRequests(headRefName: ${JSON.stringify(branch)}, first: ${LIST_MAX}, states: [OPEN, MERGED, CLOSED], orderBy: { field: CREATED_AT, direction: DESC }) { nodes { ...F } }`
47    : ''
48  const pinned = numbers.map(n => `n${n}: pullRequest(number: ${Math.trunc(n)}) { ...F }`).join('\n')
49  return `query { viewer { login } repository(owner: ${JSON.stringify(repo.owner)}, name: ${JSON.stringify(repo.name)}) {\n${byBranch}\n${pinned}\n} }\n${FIELDS}`
50}
51
52type ApiContext = { __typename?: string; name?: string; context?: string; status?: string; conclusion?: string | null; state?: string }
53
54export type ApiPr = {
55  number: number
56  url: string
57  title: string
58  state: 'OPEN' | 'MERGED' | 'CLOSED'
59  isDraft: boolean
60  merged: boolean
61  createdAt?: string
62  author?: { login: string } | null
63  additions: number
64  deletions: number
65  headRefName: string
66  baseRefName: string
67  headRef: { name: string } | null
68  headRepositoryOwner?: { login: string } | null
69  mergeable: 'MERGEABLE' | 'CONFLICTING' | 'UNKNOWN'
70  mergeStateStatus: string
71  reviewDecision: 'APPROVED' | 'CHANGES_REQUESTED' | 'REVIEW_REQUIRED' | null
72  commits: { totalCount: number; nodes: { commit: { statusCheckRollup: { state: string; contexts: { nodes: ApiContext[] } } | null } }[] }
73  reviewThreads: { nodes: { isResolved: boolean }[] }
74}
75
76/** The PRs in a query's answer: the branch's, then the pinned ones by alias, nulls (no such PR) dropped; and who asked. */
77export function prsOf(answer: unknown): { branch: ApiPr[]; pinned: ApiPr[]; viewer?: string } {
78  const data = (answer as { data?: { repository?: Record<string, unknown> | null; viewer?: { login?: string } | null } } | null)?.data
79  const repo = data?.repository ?? {}
80  const branch = ((repo.branch as { nodes?: ApiPr[] } | undefined)?.nodes ?? []).filter(Boolean)
81  const pinned = Object.entries(repo).filter(([k, v]) => k.startsWith('n') && v).map(([, v]) => v as ApiPr)
82  const viewer = data?.viewer?.login
83  return { branch, pinned, ...(viewer ? { viewer } : {}) }
84}
85
86/** Open PRs of the branch (newest first, capped); none open → the latest merged / closed one. */
87export function pickPrs(prs: readonly ApiPr[]): ApiPr[] {
88  const open = prs.filter(p => p.state === 'OPEN')
89  return open.length ? open.slice(0, LIST_MAX) : prs.slice(0, 1)
90}
91
92/** The PR's state in the MR vocabulary the rows draw: 草稿, 评审中, 待合并, 已合并, 已关闭. */
93export function prState(pr: ApiPr): string {
94  if (pr.state === 'MERGED' || pr.merged) return 'MERGED'
95  if (pr.state === 'CLOSED') return 'CLOSED'
96  if (pr.isDraft) return 'UNDER_DEV'
97  return pr.reviewDecision !== 'CHANGES_REQUESTED' && pr.reviewDecision !== 'REVIEW_REQUIRED' && MERGEABLE_NOW.has(pr.mergeStateStatus) ? 'TO_BE_MERGED' : 'UNDER_REVIEW'
98}
99
100/** The compare range that counts how far an open PR's head is behind its base (`base...owner:head`). */
101export const compareRange = (pr: ApiPr): string => `${pr.baseRefName}...${pr.headRepositoryOwner?.login ? `${pr.headRepositoryOwner.login}:` : ''}${pr.headRefName}`
102
103function ciCheck(pr: ApiPr): Check[] {
104  const rollup = pr.commits.nodes[0]?.commit.statusCheckRollup
105  if (!rollup) return []
106  const runs = rollup.contexts.nodes.map(c => ({
107    name: c.name ?? c.context ?? 'check',
108    result: c.__typename === 'StatusContext' ? (c.state === 'PENDING' || c.state === 'EXPECTED' ? 'PENDING' : c.state ?? 'PENDING') : c.status === 'COMPLETED' ? c.conclusion ?? 'PENDING' : 'PENDING',
109  }))
110  const failed = runs.filter(r => CI_FAILED.has(r.result))
111  const done = runs.filter(r => CI_PASSED.has(r.result) || CI_FAILED.has(r.result)).length
112  if (failed.length) {
113    const names = failed.slice(0, CI_NAMES_SHOWN).map(r => r.name).join('、')
114    return [{ label: `CI 失败:${names}${failed.length > CI_NAMES_SHOWN ? ` 等 ${failed.length} 项` : ''}`, status: 'fail' }]
115  }
116  if (done < runs.length) return [{ label: `CI 运行中 ${done}/${runs.length}`, status: 'pending' }]
117  return [{ label: `CI 通过(${runs.length})`, status: 'pass' }]
118}
119
120/**
121 * The same checks the Codeup rows show, from what GitHub has: merged or commits left, commits behind the base, whether
122 * the head branch still exists, conflicts, CI, the review decision and unresolved review threads.
123 */
124export function prChecks(pr: ApiPr, behind?: number): Check[] {
125  const isMerged = pr.state === 'MERGED' || pr.merged
126  const isOpen = pr.state === 'OPEN'
127  const merge: Check = isMerged
128    ? { label: `已合入 ${pr.baseRefName}`, status: 'pass' }
129    : !isOpen ? { label: '未合入(PR 已关闭)', status: 'fail' } : { label: `待合入 ${pr.commits.totalCount} 个提交`, status: 'pending' }
130  const sync: Check[] = !isOpen ? []
131    : behind !== undefined ? [behind > 0 ? { label: `落后 ${pr.baseRefName} ${behind} 个提交`, status: 'pending' } : { label: `已同步 ${pr.baseRefName}`, status: 'pass' }]
132      : pr.mergeStateStatus === 'BEHIND' ? [{ label: `落后 ${pr.baseRefName}`, status: 'pending' }] : []
133  const isAlive = pr.headRef !== null
134  const branch: Check = isOpen
135    ? isAlive ? { label: '源分支存在', status: 'pass' } : { label: '源分支已删除', status: 'fail' }
136    : isAlive ? { label: '源分支未删除', status: 'pending' } : { label: '源分支已删除', status: 'pass' }
137  const conflict: Check[] = !isOpen || pr.mergeable === 'UNKNOWN' ? []
138    : [pr.mergeable === 'CONFLICTING' ? { label: '存在冲突', status: 'fail' } : { label: '无冲突', status: 'pass' }]
139  const reviews: Record<string, Check> = {
140    APPROVED: { label: '评审通过', status: 'pass' },
141    CHANGES_REQUESTED: { label: '评审要求修改', status: 'fail' },
142    REVIEW_REQUIRED: { label: '待评审', status: 'pending' },
143  }
144  const review = pr.reviewDecision ? [reviews[pr.reviewDecision]].filter((c): c is Check => c !== undefined) : []
145  const unresolved = pr.reviewThreads.nodes.filter(t => !t.isResolved).length
146  const comments: Check[] = unresolved ? [{ label: `未解决评论 ${unresolved}`, status: 'pending' as CheckStatus }] : []
147  return [merge, ...sync, branch, ...conflict, ...ciCheck(pr), ...review, ...comments]
148}
149
150/** A PR as a row: GitHub's `#number`, `owner/repo`, its +/- and checks. */
151export function prView(pr: ApiPr, repo: GhRepo, behind?: number): MrView {
152  return {
153    id: pr.number,
154    url: pr.url,
155    title: pr.title,
156    repo: `${repo.owner}/${repo.name}`,
157    source: pr.headRefName,
158    target: pr.baseRefName,
159    state: prState(pr),
160    additions: pr.additions,
161    deletions: pr.deletions,
162    checks: prChecks(pr, behind),
163    forge: 'github',
164  }
165}
166
hooks/mr/view.tsx 183 lines
1import type { RenderElement } from 'claude-code'
2
3import type { MrView, RepoView, SessionView } from '../../types'
4import { shortError } from '../errors'
5import type { Settings } from '../settings'
6import { DISMISS_W, ICON_W, ID_W, STATE_W, TOGGLE_W, capRows, cell, foldButton, gap } from '../ui'
7import type { Fold, Section, Ui } from '../ui'
8import { CHECK_GLYPH, prIcon, stateOf, summarize, thousands } from './codeup'
9import { mrKey, mrRef } from './session'
10
11/** Fixed column widths, in cells: every MR row lines up whatever its id, state or numbers. */
12const STATS_W = 16
13const CHECKS_W = 12
14const SUMMARY_MAX = 3
15const ARROW_W = 1
16const MIN_COL_W = 6
17
18/**
19 * The settings with the repo / source / target columns narrowed to what `bodyColumns` leaves after the fixed columns,
20 * in proportion and no narrower than MIN_COL_W; the repo column is dropped when even that does not fit. So the row's
21 * controls (checks, ×) stay on screen in a narrow terminal, and every row still has the same columns.
22 */
23export function mrLayout(settings: Settings, bodyColumns: number): Settings {
24  const fixed = [ICON_W, ID_W, STATE_W, ARROW_W, settings.mrStats ? STATS_W : 0, settings.mrChecks ? CHECKS_W : 0, DISMISS_W].filter(w => w > 0)
25  const spacer = 1
26  const fit = (withRepo: boolean): Settings | null => {
27    const widths = withRepo ? [settings.mrRepoWidth, settings.mrSourceWidth, settings.mrTargetWidth] : [0, settings.mrSourceWidth, settings.mrTargetWidth]
28    const columns = fixed.length + widths.filter(w => w > 0).length + spacer
29    const room = bodyColumns - TOGGLE_W - fixed.reduce((a, b) => a + b, 0) - (columns - 1)
30    const wanted = widths.reduce((a, b) => a + b, 0)
31    const scale = Math.min(1, room / wanted)
32    const [repo = 0, src = 0, tgt = 0] = widths.map(w => (w > 0 ? Math.max(MIN_COL_W, Math.floor(w * scale)) : 0))
33    if (repo + src + tgt > room) return null
34    return { ...settings, mrRepo: withRepo, mrRepoWidth: repo || settings.mrRepoWidth, mrSourceWidth: src, mrTargetWidth: tgt }
35  }
36  return (settings.mrRepo ? fit(true) : null) ?? fit(false) ?? { ...settings, mrRepo: false, mrSourceWidth: MIN_COL_W, mrTargetWidth: MIN_COL_W }
37}
38
39export type MrActions = {
40  toggleChecks: (key: string) => void
41  dismiss: (key: string) => void
42}
43
44export type MrState = { view: SessionView | null; dismissed: readonly string[]; expanded: string | null }
45
46/**
47 * The state-coloured MR glyph. On the terminal it links to the MR like the `!id` beside it; a desktop draws it as an
48 * Svg, which no link may hold, so there the `!id` is the link.
49 */
50const icon = (ui: Ui, mr: MrView): RenderElement => {
51  const s = stateOf(mr.state)
52  if ('Svg' in ui) return <ui.Svg source={prIcon(s.hex)} alt={s.label} width={16} height={16} />
53  return <ui.Link href={mr.url}><ui.Text color={s.tone}>⑂</ui.Text></ui.Link>
54}
55
56function statsCell(ui: Ui, mr: MrView): RenderElement {
57  const { Box, Text } = ui
58  const key = `mr-stats-${mrKey(mr)}`
59  if (mr.additions === undefined || mr.deletions === undefined) return gap(ui, key, STATS_W)
60  return (
61    <Box key={key} width={STATS_W} flexShrink={0} justifyContent="flex-end" columnGap={1}>
62      <Text color="diffAdded" bold>+{thousands(mr.additions)}</Text>
63      <Text color="diffRemoved" bold>-{thousands(mr.deletions)}</Text>
64    </Box>
65  )
66}
67
68function checksCell(ui: Ui, mr: MrView, isOpen: boolean, act: MrActions): RenderElement {
69  const { Box, Button, Text } = ui
70  const key = mrKey(mr)
71  const sum = CHECK_GLYPH[summarize(mr.checks)]
72  return (
73    <Box key={`mr-checks-${key}`} minWidth={CHECKS_W} flexShrink={0}>
74      {mr.checks.length ? (
75        <Button key={`checks-${key}`} onPress={() => act.toggleChecks(key)}>
76          <Text color={sum.tone}>{sum.glyph}</Text> 检查 {isOpen ? '⌃' : '⌄'}
77        </Button>
78      ) : null}
79    </Box>
80  )
81}
82
83function checksList(ui: Ui, mr: MrView, act: MrActions): RenderElement {
84  const { Box, Text } = ui
85  const key = mrKey(mr)
86  return (
87    <Box key={`mr-checklist-${key}`} flexDirection="column" paddingLeft={ICON_W + ID_W + 2}>
88      {mr.checks.map(c => {
89        const g = CHECK_GLYPH[c.status]
90        return (
91          <Box key={`check-${key}-${c.label}`} height={1} columnGap={1}>
92            <Text color={g.tone}>{g.glyph}</Text>
93            <Text wrap="truncate-end">{c.label}</Text>
94          </Box>
95        )
96      })}
97      {foldButton(ui, `checks-fold-${key}`, () => act.toggleChecks(key))}
98    </Box>
99  )
100}
101
102/** One MR: a single fixed-height line of fixed-width columns (long names cut, full on hover), checks unfolded below. */
103function row(ui: Ui, mr: MrView, settings: Settings, isOpen: boolean, act: MrActions): RenderElement {
104  const { Box, Button, Link, Text } = ui
105  const key = mrKey(mr)
106  const s = stateOf(mr.state)
107  return (
108    <Box key={`mr-${key}`} flexDirection="column">
109      <Box height={1} flexWrap="nowrap" overflow="hidden" columnGap={1} alignItems="center">
110        <Box width={ICON_W} flexShrink={0}>{icon(ui, mr)}</Box>
111        <Box width={ID_W} flexShrink={0}><Link href={mr.url} label={mrRef(mr)} /></Box>
112        {cell(ui, { key: `mr-state-${key}`, text: s.label, width: STATE_W, color: s.tone })}
113        {settings.mrRepo ? cell(ui, { key: `mr-repo-${key}`, text: mr.repo, width: settings.mrRepoWidth, dimColor: true }) : null}
114        {cell(ui, { key: `mr-src-${key}`, text: mr.source, width: settings.mrSourceWidth, mode: 'middle', dimColor: true })}
115        <Text dimColor>→</Text>
116        {cell(ui, { key: `mr-tgt-${key}`, text: mr.target, width: settings.mrTargetWidth, mode: 'middle', dimColor: true })}
117        <Box flexGrow={1} />
118        {settings.mrStats ? statsCell(ui, mr) : null}
119        {settings.mrChecks ? checksCell(ui, mr, isOpen, act) : null}
120        <Button key={`dismiss-${key}`} role="dismiss" plain label="×" dimColor onPress={() => act.dismiss(key)} />
121      </Box>
122      {isOpen && settings.mrChecks ? checksList(ui, mr, act) : null}
123    </Box>
124  )
125}
126
127function summary(ui: Ui, mrs: readonly MrView[]): RenderElement[] {
128  const { Box, Text } = ui
129  if (!mrs.length) return [<Text key="mr-sum-err" color="warning">⑂ !</Text>]
130  const shown = mrs.slice(0, SUMMARY_MAX).map(mr => {
131    const sum = CHECK_GLYPH[summarize(mr.checks)]
132    return (
133      <Box key={`mr-sum-${mrKey(mr)}`} columnGap={1} flexShrink={0}>
134        <Text color={stateOf(mr.state).tone}>⑂{mrRef(mr)}</Text>
135        {mr.checks.length ? <Text color={sum.tone}>{sum.glyph}</Text> : null}
136      </Box>
137    )
138  })
139  const rest = mrs.length - shown.length
140  return rest > 0 ? [...shown, <Text key="mr-sum-more" dimColor>+{rest}</Text>] : shown
141}
142
143type MrError = { key: string; source: string; repo?: string; raw: string; isStale?: boolean }
144
145const errorOf = (r: RepoView): MrError[] =>
146  r.error ? [{ key: `${r.forge ?? 'codeup'}:${r.repo}`, source: r.forge === 'github' ? 'GitHub PR' : 'Codeup MR', repo: r.repo, raw: r.error, isStale: r.isStale }] : []
147
148/**
149 * One line per failed repo: where (GitHub PR / Codeup MR, the repo), a short reason, and whether it retries or kept the
150 * last rows; the raw message shows over the line on hover.
151 */
152function errorRow(ui: Ui, err: MrError): RenderElement {
153  const { Box, Text } = ui
154  const e = shortError(err.raw)
155  const next = e.isTransient ? (err.isStale ? ',显示上次结果,稍后重试' : ',稍后重试') : ''
156  const line = [err.source, err.repo, `${e.reason}${next}`].filter(Boolean).join(' · ')
157  return (
158    <Box key={`mr-err-${err.key}`} height={1} overflow="hidden">
159      <Text dimColor wrap="truncate-end">{line}</Text>
160      {e.reason === err.raw ? null : (
161        <Box position="absolute" top={0} left={0} display="none" hover={{ display: 'flex' }}>
162          <Text inverse wrap="truncate-end">{err.raw}</Text>
163        </Box>
164      )}
165    </Box>
166  )
167}
168
169/** The MR rows of the session's repos, dismissed ones left out; null with nothing to show. */
170export function mrSection(ui: Ui, state: MrState, settings: Settings, act: MrActions, fold: Fold): Section | null {
171  const v = state.view
172  if (!v) return null
173  const mrs = v.repos.flatMap(r => r.mrs).filter(mr => !state.dismissed.includes(mrKey(mr)))
174  const errors = [...(v.error ? [{ key: 'session', source: 'Codeup MR', raw: v.error }] : []), ...v.repos.flatMap(errorOf)]
175  if (!mrs.length && !errors.length) return null
176  const rows = mrs.map(mr => row(ui, mr, settings, state.expanded === mrKey(mr), act))
177  const errorRows = errors.map(err => errorRow(ui, err))
178  return {
179    rows: [...capRows(ui, 'mr', rows, settings.mrMaxRows, '个 MR', fold), ...errorRows],
180    summary: summary(ui, mrs),
181  }
182}
183