A usage panel under the prompt (model, project, context, 5-hour and weekly quota with pace warnings) with a settings toolbar, English/Chinese UI and one-click…

English | 简体中文
See your Claude Code usage at a glance, hand off long sessions in one click, and keep a pixel crab company
<img src="assets/cc-hud.gif" alt="cc-hud: a pixel-crab usage panel under the prompt" width="900">
cc-hud is a Claude Code mod. A mod is a plugin that can change what Claude Code itself draws. Install it once, and every Claude Code session (in the terminal and in the desktop app) gets:
today 21% · 20%/day), and a green ● rc while Remote Control is on[handoff]: Claude writes a self-contained prompt for continuing in a fresh session, and the mod copies it to your clipboard and saves it to a file. Click [clear & continue] (or open a new session in the same project) and the prompt is already filled in. [history] lists your earlier handoffs. At 85% context the button turns orange to remind you.Bash npm test, Read src/app.ts, …), grouped by workflow./hud lang.1. Install (run in your terminal)
claude plugin install cc-hud --marketplace kimyong6366/cc-hud
This one command adds the plugin marketplace and installs the mod.
2. Open a new claude session. The panel appears under the prompt and the crab above it.
3. Run /tui fullscreen once so you can click the panel. Claude Code saves this setting.
You don't have to do anything: the panel and the crab update on their own while you work. When you want something, click it (fullscreen only: on the default renderer the toolbar shows clicks need /tui fullscreen) or type the command, which works everywhere:
| You want to | Click (fullscreen) | Or type |
|---|---|---|
| Continue in a fresh session (long session, context filling up) | [handoff] on the toolbar, then [clear & continue] (or open a new session): the prompt is filled in for you | /hud handoff, then /clear |
| Pick up an earlier handoff | [history] on the toolbar, then a digit (1-9) | /hud history |
| See what your subagents and workflow agents are doing | +N agents in the Status cell | /hud agents |
| Switch language | [settings] → Lang | /hud lang en, /hud lang zh, /hud lang auto |
| Hide or show the crab | [settings] → Crab | /hud crab off, /hud crab on |
| Make the panel smaller or hide it | [settings] → Panel (the one-line panel keeps [settings] [handoff] at the front, so you can switch back) | /hud full, /hud compact, /hud hide, or /hud to cycle |
| Compact the conversation | compact in the Context cell (shows up at 75%) | /compact |
| Change model or effort | the model name or the effort word | /model, /effort |
| See the quota details | the 5h or Week label | /usage |
Handoff prompts are saved under ~/.claude/handoffs/<project>/, outside your repo, so a lost clipboard never loses one.
Clone the repository, then put the absolute path of the cc-hud folder in the env block of ~/.claude/settings.json. A mod loaded this way reloads in terminal sessions as soon as you save a file.
{
"env": {
"CLAUDE_CODE_PLUGIN_DIRS": "/path/to/cc-hud/cc-hud"
}
}
To try them once without changing any settings:
claude --plugin-dir ./cc-hud/cc-hud
Updating: run /plugin marketplace update cc-hud inside Claude Code, or turn on auto-update for this marketplace under /plugin → Marketplaces.
See what a mod does before you install it: a mod runs with your permissions. Clone the repository and run claude plugin validate ./cc-hud; the hooks: and calls: lines list the events it handles and what it calls.
In the terminal, cc-hud draws two things: a usage panel under the prompt, and a pixel crab that walks in a strip above it.
The panel starts with a small toolbar, [settings] [handoff] [history], followed by a 3 × 3 grid whose labels line up in columns:
| Column 1 | Column 2 | Column 3 | |
|---|---|---|---|
| Row 1 | Model + effort level | Project + git branch | Session time + cost |
| Row 2 | Context usage | 5-hour usage | Weekly usage |
| Row 3 | Status | Most-used tools | Total tokens + output (out) |
The 5-hour and weekly bars each carry a bright │ tick that marks how much of the window has passed, and a short countdown to the reset follows the bar, such as 1h54m. When the colored part runs past the tick, you are using quota faster than the clock.
Today's share sits at the right end of the toolbar: today 21% · 20%/day means you've used 21% of the weekly quota today, and your share is 20% a day. The share is what was left at your first reading of the day, divided by the days until the weekly reset (today included), so it holds steady all day. Today's number turns orange once it passes the share, and the crab starts to sweat even if the week as a whole is on pace. When room runs short it becomes today 21/20%, then 21/20%; it steps aside while [settings] is open. The first reading is shared by all your sessions that day. The day you install cc-hud starts from that moment, so it shows today 0% until you use more.
The crab above the prompt (terminal only) lives in a strip right above the input box: one blank row that keeps it apart from the conversation, then three rows of crab. It follows what Claude is doing:
| Claude is | The crab |
|---|---|
| Thinking or replying | Walks sideways, eyes on where it's going; thinking dots rise while it thinks |
| Reading or searching files | Stops and reads a page while a scan line moves |
| Writing or editing a file | Stops and taps with its right claw; each tap leaves one ink dot on the page. When the edit is done, the page flies up into the blank row and a fresh one takes its place |
| Running a command | Stops and types the command with both claws, then watches the output scroll. When it finishes, the last line turns green (red if it failed). After about 15 seconds on the same command it gets impatient: taps the desk, stamps its feet, and the screen steams |
| Searching the web | A green radar sweeps beside it while the query is typed above its head; when results come back, blips light up and the first link appears with how many more (claude.com +7) |
| Fetching a page | A page flies in from the right and loads line by line, with the URL written above; when it's fetched, the page folds away and the URL turns purple |
| Running subagents | Each running subagent, workflow agents included, adds a baby crab to the line; when it finishes, its crab waves and leaves. The status cell says how many ("+3 agents") |
| Done with a turn | Hops twice with claws up, really leaving the ground, then keeps its claws up; gold sparkles |
| Idle | Strolls a few steps now and then, blinks and looks around |
| Idle for 4 / 5 minutes | Dozes off: its eyes close into lines and its head nods / digs into the sand, puts on a nightcap and sleeps, blowing bubbles and peeking with one eye now and then. Anything that happens (work, your typing, your pointer, a quota scare) makes it pop out at once, the cap flying off |
| You type / you send | Stops and looks down at the input box / crouches, jumps up into the blank row above, lands with a squash and a puff of dust |
| At ≥ 80% context | Fades to red over about a second and sweats; at ≥ 95% pulses red smoothly |
The strip draws 13 frames a second (75 ms each), and the crabs walk half a cell at a time: each crab pixel is half a character wide, drawn with quarter-block characters (▘▝▖▗▌▐…), so walking looks twice as smooth as the text grid allows. When the big crab stops (to use a tool, to rest), it finishes its half step onto a whole cell so the props beside it stay crisp. Its legs move with its steps.
Every move has in-between frames:
The crab also has moods that follow your quota pace (pace = actual usage ÷ the usage expected for the time elapsed):
| Quota | The crab | The panel |
|---|---|---|
| Using less than the clock (pace < 0.8) | Wears sunglasses, strolls | Normal |
| Today's use is past your daily share (see the toolbar) | Sweats, walks faster | Today's number on the toolbar turns orange |
| Clearly ahead of pace, on track to run out before the reset | Sweats, walks faster | The percentage and the countdown turn red: out 40m |
| Runs out within 30 minutes, or ≥ 95% used | Panics: flings sweat up off its head, also while it works; when idle it flails its claws in turn with a red "!" beside it; scurries when walking | Same as above |
/tui fullscreen), point at the crab: it stops, waves, and holds a bubble with your usage and a tip until you move away (a sleeping crab pops out first). Point elsewhere on the strip and its eyes follow the pointer. No click needed; a click moves the keyboard focus to the strip, and Esc gives it back.[-] at the strip's right end: click it or press ctrl+x ctrl+a to fold the strip away. /hud crab off turns it off for good. In a short terminal the strip drops its blank row first, then shrinks to two rows, one row, or hides.Settings toolbar: click [settings] and the options open on the same row (they wrap onto a second row in narrower windows). Click [settings] again to close them. Each choice is remembered across sessions.
[settings] [handoff] [history] Lang [EN] 中文 Crab [on] off Panel [full] compact hide
language setting (Chinese if that's Chinese, English otherwise)./hud brings the full panel back./tui fullscreen). On the default (main-screen) renderer the terminal keeps mouse clicks for itself, so the toolbar shows a dim hint, clicks need /tui fullscreen, or type /hud handoff, in place of [history], and the /hud commands do the same jobs.Remote Control: in fullscreen, Claude Code puts its /rc label after the path in the logo at the top, which scrolls away once the conversation grows. So while Remote Control is on, a green ● rc sits at the right end of the toolbar; click it for Claude Code's Remote Control dialog (session link, QR code, Disconnect). cc-hud can't read Remote Control's state, so it goes by the /remote-control you run: it appears when you turn it on and goes away when you disconnect. It won't notice a dropped or reconnecting connection, or Remote Control started by the remoteControlAtStartup setting. On the default renderer Claude Code shows its own /rc at the bottom right, so cc-hud adds nothing there. After /reload-plugins, cc-hud has forgotten it: run /remote-control again and choose Continue.
Handoff prompts: click [handoff] (or run /hud handoff) when you want to continue in a fresh session. Claude writes a self-contained handoff prompt using the whole conversation, so the next session can pick up where you left off:
[writing handoff... 8s]. When it's done, the prompt is copied to your clipboard and saved to ~/.claude/handoffs/<project>/<YYYY-MM-DD-HHmm>.md, outside your repo, so a lost clipboard never loses it. A toast tells you where.claude session in the same project, or run /clear, and the prompt box already holds @<the handoff file> Continue from this handoff. Press Enter and Claude Code attaches the whole file.--resume), fork one, or after a compaction.@ reference, the handoff text itself is filled in.[clear & continue] appears after [handoff] once this conversation has a handoff (terminal only). Click it and cc-hud runs /clear for you (once Claude is idle), and the cleared session gets the handoff line, even if you already used that handoff once. Nothing is cleared until you click: the original session stays reachable with claude --resume.[history] on the toolbar, or /hud history, opens a pane listing this project's handoffs, newest first (up to 9). Each row shows when it was written, the branch and its first next step: `` 2 saved, newest first digit fills in · Esc closes [ 1 fill in ] [ open ] today 12:52 main ask whether to build the handoff history… [ 2 fill in ] [ open ] yesterday 18:30 feature/pay fix the refund button [ open folder ] ` Press a digit (or click fill in) and the prompt box gets that handoff's @ line; anything you had typed stays below it. open opens the file in your default editor, and open folder` shows them all.claude --resume <id> to reopen the original session), then the sections Goal, Current state, Key decisions, Files & locations, Gotchas, Next steps and Verify. Claude writes it in the language you've been using.[handoff] brackets turn orange and the crab asks 「Handoff?」 once. It asks again after the context drops below 70%, for example after a compaction./compact? /compact keeps going in the same session with a summary you don't see. A handoff is a structured file you can read, edit and reuse, and the next session starts small and clean. Hand off at a natural break, compact in the middle of a task.More practical touches
· $0.42 · 2 files changed +5 -1 · 3 tool calls (terminal only)./compact./hud agents, or click "+N agents" in the status cell, opens a side pane. It shows how long each subagent has run, how long since it last did something, and what it's doing right now: the tool plus its main argument, such as Bash npm test, Read src/app.ts or Grep "TODO" src (project paths are shown relative). Anything silent for over 5 minutes is flagged red as possibly stuck.── review-changes · 3 running · 2 done ──), with any other subagents in their own group below. They count toward "+N agents" and walk as baby crabs.Clickable parts: model name → /model, effort level → /effort, project name → opens the project folder, context → /context, 5-hour / weekly → /usage, token → a breakdown, "+N agents" → the subagent board.
The panel shrinks with the window: 81 columns or more shows the full 3 × 3 grid, 51–80 columns (such as macOS's default 80) a 3 × 2 grid, and under 51 columns a single line without the toolbar. In the terminal the panel always stays under the prompt.
| Command | What it does |
|---|---|
/hud | Cycles full → compact (one line) → hidden |
/hud agents | Opens the subagent board; Esc closes it |
/hud crab, /hud crab on, /hud crab off | Toggles the crab above the prompt (on by default) |
/hud lang en, /hud lang zh, /hud lang auto | Sets the UI language; auto follows Claude Code's language setting. /hud lang alone switches between the two |
/hud handoff | Writes a handoff prompt, copies it and saves it (same as the [handoff] chip); the next new session or /clear fills it in |
/hud history | Opens the handoff history (same as [history]); a digit fills one in, Esc closes it |
In the desktop app, the panel becomes a dedicated SVG card (crab + dashboard) above the prompt, borderless, following the light or dark theme. The desktop crab animates smoothly too:
Buttons in the desktop app. Above the card sit the app's own native buttons:
today 21% · 20%/day) and, after /remote-control, the green ● rc, the same as in the terminal.Clicks work in the desktop app without any extra setting.
<img src="assets/client.gif" alt="cc-hud in the desktop app: an SVG card above the prompt" width="900">
/cost shows. Subscribers aren't charged this amount.| Item | Notes |
|---|---|
| Claude Code | Terminal 2.1.287 or later, desktop app 2.1.286 or later (the official requirement for mods). Tested on 2.1.289 (Windows) and 2.1.290 (WSL) |
| OS | Windows: tested on Windows 11 + Windows Terminal. Linux: plugin tests and the open commands verified in WSL (Ubuntu 22.04). macOS: covered by mocked tests only; issues are welcome |
| Opening files | Windows: explorer.exe / cmd start; macOS: open; Linux: xdg-open, then gio open; in WSL, Windows' default apps first (wslview, else explorer.exe via wslpath) |
| Rendering | Clicking and hovering need fullscreen rendering (/tui fullscreen) |
| Dependencies | Node.js on your PATH (cc-hud counts tokens with a small script), git (for the branch); on Linux outside WSL, xdg-utils to open files |
CLAUDE_CONFIG_DIR, cc-hud looks for session transcripts there.Removing the marketplace also uninstalls the mod you installed from it:
claude plugin marketplace remove cc-hud
If you loaded the folder directly, remove its path from CLAUDE_CODE_PLUGIN_DIRS and restart claude.
Check and test a mod:
claude plugin validate ./cc-hud
claude plugin test ./cc-hud
/reload-plugins there.version in plugin.json after each change: cc-hud reloads itself in the desktop app when the version changes, and marketplace users only receive a new version.cc-hud/hooks/strings.ts, one table per language with identical keys (a test checks this). Add a string to both tables.│ ─ ━ ✓ and block characters. Glyphs such as • ⏱ ↻ ✦ have an ambiguous width in some terminals and overlap their neighbours.cc-hud/
hooks/register.tsx terminal panel, toolbar, handoff and events
hooks/strings.ts UI text, English and Chinese
hooks/desktop.ts desktop panel (SVG)
scripts/count-tokens.js counts a session's tokens, subagents included
assets/ GIFs for this README
See CHANGELOG.md.
MIT © 2026 kimyong6366
hooks/register.tsx 3367 lines1import type { Register } from 'claude-code'
2import { crabSvg, dashSvg, END_HOLD, END_HOLD_MS, type CrabKind, type DashData } from './desktop'
3import {
4 FRAME_MS,
5 LANE_MS,
6 SPRITE_W,
7 MINI_W,
8 DIM,
9 VALUE,
10 WARN,
11 COL,
12 mix,
13 isWide,
14 dw,
15 clip,
16 encode,
17 scenePx,
18 scenePxAll,
19 miniPx,
20 type Mood,
21 type ToolKind,
22 type Scene,
23 type Rows,
24} from './sprites'
25import { tipFit } from './sprites'
26import type { WalkProps } from './walkway' // 散步道的 Client 模块 (只取类型)
27import { S, setLang, getLang, prefOf, resolveLang, HANDOFF_PROMPT, type LangPref } from './strings'
28export { setLang } from './strings'
29export { previewLane, tipFit } from './sprites'
30export type { Mood } from './sprites'
31
32// cc-hud v0.5: 用量面板 (终端版 + 客户端版)
33//
34// 客户端 (桌面 app 的 Code 标签页): 输入框上方一张卡片, 左边 SVG 像素螃蟹 (动作由 SMIL 动画循环播放),
35// 右边 SVG 仪表盘 (自带深色底板), 下面一行可点的链接; 绘制代码在 ./desktop.ts
36//
37// 位置 (终端, v0.16 起固定): 面板在输入框下方 (画在提示行 PromptHint 里, 引擎自己的提示行保留在最下面);
38// 螃蟹在输入框正上方的横栏 (AbovePrompt) 里散步 (Client 模块 walkway.tsx; /hud crab 开关); /hud top|bottom 只回一句话
39// 螃蟹的像素画 (面板那只 + 散步道) 在 sprites.ts, hooks 和 Client 共用
40//
41// 完整版是 "3 行 x 3 列" 的对齐网格 (v0.16 起终端面板里没有螃蟹), 每列起点在三行里完全一致:
42// 模型 Opus 5.5 ▁▂▃▅▇ medium 项目 my-app main 会话 6d18h $199.91
43// 上下文 ━━━━━━━━ 14% 140k/1.0M 5小时 ━━━━━━│━━━━━━ 14% 3h05m 本周 ━━│━━━━━━━━━━ 43% 1d18h
44// 状态 ▃▅▂ 读文件 12s 工具 Bash 12 Read 4 子代理 2 个运行中
45//
46// 螃蟹动画 (全部用像素画, 不用可能宽度不一的符号):
47// 思考 -> 眼睛往右看 + 冒出思考点点 读/搜 -> 看一页纸, 扫描线上下移动
48// 改/写 -> 右钳子敲击 + 纸上逐渐写满字 跑命令 -> 双钳交替敲键盘 + 终端光标闪烁
49// 上网 -> 旋转的小地球 派子代理 / 子代理在跑 -> 散步道里跟着走的小螃蟹 (v0.14)
50// 其他工具 -> 转动的小齿轮 一轮结束 -> 举钳跳跃 + 金色闪光
51// 闲置 -> 眨眼 / 左右张望 / 偶尔挥手 5 分钟没动 -> 闭眼呼吸 + 冒泡泡
52// 上下文 >=80% -> 变红冒汗, >=95% -> 红色闪烁报警
53// 数字变化时会滚动过渡; 工作时上下文条有流光; 5小时/本周 >=90% 时用量条呼吸闪烁
54//
55// 可点击: 模型名 -> /model, 项目名 -> 打开项目文件夹, 上下文 -> /context, 5小时/本周 -> /usage
56// /hud: 完整 -> 精简(1 行) -> 隐藏 循环; /hud agents 子代理看板; /hud crab 开关散步道
57//
58// v0.12 新增:
59// 配速预警: 按 5小时/本周 窗口已过的时间算 "应该用到多少", 预计重置前会用完时, 用量条后面改成红色 "约40m后用完"
60// 螃蟹情绪: 取 5小时 和 本周 里更紧张的那个 -> 悠闲 (戴墨镜) / 正常 / 冒汗 (汗滴) / 慌张 (举钳 + "!")
61// 每轮收据: 每轮结束那行 (Crunched for 9m 6s) 后面追加 "· $0.42 · 改 3 个文件 +120 -30 · 工具 12 次"
62// 一键压缩: 上下文 >=75% 时 "上下文" 那格出现 [压缩] 按钮 -> /compact; 额度重置后弹一次 "已恢复" 提示
63// 子代理看板: /hud agents 或点状态格里的 "+N代理" -> 侧边面板, 列出每个子代理的时长/最后动静/工具/状态
64// 点档位文字 -> /effort 打开档位滑块
65// 子代理小螃蟹: 有子代理在跑时, 右侧 3 列让给小螃蟹, 干活时也看得见
66//
67// v0.13 改动:
68// 时间刻度: 5小时/本周 的用量条上画一道亮色 │, 位置 = 窗口已过时间 / 窗口长度; 彩色段超过刻度 = 用得比时间快
69// 文字缩短: 平时只写重置倒计时 "1h54m" (暗色); 会用完时百分比变红, 文字写红色的 "40m用完"
70// (v0.13.1: 预计用完的时间一定带 "用完"; 放不下就换 "4d用完", 再放不下照常写暗色的重置倒计时)
71// 完整版 5小时/本周 的附加那段从 11 列缩到 7 列, 省下的给用量条; 中等版三根条仍然一样长
72// 子代理小螃蟹: 不管几个子代理都只画一只 (3x2, 没有眼睛), 右下角慢慢跳; 数量看 "+N代理"
73//
74// v0.14 新增: 螃蟹散步道 (输入框正上方的横栏, 只在终端, 高 2 行; 只剩 1 行时画 1 行版)
75// 主会话一轮在跑 -> 大螃蟹横着走, 碰到两端掉头, 速度跟心情 (悠闲慢 / 正常 / 冒汗快 / 慌张小跑)
76// 闲着 -> 趴着偶尔眨眼; 5 分钟没动静 -> 睡着 (闭眼 + z); 一轮结束 -> 举钳跳
77// 每个运行中的子代理一只小螃蟹, 排成一队; 放不下画几只 + 暗色 "+N"; 子代理结束 -> 挥手 1.5 秒后离场
78// 主会话闲着、后台子代理还在跑 -> 大螃蟹趴着, 小螃蟹照样走; 面板里的螃蟹不再带小螃蟹
79// 气泡 (「」, 约 5 秒, 新的顶掉旧的): 搞定 3m12s / 压缩完了 / 额度刷新了 / 慢点!40m用完 (红) / 上下文快满了 / 等你点头
80// 鼠标停在横栏上 (只在全屏模式) -> 一行用量摘要 + 小贴士
81//
82// v0.16:
83// 终端面板去掉螃蟹, 网格占满整行; 各档分界前移 17 列 (完整版 81 列起, 中等版 51-80 列, 精简版不到 51 列)
84// 终端面板固定在输入框下方, 螃蟹固定在上方 (store 里存的 position 一律不读)
85// 散步道顶上加一行 "天空行" 隔开正文和螃蟹 (maxRows >=4: 天空 + 3 行版; 3: 天空 + 2 行版; 2 / 1: 没有天空行)
86// 散步道大螃蟹拿到面板螃蟹的整套动作 (scenePx): 用工具时停下做动作、道具画在右边; 在想时走, 头顶冒思考点点
87// 粒子加量 (走路同时 3-5 粒, 小跑 5-7 粒, 上限 24); 小螃蟹改成 7x4, 眼睛四周都是身体
88// 散步道整个搬进 Client 模块: 鼠标停在大螃蟹上 -> 停下举钳 + 气泡 (停下时定好), 离开约 0.5 秒后接着走
89//
90// v0.15 散步道 v2:
91// 横栏放得下 3 行就画 3 行版: 大螃蟹用面板那套 12x6 画法 (走路腿交替、眼睛看前面、会眨眼、钳子偶尔夹一下,
92// 冒汗 / 慌张 / 庆祝 / 睡觉和面板一样); 小螃蟹 9x4 排队跟着走; 不够 3 行退到 2 行 / 1 行版
93// 大螃蟹一直有动静: 主会话或子代理在跑都走; 全闲时每 20-40 秒溜达几格再东张西望; 5 分钟没有任何动静才睡
94// 打字 -> 停下低头看输入框 (停手 1.5 秒恢复); 发出消息 -> 跳一下, 落地冒尘土
95// 粒子: 走路扬尘、小跑甩汗、庆祝金色闪光、睡觉冒泡泡、小螃蟹离场冒一团 (盲文点, 只画在空格子里, 最多 16 个)
96// 悬停: 只以大螃蟹的格子为悬停区域 -> 举钳打招呼 + 旁边冒一个用量摘要气泡 (不再盖住整个顶行)
97// 子代理看板只留引擎的 x 和 Esc 关闭
98//
99// 螃蟹各种状态怎么叠 (从高到低, 只有一个能决定 "姿势"):
100// 1. 庆祝 (一轮刚结束) -> 举钳跳 + 闪光, 情绪标记暂时不画
101// 2. 工作中 (按工具做动作) -> 动作照常; 情绪只叠小标记: 冒汗 = 头边汗滴, 慌张 = 头边汗滴和红色 "!" 交替闪
102// 3. 闲置 + 慌张 -> 双钳举起 + 左右发抖 + 右侧大 "!" (慌张会把睡着的螃蟹叫醒)
103// 4. 睡觉 (5 分钟没动) -> 闭眼呼吸 + 泡泡 (冒汗时照样有汗滴)
104// 5. 闲置 -> 眨眼/张望/挥手; 悠闲时改戴墨镜 (不眨眼不张望)
105// 身体颜色永远只表示上下文 (>=80% 变红, >=95% 闪); 上下文 >=80% 也冒汗, 和情绪的汗滴是同一颗
106// 右侧 3 列 (x 12-14) 一律给道具/泡泡/闪光/大 "!" (v0.14 起子代理小螃蟹在散步道里, 不再占这里)
107
108const LAYOUTS = ['full', 'compact', 'off'] as const
109type Layout = (typeof LAYOUTS)[number]
110
111const SLEEP_AFTER_MS = 5 * 60_000
112const PRESS_GAP_MS = 800 // 双击只算一次
113const COST_MILESTONES = [5, 10, 20, 50, 100, 200, 500, 1000]
114const USAGE_URL = 'https://claude.ai/settings/usage'
115const GAP = 3
116const HPAD = 2 // 面板左右各留的空格数
117const COMPACT_AT = 75 // 上下文到这个百分比出现 [压缩] 按钮
118const HANDOFF_AT = 85 // 上下文到这个百分比: [交接] 变橙色, 螃蟹问一次「要交接吗?」(掉到 HANDOFF_REARM 以下再问)
119const HANDOFF_REARM = 70
120const HANDOFF_FILL_MS = 2 * 3600_000 // 交接写好后这么久之内, 同一个项目新开的会话 (或 /clear) 自动把它填进输入框 (只填一次)
121const STUCK_MS = 5 * 60_000 // 子代理运行中超过这么久没有工具动作 -> "可能卡住"
122const AGENTS_PANE = 'hud-agents'
123const HIST_PANE = 'hud-handoffs' // 交接历史 (v1.3)
124const HIST_MAX = 9 // 交接历史最多列几份 (数字键 1-9)
125const KEEP_ENDED = 10 // 看板里保留最近结束的子代理个数
126// 额度窗口长度
127const WINDOW_MS: Record<string, number> = { five_hour: 5 * 3600_000, seven_day: 7 * 86400_000 }
128// 窗口刚开始时外推不可靠, 已过时间不够就不算配速 (不报警、不影响情绪):
129// 5小时 = 窗口的 2% (6 分钟); 本周 = 满 1 天 (一周开头几个小时的用量起伏大, 按它外推会早早报警)
130const MIN_ELAPSED_FRAC = 0.02
131const MIN_ELAPSED_MS: Record<string, number> = { seven_day: 86400_000 }
132const PANIC_RUNOUT_MS = 30 * 60_000
133// 线性外推下 "配速 > 1" 就等于 "会在重置前用完", 稍微用快一点就报警太吵: 配速到 1.15 才算会用完
134const PACE_WARN = 1.15
135
136// ---------------- 会话状态 (模块变量) ----------------
137let layout: Layout = 'full'
138let engineWorking = false
139let turnStartedAt = 0
140let lastTurnMs = 0
141let lastTurnTools = 0
142let turnTools = 0
143let totalTools = 0
144let currentTool = ''
145let toolSeq = 0 // v1.4: 主会话第几次工具调用 (散步道认得出连着的两次)
146let toolEnd: { seq: number; ok: boolean; link?: string; hits?: number } = { seq: 0, ok: true } // v1.4: 最近结束的那次和成没成功 (散步道演收尾: 跑完变绿之类); 搜索带第一条结果和条数
147// v1.4 (第 14 项): 客户端的螃蟹按时间演 (它约 15 秒才重画一次, 动画由 SVG 自己按时间排): 这次工具什么时候开始、上次什么时候结束、是哪种
148let toolAt = 0
149let endAt = 0
150let endKind = ''
151let typeAt = 0 // 最后一次打字 (客户端低头 1.5 秒)
152let deskNap: '' | 'doze' | 'sand' = '' // 客户端上次画的是不是在睡; 从睡变醒那一下记下来演醒来
153let deskWakeAt = 0
154let deskWakeFrom: 'doze' | 'sand' = 'doze'
155const DOZE_AFTER_MS = 4 * 60_000 // 闲 4 分钟打瞌睡 (和终端一样)
156let toolArg = '' // v1.4: 最近一次主会话工具的主要参数 (抓网页的网址去掉协议、搜索词), 散步道写在天空行
157const noScheme = (u: unknown) => String(u ?? '').replace(/^[a-z][a-z0-9+.-]*:\/\//i, '')
158// 搜索结果: 第一条结果的网址 (去掉协议) 和一共几条 (results 里有的是一段段文字, 不算)
159function searchHits(result: any): { link?: string; hits: number } {
160 const items = (Array.isArray(result?.results) ? result.results : []).flatMap((r: any) => (Array.isArray(r?.content) ? r.content : []))
161 const first = items.find((c: any) => typeof c?.url === 'string')
162 return { ...(first ? { link: noScheme(first.url) } : {}), hits: items.length }
163}
164let toolCounts: Record<string, number> = {}
165let effort = ''
166let modelId = ''
167let cwd = ''
168let project = ''
169let branch = ''
170let dirty = 0
171let celebrateUntil = 0
172let lastActive = 0
173let lastPct = 0
174// 客户端横栏的宽度 (格数), 记进 store 方便按实际截图校准像素换算
175let lastDesktopCols = 0
176let savedDesktopCols = 0
177// 这个会话有没有终端在显示: 只有终端需要每 0.15 秒重画来放像素动画;
178// 只有客户端时只在数据变化时重画 (客户端的螃蟹动画由 SVG 自己播放, 频繁重画反而会闪)
179let hasTerminal = true
180// 自动更新: 客户端会话不会热重载, 发现磁盘上的版本号变了就自己执行一次 /reload-plugins
181let loadedVersion = ''
182let reloadAsked = false
183// token 统计 = 会话记录里的历史 (启动时用脚本数一遍) + 之后每次请求的实时累加
184type Tok = { input: number; output: number; cacheRead: number; cacheWrite: number }
185const zeroTok = (): Tok => ({ input: 0, output: 0, cacheRead: 0, cacheWrite: 0 })
186let tokBase: Tok = zeroTok()
187let tokLive: Tok = zeroTok()
188let tokState: 'idle' | 'counting' | 'ready' | 'failed' = 'idle'
189let transcriptPath = ''
190let resumeCtx: number | undefined
191let agentsNow = 0
192let frame = 0
193let costMilestone = 0
194let milestonePrimed = false
195let warnedContext = false
196let nightNoticed = false
197let tweening = false
198const lastPress: Record<string, number> = {}
199const shown: Record<string, number> = {}
200let mood: Mood = 'normal'
201let tick = 0 // 定时器跳了几次 (面板隐藏时 frame 不走, 额度提醒照样要查)
202
203// ---- 每轮收据 ----
204// 只算主线程的回合 (turn.start 只有主线程有; turn.complete 带 agentId 的是子代理的回合)
205// 工具次数和改文件包括子代理在这一轮里做的
206type TurnRun = { turnId: string; startedAt: number; usd0?: number; files: Set<string>; add: number; del: number; tools: number }
207type Receipt = { turnId: string; startedAt: number; completedAt: number; durationMs: number; usd?: number; files: number; add: number; del: number; tools: number; boundTo?: string }
208let turnRun: TurnRun | undefined
209// 最近一段的收据: seg = 这一段, cum = 从提问开始的累计; 只有最近一段能被配对, 一对只配一行
210type ReceiptPair = { seg: Receipt; cum: Receipt; startedAt: number; completedAt: number; boundTo?: string }
211let lastReceipt: ReceiptPair | undefined
212
213// ---- 一次提问 (v0.16.1 / v0.16.2) ----
214// Claude Code 2.1.289 起 Agent 子代理默认放到后台跑: 一次提问里主线程会结束好几段 (每段一个不带 agentId 的
215// turn.complete); 子代理结束后, 它的结果作为一次 prompt.submit 送回主线程 (origin.kind = 'task-notification'):
216// 主线程闲着时另起一段, 正在跑时塞进这一段. 最后一段结束那行引擎写的是整次提问的时长 ("Churned for 34s")
217// 怎么划分 "一次提问" (v0.16.2 起看 prompt.submit 的来源, 不看 turn.start 带不带字):
218// origin 不是 task-notification (用户回车 / 手机 / SDK / 定时任务 / 别的会话 ...) = 新提问, 上一次没做完的作废
219// task-notification = 同一次提问的延续
220// 什么时候算做完 (防抖): 主线程结束一段、没有子代理在跑之后, 先等 END_WAIT_MS; 这段时间里来了 task-notification
221// 或新的一段 (turn.start) 就取消, 接着等下一段; 什么都没来才算做完 -> 只庆祝一次, "搞定 N" 的 N = 从用户发出
222// 这条提问到最后一段结束; 有子代理已经结束、它的结果还没送回来时, 等待放宽到 END_LATE_MS
223// 已经庆祝过的提问又来了迟到的通知: 接着记账, 不再庆祝
224// 收据: 每一行 TurnDuration 同时拿去比 "这一段的时长" 和 "从提问开始的累计时长", 对上累计的显示整次提问的合计
225const END_WAIT_MS = 2000
226const END_LATE_MS = 10_000
227type Ask = {
228 startedAt: number
229 usd0?: number
230 files: Set<string>
231 add: number
232 del: number
233 tools: number
234 mainTools: number
235 segments: number
236 kidEnds: number // 这次提问里结束了几个 "会送结果回来" 的后台子代理
237 notices: number // 收到了几次 task-notification
238 lastEndAt: number // 主线程最后一段结束的时间
239 celebrated: boolean
240}
241const newAsk = (at: number, usd0?: number): Ask => ({ startedAt: at, usd0, files: new Set(), add: 0, del: 0, tools: 0, mainTools: 0, segments: 0, kidEnds: 0, notices: 0, lastEndAt: 0, celebrated: false })
242let askFromNext = false // 用户在主线程跑着时打了字 (排队): 下一个 turn.start 才算新提问开始
243let submitSinceTurn = '' // 上一个 turn.start 之后来过的 prompt.submit 的来源 ('' = 没有)
244let endToken = 0 // "提问做完" 的防抖: 每次取消 / 重排都换一个号
245let endArmed = 0 // 正在等的那个号 (0 = 没在等)
246let mainOpen = false // 主线程的一段正在跑 (只由 turn.start / turn.complete 改; 渲染时的 isWorking 不算, 免得测试或时序把它冲掉)
247let ask: Ask | undefined
248const receiptOf: Record<string, Receipt | null> = {} // TurnDuration 行的 requestId -> 收据 (null = 确定不配)
249// 子代理的 token: 只算主线程和认得的子代理 (和会话记录一样); 引擎自己的分叉 (压缩 / 记忆 ...) 的 id 谁也不认得,
250// 不算. 认出来之前先记在这里, 认出来 (SubagentStart / $.agent.list()) 时再加进去
251const tokPending = new Map<string, Tok>()
252const rowSeenAt: Record<string, number> = {} // TurnDuration 行第一次画出来的时间
253
254// ---- 额度恢复提醒 ----
255type Watch = { armed: boolean; resetAt: number }
256const watch: Record<string, Watch> = {}
257
258// ---- 子代理看板 ----
259type Kid = {
260 id: string
261 ran?: boolean // 见过它在跑 (结束时才算一次 "子代理结束")
262 endNoted?: boolean // 这次结束已经记过
263 type: string
264 desc: string
265 startedAt: number
266 lastAt: number
267 lastTool: string
268 tools: number
269 status: string
270 endedAt?: number
271 note: string
272 known: boolean // SubagentStart、agent.spawn 或 $.agent.list() 认过; 只从 tool.call 看到的 id (引擎自己的分叉) 不显示
273 listed: boolean
274 doing: string // 最后一次工具调用: 工具名 + 主要参数 (doingText)
275 wf?: { runId: string; index: number; tuid: string } // workflow 的 agent() 起的: 运行编号、第几个、起它的那次 Workflow 调用
276}
277const kids = new Map<string, Kid>()
278// workflow (v0.18): $.agent.list() 不列 workflow 的代理, 靠 agent.spawn 认; 看板按运行分组
279const wfNames = new Map<string, string>() // Workflow 工具调用的 tool_use_id -> workflow 名 (脚本 meta 里的 name)
280const wfStats = new Map<string, { ended: number }>() // 运行编号 -> 已结束几个 (按第一次见到的顺序排组)
281const wfOpened = new Set<string>() // 已经自动打开过看板的运行 (每次运行只开一次)
282
283// ---------------- 颜色 (螃蟹的颜色 COL 在 sprites.ts) ----------------
284const TRACK = 0x3f3f46
285const TICK = 0xe5e5e5 // 用量条上的时间刻度 │: 绿/黄/红的彩色段和暗色段里都看得清
286const ACCENT = '#d97757'
287const VIOLET = '#a78bfa'
288const EFFORTS = ['low', 'medium', 'high', 'xhigh', 'max']
289const EFFORT_COLOR: Record<string, string> = {
290 low: '#a1a1aa',
291 medium: '#60a5fa',
292 high: '#fbbf24',
293 xhigh: '#fb923c',
294 max: '#f87171',
295}
296
297const hex = (n: number) => '#' + n.toString(16).padStart(6, '0')
298function heat(t: number): number {
299 const g = 0x4ade80
300 const y = 0xfbbf24
301 const r = 0xf87171
302 return t < 0.6 ? mix(g, y, t / 0.6) : mix(y, r, Math.min(1, (t - 0.6) / 0.4))
303}
304
305// 外部来的名字只留安全字符, 其余换成 ?
306function safe(s: string): string {
307 let out = ''
308 for (const ch of s) {
309 const cp = ch.codePointAt(0) ?? 63
310 out += (cp >= 0x20 && cp <= 0x7e) || (cp >= 0xc0 && cp <= 0x24f) || isWide(cp) ? ch : '?'
311 }
312 return out
313}
314// 面板标签列宽 = 当前语言里最宽的标签 (中文 "上下文" 6 列, 英文 "Context" 7 列)
315const labelW = () => Math.max(...Object.values(S().label).map(dw))
316const padL = (s: string, n: number) => ' '.repeat(Math.max(0, n - dw(s))) + s
317const padR = (s: string, n: number) => s + ' '.repeat(Math.max(0, n - dw(s)))
318
319function prettyModel(id: string): string {
320 const m = id.match(/(opus|sonnet|haiku|fable)[-_ ]?(\d+)(?:[-_.](\d{1,2}))?/i)
321 if (!m) return safe(id) || '--'
322 const name = m[1][0].toUpperCase() + m[1].slice(1).toLowerCase()
323 return name + ' ' + m[2] + (m[3] ? '.' + m[3] : '') + (/\[1m\]/i.test(id) ? ' 1M' : '')
324}
325function dur(ms: number): string {
326 const s = Math.max(0, Math.round(ms / 1000))
327 if (s < 60) return s + 's'
328 const m = Math.floor(s / 60)
329 if (m < 60) return m + 'm' + String(s % 60).padStart(2, '0') + 's'
330 const h = Math.floor(m / 60)
331 if (h < 24) return h + 'h' + String(m % 60).padStart(2, '0') + 'm'
332 return Math.floor(h / 24) + 'd' + (h % 24) + 'h'
333}
334// 重置倒计时, 最多 5 列: 45m / 3h05m / 15h / 1d18h
335function durShort(ms: number): string {
336 const m = Math.max(0, Math.round(ms / 60000))
337 if (m < 60) return m + 'm'
338 const h = Math.floor(m / 60)
339 if (h < 10) return h + 'h' + String(m % 60).padStart(2, '0') + 'm'
340 if (h < 24) return h + 'h'
341 return Math.floor(h / 24) + 'd' + (h % 24) + 'h'
342}
343// 粗一点的时长, 最多 3 列: 40m / 13h / 4d (往下取整, 宁可说早); 给 "4d用完" 这种放进 7 列用
344function durCoarse(ms: number): string {
345 const m = Math.max(0, Math.floor(ms / 60000))
346 if (m < 60) return m + 'm'
347 const h = Math.floor(m / 60)
348 if (h < 24) return h + 'h'
349 return Math.floor(h / 24) + 'd'
350}
351// 大数: 999 / 12.3k / 4.56M / 345.4M / 2.26B
352function big(n: number): string {
353 if (n < 1000) return String(Math.round(n))
354 if (n < 1e6) return (n / 1e3).toFixed(n < 1e4 ? 1 : 0) + 'k'
355 if (n < 1e9) return (n / 1e6).toFixed(n < 1e7 ? 2 : 1) + 'M'
356 return (n / 1e9).toFixed(2) + 'B'
357}
358// ---------------- 配速 (纯函数) ----------------
359// 已过时间 = 窗口长度 - (重置时刻 - 现在); 应用量 = 已过 / 窗口 x 100; 配速 = 实际用量 / 应用量
360// 预计用完 = 现在 + (100 - 实际用量) / (实际用量 / 已过时间)
361// 注意: 线性外推下 "会在重置前用完" 和 "配速 > 1" 是同一件事 (100 x 已过 < 用量 x 窗口)
362// elapsedFrac = 窗口已过的比例 (0-1), 用量条上的时间刻度画在这里; 窗口刚开始 (配速不外推) 时也有
363export type Pace = { pct: number; ratio?: number; runOutIn?: number; resetIn?: number; elapsedFrac?: number; willRunOut: boolean }
364type Limit = { kind: string; percentUsed: number; resetsAt?: string }
365
366export function paceOf(l: Limit | undefined, now: number): Pace | undefined {
367 if (!l || typeof l.percentUsed !== 'number') return undefined
368 const pct = l.percentUsed
369 const win = WINDOW_MS[l.kind]
370 const at = l.resetsAt ? Date.parse(l.resetsAt) : NaN
371 if (!win || !isFinite(at)) return { pct, willRunOut: false }
372 const resetIn = Math.max(0, at - now)
373 const elapsed = Math.min(win, win - resetIn)
374 const elapsedFrac = Math.max(0, Math.min(1, elapsed / win))
375 const minElapsed = MIN_ELAPSED_MS[l.kind] ?? win * MIN_ELAPSED_FRAC
376 if (pct < 1 || elapsed < minElapsed || resetIn <= 0) return { pct, resetIn, elapsedFrac, willRunOut: false }
377 const ratio = pct / ((elapsed / win) * 100)
378 const runOutIn = pct >= 100 ? 0 : (100 - pct) / (pct / elapsed)
379 return { pct, ratio, runOutIn, resetIn, elapsedFrac, willRunOut: runOutIn < resetIn && ratio >= PACE_WARN }
380}
381
382// v1.4 (清单第 4 项): 工具栏上的「今天用了多少 · 每天能用多少」
383// 今天的起点 = 今天第一次看到的本周用量, 存在 store 的 'paceDay' (同一天开的几个会话共用); 换了一天 / 本周额度重置了就重新记
384// 每天能用 = 起点时剩下的 ÷ 从今天 0 点到重置还有几天 (算上今天, 至少 1 天), 一天之内不变; 今天用了 = 现在 - 起点
385// 今天用了超过每天能用 -> 工具栏上今天的数字变橙色, 螃蟹至少冒汗 (整周算下来还没超速时也一样)
386export type DayShare = { today: number; daily: number; over: boolean }
387const DAY_MS = 86_400_000
388export function dayShare(start: number, pct: number, resetsAt: number, dayStart: number): DayShare {
389 const days = Math.max(1, (resetsAt - dayStart) / DAY_MS)
390 const daily = Math.max(0, 100 - start) / days
391 const today = Math.max(0, pct - start)
392 return { today, daily, over: today > daily }
393}
394type PaceDay = { day: string; start: number; resetsAt: string }
395let paceDay: PaceDay | undefined
396const SAME_WINDOW_MS = 6 * 3600_000 // 重置时间差几个小时以内算同一个窗口 (防读数抖动); 额度重置时它会跳一整周
397function localDay(t: number): { key: string; start: number } {
398 const d = new Date(t)
399 return { key: `${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()}`, start: new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime() }
400}
401// 这个起点能不能接着用: 是今天的、同一个窗口、用量没有掉下去 (掉下去 = 重置过)
402function paceDayFits(p: any, key: string, week: Limit, at: number): p is PaceDay {
403 return !!p && p.day === key && typeof p.start === 'number' && typeof p.resetsAt === 'string' && Math.abs(Date.parse(p.resetsAt) - at) < SAME_WINDOW_MS && week.percentUsed >= p.start - 1
404}
405async function dayShareNow($: any, week: Limit | undefined, now: number): Promise<DayShare | undefined> {
406 if (!week || typeof week.percentUsed !== 'number' || !week.resetsAt) return undefined
407 const at = Date.parse(week.resetsAt)
408 if (!isFinite(at)) return undefined
409 const { key, start } = localDay(now)
410 if (!paceDayFits(paceDay, key, week, at)) {
411 // 记的不能用了 (新会话 / 重新加载 / 换了一天): 先看别的会话今天是不是已经记过
412 let stored: unknown
413 try {
414 stored = await $.store.get('paceDay')
415 } catch {}
416 if (paceDayFits(stored, key, week, at)) paceDay = stored
417 else {
418 paceDay = { day: key, start: week.percentUsed, resetsAt: week.resetsAt }
419 try {
420 await $.store.set('paceDay', paceDay)
421 } catch {}
422 }
423 }
424 return dayShare(paceDay!.start, week.percentUsed, at, start)
425}
426
427const MOOD_RANK: Record<Mood, number> = { chill: 0, normal: 1, sweat: 2, panic: 3 }
428function moodOne(p: Pace | undefined): Mood | undefined {
429 if (!p) return undefined
430 if (p.pct >= 95 || (p.willRunOut && (p.runOutIn ?? Infinity) <= PANIC_RUNOUT_MS)) return 'panic'
431 if (p.ratio === undefined) return 'normal'
432 if (p.ratio >= 1.2 || p.willRunOut) return 'sweat'
433 if (p.ratio < 0.8) return 'chill'
434 return 'normal'
435}
436// 今天用超了: 至少冒汗 (已经慌张的照旧)
437function withDayShare(m: Mood, d: DayShare | undefined): Mood {
438 return d?.over && MOOD_RANK[m] < MOOD_RANK.sweat ? 'sweat' : m
439}
440// 5小时 和 本周 里更紧张的那个; 两个都没有读数 (不是订阅账号) 就是 正常
441export function moodOf(...paces: Array<Pace | undefined>): Mood {
442 const ms = paces.map(moodOne).filter((m): m is Mood => !!m)
443 if (!ms.length) return 'normal'
444 return ms.reduce((a, b) => (MOOD_RANK[b] > MOOD_RANK[a] ? b : a))
445}
446
447// 用量条后面那段. 规矩: 只有一个时间 = 重置倒计时 (暗色); 预计用完的时间一定带 "用完" 两个字 (红色)
448// 会用完 -> "4d12h用完", 放不下换粗一点的 "4d用完"; 还放不下就照常写暗色的重置倒计时, 只靠红色百分比提醒
449// (以前放不下时只写红色的 "4d12h", 用户会以为是 4 天半后重置)
450function limitExtra(p: Pace | undefined, extraW: number): { text: string; warn: boolean } {
451 if (!p || p.resetIn === undefined) return { text: '', warn: false }
452 if (p.willRunOut && p.runOutIn !== undefined) {
453 for (const d of [durShort(p.runOutIn), durCoarse(p.runOutIn)]) {
454 const t = S().runOut(d)
455 if (dw(t) <= extraW) return { text: t, warn: true }
456 }
457 }
458 return { text: durShort(p.resetIn), warn: false }
459}
460// 时间刻度落在条的第几格: 已过比例 x 条长, 四舍五入, 夹在条里; 没有重置时间 -> -1 (不画)
461// 用四舍五入 (和彩色段的格数同一种取整): 用量正好跟上时间时, 彩色段的最后一格正好挨着刻度
462function tickCell(p: Pace | undefined, bw: number): number {
463 if (p?.elapsedFrac === undefined || bw <= 0) return -1
464 return Math.min(bw - 1, Math.max(0, Math.round(p.elapsedFrac * bw)))
465}
466
467function addTok(t: Tok, u: any) {
468 t.input += u?.input_tokens || 0
469 t.output += u?.output_tokens || 0
470 t.cacheRead += u?.cache_read_input_tokens || 0
471 t.cacheWrite += u?.cache_creation_input_tokens || 0
472}
473function tokSum(): Tok {
474 return {
475 input: tokBase.input + tokLive.input,
476 output: tokBase.output + tokLive.output,
477 cacheRead: tokBase.cacheRead + tokLive.cacheRead,
478 cacheWrite: tokBase.cacheWrite + tokLive.cacheWrite,
479 }
480}
481const tokTotal = (t: Tok) => t.input + t.output + t.cacheRead + t.cacheWrite
482function tok(n: number | undefined): string {
483 if (n === undefined) return '--'
484 return n >= 1e6 ? (n / 1e6).toFixed(1) + 'M' : n >= 1000 ? Math.round(n / 1000) + 'k' : String(n)
485}
486function eq(f: number): string {
487 const H = '▁▂▃▄▅▆▇'
488 const wave = [0, 2, 4, 6, 4, 2]
489 return [0, 2, 4].map(o => H[wave[(f + o) % wave.length]]).join('')
490}
491// 数字滚动过渡
492function ease(key: string, target: number | undefined): number | undefined {
493 if (target === undefined) return undefined
494 const cur = shown[key] ?? 0
495 const nxt = Math.abs(target - cur) < 0.6 ? target : cur + (target - cur) * 0.35
496 shown[key] = nxt
497 if (nxt !== target) tweening = true
498 return nxt
499}
500
501// ---------------- 工具分类 ----------------
502function toolKind(t: string): ToolKind {
503 if (!t) return 'think'
504 if (/^(Read|Grep|Glob|LS|NotebookRead)$/.test(t)) return 'read'
505 if (/^(Edit|Write|MultiEdit|NotebookEdit)$/.test(t)) return 'edit'
506 if (/^(Bash|PowerShell|BashOutput|KillShell|Monitor)$/.test(t)) return 'bash'
507 if (t === 'WebSearch') return 'search' // v1.4: 上网拆成两种 (螃蟹的动作不一样)
508 if (t === 'WebFetch') return 'fetch'
509 if (/^(Agent|Task|SendMessage)$/.test(t)) return 'agent'
510 return 'other'
511}
512// MCP 工具名是 mcp__<服务>__<工具>, 服务名本身可能带下划线 (Claude_Browser), 所以按 "__" 拆
513function mcpParts(t: string): [string, string] | undefined {
514 if (!t.startsWith('mcp__')) return undefined
515 const rest = t.slice(5)
516 const cut = rest.indexOf('__')
517 return cut > 0 ? [rest.slice(0, cut), rest.slice(cut + 2)] : [rest, '']
518}
519// 统计行里的短名: MCP 工具只留服务名
520function shortTool(t: string): string {
521 return safe(mcpParts(t)?.[0] ?? t)
522}
523function toolLabel(t: string): string {
524 if (!t) return S().thinking
525 const named = S().tool[t]
526 if (named) return named
527 const m = mcpParts(t)
528 return safe(m ? m[0] + ':' + m[1] : t)
529}
530
531// 子代理 "在做什么": 工具名 + 主要参数 (命令第一行 / 文件 / 搜索词 / 网址 ...); 项目里的路径写成相对路径
532// root = 项目根目录; 纯函数 (测试直接调). 太长由看板按列宽截断
533export function doingText(e: any, root: string): string {
534 const t = String(e?.tool ?? '')
535 const one = (v: unknown) => safe((String(v ?? '').split(/\r?\n/)[0] ?? '').replace(/\s+/g, ' ').trim())
536 const base = root.replace(/[\\/]+$/, '')
537 const rel = (v: unknown) => {
538 const p = String(v ?? '')
539 return one(base && p.length > base.length + 1 && p.startsWith(base) && /[\\/]/.test(p[base.length] ?? '') ? p.slice(base.length + 1) : p)
540 }
541 const m = mcpParts(t)
542 if (m) return safe(m[0] + ':' + m[1])
543 let arg = ''
544 switch (t) {
545 case 'Bash':
546 case 'PowerShell':
547 arg = one(e.command)
548 break
549 case 'Read':
550 case 'Edit':
551 case 'MultiEdit':
552 case 'Write':
553 arg = rel(e.file_path)
554 break
555 case 'NotebookEdit':
556 arg = rel(e.notebook_path)
557 break
558 case 'Grep':
559 arg = e.pattern !== undefined ? '"' + one(e.pattern) + '"' + (e.path ? ' ' + rel(e.path) : '') : ''
560 break
561 case 'Glob':
562 arg = one(e.pattern)
563 break
564 case 'WebFetch':
565 arg = one(String(e.url ?? '').replace(/^[a-z][a-z0-9+.-]*:\/\//i, ''))
566 break
567 case 'WebSearch':
568 arg = one(e.query)
569 break
570 case 'Agent':
571 case 'Task':
572 arg = one(e.description)
573 break
574 }
575 return safe(t) + (arg ? ' ' + arg : '')
576}
577
578// Workflow 工具调用的 workflow 名: 已保存的用 name 参数; 脚本取 meta 里的 name; 只给了脚本文件就用文件名; 都没有 -> ''
579export function workflowName(e: any): string {
580 if (typeof e?.name === 'string' && e.name.trim()) return safe(e.name.trim())
581 const script = String(e?.script ?? '')
582 const at = script.search(/\bmeta\s*=\s*\{/)
583 if (at >= 0) {
584 const close = script.indexOf('\n}', at)
585 const m = script.slice(at, close >= 0 ? close : at + 2000).match(/[{,\s]name\s*:\s*(['"`])([^'"`\n]+)\1/)
586 if (m?.[2]) return safe(m[2].trim())
587 }
588 const file = String(e?.scriptPath ?? '').split(/[\\/]/).pop() ?? ''
589 return file ? safe(file.replace(/\.(m?[jt]s)$/, '')) : ''
590}
591
592const KAOMOJI: Record<string, string> = {
593 idle: '(o_o)',
594 blink: '(-_-)',
595 work: '(o_o)/',
596 work2: '\\(o_o)',
597 hot: '(;o_o)',
598 jump: '\\(^o^)/',
599 sleep: '(-_-)zZ',
600 chill: '(B_B)',
601 panic: '\\(O_O)/!',
602}
603function kaomoji(s: Scene): string {
604 const md = s.mood ?? 'normal'
605 if (s.celebrating) return KAOMOJI.jump
606 if (s.working) return Math.floor(frame / 2) % 2 ? KAOMOJI.work : KAOMOJI.work2
607 if (md === 'panic') return KAOMOJI.panic
608 if (s.pct >= 80 || md === 'sweat') return KAOMOJI.hot
609 if (s.sleeping) return KAOMOJI.sleep
610 if (md === 'chill') return KAOMOJI.chill
611 return frame % 30 === 0 ? KAOMOJI.blink : KAOMOJI.idle
612}
613
614// ---------------- 小部件 ----------------
615function label(els: any, key: string, text: string, width: number, onPress?: () => void): any[] {
616 const { Text, Button } = els
617 const pad = ' '.repeat(Math.max(0, width - dw(text)) + 1)
618 return onPress
619 ? [<Button key={key} label={text} plain dimColor onPress={onPress} />, <Text key={key + '-p'}>{pad}</Text>]
620 : [
621 <Text key={key} color={DIM}>
622 {text + pad}
623 </Text>,
624 ]
625}
626
627// tickAt: 时间刻度画在第几格 (-1 = 不画); 那一格的 ━ 换成亮色 │, 条的总宽度不变
628function barParts(els: any, key: string, pct: number | undefined, width: number, shimmerAt: number, pulse: number, tickAt = -1): any[] {
629 const { Text } = els
630 const p = pct === undefined ? 0 : Math.max(0, Math.min(100, pct)) / 100
631 // 只用整格: 半格字符在终端里会留一道缝 (实测)
632 const full = p > 0 ? Math.max(1, Math.round(p * width)) : 0
633 // 窗口刚开始、用量只占 1 格时, 刻度和那格彩色都在第 0 格: 刻度让到第 1 格, 彩色照样看得见
634 const tick = tickAt === 0 && full === 1 && width > 1 ? 1 : tickAt
635 const cells: any[] = []
636 for (let i = 0; i < width; i++) {
637 const lit = i < full
638 let ch = '━'
639 let col = lit ? heat(i / Math.max(1, width - 1)) : TRACK
640 if (lit && pulse > 0) col = mix(col, 0xffffff, pulse)
641 if (lit && Math.abs(i - shimmerAt) < 1) col = mix(col, 0xffffff, 0.6)
642 // 刻度最后定: 不跟着呼吸 / 流光变色, 彩色段和暗色段里都一样亮
643 if (i === tick) {
644 ch = '│'
645 col = TICK
646 }
647 cells.push(
648 <Text key={key + '-c' + i} color={hex(col)}>
649 {ch}
650 </Text>,
651 )
652 }
653 return cells
654}
655
656type MeterOpts = {
657 key: string
658 label: string
659 labelW: number
660 onPress: () => void
661 labelKey?: string // 标签按钮的 key (默认 btn-<key>)
662 pct?: number
663 pctColor?: string // 百分比的颜色 (默认按用量冷暖)
664 bw: number
665 extra: string
666 extraW: number
667 extraColor?: string
668 extraParts?: any[] // 自己画附加那段 (调用方保证正好 1 + extraW 列)
669 shimmerAt: number
670 pulse: number
671 tickAt?: number // 时间刻度在第几格 (tickCell 算; 不给 = 不画)
672}
673function meter(els: any, o: MeterOpts): any[] {
674 const { Text } = els
675 const shownPct = ease(o.key, o.pct)
676 const pctText = shownPct === undefined ? '--' : Math.round(shownPct) + '%'
677 const pctColor = o.pctColor ?? (o.pct === undefined ? DIM : hex(heat(Math.min(100, o.pct) / 100)))
678 const parts = [
679 ...label(els, o.labelKey ?? 'btn-' + o.key, o.label, o.labelW, o.onPress),
680 ...barParts(els, o.key, shownPct, o.bw, o.shimmerAt, o.pulse, o.tickAt ?? -1),
681 <Text key={o.key + '-pct'} color={pctColor} bold>
682 {' ' + padL(pctText, 4)}
683 </Text>,
684 ]
685 if (o.extraW > 0 && o.extraParts) parts.push(...o.extraParts)
686 else if (o.extraW > 0) {
687 parts.push(
688 <Text key={o.key + '-x'} color={o.extraColor ?? DIM} bold={o.extraColor ? true : undefined}>
689 {' ' + padR(clip(o.extra, o.extraW), o.extraW)}
690 </Text>,
691 )
692 }
693 return parts
694}
695
696// 上下文 >= 75%: 附加那段换成 [压缩] 按钮; 放得下 (>= 10 列) 就在前面留已用 token 数
697// 宽度和原来那段完全一样: 1 + extraW 列
698function compactParts(els: any, extraW: number, used: string, onCompact: () => void): any[] {
699 const { Text, Button } = els
700 const btn = S().compact
701 const bw = dw(btn)
702 if (extraW >= bw + 6) {
703 return [
704 <Text key="cp-lead" color={DIM}>
705 {' ' + padR(clip(used, extraW - bw - 1), extraW - bw - 1) + ' '}
706 </Text>,
707 <Button key="btn-compact" label={btn} plain onPress={onCompact} />,
708 ]
709 }
710 return [<Text key="cp-lead"> </Text>, <Button key="btn-compact" label={btn} plain onPress={onCompact} />, <Text key="cp-pad">{' '.repeat(Math.max(0, extraW - dw(btn)))}</Text>]
711}
712const meterWidth = (o: { label: string; labelW: number; bw: number; extraW: number }) =>
713 Math.max(o.labelW, dw(o.label)) + 1 + o.bw + 5 + (o.extraW > 0 ? 1 + o.extraW : 0)
714
715// 档位: 五格保持彩色 (按钮不能上色), 档位文字做成按钮 -> /effort 打开档位滑块
716// room = 模型名后面还剩几列; 放不下时先把档位缩写 (medium -> med), 再放不下就只留缩写按钮不画五格
717// (以前窄的时候档位文字会被格子截掉; 现在它是点击目标, 要保证看得见)
718const EFFORT_SHORT: Record<string, string> = { low: 'low', medium: 'med', high: 'hi', xhigh: 'xhi', max: 'max' }
719function effortParts(els: any, key: string, onEffort: () => void, room = Infinity): any[] {
720 const { Button } = els
721 const word = effort ? clip(safe(effort), 6) : '--'
722 const short = EFFORT_SHORT[effort] ?? word
723 if (room < 6 + dw(word)) {
724 if (room < 6 + dw(short)) return [<Button key="btn-effort" label={short} plain onPress={onEffort} />]
725 return effortPips(els, key, short, onEffort)
726 }
727 return effortPips(els, key, word, onEffort)
728}
729function effortPips(els: any, key: string, word: string, onEffort: () => void): any[] {
730 const { Text, Button } = els
731 const i = EFFORTS.indexOf(effort)
732 const color = EFFORT_COLOR[effort] ?? DIM
733 const bars = '▁▂▃▅▇'
734 const parts: any[] = []
735 for (let k = 0; k < 5; k++) {
736 parts.push(
737 <Text key={key + '-e' + k} color={k <= i ? color : hex(TRACK)}>
738 {bars[k]}
739 </Text>,
740 )
741 }
742 parts.push(<Text key={key + '-ews'}> </Text>, <Button key="btn-effort" label={word} plain onPress={onEffort} />)
743 return parts
744}
745
746function cell(els: any, key: string, w: number, parts: any[]) {
747 const { Box } = els
748 return (
749 <Box key={key} width={w} flexShrink={0} flexDirection="row" overflow="hidden">
750 {parts}
751 </Box>
752 )
753}
754
755type Seg = { key: string; w: number; prio: number; parts: any[] }
756function fit(segs: Seg[], width: number, gap: number): Seg[] {
757 const order = segs.map((s, i) => ({ s, i })).sort((a, b) => a.s.prio - b.s.prio)
758 const keep = new Set<number>()
759 let total = 0
760 for (const { s, i } of order) {
761 const add = s.w + (keep.size ? gap : 0)
762 if (total + add <= width) {
763 keep.add(i)
764 total += add
765 }
766 }
767 return segs.filter((_, i) => keep.has(i))
768}
769
770// ---------------- 调用 $ 的动作 (必须是顶层函数) ----------------
771function redraw($: any) {
772 $.ui.invalidate('ui.render')
773}
774
775async function pressOk($: any, key: string): Promise<boolean> {
776 const now = await $.clock.now()
777 if (now - (lastPress[key] ?? 0) < PRESS_GAP_MS) return false
778 lastPress[key] = now
779 return true
780}
781
782function utf16Base64(s: string): string {
783 const bytes: number[] = []
784 for (let i = 0; i < s.length; i++) {
785 const c = s.charCodeAt(i)
786 bytes.push(c & 255, c >> 8)
787 }
788 return new Uint8Array(bytes).toBase64()
789}
790
791// ---- 跨平台 (html-shelf 里有同样一份; 带 $ 的函数必须写在本文件里, 不能 import) ----
792type OS = 'windows' | 'mac' | 'linux'
793
794// 按工作目录缓存: 同一个目录只判断一次, 换了目录 (或测试里换了系统) 再判断
795let knownOS: { key: string; os: OS } | undefined
796
797// 判断顺序: 环境变量 OS=Windows_NT (Windows 自带) → 路径像 C:\ → 有 /System/Library/CoreServices 就是 macOS → 其余按 Linux
798async function detectOS($: any, dir: string): Promise<OS> {
799 if (knownOS && knownOS.key === dir) return knownOS.os
800 let found: OS = 'linux'
801 try {
802 if ((await $.env.get('OS')) === 'Windows_NT' || /^[A-Za-z]:[\\/]/.test(dir)) found = 'windows'
803 else if (await $.fs.exists('/System/Library/CoreServices')) found = 'mac'
804 } catch {}
805 knownOS = { key: dir, os: found }
806 return found
807}
808
809const sepOf = (sys: OS) => (sys === 'windows' ? '\\' : '/')
810
811// 用户主目录: Windows 用 USERPROFILE, 其余用 HOME
812async function homeDir($: any, sys: OS): Promise<string> {
813 const h = (sys === 'windows' ? await $.env.get('USERPROFILE') : '') || (await $.env.get('HOME')) || ''
814 return h.replace(/[\\/]+$/, '')
815}
816
817// Claude Code 的配置目录: 设置了 CLAUDE_CONFIG_DIR 就用它, 否则 ~/.claude
818async function claudeDir($: any, sys: OS): Promise<string> {
819 const custom = await $.env.get('CLAUDE_CONFIG_DIR')
820 if (custom) return custom.replace(/[\\/]+$/, '')
821 const home = await homeDir($, sys)
822 return home ? home + sepOf(sys) + '.claude' : ''
823}
824
825// 跑一个命令, 退出码 0 算成功; 命令不存在会抛错, 也算失败
826async function ranOk($: any, argv: string[]): Promise<boolean> {
827 try {
828 const r = await $.process.run(argv, { timeoutMs: 10_000 })
829 return r.exitCode === 0
830 } catch {
831 return false
832 }
833}
834
835// WSL 里一般没有 Linux 的浏览器和文件管理器: 交给 Windows 那边的默认程序.
836// 先试 wslview (wslu 包), 再经 wslpath 把路径转成 Windows 写法交给 explorer.exe
837// (explorer.exe 成功也常返回 1, 所以 exit 0); 网址直接交给 explorer.exe
838function wslTries(target: string): string[][] {
839 const viaExplorer = /^[a-z][a-z0-9+.-]*:\/\//i.test(target)
840 ? ['sh', '-c', 'explorer.exe "$1"; exit 0', 'sh', target]
841 : ['sh', '-c', 'explorer.exe "$(wslpath -w "$1")"; exit 0', 'sh', target]
842 return [['wslview', target], viaExplorer]
843}
844
845// macOS / Linux: 用系统默认程序打开 (文件夹 → 文件管理器, 网址 → 浏览器); 都不行就抛错
846async function openPosix($: any, target: string, sys: OS): Promise<void> {
847 const tries: string[][] = []
848 if (sys === 'mac') tries.push(['open', target])
849 else {
850 if (await $.env.get('WSL_DISTRO_NAME')) tries.push(...wslTries(target))
851 tries.push(['xdg-open', target], ['gio', 'open', target])
852 }
853 for (const argv of tries) if (await ranOk($, argv)) return
854 throw new Error(S().toast.triedOpen(tries.map(a => (a[0] === 'sh' ? 'explorer.exe' : a[0])).join(' / ')))
855}
856// ---- 跨平台 完 ----
857
858// 项目根目录 ($.session.root): 会话开始的地方, Claude 在终端里 cd 进子目录不会改它;
859// 拿不到 (老版本引擎) 再用当前目录 ($.session.cwd)
860async function projectDir($: any): Promise<string> {
861 try {
862 const r = await $.session.root()
863 if (r) return r
864 } catch {}
865 return await $.session.cwd()
866}
867
868// Windows: Claude Code 启动子进程时把窗口设成隐藏, 直接跑 explorer.exe 打开的文件夹窗口也会是隐藏的;
869// 经 cmd 的 start 转一手, 新窗口按正常方式显示 (已在本机验证). macOS 用 open, Linux 用 xdg-open
870// 用系统默认程序打开一个文件夹或文件; 系统按项目目录认 (路径有特殊字符时 Windows 改用 PowerShell)
871async function openPath($: any, target: string) {
872 const sys = await detectOS($, cwd || (await projectDir($)))
873 if (sys !== 'windows') return openPosix($, target, sys)
874 const p = target.replace(/\//g, '\\')
875 if (/^[^&^|<>()%!"]+$/.test(p)) {
876 await $.process.run(['cmd.exe', '/d', '/c', 'start', 'cc-hud', p], { timeoutMs: 10_000 })
877 } else {
878 const script = "Start-Process -FilePath '" + p.replace(/'/g, "''") + "'"
879 await $.process.run(['powershell.exe', '-NoProfile', '-NonInteractive', '-EncodedCommand', utf16Base64(script)], {
880 timeoutMs: 20_000,
881 })
882 }
883}
884
885async function openProject($: any) {
886 if (!(await pressOk($, 'project'))) return
887 try {
888 await openPath($, cwd || (await projectDir($)))
889 $.ui.toast(S().toast.projectOpened)
890 } catch (err) {
891 $.ui.toast(S().toast.openFailed(String(err)))
892 }
893}
894
895// 新会话 / /clear: 这个项目有一份 2 小时内、还没用过的交接 -> 输入框填一行 "@<交接文件> 按这份交接继续"
896// (发送时 Claude Code 把 @ 引用的文件全文附上; 路径带空白时直接填全文). 填进去了才算用掉;
897// 有对话框挡着 / 输入框还没好就隔 1.5 秒再试几次; 一直没有输入框 (无界面运行、客户端自己画输入框) 就留给下一个会话
898type HandoffNext = { path: string; at: number; text?: string }
899async function fillHandoff($: any, tries = 0) {
900 let all: Record<string, HandoffNext> = {}
901 let root = ''
902 try {
903 all = ((await $.store.get('handoffNext')) as any) ?? {}
904 root = await projectDir($)
905 } catch {
906 return
907 }
908 const h = all[root]
909 if (!h) return
910 const drop = async () => {
911 delete all[root]
912 try {
913 await $.store.set('handoffNext', all)
914 } catch {}
915 }
916 if ((await $.clock.now()) - h.at > HANDOFF_FILL_MS) return drop()
917 let r: any
918 try {
919 r = await $.prompt.fill({ text: h.text ?? '@' + h.path + ' ' + S().handoff.fillLine, mode: 'replace' })
920 } catch {
921 return
922 }
923 if (r?.isFilled) {
924 await drop()
925 const d = new Date(h.at)
926 $.ui.toast(S().handoff.filled(pad2(d.getHours()) + ':' + pad2(d.getMinutes())), { timeoutMs: 9000 })
927 } else if (tries < 6) $.clock.after(1500, () => void fillHandoff($, tries + 1))
928}
929
930// 客户端复制不了剪贴板时: 用默认程序打开刚存的交接文件
931async function openHandoffFile($: any) {
932 if (!lastHandoff || !(await pressOk($, 'handoff-open'))) return
933 try {
934 await openPath($, lastHandoff)
935 } catch (err) {
936 $.ui.toast(S().toast.openFailed(String(err)))
937 }
938}
939
940// ---------------- 交接历史 (v1.3) ----------------
941// /hud history、工具栏 [历史]、客户端「交接历史」: 面板里列出这个项目存过的交接 (最新在上, 最多 9 份)
942// 每份: [数字 填入] [打开] 时间 分支 下一步的第一条; 填入 = 输入框里填一行 "@<文件> 按这份交接继续" (和自动填入同一行)
943
944// 这个项目的交接文件夹: <Claude 配置目录>/handoffs/<项目名> (写交接和交接历史共用); 拿不到主目录就抛错
945async function handoffDir($: any): Promise<{ dir: string; sep: string; sys: OS }> {
946 const sys = await detectOS($, cwd || (await projectDir($)))
947 const sep = sepOf(sys)
948 const base = await claudeDir($, sys)
949 if (!base) throw new Error('no home folder')
950 const slug = (project || 'project').replace(/[^A-Za-z0-9._-]+/g, '-')
951 return { dir: base + sep + 'handoffs' + sep + slug, sep, sys }
952}
953
954// 交接文件的一行摘要: 标题行里的分支, 「下一步」的第一条 (去掉编号和开头的 "Start by");
955// 没有下一步就用第一节 (目标) 的第一行
956export function handoffBrief(text: string): { branch: string; next: string } {
957 const lines = String(text ?? '').split(/\r?\n/)
958 const head = lines[0] ?? ''
959 const m = head.startsWith('#') ? /[((]([^()()]+)[))]\s*·/.exec(head) : null
960 const firstLine = (from: number) => {
961 for (let i = from; i < lines.length; i++) {
962 const l = (lines[i] ?? '').trim()
963 if (l.startsWith('#')) break
964 if (l) return l
965 }
966 return ''
967 }
968 const nextAt = lines.findIndex(l => /^#{2,3}\s*(next steps?\b|下一步)/i.test(l.trim()))
969 const goalAt = lines.findIndex(l => /^##\s/.test(l.trim()))
970 let next = nextAt >= 0 ? firstLine(nextAt + 1) : ''
971 if (!next && goalAt >= 0) next = firstLine(goalAt + 1)
972 next = next
973 .replace(/^(?:\d+[.)、]|[-*•])\s*/, '')
974 .replace(/\*\*|__/g, '')
975 .replace(/^start by\s+/i, '')
976 .replace(/[‘’]/g, "'")
977 .replace(/[“”]/g, '"')
978 .replace(/[—–]/g, '-')
979 .replace(/→/g, '->')
980 .replace(/…/g, '...')
981 .replace(/·/g, '-')
982 .replace(/\s+/g, ' ')
983 .trim()
984 return { branch: safe((m?.[1] ?? '').trim()), next: safe(next) }
985}
986
987type HistItem = { name: string; path: string; at: number; mtime: number; brief: { branch: string; next: string } }
988type HistList = { dir: string; total: number; items: HistItem[]; at: number }
989let histList: HistList | undefined // 面板每次重画都会来要: 3 秒内用上次读的 (打开面板、写完新交接时作废)
990const histBriefs = new Map<string, { mtime: number; brief: { branch: string; next: string } }>()
991
992// 文件名 YYYY-MM-DD-HHmm.md 就是写的时间; 别的名字按修改时间
993function timeOfName(name: string): number | undefined {
994 const m = /^(\d{4})-(\d\d)-(\d\d)-(\d\d)(\d\d)\.md$/i.exec(name)
995 return m ? new Date(Number(m[1]), Number(m[2]) - 1, Number(m[3]), Number(m[4]), Number(m[5])).getTime() : undefined
996}
997
998async function loadHistory($: any): Promise<HistList> {
999 const now = await $.clock.now()
1000 if (histList && now - histList.at < 3000) return histList
1001 let dir = ''
1002 let sep = '/'
1003 let entries: any[] = []
1004 try {
1005 ;({ dir, sep } = await handoffDir($))
1006 entries = await $.fs.list(dir)
1007 } catch {
1008 entries = [] // 还没写过交接: 文件夹不存在
1009 }
1010 const all = entries
1011 .filter(f => f?.kind === 'file' && /\.md$/i.test(String(f.name)))
1012 .map(f => ({ name: String(f.name), path: dir + sep + f.name, at: timeOfName(String(f.name)) ?? (Number(f.mtimeMs) || 0), mtime: Number(f.mtimeMs) || 0 }))
1013 .sort((a, b) => b.at - a.at || (a.name < b.name ? 1 : -1))
1014 const items: HistItem[] = []
1015 for (const f of all.slice(0, HIST_MAX)) {
1016 let c = histBriefs.get(f.path)
1017 if (!c || c.mtime !== f.mtime) {
1018 let brief = { branch: '', next: '' }
1019 try {
1020 brief = handoffBrief(String(await $.fs.read(f.path)))
1021 } catch {}
1022 c = { mtime: f.mtime, brief }
1023 histBriefs.set(f.path, c)
1024 }
1025 items.push({ ...f, brief: c.brief })
1026 }
1027 histList = { dir: entries.length || all.length ? dir : '', total: all.length, items, at: now }
1028 return histList
1029}
1030
1031// 时间: 今天 / 昨天 + 时分; 今年的写 月-日 时分; 更早的写年月日
1032function histWhen(at: number, now: number): string {
1033 const H = S().hist
1034 const d = new Date(at)
1035 const n = new Date(now)
1036 const day = (x: Date) => new Date(x.getFullYear(), x.getMonth(), x.getDate()).getTime()
1037 const ago = Math.round((day(n) - day(d)) / 86400_000)
1038 const t = pad2(d.getHours()) + ':' + pad2(d.getMinutes())
1039 const md = pad2(d.getMonth() + 1) + '-' + pad2(d.getDate())
1040 if (ago === 0) return H.today + ' ' + t
1041 if (ago === 1) return H.yesterday + ' ' + t
1042 return d.getFullYear() === n.getFullYear() ? md + ' ' + t : d.getFullYear() + '-' + md
1043}
1044
1045async function openHistory($: any, fromPress: boolean) {
1046 if (fromPress && !(await pressOk($, 'history'))) return
1047 histList = undefined
1048 try {
1049 const r = await $.ui.open({ id: HIST_PANE, title: S().hist.title, focus: true, closeOnEscape: true })
1050 if (r && r.isPlaced === false) $.ui.toast(S().toast.histFailed(String(r.reason ?? '')))
1051 } catch (err) {
1052 $.ui.toast(S().toast.histFailed(String(err)))
1053 }
1054}
1055
1056// 填入: 输入框里已经打的字留着, 交接那一行放在前面; 路径带空白时 @ 会断开, 填全文
1057async function fillFromHistory($: any, it: HistItem, when: string) {
1058 if (!(await pressOk($, 'hist-fill'))) return
1059 let line = '@' + it.path + ' ' + S().handoff.fillLine
1060 if (/\s/.test(it.path)) {
1061 try {
1062 line = String(await $.fs.read(it.path))
1063 } catch {}
1064 }
1065 let draft = ''
1066 try {
1067 draft = String((await $.prompt.read())?.text ?? '')
1068 } catch {}
1069 let r: any
1070 try {
1071 r = await $.prompt.fill({ text: draft.trim() ? line + '\n' + draft : line, mode: 'replace' })
1072 } catch {}
1073 if (!r?.isFilled) {
1074 $.ui.toast(S().hist.noFill, { timeoutMs: 9000 })
1075 return
1076 }
1077 // 正好是等着下一个会话自动填的那一份: 算用掉了, /clear 时不再填一次
1078 try {
1079 const root = await projectDir($)
1080 const next = ((await $.store.get('handoffNext')) as any) ?? {}
1081 if (next[root]?.path === it.path) {
1082 delete next[root]
1083 await $.store.set('handoffNext', next)
1084 }
1085 } catch {}
1086 try {
1087 await $.ui.close({ id: HIST_PANE })
1088 } catch {}
1089 $.ui.toast(S().handoff.filled(when), { timeoutMs: 9000 })
1090}
1091
1092async function openFromHistory($: any, key: string, target: string) {
1093 if (!target || !(await pressOk($, key))) return
1094 try {
1095 await openPath($, target)
1096 } catch (err) {
1097 $.ui.toast(S().toast.openFailed(String(err)))
1098 }
1099}
1100
1101// 面板: 头一行 "共 N 份" (终端右边写按键提示); 宽 (>= 72 列) 一份一行, 窄的时候下一步换到第二行; 最后 [打开文件夹]
1102async function buildHistoryPane($: any, els: any, W: number, surface: string) {
1103 const { Box, Text, Button } = els
1104 const H = S().hist
1105 const term = surface === 'terminal'
1106 const width = Math.max(30, W)
1107 const list = await loadHistory($)
1108 const now = await $.clock.now()
1109 if (!list.items.length) {
1110 return (
1111 <Box flexDirection="column">
1112 <Text key="hist-empty" color={DIM}>
1113 {H.empty}
1114 </Text>
1115 </Box>
1116 )
1117 }
1118 const count = H.count(String(list.total), String(list.items.length))
1119 const head = term && dw(count) + 3 + dw(H.keys) <= width ? padR(count, width - dw(H.keys)) + H.keys : clip(count, width)
1120 const label = (s: string) => (term ? s : cap1(s))
1121 // 终端按钮画成 "[ label ]": 比字多 4 格
1122 const fillW = term ? dw('1 ' + H.fill) + 4 : 0
1123 const openW = term ? dw(H.open) + 4 : 0
1124 const btnW = fillW + 1 + openW
1125 const whens = list.items.map(it => histWhen(it.at, now))
1126 const timeW = Math.max(...whens.map(dw))
1127 const branchW = Math.min(16, Math.max(0, ...list.items.map(it => dw(it.brief.branch))))
1128 const wide = width >= 72
1129 const rows: any[] = []
1130 list.items.forEach((it, i) => {
1131 const btns = [
1132 <Button key={'hist-fill-' + i} label={term ? i + 1 + ' ' + H.fill : label(H.fill)} hotkey={String(i + 1)} onPress={() => void fillFromHistory($, it, whens[i] ?? '')} />,
1133 <Text key={'hist-g-' + i}> </Text>,
1134 <Button key={'hist-open-' + i} label={label(H.open)} dimColor onPress={() => void openFromHistory($, 'hist-open', it.path)} />,
1135 ]
1136 const when = ' ' + padR(whens[i] ?? '', timeW)
1137 if (wide) {
1138 const branch = branchW ? ' ' + padR(clip(it.brief.branch, branchW), branchW) : ''
1139 const room = width - btnW - dw(when) - dw(branch) - 2
1140 rows.push(
1141 <Box key={'hist-row-' + i} flexDirection="row">
1142 {btns}
1143 <Text key={'hist-when-' + i} color={VALUE}>
1144 {when}
1145 </Text>
1146 <Text key={'hist-br-' + i} color={DIM}>
1147 {branch}
1148 </Text>
1149 <Text key={'hist-next-' + i} color={VALUE}>
1150 {room >= 4 ? ' ' + clip(it.brief.next, room) : ''}
1151 </Text>
1152 </Box>,
1153 )
1154 return
1155 }
1156 const roomBr = width - btnW - dw(when) - 2
1157 const branch = it.brief.branch && roomBr >= 4 ? ' ' + clip(it.brief.branch, roomBr) : ''
1158 rows.push(
1159 <Box key={'hist-row-' + i} flexDirection="row">
1160 {btns}
1161 <Text key={'hist-when-' + i} color={VALUE}>
1162 {clip(when, Math.max(0, width - btnW))}
1163 </Text>
1164 <Text key={'hist-br-' + i} color={DIM}>
1165 {branch}
1166 </Text>
1167 </Box>,
1168 )
1169 if (it.brief.next)
1170 rows.push(
1171 <Box key={'hist-row-' + i + '-2'} flexDirection="row" height={1}>
1172 <Text key={'hist-next-' + i} color={VALUE}>
1173 {' ' + clip(it.brief.next, width - 3)}
1174 </Text>
1175 </Box>,
1176 )
1177 })
1178 return (
1179 <Box flexDirection="column">
1180 <Box key="hist-head" flexDirection="row" height={1}>
1181 <Text key="hist-count" color={DIM}>
1182 {head}
1183 </Text>
1184 </Box>
1185 {rows}
1186 {list.dir ? (
1187 <Box key="hist-foot" flexDirection="row">
1188 <Button key="hist-folder" label={label(H.folder)} dimColor onPress={() => void openFromHistory($, 'hist-folder', list.dir)} />
1189 </Box>
1190 ) : null}
1191 </Box>
1192 )
1193}
1194
1195async function runSlash($: any, command: string, fallbackUrl?: string) {
1196 if (!(await pressOk($, 'cmd-' + command))) return
1197 try {
1198 await $.command.run({ command })
1199 } catch (err) {
1200 if (fallbackUrl) {hooks/desktop.ts 603 lines1// cc-hud 客户端 (桌面 app) 专用画面: 全部画成 SVG, 不依赖客户端的比例字体排版
2// - crabSvg: 像素螃蟹, 动作用 SVG 自带的 SMIL 动画循环播放 (只在状态变化时换图, 动画不会被打断)
3// - dashSvg: 3 行 x 3 列的仪表盘, 自带深色底板, 浅色/深色主题下都看得清
4// 纯函数, 不调用 $; 文字取当前界面语言 (./strings)
5import { S } from './strings'
6
7export type CrabMode = 'idle' | 'work' | 'celebrate' | 'sleep'
8export type CrabKind = 'think' | 'read' | 'edit' | 'bash' | 'web' | 'search' | 'fetch' | 'agent' | 'other' // v1.4: 终端把上网拆成 search / fetch, 客户端还画同一个地球
9export type CrabMood = 'chill' | 'normal' | 'sweat' | 'panic'
10export type CrabState = {
11 mode: CrabMode
12 kind: CrabKind
13 heat: 'ok' | 'hot' | 'crit'
14 agents: number
15 mood?: CrabMood
16 // v0.21 (桌面版也平滑): 都是 "从多久以前开始" 的毫秒数. 换图时动画接着已经过去的时间往下播, 不会从头来; 过了就不给, 图片保持不变
17 jumpMs?: number // 发出消息后过了多久 (< 750 时画那一跳)
18 celebMs?: number // 庆祝开始后过了多久 (< 1200 时连跳两下; 不给 = 刚开始)
19 heatFrom?: 'ok' | 'hot' // 身体颜色刚变: 从这个颜色渐变过来 (1 秒)
20 heatMs?: number // 颜色变了多久
21 // v1.4 (清单第 14 项, 和终端同步): 都可以不给, 不给就是原来的样子. 时间都是 "从多久以前开始" 的毫秒数, 动画按它接着播
22 toolMs?: number // 这次工具跑了多久 (跑命令: 1.35 秒后滚输出, 15 秒后不耐烦; 抓网页: 刚开始时网页飞进来); 过了 15 秒给 15000 就行
23 end?: { kind: CrabKind; ok: boolean; ms: number; hits?: number } // 刚结束的工具和结束了多久 (收尾: 变绿 / 变红 / 翻页 / 收起 / 光点); 过了 END_HOLD_MS 就不给
24 doze?: boolean // 闲 4 分钟: 打瞌睡 (mode 还是 idle)
25 sleepMs?: number // mode = sleep (钻在沙里睡) 时, 钻进去多久了; < 2400 时演下沉 + 睡帽掉下来
26 wake?: { from: 'doze' | 'sand'; ms: number } // 刚醒 (< 1000 时演蹦出来 / 抖一下, 睡帽飞走)
27 typing?: boolean // 你在打字: 低头看输入框
28}
29// 收尾撑多久 (和终端的散步道一样): 搜到了 1.8 秒, 抓完 0.9 秒, 其余 0.6 秒
30export const END_HOLD = 600
31export const END_HOLD_MS: Partial<Record<CrabKind, number>> = { search: 1800, fetch: 900 }
32
33// warn: 预计重置前用完, 百分比和说明文字画成红色
34// tick: 窗口已过的比例 (0-1), 条上画一根亮色细竖线 (时间刻度); 不给就不画 (上下文那根没有)
35export type Meter = { pct?: number; extra: string; warn?: boolean; tick?: number }
36export type DashData = {
37 model: string
38 effort: string
39 project: string
40 branch: string
41 session: string
42 cost: string
43 ctx: Meter
44 five: Meter
45 week: Meter
46 status: { text: string; tone: 'work' | 'agents' | 'idle' }
47 tools: string
48 tokenTotal: string
49 tokenOutput: string
50}
51
52const C = {
53 body: '#d97757',
54 hot: '#e5484d',
55 eye: '#1c1917',
56 eyeShut: '#7c3f2c',
57 eyeHalf: '#4b3127', // 眨眼的半闭 (身体色和眼睛色之间)
58 sweat: '#60a5fa',
59 spark: '#facc15',
60 bubble: '#a1a1aa',
61 paper: '#d4d4d8',
62 ink: '#52525b',
63 scan: '#60a5fa',
64 term: '#3f3f46',
65 cursor: '#4ade80',
66 sea: '#3b82f6',
67 land: '#4ade80',
68 gear: '#a1a1aa',
69 shades: '#09090b',
70 bridge: '#52525b',
71 alarm: '#ef4444',
72 kid: '#f2a07b', // 小螃蟹浅一号, 和大螃蟹分得开
73 kidLeg: '#a4553d',
74 warn: '#f87171',
75 tick: '#e5e5e5', // 时间刻度: 彩色段和暗色轨道上都看得清
76 // v1.4 (和终端同一套颜色)
77 radarRing: '#15803d', // 搜索的雷达环
78 radarSweep: '#4ade80', // 扫过去的亮点 / 光点
79 radarTrail: '#166534', // 亮点后面的尾巴
80 out: '#a1a1aa', // 终端里滚的输出、热气
81 sand: '#c8a96a', // 睡觉钻的沙堆
82 cap: '#4f46e5', // 睡帽
83 brim: '#e4e4e7', // 帽檐
84 pom: '#fafafa', // 绒球
85 glint: '#fafafa', // 墨镜反光
86}
87const EFFORTS = ['low', 'medium', 'high', 'xhigh', 'max']
88const EFFORT_COLOR: Record<string, string> = { low: '#a1a1aa', medium: '#60a5fa', high: '#fbbf24', xhigh: '#fb923c', max: '#f87171' }
89
90export function esc(s: string): string {
91 return s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, ''')
92}
93
94// ---------------- 螃蟹 ----------------
95const px = (x: number, y: number, fill: string, w = 1, h = 1) => `<rect x="${x}" y="${y}" width="${w}" height="${h}" fill="${fill}"/>`
96// 离散切换的 SMIL 动画 (姿势本身要清楚的地方用: 钳子、眼睛、腿)
97const steps = (attr: string, values: string[], dur: number, begin = 0) =>
98 `<animate attributeName="${attr}" values="${values.join(';')}" keyTimes="${values.map((_, i) => (i / values.length).toFixed(3)).join(';')}" dur="${dur}s" begin="${begin}s" calcMode="discrete" repeatCount="indefinite"/>`
99const moves = (values: string[], dur: number, begin = 0) =>
100 `<animateTransform attributeName="transform" type="translate" values="${values.join(';')}" keyTimes="${values.map((_, i) => (i / values.length).toFixed(3)).join(';')}" dur="${dur}s" begin="${begin}s" calcMode="discrete" repeatCount="indefinite"/>`
101
102// 平滑的 SMIL 动画 (v0.21): 值之间连续变化. spline = 起落有缓动, linear = 匀速; once = 只播一次, 停在最后一个值
103// begin 可以是负数: 动画当作已经播了这么久 (换图时接着播)
104const EASE = '0.42 0 0.58 1'
105const keyTimes = (n: number) => Array.from({ length: n }, (_, i) => +(i / (n - 1)).toFixed(3)).join(';')
106const sec = (s: number) => +s.toFixed(3)
107type GlideOpts = { begin?: number; linear?: boolean; once?: boolean }
108const glideAttrs = (values: string[], dur: number, o: GlideOpts) =>
109 `values="${values.join(';')}" keyTimes="${keyTimes(values.length)}" calcMode="${o.linear ? 'linear' : 'spline'}"` +
110 (o.linear ? '' : ` keySplines="${Array(values.length - 1).fill(EASE).join(';')}"`) +
111 ` dur="${dur}s" begin="${sec(o.begin ?? 0)}s" ${o.once ? 'fill="freeze"' : 'repeatCount="indefinite"'}`
112const glide = (attr: string, values: string[], dur: number, o: GlideOpts = {}) => `<animate attributeName="${attr}" ${glideAttrs(values, dur, o)}/>`
113const glideMove = (values: string[], dur: number, o: GlideOpts = {}) => `<animateTransform attributeName="transform" type="translate" ${glideAttrs(values, dur, o)}/>`
114// v1.4: 某一刻出现 / 消失 (秒, 从这张图开始显示算; <= 0 就是一开始). later = 先藏着, 到时候再出来
115const showAt = (s: number) => `<set attributeName="opacity" to="1" begin="${sec(Math.max(0, s))}s" fill="freeze"/>`
116const hideAt = (s: number) => `<set attributeName="opacity" to="0" begin="${sec(Math.max(0, s))}s" fill="freeze"/>`
117const later = (s: number, body: string, cls = '') => (s <= 0 ? (cls ? `<g class="${cls}">${body}</g>` : body) : `<g${cls ? ` class="${cls}"` : ''} opacity="0">${showAt(s)}${body}</g>`)
118
119// 钳子: 平伸 (第 2 行两格) / 半举 (斜着: 贴身那格在第 2 行, 钳尖在第 1 行) / 举起 (竖着, 第 0-1 行)
120// v1.4: 耷拉 (打瞌睡, 比平伸低一行)
121type Arm = 'out' | 'mid' | 'up' | 'dn'
122function arm(side: 'L' | 'R', pose: Arm, fill: string): string {
123 if (side === 'L') return pose === 'out' ? px(0, 2, fill, 2, 1) : pose === 'dn' ? px(0, 3, fill, 2, 1) : pose === 'mid' ? px(1, 2, fill) + px(0, 1, fill) : px(0, 0, fill, 1, 2)
124 return pose === 'out' ? px(10, 2, fill, 2, 1) : pose === 'dn' ? px(10, 3, fill, 2, 1) : pose === 'mid' ? px(10, 2, fill) + px(11, 1, fill) : px(11, 0, fill, 1, 2)
125}
126// 按顺序循环的钳子 (每个姿势占 dur / seq.length 秒; 离散切换, 姿势本身清楚)
127function armCycle(side: 'L' | 'R', seq: Arm[], dur: number, fill: string): string {
128 return [...new Set(seq)].map(p => `<g>${steps('opacity', seq.map(q => (q === p ? '1' : '0')), dur)}${arm(side, p, fill)}</g>`).join('')
129}
130// 敲钳子 / 敲键盘: 平伸 -> 半举 -> 举起 -> 半举 (300ms 一个来回); 闲着挥手: 12 秒里挥两下, 举起和放下都经过半举
131const TAP: Arm[] = ['out', 'mid', 'up', 'mid']
132const WAVE: Arm[] = [...Array<Arm>(36).fill('out'), 'mid', 'up', 'up', 'mid', 'out', 'mid', 'up', 'up', 'mid', 'out', 'out', 'out']
133// 眨眼 (4.5 秒一次): 半闭 -> 闭 -> 半闭, 每格 75ms
134const BLINK = Array.from({ length: 60 }, (_, i) => (i === 58 ? 'shut' : i === 57 || i === 59 ? 'half' : 'open'))
135// 跳 (发出消息, 750ms) / 庆祝连跳 (每下 600ms): 整只上下挪的轨迹, 正数往下 (蹲), 负数往上 (离地, 进顶上留出的那一行)
136const JUMP_PATH = ['0 1', '0 1', '0 -1', '0 -2', '0 -2', '0 -2', '0 -1', '0 1', '0 0', '0 0', '0 0']
137const HOP_PATH = ['0 0', '0 1', '0 -1', '0 -2', '0 -2', '0 -1', '0 1', '0 0']
138const HOPS_MS = 1200 // 连跳两下
139
140// tile: 客户端里给螃蟹配一块和仪表盘同色同高的深色底板, 也挡住小窗框可能的白底
141// 子代理小螃蟹: 客户端可以用细像素, 画一只 6x5 的正面小螃蟹 (终端版只有 3 列宽, 画不了这么细)
142// C = 钳子和身体 (浅一号的橙色, 和大螃蟹分得开), E = 眼睛 (深色, 四周都是身体), L = 腿; 腿两帧交替 = 在走
143// 1-2 只: 每个细像素 0.5 单位 (整只 3 x 2.5); 3 只: 0.4 单位 (整只 2.4 x 2), 竖着排在右侧 x 13-16
144const KID_BODY = ['C....C', 'CC..CC', 'CECCEC', '.CCCC.']
145const KID_LEGS = ['L.LL.L', '.L..L.']
146function kidSvg(x: number, y: number, u: number, phase: number, hop: string[] | null): string {
147 const paint = (rows: string[], y0: number) => {
148 let out = ''
149 rows.forEach((row, dy) => {
150 for (let dx = 0; dx < row.length; dx++) {
151 const ch = row[dx]
152 const fill = ch === 'C' ? C.kid : ch === 'E' ? C.eye : ch === 'L' ? C.kidLeg : ''
153 if (fill) out += `<rect x="${+(x + dx * u).toFixed(2)}" y="${+(y + (y0 + dy) * u).toFixed(2)}" width="${u}" height="${u}" fill="${fill}"/>`
154 }
155 })
156 return out
157 }
158 const a = phase % 2 ? ['0', '1'] : ['1', '0']
159 const b = a.map(v => (v === '1' ? '0' : '1'))
160 const legs = `<g>${steps('opacity', a, 0.5)}${paint([KID_LEGS[0]], 4)}</g><g>${steps('opacity', b, 0.5)}${paint([KID_LEGS[1]], 4)}</g>`
161 return `<g class="kid">${hop ? glideMove([...hop, hop[0] ?? '0 0'], 1, { begin: -phase * 0.17 }) : ''}${paint(KID_BODY, 0)}${legs}</g>`
162}
163
164export function crabSvg(st: CrabState, scale = 6, tile?: { w: number; h: number }): string {
165 // 身体色用 currentColor: 整只螃蟹 (身体、钳子、腿) 跟着外层 <g color> 一起变 (渐渐变红 / 一明一暗)
166 const color = st.heat === 'ok' ? C.body : C.hot
167 const body = 'currentColor'
168 let colorAnim = ''
169 if (st.heat === 'crit') colorAnim = glide('color', [C.hot, C.body, C.hot], 0.6) // 上下文 >=95%: 平滑地一明一暗
170 else if (st.heatFrom && st.heatMs !== undefined && st.heatMs < 1000) {
171 const from = st.heatFrom === 'ok' ? C.body : C.hot
172 if (from !== color) colorAnim = `<animate attributeName="color" from="${from}" to="${color}" dur="1s" begin="${sec(-st.heatMs / 1000)}s" fill="freeze"/>`
173 }
174 const parts: string[] = []
175 const fx: string[] = []
176 const mood = st.mood ?? 'normal'
177 const working = st.mode === 'work'
178 const nKids = Math.min(3, Math.max(0, st.agents))
179 const zoneFree = nKids === 0 // 右侧有子代理时让给小螃蟹 (和终端版同一套规则)
180 // 闲置 (或睡着) 时慌张: 双钳举起 + 左右发抖, 睡着的也叫醒
181 const panicIdle = mood === 'panic' && (st.mode === 'idle' || st.mode === 'sleep')
182 const mode: CrabMode = panicIdle ? 'idle' : st.mode
183 // v1.4 (和终端同步): 打瞌睡 / 钻沙睡觉 / 刚醒 / 打字低头
184 const doze = mode === 'idle' && !!st.doze
185 const sand = mode === 'sleep'
186 const typing = mode === 'idle' && !doze && !!st.typing
187 const chill = mood === 'chill' && mode === 'idle' && !doze && !typing
188 const look = working && st.kind !== 'bash' && st.kind !== 'agent' ? 1 : 0
189 // 刚结束的工具: 收尾还要撑多久 (秒); 撑着时右边画收尾, 现在这个动作的道具等它收完再出来
190 const end = st.end && zoneFree && mode !== 'celebrate' ? st.end : undefined
191 const remain = end ? Math.max(0, (END_HOLD_MS[end.kind] ?? END_HOLD) - end.ms) / 1000 : 0
192 const found = !!end && end.kind === 'search' && end.ok && remain > 0
193
194 parts.push(px(2, 0, body, 8, 4))
195
196 // 钳子 (都经过半举)
197 const rightNormal = (): string => {
198 if (working && st.kind === 'bash') return armCycle('R', TAP, 0.3, body)
199 if (working && st.kind === 'edit') return armCycle('R', TAP, 0.3, body)
200 if (doze) return arm('R', 'dn', body)
201 if (mode === 'idle' && !typing) return armCycle('R', WAVE, 12, body)
202 return arm('R', 'out', body)
203 }
204 if (mode === 'celebrate') parts.push(arm('L', 'up', body), arm('R', 'up', body))
205 // 闲着时慌张 (v0.22 甩汗): 两只钳子轮流挥, 一只举起一只半举, 每 150ms 换
206 else if (panicIdle) parts.push(armCycle('L', ['up', 'mid'], 0.3, body), armCycle('R', ['mid', 'up'], 0.3, body))
207 else {
208 parts.push(working && st.kind === 'bash' ? armCycle('L', ['up', 'mid', 'out', 'mid'], 0.3, body) : arm('L', doze ? 'dn' : 'out', body))
209 // 搜到了: 右钳举起, 收尾完再放下
210 parts.push(found ? `<g>${hideAt(remain)}${arm('R', 'up', body)}</g>${later(remain, rightNormal())}` : rightNormal())
211 }
212
213 // 腿: 走路时两对腿交替抬起
214 const legsA = px(2, 4, body) + px(7, 4, body)
215 const legsB = px(4, 4, body) + px(9, 4, body)
216 if (working || panicIdle) parts.push(`<g>${steps('opacity', ['1', '1', '1', '0'], panicIdle ? 0.4 : 0.8)}${legsA}</g><g>${steps('opacity', ['1', '0', '1', '1'], panicIdle ? 0.4 : 0.8)}${legsB}</g>`)
217 else parts.push(legsA + legsB)
218
219 // 眼睛: 一字眼只给睡觉和打瞌睡 (平时眨眼不变); 打字时低头看输入框; 悠闲戴墨镜 (加一点反光, 不像闭着眼)
220 const eyes = (fill: string, y = 1) => px(4 + look, y, fill) + px(7 + look, y, fill)
221 const lineEyes = (xs: number[] = [4, 7]) => xs.map(x => `<rect class="line-eye" x="${x}" y="1.5" width="1" height="0.5" fill="${C.eye}"/>`).join('')
222 if (sand) {
223 // 睡着: 一字眼, 每 22.5 秒睁一只眼看看你回来没
224 const peek = Array.from({ length: 30 }, (_, i) => (i === 29 ? '1' : '0'))
225 parts.push(lineEyes([4]), `<g>${steps('opacity', peek.map(v => (v === '1' ? '0' : '1')), 22.5)}${lineEyes([7])}</g><g>${steps('opacity', peek, 22.5)}${px(7, 1, C.eye)}</g>`)
226 } else if (doze) {
227 // 打瞌睡: 一字眼, 每 6 秒猛地睁一下
228 const jolt = Array.from({ length: 20 }, (_, i) => (i === 18 ? '1' : '0'))
229 parts.push(`<g>${steps('opacity', jolt.map(v => (v === '1' ? '0' : '1')), 6)}${lineEyes()}</g><g>${steps('opacity', jolt, 6)}${eyes(C.eye)}</g>`)
230 } else if (typing) parts.push(eyes(C.eye, 2))
231 else if (chill) {
232 parts.push(px(3, 1, C.shades, 2, 1), px(5, 1, C.bridge, 2, 1), px(7, 1, C.shades, 2, 1), `<rect x="3" y="1" width="0.5" height="0.5" fill="${C.glint}"/>`)
233 } else {
234 const glance = mode === 'idle' && !panicIdle ? moves(['0 0', '0 0', '0 0', '0 0', '-1 0', '1 0', '0 0', '0 0'], 16) : ''
235 const fills: Record<string, string> = { open: C.eye, half: C.eyeHalf, shut: C.eyeShut }
236 const shown = ['open', 'half', 'shut'].map(k => `<g>${steps('opacity', BLINK.map(b => (b === k ? '1' : '0')), 4.5)}${eyes(fills[k] ?? C.eye)}</g>`)
237 parts.push(`<g>${glance}${shown.join('')}</g>`)
238 }
239 // 睡帽 (跟着呼吸一起动): 帽檐在身体上面一行, 帽身两行, 帽尖朝右, 绒球; 刚钻进沙里时等钻好了才从上面掉下来
240 if (sand) {
241 const cap = px(3, -1, C.brim, 6, 1) + px(4, -2, C.cap, 5, 1) + px(5, -3, C.cap, 3, 1) + px(9, -2, C.cap) + px(10, -2, C.pom)
242 const ms = st.sleepMs
243 if (ms !== undefined && ms < 2400) {
244 const t = (1800 - ms) / 1000
245 parts.push(`<g opacity="0">${showAt(t)}<g>${glideMove(['0 -3', '0 0'], 0.6, { begin: t, once: true })}${cap}</g></g>`)
246 } else parts.push(cap)
247 }
248
249 // 头边汗珠 (平滑地往下掉、慢慢变淡): 上下文告急, 或额度 冒汗
250 // 慌张不画在头边 (v0.22 闲着时, v1.3 干活时也是): 从头顶两侧往外上方甩进顶上那一行, 每 600ms 一次
251 if (mood === 'panic' && mode !== 'celebrate') {
252 const fling = (xs: string[]) =>
253 `<rect width="1" height="1" fill="${C.sweat}">${steps('x', xs, 0.6)}${steps('y', ['-1', '-2', '-2', '-2', '-2', '-2', '-2', '-2'], 0.6)}${steps('opacity', ['1', '1', '1', '0', '0', '0', '0', '0'], 0.6)}</rect>`
254 fx.push(fling(['2', '1', '0', '0', '0', '0', '0', '0']), fling(['9', '10', '11', '11', '11', '11', '11', '11']))
255 } else if ((st.heat !== 'ok' || mood === 'sweat') && mode !== 'celebrate' && !sand)
256 fx.push(`<rect x="1" y="0" width="1" height="1" fill="${C.sweat}">${glide('y', ['0', '2'], 0.9, { linear: true })}${glide('opacity', ['1', '1', '0'], 0.9, { linear: true })}</rect>`)
257 // 慌张的 "!": 闲置且右侧空着 -> 右侧竖一个大 "!" (v1.3: 其余时候不再在头顶闪红点, 和终端一样)
258 if (panicIdle && zoneFree) fx.push(`<g>${steps('opacity', ['1', '0.35'], 0.5)}${px(14, -1, C.alarm, 1, 3)}${px(14, 3, C.alarm)}</g>`)
259
260 // 沙堆 (盖住钻进去的下半身); 钻沙时沙粒往两边溅
261 if (sand) {
262 fx.push(px(0, 4, C.sand, 12, 2), px(1, 3.5, C.sand, 2, 0.5), px(9, 3.5, C.sand, 2, 0.5))
263 if (st.sleepMs !== undefined && st.sleepMs < 1800) fx.push(sandBurst(-st.sleepMs / 1000, 3))
264 }
265 // 刚醒: 从沙里蹦出来, 沙粒溅开, 睡帽往右上飞走 (螃蟹已经在做下一件事了)
266 const wake = st.wake && st.wake.ms < 1000 && !sand ? st.wake : undefined
267 if (wake?.from === 'sand') {
268 const b = -wake.ms / 1000
269 fx.push(sandBurst(b, 1))
270 const cap = px(3, -1, C.brim, 6, 1) + px(4, -2, C.cap, 5, 1) + px(5, -3, C.cap, 3, 1) + px(9, -2, C.cap) + px(10, -2, C.pom)
271 fx.push(`<g transform="translate(0 1)"><g class="cap-off">${glideMove(['0 0', '4 -3'], 0.8, { begin: b, once: true })}${glide('opacity', ['1', '1', '0'], 0.8, { begin: b, once: true })}${cap}</g></g>`)
272 }
273
274 // 右边 3 像素宽的道具区 (x 13-15); 有子代理时让给小螃蟹. 移动的东西 (扫描线、地球、齿轮、泡泡) 平滑地滑
275 const prop: string[] = []
276 if (mode === 'celebrate') {
277 const spots: Array<[number, number]> = [[13, 0], [15, 1], [14, 3], [13, 6], [15, 5], [1, 0], [10, 0]]
278 spots.forEach(([x, y], i) => {
279 if (zoneFree || x < 13) fx.push(`<rect x="${x}" y="${y - 1}" width="1" height="1" fill="${C.spark}">${glide('opacity', ['1', '0', '1'], 0.6, { begin: -i * 0.2 })}</rect>`)
280 })
281 } else if (!zoneFree) {
282 // 道具 / 泡泡让位
283 } else if (sand) {
284 prop.push(`<rect x="14" y="5" width="1" height="1" fill="${C.bubble}">${glide('y', ['5', '0'], 2.4, { linear: true })}</rect>`)
285 prop.push(`<rect x="15" y="5" width="1" height="1" fill="${C.bubble}">${glide('y', ['5', '0'], 2.4, { linear: true, begin: -1.2 })}</rect>`)
286 } else if (working) {
287 const t = st.toolMs === undefined ? Infinity : st.toolMs / 1000 // 这个工具已经跑了几秒
288 switch (st.kind) {
289 case 'think':
290 prop.push(`<rect x="13" y="4" width="1" height="1" fill="${C.bubble}">${glide('opacity', ['0', '1', '1', '1'], 1.6, { linear: true })}</rect>`)
291 prop.push(`<rect x="14" y="2" width="1" height="1" fill="${C.bubble}">${glide('opacity', ['0', '0', '1', '1'], 1.6, { linear: true })}</rect>`)
292 prop.push(`<rect x="15" y="0" width="1" height="1" fill="${C.bubble}">${glide('opacity', ['0', '0', '0', '1'], 1.6, { linear: true })}</rect>`)
293 break
294 case 'read':
295 prop.push(px(13, 0, C.paper, 3, 4), `<rect x="13" y="0" width="3" height="1" fill="${C.scan}">${glide('y', ['0', '3'], 1.2, { linear: true })}</rect>`)
296 break
297 case 'edit':
298 // 改文件 B: 钳子每敲一下 (0.3 秒) 多一个墨点, 刚点下去蓝一下; 12 个点 + 停一下 = 4.05 秒一轮
299 prop.push(px(13, 0, C.paper, 3, 4), inkDots(true))
300 break
301 case 'bash': {
302 // 跑命令 B: 先敲 1.35 秒命令, 再盯着输出往上滚; 跑命令 C: 同一条跑到 15 秒, 冒热气、跺脚 (眼睛还盯着屏幕)
303 const typed = 1.35 - t
304 prop.push(px(13, 0, C.term, 3, 4))
305 if (typed > 0)
306 prop.push(`<g>${hideAt(typed)}${px(13, 3, C.cursor)}${later(0.45 - t, px(14, 3, C.out))}${later(0.9 - t, px(15, 3, C.out))}</g>`)
307 prop.push(later(typed, termOutput(), typed > 0 ? 'output' : ''))
308 const imp = 15 - t
309 prop.push(`<g class="impatient" opacity="0">${showAt(imp)}${steam()}</g>`)
310 parts.push(`<animateTransform attributeName="transform" type="translate" values="0 0;0 0.5;0 0" dur="0.3s" begin="${sec(Math.max(0, imp))}s" calcMode="discrete" repeatCount="indefinite" additive="sum"/>`)
311 break
312 }
313 case 'search':
314 // 上网 S2: 绿色雷达环, 亮点带着尾巴转圈 (1.2 秒一圈)
315 prop.push(radar())
316 break
317 case 'fetch':
318 // 抓网页 D+: 带蓝条的网页从右边飞进来 (刚开始时), 内容一行行加载
319 prop.push(`<g>${glideMove(['4 0', '0 0'], 0.45, { begin: -Math.min(t, 99), once: true })}${px(13, 0, C.paper, 3, 4)}${px(13, 0, C.scan, 3, 1)}${[1, 2, 3].map(y => `<rect x="13" y="${y}" width="${y === 2 ? 1 : 2}" height="1" fill="${C.out}">${steps('opacity', [0, 1, 2, 3].map(k => (k >= y ? '1' : '0')), 1.2)}</rect>`).join('')}</g>`)
320 break
321 case 'web':
322 prop.push(px(14, 0, C.sea), px(15, 1, C.sea), px(14, 2, C.sea), px(13, 1, C.sea), px(14, 1, C.sea))
323 prop.push(`<rect width="1" height="1" fill="${C.land}">${glide('x', ['14', '15', '14', '13', '14'], 1.2, { linear: true })}${glide('y', ['0', '1', '2', '1', '0'], 1.2, { linear: true })}</rect>`)
324 break
325 case 'agent':
326 break
327 default: {
328 prop.push(px(14, 1, C.gear))
329 const orbit: Array<[number, number]> = [[13, 0], [14, 0], [15, 0], [15, 1], [15, 2], [14, 2], [13, 2], [13, 1], [13, 0]]
330 prop.push(`<rect width="1" height="1" fill="${C.gear}">${glide('x', orbit.map(o => String(o[0])), 1.2, { linear: true })}${glide('y', orbit.map(o => String(o[1])), 1.2, { linear: true })}</rect>`)
331 }
332 }
333 }
334 // 收尾 (工具真的结束了): 撑一会儿再收起来, 现在这个动作的道具接着出来
335 if (end && remain > 0) {
336 const b = -end.ms / 1000
337 let fin = ''
338 if (end.kind === 'bash') fin = px(13, 0, C.term, 3, 4) + termLines() + px(13, 3, end.ok ? C.cursor : C.alarm, 3, 1)
339 else if (end.kind === 'edit')
340 fin = px(13, 0, C.paper, 3, 4) + `<g>${glideMove(['0 0', '0 -2'], 0.45, { begin: b, once: true })}${glide('opacity', ['1', '1', '0'], 0.45, { begin: b, once: true })}${px(13, 0, C.paper, 3, 4)}${inkDots(false)}</g>`
341 else if (end.kind === 'fetch')
342 fin =
343 `<rect x="13" y="0" width="3" height="4" fill="${C.paper}">${glide('height', ['4', '0'], 0.45, { begin: b, once: true })}</rect>` +
344 `<rect x="13" y="0" width="3" height="1" fill="${C.scan}">${glide('height', ['1', '0'], 0.45, { begin: b, once: true })}</rect>` +
345 `<rect x="13" y="-1" width="1" height="1" fill="${C.spark}">${glide('opacity', ['1', '0', '1'], 0.3)}</rect><rect x="15" y="0" width="1" height="1" fill="${C.spark}">${glide('opacity', ['0', '1', '0'], 0.3)}</rect>`
346 else if (end.kind === 'search') {
347 const n = end.ok ? Math.max(1, Math.min(5, end.hits ?? 1)) : 0
348 fin = RING.map(([x, y]) => px(x, y, C.radarRing)).join('') + [0, 2, 4, 6, 1].slice(0, n).map((k, i) => `<rect class="blip" x="${RING[k]![0]}" y="${RING[k]![1]}" width="1" height="1" fill="${C.radarSweep}" opacity="0">${showAt(i * 0.15 + b)}</rect>`).join('')
349 }
350 if (fin) fx.push(`<g>${hideAt(remain)}${fin}</g>`)
351 fx.push(later(remain, prop.join('')))
352 } else fx.push(...prop)
353 // 子代理小螃蟹: 任何状态下都画, 盖在最上面; 1 只上下跳着走, 2-3 只排成一列走
354 if (nKids === 1) fx.push(kidSvg(13, 1.5, 0.5, 0, ['0 0', '0 -0.5', '0 0', '0 0.5']))
355 else if (nKids === 2) fx.push(kidSvg(13, -0.5, 0.5, 0, ['0 0', '0 0.5']), kidSvg(13, 2.75, 0.5, 1, ['0 0', '0 0.5']))
356 else if (nKids >= 3) for (let i = 0; i < 3; i++) fx.push(kidSvg(13.3, -0.9 + i * 2.3, 0.4, i, null))
357
358 // 整只上下挪 (平滑): 走路时颠; 打瞌睡点头 (6 秒一下); 睡在沙里慢慢呼吸 (4 秒一下); 庆祝时先连跳两下 (真的离地, 进顶上那一行), 再原地颠
359 let bob = ''
360 if (working) bob = glideMove(['0 0', '0 1', '0 0'], 0.4)
361 else if (sand) bob = glideMove(['0 0', '0 1', '0 0'], 4)
362 else if (doze) bob = glideMove(['0 0', '0 0', '0 1', '0 1', '0 0'], 6)
363 else if (mode === 'celebrate') {
364 const c = Math.max(0, st.celebMs ?? 0)
365 if (c < HOPS_MS) bob += glideMove([...HOP_PATH, ...HOP_PATH.slice(1)], HOPS_MS / 1000, { begin: -c / 1000, once: true })
366 bob += glideMove(['0 0', '0 -1', '0 0'], 0.4, { begin: Math.max(0, HOPS_MS - c) / 1000 })
367 }
368 // 发出消息那一跳 (蹲 -> 跳起 -> 最高 -> 落下 -> 落地 -> 站好), 叠在外层, 和走路的颠一起
369 const jump = st.jumpMs !== undefined && st.jumpMs >= 0 && st.jumpMs < 750 ? glideMove(JUMP_PATH, 0.75, { begin: -st.jumpMs / 1000, once: true }) : ''
370 let crab = `<g>${bob}${parts.join('')}</g>`
371 // 钻进沙里: 整只往下沉一行, 一字眼露在沙上面 (刚钻时演下沉); 刚醒: 从沙里蹦出来 / 打瞌睡被吵醒抖一下
372 if (sand) {
373 const ms = st.sleepMs
374 crab = ms !== undefined && ms < 1800 ? `<g>${glideMove(['0 0', '0 1'], 1.8, { begin: -ms / 1000, once: true })}${crab}</g>` : `<g transform="translate(0 1)">${crab}</g>`
375 } else if (wake?.from === 'sand') crab = `<g>${glideMove(['0 1', '0 -1', '0 0'], 0.6, { begin: -wake.ms / 1000, once: true })}${crab}</g>`
376 else if (wake?.from === 'doze')
377 crab = `<g><animateTransform attributeName="transform" type="translate" values="-0.5 0;0.5 0;0 0" dur="0.225s" begin="${sec(-wake.ms / 1000)}s" calcMode="discrete" fill="freeze"/>${crab}</g>`
378 const W = 16
379 const H = 8 // 第 -2..-1 行留给跳 (和闪光 / "!" / 睡帽), 第 0-4 行是螃蟹, 第 5 行给往下颠 (和沙堆)
380 const art = `<g color="${color}">${colorAnim}${jump ? `<g>${jump}${crab}</g>` : crab}${fx.join('')}</g>`
381 // color-scheme: 让小窗框跟随客户端的深/浅色主题, 不再垫白底
382 const cs = ` style="color-scheme:light dark;background:transparent"`
383 if (!tile) {
384 return `<svg xmlns="http://www.w3.org/2000/svg" width="${W * scale}" height="${H * scale}" viewBox="0 -2 ${W} ${H}" shape-rendering="crispEdges"${cs}>${art}</svg>`
385 }
386 const ox = (tile.w - W * scale) / 2
387 const oy = (tile.h - H * scale) / 2 + 2 * scale // viewBox 从 y=-2 开始, 往下补两格
388 return (
389 `<svg xmlns="http://www.w3.org/2000/svg" width="${tile.w}" height="${tile.h}" viewBox="0 0 ${tile.w} ${tile.h}"${cs}>` +
390 `<rect x="0.5" y="0.5" width="${tile.w - 1}" height="${tile.h - 1}" rx="10" fill="${T.panel}" stroke="${T.border}"/>` +
391 `<g transform="translate(${ox} ${oy}) scale(${scale})" shape-rendering="crispEdges">${art}</g></svg>`
392 )
393}
394
395// v1.4 道具的小零件
396// 雷达环 8 格 (顺时针, 从左上开始); 亮点带一格尾巴转圈
397const RING: Array<[number, number]> = [[13, 0], [14, 0], [15, 0], [15, 1], [15, 2], [14, 2], [13, 2], [13, 1]]
398function radar(): string {
399 const xs = RING.map(r => String(r[0]))
400 const ys = RING.map(r => String(r[1]))
401 const back = (a: string[]) => [a[a.length - 1]!, ...a.slice(0, -1)]
402 return (
403 RING.map(([x, y]) => px(x, y, C.radarRing)).join('') +
404 `<rect width="1" height="1" fill="${C.radarTrail}">${steps('x', back(xs), 1.2)}${steps('y', back(ys), 1.2)}</rect>` +
405 `<rect width="1" height="1" fill="${C.radarSweep}">${steps('x', xs, 1.2)}${steps('y', ys, 1.2)}</rect>`
406 )
407}
408// 墨点 12 个 (3 列 x 4 行); live = 跟着钳子一个个点上去 (4.05 秒一轮), 否则一次全画上 (翻页那张)
409function inkDots(live: boolean): string {
410 let out = ''
411 for (let i = 0; i < 12; i++) {
412 const x = 13 + (i % 3)
413 const y = Math.floor(i / 3)
414 if (!live) {
415 out += `<rect class="ink" x="${x}" y="${y}" width="1" height="1" fill="${C.ink}"/>`
416 continue
417 }
418 const blue = Array.from({ length: 27 }, (_, k) => (k === 2 * i ? '1' : '0'))
419 const ink = Array.from({ length: 27 }, (_, k) => (k > 2 * i ? '1' : '0'))
420 out += `<g class="ink"><rect x="${x}" y="${y}" width="1" height="1" fill="${C.scan}">${steps('opacity', blue, 4.05)}</rect><rect x="${x}" y="${y}" width="1" height="1" fill="${C.ink}">${steps('opacity', ink, 4.05)}</rect></g>`
421 }
422 return out
423}
424// 终端里的输出: 三行长短不一的灰线轮着变 (看起来在往上滚), 最下面一行是提示符和闪的光标
425function termOutput(): string {
426 const rows = [
427 ['3', '1', '2', '3', '2', '1'],
428 ['1', '2', '3', '2', '1', '3'],
429 ['2', '3', '1', '1', '3', '2'],
430 ]
431 return (
432 rows.map((w, y) => `<rect x="13" y="${y}" width="3" height="1" fill="${C.out}">${steps('width', w, 1.8)}</rect>`).join('') +
433 px(13, 3, C.cursor) +
434 `<rect x="14" y="3" width="1" height="1" fill="${C.cursor}">${steps('opacity', ['1', '0'], 0.8)}</rect>`
435 )
436}
437const termLines = () => px(13, 0, C.out, 2, 1) + px(13, 1, C.out, 3, 1) + px(13, 2, C.out, 1, 1)
438// 冒热气: 终端上面两缕灰气往上飘
439function steam(): string {
440 return [14, 15]
441 .map((x, i) => `<rect class="steam" x="${x}" width="1" height="1" fill="${C.out}">${glide('y', ['-0.5', '-2'], 0.9, { linear: true, begin: -i * 0.45 })}${glide('opacity', ['1', '0'], 0.9, { linear: true, begin: -i * 0.45 })}</rect>`)
442 .join('')
443}
444// 沙粒往两边溅 (times 次, 每次 0.6 秒)
445function sandBurst(begin: number, times: number): string {
446 const grain = (x0: number, x1: number) =>
447 `<rect width="1" height="1" fill="${C.sand}"><animate attributeName="x" values="${x0};${x1}" dur="0.6s" begin="${sec(begin)}s" repeatCount="${times}"/><animate attributeName="y" values="3;1;3" dur="0.6s" begin="${sec(begin)}s" repeatCount="${times}"/><animate attributeName="opacity" values="1;1;0" dur="0.6s" begin="${sec(begin)}s" repeatCount="${times}" fill="freeze"/></rect>`
448 return grain(1, -1) + grain(10, 12)
449}
450
451// ---------------- 仪表盘 ----------------
452// 估算文字宽度 (px): 中文按 1 个字号, 西文按 0.56 个字号
453export function textW(s: string, size: number): number {
454 let w = 0
455 for (const ch of s) {
456 const cp = ch.codePointAt(0) ?? 0
457 if (cp >= 0x2e80) w += size
458 else if (ch === ' ') w += size * 0.3
459 else if (/[A-Z0-9%$]/.test(ch)) w += size * 0.62
460 else w += size * 0.52
461 }
462 return w
463}
464function heat(t: number): string {
465 const lerp = (a: number[], b: number[], k: number) => a.map((v, i) => Math.round(v + (b[i] - v) * k))
466 const g = [74, 222, 128]
467 const y = [251, 191, 36]
468 const r = [248, 113, 113]
469 const c = t < 0.6 ? lerp(g, y, t / 0.6) : lerp(y, r, Math.min(1, (t - 0.6) / 0.4))
470 return '#' + c.map(v => v.toString(16).padStart(2, '0')).join('')
471}
472
473const FONT = `'Segoe UI Variable Text','Segoe UI','Microsoft YaHei UI','PingFang SC','Noto Sans CJK SC',sans-serif`
474// 直接画在客户端的深灰卡片上: 不再自带底板和边框 (panel/border 只给可选的螃蟹底板用)
475const T = { value: '#e6e6e8', muted: '#8e8e96', sep: '#5c5c63', accent: '#e08a68', violet: '#b49cfc', track: '#3a3a40', panel: '#17171a', border: '#2a2a2f' }
476
477function text(x: number, y: number, s: string, fill: string, size = 13, weight = 400, extra = ''): string {
478 return `<text x="${x.toFixed(1)}" y="${y}" fill="${fill}" font-size="${size}" font-weight="${weight}"${extra}>${esc(s)}</text>`
479}
480
481// 一段连续的文字: 各段由浏览器自己排, 不用估宽度, 也就不会叠在一起
482// anchor='end' 时整段右对齐到 x (用于最右一列, 让三行的右边缘对齐)
483type Run = [string, string, number?, number?] | null // 文字, 颜色, 字重, 字号
484function flow(x: number, y: number, runs: Run[], size = 13, anchor: 'start' | 'end' = 'start'): string {
485 const spans = runs
486 .filter((r): r is [string, string, number?, number?] => !!r && r[0] !== '')
487 .map(([s, fill, w, fs]) => `<tspan fill="${fill}"${w ? ` font-weight="${w}"` : ''}${fs ? ` font-size="${fs}"` : ''}>${esc(s)}</tspan>`)
488 .join('')
489 return `<text x="${x.toFixed(1)}" y="${y}" font-size="${size}" text-anchor="${anchor}" xml:space="preserve" style="white-space:pre">${spans}</text>`
490}
491const SEP: Run = [' · ', T.sep]
492
493// "2h12m" -> "2h", "1d18h" -> "1d", "240k / 1.0M" -> "240k"; 会用完的说明缩短时留着 "用完": "4d12h 用完" -> "4d 用完"
494// (只剩一个时间会被看成重置倒计时); 旧写法 "约 40m 后用完" / "2h12m 后重置" 也认; 英文 "out 4d12h" -> "out 4d"
495function shortExtra(s: string): string {
496 const t = s.replace(/^约\s*/, '').trim()
497 const out = t.match(/^(\S+?)\s*后?用完$/)
498 if (out) return coarseDur(out[1]) + ' 用完'
499 const outEn = t.match(/^out\s+(\S+)$/)
500 if (outEn) return 'out ' + coarseDur(outEn[1] ?? '')
501 return coarseDur(t.replace(/\s*后?重置$/, '').split('/')[0].trim())
502}
503function coarseDur(t: string): string {
504 const hm = t.match(/^(\d+)h\d+m$/)
505 if (hm) return hm[1] + 'h'
506 const dh = t.match(/^(\d+)d\d+h$/)
507 if (dh) return dh[1] + 'd'
508 return t
509}
510
511// 一根用量条, 正好撑满一列: 标签贴列的左边, 百分比和说明贴列的右边, 中间的细条吃掉剩下的宽度
512// 说明按这一列的宽度给全文 / 缩写 / 不给; id 带尺寸前缀, 同一页面有几张图时不会互相引用错
513function meterSvg(id: string, x0: number, y: number, cw: number, label: string, m: Meter, labelW = 0): string {
514 // labelW: 固定的标签宽度, 让细条和上下两行的值从同一个位置开始 (和终端版一样)
515 const lw = labelW || textW(label, 12) + 8
516 const p = m.pct === undefined ? 0 : Math.max(0, Math.min(100, m.pct)) / 100
517 const pctText = m.pct === undefined ? '--' : Math.round(m.pct) + '%'
518 // 右边那段 (百分比 + 说明) 的估计宽度, 留一点余量, 防止压到细条
519 const tail = (e: string) => (textW(pctText, 12.5) + (e ? 6 + textW(e, 11) : 0)) * 1.08 + 4
520 const options = m.extra ? [m.extra, shortExtra(m.extra), ''] : ['']
521 const extra = options.find(e => cw - lw - tail(e) - 10 >= 40) ?? ''
522 const bx = x0 + lw
523 const bw = Math.max(16, cw - lw - tail(extra) - 10)
524 const out = [text(x0, y, label, T.muted, 12), `<rect x="${bx.toFixed(1)}" y="${y - 6}" width="${bw.toFixed(1)}" height="5" rx="2.5" fill="${T.track}"/>`]
525 if (p > 0) {
526 out.push(
527 `<linearGradient id="g${id}" gradientUnits="userSpaceOnUse" x1="${bx.toFixed(1)}" y1="0" x2="${(bx + bw).toFixed(1)}" y2="0"><stop offset="0" stop-color="${heat(0)}"/><stop offset="0.6" stop-color="${heat(0.6)}"/><stop offset="1" stop-color="${heat(1)}"/></linearGradient>`,
528 `<rect x="${bx.toFixed(1)}" y="${y - 6}" width="${Math.max(5, bw * p).toFixed(1)}" height="5" rx="2.5" fill="url(#g${id})"/>`,
529 )
530 }
531 // 时间刻度: 1.5 像素宽的亮色细竖线, 上下各比条高出 1.5 像素, 夹在条的两端之内
532 if (m.tick !== undefined && isFinite(m.tick)) {
533 const tw = 1.5
534 const tx = Math.max(bx, Math.min(bx + bw - tw, bx + bw * Math.max(0, Math.min(1, m.tick)) - tw / 2))
535 out.push(`<rect class="tick" x="${tx.toFixed(1)}" y="${y - 7.5}" width="${tw}" height="8" fill="${C.tick}"/>`)
536 }
537 // 会用完: 百分比和说明都画成红色
538 const pctFill = m.pct === undefined ? T.muted : m.warn ? C.warn : heat(p)
539 out.push(flow(x0 + cw, y, [[pctText, pctFill, 700, 12.5], extra ? [' ' + extra, m.warn ? C.warn : T.muted, m.warn ? 700 : 0, 11] : null], 12.5, 'end'))
540 return out.join('')
541}
542
543// 和终端版同一种排法: 3 行 x 3 列, 每列的标签在同一条竖线上, 值和用量条都从标签后同一个位置开始
544// 模型 Opus 5.5 ▁▂▄ medium 项目 my-app main 本会话 1h19m $64.93
545// 上下文 ━━━━━━━━━━ 34% 340k 5小时 ━━━━━━━━━ 34% 1h52m 本周 ━━━━━━━━━ 48% 1d18h
546// 状态 ✓ 待命 工具 Bash 12 Read 4 token 79.7M out 212k
547// 用量条撑满所在列, 第三列的条正好到右边缘; 一列放不下的文字在右端渐隐, 不会压到旁边一列
548export function dashSvg(d: DashData, opts: { width?: number; compact?: boolean } = {}): string {
549 const W = Math.round(opts.width ?? 640)
550 const uid = `uhud${W}${opts.compact ? 'c' : 'f'}`
551 const lh = 22
552 const y = (i: number) => 15 + i * lh
553 const H = opts.compact ? 22 : lh * 3
554 const gap = 24
555 const cw = (W - gap * 2) / 3
556 const cx = [0, cw + gap, (cw + gap) * 2]
557 const L = S().label
558 // 标签列宽: 最宽的标签 + 间距 (中文三个汉字 = 52, 英文 "Context" / "Session" 也差不多)
559 const LW = opts.compact ? 0 : Math.max(52, Math.ceil(Math.max(...Object.values(L).map(t => textW(t, 12)))) + 16)
560 const meters = (row: number) =>
561 meterSvg(uid + 'a', cx[0], y(row), cw, L.context, d.ctx, LW) +
562 meterSvg(uid + 'b', cx[1], y(row), cw, L.h5, d.five, LW) +
563 meterSvg(uid + 'c', cx[2], y(row), cw, L.week, d.week, LW)
564
565 // 每列一个遮罩: 在列的右端渐隐
566 const fade = 18 / cw
567 const defs = [0, 1, 2]
568 .map(
569 c =>
570 `<linearGradient id="${uid}f${c}" gradientUnits="userSpaceOnUse" x1="${cx[c].toFixed(1)}" y1="0" x2="${(cx[c] + cw).toFixed(1)}" y2="0"><stop offset="0" stop-color="#fff"/><stop offset="${(1 - fade).toFixed(3)}" stop-color="#fff"/><stop offset="1" stop-color="#fff" stop-opacity="0"/></linearGradient>` +
571 `<mask id="${uid}m${c}" maskUnits="userSpaceOnUse" x="${cx[c].toFixed(1)}" y="0" width="${cw.toFixed(1)}" height="${H}"><rect x="${cx[c].toFixed(1)}" y="0" width="${cw.toFixed(1)}" height="${H}" fill="url(#${uid}f${c})"/></mask>`,
572 )
573 .join('')
574 // 一格: 标签 + 从标签后开始的值
575 const cell = (c: number, row: number, label: string, runs: Run[]) =>
576 `<g mask="url(#${uid}m${c})">${text(cx[c], y(row), label, T.muted, 12)}${flow(cx[c] + LW, y(row), runs)}</g>`
577
578 let body = ''
579 if (opts.compact) {
580 body = meters(0)
581 } else {
582 const effortIdx = EFFORTS.indexOf(d.effort)
583 const effortColor = EFFORT_COLOR[d.effort] ?? T.muted
584 const pips: Run[] = '▁▂▄▆█'.split('').map((ch, k) => [ch, k <= effortIdx ? effortColor : T.track])
585 const tone = d.status.tone === 'work' ? T.accent : d.status.tone === 'agents' ? T.violet : T.muted
586 // 第 1 行: 模型 | 项目 | 本会话
587 body += cell(0, 0, L.model, [[d.model, T.accent, 600], [' ', T.sep], ...pips, [' ' + (d.effort || '--'), effortColor, 600]])
588 body += cell(1, 0, L.project, [[d.project, T.value, 600], d.branch ? [' ' + d.branch, T.violet] : null])
589 body += cell(2, 0, L.session, [[d.session, T.value, 600], d.cost ? [' ' + d.cost, T.muted] : null])
590 // 第 2 行: 三根用量条
591 body += meters(1)
592 // 第 3 行: 状态 | 工具 | token
593 body += cell(0, 2, L.status, [d.status.tone === 'idle' ? null : ['● ', tone], [d.status.text, tone, d.status.tone === 'idle' ? 0 : 600]])
594 body += cell(1, 2, L.tools, [[d.tools || S().noTools, d.tools ? T.value : T.muted]])
595 body += cell(2, 2, L.token, [[d.tokenTotal, T.value, 600], d.tokenOutput ? [' out ', T.muted] : null, d.tokenOutput ? [d.tokenOutput, T.value] : null])
596 }
597
598 return (
599 `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H}" viewBox="0 0 ${W} ${H}" font-family="${FONT}" style="color-scheme:light dark">` +
600 `<defs>${defs}</defs>${body}</svg>`
601 )
602}
603hooks/sprites.ts 1704 lines1// cc-hud: 螃蟹的像素画 (纯函数, 不碰 $), 给 hooks 模块 (register.tsx) 和散步道的 Client 模块 (walkway.tsx) 共用
2// - 面板那只大螃蟹 (scenePx / miniPx): 按工具做动作、道具区、情绪
3// - 散步道 (v0.14 起; v0.16 搬进 Client): 排队、走路、粒子、天空行; 像素 -> 格子 (laneCells), 最后一步由 walkway.tsx 画成 Text
4
5export const FRAME_MS = 150 // 面板 (输入框下方) 和面板螃蟹的一帧
6export const LANE_MS = 75 // 散步道的一帧 (v0.19: 比面板快一倍; 走路半格一步, 速度和以前一样)
7const PER = FRAME_MS / LANE_MS // 一个 150ms = 几个散步道帧 (2): 走路以外的动作仍按 150ms 的节奏, 看起来和以前一样快
8export const laneFrames = (ms: number) => Math.max(1, Math.round(ms / LANE_MS)) // 毫秒 -> 散步道帧数
9export const SPRITE_W = 15 // 12 列螃蟹 + 3 列道具
10export const MINI_W = 8
11export const JUMP_FRAMES = 4 // 发出消息那一跳: 蹲 / 腾空 / 腾空 / 落地
12export const DEF = 0x01000000 // 终端的默认颜色
13export const DIM = '#71717a'
14export const VALUE = '#d4d4d8'
15export const WARN = '#f87171' // 会用完时 百分比 和 "40m用完" 的颜色
16
17export type Mood = 'chill' | 'normal' | 'sweat' | 'panic'
18export type ToolKind = 'think' | 'read' | 'edit' | 'bash' | 'search' | 'fetch' | 'agent' | 'other' // v1.4: 上网拆成 搜索 (WebSearch) / 抓网页 (WebFetch)
19
20// ---------------- 颜色 ----------------
21export const COL = {
22 body: 0xd97757,
23 hot: 0xe5484d,
24 eye: 0x1c1917,
25 sweat: 0x60a5fa,
26 spark: 0xfacc15,
27 bubble: 0x8b8b94,
28 paper: 0xd4d4d8,
29 ink: 0x52525b,
30 scan: 0x60a5fa,
31 term: 0x3f3f46,
32 cursor: 0x4ade80,
33 sea: 0x3b82f6,
34 land: 0x4ade80,
35 gear: 0xa1a1aa,
36 thought: 0xa1a1aa,
37 shades: 0x09090b, // 墨镜镜片
38 bridge: 0x52525b, // 墨镜鼻梁
39 alarm: 0xef4444, // 慌张的 "!"
40 termOut: 0xa1a1aa, // 终端里滚动的输出 (v1.4)
41 termOld: 0x71717a, // 终端里上一条命令留下的旧输出 (v1.4)
42 seaHi: 0x93c5fd, // 天空行里的网址 / 结果链接 (v1.4)
43 visited: 0xa78bfa, // 抓完的网址 (访问过的紫色, v1.4)
44 radarRing: 0x15803d, // 搜索的雷达: 绿圈 (v1.4 S2)
45 radarSweep: 0x4ade80, // 扫描线
46 radarTrail: 0x166534, // 扫描线后面的尾巴
47 blip: 0xfafafa, // 光点闪的那一下
48 sand: 0xc8a96a, // 睡觉钻的沙堆 (v1.4)
49 cap: 0x4f46e5, // 睡帽
50 brim: 0xe4e4e7, // 帽檐
51 pom: 0xfafafa, // 绒球
52 kid: 0xf2a07b, // 小螃蟹用浅一号的颜色, 和大螃蟹分得开
53 kidEye: 0xf5f5f4, // 0.12 的小螃蟹眼睛 (会闪的浅色像素); 0.13 起不画, 留着给测试确认画面里没有它
54 kidLeg: 0xa4553d,
55}
56export function mix(a: number, b: number, t: number): number {
57 const ch = (s: number) => Math.round(((a >> s) & 255) * (1 - t) + ((b >> s) & 255) * t)
58 return (ch(16) << 16) | (ch(8) << 8) | ch(0)
59}
60
61// ---------------- 文字宽度 (中文/全角算 2 列) ----------------
62export function isWide(cp: number): boolean {
63 return (
64 (cp >= 0x1100 && cp <= 0x115f) ||
65 (cp >= 0x2e80 && cp <= 0xa4cf) ||
66 (cp >= 0xac00 && cp <= 0xd7a3) ||
67 (cp >= 0xf900 && cp <= 0xfaff) ||
68 (cp >= 0xfe30 && cp <= 0xfe4f) ||
69 (cp >= 0xff00 && cp <= 0xff60) ||
70 (cp >= 0xffe0 && cp <= 0xffe6)
71 )
72}
73export function dw(s: string): number {
74 let w = 0
75 for (const ch of s) w += isWide(ch.codePointAt(0) ?? 0) ? 2 : 1
76 return w
77}
78export function clip(s: string, max: number): string {
79 if (max <= 0) return ''
80 if (dw(s) <= max) return s
81 let out = ''
82 let w = 0
83 for (const ch of s) {
84 const cw = isWide(ch.codePointAt(0) ?? 0) ? 2 : 1
85 if (w + cw > max - 2) break
86 out += ch
87 w += cw
88 }
89 return out + '..'
90}
91
92// ---------------- 像素画 ----------------
93export type Px = number[][]
94export function canvas(w: number, h: number): Px {
95 const p: Px = []
96 for (let y = 0; y < h; y++) p.push(new Array(w).fill(-1))
97 return p
98}
99export function put(p: Px, x: number, y: number, c: number) {
100 if (y >= 0 && y < p.length && x >= 0 && x < p[y].length) p[y][x] = c
101}
102export function rect(p: Px, x0: number, y0: number, w: number, h: number, c: number) {
103 for (let y = y0; y < y0 + h; y++) for (let x = x0; x < x0 + w; x++) put(p, x, y, c)
104}
105export function encode(px: Px, cols: number, cellRows: number): string {
106 const words: number[] = []
107 for (let r = 0; r < cellRows; r++) {
108 for (let c = 0; c < cols; c++) {
109 const top = px[r * 2]?.[c] ?? -1
110 const bot = px[r * 2 + 1]?.[c] ?? -1
111 if (top < 0 && bot < 0) words.push(32, DEF, DEF)
112 else if (bot < 0) words.push(0x2580, top, DEF) // ▀
113 else if (top < 0) words.push(0x2584, bot, DEF) // ▄
114 else words.push(0x2580, top, bot)
115 }
116 }
117 return new Uint8Array(Uint32Array.from(words).buffer).toBase64()
118}
119
120// eyeDy: 眼睛在身体第几行 (默认 1, 散步道里低头看输入框时 2); legs < 0 = 腾空不画腿
121// v0.19 (散步道的中间姿势): 钳子 mid = 半举 (斜着); 眼睛 half = 眨眼时的半闭; squash = 落地压扁 (矮一行、宽两格, 贴着地)
122// v1.4: dn = 往下刨 / 耷拉着 (钻沙、打瞌睡); 眼睛 line = 闭成一字眼 (只用在睡觉和打瞌睡, 平时眨眼还是变暗的那一格); eyeR = 右眼单独 (睡着时睁一只眼)
123export type Arm = 'out' | 'mid' | 'up' | 'dn'
124export type Eyes = 'open' | 'half' | 'closed' | 'line'
125export type Pose = { bob: number; legs: number; eyes: Eyes; eyeR?: Eyes; look: number; armL: Arm; armR: Arm; body: number; eyeDy?: number; squash?: boolean }
126
127// 12x5 像素的螃蟹 (第 6 行留给上下颠); ox = 往右挪几格 (面板里是 0, 散步道里是螃蟹的位置)
128export function drawCrab(p: Px, o: Pose, ox = 0) {
129 const y = o.bob
130 const eyeC = (e: Eyes) => (e === 'open' || e === 'line' ? COL.eye : mix(o.body, COL.eye, e === 'half' ? 0.75 : 0.45))
131 const eye = eyeC(o.eyes)
132 // 一只眼: line = 两格宽的一条线 (左眼往左多一格, 右眼往右多一格)
133 const eyeAt = (x: number, ey: number, e: Eyes, side: -1 | 1) => {
134 if (e === 'line') rect(p, side < 0 ? x - 1 : x, ey, 2, 1, COL.eye)
135 else put(p, x, ey, eyeC(e))
136 }
137 if (o.squash) {
138 // 落地压扁: 身体矮一行 (第 1-3 行)、左右各宽一格, 钳子平伸贴着身体, 四条腿张开站在地上 (第 4 行)
139 rect(p, ox + 1, y + 1, 10, 3, o.body)
140 put(p, ox, y + 2, o.body)
141 put(p, ox + 11, y + 2, o.body)
142 for (const x of [1, 4, 7, 10]) put(p, ox + x, y + 4, o.body)
143 eyeAt(ox + 4 + o.look, y + 2, o.eyes, -1)
144 eyeAt(ox + 7 + o.look, y + 2, o.eyeR ?? o.eyes, 1)
145 return
146 }
147 rect(p, ox + 2, y, 8, 4, o.body)
148 // 钳子: 平伸 (第 2 行两格) / 半举 (斜着: 贴身那格在第 2 行, 钳尖在第 1 行) / 举起 (竖着, 第 0-1 行)
149 if (o.armL === 'out') rect(p, ox, y + 2, 2, 1, o.body)
150 else if (o.armL === 'mid') {
151 put(p, ox + 1, y + 2, o.body)
152 put(p, ox, y + 1, o.body)
153 } else if (o.armL === 'dn') {
154 put(p, ox + 1, y + 3, o.body)
155 put(p, ox, y + 4, o.body)
156 } else rect(p, ox, y, 1, 2, o.body)
157 if (o.armR === 'out') rect(p, ox + 10, y + 2, 2, 1, o.body)
158 else if (o.armR === 'mid') {
159 put(p, ox + 10, y + 2, o.body)
160 put(p, ox + 11, y + 1, o.body)
161 } else if (o.armR === 'dn') {
162 put(p, ox + 10, y + 3, o.body)
163 put(p, ox + 11, y + 4, o.body)
164 } else rect(p, ox + 11, y, 1, 2, o.body)
165 // 走路: 四条腿两两交替抬起
166 if (o.legs >= 0) {
167 const legs = [[2, 4, 7, 9], [2, 7], [2, 4, 7, 9], [4, 9]][o.legs % 4] ?? []
168 for (const x of legs) put(p, ox + x, y + 4, o.body)
169 }
170 const ey = y + (o.eyeDy ?? 1)
171 eyeAt(ox + 4 + o.look, ey, o.eyes, -1)
172 eyeAt(ox + 7 + o.look, ey, o.eyeR ?? o.eyes, 1)
173}
174
175// look / low / hop: 散步道用 (面板不给, 画法和以前一样):
176// look = 眼睛看哪边 (走路方向 / 东张西望); low = 打字时低头看输入框; hop = 发出消息那一跳的第几帧
177export type Scene = {
178 working: boolean
179 kind: ToolKind
180 pct: number
181 celebrating: boolean
182 sleeping: boolean
183 agents: number
184 mood?: Mood
185 look?: number
186 low?: boolean
187 hop?: number
188 // v0.19 散步道给的 (面板不给, 画法和以前一样):
189 sub?: number // 散步道的帧号 (75ms): 有它时眨眼加半闭、敲钳子 / 挥手加半举、睡觉呼吸放慢
190 bodyMix?: number // 身体颜色 0 = 平常色 .. 1 = 红: 有它时代替 bodyColor 的硬切换 (渐渐变红 / 呼吸式闪)
191 arms?: { L?: Arm; R?: Arm } // 最后盖上去的钳子姿势 (悬停打招呼收回时的半举)
192 // v1.4 散步道给的: 这次工具调用开始了几帧 / 结束了几帧 (-1 = 还在跑) / 成没成功; 不给就按帧号循环 (面板、旧测试)
193 toolAge?: number
194 endAge?: number
195 ok?: boolean
196 sky?: boolean // v1.4: 上面有天空行 (改文件翻页飞进去; 没有就让旧页直接消失)
197 room?: number // v1.4: 道具区右边还有几格空地 (抓网页的页面从这里飞进来; 不够就不飞)
198 hits?: number // v1.4: 搜到几条 (雷达亮几个光点)
199 nap?: Nap // v1.4: 睡觉组合的哪个阶段 (散步道给; 有它时整只按这个画)
200}
201// v1.4 睡觉组合 (定稿 G + H + I): 打瞌睡 -> 钻沙 -> 睡帽掉下来 -> 戴着睡帽睡 -> 一来活蹦出来; s = 这个阶段的第几帧 (75ms)
202export type Nap = { stage: 'doze' | 'burrow' | 'cap' | 'sleep' | 'wake'; s: number; from?: WakeFrom }
203export type WakeFrom = 'doze' | 'burrow' | 'cap'
204
205export function bodyColor(pct: number, f: number): number {
206 if (pct >= 95) return f % 4 < 2 ? COL.hot : COL.body
207 return pct >= 80 ? COL.hot : COL.body
208}
209
210// 按字符画盖像素: rows 里每个字符查 colors 得到颜色, 查不到 (比如 '.') 就空着
211export function paint(p: Px, x0: number, y0: number, rows: string[], colors: Record<string, number>) {
212 rows.forEach((row, dy) => {
213 for (let dx = 0; dx < row.length; dx++) {
214 const c = colors[row[dx]]
215 if (c !== undefined) put(p, x0 + dx, y0 + dy, c)
216 }
217 })
218}
219
220// 散步道的中间姿势 (每格 75ms): 敲的那只钳子 平伸 -> 半举 -> 举起 -> 半举 (300ms 一个来回, 和以前一样快);
221// 挥手 半举 -> 举起 x4 -> 半举 -> 平伸 x6 (900ms 一个来回); 睡觉呼吸每 2 秒换一下
222const ARM_TAP: Arm[] = ['out', 'mid', 'up', 'mid']
223const WAVE_ARM: Arm[] = ['mid', 'up', 'up', 'up', 'up', 'mid', 'out', 'out', 'out', 'out', 'out', 'out']
224const BREATH = 27
225
226// 改文件 B 的进度 (75ms 一帧): 写到第几点 n (纸上一共 10 点, 按 PAGE_LINES 一行行写), 敲到第几拍 tap (-1 = 不敲),
227// 翻页到第几帧 flip (-1 = 没在翻). 跑着的时候 54 帧一轮 (写 40 帧, 写满停 8 帧, 翻 6 帧);
228// 一结束就翻页 (没写满也翻: 改完一次就收起一页), 翻页那 6 帧落在结束后的收尾里
229export const PAGE_LINES = [3, 2, 3, 2]
230export function editPhase(age: number, endAge: number): { n: number; tap: number; flip: number } {
231 const at = (c: number) => (c < 40 ? (c >> 2) + 1 : 10)
232 if (endAge >= 0) return { n: at((age - endAge) % 54), tap: -1, flip: endAge } // 第 6 帧起旧页整张飞出天空行
233 const c = age % 54
234 if (c < 40) return { n: at(c), tap: c % 4, flip: -1 }
235 return { n: 10, tap: -1, flip: c < 48 ? -1 : c - 48 }
236}
237function inkPage(put1: (x: number, y: number, c: number) => void, y0: number, n: number, newBlue: boolean) {
238 for (let y = 0; y < 4; y++) for (let x = 0; x < 3; x++) put1(12 + x, y0 + y, COL.paper)
239 let i = 0
240 PAGE_LINES.forEach((len, r) => {
241 for (let x = 0; x < len; x++, i++) if (i < n) put1(12 + x, y0 + r, newBlue && i === n - 1 ? COL.scan : COL.ink)
242 })
243}
244
245// 终端屏幕里的一行输出: 长 1-3 格 (按行号算, 同一行每次都一样长)
246const hashK = (k: number) => ((k * 2654435761) >>> 0) % 1000
247function outLine(p: Px, y: number, k: number, c: number) {
248 const n = 1 + (hashK(k) % 3)
249 for (let x = 0; x < n; x++) put(p, 12 + x, y, c)
250}
251
252// over: 画布外面 (天空行 y < 0、15 列以外) 的像素放这里, 散步道再画上去 (v1.4: 改文件翻页、抓网页的页面);
253// 第 4 个数是 1 时, x 按半格算 (雷达)
254export type Over = Array<[number, number, number, number?]>
255// 雷达的圈 (5 行, 每行从第几个半格到第几个半格) 和光点的位置 (相对圈的左上角)
256const RADAR: Array<[number, number]> = [
257 [3, 6],
258 [1, 8],
259 [0, 9],
260 [1, 8],
261 [3, 6],
262]
263const BLIPS: Array<[number, number]> = [
264 [2, 1],
265 [7, 1],
266 [3, 3],
267 [6, 3],
268 [8, 2],
269]
270export function scenePx(s: Scene, f: number, over?: Over): Px {
271 const p = canvas(SPRITE_W, 6)
272 // 画布外面 (天空行 y < 0, 或 15 列以外) 的像素交给散步道去画
273 const putO = (x: number, y: number, c: number) => (y < 0 || x >= SPRITE_W ? over?.push([x, y, c]) : put(p, x, y, c))
274 const t = Math.floor(f / 2)
275 const md = s.mood ?? 'normal'
276 // 0.14 起子代理小螃蟹搬到输入框上方的散步道, 面板右侧 3 列永远给道具
277 const zoneFree = true
278 const o: Pose = { bob: 0, legs: 0, eyes: 'open', look: 0, armL: 'out', armR: 'out', body: s.bodyMix !== undefined ? mix(COL.body, COL.hot, s.bodyMix) : bodyColor(s.pct, f) }
279 const sub = s.sub
280 let shades = false
281 let bigBang = false // 右侧的大 "!"
282
283 if (s.nap) {
284 drawNap(p, o, s.nap, sub ?? f, over)
285 return p
286 }
287 if (s.hop !== undefined && s.hop >= 0 && s.hop < JUMP_FRAMES) {
288 // 散步道: 发出消息那一跳 (画布只有 6 像素高, 没法整只往上移): 蹲 -> 腾空 (不画腿) -> 落地
289 o.bob = s.hop === 0 || s.hop >= JUMP_FRAMES - 1 ? 1 : 0
290 if (s.hop === 1 || s.hop === 2) {
291 o.legs = -1
292 o.armL = 'up'
293 o.armR = 'up'
294 }
295 } else if (s.low) {
296 // 散步道: 打字时低头看输入框 (身体放低, 眼睛往下)
297 o.bob = 1
298 o.eyeDy = 2
299 } else if (s.celebrating) {
300 o.armL = 'up'
301 o.armR = 'up'
302 o.bob = t % 2
303 const spots = [[12, 0], [14, 1], [13, 3], [12, 5], [14, 4], [13, 1], [1, 0], [10, 0]]
304 spots.forEach(([x, y], i) => {
305 if ((i + f) % 3 === 0 && (zoneFree || x < 12)) put(p, x, y, COL.spark)
306 })
307 } else if (s.working) {
308 o.legs = t % 4
309 o.bob = t % 2
310 switch (s.kind) {
311 case 'think': {
312 o.look = 1
313 const dots = [[12, 4], [13, 2], [14, 0]]
314 const n = Math.floor(f / 3) % 4
315 if (zoneFree) for (let i = 0; i < n; i++) put(p, dots[i][0], dots[i][1], COL.thought)
316 break
317 }
318 case 'read': {
319 o.look = 1
320 if (zoneFree) {
321 rect(p, 12, 1, 3, 4, COL.paper)
322 rect(p, 12, 1 + (t % 4), 3, 1, COL.scan)
323 }
324 break
325 }
326 case 'edit': {
327 // v1.4 (定稿 B, 一笔一画): 右钳 平伸 -> 半举 -> 举起 -> 半举 敲一下, 落下那一帧纸上多一个墨点 (先蓝 2 帧像光标);
328 // 翻页: 写过的那页每帧往上飞 1 像素进天空行, 第 2 帧起下面换上白纸, 右钳 举起 -> 半举 -> 平伸 (扬灰在 laneBursts)
329 const F = sub ?? f
330 const ph = editPhase(s.toolAge ?? F % 54, s.endAge ?? -1)
331 o.bob = 0
332 o.legs = 0
333 o.look = 1
334 if (ph.flip < 0) {
335 o.armR = ph.tap >= 0 ? (ARM_TAP[ph.tap] ?? 'out') : 'out'
336 inkPage((x, y, c) => put(p, x, y, c), 1, ph.n, ph.tap >= 0 && ph.tap < 2)
337 } else {
338 o.armR = ph.flip < 2 ? 'up' : ph.flip < 4 ? 'mid' : 'out'
339 if (ph.flip >= 2) rect(p, 12, 1, 3, 4, COL.paper)
340 if (s.sky !== false) inkPage(putO, -ph.flip, ph.n, false) // 没有天空行: 旧页直接消失
341 }
342 break
343 }
344 case 'bash': {
345 // v1.4 (定稿 B): 敲命令 (开头 18 帧: 双钳交替敲, 最下面一行提示符后面打出两个字, 上面是上一条命令的旧输出)
346 // -> 盯着输出 (钳子放下, 灰色的输出每 3 帧往上滚一行) -> 跑完最后一行整行变绿 (报错变红), 在收尾那段里一直亮着
347 // 帧按 75ms 算 (散步道的 sub); 身体不晃, 眼睛看屏幕. 太快的命令敲到一半就结束: 直接到跑完那一下
348 const F = sub ?? f
349 const age = s.toolAge ?? F % 72
350 const ended = s.endAge !== undefined && s.endAge >= 0
351 const ran = ended ? age - (s.endAge ?? 0) : age // 跑了多久才结束 (滚到哪一行就停在哪一行)
352 o.bob = 0
353 o.legs = 0
354 o.look = 1
355 rect(p, 12, 1, 3, 4, COL.term)
356 if (!ended && age >= BASH_IMPATIENT) {
357 // 跑命令 C (等得不耐烦, 64 帧一轮): 前半右钳每 2 帧敲一下桌面, 后半跺脚 (腿每 4 帧换), 中间眨一次眼;
358 // 眼睛一直盯着屏幕 (用户 2026-10-10: 不回头看你, 看你留给等批准); 屏幕最下面一个进度点来回跳; 热气在 emitParticles
359 const c = (age - BASH_IMPATIENT) % 64
360 if (c < 32) o.armR = (F >> 1) % 2 ? 'mid' : 'out'
361 else {
362 o.legs = (F >> 2) % 2 ? 3 : 0
363 if (c === 40) o.eyes = 'closed'
364 else if (c === 39 || c === 41) o.eyes = 'half'
365 }
366 outLine(p, 1, 7, COL.termOut)
367 put(p, 12 + ([0, 1, 2, 1][(F >> 1) % 4] ?? 0), 4, COL.cursor)
368 } else if (!ended && age < 18) {
369 o.armL = ARM_TAP[(F + 2) % 4] ?? 'out'
370 o.armR = ARM_TAP[F % 4] ?? 'out'
371 for (let r = 0; r < 3; r++) outLine(p, 1 + r, 100 + r, COL.termOld)
372 put(p, 12, 4, COL.cursor)
373 const n = Math.min(2, Math.floor(age / 6))
374 for (let x = 0; x < n; x++) put(p, 13 + x, 4, COL.paper)
375 if (n < 2 && F % 4 < 2) put(p, 13 + n, 4, COL.cursor)
376 } else {
377 const k = Math.floor((Math.max(18, ran) - 18) / 3)
378 for (let r = 0; r < 4; r++) {
379 if (ended && r === 3) rect(p, 12, 4, 3, 1, s.ok === false ? COL.alarm : COL.cursor) // 报错变红 (用户 2026-10-10 选的)
380 else outLine(p, 1 + r, k - 3 + r, COL.termOut)
381 }
382 }
383 break
384 }
385 case 'fetch': {
386 // v1.4 (定稿 D+): 带蓝条的网页从右边飞进来 (每帧 2 格), 第 5-7 帧右钳举起接住; 内容一行行加载 (第 12/18/24 帧),
387 // 正在加载的那行开头蓝点闪; 抓完 (工具结束) 网页收窄 3 -> 2 -> 1 -> 没了, 亮光在 laneBursts; 网址写在天空行 (captionOf)
388 // 右边空地不够 11 格: 不飞, 直接出现在道具区
389 const F = sub ?? f
390 const age = s.toolAge ?? F % 48
391 const end = s.endAge ?? -1
392 const ran = end >= 0 ? age - end : age
393 o.bob = 0
394 o.legs = 0
395 o.look = 1
396 if (end < 0 && ran >= 5 && ran < 8) o.armR = 'up'
397 const x0 = (s.room ?? 99) >= 11 ? Math.max(12, 23 - 2 * Math.min(ran, 6)) : 12
398 const w = end < 0 ? 3 : end < 2 ? 2 : end < 4 ? 1 : 0
399 for (let y = 1; y <= 4; y++) for (let x = 0; x < w; x++) putO(x0 + x, y, y === 1 ? COL.sea : COL.paper)
400 if (end < 0 && ran >= 6) {
401 const loaded = ran < 12 ? 0 : ran < 18 ? 1 : ran < 24 ? 2 : 3
402 for (let r = 0; r < loaded; r++) for (let x = 0; x < ([3, 2, 3][r] ?? 0); x++) put(p, 12 + x, 2 + r, COL.ink)
403 if (loaded < 3 && F % 4 < 2) put(p, 12, 2 + loaded, COL.scan)
404 }
405 break
406 }
407 case 'search': {
408 // v1.4 (S2 雷达, 用户 2026-10-10 选的): 道具区起一个 5 行的绿圈 (只画圈, 半格精度, 第 26-35 个半格),
409 // 扫描线 16 帧转一圈, 后面拖一条暗一点的尾巴; 搜到了 (结束、成功、有结果) 亮起光点 (一条一个, 最多 5 个), 右钳举起;
410 // 搜索词 / 结果链接写在天空行 (captionOf)
411 const F = sub ?? f
412 const end = s.endAge ?? -1
413 o.bob = 0
414 o.legs = 0
415 o.look = 1
416 const found = end >= 0 && s.ok !== false && (s.hits ?? 0) > 0
417 if (found && end < 8) o.armR = 'up'
418 const H = (hx: number, y: number, c: number) => over?.push([hx, y, c, 1])
419 const hx0 = 26
420 const cx = hx0 + 4.5
421 RADAR.forEach(([a0, b0], i) => {
422 for (let k = a0; k <= b0; k++) if (i === 0 || i === 4 || k === a0 || k === b0) H(hx0 + k, i, COL.radarRing)
423 })
424 const ray = (th: number, c: number) => {
425 for (let r = 0.6; r <= 2.2; r += 0.4) {
426 const hx = Math.round(cx + 2 * r * Math.cos(th))
427 const y = Math.round(2 + r * Math.sin(th))
428 const row = RADAR[y]
429 if (row && hx - hx0 > row[0] && hx - hx0 < row[1]) H(hx, y, c)
430 }
431 }
432 const th = (F * Math.PI) / 8
433 ray(th - 0.5, COL.radarTrail)
434 ray(th, COL.radarSweep)
435 H(hx0 + 4, 2, COL.radarSweep)
436 H(hx0 + 5, 2, COL.radarSweep)
437 if (found) BLIPS.slice(0, Math.min(5, s.hits ?? 0)).forEach(([k, y], i) => H(hx0 + k, y, (F >> 1) % 3 === i % 3 ? COL.blip : COL.spark))
438 break
439 }
440 case 'agent':
441 break
442 default: {
443 if (zoneFree) {
444 const orbit = [[12, 1], [13, 1], [14, 1], [14, 2], [14, 3], [13, 3], [12, 3], [12, 2]]
445 put(p, 13, 2, COL.gear)
446 const [gx, gy] = orbit[f % 8]
447 put(p, gx, gy, COL.gear)
448 }
449 }
450 }
451 } else if (md === 'panic') {
452 // 闲置时慌张 (v0.22 甩汗): 两只钳子轮流挥 (一只举起一只半举, 每 150ms 换), 腿乱蹬; 右侧空着就竖一个大 "!"
453 const swap = f % 2 === 0
454 o.armL = swap ? 'up' : 'mid'
455 o.armR = swap ? 'mid' : 'up'
456 o.legs = f % 4
457 bigBang = zoneFree
458 } else if (s.sleeping) {
459 o.eyes = 'closed'
460 o.bob = sub !== undefined ? Math.floor(sub / BREATH) % 2 : Math.floor(f / 8) % 2 // 慢慢呼吸 (散步道里每 2 秒换一下, 更慢更匀)
461 if (zoneFree) {
462 const z = Math.floor(f / 3)
463 put(p, 13, 5 - (z % 6), COL.bubble)
464 put(p, 14, 5 - ((z + 3) % 6), COL.bubble)
465 }
466 } else {
467 const cyc = f % 160
468 if (md === 'chill') shades = true // 戴墨镜: 不眨眼, 不张望
469 else {
470 // 眨眼 (每 4.5 秒); 散步道里 半闭 -> 闭 -> 半闭, 每 75ms 一格
471 if (sub !== undefined) {
472 const b = sub % 60
473 if (b === 1) o.eyes = 'closed'
474 else if (b === 0 || b === 2) o.eyes = 'half'
475 } else if (f % 30 === 0) o.eyes = 'closed'
476 if (cyc >= 60 && cyc < 68) o.look = -1 // 左右张望
477 else if (cyc >= 68 && cyc < 76) o.look = 1
478 }
479 // 挥手; 散步道里举起和放下都经过半举
480 if (sub !== undefined) {
481 const w = sub % 320
482 if (w >= 240 && w < 272) o.armR = WAVE_ARM[(w - 240) % WAVE_ARM.length] ?? 'out'
483 } else if (cyc >= 120 && cyc < 136) o.armR = Math.floor(f / 3) % 2 ? 'up' : 'out'
484 }
485
486 if (s.look !== undefined && !s.low) o.look = s.look // 散步道: 眼睛看走的方向 / 东张西望
487 if (s.arms?.L) o.armL = s.arms.L
488 if (s.arms?.R) o.armR = s.arms.R
489 drawCrab(p, o)
490
491 if (shades) {
492 const y = o.bob + 1
493 rect(p, 3, y, 2, 1, COL.shades)
494 rect(p, 5, y, 2, 1, COL.bridge)
495 rect(p, 7, y, 2, 1, COL.shades)
496 over?.push([2 * 8 + 1, y, COL.blip, 1]) // v1.4: 右镜片上一点白色反光 (半格), 和睡觉的一字眼分得开
497 }
498 if (bigBang) {
499 const c = f % 4 < 2 ? COL.alarm : COL.spark
500 put(p, 13, 0, c)
501 put(p, 13, 1, c)
502 put(p, 13, 3, c)
503 }
504 // 头边 (x=1, 第 0-1 行, 任何姿势下都空着): 上下文告急 / 冒汗 -> 汗滴往下掉
505 // 慌张不画在头边 (v0.22 闲着时、v1.3 干活时也一样): 汗珠甩进天空行 (lanePx); 以前干活时这里和红色 "!" 交替, 看着像身上长了块红的
506 if (!s.celebrating && md !== 'panic' && (s.pct >= 80 || md === 'sweat')) {
507 const d = t % 4
508 if (d < 2) put(p, 1, d, COL.sweat)
509 }
510 return p
511}
512
513// ---------------- v1.4 睡觉组合 ----------------
514export const DOZE_FRAMES = laneFrames(4 * 60_000) // 闲 4 分钟打瞌睡
515export const SLEEP_LANE = laneFrames(5 * 60_000) // 闲 5 分钟钻沙 (原来的睡觉门槛)
516const BURROW = 24 // 钻沙几帧
517const CAP_DROP = 8 // 睡帽掉下来几帧
518export const WAKE_DEEP = 8 // 从沙里蹦出来几帧 (0.6 秒)
519export const WAKE_DOZE = 3 // 打瞌睡被叫醒几帧
520const PEEK = 300 // 睡着以后每隔这么多帧睁一只眼看看 (第 100-111 帧)
521// 闲了 idle 帧: 处在睡觉的哪个阶段 (还没到 4 分钟 = undefined)
522export function napOf(idle: number): Nap | undefined {
523 if (idle < DOZE_FRAMES) return undefined
524 if (idle < SLEEP_LANE) return { stage: 'doze', s: (idle - DOZE_FRAMES) % 80 }
525 const i = idle - SLEEP_LANE
526 if (i < BURROW) return { stage: 'burrow', s: i }
527 if (i < BURROW + CAP_DROP) return { stage: 'cap', s: i - BURROW }
528 return { stage: 'sleep', s: i - BURROW - CAP_DROP }
529}
530function sandHeap(p: Px, side: boolean) {
531 rect(p, 0, 5, 12, 1, COL.sand)
532 if (side) {
533 rect(p, 0, 4, 2, 1, COL.sand)
534 rect(p, 10, 4, 2, 1, COL.sand)
535 put(p, 0, 3, COL.sand)
536 put(p, 11, 3, COL.sand)
537 }
538}
539// 睡帽 (帽檐在 y 那一行, 帽身往上两行, 帽尖朝右, 绒球随呼吸上下晃); 超出画布的交给散步道
540export function nightcap(put1: (x: number, y: number, c: number) => void, y: number, pomDown: boolean, dx = 0, dy = 0) {
541 for (let x = 3; x <= 8; x++) put1(x + dx, y + dy, COL.brim)
542 for (let x = 4; x <= 8; x++) put1(x + dx, y - 1 + dy, COL.cap)
543 for (let x = 5; x <= 7; x++) put1(x + dx, y - 2 + dy, COL.cap)
544 put1(9 + dx, y - 1 + dy, COL.cap)
545 put1(10 + dx, y - (pomDown ? 0 : 1) + dy, COL.pom)
546}
547function drawNap(p: Px, o: Pose, n: Nap, F: number, over?: Over) {
548 const putO = (x: number, y: number, c: number) => (y < 0 || x >= SPRITE_W ? over?.push([x, y, c]) : put(p, x, y, c))
549 const k = n.s
550 o.legs = 0
551 o.look = 0
552 o.bob = 0
553 if (n.stage === 'doze') {
554 // 打瞌睡 (80 帧一轮): 眼皮慢慢合上, 头往下一点、钳子耷拉, 猛地醒一下左右看看, 再点一次头, 然后半睁着
555 const droop = () => {
556 o.bob = 1
557 o.armL = 'dn'
558 o.armR = 'dn'
559 }
560 if (k < 8) {
561 // 醒着
562 } else if (k < 12) o.eyes = 'half'
563 else if (k < 24) {
564 o.eyes = 'line'
565 if (k >= 15) droop()
566 } else if (k < 30) {
567 if (k < 26) {
568 o.armL = 'mid'
569 o.armR = 'mid'
570 }
571 o.look = (k >> 1) % 2 ? -1 : 1
572 } else if (k < 34) o.eyes = 'half'
573 else if (k < 46) {
574 o.eyes = 'line'
575 if (k >= 37) droop()
576 } else o.eyes = 'half'
577 drawCrab(p, o)
578 return
579 }
580 if (n.stage === 'burrow') {
581 // 睁着眼边刨边往沙里沉 (每 6 帧沉 1 像素), 前 18 帧两钳交替刨; 钻好了才闭成一字眼
582 const digging = k < 18
583 const ph = (F >> 1) % 2
584 o.bob = Math.min(3, Math.floor(k / 6))
585 o.eyes = k < 12 ? 'open' : k < 20 ? 'half' : 'line'
586 o.armL = digging ? (ph ? 'dn' : 'out') : 'out'
587 o.armR = digging ? (ph ? 'out' : 'dn') : 'out'
588 drawCrab(p, o)
589 sandHeap(p, k >= 8)
590 return
591 }
592 if (n.stage === 'cap') {
593 // 眼睛已经闭成一字眼, 睡帽从上面掉下来戴上
594 o.bob = 3
595 o.eyes = 'line'
596 drawCrab(p, o)
597 sandHeap(p, true)
598 nightcap(putO, 3, false, 0, Math.min(0, k - 5))
599 return
600 }
601 if (n.stage === 'sleep') {
602 // 戴着睡帽睡: 每 27 帧一浮一沉 (睡帽跟着), 冒泡泡; 隔一阵睁一只眼看看你回来没
603 const breathe = Math.floor(k / 27) % 2
604 const q = k % PEEK
605 const peek = q >= 100 && q < 112
606 o.bob = breathe ? 2 : 3
607 o.eyes = 'line'
608 if (peek) {
609 o.look = (q >> 2) % 2 ? 1 : 0
610 o.eyeR = q < 102 || q >= 110 ? 'half' : 'open'
611 }
612 drawCrab(p, o)
613 nightcap(putO, o.bob, breathe === 1)
614 sandHeap(p, true)
615 const z = Math.floor((F >> 1) / 3)
616 put(p, 13, 5 - (z % 6), COL.bubble)
617 put(p, 14, 5 - ((z + 3) % 6), COL.bubble)
618 return
619 }
620 // 醒来 (wake). 从打瞌睡: 睁眼、两钳一举 (3 帧). 从沙里: 第 0 帧睁眼、沙子一抖; 1-4 帧蹦进天空行 (钳子举起、腿收起, 抬高在 drawLaneBig);
621 // 第 5 帧落地压扁; 6-7 帧两钳半举左右看. 睡帽弹飞、沙子炸开、地上的沙在散步道那层接着播
622 if (n.from === 'doze') {
623 o.armL = 'up'
624 o.armR = 'up'
625 drawCrab(p, o)
626 return
627 }
628 if (k === 0) {
629 o.bob = 3
630 drawCrab(p, o)
631 if (n.from === 'cap') nightcap(putO, 3, false)
632 sandHeap(p, true)
633 put(p, 10, 3, COL.sand)
634 return
635 }
636 if (k <= 4) {
637 o.legs = -1
638 o.armL = 'up'
639 o.armR = 'up'
640 drawCrab(p, o)
641 return
642 }
643 if (k === 5) {
644 drawCrab(p, { ...o, squash: true })
645 return
646 }
647 o.armL = 'mid'
648 o.armR = 'mid'
649 o.look = (k >> 1) % 2 ? -1 : 1
650 drawCrab(p, o)
651}
652
653// 测试 / 预览用: scenePx 再把画布外那层里落在 15x6 画布内的像素画上 (雷达左半边就在道具区里)
654export function scenePxAll(s: Scene, f: number): Px {
655 const over: Over = []
656 const p = scenePx(s, f, over)
657 for (const [x, y, c, half] of over) put(p, half ? x >> 1 : x, y, c)
658 return p
659}
660
661// 精简版的一行小螃蟹 (8 列 x 2 像素); 0.14 起子代理小螃蟹在散步道里, 这里不再画
662export function miniPx(s: Scene, f: number): Px {
663 const p = canvas(MINI_W, 2)
664 const t = Math.floor(f / 2)
665 const md = s.mood ?? 'normal'
666 const body = s.bodyMix !== undefined ? mix(COL.body, COL.hot, s.bodyMix) : bodyColor(s.pct, f)
667 const bw = MINI_W
668 rect(p, 0, 0, bw, 1, body)
669 const idle = !s.working && !s.celebrating
670 const closed = s.sleeping || (idle && md !== 'chill' && f % 30 === 0)
671 const look = s.working ? 1 : 0
672 const ex = [2, 5]
673 let eye = closed ? mix(body, COL.eye, 0.45) : COL.eye
674 if (md === 'panic' && !s.celebrating && f % 4 < 2) eye = COL.spark // 慌张: 眼睛黄红闪
675 if (idle && !s.sleeping && md === 'chill') rect(p, ex[0], 0, ex[1] - ex[0] + 1, 1, COL.shades) // 墨镜
676 else {
677 put(p, ex[0] + look, 0, eye)
678 put(p, ex[1] + look, 0, eye)
679 }
680 const scramble = md === 'panic' && !s.celebrating
681 const wide = s.celebrating ? [0, 7] : (s.working || scramble) && t % 2 ? [0, 2, 5, 7] : [1, 3, 4, 6]
682 const legs = wide
683 for (const x of legs) put(p, x, 1, body)
684 // 冒汗: 左下角一颗蓝色汗滴闪
685 if (!s.celebrating && (s.pct >= 80 || md === 'sweat' || md === 'panic') && t % 4 < 2) put(p, 0, 1, COL.sweat)
686 return p
687}
688
689
690// ---------------- 螃蟹散步道 (v0.14 起: 输入框正上方的横栏, 只在终端) ----------------
691// 3 行版 (v0.15) = 6 像素高: 大螃蟹就是面板那只 (v0.16 直接用 scenePx: 按工具做动作 + 右边 3 列道具区 + 情绪), 占 15 格;
692// 小螃蟹 7x4 (v0.16: 比大螃蟹小一大截, 眼睛四周都有身体, 看前面时也只在身体里挪), 占下面两行
693// 天空行 (v0.16): 横栏放得下就在最上面空一行, 隔开上面的正文和螃蟹; 只有往上飘的粒子 (庆祝闪光 / 睡觉泡泡 / 思考点点) 能进去
694// 2 行版 = 4 像素高: 大螃蟹 9x4 (BIG2); 小螃蟹 3x2, 只占下面那行
695// 1 行版 = 2 像素高: 大螃蟹缩成 7x2 (占 9 格, 居中); 小螃蟹 3x2
696// 排队: 一维的路上谁也不能从谁身上穿过去, 所以左右顺序固定 [最新的小螃蟹 ... 最早的小螃蟹, 大螃蟹]
697// 往右走时小螃蟹跟在大螃蟹后面; 碰到一端整队一起掉头, 往左走时大螃蟹在后面赶着它们走
698// (按 "k 帧之前的位置" 跟着走的话, 掉头时每只都会和前面那只交叉重叠, 所以不用)
699// 大螃蟹什么时候走: 主会话在跑, 或者有子代理在跑 (速度跟心情); 全闲时每 20-40 秒溜达 3-8 格, 停下东张西望;
700// 5 分钟没有任何动静 (主会话 / 子代理 / 打字 / 发消息) 才睡; 打字时停下低头看输入框; 发出消息时跳一下
701// 粒子 (v0.15): 盲文点画在没有螃蟹的空格子里, 最多 24 个 (v0.16), 每个活 2-8 帧, 每帧最多挪 1 个点位, 只会慢慢变暗
702// 节奏: 每只每帧最多挪 1 格; 腿每 2-3 帧换一次; 身体颜色不闪
703export type Rows = 1 | 2 | 3
704// bw = 大螃蟹占的格数 (3 行版 = 螃蟹 12 + 右边道具区 3: 永远给道具留着地方, 不用镜像); cw = 螃蟹本身 (悬停区域); kw = 小螃蟹
705export const LANE_SIZE: Record<Rows, { bw: number; cw: number; kw: number }> = { 3: { bw: 15, cw: 12, kw: 7 }, 2: { bw: 9, cw: 9, kw: 3 }, 1: { bw: 9, cw: 9, kw: 3 } }
706export const TOOL_HOLD_FRAMES = laneFrames(600) // 工具刚结束的 600ms 里还算 "在用工具": 连着几个工具之间的空档不会走一格停一格
707const LANE_L = 5 // 放不下时左端留给暗色的 "+N"
708const LANE_ROAM = 6 // 小螃蟹再多也给整队留几格走动的地方
709export const SAY_FRAMES = laneFrames(4950) // 气泡显示多久 (约 5 秒)
710const WAVE_MS = 1500 // 子代理结束后挥手多久
711export const TYPE_FRAMES = laneFrames(1500) // 最后一次按键后多久恢复 (约 1.5 秒)
712export const BASH_IMPATIENT = laneFrames(15_000) // v1.4 跑命令 C: 同一条命令跑了这么久, 螃蟹等得不耐烦
713// 忙的时候每几帧走半格 (75ms 一帧, 半格一步: 和以前 "150ms 一帧, 一格一步" 一样快: 悠闲每格 750ms ... 慌张每格 150ms)
714const MOOD_STEP: Record<Mood, number> = { chill: 5, normal: 3, sweat: 2, panic: 1 }
715const STROLL_STEP = 3 // 溜达时每几帧走半格
716const STROLL_GAP = [laneFrames(20_000), laneFrames(40_000)] // 全闲时每隔多久溜达一次 (20-40 秒)
717const LOOK_FRAMES = laneFrames(3600) // 溜达完东张西望多久
718const LOOK_ALT = laneFrames(900) // 东张西望每 0.9 秒换一边
719// 发出消息那一跳 / 一轮结束连跳两下: 每格 75ms 一个姿势. lift = 离地多高 (像素, 负 = 往上, 进天空行; 只有 3 行版有天空行时才真的跳)
720type Leap = { lift: number; bob: number; legs: boolean; arms: Arm; squash?: boolean }
721const JUMP_PLAN: Leap[] = [
722 { lift: 0, bob: 1, legs: true, arms: 'out' }, // 蹲下蓄力
723 { lift: 0, bob: 1, legs: true, arms: 'out' },
724 { lift: -1, bob: 0, legs: true, arms: 'up' }, // 起跳
725 { lift: -2, bob: 0, legs: false, arms: 'up' }, // 最高, 收腿
726 { lift: -2, bob: 0, legs: false, arms: 'up' },
727 { lift: -2, bob: 0, legs: false, arms: 'up' },
728 { lift: -1, bob: 0, legs: true, arms: 'up' }, // 落下
729 { lift: 0, bob: 0, legs: true, arms: 'out', squash: true }, // 落地压扁 (冒尘土)
730 { lift: 0, bob: 0, legs: true, arms: 'out' }, // 弹回
731 { lift: 0, bob: 0, legs: true, arms: 'out' },
732]
733const JUMP_LANE = JUMP_PLAN.length // 发出消息那一跳占几个散步道帧 (750ms)
734const JUMP_LAND = 7 // 落地那一帧 (冒尘土)
735const HOP_PLAN: Leap[] = [
736 { lift: 0, bob: 1, legs: true, arms: 'up' }, // 蹲
737 { lift: -1, bob: 0, legs: true, arms: 'up' },
738 { lift: -2, bob: 0, legs: false, arms: 'up' },
739 { lift: -2, bob: 0, legs: false, arms: 'up' },
740 { lift: -1, bob: 0, legs: true, arms: 'up' },
741 { lift: 0, bob: 1, legs: true, arms: 'up' }, // 落地
742 { lift: 0, bob: 0, legs: true, arms: 'up' },
743 { lift: 0, bob: 0, legs: true, arms: 'up' },
744]
745const HOPS = 2 // 庆祝时连跳几下 (之后举着钳子原地颠, 和以前一样)
746const TURN_FRAMES = laneFrames(300) // 碰到一头: 停一下, 眼睛先看向回去的方向
747const HEAT_STEP = 1 / laneFrames(1000) // 变红 / 变回: 约 1 秒渐变
748const PULSE = laneFrames(600) // 上下文 >=95%: 一明一暗一个来回 600ms (和以前的闪一样快, 但是平滑)
749const PT_MAX = 24 // 同时最多几个粒子
750const DUST = 0x8a7f72 // 尘土: 暖灰
751const PT_DARK = 0x27272a // 粒子变暗的方向
752
753// state: walk = 在队里; wave = 子代理结束, 原地挥手; hop = 3 行版挥完往上跳出横栏 (还占着队里的位置, 后面的不会滑到它身下);
754// exit = 2 行版挥完走上面那行出去 (在 gone 里, 画在最底下)
755// hx = 最左边在第几个半格 (v0.19 起位置以半格为单位); x = 报告用的整格位置 (cellOf(hx))
756export type LaneKid = { id: string; hx: number; x: number; y: number; state: 'walk' | 'wave' | 'hop' | 'exit'; until: number; dir: 1 | -1 }
757// 粒子: 盲文点坐标 (每格 2 x 4 个点; y 从螃蟹区顶上算, 天空行是 -4..-1), 速度每轴 -1/0/1 (有两个轴时奇偶帧轮流动, 每帧只挪 1 个点位)
758// sky = 能不能进天空行 (只有往上飘的: 庆祝闪光 / 睡觉泡泡 / 思考点点)
759export type Particle = { x: number; y: number; vx: -1 | 0 | 1; vy: -1 | 0 | 1; age: number; life: number; color: number; sky: boolean; every: 1 | 2 }
760// greet = 鼠标停在大螃蟹上 (v0.16): 停下举钳打招呼, 队伍也停
761export type LanePose = 'greet' | 'celebrate' | 'jump' | 'type' | 'tool' | 'walk' | 'sleep' | 'doze' | 'wake' | 'idle'
762export type Lane = {
763 w: number // 宽度 (格)
764 rows: Rows // 螃蟹区几行 (不含天空行)
765 sky: boolean // 最上面有没有天空行
766 bw: number // 大螃蟹占几格 (3 行版含道具区)
767 cw: number // 大螃蟹本身几格
768 kw: number // 小螃蟹占几格
769 hx: number // 大螃蟹最左边在第几个半格 (v0.19: 位置以半格为单位, 可以是奇数 = 落在半格上)
770 bx: number // 大螃蟹最左一格 (= cellOf(hx), 气泡、悬停、粒子按格子算时用)
771 dir: 1 | -1
772 stepAt: number // 大螃蟹上次挪动的帧
773 steps: number // 走了多少个半格 (腿跟着它换)
774 kids: LaneKid[] // 队里的小螃蟹, 从右 (挨着大螃蟹) 到左
775 gone: LaneKid[] // 2 行版正在离场的
776 hidden: number // 放不下的子代理个数 (+N)
777 pt: Particle[]
778 strollLeft: number // 这次溜达还剩几格
779 strollAt: number // 下次溜达的帧 (-1 = 还没排)
780 lookUntil: number // 溜达完东张西望到哪一帧
781 celebAt: number // 这次庆祝从哪个 150ms 开始 (粒子用; -1 = 不在庆祝)
782 pose: LanePose
783 // v0.19 中间姿势:
784 heat: number // 身体有多红 (0..1, 渐变; -1 = 还没定, 第一帧直接取目标)
785 runSteps: number // 这次起步后走了几个半格 (前两步慢一点)
786 turnUntil: number // 碰到一头掉头: 停到哪一帧 (眼睛先看过去)
787 inGreet: boolean // 正在悬停打招呼
788 greetAt: number // 打招呼从哪一帧开始 (钳子先半举)
789 greetEnd: number // 打招呼在哪一帧结束 (钳子先回到半举)
790 celebStart: number // 庆祝从哪一帧开始 (连跳两下)
791 // v1.4 睡觉组合:
792 napping: WakeFrom | '' // 上一帧在睡的哪个阶段 ('' = 醒着; 一醒就蹦出来)
793 waking: number // 蹦出来还剩几帧
794 wakeAt: number // 从哪一帧醒的
795 wakeFrom: WakeFrom | '' // 从哪个阶段醒的
796}
797// 这一帧的处境: 散步道的时钟和渲染用同一份; tool = 主会话正在用的工具种类 ('' = 没有, 在想 / 在回复)
798// hold = 鼠标停在大螃蟹上 (或刚离开 0.5 秒内); lookAt = 指针在横栏别处时的列 (闲着时眼睛看过去), 没有就 undefined
799// pct = 上下文 % (身体颜色渐变要按帧算, 所以随处境一起给)
800export type LaneAct = {
801 working: boolean
802 agents: number
803 typing: boolean
804 celebrating: boolean
805 sleeping: boolean
806 jumpAge: number
807 md: Mood
808 tool: ToolKind | ''
809 hold: boolean
810 lookAt?: number
811 pct?: number
812 toolAge?: number
813 endAge?: number
814 ok?: boolean
815 arg?: string // v1.4: 这次工具的主要参数 (抓网页的网址、搜索词), 写在天空行
816 link?: string // v1.4: 搜索结束时的第一条结果网址
817 hits?: number // v1.4: 搜到几条
818 word?: string // v1.4: 搜索词前面那个字 (界面语言: 搜 / search)
819 idleF?: number // v1.4: 多少帧没有动静了 (4 分钟打瞌睡, 5 分钟钻沙)
820}
821
822// v1.4: 一次工具调用的进度 (散步道 Client 和 previewLane 共用). seq 变了 = 新的一次调用 (两次之间没有空档也认得出);
823// 工具名变成 '' = 结束了 (带上成没成功); 结束后再撑 TOOL_HOLD_FRAMES, 收尾的动作在这段里演
824export type ToolTrack = { kind: ToolKind | ''; seq: number; startF: number; endF: number; ok: boolean }
825export const newToolTrack = (): ToolTrack => ({ kind: '', seq: 0, startF: -999, endF: -1, ok: true })
826// 结束后再撑多久: 搜索的「找到了」要看得清链接 (约 1.8 秒), 抓网页的紫色网址约 0.9 秒, 其余 0.6 秒; 下一个工具来了马上换
827const endHold = (k: ToolKind | '') => (k === 'search' ? laneFrames(1800) : k === 'fetch' ? laneFrames(900) : TOOL_HOLD_FRAMES)
828export function trackTool(T: ToolTrack, f: number, kind: ToolKind | '', seq: number, ok: boolean) {
829 if (kind) {
830 if (!T.kind || T.endF >= 0 || seq !== T.seq) {
831 T.startF = f
832 T.endF = -1
833 T.ok = true
834 }
835 T.kind = kind
836 T.seq = seq
837 } else if (T.kind && T.endF < 0) {
838 T.endF = f
839 T.ok = ok
840 }
841 if (T.kind && T.endF >= 0 && f - T.endF >= endHold(T.kind)) T.kind = ''
842}
843export const toolAct = (T: ToolTrack, f: number) => ({ tool: T.kind, toolAge: f - T.startF, endAge: T.endF < 0 ? -1 : f - T.endF, ok: T.ok })
844export function newLane(w: number, rows: Rows = 3, sky = false): Lane {
845 const { bw, cw, kw } = LANE_SIZE[rows]
846 const bx = Math.max(0, Math.floor((w - bw) / 2))
847 return { w, rows, sky, bw, cw, kw, hx: bx * 2, bx, dir: 1, stepAt: 0, steps: 0, kids: [], gone: [], hidden: 0, pt: [], strollLeft: 0, strollAt: -1, lookUntil: -1, celebAt: -1, pose: 'idle', heat: -1, runSteps: 2, turnUntil: -1, inGreet: false, greetAt: -999, greetEnd: -999, celebStart: -999, napping: '', waking: 0, wakeAt: -999, wakeFrom: '' }
848}
849export const laneCap = (L: Lane) => Math.max(0, Math.floor((L.w - LANE_L - L.bw - LANE_ROAM) / (L.kw + 1)))
850const sgn = (n: number): -1 | 0 | 1 => (n > 0 ? 1 : n < 0 ? -1 : 0)
851// 半格位置 -> 报告用的整格位置: 向上取整 (落在半格上时从下一格算起; 按格子看画面时, 每格取左半边, 两边一致)
852export const cellOf = (hx: number) => (hx + 1) >> 1
853function syncCells(L: Lane) {
854 L.bx = cellOf(L.hx)
855 for (const k of L.kids) k.x = cellOf(k.hx)
856 for (const k of L.gone) k.x = cellOf(k.hx)
857}
858// 帧号做种子的伪随机 (测试里可复现)
859const rnd = (f: number, salt: number) => (Math.imul(f + 1, 2654435761) ^ Math.imul(salt + 7, 40503)) >>> 0
860
861// 宽度或行数变了: 宽度变 -> 整队平移回横栏里; 行数变 -> 螃蟹换尺寸, 小螃蟹按新尺寸重新排在大螃蟹后面
862export function laneFit(L: Lane, w: number, rows: Rows, sky: boolean) {
863 if (sky !== L.sky) {
864 L.sky = sky
865 L.pt = []
866 }
867 if (rows !== L.rows) {
868 const { bw, cw, kw } = LANE_SIZE[rows]
869 L.rows = rows
870 L.bw = bw
871 L.cw = cw
872 L.kw = kw
873 L.gone = []
874 L.pt = []
875 L.kids = L.kids.filter(k => k.state !== 'hop')
876 L.kids.forEach((k, i) => (k.hx = L.hx - 2 * (kw + 1) * (i + 1)))
877 }
878 if (w !== L.w || L.hx + 2 * L.bw > 2 * w) {
879 L.w = w
880 const shift = Math.min(0, 2 * (w - L.bw) - L.hx)
881 if (shift) {
882 L.hx += shift
883 for (const k of L.kids) k.hx += shift
884 }
885 if (L.hx < 0) L.hx = 0
886 }
887 L.kids = L.kids.slice(0, laneCap(L))
888 syncCells(L)
889}
890
891// 进队 / 出队 (不走动): 子代理结束 -> 原地挥手 WAVE_MS -> 3 行版往上跳出去, 2 行版走上面那行出去; 新的排到队尾
892export function laneSync(L: Lane, now: number, running: string[]): boolean {
893 let changed = false
894 const run = new Set(running)
895 for (const k of L.kids) {
896 if (k.state === 'walk' && !run.has(k.id)) {
897 k.state = 'wave'
898 k.until = now + WAVE_MS
899 changed = true
900 } else if (k.state === 'wave' && run.has(k.id)) {
901 k.state = 'walk'
902 changed = true
903 } else if (k.state === 'wave' && now >= k.until) {
904 changed = true
905 if (L.rows === 3) {
906 k.state = 'hop'
907 k.y = 2
908 } else {
909 k.state = 'exit'
910 k.dir = k.hx + L.kw < L.w ? -1 : 1 // 往近的那头走
911 L.gone.push(k)
912 }
913 }
914 }
915 L.kids = L.kids.filter(k => k.state !== 'exit')
916 const cap = laneCap(L)
917 const hslot = 2 * (L.kw + 1)
918 for (const id of running) {
919 if (L.kids.some(k => k.id === id)) continue
920 if (L.kids.length >= cap) break
921 const i = L.kids.length
922 const right = i ? (L.kids[i - 1]?.hx ?? L.hx) : L.hx // 右边邻居; 新来的放在队尾, 不和它挨着
923 const hx = Math.min(L.hx - hslot * (i + 1), right - hslot)
924 L.kids.push({ id, hx, x: cellOf(hx), y: 0, state: 'walk', until: 0, dir: 1 })
925 changed = true
926 }
927 const shown = L.kids.filter(k => k.state === 'walk').length
928 const hidden = Math.max(0, running.length - shown)
929 if (hidden !== L.hidden) {
930 L.hidden = hidden
931 changed = true
932 }
933 return changed
934}
935
936// 这一帧大螃蟹是什么姿势: 庆祝 > 跳 > 打字低头 > 用工具 (停下做动作) > 走 (在想 / 在回复 / 子代理在跑 / 溜达) > 睡 > 趴着
937export function lanePose(L: Lane, a: LaneAct): LanePose {
938 if (L.waking > 0) return 'wake' // v1.4: 刚醒: 先蹦出来 (0.6 秒内), 再做接下来的事
939 return poseNow(L, a)
940}
941function poseNow(L: Lane, a: LaneAct): LanePose {
942 if (a.hold) return 'greet'
943 if (a.celebrating) return 'celebrate'
944 if (a.jumpAge >= 0 && a.jumpAge < JUMP_LANE) return 'jump'
945 if (a.typing) return 'type'
946 if (a.tool) return 'tool'
947 if (a.working || a.agents > 0 || L.strollLeft > 0) return 'walk'
948 // v1.4: 慌张时不睡 (原来就是: 慌张会把睡着的叫醒); 闲 5 分钟钻沙睡, 4 分钟打瞌睡
949 if (a.md !== 'panic' && a.sleeping) return 'sleep'
950 if (a.md !== 'panic' && (a.idleF ?? 0) >= DOZE_FRAMES && L.rows === 3) return 'doze'
951 return 'idle'
952}
953
954// 粒子能到的最上面一行点: 能进天空行的到 -4, 其余到螃蟹区顶边 0
955const ptTop = (L: Lane, sky: boolean) => (sky && L.sky ? -4 : 0)
956function addPt(L: Lane, x: number, y: number, vx: -1 | 0 | 1, vy: -1 | 0 | 1, life: number, color: number, sky = false, every: 1 | 2 = 1) {
957 if (L.pt.length >= PT_MAX) return
958 if (x < 0 || y < ptTop(L, sky) || x >= L.w * 2 || y >= L.rows * 4) return
959 L.pt.push({ x, y, vx, vy, age: 0, life: Math.max(2, Math.min(8, life)), color, sky, every })
960}
961
962// 粒子按 150ms 的节奏走 (散步道的偶数帧; 和以前一样快): 活着的走一步, 到寿命就消失
963// 每粒的方向 (vx, vy) 和快慢 (every: 每 1 个或每 2 个 150ms 挪一次) 略有不同, 散开飘, 不排成一条线
964function ageParticles(L: Lane) {
965 for (const p of L.pt) {
966 p.age += 1
967 if (p.age % p.every) continue // 慢的那些隔一次才挪
968 // 两个轴都有速度时轮流动: 每次只挪 1 个点位
969 if (p.vx && p.vy) {
970 if ((p.age / p.every) % 2) p.x += p.vx
971 else p.y += p.vy
972 } else {
973 p.x += p.vx
974 p.y += p.vy
975 }
976 }
977 L.pt = L.pt.filter(p => p.age < p.life && p.x >= 0 && p.y >= ptTop(L, p.sky) && p.x < L.w * 2 && p.y < L.rows * 4)
978}
979
980// 持续冒的粒子 (也按 150ms 的节奏; t = 第几个 150ms). 盲文点每格横着 2 个 = 半格, 和半格位置 hx 同一个单位
981function emitParticles(L: Lane, t: number, a: LaneAct, pose: LanePose) {
982 const H = L.rows * 4 // 点的行数
983 const back = L.dir > 0 ? L.hx - 2 : L.hx + 2 * L.cw // 脚后那一格 (往右走: 螃蟹左边; 往左走: 螃蟹右边)
984 const away = (L.dir > 0 ? -1 : 1) as -1 | 1 // 往后
985 const fast = a.md === 'sweat' || a.md === 'panic'
986 const busy = a.working || a.agents > 0
987 const trot = fast && busy
988 // 走路扬尘: 每 1-2 个 150ms 从脚后冒 1 粒, 每粒活 4-8 个 150ms, 往后上方散开 -> 平时同时 3-5 粒; 小跑时每次都冒, 活得久一点 -> 5-7 粒
989 if (pose === 'walk') {
990 const r = rnd(t, 1)
991 if (trot || t % 3 !== 2) {
992 const vy = (r % 3 === 0 ? 0 : -1) as -1 | 0 // 大多往上飘, 少数贴着地往后走
993 const vx = (r % 4 === 1 ? 0 : away) as -1 | 0 | 1 // 大多往后, 少数直着往上
994 const life = trot ? 6 + (r % 2) : 4 + (r % 2) + (t % 3 === 0 ? 1 : 0)
995 addPt(L, back + (t % 2), H - 1 - (r % 2), vx, vy, life, DUST, false, r % 5 === 0 ? 2 : 1)
996 }
997 // 小跑: 偶尔甩出一滴蓝色汗珠 (往后下方落)
998 if (trot && rnd(t, 4) % 12 === 0) addPt(L, back, 2, away, 1, 5, mix(COL.sweat, PT_DARK, 0.25))
999 }
1000 // 一轮结束庆祝: 螃蟹两边冒一小圈金色闪光, 往上飘进天空行消失 (分三波, 同时 6-10 粒)
1001 if (pose === 'celebrate') {
1002 if (L.celebAt < 0) L.celebAt = t
1003 const age = t - L.celebAt
1004 const wave = age === 0 ? 5 : age === 2 ? 3 : age === 4 ? 2 : 0
1005 const left = L.hx - 1
1006 const right = L.hx + 2 * L.cw
1007 for (let i = 0; i < wave; i++) {
1008 const k = i + age * 3
1009 const onRight = k % 2 === 1
1010 const x = onRight ? right + ((k >> 1) % 3) : left - ((k >> 1) % 3)
1011 const y = H - 2 - ((k * 3) % Math.max(1, H - 2))
1012 addPt(L, x, y, (k >> 1) % 2 ? (onRight ? 1 : -1) : 0, -1, 5 + (rnd(t, 10 + i) % 3), mix(COL.spark, PT_DARK, 0.25), true, k % 3 === 0 ? 2 : 1)
1013 }
1014 } else L.celebAt = -1
1015 // v1.4 钻沙: 刨的时候每 150ms 往右上方扬一粒沙
1016 const nap = pose === 'sleep' ? napOf(a.idleF ?? 0) : undefined
1017 if (nap?.stage === 'burrow' && nap.s < 18 && L.rows === 3) addPt(L, L.hx + 25, 8, 1, -1, 5, COL.sand, true)
1018 // 睡着: 头边慢慢冒泡泡 (每 12 个 150ms 一个), 往上飘进天空行
1019 if (pose === 'sleep' && t % 12 === 0) {
1020 const x = L.hx + 2 * L.bw < 2 * L.w ? L.hx + 2 * L.bw : L.hx - 1
1021 addPt(L, x, Math.min(H - 1, 5), 0, -1, 5, mix(COL.bubble, PT_DARK, 0.3), true)
1022 }
1023 // v1.4 跑命令 C (同一条命令跑了 15 秒以上): 屏幕上方冒热气, 每 3 个 150ms 一缕, 往上飘 4 步, 越高越暗
1024 if (pose === 'tool' && a.tool === 'bash' && (a.endAge ?? -1) < 0 && (a.toolAge ?? 0) >= BASH_IMPATIENT && L.sky && L.rows === 3 && t % 3 === 0) {
1025 addPt(L, L.hx + 2 * (12 + (Math.floor(t / 3) % 3)), -1, 0, -1, 4, COL.termOut, true)
1026 }
1027 // 在想 / 在回复 (主会话在跑但没有工具): 头顶冒思考点点, 往上飘进天空行 (没有天空行就不冒, 头顶就是格子边)
1028 if (pose === 'walk' && a.working && !a.tool && L.sky && t % 5 === 0) {
1029 const head = L.hx + 2 * (Math.floor(L.cw / 2) + (Math.floor(t / 5) % 3) - 1)
1030 addPt(L, head + (Math.floor(t / 5) % 2), -1, 0, -1, 4 + (rnd(t, 30) % 2), mix(COL.thought, PT_DARK, 0.2), true, 2)
1031 }
1032}
1033
1034// 一次性的粒子, 在发生的那一帧冒 (哪一帧都可能): 发出消息那一跳落地 / 小螃蟹离场
1035function laneBursts(L: Lane, a: LaneAct, pose: LanePose, exits: LaneKid[]) {
1036 // v1.4 抓网页收完 (结束后第 4 帧): 两点亮光往上飘进天空行
1037 if (pose === 'tool' && a.tool === 'fetch' && L.sky && L.rows === 3 && a.endAge === 4) {
1038 addPt(L, L.hx + 25, -1, 0, -1, 4, COL.spark, true)
1039 addPt(L, L.hx + 27, -2, 0, -1, 4, COL.spark, true)
1040 }
1041 // v1.4 改文件翻页的第 3 帧: 天空行里扬起两点灰
1042 if (pose === 'tool' && a.tool === 'edit' && L.sky && L.rows === 3 && editPhase(a.toolAge ?? 0, a.endAge ?? -1).flip === 3) {
1043 addPt(L, L.hx + 22, -2, 0, -1, 3, COL.termOut, true)
1044 addPt(L, L.hx + 31, -1, 0, -1, 3, COL.termOut, true)
1045 }
1046 // 落地 (压扁的那一帧): 两只脚边冒 5 粒, 往两边散
1047 if (pose === 'jump' && a.jumpAge === JUMP_LAND) {
1048 const H = L.rows * 4
1049 const lx = L.hx - 1
1050 const rx = L.hx + 2 * L.cw
1051 addPt(L, lx, H - 1, -1, -1, 5, DUST)
1052 addPt(L, lx, H - 2, -1, 0, 4, DUST, false, 2)
1053 addPt(L, rx, H - 1, 1, -1, 5, DUST)
1054 addPt(L, rx, H - 2, 1, 0, 4, DUST, false, 2)
1055 addPt(L, rx + 1, H - 1, 1, -1, 6, DUST, false, 2)
1056 }
1057 // 小螃蟹离场: 出口处冒一小团 (5 粒, 往四周散)
1058 for (const k of exits) {
1059 const cx = L.rows === 3 ? k.hx + 8 : k.dir < 0 ? 1 : L.w * 2 - 2
1060 const cy = L.rows === 3 ? 0 : 1
1061 addPt(L, cx, cy, -1, 0, 4, DUST)
1062 addPt(L, cx + 1, cy, 1, 0, 4, DUST)
1063 addPt(L, cx, cy + 1, 0, 1, 4, DUST, false, 2)
1064 addPt(L, cx + 1, cy + 1, 1, 1, 5, DUST, false, 2)
1065 addPt(L, cx - 1, cy + 1, -1, 1, 5, DUST)
1066 }
1067}
1068
1069// 这一帧身体有多红 (0..1): 平时按 heat (渐变); 上下文 >=95% 时一明一暗 (平滑的呼吸, 600ms 一个来回)
1070function bodyMixOf(L: Lane, f: number, a: LaneAct): number {
1071 const heat = L.heat >= 0 ? L.heat : (a.pct ?? 0) >= 80 ? 1 : 0
1072 if ((a.pct ?? 0) < 95) return heat
1073 return heat * (0.55 + 0.45 * Math.cos((2 * Math.PI * f) / PULSE))
1074}
1075// 这一帧在跳 / 庆祝连跳的哪个姿势 (只有 3 行版有天空行时; 其余照旧)
1076function leapOf(L: Lane, f: number, a: LaneAct): Leap | undefined {
1077 if (L.rows !== 3 || !L.sky) return undefined
1078 if (L.pose === 'jump') return JUMP_PLAN[a.jumpAge]
1079 if (L.pose === 'celebrate') {
1080 const c = f - L.celebStart
1081 return c >= 0 && c < HOPS * HOP_PLAN.length ? HOP_PLAN[c % HOP_PLAN.length] : undefined
1082 }
1083 return undefined
1084}
1085
1086// 走路的节奏: 忙的时候跟心情, 溜达时固定; 每几帧走半格
1087const stepFrames = (a: LaneAct) => (a.working || a.agents > 0 ? MOOD_STEP[a.md] : STROLL_STEP)
1088// 走路时交给 scenePx / miniPx 的帧号 (它们按 floor(帧 / 2) 换腿、上下颠): 腿跟着步子换, 每走半格换一次
1089// (小跑每走一格换一次, 不然腿换得太快); 被挡住走不动 (原地踏步) 时按 150ms 的节奏换, 和以前一样
1090function walkFrame(L: Lane, f: number, a: LaneAct): number {
1091 const sf = stepFrames(a)
1092 if (f - L.stepAt > 2 * sf + 2) return Math.floor(f / PER)
1093 return 2 * Math.floor(L.steps / (sf === 1 ? 2 : 1))
1094}
1095
1096// 走一帧 (只是算位置和粒子, 不碰 $); 返回这一帧画面有没有变化
1097export function laneStep(L: Lane, f: number, now: number, a: LaneAct, running: string[]): boolean {
1098 const t = Math.floor(f / PER) // 第几个 150ms: 粒子和往上跳出去的小螃蟹按这个节奏 (和以前一样快)
1099 const slow = f % PER === 0
1100 let changed = laneSync(L, now, running)
1101 if (L.kids.some(k => k.state === 'wave')) changed = true // 挥手的钳子在动
1102 // 3 行版往上跳出去的: 每 150ms 升 1 像素, 整只出了顶边才让出队里的位置
1103 const exits: LaneKid[] = []
1104 if (slow) {
1105 for (const k of L.kids) {
1106 if (k.state !== 'hop') continue
1107 k.y -= 1
1108 changed = true
1109 if (k.y + 4 <= 0) exits.push(k)
1110 }
1111 }
1112 L.kids = L.kids.filter(k => !exits.includes(k))
1113 // 2 行版走上面那行出去的: 每帧半格
1114 for (const k of L.gone) {
1115 k.hx += k.dir
1116 changed = true
1117 if (k.hx + 2 * L.kw <= 0 || k.hx >= 2 * L.w) exits.push(k)
1118 }
1119 L.gone = L.gone.filter(k => !exits.includes(k))
1120 // 溜达的排程: 只在全闲时 (不忙、不打字、不跳、不庆祝、没睡) 才排; 一忙起来就清掉
1121 const busy = a.working || a.agents > 0
1122 const calm = !busy && !a.hold && !a.typing && !a.celebrating && !a.sleeping && (a.idleF ?? 0) < DOZE_FRAMES && !(a.jumpAge >= 0 && a.jumpAge < JUMP_LANE)
1123 if (!calm) {
1124 L.strollLeft = 0
1125 L.strollAt = -1
1126 } else {
1127 if (L.strollAt < 0) L.strollAt = f + STROLL_GAP[0] + (rnd(f, 20) % (STROLL_GAP[1] - STROLL_GAP[0]))
1128 if (L.strollLeft === 0 && f >= L.strollAt) {
1129 L.strollLeft = 2 * (3 + (rnd(f, 21) % 6)) // 3-8 格 = 6-16 个半格
1130 L.dir = rnd(f, 22) % 2 ? 1 : -1
1131 L.strollAt = Number.MAX_SAFE_INTEGER // 走完再排下一次
1132 }
1133 }
1134 // v1.4: 上一帧在睡 (打瞌睡 / 钻沙 / 戴睡帽), 这一帧有了动静 (来活、打字、鼠标停上来、慌张): 先蹦出来
1135 if (L.waking > 0) L.waking -= 1
1136 const next = poseNow(L, a)
1137 const nap = next === 'doze' ? 'doze' : next === 'sleep' ? ((napOf(a.idleF ?? SLEEP_LANE + BURROW + CAP_DROP)?.stage === 'burrow' ? 'burrow' : 'cap') as WakeFrom) : ''
1138 if (L.napping && !nap && L.rows === 3) {
1139 L.wakeFrom = L.napping
1140 L.wakeAt = f
1141 L.waking = L.napping === 'doze' ? WAKE_DOZE : WAKE_DEEP
1142 // 从沙里蹦出来: 沙子往八个方向炸开 (能飞进天空行)
1143 if (L.napping !== 'doze') {
1144 const burst: Array<[number, -1 | 0 | 1, -1 | 0 | 1]> = [
1145 [-3, -1, -1],
1146 [-1, -1, -1],
1147 [1, 1, -1],
1148 [3, 1, -1],
1149 [5, 1, 0],
1150 [-5, -1, 0],
1151 [0, 0, -1],
1152 [2, 0, -1],
1153 ]
1154 for (const [dx, vx, vy] of burst) addPt(L, L.hx + 12 + dx, 6, vx, vy, 5, COL.sand, true)
1155 }
1156 }
1157 L.napping = nap
1158 const prev = L.pose
1159 const pose = lanePose(L, a)
1160 if (pose !== L.pose) {
1161 L.pose = pose
1162 changed = true
1163 }
1164 if (pose === 'idle' && f < L.lookUntil) changed = true // 东张西望
1165 // 悬停打招呼的开始 / 结束 (钳子分两步举起 / 放下); 走廊的指针事件会直接把姿势改成 greet, 所以按 inGreet 认, 不按 prev
1166 if (pose === 'greet' && !L.inGreet) {
1167 L.inGreet = true
1168 L.greetAt = f
1169 } else if (pose !== 'greet' && L.inGreet) {
1170 L.inGreet = false
1171 L.greetEnd = f
1172 changed = true
1173 }
1174 if (pose !== 'greet' && f - L.greetEnd <= 1) changed = true
1175 // 开始走: 从这一帧起算, 前两步慢一点 (起步加速)
1176 if (pose === 'walk' && prev !== 'walk') {
1177 L.runSteps = 0
1178 L.stepAt = f
1179 }
1180 if (pose === 'celebrate' && prev !== 'celebrate') L.celebStart = f
1181 if (pose === 'jump' || pose === 'celebrate') changed = true
1182 // 身体颜色: 上下文到 80% 时约 1 秒渐渐变红, 掉下来时渐渐变回; >=95% 时一直在一明一暗
1183 const target = (a.pct ?? 0) >= 80 ? 1 : 0
1184 if (L.heat < 0) L.heat = target
1185 else if (L.heat !== target) {
1186 L.heat = target > L.heat ? Math.min(target, L.heat + HEAT_STEP) : Math.max(target, L.heat - HEAT_STEP)
1187 changed = true
1188 }
1189 if ((a.pct ?? 0) >= 95) changed = true
1190 // 停下来 (用工具 / 趴着 / 打字 / 庆祝 / 跳 / 睡) 时落在半格上: 往右补半格, 落在整格上 (道具区的纸、地球、终端画得清楚);
1191 // 报告的整格位置 (向上取整) 不变. 鼠标悬停 (greet) 立刻停, 不补
1192 if (pose !== 'walk' && pose !== 'greet' && L.hx % 2 !== 0 && L.hx + 1 + 2 * L.bw <= 2 * L.w) {
1193 L.hx += 1
1194 changed = true
1195 }
1196 const m = L.kids.length
1197 const lo = L.hidden ? LANE_L : 0
1198 const slot = L.kw + 1
1199 const hslot = 2 * slot
1200 let dBig: -1 | 0 | 1 = 0hooks/walkway.tsx 276 lines1// cc-hud: 螃蟹散步道 (v0.16 起是一个 Client 模块, 跑在终端的绘制线程上)
2//
3// hooks (register.tsx) 只把处境当 props 传进来: 忙不忙、心情、当前工具、上下文 %、运行中的子代理、事件气泡、
4// 打字 / 发送 / 庆祝的序号、多久没动静了、悬停时的用量摘要和小贴士; 以及宽度、行数、有没有天空行
5// 模块自己用帧钟 (surface.every, 75ms 一帧; v0.19 起走路半格一步) 推进: 走路、排队、粒子、气泡几秒后消失、5 分钟睡着、工具刚结束再撑 4 帧
6// 鼠标停在大螃蟹上 (只有全屏模式有指针事件): 大螃蟹立刻停下举钳, 队伍也停; 气泡在停下那一刻定好位置和全文;
7// 指针离开约 0.5 秒后接着走; 指针在横栏别处时, 闲着的螃蟹眼睛看过去. 点击不做任何事 (点一下 Client 会拿走键盘焦点)
8// 终端的 Client 里没有 Raster: 半格像素画成 Text (上像素当 color, 下像素当 backgroundColor), 同色的连续格子合成一段
9// 像素本身 (大螃蟹 / 小螃蟹 / 粒子) 和以前一样由 sprites.ts 生成
10
11import {
12 LANE_MS,
13 laneFrames,
14 SAY_FRAMES,
15 TYPE_FRAMES,
16 newToolTrack,
17 trackTool,
18 toolAct,
19 DEF,
20 DIM,
21 VALUE,
22 newLane,
23 laneFit,
24 laneStep,
25 lanePose,
26 lanePx,
27 laneCells,
28 bubbleSpot,
29 captionOf,
30 tipFit,
31 isWide,
32 type Lane,
33 type LaneAct,
34 type Mood,
35 type ToolKind,
36 type ToolTrack,
37 type Rows,
38} from './sprites'
39
40export type WalkProps = {
41 w: number // 宽度 (格)
42 rows: Rows // 螃蟹区几行 (不含天空行)
43 sky: boolean // 最上面有没有天空行
44 working: boolean // 主会话一轮在跑
45 agents: string[] // 运行中的子代理 (按开始时间)
46 mood: Mood
47 pct: number // 上下文 %
48 tool: ToolKind | '' // 主会话正在用的工具 ('' = 没有: 在想 / 在回复)
49 toolSeq: number // v1.4: 主会话第几次工具调用 (变了 = 新的一次, 两次之间没空档也认得出)
50 toolEnd: { seq: number; ok: boolean; link?: string; hits?: number } // v1.4: 最近结束的那次调用和成没成功 (收尾: 跑完变绿之类); 搜索还带第一条结果和条数
51 toolArg: string // v1.4: 最近一次工具的主要参数 (抓网页的网址、搜索词), 写在天空行
52 searchWord: string // v1.4: 搜索词前面那个字 (界面语言)
53 typeSeq: number // 打字的序号 (变了 = 刚按了键)
54 jumpSeq: number // 发出消息的序号
55 celebSeq: number // 一轮结束的序号
56 celebFrames: number // 这次庆祝多少帧
57 say?: { seq: number; text: string; color: string } // 最近一条事件气泡
58 idleMs: number // 多久没动静了 (hooks 记的)
59 tip: { v: string[]; tipMin: number } // 悬停气泡: 从长到短 4 种写法 + 小贴士最少要留的宽度
60}
61
62type St = {
63 L: Lane
64 f: number // 帧号
65 typeSeq: number
66 typeUntil: number // 打字低头到哪一帧
67 jumpSeq: number
68 jumpAt: number // 跳的那一帧
69 celebSeq: number
70 celebUntil: number
71 saySeq: number
72 sayUntil: number // 事件气泡显示到哪一帧
73 lastBusyF: number // 最后一次有动静的帧 (5 分钟 = 2000 帧没动静就睡)
74 track: ToolTrack // 这次工具调用的进度 (开始 / 结束 / 成没成功; 结束后再撑 TOOL_HOLD_FRAMES)
75 hover: boolean // 指针正停在大螃蟹上
76 holdUntil: number // 指针离开后再停到哪一帧
77 spot?: { x: number; text: string } // 悬停气泡 (停下那一刻定好的位置和全文)
78 ptrX?: number // 指针在横栏里的列 (不在就 undefined)
79 sig: string // 上一次画出来的样子 (没变就不重画)
80}
81
82const SLEEP_FRAMES = laneFrames(5 * 60_000)
83const HOLD_FRAMES = laneFrames(450) // 指针离开后约 0.5 秒接着走
84const live = new WeakMap<object, WalkProps>() // 帧钟回调里拿最新的 props (回调是第一次画的时候建的)
85
86const hexOf = (c: number) => (c === DEF || c < 0 ? undefined : '#' + c.toString(16).padStart(6, '0'))
87
88function actOf(st: St, p: WalkProps): LaneAct {
89 const hold = st.hover || st.f < st.holdUntil
90 return {
91 working: p.working,
92 agents: p.agents.length,
93 typing: st.f < st.typeUntil,
94 celebrating: st.f < st.celebUntil,
95 sleeping: st.f - st.lastBusyF > SLEEP_FRAMES,
96 idleF: st.f - st.lastBusyF,
97 jumpAge: st.f - st.jumpAt,
98 md: p.mood,
99 ...toolAct(st.track, st.f),
100 arg: p.toolArg,
101 word: p.searchWord,
102 ...(p.toolEnd.seq === st.track.seq && p.toolEnd.link ? { link: p.toolEnd.link } : {}),
103 ...(p.toolEnd.seq === st.track.seq && p.toolEnd.hits !== undefined ? { hits: p.toolEnd.hits } : {}),
104 hold,
105 lookAt: hold ? undefined : st.ptrX,
106 pct: p.pct,
107 }
108}
109
110type Cell = { ch: string; fg?: string; bg?: string }
111// 这一帧的样子: 每行一串格子 (含天空行、事件气泡、+N、悬停气泡)
112function view(st: St, p: WalkProps): Cell[][] {
113 const L = st.L
114 const a = actOf(st, p)
115 L.pose = lanePose(L, a)
116 const top = L.sky ? 1 : 0
117 const total = L.rows + top
118 // 半格像素 (宽 2 x 格数), 含天空行 (平时空着; 大螃蟹跳起来时会进去)
119 const hp = lanePx(L, st.f, a, p.pct)
120 const words = laneCells(hp, L.w, total, L.pt, top * 4)
121 const grid: Cell[][] = []
122 for (let r = 0; r < total; r++) {
123 const row: Cell[] = []
124 for (let c = 0; c < L.w; c++) {
125 const i = (r * L.w + c) * 3
126 const cp = words[i]
127 row.push(cp === 32 ? { ch: ' ' } : { ch: String.fromCodePoint(cp), fg: hexOf(words[i + 1]), bg: hexOf(words[i + 2]) })
128 }
129 grid.push(row)
130 }
131 // 盖在像素上面的字: 放不下的子代理 +N (最下面一行左端) / 事件气泡 / 悬停气泡 (都在螃蟹区第一行, 不进天空行)
132 const write = (r: number, x0: number, text: string, color: string) => {
133 let x = x0
134 for (const ch of text) {
135 const w = isWide(ch.codePointAt(0) ?? 0) ? 2 : 1
136 if (x < 0 || x + w > L.w) break
137 grid[r][x] = { ch, fg: color }
138 if (w === 2) grid[r][x + 1] = { ch: '' }
139 x += w
140 }
141 }
142 if (L.hidden) write(total - 1, 0, '+' + L.hidden, DIM)
143 // v1.4 天空行的字 (网址 / 搜索词 / 结果链接); 右边摆着大道具时气泡放左边
144 const caps = captionOf(L, a)
145 for (const c of caps) write(0, c.x, c.text, hexOf(c.color) ?? VALUE)
146 const wide = L.pose === 'tool' && (a.tool === 'fetch' || a.tool === 'search')
147 if (p.say && st.f < st.sayUntil && !(a.hold && st.spot)) {
148 const s = bubbleSpot(L, p.say.text, wide)
149 if (s) write(top, s.x, s.text, p.say.color)
150 }
151 if (a.hold && st.spot) write(top, st.spot.x, st.spot.text, VALUE)
152 return grid
153}
154
155// 一行格子 -> 同色连续的几段 Text
156// (Client 的一棵树最多 20,000 个节点: 最坏每格一段, 512 宽 x 4 行也只有约 2,050 个, 离上限很远)
157function segments(row: Cell[]): Cell[] {
158 const out: Cell[] = []
159 for (const c of row) {
160 const last = out[out.length - 1]
161 if (c.ch === '') {
162 if (last) last.ch += ''
163 continue
164 }
165 if (last && last.fg === c.fg && last.bg === c.bg) last.ch += c.ch
166 else out.push({ ...c })
167 }
168 return out
169}
170
171function start(p: WalkProps): St {
172 return {
173 L: newLane(p.w, p.rows, p.sky),
174 f: 0,
175 typeSeq: p.typeSeq,
176 typeUntil: -1,
177 jumpSeq: p.jumpSeq,
178 jumpAt: -999,
179 celebSeq: p.celebSeq,
180 celebUntil: -1,
181 saySeq: p.say?.seq ?? 0,
182 sayUntil: -1,
183 lastBusyF: -Math.round(p.idleMs / LANE_MS),
184 track: newToolTrack(),
185 hover: false,
186 holdUntil: -1,
187 sig: '',
188 }
189}
190
191export default function Walkway(props: WalkProps, surface: any) {
192 const { Box, Text } = surface.elements
193 live.set(surface, props)
194 if (surface.state === undefined) {
195 surface.setState(start(props))
196 surface.every(LANE_MS, () => {
197 const st: St = surface.state
198 const p = live.get(surface)
199 if (!st || !p) return
200 st.f += 1
201 // 新事件 (按序号认): 打字 -> 低头 1.5 秒; 发送 -> 跳; 一轮结束 -> 庆祝; 新气泡 -> 显示约 5 秒
202 if (p.typeSeq !== st.typeSeq) {
203 st.typeSeq = p.typeSeq
204 st.typeUntil = st.f + TYPE_FRAMES
205 st.lastBusyF = st.f
206 }
207 if (p.jumpSeq !== st.jumpSeq) {
208 st.jumpSeq = p.jumpSeq
209 st.jumpAt = st.f
210 st.lastBusyF = st.f
211 }
212 if (p.celebSeq !== st.celebSeq) {
213 st.celebSeq = p.celebSeq
214 st.celebUntil = st.f + p.celebFrames
215 }
216 if (p.say && p.say.seq !== st.saySeq) {
217 st.saySeq = p.say.seq
218 st.sayUntil = st.f + SAY_FRAMES
219 }
220 if (p.working || p.agents.length) st.lastBusyF = st.f
221 trackTool(st.track, st.f, p.tool, p.toolSeq, p.toolEnd.seq === p.toolSeq ? p.toolEnd.ok : true)
222 if (!st.hover && st.f >= st.holdUntil) st.spot = undefined
223 laneFit(st.L, p.w, p.rows, p.sky)
224 laneStep(st.L, st.f, st.f * LANE_MS, actOf(st, p), p.agents)
225 // 画面没变就不重画 (闲着、没有子代理、也没有气泡时, 只在眨眼之类的时候画)
226 const sig = JSON.stringify(view(st, p).map(segments))
227 if (sig !== st.sig) {
228 st.sig = sig
229 surface.setState({ ...st })
230 }
231 })
232 // 鼠标: 停在大螃蟹的格子上 -> 停下举钳 + 气泡; 离开 -> 约 0.5 秒后接着走; 按下 / 松开不理 (不做点击)
233 surface.onPointer((e: any) => {
234 const st: St = surface.state
235 const p = live.get(surface)
236 if (!st || !p || e.type === 'down' || e.type === 'up') return
237 const L = st.L
238 const top = L.sky ? 1 : 0
239 if (e.type === 'leave') {
240 if (st.hover) st.holdUntil = st.f + HOLD_FRAMES
241 st.hover = false
242 st.ptrX = undefined
243 } else {
244 const hit = e.x >= L.bx && e.x < L.bx + L.cw && e.y >= top && e.y < top + L.rows
245 if (hit && !st.hover) {
246 st.hover = true
247 st.lastBusyF = st.f // v1.4: 鼠标停上来 = 你在: 睡着的蹦出来, 再过 4 分钟才打瞌睡
248 L.pose = 'greet'
249 st.spot = bubbleSpot(L, tipFit(p.tip.v, p.tip.tipMin))
250 } else if (!hit && st.hover) {
251 st.hover = false
252 st.holdUntil = st.f + HOLD_FRAMES
253 }
254 st.ptrX = e.x
255 }
256 surface.setState({ ...st })
257 })
258 }
259 const st: St = surface.state ?? start(props)
260 laneFit(st.L, props.w, props.rows, props.sky)
261 const rows = view(st, props).map(segments)
262 return (
263 <Box key="walk" flexDirection="column" width={props.w} height={rows.length}>
264 {rows.map((segs, r) => (
265 <Box key={'walk-r' + r} flexDirection="row" height={1}>
266 {segs.map(s => (
267 <Text color={s.fg} backgroundColor={s.bg}>
268 {s.ch}
269 </Text>
270 ))}
271 </Box>
272 ))}
273 </Box>
274 )
275}
276hooks/strings.ts 405 lines1// cc-hud 的界面文字: 英文 (默认) 和中文两套, 键一模一样 (测试会核对)
2// 纯数据 + 纯函数, 不碰 $: register.tsx 和 desktop.ts 都直接 import
3//
4// 终端里只用 ASCII、中文、`│ ─ ━ ✓` 和方块字符; 「」!? 只用在散步道的气泡和 toast 里
5// 宽度有讲究的地方 (面板标签、"40m用完" 这种附加文字) 改动时要对一下 register.tsx 里的列宽
6
7export type Lang = 'en' | 'zh'
8
9const zh = {
10 // 面板标签 (网格第一列; 标签列宽 = 当前语言里最宽的那个)
11 label: {
12 model: '模型',
13 project: '项目',
14 session: '本会话',
15 context: '上下文',
16 h5: '5小时',
17 week: '本周',
18 status: '状态',
19 tools: '工具',
20 token: 'token',
21 },
22 compact: '压缩',
23 // 用量条后面那段: 预计用完 / 重置倒计时
24 runOut: (d: string) => d + '用完',
25 resetIn: (d: string) => d + ' 重置',
26 // 状态
27 thinking: '思考中',
28 tool: {
29 Read: '读文件',
30 Grep: '搜内容',
31 Glob: '找文件',
32 Edit: '改文件',
33 MultiEdit: '改文件',
34 Write: '写文件',
35 NotebookEdit: '改笔记本',
36 Bash: '跑命令',
37 PowerShell: '跑命令',
38 WebSearch: '搜网页',
39 WebFetch: '读网页',
40 Agent: '派子代理',
41 Task: '派子代理',
42 SendMessage: '发消息',
43 TodoWrite: '记待办',
44 Skill: '用技能',
45 ToolSearch: '找工具',
46 } as Record<string, string>,
47 ready: '✓ 待命',
48 lastTurn: (d: string, n: string) => '✓ 上一轮 ' + d + ',' + n + ' 次工具',
49 kidsBusy: '子代理在跑',
50 kidsChip: (n: string) => '+' + n + '代理',
51 noTools: '还没有',
52 counting: '统计中..',
53 sinceLaunch: ' 本次启动',
54 // v1.4: 工具栏上的「今天用了 21% · 每天能用 20%」(颜色分段画, 所以拆开); short = 位置不够时的「今天 21/20%」
55 share: { today: '今天用了 ', perDayPre: '每天能用 ', perDaySuf: '', short: '今天 ' },
56 // 客户端卡片
57 desk: {
58 runOut: (d: string) => d + ' 用完',
59 kidsTail: (n: string) => ' +' + n + ' 个子代理',
60 kidsRunning: (n: string) => n + ' 个子代理在跑',
61 crabAlt: '用量面板的小螃蟹',
62 dashAlt: (c: string, f: string, w: string) => '上下文 ' + c + '%,5小时 ' + f + '%,本周 ' + w + '%',
63 },
64 // 设置栏
65 bar: {
66 settings: '设置',
67 handoff: '交接',
68 writing: (s: string) => '正在写交接 ' + s,
69 // 客户端 (桌面 app) 的工具栏: 原生按钮; 面板约 15 秒才刷新一次, 所以不写秒数
70 writingDesk: '正在写交接…',
71 openHandoff: '打开交接文件',
72 // v1.3: 交接历史 (终端工具栏的按钮 / 客户端的原生按钮)
73 history: '历史',
74 historyDesk: '交接历史',
75 // v1.3: 写完交接后出现: 跑 /clear, 清空后的会话自动填好交接 (只在终端)
76 clearGo: '清空并继续',
77 lang: '语言',
78 crab: '螃蟹',
79 panel: '面板',
80 on: '开',
81 off: '关',
82 full: '完整',
83 compact: '精简',
84 hide: '隐藏',
85 // 不是全屏时终端不把鼠标点击交给 Claude Code: 工具栏旁边提示怎么办 (放不下就用短的, 再放不下就不放)
86 clickHint: '点击需要 /tui fullscreen,也可以输入 /hud handoff',
87 clickHintShort: '点击需要 /tui fullscreen',
88 },
89 // v1.4 散步道天空行: 搜索词前面那个字
90 searchWord: '搜',
91 // 散步道气泡 (外面会套上「」)
92 say: {
93 done: (d: string) => '搞定 ' + d,
94 quotaBack: '额度刷新了',
95 slowDown: (d: string) => '慢点!' + d + '用完',
96 ctxFull: '上下文快满了',
97 compacted: '压缩完了',
98 yourCall: '等你点头',
99 handoff: '要交接吗?',
100 },
101 // 悬停气泡
102 tipWord: ' · 小贴士 ',
103 tips: ['/hud agents 打开子代理看板', '/hud crab 关掉或打开散步的螃蟹', '/hud 切换 完整 / 精简 / 隐藏', '/hud handoff 写一份交接提示词', '/hud history 挑一份以前的交接接着干', '/hud lang en 切换成英文'],
104 // 每轮收据
105 receipt: {
106 files: (n: string) => '改 ' + n + ' 个文件',
107 tools: (n: string) => '工具 ' + n + ' 次',
108 },
109 // toast
110 toast: {
111 projectOpened: '已打开项目文件夹',
112 openFailed: (err: string) => '打开失败: ' + err,
113 triedOpen: (list: string) => '没能打开, 试过: ' + list,
114 cmdFailed: (cmd: string, err: string) => '/' + cmd + ' 运行失败: ' + err,
115 quotaBack: (name: string) => name + '额度已恢复,可以继续了',
116 costMilestone: (usd: string) => '本会话已花 $' + usd + ',螃蟹替你记着账',
117 ctxWarn: (pct: string) => '上下文已用 ' + pct + '%,螃蟹开始冒汗了,可以考虑 /compact',
118 tokScopeAll: '本会话(含子代理)',
119 tokScopeLaunch: '本次启动以来',
120 tokDetail: (scope: string, total: string, cr: string, cw: string, inp: string, out: string) =>
121 scope + '共 ' + total + ' token:读缓存 ' + cr + ',写缓存 ' + cw + ',新输入 ' + inp + ',输出 ' + out + '。读缓存最便宜,单价约为新输入的十分之一。',
122 lateNight: (h: string) => '已经凌晨 ' + h + ' 点了,螃蟹陪你干活,也记得早点休息',
123 toolMilestone: (n: string) => '本会话第 ' + n + ' 次工具调用,螃蟹给你鼓掌',
124 agentsNarrow: (reason: string) => '子代理看板等终端再宽一点才能显示: ' + reason,
125 agentsFailed: (err: string) => '子代理看板打不开: ' + err,
126 histFailed: (err: string) => '交接历史打不开: ' + err,
127 panelHidden: '用量面板已隐藏(输入 /hud 再打开)',
128 },
129 window: { five_hour: '5 小时', seven_day: '本周' } as Record<string, string>,
130 // 子代理看板
131 kids: {
132 title: '子代理',
133 running: '运行中',
134 completed: '已完成',
135 failed: '失败',
136 killed: '已停止',
137 stuck: '可能卡住',
138 ended: '已结束',
139 ago: (d: string) => d + ' 前',
140 runDetail: (ran: string, idle: string, doing: string, n: string) => doing + ' · ' + idle + ' · 已跑 ' + ran + ' · ' + n + ' 次',
141 endDetail: (ran: string, n: string) => '用时 ' + ran + ' · ' + n + ' 次工具',
142 head: { status: '状态', desc: '描述', ran: '时长', idle: '最后动静', doing: '在做什么', n: '工具' },
143 group: (name: string, r: string, d: string) => name + ' · ' + r + ' 个在跑 · ' + d + ' 个完成',
144 others: '其他子代理',
145 summary: (r: string, e: string) => ' 运行中 ' + r + ' · 已结束 ' + e,
146 none: '这个会话还没有子代理,Esc 关闭',
147 endedHead: (n: string) => '已结束 (最近 ' + n + ' 个)',
148 stuckTip: '运行中超过 5 分钟没有工具动作的会标红,Esc 关闭',
149 },
150 // /hud 命令
151 cmd: {
152 description: '用量面板 (输入框下方):完整 → 精简 → 隐藏 循环;/hud agents 子代理看板,/hud crab 开关螃蟹,/hud lang en|zh|auto 切换语言,/hud handoff 写交接提示词,/hud history 交接历史',
153 registerFailed: (err: string) => 'cc-hud: /hud 注册失败 ' + err,
154 agentsOpened: '已打开子代理看板(Esc 关闭)',
155 historyOpened: '已打开交接历史(数字键填入,Esc 关闭)',
156 crabOn: '螃蟹散步道已打开(输入框正上方)',
157 crabOff: '螃蟹散步道已关闭(/hud crab 再打开)',
158 fixed: '终端版面板固定在输入框下方,螃蟹在上方',
159 layout: (name: string) => '用量面板:' + name,
160 layoutName: { full: '完整', compact: '精简', off: '已隐藏(再输入 /hud 打开)' } as Record<string, string>,
161 lang: (name: string) => '用量面板语言:' + name + '(/hud lang en 切回英文)',
162 langAuto: (name: string) => '用量面板语言:自动(现在是' + name + ',跟随 Claude Code 的 language 设置)',
163 langName: { en: '英文', zh: '中文' } as Record<string, string>,
164 },
165 // 交接
166 handoff: {
167 started: '正在写交接提示词,写好会复制到剪贴板并存成文件',
168 busy: '交接提示词正在写,稍等',
169 title: (project: string, branch: string, date: string) => '# 交接:' + project + (branch ? '(' + branch + ')' : '') + ' · ' + date,
170 resume: (id: string) => '(想回到原来的会话:claude --resume ' + id + ')',
171 done: (chars: string, path: string) => '交接提示词已复制(' + chars + ' 字)· 已存到 ' + path + ' · 点 [清空并继续],或开新会话、/clear,都会自动填好',
172 noCopy: (path: string) => '没能复制到剪贴板 · 交接提示词已存到 ' + path + ' · 点 [清空并继续],或开新会话、/clear,都会自动填好',
173 // 新会话 / /clear 自动填进输入框的那一行 (@交接文件 + 这句)
174 fillLine: '按这份交接继续',
175 filled: (time: string) => '已填入 ' + time + ' 的交接提示词,按回车发送;不需要就删掉',
176 savedDesk: (path: string) => '交接提示词已存到 ' + path + '(客户端暂时不能复制,点「打开交接文件」看全文)',
177 noSave: (chars: string, err: string) => '交接提示词已复制(' + chars + ' 字)· 存文件失败:' + err,
178 lost: (err: string) => '交接提示词写好了,但复制和存文件都失败了:' + err,
179 nothing: '还没有可交接的内容:先和 Claude 来回至少一轮',
180 apiError: (status: string) => '交接失败:API 出错' + (status ? ' ' + status : '') + ',再试一次',
181 empty: '交接失败:Claude 没有写出内容,再试一次',
182 aborted: '交接已取消',
183 },
184 // 交接历史 (v1.3: /hud history 的面板)
185 hist: {
186 title: '交接历史',
187 count: (n: string, shown: string) => (n === shown ? '共 ' + n + ' 份,最新的在上面' : '共 ' + n + ' 份,这里是最近 ' + shown + ' 份'),
188 keys: '数字键填入 · Esc 关闭',
189 fill: '填入',
190 open: '打开',
191 folder: '打开文件夹',
192 today: '今天',
193 yesterday: '昨天',
194 empty: '这个项目还没有交接。点 [交接] 或输入 /hud handoff 写一份',
195 noFill: '没能填进输入框(有对话框挡着,或者客户端不让 mod 填)。可以点「打开」看全文',
196 },
197}
198
199export type Table = typeof zh
200
201const en: Table = {
202 label: {
203 model: 'Model',
204 project: 'Project',
205 session: 'Session',
206 context: 'Context',
207 h5: '5h',
208 week: 'Week',
209 status: 'Status',
210 tools: 'Tools',
211 token: 'Tokens',
212 },
213 compact: 'compact',
214 runOut: (d: string) => 'out ' + d,
215 resetIn: (d: string) => 'reset ' + d,
216 thinking: 'Thinking',
217 tool: {
218 Read: 'Reading',
219 Grep: 'Searching',
220 Glob: 'Finding files',
221 Edit: 'Editing',
222 MultiEdit: 'Editing',
223 Write: 'Writing',
224 NotebookEdit: 'Notebook',
225 Bash: 'Running',
226 PowerShell: 'Running',
227 WebSearch: 'Web search',
228 WebFetch: 'Web fetch',
229 Agent: 'Agents',
230 Task: 'Agents',
231 SendMessage: 'Messaging',
232 TodoWrite: 'Todos',
233 Skill: 'Skill',
234 ToolSearch: 'Tool search',
235 } as Record<string, string>,
236 ready: '✓ Ready',
237 lastTurn: (d: string, n: string) => '✓ last turn ' + d + ', ' + n + (n === '1' ? ' tool' : ' tools'),
238 kidsBusy: 'subagents running',
239 kidsChip: (n: string) => '+' + n + (n === '1' ? ' agent' : ' agents'),
240 noTools: 'none yet',
241 counting: 'counting..',
242 sinceLaunch: ' since launch',
243 share: { today: 'today ', perDayPre: '', perDaySuf: '/day', short: 'today ' },
244 desk: {
245 runOut: (d: string) => 'out ' + d,
246 kidsTail: (n: string) => ' +' + n + (n === '1' ? ' subagent' : ' subagents'),
247 kidsRunning: (n: string) => n + (n === '1' ? ' subagent running' : ' subagents running'),
248 crabAlt: 'Usage panel crab',
249 dashAlt: (c: string, f: string, w: string) => 'Context ' + c + '%, 5h ' + f + '%, week ' + w + '%',
250 },
251 bar: {
252 settings: 'settings',
253 handoff: 'handoff',
254 writing: (s: string) => 'writing handoff... ' + s,
255 writingDesk: 'Writing handoff…',
256 openHandoff: 'Open handoff file',
257 history: 'history',
258 historyDesk: 'Handoff history',
259 clearGo: 'clear & continue',
260 lang: 'Lang',
261 crab: 'Crab',
262 panel: 'Panel',
263 on: 'on',
264 off: 'off',
265 full: 'full',
266 compact: 'compact',
267 hide: 'hide',
268 clickHint: 'clicks need /tui fullscreen, or type /hud handoff',
269 clickHintShort: 'clicks need /tui fullscreen',
270 },
271 searchWord: 'search',
272 say: {
273 done: (d: string) => 'Done ' + d,
274 quotaBack: "Quota's back",
275 slowDown: (d: string) => 'Slow down! out in ' + d,
276 ctxFull: 'Context almost full',
277 compacted: 'Compacted',
278 yourCall: 'Your call',
279 handoff: 'Handoff?',
280 },
281 tipWord: ' · tip: ',
282 tips: ['/hud agents opens the subagent board', '/hud crab hides or shows the crab', '/hud cycles full / compact / hidden', '/hud handoff writes a handoff prompt', '/hud history picks up an earlier handoff', '/hud lang zh switches to Chinese'],
283 receipt: {
284 files: (n: string) => n + (n === '1' ? ' file changed' : ' files changed'),
285 tools: (n: string) => n + (n === '1' ? ' tool call' : ' tool calls'),
286 },
287 toast: {
288 projectOpened: 'Opened the project folder',
289 openFailed: (err: string) => "Couldn't open: " + err,
290 triedOpen: (list: string) => "Couldn't open it, tried: " + list,
291 cmdFailed: (cmd: string, err: string) => '/' + cmd + ' failed: ' + err,
292 quotaBack: (name: string) => 'Your ' + name + ' quota has reset. Carry on',
293 costMilestone: (usd: string) => 'This session has spent $' + usd + '. The crab is keeping count',
294 ctxWarn: (pct: string) => 'Context is ' + pct + '% full and the crab is sweating. Consider /compact or a handoff',
295 tokScopeAll: 'This session (incl. subagents)',
296 tokScopeLaunch: 'Since launch',
297 tokDetail: (scope: string, total: string, cr: string, cw: string, inp: string, out: string) =>
298 scope + ': ' + total + ' tokens. Cache reads ' + cr + ', cache writes ' + cw + ', fresh input ' + inp + ', output ' + out + '. Cache reads are the cheapest, about a tenth of fresh input.',
299 lateNight: (h: string) => "It's " + h + " AM. The crab's keeping you company, but get some rest",
300 toolMilestone: (n: string) => 'Tool call #' + n + ' this session. The crab applauds',
301 agentsNarrow: (reason: string) => 'The subagent board needs a wider terminal: ' + reason,
302 agentsFailed: (err: string) => "Couldn't open the subagent board: " + err,
303 histFailed: (err: string) => "Couldn't open the handoff history: " + err,
304 panelHidden: 'Usage panel hidden. Type /hud to bring it back',
305 },
306 window: { five_hour: '5-hour', seven_day: 'weekly' } as Record<string, string>,
307 kids: {
308 title: 'Subagents',
309 running: 'running',
310 completed: 'done',
311 failed: 'failed',
312 killed: 'stopped',
313 stuck: 'stuck?',
314 ended: 'ended',
315 ago: (d: string) => d + ' ago',
316 runDetail: (ran: string, idle: string, doing: string, n: string) => doing + ' · ' + idle + ' · ran ' + ran + ' · ' + n + ' calls',
317 endDetail: (ran: string, n: string) => 'took ' + ran + ' · ' + n + ' tool calls',
318 head: { status: 'Status', desc: 'Task', ran: 'Time', idle: 'Last seen', doing: 'Doing', n: 'Tools' },
319 group: (name: string, r: string, d: string) => name + ' · ' + r + ' running · ' + d + ' done',
320 others: 'Other subagents',
321 summary: (r: string, e: string) => ' running ' + r + ' · ended ' + e,
322 none: 'No subagents in this session yet. Esc to close',
323 endedHead: (n: string) => 'Ended (last ' + n + ')',
324 stuckTip: 'Running with no tool activity for 5+ minutes is flagged red. Esc to close',
325 },
326 cmd: {
327 description: 'Usage panel (under the prompt): cycles full -> compact -> hidden; /hud agents subagent board, /hud crab toggles the crab, /hud lang en|zh|auto language, /hud handoff writes a handoff prompt, /hud history lists past handoffs',
328 registerFailed: (err: string) => 'cc-hud: /hud registration failed ' + err,
329 agentsOpened: 'Opened the subagent board (Esc to close)',
330 historyOpened: 'Opened the handoff history (press a digit to fill one in, Esc to close)',
331 crabOn: 'Crab strip on (just above the prompt)',
332 crabOff: 'Crab strip off (/hud crab turns it back on)',
333 fixed: 'The terminal panel stays under the prompt, the crab above it',
334 layout: (name: string) => 'Usage panel: ' + name,
335 layoutName: { full: 'full', compact: 'compact', off: 'hidden (type /hud to bring it back)' } as Record<string, string>,
336 lang: (name: string) => 'Usage panel language: ' + name + ' (/hud lang zh for Chinese)',
337 langAuto: (name: string) => "Usage panel language: auto (now " + name + ", following Claude Code's language setting)",
338 langName: { en: 'English', zh: 'Chinese' } as Record<string, string>,
339 },
340 handoff: {
341 started: 'Writing a handoff prompt. It will be copied to your clipboard and saved to a file',
342 busy: 'A handoff prompt is already being written',
343 title: (project: string, branch: string, date: string) => '# Handoff: ' + project + (branch ? ' (' + branch + ')' : '') + ' · ' + date,
344 resume: (id: string) => '(To reopen the original session instead: claude --resume ' + id + ')',
345 done: (chars: string, path: string) => 'Handoff copied (' + chars + ' chars) · saved to ' + path + ' · [clear & continue], a new session or /clear fills it in for you',
346 noCopy: (path: string) => "Couldn't copy to the clipboard · handoff saved to " + path + ' · [clear & continue], a new session or /clear fills it in for you',
347 fillLine: 'Continue from this handoff',
348 filled: (time: string) => 'Filled in the handoff from ' + time + '. Press Enter to send, or delete it',
349 savedDesk: (path: string) => 'Handoff saved to ' + path + " (the desktop app can't copy yet; click Open handoff file to read it)",
350 noSave: (chars: string, err: string) => 'Handoff copied (' + chars + " chars) · couldn't save the file: " + err,
351 lost: (err: string) => "The handoff was written but couldn't be copied or saved: " + err,
352 nothing: 'Nothing to hand off yet. Have at least one exchange with Claude first',
353 apiError: (status: string) => 'Handoff failed: API error' + (status ? ' ' + status : '') + '. Try again',
354 empty: 'Handoff failed: Claude returned an empty reply. Try again',
355 aborted: 'Handoff cancelled',
356 },
357 hist: {
358 title: 'Handoffs',
359 count: (n: string, shown: string) => (n === shown ? n + ' saved, newest first' : n + ' saved, newest ' + shown + ' shown'),
360 keys: 'digit fills in · Esc closes',
361 fill: 'fill in',
362 open: 'open',
363 folder: 'open folder',
364 today: 'today',
365 yesterday: 'yesterday',
366 empty: 'No handoffs for this project yet. Press [handoff] or type /hud handoff to write one',
367 noFill: "Couldn't fill in the prompt (a dialog is open, or the app doesn't allow it). Press open to read it instead",
368 },
369}
370
371export const TABLES: Record<Lang, Table> = { en, zh }
372
373let current: Lang = 'en'
374export const setLang = (l: Lang) => {
375 current = l
376}
377export const getLang = (): Lang => current
378// 当前语言的整张表
379export const S = (): Table => TABLES[current]
380
381// store 里存的 'en' | 'zh' | 'auto' (没存 = auto); auto 跟随 Claude Code 的 language 设置: 是中文就中文, 其余英文
382export type LangPref = Lang | 'auto'
383export const prefOf = (v: unknown): LangPref => (v === 'en' || v === 'zh' ? v : 'auto')
384export function resolveLang(pref: LangPref, claudeLanguage: unknown): Lang {
385 if (pref !== 'auto') return pref
386 const l = typeof claudeLanguage === 'string' ? claudeLanguage.trim() : ''
387 return /^zh\b|^zh[-_]|chinese|mandarin|cantonese|中文|汉语|漢語|简体|繁體|繁体/i.test(l) ? 'zh' : 'en'
388}
389
390// 交接: 让 Claude (分叉, 看得到整个会话) 写的那段话; 用英文写指令, 让它用对话里用户说的语言来写
391export const HANDOFF_PROMPT = [
392 'Write a handoff prompt so a brand-new Claude Code session can continue this work.',
393 'The reader has zero memory of this conversation. Make it fully self-contained.',
394 'Write it in the language the user has been using in this conversation.',
395 'Use exactly these markdown sections, in order, and nothing before or after them:',
396 '## Goal (what the user is trying to achieve, in their words)',
397 '## Current state (what is done, what is in progress, what is not started)',
398 '## Key decisions (what was chosen and why, including options that were rejected)',
399 '## Files & locations (paths that matter, with one line each on why)',
400 '## Gotchas (dead ends, things that did not work, traps to avoid)',
401 '## Next steps (concrete and in order; the first one starts with "Start by")',
402 '## Verify (commands or tests that prove the work is correct)',
403 'Stay under about 800 words. No preamble, no sign-off.',
404].join('\n')
405