Rewind or summarize from any prompt, tool call or AskUserQuestion answer, with a reply preview and saved branches

A Claude Code mod that lets you rewind or summarize from any of your prompts, any tool call, or any question Claude asked you with AskUserQuestion.
The built-in /rewind goes back to one of your prompts. better-rewind adds a few things to that:
/better-rewind branches lets you read it.It replaces the /rewind command and adds its own command, /better-rewind. Pressing Esc twice still opens the built-in Rewind; see Open it with a key.
At the prompt of a terminal Claude Code session:
/plugin install better-rewind --marketplace hamTotk/better-rewind
Answer y to add the marketplace, then pick a scope (the user scope is first). The mod is active at once, no restart needed. Node.js must be on your PATH.
To remove it: claude plugin uninstall better-rewind.
/rewind or /better-rewind opens the list of points: each of your prompts, each AskUserQuestion question (indented under its prompt), and the other tool calls (indented one step further).▸ 3 tool calls. Press Enter on that line to show them, and again to fold them. Each time the list opens, they start folded. (Space cannot do this: the pane does not receive it.)↑ / ↓ select a point, and the reply that followed it is shown below. Enter chooses it; Esc closes the pane./better-rewind branches lists the conversations you rewound away, newest first, read-only.Pressing Esc twice opens the built-in Rewind, and a mod cannot change that: Claude Code opens it without going through any hook. You can give better-rewind a key of its own instead. Add this to ~/.claude/keybindings.json (create the file if it does not exist; if it does, add the line to its "Chat" block):
{
"bindings": [
{ "context": "Chat", "bindings": { "ctrl+q": "command:better-rewind" } }
]
}
Claude Code does not use Ctrl+Q for anything else. Your terminal may take some keys before Claude Code sees them, or pass them on changed; for example, Alt+R works in some terminals but does not reach Claude Code in others. If Ctrl+Q does nothing, pick another free key, such as alt+r or ctrl+x ctrl+r (Ctrl+X, then Ctrl+R).
You could bind "escape escape" instead, but then a single Esc no longer stops Claude while it is responding (Claude Code waits up to 3 seconds for the second Esc and drops the first). Ctrl+C still stops it.
/rewind: the mod answers the /rewind command itself, so the built-in Rewind does not open. If better-rewind cannot open its list, the built-in Rewind opens instead.~/.claude/projects/<project>/<session>.jsonl) at the point and reloads the same session with /resume. No new session is created. The full transcript from before the cut is saved first./compact and splits the conversation at the point, so only one side is summarized. The transcript is not edited directly, and a /compact line appears in the conversation./better-rewind, a notice says which rewind it was, which files may be affected and where their earlier contents are. That notice appears only once.Saved data lives in ~/.claude/better-rewind/<session>/ (under CLAUDE_CONFIG_DIR if set): snaps/ holds the file backups, branches/ what each rewind replaced. Nothing is deleted automatically; delete the folder when you no longer need it.
Getting back files that Restore code overwrote. Before a rewind changes any file, it copies the file's current contents to branches/<time>.files/<n>. branches/<time>.json lists each restored file's path and its copy in backup (null when the file did not exist), so copy that file back over path. <time> is when you rewound (UTC, for example 2026-10-10T05-03-00-000Z). branches/<time>.jsonl is the whole transcript from before a conversation rewind.
branches/)./plugin install line works in the terminal.node --test tests/transcript.test.mjs
claude plugin test .
claude plugin validate .
claude --plugin-dir .
MIT
自分の発言、ツール呼び出し、Claude が AskUserQuestion で聞いてきた質問のどこからでも、会話とコードを戻したり要約したりできる Claude Code の mod です。
組み込みの /rewind は自分の発言の地点に戻れます。better-rewind はそれに次のことを足します。
/better-rewind branches で読めます。/rewind コマンドを置き換え、専用のコマンド /better-rewind も足します。Esc を 2 回押したときは組み込みの Rewind が開きます (キーで開く を参照)。
ターミナル版の Claude Code で次の 1 行を打ちます。
/plugin install better-rewind --marketplace hamTotk/better-rewind
マーケットプレイスを追加するか聞かれたら y、続けて入れる範囲を選びます (先頭がユーザー全体)。入れた時点で使えるようになり、再起動は要りません。Node.js が PATH にある必要があります。
外すときは claude plugin uninstall better-rewind です。
/rewind か /better-rewind で地点の一覧が開きます。地点は自分の発言、AskUserQuestion の質問 (発言の下に字下げして表示)、ほかのツール呼び出し (さらに 1 段字下げして表示) です。▸ 3 tool calls のような 1 行に畳まれています。その行で Enter を押すと開き、もう一度押すと畳みます。一覧を開くたびに畳んだ状態から始まります (Space はペインに届かないので使えません)。/better-rewind branches で、巻き戻して捨てた会話を新しい順に読めます (読むだけです)。Esc を 2 回押すと組み込みの Rewind が開き、これは mod からは変えられません (Claude Code が hook を通さずに開くため)。代わりに、better-rewind を開くキーを割り当てられます。~/.claude/keybindings.json に次を書いてください (ファイルが無ければ作り、あればその "Chat" の欄に 1 行足します)。
{
"bindings": [
{ "context": "Chat", "bindings": { "ctrl+q": "command:better-rewind" } }
]
}
Ctrl+Q は Claude Code のほかの機能では使われていません。端末によってはキーを先に使ったり、変えて渡したりします (例えば Alt+R は、効く端末と Claude Code まで届かない端末があります)。Ctrl+Q で開かなければ、alt+r や ctrl+x ctrl+r (Ctrl+X の後に Ctrl+R) などほかの空いているキーにしてください。
"escape escape" に割り当てることもできますが、そうすると Claude の応答中に Esc を 1 回押しても止まらなくなります (Claude Code が 2 回目の Esc を最大 3 秒待ち、1 回目を捨てるため)。Ctrl+C では止まります。
/rewind: mod が /rewind コマンドに自分で答えるので、組み込みの Rewind は開きません。better-rewind が一覧を開けなかったときは、組み込みの Rewind が開きます。~/.claude/projects/<project>/<session>.jsonl) を地点で切り、同じセッションを /resume で読み直します。新しいセッションは増えません。切る前の記録は先に丸ごと保存します。/compact を動かし、会話を地点で分けて片側だけを要約させます。記録ファイルは直接書き換えません。会話には /compact の行が残ります。/better-rewind を開いたときには、どの巻き戻しだったか、影響を受けたかもしれないファイル、その前の中身の場所を通知します。この通知は 1 度だけです。保存先は ~/.claude/better-rewind/<session>/ (CLAUDE_CONFIG_DIR があればその下) です。snaps/ にファイルの控え、branches/ に巻き戻しで置き換えた中身が入ります。自動では消さないので、要らなくなったらフォルダごと消してください。
Restore code で上書きしたファイルを取り戻すには: 巻き戻しはファイルを変える前に、今の中身を branches/<時刻>.files/<番号> に写します。branches/<時刻>.json の files に、戻したファイルの path と写しの場所 backup (ファイルが無かったときは null) が並ぶので、その写しを path へコピーし直してください。<時刻> は巻き戻した時刻 (UTC。例: 2026-10-10T05-03-00-000Z) です。会話を戻したときは、切る前の記録全体が branches/<時刻>.jsonl に入ります。
branches/ に残ります)。hooks/register.tsx 812 lines1import { atom, read, update } from 'claude-code'
2import type { Elements, EngineInterface, Register, RenderSurface } from 'claude-code'
3
4import type { Branch, Mode, Point, RewindResult, Snap, Unfinished, View } from '../types'
5import type { OptionKey } from './lib'
6import {
7 BUSY,
8 BUSY_SUMMARIZE,
9 CURRENT,
10 branchLines,
11 changesParts,
12 clipToRows,
13 doneMessage,
14 editedFile,
15 isAsk,
16 isMissing,
17 listRows,
18 modeOptions,
19 plural,
20 pointKey,
21 restoreLines,
22 rowGap,
23 snapName,
24 splitForSummary,
25 summarizeRequest,
26 summarizedMessage,
27 unfinishedMessage,
28 windowAround,
29 windowRows,
30} from './lib'
31
32// /better-rewind (と、置き換えた組み込みの /rewind) で巻き戻し地点 (人の発言・AskUserQuestion の質問・ほかのツール呼び出し) の
33// 一覧ペインを開く。見た目は組み込みの Rewind 画面に寄せる: 発言と質問は 1 地点 2 行 (内容と、そこから次の人の発言までに
34// 変わったファイルの要約)、選択中は ❯ と suggestion 色、最後に (現在)。ほかのツール呼び出しは続くものを 1 行に畳み、
35// その行で Enter を押すと 1 行ずつ開く (ペインでは Space を受け取れない: 打つと入力欄へ移る。2026-10-11 実機で確認)。
36// Esc 2 回は置き換えられない (本体が hook を通さずに組み込みの画面を開く)。README の Alt+R の割り当てで代わりにする。
37// キー操作はペインのフォーカスリング (矢印で移動・Enter で決定・Esc で閉じる) に任せ、
38// フォーカスの移動を ui.focus で受けてカーソルとし、その地点の AI の返答を下にプレビューする。
39// 地点を Enter で選ぶと戻し方 (AskUserQuestion なら続けて回答) を選ばせ、bin/transcript.mjs (node) で記録を切って
40// /resume で同じセッションを読み直す。要約を選ぶと添える指示を聞いて $.command.run で /compact を動かし、
41// session.compact の hook が地点の前後で要約する部分と残す部分を分ける (記録は書き換えない)。
42// $.session.compact は呼ばない: 呼んだ mod 自身の session.compact hook が飛ばされ、会話全体が要約される
43// (2026-10-10 実機で確認)。/compact を経由すると hook が trigger 'manual' で呼ばれ、要約が終わってから戻る。
44// /better-rewind branches は巻き戻す前の会話を読むだけの一覧。
45// Edit / Write / NotebookEdit の直前には tool.call で対象ファイルの控えを取り、ツールが実行されたかを控えに書き足す
46
47const PANE = 'better-rewind'
48// 枝の全文から一覧へ戻るボタンの key
49const BACK = 'back'
50// 回答を自分で書く入力欄の key
51const OWN = 'answer:own'
52// 回答の段階で 1 つ前へ戻るボタンの key
53const ANSWER_BACK = 'answer:back'
54// 要約に添える指示の入力欄・指示なしで要約するボタン・戻し方の選択へ戻るボタンの key
55const CONTEXT = 'summarize:context'
56const SUMMARIZE_NOW = 'summarize:now'
57const SUMMARIZE_BACK = 'summarize:back'
58// 見出し・説明・一覧前の空行・区切り前の空行・区切り・案内前の空行・案内
59const FIXED_ROWS = 7
60// 字下げ 1 段の幅 (質問は 1 段、ほかのツール呼び出しは 2 段)
61const NEST = 4
62// 回答を選び直して読み直したあと、AI に続きを始めさせる一言
63// (AI には新しい回答しか見えないので「変えた」とは言わない)
64const CONTINUE = 'Continue based on my answer to your question.'
65// 要約を地点で分けられなかったときに /compact を断る理由
66const SPLIT_FAILED = 'better-rewind could not split the conversation at this point. Nothing was changed'
67// $.fs で控えを取る上限。base64 で 4/3 倍になり $.fs.write の 4 MiB に収める。超えたら node で写す
68const INLINE_MAX = 2.5 * 1024 * 1024
69
70const points = atom({ plugin: 'better-rewind', key: 'points' } as const, [])
71const cursor = atom({ plugin: 'better-rewind', key: 'cursor' } as const, null)
72const expanded = atom({ plugin: 'better-rewind', key: 'expanded' } as const, [])
73const status = atom({ plugin: 'better-rewind', key: 'status' } as const, '')
74const view = atom({ plugin: 'better-rewind', key: 'view' } as const, 'points')
75const picked = atom({ plugin: 'better-rewind', key: 'picked' } as const, null)
76const mode = atom({ plugin: 'better-rewind', key: 'mode' } as const, null)
77const answers = atom({ plugin: 'better-rewind', key: 'answers' } as const, [])
78const direction = atom({ plugin: 'better-rewind', key: 'direction' } as const, null)
79const pending = atom({ plugin: 'better-rewind', key: 'pending' } as const, null)
80const outcome = atom({ plugin: 'better-rewind', key: 'outcome' } as const, null)
81const sub = atom({ plugin: 'better-rewind', key: 'sub' } as const, null)
82const branches = atom({ plugin: 'better-rewind', key: 'branches' } as const, [])
83const opened = atom({ plugin: 'better-rewind', key: 'opened' } as const, null)
84const isOpen = atom({ plugin: 'better-rewind', key: 'isOpen' } as const, false)
85const isRunning = atom({ plugin: 'better-rewind', key: 'isRunning' } as const, false)
86
87type Ui = Elements[RenderSurface]
88
89// node の呼び出しの既定の時間切れ。巻き戻しは書き込みの途中で打ち切られないよう、$.process.run の上限 (10 分) にする
90const NODE_TIMEOUT = 60_000
91const REWIND_TIMEOUT = 600_000
92
93type NodeOut<T> = Partial<T> & {
94 error?: string
95 // helper が答えを返さなかった (起動できない・時間切れ・読めない出力)。途中まで進んだかもしれない
96 isUnknown?: true
97}
98
99// bin/transcript.mjs を呼んで、最後の行の JSON を返す。helper が答えなければ error に理由を入れ、isUnknown を立てる (reject しない)
100async function node<T>($: EngineInterface, args: string[], stdin?: string, timeoutMs = NODE_TIMEOUT): Promise<NodeOut<T>> {
101 let r: Awaited<ReturnType<EngineInterface['process']['run']>>
102 try {
103 r = await $.process.run(['node', `${$.plugin.root}/bin/transcript.mjs`, ...args], { timeoutMs, ...(stdin === undefined ? {} : { stdin }) })
104 } catch (err) {
105 return { error: `better-rewind's helper did not finish (${String(err)})`, isUnknown: true } as NodeOut<T>
106 }
107 try {
108 const out = JSON.parse(r.stdout.trim().split('\n').at(-1) || '') as NodeOut<T>
109 if (out && typeof out === 'object') return out
110 } catch {
111 // 下で読めない答えとして扱う
112 }
113 return { error: `better-rewind's helper gave no answer${r.stderr ? ` (${r.stderr.trim().slice(0, 120)})` : ''}`, isUnknown: true } as NodeOut<T>
114}
115
116async function loadPoints($: EngineInterface): Promise<Point[]> {
117 await update($, status, () => 'Loading…')
118 const out = await node<{ points: Point[]; unfinished: Unfinished[] }>($, ['points', await $.session.id()])
119 if (!out.points) {
120 await update($, status, () => `Could not load: ${out.error ?? ''}`)
121 return []
122 }
123 await update($, points, () => out.points ?? [])
124 // 前に途中で打ち切られた巻き戻しがあれば 1 度だけ知らせる (helper が知らせた印を付ける)
125 const warning = unfinishedMessage(out.unfinished ?? []) ?? ''
126 await update($, status, () => warning)
127 if (warning) $.ui.toast(warning, LONG_TOAST)
128 return out.points
129}
130
131// 段階を切り替え、キーボードをその段階の要素に置く
132async function showView($: EngineInterface, v: View, key: string) {
133 await update($, view, () => v)
134 await update($, sub, () => (v === 'points' ? null : key))
135 if (v === 'points') await update($, cursor, () => (key === CURRENT ? null : key))
136 await $.ui.focus({ requestId: PANE, key }).catch(() => undefined)
137}
138
139async function closePane($: EngineInterface) {
140 await update($, isOpen, () => false)
141 await update($, view, () => 'points')
142 await $.ui.close({ id: PANE })
143}
144
145async function refuseWhileRunning($: EngineInterface, message = BUSY): Promise<boolean> {
146 if (!(await read($, isRunning))) return false
147 await update($, status, () => message)
148 $.ui.toast(message)
149 return true
150}
151
152// 長い知らせ (ファイルの場所を含むもの) は読めるだけの間出しておく
153const LONG_TOAST = { timeoutMs: 15_000 }
154
155// Enter で地点を選んだとき。(現在) なら閉じる。それ以外は戻し方の段階へ (選べるのが「やめる」だけの地点は断る)
156async function choose($: EngineInterface, p: Point | undefined) {
157 if (!p) return closePane($)
158 if (await refuseWhileRunning($)) return
159 const options = modeOptions(p, await read($, points))
160 if (options.length <= 1) {
161 $.ui.toast('Cannot rewind to this point (the conversation cannot be cut or summarized here and no file backups exist)')
162 return
163 }
164 await update($, picked, () => p)
165 await update($, mode, () => null)
166 await update($, answers, () => [])
167 await update($, direction, () => null)
168 await update($, status, () => '')
169 await showView($, 'modes', `mode:${options[0]?.key ?? 'cancel'}`)
170}
171
172async function pickMode($: EngineInterface, p: Point, m: OptionKey) {
173 if (m === 'cancel') return showView($, 'points', pointKey(p))
174 if (m === 'summarize' || m === 'summarize_up_to') {
175 await update($, direction, () => (m === 'summarize' ? 'from' : 'up_to'))
176 return showView($, 'summarize', CONTEXT)
177 }
178 if (isAsk(p) && m !== 'files') {
179 await update($, mode, () => m)
180 await update($, answers, () => [])
181 return showView($, 'answer', 'answer:0')
182 }
183 return execute($, p, m)
184}
185
186// 要約に添える指示を受けて (空でもよい)、ペインを閉じて /compact を動かす。どこで分けるかは session.compact の hook が
187// pending を読んで決め、どうしたかを outcome に残す。終わったらそれを読んで知らせる。ファイルには触れず、枝も残さない
188async function summarize($: EngineInterface, p: Point, context: string) {
189 if (await refuseWhileRunning($, BUSY_SUMMARIZE)) return
190 const d = await read($, direction)
191 const request = d ? summarizeRequest(p, await read($, points), d) : undefined
192 if (!request) {
193 const msg = 'Cannot summarize from this point'
194 await update($, status, () => msg)
195 $.ui.toast(msg)
196 return
197 }
198 await update($, status, () => '')
199 await closePane($)
200 await update($, outcome, () => null)
201 await update($, pending, () => request)
202 $.ui.status('Summarizing…')
203 const instructions = context.trim()
204 try {
205 await $.command.run({ command: 'compact', ...(instructions ? { args: instructions } : {}) })
206 $.ui.toast(summarizedMessage(request.direction, await read($, outcome)))
207 } catch (err) {
208 // hook が断った後で /compact が失敗を返しても、断った理由の方を出す
209 const o = await read($, outcome)
210 $.ui.toast(o?.kind === 'skip' ? summarizedMessage(request.direction, o) : `Could not summarize: ${String(err)}`)
211 } finally {
212 $.ui.status(undefined)
213 await update($, pending, () => null)
214 }
215}
216
217// 質問 1 つ分の回答。全部そろったら巻き戻す
218async function giveAnswer($: EngineInterface, p: Point, text: string) {
219 const answer = text.trim()
220 const m = await read($, mode)
221 if (!answer || !m) return
222 const given = [...(await read($, answers)), answer]
223 if (given.length < (p.questions?.length ?? 0)) {
224 await update($, answers, () => given)
225 return showView($, 'answer', 'answer:0')
226 }
227 return execute($, p, m, given)
228}
229
230// 回答の段階で 1 つ前へ。1 問目なら戻し方の選択へ戻る
231async function stepBack($: EngineInterface, p: Point) {
232 const given = await read($, answers)
233 if (given.length === 0) return showView($, 'modes', `mode:${(await read($, mode)) ?? modeOptions(p, await read($, points))[0]?.key ?? 'cancel'}`)
234 await update($, answers, () => given.slice(0, -1))
235 return showView($, 'answer', 'answer:0')
236}
237
238// ログに書く (知らせの文に出さない生の理由)。ログの失敗は巻き戻しに響かせない
239function log($: EngineInterface, text: string) {
240 try {
241 $.ui.log(`better-rewind: ${text}`)
242 } catch {
243 // ログが書けなくても続ける
244 }
245}
246
247// 記録を切り (とファイルを戻し)、同じセッションを読み直す。回答を選び直したときは Claude に続きを始めさせ、
248// 人の発言の地点ではその発言を入力欄に戻す (会話を戻したときだけ)。
249// helper の失敗 (error) では、ふつう記録もファイルも変わっていない (書き戻せなかったファイルは error の文に場所が出る)。
250// ただし戻し終えた後で終わった印を書けなかったときは、error に transcriptChanged と戻した結果 (restored など) が付いてくる。
251// 記録が書き換わっていれば (transcriptChanged: true) 読み直してから知らせ、ファイルだけ戻したときは戻した件数と一緒に知らせる。
252// helper が答えなかったとき (isUnknown) は途中まで進んだかもしれないので、会話を戻す巻き戻しなら読み直して知らせる
253async function execute($: EngineInterface, p: Point, m: Mode, given?: string[]) {
254 if (await refuseWhileRunning($)) return
255 await update($, status, () => 'Rewinding…')
256 const sessionId = await $.session.id()
257 const spec = { uuid: p.uuid, toolUseId: p.toolUseId, label: p.label, mode: m, answers: given }
258 const out = await node<RewindResult>($, ['rewind', sessionId], JSON.stringify(spec), REWIND_TIMEOUT)
259 const isUnknown = out.isUnknown === true || (out.error === undefined && (!out.restored || !out.removed))
260 const changed = out.transcriptChanged === true
261 // 戻し終えた後の失敗 (戻した結果が付いている)
262 const finished = out.error !== undefined && Array.isArray(out.restored) && Array.isArray(out.removed)
263 if (out.error !== undefined && !isUnknown && !changed && !finished) {
264 const msg = `Rewind failed: ${out.error}`
265 await update($, status, () => msg)
266 $.ui.toast(msg, LONG_TOAST)
267 return
268 }
269 await update($, status, () => '')
270 await closePane($)
271 if (isUnknown) {
272 // 生の理由 (時間切れ・起動できない・読めない出力) はログへ。知らせには利用者が次にすることを書く
273 log($, `the rewind did not report back: ${out.error ?? 'no answer'}`)
274 // 記録が書き換わったか分からない。読み直せば、動いている会話を記録に合わせられる (変わっていなければ同じ会話が戻る)
275 const reloaded = m !== 'files' && (await $.command.run({ command: 'resume', args: sessionId }).then(() => true, () => false))
276 const next = m === 'files' ? '' : reloaded ? ' The conversation was reloaded in case it changed.' : ` Run /resume ${sessionId} to reload the conversation in case it changed.`
277 $.ui.toast(
278 `The rewind may not have finished: it stopped before reporting back (for example, because it ran longer than 10 minutes).${next} If it stopped partway, the next time you open /better-rewind it tells you which files may be affected and where their earlier contents are`,
279 LONG_TOAST,
280 )
281 return
282 }
283 if (m !== 'files' || changed) {
284 try {
285 await $.command.run({ command: 'resume', args: sessionId })
286 } catch (err) {
287 $.ui.toast(`The transcript was rewound but could not be reloaded. Run /resume ${sessionId} (${String(err)})`, LONG_TOAST)
288 return
289 }
290 if (out.error !== undefined) {
291 $.ui.toast(`The conversation was rewound and reloaded, but part of it failed: ${out.error}`, LONG_TOAST)
292 return
293 }
294 if (given) void $.prompt.submit({ text: CONTINUE }).catch(() => undefined)
295 else if (p.kind === 'prompt' && p.text) await $.prompt.fill({ text: p.text }).catch(() => undefined)
296 }
297 const done = doneMessage(m, { restored: out.restored ?? [], removed: out.removed ?? [], skipped: out.skipped ?? [] })
298 // ファイルだけ戻した後の失敗は、戻したことと一緒に知らせる
299 if (out.error !== undefined) $.ui.toast(`${done}. ${out.error}`, LONG_TOAST)
300 else $.ui.toast(done)
301}
302
303// 控えの保存先 (<設定フォルダ>/better-rewind/<session>)。セッションごとに 1 度だけ node に聞く
304const dataDirs = new Map<string, Promise<string>>()
305function dataDir($: EngineInterface, sessionId: string): Promise<string> {
306 const known = dataDirs.get(sessionId)
307 if (known) return known
308 const asked = node<{ dir: string }>($, ['dir', sessionId]).then(out => {
309 if (!out.dir) throw new Error(out.error ?? 'Backup folder not found')
310 return out.dir
311 })
312 dataDirs.set(sessionId, asked)
313 asked.catch(() => dataDirs.delete(sessionId))
314 return asked
315}
316
317// Edit / Write / NotebookEdit の実行直前の中身を snaps/<tool_use id>.json (と .b64) に控える (state は 'pending')。
318// 無いファイル (ENOENT) は「無かった」と記録する。あるのに読めないなど他の理由で stat に失敗したら控えを取らない
319// (「無かった」と控えると、戻すときに消してしまう)。エラーに ENOENT が読めないときは exists で確かめる。
320// 大きいファイルは node に写させる。返す値は書いた情報 (ファイルでないものは控えないので undefined)。
321// $.fs で読んだ中身 (base64) は、ツールが断られたときにファイルが変わったかを比べるために、書いた情報の外で持って返す
322type Taken = Snap & { base64?: string }
323async function snapshot($: EngineInterface, toolUseId: string, tool: string, file: string): Promise<Taken | undefined> {
324 const sessionId = await $.session.id()
325 const dir = `${await dataDir($, sessionId)}/snaps`
326 const id = snapName(toolUseId)
327 const meta: Snap = { toolUseId, tool, path: file, at: Date.now(), existed: false, state: 'pending' }
328 const stat = await $.fs.stat(file).catch(async (err: unknown) => {
329 if (isMissing(err) || !(await $.fs.exists(file))) return undefined
330 throw err
331 })
332 if (stat && stat.kind !== 'file') return undefined
333 if (stat && stat.size > INLINE_MAX) {
334 const out = await node<Snap>($, ['snap', sessionId, toolUseId, tool, file, String(meta.at)])
335 if (out.error !== undefined) throw new Error(out.error)
336 return { ...meta, existed: true, data: `${id}.bin` }
337 }
338 if (stat) {
339 const { base64 } = await $.fs.read(file, { as: 'bytes' })
340 const taken: Snap = { ...meta, existed: true, data: `${id}.b64` }
341 // 中身を書いてから情報を書く (情報があれば中身もある)
342 await $.fs.write(`${dir}/${id}.b64`, base64)
343 await $.fs.write(`${dir}/${id}.json`, JSON.stringify(taken))
344 return { ...taken, base64 }
345 }
346 await $.fs.write(`${dir}/${id}.json`, JSON.stringify(meta))
347 return meta
348}
349
350// 控えに失敗したとき: 利用者に知らせ、「控えが無い」印 (failed) を残す。印があれば、後でこの時点より前へ戻すとき
351// このファイルを途中の版へ黙って戻さずに「戻さない」と出せる。印も書けなければ undefined
352async function snapFailed($: EngineInterface, toolUseId: string, tool: string, file: string, err: unknown): Promise<Snap | undefined> {
353 $.ui.log(`better-rewind: could not back up ${file}: ${String(err)}`)
354 $.ui.toast(`better-rewind could not back up ${file} before ${tool} changed it, so Restore code cannot bring back its earlier contents`, LONG_TOAST)
355 const marker: Snap = { toolUseId, tool, path: file, at: Date.now(), existed: false, state: 'pending', failed: true }
356 try {
357 await $.fs.write(`${await dataDir($, await $.session.id())}/snaps/${snapName(toolUseId)}.json`, JSON.stringify(marker))
358 return marker
359 } catch {
360 return undefined
361 }
362}
363
364// 拒否・失敗の結果が来たのに、ファイルが控えた時から変わっているか。後段の hook がツールの実行後に断ったときや、
365// ツールが途中で止まったときに起きる。読めないなど比べられなければ throw する (控えは 'pending' のまま残り、
366// 後で戻すときに「実行されたか分からない」として途中の版へ黙って戻さない)
367async function changedSince($: EngineInterface, taken: Taken, file: string): Promise<boolean> {
368 if (!taken.existed) return $.fs.exists(file)
369 // 消えていれば変わった。ほかの理由で読めなければ比べられない
370 const now = await $.fs.read(file, { as: 'bytes' }).catch(async (err: unknown) => {
371 if (isMissing(err) || !(await $.fs.exists(file))) return undefined
372 throw err
373 })
374 return now === undefined || now.base64 !== taken.base64
375}
376
377// ツールの結果を見て控えの state を決める。実行されたら 'ran'。拒否・失敗でもファイルが変わっていれば、実行された
378// (控えはその直前の中身) として 'ran' にする。変わっていなければ戻す対象から外し ('denied')、中身を消す (人が拒んだ
379// ファイルの中身を残さない)。控えに失敗した印は、拒否・失敗のとき比べる中身が無いので 'pending' のまま残す。
380// 大きいファイル (.bin) は node が比べて決める。ここでの失敗はツールの結果に響かせない
381async function settleSnap($: EngineInterface, taken: Taken, file: string, ran: boolean) {
382 const sessionId = await $.session.id()
383 const dir = `${await dataDir($, sessionId)}/snaps`
384 const id = snapName(taken.toolUseId)
385 const { base64: _, ...snap } = taken
386 if (!ran && snap.failed === true) return
387 const isBig = snap.data !== undefined && !snap.data.endsWith('.b64')
388 if (ran || (!isBig && (await changedSince($, taken, file)))) {
389 await $.fs.write(`${dir}/${id}.json`, JSON.stringify({ ...snap, state: 'ran' }))
390 return
391 }
392 const { data, ...rest } = snap
393 await $.fs.write(`${dir}/${id}.json`, JSON.stringify({ ...rest, state: 'denied' }))
394 if (data?.endsWith('.b64')) await $.fs.write(`${dir}/${data}`, '')
395 // 大きいファイルは node が今の中身と比べ、変わっていれば控えを 'ran' に戻し、変わっていなければ中身ごと消す
396 else if (data) await node($, ['drop', sessionId, taken.toolUseId])
397}
398
399const DESCRIPTION = 'Rewind or summarize from any prompt, question or tool call'
400
401// 地点の一覧を開く。ツール呼び出しはすべて畳んだ状態から始める
402async function openPoints($: EngineInterface) {
403 await update($, cursor, () => null)
404 await update($, expanded, () => [])
405 await update($, view, () => 'points')
406 await update($, sub, () => null)
407 const list = await loadPoints($)
408 const opened = await $.ui.open({ id: PANE, title: 'Better Rewind', focus: true, closeOnEscape: true })
409 await update($, isOpen, () => true)
410 // キーボードを一覧の (現在) に置く。渡せなかったときは Tab かクリックで渡せることを案内する (理由はログへ)
411 const focused = await $.ui.focus({ requestId: PANE, key: CURRENT }).catch((err: unknown) => ({ deny: String(err) }))
412 if ('deny' in focused) $.ui.log(`better-rewind: could not move keyboard focus: ${focused.deny}`)
413 const note = 'deny' in focused ? ' (press Tab or click the list to use the keyboard there)' : ''
414 return { text: `Opened ${plural(list.length, 'rewind point')}${opened.isPlaced ? '' : ' (waiting: terminal too narrow)'}${note}` }
415}
416
417// 畳んだツール呼び出しの行で Enter: 開く・畳む。カーソルはその行に残す
418async function toggleGroup($: EngineInterface, key: string) {
419 await update($, expanded, list => (list.includes(key) ? list.filter(k => k !== key) : [...list, key]))
420 await update($, cursor, () => key)
421}
422
423async function openBranches($: EngineInterface) {
424 const out = await node<{ branches: Branch[] }>($, ['branches', await $.session.id()])
425 const list = out.branches ?? []
426 await update($, branches, () => list)
427 await update($, opened, () => null)
428 await update($, status, () => (out.branches ? '' : `Could not load: ${out.error ?? ''}`))
429 await update($, view, () => 'branches')
430 await update($, sub, () => list[0]?.id ?? null)
431 const placed = await $.ui.open({ id: PANE, title: 'Better Rewind', focus: true, closeOnEscape: true })
432 await update($, isOpen, () => true)
433 if (list[0]) await $.ui.focus({ requestId: PANE, key: list[0].id }).catch(() => undefined)
434 return { text: `Opened ${plural(list.length, 'saved conversation')}${placed.isPlaced ? '' : ' (waiting: terminal too narrow)'}` }
435}
436
437// 枝の全文を開く (id) か一覧へ戻る (null)。focus は次に置くキー
438async function openBranch($: EngineInterface, id: string | null, focus: string) {
439 await update($, opened, () => id)
440 await showView($, id === null ? 'branches' : 'branch', focus)
441}
442
443// 見出しと説明の 2 行。どの段階でも同じ
444function header(ui: Ui, line: string) {
445 const { Text } = ui
446 return [
447 <Text key="title" bold color="suggestion">
448 Better Rewind
449 </Text>,
450 <Text key="lead">{line}</Text>,
451 ]
452}
453
454// 段階の選択肢 1 行。一覧と同じく ❯ の 1 文字ボタンと suggestion 色
455function choiceRow(ui: Ui, key: string, label: string, isFocused: boolean, onPress: () => void, detail?: string) {
456 const { Box, Text, Button } = ui
457 return (
458 <Box key={`row:${key}`} flexDirection="column">
459 <Box flexDirection="row">
460 <Button key={key} plain label={isFocused ? '❯' : ' '} onPress={onPress} />
461 <Text> </Text>
462 <Text color={isFocused ? 'suggestion' : undefined} wrap="truncate-end">
463 {label}
464 </Text>
465 </Box>
466 {detail && (
467 <Text dimColor wrap="truncate-end">
468 {' '}
469 {detail}
470 </Text>
471 )}
472 </Box>
473 )
474}
475
476function footer(ui: Ui, note: string, hint: string) {
477 const { Box, Text } = ui
478 return (
479 <Box key="footer" flexDirection="column" marginTop={1}>
480 {note && <Text color="warning">{note}</Text>}
481 <Text dimColor>{hint}</Text>
482 </Box>
483 )
484}
485
486async function renderModes($: EngineInterface, ui: Ui, p: Point) {
487 const { Box, Text } = ui
488 const focus = await read($, sub)
489 const options = modeOptions(p, await read($, points))
490 const at = options.some(o => `mode:${o.key}` === focus) ? focus : `mode:${options[0]?.key}`
491 // Restore code が戻すファイル: rewind と同じ計画 (地点より後の発言で変わったファイルも含む) を helper から受け取って出す
492 const r = restoreLines(p.restore)
493 return (
494 <Box flexDirection="column">
495 {header(ui, isAsk(p) ? `Change your answer to "${p.label}"` : `Rewind to just before "${p.label}"`)}
496 <Box flexDirection="column" marginTop={1}>
497 {options.map(o => choiceRow(ui, `mode:${o.key}`, o.label, `mode:${o.key}` === at, () => void pickMode($, p, o.key)))}
498 </Box>
499 {(p.restorable || r.skipped) && (
500 <Box flexDirection="column" marginTop={1}>
501 {p.restorable && (
502 <Text key="restore:lead" dimColor wrap="truncate-end">
503 {r.lead}
504 </Text>
505 )}
506 {p.restorable &&
507 r.files.map((f, i) => (
508 <Text key={`restore:${i}`} dimColor wrap="truncate-end">
509 {' '}
510 {f}
511 </Text>
512 ))}
513 {r.skipped && (
514 <Text key="restore:skipped" color="warning" wrap="truncate-end">
515 {r.skipped}
516 </Text>
517 )}
518 </Box>
519 )}
520 {footer(ui, await read($, status), '↑↓ to select · Enter to confirm · Esc to close')}
521 </Box>
522 )
523}
524
525// 要約に添える指示を聞く段階。組み込みと同じく指示は任意で、空のまま Enter でも要約する
526async function renderSummarize($: EngineInterface, ui: Ui, p: Point) {
527 const { Box, Text } = ui
528 const d = await read($, direction)
529 const focus = await read($, sub)
530 const back = `mode:${d === 'up_to' ? 'summarize_up_to' : 'summarize'}`
531 return (
532 <Box flexDirection="column">
533 {header(ui, d === 'up_to' ? `Summarize up to "${p.label}"` : `Summarize from "${p.label}"`)}
534 <Box marginTop={1}>
535 <Text dimColor>
536 {d === 'up_to'
537 ? 'Messages before this point are replaced with a summary. This point and later stay as they are. Files are not changed'
538 : 'This point and everything after it are replaced with a summary. Earlier messages stay as they are. Files are not changed'}
539 </Text>
540 </Box>
541 {/* 入力欄の無い画面 (mobile) では指示なしで要約するボタンだけ。ラベルの後ろの「: 」は入力欄が自分で描く */}
542 {'Input' in ui && (
543 <Box marginTop={1}>
544 <ui.Input key={CONTEXT} label="Add context (optional)" placeholder="What the summary should keep" submitLabel="Summarize" onSubmit={(value: string) => void summarize($, p, value)} />
545 </Box>
546 )}
547 <Box flexDirection="column" marginTop={1}>
548 {choiceRow(ui, SUMMARIZE_NOW, 'Summarize without context', focus === SUMMARIZE_NOW, () => void summarize($, p, ''))}
549 {choiceRow(ui, SUMMARIZE_BACK, 'Back to rewind options', focus === SUMMARIZE_BACK, () => void showView($, 'modes', back))}
550 </Box>
551 {footer(ui, await read($, status), 'Enter to summarize · Esc to close')}
552 </Box>
553 )
554}
555
556async function renderAnswer($: EngineInterface, ui: Ui, p: Point) {
557 const { Box, Text } = ui
558 const questions = p.questions ?? []
559 const done = (await read($, answers)).length
560 const q = questions[done]
561 if (!q) return <Text dimColor>No questions</Text>
562 const focus = await read($, sub)
563 const options = q.options ?? []
564 const count = questions.length > 1 ? ` (${done + 1}/${questions.length})` : ''
565 return (
566 <Box flexDirection="column">
567 {header(ui, `${q.header ? `${q.header}: ` : ''}${q.question}${count}`)}
568 <Box flexDirection="column" marginTop={1}>
569 {options.map((o, i) => choiceRow(ui, `answer:${i}`, o.label, `answer:${i}` === focus, () => void giveAnswer($, p, o.label), o.description))}
570 {choiceRow(ui, ANSWER_BACK, done > 0 ? 'Back to previous question' : 'Back to rewind options', focus === ANSWER_BACK, () => void stepBack($, p))}
571 </Box>
572 {/* 入力欄の無い画面 (mobile) では選択肢だけ */}
573 {'Input' in ui && (
574 <Box marginTop={1}>
575 <ui.Input
576 key={OWN}
577 label="Your answer"
578 placeholder={q.multiSelect ? 'Separate multiple answers with commas' : 'Type an answer and press Enter'}
579 submitLabel="Answer"
580 onSubmit={(value: string) => void giveAnswer($, p, value)}
581 />
582 </Box>
583 )}
584 {footer(ui, await read($, status), '↑↓ to select · Enter to confirm · Esc to close')}
585 </Box>
586 )
587}
588
589async function renderBranches($: EngineInterface, ui: Ui, rows: number, columns: number) {
590 const { Box, Text, Markdown } = ui
591 const list = await read($, branches)
592 const note = await read($, status)
593 const openId = await read($, opened)
594 const shown = list.find(b => b.id === openId)
595
596 // 全文: 読むだけ。一覧へ戻るボタンを最後に置く
597 if (shown) {
598 const lines = branchLines(shown)
599 return (
600 <Box flexDirection="column">
601 {header(ui, `${lines.title} (${lines.detail})`)}
602 <Box flexDirection="column" marginTop={1}>
603 <Markdown text={shown.text || '(no conversation)'} />
604 </Box>
605 <Box marginTop={1}>{choiceRow(ui, BACK, 'Back to list', true, () => void openBranch($, null, shown.id))}</Box>
606 {footer(ui, '', 'Enter to go back · Esc to close')}
607 </Box>
608 )
609 }
610
611 if (list.length === 0) return <Text dimColor>{note || 'No saved conversations yet'}</Text>
612 const focus = await read($, sub)
613 const found = list.findIndex(b => b.id === focus)
614 const index = found >= 0 ? found : 0
615 const previewRows = Math.min(10, Math.max(3, Math.floor(rows * 0.3)))
616 const visible = Math.max(1, Math.floor((rows - FIXED_ROWS - previewRows + 1) / 3))
617 const [start, end] = windowAround(index, list.length, visible)
618 const items = list.slice(start, end).map((b, i) => {
619 const lines = branchLines(b)
620 return (
621 <Box key={`gap:${b.id}`} marginTop={i > 0 ? 1 : 0}>
622 {choiceRow(ui, b.id, lines.title, start + i === index, () => void openBranch($, b.id, BACK), lines.detail)}
623 </Box>
624 )
625 })
626 return (
627 <Box flexDirection="column">
628 {header(ui, 'Saved conversations (read-only)')}
629 <Box flexDirection="column" marginTop={1}>
630 {items}
631 </Box>
632 <Box marginTop={1}>
633 <Text dimColor>── Conversation after the rewind point</Text>
634 </Box>
635 <Markdown text={clipToRows(list[index]?.text || '(no conversation)', previewRows, columns)} />
636 {footer(ui, note, '↑↓ to select · Enter to read all · Esc to close')}
637 </Box>
638 )
639}
640
641export const register: Register = on => {
642 on('session.start', async ($, e, next) => {
643 const started = await next(e)
644 await update($, isRunning, () => false)
645 await $.command.register({ name: 'better-rewind', description: DESCRIPTION, argumentHint: '[branches]' })
646 return started
647 })
648
649 on('command.run', { command: 'better-rewind' }, async ($, e) => (e.args.trim() === 'branches' ? openBranches($) : openPoints($)))
650
651 // 組み込みの /rewind (と別名) を置き換える。next を呼ばないので組み込みの画面は開かない。開けなかったときは組み込みに任せる
652 on('command.run', { command: 'rewind' }, $ => openPoints($)).catch(($, e, next) => (next.called ? { text: 'better-rewind could not open its list' } : next(e)))
653 on('command.describe', { command: 'rewind' }, ($, e, next) => next({ ...e, description: `${DESCRIPTION} (better-rewind)` })).catch(($, e, next) => next(e))
654
655 on('ui.close', async ($, e, next) => {
656 if (e.id === PANE) {
657 await update($, isOpen, () => false)
658 await update($, view, () => 'points')
659 }
660 return next(e)
661 }).catch(($, e, next) => next(e))
662
663 // AI が応答している間は巻き戻しを断る (記録へ書き足している最中に切ると壊れる)
664 on('turn.start', async ($, e, next) => {
665 await update($, isRunning, () => true)
666 return next(e)
667 }).catch(($, e, next) => next(e))
668
669 // 応答が終わったら断るのをやめ、開いているペインは地点を読み直す (戻し方・回答・要約の段階でも、
670 // 要約の頼みで同じ本文の発言を後ろから数えるのに新しい一覧を使う)
671 on('turn.complete', async ($, e, next) => {
672 const done = await next(e)
673 if (e.agentId === undefined) {
674 await update($, isRunning, () => false)
675 const v = await read($, view)
676 if ((await read($, isOpen)) && v !== 'branches' && v !== 'branch') await loadPoints($)
677 }
678 return done
679 })
680
681 // ペインから頼んだ要約 (pending) だけを、地点の前後で分けて行う。ペインは /compact を動かすので trigger は manual
682 // (plugin も同じに扱う)。from は地点から後ろを、up_to は地点より前を core に要約させ、残す部分とつなぐ。
683 // 頼みの無い /compact・自動の要約・subagent の要約には手を付けずに通す
684 on('session.compact', async ($, e, next) => {
685 if ((e.trigger !== 'manual' && e.trigger !== 'plugin') || e.agentId !== undefined) return next(e)
686 const request = await read($, pending)
687 if (!request) return next(e)
688 // 頼み 1 つで分けるのは 1 回だけ。先に下ろして、後から来た要約を分けない
689 await update($, pending, () => null)
690 let result: Awaited<ReturnType<typeof next>>
691 try {
692 const split = splitForSummary(e.messages, request)
693 if ('skip' in split) result = { skip: split.skip }
694 else {
695 const done = await next({ ...e, messages: split.summarize })
696 result = done.skip !== undefined ? done : { ...done, messages: split.join(done.messages) }
697 }
698 } catch {
699 // 分ける途中や core の要約で失敗したら断る。next(e) に任せると、会話全体の要約か、要約した部分だけ (残す部分が消える) になる
700 result = { skip: SPLIT_FAILED }
701 }
702 await update($, outcome, () => (result.skip !== undefined ? { kind: 'skip' as const, reason: result.skip } : { kind: 'done' as const })).catch(() => undefined)
703 return result
704 })
705 // ここに来るのは頼みを下ろす前の失敗だけ。分けずにそのまま通す
706 .catch(($, e, next) => next(e))
707
708 // 書き換える直前のファイルを控える。控えに失敗してもツールは止めない (知らせて印を残す)。
709 // 控えは権限の確認より前に取るので、ツールの結果を見て、実行された呼び出しの控えだけを戻す対象にする
710 // (拒否・失敗した呼び出しの控えで、人が拒んだファイルを後から書き換えない)
711 on('tool.call', async ($, e, next) => {
712 const file = editedFile(e)
713 if (file === undefined) return next(e)
714 const taken: Taken | undefined = await snapshot($, e.tool_use_id, e.tool, file).catch((err: unknown) => snapFailed($, e.tool_use_id, e.tool, file, err))
715 const result = await next(e)
716 if (taken) await settleSnap($, taken, file, result.deny === undefined && result.isError !== true).catch((err: unknown) => log($, `could not record whether ${e.tool} ran on ${file}: ${String(err)}`))
717 return result
718 }).catch(($, e, next) => next(e))
719
720 // 矢印・Tab・クリックでフォーカスが動いたら、それをカーソルにする (一覧以外の段階では sub に)
721 on('ui.focus', async ($, e, next) => {
722 if (e.component === 'Pane' && e.requestId === PANE && e.element) {
723 const key = e.element
724 if ((await read($, view)) === 'points') await update($, cursor, () => (key === CURRENT ? null : key))
725 else await update($, sub, () => key)
726 }
727 return next(e)
728 }).catch(($, e, next) => next(e))
729
730 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
731 const ui = $.ui.resolve(e)
732 const { Box, Text, Button, Markdown } = ui
733 const rows = e.viewport?.rows ?? 24
734 const columns = e.viewport?.columns ?? 80
735 const v = await read($, view)
736 const p = await read($, picked)
737 if (v === 'modes' && p) return renderModes($, ui, p)
738 if (v === 'answer' && p) return renderAnswer($, ui, p)
739 if (v === 'summarize' && p) return renderSummarize($, ui, p)
740 if (v === 'branches' || v === 'branch') return renderBranches($, ui, rows, columns)
741
742 const list = await read($, points)
743 const note = await read($, status)
744 if (list.length === 0) return <Text dimColor>{note || 'No rewind points'}</Text>
745
746 // 一覧の並び: 地点 (畳んだツール呼び出しは 1 行) のあとに (現在)。カーソルが見えている行に無ければ (現在)
747 const all = listRows(list, await read($, expanded))
748 const at = await read($, cursor)
749 const found = at === null ? -1 : all.findIndex(r => r.key === at)
750 const index = found >= 0 ? found : all.length - 1
751 const selected = all[index]
752
753 const previewRows = Math.min(10, Math.max(3, Math.floor(rows * 0.3)))
754 const [start, end] = windowRows(all, index, Math.max(1, rows - FIXED_ROWS - previewRows))
755
756 const items = []
757 for (let i = start; i < end; i++) {
758 const r = all[i]
759 if (!r) continue
760 const isFocused = i === index
761 const p = r.kind === 'point' ? r.point : undefined
762 const c = p && r.kind === 'point' && r.depth < 2 ? changesParts(p.changes) : undefined
763 // 人の発言 (組み込みの rewind に出る項目) を上の階層に置き、その応答の中の質問は 1 段、ほかのツール呼び出しは 2 段字下げする
764 const depth = r.kind === 'point' ? r.depth : r.kind === 'group' ? 2 : 0
765 const label = r.kind === 'group' ? `${r.isOpen ? '▾' : '▸'} ${plural(r.tools.length, 'tool call')}` : p ? `${depth === 1 ? '● ' : ''}${p.label}` : '(current)'
766 items.push(
767 <Box key={`row:${r.key}`} flexDirection="column" marginTop={i > start ? rowGap(r) : 0} paddingLeft={depth * NEST}>
768 <Box flexDirection="row">
769 <Button key={r.key} plain label={isFocused ? '❯' : ' '} onPress={() => void (r.kind === 'group' ? toggleGroup($, r.key) : choose($, p))} />
770 <Text> </Text>
771 <Text color={isFocused ? 'suggestion' : undefined} dimColor={(r.kind === 'group' && !isFocused) || undefined} italic={r.kind === 'current' || undefined} wrap="truncate-end">
772 {label}
773 </Text>
774 </Box>
775 {c && (
776 <Text color="inactive" dimColor={!isFocused} wrap="truncate-end">
777 {' '}
778 {c.text}
779 {c.added && <Text color="success"> {c.added}</Text>}
780 {c.removed && <Text color="error"> {c.removed}</Text>}
781 </Text>
782 )}
783 </Box>,
784 )
785 }
786 // 下のプレビュー: 地点ならその後の返答、まとまりなら中のツール呼び出し
787 const preview =
788 selected?.kind === 'point' ? selected.point.reply || '(no reply)' : selected?.kind === 'group' ? selected.tools.map(t => `▸ ${t.label}`).join('\n') : 'This is the current state'
789 const isGroup = selected?.kind === 'group'
790
791 return (
792 <Box flexDirection="column">
793 <Text bold color="suggestion">
794 Better Rewind
795 </Text>
796 <Text>Restore the code and/or conversation to the point before…</Text>
797 <Box flexDirection="column" marginTop={1}>
798 {items}
799 </Box>
800 <Box marginTop={1}>
801 <Text dimColor>{isGroup ? '── Tool calls in this group' : "── Claude's reply from this point"}</Text>
802 </Box>
803 {/* AI の返答と同じ描き方 (見出し・強調・コード)。行数は元の文で見積もって切る */}
804 <Markdown text={clipToRows(preview, previewRows, columns)} />
805 <Box marginTop={1}>
806 <Text dimColor>{isGroup ? `↑↓ to select · Enter to ${selected?.kind === 'group' && selected.isOpen ? 'hide' : 'show'} tool calls · Esc to close` : '↑↓ to select · Enter to confirm · Esc to close'}</Text>
807 </Box>
808 </Box>
809 )
810 })
811}
812hooks/lib.ts 294 lines1import type { SessionMessage } from 'claude-code'
2
3import type { Branch, Direction, Mode, Point, RestorePlan, RewindResult, SummarizeOutcome, SummarizeRequest, Unfinished } from '../types'
4
5// 1 行に複数のツール呼び出しが乗ることがあるので、uuid に種類 (tool_use id) を足して一意にする
6export const pointKey = (p: Point) => `${p.uuid}:${p.toolUseId ?? p.kind}`
7
8// カーソルを中央に置いた表示範囲 [start, end)。端では詰める
9export function windowAround(index: number, total: number, size: number): [number, number] {
10 if (total <= size) return [0, total]
11 const start = Math.min(Math.max(0, index - Math.floor(size / 2)), total - size)
12 return [start, start + size]
13}
14
15// 端末での表示幅。全角 (CJK・全角記号) は 2 とみなす
16const charWidth = (ch: string) => ((ch.codePointAt(0) ?? 0) >= 0x1100 ? 2 : 1)
17export const cellWidth = (s: string) => [...s].reduce((n, ch) => n + charWidth(ch), 0)
18
19function sliceCells(s: string, cells: number): string {
20 let used = 0
21 let out = ''
22 for (const ch of s) {
23 if (used + charWidth(ch) > cells) break
24 out += ch
25 used += charWidth(ch)
26 }
27 return out
28}
29
30// 本文を幅で折り返したと見なして、rows 行に収まるところで切る
31export function clipToRows(text: string, rows: number, columns: number): string {
32 const width = Math.max(2, columns)
33 const out: string[] = []
34 let used = 0
35 for (const line of text.split('\n')) {
36 const need = Math.max(1, Math.ceil(cellWidth(line) / width))
37 if (used + need > rows) {
38 const room = rows - used
39 if (room > 0) out.push(`${sliceCells(line, room * width - 1)}…`)
40 else if (out.length > 0) out[out.length - 1] += '…'
41 break
42 }
43 out.push(line)
44 used += need
45 }
46 return out.join('\n')
47}
48
49// 2 行目の要約を組み込みの書き方で作る: 変更なし / 1 ファイルならその名前 / 複数なら件数。増減は 0 なら出さない
50export function changesParts(c: Point['changes']): { text: string; added: string; removed: string } {
51 const added = c.added > 0 ? `+${c.added}` : ''
52 const removed = c.removed > 0 ? `-${c.removed}` : ''
53 if (c.files.length === 0) return { text: 'No code changes', added: '', removed: '' }
54 const only = c.files[0]
55 const text = c.files.length === 1 && only ? (only.split(/[\\/]/).pop() ?? only) : `${c.files.length} files changed`
56 return { text, added, removed }
57}
58
59// 件数と名詞 (1 file / 2 files)
60export const plural = (n: number, noun: string) => `${n} ${noun}${n === 1 ? '' : 's'}`
61
62// Claude の応答中に断る文。巻き戻しと要約で言い分ける
63export const BUSY = 'Cannot rewind while Claude is responding. Try again when it finishes'
64export const BUSY_SUMMARIZE = 'Cannot summarize while Claude is responding. Try again when it finishes'
65
66// ファイルを見分けられる短い名前。ふつうはファイル名だけで、同じ名前が並ぶときは見分けられるまで親フォルダを
67// 前に足す (src/a.ts と test/a.ts)。区切りは / にそろえる
68export function shortNames(paths: readonly string[]): string[] {
69 const parts = paths.map(p => p.split(/[\\/]/).filter(Boolean))
70 return parts.map((ps, i) => {
71 for (let n = 1; n <= ps.length; n++) {
72 const tail = ps.slice(-n).join('/')
73 if (!parts.some((qs, j) => j !== i && qs.slice(-n).join('/') === tail)) return tail
74 }
75 return paths[i] ?? ''
76 })
77}
78
79// Restore code の確認画面に出す行: 何件のファイルをどう戻すか (地点より後の発言で変わったファイルも含む) と、戻さないファイル。
80// 件数は全部、名前は届いた分だけ (残りは「…and N more」)。戻すファイルと戻さないファイルを合わせて見分けられる名前にする
81export function restoreLines(r: RestorePlan): { lead: string; files: string[]; skipped: string | undefined } {
82 const lead =
83 r.total > 0
84 ? `Restore code puts back ${plural(r.total, 'file')} changed after this point, including by later prompts:`
85 : 'Restore code has nothing to put back from this point'
86 const shown = shortNames([...r.files.map(f => f.path), ...r.skipped])
87 const files = r.files.map((f, i) => (f.action === 'delete' ? `${shown[i]} (deleted: it did not exist at this point)` : (shown[i] ?? f.path)))
88 if (r.total > r.files.length) files.push(`…and ${r.total - r.files.length} more`)
89 const names = shown.slice(r.files.length).join(', ') + (r.skippedTotal > r.skipped.length ? ` and ${r.skippedTotal - r.skipped.length} more` : '')
90 const skipped = r.skippedTotal > 0 ? `Not restored, because no backup could be taken before an edit: ${names}` : undefined
91 return { lead, files, skipped }
92}
93
94// 途中で打ち切られた巻き戻しの知らせ (次に一覧を開いたとき 1 度だけ)
95export function unfinishedMessage(list: readonly Unfinished[]): string | undefined {
96 const u = list[0]
97 if (!u) return undefined
98 const more = list.length > 1 ? ` (and ${list.length - 1} more)` : ''
99 const files = u.files.length > 0 ? ` ${shortNames(u.files).join(', ')} may be only partly restored; their contents from before the rewind are in ${u.saved} (${u.details} lists which file is which)` : ''
100 return `A rewind to "${u.label}" was stopped before it finished${more}.${files}`
101}
102
103// 回答を選び直せる地点か (AskUserQuestion で質問が読める)
104export const isAsk = (p: Point) => p.tool === 'AskUserQuestion' && (p.questions?.length ?? 0) > 0
105
106// ---- 一覧の行 ----
107
108// 一覧の最後の「(現在)」の key。選ぶと巻き戻さずに閉じる
109export const CURRENT = 'current'
110
111// 一覧の 1 行。人の発言と質問は地点の行。ほかのツール呼び出しは、続けて並ぶものを 1 つのまとまり (group) に畳み、
112// 開いたまとまりは自分の下に地点の行として並べる。depth は字下げの段 (人の発言 0・質問 1・ほかのツール呼び出し 2)
113export type Row =
114 | { kind: 'point'; key: string; point: Point; depth: number }
115 | { kind: 'group'; key: string; tools: Point[]; isOpen: boolean }
116 | { kind: 'current'; key: string }
117
118export const depthOf = (p: Point) => (p.kind === 'prompt' ? 0 : isAsk(p) ? 1 : 2)
119
120// まとまりの key は先頭の呼び出しで決める (一覧を読み直しても、先頭が同じなら開いたまま)
121export const groupKey = (first: Point) => `tools:${pointKey(first)}`
122
123export function listRows(list: readonly Point[], expanded: readonly string[]): Row[] {
124 const rows: Row[] = []
125 for (let i = 0; i < list.length; ) {
126 const p = list[i] as Point
127 if (depthOf(p) < 2) {
128 rows.push({ kind: 'point', key: pointKey(p), point: p, depth: depthOf(p) })
129 i++
130 continue
131 }
132 let j = i
133 while (j < list.length && depthOf(list[j] as Point) === 2) j++
134 const tools = list.slice(i, j)
135 const key = groupKey(p)
136 const isOpen = expanded.includes(key)
137 rows.push({ kind: 'group', key, tools, isOpen })
138 if (isOpen) for (const t of tools) rows.push({ kind: 'point', key: pointKey(t), point: t, depth: 2 })
139 i = j
140 }
141 rows.push({ kind: 'current', key: CURRENT })
142 return rows
143}
144
145// 行の高さ: 人の発言と質問は 2 行 (内容と変わったファイル)、ツール呼び出しとまとまりは 1 行
146export const rowLines = (r: Row) => (r.kind === 'point' && r.depth < 2 ? 2 : 1)
147// 行の上の空き: ツール呼び出しとまとまりは上の行に付けて詰める。ほかは 1 行空ける (組み込みと同じ間隔)
148export const rowGap = (r: Row) => (r.kind === 'group' || (r.kind === 'point' && r.depth === 2) ? 0 : 1)
149
150// カーソルの行から上下に交互に広げて、lines 行に収まる表示範囲 [start, end)。先頭の行の上の空きは描かないので数えない
151export function windowRows(rows: readonly Row[], index: number, lines: number): [number, number] {
152 const at = (i: number) => rows[i] as Row
153 let start = index
154 let end = index + 1
155 let used = rowLines(at(index))
156 for (let grew = true; grew; ) {
157 grew = false
158 if (end < rows.length && used + rowGap(at(end)) + rowLines(at(end)) <= lines) {
159 used += rowGap(at(end)) + rowLines(at(end))
160 end++
161 grew = true
162 }
163 // 上に足すと、それまで先頭だった行の上の空きも描かれる
164 if (start > 0 && used + rowLines(at(start - 1)) + rowGap(at(start)) <= lines) {
165 used += rowLines(at(start - 1)) + rowGap(at(start))
166 start--
167 grew = true
168 }
169 }
170 return [start, end]
171}
172
173// 戻し方の選択肢の key。要約の 2 つは組み込みの値に合わせる
174export type OptionKey = Mode | 'summarize' | 'summarize_up_to' | 'cancel'
175
176// 戻し方の選択肢。並びは組み込みと同じく 戻す → 要約 → やめる。会話を戻せない地点・控えの無い地点では、その選択肢を出さない。
177// AskUserQuestion の地点で会話を戻すときは、質問の直後に戻して回答を選び直す。
178// 要約は記録の中で位置を探せる地点だけ。「ここまでを要約」は前に要約するものがある地点 (一覧の先頭でない) だけ
179export function modeOptions(p: Point, list: readonly Point[]): { key: OptionKey; label: string }[] {
180 const ask = isAsk(p)
181 const out: { key: OptionKey; label: string }[] = []
182 if (p.canCut && p.restorable) out.push({ key: 'both', label: ask ? 'Restore code and conversation, then re-answer' : 'Restore code and conversation' })
183 if (p.canCut) out.push({ key: 'conversation', label: ask ? 'Restore conversation, then re-answer' : 'Restore conversation' })
184 if (p.restorable) out.push({ key: 'files', label: 'Restore code' })
185 if (canSummarize(p)) {
186 out.push({ key: 'summarize', label: 'Summarize from here' })
187 if (list.findIndex(q => pointKey(q) === pointKey(p)) > 0) out.push({ key: 'summarize_up_to', label: 'Summarize up to here' })
188 }
189 out.push({ key: 'cancel', label: 'Never mind' })
190 return out
191}
192
193// ---- 要約 ----
194
195// 人の発言を見比べる形。貼り付けの囲みを外して空白をすべて除く (記録の本文と SessionMessage の text で区切りの書き方が違ってもそろう)
196const promptKey = (s: string) => s.replace(/<pasted_content[^>]*>([\s\S]*?)<\/pasted_content[^>]*>/g, '$1').replace(/\s+/g, '')
197
198// 要約できる地点か。質問の地点は tool_use id で、人の発言は本文で e.messages の中の位置を探す
199// (コマンドと長すぎる発言は本文を持たないので探せない)
200export const canSummarize = (p: Point) => (p.kind === 'tool' ? p.toolUseId !== undefined : promptKey(p.text ?? '') !== '')
201
202// 地点 p への要約の頼み。同じ本文の発言は、一覧で p より後ろにいくつあるか (fromEnd) で区別する。
203// 前から数えないのは、要約済みの会話では e.messages が前の方を欠くため (後ろはどちらも今の会話の先端でそろう)
204export function summarizeRequest(p: Point, list: readonly Point[], direction: Direction): SummarizeRequest | undefined {
205 if (!canSummarize(p)) return undefined
206 if (p.kind === 'tool') return { direction, toolUseId: p.toolUseId, fromEnd: 0 }
207 const at = list.findIndex(q => pointKey(q) === pointKey(p))
208 if (at < 0) return undefined
209 const key = promptKey(p.text ?? '')
210 const fromEnd = list.slice(at + 1).filter(q => q.kind === 'prompt' && promptKey(q.text ?? '') === key).length
211 return { direction, text: p.text, fromEnd }
212}
213
214type Message = Pick<SessionMessage, 'role' | 'text' | 'toolUses' | 'toolResults'>
215
216const NOT_FOUND = 'Could not find this point in the conversation (it may already be summarized). Nothing was changed'
217
218// 地点が e.messages の何番目かを探す。見つからない・1 つに決まらないときは推測せず、要約を断る理由を返す。
219// 人の発言は本文が同じものの後ろから fromEnd 番目。同じ本文が無いときに限り、本文で始まるメッセージが 1 つだけならそれを使う
220// (エンジンが発言に何かを付けて 1 つのメッセージにしている場合)
221export function locatePoint(messages: readonly Message[], r: SummarizeRequest): { index: number } | { skip: string } {
222 const hits = (match: (m: Message) => boolean) => messages.flatMap((m, i) => (match(m) ? [i] : []))
223 if (r.toolUseId !== undefined) {
224 const found = hits(m => m.role === 'assistant' && m.toolUses.some(u => u.tool_use_id === r.toolUseId))
225 if (found.length > 1) return { skip: 'This point matches more than one message in the conversation. Nothing was changed' }
226 return found[0] === undefined ? { skip: NOT_FOUND } : { index: found[0] }
227 }
228 const key = promptKey(r.text ?? '')
229 if (key === '') return { skip: NOT_FOUND }
230 const isPrompt = (m: Message) => m.role === 'user' && (m.toolResults?.length ?? 0) === 0
231 const same = hits(m => isPrompt(m) && promptKey(m.text) === key)
232 if (same.length > 0) {
233 const index = same[same.length - 1 - r.fromEnd]
234 return index === undefined ? { skip: NOT_FOUND } : { index }
235 }
236 const starts = hits(m => isPrompt(m) && promptKey(m.text).startsWith(key))
237 return starts.length === 1 && r.fromEnd === 0 && starts[0] !== undefined ? { index: starts[0] } : { skip: NOT_FOUND }
238}
239
240// 要約に回す部分と残す部分に分ける。from は地点から後ろを、up_to は地点より前を要約する。
241// join は要約の結果 (core が返すメッセージ) を残す部分とつないで、要約した後の会話にする
242export function splitForSummary<M extends Message>(messages: readonly M[], r: SummarizeRequest): { summarize: M[]; join: (summary: readonly M[]) => M[] } | { skip: string } {
243 const at = locatePoint(messages, r)
244 if ('skip' in at) return at
245 const before = messages.slice(0, at.index)
246 const after = messages.slice(at.index)
247 if (r.direction === 'from') return { summarize: after, join: summary => [...before, ...summary] }
248 if (before.length === 0) return { skip: 'There is nothing before this point to summarize' }
249 return { summarize: before, join: summary => [...summary, ...after] }
250}
251
252// /compact を通して要約を頼み終えたときの一言。hook が分けた・断った・(結末が無く) hook まで届かなかったで分ける
253export function summarizedMessage(direction: Direction, outcome: SummarizeOutcome | null): string {
254 if (outcome?.kind === 'done') return direction === 'from' ? 'Summarized from here' : 'Summarized up to here'
255 if (outcome?.kind === 'skip') return `Not summarized: ${outcome.reason}`
256 // hook まで届かなかった: 地点で分けずに、会話全体が要約されたかもしれない
257 return 'Could not summarize from this point: the summary did not go through better-rewind, so it may have covered the whole conversation. Scroll up to check it'
258}
259
260// 巻き戻しを終えたときの一言
261export function doneMessage(mode: Mode, r: Pick<RewindResult, 'restored' | 'removed'> & Partial<Pick<RewindResult, 'skipped'>>): string {
262 const parts = [mode === 'files' ? 'Code restored' : 'Rewound']
263 if (mode !== 'conversation') parts.push(plural(r.restored.length + r.removed.length, 'file'))
264 const skipped = r.skipped ?? []
265 if (skipped.length > 0) parts.push(`not restored (no backup): ${shortNames(skipped).join(', ')}`)
266 if (mode !== 'files') parts.push('see the previous conversation with /better-rewind branches')
267 return parts.join(' · ')
268}
269
270// 枝の一覧の 1 行目 (いつ・どの地点で) と 2 行目 (どう戻したか)
271export function branchLines(b: Branch): { title: string; detail: string } {
272 const d = new Date(b.at)
273 const pad = (n: number) => String(n).padStart(2, '0')
274 const when = Number.isNaN(d.getTime()) ? b.at : `${d.getMonth() + 1}/${d.getDate()} ${pad(d.getHours())}:${pad(d.getMinutes())}`
275 const how = b.answered ? 'Answer changed' : b.mode === 'both' ? 'Code and conversation restored' : 'Conversation restored'
276 return { title: `${when} ${b.label}`, detail: how }
277}
278
279// Edit / Write / NotebookEdit が書き換えるファイル。それ以外のツールは undefined
280export function editedFile(e: { tool: string }): string | undefined {
281 const args = e as { tool: string; file_path?: unknown; notebook_path?: unknown }
282 const file = e.tool === 'NotebookEdit' ? args.notebook_path : e.tool === 'Edit' || e.tool === 'Write' ? args.file_path : undefined
283 return typeof file === 'string' && file !== '' ? file : undefined
284}
285
286// $.fs が「無い」(ENOENT) と断ったか。読み取り権限が無いなどの失敗とは分ける
287export function isMissing(err: unknown): boolean {
288 const e = err as { code?: unknown; message?: unknown } | null | undefined
289 return e?.code === 'ENOENT' || /\bENOENT\b/.test(String(e?.message ?? err))
290}
291
292// 控えのファイル名。bin/transcript.mjs の snapName と同じ規則
293export const snapName = (id: string) => id.replace(/[^\w-]/g, '_')
294types/index.d.ts 154 lines1// AskUserQuestion の質問 1 つ (ツールの入力のまま)
2export type Question = {
3 question: string
4 header?: string
5 multiSelect?: boolean
6 options?: { label: string; description?: string }[]
7}
8
9// 巻き戻し地点。bin/transcript.mjs の points() が返す形
10export type Point = {
11 uuid: string
12 // 人の発言 (prompt) かツール呼び出し (tool。AskUserQuestion の質問を含む)。並列の呼び出しは最初の 1 つだけ
13 kind: 'prompt' | 'tool'
14 label: string
15 reply: string
16 tool?: string
17 toolUseId?: string
18 resultUuid?: string
19 // 人の発言の本文。巻き戻した後に入力欄へ戻す (コマンドと長すぎる発言では無い)
20 text?: string
21 // AskUserQuestion の地点の質問
22 questions?: Question[]
23 // その地点から次の人の発言までに Edit/Write で変わったファイル (絶対パス) と増減の行数
24 changes: { files: string[]; added: number; removed: number }
25 // 会話を戻せるか (最初の発言の前や、切ると記録が壊れる地点は false)
26 canCut: boolean
27 // 戻せるファイルの控えがあるか (restore.total > 0)
28 restorable: boolean
29 // Restore code が戻すファイル。rewind と同じ計画 (fileRestorePlan) で、地点より後の発言で変わったファイルも含む
30 restore: RestorePlan
31}
32
33// Restore code が戻すファイルの要約。files と skipped は先頭の数件だけ (件数は total と skippedTotal)。
34// total と files は実際に書く・消すファイルだけ (地点の時点で無く、今も無いファイルは消すものが無いので数えない)
35export type RestorePlan = {
36 total: number
37 // write は控えの中身に戻す、delete は地点の時点で無かったので消す
38 files: { path: string; action: 'write' | 'delete' }[]
39 // 編集の直前に控えを取れなかった (か、実行されたか分からない) ので戻さないファイル
40 skippedTotal: number
41 skipped: string[]
42}
43
44// 途中で打ち切られた巻き戻し。bin/transcript.mjs の unfinished() が返す形 (points と一緒に届く)
45export type Unfinished = {
46 id: string
47 at: string
48 label: string
49 // 戻そうとしていたファイル
50 files: string[]
51 // 戻す前の中身を退避したフォルダと、どのファイルかを書いた情報ファイル
52 saved: string
53 details: string
54}
55
56// ファイルの控えの情報 (snaps/<tool_use id>.json)。state は bin/transcript.mjs の「ファイルの控え」の説明を参照
57// (拒否・失敗の結果でもファイルが変わっていれば 'ran')
58export type Snap = {
59 toolUseId: string
60 tool: string
61 path: string
62 at: number
63 existed: boolean
64 data?: string
65 state: 'pending' | 'ran' | 'denied'
66 // 控えを取ろうとして失敗した印 (中身は無い)
67 failed?: true
68}
69
70// 戻し方: 会話とファイル / 会話だけ / ファイルだけ
71export type Mode = 'both' | 'conversation' | 'files'
72
73// 要約の向き (組み込みの summarizeMetadata.direction と同じ値): 地点から後ろを要約する / 地点より前を要約する
74export type Direction = 'from' | 'up_to'
75
76// 要約の頼み。session.compact の hook が e.messages の中で地点を探す手がかり (SessionMessage には uuid が無い)。
77// 質問の地点は toolUseId、人の発言は本文 (text) と、同じ本文の発言のうち後ろから何番目か (fromEnd)
78export type SummarizeRequest = {
79 direction: Direction
80 toolUseId?: string
81 text?: string
82 fromEnd: number
83}
84
85// ペインから頼んだ要約の結末。session.compact の hook が記録し、要約を頼んだ側が読んで知らせる。
86// done は地点の前後で分けて要約した、skip は分けずに断った (reason はその理由)
87export type SummarizeOutcome = { kind: 'done' } | { kind: 'skip'; reason: string }
88
89// ペインの段階: 地点の一覧 → 戻し方 → (AskUserQuestion なら) 回答 / (要約なら) 添える指示。枝の一覧 → 枝の全文
90export type View = 'points' | 'modes' | 'answer' | 'summarize' | 'branches' | 'branch'
91
92// 巻き戻す前の会話 (枝)。bin/transcript.mjs の branches() が返す形
93export type Branch = {
94 id: string
95 at: string
96 label: string
97 mode: Mode
98 answered: boolean
99 // 切った地点より後ろの会話 (読むだけ)
100 text: string
101}
102
103// bin/transcript.mjs の rewind() が返す形
104export type RewindResult = {
105 id: string
106 mode: Mode
107 leaf?: string
108 dropped: number
109 restored: string[]
110 removed: string[]
111 // 控えが取れていないので戻さなかったファイル
112 skipped: string[]
113 // 記録を書き換えたか (会話を戻したとき true)。helper は記録の rename を最後の書き換えに置くので、ふつうの失敗では
114 // error と false を返す (記録は書き換えていない)。戻し終えた後で終わった印を書けなかったときだけ、error と一緒に
115 // 戻した結果 (restored・removed など) と、会話を戻したなら true を返す。mod は true なら読み直してから失敗を知らせる
116 transcriptChanged: boolean
117}
118
119declare module 'claude-code' {
120 interface PluginState {
121 'better-rewind': {
122 points: Point[]
123 // カーソルのある行の key (地点は pointKey、畳んだツール呼び出しの行は groupKey)。null は一覧の最後の (現在)
124 cursor: string | null
125 // 開いているツール呼び出しのまとまり (groupKey)。ペインを開くたびに空 (すべて畳む) に戻す
126 expanded: string[]
127 // 読み込み中・失敗の一言。空なら表示しない
128 status: string
129 view: View
130 // 戻し方・回答の段階で選んでいる地点
131 picked: Point | null
132 // 回答の段階に進んだときの戻し方
133 mode: Mode | null
134 // AskUserQuestion の質問ごとに選んだ回答 (先頭から)
135 answers: string[]
136 // 要約の段階に進んだときの向き
137 direction: Direction | null
138 // ペインから頼んだ要約。/compact を動かす間だけ立て、hook が最初の 1 回で下ろす (立っていない要約は hook が素通しする)
139 pending: SummarizeRequest | null
140 // pending を下ろした hook がどうしたか。/compact の前に null に戻す (null のままなら hook は動かなかった)
141 outcome: SummarizeOutcome | null
142 // 一覧以外の段階でフォーカスのある要素の key
143 sub: string | null
144 branches: Branch[]
145 // 全文を開いている枝の id
146 opened: string | null
147 // ペインが開いているか
148 isOpen: boolean
149 // AI が応答している最中か (turn.start から turn.complete まで)
150 isRunning: boolean
151 }
152 }
153}
154