xmuse collaboration panel: assistants, threads and messages from the project's hub, in a right-side pane (T8)

在 Claude Code 里聚合 OpenCode、dsh、agy 等本地 agent,一起干活。
你可以让 Claude 当主控,把活派给其他 agent 去干;也可以让几个 agent 平等地讨论同一个方案,互相挑毛病。不管哪种方式,agent 之间的决定、假设和待决问题都由 xmuse 的信息协作层管理:谁该知道什么、什么时候知道。每个 agent 仍在自己原生的环境里运行,协作界面是 Claude 桌面 App 里的一个面板。
v1(房间运行时)已废弃,代码留在
v1分支。
几个独立的 agent 一起干活时,难点在上下文:每个 agent 该知道什么、什么时候知道。约定改了,没收到的那个会照旧干;全量转发聊天记录,上下文又会越涨越长。xmuse 把精力放在这件事上,而不去接管 agent 本身:会话、工具、权限、上下文压缩,都由各家自己管。
具体做法:
kind=decision|assumption|question),新条目可以用 supersedes 取代旧的。条目按话题归属,只发给相关的成员。flowchart TB
USER["用户"] --> PANEL["xmuse 面板<br/>(Claude Code 插件)"]
CC["Claude Code<br/>(主控)"] --- PANEL
subgraph HELPERS["助手"]
OC["OpenCode"]
AGY["agy"]
DSH["dsh"]
end
CC -->|"MCP 工具"| HUB
PANEL -->|"HTTP"| HUB
subgraph HUB["hub (本地, 每个项目一个)"]
MAIL["消息、话题"]
ENG["唤醒引擎"]
ALIGN["约定条目"]
DB[("hub.db (SQLite)")]
end
ENG -->|"各家适配器"| HELPERS
HUB -.->|"可选"| MO["MemoryOS"]
hub 是一个本地 Python 进程,所有状态存在一个 SQLite 文件里。agent 通过一组 MCP 工具收发消息、申报约定。助手由 hub 按各家的方式叫醒:OpenCode 走它的后台服务接口,agy 和 dsh 走无界面模式。Claude 保留自己的全部能力,hub 不驱动它。
MemryOS-lite 可以作为可选的记忆层接入,不配置就不用。
需要 Linux 或 WSL、uv、Node 22,以及要接入的 agent 的 CLI。
git clone https://github.com/iiyazu/Cross-Muse.git && cd Cross-Muse
scripts/bootstrap.sh # 安装依赖并自检,可重复执行
然后在 Claude Code 的终端会话里安装面板插件:
/plugin install xmuse --marketplace <integrations/xmuse-panel 的路径>
打开面板,点"开房间",再在顶部添加助手。也可以不用面板,直接用命令行:
export PATH="$PWD/hub/.venv/bin:$PATH"
xmuse init ~/work/demo && cd ~/work/demo
xmuse agent add oc-1 --vendor opencode
xmuse hub start
xmuse send oc-1 "实现 calc.sub,写完交给 claude 复核"
Windows 加 WSL 的细节见 hub/README.md 和 面板说明。
| 路径 | 内容 |
|---|---|
hub/ | hub 和命令行 xmuse;src/xmuse/adapters/ 是各家适配器 |
shim/ | MCP 垫片,把工具调用转给 hub |
integrations/xmuse-panel/ | Claude Code 面板插件 |
integrations/dsh-bundle/ | dsh 桌面端插件包 |
skill/、templates/ | 写进项目的协作技能和 AGENTS.md 段落 |
tests/ | hub 测试,用假 agent 回放录制的输出 |
experiments/、docs/design/ | 实验、设计稿和报告 |
用机制探针验证:在一个小的模拟项目里每次只测一项功能,结果由程序判定,每格 10 次。
数据和效度讨论见 HANDOFF-BASE-REPORT.zh.md 的"S 系列阶段分析"一节和 M2b 实验报告,探针设计见 XMUSE2-PROBES.zh.md。
hub/.venv/bin/python -m pytest tests -q -p no:cacheprovider
(cd integrations/dsh-bundle && npm test)
claude plugin test integrations/xmuse-panel
hooks/register.tsx 2541 lines1import { atom, read, update } from 'claude-code'
2import type { Register } from 'claude-code'
3
4import type { ConnInfo } from '../types'
5import type { Pal, RailItem, Tone } from './logic'
6import {
7 C_AMBER, C_BLUE, C_GREEN, C_ORANGE, C_RED, agoText, approvalHasAlways, approvalKindLabel, approvalText, approvalsOf, avatarSvg, backoffMs,
8 bigInputPlan, buildRows, buildSay, buildWakePrompt, displayName, doneInfo, expandNewlines, fmtClock, hardBreaks, isAutoForward,
9 isDoneMsg, isLoopbackUrl, isToClaude, matchHubs, maxWakeId, membersOf, messagesFor, noiseSummary, parseHubs, parseMentions, replyLabel,
10 statusOf, summaryLine, railOf, activeTabOf, dmThreadId, roomSvg, toLabel, toolCount, unreadThreadsFor, wakeCandidates, zhNotice,
11 workingMembers, doneLine, finishedMembers, toPosix, structOf,
12 badgeOf, completeMention, dayLabel, foldLong, isLightTheme, memberColor, mentionCandidates, mixHex, palOf, rowAt, splitBlocks,
13 trailingMention, vendorKey, canCompact, ctxLevel, ctxText, mergeCompactInstructions, hubStartScript,
14 TONES, ctxBarSvg, noiseTitle, noiseTone, freshMessage, revealSteps, shortModel, softWrap, clip,
15} from './logic'
16
17// xmuse panel (slice T8d): read-only view of the project's hub plus sending. Design: docs/design/XMUSE2-T8.zh.md §2.1, §3.
18// Windowing rule from experiments: `$` may only be passed to functions declared at the top level of this file.
19// T8e: approval cards, working strip, add-assistant, wake Claude. T8f: typing effect and done line. H1: open-room button.
20// T8 wrap-up: stop, retract, compaction (context size per member, the 压缩 button, the session.compact hook), the hub
21// found through WSL instead of fixed paths, and a known room's hub started by itself after a reboot.
22// TODO: "open in terminal" (H7).
23// DEV (./dev.ts) is false in the repository and true in a dev mod folder. It switches the dev-only things: LOAD_MARK,
24// FOCUS_MARK and REBIND_MARK (written for diagnosis), the ROOM_OVERRIDE fallback and DEV_AVATAR_DIR.
25import { DEV, DEV_AVATAR_DIR, FOCUS_MARK, LOAD_MARK, REBIND_MARK, ROOM_OVERRIDE } from './dev'
26
27const PANE = 'xmuse'
28// The registry directory (hubs.json, sidebar.key, install.json) and how to start a hub are found once through WSL and
29// kept in the store: see hubSetup. Nothing machine-specific is written here.
30const STORE_SETUP = 'setup' // HubSetup
31const STORE_KNOWN = 'knownRooms' // string[]: room directories this panel has joined; one found down gets its hub started
32const STORE_CONN = 'conn' // key prefix, 'conn:<room dir>' (connKey): { url, token, member }, the operator token from /v1/join
33// The sidebar's Claude joins as the room's coordinator: its id is the room's `host` in hubs.json.
34const STORE_AUTO = 'autoWake' // boolean: submit a turn when a message for the panel arrives (default off)
35const STORE_SEEN = 'wakeSeen' // number: highest message id already handled (submitted or baseline)
36
37const connAtom = atom({ plugin: 'xmuse', key: 'conn' } as const, { phase: 'idle', error: '' } as ConnInfo)
38const viewAtom = atom({ plugin: 'xmuse', key: 'view' } as const, null as any)
39const tabAtom = atom({ plugin: 'xmuse', key: 'tab' } as const, '#room') // the open rail entry: '#room', a dm: thread id, or 'all'
40const replyAtom = atom({ plugin: 'xmuse', key: 'replyTo' } as const, 0)
41const genAtom = atom({ plugin: 'xmuse', key: 'gen' } as const, 0)
42const promotedAtom = atom({ plugin: 'xmuse', key: 'promoted' } as const, {} as Record<string, string>)
43const lastReadAtom = atom({ plugin: 'xmuse', key: 'lastRead' } as const, '')
44const themeAtom = atom({ plugin: 'xmuse', key: 'light' } as const, false) // the /config theme is a light one
45const mentionAtom = atom({ plugin: 'xmuse', key: 'mention' } as const, null as string | null) // typed prefix after a trailing @, or null
46// the text the Input is drawn with (a @ completion, a retracted message put back), or null: a new `value` on the same
47// Input replaces its text in place, so the field keeps the focus (a new key would mount a fresh, unfocused field)
48const forcedAtom = atom({ plugin: 'xmuse', key: 'forced' } as const, null as string | null)
49const decisionAtom = atom({ plugin: 'xmuse', key: 'decision' } as const, { id: 0, text: '', ok: true })
50const avatarVerAtom = atom({ plugin: 'xmuse', key: 'avatarVer' } as const, 0)
51let draftLive = '' // the Input's text as last reported by onInput; read at press time, no redraw per key
52const avatarImgs: Record<string, string> = {} // member id or 'v:<vendor>' -> data: URI of a custom avatar PNG
53let avatarTried: Record<string, boolean> = {}
54let decisionN = 0
55const toastSeen = new Set<string>()
56let toastSeeded = false
57const sendNAtom = atom({ plugin: 'xmuse', key: 'sendN' } as const, 0) // goes into the Input key: a new key clears it
58// bumped by an @ completion: part of the Input key, so the field is remounted with the completed text
59const inputGenAtom = atom({ plugin: 'xmuse', key: 'inputGen' } as const, 0)
60const sendingAtom =atom({ plugin: 'xmuse', key: 'sending' } as const, false)
61const addOpenAtom = atom({ plugin: 'xmuse', key: 'addOpen' } as const, false)
62const expandedAtom = atom({ plugin: 'xmuse', key: 'expanded' } as const, '') // id of the member whose card is open under the chips, or ''
63const foldAtom = atom({ plugin: 'xmuse', key: 'fold' } as const, {} as Record<string, boolean>) // opened rows: done lines, noise runs, warnings
64// Message actions (reply / promote) show on hover. If hover does not work in the desktop pane, set this to false: the buttons stay visible.
65const HOVER_ACTIONS: boolean = true
66const STORE_BRIEF = 'briefMissing' // boolean: the room was opened and has no project brief yet
67const TOOL = 'xmuse_send' // registered as mcp__xmuse__xmuse_send
68const TOOL_BRIEF = 'xmuse_brief' // mcp__xmuse__xmuse_brief: writes the project brief
69const openAtom = atom({ plugin: 'xmuse', key: 'open' } as const, { busy: false, msg: '', error: '' })
70// The latest full view from the hub, kept outside the atom: its members' `progress` (text, tool, counts) changes every few
71// seconds, and every atom write redraws the whole panel. viewAtom holds structOf(view) and is written only when that changes;
72// the live parts (live.tsx Clients) read this through the ui.message hook.
73let liveView: any = null
74let structJson = ''
75const doneAtom = atom({ plugin: 'xmuse', key: 'done' } as const, {} as Record<string, { tools: number; startedMs: number; endedMs: number }>)
76const briefAtom = atom({ plugin: 'xmuse', key: 'brief' } as const, false) // mirrors STORE_BRIEF so the panel redraws
77const DONE_KEEP_MS = 30_000 // how long the grey "finished" line stays
78const POOL = 5000 // messages a tab can scroll through: the view's own plus every older page loaded
79const OLDER_PAGE = 100 // one "加载更早的消息" press
80const seenMsgs = new Map<number, any>() // every timeline item seen this load, by id (the newest copy wins)
81let seenRoom = ''
82// older pages fetched from /v1/timeline (oldest first), and whether the hub has still older ones
83const olderAtom = atom({ plugin: 'xmuse', key: 'older' } as const, { items: [] as any[], hasMore: true, loading: false })
84// messages drawn per conversation (newest first): a draw builds only these, the rest waits behind "显示更早的"
85const shownAtom = atom({ plugin: 'xmuse', key: 'shown' } as const, {} as Record<string, number>)
86const SHOW_STEP = 40
87const busyAtom =atom({ plugin: 'xmuse', key: 'busy' } as const, {} as Record<string, boolean>) // approval ids in flight
88const selfCtxAtom = atom({ plugin: 'xmuse', key: 'selfCtx' } as const, 0) // this session's own context fill (session.measure)
89// a member's message that just arrived, drawn growing to its full length (the vendors give no token stream for it)
90const revealAtom = atom({ plugin: 'xmuse', key: 'reveal' } as const, { id: 0, steps: [] as number[], run: 0 })
91// the model picker of one member: what the hub offers (act models), or loading / an error
92type ModelPick = { member: string; current: string; options: { value: string; label?: string }[]; format: string; note: string; loading: boolean; error: string }
93const modelAtom = atom({ plugin: 'xmuse', key: 'modelPick' } as const, null as ModelPick | null)
94let feedMaxId = -1 // highest timeline id seen this load; -1 until the first view sets the baseline (history: no effect)
95let revealRunN = 0
96const REVEAL_STEP_MS = 70
97const NARROW_COLS = 56 // below this many cells (about 420 px) member chips shrink to avatar and state dot
98const RAIL_COLS = 22 // the vertical list's widest width, in cells (it shrinks with the pane: railW in drawPanel)
99const STORE_PROBE = 'probe' // boolean: the two probes (scroll events, the band above the prompt) are on; toggled by `/xmuse probe`
100const probeAtom = atom({ plugin: 'xmuse', key: 'probe' } as const, false) // mirrors STORE_PROBE so the panel and the band redraw
101type ScrollProbe = { n: number; by: number; offset: number; bodyRows: number; contentRows: number; origin: string }
102const scrollProbeAtom = atom({ plugin: 'xmuse', key: 'scrollProbe' } as const, { n: 0, by: 0, offset: 0, bodyRows: 0, contentRows: 0, origin: '' } as ScrollProbe)
103let scrollProbe: ScrollProbe = { n: 0, by: 0, offset: 0, bodyRows: 0, contentRows: 0, origin: '' } // every Pane ui.scroll seen this load
104let scrollProbeAt = -Infinity // host clock of the last write of scrollProbe to the atom
105let bandDraws = 0 // draws of the AbovePrompt probe band
106// Layouts: 'chat' (default: oldest message first, the newest and the composer at the bottom, the pane scrolls as a whole page and
107// follows the newest message) | 'flow' (newest first under the composer). A stored 'pinned' (an older layout) reads as 'chat'.
108const STORE_LAYOUT = 'layout' // toggled by `/xmuse layout`
109const layoutAtom = atom({ plugin: 'xmuse', key: 'layout' } as const, 'chat' as 'chat' | 'flow')
110// The rail can be folded by hand to avatars only (the `rail-fold` button); kept in the store across loads.
111const STORE_RAIL = 'railFold' // boolean
112const railFoldAtom = atom({ plugin: 'xmuse', key: 'railFold' } as const, false)
113const RAIL_FOLD_COLS = 6 // the folded rail's width in cells
114// Following the newest message: true while the person's last scroll left the window at the end (a plugin-made move does not count).
115let atBottom = true
116let pollMaxId = -1 // highest timeline id the poll has seen
117let pollDrafts = '' // ids of the members with a draft row at the last view
118let firstViewSeen = false // the first successful view of this loop has been handled
119const GROW_GRACE_MS =1500 // a grow Client that has not reported this long after its last step is dropped (growDone clears the atom)
120
121// ---- hub access ----------------------------------------------------------------------------------------------
122
123// token: operator (speaks as the user); memberToken: this session's own member; sid: the session the member was bound
124// to last. Both tokens live in the hub's state (db, tokens/), so they outlive a hub restart: only `url` changes then.
125type HubConn = { url: string; token: string; member: string; memberToken?: string; dir?: string; sid?: string }
126const suspect = new Set<string>() // room dirs whose stored address failed a call: check it before trusting it again
127let legacyConnDropped = false
128
129const elapsedStart = (v: any): number => (typeof v === 'number' && isFinite(v) ? v : 0) // started_at as a Client prop (plain JSON)
130
131// Every atom write redraws the whole panel (and voids the handlers of its buttons), so the writes that run on every
132// poll skip a value that did not change (read first, compare). `read` and `update` need the atom as a const of this
133// file, so the check is written at each call site instead of in a helper.
134async function setConn($: any, phase: ConnInfo['phase'], error: string) {
135 const cur = await read($, connAtom)
136 if (cur.phase === phase && cur.error === error) return
137 await update($, connAtom, () => ({ phase, error }))
138}
139
140/** One store key per room directory: sessions on different rooms share the plugin's store and must not overwrite each other. */
141function connKey(dir: string): string {
142 return STORE_CONN + ':' + dir
143}
144
145async function clearConn($: any, dir: string) {
146 suspect.delete(dir)
147 try { await $.store.delete(connKey(dir)) } catch { /* nothing stored */ }
148}
149
150/** Does this hub take our operator token? 'ok', 'denied' (another room, or its state was reset) or 'down'. 3 s at most. */
151async function probeToken($: any, url: string, token: string): Promise<'ok' | 'denied' | 'down'> {
152 try {
153 const r: any = await Promise.race([
154 $.http.fetch(`${url}/v1/view?since=0&wait=0`, { method: 'GET', headers: { authorization: `Bearer ${token}` } }),
155 $.clock.sleep(3000).then(() => { throw new Error('timeout') }),
156 ])
157 return r.status === 200 || r.status === 204 ? 'ok' : 'denied'
158 } catch { return 'down' }
159}
160
161/**
162 * The member stays bound to the session that uses it: after the desktop app restarted (a new session id) the member
163 * is moved over with /v1/rebind (the member token proves it is ours), once per load of this session (`rebound`): the
164 * store is shared, so two sessions open on one room would otherwise take the member back from each other on every poll
165 * (each take changes the view: both panels redraw without pause). /xmuse takes it over again. Failing that, the panel still
166 * works on the operator token; only the model's xmuse_send would be refused as "bound to another session".
167 * The rebind races a 3 s timeout like probeToken (no hang: see §3.2); the outcome goes to REBIND_MARK under DEV.
168 */
169const rebound = new Set<string>() // '<room dir>|<session id>' already bound by this load: never taken back unasked
170
171async function ensureBound($: any, c: HubConn): Promise<HubConn> {
172 const sid: string = await $.session.id()
173 if (c.sid === sid || !c.memberToken) return c
174 const once = `${c.dir ?? ''}|${sid}`
175 if (rebound.has(once)) return c // another session took it later: leave it there
176 rebound.add(once)
177 const mark = async (s: string) => {
178 if (DEV) { try { await $.fs.write(REBIND_MARK, `${new Date().toISOString()} ${s}\n`) } catch { /* diagnostics only */ } }
179 }
180 try {
181 const r: any = await Promise.race([
182 $.http.fetch(`${c.url}/v1/rebind`, {
183 method: 'POST', headers: { authorization: `Bearer ${c.memberToken}`, 'content-type': 'application/json' },
184 body: JSON.stringify({ session_id: sid }),
185 }),
186 $.clock.sleep(3000).then(() => { throw new Error('timeout') }),
187 ])
188 if (r.status !== 200) { await mark(`rebind ${r.status}`); return c }
189 } catch (err) { await mark(`rebind ${errText(err)}`); return c }
190 const n = { ...c, sid }
191 await $.store.set(connKey(n.dir ?? await roomDirFor($)), n)
192 await mark('rebind ok')
193 return n
194}
195
196function errText(err: unknown): string {
197 const s = err instanceof Error ? err.message : String(err)
198 return s.slice(0, 200)
199}
200
201/** No room for this directory yet: the panel offers the "open room" button instead of retrying. */
202class NoRoomError extends Error {}
203/** A room this panel has joined before has no hub answering (after a reboot): the panel starts it once by itself. */
204class HubDownError extends Error {}
205
206// stateDir: the registry directory as a Windows path; distro and python: from install.json, which every hub writes
207type HubSetup = { stateDir: string; distro: string; python: string; path?: string }
208let setupCache: HubSetup | null = null
209let autoStartTried = false
210
211async function readText($: any, path: string): Promise<string | null> {
212 try { return String(await $.fs.read(path)) } catch { return null }
213}
214
215async function withInstall($: any, s: HubSetup): Promise<HubSetup> {
216 try {
217 const j = JSON.parse((await readText($, `${s.stateDir}/install.json`)) ?? '')
218 return { ...s, python: typeof j?.python === 'string' ? j.python : s.python, distro: typeof j?.distro === 'string' && j.distro ? j.distro : s.distro,
219 path: typeof j?.path === 'string' ? j.path : s.path }
220 } catch { return s }
221}
222
223/**
224 * Where the hub registry is and how to start a hub. The stored answer is used while its directory still reads; else
225 * the default WSL distro is asked for its registry directory (registry.py directory()), which also boots WSL after a
226 * reboot. install.json, when a hub has written it, names the interpreter.
227 */
228async function hubSetup($: any): Promise<HubSetup> {
229 if (setupCache) return setupCache
230 const stored = (await $.store.get(STORE_SETUP)) as HubSetup | undefined
231 if (stored?.stateDir && ((await readText($, `${stored.stateDir}/install.json`)) !== null
232 || (await readText($, `${stored.stateDir}/hubs.json`)) !== null)) {
233 setupCache = await withInstall($, stored)
234 } else {
235 const r = await $.process.run(['wsl.exe', '-e', 'sh', '-s'], {
236 stdin: 'echo "$WSL_DISTRO_NAME"\necho "${XDG_STATE_HOME:-$HOME/.local/state}/xmuse"\n', timeoutMs: 30_000 })
237 const [distro, dir] = String(r.stdout ?? '').split(/\r?\n/).map((s: string) => s.trim())
238 if (r.exitCode !== 0 || !distro || !dir || !dir.startsWith('/')) {
239 throw new Error(`找不到 WSL 里的 xmuse 登记目录(wsl.exe 退出码 ${r.exitCode})`)
240 }
241 setupCache = await withInstall($, { stateDir: `//wsl.localhost/${distro}${dir}`, distro, python: '' })
242 }
243 if (JSON.stringify(stored) !== JSON.stringify(setupCache)) await $.store.set(STORE_SETUP, setupCache)
244 return setupCache
245}
246
247async function knownRooms($: any): Promise<string[]> {
248 const v = await $.store.get(STORE_KNOWN)
249 return Array.isArray(v) ? v.filter((x: unknown) => typeof x === 'string') : []
250}
251
252async function addKnown($: any, dir: string) {
253 const k = await knownRooms($)
254 if (!k.includes(dir)) await $.store.set(STORE_KNOWN, [...k, dir].slice(-20))
255}
256
257/** A hub answers at this address (any HTTP status counts); 3 s at most. */
258async function hubAlive($: any, url: string, key: string): Promise<boolean> {
259 try {
260 await Promise.race([
261 $.http.fetch(`${url}/v1/rooms`, { method: 'GET', headers: { 'x-xmuse-sidebar': key } }),
262 $.clock.sleep(3000).then(() => { throw new Error('timeout') }),
263 ])
264 return true
265 } catch { return false }
266}
267
268/**
269 * The room directory of this session and the hubs registered for it: the session's cwd, or (DEV, no hub for the cwd)
270 * the override file's directory. getConn and roomDirFor use the same rule.
271 */
272async function lookupRoom($: any) {
273 const cwd: string = await $.session.cwd()
274 let hubsText = ''
275 let hubsErr = ''
276 let stateDir = ''
277 try {
278 stateDir = (await hubSetup($)).stateDir
279 hubsText = await $.fs.read(`${stateDir}/hubs.json`)
280 } catch {
281 hubsErr = '读不到本机登记表(hubs.json):WSL 没启动,或还没有 hub'
282 }
283 let roomDir = toPosix(cwd)
284 let cands = matchHubs(parseHubs(hubsText), cwd).filter(e => isLoopbackUrl(e.url ?? ''))
285 if (!cands.length && DEV) {
286 // Dev only: a session whose own directory has no room can point at a test room's directory.
287 let alt = ''
288 try { alt = String(await $.fs.read(ROOM_OVERRIDE)).trim() } catch { /* no override */ }
289 if (alt) { roomDir = alt; cands = matchHubs(parseHubs(hubsText), alt).filter(e => isLoopbackUrl(e.url ?? '')) }
290 }
291 return { cwd, roomDir, cands, hubsErr, stateDir }
292}
293
294async function roomDirFor($: any): Promise<string> {
295 return (await lookupRoom($)).roomDir
296}
297
298/**
299 * Stored connection of this session's room, or find the room for this session's directory and join it with the
300 * sidebar key. Connections are kept per room directory (the store is shared by every session of the plugin).
301 */
302async function getConn($: any): Promise<HubConn> {
303 if (!legacyConnDropped) {
304 legacyConnDropped = true
305 try { await $.store.delete('conn') } catch { /* nothing stored */ } // the old single, session-shared key
306 }
307 const { cwd, roomDir, cands, hubsErr, stateDir } = await lookupRoom($)
308 const stored = (await $.store.get(connKey(roomDir))) as HubConn | undefined
309 // joined before (the list, or a connection kept from before the list existed)
310 const kr = await knownRooms($)
311 const known = kr.includes(roomDir) || kr.includes(toPosix(cwd)) || (!!stored?.dir && stored.dir === roomDir)
312 if (known && !kr.includes(roomDir)) await addKnown($, roomDir)
313 if (!cands.length && known) throw new HubDownError(hubsErr || '房间的 hub 没在运行')
314 if (!cands.length) throw new NoRoomError(hubsErr || '这个目录还没有 xmuse 房间')
315 // A stored connection is reused while the hub still takes it. The hub restarted on a new address: the tokens still
316 // hold there, so only the address moves (a re-join would be refused: the member is still bound to the session that
317 // last used it).
318 if (stored && typeof stored.url === 'string' && typeof stored.token === 'string') {
319 const urls = cands.map(e => String(e.url).replace(/\/$/, ''))
320 if (urls.includes(stored.url) && !suspect.has(roomDir)) {
321 return ensureBound($, stored)
322 } else {
323 let down = 0
324 for (const url of [stored.url, ...urls.filter(u => u !== stored.url)].filter(u => urls.includes(u))) {
325 const p = await probeToken($, url, stored.token)
326 if (p === 'ok') {
327 suspect.delete(roomDir)
328 const moved = { ...stored, url }
329 if (url !== stored.url) await $.store.set(connKey(roomDir), moved)
330 return ensureBound($, moved)
331 }
332 if (p === 'down') down++
333 }
334 if (known && down === urls.length) throw new HubDownError(`连不上 ${urls.join('、')}`)
335 await clearConn($, roomDir) // a hub that refuses our token (its state was reset): join afresh below
336 }
337 }
338
339 let key = ''
340 try { key = String(await $.fs.read(`${stateDir}/sidebar.key`)).trim() } catch { /* handled below */ }
341 if (!/^[0-9a-f]{64}$/.test(key)) throw new Error('读不到侧栏凭据(sidebar.key)')
342
343 const sid: string = await $.session.id()
344 let last = '没有可用的 hub'
345 let unreachable = 0
346 for (const e of cands) {
347 const url = String(e.url).replace(/\/$/, '')
348 // The coordinator id is the room's host from hubs.json (it differs per room); a registry without it: 'claude'.
349 const member = typeof e.host === 'string' && e.host ? e.host : 'claude'
350 try {
351 const body: Record<string, unknown> = { dir: roomDir, vendor: 'claude', session_id: sid, name: member }
352 const r = await $.http.fetch(`${url}/v1/join`, {
353 method: 'POST',
354 headers: { 'content-type': 'application/json', 'x-xmuse-sidebar': key },
355 body: JSON.stringify(body),
356 })
357 let data: any = null
358 try { data = JSON.parse(r.text) } catch { /* not JSON */ }
359 if (r.status === 200 && data && typeof data.operator_token === 'string') {
360 const conn: HubConn = { url, dir: roomDir, token: data.operator_token, member: String(data.member_id ?? ''),
361 memberToken: typeof data.member_token === 'string' ? data.member_token : undefined, sid }
362 await $.store.set(connKey(roomDir), conn)
363 await addKnown($, roomDir)
364 rebound.add(`${roomDir}|${sid}`)
365 return conn
366 }
367 if (r.status === 404 && data?.error === 'no_room') throw new NoRoomError('hub 已启动,但还没有房间')
368 if (r.status === 409 && data?.error === 'member_exists') {
369 // a sidebar join takes a member bound to another session over, so this is a removed member or another vendor's id
370 last = `成员 ${member} 不能加入:已被移出房间,或这个 id 属于别的厂商`
371 continue
372 }
373 last = `join 失败 ${r.status}: ${String(data?.message ?? data?.error ?? '').slice(0, 120)}`
374 } catch (err) {
375 if (err instanceof NoRoomError) throw err
376 last = `连不上 ${url}: ${errText(err)}`
377 unreachable++
378 }
379 }
380 // every registered address is dead (entries a killed hub left behind, as after a reboot)
381 if (known && unreachable === cands.length) throw new HubDownError(last)
382 throw new Error(last)
383}
384
385/** One authenticated call to the hub. A 401 re-joins once; a network failure drops the stored connection. */
386async function callHub($: any, method: string, path: string, body?: unknown): Promise<{ status: number; data: any }> {
387 for (let attempt = 0; attempt < 2; attempt++) {
388 const conn = await getConn($)
389 let r: any
390 try {
391 r = await $.http.fetch(conn.url + path, {
392 method,
393 headers: { authorization: `Bearer ${conn.token}`, 'content-type': 'application/json' },
394 body: body === undefined ? undefined : JSON.stringify(body),
395 })
396 } catch (err) {
397 if (conn.dir) suspect.add(conn.dir) // the hub may have restarted on another port: getConn checks before trusting it (tokens kept)
398 throw new Error(`连不上 ${conn.url}: ${errText(err)}`)
399 }
400 if (r.status === 401 && attempt === 0) { await clearConn($, conn.dir ?? await roomDirFor($)); continue }
401 let data: any = null
402 try { data = r.text ? JSON.parse(r.text) : null } catch { /* 204 or not JSON */ }
403 return { status: r.status, data }
404 }
405 throw new Error('令牌失效,重新加入后仍是 401')
406}
407
408// ---- polling loop --------------------------------------------------------------------------------------------
409
410async function pollOnce($: any, gen: number, fails: number) {
411 if ((await read($, genAtom)) !== gen) return // superseded by a newer loop (retry, reload)
412 try {
413 const cur = await read($, viewAtom)
414 const since = Number(liveView?.version ?? cur?.version ?? 0)
415 const r = await callHub($, 'GET', `/v1/view?since=${since}&wait=25`)
416 if ((await read($, genAtom)) !== gen) return
417 if (r.status === 204) {
418 $.clock.after(50, () => { void pollOnce($, gen, 0) })
419 return
420 }
421 if (r.status !== 200 || !r.data) {
422 throw new Error(`hub 返回 ${r.status}: ${String(r.data?.message ?? r.data?.error ?? '').slice(0, 120)}`)
423 }
424 const oldLive = liveView
425 liveView = r.data // the live parts (live.tsx) read progress from here
426 await trackDone($, oldLive ?? cur, r.data) // needs the real progress (tool counts): full views
427 const grew = await newestGrew($, r.data)
428 await revealStart($, r.data) // before the view lands: a new member message is first drawn empty, then grows
429 // progress-only changes (text, tool, counts) do not write the atom: the panel is not redrawn for them
430 const s = structOf(r.data)
431 const j = JSON.stringify({ ...s, version: 0 })
432 if (j !== structJson) { structJson = j; await update($, viewAtom, () => s) }
433 if (!firstViewSeen) { firstViewSeen = true; scrollEndLater($) } // the first view: show the newest
434 else if (grew && atBottom) scrollEndLater($)
435 await settleBusy($, r.data)
436 await setConn($, 'ok', '')
437 await wakeCheck($, r.data, false)
438 await refreshStatus($, r.data)
439 await refreshTheme($)
440 await loadAvatars($, r.data)
441 await toastNew($, r.data)
442 await autoRead($, r.data)
443 $.clock.after(50, () => { void pollOnce($, gen, 0) })
444 } catch (err) {
445 if (err instanceof NoRoomError) { // not an outage: stop polling, the panel shows the open-room button
446 await setConn($, 'noroom', err.message)
447 return
448 }
449 if (err instanceof HubDownError && !autoStartTried) { // a room joined before, no hub (a reboot): start it, once per load
450 autoStartTried = true
451 await setConn($, 'connecting', '')
452 $.clock.after(0, () => { void openRoom($, true) })
453 return
454 }
455 const n = fails + 1
456 const wait = backoffMs(n)
457 await setConn($, 'error', `${errText(err)}(${Math.round(wait / 1000)} 秒后重试)`)
458 $.clock.after(wait, () => { void pollOnce($, gen, n) })
459 }
460}
461
462async function startLoop($: any) {
463 const gen = (await read($, genAtom)) + 1
464 await update($, genAtom, () => gen)
465 firstViewSeen = false
466 await setConn($, 'connecting', '')
467 void pollOnce($, gen, 0)
468}
469
470// ---- chat layout: following the newest message ----------------------------------------------------------------
471
472/** Scroll the pane to its end (the newest message) and follow it from here on. Never call inside a draw. */
473async function scrollToEnd($: any) {
474 try { await $.ui.scroll({ to: 'end', in: PANE }) } catch { /* no engine window (not open yet): nothing to scroll */ }
475 atBottom = true
476}
477
478/** Off the current handler: scroll to the end after the next tick, in the chat layout only (flow keeps the newest at the top). */
479function scrollEndLater($: any) {
480 $.clock.after(0, () => { void scrollEndIfChat($) })
481}
482
483async function scrollEndIfChat($: any) {
484 if ((await read($, layoutAtom)) === 'flow') return
485 await scrollToEnd($)
486}
487
488/** Did the open conversation gain a message or a draft row with this view? The first view only sets the baseline. */
489async function newestGrew($: any, view: any): Promise<boolean> {
490 const tl: any[] = Array.isArray(view?.timeline) ? view.timeline : []
491 const max = tl.reduce((n, m) => (typeof m?.id === 'number' && m.id > n ? m.id : n), 0)
492 const prev = pollMaxId
493 pollMaxId = Math.max(pollMaxId, max)
494 const tab = activeTabOf(view, await read($, tabAtom))
495 const item = railOf(view).find(t => t.id === tab)
496 const drafts = workingMembers(view).filter(m => (!item?.peer || item.peer === m.id) && m.progress?.has_text).map(m => m.id).join(',')
497 const prevDrafts = pollDrafts
498 pollDrafts = drafts
499 if (prev < 0) return false
500 const fresh = max > prev && messagesFor(view, item ? tab : '#room', POOL).some(m => m.id > prev && !m.retracted)
501 return fresh || (drafts !== '' && drafts !== prevDrafts)
502}
503
504async function toggleRailFold($: any) {
505 const on = !(await read($, railFoldAtom))
506 await $.store.set(STORE_RAIL, on)
507 await update($, railFoldAtom, () => on)
508}
509
510// ---- finished line and typing effect (T8f) ---------------------------------------------------------------------
511
512/** A member that stopped running since the last view gets a grey "finished" line for DONE_KEEP_MS. */
513async function trackDone($: any, oldView: any, newView: any) {
514 const fin = finishedMembers(oldView, newView)
515 const runningNow = workingMembers(newView).map(m => m.id)
516 const cur = await read($, doneAtom)
517 if (!fin.length && !runningNow.some(id => cur[id])) return
518 const now = await $.clock.now()
519 await update($, doneAtom, m => {
520 const n = { ...m }
521 for (const id of runningNow) delete n[id] // running again: the old line goes
522 for (const f of fin) n[f.id] = { tools: f.tools, startedMs: f.startedMs, endedMs: now }
523 return n
524 })
525 for (const f of fin) $.clock.after(DONE_KEEP_MS, () => { void expireDone($, f.id, now) })
526}
527
528async function expireDone($: any, id: string, endedMs: number) {
529 const cur = await read($, doneAtom)
530 if (cur[id]?.endedMs !== endedMs) return // replaced by a newer run: that one has its own timer
531 await update($, doneAtom, m => { const n = { ...m }; delete n[id]; return n })
532}
533
534/**
535 * Fresh props for a live.tsx Client (the ui.message hook answers its post): the member's progress from the latest full
536 * view. A member that is gone or not working gets the same shape, empty.
537 */
538async function liveProps($: any, part: string, id: string) {
539 const v = liveView ?? await read($, viewAtom)
540 const m = workingMembers(v).find(x => x.id === id)
541 const p = m?.progress
542 return {
543 part, id,
544 tool: typeof p?.last_tool === 'string' ? p.last_tool.trim() : '',
545 text: String(p?.text ?? ''),
546 tools: toolCount(p),
547 startedAt: elapsedStart(p?.started_at),
548 nowMs: Number(await $.clock.now()),
549 }
550}
551
552/**
553 * A member's message that a fresh view brought grows to its full length in a few steps (about 40 characters each,
554 * REVEAL_STEP_MS apart), so it reads as streamed; a Client (grow.tsx) runs the steps. The first view of a load only
555 * sets the baseline; a newer arrival replaces it.
556 */
557async function revealStart($: any, view: any) {
558 const tl: any[] = Array.isArray(view?.timeline) ? view.timeline : []
559 const max = tl.reduce((n, m) => (typeof m?.id === 'number' && m.id > n ? m.id : n), 0)
560 if (feedMaxId < 0) { feedMaxId = max; return }
561 const m = freshMessage(view, feedMaxId)
562 feedMaxId = Math.max(feedMaxId, max)
563 if (!m) return
564 const steps = revealSteps(String(m.text ?? '').length)
565 if (!steps.length) return
566 const run = ++revealRunN
567 await update($, revealAtom, () => ({ id: m.id, steps, run }))
568 $.clock.after(steps.length * REVEAL_STEP_MS + GROW_GRACE_MS, () => { void growDone($, { grown: `r:${m.id}:${run}` }) }) // likewise
569}
570
571/** ui.message from a grow Client: it showed its last step; the atom goes idle and the normal rendering comes back. */
572async function growDone($: any, data: any) {
573 const id = typeof data?.grown === 'string' ? data.grown : ''
574 const kind = id.slice(0, 2) // 'r:<message id>:<run>'
575 const n = Number(id.slice(id.lastIndexOf(':') + 1))
576 if (kind === 'r:') await update($, revealAtom, r => (r.run === n ? { id: 0, steps: [], run: 0 } : r))
577}
578
579// ---- opening a room (H1) -------------------------------------------------------------------------------------
580
581async function openStep($: any, msg: string) {
582 await update($, openAtom, () => ({ busy: true, msg, error: '' }))
583}
584
585async function openFail($: any, error: string) {
586 await update($, openAtom, () => ({ busy: false, msg: '', error }))
587}
588
589/** A registry entry for exactly this (POSIX) directory whose hub answers (a killed hub leaves its entry behind). */
590async function findHub($: any, dir: string, key: string): Promise<{ url: string } | null> {
591 const text = await readText($, `${(await hubSetup($)).stateDir}/hubs.json`)
592 if (text === null) return null
593 for (const e of parseHubs(text)) {
594 if (!isLoopbackUrl(e.url ?? '') || toPosix(e.dir ?? '').toLowerCase() !== dir.toLowerCase()) continue
595 const url = String(e.url).replace(/\/$/, '')
596 if (await hubAlive($, url, key)) return { url }
597 }
598 return null
599}
600
601/**
602 * The "open room" button: start a hub for this directory inside WSL (unless one is registered already), create the
603 * room with the sidebar key (this session becomes a member and the host), keep the tokens, and start the panel loop.
604 * Each step shows in the panel; each failure shows its reason there.
605 */
606/** The directory a room is opened for: the session's own, or (dev) the override file's. getConn uses the same rule. */
607async function roomTarget($: any): Promise<string> {
608 if (DEV) {
609 let alt = ''
610 try { alt = String(await $.fs.read(ROOM_OVERRIDE)).trim() } catch { /* no override */ }
611 if (alt) return alt
612 }
613 return toPosix(await $.session.cwd())
614}
615
616async function openRoomLater($: any) {
617 // A press handler has a 10 s budget; opening a room takes longer, so it runs off the press.
618 $.clock.after(0, () => { void openRoom($) })
619}
620
621/** The error card's "启动 hub": the automatic start, by hand (it runs once per load by itself). */
622async function startHubLater($: any) {
623 await setConn($, 'connecting', '')
624 $.clock.after(0, () => { void openRoom($, true) })
625}
626
627/**
628 * `auto`: the panel found a room it had joined with no hub answering (after a reboot). Only the hub is started (no
629 * `xmuse init`, no room created); the normal join then takes over, and a hub without that room shows the open button.
630 */
631async function openRoom($: any, auto = false) {
632 if ((await read($, openAtom)).busy) return
633 try {
634 await openStep($, auto ? '房间的 hub 没在运行,自动启动…' : '读取工作目录…')
635 const dir = await roomTarget($)
636 if (!dir.startsWith('/') || /['\r\n\0]/.test(dir)) throw new Error(`不支持的工作目录: ${dir}`)
637 const setup = await hubSetup($)
638 // the key may not exist yet on a machine where no hub ever ran: then nothing can answer, and the hub makes it
639 let key = String((await readText($, `${setup.stateDir}/sidebar.key`)) ?? '').trim()
640
641 let hub = /^[0-9a-f]{64}$/.test(key) ? await findHub($, dir, key) : null
642 if (!hub) {
643 if (!setup.python || /[\r\n\0]/.test(setup.python) || !/^[\w.-]*$/.test(setup.distro)) {
644 throw new Error('没有 hub 的安装记录(登记目录里的 install.json):先在 WSL 里手动启动一次 hub,之后面板就能自己启动')
645 }
646 await openStep($, '在 WSL 里启动 hub…')
647 // The script goes in on stdin (no quoting through wsl.exe's command line); see hubStartScript for why a unit.
648 // `xmuse init` makes the workspace's state (idempotent); the hub's own output goes to the state dir's hub.log.
649 const script = hubStartScript({ python: setup.python, dir, path: setup.path, init: !auto })
650 const argv = setup.distro ? ['wsl.exe', '-d', setup.distro, '-e', 'bash', '-l', '-s'] : ['wsl.exe', '-e', 'bash', '-l', '-s']
651 const r = await $.process.run(argv, { stdin: script, timeoutMs: 25_000 })
652 if (r.exitCode !== 0) throw new Error(`WSL 启动命令失败(退出码 ${r.exitCode}): ${String(r.stderr || r.stdout).replace(/\s+/g, ' ').slice(0, 160)}`)
653 await openStep($, '等 hub 出现在登记表(启动时要先检查各家模型,约 10–30 秒)…')
654 for (let i = 0; i < 60 && !hub; i++) {
655 await $.clock.sleep(1000)
656 if (!/^[0-9a-f]{64}$/.test(key)) key = String((await readText($, `${setup.stateDir}/sidebar.key`)) ?? '').trim()
657 if (/^[0-9a-f]{64}$/.test(key)) hub = await findHub($, dir, key)
658 }
659 if (!hub) throw new Error('60 秒内 hub 没有登记(可能还在启动,稍后点重试;日志在房间状态目录 logs/hub.log,'
660 + '单元状态:systemctl --user status xmuse-hub-*)')
661 }
662 if (auto) {
663 await clearConn($, dir) // the old address is dead: join afresh at the new one
664 await update($, openAtom, () => ({ busy: false, msg: '', error: '' }))
665 await startLoop($)
666 return
667 }
668
669 await openStep($, '创建房间…')
670 if (!/^[0-9a-f]{64}$/.test(key)) throw new Error('读不到侧栏凭据(sidebar.key)')
671 const sid: string = await $.session.id()
672 const body: Record<string, unknown> = { dir, vendor: 'claude', session_id: sid, member_id: 'claude' } // a new room's host is the sidebar's Claude
673 const r = await $.http.fetch(`${hub.url}/v1/rooms`, {
674 method: 'POST',
675 headers: { 'content-type': 'application/json', 'x-xmuse-sidebar': key },
676 body: JSON.stringify(body),
677 })
678 let data: any = null
679 try { data = JSON.parse(r.text) } catch { /* not JSON */ }
680 if (r.status === 200 && data && typeof data.operator_token === 'string') {
681 const conn: HubConn = { url: hub.url, dir, token: data.operator_token, member: String(data.member_id ?? ''),
682 memberToken: typeof data.member_token === 'string' ? data.member_token : undefined, sid }
683 await $.store.set(connKey(dir), conn)
684 await addKnown($, dir)
685 if (data.brief_missing === true) { await $.store.set(STORE_BRIEF, true); await update($, briefAtom, () => true) }
686 } else if (r.status === 409 && data?.error === 'room_exists') {
687 await clearConn($, dir) // the hub already has a room (another session opened it): the normal join takes over below
688 } else {
689 throw new Error(`建房失败 ${r.status}: ${String(data?.message ?? data?.error ?? r.text ?? '').slice(0, 140)}`)
690 }
691 await update($, openAtom, () => ({ busy: false, msg: '', error: '' }))
692 await startLoop($)
693 } catch (err) {
694 if (!auto) { await openFail($, errText(err)); return }
695 await update($, openAtom, () => ({ busy: false, msg: '', error: '' })) // the error card says it, with a start button
696 await setConn($, 'error', `启动 hub 失败:${errText(err)}`)
697 }
698}
699
700/** The panel's "let Claude write it" button: asks the model for the brief and to save it with xmuse_brief. */
701async function askBrief($: any) {
702 try {
703 await $.prompt.submit({ text: '[xmuse] 这个项目的协作室还没有项目简介。请先读一下项目(README、目录结构、配置文件),'
704 + '写一段项目简介(目标、技术栈、约定,200 字内),然后调用工具 xmuse_brief,参数 text 填这段简介,保存到协作室。' })
705 } catch (err) {
706 $.ui.toast(`发送失败: ${errText(err)}`)
707 }
708}
709
710async function dismissBrief($: any) {
711 await $.store.set(STORE_BRIEF, false)
712 await update($, briefAtom, () => false)
713}
714
715/** The model's xmuse_brief tool: writes the project brief with the operator token. */
716async function briefTool($: any, e: any): Promise<any> {
717 const text = typeof e?.text === 'string' ? e.text.trim() : ''
718 if (!text) return { deny: '缺少 text(项目简介正文)' }
719 try {
720 const r = await callHub($, 'POST', '/v1/act', { act: 'brief', text })
721 if (r.status !== 200) return { deny: `保存失败 ${r.status}: ${String(r.data?.message ?? r.data?.error ?? '').slice(0, 200)}` }
722 await dismissBrief($)
723 return { result: `项目简介已保存${r.data?.entry ? `(${r.data.entry})` : ''}` }
724 } catch (err) {
725 return { deny: `保存失败: ${errText(err)}` }
726 }
727}
728
729// ---- actions -------------------------------------------------------------------------------------------------
730
731async function markRead($: any, threads: string[]) {
732 for (const t of threads) {
733 try { await callHub($, 'POST', '/v1/act', { act: 'read', thread: t }) } catch { /* the next view shows it unread again */ }
734 }
735}
736
737/** Move the read cursor of what the current tab shows, once per (tab, view version). */
738async function autoRead($: any, view: any) {
739 const tab = activeTabOf(view, await read($, tabAtom)) // the tab the pane shows, not a stale one
740 const todo = unreadThreadsFor(view, tab)
741 if (!todo.length) return
742 const mark = `${tab}:${view.version ?? ''}`
743 if ((await read($, lastReadAtom)) === mark) return
744 await update($, lastReadAtom, () => mark)
745 await markRead($, todo)
746}
747
748async function setTab($: any, tab: string) {
749 await update($, tabAtom, () => tab)
750 scrollEndLater($)
751 if ((await read($, replyAtom)) !== 0) await update($, replyAtom, () => 0) // every write is a redraw: only a real one
752 // the network part runs off the press: switching shows at once
753 $.clock.after(0, () => { void markReadFor($, tab) })
754}
755
756async function markReadFor($: any, tab: string) {
757 const view = await read($, viewAtom)
758 if (view) await markRead($, unreadThreadsFor(view, tab))
759}
760
761async function setReply($: any, id: number) {
762 await update($, replyAtom, () => id)
763}
764
765/** The `say` body for the open conversation and the pending reply (null: nothing to send). Shared by the panel box and /x. */
766async function sayBody($: any, text: string) {
767 const view = await read($, viewAtom)
768 return buildSay(expandNewlines(text), activeTabOf(view, await read($, tabAtom)), await read($, replyAtom), view)
769}
770
771/** `/x <text>`: the same send as the panel's box, written in Claude's own prompt box. Answers the command's { text }. */
772async function sendFromCommand($: any, raw: string): Promise<{ text: string }> {
773 const text = raw.trim()
774 if (!text) return { text: '用法:/x 消息内容(@名字 可以指定成员)' }
775 try {
776 const body = await sayBody($, text)
777 if (!body) return { text: '发送失败:没有可发的内容' }
778 const r = await callHub($, 'POST', '/v1/act', body)
779 if (r.status !== 200) return { text: `发送失败 ${r.status}: ${String(r.data?.message ?? r.data?.error ?? '').slice(0, 100)}` }
780 await update($, replyAtom, () => 0)
781 scrollEndLater($)
782 const view = await read($, viewAtom)
783 const tab = activeTabOf(view, await read($, tabAtom))
784 const item = railOf(view).find(t => t.id === tab)
785 const label = item?.kind === 'dm' ? String(item.peer ?? item.label) : '大群'
786 return { text: `已发到 ${label}` }
787 } catch (err) {
788 return { text: `发送失败: ${errText(err)}` }
789 }
790}
791
792/** `⤢ 大输入框`: the panel's draft moves into Claude's own multi-line prompt box as `/x <draft>` (Enter there sends it). */
793async function openBigInput($: any) {
794 try {
795 const cur = await $.prompt.read()
796 const plan = bigInputPlan(draftLive, String(cur?.text ?? ''))
797 if (!plan.ok) { $.ui.toast('先清空 Claude 输入框里的内容'); return }
798 const r = await $.prompt.fill({ text: plan.text, mode: 'replace' })
799 if (r?.isFilled === false) { $.ui.toast('没能放进 Claude 输入框'); return }
800 const view = await read($, viewAtom)
801 const tab = activeTabOf(view, await read($, tabAtom))
802 const it = railOf(view).find(t => t.id === tab)
803 const label = it?.kind === 'dm' ? String(it.peer ?? it.label) : '大群'
804 $.ui.toast(`已放进 Claude 输入框:Shift+Enter 换行,回车发到「${label}」`)
805 } catch (err) {
806 $.ui.toast(`没能放进 Claude 输入框: ${errText(err)}`)
807 }
808}
809
810async function sendMsg($: any, text: string) {
811 if (await read($, sendingAtom)) return // a send is in flight: ignore the repeat press
812 const body = await sayBody($, text)
813 if (!body) return
814 await update($, sendingAtom, () => true)
815 try {
816 const r = await callHub($, 'POST', '/v1/act', body)
817 if (r.status !== 200) {
818 $.ui.toast(`发送失败 ${r.status}: ${String(r.data?.message ?? r.data?.error ?? '').slice(0, 100)}`)
819 return
820 }
821 await update($, replyAtom, () => 0)
822 scrollEndLater($)
823 draftLive = ''
824 await update($, mentionAtom, () => null)
825 await update($, forcedAtom, () => null)
826 await update($, sendNAtom, n => n + 1) // new Input key: the box comes back empty
827 refocusInput($)
828 } catch (err) {
829 $.ui.toast(`发送失败: ${errText(err)}`)
830 } finally {
831 await update($, sendingAtom, () => false)
832 }
833}
834
835async function approve($: any, id: string, decision: 'once' | 'always' | 'reject', label = '') {
836 if ((await read($, busyAtom))[id]) return
837 await update($, busyAtom, m => ({ ...m, [id]: true }))
838 try {
839 const r = await callHub($, 'POST', '/v1/act', { act: 'approve', id, decision })
840 if (r.status !== 200) $.ui.toast(`审批失败 ${r.status}: ${String(r.data?.message ?? r.data?.error ?? '').slice(0, 100)}`)
841 else await leaveDecision($, decision === 'reject' ? `✗ 已拒绝 ${label}` : `✓ 已批准 ${label}`, decision !== 'reject')
842 } catch (err) {
843 $.ui.toast(`审批失败: ${errText(err)}`)
844 } finally {
845 await update($, busyAtom, m => { const n = { ...m }; delete n[id]; return n })
846 }
847}
848
849/** Enter in the input: with the @ list showing it picks the first member (keyboard completion), else it sends. */
850async function submitInput($: any, v: string) {
851 draftLive = v
852 const q = trailingMention(v)
853 if (q !== null) {
854 const cands = mentionCandidates(await read($, viewAtom), q, 6)
855 if (cands.length) { await pickMention($, String(cands[0]!.id)); return }
856 }
857 await sendMsg($, v)
858}
859
860/** "撤回": the hub cancels what was not delivered yet and interrupts a turn that took it; the text goes back into the input. */
861async function retractMsg($: any, id: number, text: string) {
862 if ((await read($, busyAtom))[`rt${id}`]) return
863 await update($, busyAtom, m => ({ ...m, [`rt${id}`]: true }))
864 try {
865 const r = await callHub($, 'POST', '/v1/act', { act: 'retract', id })
866 if (r.status !== 200) { $.ui.toast(`撤回失败 ${r.status}: ${String(r.data?.message ?? r.data?.error ?? '').slice(0, 100)}`); return }
867 const cut: string[] = Array.isArray(r.data?.canceled) ? r.data.canceled : []
868 const hit: string[] = Array.isArray(r.data?.interrupted) ? r.data.interrupted : []
869 const parts = [cut.length ? `${cut.map(displayName).join('、')} 还没收到` : '', hit.length ? `已打断 ${hit.map(displayName).join('、')}` : '']
870 .filter(Boolean)
871 $.ui.toast(`已撤回${parts.length ? ':' + parts.join(';') : '(对方可能已经读过)'},原文放回输入框`)
872 draftLive = text
873 await update($, forcedAtom, () => text)
874 } catch (err) {
875 $.ui.toast(`撤回失败: ${errText(err)}`)
876 } finally {
877 await update($, busyAtom, m => { const n = { ...m }; delete n[`rt${id}`]; return n })
878 }
879}
880
881/** "停止" on a working member: its queued mail is canceled and its running turn interrupted (hub act stop). */
882async function stopMember($: any, id: string) {
883 if ((await read($, busyAtom))[`st${id}`]) return
884 await update($, busyAtom, m => ({ ...m, [`st${id}`]: true }))
885 try {
886 const r = await callHub($, 'POST', '/v1/act', { act: 'stop', member: id })
887 if (r.status !== 200) $.ui.toast(`停止失败 ${r.status}: ${String(r.data?.message ?? r.data?.error ?? '').slice(0, 100)}`)
888 else $.ui.toast(r.data?.stopped ? `已停止 ${displayName(id)}` : `${displayName(id)} 没有在执行`)
889 } catch (err) {
890 $.ui.toast(`停止失败: ${errText(err)}`)
891 } finally {
892 await update($, busyAtom, m => { const n = { ...m }; delete n[`st${id}`]; return n })
893 }
894}
895
896/**
897 * "压缩" on a member. opencode: the hub compacts it in the background with its own instruction (act compact) and posts
898 * a notice when done. This session's own Claude: the engine compacts it ($.session.compact), and the session.compact
899 * hook below adds the hub's instruction. A press has a 10 s budget, so the Claude one runs off the press.
900 */
901async function compactMember($: any, id: string, self: boolean) {
902 if ((await read($, busyAtom))[`cp${id}`]) return
903 // the button turns into "压缩中…" at once; for opencode it stays so until the view carries the hub's own flag
904 await update($, busyAtom, m => ({ ...m, [`cp${id}`]: true }))
905 if (self) { $.clock.after(0, () => { void compactSelf($, id) }); return }
906 let started = false
907 try {
908 const r = await callHub($, 'POST', '/v1/act', { act: 'compact', member: id })
909 started = r.status === 200
910 if (started) $.ui.toast(`${displayName(id)} 开始压缩,完成后会在私聊里通知`)
911 else if (r.data?.error === 'busy') $.ui.toast(`${displayName(id)} 正在执行,等它停下再压缩`)
912 else if (r.data?.error === 'unsupported') $.ui.toast(`${displayName(id)} 不支持由协作室触发压缩`)
913 else if (r.data?.error === 'no_session') $.ui.toast(`${displayName(id)} 还没有会话,不需要压缩`)
914 else $.ui.toast(`压缩失败 ${r.status}: ${String(r.data?.message ?? r.data?.error ?? '').slice(0, 100)}`)
915 } catch (err) {
916 $.ui.toast(`压缩失败: ${errText(err)}`)
917 } finally {
918 if (started) $.clock.after(15_000, () => { void unbusy($, `cp${id}`) }) // by then the view shows compacting/compacted
919 else await unbusy($, `cp${id}`)
920 }
921}
922
923/** A view that carries a member's compacting flag takes over from the button's own "压缩中…". */
924async function settleBusy($: any, view: any) {
925 const busy = await read($, busyAtom)
926 for (const m of membersOf(view)) if (m.compacting && busy[`cp${m.id}`]) await unbusy($, `cp${m.id}`)
927}
928
929async function unbusy($: any, key: string) {
930 await update($, busyAtom, m => { const n = { ...m }; delete n[key]; return n })
931}
932
933async function compactSelf($: any, id: string) {
934 await update($, busyAtom, m => ({ ...m, [`cp${id}`]: true }))
935 try {
936 const r = await $.session.compact({})
937 if (r?.skip) $.ui.toast(`没有压缩:${String(r.skip).slice(0, 100)}`)
938 else {
939 const k = (n: unknown) => ctxText(n) || '?'
940 $.ui.toast(r?.tokensBefore ? `已压缩:${k(r.tokensBefore)} → ${k(r.tokensAfter)}` : '已压缩')
941 }
942 } catch (err) {
943 $.ui.toast(`压缩失败: ${errText(err)}`)
944 } finally {
945 await update($, busyAtom, m => { const n = { ...m }; delete n[`cp${id}`]; return n })
946 }
947}
948
949/**
950 * Any compaction of this session's main conversation (/compact, the engine's auto one, the panel button): the hub's
951 * instruction goes to the summarizer after the person's own text. Whatever fails, the compaction goes on unchanged.
952 */
953async function compactHook($: any, e: any, next: any) {
954 if (e.agentId || e.trigger === 'precompute') return next(e)
955 let hub = ''
956 try {
957 // at most 5 s in all (room lookup included): a hub that does not answer must not hold the compaction up
958 const r: any = await Promise.race([
959 (async () => {
960 const stored = (await $.store.get(connKey(await roomDirFor($)))) as HubConn | undefined
961 if (!stored?.member) return null
962 return callHub($, 'GET', `/v1/compact_instructions?member=${encodeURIComponent(stored.member)}`)
963 })(),
964 $.clock.sleep(5000).then(() => null),
965 ])
966 if (r?.status === 200 && typeof r.data?.text === 'string') hub = r.data.text
967 } catch { /* no hub: the engine's own prompt alone */ }
968 if (!hub) return next(e)
969 return next({ ...e, instructions: mergeCompactInstructions(e.instructions, hub) })
970}
971
972/** The member card's model button: opens (or closes) the picker with what the hub offers for that member. */
973async function toggleModelPicker($: any, id: string) {
974 if ((await read($, modelAtom))?.member === id) { await update($, modelAtom, () => null); return }
975 await update($, modelAtom, () => ({ member: id, current: '', options: [], format: '', note: '', loading: true, error: '' }))
976 try {
977 const r = await callHub($, 'POST', '/v1/act', { act: 'models', member: id })
978 if ((await read($, modelAtom))?.member !== id) return // closed or switched meanwhile
979 if (r.status !== 200) {
980 await update($, modelAtom, m => m && { ...m, loading: false, error: `读取失败 ${r.status}: ${String(r.data?.message ?? r.data?.error ?? '').slice(0, 100)}` })
981 return
982 }
983 await update($, modelAtom, () => ({ member: id, current: String(r.data?.current ?? ''), options: Array.isArray(r.data?.options) ? r.data.options : [],
984 format: String(r.data?.format ?? ''), note: String(r.data?.note ?? ''), loading: false, error: '' }))
985 } catch (err) {
986 await update($, modelAtom, m => m && { ...m, loading: false, error: `读取失败: ${errText(err)}` })
987 }
988}
989
990/** A model picked (or typed): member_edit, which the member's next turn uses. */
991async function setModel($: any, id: string, model: string) {
992 const name = model.trim()
993 const cur = await read($, modelAtom)
994 if (!name || (await read($, busyAtom))[`md${id}`]) return
995 if (cur && name === cur.current) { await update($, modelAtom, () => null); return }
996 await update($, busyAtom, m => ({ ...m, [`md${id}`]: true }))
997 try {
998 const r = await callHub($, 'POST', '/v1/act', { act: 'member_edit', member: id, model: name })
999 if (r.status !== 200) {
1000 await update($, modelAtom, m => m && { ...m, error: `没有换成:${String(r.data?.message ?? r.data?.error ?? r.status).slice(0, 120)}` })
1001 return
1002 }
1003 $.ui.toast(`${displayName(id)} 换成 ${name},下一轮起生效`)
1004 await update($, modelAtom, () => null)
1005 } catch (err) {
1006 await update($, modelAtom, m => m && { ...m, error: `没有换成:${errText(err)}` })
1007 } finally {
1008 await unbusy($, `md${id}`)
1009 }
1010}
1011
1012const OLDER_MAX_PAGES = 10 // one press fetches up to this many pages while they show nothing but folded notices
1013
1014/**
1015 * Older history from /v1/timeline. A page that the panel would fold entirely into notice rows (the same buildRows the
1016 * draw uses, for the open tab) shows the person nothing new, so the next page is fetched too, up to OLDER_MAX_PAGES.
1017 * The atom is written once at the end: one redraw, the button reads "加载中…" meanwhile.
1018 */
1019async function loadOlder($: any) {
1020 const cur = await read($, olderAtom)
1021 if (cur.loading) return
1022 const view = await read($, viewAtom)
1023 const ids = [...cur.items, ...seenMsgs.values(), ...(Array.isArray(view?.timeline) ? view.timeline : [])].map((m: any) => m?.id).filter((x: any) => typeof x === 'number')
1024 if (!ids.length) return
1025 await update($, olderAtom, o => ({ ...o, loading: true }))
1026 try {
1027 const activeTab = activeTabOf(view, await read($, tabAtom))
1028 let before = Math.min(...ids)
1029 let got: any[] = []
1030 let hasMore = true
1031 let pages = 0
1032 let shows = false
1033 while (pages < OLDER_MAX_PAGES && hasMore && !shows) {
1034 const r = await callHub($, 'GET', `/v1/timeline?before=${before}&limit=${OLDER_PAGE}`)
1035 if (r.status !== 200) {
1036 $.ui.toast(`加载失败 ${r.status}`)
1037 if (!got.length) { await update($, olderAtom, o => ({ ...o, loading: false })); return }
1038 break
1039 }
1040 pages++
1041 const items: any[] = Array.isArray(r.data?.items) ? r.data.items : []
1042 got = [...items, ...got]
1043 hasMore = !!r.data?.has_more && items.length > 0
1044 const ids2 = items.map((m: any) => m?.id).filter((x: any) => typeof x === 'number')
1045 if (ids2.length) before = Math.min(before, ...ids2)
1046 shows = buildRows(messagesFor({ ...view, timeline: items }, activeTab, POOL).reverse()).some(row => row.kind !== 'noise')
1047 }
1048 if (!shows && hasMore && pages >= OLDER_MAX_PAGES) $.ui.toast(`更早的 ${pages * OLDER_PAGE} 条都是通知,已折叠;再点继续`)
1049 await update($, olderAtom, o => ({ items: [...got, ...o.items], hasMore, loading: false }))
1050 const more = messagesFor({ ...view, timeline: got }, activeTab, POOL).length // what was fetched for this conversation shows
1051 if (more) await update($, shownAtom, m => ({ ...m, [activeTab]: (m[activeTab] ?? SHOW_STEP) + more }))
1052 } catch (err) {
1053 $.ui.toast(`加载失败: ${errText(err)}`)
1054 await update($, olderAtom, o => ({ ...o, loading: false }))
1055 }
1056}
1057
1058/** "显示更早的": the next SHOW_STEP messages of the open conversation that are already here (no hub call). */
1059async function showMore($: any, tab: string) {
1060 await update($, shownAtom, m => ({ ...m, [tab]: (m[tab] ?? SHOW_STEP) + SHOW_STEP }))
1061}
1062
1063/** A member chip pressed: its full card opens (one at a time); pressing the open one closes it. */
1064async function toggleExpand($: any, id: string) {
1065 await update($, expandedAtom, v => (v === id ? '' : id))
1066}
1067
1068/**
1069 * The member menu's 暂停 / 恢复 / 移出 (hub acts pause, resume, remove). 移出 takes two presses: the first turns the
1070 * button into "确认移出", the second removes (the member's history stays; its token stops working).
1071 */
1072async function memberAct($: any, id: string, act: 'pause' | 'resume' | 'remove') {
1073 const busy = await read($, busyAtom)
1074 if (busy[`ma${id}`]) return
1075 if (act === 'remove' && !busy[`rmq${id}`]) {
1076 await update($, busyAtom, m => ({ ...m, [`rmq${id}`]: true }))
1077 return
1078 }
1079 await update($, busyAtom, m => ({ ...m, [`ma${id}`]: true }))
1080 const label = act === 'pause' ? '暂停' : act === 'resume' ? '恢复' : '移出'
1081 try {
1082 const r = await callHub($, 'POST', '/v1/act', { act, member: id })
1083 if (r.status !== 200) $.ui.toast(`${label}失败 ${r.status}: ${String(r.data?.message ?? r.data?.error ?? '').slice(0, 100)}`)
1084 else {
1085 $.ui.toast(`已${label} ${displayName(id)}`)
1086 if (act === 'remove') { await update($, tabAtom, () => '#room'); await update($, expandedAtom, () => '') }
1087 }
1088 } catch (err) {
1089 $.ui.toast(`${label}失败: ${errText(err)}`)
1090 } finally {
1091 await update($, busyAtom, m => { const n = { ...m }; delete n[`ma${id}`]; delete n[`rmq${id}`]; return n })
1092 }
1093}
1094
1095async function toggleAddOpen($: any) {
1096 await update($, addOpenAtom, v => !v)
1097}
1098
1099async function addMember($: any, vendor: string) {
1100 if ((await read($, busyAtom))['add']) return
1101 await update($, busyAtom, m => ({ ...m, add: true }))
1102 try {
1103 const r = await callHub($, 'POST', '/v1/act', { act: 'member_add', vendor }) // name and model: the hub's defaults
1104 if (r.status !== 200) {
1105 $.ui.toast(`添加失败 ${r.status}: ${String(r.data?.message ?? r.data?.error ?? '').slice(0, 100)}`)
1106 return
1107 }
1108 $.ui.toast(`已添加 ${String(r.data?.member_id ?? vendor)}`)
1109 await update($, addOpenAtom, () => false)
1110 } catch (err) {
1111 $.ui.toast(`添加失败: ${errText(err)}`)
1112 } finally {
1113 await update($, busyAtom, m => { const n = { ...m }; delete n.add; return n })
1114 }
1115}
1116
1117// ---- status line, working-strip clock, waking Claude ---------------------------------------------------------
1118
1119async function pendingForMe($: any, view: any): Promise<number> {
1120 const seen = await $.store.get(STORE_SEEN)
1121 return wakeCandidates(view, typeof seen === 'number' ? seen : maxWakeId(view)).length
1122}
1123
1124let lastStatus: string | null = null // the status line as last set: set again only when its text changes
1125
1126async function refreshStatus($: any, view: any) {
1127 const line = summaryLine(view, await pendingForMe($, view), (await $.store.get(STORE_AUTO)) === true)
1128 if (line === lastStatus) return
1129 lastStatus = line
1130 $.ui.status(line)
1131}
1132
1133/** Messages for the panel newer than the handled mark: submit one turn for all of them (auto on, or `force`). */
1134async function wakeCheck($: any, view: any, force: boolean) {
1135 let seen = await $.store.get(STORE_SEEN)
1136 if (typeof seen !== 'number') { // first sight: what is already there is history, not a wake-up
1137 seen = maxWakeId(view)
1138 await $.store.set(STORE_SEEN, seen)
1139 }
1140 const pend = wakeCandidates(view, seen)
1141 if (!pend.length) return
1142 if (!force && (await $.store.get(STORE_AUTO)) !== true) return
1143 const top = pend.reduce((n, m) => Math.max(n, m.id), seen)
1144 await $.store.set(STORE_SEEN, top) // mark first so a second view cannot submit the same ones
1145 $.prompt.submit({ text: buildWakePrompt(pend) }).catch(async (err: unknown) => {
1146 await $.store.set(STORE_SEEN, seen) // not taken: they count as pending again
1147 $.ui.toast(`叫醒 Claude 失败: ${errText(err)}`)
1148 })
1149}
1150
1151async function wakeNow($: any) {
1152 if ((await read($, busyAtom)).wake) return
1153 await update($, busyAtom, m => ({ ...m, wake: true }))
1154 try {
1155 const view = await read($, viewAtom)
1156 if (view) { await wakeCheck($, view, true); await refreshStatus($, view) }
1157 } finally {
1158 await unbusy($, 'wake')
1159 }
1160}
1161
1162async function toggleAuto($: any) {
1163 const on = (await $.store.get(STORE_AUTO)) === true
1164 await $.store.set(STORE_AUTO, !on)
1165 const view = await read($, viewAtom)
1166 if (view && !on) await wakeCheck($, view, false)
1167 if (view) await refreshStatus($, view)
1168}
1169
1170async function promote($: any, id: number) {
1171 if ((await read($, busyAtom))[`pr${id}`]) return
1172 await update($, busyAtom, m => ({ ...m, [`pr${id}`]: true }))
1173 try {
1174 const r = await callHub($, 'POST', '/v1/act', { act: 'promote', message_id: id })
1175 if (r.status !== 200) {
1176 $.ui.toast(`设为决定失败 ${r.status}: ${String(r.data?.message ?? r.data?.error ?? '').slice(0, 100)}`)
1177 return
1178 }
1179 const entry = String(r.data?.entry ?? '已设')
1180 await update($, promotedAtom, m => ({ ...m, [String(id)]: entry }))
1181 } catch (err) {
1182 $.ui.toast(`设为决定失败: ${errText(err)}`)
1183 } finally {
1184 await unbusy($, `pr${id}`)
1185 }
1186}
1187
1188/** The model's xmuse_send tool: one `say` through the panel's own token. Answers { result } or { deny }. */
1189/** Claude speaks as its own member (member token, /v1/tools/xmuse_send), never as the user (the operator token). */
1190async function callAsMember($: any, args: Record<string, unknown>): Promise<{ status: number; data: any }> {
1191 for (let attempt = 0; attempt < 2; attempt++) {
1192 const conn = await getConn($)
1193 if (!conn.memberToken) { await clearConn($, conn.dir ?? await roomDirFor($)); if (attempt === 0) continue; throw new Error('没有成员令牌(重新加入后仍缺)') }
1194 const r = await $.http.fetch(`${conn.url}/v1/tools/xmuse_send`, {
1195 method: 'POST',
1196 // the member is bound to this session (ensureBound): a bound member's tool calls name it
1197 headers: { authorization: `Bearer ${conn.memberToken}`, 'content-type': 'application/json',
1198 ...(conn.sid ? { 'x-xmuse-session': conn.sid } : {}) },
1199 body: JSON.stringify({ args }), // the hub's tool route reads body.args
1200 })hooks/logic.ts 1121 lines1// Pure logic for the xmuse panel: no $, no network, no state, so it can be unit-tested later.
2// Hub view shape: hub/src/xmuse/room.py view(). Every field may be missing; callers get safe defaults.
3
4export type Member = {
5 id: string
6 vendor?: string
7 status?: string
8 online?: boolean
9 paused?: boolean
10 unread?: number
11 queued?: number
12 description?: string
13 progress?: Progress | null
14 model?: string // what its next turn runs on (member_edit changes it)
15 context_tokens?: number // the latest turn's context size (T8c H3)
16 compacting?: boolean // a hub-run compaction is in flight
17 compacted?: boolean // compacted since its last turn: context_tokens is 0 until the next turn
18}
19export type Progress = { turn?: number; started_at?: number; tools?: number | unknown[]; last_tool?: string; text?: string; updated_at?: number }
20export type Approval = { id: string; kind?: string; member?: string; summary?: string; detail?: unknown; risk?: string; at?: number }
21export type Thread = { id: string; kind?: string; title?: string; members?: string[]; private?: boolean; unread?: number }
22export type Msg = {
23 id: number
24 thread?: string
25 from?: string
26 to?: string[]
27 mentions?: string[]
28 kind?: string
29 text?: string
30 at?: number
31 reply_to?: number
32 via?: string | null
33 for_me?: boolean
34 outcome?: string | null
35}
36export type Tab = { id: string; label: string; unread: number; peer?: string; group?: boolean }
37
38// ---- paths ---------------------------------------------------------------------------------------------------
39
40/** Windows or UNC path (as the Claude session sees it) to the POSIX form the hub registry uses. */
41export function toPosix(p: string): string {
42 let s = String(p || '').trim().replace(/\\/g, '/')
43 const unc = s.match(/^\/\/(?:wsl\.localhost|wsl\$)\/[^/]+(\/.*)?$/i)
44 if (unc) s = unc[1] ?? '/'
45 else {
46 const drive = s.match(/^([A-Za-z]):(\/.*)?$/)
47 if (drive) s = `/mnt/${drive[1]!.toLowerCase()}${drive[2] ?? ''}`
48 }
49 if (s.length > 1) s = s.replace(/\/+$/, '')
50 return s
51}
52
53export type HubEntry = { room_id?: string; name?: string; dir?: string; url?: string; host?: string; pid?: number; started_at?: number }
54
55/** hubs.json text to entries; broken or missing content gives []. */
56export function parseHubs(text: string): HubEntry[] {
57 try {
58 const data = JSON.parse(text)
59 const list = Array.isArray(data?.hubs) ? data.hubs : []
60 return list.filter((e: any) => e && typeof e === 'object' && typeof e.url === 'string')
61 } catch {
62 return []
63 }
64}
65
66/**
67 * Entries whose room dir is exactly the session's cwd, newest hub first. Not a parent's: a hub serves only its own
68 * directory (join elsewhere is 400 wrong_dir), so a subfolder of a room's directory has no room of its own yet.
69 */
70export function matchHubs(entries: HubEntry[], cwd: string): HubEntry[] {
71 const me = toPosix(cwd).toLowerCase()
72 return entries.filter(e => !!e.dir && toPosix(e.dir).toLowerCase() === me)
73 .sort((a, b) => (b.started_at ?? 0) - (a.started_at ?? 0))
74}
75
76export function isLoopbackUrl(url: string): boolean {
77 return /^https?:\/\/(127\.\d+\.\d+\.\d+|localhost|\[::1\])(:\d+)?(\/|$)/i.test(String(url))
78}
79
80// ---- people --------------------------------------------------------------------------------------------------
81
82const PALETTE = ['#5B8DEF', '#3FB68B', '#E0A030', '#C86DD7', '#E06C75', '#4FB3C8', '#9AB84A', '#D98B5F']
83const FIXED: Record<string, string> = { claude: '#D97757', human: '#9A8CF0' }
84
85export function hashStr(s: string): number {
86 let h = 0
87 for (let i = 0; i < s.length; i++) h = (h * 31 + s.charCodeAt(i)) >>> 0
88 return h
89}
90
91export function colorOf(id: string): string {
92 return FIXED[id] ?? PALETTE[hashStr(id) % PALETTE.length]!
93}
94
95/** a * (1 - t) + b * t, per channel; both '#RRGGBB'. */
96export function mixHex(a: string, b: string, t: number): string {
97 const pa = /^#([0-9a-f]{6})$/i.exec(a), pb = /^#([0-9a-f]{6})$/i.exec(b)
98 if (!pa || !pb) return a
99 const ch = (h: string, i: number) => parseInt(h.slice(i, i + 2), 16)
100 const out = [0, 2, 4].map(i => Math.round(ch(pa[1]!, i) * (1 - t) + ch(pb[1]!, i) * t))
101 return '#' + out.map(n => n.toString(16).padStart(2, '0')).join('')
102}
103
104// ---- vendors: logo avatars and name colours ------------------------------------------------------------------
105
106export type VendorKey = 'claude' | 'opencode' | 'deepseek' | 'google' | ''
107
108/** The vendor family of a member: from the vendor field, else guessed from the id (opencode-2 -> opencode). */
109export function vendorKey(id: string, vendor?: string): VendorKey {
110 const v = String(vendor ?? '').toLowerCase()
111 const base = String(id ?? '').toLowerCase().replace(/-\d+$/, '')
112 for (const s of [v, base]) {
113 if (s.includes('claude')) return 'claude'
114 if (s.includes('opencode')) return 'opencode'
115 if (s === 'agy' || s.includes('antigravity') || s.includes('google') || s.includes('gemini')) return 'google'
116 if (s === 'dsh' || s.includes('deepseek')) return 'deepseek'
117 }
118 return ''
119}
120
121// [dark theme, light theme]. opencode is teal on purpose: it must not look like Claude's orange.
122const VENDOR_COLOR: Record<string, [string, string]> = {
123 claude: ['#D97757', '#C4562F'],
124 opencode: ['#2DB7A3', '#14806F'],
125 deepseek: ['#5B7CFF', '#3350D0'],
126 google: ['#E0559E', '#B93580'],
127 human: ['#9A8CF0', '#6A4FD0'],
128}
129
130/** Colour of a member's name: by vendor, the user in purple, others from the hashed palette (darker in the light theme). */
131export function memberColor(id: string, vendor: string | undefined, light: boolean): string {
132 const k = id === 'human' ? 'human' : vendorKey(id, vendor)
133 const pair = k ? VENDOR_COLOR[k] : undefined
134 if (pair) return pair[light ? 1 : 0]
135 const c = colorOf(id)
136 return light ? mixHex(c, '#000000', 0.25) : c
137}
138
139/** Small number for a corner badge when several members share a vendor: opencode-2 -> '2', plain opencode -> '1'. */
140export function badgeOf(id: string, vendor: string | undefined, all: { id: string; vendor?: string }[]): string {
141 const k = vendorKey(id, vendor)
142 if (!k) return ''
143 const same = all.filter(m => vendorKey(m.id, m.vendor) === k)
144 if (same.length < 2) return ''
145 const m = /-(\d+)$/.exec(id)
146 return m ? m[1]! : '1'
147}
148
149// ---- colour palettes (dark / light) for what must be a concrete colour -----------------------------------------
150
151export type Pal = {
152 bubble: string; bubbleBorder: string
153 mine: string; mineBorder: string
154 toClaude: string
155 codeBg: string; hoverBg: string; banner: string
156}
157
158export const PAL_DARK: Pal = {
159 bubble: '#2A2A2E', bubbleBorder: '#3A3A40',
160 mine: '#4B3F8F', mineBorder: '#6A5CC0',
161 toClaude: '#2E2723',
162 codeBg: '#1A1A1D', hoverBg: '#1F1F23', banner: '#3A2F14',
163}
164
165export const PAL_LIGHT: Pal = {
166 bubble: '#F1F1F4', bubbleBorder: '#D2D2DA',
167 mine: '#E4DFFA', mineBorder: '#A99BEA',
168 toClaude: '#FCEEE6',
169 codeBg: '#E7E7EC', hoverBg: '#FFFFFF', banner: '#FFF1CF',
170}
171
172/** Translucent tints that read on both a dark and a light pane. The desktop app's own light/dark setting is not
173 * visible to a mod (the /config theme row is the terminal's), so the panel no longer picks a palette by theme. */
174export const PAL_TINT: Pal = {
175 bubble: '#8C8C9614', bubbleBorder: '#8C8C9659',
176 mine: '#7C6AE62E', mineBorder: '#7C6AE6A6',
177 toClaude: '#E8875B24',
178 codeBg: '#8C8C961F', hoverBg: '#8C8C9640', banner: '#F0B42938',
179}
180
181export function palOf(_light: boolean): Pal {
182 return PAL_TINT
183}
184
185/** The `theme` row of /config: any value naming "light" is a light theme (auto and unknown count as dark). */
186export function isLightTheme(value: unknown): boolean {
187 return /light/i.test(String(value ?? ''))
188}
189
190// ---- logo avatars ---------------------------------------------------------------------------------------------
191
192function esc(s: string): string {
193 return s.replace(/[<>&"]/g, '')
194}
195
196/**
197 * Avatar as SVG. Logos are simplified shapes drawn here (no official bitmaps): Claude an orange burst, OpenCode a black
198 * terminal square, DeepSeek a blue whale; unknown vendors the initial on a coloured disc. `image` (a data: URI of a PNG)
199 * replaces the logo; `badge` is a small number in the corner.
200 */
201export function avatarSvg(id: string, size: number, vendor?: string, badge = '', image = ''): string {
202 const k = id === 'human' ? 'human' : vendorKey(id, vendor)
203 let body: string
204 if (image) {
205 body = `<defs><clipPath id="c"><circle cx="16" cy="16" r="16"/></clipPath></defs>`
206 + `<image href="${image}" x="0" y="0" width="32" height="32" preserveAspectRatio="xMidYMid slice" clip-path="url(#c)"/>`
207 } else if (k === 'claude') {
208 let rays = ''
209 for (let i = 0; i < 12; i++) {
210 const a = (i * Math.PI) / 6
211 const r1 = 3, r2 = i % 2 ? 9 : 12.5
212 rays += `<line x1="${(16 + Math.cos(a) * r1).toFixed(2)}" y1="${(16 + Math.sin(a) * r1).toFixed(2)}" x2="${(16 + Math.cos(a) * r2).toFixed(2)}" y2="${(16 + Math.sin(a) * r2).toFixed(2)}"/>`
213 }
214 body = `<circle cx="16" cy="16" r="16" fill="#D97757"/><g stroke="#FFF4EC" stroke-width="2.6" stroke-linecap="round">${rays}</g>`
215 } else if (k === 'opencode') {
216 body = `<rect x="1" y="1" width="30" height="30" rx="6" fill="#0E0E10" stroke="#8A8A92" stroke-width="1.5"/>`
217 + `<polyline points="8,11 14,16 8,21" fill="none" stroke="#FFFFFF" stroke-width="2.6" stroke-linecap="round" stroke-linejoin="round"/>`
218 + `<line x1="17" y1="22" x2="24" y2="22" stroke="#9A9AA2" stroke-width="2.6" stroke-linecap="round"/>`
219 } else if (k === 'deepseek') {
220 body = `<circle cx="16" cy="16" r="16" fill="#4D6BFE"/>`
221 + `<path d="M5 17 C5 11.5 10 9 15 10 C19 10.8 21 13 23 14.5 C24.5 12.5 26 11.5 27.5 11 C27.5 13.5 26.5 15.5 25 17 C26.5 18 27.5 20 27.5 22.5 C25.5 21.8 24 21 22.5 19.5 C20 23.5 14 24.5 9.5 22 C7 20.6 5.4 19 5 17 Z" fill="#FFFFFF"/>`
222 + `<circle cx="10" cy="16.5" r="1.3" fill="#4D6BFE"/>`
223 + `<path d="M13 9.5 C13 7.5 12 6.5 10.5 6 M13 9.5 C13.5 7.5 14.5 6.5 16 6.2" fill="none" stroke="#FFFFFF" stroke-width="1.6" stroke-linecap="round"/>`
224 } else if (k === 'google') {
225 body = '<circle cx="16" cy="16" r="16" fill="#E0559E"/>'
226 + '<path d="M16 5 C17 11.5 20.5 15 27 16 C20.5 17 17 20.5 16 27 C15 20.5 11.5 17 5 16 C11.5 15 15 11.5 16 5 Z" fill="#FFFFFF"/>'
227 } else {
228 const letter = esc(initialOf(id))
229 const fs = letter.length > 1 || letter === '你' ? 13 : 15
230 body = `<circle cx="16" cy="16" r="16" fill="${k === 'human' ? '#7B6CE0' : colorOf(id)}"/>`
231 + `<text x="16" y="21" font-size="${fs}" font-family="sans-serif" font-weight="600" fill="#fff" text-anchor="middle">${letter}</text>`
232 }
233 const bdg = badge
234 ? `<circle cx="25.5" cy="25.5" r="6.5" fill="#1B1B1F" stroke="#FFFFFF" stroke-width="1.2"/>`
235 + `<text x="25.5" y="28.6" font-size="9" font-family="sans-serif" font-weight="700" fill="#fff" text-anchor="middle">${esc(badge).slice(0, 2)}</text>`
236 : ''
237 return `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 32 32">${body}${bdg}</svg>`
238}
239
240export function displayName(id: string | undefined): string {
241 if (!id) return '?'
242 if (id === 'human') return '你'
243 if (id === 'hub') return 'hub'
244 return id
245}
246
247export function initialOf(id: string | undefined): string {
248 if (id === 'human') return '你'
249 const c = (id ?? '?').trim().charAt(0)
250 return c ? c.toUpperCase() : '?'
251}
252
253export function statusLine(m: Member): string {
254 let s: string
255 if (m.paused || m.status === 'paused') s = '⏸ 已暂停'
256 else if (m.status === 'running') s = '● 执行中'
257 else if (m.online === false || m.status === 'offline') s = '○ 离线'
258 else s = '○ 空闲'
259 const q = Number(m.queued ?? 0)
260 return q > 0 ? `${s} · 排队 ${q}` : s
261}
262
263// ---- view ----------------------------------------------------------------------------------------------------
264
265export function membersOf(view: any): Member[] {
266 const list: Member[] = Array.isArray(view?.members) ? view.members.filter((m: any) => m && typeof m.id === 'string') : []
267 // Only the panel's own member is hidden; a host that is someone else shows (the caller marks it with a star).
268 const me = view?.me?.id
269 return list.filter(m => m.id !== me)
270}
271
272export function threadsOf(view: any): Thread[] {
273 return Array.isArray(view?.threads) ? view.threads.filter((t: any) => t && typeof t.id === 'string') : []
274}
275
276export function timelineOf(view: any): Msg[] {
277 return Array.isArray(view?.timeline) ? view.timeline.filter((m: any) => m && typeof m.id === 'number') : []
278}
279
280function tabLabel(t: Thread, hostIds: string[]): string {
281 const ms = (t.members ?? []).filter(x => x !== 'human' && !hostIds.includes(x))
282 if (t.kind === 'dm') {
283 if (ms.length === 1) return ms[0]!
284 const other = (t.members ?? []).filter(x => x !== 'human')
285 if (other.length === 1) return other[0]!
286 return t.title || t.id
287 }
288 return t.title || t.id
289}
290
291/** "全部" first, then every thread except #room (which "全部" sends to). */
292export function tabsOf(view: any): Tab[] {
293 const hostIds = [view?.room?.host, view?.me?.id].filter((x): x is string => typeof x === 'string')
294 const ths = threadsOf(view).filter(t => t.id !== '#room')
295 const roomT = threadsOf(view).find(t => t.id === '#room')
296 const allUnread = threadsOf(view).reduce((n, t) => n + Number(t.unread ?? 0), 0)
297 void roomT
298 const out: Tab[] = [{ id: 'all', label: '全部', unread: allUnread }]
299 const dms = ths.filter(t => t.kind === 'dm')
300 const groups = ths.filter(t => t.kind !== 'dm')
301 for (const t of [...dms, ...groups]) {
302 const tab: Tab = { id: t.id, label: (t.private && t.kind !== 'dm' ? '🔒' : '') + tabLabel(t, hostIds), unread: Number(t.unread ?? 0) }
303 if (t.kind === 'dm') tab.peer = tabLabel(t, hostIds) // a private chat: the draw puts that member's colour dot before the label
304 else tab.group = true
305 out.push(tab)
306 }
307 return out
308}
309
310/** The private chat between the user and a member, as the hub names it (mail.dm_id): `dm:` + the two ids sorted. */
311export function dmThreadId(member: string): string {
312 return 'dm:' + ['human', member].sort().join('+')
313}
314
315/** One entry of the left rail: the room, a member (its private chat with the user), or everything. */
316export type RailItem = { id: string; kind: 'room' | 'dm' | 'all'; label: string; unread: number; peer?: string }
317
318/**
319 * The left rail, IM style: the room (#room) first, then one entry per member (the user's private chat with it, which
320 * the hub creates on the first message), then "全部" (every thread the user can see, the other members' DMs included).
321 * Unread counts come from the view's threads; a chat that does not exist yet has none.
322 */
323export function railOf(view: any): RailItem[] {
324 const ths = threadsOf(view)
325 const unread = (id: string) => Number(ths.find(t => t.id === id)?.unread ?? 0)
326 const out: RailItem[] = [{ id: '#room', kind: 'room', label: String(view?.room?.name ?? '') || '大群', unread: unread('#room') }]
327 for (const m of membersOf(view)) {
328 const id = dmThreadId(m.id)
329 out.push({ id, kind: 'dm', label: m.id, unread: unread(id), peer: m.id })
330 }
331 // threads that are neither the room nor one of the user's chats (members' DMs, groups): only counted under 全部
332 const mine = new Set(out.map(x => x.id))
333 const rest = ths.filter(t => !mine.has(t.id)).reduce((n, t) => n + Number(t.unread ?? 0), 0)
334 out.push({ id: 'all', kind: 'all', label: '全部', unread: rest })
335 return out
336}
337
338/** The stored tab if the rail still has it, else '#room' (a tab from the former tab bar, e.g. a `#plan` group, is not on the rail). */
339export function activeTabOf(view: any, tab: string): string {
340 return railOf(view).some(t => t.id === tab) ? tab : '#room'
341}
342
343/** The room's avatar: a disc with three heads, the group's mark in the rail and the room header. */
344export function roomSvg(size: number): string {
345 const head = (x: number, y: number, r: number) => `<circle cx="${x}" cy="${y}" r="${r}" fill="#FFFFFF"/>`
346 const body = (x: number, y: number, w: number) =>
347 `<path d="M${x - w} ${y + 6} C${x - w} ${y} ${x + w} ${y} ${x + w} ${y + 6} Z" fill="#FFFFFF"/>`
348 return `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 32 32">`
349 + `<circle cx="16" cy="16" r="16" fill="#3D8B6E"/>`
350 + `<g opacity="0.75">${head(9.5, 13, 3)}${body(9.5, 18, 4.5)}${head(22.5, 13, 3)}${body(22.5, 18, 4.5)}</g>`
351 + `${head(16, 11.5, 3.6)}${body(16, 17, 5.6)}</svg>`
352}
353
354/** Thread id to use for `say` and `read` on a tab. */
355export function threadForTab(tab: string): string {
356 return tab === 'all' ? '#room' : tab
357}
358
359/** Thread ids whose read cursor should move when the tab is shown. */
360export function unreadThreadsFor(view: any, tab: string): string[] {
361 const ths = threadsOf(view)
362 if (tab === 'all') return ths.filter(t => Number(t.unread ?? 0) > 0).map(t => t.id)
363 const t = ths.find(x => x.id === tab)
364 return t && Number(t.unread ?? 0) > 0 ? [t.id] : []
365}
366
367export function messagesFor(view: any, tab: string, limit = 50): Msg[] {
368 const all = timelineOf(view)
369 const shown = tab === 'all' ? all : all.filter(m => m.thread === tab)
370 return shown.slice(-limit)
371}
372
373export function toLabel(m: Msg): string {
374 const ments = Array.isArray(m.mentions) ? m.mentions : []
375 const to = Array.isArray(m.to) ? m.to : []
376 const th = m.thread ?? ''
377 // in the room everyone reads it: @ only says whom it wakes, so it must not read as a private message
378 if ((th === '#room' || th === '') && ments.length) return `全员 · @${ments.map(displayName).join(' @')}`
379 let who: string[]
380 if (ments.length) who = ments
381 else if (th.startsWith('dm:')) who = to
382 else if (th === '#room' || th === '') who = []
383 else who = [th]
384 return who.length ? who.map(displayName).join('、') : '全员'
385}
386
387export function fmtClock(at: number | undefined): string {
388 if (typeof at !== 'number' || !isFinite(at)) return ''
389 const d = new Date(at * 1000)
390 const p = (n: number) => String(n).padStart(2, '0')
391 return `${p(d.getHours())}:${p(d.getMinutes())}`
392}
393
394/** "xmuse · opencode 执行中 · 1 条待审批 · 2 条给你"; with nothing going on: "xmuse · 3 助手 · 0 未读". */
395export function summaryLine(view: any, forMe = 0, auto = true): string {
396 // Most urgent first: approvals, messages waiting for Claude, paused, running, unread (the line has no colour).
397 const ms = membersOf(view)
398 const unread = threadsOf(view).reduce((s, t) => s + Number(t.unread ?? 0), 0)
399 const running = ms.filter(m => m.status === 'running' || m.progress).map(m => m.id)
400 const paused = ms.filter(m => m.paused || m.status === 'paused').map(m => m.id)
401 const appr = approvalsOf(view).length
402 const parts: string[] = []
403 if (appr) parts.push(`⚠ ${appr} 条待审批`)
404 if (forMe) parts.push(auto ? `${forMe} 条给你` : `⚠ ${forMe} 条消息等 Claude 处理`)
405 if (paused.length) parts.push(`${paused.join('、')} 已暂停`)
406 if (running.length) parts.push(`${running.join('、')} 执行中`)
407 if (unread) parts.push(`${unread} 未读`)
408 if (!parts.length) parts.push(`${ms.length} 助手`, '空闲')
409 return ['xmuse', ...parts].join(' · ')
410}
411
412export function approvalsOf(view: any): Approval[] {
413 return Array.isArray(view?.approvals) ? view.approvals.filter((a: any) => a && typeof a.id === 'string') : []
414}
415
416/** What the card shows for an approval: the summary (or detail text), cut to 200 chars. */
417export function approvalText(a: Approval): string {
418 let t = typeof a.summary === 'string' && a.summary ? a.summary : typeof a.detail === 'string' ? a.detail : ''
419 if (!t && a.detail && typeof a.detail === 'object') { try { t = JSON.stringify(a.detail) } catch { t = '' } }
420 return t.length > 200 ? t.slice(0, 200) + '…' : t
421}
422
423/** Alignment proposals and resume requests have one yes; shell and share requests have once / always / reject. */
424export function approvalHasAlways(a: Approval): boolean {
425 return a.kind !== 'alignment' && a.kind !== 'resume'
426}
427
428// ---- working strip -------------------------------------------------------------------------------------------
429
430export function workingMembers(view: any): Member[] {
431 return membersOf(view).filter(m => m.progress && typeof m.progress === 'object')
432}
433
434/** "1:12" or "1:02:03"; startedAt in epoch seconds (milliseconds also accepted), nowMs in milliseconds. */
435export function fmtElapsed(startedAt: number | undefined, nowMs: number): string {
436 if (typeof startedAt !== 'number' || !isFinite(startedAt) || !nowMs) return '0:00'
437 const startMs = startedAt > 1e11 ? startedAt : startedAt * 1000
438 const sec = Math.max(0, Math.floor((nowMs - startMs) / 1000))
439 const p = (n: number) => String(n).padStart(2, '0')
440 const h = Math.floor(sec / 3600)
441 const m = Math.floor((sec % 3600) / 60)
442 return h > 0 ? `${h}:${p(m)}:${p(sec % 60)}` : `${m}:${p(sec % 60)}`
443}
444
445export function toolCount(p: Progress | null | undefined): number {
446 if (!p) return 0
447 return Array.isArray(p.tools) ? p.tools.length : Number(p.tools ?? 0) || 0
448}
449
450/** "● opencode 执行中 1:12 · 9 个工具 · 排队 2" */
451export function workingLine(m: Member, nowMs: number): string {
452 const p = m.progress
453 const parts = [`● ${m.id} 执行中 ${fmtElapsed(p?.started_at, nowMs)}`, `${toolCount(p)} 个工具`]
454 const lt = typeof p?.last_tool === 'string' ? p.last_tool.trim() : ''
455 if (lt) parts.push(`最近: ${lt.length > 40 ? lt.slice(0, 40) + '…' : lt}`)
456 const q = Number(m.queued ?? 0)
457 if (q > 0) parts.push(`排队 ${q}`)
458 return parts.join(' · ')
459}
460
461/** "49 秒" or "1 分 49 秒" or "1 小时 2 分". */
462export function fmtDuration(sec: number): string {
463 const s = Math.max(0, Math.floor(sec))
464 if (s < 60) return `${s} 秒`
465 const m = Math.floor(s / 60)
466 if (m < 60) return `${m} 分 ${s % 60} 秒`
467 return `${Math.floor(m / 60)} 小时 ${m % 60} 分`
468}
469
470export function startedMsOf(startedAt: number | undefined): number {
471 if (typeof startedAt !== 'number' || !isFinite(startedAt) || startedAt <= 0) return 0
472 return startedAt > 1e11 ? startedAt : startedAt * 1000
473}
474
475/** Members that were running in the old view and are present but idle in the new one (last seen tools and start). */
476export function finishedMembers(oldView: any, newView: any): { id: string; tools: number; startedMs: number }[] {
477 if (!oldView) return []
478 const now = membersOf(newView)
479 const out: { id: string; tools: number; startedMs: number }[] = []
480 for (const m of workingMembers(oldView)) {
481 const cur = now.find(x => x.id === m.id)
482 if (cur && !(cur.progress && typeof cur.progress === 'object')) {
483 out.push({ id: m.id, tools: toolCount(m.progress), startedMs: startedMsOf(m.progress?.started_at) })
484 }
485 }
486 return out
487}
488
489/** "✓ opencode 已完成 · 3 个工具 · 1 分 49 秒" */
490export function doneLine(id: string, tools: number, startedMs: number, endedMs: number): string {
491 const parts = [`✓ ${id} 已完成`, `${tools} 个工具`]
492 if (startedMs > 0 && endedMs > startedMs) parts.push(fmtDuration((endedMs - startedMs) / 1000))
493 return parts.join(' · ')
494}
495
496export function textsOf(view: any): Record<string, string> {
497 const out: Record<string, string> = {}
498 for (const m of workingMembers(view)) out[m.id] = String(m.progress?.text ?? '')
499 return out
500}
501
502/** The last running member whose partial output differs from `prev`. */
503export function changedWorker(prev: Record<string, string>, view: any): { id: string; text: string; old: string } | null {
504 let hit: { id: string; text: string; old: string } | null = null
505 for (const m of workingMembers(view)) {
506 const text = String(m.progress?.text ?? '')
507 const old = prev[m.id] ?? ''
508 if (text !== old) hit = { id: m.id, text, old }
509 }
510 return hit
511}
512
513/** Shown lengths of the typing effect, from `from` (exclusive) to `to` (inclusive), in n steps. */
514export function typingSteps(from: number, to: number, n = 4): number[] {
515 const out: number[] = []
516 for (let i = 1; i <= n; i++) out.push(Math.min(to, from + Math.ceil(((to - from) * i) / n)))
517 out[out.length - 1] = to
518 return out
519}
520
521/** What of a member's partial output to draw: the typed prefix while the typing effect runs for that member. */
522export function typedText(full: string, typed: { id: string; full: string; shown: number } | undefined, id: string): string {
523 if (typed && typed.id === id && typed.full === full && typed.shown < full.length) return full.slice(0, Math.max(0, typed.shown))
524 return full
525}
526
527/**
528 * The message a fresh view brought that the feed reveals as if typed: the newest one past `sinceId` that a member
529 * (not the user) wrote as plain chat text. null when there is none.
530 */
531export function freshMessage(view: any, sinceId: number): Msg | null {
532 const tl: Msg[] = Array.isArray(view?.timeline) ? view.timeline : []
533 let hit: Msg | null = null
534 for (const m of tl) {
535 if (typeof m?.id !== 'number' || m.id <= sinceId || m.from === 'human') continue
536 if (m.kind === 'system' || m.kind === 'done' || (m as any).retracted || !String(m.text ?? '').trim()) continue
537 if (!hit || m.id > hit.id) hit = m
538 }
539 return hit
540}
541
542/** Shown lengths for revealing a message of `len` characters: about 40 characters a step, 3 to 10 steps. */
543export function revealSteps(len: number): number[] {
544 return len > 0 ? typingSteps(0, len, Math.min(10, Math.max(3, Math.ceil(len / 40)))) : []
545}
546
547/** The tail of a live draft: its last `max` characters, cut at a line start when one is near, "…" before a cut. */
548export function draftTail(text: string, max = 280): string {
549 const t = String(text ?? '').trim()
550 if (t.length <= max) return t
551 let s = t.slice(-max)
552 const nl = s.indexOf('\n')
553 if (nl >= 0 && nl < 80) s = s.slice(nl + 1)
554 return '…' + s
555}
556
557/**
558 * The view without the live parts: a shallow copy whose members' `progress` keeps only `started_at`. A view that
559 * differs from the last one only in progress text / tool / tool counts is the same structure: it does not redraw the panel.
560 */
561export function structOf(view: any): any {
562 if (!view || typeof view !== 'object') return view
563 if (!Array.isArray(view.members)) return { ...view }
564 return {
565 ...view,
566 members: view.members.map((m: any) => (m && typeof m === 'object' && 'progress' in m
567 ? { ...m, progress: m.progress && typeof m.progress === 'object' ? { started_at: m.progress.started_at, has_text: String(m.progress.text ?? '').trim() !== '' } : m.progress }
568 : m)),
569 }
570}
571
572/** Last n non-empty lines of the member's partial output ('' when there is none). */
573export function lastLines(text: string | undefined, n = 2): string {
574 const ls = String(text ?? '').split('\n').map(x => x.trimEnd()).filter(x => x.trim())
575 return ls.slice(-n).map(x => (x.length > 160 ? x.slice(0, 160) + '…' : x)).join('\n')
576}
577
578// ---- messages ------------------------------------------------------------------------------------------------
579
580/** "↩ #12 first 30 chars" when the replied-to message is on the timeline, else "↩ #12". */
581export function replyLabel(view: any, id: number): string {
582 const orig = timelineOf(view).find(m => m.id === id)
583 const t = orig ? String(orig.text ?? '').replace(/\s+/g, ' ').trim() : ''
584 return t ? `↩ #${id} ${t.length > 30 ? t.slice(0, 30) + '…' : t}` : `↩ #${id}`
585}
586
587/** A reply the hub forwarded by itself: `via` is set and is not a human relay (cli / sidebar / coordinator). */
588export function isAutoForward(m: Msg): boolean {
589 const v = m.via
590 if (!v || typeof v !== 'string') return false
591 return v !== 'cli' && v !== 'coordinator' && !v.endsWith(' sidebar')
592}
593
594// ---- waking Claude -------------------------------------------------------------------------------------------
595
596function isForPanel(m: Msg, me: string): boolean {
597 if (m.for_me === true) return true
598 if (Array.isArray(m.mentions) && m.mentions.includes(me)) return true
599 const th = m.thread ?? ''
600 return th.startsWith('dm:') && th.slice(3).split('+').includes(me)
601}
602
603/** Messages to the panel's own member from someone who is not the user (the user's go through the prompt box). */
604export function wakeCandidates(view: any, afterId = 0): Msg[] {
605 const me = view?.me?.id
606 if (typeof me !== 'string' || !me) return []
607 return timelineOf(view).filter(m =>
608 m.id > afterId && m.kind !== 'system' && m.from !== me && m.from !== 'human' && m.from !== 'hub' && isForPanel(m, me))
609}
610
611export function maxWakeId(view: any): number {
612 return wakeCandidates(view, 0).reduce((n, m) => Math.max(n, m.id), 0)
613}
614
615export function buildWakePrompt(msgs: Msg[]): string {
616 if (msgs.length === 1) {
617 const m = msgs[0]!
618 return `[xmuse] ${m.from ?? '?'} 在 ${m.thread ?? '#room'} 给你发了消息 #${m.id}:${String(m.text ?? '').slice(0, 500)}。用 xmuse_send 工具回复(reply_to=${m.id})。`
619 }
620 const lines = msgs.slice(0, 8).map(m => `- ${m.from ?? '?'} 在 ${m.thread ?? '#room'},消息 #${m.id}:${String(m.text ?? '').slice(0, 300)}`)
621 const more = msgs.length > 8 ? `\n(另有 ${msgs.length - 8} 条更早的没列出)` : ''
622 return `[xmuse] 有 ${msgs.length} 条消息给你:\n${lines.join('\n')}${more}\n用 xmuse_send 工具逐条回复(reply_to 填对应消息 id)。`
623}
624
625// ---- sending -------------------------------------------------------------------------------------------------
626
627/** @names in the text that are real member ids (host included: the user may @claude). Order kept, no repeats. */
628export function parseMentions(text: string, view: any): string[] {
629 const ids: string[] = Array.isArray(view?.members) ? view.members.map((m: any) => String(m.id)) : []
630 const found: string[] = []
631 const re = /@([A-Za-z0-9][A-Za-z0-9-]*)/g
632 let m: RegExpExecArray | null
633 while ((m = re.exec(text)) !== null) {
634 const name = m[1]!
635 const hit = ids.find(i => i.toLowerCase() === name.toLowerCase())
636 if (hit && !found.includes(hit)) found.push(hit)
637 }
638 return found
639}
640
641export type SayBody = { act: 'say'; to: string; text: string; mentions: string[]; reply_to?: number }
642
643/** The Input is one line: a literal backslash-n in the text becomes a real line break. */
644export function expandNewlines(text: string): string {
645 return text.replace(/\\n/g, '\n')
646}
647
648/**
649 * The big-input button moves the panel's draft into Claude's own (multi-line) prompt box as `/x <draft>`. Allowed when that
650 * box is empty or already a /x line (it is replaced); any other text there is never overwritten.
651 */
652export function bigInputPlan(draft: string, promptText: string): { ok: true; text: string } | { ok: false } {
653 const p = promptText.trim()
654 if (p && !(p === '/x' || p.startsWith('/x ') || p.startsWith('/x\n'))) return { ok: false }
655 return { ok: true, text: '/x ' + draft }
656}
657
658export function buildSay(text: string, tab: string, replyTo: number, view: any): SayBody | null {
659 const t = text.trim()
660 if (!t) return null
661 const to = threadForTab(tab)
662 let mentions = parseMentions(t, view)
663 // a private chat has two members: an @ of anyone else is just text there (the hub refuses mentions outside a thread)
664 if (to.startsWith('dm:')) mentions = mentions.filter(m => to.slice(3).split('+').includes(m))
665 const body: SayBody = { act: 'say', to, text: t, mentions }
666 if (replyTo > 0) body.reply_to = replyTo
667 return body
668}
669
670// ---- display -------------------------------------------------------------------------------------------------
671
672/**
673 * The Markdown renderer treats a single newline as a space. Outside ``` / ~~~ fences, a non-blank line followed
674 * directly by a non-blank line gets two trailing spaces (a hard break). Blank lines, fence lines and everything
675 * inside a fence stay as they are; list, table, heading and quote lines are not harmed by trailing spaces.
676 */
677export function hardBreaks(text: string): string {
678 const lines = String(text ?? '').replace(/\r\n?/g, '\n').split('\n')
679 let fence = ''
680 const out: string[] = []
681 for (let i = 0; i < lines.length; i++) {
682 const line = lines[i]!
683 const m = line.match(/^\s{0,3}(`{3,}|~{3,})/)
684 if (fence) {
685 if (m && m[1]![0] === fence[0] && m[1]!.length >= fence.length && !line.replace(m[0], '').trim()) fence = ''
686 out.push(line)
687 continue
688 }
689 if (m) { fence = m[1]!; out.push(line); continue }
690 const next = lines[i + 1]
691 const brk = line.trim() !== '' && next !== undefined && next.trim() !== '' && !/ {2}$/.test(line)
692 out.push(brk ? line + ' ' : line)
693 }
694 return out.join('\n')
695}
696
697const URL_RE = /^(https?:\/\/[^\s<>()]+?)([.,;:!?)\],。;:!?)」』]*)$/
698const ZWSP = ''
699
700/** The label a long bare URL is drawn with: host, the last path part, '…' between (the link keeps the full target). */
701export function urlLabel(url: string, max = 28): string {
702 const m = /^https?:\/\/([^/?#]+)(.*)$/.exec(url)
703 if (!m) return clip(url, max)
704 const host = m[1]!, rest = m[2]!
705 if ((host + rest).length <= max) return host + rest
706 const last = rest.split(/[/?#]/).filter(Boolean).pop() ?? ''
707 return clip(`${host}/…/${last}`, max)
708}
709
710/**
711 * Text the pane can wrap at any width. The desktop draws Markdown with the browser's line breaking, which never breaks
712 * inside a long run of letters (a path, a hash, a URL): the bubble then grows past the pane. Outside ``` / ~~~ fences
713 * and inline code, a bare URL longer than 40 characters becomes a link with a short label, and any other run of 28 or
714 * more non-space characters gets a zero-width break every 16. Copy uses the original text. `links` false (plain Text,
715 * not Markdown): URLs get breaks like any other run.
716 */
717export function softWrap(text: string, links = true): string {
718 const lines = String(text ?? '').split('\n')
719 let fence = ''
720 return lines.map(line => {
721 const m = line.match(/^\s{0,3}(`{3,}|~{3,})/)
722 if (fence) { if (m && m[1]![0] === fence[0] && m[1]!.length >= fence.length) fence = ''; return line }
723 if (m) { fence = m[1]!; return line }
724 if (!/\S{28,}/.test(line)) return line
725 return line.split(/(\s+)/).map(tok => {
726 if (tok.length < 28 || /\s/.test(tok) || tok.includes('`') || tok.includes('](') || tok.startsWith('<')) return tok
727 const u = links ? URL_RE.exec(tok) : null
728 if (u) return u[1]!.length > 40 ? `[${urlLabel(u[1]!)}](${u[1]})${u[2]}` : tok
729 return tok.replace(/[^\s -鿿-]{16}(?=[^\s -鿿-])/g, s => s + ZWSP)
730 }).join('')
731 }).join('\n')
732}
733
734/** At most `n` characters, '…' as the last one when cut (for labels the layout cannot truncate: a tab, a button). */
735export function clip(s: string, n: number): string {
736 const t = String(s ?? '')
737 return t.length > n ? t.slice(0, Math.max(1, n - 1)) + '…' : t
738}
739
740// ---- retry ---------------------------------------------------------------------------------------------------
741
742/** 2s, 4s, 8s ... capped at 30s. `fails` is the number of consecutive failures so far (>= 1). */
743export function backoffMs(fails: number): number {
744 return Math.min(30000, 2000 * 2 ** Math.max(0, fails - 1))
745}
746
747// ---- status, notices, done lines, approvals (polish batch 1) -------------------------------------------------
748
749// Text and border colours are theme keys, so they follow the light / dark theme by themselves.
750export const C_BLUE = 'suggestion'
751export const C_AMBER = 'warning'
752export const C_RED = 'error'
753export const C_GREEN = 'success'
754export const C_ORANGE = 'claude'
755
756/** Dot colour and label of a member's state (A1, A2). Waiting for approval wins, then paused, running, offline, idle. */
757export function statusOf(m: Member, waiting = false): { dot: string; label: string; color: string } {
758 if (waiting) return { dot: '⚠', label: '等审批', color: C_AMBER }
759 if (m.paused || m.status === 'paused') return { dot: '⏸', label: '已暂停', color: C_AMBER }
760 if (m.status === 'running' || (m.progress && typeof m.progress === 'object')) return { dot: '●', label: '执行中', color: C_BLUE }
761 if (m.online === false || m.status === 'offline') return { dot: '●', label: '离线', color: 'subtle' }
762 return { dot: '●', label: '空闲', color: 'inactive' }
763}
764
765// ---- starting a hub inside WSL ---------------------------------------------------------------------------------
766
767/** A POSIX shell single-quoted word. */
768export function shq(s: string): string {
769 return `'${String(s).replace(/'/g, `'\\''`)}'`
770}
771
772/**
773 * The bash script (fed to `wsl.exe ... bash -l -s` on stdin) that starts the hub for `dir`. A process left behind by
774 * a wsl.exe call dies when that call returns, so with a systemd user manager the hub runs as a transient unit
775 * (`hub run` itself, as `hub start` would launch it: XMUSE_STATE set, output appended to the state's logs/hub.log;
776 * --collect unloads it when the hub exits); without one it falls back to setsid. `path`: the PATH a hub last ran with
777 * (install.json), since a login shell may lack the agent CLIs. `init`: also make the workspace (`xmuse init`).
778 * WSL_INTEROP points at init's socket, which outlives this call (Windows exes such as agy need it).
779 */
780export function hubStartScript(o: { python: string; dir: string; path?: string; init: boolean }): string {
781 const unit = 'xmuse-hub-' + Array.from(o.dir).reduce((h, c) => (h * 31 + c.charCodeAt(0)) >>> 0, 7).toString(16)
782 return [
783 'set -e',
784 `PY=${shq(o.python)}`,
785 `D=${shq(o.dir)}`,
786 'cd "$D"',
787 // no recorded PATH (a hub older than the record): the usual per-user CLI dirs a login shell skips
788 o.path ? `export PATH=${shq(o.path)}`
789 : 'for p in "$HOME/.opencode/bin" "$HOME/.local/bin"; do [ -d "$p" ] && PATH="$p:$PATH"; done; export PATH',
790 o.init ? '"$PY" -m xmuse init "$D" >/dev/null' : '',
791 'I=/run/WSL/1_interop; [ -S "$I" ] || I=$(ls -t /run/WSL/*_interop 2>/dev/null | head -1)',
792 'if command -v systemd-run >/dev/null && systemctl --user show-environment >/dev/null 2>&1; then',
793 // the unit runs `hub run` itself, so it lives exactly as long as the hub; a unit of the same name still loaded
794 // is a hub that does not answer (the panel found none alive): it is stopped first
795 ' ST=$("$PY" -c \'import sys; from pathlib import Path; from xmuse import config; print(config.find_state(Path(sys.argv[1])))\' "$D")',
796 ' mkdir -p "$ST/logs"',
797 // a stopped transient unit can stay loaded under its name: each start takes a fresh one (dir hash + time)
798 ` systemctl --user stop '${unit}*' 2>/dev/null || true`,
799 ` systemctl --user reset-failed '${unit}*' 2>/dev/null || true`,
800 ` U=${unit}-$(date +%s)`,
801 ' systemd-run --user --unit="$U" --collect --working-directory="$D" --setenv=XMUSE_STATE="$ST" \\',
802 ' --setenv=PATH="$PATH" --setenv=HOME="$HOME" ${I:+--setenv=WSL_INTEROP=$I} \\',
803 ' ${WSL_DISTRO_NAME:+--setenv=WSL_DISTRO_NAME=$WSL_DISTRO_NAME} \\',
804 ' /bin/sh -c \'exec "$0" -m xmuse hub run >> "$1/logs/hub.log" 2>&1\' "$PY" "$ST" >/dev/null',
805 ' echo "started unit $U"',
806 'else',
807 ' setsid nohup "$PY" -m xmuse --ws "$D" hub start </dev/null >/dev/null 2>&1 &',
808 ' echo started',
809 'fi',
810 ].filter(Boolean).join('\n') + '\n'
811}
812
813// ---- context size and compaction (T8c H3) ----------------------------------------------------------------------
814
815export const AUTO_COMPACT_TOKENS = 500_000 // the hub's auto_compact_tokens default
816
817/** "312k" for a member's latest context size; '' when the hub has none (no turn yet, or a vendor that reports none). */
818export function ctxText(tokens: unknown): string {
819 const t = Number(tokens)
820 if (!isFinite(t) || t <= 0) return ''
821 return t >= 1_000_000 ? `${(t / 1_000_000).toFixed(1)}M` : `${Math.max(1, Math.round(t / 1000))}k`
822}
823
824/** 0 normal, 1 past 80% of the auto-compact mark, 2 past it. */
825export function ctxLevel(tokens: unknown, mark = AUTO_COMPACT_TOKENS): number {
826 const t = Number(tokens)
827 if (!isFinite(t) || t <= 0) return 0
828 return t >= mark ? 2 : t >= mark * 0.8 ? 1 : 0
829}
830
831/** A model name short enough for a member card: the part after the provider, at most 24 characters. */
832export function shortModel(model: unknown): string {
833 const s = String(model ?? '').trim()
834 const tail = s.includes('/') ? s.slice(s.lastIndexOf('/') + 1) : s
835 return tail.length > 24 ? tail.slice(0, 23) + '…' : tail
836}
837
838/** Whether the panel offers "压缩" for this member: opencode via the hub, or this session's own Claude via the engine. */
839export function canCompact(m: Member, meId: string): boolean {
840 return (!!meId && m.id === meId) || vendorKey(String(m.id), String(m.vendor ?? '')) === 'opencode'
841}
842
843/**
844 * What Claude's summarizer is told: the person's own /compact text first (it wins where they differ), then the hub's
845 * instruction (task, handoffs, alignment points). Either may be empty.
846 */
847export function mergeCompactInstructions(user: string | undefined, hub: string | undefined): string {
848 const u = String(user ?? '').trim()
849 const x = String(hub ?? '').trim()
850 if (!x) return u
851 if (!u) return x
852 return `${u}\n\n(以下是 xmuse 协作室的压缩要求;和上面冲突时以上面为准)\n${x}`
853}
854
855/** 0 normal, 1 over 5 minutes, 2 over 15 minutes (E3). */
856export function elapsedLevel(startedAt: number | undefined, nowMs: number): number {
857 const s = startedMsOf(startedAt)
858 if (!s || !nowMs) return 0
859 const sec = (nowMs - s) / 1000
860 return sec > 900 ? 2 : sec > 300 ? 1 : 0
861}
862
863/** The trailing "@word" of the draft (what is after the last @ when that word starts with @), or null. */
864export function trailingMention(draft: string): string | null {
865 const m = /(?:^|\s)@([A-Za-z0-9-]*)$/.exec(draft)
866 return m ? m[1]! : null
867}
868
869/** Members whose id starts with the typed prefix, at most n; the user's own member is not offered. */
870export function mentionCandidates(view: any, q: string, n = 6): Member[] {
871 const me = view?.me?.id
872 const list: Member[] = Array.isArray(view?.members) ? view.members.filter((m: any) => m && typeof m.id === 'string' && m.id !== me) : []
873 const lq = q.toLowerCase()
874 return list.filter(m => m.id.toLowerCase().startsWith(lq)).slice(0, n)
875}
876
877/** The draft with its trailing @word replaced by "@id ". */
878export function completeMention(draft: string, id: string): string {
879 return draft.replace(/@[A-Za-z0-9-]*$/, `@${id} `)
880}
881
882/** Long text folded to its first lines: null when it is short. Never cuts inside a ``` fence (a closing fence is added). */
883export function foldLong(text: string, maxLines = 14, maxChars = 900, keep = 8): { text: string; hidden: number } | null {
884 const lines = String(text ?? '').split('\n')
885 if (lines.length <= maxLines && text.length <= maxChars) return null
886 let cut = Math.min(keep, lines.length)
887 while (cut > 1 && lines.slice(0, cut).join('\n').length > maxChars) cut--
888 const head = lines.slice(0, cut)
889 let open = false
890 for (const l of head) if (/^\s{0,3}(```|~~~)/.test(l)) open = !open
891 if (open) head.push('```')
892 return { text: head.join('\n'), hidden: lines.length - cut }
893}
894
895export type Block = { kind: 'md' | 'diff'; text: string }
896
897/** Splits text at ```diff fences: diff blocks are drawn with Code, the rest with Markdown. */
898export function splitBlocks(text: string): Block[] {
899 const out: Block[] = []
900 const lines = String(text ?? '').split('\n')
901 let cur: string[] = []
902 let diff: string[] | null = null
903 const pushMd = () => { if (cur.join('\n').trim()) out.push({ kind: 'md', text: cur.join('\n') }); cur = [] }
904 for (const l of lines) {
905 if (diff === null) {
906 if (/^\s{0,3}```diff\s*$/.test(l)) { pushMd(); diff = []; continue }
907 cur.push(l)
908 } else if (/^\s{0,3}```\s*$/.test(l)) {
909 if (diff.length) out.push({ kind: 'diff', text: diff.join('\n') })
910 diff = null
911 } else diff.push(l)
912 }
913 if (diff !== null) cur.push('```diff', ...diff) // unterminated: leave it as plain text
914 pushMd()
915 return out.length ? out : [{ kind: 'md', text: String(text ?? '') }]
916}
917
918/** Day heading for the divider between days: 今天 / 昨天 / "10-11 周日". */
919export function dayLabel(at: number | undefined, nowMs: number): string {
920 if (typeof at !== 'number' || !isFinite(at)) return ''
921 const d = new Date(at * 1000)
922 const n = new Date(nowMs)
923 const key = (x: Date) => x.getFullYear() * 400 + x.getMonth() * 32 + x.getDate()
924 const y = new Date(nowMs - 86400000)
925 if (key(d) === key(n)) return '今天'
926 if (key(d) === key(y)) return '昨天'
927 const p = (v: number) => String(v).padStart(2, '0')
928 return `${p(d.getMonth() + 1)}-${p(d.getDate())} 周${'日一二三四五六'[d.getDay()]}`
929}
930
931export type NoticeInfo = { kind: 'noise' | 'warn' | 'error'; text: string; raw: string; cmds?: string[] }
932
933/** The quoted strings of a Python/JSON list literal as the hub prints a shell request: ['a', "b"] -> [a, b]. */
934export function parseCmdList(s: string): string[] {
935 const out: string[] = []
936 const re = /'((?:[^'\\]|\\.)*)'|"((?:[^"\\]|\\.)*)"/g
937 let m: RegExpExecArray | null
938 while ((m = re.exec(s))) out.push((m[1] ?? m[2] ?? '').replace(/\\(["'\\])/g, '$1').replace(/\\n/g, '\n'))
939 return out
940}
941
942const DECISION_ZH: Record<string, string> = { once: '已批准一次', always: '已总是批准', reject: '已拒绝', expired: '已过期' }
943
944/** A hub system notice (first line) as short Chinese. Warnings and errors are kept apart; unknown text stays as it is. */
945export function zhNotice(rawText: string): NoticeInfo {
946 const raw = String(rawText ?? '').split('\n')[0]!.trim()
947 const warn = (text: string): NoticeInfo => ({ kind: 'warn', text, raw })
948 let m: RegExpMatchArray | null
949 const noise = (text: string, cmds?: string[]): NoticeInfo => ({ kind: 'noise', text, raw, ...(cmds ? { cmds } : {}) })
950 // command traces first: an assistant asked to run commands, and how the approval ended (the commands
951 // themselves may say "error", which must not turn the trace into a red warning)
952 if ((m = raw.match(/^(\S+) asks permission: (\w+) (\[.*?\])(?: —|$)/))) {
953 const cmds = parseCmdList(m[3]!)
954 return noise(`${m[1]} 请求${approvalKindLabel(m[2])}(${cmds.length} 条)`, cmds)
955 }
956 if ((m = raw.match(/^approval \S+ \((\w+) (\[.*\])\): (\w+)/))) {
957 const cmds = parseCmdList(m[2]!)
958 return noise(`${DECISION_ZH[m[3]!] ?? m[3]}:${approvalKindLabel(m[1])}(${cmds.length} 条)`, cmds)
959 }
960 if (/^审批 \S+ 已过期/.test(raw)) return noise('审批已过期(助手那边的请求已不存在)')
961 if ((m = raw.match(/^(\S+) paused(?: \((.*)\))?/))) return warn(`⏸ ${m[1]} 已暂停${m[2] ? `(${m[2]})` : ''}`)
962 if ((m = raw.match(/^(\S+) hit its vendor usage limit/))) return warn(`⚠ ${m[1]} 触到厂商额度上限,消息已挂起`)
963 if ((m = raw.match(/^turn \S+ of (\S+) ended without xmuse_send/))) return warn(`⚠ ${m[1]} 的回合结束了,但没有回复`)
964 if ((m = raw.match(/^chain (\S+) capped/))) return warn(`⚠ 连锁对话 ${m[1]} 已封顶,待处理消息被扣下`)
965 if (/no longer bound/i.test(raw) || /\bstall/i.test(raw)) return warn(`⚠ ${raw}`)
966 if (/\b(failed|error)\b/i.test(raw)) return { kind: 'error', text: `⚠ ${raw}`, raw }
967 if ((m = raw.match(/^(\S+) joined the room \((.*)\)$/))) return noise(`${m[1]} 加入(${m[2]})`)
968 if ((m = raw.match(/^(\S+) opened the room/))) return noise(`${m[1]} 打开了房间`)
969 if ((m = raw.match(/^(\S+) left its sidebar session/))) return noise(`${m[1]} 离开了侧栏(仍是成员)`)
970 if ((m = raw.match(/^(\S+) was removed from the room/))) return noise(`${m[1]} 被移出房间`)
971 if ((m = raw.match(/^(\S+) now hosts the room/))) return noise(`${m[1]} 成为主控`)
972 if ((m = raw.match(/^(\S+) was edited: (.*)$/))) return noise(`${m[1]} 的设置已修改:${m[2]}`)
973 if ((m = raw.match(/^private group (\S+) created with (.*)$/))) return noise(`私有小群 ${m[1]} 已建立:${m[2]!.split(/,\s*/).join('、')}`)
974 if ((m = raw.match(/^(\S+) was added to (\S+)$/))) return noise(`${m[1]} 加入 ${m[2]}`)
975 if ((m = raw.match(/^(\S+) was removed from (\S+)$/))) return noise(`${m[1]} 被移出 ${m[2]}`)
976 if ((m = raw.match(/^(\S+) left (\S+)$/))) return noise(`${m[1]} 退出 ${m[2]}`)
977 return noise(raw)
978}
979
980export type NoiseItem = { id: number; text: string; at?: number; cmds?: string[] }
981export type Row =
982 | { kind: 'msg'; m: Msg }
983 | { kind: 'group'; key: string; items: Msg[] } // same sender, same place, within 3 minutes: items oldest first
984 | { kind: 'noise'; key: string; items: NoiseItem[] }
985
986const GROUP_GAP_SEC = 180
987const GROUP_MAX = 6
988
989function plainMsg(m: Msg): boolean {
990 return m.kind !== 'system' && m.kind !== 'done' && !(m as any).retracted
991}
992
993/** older and newer (newest-first list) go under one avatar: same sender, thread and addressees, close in time. */
994function groupable(older: Msg, newer: Msg): boolean {
995 if (!plainMsg(older) || !plainMsg(newer)) return false
996 if (older.from !== newer.from || (older.thread ?? '') !== (newer.thread ?? '')) return false
997 if (toLabel(older) !== toLabel(newer)) return false
998 const a = older.at, b = newer.at
999 return typeof a === 'number' && typeof b === 'number' && b - a <= GROUP_GAP_SEC
1000}
1001
1002/** Newest-first messages to display rows: a run of consecutive noise notices becomes one row (items oldest first). */
1003export function buildRows(msgs: Msg[]): Row[] {
1004 const rows: Row[] = []
1005 let run: NoiseItem[] = []
1006 const flush = () => {
1007 if (!run.length) return
1008 const items = run.slice().reverse()
1009 rows.push({ kind: 'noise', key: `ns-${items[0]!.id}`, items })
1010 run = []
1011 }
1012 for (const m of msgs) {
1013 const zn = m.kind === 'system' ? zhNotice(String(m.text ?? '')) : null
1014 if (zn && zn.kind === 'noise') {
1015 run.push({ id: m.id, text: zn.text, at: m.at, ...(zn.cmds ? { cmds: zn.cmds } : {}) })
1016 continue
1017 }
1018 flush()
1019 const last = rows[rows.length - 1]
1020 const newer = last?.kind === 'msg' ? last.m : last?.kind === 'group' ? last.items[0]! : null
1021 if (last && newer && groupable(m, newer)) {
1022 if (last.kind === 'msg') { rows[rows.length - 1] = { kind: 'group', key: `g-${m.id}`, items: [m, last.m] }; continue }
1023 if (last.kind === 'group' && last.items.length < GROUP_MAX) { rows[rows.length - 1] = { kind: 'group', key: `g-${m.id}`, items: [m, ...last.items] }; continue }
1024 }
1025 rows.push({ kind: 'msg', m })
1026 }
1027 flush()
1028 return rows
1029}
1030
1031/** Time (epoch seconds) a row stands for: its newest item. */
1032export function rowAt(r: Row): number | undefined {
1033 if (r.kind === 'msg') return r.m.at
1034 if (r.kind === 'group') return r.items[r.items.length - 1]?.at
1035 return r.items[r.items.length - 1]?.at
1036}
1037
1038// ---- event cards in the feed: a tone per kind of event, so actions read apart from messages ----------------------
1039
1040export type ToneKey = 'ask' | 'ok' | 'no' | 'info' | 'warn' | 'error' | 'done'
1041// fg: a theme colour name for the icon; bg / border: translucent tints that read on a dark and a light pane
1042export type Tone = { icon: string; fg: string; bg: string; border: string }
1043export const TONES: Record<ToneKey, Tone> = {
1044 ask: { icon: '⌘', fg: 'warning', bg: '#D299220F', border: '#D2992240' },
1045 ok: { icon: '✓', fg: 'success', bg: '#3FB9500D', border: '#3FB95038' },
1046 no: { icon: '✕', fg: 'error', bg: '#F851490D', border: '#F8514938' },
1047 info: { icon: '•', fg: 'subtle', bg: '#8C8C960A', border: '#8C8C962E' },
1048 warn: { icon: '!', fg: 'warning', bg: '#D299220F', border: '#D2992240' },
1049 error: { icon: '!', fg: 'error', bg: '#F851490F', border: '#F8514945' },
1050 done: { icon: '✓', fg: 'success', bg: '#3FB9500A', border: '#3FB95030' },
1051}
1052
1053/** The tone of a run of notices: a pending request wins, then a rejection, an approval; else plain information. */
1054export function noiseTone(items: NoiseItem[]): ToneKey {
1055 const t = items.map(i => i.text)
1056 if (t.some(x => x.includes('请求'))) return 'ask'
1057 if (t.some(x => x.includes('拒绝'))) return 'no'
1058 if (t.some(x => x.includes('批准'))) return 'ok'
1059 return 'info'
1060}
1061
1062/** A noise run's title without its time (the card shows the time apart): the events joined, or "N 件事" past three. */
1063export function noiseTitle(items: NoiseItem[]): string {
1064 return items.length > 3 ? `${items[items.length - 1]!.text} 等 ${items.length} 件事` : items.map(i => i.text).join('、')
1065}
1066
1067/** A small context meter: a rounded track and a fill up to the auto-compact mark, green / amber / red. */
1068export function ctxBarSvg(tokens: unknown, mark = AUTO_COMPACT_TOKENS, w = 56, h = 6): string {
1069 const t = Math.max(0, Number(tokens) || 0)
1070 const ratio = Math.min(1, t / mark)
1071 const lvl = ctxLevel(t, mark)
1072 const fill = lvl === 2 ? '#F85149' : lvl === 1 ? '#D29922' : '#3FB950'
1073 const fw = t > 0 ? Math.max(h, Math.round(ratio * w)) : 0
1074 return `<svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="${h}" viewBox="0 0 ${w} ${h}">`
1075 + `<rect width="${w}" height="${h}" rx="${h / 2}" fill="#8C8C9640"/>`
1076 + (fw ? `<rect width="${fw}" height="${h}" rx="${h / 2}" fill="${fill}"/>` : '') + '</svg>'
1077}
1078
1079/** One line for a noise run: the events joined, or "共 N 件事" past three. */
1080export function noiseSummary(items: NoiseItem[]): string {
1081 const when = fmtClock(items[items.length - 1]?.at)
1082 const body = items.length > 3 ? `共 ${items.length} 件事` : items.map(i => i.text).join('、')
1083 return `· ${when ? when + ' · ' : ''}${body}`
1084}
1085
1086const KIND_ZH: Record<string, string> = { shell: '执行命令', share: '分享私信', alignment: '对齐提案', resume: '恢复会话' }
1087export function approvalKindLabel(kind: string | undefined): string {
1088 const k = kind || 'shell'
1089 return KIND_ZH[k] ?? k
1090}
1091
1092/** "3 分钟前" for an epoch-seconds time ('' when unknown). */
1093export function agoText(at: number | undefined, nowMs: number): string {
1094 if (typeof at !== 'number' || !isFinite(at) || !nowMs) return ''
1095 const sec = Math.max(0, Math.floor((nowMs - (at > 1e11 ? at : at * 1000)) / 1000))
1096 if (sec < 60) return '刚刚'
1097 if (sec < 3600) return `${Math.floor(sec / 60)} 分钟前`
1098 if (sec < 86400) return `${Math.floor(sec / 3600)} 小时前`
1099 return `${Math.floor(sec / 86400)} 天前`
1100}
1101
1102/** A message the assistant wrote when it ended its turn with xmuse_done: text is "{summary}\nnext: {who}". */
1103export function isDoneMsg(m: Msg): boolean {
1104 return m.kind === 'done'
1105}
1106
1107export function doneInfo(m: Msg): { summary: string; next: string; outcome: string } {
1108 const t = String(m.text ?? '')
1109 const k = t.lastIndexOf('\nnext: ')
1110 const body = k >= 0 ? t.slice(0, k) : t
1111 const next = k >= 0 ? t.slice(k + 7).trim() : ''
1112 let summary = body.split('\n').find(l => l.trim())?.trim() ?? ''
1113 if (summary.length > 80) summary = summary.slice(0, 80) + '…'
1114 return { summary, next, outcome: typeof m.outcome === 'string' ? m.outcome : '' }
1115}
1116
1117/** Gets the emphasised "to Claude" look: addressed to the panel's member, and not written by the user or by itself. */
1118export function isToClaude(m: Msg, me: string): boolean {
1119 return m.for_me === true && m.from !== 'human' && m.from !== me
1120}
1121hooks/dev.ts 9 lines1// Development switches of the panel. This copy has DEV false and names no file on any machine; a dev mod folder
2// hot-reloaded in a desktop session keeps its own copy with DEV true and paths of its own (see README.zh.md).
3export const DEV: boolean = false
4export const ROOM_OVERRIDE = '' // dev: a file holding a room directory to use instead of the session's
5export const LOAD_MARK = '' // dev: a file written on each load
6export const FOCUS_MARK = '' // dev: a file the last $.ui.focus answer is written to
7export const REBIND_MARK = '' // dev: a file the last ensureBound outcome is written to
8export const DEV_AVATAR_DIR = '' // dev: avatars, instead of <registry>/avatars
9hooks/grow.tsx 60 lines1import type { ClientModule } from 'claude-code'
2
3// Surface module (a Client region): text that grows step by step (the typing effect of a running member's draft, the
4// reveal of a new message). Its own timer advances it, so the panel is not redrawn per step. When the last step is
5// shown it posts { grown: id } (ui.message in register.tsx) and the panel swaps in its normal rendering.
6// draftTail is a copy of ./logic.ts (a surface module has no documented import): keep it in step.
7
8type GrowProps = {
9 id: string // 't:<member>:<run>' or 'r:<message id>:<run>'; posted back when done
10 text: string
11 from: number // characters shown before the first step
12 stepMs: number
13 steps: number[] // cumulative shown lengths, the last one is text.length
14 mode: string // 'draft' (dim tail in a bubble in the making) or 'md' (a message, Markdown)
15}
16type GrowState = { i: number }
17
18function draftTail(text: string, max = 280): string {
19 const t = String(text ?? '').trim()
20 if (t.length <= max) return t
21 let s = t.slice(-max)
22 const nl = s.indexOf('\n')
23 if (nl >= 0 && nl < 80) s = s.slice(nl + 1)
24 return '…' + s
25}
26
27/** Text a surface can always take: no control characters but tab and newline, and no half of a surrogate pair at a cut. */
28function clean(s: string): string {
29 const t = s.replace(/\r\n?/g, '\n').replace(/[\u0000-\u0008\u000b-\u001f\u007f]/g, '')
30 const last = t.charCodeAt(t.length - 1)
31 return last >= 0xd800 && last <= 0xdbff ? t.slice(0, -1) : t
32}
33
34const Grow: ClientModule<GrowProps, GrowState> = (p, surface) => {
35 const { Text } = surface.elements
36 const st = surface.state
37 if (!st) {
38 surface.setState({ i: 0 })
39 const stop = surface.every(p.stepMs, () => {
40 const s = surface.state
41 const i = (s ? s.i : 0) + 1
42 surface.setState({ i })
43 if (i >= p.steps.length) {
44 stop()
45 surface.post({ grown: p.id })
46 }
47 })
48 }
49 const i = st ? st.i : 0
50 const done = i >= p.steps.length
51 const shown = i <= 0 || !p.steps.length ? p.from : p.steps[Math.min(i, p.steps.length) - 1]!
52 const prefix = clean(p.text.slice(0, shown))
53 // Plain Text in both modes: a Markdown element as the root of a Client made the desktop refuse the tree ("returned a
54 // tree the page cannot draw"); the panel draws the message as Markdown once this is done.
55 if (p.mode === 'md') return <Text>{done ? clean(p.text) : `${prefix} ▍`}</Text>
56 return <Text dimColor>{`${draftTail(prefix)} ▍`}</Text>
57}
58
59export default Grow
60hooks/live.tsx 130 lines1import type { ClientModule } from 'claude-code'
2
3// Surface module (a Client region): the live parts of a working member, drawn without redrawing the panel.
4// part 'act' : "正在:<tool or last line> · m:ss" (the working strip)
5// part 'draft' : the member's latest partial output, typed in a few steps (the draft bubble body)
6// part 'tools' : " · N 个工具" (the running member card's tool count)
7// One timer per instance (every 250 ms): every 4th tick it posts { live: part, id } and the ui.message hook in
8// register.tsx answers with fresh props (liveProps), so the panel itself is not redrawn. The draft's typing runs on the
9// same timer. The elapsed time is computed from the latest props (nowMs is the host clock when the hook answered).
10// startMsOf, fmtElapsed, elapsedLevel, draftTail and softBreak are copies of ./logic.ts / ./elapsed.tsx (a surface module
11// has no documented import): keep them in step.
12
13type LiveProps = { part: string; id: string; tool: string; text: string; tools?: number; startedAt: number; nowMs: number }
14type LiveState = { shown: number; text: string }
15
16const C_AMBER = 'warning'
17const C_RED = 'error'
18const TICK_MS = 250
19const POST_EVERY = 4 // ticks between two posts: once a second
20
21// the newest props of each instance, for its timer (the timer was made by the first render, whose `p` is stale by then)
22const latest = new Map<string, LiveProps>()
23
24function startMsOf(startedAt: number | undefined): number {
25 if (typeof startedAt !== 'number' || !isFinite(startedAt) || startedAt <= 0) return 0
26 return startedAt > 1e11 ? startedAt : startedAt * 1000
27}
28
29function fmtElapsed(startedAt: number | undefined, nowMs: number): string {
30 const s = startMsOf(startedAt)
31 if (!s || !nowMs) return '0:00'
32 const sec = Math.max(0, Math.floor((nowMs - s) / 1000))
33 const p = (n: number) => String(n).padStart(2, '0')
34 const h = Math.floor(sec / 3600)
35 const m = Math.floor((sec % 3600) / 60)
36 return h > 0 ? `${h}:${p(m)}:${p(sec % 60)}` : `${m}:${p(sec % 60)}`
37}
38
39function elapsedLevel(startedAt: number | undefined, nowMs: number): number {
40 const s = startMsOf(startedAt)
41 if (!s || !nowMs) return 0
42 const sec = (nowMs - s) / 1000
43 return sec > 900 ? 2 : sec > 300 ? 1 : 0
44}
45
46function draftTail(text: string, max = 280): string {
47 const t = String(text ?? '').trim()
48 if (t.length <= max) return t
49 let s = t.slice(-max)
50 const nl = s.indexOf('\n')
51 if (nl >= 0 && nl < 80) s = s.slice(nl + 1)
52 return '…' + s
53}
54
55/** Zero-width breaks every 16 characters in runs of 28+ characters that are not space or CJK (a path, a hash). */
56function softBreak(text: string): string {
57 return String(text ?? '').split('\n').map(line => {
58 if (!/\S{28,}/.test(line)) return line
59 return line.split(/(\s+)/).map(tok => {
60 if (tok.length < 28 || /\s/.test(tok)) return tok
61 return tok.replace(/[^\s -鿿-]{16}(?=[^\s -鿿-])/g, s => s + '')
62 }).join('')
63 }).join('\n')
64}
65
66/** Text a surface can always take: no control characters but tab and newline, and no half of a surrogate pair at a cut. */
67function clean(s: string): string {
68 const t = s.replace(/\r\n?/g, '\n').replace(/[\u0000-\u0008\u000b-\u001f\u007f]/g, '')
69 const last = t.charCodeAt(t.length - 1)
70 return last >= 0xd800 && last <= 0xdbff ? t.slice(0, -1) : t
71}
72
73function lastLine(text: string): string {
74 const ls = String(text ?? '').split('\n').map(x => x.trimEnd()).filter(x => x.trim())
75 const l = ls[ls.length - 1] ?? ''
76 return l.length > 160 ? l.slice(0, 160) + '…' : l
77}
78
79/** How much of `text` to show, given the state: an extension of what was seen keeps its shown length, anything else shows at once. */
80function shownOf(st: LiveState | undefined, text: string): number {
81 if (!st) return text.length
82 if (st.text === text) return Math.min(st.shown, text.length)
83 return text.startsWith(st.text) ? Math.min(st.shown, text.length) : text.length
84}
85
86const Live: ClientModule<LiveProps, LiveState> = (p, surface) => {
87 const { Box, Text } = surface.elements
88 const key = `${p.part}:${p.id}`
89 latest.set(key, p)
90 const st = surface.state
91 if (!st) {
92 // the one timer; it reads the newest props and the live state each tick
93 surface.setState({ shown: p.text.length, text: p.text })
94 let n = 0
95 surface.every(TICK_MS, () => {
96 n++
97 const cur = latest.get(key)
98 if (!cur) return
99 if (cur.part === 'draft') {
100 const s = surface.state
101 const sh = shownOf(s, cur.text)
102 const len = cur.text.length
103 const next = sh >= len ? len : Math.min(len, sh + Math.max(1, Math.ceil((len - sh) / 2)))
104 if (!s || s.text !== cur.text || s.shown !== next) surface.setState({ shown: next, text: cur.text })
105 }
106 if (n % POST_EVERY === 0) surface.post({ live: cur.part, id: cur.id })
107 })
108 }
109
110 const t = fmtElapsed(p.startedAt, p.nowMs)
111 if (p.part === 'draft') {
112 const prefix = clean(p.text.slice(0, shownOf(st, p.text)))
113 return <Text dimColor>{`${softBreak(draftTail(prefix))} ▍`}</Text>
114 }
115 if (p.part === 'tools') return <Text dimColor>{` · ${Number(p.tools ?? 0)} 个工具`}</Text>
116 const lvl = elapsedLevel(p.startedAt, p.nowMs)
117 return (
118 <Box flexDirection="row" minWidth={0}>
119 <Box flexShrink={1} minWidth={0} overflow="hidden">
120 <Text dimColor wrap="truncate-end">{`正在:${p.tool || lastLine(p.text) || '思考中'}`}</Text>
121 </Box>
122 <Box flexShrink={0}>
123 <Text color={lvl === 2 ? C_RED : lvl === 1 ? C_AMBER : undefined} dimColor={lvl === 0}>{` ${t}`}</Text>
124 </Box>
125 </Box>
126 )
127}
128
129export default Live
130hooks/elapsed.tsx 64 lines1import type { ClientModule } from 'claude-code'
2
3// Surface module (a Client region): the once-a-second elapsed time of a running member. It counts on its own timer, so the
4// panel is not redrawn every second. Props are plain data; baseMs is the host clock ($.clock.now()) when the panel drew.
5// The sandbox Date.now is not the host clock, so the time shown is baseMs plus the ticks counted here.
6// fmtElapsed, elapsedLevel and the two colours are copies of ./logic.ts (a surface module has no documented import): keep them in step.
7
8type ElProps = { startedAt: number; baseMs: number; kind: string } // kind: 'dots' (dots and time), 'plain', 'level' (coloured by age)
9type ElState = { base: number; ticks: number }
10
11const C_AMBER = 'warning'
12const C_RED = 'error'
13
14function startMsOf(startedAt: number | undefined): number {
15 if (typeof startedAt !== 'number' || !isFinite(startedAt) || startedAt <= 0) return 0
16 return startedAt > 1e11 ? startedAt : startedAt * 1000
17}
18
19function fmtElapsed(startedAt: number | undefined, nowMs: number): string {
20 const s = startMsOf(startedAt)
21 if (!s || !nowMs) return '0:00'
22 const sec = Math.max(0, Math.floor((nowMs - s) / 1000))
23 const p = (n: number) => String(n).padStart(2, '0')
24 const h = Math.floor(sec / 3600)
25 const m = Math.floor((sec % 3600) / 60)
26 return h > 0 ? `${h}:${p(m)}:${p(sec % 60)}` : `${m}:${p(sec % 60)}`
27}
28
29function elapsedLevel(startedAt: number | undefined, nowMs: number): number {
30 const s = startMsOf(startedAt)
31 if (!s || !nowMs) return 0
32 const sec = (nowMs - s) / 1000
33 return sec > 900 ? 2 : sec > 300 ? 1 : 0
34}
35
36const Elapsed: ClientModule<ElProps, ElState> = (p, surface) => {
37 const { Text } = surface.elements
38 const st = surface.state
39 if (!st) {
40 // start the one timer; the callback reads the live state, so it follows the props of later draws
41 surface.setState({ base: p.baseMs, ticks: 0 })
42 surface.every(1000, () => {
43 const s = surface.state
44 if (s) surface.setState({ base: s.base, ticks: s.ticks + 1 })
45 })
46 } else if (st.base !== p.baseMs) {
47 surface.setState({ base: p.baseMs, ticks: 0 }) // the panel redrew with a fresh clock reading: count from it
48 }
49 const ticks = st && st.base === p.baseMs ? st.ticks : 0
50 const now = p.baseMs + ticks * 1000
51 const t = fmtElapsed(p.startedAt, now)
52 if (p.kind === 'dots') {
53 const dots = ['· ', '·· ', '···'][Math.floor(now / 1000) % 3]!
54 return <Text dimColor>{`${dots} ${t}`}</Text>
55 }
56 if (p.kind === 'level') {
57 const lvl = elapsedLevel(p.startedAt, now)
58 return <Text color={lvl === 2 ? C_RED : lvl === 1 ? C_AMBER : undefined} dimColor={lvl === 0}>{` ${t}`}</Text>
59 }
60 return <Text dimColor>{` ${t}`}</Text>
61}
62
63export default Elapsed
64types/index.d.ts 43 lines1export type ConnInfo = { phase: 'idle' | 'connecting' | 'ok' | 'error' | 'noroom'; error: string }
2
3declare module 'claude-code' {
4 interface PluginState {
5 xmuse: {
6 conn: ConnInfo
7 view: any
8 tab: string
9 replyTo: number
10 gen: number
11 promoted: Record<string, string>
12 lastRead: string
13 light: boolean
14 mention: string | null
15 forced: string | null
16 decision: { id: number; text: string; ok: boolean }
17 avatarVer: number
18 sendN: number
19 inputGen: number
20 sending: boolean
21 addOpen: boolean
22 expanded: string
23 busy: Record<string, boolean>
24 fold: Record<string, boolean>
25 open: { busy: boolean; msg: string; error: string }
26 done: Record<string, { tools: number; startedMs: number; endedMs: number }>
27 brief: boolean
28 older: { items: any[]; hasMore: boolean; loading: boolean }
29 shown: Record<string, number>
30 selfCtx: number
31 probe: boolean
32 layout: 'chat' | 'flow'
33 railFold: boolean
34 scrollProbe: { n: number; by: number; offset: number; bodyRows: number; contentRows: number; origin: string }
35 reveal: { id: number; steps: number[]; run: number }
36 modelPick: {
37 member: string; current: string; options: { value: string; label?: string }[]; format: string; note: string
38 loading: boolean; error: string
39 } | null
40 }
41 }
42}
43