SLOPSHOPPER

status-card

输入框上方的会话摘要卡片:目标、现在、下一步、等你处理的事。跨重启保留,回看旧会话也能看到;可展开详情、折叠成胶囊。

bandguardpromptmodelprocesstimer
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · status-card
› fix the failing auth test and add an audit log call ⏺ Read(src/auth.ts) ⎿ Read 6 lines ⏺ Update(src/auth.ts) ⎿ Added 2 lines, removed 1 line ⏺ Bash(bun test) ⎿ 3 pass, 1 fail ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM ╭──────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮ │ 🎯 The goal is summarized when this turn ends turn 2 · 08:53 │ │ │ │ ✅ fix the failing auth test and add an audit log call 0s │ │ │ │ Details Fold │ ╰──────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯ ⟨Claude Code's own drawing⟩ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
╭──────────────────────────────────────────────────────────────────────────────────────────────────╮ │ 🎯 The goal is summarized when this turn ends turn 2 · 08:53 │ │ │ │ ✅ fix the failing auth test and add an audit log call 0s │ │ │ │ Details Fold │ ╰──────────────────────────────────────────────────────────────────────────────────────────────────╯ ⟨Claude Code's own drawing⟩
README

English | 简体中文

status-card

Mods Code: status-card reach validates

A recap card above the Claude Code prompt: the goal, what is happening now, and what waits on you. The recap is saved per conversation, so it is still there after you restart the app or open a session from days ago. Made for long sessions: step away, come back, and pick up where you left off at a glance.

<img src="docs/card-waiting.en.svg" alt="Card waiting on you, with the details open" width="720">

<img src="docs/card-idle.en.svg" alt="Card while idle" width="720">

Built on the source of where-am-i by hamzafer. See Credits.

The screenshots are drawn from sample data by docs/render_screenshots.py.

What the card shows

Always three lines:

  1. 🎯 Goal: the mainline of the whole session. It changes only when you move on to different work. On the right: turn N · last update (while working, N is the turn in progress and the time is when you sent its message; the time shows as HH:mm on the same day only and is left out on other days, since every reply in the conversation already carries its date and time). When it is your turn, the cache hint follows the time; see below.
  2. Now: while Claude works, a dot in the working colour and This turn: what it is doing, in one phrase (thinking ... until that phrase is written); after the turn, ✅ and what the turn did. On the right: the elapsed time. It ticks every second while Claude works, then keeps the turn's final time, even after a restart. The line is at most 60 characters. It does not repeat the per-tool status Claude Code already shows.
  3. ⏳ waiting on you: what Claude needs from you. Empty while Claude works (line 2 already says what it is doing) and when nothing waits on you. On the right: the Details and Fold buttons.

When the window gets narrow, the turn, time, cache hint, stats and buttons on the right stay whole and the text on the left is cut instead.

  • Cache hint: how long Claude's prompt cache has left, as plain text: dim cache 45m with more than 10 minutes left, red cache 6m within 10 minutes, and dim cache expired once it lapses. Carrying on while the cache is warm saves rewriting the whole context into it. It counts from when the main thread's last request was sent; the lifetime (5 minutes or 1 hour) is read from this session's transcript, and when it cannot be read the hint is not shown. It is kept per model: switching to a model this session has not used yet shows it expired, and switching back shows the original model's time left. A cache last used on another day (say, looking back at yesterday's session) is not shown. Shown only when it is your turn, not while Claude works.
  • The border colour shows the state: working, waiting on you, or idle.
  • Details: for when you come back and have forgotten what the session was about. One paragraph of two or three sentences (at most 90 English words or 180 Chinese characters): the mainline and why, how far it got, and what to do next, including to-dos agreed but not done yet. It starts from the mainline, not from the latest small problem. It is drawn in the card only and never enters the conversation. It is cached per turn and only rewritten after a new turn; while it is open, a new turn refreshes it.
  • Fold: shrinks the card to a one-line capsule showing one thing: while Claude works, a dot in the working colour and what it is doing this turn; when something waits on you, ⏳ and what it is; otherwise ✅ and the goal; on the right, without the turn, the update time, then the elapsed time while Claude works or the cache hint when it is your turn, and an Unfold button. The capsule is as wide as its content and at most one full line; when it does not fit, the text on the left is cut first. The fold state is kept across sessions.

Install

In Claude Code in a terminal:

/plugin install status-card --marketplace tyler4400/tyler-claude-mods

Or from a shell:

claude plugin marketplace add tyler4400/tyler-claude-mods
claude plugin install status-card@tyler-claude-mods --scope user

The card appears as soon as you send your first message; until the first recap is ready, the goal line reads "The goal is summarized when this turn ends". If you install it in the middle of a turn, that turn's card has no elapsed time on the right; it shows from the next turn.

Upgrading from where-am-i or goal-card: these are earlier names of this mod. Uninstall the old one, then install status-card. Recaps are stored per plugin name, so old recaps do not carry over.

claude plugin uninstall where-am-i@tyler-claude-mods   # or goal-card@tyler-claude-mods
claude plugin install status-card@tyler-claude-mods --scope user

Configuration

Change these in /config or /plugin configure status-card@tyler-claude-mods. Changes apply right away.

OptionDefaultMeaning
languageautoRecap language: auto follows the latest messages you typed (Chinese or English); background notifications and messages from other sessions do not count; zh; en
modelhaikuModel that writes the recap and the details
accentColorsuggestionColour while working: a theme colour name (suggestion, claude, success, warning, error, …) or #hex
waitingColorwarningColour while waiting on you
idleColorsuccessColour while idle
borderStyleroundCard border: round, single, bold, double, none
densitycomfortableLine spacing: comfortable leaves a blank row between lines; compact does not
showMetatrueShow "turn N · time"
retentionDays180Recaps not updated for this many days are removed; -1 never removes them

How it works

Two model calls per turn. When you send a message, one haiku call writes the "This turn: …" phrase from your message (first 1000 + last 500 characters) and the previous recap. The phrase is at most 60 characters; output is capped at 150 tokens.

After each turn of the main conversation, another haiku call updates the recap. Its input is:

  • the previous recap and a running summary of the whole session (updated every turn from the previous one, about 400 characters at most: the mainline, milestones reached, the current small problem, open to-dos);
  • every message you sent in the session, the first 150 characters of each; past 15 messages it keeps the first 3 and the latest 12. This is how it tells the mainline from the problem at hand;
  • your message for this turn (first 1000 + last 500 characters);
  • short labels for this turn's tool calls (a command's description or first 60 characters, file paths, search terms);
  • Claude's reply (first 1500 + last 1500 characters).

Long text keeps its head and tail with a note saying how much was cut, and the model is told the cut is on purpose so it does not treat the text as incomplete. Output is capped at 700 tokens.

Opening the details makes one more call. Its input is the running summary, the latest card, every message you sent (as above) and the last 6 messages (first 600 + last 600 characters each). It writes two or three sentences, capped at 400 tokens.

These are real model requests and count toward your usage.

Where the data lives: in $.store, which Claude Code gives each plugin as a JSON file under ~/.claude/plugins/store/. There is one record per session (latest recap, running summary, turn, update time, language, last turn's stats, cached details) and one prompt-cache state (each model's last request time and cache lifetime), plus the fold preference. Records not updated for retentionDays are removed when a session starts.

Records are keyed by session id: resuming and compaction keep the id, so the card comes back as it was. A session opened by forking, or by right-clicking and choosing Start a side chat, gets a new id; its transcript starts with entries copied from the original, which still carry the original session's id, so status-card copies the original's card and the two update separately from then on. Records 0.5.x stored under a fingerprint of the working directory and first message are migrated only through the session-id mapping recorded at the time.

