A whiteboard Claude writes to: titled Markdown cards (steps, running jobs, links) that stay put instead of scrolling away in the chat

Claude が書き込む作業ボードです。手順、動かしている処理、URL、決めたことなど、チャットで流れてしまう情報を、カードにして画面の右に残します。「さっき言っていた手順をもう一回」と聞き直す手間と、そのためのトークンを減らします。
インストール方法は、リポジトリの README を見てください。
Claude に頼みます。
ボードに今日の作業手順を書いて
ボードに今開いているプレビューの URL を残して
ボードの手順 3 は?
ボードの手順 3 を済みにして
ボードのあれを消して
ボードを整理して
頼まなくても、Claude が自分でボードに書くことがあります。カードの書き換えにボタンはありません。
ボードには名前があり、セッションとは別に保存されます。アプリを閉じても、セッションを新しくしても残ります。新しいセッションはどのボードにもつながっていないので、最初にボードを選びます(下の「ボードを選ぶ」)。
入力欄の上の帯に「ホワイトボード 3件」と [開く] が出ます。押すと右にパネルが開き、いちばん上にボードの名前が見出しで出て、その下にカードが追加した順に並びます。いちばん下に [別のボードへ] [名前を変える] [読み直す] が並びます。/whiteboard でも開けます。カードごとに、タイトル、その下に最後に書いた時刻、本文が出ます。
時刻の行には、カードの今の様子が付きます。
- [ ] / - [x] のチェックリストがあると「3/5」のように進み具合が出て、全部済むと「済」が付きますstaleHours)書き換えていないと「古い」と付いて、題が薄くなります。勝手には消えません長いカードは畳まれて出て、[続きを表示] で開けます。固定したカードと、最後の依頼のあとで Claude が書き換えたカードは開いたまま出ます。
カードが 6 枚以上あると、一覧の上に入力欄が出ます。打った語でカードを絞り込めます(空白で区切ると、すべてを含むもの)。パネルを開き直すと解けます。
カードが 3 枚以上あると、件数の横に [並び: 追加順] が出ます。押すと最後に書き換えた順に並び替わり、もう一度押すと戻ります(固定したカードは上のまま)。
常に見ていたいカード(今の手順の全体像、URL の一覧など)は、Claude に頼んで「固定」にできます。固定したカードは上に並びます。
帯には、件数のほかに「更新 2枚」「古い 2枚」と、いちばん最近書き換えた固定カードの題(「ホワイトボード 3件 · 朝の確認リスト 2/5」)が出ます。パネルを開かなくても今の要点が分かります。幅が足りないときは、題から省きます。
「deploy のカードは青で」のように頼むと、カードの枠(太い線になります)と見出しに色が付きます。色は red、orange、yellow、green、blue、purple、gray の 7 つで、none で外せます。色に決まった意味はありません。意味を決めたいときは、会話で Claude に伝えてください(「止まっている作業は赤にして」など)。
既定の色はテーマに合わせて変わります。見分けにくい色があれば、設定 colors で好きな色に割り当て直せます。
色だけでは見分けにくいときは、設定 styleMarks をオンにすると、見出しと帯の題の前に色の名前ごとの印(red ●、orange ▲、yellow ◆、green ■、blue ★、purple ✚、gray ○)が付きます(印は色の名前で決まり、colors で色を変えても変わりません)。
本文は Markdown です(見出し、箇条書き、リンク、コード、表)。
`mermaid の囲みに、基本的な flowchart / graph と sequenceDiagram を書くと、パネルで図になります。subgraph は枠で囲んで描きますが、subgraph そのものに矢印を引いた図は描きません。描けない書き方は、コードブロックのまま表示されます。ターミナルでは、いつもコードブロックです。
ボードにつながっていないセッションでは、帯に「ホワイトボード · ボードを選ぶ」と出ます。パネルを開くと、このプロジェクトのボードが新しい順に並びます。各ボードには、名前と最後に書いた時刻、最後に書いたセッション(そのセッションで最初に入力した依頼)、カードのタイトル(固定したものが先、チェックリストの進み具合つき)が出ます。[つなぐ] を押すと、そのボードのカードが出て、Claude もそのボードに書きます。[中身を見る] で、全部のカードのタイトルを見られます。ほかのプロジェクトのボードと古いボードは、畳まれた行の [表示] で出ます。
Claude に頼んでもつなげます。
whiteboard 開発のボードを使って
CI の修正のボードを作って
同じ名前のボードがあればそれにつながり、なければその名前で作ります。セッションを入れ替えるときは、引き継ぎの文に「◯◯のボードを使って」と書いておけば、新しいセッションの Claude が自分でつなぎます。
Claude は次のツール(mcp__whiteboard__ で始まります)でボードを操作します。初めて使うときに、許可を求められることがあります。
| ツール | 入力 | 内容 |
|---|---|---|
set_card | id, title, body, pin と style(省略できる) | カードを追加する。同じ id があれば上書きする。pin で固定する・外す。style で色を付ける・外す |
edit_card | id, find, replace, all, style(id 以外は省略できる) | 本文の一部だけを置き換える。find は本文の中で 1 箇所にだけ一致する長さにする(all: true なら全部)。id と style だけなら色だけを変える |
append_card | id, text | 本文の末尾に足す |
remove_card | id | カードを 1 枚消す |
clear | なし | カードを全部消す |
list_cards | なし、または titles_only / id / query / since | ボードを読む。引数なしは全文。titles_only は目次、id はそのカード 1 枚、query は語で探す、since は前に読んだ版から変わったカードだけ |
undo_card | id | カードの最後の書き換えを 1 つ戻す(もう一度でやり直し)。最近消した 5 枚までは、消したカードも戻せる |
open_board | name | その名前のボードにつなぐ。なければ作ってつなぐ |
list_boards | なし、または all | ボードの一覧を読む。all でほかのプロジェクトのボードと古いボードも |
rename_board | name | つないでいるボードの名前を変える |
カードのツールは、ボードにつながっていないと断られます。Claude は先に open_board でつなぎます。
ボードの内容を聞かれたときは、まず titles_only か query で探し、必要なカードだけ id で読みます。会話が圧縮されたときは、圧縮の後の最初の入力と一緒に、つないでいるボードのカードの id とタイトルの一覧を Claude に渡すので、Claude はボードのことを忘れずに続けられます(一覧は画面には出ません)。このプラグインには、使い方を Claude に教えるスキル whiteboard-guide も入っています。
whiteboard のプラグインの設定で変えます。
| 設定 | 既定 | 内容 |
|---|---|---|
guide | off | 新しいセッションの Claude に、ボードがあることを伝える。short: 会話の最初の入力と一緒に、毎回同じ短い文(約 150 文字)を Claude に渡す。/clear や圧縮で会話から消えたら、次の入力でもう一度渡す。full: short に加えて、入力に guideKeywords の語が含まれるときだけ、ツールの使い分けの要点を渡す(5 ターンに 1 回まで)。どちらも入力そのものは変えず、画面にも出ない |
guideKeywords | ボード,whiteboard | full のきっかけの語(カンマ区切り) |
colors | 空 | カードの色の割り当て。red=#D55E00, green=#009E73, blue=suggestion のように、色の名前ごとにテーマの色名か #rgb / #rrggbb を書く。書けていない項目は無視され、既定の色のまま |
styleMarks | オフ | 色の付いたカードの見出しと帯の題の前に、色の名前ごとに形の違う小さな印を付ける |
bandTitle | オン | 帯に、いちばん最近書き換えた固定カードの題(チェックリストがあれば進み具合も)を出す |
staleHours | 3 | 固定していないカードを、この時間(時間単位)より長く書き換えていないと「古い」と示す。0 で示さない |
maxCards | 20 | 1 つのボードに置けるカードの枚数の上限(5〜40)。範囲の外は 5 か 40 に、数でなければ 20 になる。多くすると、パネルが長くなり、保存も大きくなる。減らしても、すでにあるカードは消えず、上限より多い間はカードを足せない |
| 項目 | 上限 |
|---|---|
| カードの枚数 | 20 枚(設定 maxCards で 5〜40) |
| タイトル | 60 文字 |
| 本文 | 4000 文字 |
| id | 40 文字(英数字と _ -) |
超えると Claude にエラーが返り、Claude が短くするか、済んだカードを消してからやり直します。
Claude Code v2.1.289 から v2.1.306 のデスクトップアプリ(Code タブ)で動作を確認しています。
hooks/register.js 996 lines1// A whiteboard Claude writes to: titled Markdown cards (steps, running jobs, links) that stay put instead of scrolling away in the chat
2//
3// register.js every hook and every $ call: the tool calls, the boards' load and save, attaching a
4// session to a board, the move of 0.10.0's boards, the pane and the band, /whiteboard
5// tools.js the tools Claude calls: the seven card tools (set_card, edit_card, append_card,
6// remove_card, clear, list_cards, undo_card), what each is told, its input, and what it
7// does to the cards; the three board tools (open_board, list_boards, rename_board) (pure)
8// board.js the limits, what each card tool does to the cards and answers, the band's fit (pure)
9// boards.js the named boards: the keys, the meta, the root's hash, the list's groups (pure)
10// migrate.js what becomes of a board of 0.10.0 and before (pure)
11// shelf.js the store's keys turned into the list of boards (pure)
12// catalog.js what Claude reads about the boards: the board tools' answers, the refusals (pure)
13// view-state.js the small state values read with their defaults (pure)
14// store.js the queue (pure)
15// mermaid.js the mermaid fences drawn as pictures (pure)
16// pane.js what the pane and the band draw (pure)
17// style.js a card's style: the names Claude may give, the palette and the setting `colors` (pure)
18// guide.js the fixed text that tells a new session the board exists, and when to repeat the tool lines (pure)
19// recent.js the person's turns and the cards changed in the latest one, with their line counts (pure)
20// fold.js long cards folded in the pane, and the person's fold choices (pure)
21// search.js the pane's search field: the cards narrowed by words typed, the view only (pure)
22// order.js the pane's order: as added, or the latest write first, the view only (pure)
23// stale.js the cards not written for a while (the setting `staleHours`), pointed out, never removed (pure)
24// press-guard.js runs a pane press again that did not reach its Button (pure)
25//
26// A board belongs to no session (boards.js): `b:<boardId>` holds its record (the cards with the
27// board's revision and the cards removed lately, which undo_card brings back; board.js), written in
28// one store write, and `bm:<boardId>` its name, project, times, count and the title of the session
29// that wrote it last. `attach:<sessionId>` says which board a session is attached to; a new session
30// is attached to none, and the card tools refuse until Claude attaches it (open_board) or the person
31// does ([つなぐ] in the pane). Several sessions may be attached to one board. So the boards outlive
32// the app and the session: the same session opened again is still attached, and any session may
33// attach to a board by its name. The store is written first; a write it refuses (a store over its
34// size limit) leaves the board as it was and the tool answers an error.
35//
36// The rule for the cards: the store is the truth and $.state is a copy for the drawings. What is
37// read to be written over (the tools, an attach) is read from the store, inside `exclusive`. It is
38// never read from $.state: one dispatch (a tool call, a press) reads $.state as it stood at its
39// first read and keeps that. The state's `owner` and `attached` say whose cards `cards` holds (after
40// /clear the process goes on under another session id), and the drawings do not take cards of
41// another owner. Another session attached to the same board writes the store only, so this
42// session's drawings show its writes at this session's next read (a tool call, the pane opened);
43// and a write reads the board's revision again just before it saves, refusing when another session
44// wrote in between.
45//
46// The engine follows $ into the functions of the file it is in and never across an import (validate
47// refuses $ passed to an imported function), so everything that takes $ is here; the other modules
48// are pure.
49
50import {
51 LIMITS,
52 maxCardsOf,
53 isBoardRecord,
54 readBoard,
55 boardRecord,
56 stampRevs,
57 shownCards,
58 trackPrev,
59 removedAfter,
60 compactionNote,
61 bandCard,
62 BOARD_NAME,
63 clockOf,
64} from './board.js'
65import { boardKey, metaKey, attachKey, readMeta, mergeMeta, readAttach, rootOf, promptLine, isText, nameOf, newBoardId, findByName, nameTaken, NAME_LIMIT } from './boards.js'
66import { oldKeysOf, oldSessionsOf, planMove } from './migrate.js'
67import { isSame, isMine, isMetaKey, scanBoards, listSigOf } from './shelf.js'
68import { NOT_ATTACHED, CHANGED_MEANWHILE, listBoardsText, attachedText, alreadyText, renamedText, takenText } from './catalog.js'
69import { TOOLS, toolsFor, BOARD_TOOLS } from './tools.js'
70import { NO_VIEW, attachedOf, viewOf, boardsOf, rootValueOf, aboutOf } from './view-state.js'
71import { makeQueue } from './store.js'
72import { GUIDE_SHORT, guideModeOf, keywordsOf, makeGuideTurns, lookAfter, hasGuideIn } from './guide.js'
73import { PANE_ID, widthOf, drawPane, drawBand } from './pane.js'
74import { isPersonPrompt, readTurn, turnAfter, markWrite, shownMarks, marksOf, seedMarks, markedCount } from './recent.js'
75import { paletteOf, shapesOn } from './style.js'
76import { foldsOf, foldsAfter, foldsKept } from './fold.js'
77import { SEARCH_MIN, filterOf, filterAfter, filterCleared } from './search.js'
78import { orderOf, orderAfter } from './order.js'
79import { STALE_DEFAULT_HOURS, staleHoursOf, staleCount } from './stale.js'
80import { GRACE_MS, guardDrawing, beginPress, hasStarted, takeOver, endPress } from './press-guard.js'
81
82// The state this file writes (declared in types/index.d.ts)
83const CARDS = { plugin: 'whiteboard', key: 'cards' }
84const OWNER = { plugin: 'whiteboard', key: 'owner' }
85const ATTACHED = { plugin: 'whiteboard', key: 'attached' }
86const BOARDS = { plugin: 'whiteboard', key: 'boards' }
87const ROOT = { plugin: 'whiteboard', key: 'root' }
88const ABOUT = { plugin: 'whiteboard', key: 'about' }
89const VIEW = { plugin: 'whiteboard', key: 'view' }
90const TURN = { plugin: 'whiteboard', key: 'turn' }
91const RECENT = { plugin: 'whiteboard', key: 'recent' }
92const LOOK = { plugin: 'whiteboard', key: 'look' }
93
94// The cards and the attachments have a queue (the tools, an attach, the start's move and load);
95// the list of boards has one of its own, so a tool never waits on it; the small state values
96// (`view`) have a third
97const exclusive = makeQueue()
98const exclusiveBoards = makeQueue()
99const exclusiveState = makeQueue()
100
101const messageOf = (error) => String(error?.message ?? error)
102
103// The board a session is attached to when none is: no cards, no name
104const NONE = { board: null, name: '', stamp: 0 }
105
106// The `attached` state value for the board `att` ({ id, meta }, or null for none): with the meta's
107// time of the last write (`stamp`), which tells a read later whether anyone wrote the board since
108const attachedValue = (me, att) => (att === null ? { owner: me, ...NONE } : { owner: me, board: att.id, name: att.meta.name, stamp: att.meta.updatedAt })
109
110// ---- The root and what the session is about
111
112// The session root as this session first saw it ({ name, hash }), fixed in $.state: the app may
113// move the working folder (and with it the root) into a nested repository, which must not move the
114// boards to another project. Read once and kept; a drawing reads it with rootForDrawing.
115async function fixedRoot($) {
116 const me = await $.session.id()
117 const held = rootValueOf((await $.state.get(ROOT)).value, me)
118 if (held !== null) return held
119 const root = rootOf(await $.session.root())
120 await $.state.set(ROOT, { owner: me, ...root })
121 return root
122}
123
124// The same for a drawing, which may not write the state; null when it cannot be read
125async function rootForDrawing($) {
126 try {
127 const held = rootValueOf((await $.state.get(ROOT)).value, await $.session.id())
128 return held ?? rootOf(await $.session.root())
129 } catch {
130 return null
131 }
132}
133
134// The person's first request, kept in $.state (it outlives a hot reload there), from the first
135// prompt.submit of theirs that is not a slash command. The session's title is no longer taken:
136// the events that carried it (the classic SessionStart and UserPromptSubmit) are not passed to
137// installed mods everywhere, and no other event or $ call gives it. A title an earlier version
138// kept in the state is still used.
139async function noteAbout($, e) {
140 try {
141 if (e?.command !== undefined || !isText(e?.text)) return
142 const me = await $.session.id()
143 const about = aboutOf((await $.state.get(ABOUT)).value, me)
144 if (about.firstPrompt !== null) return
145 const firstPrompt = promptLine(e.text) || null
146 if (firstPrompt !== null) await $.state.set(ABOUT, { owner: me, title: about.title, firstPrompt })
147 } catch {}
148}
149
150// What the meta keeps of the session that wrote a board last: its title, else its first request
151// (in 「」), else the first thing the person typed as the transcript has it (a session the mod was
152// loaded into after its first prompt); null when none is known
153async function sessionTitle($, me) {
154 try {
155 const about = aboutOf((await $.state.get(ABOUT)).value, me)
156 if (about.title !== null) return about.title
157 if (about.firstPrompt !== null) return `「${about.firstPrompt}」`
158 const messages = await $.session.messages()
159 const first = Array.isArray(messages) ? messages.find((m) => m?.role === 'user' && isText(m.text) && !(Array.isArray(m.toolResults) && m.toolResults.length > 0)) : undefined
160 const line = first ? promptLine(first.text) : ''
161 if (line === '') return null
162 await $.state.set(ABOUT, { owner: me, title: null, firstPrompt: line })
163 return `「${line}」`
164 } catch {
165 return null
166 }
167}
168
169// ---- The boards in the store
170
171// The board `id` as the store has it, the truth (see the top of this file): { cards, rev, removed } (board.js readBoard)
172async function storedBoard($, id) {
173 return readBoard(await $.store.get(boardKey(id)))
174}
175
176// The board the session `me` is attached to, as the store has it: { id, meta }, or null when it is
177// attached to none (or to a board whose meta is gone)
178async function attachmentOf($, me) {
179 const att = readAttach(await $.store.get(attachKey(me)))
180 if (att === null) return null
181 const meta = readMeta(await $.store.get(metaKey(att.board)))
182 return meta === null ? null : { id: att.board, meta }
183}
184
185// Puts the cards of the board `att` ({ id, meta }, or null for none) into $.state for the drawings
186// ($.state holds the cards without `prev`), with whose they are
187async function showBoard($, me, att, cards) {
188 await $.state.set(CARDS, att === null ? [] : shownCards(cards))
189 await $.state.set(OWNER, me)
190 await $.state.set(ATTACHED, attachedValue(me, att))
191}
192
193// The board this session is attached to, from the store; $.state is brought in line when it
194// differs. { me, att, board } (att and board null when attached to none). Call it inside
195// `exclusive`, not from a press before it waits there.
196async function loadBoard($) {
197 const me = await $.session.id()
198 const att = await attachmentOf($, me)
199 const board = att === null ? null : await storedBoard($, att.id)
200 const shown = att === null ? [] : shownCards(board.cards)
201 const attached = attachedValue(me, att)
202 if (!isSame((await $.state.get(CARDS)).value, shown) || (await $.state.get(OWNER)).value !== me || !isSame((await $.state.get(ATTACHED)).value, attached)) {
203 await showBoard($, me, att, board?.cards ?? [])
204 }
205 return { me, att, board }
206}
207
208// Writes the board's record to the store (one write: the cards, the revision and the removed
209// cards together) and then the cards to $.state; the drawings read the state. An emptied board
210// keeps its record (board.js). The meta follows: the time, the count and the session that wrote
211// it; a meta the store refuses is let go (the list then shows the time before).
212async function saveBoard($, me, att, board) {
213 const record = boardRecord(board)
214 if (record === null) await $.store.delete(boardKey(att.id))
215 else await $.store.set(boardKey(att.id), record)
216 let meta = null
217 try {
218 const prev = readMeta(await $.store.get(metaKey(att.id))) ?? att.meta
219 const lastTitle = await sessionTitle($, me)
220 // The writer's id goes with its title (null when no title is known: another session's title is not kept for it)
221 const next = mergeMeta(prev, { updatedAt: await $.clock.now(), count: board.cards.length, lastTitle: lastTitle ?? null, lastSid: lastTitle === null ? null : me })
222 await $.store.set(metaKey(att.id), next)
223 meta = readMeta(next)
224 } catch {}
225 await $.state.set(CARDS, shownCards(board.cards))
226 await $.state.set(OWNER, me)
227 // This session's own write is no news to it at the next boundary (syncBoard)
228 if (meta !== null) await $.state.set(ATTACHED, attachedValue(me, { id: att.id, meta }))
229 await pruneView($, me, board.cards)
230}
231
232// After a write: the fold choices of cards no longer on the board are let go (fold.js foldsKept),
233// so a new card under a removed card's id does not take its choice; with fewer cards than bring
234// the search field, its filter is let go too (search.js), so it does not come back with the field.
235// A failure here never fails the write.
236async function pruneView($, id, cards) {
237 try {
238 await exclusiveState(async () => {
239 const read = await readView($)
240 let view = read
241 const folds = foldsKept(view.folds, id, cards.map((c) => c.id))
242 if (folds !== null) view = { ...view, folds }
243 if (cards.length < SEARCH_MIN) view = filterCleared(view)
244 if (view !== read) await setView($, view)
245 })
246 } catch {}
247}
248
249// Saves a write: `after`, what a tool made of `board`'s cards (the board as read in the same turn
250// of `exclusive`), with each card's previous version (trackPrev), the revisions stamped on
251// (stampRevs) and the removed cards brought in line (removedAfter: a card gone from the board joins
252// them, one back on the board leaves them). Answers the board's revision after it.
253async function commitBoard($, me, att, board, after) {
254 const stamped = stampRevs(board.cards, trackPrev(board.cards, after), board.rev)
255 const { removed } = removedAfter(board.removed, board.cards, stamped.cards)
256 await saveBoard($, me, att, { cards: stamped.cards, rev: stamped.rev, removed })
257 return stamped.rev
258}
259
260// The store's keys and the values under the mod's own, turned into the list (shelf.js scanBoards)
261async function scanStore($) {
262 const keys = await $.store.keys()
263 const values = new Map()
264 for (const key of keys) if (isMine(key)) values.set(key, await $.store.get(key))
265 return scanBoards(keys, values)
266}
267
268// ---- Attaching
269
270// Attaches the session `me` to the board `id` (it must have a meta): the store first, then the
271// state; a board that was old is used again, so it is not old any more. The view's choices on the
272// cards of the board before (folds, the filter) and this turn's marks are let go. Call it inside
273// `exclusive`. Answers { meta, board }.
274async function attachTo($, me, id) {
275 const meta = readMeta(await $.store.get(metaKey(id)))
276 if (meta === null) throw new Error(`その${BOARD_NAME}は、もうありません`)
277 await $.store.set(attachKey(me), { board: id, at: await $.clock.now() })
278 if (meta.old) await $.store.set(metaKey(id), mergeMeta(meta, { old: null }))
279 const board = await storedBoard($, id)
280 await showBoard($, me, { id, meta }, board.cards)
281 recentMarks = null
282 await $.state.set(RECENT, { owner: me, turn: 0, cards: {} })
283 await exclusiveState(async () => setView($, filterCleared({ ...(await readView($)), pick: '', shown: false, rename: false, folds: null })))
284 return { meta: { ...meta, old: false }, board }
285}
286
287// open_board: attaches to the board of that name (this project's first), or makes it
288async function openBoard($, e) {
289 const named = nameOf(e?.name)
290 if (named.error) return { deny: named.error }
291 try {
292 const text = await exclusive(async () => {
293 const me = await $.session.id()
294 const root = await fixedRoot($)
295 const { rows } = await scanStore($)
296 const found = findByName(rows, named.name, root.hash)
297 if (found !== null) {
298 const current = readAttach(await $.store.get(attachKey(me)))
299 if (current?.board === found.id) {
300 await loadBoard($)
301 return alreadyText(found)
302 }
303 await attachTo($, me, found.id)
304 return attachedText(found, { project: root.hash !== null && found.rootHash === root.hash })
305 }
306 const now = await $.clock.now()
307 const id = newBoardId(now, Math.random())
308 await $.store.set(metaKey(id), mergeMeta(null, { name: named.name, rootHash: root.hash, cwdName: root.name, createdAt: now, updatedAt: now, count: 0 }))
309 await attachTo($, me, id)
310 return attachedText({ name: named.name }, { created: true })
311 })
312 await refreshBoards($).catch(() => {})
313 return { result: text }
314 } catch (error) {
315 return { deny: `ボードにつなげませんでした: ${messageOf(error)}` }
316 }
317}
318
319// list_boards: the boards, read from the store; nothing is written but the root, once
320async function listBoards($, e) {
321 if (e?.all !== undefined && typeof e.all !== 'boolean') return { deny: 'all は true か false で指定してください' }
322 try {
323 const me = await $.session.id()
324 const root = await fixedRoot($)
325 const { rows } = await scanStore($)
326 const att = await attachmentOf($, me)
327 return { result: listBoardsText(rows, { rootHash: root.hash, cwdName: root.name, current: att?.id ?? null, all: e?.all === true }) }
328 } catch (error) {
329 return { deny: `ボードの一覧を読めませんでした: ${messageOf(error)}` }
330 }
331}
332
333// Gives the board this session is attached to the name `name` (checked already): { from, to },
334// { taken: true } when another board of its project has it, { unattached: true } with no board
335function renameAttached($, name) {
336 return exclusive(async () => {
337 const me = await $.session.id()
338 const att = await attachmentOf($, me)
339 if (att === null) return { unattached: true }
340 const root = await fixedRoot($)
341 const { rows } = await scanStore($)
342 if (nameTaken(rows, name, att.meta.rootHash ?? root.hash, att.id)) return { taken: true }
343 const meta = readMeta(await $.store.get(metaKey(att.id))) ?? att.meta
344 if (meta.name !== name) {
345 await $.store.set(metaKey(att.id), mergeMeta(meta, { name }))
346 await $.state.set(ATTACHED, { owner: me, board: att.id, name, stamp: meta.updatedAt })
347 }
348 return { from: meta.name, to: name }
349 })
350}
351
352// rename_board
353async function renameBoard($, e) {
354 const named = nameOf(e?.name)
355 if (named.error) return { deny: named.error }
356 try {
357 const out = await renameAttached($, named.name)
358 if (out.unattached) return { deny: NOT_ATTACHED }
359 if (out.taken) return { deny: takenText(named.name) }
360 await refreshBoards($).catch(() => {})
361 return { result: renamedText(out.from, out.to) }
362 } catch (error) {
363 return { deny: `ボードの名前を変えられませんでした: ${messageOf(error)}` }
364 }
365}
366
367// ---- Reading again at the turn's boundaries (no timer)
368
369// The board this session is attached to, read again when another session may have written it: a
370// cheap look first (the attachment and the meta's time of the last write, against $.state), and
371// the cards only when they moved. Cards read this way are not marked as this session's changes
372// (recent.js marks only this session's own tool writes). A failure is let go.
373async function syncBoard($) {
374 try {
375 await exclusive(async () => {
376 const me = await $.session.id()
377 const held = attachedOf((await $.state.get(ATTACHED)).value, me)
378 const att = await attachmentOf($, me)
379 const same = held !== null && (att?.id ?? null) === held.board && (att === null || (att.meta.updatedAt === held.stamp && att.meta.name === held.name))
380 if (!same) await loadBoard($)
381 })
382 } catch {}
383}
384
385// The list of boards, read again when the pane would draw it (attached to none, or the other
386// boards shown) and the boards' metas moved since it was read; the line about the last action stays
387async function syncList($) {
388 try {
389 const me = await $.session.id()
390 const held = attachedOf((await $.state.get(ATTACHED)).value, me)
391 if (held !== null && held.board !== null && !(await readView($)).shown) return
392 const keys = await $.store.keys()
393 const metas = new Map()
394 for (const key of keys) if (isMetaKey(key)) metas.set(key, await $.store.get(key))
395 const boards = boardsOf((await $.state.get(BOARDS)).value, me)
396 if (boards.sig === listSigOf(keys, metas)) return
397 await refreshBoards($)
398 } catch {}
399}
400
401// [読み直す]: the board and the list, from the store now, whatever moved; a toast says so
402async function reloadNow($) {
403 try {
404 await exclusive(() => loadBoard($))
405 await refreshBoards($)
406 say($, `${clockOf(await nowOf($))} に読み直しました`)
407 } catch (error) {
408 say($, `読み直せませんでした: ${messageOf(error)}`)
409 }
410 await patchView($, { shown: false, rename: false }).catch(() => {})
411}
412
413// What a press in the pane did, said in a toast: the pane shows the board only (a failing toast is let go)
414function say($, text) {
415 try {
416 $.ui.toast(text)
417 } catch {}
418}
419
420// ---- The move of 0.10.0's boards (migrate.js)
421
422// Moves every board of 0.10.0 and before still in the store. Run at each session's start, inside
423// `exclusive`: a board that could not be moved keeps its old keys and is tried again next time.
424async function moveOldBoards($, root) {
425 const keys = await $.store.keys()
426 const sids = oldSessionsOf(keys)
427 if (sids.length === 0) return
428 const present = new Set(keys)
429 const now = await $.clock.now()
430 for (const sid of sids) {
431 try {
432 await moveOne($, sid, present, root, now)
433 } catch (error) {
434 noteNotMoved($, messageOf(error))
435 }
436 }
437}
438
439function noteNotMoved($, reason) {
440 try {
441 $.ui.log(`whiteboard: 前の版の${BOARD_NAME}を 1 つ移せませんでした(${reason})。元のデータは残してあり、次の起動でもう一度試します`)
442 } catch {}
443}
444
445// One old session's keys: the new keys written (unless a board moved from it is there already),
446// read back, and only then the old keys deleted
447async function moveOne($, sid, present, root, now) {
448 const old = oldKeysOf(sid)
449 const values = {}
450 for (const [kind, key] of Object.entries(old)) values[kind] = present.has(key) ? await $.store.get(key) : undefined
451 const plan = planMove(sid, values, root, now)
452 if (plan.kind === 'broken') {
453 noteNotMoved($, plan.reason)
454 return
455 }
456 if (plan.kind === 'move') {
457 // Another session that started at the same time may have moved it already: its keys stay
458 const had = readMeta(await $.store.get(metaKey(plan.id))) !== null
459 if (!had) {
460 if (plan.record !== null) await $.store.set(boardKey(plan.id), plan.record)
461 await $.store.set(metaKey(plan.id), plan.meta)
462 }
463 if (readAttach(await $.store.get(attachKey(sid))) === null) await $.store.set(attachKey(sid), plan.attach)
464 const meta = await $.store.get(metaKey(plan.id))
465 const record = await $.store.get(boardKey(plan.id))
466 const sound = had
467 ? readMeta(meta) !== null && (plan.record === null || isBoardRecord(record))
468 : isSame(meta, plan.meta) && (plan.record === null || isSame(record, plan.record))
469 if (!sound) throw new Error('書いた内容を読み戻せませんでした')
470 }
471 for (const key of Object.values(old)) if (present.has(key)) await $.store.delete(key)
472}
473
474// ---- The small state values (their shapes: view-state.js)
475
476async function readView($) {
477 return viewOf((await $.state.get(VIEW)).value)
478}
479
480// Writes a state value only when it differs from what is there (a write redraws the drawings).
481// The engine wants the reference spelled out at each call, so one function for each value.
482async function setView($, next) {
483 const { value } = await $.state.get(VIEW)
484 if (!isSame(value, next)) await $.state.set(VIEW, next)
485}
486async function setBoards($, next) {
487 const { value } = await $.state.get(BOARDS)
488 if (!isSame(value, next)) await $.state.set(BOARDS, next)
489}
490
491// A change to the view
492function patchView($, patch) {
493 return exclusiveState(async () => setView($, { ...(await readView($)), ...patch }))
494}
495
496// Reads the boards from the store into $.state (`boards`); written only if it differs from what is there
497function refreshBoards($) {
498 return exclusiveBoards(async () => {
499 const me = await $.session.id()
500 const { rows, bytes, sig } = await scanStore($)
501 await setBoards($, { owner: me, rows, bytes, sig })
502 })
503}
504
505// The board and its cards for a drawing: the state's, when they are this session's; else read from
506// the store (a drawing may read the store, but may not write the state). { attached: { board,
507// name } (board null for none), cards }.
508async function shownBoard($) {
509 try {
510 const me = await $.session.id()
511 const held = attachedOf((await $.state.get(ATTACHED)).value, me)
512 if (held !== null) {
513 if (held.board === null) return { attached: held, cards: [] }
514 const { value } = await $.state.get(CARDS)
515 if (Array.isArray(value) && (await $.state.get(OWNER)).value === me) return { attached: held, cards: value }
516 return { attached: held, cards: shownCards((await storedBoard($, held.board)).cards) }
517 }
518 const att = await attachmentOf($, me)
519 if (att === null) return { attached: NONE, cards: [] }
520 return { attached: { board: att.id, name: att.meta.name }, cards: shownCards((await storedBoard($, att.id)).cards) }
521 } catch {
522 return { attached: NONE, cards: [] }
523 }
524}
525
526// The time, with the clock's own call; the system's if that fails (a drawing must not fail on it)
527async function nowOf($) {
528 try {
529 return await $.clock.now()
530 } catch {
531 return Date.now()
532 }
533}
534
535// ---- The cards changed since the person's latest prompt (recent.js)
536
537// This load's marks of the current turn, with the bases the line counts need: { owner, turn, cards }
538// or null. Kept here rather than read back from $.state, which a dispatch reads as it stood at its
539// first read; the tools that write them run one at a time in `exclusive`. $.state gets a copy
540// without the bases (`recent`) for the drawings.
541let recentMarks = null
542
543// The setting `staleHours` (stale.js), read once a load like the others; module-wide because the
544// tools (list_cards' titles_only) read it as well as the drawings
545let staleHours = STALE_DEFAULT_HOURS
546
547// The setting `maxCards` (board.js maxCardsOf) and the tools built for it (tools.js toolsFor), read
548// once a load like the others; module-wide because the tool calls and the compaction note take the limit
549let maxCards = LIMITS.cards
550let tools = TOOLS
551
552// The person's prompt: the turn moves on (the drawings stop showing the last turn's marks)
553async function nextTurn($, e) {
554 if (!isPersonPrompt(e)) return
555 try {
556 const id = await $.session.id()
557 await $.state.set(TURN, turnAfter((await $.state.get(TURN)).value, id))
558 recentMarks = null
559 } catch {}
560}
561
562// After a tool's write that turned `before` into `after`: the cards it changed are marked for the
563// current turn. With no turn known (no prompt yet, the counter lost) nothing is marked. A failure
564// here never fails the write.
565async function markChanged($, before, after) {
566 try {
567 const id = await $.session.id()
568 const turn = readTurn((await $.state.get(TURN)).value, id)
569 if (turn === null) return
570 if (recentMarks === null || recentMarks.owner !== id || recentMarks.turn !== turn) {
571 // After a reload the state may still hold this turn's marks; they are taken back
572 recentMarks = { owner: id, turn, cards: seedMarks(marksOf((await $.state.get(RECENT)).value, id, turn)) }
573 }
574 const cards = markWrite(recentMarks.cards, before, after)
575 if (cards === recentMarks.cards) return
576 recentMarks = { owner: id, turn, cards }
577 await $.state.set(RECENT, { owner: id, turn, cards: shownMarks(cards) })
578 } catch {}
579}
580
581// The marks the drawings show: this session's, of the current turn; {} otherwise or on a failure
582async function marksNow($) {
583 try {
584 const id = await $.session.id()
585 const turn = readTurn((await $.state.get(TURN)).value, id)
586 return marksOf((await $.state.get(RECENT)).value, id, turn)
587 } catch {
588 return {}
589 }
590}
591
592// ---- The pane's actions
593
594// [つなぐ]: attaches this session to the board, then the list is read again; a toast says what came of it
595async function attachFromPane($, id) {
596 try {
597 const { meta } = await exclusive(async () => attachTo($, await $.session.id(), id))
598 say($, `「${meta.name}」につなぎました`)
599 } catch (error) {
600 say($, `つなげませんでした: ${messageOf(error)}`)
601 }
602 await refreshBoards($).catch(() => {})
603}
604
605// [中身を見る] / [閉じる]: one board is open at a time
606async function peek($, id) {
607 const view = await readView($)
608 await patchView($, { pick: view.pick === id ? '' : id })
609}
610
611// [表示] / [隠す] on a folded group of the list
612async function showGroup($, name, open) {
613 const view = await readView($)
614 await patchView($, { groups: { ...view.groups, [name]: open === true } })
615}
616
617// [別のボードに切り替える] / [ほかのボードを閉じる]
618async function toggleShown($) {
619 const view = await readView($)
620 if (!view.shown) await refreshBoards($).catch(() => {})
621 await patchView($, { shown: !view.shown, pick: '' })
622}
623
624// [名前を変える]: the editor, under a new key so it starts empty
625async function renameOpen($) {
626 const view = await readView($)
627 await patchView($, { rename: true, renameGen: view.renameGen + 1 })
628}
629
630// The name typed in the editor and Enter: an empty one closes the editor, anything else is checked
631// as Claude's is, and a toast says what came of it. Done (or the same name), the row of buttons
632// comes back; a name that cannot be taken keeps the editor open.
633async function renameFromPane($, value) {
634 const text = typeof value === 'string' ? value.replace(/\s+/g, ' ').trim() : ''
635 if (text === '') {
636 await patchView($, { rename: false })
637 return
638 }
639 const named = nameOf(text)
640 if (named.error) {
641 say($, `名前は ${NAME_LIMIT} 文字までです。短くしてください`)
642 return
643 }
644 try {
645 const out = await renameAttached($, named.name)
646 if (out.unattached) say($, `この${BOARD_NAME}には、もうつながっていません`)
647 else if (out.taken) say($, `このプロジェクトには「${named.name}」という名前の${BOARD_NAME}がもうあります。別の名前にしてください`)
648 else {
649 if (out.from !== out.to) say($, `名前を「${out.from}」から「${out.to}」に変えました`)
650 await patchView($, { rename: false })
651 }
652 } catch (error) {
653 say($, `名前を変えられませんでした: ${messageOf(error)}`)
654 }
655 await refreshBoards($).catch(() => {})
656}
657
658// A change to a part of the view kept with this session's id (fold.js, search.js, order.js), so
659// after /clear it reads as the default; the cards and the store are not touched. `make` answers
660// the view to write from the view as it stands in the queue and the id, read before the queue.
661async function patchOwnView($, make) {
662 const me = await $.session.id()
663 return exclusiveState(async () => setView($, make(await readView($), me)))
664}
665
666// [続きを表示(残り N 行)] / [畳む] on a long card. `rev` is the card's revision as drawn, `ids` the
667// cards the pane drew (fold.js foldsAfter).
668function setFold($, id, open, rev, ids) {
669 return patchOwnView($, (view, me) => ({ ...view, folds: foldsAfter(view.folds, me, id, open, rev, ids) }))
670}
671
672// The search field's text, typed or cleared (search.js)
673function setFilter($, text) {
674 return patchOwnView($, (view, me) => ({ ...view, filter: filterAfter(me, text) }))
675}
676
677// [絞り込みを解く], and the pane opened again: the filter is let go and the field drawn anew, empty
678function clearFilter($) {
679 return exclusiveState(async () => setView($, filterCleared(await readView($))))
680}
681
682// [並び: …]: the order `by` the press asked for (not a toggle of what is stored, so a press that
683// ran late sets what its label said)
684function setOrder($, by) {
685 return patchOwnView($, (view, me) => ({ ...view, order: orderAfter(me, by) }))
686}
687
688// This session's part of the view for the drawing (`read` takes the session id), or `fallback`
689// on a failure: the fold choices ({}), the search field's text ('') and the order ('added')
690async function ownPart($, read, fallback) {
691 try {
692 return read(await $.session.id())
693 } catch {
694 return fallback
695 }
696}
697
698// ---- What the drawings read, and the entrances
699
700// Opens the pane: /whiteboard and the band's button. The board and the list are read again first
701// (the line about the last action is let go, the pane's view starts afresh but for the long cards'
702// fold choices and the order; the search field starts empty), so the pane is as the store has it now.
703async function openPane($) {
704 try {
705 await exclusive(() => loadBoard($))
706 } catch {}
707 try {
708 await refreshBoards($)
709 } catch {}
710 try {
711 await patchView($, NO_VIEW)
712 await clearFilter($)
713 } catch {}
714 return $.ui.open({ id: PANE_ID, title: BOARD_NAME })
715}
716
717// What a card tool's call does (the table: tools.js), on the board this session is attached to,
718// read from the store; with none it is refused (NOT_ATTACHED). A write reads the board's revision
719// again just before it saves: another session attached to the same board may have written it
720// since, and the write is refused then (CHANGED_MEANWHILE), the state taking the board as it is.
721async function runTool($, tool, e) {
722 try {
723 const outcome = await exclusive(async () => {
724 const { me, att, board } = await loadBoard($)
725 if (att === null) return { error: NOT_ATTACHED }
726 const before = board.cards
727 // The context: the board's revision, the time and the setting for the stale flag
728 // (list_cards), the removed cards (undo_card), the card limit (set_card, undo_card)
729 const now = await $.clock.now()
730 const change = tool.apply(before, e, now, { rev: board.rev, removed: board.removed, now, staleHours, maxCards })
731 if (tool.writes && !change.error && change.cards !== before) {
732 const again = await storedBoard($, att.id)
733 if (again.rev !== board.rev) {
734 await showBoard($, me, att, again.cards)
735 return { error: CHANGED_MEANWHILE }
736 }
737 await commitBoard($, me, att, board, change.cards)
738 // Marked for the person's current turn
739 await markChanged($, before, change.cards)
740 }
741 return change
742 })
743 return outcome.error ? { deny: outcome.error } : { result: outcome.text }
744 } catch (error) {
745 return { deny: `${tool.writes ? 'ボードを保存できませんでした' : 'ボードを読めませんでした'}: ${messageOf(error)}` }
746 }
747}
748
749// ---- What the model is handed with the person's prompt (prompt.submit's `context`)
750//
751// The model's conversation is read ($.session.messages as the next request is built from it) at
752// each of the person's prompts and at each main turn's end (guide.js lookAfter): whether the guide
753// is still in it, and whether its start was replaced since the last look (a compaction). The
754// state `look` keeps the last look and a compaction not yet followed by a prompt.
755
756// Whether the guide was handed over in this load, for when the conversation cannot be read
757let guidedInLoad = false
758
759// Looks at the conversation and keeps the look; null when it cannot be read
760async function lookConversation($) {
761 try {
762 const me = await $.session.id()
763 const messages = await $.session.messages({ as: 'api' })
764 if (!Array.isArray(messages)) return null
765 const value = lookAfter((await $.state.get(LOOK)).value, me, messages)
766 await $.state.set(LOOK, value)
767 return { me, value, hasGuide: hasGuideIn(messages) }
768 } catch {
769 return null
770 }
771}
772
773// The attached board's table of contents (compactionNote), read from the store inside
774// `exclusive` as the tools read it; '' when no board is attached, it is empty, or the read fails
775async function boardContents($, me) {
776 try {
777 const found = await exclusive(async () => {
778 const att = await attachmentOf($, me)
779 return att === null ? null : { name: att.meta.name, cards: (await storedBoard($, att.id)).cards }
780 })
781 if (found === null || found.cards.length === 0) return ''
782 return compactionNote(found.cards, { name: found.name, maxCards })
783 } catch (error) {
784 try {
785 $.ui.log(`whiteboard: 圧縮の後にボードの目次を渡せませんでした: ${messageOf(error)}`, { to: 'debug' })
786 } catch {}
787 return ''
788 }
789}
790
791// The blocks to hand the model with one of the person's prompts, in order: the guide (short and
792// full) when the conversation no longer holds it (a fresh session, after /clear or a compaction);
793// the board's table of contents on the first prompt after a compaction (any guide setting); with
794// full, the tool lines when the prompt holds a keyword (guide.js makeGuideTurns). Never throws.
795async function contextFor($, e, guideMode, guideTurns) {
796 const blocks = []
797 const look = await lookConversation($)
798 if (guideMode !== 'off' && (look === null ? !guidedInLoad : !look.hasGuide)) {
799 blocks.push(GUIDE_SHORT)
800 guidedInLoad = true
801 }
802 if (look !== null && look.value.compacted) {
803 const contents = await boardContents($, look.me)
804 if (contents !== '') blocks.push(contents)
805 try {
806 await $.state.set(LOOK, { ...look.value, compacted: false })
807 } catch {}
808 }
809 if (guideMode === 'full') {
810 const lines = guideTurns(e.text)
811 if (lines !== '') blocks.push(lines)
812 }
813 return blocks
814}
815
816export function register(on, options) {
817 recentMarks = null
818 guidedInLoad = false
819 staleHours = staleHoursOf(options)
820 maxCards = maxCardsOf(options)
821 tools = toolsFor(maxCards)
822 const guideMode = guideModeOf(options)
823 // The setting `colors`, read once a load like the others
824 const palette = paletteOf(options)
825 // The setting `styleMarks` (off unless true): a shape per colour name before the title
826 const shapes = shapesOn(options)
827 // The setting `bandTitle` (on unless false): the band shows a pinned card's title
828 const bandTitle = options?.bandTitle !== false
829 // The turns' count lives in this load only (a hot reload starts it again)
830 const guideTurns = makeGuideTurns(keywordsOf(options))
831
832 // Fires on the session's start, and again after a hot reload: the tools, the root fixed, the old
833 // boards moved, this session's board (if any) and the list read
834 on('session.start', async ($, e, next) => {
835 for (const [name, tool] of [...Object.entries(tools), ...Object.entries(BOARD_TOOLS)]) {
836 await $.tool.register({ name, description: tool.description, inputSchema: tool.inputSchema })
837 }
838 // A refused name throws, and a throw would skip the rest of this hook (the board would not load)
839 try {
840 await $.command.register({ name: 'whiteboard', description: `${BOARD_NAME}を開く` })
841 } catch (error) {
842 try {
843 $.ui.log(`whiteboard: コマンド /whiteboard を登録できませんでした: ${messageOf(error)}`, { to: 'debug' })
844 } catch {}
845 }
846 try {
847 const root = await fixedRoot($)
848 await exclusive(() => moveOldBoards($, root))
849 } catch {}
850 try {
851 await exclusive(() => loadBoard($))
852 } catch {}
853 try {
854 await refreshBoards($)
855 } catch {}
856 return next(e)
857 })
858
859 // One hook per tool, the matcher written out so that validate can list it
860 on('tool.call', { tool: 'mcp__whiteboard__set_card' }, ($, e) => runTool($, tools.set_card, e))
861 on('tool.call', { tool: 'mcp__whiteboard__edit_card' }, ($, e) => runTool($, tools.edit_card, e))
862 on('tool.call', { tool: 'mcp__whiteboard__append_card' }, ($, e) => runTool($, tools.append_card, e))
863 on('tool.call', { tool: 'mcp__whiteboard__remove_card' }, ($, e) => runTool($, tools.remove_card, e))
864 on('tool.call', { tool: 'mcp__whiteboard__clear' }, ($, e) => runTool($, tools.clear, e))
865 on('tool.call', { tool: 'mcp__whiteboard__list_cards' }, ($, e) => runTool($, tools.list_cards, e))
866 on('tool.call', { tool: 'mcp__whiteboard__undo_card' }, ($, e) => runTool($, tools.undo_card, e))
867 on('tool.call', { tool: 'mcp__whiteboard__open_board' }, ($, e) => openBoard($, e))
868 on('tool.call', { tool: 'mcp__whiteboard__list_boards' }, ($, e) => listBoards($, e))
869 on('tool.call', { tool: 'mcp__whiteboard__rename_board' }, ($, e) => renameBoard($, e))
870
871 // A prompt. The person's own (recent.js isPersonPrompt): the first request is kept for the
872 // meta, a new turn starts for the marks of the cards Claude changes (recent.js), and what
873 // contextFor gives is handed to the model with it as `context` blocks the person does not see
874 // (the prompt itself is not changed). Any prompt: another session on the same board may have
875 // written it since the last turn. A slash command gets no context.
876 on('prompt.submit', async ($, e, next) => {
877 const isPerson = isPersonPrompt(e)
878 if (isPerson) {
879 await noteAbout($, e)
880 await nextTurn($, e)
881 }
882 await syncBoard($)
883 await syncList($)
884 const blocks = isPerson && e.command === undefined ? await contextFor($, e, guideMode, guideTurns) : []
885 return next(blocks.length === 0 ? e : { ...e, context: [...(e.context ?? []), ...blocks] })
886 })
887
888 // The main loop's turn ends: what another session wrote meanwhile shows now, and the
889 // conversation is looked at, so that a compaction during the turn is known at the next prompt
890 // (a subagent's end is left alone)
891 on('turn.complete', async ($, e, next) => {
892 const result = await next(e)
893 if (e.agentId === undefined) {
894 await syncBoard($)
895 await syncList($)
896 await lookConversation($)
897 }
898 return result
899 })
900
901 // /whiteboard opens the pane (a helper: the band's button is the way in)
902 on('command.run', { command: 'whiteboard' }, async ($) => {
903 const opened = await openPane($)
904 return { text: opened?.isPlaced === false ? `${BOARD_NAME}を開きました(まだ表示されていません)` : `${BOARD_NAME}を開きました` }
905 })
906
907 on('ui.render', { component: 'Pane', requestId: 'whiteboard' }, async ($, e) => {
908 // The Buttons' presses are guarded (press-guard.js): the first press on an unfocused pane can be lost
909 const guard = guardDrawing(e.requestId)
910 const ui = guard.wrap($.ui.resolve(e))
911 const view = await readView($)
912 const { attached, cards } = await shownBoard($)
913 const data = {
914 attached,
915 cards,
916 boards: boardsOf((await $.state.get(BOARDS)).value, await ownPart($, (me) => me, '')),
917 root: await rootForDrawing($),
918 view,
919 folds: await ownPart($, (me) => foldsOf(view.folds, me), {}),
920 filter: await ownPart($, (me) => filterOf(view.filter, me), ''),
921 order: await ownPart($, (me) => orderOf(view.order, me), 'added'),
922 now: await nowOf($),
923 palette,
924 shapes,
925 marks: await marksNow($),
926 staleHours,
927 }
928 const actions = {
929 attach: (id) => attachFromPane($, id),
930 peek: (id) => peek($, id),
931 group: (name, open) => showGroup($, name, open),
932 toggleShown: () => toggleShown($),
933 reload: () => reloadNow($),
934 renameOpen: () => renameOpen($),
935 renameCancel: () => patchView($, { rename: false }),
936 rename: (value) => renameFromPane($, value),
937 fold: (id, open, rev, ids) => setFold($, id, open, rev, ids),
938 filter: (text) => setFilter($, text),
939 clearFilter: () => clearFilter($),
940 order: (by) => setOrder($, by),
941 }
942 return guard.done(drawPane(ui, data, { surface: e.surface, columns: widthOf(e) }, actions))
943 })
944
945 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
946 const rest = await next(e)
947 if (e.props.hasSurvey) return rest
948 const { attached, cards } = await shownBoard($)
949 const isAttached = attached.board !== null
950 const ui = $.ui.resolve(e)
951 const card = bandTitle && isAttached ? bandCard(cards) : null
952 const marks = await marksNow($)
953 const changed = markedCount(marks, cards)
954 // Worked out at each drawing, no timer: a card turns stale at the next redraw
955 const stale = staleCount(cards, await nowOf($), staleHours, marks)
956 const count = isAttached ? cards.length : null
957 const mine = drawBand(ui, e.surface, widthOf(e), count, isAttached ? '' : 'ボードを選ぶ', () => openPane($), { card, palette, changed, stale, shapes })
958 if (!rest) return mine
959 return ui.Box({ flexDirection: 'column', children: [mine, rest] })
960 })
961
962 // A press on this mod's elements (the pane and the band). On the pane (press-guard.js) it also
963 // checks that the press reached the Button's onPress; when the chain settled, threw, or stayed
964 // silent for GRACE_MS without it, the press runs once with the latest drawing's closure under
965 // the same key.
966 on('ui.press', { plugin: 'whiteboard' }, async ($, e, next) => {
967 const record = beginPress(e)
968 const chain = next(e).then(
969 (value) => ({ kind: 'value', value }),
970 (error) => ({ kind: 'error', error }),
971 )
972 let outcome
973 if (record) {
974 const timer = new AbortController()
975 const grace = $.clock.sleep(GRACE_MS, { signal: timer.signal }).then(
976 () => ({ kind: 'grace' }),
977 () => new Promise(() => {}),
978 )
979 outcome = await Promise.race([chain, grace])
980 timer.abort()
981 if (outcome.kind === 'grace' && hasStarted(record)) outcome = await chain
982 } else {
983 outcome = await chain
984 }
985 if (!record || hasStarted(record)) {
986 if (record) endPress(e, record)
987 if (outcome.kind === 'error') throw outcome.error
988 return outcome.value
989 }
990 try {
991 await takeOver(record, e)
992 } catch {}
993 return { element: e.element }
994 })
995}
996hooks/board.js 758 lines1// The board's rules, kept apart from the host calls: what a card is, the limits, how the seven
2// tools change a list of cards and what they answer, the one previous version a card keeps and the
3// cards removed lately (undo_card), and how the band fits a narrow line (the count, a hint, the
4// title of the pinned card written last, the count of cards changed since the latest prompt, and
5// the count of stale cards).
6// Pure: no $ here, so register.js keeps every $ call itself.
7
8import { styleOf, styleInput } from './style.js'
9import { isStaleCard, staleText } from './stale.js'
10
11/** The board's name in what the person sees (the band, the pane, its title, /whiteboard); what Claude reads says 「ボード」. */
12export const BOARD_NAME = 'ホワイトボード'
13
14/**
15 * The card limit: the setting `maxCards` (maxCardsOf), `default` when it is not set, kept within
16 * min..max. A stored board is read up to `max` whatever the setting (sanitizeCards), so lowering
17 * the setting never drops cards: a board over the limit keeps them, and only adding is refused.
18 */
19export const CARD_LIMIT = { default: 20, min: 5, max: 40 }
20
21/**
22 * What the board holds at most; a call over a limit is refused with the reason. `cards` is the
23 * default card limit only: the tools and the compaction note take the one the setting gives
24 * (maxCardsOf) as an argument.
25 */
26export const LIMITS = {
27 cards: CARD_LIMIT.default,
28 id: 40,
29 title: 60,
30 body: 4000,
31}
32
33/**
34 * The setting `maxCards`: a number (or a numeric string) rounded down to a whole number and kept
35 * within CARD_LIMIT.min..max (below: min, above: max). Absent, empty, or not a finite number: the default.
36 */
37export function maxCardsOf(options) {
38 const raw = options?.maxCards
39 const n = typeof raw === 'number' ? raw : typeof raw === 'string' && raw.trim() !== '' ? Number(raw.trim()) : NaN
40 if (!Number.isFinite(n)) return CARD_LIMIT.default
41 return Math.min(CARD_LIMIT.max, Math.max(CARD_LIMIT.min, Math.floor(n)))
42}
43
44/** A card limit as the functions below take it: a whole number within CARD_LIMIT, else the default. */
45const limitOf = (n) => (Number.isSafeInteger(n) && n >= CARD_LIMIT.min && n <= CARD_LIMIT.max ? n : CARD_LIMIT.default)
46
47/** Ids are short and plain, so Claude can name a card again without guessing at its spelling. */
48export const ID_PATTERN = /^[A-Za-z0-9_-]+$/
49
50// ---- The stored board: one record under `b:<boardId>` (boards.js), written in one store write,
51// { v: 2, cards, rev, removed }
52// `cards` the cards (each may carry `prev`, see trackPrev), `rev` the board's revision, `removed`
53// the cards removed lately (undo_card). A board that became empty keeps its record (cards []), so
54// its revision goes on and its removed cards can still be brought back. Only a record with nothing
55// in it (no cards, revision 0, nothing removed) is not written: the key is deleted.
56//
57// Older boards: up to 0.9.2 the value was the cards alone (a list), and builds in between kept the
58// revision and the removed cards under keys of their own. migrate.js reads them with readBoard and
59// moves them to the record.
60
61/** The version of the stored record. */
62export const BOARD_VERSION = 2
63
64/** Whether a stored value is the record (as opposed to an older board, a list of cards). */
65export const isBoardRecord = (value) => value != null && typeof value === 'object' && !Array.isArray(value) && value.v === BOARD_VERSION && Array.isArray(value.cards)
66
67/** The cards of a stored board, of either form: sanitizeCards of the record's `cards` or of the list. */
68export const boardCardsOf = (value) => sanitizeCards(isBoardRecord(value) ? value.cards : value)
69
70/**
71 * A stored board as the tools use it: { cards, rev, removed, legacy }. `legacy` holds the values an
72 * older build kept beside the board ({ rev, removed }, either undefined), read only for a board that
73 * is not a record; `legacy` in the answer is true for such a board.
74 */
75export function readBoard(value, legacy = {}) {
76 const record = isBoardRecord(value)
77 const cards = sanitizeCards(record ? value.cards : value)
78 const source = record ? value : legacy
79 return { cards, rev: boardRevOf(cards, source?.rev), removed: sanitizeRemoved(source?.removed), legacy: !record }
80}
81
82/** The record to store for a board, or null when there is nothing in it to keep (the key is deleted then). */
83export function boardRecord({ cards, rev, removed }) {
84 if (cards.length === 0 && rev === 0 && removed.length === 0) return null
85 return { v: BOARD_VERSION, cards, rev, removed }
86}
87
88// ---- Revisions: every write that changes the board moves its revision on by one, and each card
89// it changed (added, rewritten, pinned, styled) carries that number as
90// `rev`. A removal moves the board's revision too. list_cards answers the board's revision, and its
91// `since` returns only the cards with a greater `rev`. The board's revision is the record's `rev`,
92// which an emptied board keeps.
93
94const isRev = (n) => Number.isSafeInteger(n) && n >= 0
95
96/** A stored board revision; 0 for anything else (a board written before revisions existed). */
97export const readRev = (value) => (isRev(value) ? value : 0)
98
99/** A card's revision; 0 for a card written before revisions existed. */
100export const revOf = (c) => (isRev(c?.rev) ? c.rev : 0)
101
102/** The board's revision: the stored one, or the greatest card's if that is ahead of it. */
103export const boardRevOf = (cards, stored) => cards.reduce((m, c) => Math.max(m, revOf(c)), readRev(stored))
104
105// A card's `rev` field as it is kept: present only from revision 1
106const revPart = (rev) => (rev > 0 ? { rev } : {})
107
108/** A card's (or a version's) `pinned` and `style` fields as they are kept: each present only when set. */
109const looksPart = (c) => ({ ...(c?.pinned === true ? { pinned: true } : {}), ...(styleOf(c) !== null ? { style: styleOf(c) } : {}) })
110
111// Whether two cards say the same: title, body, pin and style (the time is not looked at)
112export const sameContent = (a, b) => a.title === b.title && a.body === b.body && (a.pinned === true) === (b.pinned === true) && styleOf(a) === styleOf(b)
113
114/**
115 * The cards after a write, with their revisions: `after` is what a tool made of
116 * `before`, `rev` the board's revision before it. When a card is new or says something else than
117 * it did, or a card is gone, the board moves to rev + 1 and each new or changed card carries it;
118 * the others keep theirs. A write that changed nothing (the same card set again) keeps `rev`.
119 * { cards, rev }.
120 */
121export function stampRevs(before, after, rev) {
122 const was = new Map(before.map((c) => [c.id, c]))
123 const next = rev + 1
124 const ids = new Set(after.map((c) => c.id))
125 let moved = before.some((c) => !ids.has(c.id))
126 const cards = after.map((c) => {
127 const { rev: _rev, ...rest } = c
128 const old = was.get(c.id)
129 if (old && sameContent(old, c)) return { ...rest, ...revPart(revOf(old)) }
130 moved = true
131 return { ...rest, rev: next }
132 })
133 return { cards, rev: moved ? next : rev }
134}
135
136// A card's `arrivedAt` field as it is kept: present only as a finite number
137const arrivedPart = (c) => (typeof c?.arrivedAt === 'number' && Number.isFinite(c.arrivedAt) ? { arrivedAt: c.arrivedAt } : {})
138
139const isCard = (c) =>
140 c != null &&
141 typeof c === 'object' &&
142 typeof c.id === 'string' &&
143 c.id.length > 0 &&
144 c.id.length <= LIMITS.id &&
145 ID_PATTERN.test(c.id) &&
146 typeof c.title === 'string' &&
147 typeof c.body === 'string' &&
148 typeof c.updatedAt === 'number'
149
150/**
151 * The cards of a stored value: the well-formed ones, each id once, up to CARD_LIMIT.max (not the
152 * setting, so a board written under a higher one keeps its cards); [] for anything
153 * else. `pinned` is kept only as true; any other value is dropped (the card stays, unpinned). `style`
154 * is kept only as one of the styles (style.js); anything else is dropped (the card has none). `rev`
155 * is kept only as a positive integer; a card without one reads as revision 0 and is not rewritten for it.
156 * `prev` (the previous version, see trackPrev) is kept only when it is well-formed; a card without
157 * one has nothing to undo. `arrivedAt` (when a 0.10.0 hand-over copied the card in; stale.js) is
158 * kept only as a number.
159 */
160export function sanitizeCards(value) {
161 if (!Array.isArray(value)) return []
162 const seen = new Set()
163 const cards = []
164 for (const c of value) {
165 if (!isCard(c) || seen.has(c.id)) continue
166 seen.add(c.id)
167 cards.push({ id: c.id, title: c.title, body: c.body, updatedAt: c.updatedAt, ...arrivedPart(c), ...looksPart(c), ...revPart(revOf(c)), ...prevPart(c) })
168 if (cards.length >= CARD_LIMIT.max) break
169 }
170 return cards
171}
172
173// ---- Undo: each card keeps one previous version as `prev` ({ title, body, pinned?, style? }), in
174// the store only: list_cards, the pane and the band never see it ($.state holds the cards without
175// it, shownCards). A card undo_card brought back from the removed
176// ones has `prev: { gone: true }` instead (before it the card was not on the board), so that undo
177// on it again removes it: the redo. The cards removed lately are the record's `removed`.
178
179/** How many removed cards are kept to bring back: the latest removals, one entry an id. */
180export const REMOVED_KEEP = 5
181
182const isVersion = (v) =>
183 v != null && typeof v === 'object' && typeof v.title === 'string' && v.title !== '' && v.title.length <= LIMITS.title && typeof v.body === 'string' && v.body.length <= LIMITS.body
184
185/** The `prev` of a card undo_card brought back from the removed cards: before it, the card was not on the board. */
186const GONE_PREV = { gone: true }
187const isGonePrev = (v) => v != null && typeof v === 'object' && v.gone === true
188
189// A card's version as `prev` keeps it: title, body, pin and style (not the time, the id or the revision)
190const versionOf = (c) => ({ title: c.title, body: c.body, ...looksPart(c) })
191
192// A card's `prev` field as it is kept: present only when well-formed
193const prevPart = (c) => (isVersion(c?.prev) ? { prev: versionOf(c.prev) } : isGonePrev(c?.prev) ? { prev: GONE_PREV } : {})
194
195/** The cards as $.state holds them for the drawings: without `prev`. */
196export const shownCards = (cards) => cards.map(({ prev: _prev, ...rest }) => rest)
197
198/**
199 * The cards after a write, each with its `prev`: a card that says something else than it did in
200 * `before` keeps what it said there; one that says the same keeps the `prev` it had; a card that
201 * was not in `before` has none (new), except a card undo_card brought
202 * back, which keeps its `{ gone: true }`. undo_card's swap needs nothing more: the version it
203 * brings back differs, so the one it replaced becomes the `prev`, and a second undo brings that back.
204 */
205export function trackPrev(before, after) {
206 const was = new Map(before.map((c) => [c.id, c]))
207 return after.map((c) => {
208 const { prev, ...rest } = c
209 const old = was.get(c.id)
210 if (!old) return isGonePrev(prev) ? { ...rest, prev: GONE_PREV } : rest
211 if (sameContent(old, c)) return { ...rest, ...prevPart(old) }
212 return { ...rest, prev: versionOf(old) }
213 })
214}
215
216// A removed card as the list keeps it
217const removedEntryOf = (c) => ({ id: c.id, title: c.title, body: c.body, updatedAt: c.updatedAt, ...looksPart(c) })
218
219/** The removed cards of a stored value: the well-formed ones, each id once (its latest removal), the last REMOVED_KEEP; [] for anything else. */
220export function sanitizeRemoved(value) {
221 if (!Array.isArray(value)) return []
222 const out = []
223 for (const c of value) {
224 if (!isCard(c) || c.title === '' || c.title.length > LIMITS.title || c.body.length > LIMITS.body) continue
225 const at = out.findIndex((r) => r.id === c.id)
226 if (at >= 0) out.splice(at, 1)
227 out.push(removedEntryOf(c))
228 }
229 return out.slice(-REMOVED_KEEP)
230}
231
232/**
233 * The removed cards after a write that turned `before` into `after`: the cards gone from the board
234 * go to the end (a clear's cards in the order they were last written, so the most recently written
235 * are the ones kept), an older entry of the same id gives way, an id that is on the board again is
236 * let go, and only the last REMOVED_KEEP stay. { removed, added } (added: a card was removed).
237 */
238export function removedAfter(removed, before, after) {
239 const ids = new Set(after.map((c) => c.id))
240 const gone = before.filter((c) => !ids.has(c.id)).sort((a, b) => a.updatedAt - b.updatedAt)
241 const goneIds = new Set(gone.map((c) => c.id))
242 const kept = removed.filter((c) => !ids.has(c.id) && !goneIds.has(c.id))
243 return { removed: [...kept, ...gone.map(removedEntryOf)].slice(-REMOVED_KEEP), added: gone.length > 0 }
244}
245
246// ---- Checklists
247
248// A Markdown task-list item: a bullet (- * +) or a number (1. 1)), then [ ], [x] or [X], then a blank or the line's end
249const TASK_LINE = /^\s*(?:[-*+]|\d{1,9}[.)])\s+\[([ xX])\](?:\s|$)/
250// A fence's opening or closing line: three or more ` or ~ (an opening ``` may carry an info string without `)
251const FENCE_LINE = /^\s*(`{3,}|~{3,})(.*)$/
252
253/**
254 * The task-list items of a body: { done, total }, counting `- [ ]` / `- [x]` lines (any bullet or
255 * number, any indent). Lines inside a fenced code block (``` or ~~~, mermaid too) are not counted;
256 * a fence never closed runs to the end, as Markdown draws it.
257 */
258export function taskCounts(body) {
259 let done = 0
260 let total = 0
261 let fence = null
262 for (const raw of String(body ?? '').split('\n')) {
263 const line = raw.replace(/\r$/, '')
264 const f = FENCE_LINE.exec(line)
265 if (fence !== null) {
266 // Closed by the same character, at least as long, with nothing after it
267 if (f && f[1][0] === fence[0] && f[1].length >= fence.length && f[2].trim() === '') fence = null
268 continue
269 }
270 if (f && !(f[1][0] === '`' && f[2].includes('`'))) {
271 fence = f[1]
272 continue
273 }
274 const t = TASK_LINE.exec(line)
275 if (!t) continue
276 total++
277 if (t[1] !== ' ') done++
278 }
279 return { done, total }
280}
281
282/** The progress of a card's checklist, `3/5` (`5/5 済` when all are done); '' for a body with no task items. */
283export function taskProgress(body) {
284 const { done, total } = taskCounts(body)
285 if (total === 0) return ''
286 return `${done}/${total}` + (done === total ? ' 済' : '')
287}
288
289// ---- The tools: each takes the cards and the call's input, and answers { cards, text } (the
290// new list and the short reply) or { error } (the call is refused with this text). A call that
291// changes nothing answers the same `cards` array it was given.
292
293/** The id of an input, or the reason it cannot be one. */
294function idOf(input) {
295 const id = typeof input?.id === 'string' ? input.id.trim() : ''
296 if (id === '') return { error: 'id が空です。短い英数字の id を指定してください(例: plan, urls)' }
297 if (id.length > LIMITS.id || !ID_PATTERN.test(id)) {
298 return { error: `id は英数字と _ - だけで ${LIMITS.id} 文字までです(受け取ったのは ${id.length} 文字)。例: plan, urls` }
299 }
300 return { id }
301}
302
303/** The words after a reply when a style changed: `。色を blue にしました` / `。色を外しました`, '' when it did not. */
304const styleNote = (was, is) => (was === is ? '' : is === null ? '。色を外しました' : `。色を ${is} にしました`)
305
306/** The cards as the pane shows them: the pinned ones first, then the others; each group in the order added. */
307export const orderedCards = (cards) => [...cards.filter((c) => c.pinned === true), ...cards.filter((c) => c.pinned !== true)]
308
309/**
310 * set_card: adds a card, or overwrites the one with the same id in place. `pin` fixes it to the top
311 * (true), frees it (false), or leaves it as it was (absent). `style` the same way: one of the
312 * styles, `none` (removes it), or absent (as it was). A card set again as it is (title, body, pin
313 * and style the same) is not written: the same `cards` come back, its time stays. `maxCards` (the
314 * setting, maxCardsOf) is how many cards the board may hold: a new card beyond it is refused.
315 */
316export function applySet(cards, input, now, { maxCards } = {}) {
317 const limit = limitOf(maxCards)
318 const { id, error } = idOf(input)
319 if (error) return { error }
320 const title = typeof input.title === 'string' ? input.title.trim() : ''
321 if (title === '') return { error: 'title が空です。カードの見出しを指定してください' }
322 if (title.length > LIMITS.title) return { error: `title は ${LIMITS.title} 文字までです(受け取ったのは ${title.length} 文字)。短くしてください` }
323 const body = typeof input.body === 'string' ? input.body : ''
324 if (body.length > LIMITS.body) {
325 return { error: `body は ${LIMITS.body} 文字までです(受け取ったのは ${body.length} 文字)。要点に絞るか、カードを分けてください` }
326 }
327 if (input.pin !== undefined && typeof input.pin !== 'boolean') return { error: 'pin は true か false で指定してください(省略すると今のまま)' }
328 const styled = styleInput(input.style)
329 if (styled.error) return { error: styled.error }
330 const index = cards.findIndex((c) => c.id === id)
331 const was = index >= 0 && cards[index].pinned === true
332 const is = input.pin === undefined ? was : input.pin
333 const styleWas = index >= 0 ? styleOf(cards[index]) : null
334 const styleIs = styled.keep ? styleWas : styled.style
335 const card = { id, title, body, updatedAt: now, ...looksPart({ pinned: is, style: styleIs }) }
336 if (index >= 0 && sameContent(cards[index], card)) return { cards, text: `${id} は同じ内容なので、書き換えていません(全 ${cards.length} 件)` }
337 const pinNote = (is === was ? '' : is ? '。固定しました' : '。固定を外しました') + styleNote(styleWas, styleIs)
338 if (index < 0) {
339 if (cards.length >= limit) {
340 return { error: `カードは ${limit} 枚までで、いっぱいです。済んだカードを remove_card で消してから追加してください` }
341 }
342 return { cards: [...cards, card], text: `追加しました: ${id}(全 ${cards.length + 1} 件)${pinNote}` }
343 }
344 return { cards: cards.map((c, i) => (i === index ? card : c)), text: `上書きしました: ${id}(全 ${cards.length} 件)${pinNote}` }
345}
346
347/** The card's body with a new text, or the reason it cannot be: the body over the limit is refused with the excess. */
348function withBody(cards, index, body, now) {
349 if (body.length > LIMITS.body) {
350 return { error: `本文が上限の ${LIMITS.body} 文字を ${body.length - LIMITS.body} 文字超えます(${body.length} 文字になります)。要点に絞るか、カードを分けてください` }
351 }
352 // Title, pin, style and position stay; only the body and the time change
353 return { cards: cards.map((c, i) => (i === index ? { ...c, body, updatedAt: now } : c)) }
354}
355
356/** The card with a new style (null: none); title, body, pin and position stay. */
357function withStyle(cards, index, style, now) {
358 return cards.map((c, i) => {
359 if (i !== index) return c
360 const { style: _old, ...rest } = c
361 return { ...rest, updatedAt: now, ...(style !== null ? { style } : {}) }
362 })
363}
364
365const noCardText = (id) => `${id} というカードはありません。set_card で作ってください`
366
367/**
368 * edit_card: replaces `find` in the card's body with `replace`. Like an editor's replace: it
369 * must match in exactly one place, unless `all` is true (every place). A `find` that is nowhere
370 * in the body, or in several places without `all`, is refused. `replace` may be empty (deletes).
371 * `style` (as in set_card) changes the card's style too; with `style` and no `find` / `replace`
372 * only the style changes. A call with neither `find` nor `style` is refused.
373 */
374export function applyEdit(cards, input, now) {
375 const { id, error } = idOf(input)
376 if (error) return { error }
377 const styled = styleInput(input.style)
378 if (styled.error) return { error: styled.error }
379 if (input.find === undefined && input.replace === undefined) {
380 if (styled.keep) return { error: 'find(本文の置き換え)か style(色)を指定してください。本文を置き換えるなら find と replace、色だけを変えるなら style だけでよい' }
381 return editStyle(cards, id, styled.style, now)
382 }
383 if (typeof input.find !== 'string' || input.find === '') return { error: 'find が空です。本文の中で置き換えたい文字列を指定してください' }
384 if (typeof input.replace !== 'string') return { error: 'replace は文字列で指定してください(空にすると find の部分を消します)' }
385 if (input.all !== undefined && typeof input.all !== 'boolean') return { error: 'all は true か false で指定してください' }
386 const index = cards.findIndex((c) => c.id === id)
387 if (index < 0) return { cards, text: noCardText(id) }
388 const parts = cards[index].body.split(input.find)
389 const found = parts.length - 1
390 if (found === 0) return { error: `${id} の本文に find が見つかりませんでした。list_cards の id で本文を読んで、一字一句合わせてください(改行も含めて)` }
391 if (found > 1 && input.all !== true) {
392 return { error: `find が ${id} の本文に ${found} 箇所あります。すべて置き換えるなら all: true、1 箇所だけなら前後も含めて一意になる find にしてください` }
393 }
394 const body = (input.all === true ? parts : [parts[0], parts.slice(1).join(input.find)]).join(input.replace)
395 const changed = withBody(cards, index, body, now)
396 if (changed.error) return changed
397 const text = `編集しました: ${id}(${input.all === true ? found : 1} 箇所)`
398 if (styled.keep) return { cards: changed.cards, text }
399 const styleWas = styleOf(cards[index])
400 return { cards: withStyle(changed.cards, index, styled.style, now), text: text + styleNote(styleWas, styled.style) }
401}
402
403/** edit_card with `style` alone: the card's style, nothing else. The same style again changes nothing. */
404function editStyle(cards, id, style, now) {
405 const index = cards.findIndex((c) => c.id === id)
406 if (index < 0) return { cards, text: noCardText(id) }
407 const was = styleOf(cards[index])
408 if (was === style) return { cards, text: style === null ? `${id} に色はありません` : `${id} はすでに ${style} です` }
409 return { cards: withStyle(cards, index, style, now), text: style === null ? `色を外しました: ${id}` : `色を ${style} にしました: ${id}` }
410}
411
412/**
413 * append_card: adds `text` to the end of the card's body, on a line of its own (one newline
414 * between, none when the body is empty or already ends with one).
415 */
416export function applyAppend(cards, input, now) {
417 const { id, error } = idOf(input)
418 if (error) return { error }
419 if (typeof input.text !== 'string' || input.text === '') return { error: 'text が空です。足したい文を指定してください' }
420 const index = cards.findIndex((c) => c.id === id)
421 if (index < 0) return { cards, text: noCardText(id) }
422 const old = cards[index].body
423 const body = old + (old === '' || old.endsWith('\n') ? '' : '\n') + input.text
424 const changed = withBody(cards, index, body, now)
425 if (changed.error) return changed
426 return { cards: changed.cards, text: `追記しました: ${id}(本文 ${body.length} 文字)` }
427}
428
429/** remove_card: removes the card with this id; says so when there is none. */
430export function applyRemove(cards, input) {
431 const { id, error } = idOf(input)
432 if (error) return { error }
433 if (!cards.some((c) => c.id === id)) return { cards, text: `${id} というカードはありません` }
434 const rest = cards.filter((c) => c.id !== id)
435 return { cards: rest, text: `削除しました: ${id}(残り ${rest.length} 件)` }
436}
437
438/** clear: removes every card. */
439export function applyClear(cards) {
440 if (cards.length === 0) return { cards, text: 'ボードはすでに空です' }
441 return { cards: [], text: `全部で ${cards.length} 件を削除しました` }
442}
443
444/**
445 * undo_card: a card on the board goes back to its `prev` (title, body, pin, style; its place
446 * stays), and the version it had becomes the `prev` (trackPrev), so a second call redoes. A card
447 * not on the board is brought back from `removed` (the context's removed cards), at the end, while
448 * the limit leaves room, with `prev: { gone: true }`: a second call removes it again (it goes back
449 * to the removed cards, so a third brings it back). One level only. `maxCards` as in applySet.
450 */
451export function applyUndo(cards, input, now, { removed = [], maxCards } = {}) {
452 const limit = limitOf(maxCards)
453 const { id, error } = idOf(input)
454 if (error) return { error }
455 const index = cards.findIndex((c) => c.id === id)
456 if (index >= 0) {
457 const p = cards[index].prev
458 if (isGonePrev(p)) {
459 const rest = cards.filter((c) => c.id !== id)
460 return { cards: rest, text: `戻した ${id} を、もう一度消しました(残り ${rest.length} 件)。もう一度 undo_card を呼ぶと、また戻します` }
461 }
462 if (!isVersion(p)) return { cards, text: `${id} に戻せる前の版はありません(戻せるのは、最後の書き換えの 1 つ前だけです)` }
463 const back = { id, title: p.title, body: p.body, updatedAt: now, ...looksPart(p) }
464 return {
465 cards: cards.map((c, i) => (i === index ? back : c)),
466 text: `${id} を 1 つ前の版に戻しました(全 ${cards.length} 件)。もう一度 undo_card を呼ぶと、戻す前の版にやり直します`,
467 }
468 }
469 const entry = removed.find((c) => c.id === id)
470 if (!entry) {
471 const others = removed.filter((c) => !cards.some((d) => d.id === c.id)).map((c) => c.id)
472 return { cards, text: `${id} というカードはなく、消したカードにもありません` + (others.length > 0 ? `(戻せる消したカード: ${others.join(', ')})` : '') }
473 }
474 if (cards.length >= limit) {
475 return { error: `カードは ${limit} 枚までで、いっぱいなので ${id} を戻せません。済んだカードを remove_card で消してから、もう一度 undo_card を呼んでください` }
476 }
477 const back = { id, title: entry.title, body: entry.body, updatedAt: now, ...looksPart(entry), prev: GONE_PREV }
478 return { cards: [...cards, back], text: `消したカードを戻しました: ${id}(全 ${cards.length + 1} 件)。もう一度 undo_card を呼ぶと、また消します` }
479}
480
481/** What list_cards' search shows of a match: at most this many lines a card, each cut to this many characters. */
482export const SEARCH = { matches: 5, text: 120 }
483
484const cut = (line, max) => {
485 const chars = [...String(line)]
486 return chars.length > max ? chars.slice(0, max - 1).join('') + '…' : String(line)
487}
488// What titles_only adds for a card with a checklist: `tasks: "3/5"` (done/total)
489const tasksPart = (c) => {
490 const { done, total } = taskCounts(c.body)
491 return total > 0 ? { tasks: `${done}/${total}` } : {}
492}
493
494/** The matches of a card for these (lower-cased) terms: the title or id first (line 0), then the body lines holding any term. */
495function matchesOf(card, terms) {
496 const out = []
497 const holds = (text) => terms.some((t) => text.toLowerCase().includes(t))
498 if (holds(card.title) || holds(card.id)) out.push({ line: 0, text: cut(card.title, SEARCH.text) })
499 const lines = card.body.split(/\r?\n/)
500 for (let i = 0; i < lines.length && out.length < SEARCH.matches; i++) {
501 if (holds(lines[i])) out.push({ line: i + 1, text: cut(lines[i], SEARCH.text) })
502 }
503 return out.slice(0, SEARCH.matches)
504}
505
506/** The words of a list_cards query: split on blanks, the empty ones let go. */
507export const queryTerms = (query) => (typeof query === 'string' ? query.split(/\s+/).filter((t) => t !== '') : [])
508
509/**
510 * list_cards' search: the cards of `cards` (in the order given) holding every one of `terms` in
511 * their id, title or body (any case, part of a word will do), each as { id, title, pinned?,
512 * style?, matches } (no `matches` with `titlesOnly`). Also used for the other sessions' boards (others.js).
513 */
514export function searchCards(cards, terms, titlesOnly = false) {
515 const lower = terms.map((t) => t.toLowerCase())
516 return cards
517 .filter((c) => {
518 const text = (c.id + '\n' + c.title + '\n' + c.body).toLowerCase()
519 return lower.every((t) => text.includes(t))
520 })
521 .map((c) => ({ id: c.id, title: c.title, ...looksPart(c), ...(titlesOnly ? {} : { matches: matchesOf(c, lower) }) }))
522}
523
524/**
525 * list_cards, in the order the pane shows the cards (the pinned first). The answer's first line is
526 * always the board's revision, `rev: 42` (then `notice`, the read-only line, when there is one).
527 * With no argument, every card's id, title and body as JSON (a body may hold any line, so no line
528 * format is safe); a pinned card adds `pinned: true`, a card with a style its `style`. Arguments:
529 * id wins over all the others: that one card, { id, title, body, pinned? }
530 * since a revision read before: only the cards changed after it (rev > since), after a
531 * line `ids: a, b, c` of every card on the board (a card not there was removed).
532 * With nothing changed, one line says so. A `since` ahead of the board's revision
533 * (from another board, or a board reset) reads every card, with a line saying so.
534 * The two below apply to those cards only.
535 * query the cards holding every one of its words (split on blanks; in the id, title or body,
536 * any case, part of a word will do), { id, title, pinned?, matches: [{ line, text }] }
537 * (without `matches` when titles_only is there too)
538 * titles_only { id, title, chars (the body's length), pinned?, style?, tasks?, stale? } of every card,
539 * `tasks` ("3/5", done/total) for a card whose body has task-list items, `stale: true`
540 * for a card not written for `staleHours` hours at `now` (stale.js; none when either is absent)
541 */
542export function applyList(cards, input = {}, { rev = 0, notice = '', now, staleHours = 0 } = {}) {
543 const wrong = (name, type) => ({ error: `${name} は${type}で指定してください` })
544 if (input.id !== undefined && typeof input.id !== 'string') return wrong('id', '文字列')
545 if (input.query !== undefined && typeof input.query !== 'string') return wrong('query', '文字列')
546 if (input.titles_only !== undefined && typeof input.titles_only !== 'boolean') return wrong('titles_only', ' true か false')
547 if (input.since !== undefined && !isRev(input.since)) return wrong('since', ' 0 以上の整数(前に読んだときの rev)')
548 const answer = (...lines) => ({ cards, text: [`rev: ${rev}`, ...(notice !== '' ? [notice] : []), ...lines].join('\n') })
549 const id = typeof input.id === 'string' ? input.id.trim() : ''
550 if (id !== '') {
551 const card = cards.find((c) => c.id === id)
552 if (!card) return answer(`${id} というカードはありません`)
553 return answer(JSON.stringify({ id: card.id, title: card.title, body: card.body, ...looksPart(card) }))
554 }
555 if (cards.length === 0) return answer('ボードにカードはありません')
556 const ordered = orderedCards(cards)
557 // With `since`, the cards changed after it, and the lines above them
558 const head = []
559 let pool = ordered
560 let within = ''
561 if (input.since !== undefined) {
562 const since = input.since
563 if (since === rev) return answer(`rev ${rev} から変更はありません`)
564 head.push('ids: ' + ordered.map((c) => c.id).join(', '))
565 if (since > rev) {
566 head.push(`since ${since} が今の rev より大きいので、全カードを返します`)
567 } else {
568 pool = ordered.filter((c) => revOf(c) > since)
569 if (pool.length === 0) return answer(...head, `rev ${since} の後に書き換えられたカードはありません(ids に無いカードは消されています)`)
570 within = `(rev ${since} の後に変わったカードの中)`
571 }
572 }
573 const terms = queryTerms(input.query)
574 if (terms.length > 0) {
575 const rows = searchCards(pool, terms, input.titles_only === true)
576 if (rows.length === 0) return answer(...head, `見つかりませんでした${within}: ${terms.join(' ')}`)
577 return answer(...head, JSON.stringify(rows))
578 }
579 if (input.titles_only === true) {
580 const stalePart = (c) => (isStaleCard(c, now, staleHours) ? { stale: true } : {})
581 return answer(...head, JSON.stringify(pool.map((c) => ({ id: c.id, title: c.title, chars: c.body.length, ...looksPart(c), ...tasksPart(c), ...stalePart(c) }))))
582 }
583 return answer(...head, JSON.stringify(pool.map((c) => ({ id: c.id, title: c.title, body: c.body, ...looksPart(c) }))))
584}
585
586// ---- The note after a compaction
587
588/** The compaction note's size: at most this many characters in all, a title cut no shorter than `minTitle`. */
589export const COMPACTION_NOTE = { chars: 1500, minTitle: 8 }
590
591/**
592 * The text handed to the model with the person's first prompt after a compaction, so it still knows the board and what is on
593 * it: a first line, then `- id: title` for each card in the pane's order (pinned first, marked
594 * (固定)). Titles only; they are cut shorter, all alike, until the whole fits COMPACTION_NOTE.chars.
595 * `name` is the board's name, which the first line gives (the session is attached to it). At most
596 * `maxCards` cards (the setting, maxCardsOf). '' for a board with no cards.
597 */
598export function compactionNote(cards, { name = '', maxCards } = {}) {
599 if (!Array.isArray(cards) || cards.length === 0) return ''
600 const ordered = orderedCards(cards).slice(0, limitOf(maxCards))
601 const which = typeof name === 'string' && name !== '' ? `このセッションがつないでいるボード「${cut(name.replace(/\s+/g, ' ').trim(), 40)}」` : 'このセッションがつないでいるボード'
602 const head =
603 `(whiteboard)${which}に ${ordered.length} 枚のカードがあります` +
604 '。続きの作業で必要なら mcp__whiteboard__list_cards で読めます(id を渡すとその 1 枚の本文):'
605 const lineOf = (c, max) => `- ${c.id}: ${cut(String(c.title).replace(/\s+/g, ' ').trim(), max)}${c.pinned === true ? '(固定)' : ''}`
606 let text = ''
607 for (let max = LIMITS.title; max >= COMPACTION_NOTE.minTitle; max--) {
608 text = [head, ...ordered.map((c) => lineOf(c, max))].join('\n')
609 if (text.length <= COMPACTION_NOTE.chars) break
610 }
611 return text
612}
613
614// ---- The band
615
616/** Character cells a text takes: two for a wide (CJK, full-width) character, one otherwise. */
617export function cells(text) {
618 let n = 0
619 for (const ch of String(text)) {
620 const c = ch.codePointAt(0)
621 n += c >= 0x1100 && (c <= 0x115f || (c >= 0x2e80 && c <= 0xa4cf) || (c >= 0xac00 && c <= 0xd7a3) || (c >= 0xf900 && c <= 0xfaff) || (c >= 0xfe30 && c <= 0xfe4f) || (c >= 0xff00 && c <= 0xff60) || (c >= 0xffe0 && c <= 0xffe6)) ? 2 : 1
622 }
623 return n
624}
625
626/** The cells a Button takes: its label in brackets on a terminal, inside a frame elsewhere (an estimate). */
627export const buttonCells = (surface, label) => cells(label) + (surface === 'terminal' ? 2 : 4)
628
629/**
630 * The line's label, "ホワイトボード 3件" (and "ホワイトボード 0件" while the board is empty); the name
631 * alone for a session attached to no board (`count` null).
632 */
633export const countLabel = (count) => (count === null ? BOARD_NAME : `${BOARD_NAME} ${count}件`)
634
635// The line's last columns, which the terminal may draw over
636const RESERVED_COLUMNS = 2
637
638/** The band's label with its hint: "ホワイトボード · ボードを選ぶ" ("ホワイトボード 3件" with none). */
639export const bandLabel = (count, hint = '') => countLabel(count) + (hint !== '' ? ` · ${hint}` : '')
640
641/**
642 * What the band draws in `columns`: { hasLabel, label, buttonLabel }. The wide form is the label
643 * (the card count, and the hint after it when there is one) and a [開く] button after it. When
644 * that does not fit, the button alone, carrying the count only (the hint is let go). With no
645 * width known (0, absent), the wide form. The same at any count, 0 included; `count` null (no
646 * board attached) has the name without a count.
647 */
648export function fitBand({ surface, columns, count, hint = '' }) {
649 const label = bandLabel(count, hint)
650 const wide = { hasLabel: true, label, buttonLabel: '開く' }
651 if (!(typeof columns === 'number' && columns > 0)) return wide
652 const room = columns - RESERVED_COLUMNS
653 if (cells(label) + 1 + buttonCells(surface, wide.buttonLabel) <= room) return wide
654 const short = countLabel(count)
655 return { hasLabel: false, label: short, buttonLabel: short }
656}
657
658/**
659 * The card whose title the band shows: of the pinned cards, the one written last (the greatest
660 * updatedAt; on a tie the greater revision, then the later in the list). null when none is pinned.
661 */
662export function bandCard(cards) {
663 let best = null
664 for (const c of Array.isArray(cards) ? cards : []) {
665 if (c?.pinned !== true || typeof c.title !== 'string') continue
666 if (best === null || c.updatedAt > best.updatedAt || (c.updatedAt === best.updatedAt && revOf(c) >= revOf(best))) best = c
667 }
668 return best
669}
670
671/** The band's title: at most `chars` characters (… included); let go when fewer than `minCells` cells are left for it. */
672export const BAND_TITLE = { chars: 40, minCells: 6 }
673
674// What goes before the title in the band
675const TITLE_LEAD = '· '
676
677// A text cut to `max` cells, … taking the last one
678function cutCells(text, max) {
679 if (cells(text) <= max) return text
680 let out = ''
681 for (const ch of text) {
682 if (cells(out + ch) + 1 > max) break
683 out += ch
684 }
685 return out + '…'
686}
687
688// The band's parts take the room in this order: the label (with its hint) and [開く], then
689// `· 更新 N枚`, then `· 古い N枚`, then the pinned card's title with what is left. They are drawn
690// in the order label · 更新 · 古い · title · [開く].
691
692// The cells the label, [開く] and the counts as fitted (`recent`, `old`: '' for none) take, gaps included
693const takenCells = (fit, surface, recent = '', old = '') =>
694 cells(fit.label) + 1 + buttonCells(surface, fit.buttonLabel) + (recent !== '' ? 1 + cells(recent) : 0) + (old !== '' ? 1 + cells(old) : 0)
695
696/**
697 * The pinned card's title in the band, drawn as "· title progress" after the label (and its hint)
698 * and the counts, before [開く]: { title, progress }, the title on one line, cut to
699 * BAND_TITLE.chars and then to the room the line has left after the label, [開く], `· 更新 N枚`
700 * (`recent`, fitBandRecent's answer) and `· 古い N枚` (`old`, fitBandStale's answer); the progress
701 * is never cut. null when it is let go: no title, the band in its narrow form (the button alone),
702 * or fewer than BAND_TITLE.minCells left (a short title that fits is kept). Lowest in priority:
703 * the hint and the counts keep their place and the title gives way first. With no width known,
704 * the title is only cut to BAND_TITLE.chars.
705 */
706export function fitBandTitle({ surface, columns, count, hint = '', title, progress = '', recent = '', old = '', shape = '' }) {
707 const capped = cut(String(title ?? '').replace(/\s+/g, ' ').trim(), BAND_TITLE.chars)
708 if (capped === '') return null
709 const fit = fitBand({ surface, columns, count, hint })
710 if (!fit.hasLabel) return null
711 if (!(typeof columns === 'number' && columns > 0)) return { title: capped, progress }
712 // A style's shape (`shape`, the setting styleMarks) and its blank: counted as two cells and one,
713 // as the shapes are of ambiguous width and some fonts draw them wide
714 const used = takenCells(fit, surface, recent, old) + 1 + cells(TITLE_LEAD) + (shape !== '' ? 3 : 0) + (progress !== '' ? 1 + cells(progress) : 0)
715 const left = columns - RESERVED_COLUMNS - used
716 if (cells(capped) > left && left < BAND_TITLE.minCells) return null
717 return { title: cutCells(capped, left), progress }
718}
719
720/** The band's word for the cards changed since the person's latest prompt, `· 更新 2枚`. */
721export const recentText = (n) => `· 更新 ${n}枚`
722
723/**
724 * The band's `· 更新 N枚` after the label (and its hint): the text, or '' when no card is marked or
725 * it does not fit. First after the label and [開く]: drawn only in the wide form and only in the
726 * room those two leave, so it never cuts or drops the hint; the stale count and the title take
727 * what it leaves. With no width known, drawn.
728 */
729export function fitBandRecent({ surface, columns, count, hint = '', changed = 0 }) {
730 if (!(Number.isSafeInteger(changed) && changed > 0)) return ''
731 const fit = fitBand({ surface, columns, count, hint })
732 if (!fit.hasLabel) return ''
733 const text = recentText(changed)
734 if (!(typeof columns === 'number' && columns > 0)) return text
735 return takenCells(fit, surface) + 1 + cells(text) <= columns - RESERVED_COLUMNS ? text : ''
736}
737
738/**
739 * The band's `· 古い N枚` (stale.js) after `· 更新 N枚`: the text, or '' when no card is stale or it
740 * does not fit. After 更新: drawn only in the wide form and only in the room the label, [開く] and
741 * `· 更新 N枚` as fitted (`recent`, fitBandRecent's answer) leave; the title takes what it leaves.
742 * With no width known, drawn.
743 */
744export function fitBandStale({ surface, columns, count, hint = '', recent = '', stale = 0 }) {
745 if (!(Number.isSafeInteger(stale) && stale > 0)) return ''
746 const fit = fitBand({ surface, columns, count, hint })
747 if (!fit.hasLabel) return ''
748 const text = staleText(stale)
749 if (!(typeof columns === 'number' && columns > 0)) return text
750 return takenCells(fit, surface, recent) + 1 + cells(text) <= columns - RESERVED_COLUMNS ? text : ''
751}
752
753/** The local time of a card's last write, `14:05`. */
754export function clockOf(ms) {
755 const d = new Date(ms)
756 return String(d.getHours()).padStart(2, '0') + ':' + String(d.getMinutes()).padStart(2, '0')
757}
758hooks/boards.js 273 lines1// The named boards in $.store and which one a session is attached to (pure: no $ here, register.js
2// keeps the calls).
3//
4// A board belongs to no session. It is two keys, under its own id (made when it is created, or
5// `s-<sessionId>` for a board moved from 0.10.0, migrate.js):
6// b:<boardId> the cards, with the board's revision and the cards removed lately (board.js);
7// absent while there is nothing to keep
8// bm:<boardId> { name, rootHash?, cwdName, createdAt, updatedAt, count, lastTitle?, lastSid?, old? }
9// the board's name (Claude gives it, the person may change it), a hash of the
10// session root's full path it was made under (rootHashOf; the path itself is not
11// kept) with that root's last folder, when it was made and last written, its card
12// count, the title of the session that wrote it last (its first request in 「」
13// when no title is known; with that session's id, `lastSid`), and `old` for a board moved from a read-only 0.10.0 board. A board is listed when its meta is there.
14// A session's attachment is `attach:<sessionId>` ({ board, at }): the same session opened again is
15// still attached. A new session is attached to nothing. Several sessions may be attached to one board.
16//
17// The prefixes differ from 0.10.0's (`board:`, `meta:`, `seal:`), so an old key is never read as a new one.
18
19import { BOARD_NAME, boardCardsOf, orderedCards, clockOf, taskProgress } from './board.js'
20
21// The engine clips a long text and appends this marker
22const CLIP_MARKER = /\.\.\. \[\+\d+ chars\]\s*$/
23
24/** One line of a text: blanks folded, the engine's "... [+N chars]" marker made …, cut to `max` characters with a trailing …. */
25export function clip(value, max = 60) {
26 const line = (typeof value === 'string' ? value : '').replace(CLIP_MARKER, '…').replace(/\s+/g, ' ').trim()
27 const chars = [...line]
28 return chars.length > max ? chars.slice(0, max - 1).join('') + '…' : line
29}
30
31/** What a list row shows and keeps at most. */
32export const LIST_LIMITS = {
33 /** The titles a closed row shows. */
34 titles: 3,
35 /** The characters of a title, of a session's title or first request. */
36 title: 60,
37}
38
39/** The most characters of a board's name. */
40export const NAME_LIMIT = 40
41
42/** The word for a folder that is not known. */
43export const UNKNOWN_FOLDER = '不明'
44
45const DAY_MS = 24 * 60 * 60 * 1000
46const MIB = 1024 * 1024
47
48/** The store holds 4 MiB in all; the pane warns from half of it. */
49export const WARN_BYTES = 2 * MIB
50const STORE_MIB = 4
51
52// ---- The keys
53
54export const BOARD_PREFIX = 'b:'
55export const META_PREFIX = 'bm:'
56export const ATTACH_PREFIX = 'attach:'
57export const boardKey = (boardId) => BOARD_PREFIX + boardId
58export const metaKey = (boardId) => META_PREFIX + boardId
59export const attachKey = (sessionId) => ATTACH_PREFIX + sessionId
60
61/** The board id of a `bm:` key, or null for any other key. */
62export const boardOfMetaKey = (key) => (typeof key === 'string' && key.startsWith(META_PREFIX) && key.length > META_PREFIX.length ? key.slice(META_PREFIX.length) : null)
63
64/** A new board's id from the time and a random number in [0, 1): `n-<time>-<random>`, plain characters only. */
65export const newBoardId = (now, random) => 'n-' + Math.max(0, Math.floor(now)).toString(36) + '-' + Math.floor(random * 36 ** 6).toString(36).padStart(6, '0')
66
67// ---- The root
68
69/** The last folder of a path, nothing above it; UNKNOWN_FOLDER when there is none. */
70export function cwdNameOf(path) {
71 const parts = String(path ?? '')
72 .split(/[\\/]+/)
73 .filter((p) => p !== '')
74 return parts.at(-1) ?? UNKNOWN_FOLDER
75}
76
77/**
78 * A session root's full path as it is hashed: separators made `/` and folded, no trailing one;
79 * a path with a drive letter (Windows, which does not tell cases apart) lower-cased. '' for none.
80 */
81export function rootKeyOf(path) {
82 const p = String(path ?? '')
83 .trim()
84 .replace(/[\\/]+/g, '/')
85 const key = p.length > 1 ? p.replace(/\/$/, '') : p
86 return /^[A-Za-z]:/.test(key) ? key.toLowerCase() : key
87}
88
89/**
90 * The meta's `rootHash`: FNV-1a (64 bits) of rootKeyOf's UTF-8 bytes, 16 hex digits, so boards of
91 * one project match without the path being kept; null when the path is empty.
92 */
93export function rootHashOf(path) {
94 const key = rootKeyOf(path)
95 if (key === '') return null
96 let h = 0xcbf29ce484222325n
97 for (const byte of new TextEncoder().encode(key)) {
98 h ^= BigInt(byte)
99 h = (h * 0x100000001b3n) & 0xffffffffffffffffn
100 }
101 return h.toString(16).padStart(16, '0')
102}
103
104/** The root a session keeps for its whole life (register.js fixes it at the first look): { name, hash }. */
105export const rootOf = (path) => ({ name: cwdNameOf(path), hash: rootHashOf(path) })
106
107const ROOT_HASH = /^[0-9a-f]{16}$/
108
109// ---- The values
110
111const isNum = (n) => typeof n === 'number' && Number.isFinite(n)
112export const isText = (s) => typeof s === 'string' && s !== ''
113
114/** A request or a title cut to the length the meta keeps: blanks and line breaks as one blank, `…` at the cut. */
115export const promptLine = (text, max = LIST_LIMITS.title) => clip(text, max)
116
117/** A board's name as given (by Claude or the person): { name } (blanks folded, trimmed) or { error } (read by whoever gave it). */
118export function nameOf(value) {
119 if (typeof value !== 'string') return { error: 'name は文字列で指定してください' }
120 const name = value.replace(/\s+/g, ' ').trim()
121 if (name === '') return { error: 'name が空です。ボードの名前を指定してください(例: whiteboard 開発)' }
122 if ([...name].length > NAME_LIMIT) return { error: `name は ${NAME_LIMIT} 文字までです(受け取ったのは ${[...name].length} 文字)。短くしてください` }
123 return { name }
124}
125
126/** A name as names are compared: width and case folded. */
127export const nameKey = (name) => String(name ?? '').normalize('NFKC').replace(/\s+/g, ' ').trim().toLowerCase()
128
129/**
130 * A stored `bm:` value when it is sound, else null: { name, updatedAt, createdAt, count, cwdName,
131 * rootHash (null when it has none), lastTitle (null), lastSid (null), old }. A field it does not know, or one of the
132 * wrong type, is let go.
133 */
134export function readMeta(value) {
135 if (value == null || typeof value !== 'object' || Array.isArray(value)) return null
136 if (!isText(value.name) || !isNum(value.updatedAt)) return null
137 return {
138 name: value.name,
139 updatedAt: value.updatedAt,
140 createdAt: isNum(value.createdAt) ? value.createdAt : value.updatedAt,
141 count: Number.isSafeInteger(value.count) && value.count >= 0 ? value.count : 0,
142 cwdName: isText(value.cwdName) ? value.cwdName : UNKNOWN_FOLDER,
143 rootHash: typeof value.rootHash === 'string' && ROOT_HASH.test(value.rootHash) ? value.rootHash : null,
144 lastTitle: isText(value.lastTitle) ? value.lastTitle : null,
145 lastSid: isText(value.lastSid) ? value.lastSid : null,
146 old: value.old === true,
147 }
148}
149
150/**
151 * The meta to store after a change: `prev` (as readMeta answers it) with `patch` over it. A patch
152 * value that is undefined changes nothing, null removes the field; a null or false field is not kept.
153 */
154export function mergeMeta(prev, patch) {
155 const out = { ...(prev ?? {}) }
156 for (const [key, value] of Object.entries(patch ?? {})) {
157 if (value === undefined) continue
158 if (value === null) delete out[key]
159 else out[key] = value
160 }
161 for (const [key, value] of Object.entries(out)) if (value === null || value === false) delete out[key]
162 return out
163}
164
165/** A stored `attach:` value when it is sound ({ board, at }), else null. */
166export function readAttach(value) {
167 if (value == null || typeof value !== 'object' || !isText(value.board)) return null
168 return { board: value.board, at: isNum(value.at) ? value.at : 0 }
169}
170
171// ---- The time
172
173const dayStart = (ms) => {
174 const d = new Date(ms)
175 return new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime()
176}
177
178/** How many calendar days (local) `ms` lies before `now`: 0 today, 1 yesterday, negative for the future. */
179const daysBefore = (ms, now) => Math.round((dayStart(now) - dayStart(ms)) / DAY_MS)
180
181/** `10/08 23:01`, local. */
182export function stampOf(ms) {
183 const d = new Date(ms)
184 return String(d.getMonth() + 1).padStart(2, '0') + '/' + String(d.getDate()).padStart(2, '0') + ' ' + clockOf(ms)
185}
186
187/** `2026-10-08 23:01`, local. */
188export const fullStampOf = (ms) => new Date(ms).getFullYear() + '-' + stampOf(ms).replace('/', '-')
189
190/** `今日 14:05`, `昨日 14:05`, else `10/08 14:05` (local), as `now` sees the day. */
191export function dayStampOf(ms, now) {
192 const days = daysBefore(ms, now)
193 if (days === 0) return '今日 ' + clockOf(ms)
194 if (days === 1) return '昨日 ' + clockOf(ms)
195 return stampOf(ms)
196}
197
198/** A card's time: `14:05` on the day of `now`, else `10/08 14:05`. */
199export const cardStampOf = (ms, now) => (typeof now === 'number' && daysBefore(ms, now) !== 0 ? stampOf(ms) : clockOf(ms))
200
201// ---- The list
202
203/**
204 * One board as the lists show it: { id, name, updatedAt, createdAt, cwdName, rootHash, count,
205 * titles, lastTitle, old }. `titles` are every card's in the pane's order (the pinned first), each
206 * { title, pinned, progress } (progress: the checklist's `3/7`, '' for none); `count` is the cards the
207 * record holds. null when the meta is not sound (such a board is not listed).
208 */
209export function summarizeBoard(id, recordValue, metaValue) {
210 const meta = readMeta(metaValue)
211 if (meta === null) return null
212 const cards = orderedCards(boardCardsOf(recordValue))
213 return {
214 id,
215 name: meta.name,
216 updatedAt: meta.updatedAt,
217 createdAt: meta.createdAt,
218 cwdName: meta.cwdName,
219 rootHash: meta.rootHash,
220 count: cards.length,
221 titles: cards.map((c) => ({ title: clip(c.title, LIST_LIMITS.title), pinned: c.pinned === true, progress: taskProgress(c.body) })),
222 lastTitle: meta.lastTitle,
223 old: meta.old,
224 }
225}
226
227const byNewest = (a, b) => (b.updatedAt ?? -Infinity) - (a.updatedAt ?? -Infinity)
228
229/**
230 * The boards in the three groups the lists show, each newest first: `mine`, this project's (the
231 * same root hash) that are not old; `others`, the other projects' (or of no known project) that
232 * are not old; `old`, the old ones of any project. `except` (a board id, or null) is left out: the
233 * board the session is attached to, when it looks for another.
234 */
235export function groupBoards(rows, { rootHash = null, except = null } = {}) {
236 const shown = rows.filter((r) => r != null && r.id !== except)
237 const same = (r) => rootHash !== null && r.rootHash === rootHash
238 return {
239 mine: shown.filter((r) => !r.old && same(r)).sort(byNewest),
240 others: shown.filter((r) => !r.old && !same(r)).sort(byNewest),
241 old: shown.filter((r) => r.old).sort(byNewest),
242 }
243}
244
245/**
246 * The board named `name` (as nameKey compares names): of this project first, then of any; the
247 * newest of those. null when no board has the name.
248 */
249export function findByName(rows, name, rootHash = null) {
250 const key = nameKey(name)
251 const named = rows.filter((r) => r != null && nameKey(r.name) === key).sort(byNewest)
252 return named.find((r) => rootHash !== null && r.rootHash === rootHash) ?? named[0] ?? null
253}
254
255/** A board of this project, other than `id`, that already has the name: the person and Claude are asked for another. */
256export const nameTaken = (rows, name, rootHash, id) =>
257 rows.some((r) => r != null && r.id !== id && rootHash !== null && r.rootHash === rootHash && nameKey(r.name) === nameKey(name))
258
259/** A row's card titles in one line: the first `max` (`固定: ` before a pinned one, its progress after), then `ほか N 枚`. */
260export function titlesLine(row, max = LIST_LIMITS.titles) {
261 if (row.count === 0) return 'カードはまだありません'
262 const shown = row.titles.slice(0, max).map((t) => (t.pinned ? '固定: ' : '') + t.title + (t.progress !== '' ? ' ' + t.progress : ''))
263 const rest = row.count - shown.length
264 return shown.join(' ・ ') + (rest > 0 ? ` ほか ${rest} 枚` : '')
265}
266
267/** The warning about the store's size: only from half of the 4 MiB, else ''. */
268export function storeWarning(bytes) {
269 if (!(bytes > WARN_BYTES)) return ''
270 const mb = Math.round((bytes / MIB) * 10) / 10
271 return `保存できる量の半分を超えています(${mb.toFixed(1)} MB / ${STORE_MIB} MB)。これ以上増えると、${BOARD_NAME}を保存できなくなります`
272}
273hooks/migrate.js 97 lines1// Moving the boards of 0.10.0 and before to the named boards (pure: no $ here; register.js reads
2// the store, writes what this plans, reads it back and deletes the old keys).
3//
4// 0.10.0 kept one board per session: `board:<sessionId>` (the record, or up to 0.9.2 the cards as
5// a list), `meta:<sessionId>`, `seal:<sessionId>` (the board was taken over: read-only), and from
6// builds in between `rev:<sessionId>` and `removed:<sessionId>`; a 0.9.0 meta held the seal as
7// `handedOver`. Each old board with cards becomes one named board:
8// - its id is decided by the old session id (`s-<sessionId>`), so two sessions that start at
9// once and move the same board write the same keys with the same values;
10// - the cards, the revision, the removed cards and each card's previous version go as they are;
11// - the name is the session's title, else its first request, else the title of a pinned card (or
12// the first card), else `<date> のボード`;
13// - the project is the meta's root hash; a meta from before the hash (0.9.1 and before) whose
14// folder name is this session root's is taken as this project, any other as not known;
15// - a board that was read-only (sealed) is an old board: its cards were copied to another;
16// - the session it belonged to is attached to it, so a session open across the update goes on.
17// A board with no cards (and the keys left beside none) is not moved: its old keys are deleted.
18// One that cannot be read (not a record nor a list, or a list of which no card is sound) is left
19// as it is and reported.
20
21import { readBoard, isBoardRecord, boardRecord, orderedCards } from './board.js'
22import { clip, isText, NAME_LIMIT, UNKNOWN_FOLDER, stampOf } from './boards.js'
23
24/** The prefixes of the keys of 0.10.0 and before, each followed by a session id. */
25export const OLD_PREFIXES = ['board:', 'meta:', 'seal:', 'rev:', 'removed:']
26
27/** The old keys of the session `sid`, by kind. */
28export const oldKeysOf = (sid) => ({ board: 'board:' + sid, meta: 'meta:' + sid, seal: 'seal:' + sid, rev: 'rev:' + sid, removed: 'removed:' + sid })
29
30/** The id of the board moved from the session `sid`. */
31export const movedBoardId = (sid) => 's-' + sid
32
33const isNum = (n) => typeof n === 'number' && Number.isFinite(n)
34
35/** The session ids that have an old key, in the order their first key comes. */
36export function oldSessionsOf(keys) {
37 const out = []
38 for (const key of keys) {
39 if (typeof key !== 'string') continue
40 const prefix = OLD_PREFIXES.find((p) => key.startsWith(p) && key.length > p.length)
41 if (prefix === undefined) continue
42 const sid = key.slice(prefix.length)
43 if (!out.includes(sid)) out.push(sid)
44 }
45 return out
46}
47
48/** The name of a moved board: the title, the first request, a pinned or the first card's title, `<date> のボード`. */
49export function movedName(meta, cards, updatedAt) {
50 const first = orderedCards(cards)[0]
51 for (const candidate of [meta?.title, meta?.firstPrompt, first?.title]) {
52 const name = clip(candidate, NAME_LIMIT)
53 if (name !== '') return name
54 }
55 return `${stampOf(updatedAt).slice(0, 5)} のボード`
56}
57
58/**
59 * What to do with the old keys of the session `sid`. `values` holds what the store has under each
60 * of oldKeysOf(sid) (undefined for none); `root` this session's { name, hash }; `now` the time.
61 * { kind: 'move', id, record, meta, attach } write b:<id> (record; null for none), bm:<id> (meta),
62 * attach:<sid> (attach), then delete the old keys
63 * { kind: 'drop' } nothing to move: delete the old keys
64 * { kind: 'broken', reason } leave the old keys as they are
65 */
66export function planMove(sid, values, root, now) {
67 const raw = values.board
68 if (raw !== undefined && !isBoardRecord(raw) && !Array.isArray(raw)) return { kind: 'broken', reason: '形が読めません' }
69 const board = readBoard(raw, isBoardRecord(raw) ? {} : { rev: values.rev, removed: values.removed })
70 const rawCards = isBoardRecord(raw) ? raw.cards : Array.isArray(raw) ? raw : []
71 if (board.cards.length === 0 && rawCards.length > 0) return { kind: 'broken', reason: '読めるカードがありません' }
72 if (board.cards.length === 0) return { kind: 'drop' }
73 const meta = values.meta != null && typeof values.meta === 'object' && !Array.isArray(values.meta) ? values.meta : null
74 const newest = board.cards.reduce((m, c) => Math.max(m, c.updatedAt), -Infinity)
75 const updatedAt = isNum(meta?.updatedAt) ? meta.updatedAt : Number.isFinite(newest) ? newest : now
76 const cwdName = isText(meta?.cwdName) ? meta.cwdName : UNKNOWN_FOLDER
77 const rootHash = typeof meta?.rootHash === 'string' && /^[0-9a-f]{16}$/.test(meta.rootHash) ? meta.rootHash : meta !== null && cwdName === root.name ? root.hash : null
78 const sealed = (values.seal != null && typeof values.seal === 'object') || (meta?.handedOver != null && typeof meta.handedOver === 'object')
79 const lastTitle = isText(meta?.title) ? clip(meta.title) : isText(meta?.firstPrompt) ? `「${clip(meta.firstPrompt)}」` : null
80 return {
81 kind: 'move',
82 id: movedBoardId(sid),
83 record: boardRecord(board),
84 meta: {
85 name: movedName(meta, board.cards, updatedAt),
86 ...(rootHash !== null ? { rootHash } : {}),
87 cwdName,
88 createdAt: updatedAt,
89 updatedAt,
90 count: board.cards.length,
91 ...(lastTitle !== null ? { lastTitle, lastSid: sid } : {}),
92 ...(sealed ? { old: true } : {}),
93 },
94 attach: { board: movedBoardId(sid), at: now },
95 }
96}
97hooks/shelf.js 63 lines1// The boards as register.js finds them in $.store (pure: no $ here).
2//
3// register.js reads the store's keys and the values under the mod's own (`b:`, `bm:`, `attach:`,
4// and any key of 0.10.0 still there); this turns them into the list the pane and list_boards show
5// (the `boards` value of $.state: a row per board whose meta is sound) and the store's size.
6
7import { BOARD_PREFIX, META_PREFIX, ATTACH_PREFIX, boardKey, boardOfMetaKey, summarizeBoard } from './boards.js'
8import { OLD_PREFIXES } from './migrate.js'
9
10// Every prefix of the mod's keys
11const PREFIXES = [BOARD_PREFIX, META_PREFIX, ATTACH_PREFIX, ...OLD_PREFIXES]
12
13/** The `boards` value when nothing is known yet. */
14export const NO_BOARDS = { owner: '', rows: [], bytes: 0, sig: '' }
15
16/** Whether two state values are the same (compared as JSON), so a write is made only when the value changed. */
17export const isSame = (a, b) => JSON.stringify(a) === JSON.stringify(b)
18
19/** The JSON length of a stored value (0 for none). */
20export const sizeOf = (value) => (value === undefined ? 0 : JSON.stringify(value).length)
21
22/** Whether a key is one of the mod's own. */
23export const isMine = (key) => typeof key === 'string' && PREFIXES.some((p) => key.startsWith(p) && key.length > p.length)
24
25/** Whether a key is a board's meta. */
26export const isMetaKey = (key) => boardOfMetaKey(key) !== null
27
28/**
29 * A sign of the list from the store's `keys` and a Map of the metas' values (by key): it differs
30 * when a board came, went, or was written, renamed or retitled, so the list is read again only then.
31 */
32export function listSigOf(keys, metas) {
33 const parts = []
34 for (const key of keys) {
35 if (!isMetaKey(key)) continue
36 const m = metas.get(key)
37 parts.push([key, m?.updatedAt, m?.name, m?.count, m?.lastTitle, m?.old === true])
38 }
39 return JSON.stringify(parts)
40}
41
42/** Whether a key is read for the list: a board's record or its meta (the attachments are not). */
43export const isListed = (key) => typeof key === 'string' && (key.startsWith(BOARD_PREFIX) || key.startsWith(META_PREFIX))
44
45/**
46 * Every board from the store's `keys` and a Map of their `values` (by key): { rows (boards.js
47 * summarizeBoard, in the store's order), bytes: the JSON length of the mod's keys whose values were
48 * read, sig: listSigOf of the same metas }.
49 */
50export function scanBoards(keys, values) {
51 const rows = []
52 let bytes = 0
53 for (const key of keys) {
54 if (!isMine(key)) continue
55 bytes += sizeOf(values.get(key))
56 const id = boardOfMetaKey(key)
57 if (id === null) continue
58 const row = summarizeBoard(id, values.get(boardKey(id)), values.get(key))
59 if (row !== null) rows.push(row)
60 }
61 return { rows, bytes, sig: listSigOf(keys, values) }
62}
63hooks/catalog.js 110 lines1// What Claude reads about the boards (pure: no $ here): the answers of open_board, list_boards and
2// rename_board, and the refusal of a card tool while the session is attached to no board.
3
4import { groupBoards, titlesLine, fullStampOf, UNKNOWN_FOLDER } from './boards.js'
5
6/** What one list_boards answer holds at most, in characters. */
7export const CATALOG_LIMITS = { chars: 6000 }
8
9/** What a card tool answers while the session is attached to no board. */
10export const NOT_ATTACHED =
11 'このセッションは、まだどのボードにもつながっていません。先に open_board でボードにつないでください' +
12 '(name に、作業の内容が分かる短い名前を付ける。同じ名前のボードがあればそれにつながり、無ければ作る)。' +
13 'どのボードがあるかは list_boards で読めます。利用者が「◯◯のボードを使って」と言っていれば、その名前で open_board を呼びます。'
14
15/** What a write answers when another session wrote the same board between the read and the save. */
16export const CHANGED_MEANWHILE =
17 'ほかのセッションが同じボードを書き換えたので、書き込みませんでした。list_cards(titles_only か、前の rev を since に渡す)で読み直してから、もう一度書いてください。'
18
19/** The line put at the end of an answer cut to `max` characters. */
20export const truncatedLine = (max = CATALOG_LIMITS.chars) => `(${max} 文字を超えたので、ここで切りました)`
21
22/**
23 * The lines joined, at most `max` characters: whole lines while they fit, the first that does not
24 * cut to the room left (with …), then truncatedLine.
25 */
26export function capText(lines, max = CATALOG_LIMITS.chars) {
27 const whole = lines.join('\n')
28 if (whole.length <= max) return whole
29 const note = truncatedLine(max)
30 const budget = max - note.length - 1
31 const out = []
32 let used = 0
33 for (const line of lines) {
34 const sep = out.length > 0 ? 1 : 0
35 if (used + sep + line.length <= budget) {
36 out.push(line)
37 used += sep + line.length
38 continue
39 }
40 const room = budget - used - sep - 1
41 if (room > 0) {
42 let part = line.slice(0, room)
43 // Not half of a surrogate pair
44 if (/[\uD800-\uDBFF]$/.test(part)) part = part.slice(0, -1)
45 out.push(part + '…')
46 }
47 break
48 }
49 out.push(note)
50 return out.join('\n')
51}
52
53/** One board in list_boards: `- 「名前」 · 2026-10-13 14:05 · 5 枚 · 最後に書いたセッション: … · カード: …`, and the folder for another project's. */
54export function boardLine(row, { current = null, folder = false } = {}) {
55 const parts = [`- 「${row.name}」`]
56 if (row.id === current) parts.push('(このセッションがつないでいる)')
57 if (folder) parts.push(`フォルダ ${row.cwdName ?? UNKNOWN_FOLDER}`)
58 parts.push(typeof row.updatedAt === 'number' ? fullStampOf(row.updatedAt) : '時刻不明', `${row.count} 枚`)
59 if (row.lastTitle) parts.push(`最後に書いたセッション: ${row.lastTitle}`)
60 parts.push(`カード: ${titlesLine(row)}`)
61 return parts.join(' · ')
62}
63
64/**
65 * list_boards' answer: this project's boards newest first (the one attached marked), then how many
66 * the other projects and the old boards have; `all` lists those too, each with its folder.
67 */
68export function listBoardsText(rows, { rootHash, cwdName, current = null, all = false, max = CATALOG_LIMITS.chars } = {}) {
69 const { mine, others, old } = groupBoards(rows, { rootHash })
70 const where = typeof cwdName === 'string' && cwdName !== '' ? cwdName : UNKNOWN_FOLDER
71 const lines = []
72 if (mine.length === 0) lines.push(`このプロジェクト(${where})のボードはまだありません。open_board に名前を渡すと作れます`)
73 else {
74 lines.push(`このプロジェクト(${where})のボード(${mine.length} 件、新しい順)`)
75 for (const row of mine) lines.push(boardLine(row, { current }))
76 }
77 if (all) {
78 if (others.length > 0) {
79 lines.push(`ほかのプロジェクトのボード(${others.length} 件)`)
80 for (const row of others) lines.push(boardLine(row, { current, folder: true }))
81 }
82 if (old.length > 0) {
83 lines.push(`古いボード(${old.length} 件。前の版で別のセッションに引き継がれたもの)`)
84 for (const row of old) lines.push(boardLine(row, { current, folder: row.rootHash !== rootHash }))
85 }
86 } else if (others.length + old.length > 0) {
87 lines.push(`ほかに、ほかのプロジェクトのボード ${others.length} 件と古いボード ${old.length} 件があります(all: true で一覧)`)
88 }
89 if (current === null) lines.push('このセッションは、まだどのボードにもつながっていません。open_board に名前を渡すと、そのボードにつながります')
90 return capText(lines, max)
91}
92
93/** open_board's answer after attaching to a board that was there. */
94export function attachedText(row, { created = false, project = true } = {}) {
95 if (created) return `ボード「${row.name}」を作って、このセッションをつなぎました。カードは set_card で書きます`
96 const when = typeof row.updatedAt === 'number' ? `、最後の書き込み ${fullStampOf(row.updatedAt)}` : ''
97 const where = project ? '' : `(ほかのプロジェクト ${row.cwdName ?? UNKNOWN_FOLDER} のボード)`
98 const read = row.count > 0 ? '。中身は list_cards の titles_only で読めます' : ''
99 return `ボード「${row.name}」${where}につなぎました(カード ${row.count} 枚${when})${read}`
100}
101
102/** open_board's answer when the session is attached to that board already. */
103export const alreadyText = (row) => `このセッションは、すでにボード「${row.name}」につながっています(カード ${row.count} 枚)`
104
105/** rename_board's answer. */
106export const renamedText = (from, to) => (from === to ? `ボードの名前は、すでに「${to}」です` : `ボードの名前を「${from}」から「${to}」に変えました`)
107
108/** What open_board and rename_board answer when a name of this project is taken by another board (rename only). */
109export const takenText = (name) => `このプロジェクトには「${name}」という名前のボードがもうあります。別の名前にしてください(そのボードを使うなら open_board でその名前を渡す)`
110hooks/tools.js 183 lines1// The tools Claude calls (pure; how a call runs against the store is register.js's):
2// toolsFor, TOOLS the seven card tools: what each is told, its input, whether it writes, and what
3// it does to the cards of the board the session is attached to (board.js)
4// BOARD_TOOLS the three board tools (open_board, list_boards, rename_board): what each is
5// told and its input; register.js does their work
6
7import { LIMITS, applySet, applyEdit, applyAppend, applyRemove, applyClear, applyList, applyUndo, REMOVED_KEEP } from './board.js'
8import { NAME_LIMIT } from './boards.js'
9import { STYLE_INPUTS } from './style.js'
10
11// What every card tool's description starts with: the cards are on the board the session is attached to
12const ATTACHED_FIRST = 'このセッションがつないでいるボードが相手。どのボードにもつないでいなければ断られるので、先に open_board でつなぐ。'
13
14// The `style` input of set_card and edit_card: a plain string checked in board.js (no enum), so
15// the names listed here are the only ones Claude is told of
16const STYLE_DESCRIPTION = `カードの色: ${STYLE_INPUTS.join(' / ')}。none で色を外す。省略すると今のまま。色の名前だけで、色コードは使えない`
17
18/**
19 * The tools for a card limit (the setting `maxCards`, board.js maxCardsOf): the descriptions name
20 * it, and the calls that add a card are refused beyond it (the call's context carries it, register.js).
21 * With the default limit the descriptions are the same text as before the setting existed.
22 */
23export const toolsFor = (maxCards = LIMITS.cards) => ({
24 set_card: {
25 description:
26 'ボード(人が画面の右のパネルで見る作業メモ)に、カードを追加するか上書きする。会話のログに埋もれて流れてしまう情報を残すために使う: ' +
27 '進行中の手順やチェックリスト、並行して動かしている処理の状況、このセッションに関わる URL、決めたこと。' +
28 ATTACHED_FIRST +
29 '同じ id のカードは上書きされ(位置は変わらない)、状況が変わったら同じ id で更新する。1 カード 1 話題にして、本文は要点だけにする。' +
30 '本文の一部だけを変えるときは、全文を書き直さず edit_card(一部の置き換え)か append_card(末尾に足す)を使う。' +
31 '用が済んだカードは remove_card で消す。会話にもう書いたことを、ただ写すためには使わない。' +
32 'body は Markdown。```mermaid の基本的な flowchart / graph(subgraph の枠も。ただし subgraph 自体へ矢印を引くと図にならない)と、参加者と矢印だけの sequenceDiagram は図になる。それ以外の図(mermaid の別の種類、ASCII など)は、コードブロックとして読める形で表示される(描画はされない)。' +
33 '関係や流れは、箇条書きや表でも伝わる。' +
34 'pin: true は、人が常に見ていたいカード(今の手順の全体像、URL の一覧など)に使う。使いすぎない。固定したカードは一覧の上に並ぶ。' +
35 'style はカードの色(枠と見出し)。色に決まった意味はない。人に色を頼まれたときか、同じ話題のカードを同じ色にそろえるときだけ付ける。' +
36 `上限: ${maxCards} 枚、title ${LIMITS.title} 文字、body ${LIMITS.body} 文字、id は英数字と _ - の ${LIMITS.id} 文字まで。` +
37 '会話の圧縮などで内容を思い出せないときは list_cards で読み返す。',
38 inputSchema: {
39 type: 'object',
40 properties: {
41 id: { type: 'string', description: `カードの名前。短い英数字と _ -(例: plan, urls, jobs)。${LIMITS.id} 文字まで` },
42 title: { type: 'string', description: `カードの見出し。${LIMITS.title} 文字まで` },
43 body: { type: 'string', description: `本文(Markdown)。${LIMITS.body} 文字まで。空でもよい` },
44 pin: { type: 'boolean', description: 'true で先頭に固定、false で固定を外す。省略すると今のまま(新しいカードは固定なし)' },
45 style: { type: 'string', description: STYLE_DESCRIPTION },
46 },
47 required: ['id', 'title', 'body'],
48 },
49 writes: true,
50 apply: (cards, e, now, context) => applySet(cards, e, now, context),
51 },
52 edit_card: {
53 description:
54 'ボードのカードの本文の一部だけを書き換える。「手順の 1 項目を済みにする」「リンクの 1 つを直す」のように、数行しか変えないときに使う(全文を書き直すより軽い)。' +
55 'find(本文の中にある文字列。改行を含んでよい)を replace に置き換える。find は、本文の中にちょうど 1 箇所だけ一致する長さにする' +
56 '(0 箇所なら見つからなかった、2 箇所以上なら曖昧だとして断られる)。同じ文字列をすべて置き換えるなら all: true。replace を空にすると find の部分を消す。' +
57 'title、固定、カードの位置は変わらない。カードが無ければ set_card で作る。全体を書き直すときは set_card。' +
58 `置き換えたあとの本文が ${LIMITS.body} 文字を超える場合も断られる。` +
59 '色だけを変えるときは id と style だけを渡す(find と replace は要らない、本文を送り直さない)。find も style もない呼び出しは断られる。',
60 inputSchema: {
61 type: 'object',
62 properties: {
63 id: { type: 'string', description: '書き換えるカードの id' },
64 find: { type: 'string', description: '本文の中で置き換える文字列(空でない、改行を含んでよい)。1 箇所だけに一致する長さにする。style だけを変えるときは省く' },
65 replace: { type: 'string', description: '置き換える文字列。空にすると find の部分を消す。find があるときは必須' },
66 all: { type: 'boolean', description: 'true で、find に一致する箇所をすべて置き換える。省略すると、一致が 1 箇所のときだけ置き換える' },
67 style: { type: 'string', description: STYLE_DESCRIPTION },
68 },
69 required: ['id'],
70 },
71 writes: true,
72 apply: (cards, e, now) => applyEdit(cards, e, now),
73 },
74 append_card: {
75 description:
76 'ボードのカードの本文の末尾に、文を足す。「URL を 1 つ足す」「経過を 1 行足す」のように、一部だけ変えるときに使う(全文を書き直すより軽い)。' +
77 '本文が空でなければ、間に改行を 1 つ入れて、新しい行として足す。title、固定、カードの位置は変わらない。' +
78 `カードが無ければ set_card で作る。全体を書き直すときは set_card。足したあとの本文が ${LIMITS.body} 文字を超える場合は断られる。`,
79 inputSchema: {
80 type: 'object',
81 properties: {
82 id: { type: 'string', description: '足すカードの id' },
83 text: { type: 'string', description: '本文の末尾に足す文(Markdown)' },
84 },
85 required: ['id', 'text'],
86 },
87 writes: true,
88 apply: (cards, e, now) => applyAppend(cards, e, now),
89 },
90 remove_card: {
91 description: 'ボードのカードを id で消す。済んだ手順、終わった処理、古くなった URL のカードは、残さず消す。id が無ければ、その旨を返す。',
92 inputSchema: { type: 'object', properties: { id: { type: 'string', description: '消すカードの id' } }, required: ['id'] },
93 writes: true,
94 apply: (cards, e) => applyRemove(cards, e),
95 },
96 clear: {
97 description: 'ボードのカードを全部消す。人から「ボードを空にして」と頼まれたときや、作業が丸ごと終わったときに使う。1 枚だけ消すなら remove_card。',
98 inputSchema: { type: 'object', properties: {} },
99 writes: true,
100 apply: (cards) => applyClear(cards),
101 },
102 list_cards: {
103 description:
104 'ボードのカードを読む。引数なしは全カードの id・title・body を全文で返すので重い。' +
105 'まず titles_only: true(目次: id・title・本文の文字数)か query(検索)で探し、必要なカードだけ id で読む。' +
106 '利用者が「ボードの手順 3 は?」のようにボードの内容を尋ねたときも、この順で探す。' +
107 '会話の圧縮のあとなどに、何を書いたか思い出すためにも使う。固定したカードが先に並び、固定のカードには pinned: true が付く。色のあるカードには style が付く。' +
108 'id が最優先で、あれば他は無視する(そのカード 1 枚の id・title・body)。' +
109 'query は空白で分けた語をすべて含むカードを返す(id・title・body のどれか、大文字小文字は区別せず、日本語は部分一致)。各カードに、一致した行の番号(本文の 1 始まり。title か id だけの一致は 0)と、その行の先頭 120 文字を最大 5 件付ける。titles_only も一緒にあれば、その一致の行は付けず title だけにする。' +
110 '結果の 1 行目は rev: N(ボードの版。書き換えのたびに増える)。読んだ rev を覚えておき、次は since にその rev を渡すと、その後に書き換えられたカードだけと、今ある全カードの ids が返る(ids に無いカードは消された)。全部を読み直さずに済む。' +
111 'since は titles_only・query と組み合わせられる(変わったカードの中だけ)。会話の圧縮のあとや rev が分からないときは、titles_only から読む。' +
112 ATTACHED_FIRST +
113 'ほかのボードの中身を読むときは、list_boards で探して、open_board でそのボードにつなぎ直す。',
114 inputSchema: {
115 type: 'object',
116 properties: {
117 titles_only: {
118 type: 'boolean',
119 description:
120 'true で各カードの id・title・chars(本文の文字数)だけを返す。本文に - [ ] / - [x] のチェックリストがあるカードには tasks(済んだ数/全体、例 "3/5")も付く。' +
121 'しばらく書き換えのない固定でないカードには stale: true が付く(消すかどうかは利用者に確かめる)。目次として軽く読む',
122 },
123 id: { type: 'string', description: 'このカード 1 枚の id・title・body だけを返す' },
124 query: { type: 'string', description: '検索語。空白で分けた語をすべて含むカードを返す(大文字小文字は区別しない、日本語は部分一致)' },
125 since: { type: 'integer', description: '前に読んだときの rev。それより後に書き換えられたカードだけと、今ある全カードの ids を返す' },
126 },
127 },
128 writes: false,
129 apply: (cards, e, _now, context) => applyList(cards, e, context),
130 },
131 undo_card: {
132 description:
133 'ボードのカードの最後の書き換えを 1 つ戻す。利用者に「さっきの書き換えを戻して」と頼まれたときや、自分がカードを間違えて上書き・編集したと気づいたときに使う。' +
134 'set_card・edit_card・append_card(固定や色の変更も)で書き換えたカードは、title・body・固定・色が 1 つ前の版に戻る(カードの位置は変わらない)。' +
135 '戻せるのは 1 段だけで、続けてもう一度呼ぶと、戻す前の版にやり直す。' +
136 `remove_card や clear で消したカードも、最近消した ${REMOVED_KEEP} 枚まで戻せる(clear で消したときは、最後に書いたものから ${REMOVED_KEEP} 枚)。戻したカードは末尾に並び、戻した直後にもう一度呼ぶと、また消す(やり直し)。` +
137 `カードが ${maxCards} 枚あるときは、消したカードは戻せない。`,
138 inputSchema: { type: 'object', properties: { id: { type: 'string', description: '戻すカードの id' } }, required: ['id'] },
139 writes: true,
140 apply: (cards, e, now, context) => applyUndo(cards, e, now, context),
141 },
142})
143
144/** The tools with the default card limit. */
145export const TOOLS = toolsFor()
146
147/** The three board tools: what each is told and its input (register.js runs them). */
148export const BOARD_TOOLS = {
149 open_board: {
150 description:
151 'ボード(人が画面の右のパネルで見る作業メモ)に、このセッションをつなぐ。ボードはセッションに属さず、名前で呼ぶ。新しいセッションはどのボードにもつながっていないので、カードを書く・読む前に一度呼ぶ。' +
152 'name と同じ名前のボードがあれば(このプロジェクトのものを優先、大文字小文字や全角半角は区別しない)それにつなぎ、無ければその名前で新しく作ってつなぐ。' +
153 '名前は作業の内容が分かる短い言葉にする(例: whiteboard 開発、CI の修正)。プロジェクト全体で 1 枚にするか、話題ごとに分けるかは、利用者の頼み方に合わせる。' +
154 '利用者が「◯◯のボードを使って」と言ったときや、引き継ぎの文にボードの名前が書いてあるときは、その名前を渡す。迷うときは先に list_boards で今あるボードを見る。' +
155 `ほかのボードにつなぎ直すこともできる(同じボードに、ほかのセッションも同時につながっていてよい)。名前は ${NAME_LIMIT} 文字まで。`,
156 inputSchema: {
157 type: 'object',
158 properties: { name: { type: 'string', description: `つなぐ(無ければ作る)ボードの名前。${NAME_LIMIT} 文字まで` } },
159 required: ['name'],
160 },
161 },
162 list_boards: {
163 description:
164 'ボードの一覧を読む。このプロジェクトのボードを新しい順に、名前・最後の書き込みの日時・枚数・最後に書いたセッションの題・カードの題(固定が先、チェックリストの進み具合つき)で並べる。' +
165 'このセッションがつないでいるボードには印が付く。ほかのプロジェクトのボードと古いボード(前の版で別のセッションに引き継がれたもの)は件数だけで、all: true なら一覧に入る。' +
166 'どのボードにつなぐか決めるときや、「前に書いたボードはある?」と聞かれたときに使う。中身を読むには open_board でつないでから list_cards。',
167 inputSchema: {
168 type: 'object',
169 properties: { all: { type: 'boolean', description: 'true で、ほかのプロジェクトのボードと古いボードも並べる' } },
170 },
171 },
172 rename_board: {
173 description:
174 `このセッションがつないでいるボードの名前を変える。利用者に頼まれたときや、話題が変わって名前が合わなくなったときに使う。${NAME_LIMIT} 文字まで。` +
175 'このプロジェクトのほかのボードと同じ名前にはできない。つないでいなければ断られる。',
176 inputSchema: {
177 type: 'object',
178 properties: { name: { type: 'string', description: `新しい名前。${NAME_LIMIT} 文字まで` } },
179 required: ['name'],
180 },
181 },
182}
183hooks/view-state.js 68 lines1// The small state values as $.state holds them (`attached`, `view`, `boards`, `root`, `about`): what
2// a drawing or a press reads of each, a value of an older shape filled with the defaults (pure)
3
4import { NO_BOARDS } from './shelf.js'
5
6// The view with no board opened in the list, the list of other boards closed, its groups folded,
7// and the name not being edited; the fields it leaves out are kept by a patch
8export const NO_VIEW = { pick: '', shown: false, groups: { others: false, old: false }, rename: false }
9
10const objectOr = (value, fallback) => (value != null && typeof value === 'object' && !Array.isArray(value) ? value : fallback)
11const textOr = (value, fallback) => (typeof value === 'string' && value !== '' ? value : fallback)
12
13// `attached`: the board the session `owner` is attached to ({ board, name, stamp }, board null for
14// none, stamp the meta's time of the last write as read), or null when the value is another
15// session's or not there (the store is read then)
16export function attachedOf(value, me) {
17 const v = objectOr(value, null)
18 if (v === null || v.owner !== me) return null
19 return { board: textOr(v.board, null), name: textOr(v.name, ''), stamp: typeof v.stamp === 'number' ? v.stamp : 0 }
20}
21
22// `view`: the board opened in the list, whether the list is shown over the cards, the groups
23// unfolded, whether the name is being edited (and the editor's key), with the fold choices
24// (fold.js), the search field's text and key (search.js) and the order (order.js) riding along,
25// so a patch of the other fields keeps them
26export function viewOf(value) {
27 const v = objectOr(value, {})
28 const g = objectOr(v.groups, {})
29 return {
30 pick: typeof v.pick === 'string' ? v.pick : '',
31 shown: v.shown === true,
32 groups: { others: g.others === true, old: g.old === true },
33 rename: v.rename === true,
34 renameGen: Number.isSafeInteger(v.renameGen) && v.renameGen >= 0 ? v.renameGen : 0,
35 folds: objectOr(v.folds, null),
36 filter: objectOr(v.filter, null),
37 order: objectOr(v.order, null),
38 searchGen: Number.isSafeInteger(v.searchGen) && v.searchGen >= 0 ? v.searchGen : 0,
39 }
40}
41
42// `boards`: the list (shelf.js scanBoards' rows), the store's size and the sign of the metas read;
43// a row of an older shape is left out rather than drawn wrong
44export function boardsOf(value, me) {
45 const v = objectOr(value, null)
46 if (v === null || !Array.isArray(v.rows)) return NO_BOARDS
47 return {
48 owner: textOr(v.owner, ''),
49 rows: v.rows.filter((r) => r != null && typeof r.id === 'string' && typeof r.name === 'string' && Array.isArray(r.titles)),
50 bytes: typeof v.bytes === 'number' ? v.bytes : 0,
51 sig: typeof v.sig === 'string' ? v.sig : '',
52 }
53}
54
55// `root`: the session root as the session `owner` first saw it ({ name, hash }), or null
56export function rootValueOf(value, me) {
57 const v = objectOr(value, null)
58 if (v === null || v.owner !== me || typeof v.name !== 'string') return null
59 return { name: v.name, hash: typeof v.hash === 'string' ? v.hash : null }
60}
61
62// `about`: what the session `owner` is about ({ title, firstPrompt }, each null when not known)
63export function aboutOf(value, me) {
64 const v = objectOr(value, null)
65 if (v === null || v.owner !== me) return { title: null, firstPrompt: null }
66 return { title: textOr(v.title, null), firstPrompt: textOr(v.firstPrompt, null) }
67}
68hooks/store.js 16 lines1// The queue that keeps a read-change-write of the store or of $.state from overlapping another's
2// (pure: no $ here; the calls are register.js's).
3
4/** A queue: the calls run one at a time, in the order they came; one that fails does not stop the next. */
5export function makeQueue() {
6 let queue = Promise.resolve()
7 return (fn) => {
8 const run = queue.then(fn)
9 queue = run.then(
10 () => undefined,
11 () => undefined,
12 )
13 return run
14 }
15}
16hooks/guide.js 104 lines1// The guide that tells a Claude in a fresh session the board exists (pure: no $ here; register.js
2// hooks it up). Both texts are handed to the model with the person's prompt as prompt.submit
3// `context` blocks, which the person does not see; the prompt itself is not touched.
4//
5// short the fixed text below, handed over with the person's prompt whenever the model's
6// conversation does not hold it: the first prompt of a session, and the first after
7// /clear or a compaction (hasGuideIn). It never holds a card, a count, a time or anything
8// else of the session, and once handed over it stays where it is in the conversation.
9// full short, plus a few lines on which tool to use for what, on a turn whose message holds
10// one of the keywords, and at most once in GUIDE_EVERY turns.
11// off nothing added.
12//
13// The person sees the board as 「ホワイトボード」 (board.js BOARD_NAME); the texts say ボード, which
14// that name holds, and the keyword ボード matches it too (keywords match as parts of the message).
15
16/** The guide's text: fixed. Keep it to a sentence or two. */
17export const GUIDE_SHORT =
18 '作業ボード(mcp__whiteboard__*)があります。使う前に open_board で名前のボードにつなぐ。流れる手順・URL・状況はカードに残し、読むなら list_cards を titles_only か query で。使い方は ToolSearch で whiteboard を引く。'
19
20/** The few lines of `full`: which tool for what, and how to pin. Fixed too. */
21export const GUIDE_FULL =
22 'ボードの使い分け: つないでいなければ先に open_board。全文を書き直すのは set_card。一部だけ変えるときは edit_card(本文中の find を replace に置き換える。一致が 1 箇所のときだけ)、末尾に足すだけなら append_card。' +
23 '読むときは list_cards を titles_only か query で呼び、必要なカードだけ id で読む。' +
24 '人が常に見ていたいカード(今の手順の全体像、URL の一覧)だけ pin: true にし、使いすぎない。済んだカードは remove_card で消す。'
25
26/** The most turns `full` waits before it adds the lines again: once in this many. */
27export const GUIDE_EVERY = 5
28
29export const GUIDE_MODES = ['off', 'short', 'full']
30
31/** The setting `guide`: one of the three; anything else is `short`. */
32export const guideModeOf = (options) => (GUIDE_MODES.includes(options?.guide) ? options.guide : 'short')
33
34/** The setting `guideKeywords`, "a,b" (a full-width comma or 、 splits too): the words, blanks dropped, lower-cased. */
35export function keywordsOf(options) {
36 const raw = typeof options?.guideKeywords === 'string' ? options.guideKeywords : 'ボード,whiteboard'
37 return raw
38 .split(/[,,、]/)
39 .map((w) => w.trim().toLowerCase())
40 .filter((w) => w !== '')
41}
42
43/**
44 * The turns' counter of `full`. `next(prompt)` is called for each message the person sends and
45 * answers the lines to hand over, or '' for none: the message must hold a keyword (any case),
46 * and the lines must not have been given in the last GUIDE_EVERY - 1 turns before it.
47 */
48export function makeGuideTurns(keywords) {
49 const lines = GUIDE_FULL
50 let turn = 0
51 let last = null
52 return (prompt) => {
53 turn++
54 const text = typeof prompt === 'string' ? prompt.toLowerCase() : ''
55 if (!keywords.some((w) => text.includes(w))) return ''
56 if (last !== null && turn - last < GUIDE_EVERY) return ''
57 last = turn
58 return lines
59 }
60}
61
62// ---- The model's conversation, looked at (register.js lookConversation)
63
64/**
65 * Whether the conversation (`$.session.messages({ as: 'api' })`) holds the guide's text in a
66 * user message: handed over earlier and not yet compacted away or cleared.
67 */
68export const hasGuideIn = (messages) =>
69 Array.isArray(messages) &&
70 messages.some((m) => m?.role === 'user' && Array.isArray(m.content) && m.content.some((b) => b?.type === 'text' && typeof b.text === 'string' && b.text.includes(GUIDE_SHORT)))
71
72// How much of the first answer stands for the conversation's start
73const HEAD_CHARS = 200
74
75/**
76 * What stands for the start of the conversation: the first assistant message's text, its tool
77 * calls' ids and its thinking's signatures, cut short; null when no answer is in it yet. The
78 * engine puts a user message's reminders into user messages, never into an answer, so this stays
79 * the same until the start is replaced (a compaction) or the conversation starts over.
80 */
81export function headOf(messages) {
82 if (!Array.isArray(messages)) return null
83 const first = messages.find((m) => m?.role === 'assistant')
84 if (!first) return null
85 const blocks = Array.isArray(first.content) ? first.content : []
86 const part = (b) =>
87 b?.type === 'text' ? String(b.text ?? '') : b?.type === 'tool_use' ? 'tool:' + String(b.id ?? '') : b?.type === 'thinking' ? 'th:' + String(b.signature ?? '').slice(0, 40) : ''
88 return blocks.map(part).join('|').slice(0, HEAD_CHARS)
89}
90
91/**
92 * The `look` state value after a look at the conversation of the session `owner`: its head now,
93 * and whether a compaction waits for the board's table of contents. A compaction is a start that
94 * changed while the conversation goes on (not empty); it stays waiting until the prompt that
95 * takes it clears it. An empty conversation (a fresh one, after /clear) starts over.
96 */
97export function lookAfter(value, owner, messages) {
98 const prev = value != null && typeof value === 'object' && value.owner === owner ? value : null
99 if (!Array.isArray(messages) || messages.length === 0) return { owner, head: null, compacted: false }
100 const head = headOf(messages)
101 const replaced = prev !== null && typeof prev.head === 'string' && head !== prev.head
102 return { owner, head, compacted: prev?.compacted === true || replaced }
103}
104hooks/pane.js 491 lines1// What the pane and the band draw (pure: no $ here; register.js reads the state, hands the values
2// over with the actions the Buttons run, and registers the hooks).
3//
4// The pane holds the cards, the pinned ones first and each group in the order they were added: a
5// title on a line of its own, then a dim line with the checklist's progress (`3/5`, `5/5 済`; only
6// for a body with task-list items), 新規 or 更新 for a card Claude changed since the person's latest
7// prompt (recent.js; a changed card also gets `+3 −1 行` after it), 固定, 古い and the time of the
8// last write (never the card's id, which is Claude's name for it), and the body as Markdown (handed
9// over as written, except that a mermaid fence mermaid.js can draw is an Svg). No button changes a
10// card: the person reads, Claude writes. A long card is folded to its first lines with a secondary
11// button [続きを表示(残り N 行)], an opened one has [畳む] after its body (fold.js; the view
12// only). With 6 cards or more, a search field over them narrows the cards drawn to those holding
13// every word typed, drawn whole while it does (search.js; the view only). With 3 cards or more, a
14// secondary button beside the count switches the order to the latest write first, the pinned ones still
15// first (order.js; the view only). With none, a note says
16// so. A card with a single-colour
17// style draws its border (bold) and title in that colour (the palette, style.js), with the setting
18// `styleMarks` a shape of its own before the title (style.js SHAPES); the rainbow draws a
19// stripe of seven hues across its top and its title one character a hue, the border as any card's.
20// A stale card (stale.js: not pinned, not marked this turn, not written for `staleHours` hours) has
21// a dim 古い before the time on its meta line, its title dim instead of its colour and its border
22// dimmed (the rainbow's stripe is left out); it is only pointed out, never removed.
23//
24// The cards are those of the board the session is attached to (boards.js), under the board's name
25// as one Markdown heading (escaped, so it shows as typed); at the very bottom one row of the
26// board's tools ([別のボードへ], [名前を変える], [読み直す]), always shown. A session attached to no board has the list
27// instead of the cards: this project's boards newest first (name and time, the session that wrote
28// it last, the card titles, [つなぐ] and [中身を見る]), the other projects' and the old boards folded
29// under a line with [表示], [読み直す] at the bottom. A board's id is never shown. What an action did
30// is a toast (register.js), never a line in the pane. A line when the store is over half full.
31//
32// The band is one short line, the card count (or, attached to no board, a hint to choose one) with
33// a button that opens the pane, drawn at 0 cards too. Cards changed since the person's latest
34// prompt add a dim `· 更新 N枚` after the count, stale cards a dim `· 古い N枚` after that. With a
35// pinned card (and the setting `bandTitle` on), the title of the pinned card written last follows
36// them, in its colour, with its checklist's progress. On a narrow line the title goes first, then
37// 古い, then 更新; the hint stays with the label.
38//
39// Nothing here calls $.ui.invalidate or draws on a timer (in the desktop app every redraw
40// rebuilds every mod's drawing, other mods' open panes included).
41
42import { BOARD_NAME, fitBand, fitBandTitle, fitBandRecent, fitBandStale, taskProgress } from './board.js'
43import { markLabel, diffLine } from './recent.js'
44import { isFoldable, isFolded, foldCut, foldLabel, revOfCard } from './fold.js'
45import { mermaidSvg, splitFences } from './mermaid.js'
46import { RAINBOW, DEFAULT_PALETTE, colorOf, shapeOf } from './style.js'
47import { dayStampOf, cardStampOf, storeWarning, groupBoards, titlesLine, UNKNOWN_FOLDER } from './boards.js'
48import { isStaleCard, STALE_LABEL } from './stale.js'
49import { SEARCH_PLACEHOLDER, SEARCH_CLEAR, SEARCH_NONE, searchCount, hasSearch, hasInput, isFiltering, filterCards, inputKey } from './search.js'
50import { ORDER_LABELS, hasOrder, sortCards } from './order.js'
51
52// The pane's title is the board's name (board.js BOARD_NAME), given where register.js opens it
53export const PANE_ID = 'whiteboard'
54
55// Element keys allow a plain set of characters; a card's id is checked to, but not trusted to
56const keyOf = (prefix, id) => prefix + '-' + String(id).replace(/[^A-Za-z0-9_-]/g, '_')
57
58// The cells across a drawing: the site's own width, else what the surface measured; null when
59// neither is known
60export function widthOf(e) {
61 const n = e.props?.bodyColumns
62 if (typeof n === 'number' && n > 0) return n
63 const v = e.viewport?.columns
64 return typeof v === 'number' && v > 0 ? v : null
65}
66
67// A card's body. The Markdown element shows a mermaid fence as a code block, so on a surface with
68// Svg the fences mermaid.js can draw become pictures, the rest of the body staying Markdown as
69// written (a fence it cannot draw too). With none drawn the body is one Markdown, untouched.
70function drawBody(ui, card, view) {
71 const { Box, Markdown, Svg } = ui
72 const whole = () => Markdown({ key: keyOf('body', card.id), text: card.body })
73 if (view.surface === 'terminal' || typeof Svg !== 'function' || !/mermaid/i.test(card.body)) return whole()
74 const items = []
75 let drawn = 0
76 const addText = (text) => {
77 if (items.at(-1)?.text !== undefined) items[items.length - 1].text += '\n' + text
78 else items.push({ text })
79 }
80 for (const piece of splitFences(card.body)) {
81 const picture = piece.type === 'mermaid' ? mermaidSvg(piece.source) : null
82 if (picture) {
83 items.push({ picture })
84 drawn++
85 } else {
86 addText(piece.type === 'mermaid' ? piece.raw : piece.text)
87 }
88 }
89 if (drawn === 0) return whole()
90 // About the cells of the pane less its borders and padding, at 8 pixels a cell
91 const room = view.columns ? Math.max(160, (view.columns - 8) * 8) : 560
92 const children = items.flatMap((item, n) => {
93 if (item.text !== undefined) return item.text.trim() === '' ? [] : [Markdown({ key: keyOf('body', card.id) + '-' + n, text: item.text })]
94 const { picture } = item
95 const scale = Math.min(1, room / picture.width)
96 return [
97 Box({
98 key: keyOf('diagram', card.id) + '-' + n,
99 children: [Svg({ source: picture.source, alt: picture.alt, width: Math.round(picture.width * scale), height: Math.round(picture.height * scale) })],
100 }),
101 ]
102 })
103 return Box({ key: keyOf('body', card.id), flexDirection: 'column', rowGap: 1, children })
104}
105
106// The rainbow's title: one hue a character, cycling through RAINBOW; blanks take none
107function rainbowTitle(ui, title) {
108 const { Text } = ui
109 let n = 0
110 const parts = [...title].map((ch) => (/\s/.test(ch) ? ch : Text({ color: RAINBOW[n++ % RAINBOW.length], children: [ch] })))
111 return Text({ bold: true, wrap: 'wrap', children: parts })
112}
113
114// The rainbow's stripe: seven Boxes side by side, one fixed hue each
115function rainbowStripe(ui, card) {
116 const { Box, Text } = ui
117 return Box({
118 key: keyOf('stripe', card.id),
119 flexDirection: 'row',
120 width: '100%',
121 children: RAINBOW.map((hex, i) => Box({ key: keyOf('stripe', card.id) + '-' + i, flexGrow: 1, height: 1, backgroundColor: hex, children: [Text({ children: [' '] })] })),
122 })
123}
124
125// A long card's button: [続きを表示(残り N 行)] when folded, [畳む] when open; it only changes the view.
126// Secondary, not plain: a plain Button is drawn as bare text, which does not look pressable.
127// The key says what the press does (`fold-open-<id>` / `fold-close-<id>`), so a press aimed at a
128// drawing that has since been replaced (press-guard.js runs the latest drawing's closure under the
129// same key) finds no handler once the card has turned the other way, rather than undoing the intent.
130function drawFoldButton(ui, card, folded, remaining, onFold) {
131 const { Box, Button } = ui
132 return Box({
133 key: keyOf('fold-row', card.id),
134 flexDirection: 'row',
135 children: [Button({ key: keyOf(folded ? 'fold-open' : 'fold-close', card.id), label: foldLabel(folded, remaining), variant: 'secondary', onPress: () => onFold(card.id, folded, revOfCard(card)) })],
136 })
137}
138
139function drawCard(ui, card, view, onFold) {
140 const { Box, Text } = ui
141 const rainbow = card.style === 'rainbow'
142 const color = colorOf(card.style, view.palette ?? DEFAULT_PALETTE)
143 // Changed since the person's latest prompt (recent.js): a dim word, and the lines it moved
144 const mark = view.marks?.[card.id]
145 const marked = markLabel(mark)
146 const diff = diffLine(mark)
147 // Not written for a while (stale.js): a dim 古い, the title dim instead of its colour, the border dimmed, no stripe
148 const stale = isStaleCard(card, view.now, view.staleHours, mark !== undefined)
149 // The setting `styleMarks`: the style's shape before the title, in the title's colour (dim when stale)
150 const shape = view.shapes === true ? shapeOf(card.style) : null
151 const tint = stale ? { dimColor: true } : color !== null ? { color } : {}
152 const words = shape !== null ? [Text({ ...tint, children: [shape] }), ' ' + card.title] : [card.title]
153 const title = stale
154 ? Text({ bold: true, dimColor: true, wrap: 'wrap', children: words })
155 : rainbow
156 ? rainbowTitle(ui, card.title)
157 : Text({ bold: true, wrap: 'wrap', ...(color !== null ? { color } : {}), children: words })
158 // The checklist's progress, dim like the rest of the meta line and never coloured by the style
159 const progress = taskProgress(card.body)
160 // The meta line under the title: dim words, the time last. The card's id is Claude's name for
161 // it and is not shown.
162 const meta = [
163 ...(progress !== '' ? [Text({ dimColor: true, children: [progress] })] : []),
164 ...(marked !== '' ? [Text({ dimColor: true, children: [marked] })] : []),
165 ...(diff !== '' ? [Box({ key: keyOf('diff', card.id), children: [Text({ dimColor: true, children: [diff] })] })] : []),
166 ...(card.pinned === true ? [Text({ dimColor: true, children: ['固定'] })] : []),
167 ...(stale ? [Text({ dimColor: true, children: [STALE_LABEL] })] : []),
168 Text({ dimColor: true, children: [cardStampOf(card.updatedAt, view.now)] }),
169 ]
170 const children = [
171 // A stale card shows no stripe: its colours are let go like the title's
172 ...(rainbow && !stale ? [rainbowStripe(ui, card)] : []),
173 // The header in two lines: the title alone (wrapping), then the meta line
174 Box({
175 key: keyOf('head', card.id),
176 flexDirection: 'column',
177 children: [
178 Box({ key: keyOf('title', card.id), children: [title] }),
179 Box({ key: keyOf('meta', card.id), flexDirection: 'row', flexWrap: 'wrap', columnGap: 2, children: meta }),
180 ],
181 }),
182 ]
183 // A drawable mermaid fence counts as one line where the pane draws pictures (drawBody)
184 const lines = { pictures: view.surface !== 'terminal' && typeof ui.Svg === 'function' }
185 // While the search field narrows the cards, every card drawn is whole and has no fold button: the
186 // words may have matched in the lines a fold leaves out, and a folded card would hide why it is
187 // there. The person's fold choices are kept and come back once the filter is cleared.
188 if (!view.filtering && isFoldable(card.body, lines)) {
189 // Folded: the first lines as fold.js cuts them (never none: such a card does not fold), then the button
190 const folded = isFolded(card, view.folds?.[card.id], mark !== undefined, lines)
191 const cut = folded ? foldCut(card.body, lines) : null
192 children.push(drawBody(ui, folded ? { ...card, body: cut.text } : card, view))
193 children.push(drawFoldButton(ui, card, folded, folded ? cut.remaining : 0, onFold))
194 } else if (card.body.trim() !== '') {
195 children.push(drawBody(ui, card, view))
196 }
197 // A single-colour card has a bold border in its colour (dimmed when stale), so it stands out from
198 // the thin round dim border of a card with no style and of the rainbow
199 const border = color !== null ? { borderStyle: 'bold', borderColor: color, ...(stale ? { borderDimColor: true } : {}) } : { borderStyle: 'round', borderDimColor: true }
200 return Box({ key: keyOf('card', card.id), flexDirection: 'column', width: '100%', ...border, paddingX: 1, children })
201}
202
203// The cards' blocks: a note and a box each, or what to ask for while there are none
204function drawCards(ui, cards, view, actions) {
205 const { Box, Text } = ui
206 if (cards.length === 0) {
207 return [
208 Box({ key: 'empty', flexDirection: 'column', children: [
209 Text({ wrap: 'wrap', children: ['まだ何も書かれていません'] }),
210 Text({ dimColor: true, wrap: 'wrap', children: [`Claude に「${BOARD_NAME}に手順を書いて」のように頼むと、ここにカードとして残ります`] }),
211 ] }),
212 ]
213 }
214 // The fold's choice keeps only the cards on the board (fold.js foldsAfter), every one of them
215 // even while the search field leaves some out, so a filter never lets a choice go
216 const ids = cards.map((c) => c.id)
217 const onFold = (id, open, rev) => actions.fold?.(id, open, rev, ids)
218 // The search field (search.js): with enough cards and an Input the surface draws; the words
219 // apply only while it is drawn
220 const searching = hasSearch(cards, ui, view.surface)
221 const text = searching ? view.filter ?? '' : ''
222 const filtering = isFiltering(text)
223 const shown = filtering ? filterCards(cards, text) : cards
224 // The order button (order.js): with enough cards; with fewer the added order is drawn
225 const ordering = hasOrder(cards)
226 const by = ordering && view.order === 'updated' ? 'updated' : 'added'
227 const count = Text({ dimColor: true, wrap: 'wrap', children: [`${cards.length} 件`] })
228 return [
229 Box({
230 key: 'about',
231 flexDirection: 'row',
232 flexWrap: 'wrap',
233 columnGap: 2,
234 alignItems: 'center',
235 children: ordering ? [count, drawOrderButton(ui, by, actions)] : [count],
236 }),
237 ...(searching ? [drawSearch(ui, view.searchGen, filtering ? { total: cards.length, shown: shown.length } : null, actions)] : []),
238 ...(filtering && shown.length === 0 ? [Box({ key: 'search-none', children: [Text({ wrap: 'wrap', children: [SEARCH_NONE] })] })] : []),
239 ...sortCards(shown, by).map((card) => drawCard(ui, card, { ...view, filtering }, onFold)),
240 ]
241}
242
243// The order button: its label names the order drawn now, a press switches to the other. Secondary,
244// as the fold's: a plain Button is drawn as bare text, which does not look pressable. The key
245// says what the press does (`order-updated` switches to the newest first, `order-added` back), so
246// a press aimed at a replaced drawing finds no handler once the order has turned, as the fold's.
247function drawOrderButton(ui, by, actions) {
248 const { Button } = ui
249 const to = by === 'updated' ? 'added' : 'updated'
250 return Button({ key: 'order-' + to, label: ORDER_LABELS[by], variant: 'secondary', onPress: () => actions.order?.(to) })
251}
252
253// The search field over the cards; while it narrows (`count` { total, shown }), a dim line with
254// the counts and a plain button that clears it. The field types live (onInput, every change) and
255// Enter does the same (onSubmit, which an Input must have). The field keeps its own text (no
256// `value`); [絞り込みを解く] moves `gen` on, so the field is drawn under a new key, empty (search.js).
257function drawSearch(ui, gen, count, actions) {
258 const { Box, Text, Button, Input } = ui
259 const onText = (value) => actions.filter?.(value)
260 const children = [Input({ key: inputKey(gen), placeholder: SEARCH_PLACEHOLDER, onInput: onText, onSubmit: onText })]
261 if (count !== null) {
262 children.push(
263 Box({
264 key: 'search-status',
265 flexDirection: 'row',
266 flexWrap: 'wrap',
267 columnGap: 2,
268 alignItems: 'center',
269 children: [
270 Text({ dimColor: true, children: [searchCount(count.total, count.shown)] }),
271 Button({ key: 'search-clear', label: SEARCH_CLEAR, variant: 'secondary', onPress: () => actions.clearFilter?.() }),
272 ],
273 }),
274 )
275 }
276 return Box({ key: 'search', flexDirection: 'column', children })
277}
278
279// ---- The board's name, and the list of boards
280
281const boxed = (key, children) => ({ key, flexDirection: 'column', rowGap: 1, width: '100%', borderStyle: 'round', borderDimColor: true, paddingX: 1, children })
282
283// A text as Markdown shows it literally: line breaks and blanks as one blank, every ASCII
284// punctuation mark escaped with a backslash (CommonMark lets any of them be escaped)
285export const markdownLiteral = (text) => String(text ?? '').replace(/\s+/g, ' ').replace(/[!-/:-@[-`{-~]/g, (ch) => '\\' + ch)
286
287// A heading (`## …`): the one way the pane has to draw text larger than the cards' (Text has no size)
288const heading = (ui, key, text) => ui.Markdown({ key, text: '## ' + markdownLiteral(text) })
289
290// The name of the board the session is attached to: one heading above the cards
291function drawBoardName(ui, attached) {
292 return heading(ui, 'board-name', attached.name)
293}
294
295// One board in the list: its name and time, the session that wrote it last, its card titles (all
296// of them once opened), [つなぐ] and [中身を見る]. `folder` adds the folder for another project's.
297function drawBoardRow(ui, row, { open, folder, now }, actions) {
298 const { Box, Text, Button } = ui
299 const head = [
300 Text({ bold: true, wrap: 'wrap', children: [row.name] }),
301 ...(folder ? [Text({ dimColor: true, wrap: 'wrap', children: [row.cwdName] })] : []),
302 Text({ dimColor: true, children: [typeof row.updatedAt === 'number' ? dayStampOf(row.updatedAt, now) : '時刻不明'] }),
303 ]
304 const children = [Box({ key: keyOf('row-head', row.id), flexDirection: 'row', flexWrap: 'wrap', columnGap: 2, children: head })]
305 if (row.lastTitle) children.push(Box({ key: keyOf('row-about', row.id), children: [Text({ dimColor: true, wrap: 'wrap', children: [`最後に書いたセッション: ${row.lastTitle}`] })] }))
306 if (open && row.titles.length > 0) {
307 children.push(
308 Box({
309 key: keyOf('row-titles', row.id),
310 flexDirection: 'column',
311 children: row.titles.map((t) => Text({ wrap: 'wrap', children: [`・${t.title}${t.pinned ? '(固定)' : ''}${t.progress !== '' ? ' ' + t.progress : ''}`] })),
312 }),
313 )
314 } else {
315 children.push(Box({ key: keyOf('row-titles', row.id), children: [Text({ dimColor: true, wrap: 'wrap', children: [titlesLine(row)] })] }))
316 }
317 const buttons = [Button({ key: keyOf('attach', row.id), label: 'つなぐ', variant: 'secondary', onPress: () => actions.attach?.(row.id) })]
318 if (row.count > 0) buttons.push(Button({ key: keyOf('peek', row.id), label: open ? '閉じる' : '中身を見る', variant: 'secondary', onPress: () => actions.peek?.(row.id) }))
319 children.push(Box({ key: keyOf('row-buttons', row.id), flexDirection: 'row', columnGap: 1, children: buttons }))
320 return Box({ ...boxed(keyOf('row', row.id), children), rowGap: 0 })
321}
322
323// A folded group (the other projects' boards, the old boards): its name and count with [表示] /
324// [隠す], and its rows while it is shown
325function drawGroup(ui, name, label, rows, open, { now, pick, folder }, actions) {
326 const { Box, Text, Button } = ui
327 if (rows.length === 0) return []
328 const line = Box({
329 key: 'group-' + name,
330 flexDirection: 'row',
331 flexWrap: 'wrap',
332 columnGap: 2,
333 alignItems: 'center',
334 children: [Text({ wrap: 'wrap', children: [`${label}(${rows.length})`] }), Button({ key: 'show-' + name, label: open ? '隠す' : '表示', variant: 'secondary', onPress: () => actions.group?.(name, !open) })],
335 })
336 return [line, ...(open ? rows.map((r) => drawBoardRow(ui, r, { open: pick === r.id, folder: folder(r), now }, actions)) : [])]
337}
338
339/**
340 * The list of boards to attach to: this project's newest first, then the other projects' and the
341 * old boards, each folded under a line with [表示]. `except` (a board id or null) is left out: the
342 * board the session is attached to. `reload` puts [読み直す] at its bottom (attached to none; when
343 * attached it is in the board's tools). Answers the blocks.
344 */
345function drawChooser(ui, { rows, root, except, title, view, now, reload = false }, actions) {
346 const { Box, Text } = ui
347 const groups = groupBoards(rows, { rootHash: root?.hash ?? null, except })
348 const where = root?.name ?? UNKNOWN_FOLDER
349 // Attached to none the list is the whole pane, and its title a heading; in the board's tools, a bold line
350 const blocks = [reload ? heading(ui, 'chooser-heading', title) : Text({ bold: true, wrap: 'wrap', children: [title] })]
351 if (groups.mine.length > 0) {
352 blocks.push(Text({ wrap: 'wrap', children: [`このプロジェクト(${where})のボード`] }))
353 for (const r of groups.mine) blocks.push(drawBoardRow(ui, r, { open: view.pick === r.id, folder: false, now }, actions))
354 } else {
355 blocks.push(Text({ wrap: 'wrap', children: [`このプロジェクト(${where})のボードは、まだありません`] }))
356 }
357 blocks.push(...drawGroup(ui, 'others', 'ほかのプロジェクトのボード', groups.others, view.groups.others, { now, pick: view.pick, folder: () => true }, actions))
358 blocks.push(...drawGroup(ui, 'old', '古いボード', groups.old, view.groups.old, { now, pick: view.pick, folder: (r) => r.rootHash !== (root?.hash ?? null) }, actions))
359 blocks.push(Text({ dimColor: true, wrap: 'wrap', children: [`新しい${BOARD_NAME}は、Claude に「◯◯のボードを作って」と頼むとできます`] }))
360 if (reload) blocks.push(Box({ key: 'chooser-foot', flexDirection: 'row', children: [reloadButton(ui, actions)] }))
361 return [Box({ key: 'chooser', flexDirection: 'column', rowGap: 1, width: '100%', children: blocks })]
362}
363
364// [読み直す]: the board and the list from the store now (another session may have written them)
365const reloadButton = (ui, actions) => ui.Button({ key: 'reload', label: '読み直す', variant: 'secondary', onPress: () => actions.reload?.() })
366
367// The board's tools, at the very bottom of an attached pane: one row of three secondary buttons,
368// always shown, each saying what it does: [別のボードへ], [名前を変える] (left out where no Input is
369// drawn) and [読み直す]. [名前を変える] puts an Input in the row's place (drawn under a new key each
370// time, so it starts empty) with [やめる]; [別のボードへ] puts the list of the other boards there,
371// with [やめる] at its bottom. A rename that is done, or a board attached to, brings the row back.
372function drawTools(ui, attached, view, canInput, chooser, actions) {
373 const { Box, Button, Input } = ui
374 const cancel = (key, onPress) => Box({ key: key + '-row', flexDirection: 'row', children: [Button({ key, label: 'やめる', variant: 'secondary', onPress })] })
375 if (view.rename && canInput) {
376 const key = 'rename-input' + (view.renameGen > 0 ? '-' + view.renameGen : '')
377 return [
378 Box({
379 key: 'board-tools',
380 flexDirection: 'column',
381 rowGap: 1,
382 width: '100%',
383 children: [Input({ key, label: '新しい名前', placeholder: attached.name, submitLabel: '変える', onSubmit: (value) => actions.rename?.(value) }), cancel('rename-cancel', () => actions.renameCancel?.())],
384 }),
385 ]
386 }
387 if (view.shown) {
388 return [Box(boxed('board-tools', [...chooser(attached.board, '切り替えるボードを選ぶ'), cancel('switch-cancel', () => actions.toggleShown?.())]))]
389 }
390 return [
391 Box({
392 key: 'board-tools',
393 flexDirection: 'row',
394 flexWrap: 'wrap',
395 columnGap: 1,
396 children: [
397 Button({ key: 'switch', label: '別のボードへ', variant: 'secondary', onPress: () => actions.toggleShown?.() }),
398 ...(canInput ? [Button({ key: 'rename', label: '名前を変える', variant: 'secondary', onPress: () => actions.renameOpen?.() })] : []),
399 reloadButton(ui, actions),
400 ],
401 }),
402 ]
403}
404
405/**
406 * The pane's tree. `data` is what register.js read from $.state: { attached ({ board, name }, board
407 * null for a session attached to no board), cards, boards: { rows, bytes } (view-state.js boardsOf),
408 * root ({ name, hash } or null), view (view-state.js viewOf), now, palette (style.js), marks
409 * (recent.js: the cards changed since the person's latest prompt, by id), folds (fold.js: the
410 * person's fold choices, by id), filter (search.js: the search field's text, '' for none), order
411 * (order.js: 'added' or 'updated'), staleHours (stale.js: the setting, 0 for off), shapes (style.js:
412 * the setting `styleMarks`) }; `where` is { surface, columns }; `actions` the Buttons' work.
413 *
414 * Only what the board is for: attached, the board's name as one heading, then the cards, and at
415 * the very bottom one row of the board's tools, each saying what it does (drawTools). Not attached: the list, to choose
416 * one ([つなぐ]), with [読み直す] at its bottom. What an action did is said in a toast, never in the
417 * pane. The one line kept beside the cards is the warning that the store is over half full: it is
418 * a lasting state the person has to act on, not a report. It comes above the tools.
419 */
420export function drawPane(ui, data, where, actions) {
421 const { attached, cards, boards, root = null, view, now, palette, marks = {}, folds = {}, filter = '', order = 'added', staleHours = 0, shapes = false } = data
422 const { Box, Text } = ui
423 const warning = storeWarning(boards.bytes)
424 const canInput = hasInput(ui, where.surface)
425 const isAttached = attached !== null && attached.board !== null
426 const chooser = (except, title) => drawChooser(ui, { rows: boards.rows, root, except, title, view, now, reload: except === null }, actions)
427 const warn = warning !== '' ? [Box({ key: 'store-warning', children: [Text({ dimColor: true, wrap: 'wrap', children: [warning] })] })] : []
428 const children = isAttached
429 ? [
430 drawBoardName(ui, attached),
431 ...drawCards(ui, cards, { ...where, now, palette, marks, folds, filter, order, searchGen: view.searchGen ?? 0, staleHours, shapes }, actions),
432 ...warn,
433 ...drawTools(ui, attached, view, canInput, chooser, actions),
434 ]
435 : [...chooser(null, 'つなぐボードを選ぶ'), ...warn]
436 return ui.Box({ key: 'whiteboard', flexDirection: 'column', rowGap: 1, paddingX: 1, width: '100%', children })
437}
438
439// The band's "· title progress": the title in the card's single colour (the rainbow and no style
440// plain), the progress dim. The only part that may shrink: its Text cuts at the edge with an
441// ellipsis should the estimate of the line's room be short.
442function drawBandTitle(ui, part, color, shape) {
443 const { Box, Text } = ui
444 const tint = color !== null ? { color } : {}
445 return Box({
446 key: 'board-title',
447 flexShrink: 1,
448 minWidth: 0,
449 children: [
450 Text({
451 wrap: 'truncate-end',
452 children: [
453 '· ',
454 // The setting `styleMarks`: the style's shape before the title, in the same colour
455 ...(shape !== null ? [Text({ ...tint, children: [shape + ' '] })] : []),
456 Text({ ...tint, children: [part.title] }),
457 ...(part.progress !== '' ? [Text({ dimColor: true, children: [' ' + part.progress] })] : []),
458 ],
459 }),
460 ],
461 })
462}
463
464/**
465 * The band's tree; `hint` is '' or the few words after the count; `onOpen` is what [開く] does.
466 * `card` is the pinned card whose title follows the counts (board.js bandCard), or null; `palette`
467 * gives its colour (style.js); `changed` is how many cards on the board were changed since the
468 * person's latest prompt (a dim `· 更新 N枚` after the label); `stale` how many cards are stale
469 * (stale.js: a dim `· 古い N枚` after it). The room goes to the label and [開く], then 更新, then
470 * 古い, then the title, which is the first to go. `shapes` is the setting `styleMarks` (the
471 * style's shape before the title).
472 */
473export function drawBand(ui, surface, columns, count, hint, onOpen, { card = null, palette = DEFAULT_PALETTE, changed = 0, stale = 0, shapes = false } = {}) {
474 const { Box, Text, Button } = ui
475 const fit = fitBand({ surface, columns, count, hint })
476 // The room goes to 更新 first, then 古い, then the title (board.js)
477 const recent = fitBandRecent({ surface, columns, count, hint, changed })
478 const old = fitBandStale({ surface, columns, count, hint, recent, stale })
479 const shape = card !== null && shapes === true ? shapeOf(card.style) : null
480 const part = card !== null ? fitBandTitle({ surface, columns, count, hint, title: card.title, progress: taskProgress(card.body), recent, old, shape: shape ?? '' }) : null
481 const children = []
482 if (fit.hasLabel) children.push(Box({ key: 'board-label', flexShrink: 0, children: [Text({ children: [fit.label] })] }))
483 if (recent !== '') children.push(Box({ key: 'board-recent', flexShrink: 0, children: [Text({ dimColor: true, children: [recent] })] }))
484 if (old !== '') children.push(Box({ key: 'board-stale', flexShrink: 0, children: [Text({ dimColor: true, children: [old] })] }))
485 if (part !== null) children.push(drawBandTitle(ui, part, colorOf(card.style, palette), shape))
486 children.push(
487 Box({ key: 'board-open-slot', flexShrink: 0, children: [Button({ key: 'board-open', label: fit.buttonLabel, variant: 'secondary', onPress: onOpen })] }),
488 )
489 return Box({ key: 'whiteboard-band', flexDirection: 'row', flexWrap: 'nowrap', columnGap: 1, alignItems: 'center', children })
490}
491hooks/recent.js 192 lines1// Which cards Claude changed since the person's latest prompt (pure: no $ here).
2//
3// The person's prompts count turns: each one moves the counter on (`turn` in $.state, with the
4// session it belongs to). A tool write that changes a card marks it for the current turn: a card
5// that was not on the board before the turn's first write to it is new, any other changed. A
6// changed card also keeps the body it had before that first write (its base), so the line count
7// sums the whole turn, not only the last write. The marks live in the load and are mirrored into
8// $.state (`recent`, without the bases) for the drawings; the drawings show them only while their
9// turn is the current one, so the next prompt clears them without a write. A counter that is not
10// there (never set, or lost) means no marks: nothing is marked and nothing is shown.
11
12import { sameContent } from './board.js'
13
14// The origins of a prompt.submit that count as the person's own prompt: the composer, the Remote
15// Control bridge (a phone or web client), and an SDK host's turn. A prompt the person does not see
16// as typed (`isMeta`) never counts. Whether the desktop app's prompts arrive as `composer` or `sdk`
17// is not verified; both are accepted so that they count either way.
18const PERSON_ORIGINS = new Set(['composer', 'bridge', 'sdk'])
19
20/**
21 * Whether a prompt.submit is the person's own prompt (not a notification, a peer's message, a
22 * schedule or a plugin's). One rule for every use: the turns of the marks, the first request kept
23 * for the meta, and the guide. An input without an origin (none the engine raises) counts.
24 */
25export const isPersonPrompt = (e) => e != null && e.isMeta !== true && (e.origin == null || PERSON_ORIGINS.has(e.origin.kind))
26
27const isTurn = (n) => Number.isSafeInteger(n) && n > 0
28
29/** The current turn of the `turn` state value for the session `owner`; null when there is none. */
30export function readTurn(value, owner) {
31 if (value == null || typeof value !== 'object' || value.owner !== owner || !isTurn(value.n)) return null
32 return value.n
33}
34
35/** The `turn` state value after a prompt: one more than this session's, 1 when there is none. */
36export const turnAfter = (value, owner) => ({ owner, n: (readTurn(value, owner) ?? 0) + 1 })
37
38// ---- The line count
39
40// A body's lines; a last newline ends the last line rather than starting an empty one
41function linesOf(text) {
42 const s = String(text ?? '')
43 if (s === '') return []
44 const lines = s.split(/\r?\n/)
45 if (lines.at(-1) === '') lines.pop()
46 return lines
47}
48
49// Above this many cells (lines before x lines after, once the common ends are cut), the lines are
50// matched as multisets rather than in order
51const LCS_CELLS = 250_000
52
53// The length of the longest common subsequence of two lists of lines
54function lcsLength(a, b) {
55 const row = new Array(b.length + 1).fill(0)
56 for (let i = 1; i <= a.length; i++) {
57 let diag = 0
58 for (let j = 1; j <= b.length; j++) {
59 const up = row[j]
60 row[j] = a[i - 1] === b[j - 1] ? diag + 1 : Math.max(row[j], row[j - 1])
61 diag = up
62 }
63 }
64 return row[b.length]
65}
66
67// How many lines the two lists share, order not looked at
68function sharedCount(a, b) {
69 const counts = new Map()
70 for (const line of a) counts.set(line, (counts.get(line) ?? 0) + 1)
71 let shared = 0
72 for (const line of b) {
73 const n = counts.get(line) ?? 0
74 if (n > 0) {
75 shared++
76 counts.set(line, n - 1)
77 }
78 }
79 return shared
80}
81
82/**
83 * The lines added and removed from `before` to `after`: { added, removed }. A changed line counts
84 * as one removed and one added. The lines the two share at their start and end are cut first, the
85 * rest matched in order (a longest common subsequence), or as multisets when that would be large.
86 */
87export function lineDiff(before, after) {
88 const a = linesOf(before)
89 const b = linesOf(after)
90 let start = 0
91 while (start < a.length && start < b.length && a[start] === b[start]) start++
92 let endA = a.length
93 let endB = b.length
94 while (endA > start && endB > start && a[endA - 1] === b[endB - 1]) {
95 endA--
96 endB--
97 }
98 const x = a.slice(start, endA)
99 const y = b.slice(start, endB)
100 const common = x.length === 0 || y.length === 0 ? 0 : x.length * y.length <= LCS_CELLS ? lcsLength(x, y) : sharedCount(x, y)
101 return { added: y.length - common, removed: x.length - common }
102}
103
104// ---- The marks: { [card id]: { base, added, removed } }, base null for a new card (no counts),
105// else the card as it was before the turn's first write to it ({ title, body, pinned, style })
106
107// A card's version as a base keeps it
108const baseOf = (c) => ({ title: c.title, body: c.body, pinned: c.pinned === true, style: c.style ?? null })
109
110/**
111 * The marks after a write that turned `before` into `after`: each card that is new or says
112 * something else than it did is marked. A card marked earlier in the turn keeps its base, so its
113 * counts compare the body before the turn's first write with the body now, and a card that says
114 * again what its base said (undone back to the turn's start) loses its mark; a base not known
115 * (undefined, marks taken back from the state after a reload) falls back to the card before this
116 * write. Marks of cards that are gone stay (a card removed and brought back in the same turn keeps
117 * its base). The same object when nothing changed.
118 */
119export function markWrite(marks, before, after) {
120 const was = new Map(before.map((c) => [c.id, c]))
121 let next = marks
122 const put = (id, mark) => {
123 if (next === marks) next = { ...marks }
124 if (mark === undefined) delete next[id]
125 else next[id] = mark
126 }
127 for (const c of after) {
128 const old = was.get(c.id)
129 if (old && sameContent(old, c)) continue
130 const had = marks[c.id]
131 const base = had !== undefined && had.base !== undefined ? had.base : old ? baseOf(old) : null
132 if (base !== null && sameContent(base, c)) {
133 if (had !== undefined) put(c.id, undefined)
134 continue
135 }
136 put(c.id, base === null ? { base: null } : { base, ...lineDiff(base.body, c.body) })
137 }
138 return next
139}
140
141/** The marks as $.state keeps them for the drawings: { kind: 'new' } or { kind: 'changed', added, removed }, no bases. */
142export function shownMarks(marks) {
143 const out = {}
144 for (const [id, m] of Object.entries(marks)) out[id] = m.base === null ? { kind: 'new' } : { kind: 'changed', added: m.added, removed: m.removed }
145 return out
146}
147
148const isCount = (n) => Number.isSafeInteger(n) && n >= 0
149
150// A state mark that is well-formed, else null
151function readMark(m) {
152 if (m == null || typeof m !== 'object') return null
153 if (m.kind === 'new') return { kind: 'new' }
154 if (m.kind === 'changed' && isCount(m.added) && isCount(m.removed)) return { kind: 'changed', added: m.added, removed: m.removed }
155 return null
156}
157
158/**
159 * The marks of the `recent` state value when it is this session's and of the turn `turn`, else {}.
160 * Entries of another shape are left out.
161 */
162export function marksOf(value, owner, turn) {
163 if (turn === null || value == null || typeof value !== 'object' || value.owner !== owner || value.turn !== turn) return {}
164 const cards = value.cards
165 if (cards == null || typeof cards !== 'object' || Array.isArray(cards)) return {}
166 const out = {}
167 for (const [id, m] of Object.entries(cards)) {
168 const mark = readMark(m)
169 if (mark !== null) out[id] = mark
170 }
171 return out
172}
173
174/** The load's marks taken back from the state (after a reload): new ones keep base null, changed ones an unknown base. */
175export function seedMarks(shown) {
176 const out = {}
177 for (const [id, m] of Object.entries(shown)) out[id] = m.kind === 'new' ? { base: null } : { base: undefined, added: m.added, removed: m.removed }
178 return out
179}
180
181/** How many of the cards on the board are marked. */
182export const markedCount = (marks, cards) => (Array.isArray(cards) ? cards.filter((c) => marks[c?.id] !== undefined).length : 0)
183
184/** The header's word for a mark: 新規 or 更新; '' for none. */
185export const markLabel = (mark) => (mark == null ? '' : mark.kind === 'new' ? '新規' : '更新')
186
187/** The line under the header of a changed card, `+3 −1 行`; '' for a new card, none, or a change that moved no line. */
188export function diffLine(mark) {
189 if (mark?.kind !== 'changed' || mark.added + mark.removed === 0) return ''
190 return `+${mark.added} −${mark.removed} 行`
191}
192