Files
themiz/plugins/femida-lineup/hooks/register.tsx
T

163 lines
8.5 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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 вложенные картинки <image>, а контуры рисует.
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<string, string> = {
ok: '#3a8f5c', running: '#c9a227', start: '#c9a227', fail: '#b3261e', stopped: '#b3261e', failed: '#b3261e',
}
const MARK: Record<string, string> = { ok: '✓', fail: '✕', stopped: '✕', failed: '✕' }
const W = 96
const H = 118
const esc = (s: string) => s.replace(/[&<>"]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[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<string, Face> = 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
? `<circle cx="${x}" cy="36" r="31" fill="none" stroke="${color}" stroke-width="3"><animate attributeName="r" values="30;34;30" dur="1.6s" repeatCount="indefinite"/><animate attributeName="stroke-opacity" values="1;.35;1" dur="1.6s" repeatCount="indefinite"/></circle>`
: `<circle cx="${x}" cy="36" r="30" fill="none" stroke="${color}" stroke-width="${idle ? 1 : 3}"/>`
const mark = MARK[st.status]
? `<circle cx="${x + 21}" cy="57" r="9" fill="${color}"/><text x="${x + 21}" y="61" font-size="12" fill="#fff" text-anchor="middle">${MARK[st.status]}</text>`
: ''
const link = i < s.stations.length - 1
? `<line x1="${x + 32}" y1="36" x2="${x + W - 32}" y2="36" stroke="${st.status === 'ok' ? COLOR.ok : '#8a8a8a'}" stroke-width="2" stroke-opacity="${st.status === 'ok' ? 1 : 0.35}"/>`
: ''
const face = pic
? `<g clip-path="url(#c${i})" opacity="${idle ? 0.35 : 1}"${idle ? ' filter="url(#gray)"' : ''}>`
+ `<g transform="translate(${x - 28} 8) scale(${56 / FACE_PX})" fill="none" shape-rendering="crispEdges">`
+ `<rect width="${FACE_PX}" height="${FACE_PX}" fill="${pic[0]}"/>`
+ pic[1].map(([stroke, d]) => `<path stroke="${stroke}" d="${d}"/>`).join('') + '</g></g>'
: `<circle cx="${x}" cy="36" r="28" fill="#8a8a8a" fill-opacity=".2"/>`
return `<clipPath id="c${i}"><circle cx="${x}" cy="36" r="28"/></clipPath>${link}${face}${ring}${mark}`
+ `<text x="${x}" y="88" font-size="12" font-weight="${live ? 700 : 500}" fill="${idle ? '#8a8a8a' : 'currentColor'}" text-anchor="middle">${esc(st.title)}</text>`
+ `<text x="${x}" y="104" font-size="10.5" fill="#8a8a8a" text-anchor="middle">${esc(st.who)}</text>`
+ `<title>${esc(`${st.title}: ${st.who}`)}</title>`
})
return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${W * s.stations.length} ${H}" font-family="-apple-system, system-ui, sans-serif" style="color:#999">`
+ `<defs><filter id="gray"><feColorMatrix type="saturate" values="0"/></filter></defs>${cells.join('')}</svg>`
}
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 (
<Box flexDirection="column">
<Box>
{s.stations.map(st => (
<Text key={st.id} color={isLive(s, st) ? 'yellow' : st.status === 'ok' ? 'green' : MARK[st.status] ? 'red' : undefined} dimColor={!st.status && !isLive(s, st)}>
{isLive(s, st) ? '● ' : MARK[st.status] ? `${MARK[st.status]} ` : '○ '}{st.title} ({st.who}){' '}
</Text>
))}
</Box>
<Box>
<Text dimColor>{line} </Text>
<Button {...hide} />
</Box>
</Box>
)
}
const { Box, Text, Button, Svg } = $.ui.resolve(e)
return (
<Box flexDirection="column">
{/* живой кадр (пульс) - только когда кто-то реально работает; иначе неподвижная картинка */}
{Svg ? <Svg source={lineupSvg(s)} alt={line} isInteractive={s.stations.some(st => isLive(s, st))} /> : null}
<Box>
<Text dimColor>{line} </Text>
<Button {...hide} />
</Box>
</Box>
)
})
}