What it does and does not do: the tool.call hook only watches. Every call goes through unchanged; it counts calls and the files edited by Edit or Write (kept in the stored stats, no longer shown). It does not change your messages or Claude's replies. Apart from the model calls above, it runs date +%z once per session to get the local time zone, and, when the current session has no card yet, greps the sessionId values out of that session's own transcript to find the original session of a fork or side chat; at the end of each turn it runs grep and tail to read the last few transcript lines containing ephemeral_, which give the lifetime the request wrote the prompt cache with. It makes no other network requests and otherwise reads or writes no files outside its store.

Hooks: session.start, classic.SessionStart, classic.UserPromptSubmit, classic.PostModelSwitch, session.end, prompt.submit, tool.call, turn.step (only to note when each request is sent), turn.complete, ui.render (AbovePrompt).

Limitations

  • Finding the original session of a fork or side chat reads its transcript. If Claude Code changes the transcript format, such a session starts with an empty card rather than picking up another conversation's.
  • The cache lifetime is read from the transcript's usage.cache_creation. If Claude Code changes the transcript format, the cache hint stops showing rather than showing a wrong time. The time left is worked out from the last request, not asked of the API; requests sent to the same conversation from elsewhere (another process resuming it) are not seen here.
  • If a model call fails or returns something malformed, the previous recap stays.
  • In the desktop app, the card is hidden while a "next step" box with a question is showing; see The card disappears behind a "next step" box.
  • The turn number counts your messages with text in the session, slash commands included. After compaction it keeps counting up and never goes back.
  • Drawn only in Claude Code's desktop app and terminal; not in the VS Code extension or claude -p.
  • Checked with claude plugin validate and claude plugin test on Claude Code 2.1.294 / 2.1.295 / 2.1.299.

The card disappears behind a "next step" box

In Claude Code's desktop app, when an agent ends a turn with a "next step" box that carries a question (a question with option buttons), the card above the prompt goes away. It comes back once the box closes. A turn that ends with only a recap, without a question, leaves the card in place. The terminal does not do this.

The card is not covered. The desktop app stops drawing it on purpose, and the mod still hands over its card each time. The app shows the box and the mod band above the prompt one at a time: while the box has a visible button or text, the app draws nothing in the band. That check reads the box, not the card, so nothing in the card changes it (adding a close button does not help). The mod API has no setting for it either.

What you can do:

  • Ask the agent not to attach a question when it ends a turn; if you want it to stop and wait for you, ask in the reply itself.
  • If you want both on screen at once, it has to change in the desktop app; send feedback to Anthropic.

This was traced in the desktop app's front-end code as of 2026-10-17 (the band is wrapped so that it draws nothing while the session's turnCardShown is true). That code is not public and may change.

Credits

Built on the source of where-am-i in hamzafer/claude-code-mods (MIT, Copyright (c) 2026 Hamza Zafar). It was called where-am-i here too and was renamed status-card to avoid clashing with the original. This version turns it into a card and adds persistence, the running summary, language following, details, folding and options.

