import { atom, read, update } from 'claude-code' import type { Engine, Register } from 'claude-code' import type { Snapshot, Station } from '../types' import { FACE_PX, FACES } from './faces' // Линейка прогона Фемиды над полем ввода: портреты юристов по этапам core.PHASES. // Данные - state.json и events.jsonl последнего прогона, читает hooks/snapshot.py. // Мод живет в репозитории Фемиды (plugins/femida-lineup): корень Фемиды - корень сессии. const PYTHON = ['/usr/bin/env', 'python3'] // Портрет - штрихи по цветам (hooks/faces.ts, собирает hooks/vectorize.py из портретов кокпита): // приложение вырезает из Svg вложенные картинки , а контуры рисует. type Face = [string, Array<[string, string]>] const POLL_MS = 3_000 // как board.py const SHOW_MIN = 20 // законченный прогон висит 20 минут после последней записи const snap = atom({ plugin: 'femida-lineup', key: 'snap' } as const, null) const hidden = atom({ plugin: 'femida-lineup', key: 'hidden' } as const, '') const problem = atom({ plugin: 'femida-lineup', key: 'problem' } as const, null) const pinned = atom({ plugin: 'femida-lineup', key: 'pinned' } as const, false) const COLOR: Record = { ok: '#3a8f5c', running: '#c9a227', start: '#c9a227', fail: '#b3261e', stopped: '#b3261e', failed: '#b3261e', } const MARK: Record = { ok: '✓', fail: '✕', stopped: '✕', failed: '✕' } const W = 96 const H = 118 const esc = (s: string) => s.replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[c]!) const clock = (s: number) => (s < 3600 ? `${Math.max(1, Math.round(s / 60))} мин` : `${Math.floor(s / 3600)} ч ${Math.floor((s % 3600) / 60)} мин`) // Этап, который сейчас идет: фаза из state.json, пока прогон жив. export const isLive = (s: Snapshot, st: Station) => s.status === 'running' && st.id === s.phase && st.status !== 'ok' export function lineupSvg(s: Snapshot, pics: Record = FACES): string { const cells = s.stations.map((st, i) => { const x = i * W + W / 2 const live = isLive(s, st) const color = live ? COLOR.running : COLOR[st.status] ?? '#8a8a8a' const idle = !live && !st.status const pic = pics[st.face] const ring = live ? `` : `` const mark = MARK[st.status] ? `${MARK[st.status]}` : '' const link = i < s.stations.length - 1 ? `` : '' const face = pic ? `` + `` + `` + pic[1].map(([stroke, d]) => ``).join('') + '' : `` return `${link}${face}${ring}${mark}` + `${esc(st.title)}` + `${esc(st.who)}` + `${esc(`${st.title}: ${st.who}`)}` }) return `` + `${cells.join('')}` } export function headline(s: Snapshot): string { const live = s.stations.find(st => isLive(s, st)) const now = live ? `${live.title} · ${s.who || live.who}` : s.label // время не тикает: строка меняется только с новым событием прогона, иначе линейка перерисовывается и мерцает const time = s.status === 'running' ? `с ${s.since}` : `шел ${clock(s.elapsed)}` return `Фемида · ${s.kase} · ${s.track} · ${s.doc} — ${now} · этапов ${s.done} из ${s.total} · ${time}` } let busy = false let last = '' let themiz = '' async function poll($: Engine) { if (busy) return busy = true try { const out = await $.process.run([...PYTHON, `${$.plugin.root}/hooks/snapshot.py`, themiz], { timeoutMs: 10_000 }) if (out.exitCode !== 0) throw new Error(out.stderr.trim().split('\n').pop() || `код ${out.exitCode}`) const value = JSON.parse(out.stdout) as Snapshot | null const fresh = value ? { ...value, fresh: value.status === 'running' || Date.now() / 1000 - value.mtime < SHOW_MIN * 60 } : null const key = JSON.stringify(fresh) if (key !== last) { last = key await update($, snap, () => fresh) } if ((await read($, problem)) !== null) await update($, problem, () => null) } catch (error) { const text = error instanceof Error ? error.message : String(error) await update($, problem, () => text) } finally { busy = false } } export const register: Register = on => { on('session.start', async ($, e, next) => { const root = await $.session.root() if (!(await $.fs.exists(`${root}/themiz-next/core.py`))) return next(e) themiz = root await $.command.register({ name: 'lineup', description: 'Линейка юристов Фемиды: показать последний прогон или скрыть' }) void poll($) $.clock.every(POLL_MS, () => void poll($)) return next(e) }) on('command.run', { command: 'lineup' }, async $ => { const show = !(await read($, pinned)) await update($, pinned, () => show) await update($, hidden, () => '') void poll($) return { text: show ? 'Линейка Фемиды открыта.' : 'Линейка Фемиды показывается только во время прогона.' } }) on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => { const s = await read($, snap) if (e.props.hasSurvey || s === null) return next(e) if (!s.fresh && !(await read($, pinned))) return next(e) if ((await read($, hidden)) === s.run) return next(e) const trouble = await read($, problem) const line = headline(s) + (trouble ? ` · табло: ${trouble}` : '') const hide = { key: 'hide', label: 'Скрыть', onPress: () => update($, hidden, () => s.run) } if (e.surface === 'terminal') { const { Box, Text, Button } = $.ui.resolve(e) return ( {s.stations.map(st => ( {isLive(s, st) ? '● ' : MARK[st.status] ? `${MARK[st.status]} ` : '○ '}{st.title} ({st.who}){' '} ))} {line}