Source 3 files
hooks/register.tsx 562 lines
1// status-card:输入框上方的会话摘要卡片,摘要存进 $.store,重启或回看旧会话时恢复。
2// 借鉴 hamzafer/claude-code-mods 中 where-am-i 的源码(MIT),改为卡片样式并加上持久化、滚动总结和语言跟随。
3import { atom, read, update } from 'claude-code'
4import type { EngineInterface, PluginOptions, Register } from 'claude-code'
5
6import type { CacheState, DetailView, Lang, SessionRecord, TurnProgress, TurnStats } from '../types'
7import {
8  cacheHint,
9  cacheTtlFromTranscript,
10  clip,
11  countTurns,
12  describeTool,
13  detailRequest,
14  formatElapsed,
15  formatStats,
16  formatTime,
17  intentRequest,
18  isExpired,
19  isTypedPrompt,
20  labels,
21  modelKey,
22  nextCacheChange,
23  NOW_MAX,
24  parseIntent,
25  parseOffset,
26  parseSummary,
27  resolveLang,
28  retentionDaysFrom,
29  summaryRequest,
30} from './recap'
31
32type Engine = EngineInterface
33
34// store 是 ~/.claude/plugins/store/ 下本 plugin 的 JSON 文件
35// rec:<session id> 是一个 session 的记录,cache:<session id> 是它的提示缓存状态。以下是旧格式,只读不写:
36// conv:<指纹> 和 id:<session id>(指向它属于的 conv:)是 0.3.0–0.5.x 的,session:<id> 是 0.3.0 之前的
37const REC_PREFIX = 'rec:'
38const CACHE_PREFIX = 'cache:'
39const CONV_PREFIX = 'conv:'
40const ID_PREFIX = 'id:'
41const LEGACY_PREFIX = 'session:'
42const FOLDED_KEY = 'pref:folded'
43const MAX_LOG = 20
44const EDIT_TOOLS = new Set(['Edit', 'Write', 'NotebookEdit', 'MultiEdit'])
45
46// 由宿主保管,热重载后仍在;跨进程的部分另存 $.store
47const recordAtom = atom({ plugin: 'status-card', key: 'record' } as const, null as SessionRecord | null)
48const progress = atom({ plugin: 'status-card', key: 'progress' } as const, null as TurnProgress | null)
49// 工作期间每秒写一次,让已用时跟着走
50const clockNow = atom({ plugin: 'status-card', key: 'clockNow' } as const, 0)
51const isExpanded = atom({ plugin: 'status-card', key: 'isExpanded' } as const, false)
52const isFolded = atom({ plugin: 'status-card', key: 'isFolded' } as const, false)
53const detailView = atom({ plugin: 'status-card', key: 'detail' } as const, null as DetailView | null)
54// classic.SessionStart 和 classic.UserPromptSubmit 给的 transcript 路径:fork 时靠它找到原 session,也从它读缓存时长
55const transcriptPath = atom({ plugin: 'status-card', key: 'transcriptPath' } as const, '')
56// 不放进 SessionRecord:摘要在后台慢慢生成,写回记录时会盖掉这期间更新的缓存状态
57const cacheAtom = atom({ plugin: 'status-card', key: 'cache' } as const, null as CacheState | null)
58
59type Settings = {
60  language: unknown
61  model: string
62  accentColor: string
63  waitingColor: string
64  idleColor: string
65  borderStyle: string
66  density: string
67  showMeta: boolean
68  retentionDays: number
69}
70
71function settingsFrom(options: PluginOptions): Settings {
72  const text = (key: string, fallback: string) =>
73    typeof options[key] === 'string' && (options[key] as string).trim() !== '' ? (options[key] as string).trim() : fallback
74  return {
75    language: options.language,
76    model: text('model', 'haiku'),
77    accentColor: text('accentColor', 'suggestion'),
78    waitingColor: text('waitingColor', 'warning'),
79    idleColor: text('idleColor', 'success'),
80    borderStyle: text('borderStyle', 'round'),
81    density: text('density', 'comfortable'),
82    showMeta: options.showMeta !== false,
83    retentionDays: retentionDaysFrom(options.retentionDays),
84  }
85}
86
87// 某个 session 自己的记录;旧格式的 conv: 记录只按这个 session 的 id: 映射认领,不按对话内容猜
88async function recordOf($: Engine, id: string): Promise<SessionRecord | undefined> {
89  const own = (await $.store.get(REC_PREFIX + id)) as SessionRecord | undefined
90  if (own) return own
91  const mapped = (await $.store.get(ID_PREFIX + id)) as { conv?: string } | undefined
92  const migrated = mapped?.conv ? ((await $.store.get(mapped.conv)) as SessionRecord | undefined) : undefined
93  return migrated ?? ((await $.store.get(LEGACY_PREFIX + id)) as SessionRecord | undefined)
94}
95
96// fork 出来的 transcript 开头是从原对话复制来的条目,仍带着原 session 的 id;
97// 自己的条目之前出现的其他 id 就是祖先,按从近到远返回
98async function ancestorIds($: Engine, id: string): Promise<string[]> {
99  const path = await read($, transcriptPath)
100  if (!path.endsWith(`/${id}.jsonl`)) return []
101  const { stdout } = await $.process.run(['grep', '-o', '-E', '"sessionId":"[0-9a-f-]{36}"', path])
102  const ids = stdout.split('\n').filter(line => line !== '').map(line => line.slice('"sessionId":"'.length, -1))
103  const ownAt = ids.indexOf(id)
104  const copied = ownAt === -1 ? ids : ids.slice(0, ownAt)
105  return [...new Set(copied.reverse())].filter(other => other !== id)
106}
107
108async function saveRecord($: Engine, record: SessionRecord): Promise<void> {
109  await update($, recordAtom, () => record)
110  await $.store.set(REC_PREFIX + (await $.session.id()), record)
111}
112
113async function pruneOldRecords($: Engine, retentionDays: number): Promise<void> {
114  const now = await $.clock.now()
115  for (const key of await $.store.keys()) {
116    if (![REC_PREFIX, CACHE_PREFIX, CONV_PREFIX, ID_PREFIX, LEGACY_PREFIX].some(prefix => key.startsWith(prefix))) continue
117    const entry = (await $.store.get(key)) as { updatedAt?: number } | undefined
118    if (!entry || isExpired(entry.updatedAt, now, retentionDays)) await $.store.delete(key)
119  }
120}
121
122// 先找这个 session 自己的记录;没有时,fork 出来的 session 复制一份原 session 的,之后各自更新
123async function restoreRecord($: Engine): Promise<void> {
124  const id = await $.session.id()
125  let saved = await recordOf($, id)
126  if (!saved) {
127    try {
128      for (const ancestor of await ancestorIds($, id)) {
129        saved = await recordOf($, ancestor)
130        if (saved) break
131      }
132    } catch {
133      // 读不到 transcript 时当作新会话
134    }
135  }
136  if (!saved) return
137  lang = saved.lang
138  await update($, recordAtom, () => saved)
139  if (!(await $.store.get(REC_PREFIX + id))) await $.store.set(REC_PREFIX + id, saved)
140}
141
142async function setFolded($: Engine, value: boolean): Promise<void> {
143  await update($, isFolded, () => value)
144  await $.store.set(FOLDED_KEY, value)
145}
146
147// 第二行行首:这一轮已完成时用 ✅,和第一行的 🎯、第三行的 ⏳ 一样;工作中仍是状态色的圆点
148const DONE_MARK = '✅'
149
150// 模块级状态:热重载后重置,需要跨重载的都在 atom 和 $.store 里
151let settings = settingsFrom({})
152let prompt = ''
153let log: string[] = []
154let lang: Lang = 'zh'
155// 本机时区相对 UTC 的分钟数:mod 运行环境的时区不一定是本机的
156let offsetMinutes = 0
157let ticker: { cancel: () => void } | undefined
158// 空闲时在缓存提示的分钟数变化那一刻刷新一次
159let cacheTimer: { cancel: () => void } | undefined
160// 主线程这一轮最后一次请求:哪个模型、什么时候发出;缓存从这一刻重新计时
161let lastStep: { model: string; at: number } | undefined
162
163// 占位卡片还没有摘要内容,不能当作上一份摘要
164async function lastRecap($: Engine): Promise<SessionRecord | null> {
165  const record = await read($, recordAtom)
166  return record?.draft ? null : record
167}
168
169async function writeIntent($: Engine, text: string): Promise<void> {
170  try {
171    const request = intentRequest({ lang, previous: await lastRecap($), prompt: text })
172    const result = await $.model.complete({ model: settings.model, ...request })
173    if (!result.isAnswered) return
174    const intent = parseIntent(result.text)
175    if (intent) await update($, progress, p => (p ? { ...p, intent } : p))
176  } catch {
177    // 拿不到一句话目标时第二行一直显示 thinking ...
178  }
179}
180
181async function tick($: Engine): Promise<void> {
182  const now = await $.clock.now()
183  await update($, clockNow, () => now)
184}
185
186async function saveCache($: Engine, state: CacheState | null): Promise<void> {
187  await update($, cacheAtom, () => state)
188  const key = CACHE_PREFIX + (await $.session.id())
189  if (state) await $.store.set(key, state)
190  else await $.store.delete(key)
191}
192
193async function restoreCache($: Engine): Promise<void> {
194  const saved = (await $.store.get(CACHE_PREFIX + (await $.session.id()))) as CacheState | undefined
195  await update($, cacheAtom, () => saved ?? null)
196  await scheduleCacheTick($)
197}
198
199// TTL 只从 transcript 读,且只认这个模型自己的写入
200async function readCacheTtl($: Engine, model: string): Promise<number | undefined> {
201  const path = await read($, transcriptPath)
202  if (!path) return undefined
203  try {
204    const { stdout } = await $.process.run(['sh', '-c', 'grep -F \'"ephemeral_\' "$1" | tail -n 20', 'sh', path])
205    return cacheTtlFromTranscript(stdout, model)
206  } catch {
207    return undefined
208  }
209}
210
211async function recordCache($: Engine): Promise<void> {
212  const step = lastStep
213  lastStep = undefined
214  if (!step) return
215  const byModel = { ...(await read($, cacheAtom))?.byModel }
216  // 这次只读了缓存、没有写入时,沿用这个模型已知的 TTL;一直读不到才不显示
217  const ttlMs = (await readCacheTtl($, step.model)) ?? byModel[step.model]?.ttlMs
218  if (ttlMs) byModel[step.model] = { at: step.at, ttlMs }
219  else delete byModel[step.model]
220  await saveCache($, { model: step.model, byModel, updatedAt: step.at })
221}
222
223async function scheduleCacheTick($: Engine): Promise<void> {
224  cacheTimer?.cancel()
225  cacheTimer = undefined
226  const delay = nextCacheChange(await read($, cacheAtom), await $.clock.now())
227  if (delay === undefined) return
228  cacheTimer = $.clock.after(delay, async () => {
229    await tick($)
230    await scheduleCacheTick($)
231  })
232}
233
234async function summarize($: Engine, answer: string, stats: TurnStats | undefined, turn: number | undefined): Promise<void> {
235  const previous = await lastRecap($)
236  const messages = await $.session.messages()
237  const request = summaryRequest({ lang, previous, prompt, tools: log, answer, messages })
238  const result = await $.model.complete({ model: settings.model, ...request })
239  if (!result.isAnswered) return
240  const parsed = parseSummary(result.text)
241  if (!parsed) return
242  const record: SessionRecord = {
243    recap: parsed.recap,
244    overall: parsed.overall || previous?.overall || '',
245    // 上下文压缩后重启,session.messages() 只剩压缩后的消息,轮次不能因此倒退
246    turn: Math.max(turn ?? 0, countTurns(messages), (previous?.turn ?? 0) + 1),
247    lang,
248    updatedAt: await $.clock.now(),
249    detail: previous?.detail,
250    stats: stats ?? previous?.stats,
251  }
252  await saveRecord($, record)
253  // 详情展开着时跟着新的一轮刷新
254  if (await read($, isExpanded)) await loadDetail($)
255}
256
257async function loadDetail($: Engine): Promise<void> {
258  const record = await lastRecap($)
259  if (!record) {
260    await update($, detailView, () => ({ status: 'error', text: labels(lang).noRecap }))
261    return
262  }
263  if (record.detail?.turn === record.turn && record.detail.kind === 'mainline') {
264    const text = record.detail.text
265    await update($, detailView, () => ({ status: 'ready', text }))
266    return
267  }
268  await update($, detailView, () => ({ status: 'loading', text: '' }))
269  const request = detailRequest({ lang: record.lang, record, messages: await $.session.messages() })
270  const result = await $.model.complete({ model: settings.model, ...request })
271  if (!result.isAnswered || result.text.trim() === '') {
272    await update($, detailView, () => ({ status: 'error', text: labels(record.lang).failed }))
273    return
274  }
275  const text = result.text.trim()
276  const latest = (await read($, recordAtom)) ?? record
277  await saveRecord($, { ...latest, detail: { text, turn: record.turn, kind: 'mainline' } })
278  await update($, detailView, () => ({ status: 'ready', text }))
279}
280
281async function setExpanded($: Engine, value: boolean): Promise<void> {
282  await update($, isExpanded, () => value)
283  if (!value) return
284  try {
285    await loadDetail($)
286  } catch {
287    await update($, detailView, () => ({ status: 'error', text: labels(lang).failed }))
288  }
289}
290
291async function summarizeQuietly($: Engine, answer: string, stats: TurnStats | undefined, turn: number | undefined): Promise<void> {
292  try {
293    await summarize($, answer, stats, turn)
294  } catch {
295    // 摘要是附加功能:失败就保留上一份
296  }
297}
298
299export const register: Register = (on, options) => {
300  settings = settingsFrom(options)
301
302  on('session.start', async ($, e, next) => {
303    const result = await next(e)
304    try {
305      offsetMinutes = parseOffset((await $.process.run(['date', '+%z'])).stdout)
306    } catch {
307      offsetMinutes = 0
308    }
309    await pruneOldRecords($, settings.retentionDays)
310    await restoreRecord($)
311    await restoreCache($)
312    const folded = await $.store.get(FOLDED_KEY)
313    if (typeof folded === 'boolean') await update($, isFolded, () => folded)
314    return result
315  })
316
317  // 只为拿 transcript 路径:fork 出来的 session 启动时还没有自己的记录,读到路径后再找一次
318  on('classic.SessionStart', async ($, e, next) => {
319    const result = await next(e)
320    await update($, transcriptPath, () => e.transcript_path)
321    if (!(await read($, recordAtom))) await restoreRecord($)
322    if (!(await read($, cacheAtom))) await restoreCache($)
323    return result
324  })
325
326  // 热重载或会话中途装上时不会再有 classic.SessionStart,每轮发消息时再记一次 transcript 路径
327  on('classic.UserPromptSubmit', async ($, e, next) => {
328    const result = await next(e)
329    await update($, transcriptPath, () => e.transcript_path)
330    return result
331  })
332
333  // 切换模型后提示跟着换成新模型的缓存;切回来时原模型的缓存没过期就继续显示剩余时间
334  on('classic.PostModelSwitch', async ($, e, next) => {
335    const result = await next(e)
336    const state = await read($, cacheAtom)
337    if (state) await saveCache($, { ...state, model: modelKey(e.to_model) })
338    await scheduleCacheTick($)
339    return result
340  })
341
342  // /clear 或 /resume 后进程换到另一个 session,旧卡片和旧 transcript 不再适用;新 session 的卡片由 classic.SessionStart 找回
343  on('session.end', async ($, e, next) => {
344    const result = await next(e)
345    if (e.reason === 'clear' || e.reason === 'resume') {
346      await update($, recordAtom, () => null)
347      await update($, transcriptPath, () => '')
348      await update($, cacheAtom, () => null)
349      cacheTimer?.cancel()
350      await update($, detailView, () => null)
351      await update($, isExpanded, () => false)
352    }
353    return result
354  })
355
356  on('prompt.submit', async ($, e, next) => {
357    // 续接的会话在启动时可能还没载入对话内容,这里再找一次
358    if (!(await read($, recordAtom))) await restoreRecord($)
359    const record = await read($, recordAtom)
360    // 第几轮按对话里你发过的消息数,这一条还没进对话所以加一;压缩上下文后消息变少,不能比上一轮小
361    const turn = Math.max(countTurns(await $.session.messages()) + 1, (record?.turn ?? 0) + 1)
362    prompt = e.text
363    log = []
364    // 不是你打的字、或太短(如"好""开始")不足以判断语言时,沿用上一次的
365    const isLangSample = isTypedPrompt(e.origin, e.text) && Array.from(e.text.trim()).length >= 8
366    if (isLangSample || settings.language === 'zh' || settings.language === 'en') {
367      lang = resolveLang(settings.language, e.text)
368    }
369    const startedAt = await $.clock.now()
370    await update($, clockNow, () => startedAt)
371    await update($, progress, () => ({ intent: '', turn, calls: 0, files: [], startedAt }))
372    // 第一份摘要出来前先画占位卡片,第一轮也有卡片
373    if (!record || record.draft) {
374      const recap = { goal: '', now: '', waiting: '', next: '' }
375      await update($, recordAtom, () => ({ recap, overall: '', turn, lang, updatedAt: startedAt, draft: true }))
376    }
377    ticker?.cancel()
378    ticker = $.clock.every(1000, () => void tick($))
379    cacheTimer?.cancel()
380    const text = e.text
381    $.clock.after(0, () => void writeIntent($, text))
382    return next(e)
383  })
384
385  // 只观察:记下在做什么,调用原样放行。其他 mod 在后台发起的调用不算
386  on('tool.call', async ($, e, next) => {
387    if (next.origin.plugin !== 'engine') return next(e)
388    const input = e as unknown as Record<string, unknown>
389    const line = describeTool(input, lang)
390    log = [...log, e.agentId ? `(agent) ${line}` : line].slice(-MAX_LOG)
391    const file = EDIT_TOOLS.has(String(input.tool)) && typeof input.file_path === 'string' ? input.file_path : ''
392    await update($, progress, p =>
393      p ? { ...p, calls: p.calls + 1, files: file && !p.files.includes(file) ? [...p.files, file] : p.files } : p,
394    )
395    return next(e)
396  })
397
398  // 只记时间:主线程每次请求都会让缓存重新计时,子代理的请求不算
399  on('turn.step', async function* ($, e, next) {
400    if (!e.agentId) lastStep = { model: modelKey(e.model), at: await $.clock.now() }
401    return yield* next(e)
402  })
403
404  on('turn.complete', async ($, e, next) => {
405    const result = await next(e)
406    if (!e.agentId) {
407      ticker?.cancel()
408      ticker = undefined
409      const finished = await read($, progress)
410      const stats = finished
411        ? { calls: finished.calls, files: finished.files.length, elapsedMs: (await $.clock.now()) - finished.startedAt }
412        : undefined
413      await update($, progress, () => null)
414      await recordCache($)
415      await scheduleCacheTick($)
416      // 统计先写进记录,摘要还在生成时第二行右侧就已经是这一轮的最终数字
417      const record = await read($, recordAtom)
418      if (record?.draft) {
419        // 摘要出来前,占位卡片的第二行先写这一轮的意图
420        const now = finished?.intent || clip(prompt, NOW_MAX)
421        await update($, recordAtom, () => ({ ...record, recap: { ...record.recap, now }, stats: stats ?? record.stats }))
422      } else if (record && stats) {
423        await saveRecord($, { ...record, stats })
424      }
425      const answer = e.answer
426      const turn = finished?.turn
427      // 放到定时器里跑,不拖住这一轮的收尾
428      $.clock.after(0, () => void summarizeQuietly($, answer, stats, turn))
429    }
430    return result
431  })
432
433  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
434    const rest = await next(e) // 其他 mod 和 Claude Code 自己画在这里的内容保留在卡片下方
435    const record = await read($, recordAtom)
436    if (e.props.hasSurvey || !record) return rest
437
438    const { Box, Text, Button, Markdown } = $.ui.resolve(e)
439    const L = labels(record.lang)
440    const isWorking = e.props.isWorking
441    const turnProgress = isWorking ? await read($, progress) : null
442    const isWaiting = !isWorking && record.recap.waiting !== ''
443    const stateColor = isWorking ? settings.accentColor : isWaiting ? settings.waitingColor : settings.idleColor
444    const now = await $.clock.now()
445    // 读 clockNow 是为了让空闲时的定时刷新重画卡片;缓存提示只在轮到你时显示
446    await read($, clockNow)
447    const cache = isWorking ? undefined : cacheHint(await read($, cacheAtom), now, offsetMinutes, record.lang)
448    // 右上角是轮次和时间,时间只在当天显示:工作中是正在进行的这一轮和你发出消息的时间,轮到你时是上一轮和摘要更新的时间
449    const updatedAt = settings.showMeta ? formatTime(turnProgress?.startedAt ?? record.updatedAt, now, offsetMinutes) : ''
450    const meta = settings.showMeta ? [L.turn(turnProgress?.turn ?? record.turn), updatedAt].filter(part => part !== '').join(' · ') : ''
451    const goal = record.draft ? L.goalPending : record.recap.goal
452
453    const border = settings.borderStyle === 'none' ? {} : { borderStyle: settings.borderStyle, borderColor: stateColor }
454
455    // 工作中显示这一轮的实时统计,结束后保留上一轮的最终统计
456    const stats: TurnStats | undefined = turnProgress
457      ? {
458          calls: turnProgress.calls,
459          files: turnProgress.files.length,
460          elapsedMs: (await read($, clockNow)) - turnProgress.startedAt,
461        }
462      : record.stats
463    const progressStats = stats ? formatStats(stats, record.lang) : ''
464    // 第二行:工作中是「本轮:…」(重载后丢了这一轮的进度时退回上一份摘要),结束后是这一轮做了什么
465    const nowText = turnProgress ? `${L.thisTurn}${L.sep}${turnProgress.intent || L.thinking}` : record.recap.now
466
467    // 右上角的暗色文字,轮到你时后面跟缓存提示;缓存不到 10 分钟时这段提示用红色
468    const metaText = (prefix: string) => {
469      if (cache?.tone !== 'low') {
470        const text = [prefix, cache?.text ?? ''].filter(part => part !== '').join(' · ')
471        return text === '' ? undefined : <Text dimColor>{text}</Text>
472      }
473      const warning = <Text color="error">{cache.text}</Text>
474      return prefix === '' ? warning : <Text><Text dimColor>{`${prefix} · `}</Text>{warning}</Text>
475    }
476
477    if (await read($, isFolded)) {
478      // 胶囊依次优先显示:工作中这一轮在做什么、等你处理的事、目标;放不下时截断这段文字,右侧的时间、用时或缓存和展开按钮保持完整
479      const capsuleText = isWorking
480        ? nowText
481        : isWaiting
482          ? `⏳ ${L.waiting}${L.sep}${record.recap.waiting}`
483          : `🎯 ${goal}`
484      // 右侧不显示轮次:工作中是时间和实时用时,轮到你时是时间和缓存提示
485      const capsuleMeta = [updatedAt, isWorking && stats ? formatElapsed(stats.elapsedMs, record.lang) : '']
486        .filter(part => part !== '')
487        .join(' · ')
488      return (
489        <Box flexDirection="column">
490          {/* 外层整行,胶囊作为可收缩的子项:内容短时按内容宽,超出一行时收缩 */}
491          <Box flexDirection="row">
492            <Box flexDirection="row" flexShrink={1} minWidth={0} gap={1} paddingX={1} {...border}>
493              {/* 行首:工作中是状态色圆点;等你时文字自带 ⏳,不加标记;空闲是 ✅ */}
494              {isWorking ? <Text color={stateColor}>{'●'}</Text> : !isWaiting && <Text>{DONE_MARK}</Text>}
495              <Box flexShrink={1} minWidth={0} overflow="hidden">
496                {isWaiting
497                  ? <Text color={settings.waitingColor} wrap="truncate-end">{capsuleText}</Text>
498                  : <Text wrap="truncate-end">{capsuleText}</Text>}
499              </Box>
500              <Box flexDirection="row" flexShrink={0} gap={1}>
501                {metaText(capsuleMeta)}
502                <Button key="unfold" plain label={L.unfold} onPress={() => setFolded($, false)} />
503              </Box>
504            </Box>
505          </Box>
506          {rest}
507        </Box>
508      )
509    }
510
511    const expanded = await read($, isExpanded)
512    const detail = expanded ? await read($, detailView) : null
513    // 第三行只在等你时有内容:工作中第二行已经说了在做什么,空闲时没有要你处理的事
514    const actionLine = isWaiting
515      ? <Text color={settings.waitingColor} wrap="truncate-end">{`⏳ ${L.waiting}${L.sep}${record.recap.waiting}`}</Text>
516      : <Text>{' '}</Text>
517
518    return (
519      <Box flexDirection="column">
520        <Box flexDirection="column" paddingX={1} rowGap={settings.density === 'compact' ? 0 : 1} {...border}>
521          <Box flexDirection="row" justifyContent="space-between" gap={2}>
522            <Box flexGrow={1} flexShrink={1} minWidth={0} overflow="hidden">
523              {record.draft
524                ? <Text dimColor wrap="truncate-end">{`🎯 ${goal}`}</Text>
525                : <Text bold wrap="truncate-end">{`🎯 ${goal}`}</Text>}
526            </Box>
527            {(meta !== '' || cache) && <Box flexShrink={0}>{metaText(meta)}</Box>}
528          </Box>
529          <Box flexDirection="row" justifyContent="space-between" gap={2}>
530            <Box flexGrow={1} flexShrink={1} minWidth={0} overflow="hidden">
531              <Text wrap="truncate-end">
532                {isWorking ? <Text color={stateColor}>{'● '}</Text> : `${DONE_MARK} `}
533                {nowText}
534              </Text>
535            </Box>
536            {progressStats !== '' && (
537              <Box flexShrink={0}>
538                <Text dimColor>{progressStats}</Text>
539              </Box>
540            )}
541          </Box>
542          <Box flexDirection="row" justifyContent="space-between" gap={2}>
543            <Box flexGrow={1} flexShrink={1} minWidth={0} overflow="hidden">{actionLine}</Box>
544            <Box flexDirection="row" flexShrink={0} gap={2}>
545              <Button key="detail" plain onPress={() => setExpanded($, !expanded)}>
546                {expanded ? L.collapse : L.expand}
547              </Button>
548              <Button key="fold" plain onPress={() => setFolded($, true)}>
549                {L.fold}
550              </Button>
551            </Box>
552          </Box>
553          {detail?.status === 'ready' && <Markdown text={detail.text} />}
554          {detail?.status === 'loading' && <Text dimColor>{L.loading}</Text>}
555          {detail?.status === 'error' && <Text dimColor>{detail.text}</Text>}
556        </Box>
557        {rest}
558      </Box>
559    )
560  })
561}
562
hooks/recap.ts 367 lines
1// 不依赖引擎的纯逻辑:语言判断、截断、提示词、解析和时间格式,单独测试
2import type { PromptOrigin } from 'claude-code'
3
4import type { CacheEntry, CacheHint, CacheState, Lang, Recap, SessionRecord, TurnStats } from '../types'
5
6const FIELD_MAX = 100
7/** 第二行(现在 / 本轮)要和右侧用时挤在一行里,放得更短 */
8export const NOW_MAX = 60
9const OVERALL_MAX = 400
10
11const LABELS = {
12  zh: {
13    turn: (n: number) => `第 ${n} 轮`,
14    sep: ':',
15    thisTurn: '本轮',
16    thinking: 'thinking ...',
17    waiting: '等你',
18    expand: '详情',
19    collapse: '收起',
20    fold: '折叠',
21    unfold: '展开',
22    loading: '正在生成详情…',
23    failed: '详情生成失败,稍后再试。',
24    noRecap: '还没有摘要,等这一轮结束后再试。',
25    goalPending: '目标会在这一轮结束后总结',
26    cacheLeft: (minutes: number) => `缓存 ${minutes} 分`,
27    cacheExpired: '缓存过期',
28  },
29  en: {
30    turn: (n: number) => `turn ${n}`,
31    sep: ': ',
32    thisTurn: 'This turn',
33    thinking: 'thinking ...',
34    waiting: 'waiting on you',
35    expand: 'Details',
36    collapse: 'Hide',
37    fold: 'Fold',
38    unfold: 'Unfold',
39    loading: 'Writing the details…',
40    failed: 'Could not write the details. Try again later.',
41    noRecap: 'No recap yet. Try again after this turn ends.',
42    goalPending: 'The goal is summarized when this turn ends',
43    cacheLeft: (minutes: number) => `cache ${minutes}m`,
44    cacheExpired: 'cache expired',
45  },
46}
47
48export function labels(lang: Lang) {
49  return LABELS[lang]
50}
51
52/** 中日韩文字占字母类字符三成以上视为中文会话 */
53export function detectLang(text: string): Lang {
54  const cjk = text.match(/[㐀-鿿豈-﫿]/g)?.length ?? 0
55  const latin = text.match(/[A-Za-z]/g)?.length ?? 0
56  if (cjk === 0) return 'en'
57  // 一个汉字的信息量约等于一个英文单词,按 1:4 折算字母
58  return cjk / (cjk + latin / 4) >= 0.3 ? 'zh' : 'en'
59}
60
61export function resolveLang(option: unknown, sample: string): Lang {
62  if (option === 'zh' || option === 'en') return option
63  return detectLang(sample)
64}
65
66// 你亲手发出的:输入框、Remote Control、desktop 等 SDK 宿主、Slack 上点名本会话
67const TYPED_ORIGINS = new Set<PromptOrigin['kind']>(['composer', 'bridge', 'sdk', 'slack-ping'])
68// 引擎包装过的文本,不是谁打的字
69const ENGINE_WRAPPER = /^<(task-notification|local-command-caveat|local-command-stdout|command-name|command-message|command-args|system-reminder)\b/
70
71/**
72 * 只有你亲手发的消息能用来判断语言:后台任务通知、其他会话的消息、定时任务也走 prompt.submit,
73 * 而且多是英文模板,拿来判断会把中文会话的卡片带成英文。判断方式借鉴 hamzafer 的 session-saver
74 */
75export function isTypedPrompt(origin: PromptOrigin | undefined, text: string): boolean {
76  const head = text.trimStart()
77  if (ENGINE_WRAPPER.test(head) || head.startsWith('Another Claude session sent a message')) return false
78  // 类型上必有,但测试引擎等场景不带:只能按文本判断
79  if (!origin) return true
80  return TYPED_ORIGINS.has(origin.kind) || (origin.kind === 'plugin' && origin.asUser === true)
81}
82
83/** 保留开头和结尾(结论通常在末尾),中间注明省略了多少字,避免模型以为信息不全 */
84export function headTail(text: string, head: number, tail: number): string {
85  const chars = Array.from(text)
86  if (chars.length <= head + tail) return text
87  const omitted = chars.length - head - tail
88  return `${chars.slice(0, head).join('')}\n[…中间省略 ${omitted} 字 / ${omitted} chars omitted…]\n${chars.slice(-tail).join('')}`
89}
90
91// 中文句末标点直接断句;英文标点后面要有空白或到结尾,避免把版本号 0.3.3 当成句号
92const SENTENCE_END = /(?<=[。!?])\s*|(?<=[.!?])(?:\s+|$)/
93
94/** 一句话、最多 max 个字符;英文在词边界截断,中文直接截断 */
95export function clip(text: string, max = FIELD_MAX): string {
96  const first = text.trim().split(SENTENCE_END)[0] ?? ''
97  const chars = Array.from(first)
98  if (chars.length <= max) return first.replace(/[.。]$/, '')
99  const cut = chars.slice(0, max - 1).join('')
100  const space = cut.lastIndexOf(' ')
101  return `${space > max * 0.6 ? cut.slice(0, space) : cut}…`
102}
103
104const LANG_RULE: Record<Lang, string> = {
105  zh: '所有字段都用简体中文书写;代码标识符、文件路径、命令和专有名词保留原文。',
106  en: 'Write every field in English.',
107}
108
109const SYSTEM_REMINDER = /<system-reminder>[\s\S]*?<\/system-reminder>/g
110const TRAIL_ITEM_MAX = 150
111const TRAIL_HEAD = 3
112const TRAIL_TAIL = 12
113
114type Message = { role: 'user' | 'assistant'; text: string }
115
116/**
117 * 你发过的全部消息各取开头一句,太多时保留最早几条和最近十几条。
118 * 摘要只看这一轮时容易被眼前的小问题带偏,这条轨迹让模型认得出整个会话的主线。
119 */
120export function userTrail(messages: readonly Message[]): string {
121  const items = messages
122    .filter(m => m.role === 'user')
123    .map(m => m.text.replace(SYSTEM_REMINDER, '').replace(/\s+/g, ' ').trim())
124    .filter(text => text !== '')
125    .map((text, i) => {
126      const chars = Array.from(text)
127      return `${i + 1}. ${chars.length > TRAIL_ITEM_MAX ? chars.slice(0, TRAIL_ITEM_MAX).join('') + '…' : text}`
128    })
129  if (items.length <= TRAIL_HEAD + TRAIL_TAIL) return items.join('\n')
130  const omitted = items.length - TRAIL_HEAD - TRAIL_TAIL
131  return [...items.slice(0, TRAIL_HEAD), `[…省略 ${omitted} 条 / ${omitted} messages omitted…]`, ...items.slice(-TRAIL_TAIL)].join('\n')
132}
133
134const MAINLINE_RULE = [
135  'The mainline is what the whole session is working towards, judged from all of the person\'s messages, for example "build and publish a set of mods".',
136  'A bug, question or detour that comes up on the way is a sub-problem of the mainline, not a new mainline, even if it takes several turns.',
137  'The mainline changes when the person\'s latest 2 messages both point to a different piece of work than the previous goal, or when they say outright that they are moving on.',
138].join(' ')
139
140export function summaryRequest(input: {
141  lang: Lang
142  previous: SessionRecord | null
143  prompt: string
144  tools: string[]
145  answer: string
146  messages: readonly Message[]
147}) {
148  const { lang, previous } = input
149  const system = [
150    'You keep a one-glance recap of a coding session. Plain words, no em dashes.',
151    'Reply with JSON only: {"goal","now","waiting","next","overall"}.',
152    `"goal", "waiting", "next": one sentence each, at most ${FIELD_MAX} characters. "now": one sentence, at most ${NOW_MAX} characters.`,
153    MAINLINE_RULE,
154    '"goal": the mainline. The previous goal is only a hint and may be outdated: check it against the person\'s latest messages. Replace it when the mainline changed, but not for a single sub-problem or detour.',
155    '"now": what was just done. "waiting": what the assistant is waiting on from the person, or "". "next": the next step.',
156    `"overall": a running summary of the whole session, at most ${OVERALL_MAX} characters, in this order: the mainline and why; milestones reached; the current sub-problem, if any; to-dos agreed but not done yet.`,
157    'Update the previous overall summary with this turn. Keep the mainline and open to-dos until they are done; shorten finished sub-problems to their outcome; drop details that no longer matter.',
158    'Text marked as omitted was cut for length on purpose: summarize from what is shown and do not treat the reply as incomplete.',
159    LANG_RULE[lang],
160  ].join('\n')
161  // goal 单独标注为可能过期,放在 JSON 里模型会当成既定事实原样抄回
162  const { goal: previousGoal, ...previousRest } = previous?.recap ?? { goal: '' }
163  const prompt = [
164    `Previous recap: ${previous ? JSON.stringify(previousRest) : 'none'}`,
165    `Previous goal (may be outdated, re-judge it against the person's latest messages): ${previousGoal || 'none'}`,
166    `Previous overall summary: ${previous?.overall || 'none'}`,
167    `<all_messages_from_the_person>\n${userTrail(input.messages)}\n</all_messages_from_the_person>`,
168    `The person's latest message:\n${headTail(input.prompt, 1000, 500)}`,
169    `Tools used this turn: ${input.tools.join('; ') || 'none'}`,
170    `The assistant's reply:\n${headTail(input.answer, 1500, 1500)}`,
171  ].join('\n\n')
172  return { system, prompt, maxTokens: 900 }
173}
174
175export function detailRequest(input: { lang: Lang; record: SessionRecord; messages: readonly Message[] }) {
176  const recent = input.messages
177    .filter(m => m.text.trim() !== '')
178    .slice(-6)
179    .map(m => `[${m.role === 'user' ? 'person' : 'assistant'}] ${headTail(m.text, 600, 600)}`)
180    .join('\n\n')
181  const system = [
182    'The person has been away from this coding session long enough to forget it. Help them pick it up again.',
183    MAINLINE_RULE,
184    'Write one paragraph of 2 or 3 short sentences, in this order: the mainline and why; how far it got (the milestones that matter, and the current sub-problem only if one is open); what to do next to move the mainline forward, including to-dos agreed but not done yet.',
185    'Start from the mainline, not from the latest sub-problem. End with the next steps.',
186    'At most 180 Chinese characters or 90 English words. No bullets, headings or preamble.',
187    'Plain words, no em dashes. Text marked as omitted was cut for length on purpose: do not treat it as incomplete.',
188    LANG_RULE[input.lang],
189  ].join('\n')
190  const prompt = [
191    `Overall summary so far: ${input.record.overall || 'none'}`,
192    `Latest recap card: ${JSON.stringify(input.record.recap)}`,
193    `<all_messages_from_the_person>\n${userTrail(input.messages)}\n</all_messages_from_the_person>`,
194    `<recent_messages>\n${recent}\n</recent_messages>`,
195    'Write the paragraph now, not a reply to the messages.',
196  ].join('\n\n')
197  return { system, prompt, maxTokens: 400 }
198}
199
200/** 这一轮要做什么:你发消息时生成,工作期间固定显示,不随工具调用跳动 */
201export function intentRequest(input: { lang: Lang; previous: SessionRecord | null; prompt: string }) {
202  const system = [
203    'Say in one short phrase what the assistant is about to do in this turn of a coding session, based on the person\'s message.',
204    'If the message is short (like "ok", "start", "go on"), infer it from the previous recap\'s next step and what was waiting on the person.',
205    `At most ${NOW_MAX} characters. Reply with the phrase only: no quotes, no trailing period.`,
206    LANG_RULE[input.lang],
207  ].join('\n')
208  const prompt = [
209    `Previous recap: ${input.previous ? JSON.stringify(input.previous.recap) : 'none'}`,
210    `The person's message:\n${headTail(input.prompt, 1000, 500)}`,
211  ].join('\n\n')
212  return { system, prompt, maxTokens: 150 }
213}
214
215export function parseIntent(text: string): string {
216  const line = text.trim().split('\n')[0] ?? ''
217  return clip(line.replace(/^["'“”「」]+|["'“”「」]+$/g, ''), NOW_MAX)
218}
219
220/** 已用时:45s、1m32s、1h05m;中文用 秒/分/时 */
221export function formatElapsed(ms: number, lang: Lang): string {
222  const total = Math.max(0, Math.floor(ms / 1000))
223  const h = Math.floor(total / 3600)
224  const m = Math.floor((total % 3600) / 60)
225  const sec = total % 60
226  const pad = (n: number) => String(n).padStart(2, '0')
227  if (lang === 'zh') return h > 0 ? `${h}时${pad(m)}分` : m > 0 ? `${m}分${pad(sec)}秒` : `${sec}秒`
228  return h > 0 ? `${h}h${pad(m)}m` : m > 0 ? `${m}m${pad(sec)}s` : `${sec}s`
229}
230
231/** 解析模型返回的 JSON,容忍外面包了代码块 */
232export function parseSummary(text: string): { recap: Recap; overall: string } | null {
233  const body = text.slice(text.indexOf('{'), text.lastIndexOf('}') + 1)
234  try {
235    const o = JSON.parse(body) as Record<string, unknown>
236    const raw = (k: string) => (typeof o[k] === 'string' ? (o[k] as string).replace(/\s*—\s*/g, ', ').trim() : '')
237    const goal = clip(raw('goal'))
238    if (!goal) return null
239    const recap = { goal, now: clip(raw('now'), NOW_MAX), waiting: clip(raw('waiting')), next: clip(raw('next')) }
240    return { recap, overall: Array.from(raw('overall')).slice(0, OVERALL_MAX * 2).join('') }
241  } catch {
242    return null
243  }
244}
245
246/** 一个人会怎么描述这次工具调用 */
247export function describeTool(e: Record<string, unknown>, lang: Lang): string {
248  const tool = String(e.tool)
249  const s = (k: string) => (typeof e[k] === 'string' ? (e[k] as string) : '')
250  const file = (p: string) => p.split('/').slice(-2).join('/')
251  const zh = lang === 'zh'
252  if (tool === 'Bash') return `${zh ? '运行' : 'running'} ${s('description') || s('command').slice(0, 60)}`
253  if (tool === 'Edit' || tool === 'Write') return `${zh ? '编辑' : 'editing'} ${file(s('file_path'))}`
254  if (tool === 'Read') return `${zh ? '读取' : 'reading'} ${file(s('file_path'))}`
255  if (tool === 'Grep' || tool === 'Glob') return `${zh ? '搜索' : 'searching for'} ${s('pattern').slice(0, 40)}`
256  if (tool === 'Agent') return `${zh ? '启动子代理:' : 'starting an agent: '}${s('description')}`
257  if (tool === 'AskUserQuestion') return zh ? '向你提问' : 'asking you a question'
258  if (tool.startsWith('mcp__')) return `${zh ? '使用' : 'using'} ${tool.split('__').slice(1).join(' ')}`
259  return `${zh ? '使用' : 'using'} ${tool}`
260}
261
262/** 你发出的消息数,即轮次;工具结果的 user 行没有文字,不计入 */
263export function countTurns(messages: readonly { role: string; text: string }[]): number {
264  return messages.filter(m => m.role === 'user' && m.text.trim() !== '').length
265}
266
267function isSameLocalDay(a: number, b: number, offsetMinutes: number): boolean {
268  const x = new Date(a + offsetMinutes * 60_000)
269  const y = new Date(b + offsetMinutes * 60_000)
270  return x.getUTCFullYear() === y.getUTCFullYear() && x.getUTCMonth() === y.getUTCMonth() && x.getUTCDate() === y.getUTCDate()
271}
272
273/** 更新时间:当天显示 `HH:mm`,按本机时区;其他日子返回空字符串,不显示(对话里每条回复本来就有日期时间) */
274export function formatTime(at: number, now: number, offsetMinutes: number): string {
275  if (!isSameLocalDay(at, now, offsetMinutes)) return ''
276  const a = new Date(at + offsetMinutes * 60_000)
277  const pad = (n: number) => String(n).padStart(2, '0')
278  return `${pad(a.getUTCHours())}:${pad(a.getUTCMinutes())}`
279}
280
281/** `date +%z` 的输出(+0800)转成分钟 */
282export function parseOffset(z: string): number {
283  const m = z.trim().match(/^([+-])(\d{2})(\d{2})$/)
284  if (!m) return 0
285  const minutes = Number(m[2]) * 60 + Number(m[3])
286  return m[1] === '-' ? -minutes : minutes
287}
288
289const DAY_MS = 24 * 60 * 60 * 1000
290
291/** 摘要保留天数:正数照用,-1 表示永不清理,其他值回落到 180 */
292export function retentionDaysFrom(value: unknown): number {
293  return typeof value === 'number' && (value > 0 || value === -1) ? value : 180
294}
295
296/** 记录是否已超过保留天数没更新;-1 永远不算过期 */
297export function isExpired(updatedAt: number | undefined, now: number, retentionDays: number): boolean {
298  return retentionDays !== -1 && now - (updatedAt ?? 0) > retentionDays * DAY_MS
299}
300
301/** 第二行右侧:只显示用时 */
302export function formatStats(stats: TurnStats, lang: Lang): string {
303  return formatElapsed(stats.elapsedMs, lang)
304}
305
306const MINUTE_MS = 60_000
307const CACHE_LOW_MS = 10 * MINUTE_MS
308const TTL_5M_MS = 5 * MINUTE_MS
309const TTL_1H_MS = 60 * MINUTE_MS
310
311/** 同一模型的不同写法归成一个:去掉 `[1m]` 这类上下文窗口后缀 */
312export function modelKey(model: string): string {
313  return model.replace(/\[[^\]]*\]$/, '')
314}
315
316/**
317 * transcript 里含 `ephemeral_` 的几行中,主线程里这个模型最近一次写入缓存用的 TTL;读不到返回 undefined。
318 * 缓存按模型分开,别的模型写的 TTL 不能算到它头上;这个模型只读缓存的响应没有写入,也跳过
319 * 同一次请求两种都写了时按 5 分钟算:短的那段在前缀末尾,它过期后整段就命中不了
320 */
321export function cacheTtlFromTranscript(lines: string, model: string): number | undefined {
322  for (const row of lines.split('\n').reverse()) {
323    let entry: { type?: string; isSidechain?: boolean; message?: { model?: string; usage?: { cache_creation?: Record<string, number> } } }
324    try {
325      entry = JSON.parse(row)
326    } catch {
327      continue
328    }
329    if (entry?.type !== 'assistant' || entry.isSidechain) continue
330    if (typeof entry.message?.model !== 'string' || modelKey(entry.message.model) !== model) continue
331    const creation = entry.message?.usage?.cache_creation
332    if ((creation?.ephemeral_5m_input_tokens ?? 0) > 0) return TTL_5M_MS
333    if ((creation?.ephemeral_1h_input_tokens ?? 0) > 0) return TTL_1H_MS
334  }
335  return undefined
336}
337
338function cacheLeftMs(entry: CacheEntry, now: number): number {
339  return entry.at + entry.ttlMs - now
340}
341
342/**
343 * 右上角的缓存提示。缓存不是今天用过的不显示;当前模型没有记录(刚切到一个这次还没用过的模型)算过期。
344 * 分钟数向上取整:10 分以上是 fresh,10 分及以下是 low(卡片上标红)
345 */
346export function cacheHint(state: CacheState | null, now: number, offsetMinutes: number, lang: Lang): CacheHint | undefined {
347  const entries = state ? Object.values(state.byModel) : []
348  if (!state || entries.length === 0) return undefined
349  const lastUsed = Math.max(...entries.map(entry => entry.at))
350  if (!isSameLocalDay(lastUsed, now, offsetMinutes)) return undefined
351  const L = labels(lang)
352  const entry = state.byModel[state.model]
353  const left = entry ? cacheLeftMs(entry, now) : 0
354  if (left <= 0) return { text: L.cacheExpired, tone: 'expired' }
355  const minutes = Math.ceil(left / MINUTE_MS)
356  return { text: L.cacheLeft(minutes), tone: left > CACHE_LOW_MS ? 'fresh' : 'low' }
357}
358
359/** 到提示的分钟数下一次变化还有多久;已失效或没有记录时不用再刷新 */
360export function nextCacheChange(state: CacheState | null, now: number): number | undefined {
361  const entry = state?.byModel[state.model]
362  if (!entry) return undefined
363  const left = cacheLeftMs(entry, now)
364  if (left <= 0) return undefined
365  return left % MINUTE_MS || MINUTE_MS
366}
367
types/index.d.ts 54 lines
1export type Lang = 'zh' | 'en'
2
3/** 卡片上的四个字段:每轮由模型重写 */
4export type Recap = { goal: string; now: string; waiting: string; next: string }
5
6/** 展开的详情:按生成时的轮次缓存,轮次没变就不重新生成;kind 区分旧版格式,旧的缓存作废重写 */
7export type Detail = { text: string; turn: number; kind?: 'mainline' }
8
9/** 上一轮的统计:一轮结束后继续显示在第二行右侧 */
10export type TurnStats = { calls: number; files: number; elapsedMs: number }
11
12/** 每个会话在 $.store 里的一条记录,回看旧会话时靠它恢复卡片 */
13export type SessionRecord = {
14  recap: Recap
15  /** 整个会话的滚动总结,每轮在上一份基础上更新 */
16  overall: string
17  turn: number
18  lang: Lang
19  updatedAt: number
20  detail?: Detail
21  stats?: TurnStats
22  /** 第一份摘要出来前的占位卡片:只在内存里,不写进 store */
23  draft?: true
24}
25
26/** 进行中这一轮的进度:一句话目标由模型写,turn 是这一轮在对话里的序号,其余在本地统计 */
27export type TurnProgress = { intent: string; turn: number; calls: number; files: string[]; startedAt: number }
28
29export type DetailView = { status: 'loading' | 'ready' | 'error'; text: string }
30
31/** 某个模型的提示缓存:主线程最后一次请求的时刻,和 transcript 里这次写入缓存用的 TTL */
32export type CacheEntry = { at: number; ttlMs: number }
33
34/** 一个 session 的提示缓存,按模型分开记:切回原来的模型时,它的缓存可能还没过期 */
35export type CacheState = { model: string; byModel: Record<string, CacheEntry>; updatedAt: number }
36
37/** 右上角的缓存提示:fresh 剩 10 分钟以上,low 不到 10 分钟(标红),expired 已过期 */
38export type CacheHint = { text: string; tone: 'fresh' | 'low' | 'expired' }
39
40declare module 'claude-code' {
41  interface PluginState {
42    'status-card': {
43      record: SessionRecord | null
44      progress: TurnProgress | null
45      clockNow: number
46      isExpanded: boolean
47      isFolded: boolean
48      detail: DetailView | null
49      transcriptPath: string
50      cache: CacheState | null
51    }
52  }
53}
54