Source 9 files
hooks/register.mjs 293 lines
1// factory v2 - the side panel of all agents, read-only:
2// /factory [mission|focus|arbre|workflow|pipeline|quotas|systeme|journal] [title or id] /factory workflow [all]
3// Tabs on top, each screen stacked top to bottom and as wide as the pane (draw.mjs, native elements, no canvas).
4// Data: scanner/factory_scan.py (incremental tail reads of the transcripts, cache in the effort-board); quotas and runner
5// load from lib/core (usage.mjs, runner.mjs) through scanner/extras.mjs, plus $.session.usage(); Système's PC sample from
6// the machine mod's sampler. These screens now also live inside Cockpit (/cockpit). Each
7// source runs only while the pane is open and its tab is showing. Nothing here blocks, rewrites or adds to a prompt.
8import { deepMerge, pickSession, scanArgs, engineAtLeast } from './logic.mjs'
9import { waitingConfig, waitingRows, waitingArgs, toAnnounce, notifyText, holdsLease, fill } from './waiting.mjs'
10import { screensConfig, tabsOf, parseArgs } from './screens.mjs'
11import { drawFactoryPane, allTabs } from './workflow_draw.mjs'
12import { workflowConfig, parseWorkflowArgs, workflowArgs } from './workflow.mjs'
13
14let CFG = null
15const D = {
16 scan: null, target: null, self: null, busy: false, error: '', at: 0, open: false, tab: null, filter: 'all', jfilter: 'all', jproject: '',
17 picking: false, live: [], quotas: null, quotasAt: 0, machine: { sample: null, runner: null, prev: null, tick: 0, missing: false, metricsMissing: false, error: '', runnerAt: 0 },
18 columns: 0, engine: '',
19 wf: null, wfAt: 0, wfBusy: false, wfError: '', wfScope: null, wfOpen: {},
20}
21
22async function homeDir($) {
23 return ((await $.env.get('USERPROFILE')) || (await $.env.get('HOME')) || '').replace(/\\/g, '/')
24}
25
26// FACTORY_BOARD overrides the effort-board folder (tests, dry runs); default ~/.claude/effort-board.
27async function board($) {
28 const o = await $.env.get('FACTORY_BOARD')
29 return o ? o.replace(/\\/g, '/') : (await homeDir($)) + '/.claude/effort-board'
30}
31
32async function readJson($, path) {
33 try {
34 if (!(await $.fs.exists(path))) return null
35 return JSON.parse(await $.fs.read(path))
36 } catch {
37 return null
38 }
39}
40
41// factory.config.json beside the mod, deep-merged with ~/.claude/effort-board/factory.config.json when present.
42async function loadConfig($) {
43 const base = (await readJson($, $.plugin.root.replace(/\\/g, '/') + '/factory.config.json')) || {}
44 const wf = await readJson($, $.plugin.root.replace(/\\/g, '/') + '/workflow.config.json')
45 const over = await readJson($, (await board($)) + '/factory.config.json')
46 CFG = deepMerge(deepMerge(base, wf ? { workflow: wf } : {}), over || {})
47 if (!D.tab) D.tab = screensConfig(CFG).start
48 return CFG
49}
50
51const root = ($) => $.plugin.root.replace(/\\/g, '/')
52const sibling = ($, mod) => root($).replace(/\/[^/]+\/?$/, '') + '/' + mod
53
54async function rescan($) {
55 if (D.busy) return
56 D.busy = true
57 try {
58 const cfg = CFG || (await loadConfig($))
59 const argv = [cfg.python || 'python', ...scanArgs(cfg, {
60 script: root($) + '/scanner/factory_scan.py', cache: (await board($)) + '/factory_cache.json', detail: D.target || D.self,
61 extra: [...waitingArgs(cfg), '--recent', String(screensConfig(cfg).recent_events)],
62 })]
63 const r = await $.process.run(argv, { timeoutMs: 180000 })
64 if (r.exitCode !== 0) throw new Error((r.stderr || '').trim().split('\n').pop() || `scanner exit ${r.exitCode}`)
65 D.scan = JSON.parse(r.stdout)
66 D.error = ''
67 D.at = await $.clock.now()
68 } catch (err) {
69 D.error = String(err && err.message ? err.message : err).slice(0, 300)
70 } finally {
71 D.busy = false
72 }
73 $.ui.invalidate('ui.render')
74 if (D.scan && !D.error) await announce($).catch(() => undefined)
75}
76
77// The Workflow screen's own scanner (scanner/workflow_scan.py): runs only while that tab is showing.
78async function rescanWorkflow($) {
79 if (D.wfBusy) return
80 D.wfBusy = true
81 $.ui.invalidate('ui.render')
82 try {
83 const cfg = CFG || (await loadConfig($))
84 const scope = D.wfScope || workflowConfig(cfg).scope
85 const argv = [cfg.python || 'python', ...workflowArgs(cfg, {
86 script: root($) + '/scanner/workflow_scan.py', cache: (await board($)) + '/factory_workflow_cache.json', scope, session: D.self || '',
87 })]
88 const r = await $.process.run(argv, { timeoutMs: 180000 })
89 if (r.exitCode !== 0) throw new Error((r.stderr || '').trim().split('\n').pop() || `workflow_scan exit ${r.exitCode}`)
90 D.wf = JSON.parse(r.stdout)
91 D.wfError = ''
92 D.wfAt = await $.clock.now()
93 } catch (err) {
94 D.wfError = String(err && err.message ? err.message : err).slice(0, 300)
95 } finally {
96 D.wfBusy = false
97 }
98 $.ui.invalidate('ui.render')
99}
100
101const refreshTab = ($) => (D.tab === 'workflow' ? rescanWorkflow($) : rescan($))
102
103// ---- extras: only for the tab on screen ----------------------------------------------------------------------------
104
105async function loadQuotas($, force) {
106 const sc = screensConfig(CFG || {})
107 const now = await $.clock.now()
108 if (!force && D.quotas && now - D.quotasAt < sc.quotas_refresh_s * 1000) return
109 try { D.live = ((await $.session.usage()) || {}).rateLimits || [] } catch { D.live = [] }
110 try {
111 const r = await $.process.run([CFG.node || 'node', root($) + '/scanner/extras.mjs', 'quotas'], {
112 stdin: JSON.stringify({ live: D.live, now, home: await homeDir($) }), timeoutMs: 60000,
113 })
114 D.quotas = r.exitCode === 0 ? JSON.parse(r.stdout) : { available: false, reason: (r.stderr || '').trim().split('\n').pop() || 'extras' }
115 } catch (err) {
116 D.quotas = { available: false, reason: String(err && err.message ? err.message : err).slice(0, 120) }
117 }
118 D.quotasAt = now
119 $.ui.invalidate('ui.render')
120}
121
122async function sampleMachine($) {
123 const sc = screensConfig(CFG || {})
124 const M = D.machine
125 const script = sibling($, 'machine') + '/scanner/machine.py'
126 try { M.missing = !(await $.fs.exists(script)) } catch { M.missing = true }
127 try { M.metricsMissing = !(await $.fs.exists(sibling($, 'metrics') + '/.claude-plugin/plugin.json')) } catch { M.metricsMissing = true }
128 if (M.missing) { $.ui.invalidate('ui.render'); return }
129 const py = (CFG && CFG.python) || 'python'
130 try {
131 const gpu = M.tick % Math.max(1, sc.gpu_every) === 0
132 M.tick += 1
133 const r = await $.process.run([py, '-I', script, 'sample'], { stdin: JSON.stringify({ prev: M.prev, gpu, top_n: 5 }), timeoutMs: 20000 })
134 if (r.exitCode !== 0) throw new Error((r.stderr || '').trim().split('\n').pop() || `machine exit ${r.exitCode}`)
135 const s = JSON.parse(r.stdout)
136 M.prev = s.raw
137 if (!gpu && M.sample && M.sample.gpu) s.gpu = M.sample.gpu // keep the last GPU reading between spaced reads
138 M.sample = s
139 M.error = ''
140 const now = await $.clock.now()
141 if (now - M.runnerAt > sc.system_refresh_s * 6000) {
142 M.runnerAt = now
143 // runner load: lib/core/runner.mjs through scanner/extras.mjs (the ci mod's cache), the same figures as band and cockpit
144 const rr = await $.process.run([(CFG && CFG.node) || 'node', root($) + '/scanner/extras.mjs', 'runner'], { stdin: JSON.stringify({ now, home: await homeDir($) }), timeoutMs: 30000 })
145 M.runner = rr.exitCode === 0 ? JSON.parse(rr.stdout) : { error: 'runner : lecture impossible' }
146 }
147 } catch (err) {
148 M.error = String(err && err.message ? err.message : err).slice(0, 200)
149 }
150 $.ui.invalidate('ui.render')
151}
152
153async function onTabShown($) {
154 if (D.tab === 'quotas') await loadQuotas($, false)
155 if (D.tab === 'systeme') await sampleMachine($)
156}
157
158// ---- "Ça t'attend": notifications, one per row ever (keys kept in $.store, shared by every session) ---------------
159
160async function announce($) {
161 const w = waitingConfig(CFG)
162 if (!w.enabled) return
163 const { rows } = waitingRows(D.scan, CFG, D.at)
164 let seen = null
165 try { seen = (await $.store.get('waiting_seen')) ?? null } catch { seen = null }
166 const r = toAnnounce(rows, seen, CFG, D.at)
167 try { await $.store.set('waiting_seen', r.seen) } catch { return } // without a record, do not risk repeating
168 for (const row of r.announce) await notify($, notifyText(row), w)
169 if (r.more) await notify($, fill(w.labels.notify_more, { n: r.more }), w)
170}
171
172// $.ui.notify (a native notification through the person's channel) is in the build's types, not on the doc pages:
173// when it is missing or not sent, a toast says the same thing.
174async function notify($, text, w) {
175 try {
176 const res = await $.ui.notify(text, { title: w.labels.notify_title })
177 if (res && res.isSent) return
178 } catch { /* fall back to a toast */ }
179 $.ui.toast(`${w.labels.notify_title}: ${text}`, { timeoutMs: 8000 })
180}
181
182// With the pane closed, one session on the PC (the lease holder) still scans every background_s for notifications.
183async function background($) {
184 const w = waitingConfig(CFG || {})
185 if (!w.enabled || !w.notify || D.open || D.busy) return
186 const now = await $.clock.now()
187 const self = D.self || 'unknown'
188 let lease = null
189 try { lease = await $.store.get('waiting_lease') } catch { return }
190 if (!holdsLease(lease, self, now, w.background_s * 1000)) return
191 try { await $.store.set('waiting_lease', { sid: self, at: now }) } catch { return }
192 await rescan($)
193}
194
195// ---- navigation ------------------------------------------------------------------------------------------------------
196
197async function go($, tab, target) {
198 if (tab) D.tab = tab
199 if (target !== undefined) { D.target = target === D.self ? null : target; D.picking = false }
200 $.ui.invalidate('ui.render')
201 await refreshTab($)
202 await onTabShown($)
203}
204
205async function openPane($) {
206 D.open = true
207 await $.ui.open({ id: 'factory', title: 'Factory', focus: true, closeOnEscape: true })
208}
209
210function actions($) {
211 const redraw = () => $.ui.invalidate('ui.render')
212 return {
213 tab: (id) => { D.tab = id; redraw(); if (id === 'workflow') void rescanWorkflow($); else { if (!D.scan) void rescan($); void onTabShown($) } },
214 go: (cli) => { void go($, 'arbre', cli) },
215 refresh: () => { void refreshTab($); if (D.tab === 'quotas') void loadQuotas($, true); if (D.tab === 'systeme') void sampleMachine($) },
216 filter: (k) => { D.filter = k; redraw() },
217 jfilter: (k) => { D.jfilter = k; redraw() },
218 jproject: (p) => { D.jproject = p; redraw() },
219 pick: () => { D.picking = !D.picking; redraw() },
220 wfScope: (k) => { D.wfScope = k; redraw(); void rescanWorkflow($) },
221 wfToggle: (key, open) => { D.wfOpen = { ...D.wfOpen, [key]: open }; redraw() },
222 openAgent: (id) => { void viewAgent($, { agentId: id }) },
223 backToConv: () => { void viewAgent($, {}) },
224 }
225}
226
227// « Ouvrir l'agent »: the engine's transcript view of one agent of this conversation ($.ui.view, 2.1.300+; a press is
228// person-initiated, which the engine requires). Older engines have no $.ui.view: the button is not drawn, a toast here.
229const VIEW_MIN = '2.1.300'
230
231async function viewAgent($, target) {
232 if (!engineAtLeast(D.engine, VIEW_MIN)) { $.ui.toast(`Ouvrir un agent demande Claude Code ${VIEW_MIN} ou plus récent (claude update)`); return }
233 try {
234 const r = await $.ui.view(target)
235 if (r && r.deny) $.ui.toast(`Agent non ouvert : ${r.deny}`)
236 } catch (err) {
237 $.ui.toast(`Agent non ouvert : ${String(err && err.message ? err.message : err).slice(0, 120)}`)
238 }
239}
240
241export function register(on) {
242 on('session.start', async ($, e, next) => {
243 try { D.self = await $.session.id() } catch { D.self = null }
244 try { D.engine = ((await $.session.version()) || {}).version || '' } catch { D.engine = '' }
245 await loadConfig($).catch(() => { CFG = {} })
246 const sc = screensConfig(CFG || {})
247 $.clock.every(Math.max(5, (CFG && CFG.refresh_s) || 20) * 1000, () => { if (D.open && D.tab !== 'workflow') void rescan($) })
248 $.clock.every(Math.max(5, workflowConfig(CFG || {}).refresh_s) * 1000, () => { if (D.open && D.tab === 'workflow') void rescanWorkflow($) })
249 $.clock.every(Math.max(3, sc.system_refresh_s) * 1000, () => { if (D.open && D.tab === 'systeme') void sampleMachine($) })
250 $.clock.every(Math.max(30, sc.quotas_refresh_s) * 1000, () => { if (D.open && D.tab === 'quotas') void loadQuotas($, true) })
251 $.clock.every(Math.max(30, waitingConfig(CFG || {}).background_s) * 1000, () => { void background($).catch(() => undefined) })
252 try {
253 await $.command.register({
254 name: 'factory', immediate: true,
255 description: 'Factory : Mission, Focus, Arbre, Workflow, Pipeline, Quotas, Système, Journal de tous les agents (/factory [onglet] [titre ou id], /factory workflow [all])',
256 argumentHint: '[mission|focus|arbre|workflow|pipeline|quotas|systeme|journal] [titre ou id] | workflow all | close',
257 })
258 } catch { /* a name clash must not break the rest */ }
259 return next(e)
260 })
261
262 on('command.run', { command: 'factory' }, async ($, e) => {
263 await loadConfig($)
264 try { D.self = (await $.session.id()) || D.self } catch { /* keep the last one */ }
265 try { D.engine = ((await $.session.version()) || {}).version || D.engine } catch { /* keep */ }
266 const q = String(e.args || '').trim()
267 if (q.toLowerCase() === 'close') { D.open = false; await $.ui.close({ id: 'factory' }); return {} }
268 await openPane($)
269 const wa = parseWorkflowArgs(q)
270 if (wa.workflow) { if (wa.scope) D.wfScope = wa.scope; await go($, 'workflow'); return {} }
271 const { tab, rest } = parseArgs(q, CFG)
272 if (!rest) { await go($, tab || D.tab || screensConfig(CFG).start); return {} }
273 if (!D.scan) await rescan($)
274 const s = pickSession(D.scan && D.scan.sessions, rest)
275 await go($, tab || 'arbre', s ? s.cli : rest)
276 return {}
277 })
278
279 on('ui.close', { id: 'factory' }, async ($, e, next) => { D.open = false; return next(e) }).catch(() => undefined)
280
281 on('ui.render', { component: 'Pane' }, async ($, e, next) => {
282 if (e.requestId !== 'factory') return next(e)
283 const el = $.ui.resolve(e)
284 if (!CFG) CFG = {}
285 const cols = Number(e.props && e.props.bodyColumns) || 0
286 D.columns = cols
287 if (!allTabs(CFG).some((t) => t.id === D.tab)) D.tab = (tabsOf(CFG)[0] || { id: 'mission' }).id
288 const canView = engineAtLeast(D.engine, VIEW_MIN)
289 const viewAgent = (e.props && e.props.view && e.props.view.agentId) || null
290 return drawFactoryPane(el, { ...D, cfg: CFG, columns: cols, canView, viewAgent, act: actions($) })
291 })
292}
293
hooks/logic.mjs 291 lines
1// factory - pure logic (no $, no I/O): config merge, pricing, warnings, and the models the two views draw.
2// Input is the JSON printed by scanner/factory_scan.py. Tested with node --test tests/logic.test.mjs.
3
4export const FAMILIES = ['opus', 'sonnet', 'haiku', 'fable']
5
6export function deepMerge(base, over) {
7 if (!over || typeof over !== 'object' || Array.isArray(over)) return over === undefined ? base : over
8 const out = { ...(base || {}) }
9 for (const [k, v] of Object.entries(over)) {
10 out[k] = v && typeof v === 'object' && !Array.isArray(v) && base && typeof base[k] === 'object' && !Array.isArray(base[k])
11 ? deepMerge(base[k], v) : v
12 }
13 return out
14}
15
16export function family(model) {
17 const m = String(model || '').toLowerCase()
18 return FAMILIES.find((f) => m.includes(f)) || 'other'
19}
20
21// Rate for a model id: exact id, else its family, else default.
22export function rateFor(model, cfg) {
23 const r = cfg.rates || {}
24 return r[model] || r[family(model)] || r.default || { in: 0, out: 0, cache_read: 0, cache_write_5m: 0, cache_write_1h: 0 }
25}
26
27// v = [in, out, cache_read, cache_write_5m, cache_write_1h, calls]
28export function costOf(model, v, cfg) {
29 const r = rateFor(model, cfg)
30 return ((v[0] || 0) * r.in + (v[1] || 0) * r.out + (v[2] || 0) * r.cache_read + (v[3] || 0) * r.cache_write_5m
31 + (v[4] || 0) * r.cache_write_1h) / 1e6
32}
33
34export function tokensOf(v) {
35 return (v[0] || 0) + (v[1] || 0) + (v[2] || 0) + (v[3] || 0) + (v[4] || 0)
36}
37
38// Sum a list of {model: vec} maps into {model: {tokens, cost, calls, out}}.
39export function billByModel(maps, cfg) {
40 const out = {}
41 for (const mp of maps) {
42 for (const [m, v] of Object.entries(mp || {})) {
43 const o = out[m] || (out[m] = { tokens: 0, cost: 0, calls: 0, out: 0 })
44 o.tokens += tokensOf(v)
45 o.cost += costOf(m, v, cfg)
46 o.calls += v[5] || 0
47 o.out += v[1] || 0
48 }
49 }
50 return out
51}
52
53export function sumCost(bill) {
54 return Object.values(bill).reduce((a, b) => a + b.cost, 0)
55}
56
57export function localDay(epochMs) {
58 const d = new Date(epochMs)
59 return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
60}
61
62export function fmtTokens(n) {
63 if (n >= 1e9) return (n / 1e9).toFixed(1) + 'B'
64 if (n >= 1e6) return (n / 1e6).toFixed(1) + 'M'
65 if (n >= 1e3) return Math.round(n / 1e3) + 'K'
66 return String(n || 0)
67}
68
69export function fmtUsd(x) {
70 return '$' + (x >= 100 ? x.toFixed(0) : x.toFixed(2))
71}
72
73export function hhmm(ts) {
74 if (!ts) return '--:--'
75 const d = new Date(ts)
76 return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}:${String(d.getSeconds()).padStart(2, '0')}`
77}
78
79export function short(model) {
80 const m = String(model || '?')
81 return m.replace(/^claude-/, '').replace(/-\d{8}$/, '').replace(/-(\d+)-(\d+)$/, ' $1.$2')
82}
83
84// The engine's version ("2.1.302", $.session.version().version) is at least min: how a mod turns on an API newer
85// than the oldest engine it runs on (a mod may not read $.noun.event as a value to test it). Unknown: false.
86export function engineAtLeast(version, min) {
87 const a = String(version || '').split(/[.-]/).slice(0, 3).map((x) => Number(x))
88 const b = String(min || '').split('.').map((x) => Number(x))
89 if (a.length < 3 || a.some((x) => !Number.isFinite(x))) return false
90 for (let i = 0; i < 3; i++) if (a[i] !== b[i]) return a[i] > b[i]
91 return true
92}
93
94export function repoOf(s) {
95 const p = String(s.origin || s.cwd || '').replace(/\\/g, '/')
96 const i = p.indexOf('/.claude/worktrees/')
97 const base = i >= 0 ? p.slice(0, i) : p
98 return base.split('/').filter(Boolean).pop() || '?'
99}
100
101export function titleOf(s) {
102 return s.app_title || s.title || String(s.cli || '').slice(0, 8)
103}
104
105export function architectReason(text, cfg) {
106 const a = cfg.architect || {}
107 for (const r of a.reasons || []) if (new RegExp(r.match, 'i').test(text || '')) return r.label
108 return a.fallback || 'other'
109}
110
111export function isArchitect(sub, cfg) {
112 return ((cfg.architect && cfg.architect.types) || ['architect']).includes(sub.type)
113}
114
115export function ctxPct(ctx, cfg) {
116 return Math.round((100 * (ctx || 0)) / (cfg.context_window || 400000))
117}
118
119export function ctxLevel(ctx, cfg) {
120 const p = (100 * (ctx || 0)) / (cfg.context_window || 400000)
121 const t = cfg.thresholds || {}
122 return p >= (t.ctx_bad_pct ?? 62.5) ? 'bad' : p >= (t.ctx_warn_pct ?? 50) ? 'warn' : 'ok'
123}
124
125function loopText(loops) {
126 return Object.entries(loops || {}).filter(([, n]) => n > 0).map(([k, n]) => `${k} x${n}`).join(', ')
127}
128
129// Warnings for one conversation (row or detail). Each: {level, text}.
130export function warnings(s, cfg) {
131 const t = cfg.thresholds || {}
132 const out = []
133 const subs = s.subs || []
134 const noModel = subs.filter((x) => !x.workflow && !x.explicit_model)
135 if (noModel.length) {
136 out.push({ level: 'warn', text: `${noModel.length} subagent(s) without explicit model (inherit ${short(s.model)}): ${noModel.slice(0, 3).map((x) => x.desc || x.type).join(', ')}` })
137 }
138 const ro = (cfg.readonly_agent_types || [])
139 const exempt = (cfg.readonly_exempt_types || [])
140 const opusRo = subs.filter((x) => family(x.model) === 'opus' && !exempt.includes(x.type) && (ro.includes(x.type)
141 || (x.tools >= (t.readonly_opus_min_calls ?? 5) && x.readonly / Math.max(1, x.tools) >= (t.readonly_opus_share ?? 0.8))))
142 if (opusRo.length) out.push({ level: 'warn', text: `Opus doing read-only search in ${opusRo.length} subagent(s): ${opusRo.slice(0, 3).map((x) => x.desc || x.type).join(', ')} (use Haiku)` })
143 if (family(s.model) === 'opus' && s.tools >= 20 && s.readonly / Math.max(1, s.tools) >= (t.readonly_opus_share ?? 0.8)) {
144 out.push({ level: 'warn', text: `Opus main thread: ${s.readonly}/${s.tools} tool calls are read-only search (delegate to explore-fast on Haiku)` })
145 }
146 if ((s.ctx || 0) > (t.handoff_tokens ?? 250000) && !s.resume_md) {
147 out.push({ level: 'bad', text: `context ${fmtTokens(s.ctx)} > ${fmtTokens(t.handoff_tokens ?? 250000)} and no handoff/RESUME.md` })
148 }
149 const loops = [loopText(s.loops), ...subs.map((x) => loopText(x.loops))].filter(Boolean)
150 if (loops.length) out.push({ level: 'warn', text: `timer/loop tools used: ${loops.join('; ')} (V4.7: no timer wake-ups)` })
151 return out
152}
153
154export function isGuard(text, cfg) {
155 return new RegExp(cfg.guard_match || 'denied|refused', 'i').test(text || '')
156}
157
158export function waitingOnJulian(s) {
159 return Boolean(s.ask_open || (s.needs_action && String(s.needs_action).trim()))
160}
161
162// ---- Global dashboard -------------------------------------------------------------------------------------------
163
164export function dashboard(scan, cfg, nowMs) {
165 const today = localDay(nowMs)
166 const rows = []
167 const byModel = {}
168 const byProject = {}
169 for (const s of scan.sessions || []) {
170 if (s.archived && !s.live) continue
171 const dayMaps = [(s.days || {})[today], ...(s.subs || []).map((x) => (x.days || {})[today])]
172 const billToday = billByModel(dayMaps, cfg)
173 const costToday = sumCost(billToday)
174 for (const [m, b] of Object.entries(billToday)) {
175 const o = byModel[m] || (byModel[m] = { tokens: 0, cost: 0, calls: 0 })
176 o.tokens += b.tokens; o.cost += b.cost; o.calls += b.calls
177 }
178 const repo = repoOf(s)
179 const p = byProject[repo] || (byProject[repo] = { cost: 0, tokens: 0, sessions: 0 })
180 p.cost += costToday; p.tokens += Object.values(billToday).reduce((a, b) => a + b.tokens, 0); p.sessions += 1
181 const w = warnings(s, cfg)
182 const err = s.last_error && s.last_error[2]
183 rows.push({
184 cli: s.cli, sid: s.sid, title: titleOf(s), repo, branch: s.branch || '', model: s.app_model || s.model,
185 effort: s.app_effort || s.effort || '?', ctx: s.ctx, ctxPct: ctxPct(s.ctx, cfg), ctxLevel: ctxLevel(s.ctx, cfg),
186 costToday, running: (s.subs || []).filter((x) => x.status === 'running').length, subs: (s.subs || []).length,
187 pr: s.pr ? { number: s.pr.number, url: s.pr.url, state: (s.ci || {}).state || '?', ci: (s.ci || {}).ci || '?' } : null,
188 problem: w.length ? w[0].text : err || '', problemLevel: w.length ? w[0].level : err ? 'warn' : 'ok',
189 waiting: waitingOnJulian(s), live: Boolean(s.live), last: s.last_activity,
190 })
191 }
192 const totalCalls = Object.values(byModel).reduce((a, b) => a + b.calls, 0)
193 const fam = {}
194 for (const [m, b] of Object.entries(byModel)) {
195 const f = family(m)
196 const o = fam[f] || (fam[f] = { calls: 0, cost: 0, tokens: 0 })
197 o.calls += b.calls; o.cost += b.cost; o.tokens += b.tokens
198 }
199 const targets = cfg.routing_targets || {}
200 const share = ['opus', 'sonnet', 'haiku'].map((f) => {
201 const v = fam[f] || { calls: 0, cost: 0 }
202 const sh = totalCalls ? v.calls / totalCalls : 0
203 const tg = targets[f] || {}
204 const ok = (tg.max === undefined || sh <= tg.max) && (tg.min === undefined || sh >= tg.min)
205 return { family: f, share: sh, calls: v.calls, cost: v.cost, target: tg.max !== undefined ? `<= ${Math.round(tg.max * 100)}%` : tg.min !== undefined ? `>= ${Math.round(tg.min * 100)}%` : '-', ok }
206 })
207 rows.sort((a, b) => (b.live - a.live) || (b.last - a.last))
208 return {
209 today, rows, byModel, byProject, share, totalCost: Object.values(byModel).reduce((a, b) => a + b.cost, 0), totalCalls,
210 }
211}
212
213// ---- One conversation ---------------------------------------------------------------------------------------------
214
215export function conversation(d, cfg, nowMs) {
216 const subs = d.subs || []
217 const mainBill = billByModel([d.models], cfg)
218 const node = (x) => {
219 const bill = billByModel([x.models], cfg)
220 const arch = isArchitect(x, cfg)
221 return {
222 id: x.id, type: x.type, model: x.model, explicit: x.explicit_model || null, effort: x.effort || '?', status: x.status,
223 tokens: Object.values(bill).reduce((a, b) => a + b.tokens, 0), cost: sumCost(bill),
224 task: x.desc || x.prompt || '', architect: arch ? architectReason(`${x.desc || ''} ${x.prompt || ''}`, cfg) : null,
225 phase: x.phase || null, bg: x.bg, ts: x.ts,
226 }
227 }
228 const agents = subs.filter((x) => !x.workflow).map(node)
229 const wfIds = [...new Set(subs.filter((x) => x.workflow).map((x) => x.workflow))]
230 const calls = d.calls || []
231 const workflows = wfIds.map((id) => {
232 const call = calls.find((c) => c.tool === 'Workflow' && c.runId === id)
233 const nodes = subs.filter((x) => x.workflow === id).map(node)
234 return { id, name: call ? call.desc : id, nodes, cost: nodes.reduce((a, b) => a + b.cost, 0),
235 tokens: nodes.reduce((a, b) => a + b.tokens, 0), running: nodes.filter((n) => n.status === 'running').length }
236 })
237 const allBill = billByModel([d.models, ...subs.map((x) => x.models)], cfg)
238 // cost per turn: the main thread's usage in the turn plus the subagents started during it
239 const turns = (d.turns || []).map((t, i, arr) => {
240 const next = arr[i + 1] ? arr[i + 1].ts : '9999'
241 const inTurn = subs.filter((x) => x.ts && x.ts >= t.ts && x.ts < next)
242 const own = sumCost(billByModel([t.models], cfg))
243 const sub = sumCost(billByModel(inTurn.map((x) => x.models), cfg))
244 return { ts: t.ts, kind: t.kind || 'human', text: t.text, cost: own + sub, own, sub, agents: inTurn.length }
245 })
246 const guards = [
247 ...(d.errors || []).filter((e) => isGuard(e[2], cfg)).map((e) => ({ ts: e[0], text: e[2], src: 'tool' })),
248 ...(d.guards || []).map((g) => ({ ts: g[0], text: `${g[1]}: ${g[2]}`, src: 'cc-control' })),
249 ].sort((a, b) => String(a.ts).localeCompare(String(b.ts)))
250 return {
251 title: titleOf(d), repo: repoOf(d), branch: d.branch || '',
252 main: {
253 model: d.app_model || d.model, effort: d.app_effort || d.effort || '?', ctx: d.ctx, ctxPct: ctxPct(d.ctx, cfg),
254 ctxLevel: ctxLevel(d.ctx, cfg), window: cfg.context_window || 400000, cost: sumCost(allBill), ownCost: sumCost(mainBill),
255 live: Boolean(d.live),
256 },
257 agents, workflows, bill: allBill, total: sumCost(allBill), turns: turns.slice(-(cfg.turn_count || 10)),
258 guards: guards.slice(-12), events: compactEvents(d.events || []).slice(-(cfg.event_count || 15)), warnings: warnings(d, cfg),
259 pr: d.pr ? { ...d.pr, ...(d.ci || {}) } : null, waiting: waitingOnJulian(d),
260 }
261}
262
263// Session log: mcp__server__tool -> tool (server); runs of the same event collapse to one row "×n".
264export function compactEvents(events) {
265 const out = []
266 for (const e of events) {
267 const text = String(e[2]).replace(/\bmcp__([^_ ]+(?:_[^_ ]+)*)__([\w-]+)/, (m, srv, tool) => `${tool} (${srv.replace(/^ccd_/, '')})`)
268 const last = out[out.length - 1]
269 if (last && last[1] === e[1] && last[3] === text) { last[4] += 1; last[0] = e[0]; last[2] = `${text} ×${last[4]}`; continue }
270 out.push([e[0], e[1], text, text, 1])
271 }
272 return out.map((e) => [e[0], e[1], e[2]])
273}
274
275// Pick a conversation from the last scan by id prefix or title fragment (most recent first).
276export function pickSession(sessions, query) {
277 const q = String(query || '').trim().toLowerCase()
278 if (!q) return null
279 return (sessions || []).find((s) => String(s.cli).startsWith(q) || String(s.sid || '').replace(/^local_/, '').startsWith(q))
280 || (sessions || []).find((s) => titleOf(s).toLowerCase().includes(q)) || null
281}
282
283export function scanArgs(cfg, opts) {
284 const a = [opts.script, '--cache', opts.cache, '--hours', String((cfg.thresholds || {}).recent_hours ?? 36),
285 '--ci-ttl', String(cfg.ci_ttl_s ?? 600), '--live-s', String((cfg.thresholds || {}).live_s ?? 180)]
286 if (opts.detail) a.push('--detail', opts.detail)
287 if (cfg.include_cli) a.push('--cli')
288 if (opts.extra) a.push(...opts.extra)
289 return a
290}
291
hooks/waiting.mjs 238 lines
1// factory - "Ça t'attend" strip: pure logic (no $, no I/O), tested with node --test tests/logic.test.mjs.
2// Input: the scanner JSON (sessions + reviews from --waiting). Output: the rows the strip draws and the notifications to raise.
3// Ported from the old coordinator mod (green PR left open, question pending), plus the 3 Oct incidents A2-A4:
4// a lane idle while its PR is red, conflicting or its pipeline skipped. Read-only: nothing here sends or blocks anything.
5// Canonical copy: lib/core/waiting.mjs (repo root). factory/hooks/waiting.mjs and every mods/*/lib/core/waiting.mjs are
6// byte copies made by scripts/sync-libs.mjs: never edit a copy by hand. No imports, so every copy works on its own.
7
8// Same as factory's logic.mjs repoOf / titleOf (kept here so this file has no sibling to carry).
9function repoOf(s) {
10 const p = String(s.origin || s.cwd || '').replace(/\\/g, '/')
11 const i = p.indexOf('/.claude/worktrees/')
12 const base = i >= 0 ? p.slice(0, i) : p
13 return base.split('/').filter(Boolean).pop() || '?'
14}
15
16function titleOf(s) {
17 return s.app_title || s.title || String(s.cli || '').slice(0, 8)
18}
19
20export const WAITING_DEFAULTS = {
21 enabled: true,
22 green_min: 30,
23 idle_min: 20,
24 ask_min: 5,
25 julian_max_age_h: 72,
26 idle_pr_states: ['failed', 'canceled', 'skipped', 'conflict'],
27 max_rows: 12,
28 show_children: true,
29 show_archived_children: false,
30 session_link: 'claude://claude.ai/epitaxy/{id}',
31 notify: true,
32 notify_kinds: ['green', 'ask', 'needs', 'awaiting', 'idle'],
33 notify_existing_on_first_run: false,
34 notify_max_per_scan: 3,
35 notify_keep_days: 14,
36 background_s: 120,
37 pr_ttl_s: 300,
38 pr_max_age_days: 14,
39 pr_max_checks: 25,
40 gitlab_host: '',
41 labels: {
42 title: "Ça t'attend",
43 none: 'Rien ne t’attend.',
44 children: 'Sous-conversations',
45 since: 'depuis',
46 more: '+ {n} autres',
47 open_session: 'Ouvrir',
48 kinds: { green: 'PR verte', ask: 'Question', needs: 'Attend Julian', awaiting: 'Attend Julian', idle: 'Lane à l’arrêt' },
49 green: '{pr} verte depuis {age}, pas mergée',
50 ask: 'Question en attente : {question}',
51 needs: 'Attend Julian : {text}',
52 awaiting: 'Interrompue, attend une personne',
53 idle: 'Aucun tour depuis {age} alors que {pr} est {state}',
54 states: { failed: 'rouge', canceled: 'annulée', skipped: 'sans pipeline (skipped)', conflict: 'en conflit', none: 'sans CI', manual: 'en attente d’un job manuel' },
55 child: { working: 'travaille', julian: 'attend Julian', blocked: 'bloquée', done: 'terminée', review: 'à relire', idle: 'inactive', archived: 'archivée' },
56 notify_title: "Ça t'attend",
57 notify_more: '{n} autres lignes dans /factory',
58 reviews_error: 'PR/MR non lues : {errors}',
59 },
60}
61
62export function waitingConfig(cfg) {
63 const w = (cfg && cfg.waiting) || {}
64 return { ...WAITING_DEFAULTS, ...w, labels: deepLabels(WAITING_DEFAULTS.labels, w.labels || {}) }
65}
66
67function deepLabels(a, b) {
68 const out = { ...a }
69 for (const [k, v] of Object.entries(b)) out[k] = v && typeof v === 'object' && !Array.isArray(v) ? { ...(a[k] || {}), ...v } : v
70 return out
71}
72
73export function fill(tpl, vars) {
74 return String(tpl || '').replace(/\{(\w+)\}/g, (m, k) => (vars[k] !== undefined && vars[k] !== null ? String(vars[k]) : m))
75}
76
77export function age(ms) {
78 const m = Math.max(0, Math.round(ms / 60000))
79 if (m < 60) return `${m} min`
80 const h = Math.floor(m / 60)
81 if (h < 48) return `${h} h ${String(m % 60).padStart(2, '0')}`
82 return `${Math.floor(h / 24)} j`
83}
84
85export function normUrl(u) {
86 return String(u || '').trim().replace(/\/+$/, '').toLowerCase()
87}
88
89export function prLabel(r) {
90 const repo = String(r.repo || '').split('/').filter(Boolean).pop() || '?'
91 return `${repo}${r.provider === 'gitlab' || /gitlab/.test(r.url || '') ? '!' : '#'}${r.number}`
92}
93
94// Small stable hash so a changed needs_action text is a new row (and a new notification), the same text is not.
95export function hash(s) {
96 let h = 5381
97 for (const c of String(s || '')) h = ((h * 33) ^ c.codePointAt(0)) >>> 0
98 return h.toString(36)
99}
100
101function tsMs(v) {
102 if (!v) return null
103 if (typeof v === 'number') return v > 1e12 ? v : v * 1000
104 const t = Date.parse(v)
105 return Number.isFinite(t) ? t : null
106}
107
108function sessionRef(s, w) {
109 return { cli: s.cli, sid: s.sid || null, title: titleOf(s), repo: repoOf(s), link: s.sid ? fill(w.session_link, { id: s.sid }) : null }
110}
111
112// PR state for the idle rule: the review list first (it carries conflicts), else the per-session CI lookup.
113function prState(rev, ci) {
114 if (rev) return rev.conflict ? 'conflict' : rev.ci
115 if (ci && /open/.test(String(ci.state || ''))) return String(ci.ci || '').toLowerCase()
116 return null
117}
118
119export function waitingRows(scan, cfg, nowMs) {
120 const w = waitingConfig(cfg)
121 const L = w.labels
122 const sessions = (scan && scan.sessions) || []
123 const reviews = (scan && scan.reviews && scan.reviews.items) || []
124 const byUrl = new Map(reviews.map((r) => [normUrl(r.url), r]))
125 const owner = new Map()
126 for (const s of sessions) {
127 for (const u of [s.pr && s.pr.url, ...(s.app_prs || []).map((p) => p.url)]) if (u && !owner.has(normUrl(u))) owner.set(normUrl(u), s)
128 }
129 const rows = []
130 // (1) green PR/MR left open
131 for (const r of reviews) {
132 if (r.ci !== 'success' || r.conflict) continue
133 const since = tsMs(r.green_since) || tsMs(r.updated)
134 if (!since || nowMs - since < w.green_min * 60000) continue
135 const s = owner.get(normUrl(r.url))
136 rows.push({ key: `green:${normUrl(r.url)}`, kind: 'green', level: 'warn', since, link: r.url,
137 what: fill(L.green, { pr: prLabel(r), age: age(nowMs - since), title: r.title }), detail: r.title || '', pr: prLabel(r),
138 session: s ? sessionRef(s, w) : null })
139 }
140 for (const s of sessions) {
141 if (s.archived) continue
142 const last = tsMs(s.last_activity) || tsMs(s.mtime) || 0
143 const ref = sessionRef(s, w)
144 // (2) waiting on Julian: pending AskUserQuestion, a wrap-up that needs an action, an interrupted turn awaiting a person
145 if (nowMs - last <= w.julian_max_age_h * 3600000) {
146 const askAt = tsMs(s.ask_ts)
147 if (s.ask_open && (!askAt || nowMs - askAt >= w.ask_min * 60000)) {
148 rows.push({ key: `ask:${s.cli}:${s.ask_ts || ''}`, kind: 'ask', level: 'warn', since: askAt || last, link: ref.link,
149 what: fill(L.ask, { question: s.ask_q || 'AskUserQuestion' }), session: ref })
150 }
151 const needs = String(s.needs_action || '').trim()
152 if (needs) {
153 rows.push({ key: `needs:${s.cli}:${hash(needs)}`, kind: 'needs', level: s.status_category === 'blocked' ? 'bad' : 'warn', since: last,
154 link: ref.link, what: fill(L.needs, { text: needs }), session: ref })
155 }
156 if (s.awaiting) {
157 rows.push({ key: `awaiting:${s.cli}`, kind: 'awaiting', level: 'warn', since: last, link: ref.link, what: L.awaiting, session: ref })
158 }
159 }
160 // (3) lane idle while its PR is red, conflicting or its pipeline skipped
161 if (!s.live && nowMs - last >= w.idle_min * 60000) {
162 const urls = [...new Set([s.pr && s.pr.url, ...(s.app_prs || []).map((p) => p.url)].filter(Boolean).map(normUrl))]
163 for (const u of urls) {
164 const rev = byUrl.get(u)
165 const st = prState(rev, s.pr && normUrl(s.pr.url) === u ? s.ci : null)
166 if (!st || !w.idle_pr_states.includes(st)) continue
167 const label = rev ? prLabel(rev) : prLabel({ ...(s.pr || {}), repo: (s.pr || {}).repo })
168 rows.push({ key: `idle:${s.cli}:${u}:${st}`, kind: 'idle', level: 'bad', since: last, link: rev ? rev.url : s.pr.url, pr: label,
169 what: fill(L.idle, { age: age(nowMs - last), pr: label, state: (L.states || {})[st] || st }), session: ref })
170 }
171 }
172 }
173 rows.sort((a, b) => a.since - b.since)
174 return { rows, children: w.show_children ? childGroups(sessions, w, nowMs) : [], errors: (scan && scan.reviews && scan.reviews.errors) || [] }
175}
176
177// (4) sub-conversations linked to a lead (app session file field spawnedFrom), with their state.
178export function childState(s, w, nowMs) {
179 if (s.archived) return 'archived'
180 if (s.live) return 'working'
181 if (s.ask_open || String(s.needs_action || '').trim() || s.awaiting) return 'julian'
182 if (s.status_category === 'blocked') return 'blocked'
183 if (s.status_category === 'completed') return 'done'
184 if (s.status_category === 'review_ready') return 'review'
185 return 'idle'
186}
187
188export function childGroups(sessions, w, nowMs) {
189 const bySid = new Map(sessions.filter((s) => s.sid).map((s) => [s.sid, s]))
190 const groups = new Map()
191 for (const s of sessions) {
192 if (!s.parent || (s.archived && !w.show_archived_children)) continue
193 const g = groups.get(s.parent) || { sid: s.parent, title: bySid.has(s.parent) ? titleOf(bySid.get(s.parent)) : (s.parent_title || s.parent),
194 link: fill(w.session_link, { id: s.parent }), cli: bySid.has(s.parent) ? bySid.get(s.parent).cli : null, children: [], last: 0 }
195 const st = childState(s, w, nowMs)
196 const last = tsMs(s.last_activity) || 0
197 g.children.push({ title: titleOf(s), cli: s.cli, state: st, label: (w.labels.child || {})[st] || st, since: last,
198 link: s.sid ? fill(w.session_link, { id: s.sid }) : null })
199 g.last = Math.max(g.last, last)
200 groups.set(s.parent, g)
201 }
202 return [...groups.values()].sort((a, b) => b.last - a.last)
203}
204
205// Which rows to announce: those never announced before (one notification per row, ever), of the configured kinds.
206// `seen` is {key: epochMs} kept in $.store; returns {announce, seen} with old keys pruned. On the very first run
207// (seen === null) every current row is marked seen without a notification unless notify_existing_on_first_run.
208export function toAnnounce(rows, seen, cfg, nowMs) {
209 const w = waitingConfig(cfg)
210 const first = seen === null || seen === undefined
211 const next = {}
212 const keep = w.notify_keep_days * 86400000
213 for (const [k, t] of Object.entries(seen || {})) if (nowMs - t < keep) next[k] = t
214 const fresh = rows.filter((r) => !(r.key in next))
215 for (const r of rows) if (!(r.key in next)) next[r.key] = nowMs
216 if (!w.notify || (first && !w.notify_existing_on_first_run)) return { announce: [], more: 0, seen: next }
217 const due = fresh.filter((r) => w.notify_kinds.includes(r.kind))
218 return { announce: due.slice(0, w.notify_max_per_scan), more: Math.max(0, due.length - w.notify_max_per_scan), seen: next }
219}
220
221export function notifyText(row) {
222 return row.session ? `${row.what} · ${row.session.title}` : row.what
223}
224
225// Scanner flags for the review list (gh / glab), from the config.
226export function waitingArgs(cfg) {
227 const w = waitingConfig(cfg)
228 if (!w.enabled) return []
229 const a = ['--waiting', '--pr-ttl', String(w.pr_ttl_s), '--pr-max-age-days', String(w.pr_max_age_days), '--pr-max-checks', String(w.pr_max_checks)]
230 if (w.gitlab_host) a.push('--gl-host', String(w.gitlab_host))
231 return a
232}
233
234// Background scans: one session at a time holds the lease (kept in $.store, shared by every session on the PC).
235export function holdsLease(lease, self, nowMs, intervalMs) {
236 return !lease || !lease.sid || lease.sid === self || nowMs - (lease.at || 0) > 3 * intervalMs
237}
238
hooks/screens.mjs 473 lines
1// factory v2 - the screens of the side panel, as pure view models (no $, no I/O; node --test tests/logic.test.mjs).
2// Input: the scanner JSON (sessions with their recent events, detail of one conversation, reviews), the usage and
3// machine extras when those mods are present. Output: what draw.mjs stacks top to bottom. Every label, threshold and
4// the list of screens come from factory.config.json (`screens`), so nothing here is hard-coded but the arithmetic.
5import {
6 dashboard, conversation, titleOf, repoOf, short, family, ctxPct, ctxLevel, waitingOnJulian, localDay, fmtTokens,
7 billByModel, sumCost,
8} from './logic.mjs'
9import { waitingRows, age } from './waiting.mjs'
10
11export const SCREEN_DEFAULTS = {
12 order: ['mission', 'focus', 'arbre', 'pipeline', 'quotas', 'systeme', 'journal'],
13 enabled: ['mission', 'focus', 'arbre', 'pipeline', 'quotas', 'systeme', 'journal'],
14 start: 'mission',
15 recent_events: 12,
16 quiet_min: 30,
17 quiet_max_h: 12,
18 timeline_max: 25,
19 journal_max: 60,
20 tree_children: true,
21 tree_max_agents: 12,
22 pipeline_hours: 24,
23 plan_readonly_share: 0.9,
24 quotas_refresh_s: 300,
25 system_refresh_s: 10,
26 gpu_every: 6,
27 stages: ['plan', 'build', 'review', 'test', 'merge'],
28 agent_stage: { Plan: 'plan', architect: 'plan', Explore: 'plan', 'explore-fast': 'plan', coder: 'build', 'general-purpose': 'build',
29 'code-review': 'review', auditor: 'review', verify: 'review', tester: 'test', debug: 'test' },
30 handoff_match: 'handoff|RESUME\\.md|passe le relais|hand(ed)? off',
31 layout: { narrow: 70, wide: 110, bar_min: 8, bar_max: 40 },
32 labels: {
33 tabs: { mission: 'Mission', focus: 'Focus', arbre: 'Arbre', pipeline: 'Pipeline', quotas: 'Quotas', systeme: 'Système', journal: 'Journal' },
34 counters: { working: 'en cours', idle: 'au repos', blocked: 'bloquées', julian: 'attend Julian', done: 'terminées aujourd’hui', cost: 'coût du jour' },
35 states: { working: 'en cours', idle: 'au repos', blocked: 'bloquée', julian: 'attend Julian', done: 'terminée', archived: 'archivée' },
36 agent_states: { running: 'en cours', done: 'terminé', failed: 'échoué', stopped: 'arrêté' },
37 stages: { plan: 'plan', build: 'build', review: 'revue', test: 'test / CI', merge: 'merge' },
38 timeline: { stuck: 'Bloquée', quiet: 'Calme', context: 'Contexte', compact: 'Compactage', merged: 'PR mergée', pr: 'PR liée',
39 blocked: 'Bloquée', handoff: 'Relais', done: 'Terminée', julian: 'Attend Julian', failed: 'Agent échoué' },
40 journal_kinds: { all: 'tout', prompt: 'prompts', tool: 'outils', agent: 'agents', compact: 'compactages', pr: 'PR', notif: 'notifications', error: 'erreurs' },
41 mission_title: 'Mission',
42 projects: 'Projets',
43 lead: 'lead',
44 subconv: 'sous-conv.',
45 workers: 'agents',
46 share_title: 'Part des modèles aujourd’hui vs cibles V6 ({metric})',
47 target: 'cible',
48 list_title: 'Conversations',
49 filters: { all: 'Toutes', live: 'En cours', problems: 'Problèmes', julian: 'Attend Julian' },
50 focus_title: 'Ce qui me concerne',
51 pulse: 'Pouls de la flotte',
52 agents_running: 'agents en cours',
53 timeline_title: 'Fil en direct',
54 progress: 'Progrès aujourd’hui',
55 progress_row: '{done}/{total} terminées · {merged} PR mergées',
56 tree_title: 'Arbre de la conversation',
57 pick: 'Choisir une conversation',
58 this_conv: 'Cette conversation',
59 main: 'lead',
60 subconvs: 'Sous-conversations',
61 workflow: 'workflow',
62 no_agents: 'aucun sous-agent',
63 // « Ouvrir l'agent » on a running agent of this conversation: $.ui.view({ agentId }) (engine 2.1.300+)
64 open_agent: 'Ouvrir l’agent',
65 back_conv: '← Conversation',
66 architect_title: 'architecte · sur appel',
67 architect_triggers: ['before plan', 'error repeats', 'before done'],
68 architect_trigger_labels: { 'before plan': 'avant un plan', 'error repeats': 'erreur répétée', 'before done': 'avant « fini »' },
69 architect_none: 'aucun appel à l’architecte dans cette conversation',
70 architect_calls: 'appels {calls} · lus {tokens}',
71 bill_title: 'Facture (estimation)',
72 bill_every: 'à chaque tour',
73 bill_on_call: 'sur appel (architecte)',
74 guards_title: 'Approbations et garde-fous',
75 guards_none: 'rien de refusé',
76 log_title: 'Journal de session',
77 warnings_title: 'Alertes',
78 warnings_none: 'aucune',
79 status_line: 'lead [{model} · {effort}] agents [{running}/{total}] architecte [{arch}] ctx [{ctx}%]',
80 arch_idle: 'au repos',
81 arch_busy: 'consulté',
82 pipeline_title: 'Travail en vol',
83 pipeline_note: 'Étape déduite des sessions, PR et CI (heuristique, non vérifié).',
84 quotas_title: 'Quotas',
85 five_hour: 'Claude 5 h',
86 seven_day: 'Claude semaine',
87 reset: 'reset {when}',
88 exhausted: 'épuisé {when}',
89 left_at_reset: 'il restera {pct} % au reset',
90 codex: 'Codex',
91 cost_model: 'Coût du jour par modèle',
92 cost_project: 'Coût du jour par projet',
93 system_title: 'Système',
94 cpu: 'CPU', ram: 'RAM', gpu: 'GPU', disk: 'Disque', runner: 'Runner GitLab',
95 journal_title: 'Journal',
96 module_missing: 'module {mod} non chargé',
97 module_missing_hint: 'Installe le mod « {mod} » à côté de factory (même dossier mods/) pour voir cette section.',
98 unavailable: 'non disponible',
99 scanning: 'Lecture des transcripts…',
100 not_found: 'Conversation introuvable dans le dernier passage.',
101 refresh: 'Rafraîchir',
102 refreshing: 'Lecture…',
103 updated: 'mis à jour {time}',
104 nothing: 'rien',
105 open: 'Ouvrir',
106 },
107}
108
109// ---- config ---------------------------------------------------------------------------------------------------------
110
111function merge(a, b) {
112 if (!b || typeof b !== 'object' || Array.isArray(b)) return b === undefined ? a : b
113 const out = { ...(a || {}) }
114 for (const [k, v] of Object.entries(b)) out[k] = v && typeof v === 'object' && !Array.isArray(v) && a && typeof a[k] === 'object' && !Array.isArray(a[k]) ? merge(a[k], v) : v
115 return out
116}
117
118export function screensConfig(cfg) {
119 return merge(SCREEN_DEFAULTS, (cfg && cfg.screens) || {})
120}
121
122export function fill(tpl, vars) {
123 return String(tpl ?? '').replace(/\{(\w+)\}/g, (m, k) => (vars[k] !== undefined && vars[k] !== null ? String(vars[k]) : m))
124}
125
126// The tabs shown, in order: `order` filtered by `enabled`; unknown ids dropped.
127export function tabsOf(cfg) {
128 const c = screensConfig(cfg)
129 const known = new Set(SCREEN_DEFAULTS.order)
130 return c.order.filter((t) => known.has(t) && c.enabled.includes(t)).map((id) => ({ id, label: (c.labels.tabs || {})[id] || id }))
131}
132
133const TAB_ALIASES = { systeme: 'systeme', system: 'systeme', 'système': 'systeme', arbre: 'arbre', tree: 'arbre', journal: 'journal', log: 'journal',
134 mission: 'mission', focus: 'focus', pipeline: 'pipeline', quotas: 'quotas', quota: 'quotas' }
135
136// "/factory quotas" -> {tab: 'quotas', rest: ''}; "/factory My lane" -> {tab: null, rest: 'My lane'}.
137export function parseArgs(args, cfg) {
138 const words = String(args || '').trim().split(/\s+/).filter(Boolean)
139 const t = words.length ? TAB_ALIASES[words[0].toLowerCase()] : null
140 const ok = t && tabsOf(cfg).some((x) => x.id === t)
141 return { tab: ok ? t : null, rest: (ok ? words.slice(1) : words).join(' ') }
142}
143
144// ---- layout: everything stacks; only the counters grid, bar widths and label pads follow the pane width ------------
145
146export function layout(columns, cfg) {
147 const L = screensConfig(cfg).layout
148 const cols = Number(columns) > 0 ? Number(columns) : 80
149 const narrow = cols < L.narrow
150 const wide = cols >= L.wide
151 return {
152 cols, narrow, wide,
153 counterCols: wide ? 6 : narrow ? 2 : 3,
154 cardCols: wide ? 2 : 1,
155 bar: Math.max(L.bar_min, Math.min(L.bar_max, Math.floor(cols * (narrow ? 0.35 : 0.3)))),
156 pad: narrow ? 12 : 18,
157 textMax: Math.max(20, cols - 6),
158 }
159}
160
161export function chunk(list, n) {
162 const out = []
163 for (let i = 0; i < list.length; i += Math.max(1, n)) out.push(list.slice(i, i + Math.max(1, n)))
164 return out
165}
166
167export function bar(pct, width) {
168 const p = Math.max(0, Math.min(100, Number(pct) || 0))
169 const full = Math.round((p / 100) * width)
170 return '█'.repeat(full) + '░'.repeat(Math.max(0, width - full))
171}
172
173const EFFORT = { low: 1, medium: 2, med: 2, high: 3, xhigh: 4, max: 4 }
174
175export function effortBars(effort) {
176 const n = EFFORT[String(effort || '').toLowerCase()]
177 return n ? '▮'.repeat(n) + '▯'.repeat(4 - n) : '····'
178}
179
180export function modelEffort(model, effort) {
181 return `${short(model)} · ${effortBars(effort)} ${effort || '?'}`
182}
183
184export function clip(s, n) {
185 s = String(s ?? '')
186 return s.length <= n ? s : s.slice(0, Math.max(1, n - 1)) + '…'
187}
188
189function tsMs(v) {
190 if (!v) return null
191 if (typeof v === 'number') return v > 1e12 ? v : v * 1000
192 const t = Date.parse(v)
193 return Number.isFinite(t) ? t : null
194}
195
196// ---- one conversation's state ----------------------------------------------------------------------------------------
197
198// working | julian | blocked | done | idle | archived, with a short reason for blocked / julian.
199export function sessionState(s, cfg) {
200 if (s.archived && !s.live) return { state: 'archived', reason: '' }
201 if (s.live) return { state: 'working', reason: '' }
202 if (waitingOnJulian(s) || s.awaiting) return { state: 'julian', reason: String(s.needs_action || s.ask_q || '').trim() }
203 const ci = s.ci || {}
204 if (s.status_category === 'blocked') return { state: 'blocked', reason: String(s.status_detail || s.needs_action || 'bloquée').trim() }
205 if (/open/.test(String(ci.state || '')) && ['failed', 'canceled', 'skipped'].includes(String(ci.ci || ''))) {
206 return { state: 'blocked', reason: `PR #${(s.pr || {}).number} CI ${ci.ci}` }
207 }
208 if (s.status_category === 'completed' || /merged/.test(String(ci.state || ''))) return { state: 'done', reason: '' }
209 return { state: 'idle', reason: '' }
210}
211
212function isToday(s, nowMs) {
213 const t = tsMs(s.last_activity) || tsMs(s.mtime)
214 return Boolean(t) && localDay(t) === localDay(nowMs)
215}
216
217function visible(scan) {
218 return ((scan && scan.sessions) || []).filter((s) => !(s.archived && !s.live))
219}
220
221// ---- Mission -----------------------------------------------------------------------------------------------------
222
223export function mission(scan, cfg, nowMs) {
224 const c = screensConfig(cfg)
225 const dash = dashboard(scan || { sessions: [] }, cfg, nowMs)
226 const sessions = visible(scan)
227 const states = new Map(sessions.map((s) => [s.cli, sessionState(s, cfg)]))
228 const count = (st) => sessions.filter((s) => states.get(s.cli).state === st).length
229 const blocked = sessions.filter((s) => states.get(s.cli).state === 'blocked')
230 const counters = {
231 working: count('working'),
232 idle: count('idle'),
233 blocked: blocked.length,
234 blockedReasons: blocked.slice(0, 3).map((s) => `${clip(titleOf(s), 28)} : ${states.get(s.cli).reason}`),
235 julian: count('julian'),
236 done: sessions.filter((s) => states.get(s.cli).state === 'done' && isToday(s, nowMs)).length,
237 cost: dash.totalCost,
238 }
239 const costByCli = new Map(dash.rows.map((r) => [r.cli, r.costToday]))
240 const groups = new Map()
241 for (const s of sessions) {
242 const repo = repoOf(s)
243 const g = groups.get(repo) || { repo, sessions: [] }
244 g.sessions.push(s)
245 groups.set(repo, g)
246 }
247 const projects = [...groups.values()].map((g) => {
248 const sids = new Set(g.sessions.map((s) => s.sid).filter(Boolean))
249 const parents = new Set(g.sessions.map((s) => s.parent).filter((p) => p && sids.has(p)))
250 const byRecent = [...g.sessions].sort((a, b) => (b.live - a.live) || ((tsMs(b.last_activity) || 0) - (tsMs(a.last_activity) || 0)))
251 const lead = byRecent.find((s) => parents.has(s.sid)) || byRecent.find((s) => !s.parent) || byRecent[0]
252 const subconvs = g.sessions.filter((s) => s.parent && s !== lead)
253 const workers = g.sessions.reduce((a, s) => a + (s.subs || []).filter((x) => x.status === 'running').length, 0)
254 const st = {}
255 for (const s of g.sessions) { const k = states.get(s.cli).state; st[k] = (st[k] || 0) + 1 }
256 return {
257 repo: g.repo, lead: { cli: lead.cli, title: titleOf(lead), model: lead.app_model || lead.model, effort: lead.app_effort || lead.effort || '?',
258 ctxPct: ctxPct(lead.ctx, cfg), ctxLevel: ctxLevel(lead.ctx, cfg), state: states.get(lead.cli).state },
259 subconvs: subconvs.map((s) => ({ cli: s.cli, title: titleOf(s), state: states.get(s.cli).state, model: s.app_model || s.model, effort: s.app_effort || s.effort || '?' })),
260 sessions: g.sessions.length, workers, states: st, live: g.sessions.some((s) => s.live),
261 maxCtxPct: Math.max(0, ...g.sessions.map((s) => ctxPct(s.ctx, cfg))),
262 cost: g.sessions.reduce((a, s) => a + (costByCli.get(s.cli) || 0), 0),
263 }
264 }).sort((a, b) => (b.live - a.live) || (b.cost - a.cost))
265 const metric = (cfg.routing_targets || {}).metric || 'calls'
266 return { counters, projects, share: dash.share, shareTitle: fill(c.labels.share_title, { metric }), rows: dash.rows, dash, states }
267}
268
269// ---- Focus: timeline, pulse, progress ---------------------------------------------------------------------------------
270
271export function timeline(scan, cfg, nowMs) {
272 const c = screensConfig(cfg)
273 const T = c.labels.timeline
274 const hand = new RegExp(c.handoff_match, 'i')
275 const handoffTokens = ((cfg.thresholds || {}).handoff_tokens) ?? 250000
276 const out = []
277 const add = (s, ts, kind, level, text) => {
278 if (!ts) return
279 out.push({ ts, kind, label: T[kind] || kind, level, text, title: titleOf(s), repo: repoOf(s), cli: s.cli })
280 }
281 for (const s of visible(scan)) {
282 const last = tsMs(s.last_activity) || tsMs(s.mtime)
283 const st = sessionState(s, cfg)
284 for (const e of s.recent || []) {
285 const t = tsMs(e[0])
286 if (e[1] === 'compact') add(s, t, 'compact', 'warn', e[2])
287 else if (e[1] === 'pr') add(s, t, 'pr', 'ok', e[2])
288 else if (e[1] === 'notif' && /fail|killed|error|échou/i.test(e[2])) add(s, t, 'failed', 'bad', e[2])
289 else if (hand.test(String(e[2] || ''))) add(s, t, 'handoff', 'ok', e[2])
290 }
291 if ((s.ctx || 0) > handoffTokens && !s.archived) {
292 add(s, last, 'context', s.resume_md ? 'warn' : 'bad', `${fmtTokens(s.ctx)} > ${fmtTokens(handoffTokens)} : passer le relais${s.resume_md ? '' : ' (pas de handoff/RESUME.md)'}`)
293 }
294 if (st.state === 'blocked') add(s, last, 'blocked', 'bad', st.reason)
295 if (st.state === 'julian') add(s, last, 'julian', 'warn', st.reason || 'question en attente')
296 if (st.state === 'done' && /merged/.test(String((s.ci || {}).state || ''))) add(s, last, 'merged', 'ok', `PR #${(s.pr || {}).number}`)
297 else if (st.state === 'done') add(s, last, 'done', 'ok', s.status_detail || '')
298 if (st.state === 'idle' && last && nowMs - last >= c.quiet_min * 60000 && nowMs - last <= c.quiet_max_h * 3600000) {
299 add(s, last, 'quiet', 'dim', `aucun tour depuis ${age(nowMs - last)}`)
300 }
301 if (st.state === 'working' && (s.subs || []).some((x) => x.status === 'running') === false && s.last_error && tsMs(s.last_error[0]) && nowMs - tsMs(s.last_error[0]) < 10 * 60000) {
302 add(s, tsMs(s.last_error[0]), 'stuck', 'warn', s.last_error[2])
303 }
304 }
305 return out.sort((a, b) => b.ts - a.ts).slice(0, c.timeline_max)
306}
307
308export function focus(scan, cfg, nowMs) {
309 const m = mission(scan, cfg, nowMs)
310 const w = waitingRows(scan || { sessions: [] }, cfg, nowMs)
311 const running = visible(scan).reduce((a, s) => a + (s.subs || []).filter((x) => x.status === 'running').length, 0)
312 const progress = m.projects.map((p) => {
313 const ss = visible(scan).filter((s) => repoOf(s) === p.repo && isToday(s, nowMs))
314 const done = ss.filter((s) => m.states.get(s.cli).state === 'done').length
315 const merged = ss.reduce((a, s) => a + (s.merged_prs || 0), 0)
316 return { repo: p.repo, done, total: ss.length, merged, pct: ss.length ? Math.round((100 * done) / ss.length) : 0 }
317 }).filter((p) => p.total > 0)
318 return { waiting: w, pulse: { ...m.counters, running }, timeline: timeline(scan, cfg, nowMs), progress }
319}
320
321// ---- Arbre: one conversation, Codex agent-tree style, top to bottom ---------------------------------------------------
322
323// Running nodes first, then the most recent; past max, one summary line (count per type) instead of the rest.
324export function trimNodes(nodes, max) {
325 const sorted = [...nodes].sort((a, b) => ((b.status === 'running') - (a.status === 'running')) || String(b.ts || '').localeCompare(String(a.ts || '')))
326 const shown = sorted.slice(0, Math.max(1, max))
327 const rest = sorted.slice(shown.length)
328 const by = {}
329 for (const n of rest) by[n.type] = (by[n.type] || 0) + 1
330 return { shown, hidden: rest.length, hiddenText: Object.entries(by).sort((a, b) => b[1] - a[1]).map(([k, n]) => `${k} ×${n}`).join(', ') }
331}
332
333export function tree(scan, cfg, nowMs) {
334 const c = screensConfig(cfg)
335 const d = scan && scan.detail
336 if (!d) return null
337 const conv = conversation(d, cfg, nowMs)
338 const sessions = (scan && scan.sessions) || []
339 const children = c.tree_children && d.sid ? sessions.filter((s) => s.parent === d.sid).map((s) => {
340 const st = sessionState(s, cfg)
341 const bill = billByModel([s.models, ...(s.subs || []).map((x) => x.models)], cfg)
342 return { cli: s.cli, title: titleOf(s), state: st.state, reason: st.reason, model: s.app_model || s.model, effort: s.app_effort || s.effort || '?',
343 ctxPct: ctxPct(s.ctx, cfg), ctxLevel: ctxLevel(s.ctx, cfg), cost: sumCost(bill), tokens: Object.values(bill).reduce((a, b) => a + b.tokens, 0),
344 agents: (s.subs || []).length, running: (s.subs || []).filter((x) => x.status === 'running').length,
345 pr: s.pr ? { number: s.pr.number, state: (s.ci || {}).state || '?', ci: (s.ci || {}).ci || '?' } : null }
346 }) : []
347 const all = [...conv.agents, ...conv.workflows.flatMap((w) => w.nodes)]
348 const arch = all.filter((n) => n.architect)
349 const triggers = c.labels.architect_triggers.map((t) => ({ id: t, label: (c.labels.architect_trigger_labels || {})[t] || t, count: arch.filter((n) => n.architect === t).length }))
350 const archCost = arch.reduce((a, n) => a + n.cost, 0)
351 const running = all.filter((n) => n.status === 'running').length
352 const archBusy = arch.some((n) => n.status === 'running')
353 const status = fill(c.labels.status_line, { model: short(conv.main.model), effort: conv.main.effort, running, total: all.length,
354 arch: archBusy ? c.labels.arch_busy : arch.length ? `${arch.length} appel(s)` : c.labels.arch_idle, ctx: conv.main.ctxPct })
355 return {
356 ...conv, children,
357 agentsView: trimNodes(conv.agents, c.tree_max_agents),
358 workflowsView: conv.workflows.map((w) => ({ ...w, view: trimNodes(w.nodes, c.tree_max_agents) })),
359 architect: { calls: arch.length, tokens: arch.reduce((a, n) => a + n.tokens, 0), cost: archCost, triggers, busy: archBusy,
360 last: arch.length ? arch[arch.length - 1] : null },
361 billSplit: { every: conv.total - archCost, onCall: archCost },
362 running, totalAgents: all.length, status,
363 }
364}
365
366// ---- Pipeline ------------------------------------------------------------------------------------------------------
367
368export function stageOf(s, cfg) {
369 const c = screensConfig(cfg)
370 const ci = s.ci || {}
371 const st = String(ci.state || '')
372 if (s.pr && /merged|closed/.test(st)) return null
373 if (s.pr && /open/.test(st)) return ci.ci === 'success' ? 'merge' : 'test'
374 if ((s.app_prs || []).length) return 'test'
375 const order = c.stages
376 const running = (s.subs || []).filter((x) => x.status === 'running').map((x) => c.agent_stage[x.type]).filter(Boolean)
377 if (running.length) return running.sort((a, b) => order.indexOf(b) - order.indexOf(a))[0]
378 if (!s.tools || (s.readonly || 0) / Math.max(1, s.tools) >= c.plan_readonly_share) return 'plan'
379 return 'build'
380}
381
382export function pipeline(scan, cfg, nowMs) {
383 const c = screensConfig(cfg)
384 const from = nowMs - c.pipeline_hours * 3600000
385 const rows = new Map()
386 for (const s of visible(scan)) {
387 const last = tsMs(s.last_activity) || tsMs(s.mtime) || 0
388 if (last < from && !s.live) continue
389 const st = sessionState(s, cfg)
390 if (st.state === 'done') continue
391 const stage = stageOf(s, cfg)
392 if (!stage) continue
393 const repo = repoOf(s)
394 const r = rows.get(repo) || { repo, stages: Object.fromEntries(c.stages.map((k) => [k, []])) }
395 const ci = s.ci || {}
396 r.stages[stage].push({ cli: s.cli, title: titleOf(s), state: st.state, live: Boolean(s.live),
397 level: st.state === 'blocked' || ci.ci === 'failed' ? 'bad' : st.state === 'julian' ? 'warn' : s.live ? 'running' : 'dim',
398 pr: s.pr ? `#${s.pr.number}${ci.ci ? ' ' + ci.ci : ''}` : '' })
399 rows.set(repo, r)
400 }
401 const list = [...rows.values()].sort((a, b) => c.stages.reduce((n, k) => n + b.stages[k].length, 0) - c.stages.reduce((n, k) => n + a.stages[k].length, 0))
402 const totals = Object.fromEntries(c.stages.map((k) => [k, list.reduce((n, r) => n + r.stages[k].length, 0)]))
403 return { stages: c.stages.map((k) => ({ id: k, label: c.labels.stages[k] || k })), rows: list, totals }
404}
405
406// ---- Quotas --------------------------------------------------------------------------------------------------------
407
408// live: $.session.usage().rateLimits; extras: scanner/extras.mjs quotas output (usage mod), or {available:false}.
409export function quotas(scan, cfg, nowMs, live, extras) {
410 const c = screensConfig(cfg)
411 const L = c.labels
412 const dash = dashboard(scan || { sessions: [] }, cfg, nowMs)
413 const win = (kind, label) => {
414 const fromUsage = extras && extras.available && extras[kind]
415 const l = (live || []).find((r) => r.kind === kind)
416 const pct = fromUsage && Number.isFinite(fromUsage.pct) ? fromUsage.pct : l && Number.isFinite(l.percentUsed) ? l.percentUsed : null
417 if (pct === null) return { kind, label, available: false }
418 const reset = (fromUsage && fromUsage.reset) || (l && Date.parse(l.resetsAt || '')) || null
419 return { kind, label, available: true, pct, reset: Number.isFinite(reset) ? reset : null, forecast: fromUsage ? fromUsage.forecast || '' : '', live: Boolean(l) }
420 }
421 const byModel = Object.entries(dash.byModel).map(([m, b]) => ({ model: m, family: family(m), cost: b.cost, tokens: b.tokens, calls: b.calls })).sort((a, b) => b.cost - a.cost)
422 const byProject = Object.entries(dash.byProject).filter(([, b]) => b.cost > 0).map(([p, b]) => ({ repo: p, cost: b.cost, tokens: b.tokens, sessions: b.sessions })).sort((a, b) => b.cost - a.cost)
423 return {
424 windows: [win('five_hour', L.five_hour), win('seven_day', L.seven_day)],
425 usage: extras && extras.available ? 'ok' : 'missing', usageReason: extras && extras.reason,
426 codex: extras && extras.codex ? extras.codex : null,
427 byModel, byProject, total: dash.totalCost,
428 }
429}
430
431// ---- Système -------------------------------------------------------------------------------------------------------
432
433export function system(sample, runner) {
434 if (!sample) return { available: false }
435 const gb = (b) => (b ? (b / 1e9).toFixed(1) : '?')
436 const gpus = ((sample.gpu && sample.gpu.gpus) || []).map((g) => ({ name: g.name, pct: g.util, mem: g.mem_total_mb ? `${Math.round(g.mem_used_mb)} / ${Math.round(g.mem_total_mb)} Mo` : '', temp: g.temp_c }))
437 return {
438 available: true, at: sample.at, ncpu: sample.ncpu,
439 cpu: sample.cpu && Number.isFinite(sample.cpu.total) ? sample.cpu.total : null,
440 ram: sample.ram ? { pct: sample.ram.pct, text: `${gb(sample.ram.used)} / ${gb(sample.ram.total)} Go` } : null,
441 disks: (sample.disks || []).map((d) => ({ drive: d.drive, pct: d.pct_used, text: `${gb(d.free)} Go libres` })),
442 gpus, gpuRead: Boolean(sample.gpu),
443 families: Object.entries((sample.procs && sample.procs.families) || {}).map(([k, v]) => ({ name: k, count: v.count, cpu: v.cpu })).sort((a, b) => b.cpu - a.cpu).slice(0, 6),
444 runnerProc: sample.procs && sample.procs.runner ? sample.procs.runner : null,
445 runners: runner && !runner.error ? (runner.backends || []).map((b) => ({ label: b.label, usable: b.usable, why: b.why,
446 jobs: b.jobs, runners: b.runners, concurrent: b.concurrent })) : [],
447 runnerError: runner && runner.error ? runner.error : '',
448 }
449}
450
451// ---- Journal ------------------------------------------------------------------------------------------------------
452
453export const JOURNAL_KINDS = ['all', 'prompt', 'tool', 'agent', 'compact', 'pr', 'notif', 'error']
454
455export function journal(scan, cfg, filter = 'all', project = '') {
456 const c = screensConfig(cfg)
457 const out = []
458 for (const s of visible(scan)) {
459 const repo = repoOf(s)
460 if (project && repo !== project) continue
461 for (const e of s.recent || []) {
462 const kind = e[1] === 'peer' || e[1] === 'task-notification' ? 'notif' : e[1]
463 out.push({ ts: tsMs(e[0]) || 0, kind, text: e[2], title: titleOf(s), repo, cli: s.cli })
464 }
465 if (s.last_error) out.push({ ts: tsMs(s.last_error[0]) || 0, kind: 'error', text: s.last_error[2], title: titleOf(s), repo, cli: s.cli })
466 }
467 const counts = Object.fromEntries(JOURNAL_KINDS.map((k) => [k, k === 'all' ? out.length : out.filter((x) => x.kind === k).length]))
468 const rows = out.filter((x) => filter === 'all' || x.kind === filter).sort((a, b) => b.ts - a.ts).slice(0, c.journal_max)
469 const projects = [...new Set(visible(scan).map(repoOf))].sort()
470 return { rows, counts, projects }
471}
472
473
hooks/workflow_draw.mjs 253 lines
1// factory « Workflow » screen and the pane around every screen, native elements only (Box, Text, Button).
2// drawFactoryPane is drawPane (draw.mjs) plus a « Workflow » tab: the top bar is drawn here and the other screens come
3// from draw.mjs's drawScreen, so draw.mjs, screens.mjs and factory.config.json (byte-copied by cockpit) stay as they are.
4// Pure except for `el` and the callbacks in V.act. View models: workflow.mjs; the Gantt bars, axis and legend are
5// lib/core/gantt.mjs's (the ci mod's Diagramme draws with the same renderer).
6import { hhmm, short, family } from './logic.mjs'
7import { screensConfig, tabsOf, layout, clip } from './screens.mjs'
8import { drawScreen } from './draw.mjs'
9import {
10 workflowConfig, workflowScreen, gantt, axis, ganttLegend, fill, frTokens, frUsd, frDur, clock, loneAgents,
11} from './workflow.mjs'
12
13function mk(el, cfg) {
14 const color = (k) => (cfg && cfg.colors && cfg.colors[k]) || undefined
15 const T = (text, o = {}) => {
16 const p = { children: [String(text ?? '')], wrap: o.wrap || 'wrap' }
17 if (o.color) p.color = color(o.color) || o.color
18 if (o.bold) p.bold = true
19 if (o.dim) p.dimColor = true
20 return el.Text(p)
21 }
22 const row = (parts, o = {}) => el.Box({ flexDirection: 'row', flexWrap: 'wrap', gap: 1, ...o, children: parts.filter(Boolean) })
23 const col = (parts, o = {}) => el.Box({ flexDirection: 'column', ...o, children: parts.filter(Boolean) })
24 const section = (title, parts, o = {}) => el.Box({
25 flexDirection: 'column', borderStyle: 'round', borderColor: color(o.color || 'dim'), paddingX: 1, marginBottom: 1,
26 ...(o.key ? { key: o.key } : {}), ...(o.marginLeft ? { marginLeft: o.marginLeft } : {}),
27 children: [title ? T(title, { bold: true, color: o.color }) : null, ...parts].filter(Boolean),
28 })
29 const btn = (label, onPress, primary) => el.Button({ children: [label], variant: primary ? 'primary' : 'secondary', onPress })
30 return { T, row, col, section, btn, color }
31}
32
33const hm = (ts) => hhmm(ts).slice(0, 5)
34
35export function workflowTab(cfg) {
36 return { id: 'workflow', label: workflowConfig(cfg).labels.tab }
37}
38
39// Tabs of factory with « Workflow » inserted after workflow.tab_after (or at the end).
40export function allTabs(cfg) {
41 const tabs = [...tabsOf(cfg)]
42 const at = tabs.findIndex((t) => t.id === workflowConfig(cfg).tab_after)
43 tabs.splice(at >= 0 ? at + 1 : tabs.length, 0, workflowTab(cfg))
44 return tabs
45}
46
47// V = drawPane's V + { wf, wfAt, wfBusy, wfError, wfScope, wfOpen }
48export function drawFactoryPane(el, V) {
49 const cfg = V.cfg || {}
50 const L = screensConfig(cfg).labels
51 const h = mk(el, cfg)
52 const tabs = allTabs(cfg)
53 const tab = tabs.some((t) => t.id === V.tab) ? V.tab : (tabs[0] || { id: 'mission' }).id
54 const isWf = tab === 'workflow'
55 const at = isWf ? V.wfAt : V.at
56 const top = [
57 h.row(tabs.map((t) => h.btn(t.label, () => V.act.tab(t.id), t.id === tab)), { marginBottom: 1 }),
58 h.row([
59 h.btn((isWf ? V.wfBusy : V.busy) ? L.refreshing : L.refresh, () => V.act.refresh()),
60 h.T(fill(L.updated, { time: at ? hm(at) : '--:--' }), { dim: true }),
61 ], { marginBottom: 1, alignItems: 'center' }),
62 ]
63 if (isWf) {
64 if (V.wfError) top.push(h.T(`workflow_scan : ${V.wfError}`, { color: 'bad' }))
65 if (!V.wf) return h.col([...top, h.T(workflowConfig(cfg).labels.scanning, { dim: true })])
66 return h.col([...top, ...drawWorkflow(h, V, cfg, layout(V.columns, cfg))])
67 }
68 if (V.error) top.push(h.T(`scanner : ${V.error}`, { color: 'bad' }))
69 if (!V.scan) return h.col([...top, h.T(L.scanning, { dim: true })])
70 return h.col([...top, ...drawScreen(el, V, tab)])
71}
72
73// The Workflow screen's body without factory's tab bar, for a mod that composes it in its own pane (cockpit).
74export function drawWorkflowBody(el, V) {
75 const cfg = V.cfg || {}
76 const h = mk(el, cfg)
77 const out = []
78 if (V.wfError) out.push(h.T(`workflow_scan : ${V.wfError}`, { color: 'bad' }))
79 if (!V.wf) return [...out, h.T(workflowConfig(cfg).labels.scanning, { dim: true })]
80 return [...out, ...drawWorkflow(h, V, cfg, layout(V.columns, cfg))]
81}
82
83const STATUS_COLOR = { running: 'running', done: 'done', completed: 'done', failed: 'failed', killed: 'warn', interrupted: 'warn', skipped: 'dim', waiting: 'dim', tail: 'running', now: 'warn', empty: 'dim' }
84
85function isOpen(V, key, dflt) {
86 const o = V.wfOpen || {}
87 return Object.prototype.hasOwnProperty.call(o, key) ? Boolean(o[key]) : dflt
88}
89
90// A foldable block: « ▾ title » button, then its parts when open.
91function fold(h, V, W, key, title, parts, dflt, o = {}) {
92 const open = isOpen(V, key, dflt)
93 return h.col([
94 h.row([h.btn(`${open ? W.labels.open : W.labels.closed} ${title}`, () => V.act.wfToggle(key, !open)), ...(o.extra || [])], { alignItems: 'center' }),
95 open ? h.col(parts, { marginLeft: 2 }) : null,
96 ], { key: 'fold-' + key, marginBottom: 1 })
97}
98
99export function drawWorkflow(h, V, cfg, lay) {
100 const W = workflowConfig(cfg)
101 const WL = W.labels
102 const now = V.wfAt || Date.now()
103 const s = workflowScreen(V.wf, cfg, now)
104 const scope = V.wfScope || W.scope
105 const out = [h.T(WL.title, { bold: true })]
106 out.push(h.row([
107 h.btn(WL.scope_conv, () => V.act.wfScope('conversation'), scope !== 'all'),
108 h.btn(WL.scope_all, () => V.act.wfScope('all'), scope === 'all'),
109 ], { marginBottom: 1 }))
110 // PC-wide parallelism vs the rules
111 const lim = s.limits
112 out.push(h.section(WL.limits, [
113 h.T(lim.text, { color: lim.level === 'bad' ? 'bad' : lim.level === 'warn' ? 'warn' : undefined, bold: lim.level !== 'ok' }),
114 ...lim.highlights.map((x) => h.T(`▲ ${x.text}`, { color: x.level })),
115 h.T(WL.limits_note, { dim: true }),
116 ], { key: 'limits', color: lim.level === 'bad' ? 'bad' : 'dim' }))
117 // Vitesse of the whole scope
118 if (s.runs.length) out.push(speedBlock(h, V, W, s.speed, 'scope', fill(WL.speed_scope, { scope: scope === 'all' ? WL.scope_all.toLowerCase() : WL.scope_conv.toLowerCase() }), false))
119 if (!s.runs.length) out.push(h.T(fill(scope === 'all' ? WL.none_all : WL.none, { hours: W.hours }), { dim: true }))
120 for (const v of s.runs) out.push(runBlock(h, V, cfg, W, lay, v, now))
121 // Agent-tool agents launched outside a Workflow (factory's scan), with their ETA
122 if (W.lone && W.lone.enabled !== false && V.scan) {
123 const lone = loneAgents(V.scan, cfg, V.at || now, { scope, cli: V.target || V.self })
124 out.push(h.section(`${WL.lone} (${lone.length})`, lone.length
125 ? lone.map((a) => h.T(`● ${a.text}`, { color: a.eta && a.eta.overrun ? 'warn' : 'running' }))
126 : [h.T(WL.lone_none, { dim: true })], { key: 'lone', color: lone.length ? 'running' : 'dim' }))
127 }
128 out.push(h.T(WL.glossary, { dim: true }))
129 return out
130}
131
132function speedBlock(h, V, W, sp, key, title, dflt) {
133 const WL = W.labels
134 return fold(h, V, W, 'speed-' + key, `${title} : ${sp.sentence}`, sp.empty ? [h.T(sp.sentence, { dim: true })] : [
135 h.row([h.T(`0 ┤${sp.spark}├ ${sp.max}`, { color: 'running' }), h.T(`moy. ${sp.avg.toFixed(1).replace('.', ',')} · plafond ${sp.cap}`, { dim: true })], { flexWrap: 'nowrap' }),
136 h.T(sp.capText, { dim: true }),
137 sp.idleText ? h.T(sp.idleText) : null,
138 ...sp.could.slice(0, 6).map((c) => h.T(`↔ ${WL.speed_could} : ${c.text}`, { color: 'warn' })),
139 sp.limitsHit ? h.T(sp.limitsText, { color: 'bad' }) : h.T(sp.limitsText, { color: 'ok' }),
140 ], dflt)
141}
142
143function runBlock(h, V, cfg, W, lay, v, now) {
144 const WL = W.labels
145 const st = (WL.status || {})[v.status] || v.status
146 const key = v.id
147 const open = isOpen(V, key, v.live || W.open_finished)
148 const head = [
149 h.row([
150 h.btn(`${open ? WL.open : WL.closed} ${clip(v.name, lay.textMax - 30)}`, () => V.act.wfToggle(key, !open), v.live),
151 h.T(st, { color: STATUS_COLOR[v.status], bold: true }),
152 h.T(`${WL.complexity} ${v.badge}`, { bold: true, color: v.badge === 'XL' || v.badge === 'L' ? 'warn' : 'dim' }),
153 h.T(v.live ? fill(WL.elapsed, { dur: frDur(v.elapsed) }) : `${clock(v.start)} → ${clock(v.end)}`, { dim: true }),
154 ], { alignItems: 'center' }),
155 h.T(v.sentence, { bold: v.live }),
156 ]
157 if (!open) return h.section(null, head, { key: 'run-' + key, color: v.highlights.some((x) => x.level === 'bad') ? 'bad' : v.live ? 'running' : 'dim' })
158 const parts = [...head]
159 if (v.description) parts.push(h.T(v.description, { dim: true }))
160 parts.push(h.T(`${frTokens(v.tokens)} tokens · ~${frUsd(v.cost)} (${cfg.cost_label || 'estimation'}) · ${v.agents.length} agent(s) · ${v.models.join(', ') || '?'}${V.wfScope === 'all' ? ' · ' + v.project.replace(/^[A-Z]--/, '').slice(0, 40) : ''}`, { dim: true }))
161 // highlights
162 if (v.highlights.length) {
163 parts.push(h.col(v.highlights.map((x, i) => h.T(`▲ ${x.text}`, { color: x.level, key: 'hl' + i })), { marginBottom: 1 }))
164 }
165 // phases: vertical timeline with agents under each
166 parts.push(fold(h, V, W, key + ':phases', WL.phases, v.phases.map((p) => phaseBlock(h, W, lay, p, v, now)), true))
167 // estimates
168 if (v.live) parts.push(fold(h, V, W, key + ':est', WL.estimates, estimateLines(h, W, v), true))
169 // Gantt
170 parts.push(fold(h, V, W, key + ':gantt', WL.gantt, ganttLines(h, W, v, now, lay.cols - 12, cfg), v.live))
171 // speed
172 parts.push(speedBlock(h, V, W, v.speed, key, WL.speed, false))
173 return h.section(null, parts, { key: 'run-' + key, color: v.highlights.some((x) => x.level === 'bad') ? 'bad' : v.live ? 'running' : 'dim' })
174}
175
176const PHASE_MARK = { done: '●', running: '◐', waiting: '○', failed: '✗' }
177
178function phaseBlock(h, W, lay, p, v, now) {
179 const WL = W.labels
180 const pst = (WL.phase_status || {})[p.status] || p.status
181 const pe = v.estimate ? v.estimate.phases.find((x) => x.index === p.index) : null
182 const kids = [
183 h.row([
184 h.T(PHASE_MARK[p.status] || '○', { color: STATUS_COLOR[p.status], bold: true }),
185 h.T(`${p.index}. ${p.title || '-'}`, { bold: true }),
186 h.T(pst, { color: STATUS_COLOR[p.status] }),
187 h.T(`${p.agents.length} agent(s)${p.running ? `, ${p.running} en cours` : ''}`, { dim: true }),
188 pe && pe.enough && pe.ms ? h.T(`reste ~${frDur(pe.ms.mid)}`, { dim: true }) : null,
189 ]),
190 p.detail ? h.T(`│ ${clip(p.detail, lay.textMax - 4)}`, { dim: true }) : null,
191 ]
192 for (const a of p.agents) kids.push(agentLines(h, W, lay, a, now))
193 return h.col(kids, { key: 'ph-' + p.index, marginBottom: 1 })
194}
195
196function agentLines(h, W, lay, a, now) {
197 const WL = W.labels
198 const st = a.stuck ? `${WL.agent_status.running} · bloqué ?` : (WL.agent_status || {})[a.status] || a.status
199 const color = a.stuck || a.status === 'failed' ? 'bad' : STATUS_COLOR[a.status]
200 return h.col([
201 h.row([h.T('│ ├', { dim: true }), h.T(clip(a.label, lay.textMax - 24), { bold: true }), h.T(st, { color, bold: a.stuck || a.status === 'failed' })]),
202 h.row([
203 h.T('│ │ ', { dim: true }),
204 h.T(`${short(a.model)}${a.effort ? ' · ' + a.effort : ''}`, { color: family(a.model) }),
205 a.explicit ? null : h.T(WL.model_inherited, { color: 'warn' }),
206 h.T(`${frDur(a.durMs)} · ${frTokens(a.tokens)} tok · ${frUsd(a.cost)}`, { dim: true }),
207 ]),
208 a.lastLine ? h.T(`│ │ ${clip(a.lastLine, Math.min(100, lay.textMax - 6))}`, { dim: a.status !== 'running' }) : null,
209 a.branch || a.worktree || a.pr ? h.T(`│ │ ${[a.branch ? 'branche ' + a.branch : '', a.worktree && !a.branch ? 'worktree ' + a.worktree : '', a.pr ? 'PR #' + a.pr : ''].filter(Boolean).join(' · ')}`, { dim: true }) : null,
210 a.est ? h.T(`│ │ ${a.est.overrun ? WL.overrun : `reste ~${frDur(a.est.ms.mid)} (${frDur(a.est.ms.lo)}–${frDur(a.est.ms.hi)}), ${fill(WL.samples, { n: a.est.n })}`}`, { color: a.est.overrun ? 'warn' : 'dim' }) : null,
211 ], { key: 'ag-' + a.id })
212}
213
214function estimateLines(h, W, v) {
215 const WL = W.labels
216 const e = v.estimate
217 if (!e) return [h.T(WL.no_history, { dim: true })]
218 const lines = []
219 const row = (what, x) => (x && x.ms ? fill(WL.est_row, {
220 what, dur: frDur(x.ms.mid), range: `(${frDur(x.ms.lo)}–${frDur(x.ms.hi)})`, tokens: frTokens(x.tok.mid), cost: frUsd(x.usd ? x.usd.mid : 0),
221 n: fill(WL.samples, { n: x.n }) + (x.level ? ' · ' + ((WL.est_level || {})[x.level] || x.level) : ''),
222 }) : `${what} : ${WL.no_history}`)
223 if (e.enough) {
224 lines.push(h.T(`${fill(WL.eta, { time: clock(e.eta.mid) })} ${fill(WL.eta_range, { lo: clock(e.eta.lo), hi: clock(e.eta.hi) })}`, { bold: true }))
225 lines.push(h.T(`${WL.est_total} : ~${frTokens(e.finalTokens.mid)} tokens (${frTokens(e.finalTokens.lo)}–${frTokens(e.finalTokens.hi)}) · ~${frUsd(e.finalCost.mid)} (${frUsd(e.finalCost.lo)}–${frUsd(e.finalCost.hi)}) · ${fill(WL.samples, { n: e.n })}`))
226 } else {
227 lines.push(h.T(`${WL.est_total} : ${WL.no_history} (${fill(WL.samples, { n: e.n })}, il en faut ${W.min_samples})`, { dim: true }))
228 }
229 for (const p of e.phases) lines.push(h.T(row(fill(WL.est_phase, { title: p.title || p.index }), p.enough ? p : null), { dim: !p.enough }))
230 if (e.overrun.length) lines.push(h.T(`${WL.overrun} : ${e.overrun.join(', ')}`, { color: 'warn' }))
231 return lines
232}
233
234function ganttLines(h, W, v, now, width, cfg) {
235 const g = gantt(v, now, Math.max(20, width), cfg)
236 if (g.mode === 'empty') return [h.T(W.labels.nothing, { dim: true })]
237 if (g.mode === 'vertical') {
238 return g.rows.map((r, i) => h.row([h.T(r.time, { dim: true }), h.T(r.text, { color: STATUS_COLOR[r.kind], bold: r.kind === 'now' })], { key: 'gv' + i, flexWrap: 'nowrap' }))
239 }
240 const out = [h.T(axis(g), { dim: true })]
241 for (const grp of g.groups) {
242 out.push(h.T(`${grp.index}. ${grp.title || '-'}`, { bold: true }))
243 for (const [i, r] of grp.rows.entries()) {
244 out.push(h.row([
245 h.T(clip(r.label, g.labelW).padEnd(g.labelW, ' ') + ' ', { dim: r.status !== 'running' }),
246 ...r.cells.map((c, j) => h.T(c.text, { color: STATUS_COLOR[c.kind], key: 'c' + j })),
247 ], { key: `g-${grp.index}-${i}`, flexWrap: 'nowrap', gap: 0 }))
248 }
249 }
250 out.push(h.T(ganttLegend({ est: W.labels.est_tail, now: W.labels.now }), { dim: true })) // lib/core/gantt.mjs, same as ci's Diagramme
251 return out
252}
253
hooks/workflow.mjs 603 lines
1// factory « Workflow » screen - view models only (no $, no I/O; node --test mods/factory/tests/workflow.test.mjs).
2// Input: the JSON of scanner/workflow_scan.py ({runs, live, history}). Output: per workflow its phases as a vertical
3// timeline, its agents, highlights (failed, stuck, no explicit model, parallel limits), estimates from this PC's past
4// runs (median, range, sample size) with an ETA clock time, a complexity badge, a Gantt and one plain French sentence.
5// Every label, threshold and limit comes from workflow.config.json / factory.config.json → `workflow`.
6import { billByModel, sumCost, tokensOf, family, short, costOf, titleOf, repoOf } from './logic.mjs'
7// One estimate rule and one Gantt for Workflows (here) and pipelines (ci mod): byte copies of lib/core (scripts/sync-libs.mjs).
8import { quantiles, remaining, estimateOf, etaOf } from '../lib/core/estimate.mjs'
9import { gantt as coreGantt, axis as coreAxis, legend as coreLegend } from '../lib/core/gantt.mjs'
10
11export const WORKFLOW_DEFAULTS = {
12 tab_after: 'arbre',
13 scope: 'conversation',
14 hours: 36,
15 stale_h: 6,
16 history_days: 30,
17 stuck_min: 15,
18 min_samples: 3,
19 max_runs: 12,
20 refresh_s: 20,
21 limits: { ci: 4, npm: 3 },
22 ci_match: 'gh (pr|run) (checks|watch)|glab (ci|pipeline) (status|view|list)|--watch|ci status --live',
23 npm_match: '\\bnpm (ci|install|i)\\b|\\btsc\\b|npm run (build|typecheck|check)|\\bpnpm (install|i)\\b',
24 complexity: { m: 1, l: 5, xl: 20 },
25 gantt: { min_bar: 16, label_w: 14 },
26 speed: { cap_max: 16, cpu_reserve: 2, session_guideline: 10, seq_gap_s: 90, buckets: 24 },
27 open_finished: false,
28 // Agent-tool agents launched outside a Workflow (run_in_background or not), from factory's scan (its `subs` rows):
29 // shown under the Workflows with an ETA from past agents of the same type on this PC (min_samples, else none).
30 lone: { enabled: true, max: 12, min_samples: 3 },
31 labels: {
32 tab: 'Workflow',
33 title: 'Workflows',
34 scope_conv: 'Cette conversation',
35 scope_all: 'Toutes les conversations',
36 none: 'Aucun workflow dans cette conversation (dernières {hours} h).',
37 none_all: 'Aucun workflow sur ce PC (dernières {hours} h).',
38 scanning: 'Lecture des workflows…',
39 status: { running: 'en cours', completed: 'terminé', failed: 'échoué', killed: 'arrêté', interrupted: 'interrompu' },
40 agent_status: { running: 'en cours', done: 'fini', failed: 'échoué', skipped: 'sauté', waiting: 'en attente' },
41 phase_status: { done: 'fini', running: 'en cours', waiting: 'à venir', failed: 'échoué' },
42 sentence_running: 'Phase {phase} sur {phases} ({title}), {running} agent(s) en cours, {eta}, ~{tokens} tokens, ~{cost}',
43 sentence_done: 'Terminé à {end} en {dur}, {agents} agent(s), {tokens} tokens, ~{cost}',
44 sentence_failed: '{status} à {end} après {dur}, {failed} agent(s) en échec, {tokens} tokens, ~{cost}',
45 eta: 'fini vers {time}',
46 eta_range: '(entre {lo} et {hi})',
47 no_history: 'pas assez d’historique',
48 samples: 'n = {n}',
49 phases: 'Phases',
50 gantt: 'Gantt',
51 agents: 'Agents',
52 estimates: 'Estimations',
53 highlights: 'À regarder',
54 limits: 'Parallélisme sur ce PC',
55 limits_row: '{agents} agents de workflow en cours · CI {ci} / {ci_max} · npm ci / tsc {npm} / {npm_max}',
56 limits_note: 'Compté sur les workflows en cours de tout le PC, d’après la dernière commande de chaque agent (heuristique).',
57 stuck: '{label} : aucun événement depuis {min} min',
58 failed: '{label} a échoué',
59 no_model: '{n} agent(s) sans modèle explicite (hérité) : {labels}',
60 over_ci: 'CI : {n} pipelines attendus en même temps, la règle dit ≤ {max}',
61 over_npm: 'npm ci / tsc : {n} en même temps, la règle dit ≤ {max}',
62 run_failed: 'Le workflow a échoué : {error}',
63 run_killed: 'Le workflow a été arrêté avant la fin',
64 run_interrupted: 'Plus aucun événement depuis {age} et pas de bilan : interrompu ?',
65 nothing: 'rien à signaler',
66 elapsed: 'depuis {dur}',
67 complexity: 'complexité',
68 now: 'maintenant',
69 est_tail: 'fin estimée',
70 est_row: '{what} : reste {dur} {range}, ~{tokens} tokens, ~{cost} · {n}',
71 est_total: 'Total',
72 est_phase: 'Phase {title}',
73 est_level: { label: 'même étiquette', role: 'même rôle, modèle et phase', phase: 'même modèle et phase', type: 'même modèle et type', family: 'même modèle', workflow: 'mêmes runs de ce workflow', generic: 'toutes les phases passées' },
74 overrun: 'dépasse l’habituel',
75 model_inherited: 'modèle hérité',
76 speed: 'Vitesse',
77 speed_scope: 'Vitesse ({scope})',
78 speed_sentence: 'Utilisé {avg}/{cap} agents en moyenne (pic {max}), {seq}, {limits}',
79 speed_seq_none: 'rien n’aurait pu tourner en parallèle de plus',
80 speed_seq: '{n} agent(s) auraient pu tourner en parallèle',
81 speed_limits_none: 'aucune limite atteinte',
82 speed_limits: 'limites atteintes : {list}',
83 speed_rate: '{n} erreur(s) 429 / surcharge',
84 speed_ci: 'CI {n} > {max}',
85 speed_npm: 'npm ci / tsc {n} > {max}',
86 speed_idle: 'lead sans agent en cours pendant {dur} entre deux agents',
87 speed_cap: 'plafond workflow {cap} (min({cap_max}, {cpus} CPU − {reserve})) · repère conversation {guide} agents',
88 speed_could: 'aurait pu tourner en parallèle',
89 speed_could_row: '{label} a démarré {gap} après la fin de {prev}, même phase, sans dépendance visible',
90 lone: 'Agents hors workflow',
91 lone_none: 'aucun agent lancé hors workflow en cours',
92 lone_row: '{type}{bg} · {desc} ({conv}), depuis {dur} : {eta}',
93 lone_eta: 'fin vers {time} (n = {n})',
94 lone_overrun: 'au-delà de l’habituel (n = {n})',
95 lone_bg: 'arrière-plan',
96 open: '▾', closed: '▸',
97 glossary: 'Phase : une étape du workflow, les phases passent l’une après l’autre · Agent : un Claude qui fait une tâche, en parallèle des autres de sa phase · Worktree : une copie isolée du dépôt pour un agent · Tokens : texte lu et écrit par les modèles · $ : estimation au tarif public',
98 },
99}
100
101function merge(a, b) {
102 if (!b || typeof b !== 'object' || Array.isArray(b)) return b === undefined ? a : b
103 const out = { ...(a || {}) }
104 for (const [k, v] of Object.entries(b)) out[k] = v && typeof v === 'object' && !Array.isArray(v) && a && typeof a[k] === 'object' && !Array.isArray(a[k]) ? merge(a[k], v) : v
105 return out
106}
107
108export function workflowConfig(cfg) {
109 return merge(WORKFLOW_DEFAULTS, (cfg && cfg.workflow) || {})
110}
111
112export function fill(tpl, vars) {
113 return String(tpl ?? '').replace(/\{(\w+)\}/g, (m, k) => (vars[k] !== undefined && vars[k] !== null ? String(vars[k]) : m))
114}
115
116// ---- scrubbing (the scanner scrubs already; this is the second lock before anything is drawn) --------------------
117
118const SECRETS = [
119 [/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(-----END [A-Z ]*PRIVATE KEY-----|$)/g, '<clé privée>'],
120 [/\b(gh[pousr]_|github_pat_)[A-Za-z0-9_]{16,}/g, '<jeton>'],
121 [/\bglpat-[A-Za-z0-9_-]{12,}/g, '<jeton>'],
122 [/\bsk-[A-Za-z0-9_-]{16,}/g, '<clé>'],
123 [/\bxox[abprs]-[A-Za-z0-9-]{10,}/g, '<jeton>'],
124 [/\bAKIA[0-9A-Z]{16}\b/g, '<clé>'],
125 [/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{4,}/g, '<jeton>'],
126 [/\b(bearer|basic)\s+[A-Za-z0-9._~+/=-]{12,}/gi, '$1 <masqué>'],
127 [/\b(password|passwd|pwd|token|secret|api[_-]?key|apikey|authorization|client[_-]?secret)(["']?\s*[:=]\s*)["']?[^\s"',;]+/gi, '$1$2<masqué>'],
128 [/(:\/\/[^/\s:@]+:)[^@\s/]+@/g, '$1<masqué>@'],
129 [/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+\.[A-Za-z.]{2,}\b/g, '<e-mail>'],
130 [/\b[A-Z]:[\\/]+Users[\\/]+[^\\/\s"']+/gi, '~'],
131 [/\/(?:home|Users)\/[^/\s"']+/g, '~'],
132 [/\b[A-Fa-f0-9]{40,}\b/g, '<hex>'],
133 [/[A-Za-z0-9+/_-]{48,}={0,2}/g, '<masqué>'],
134]
135
136export function scrub(s, n = 100) {
137 let t = String(s ?? '')
138 for (const [rx, rep] of SECRETS) t = t.replace(rx, rep)
139 t = t.replace(/\s+/g, ' ').trim()
140 return t.length <= n ? t : t.slice(0, Math.max(1, n - 1)) + '…'
141}
142
143// ---- formatting (French) ---------------------------------------------------------------------------------------------
144
145export function frTokens(n) {
146 n = Number(n) || 0
147 if (n >= 1e6) return `${(n / 1e6).toFixed(1).replace('.', ',')} M`
148 if (n >= 1e3) return `${Math.round(n / 1e3)} K`
149 return String(Math.round(n))
150}
151
152export function frUsd(x) {
153 x = Number(x) || 0
154 return x >= 10 ? `${Math.round(x)} $` : `${x.toFixed(2).replace('.', ',')} $`
155}
156
157export function frDur(ms) {
158 const m = Math.max(0, Math.round((Number(ms) || 0) / 60000))
159 if (m < 1) return '< 1 min'
160 if (m < 60) return `${m} min`
161 const h = Math.floor(m / 60)
162 return `${h} h ${String(m % 60).padStart(2, '0')}`
163}
164
165export function clock(ms) {
166 if (!ms) return '--:--'
167 const d = new Date(ms)
168 return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
169}
170
171// ---- estimator -------------------------------------------------------------------------------------------------------
172
173// quantiles: lib/core/estimate.mjs (same linear interpolation), re-exported for the tests and the cockpit copy.
174export { quantiles }
175
176const roleOf = (label) => (String(label || '').includes(':') ? String(label).split(':')[0].trim().toLowerCase() : '')
177
178// history rows: {run, name, label, phase, model, tokens, duration_ms, type}. Matching levels, most specific first; the
179// first level with at least min_samples past agents wins, else null (« pas assez d'historique »).
180export function estimator(history, cfg) {
181 const w = workflowConfig(cfg)
182 const rows = (history || []).filter((h) => Number(h.duration_ms) > 0)
183 .map((h) => ({ ...h, usd: Array.isArray(h.vec) ? costOf(h.model || 'default', [...h.vec, 0], cfg) : 0 }))
184 const levels = [
185 ['label', (a, h) => h.name && a.workflow && h.name === a.workflow && h.label === a.label],
186 ['role', (a, h) => roleOf(a.label) && roleOf(h.label) === roleOf(a.label) && family(h.model) === family(a.model) && h.phase === a.phase],
187 ['phase', (a, h) => family(h.model) === family(a.model) && h.phase === a.phase],
188 ['type', (a, h) => a.type && family(h.model) === family(a.model) && h.type === a.type],
189 ['family', (a, h) => family(h.model) === family(a.model)],
190 ]
191 const agent = (a) => {
192 for (const [level, match] of levels) {
193 const hits = rows.filter((h) => match(a, h))
194 if (hits.length >= w.min_samples) {
195 return { level, n: hits.length, dur: quantiles(hits.map((h) => h.duration_ms)), tok: quantiles(hits.map((h) => Number(h.tokens) || 0)), usd: quantiles(hits.map((h) => h.usd)) }
196 }
197 }
198 return null
199 }
200 // one phase of a past run: its agents (count), wall time (longest agent) and tokens (sum)
201 const runs = new Map()
202 for (const h of rows) {
203 const k = h.run + '\u0000' + h.phase
204 const r = runs.get(k) || { name: h.name, phase: h.phase, agents: 0, dur: 0, tok: 0, usd: 0 }
205 r.usd += h.usd
206 r.agents += 1
207 r.dur = Math.max(r.dur, h.duration_ms)
208 r.tok += Number(h.tokens) || 0
209 runs.set(k, r)
210 }
211 const phasesPast = [...runs.values()]
212 const phase = (name, title) => {
213 let hits = phasesPast.filter((p) => p.name === name && p.phase === title)
214 let level = 'workflow'
215 if (hits.length < w.min_samples) { hits = phasesPast; level = 'generic' }
216 if (hits.length < w.min_samples) return null
217 return { level, n: hits.length, agents: quantiles(hits.map((p) => p.agents)), dur: quantiles(hits.map((p) => p.dur)), tok: quantiles(hits.map((p) => p.tok)), usd: quantiles(hits.map((p) => p.usd)) }
218 }
219 const perAgentTok = quantiles(rows.map((h) => Number(h.tokens) || 0))
220 return { agent, phase, perAgentTok, size: rows.length }
221}
222
223// Remaining work of one running agent from its estimate: {lo, mid, hi} ms, tokens and $, overrun when past p75.
224export function remainingOf(est, elapsedMs, tokensNow, costNow = 0) {
225 if (!est) return null
226 const t = est.tok
227 const u = est.usd || { p25: 0, median: 0, p75: 0 }
228 const r = remaining({ enough: true, ...est.dur }, elapsedMs) // lib/core/estimate.mjs: {lo, mid, hi}, overrun past p75
229 const ms = { lo: r.lo, mid: r.mid, hi: r.hi }
230 const tok = { lo: Math.max(0, t.p25 - tokensNow), mid: Math.max(0, t.median - tokensNow), hi: Math.max(0, t.p75 - tokensNow) }
231 const usd = { lo: Math.max(0, u.p25 - costNow), mid: Math.max(0, u.median - costNow), hi: Math.max(0, u.p75 - costNow) }
232 return { ms, tok, usd, overrun: r.overrun, n: est.n, level: est.level }
233}
234
235// ---- one run -----------------------------------------------------------------------------------------------------------
236
237function phaseList(run) {
238 const out = []
239 const seen = new Set()
240 for (const p of run.phases || []) if (p && p.title && !seen.has(p.title)) { seen.add(p.title); out.push({ title: p.title, detail: p.detail || '' }) }
241 for (const a of run.agents || []) if (a.phase && !seen.has(a.phase)) { seen.add(a.phase); out.push({ title: a.phase, detail: '' }) }
242 if (!out.length) out.push({ title: '', detail: '' })
243 return out
244}
245
246export function runView(run, est, cfg, nowMs) {
247 const w = workflowConfig(cfg)
248 const L = w.labels
249 const live = run.status === 'running'
250 const stuckMs = w.stuck_min * 60000
251 const ciRx = new RegExp(w.ci_match, 'i')
252 const npmRx = new RegExp(w.npm_match, 'i')
253 const allModels = {}
254 const agents = (run.agents || []).map((a) => {
255 const bill = billByModel([a.models || {}], cfg)
256 for (const [m, v] of Object.entries(a.models || {})) {
257 const cur = allModels[m] || (allModels[m] = [0, 0, 0, 0, 0, 0])
258 for (let i = 0; i < 6; i++) cur[i] += v[i] || 0
259 }
260 const tokens = Object.values(bill).reduce((x, b) => x + b.tokens, 0) || Number(a.tokens_record) || 0
261 const end = a.status === 'running' ? null : a.end || a.last || null
262 const start = a.start || null
263 const stuck = a.status === 'running' && live && Boolean(a.last || start) && nowMs - (a.last || start) > stuckMs
264 const view = {
265 id: a.id, label: scrub(a.label, 60), phase: a.phase || '', type: a.type || '', model: a.model || run.default_model || '',
266 explicit: Boolean(a.explicit_model), explicitModel: a.explicit_model || '', effort: a.effort || '', status: a.status, stuck,
267 start, end, durMs: start ? (end || nowMs) - start : 0, tokens, cost: sumCost(bill),
268 lastLine: scrub(a.status === 'running' ? a.last_tool || a.last_text : a.last_text || a.last_tool, 100),
269 ci: a.status === 'running' && ciRx.test(a.last_cmd || ''), npm: a.status === 'running' && npmRx.test(a.last_cmd || ''),
270 worktree: scrub(a.worktree, 80), branch: scrub(a.branch, 60), pr: a.pr || null, idle: a.last ? nowMs - a.last : null,
271 rateLimits: Number(a.rate_limits) || 0, lastCmd: a.last_cmd || '',
272 workflow: run.name,
273 }
274 view.est = view.status === 'running' && est ? remainingOf(est.agent(view), start ? nowMs - start : 0, tokens, view.cost) : null
275 return view
276 })
277 const phases = phaseList(run).map((p, i) => {
278 const ag = agents.filter((a) => (a.phase || '') === p.title || (!a.phase && i === 0 && !p.title))
279 const running = ag.filter((a) => a.status === 'running').length
280 const failed = ag.filter((a) => a.status === 'failed').length
281 const status = running ? 'running' : !ag.length ? (live ? 'waiting' : 'waiting') : failed && !ag.some((a) => a.status === 'done') ? 'failed' : 'done'
282 return { index: i + 1, title: p.title, detail: p.detail, status, agents: ag, running, failed }
283 })
284 // a phase with no agent yet, after the last started one, waits; one before it was skipped by the script (done)
285 const lastStarted = Math.max(-1, ...phases.map((p, i) => (p.agents.length ? i : -1)))
286 for (const [i, p] of phases.entries()) if (!p.agents.length && i < lastStarted) p.status = 'done'
287 if (!live) for (const p of phases) if (p.status === 'waiting') p.status = run.status === 'completed' ? 'done' : 'waiting'
288 const current = phases.find((p) => p.status === 'running') || phases.find((p) => p.status === 'waiting') || phases[phases.length - 1]
289 const tokens = agents.reduce((x, a) => x + a.tokens, 0) || Number(run.tokens_record) || 0
290 const cost = sumCost(billByModel([allModels], cfg))
291 const start = run.start || Math.min(...agents.map((a) => a.start).filter(Boolean)) || null
292 const end = live ? null : run.end || Math.max(0, ...agents.map((a) => a.end || 0)) || run.last_activity || null
293 // estimates: running agents (parallel inside a phase) + phases still waiting (one after the other)
294 let estimate = null
295 if (live && est) {
296 const runningAgents = agents.filter((a) => a.status === 'running')
297 const known = runningAgents.filter((a) => a.est)
298 const max = (k) => Math.max(0, ...known.map((a) => a.est.ms[k]))
299 const sumTok = (k) => known.reduce((x, a) => x + a.est.tok[k], 0)
300 const sumUsd = (k) => known.reduce((x, a) => x + a.est.usd[k], 0)
301 const ns = known.map((a) => a.est.n)
302 const phaseEst = []
303 let ms = { lo: max('lo'), mid: max('mid'), hi: max('hi') }
304 let tok = { lo: sumTok('lo'), mid: sumTok('mid'), hi: sumTok('hi') }
305 let usd = { lo: sumUsd('lo'), mid: sumUsd('mid'), hi: sumUsd('hi') }
306 for (const p of phases) {
307 if (p.status === 'running') {
308 const ka = p.agents.filter((a) => a.est)
309 phaseEst.push({ title: p.title, index: p.index, ms: { lo: Math.max(0, ...ka.map((a) => a.est.ms.lo)), mid: Math.max(0, ...ka.map((a) => a.est.ms.mid)), hi: Math.max(0, ...ka.map((a) => a.est.ms.hi)) },
310 tok: { lo: ka.reduce((x, a) => x + a.est.tok.lo, 0), mid: ka.reduce((x, a) => x + a.est.tok.mid, 0), hi: ka.reduce((x, a) => x + a.est.tok.hi, 0) },
311 usd: { lo: ka.reduce((x, a) => x + a.est.usd.lo, 0), mid: ka.reduce((x, a) => x + a.est.usd.mid, 0), hi: ka.reduce((x, a) => x + a.est.usd.hi, 0) },
312 n: ka.length ? Math.min(...ka.map((a) => a.est.n)) : 0, enough: ka.length === p.running, level: ka.length ? ka[0].est.level : '' })
313 }
314 if (p.status !== 'waiting') continue
315 const pe = est.phase(run.name, p.title)
316 if (!pe) { phaseEst.push({ title: p.title, index: p.index, enough: false, n: 0 }); ns.push(0); continue }
317 ns.push(pe.n)
318 phaseEst.push({ title: p.title, index: p.index, ms: { lo: pe.dur.p25, mid: pe.dur.median, hi: pe.dur.p75 }, tok: { lo: pe.tok.p25, mid: pe.tok.median, hi: pe.tok.p75 }, usd: { lo: pe.usd.p25, mid: pe.usd.median, hi: pe.usd.p75 }, n: pe.n, enough: true, level: pe.level, agents: Math.round(pe.agents.median) })
319 ms = { lo: ms.lo + pe.dur.p25, mid: ms.mid + pe.dur.median, hi: ms.hi + pe.dur.p75 }
320 tok = { lo: tok.lo + pe.tok.p25, mid: tok.mid + pe.tok.median, hi: tok.hi + pe.tok.p75 }
321 usd = { lo: usd.lo + pe.usd.p25, mid: usd.mid + pe.usd.median, hi: usd.hi + pe.usd.p75 }
322 }
323 const enough = known.length === runningAgents.length && phaseEst.every((p) => p.enough) && (runningAgents.length > 0 || phaseEst.length > 0)
324 estimate = {
325 enough, n: ns.length ? Math.min(...ns) : 0, ms, tok, phases: phaseEst,
326 eta: { lo: nowMs + ms.lo, mid: nowMs + ms.mid, hi: nowMs + ms.hi },
327 finalTokens: { lo: tokens + tok.lo, mid: tokens + tok.mid, hi: tokens + tok.hi },
328 finalCost: { lo: cost + usd.lo, mid: cost + usd.mid, hi: cost + usd.hi },
329 remainingCost: usd,
330 overrun: known.filter((a) => a.est.overrun).map((a) => a.label),
331 }
332 }
333 // complexity: agents × phases × typical tokens per past agent (millions)
334 const perAgent = est && est.perAgentTok.n ? est.perAgentTok.median : tokens / Math.max(1, agents.length)
335 const nAgents = Math.max(agents.length, Number(run.agent_count) || 0) + (estimate ? estimate.phases.reduce((x, p) => x + (p.agents || 0), 0) : 0)
336 const score = nAgents * phases.length * (perAgent / 1e6)
337 const C = w.complexity
338 const badge = score >= C.xl ? 'XL' : score >= C.l ? 'L' : score >= C.m ? 'M' : 'S'
339 // highlights: red only for real problems
340 const hl = []
341 if (run.status === 'failed') hl.push({ level: 'bad', text: fill(L.run_failed, { error: scrub(run.error || '?', 120) }) })
342 if (run.status === 'killed') hl.push({ level: 'warn', text: L.run_killed })
343 if (run.status === 'interrupted') hl.push({ level: 'warn', text: fill(L.run_interrupted, { age: frDur(nowMs - (run.last_activity || nowMs)) }) })
344 for (const a of agents.filter((x) => x.status === 'failed')) hl.push({ level: 'bad', text: fill(L.failed, { label: a.label }) })
345 for (const a of agents.filter((x) => x.stuck)) hl.push({ level: 'bad', text: fill(L.stuck, { label: a.label, min: Math.round((nowMs - (a.idle !== null ? nowMs - a.idle : a.start)) / 60000) }) })
346 const noModel = agents.filter((a) => !a.explicit && a.status !== 'skipped')
347 if (noModel.length) hl.push({ level: 'warn', text: fill(L.no_model, { n: noModel.length, labels: noModel.slice(0, 4).map((a) => a.label).join(', ') + (noModel.length > 4 ? '…' : '') }) })
348 // the sentence on top
349 const running = agents.filter((a) => a.status === 'running').length
350 let sentence
351 if (live) {
352 const eta = !estimate || !estimate.enough ? `fin : ${L.no_history}`
353 : estimate.overrun.length && estimate.ms.mid < 60000 ? `${L.overrun} (${estimate.overrun.length} agent(s))` : fill(L.eta, { time: clock(estimate.eta.mid) })
354 sentence = fill(L.sentence_running, {
355 phase: current ? current.index : '?', phases: phases.length, title: current && current.title ? current.title : '-', running, eta,
356 tokens: frTokens(estimate && estimate.enough ? estimate.finalTokens.mid : tokens), cost: frUsd(estimate && estimate.enough ? estimate.finalCost.mid : cost),
357 })
358 } else if (run.status === 'completed') {
359 sentence = fill(L.sentence_done, { end: clock(end), dur: frDur((end || 0) - (start || end || 0)), agents: agents.length, tokens: frTokens(tokens), cost: frUsd(cost) })
360 } else {
361 sentence = fill(L.sentence_failed, { status: (L.status || {})[run.status] || run.status, end: clock(end), dur: frDur((end || 0) - (start || end || 0)),
362 failed: agents.filter((a) => a.status === 'failed').length, tokens: frTokens(tokens), cost: frUsd(cost) })
363 }
364 return {
365 id: run.run_id, cli: run.cli, project: run.project, name: scrub(run.name, 60), description: scrub(run.description, 200), status: run.status, live,
366 start, end, elapsed: start ? (end || nowMs) - start : 0, tokens, cost, agents, phases, current, estimate, badge, score, highlights: hl, sentence,
367 running, models: [...new Set(agents.map((a) => short(a.model)).filter((m) => m && m !== '?'))],
368 }
369}
370
371// ---- Vitesse: parallel width over time, average vs cap, lead idle gaps, sequential agents that could overlap -------
372
373const SPARK = '▁▂▃▄▅▆▇█'
374
375export function capOf(cfg, cpus) {
376 const S = workflowConfig(cfg).speed
377 const n = Number(cpus) || 0
378 return n ? Math.max(1, Math.min(S.cap_max, n - S.cpu_reserve)) : S.cap_max
379}
380
381// views: one run (per workflow) or several (per conversation / all). Pure arithmetic on agent start / end.
382export function speed(views, cfg, cpus, nowMs, limits) {
383 const w = workflowConfig(cfg)
384 const S = w.speed
385 const L = w.labels
386 const cap = capOf(cfg, cpus)
387 const spans = []
388 for (const v of views) for (const a of v.agents) if (a.start) spans.push({ s: a.start, e: Math.max(a.start, a.end || (a.status === 'running' ? nowMs : a.start)), a, run: v.id })
389 const rate = views.reduce((x, v) => x + v.agents.reduce((y, a) => y + (a.rateLimits || 0), 0), 0)
390 const limitList = []
391 if (rate) limitList.push(fill(L.speed_rate, { n: rate }))
392 if (limits && limits.ci > limits.ciMax) limitList.push(fill(L.speed_ci, { n: limits.ci, max: limits.ciMax }))
393 if (limits && limits.npm > limits.npmMax) limitList.push(fill(L.speed_npm, { n: limits.npm, max: limits.npmMax }))
394 const limitsText = limitList.length ? fill(L.speed_limits, { list: limitList.join(', ') }) : L.speed_limits_none
395 if (!spans.length) return { empty: true, cap, avg: 0, max: 0, spark: '', idleMs: 0, could: [], rate, limitsText, limitsHit: limitList.length > 0,
396 sentence: fill(L.speed_sentence, { avg: 0, cap, max: 0, seq: L.speed_seq_none, limits: limitsText }) }
397 // per run: busy time, idle gaps (no agent running between the first start and the last end), peak
398 let busy = 0
399 let wall = 0
400 let idleMs = 0
401 let max = 0
402 const byRun = new Map()
403 for (const sp of spans) { const l = byRun.get(sp.run) || []; l.push(sp); byRun.set(sp.run, l) }
404 for (const list of byRun.values()) {
405 const t0 = Math.min(...list.map((x) => x.s))
406 const t1 = Math.max(...list.map((x) => x.e))
407 wall += t1 - t0
408 busy += list.reduce((x, sp) => x + (sp.e - sp.s), 0)
409 const pts = list.flatMap((sp) => [[sp.s, 1], [sp.e, -1]]).sort((a, b) => a[0] - b[0] || a[1] - b[1])
410 let cur = 0
411 let last = t0
412 for (const [t, d] of pts) {
413 if (cur === 0 && t > last) idleMs += t - last
414 cur += d
415 max = Math.max(max, cur)
416 last = t
417 }
418 }
419 const avg = wall > 0 ? busy / wall : 0
420 // the mini chart: agents running at once, sampled on `buckets` points across the whole span
421 const T0 = Math.min(...spans.map((x) => x.s))
422 const T1 = Math.max(...spans.map((x) => x.e), T0 + 1)
423 const B = Math.max(4, S.buckets)
424 const series = []
425 for (let i = 0; i < B; i++) {
426 const t = T0 + ((i + 0.5) / B) * (T1 - T0)
427 series.push(spans.filter((sp) => sp.s <= t && sp.e > t).length)
428 }
429 const top = Math.max(1, ...series)
430 const spark = series.map((n) => (n ? SPARK[Math.min(7, Math.round((n / top) * 7))] : ' ')).join('')
431 // agents that started right after another of the same phase ended, without overlap: could have run in parallel
432 const could = []
433 const gapMs = S.seq_gap_s * 1000
434 for (const list of byRun.values()) {
435 const byPhase = new Map()
436 for (const sp of list) { const l = byPhase.get(sp.a.phase) || []; l.push(sp); byPhase.set(sp.a.phase, l) }
437 for (const ph of byPhase.values()) {
438 ph.sort((x, y) => x.s - y.s)
439 for (let i = 1; i < ph.length; i++) {
440 const prev = ph.slice(0, i).reduce((p, x) => (x.e > p.e ? x : p))
441 const overlap = ph.slice(0, i).some((x) => x.e > ph[i].s)
442 if (!overlap && ph[i].s - prev.e <= gapMs && prev.a.status !== 'failed') {
443 could.push({ label: ph[i].a.label, prev: prev.a.label, gap: ph[i].s - prev.e, text: fill(L.speed_could_row, { label: ph[i].a.label, prev: prev.a.label, gap: frDur(ph[i].s - prev.e) }) })
444 }
445 }
446 }
447 }
448 const avgTxt = avg >= 10 ? String(Math.round(avg)) : avg.toFixed(1).replace('.', ',').replace(/,0$/, '')
449 return {
450 empty: false, cap, cpus: Number(cpus) || 0, guideline: S.session_guideline, avg, max, series, spark, idleMs, could, rate, limitsText, limitsHit: limitList.length > 0,
451 capText: fill(L.speed_cap, { cap, cap_max: S.cap_max, cpus: Number(cpus) || '?', reserve: S.cpu_reserve, guide: S.session_guideline }),
452 idleText: idleMs >= 60000 ? fill(L.speed_idle, { dur: frDur(idleMs) }) : '',
453 sentence: fill(L.speed_sentence, { avg: avgTxt, cap, max, seq: could.length ? fill(L.speed_seq, { n: could.length }) : L.speed_seq_none, limits: limitsText }),
454 }
455}
456
457// ---- PC-wide parallelism vs the rules' limits -------------------------------------------------------------------------
458
459export function limitsView(views, cfg) {
460 const w = workflowConfig(cfg)
461 const L = w.labels
462 const running = views.filter((v) => v.live).flatMap((v) => v.agents.filter((a) => a.status === 'running'))
463 const ci = running.filter((a) => a.ci).length
464 const npm = running.filter((a) => a.npm).length
465 const hl = []
466 if (ci > w.limits.ci) hl.push({ level: 'bad', text: fill(L.over_ci, { n: ci, max: w.limits.ci }) })
467 if (npm > w.limits.npm) hl.push({ level: 'bad', text: fill(L.over_npm, { n: npm, max: w.limits.npm }) })
468 return {
469 agents: running.length, ci, npm, ciMax: w.limits.ci, npmMax: w.limits.npm, highlights: hl,
470 text: fill(L.limits_row, { agents: running.length, ci, ci_max: w.limits.ci, npm, npm_max: w.limits.npm }),
471 level: hl.length ? 'bad' : ci === w.limits.ci || npm === w.limits.npm ? 'warn' : 'ok',
472 }
473}
474
475// The whole screen. scope 'conversation' shows runs of this conversation (the scanner's --session), 'all' every one.
476export function workflowScreen(scan, cfg, nowMs) {
477 const w = workflowConfig(cfg)
478 const est = estimator((scan && scan.history) || [], cfg)
479 const runs = ((scan && scan.runs) || []).slice(0, w.max_runs).map((r) => runView(r, est, cfg, nowMs))
480 const others = ((scan && scan.live) || []).map((r) => runView(r, est, cfg, nowMs))
481 const limits = limitsView([...runs, ...others], cfg)
482 const cpus = (scan && scan.cpus) || 0
483 for (const v of runs) v.speed = speed([v], cfg, cpus, nowMs, v.live ? limits : null)
484 return { runs, limits, historySize: est.size, speed: speed(runs, cfg, cpus, nowMs, limits), cpus }
485}
486
487// ---- Gantt -----------------------------------------------------------------------------------------------------------
488
489// Horizontal when `width` columns leave at least gantt.min_bar for the bars, else vertical (time goes down).
490// Horizontal: rows grouped by phase, each {label, cells: [{text, kind}]}; kind = done|running|failed|skipped|tail|now|empty.
491export function gantt(view, nowMs, width, cfg) {
492 const w = workflowConfig(cfg)
493 const G = w.gantt
494 const items = view.agents.filter((a) => a.start)
495 if (!items.length) return { mode: 'empty', rows: [] }
496 const t0 = Math.min(...items.map((a) => a.start))
497 const tailEnd = (a) => (a.status === 'running' && a.est ? nowMs + a.est.ms.mid : null)
498 const t1 = Math.max(view.live ? nowMs : 0, ...items.map((a) => a.end || (a.status === 'running' ? nowMs : a.start)), ...items.map((a) => tailEnd(a) || 0), t0 + 60000)
499 const labelW = Math.min(G.label_w, Math.max(6, Math.floor(width / 4)))
500 const barW = width - labelW - 1
501 if (barW < G.min_bar) {
502 // vertical: one line per start / end / estimated end, in time order, with the now line in between
503 const ev = []
504 for (const a of items) {
505 ev.push({ ts: a.start, text: `▶ ${a.label}`, kind: 'running', phase: a.phase })
506 if (a.end && a.status !== 'running') ev.push({ ts: a.end, text: `${a.status === 'failed' ? '✗' : '■'} ${a.label} (${frDur(a.end - a.start)})`, kind: a.status, phase: a.phase })
507 const te = tailEnd(a)
508 if (te) ev.push({ ts: te, text: `┄ ${a.label} ${w.labels.est_tail}`, kind: 'tail', phase: a.phase })
509 }
510 if (view.live) ev.push({ ts: nowMs, text: `── ${w.labels.now} ──`, kind: 'now' })
511 ev.sort((a, b) => a.ts - b.ts || (a.kind === 'now' ? 1 : -1))
512 return { mode: 'vertical', rows: ev.map((e) => ({ ...e, time: clock(e.ts) })) }
513 }
514 // horizontal: ONE renderer with the ci mod's Diagramme (lib/core/gantt.mjs), one span for every phase
515 const flat = []
516 for (const p of view.phases) for (const a of p.agents) if (a.start) flat.push({ p, a })
517 const g = coreGantt(flat.map(({ a }) => ({
518 label: a.label, status: coreStatus(a.status), startMs: a.start, endMs: a.status === 'running' ? null : a.end || a.start,
519 estEndMs: tailEnd(a),
520 })), nowMs, barW)
521 const groups = []
522 flat.forEach(({ p, a }, i) => {
523 let grp = groups.find((x) => x.index === p.index)
524 if (!grp) groups.push((grp = { title: p.title, index: p.index, rows: [] }))
525 const r = g.rows[i]
526 grp.rows.push({ label: a.label, status: a.status, cells: r.segs.map((sg) => ({ kind: KIND[sg.kind] || sg.kind, text: sg.text })) })
527 })
528 return { mode: 'horizontal', labelW, barW, nowCol: g.nowCol, from: clock(g.t0), to: clock(g.t1), t0: g.t0, t1: g.t1, groups }
529}
530
531// agent status -> lib/core/gantt status; core segment kind -> this screen's kind (colours of workflow_draw.mjs)
532const coreStatus = (s) => (s === 'running' ? 'running' : s === 'failed' || s === 'killed' || s === 'interrupted' ? 'failed' : 'success')
533const KIND = { est: 'tail', queue: 'skipped' }
534
535/** The legend under the bars: lib/core/gantt.mjs legend, the same words as ci's Diagramme. */
536export const ganttLegend = (labels) => coreLegend(labels)
537
538export function axis(g) {
539 if (g.mode !== 'horizontal') return ''
540 return coreAxis({ t0: g.t0, t1: g.t1, width: g.barW }, g.labelW + 1, clock)
541}
542
543// ---- command arguments -----------------------------------------------------------------------------------------------
544
545const WORDS = new Set(['workflow', 'workflows', 'wf'])
546
547// "/factory workflow" -> {workflow: true, scope: null}; "/factory workflow all" -> scope 'all'; else {workflow: false}.
548export function parseWorkflowArgs(args) {
549 const words = String(args || '').trim().toLowerCase().split(/\s+/).filter(Boolean)
550 if (!words.length || !WORDS.has(words[0])) return { workflow: false, scope: null }
551 const s = words[1]
552 return { workflow: true, scope: s === 'all' || s === 'tout' || s === 'toutes' ? 'all' : s === 'conv' || s === 'conversation' ? 'conversation' : null }
553}
554
555export function workflowArgs(cfg, opts) {
556 const w = workflowConfig(cfg)
557 const a = [opts.script, '--cache', opts.cache, '--hours', String(w.hours), '--stale-h', String(w.stale_h), '--history-days', String(w.history_days)]
558 if (opts.scope === 'all') a.push('--all')
559 else if (opts.session) a.push('--session', opts.session)
560 return ['-I', ...a]
561}
562
563// ---- Agent-tool agents outside a Workflow -----------------------------------------------------------------------------
564
565const msOf = (v) => (!v ? 0 : typeof v === 'number' ? (v > 1e12 ? v : v * 1000) : Date.parse(v) || 0)
566
567/**
568 * Running Agent-tool agents with no Workflow, from factory's scan (sessions[].subs). scope 'all': every conversation;
569 * else only `cli`. ETA: durations (first → last line) of finished agents of the same type in the scan, then of every
570 * type, through lib/core/estimate.mjs (min_samples, else « pas assez d'historique »). Pure.
571 * Returns [{id, cli, conv, repo, type, desc, model, bg, start, eta: {mid, lo, hi, overrun, n} | null, text}].
572 */
573export function loneAgents(scan, cfg, nowMs, opts = {}) {
574 const w = workflowConfig(cfg)
575 if (!w.lone || w.lone.enabled === false) return []
576 const L = w.labels
577 const sessions = (scan && scan.sessions) || []
578 const done = []
579 for (const s of sessions) for (const x of s.subs || []) {
580 const a = msOf(x.ts)
581 const b = msOf(x.last_ts)
582 if (!x.workflow && x.status === 'done' && a && b > a) done.push({ type: x.type, ms: b - a })
583 }
584 const min = Number(w.lone.min_samples) || 3
585 const out = []
586 for (const s of sessions) {
587 if (opts.scope !== 'all' && opts.cli && s.cli !== opts.cli) continue
588 for (const x of s.subs || []) {
589 if (x.workflow || x.status !== 'running') continue
590 const start = msOf(x.ts) || nowMs
591 const est = estimateOf(done.filter((d) => d.type === x.type).map((d) => d.ms), { fallback: done.map((d) => d.ms), min })
592 const eta = etaOf(est, start, nowMs)
593 const etaText = !eta ? L.no_history : eta.overrun ? fill(L.lone_overrun, { n: eta.n }) : fill(L.lone_eta, { time: clock(eta.mid), n: eta.n })
594 const conv = scrub(titleOf(s), 40)
595 out.push({ id: x.id, cli: s.cli, conv, repo: repoOf(s), type: x.type || 'agent', desc: scrub(x.desc || '', 60), model: x.model || '', bg: Boolean(x.bg),
596 start, eta, text: fill(L.lone_row, { type: x.type || 'agent', bg: x.bg ? ` (${L.lone_bg})` : '', desc: scrub(x.desc || '', 60) || '—', conv, dur: frDur(nowMs - start), eta: etaText }) })
597 }
598 }
599 return out.sort((a, b) => b.start - a.start).slice(0, Math.max(1, Number(w.lone.max) || 12))
600}
601
602export { tokensOf }
603
hooks/draw.mjs 447 lines
1// factory v2 - draws the side panel with native elements only (Box, Text, Button, Link): tabs on top, each screen a
2// stack of sections, top to bottom, that fills the pane's width. No fixed-size canvas, so nothing needs zoom.
3// Pure except for the element factory `el` (from $.ui.resolve, or the text renderer of scanner/preview.mjs) and the
4// action callbacks in `V.act`. The view models come from screens.mjs. Screen ideas (big counters, Focus "what needs
5// me", live timeline) from rig-console in github.com/korallis/agent-stack (Apache-2.0); no code copied.
6import { fmtTokens, fmtUsd, hhmm, short, family, rateFor, compactEvents } from './logic.mjs'
7import { waitingConfig, fill as wfill, age } from './waiting.mjs'
8import {
9 screensConfig, tabsOf, layout, chunk, bar, effortBars, clip, fill, mission, focus, tree, pipeline, quotas, system, journal,
10 JOURNAL_KINDS,
11} from './screens.mjs'
12
13// ---- small helpers --------------------------------------------------------------------------------------------------
14
15function mk(el, cfg) {
16 const color = (k) => (cfg && cfg.colors && cfg.colors[k]) || undefined
17 const T = (text, o = {}) => {
18 const p = { children: [String(text ?? '')] }
19 if (o.color) p.color = color(o.color) || o.color
20 if (o.bold) p.bold = true
21 if (o.dim) p.dimColor = true
22 p.wrap = o.wrap || 'wrap'
23 return el.Text(p)
24 }
25 const row = (parts, o = {}) => el.Box({ flexDirection: 'row', flexWrap: 'wrap', gap: 1, ...o, children: parts.filter(Boolean) })
26 const col = (parts, o = {}) => el.Box({ flexDirection: 'column', ...o, children: parts.filter(Boolean) })
27 const section = (title, parts, o = {}) => el.Box({
28 flexDirection: 'column', borderStyle: 'round', borderColor: color(o.color || 'dim'), paddingX: 1, marginBottom: 1,
29 ...(o.key ? { key: o.key } : {}),
30 ...(o.marginLeft ? { marginLeft: o.marginLeft } : {}),
31 ...(o.grow ? { flexGrow: 1 } : {}),
32 children: [title ? T(title, { bold: true, color: o.color }) : null, ...parts].filter(Boolean),
33 })
34 const btn = (label, onPress, primary, key) => el.Button({ children: [label], variant: primary ? 'primary' : 'secondary', onPress, ...(key ? { key } : {}) })
35 const link = (href, label) => (href ? (el.Link ? el.Link({ href, children: [label] }) : T(label, { dim: true })) : null)
36 const famColor = (model) => family(model)
37 return { T, row, col, section, btn, link, color, famColor }
38}
39
40const hm = (ts) => hhmm(ts).slice(0, 5)
41
42function whenText(ms) {
43 if (!ms) return ''
44 const d = new Date(ms)
45 const days = ['dim', 'lun', 'mar', 'mer', 'jeu', 'ven', 'sam']
46 return `${days[d.getDay()]} ${String(d.getDate()).padStart(2, '0')}/${String(d.getMonth() + 1).padStart(2, '0')} ${d.getHours()}h${String(d.getMinutes()).padStart(2, '0')}`
47}
48
49// ---- the pane -----------------------------------------------------------------------------------------------------
50
51// V = { cfg, tab, scan, at, busy, error, columns, filter, jfilter, jproject, picking, live, quotas, machine, act }
52export function drawPane(el, V) {
53 const cfg = V.cfg || {}
54 const sc = screensConfig(cfg)
55 const L = sc.labels
56 const lay = layout(V.columns, cfg)
57 const h = mk(el, cfg)
58 const tabs = tabsOf(cfg)
59 const tab = tabs.some((t) => t.id === V.tab) ? V.tab : (tabs[0] || { id: 'mission' }).id
60 const top = [
61 h.row(tabs.map((t) => h.btn(t.label, () => V.act.tab(t.id), t.id === tab)), { marginBottom: 1 }),
62 h.row([
63 h.btn(V.busy ? L.refreshing : L.refresh, () => V.act.refresh()),
64 h.T(fill(L.updated, { time: V.at ? hm(V.at) : '--:--' }), { dim: true }),
65 ], { marginBottom: 1, alignItems: 'center' }),
66 ]
67 if (V.error) top.push(h.T(`scanner : ${V.error}`, { color: 'bad' }))
68 if (!V.scan) return h.col([...top, h.T(L.scanning, { dim: true })])
69 return h.col([...top, ...drawScreen(el, V, tab)])
70}
71
72const SCREENS = {
73 mission: drawMission, focus: drawFocus, arbre: drawTree, pipeline: drawPipeline, quotas: drawQuotas, systeme: drawSystem, journal: drawJournal,
74}
75
76// One screen's body (the sections under the tabs), for a mod that composes factory screens in its own pane (cockpit).
77// V as for drawPane; V.embedded hides the Arbre's « Cette conversation / Choisir » row (the host picks the conversation).
78export function drawScreen(el, V, tab) {
79 const cfg = V.cfg || {}
80 const draw = SCREENS[tab]
81 if (!draw || !V.scan) return []
82 return draw(mk(el, cfg), V, cfg, screensConfig(cfg).labels, layout(V.columns, cfg))
83}
84
85// ---- Mission ---------------------------------------------------------------------------------------------------------
86
87function counterGrid(h, items, n) {
88 return chunk(items, n).map((line, i) => h.row(line.map((it) => h.section(null, [
89 h.T(it.value, { bold: true, color: it.color }),
90 h.T(it.label, { dim: true }),
91 ...(it.sub || []).map((s) => h.T(s, { color: it.color })),
92 ], { color: it.color, key: 'c-' + it.label, grow: true })), { key: 'cg' + i, flexWrap: 'nowrap', gap: 1 }))
93}
94
95function drawMission(h, V, cfg, L, lay) {
96 const m = mission(V.scan, cfg, V.at)
97 const c = m.counters
98 const C = L.counters
99 const out = []
100 out.push(...counterGrid(h, [
101 { value: c.working, label: C.working, color: 'running' },
102 { value: c.idle, label: C.idle, color: 'dim' },
103 { value: c.blocked, label: C.blocked, color: c.blocked ? 'bad' : 'dim', sub: c.blockedReasons.map((r) => clip(r, lay.textMax)) },
104 { value: c.julian, label: C.julian, color: c.julian ? 'warn' : 'dim' },
105 { value: c.done, label: C.done, color: 'ok' },
106 { value: fmtUsd(c.cost), label: `${C.cost} (${cfg.cost_label || 'estimation'})`, color: 'opus' },
107 ], lay.counterCols))
108 // projects
109 const cards = m.projects.map((p) => h.section(p.repo, [
110 h.row([
111 h.T(`${L.lead} `, { dim: true }),
112 h.btn(clip(p.lead.title, lay.narrow ? 30 : 48), () => V.act.go(p.lead.cli)),
113 h.T(`${short(p.lead.model)} · ${effortBars(p.lead.effort)} ${p.lead.effort}`, { color: h.famColor(p.lead.model) }),
114 h.T(`ctx ${p.lead.ctxPct}%`, { color: p.lead.ctxLevel }),
115 h.T((L.states || {})[p.lead.state] || p.lead.state, { color: stateColor(p.lead.state) }),
116 ], { alignItems: 'center' }),
117 p.subconvs.length ? h.T(`${L.subconv} : ${p.subconvs.map((s) => `${clip(s.title, 26)} (${(L.states || {})[s.state] || s.state}, ${short(s.model)} ${s.effort})`).join(' · ')}`) : null,
118 h.T(`${p.sessions} conv. · ${L.workers} ${p.workers} · ctx max ${p.maxCtxPct}% · ${fmtUsd(p.cost)} ${L.counters.cost}`, { dim: true }),
119 h.T(Object.entries(p.states).map(([k, n]) => `${(L.states || {})[k] || k} ${n}`).join(' · '), { dim: true }),
120 ], { key: 'p-' + p.repo, color: p.live ? 'running' : 'dim', grow: lay.cardCols > 1 }))
121 out.push(h.T(L.projects, { bold: true }))
122 if (lay.cardCols > 1) out.push(...chunk(cards, lay.cardCols).map((r, i) => h.row(r, { key: 'pc' + i, flexWrap: 'nowrap' })))
123 else out.push(...cards)
124 if (!cards.length) out.push(h.T(L.nothing, { dim: true }))
125 // model share vs targets
126 out.push(h.section(m.shareTitle, m.share.map((s) => h.col([
127 h.row([h.T(`${s.family} ${Math.round(s.share * 100)} %`, { bold: true, color: s.family }), h.T(`${L.target} ${s.target}`, { dim: true }),
128 h.T(s.ok ? '✓' : '✗', { color: s.ok ? 'ok' : 'bad', bold: true }), h.T(`${s.calls} appels · ${fmtUsd(s.cost)}`, { dim: true })]),
129 h.T(bar(s.share * 100, lay.bar), { color: s.ok ? s.family : 'bad' }),
130 ], { key: 'sh-' + s.family }))))
131 // conversations with the old All / Live / Problems / Waiting filters
132 out.push(h.T(L.list_title, { bold: true }))
133 const F = [['all', L.filters.all], ['live', L.filters.live], ['problems', L.filters.problems], ['julian', L.filters.julian]]
134 out.push(h.row(F.map(([k, label]) => h.btn(`${label} (${filterRows(m.rows, k).length})`, () => V.act.filter(k), (V.filter || 'all') === k)), { marginBottom: 1 }))
135 for (const r of filterRows(m.rows, V.filter || 'all')) {
136 out.push(h.section(null, [
137 h.row([h.btn(`${r.live ? '● ' : ''}${clip(r.title, lay.textMax - 4)}`, () => V.act.go(r.cli))]),
138 h.row([
139 h.T(`${r.repo}${r.branch ? ' · ' + r.branch.replace(/^claude\//, '') : ''}`, { dim: true }),
140 h.T(`${short(r.model)} · ${effortBars(r.effort)} ${r.effort}`, { color: h.famColor(r.model) }),
141 h.T(`ctx ${r.ctxPct}%`, { color: r.ctxLevel }),
142 h.T(`${fmtUsd(r.costToday)} aujourd’hui`),
143 h.T(`agents ${r.running}/${r.subs}`, { color: r.running ? 'running' : 'dim' }),
144 r.pr ? h.T(`PR #${r.pr.number} ${r.pr.state} · CI ${r.pr.ci}`, { color: r.pr.ci === 'failed' ? 'bad' : r.pr.ci === 'success' ? 'ok' : 'dim' }) : null,
145 r.waiting ? h.T(L.counters.julian, { color: 'warn', bold: true }) : null,
146 ]),
147 r.problem ? h.T(r.problem, { color: r.problemLevel }) : null,
148 ], { key: 'conv-' + r.cli, color: r.waiting ? 'warn' : r.live ? 'running' : 'dim' }))
149 }
150 return out
151}
152
153export function filterRows(rows, f) {
154 if (f === 'live') return rows.filter((r) => r.live)
155 if (f === 'problems') return rows.filter((r) => r.problem && r.problemLevel !== 'ok')
156 if (f === 'julian') return rows.filter((r) => r.waiting)
157 return rows
158}
159
160function stateColor(st) {
161 return { working: 'running', julian: 'warn', blocked: 'bad', done: 'ok', idle: 'dim', archived: 'dim', running: 'running', failed: 'failed', stopped: 'stopped' }[st] || 'dim'
162}
163
164// ---- Focus -----------------------------------------------------------------------------------------------------------
165
166function waitingSection(h, V, cfg, lay) {
167 const w = waitingConfig(cfg)
168 if (!w.enabled) return null
169 const WL = w.labels
170 const f = focus(V.scan, cfg, V.at)
171 const g = f.waiting
172 const shown = g.rows.slice(0, w.max_rows)
173 const kids = []
174 if (!g.rows.length) kids.push(h.T(WL.none, { dim: true }))
175 for (const r of shown) {
176 kids.push(h.col([
177 h.row([h.T((WL.kinds || {})[r.kind] || r.kind, { color: r.level, bold: true }), h.T(`${WL.since} ${hm(r.since)} (${age(V.at - r.since)})`, { dim: true })]),
178 h.T(r.what),
179 h.row([
180 r.session ? h.btn(`${WL.open_session} ${clip(r.session.title, 36)}`, () => V.act.go(r.session.cli)) : null,
181 h.link(r.link, r.kind === 'green' || r.kind === 'idle' ? r.pr || 'PR' : 'session'),
182 ], { alignItems: 'center' }),
183 ], { key: 'wait-' + r.key, marginBottom: 1 }))
184 }
185 if (g.rows.length > shown.length) kids.push(h.T(wfill(WL.more, { n: g.rows.length - shown.length }), { dim: true }))
186 if (g.errors.length) kids.push(h.T(wfill(WL.reviews_error, { errors: g.errors.join(' · ') }), { color: 'warn' }))
187 if (g.children.length) {
188 kids.push(h.T(WL.children, { bold: true }))
189 for (const c of g.children) {
190 kids.push(h.col([
191 c.cli ? h.btn(clip(c.title, lay.textMax - 4), () => V.act.go(c.cli)) : h.T(c.title, { bold: true }),
192 ...c.children.map((k) => h.T(` └ ${clip(k.title, lay.textMax - 20)} (${k.label})`, { color: k.state === 'julian' || k.state === 'blocked' ? 'warn' : k.state === 'working' ? 'running' : 'dim' })),
193 ], { key: 'lead-' + c.sid }))
194 }
195 }
196 return h.section(`${WL.title} (${g.rows.length})`, kids, { color: g.rows.length ? 'warn' : 'dim', key: 'waiting' })
197}
198
199function drawFocus(h, V, cfg, L, lay) {
200 const f = focus(V.scan, cfg, V.at)
201 const p = f.pulse
202 const out = [h.T(L.focus_title, { bold: true })]
203 out.push(waitingSection(h, V, cfg, lay))
204 out.push(h.section(L.pulse, [
205 h.row([
206 h.T(`${p.working} ${L.counters.working}`, { color: 'running', bold: true }),
207 h.T(`${p.idle} ${L.counters.idle}`, { dim: true }),
208 h.T(`${p.blocked} ${L.counters.blocked}`, { color: p.blocked ? 'bad' : 'dim', bold: Boolean(p.blocked) }),
209 h.T(`${p.julian} ${L.counters.julian}`, { color: p.julian ? 'warn' : 'dim', bold: Boolean(p.julian) }),
210 h.T(`${p.running} ${L.agents_running}`, { color: 'running' }),
211 h.T(`${fmtUsd(p.cost)} ${L.counters.cost}`),
212 ]),
213 ...p.blockedReasons.map((r) => h.T(`▲ ${r}`, { color: 'bad' })),
214 ], { key: 'pulse' }))
215 out.push(h.section(L.timeline_title, f.timeline.length ? f.timeline.map((t, i) => h.col([
216 h.row([h.T(hm(t.ts), { dim: true }), h.T(t.label, { color: t.level, bold: true }), h.T(clip(t.title, 40), { dim: true })]),
217 t.text ? h.T(` ${t.text}`) : null,
218 ], { key: 'tl' + i })) : [h.T(L.nothing, { dim: true })], { key: 'timeline' }))
219 out.push(h.section(L.progress, f.progress.length ? f.progress.map((pr) => h.col([
220 h.row([h.T(pr.repo, { bold: true }), h.T(fill(L.progress_row, pr), { dim: true })]),
221 h.T(bar(pr.pct, lay.bar), { color: pr.pct >= 100 ? 'ok' : 'running' }),
222 ], { key: 'pg-' + pr.repo })) : [h.T(L.nothing, { dim: true })], { key: 'progress' }))
223 return out
224}
225
226// ---- Arbre -----------------------------------------------------------------------------------------------------------
227
228// Running and architect nodes get a box; finished ones a compact 2-3 line entry, model and effort always visible.
229// open: (id) => opens that agent's transcript ($.ui.view), given only for this conversation on an engine that has it.
230function nodeBox(h, n, cfg, L, lay, indent, inWorkflow, open) {
231 const st = (L.agent_states || {})[n.status] || n.status
232 if (n.status !== 'running' && !n.architect) {
233 return h.col([
234 h.row([h.T('├', { dim: true }), h.T(n.type, { bold: true }), h.T(st, { color: stateColor(n.status) }),
235 h.T(`${short(n.model)} · ${effortBars(n.effort)} ${n.effort}`, { color: h.famColor(n.model), bold: true }),
236 n.explicit || inWorkflow ? null : h.T('modèle hérité', { color: 'warn' }), h.T(`${fmtTokens(n.tokens)} tok · ${fmtUsd(n.cost)}`, { dim: true })]),
237 n.task ? h.T(`│ ${clip(n.task, lay.textMax - 6)}`, { dim: true }) : null,
238 ], { key: 'n-' + n.id, marginLeft: indent || 0 })
239 }
240 return h.section(null, [
241 h.row([h.T(n.type, { bold: true }), h.T(`· ${st}`, { color: stateColor(n.status) }), n.bg ? h.T('arrière-plan', { dim: true }) : null,
242 n.architect ? h.T(`architecte : ${(L.architect_trigger_labels || {})[n.architect] || n.architect}`, { color: 'architect', bold: true }) : null]),
243 h.row([h.T(short(n.model), { color: h.famColor(n.model), bold: true }), h.T(`effort ${effortBars(n.effort)} ${n.effort}`, { color: h.famColor(n.model) }),
244 n.explicit || inWorkflow ? null : h.T('modèle non précisé (hérité)', { color: 'warn' })]),
245 h.row([h.T(`${fmtTokens(n.tokens)} tok`), h.T(fmtUsd(n.cost)), n.phase ? h.T(`phase ${n.phase}`, { dim: true }) : null]),
246 n.task ? h.T(clip(n.task, lay.textMax * 2), { dim: true }) : null,
247 open && n.status === 'running' ? h.row([h.btn(L.open_agent || 'Ouvrir l’agent', () => open(n.id), true, 'open-agent-' + n.id)], { key: 'open-' + n.id }) : null,
248 ], { key: 'n-' + n.id, color: n.architect ? 'architect' : stateColor(n.status), ...(indent ? { marginLeft: indent } : {}) })
249}
250
251function drawTree(h, V, cfg, L, lay) {
252 const out = []
253 if (!V.embedded) out.push(h.row([
254 h.btn(L.this_conv, () => V.act.go(null), !V.target),
255 h.btn(L.pick, () => V.act.pick(), Boolean(V.picking)),
256 ], { marginBottom: 1 }))
257 if (V.picking) {
258 const rows = mission(V.scan, cfg, V.at).rows
259 out.push(h.section(L.pick, rows.map((r) => h.row([
260 h.btn(`${r.live ? '● ' : ''}${clip(r.title, lay.textMax - 20)}`, () => V.act.go(r.cli)),
261 h.T(`${r.repo} · ${short(r.model)} ${r.effort}`, { dim: true }),
262 ], { key: 'pick-' + r.cli, alignItems: 'center' })), { key: 'picker' }))
263 }
264 const t = tree(V.scan, cfg, V.at)
265 if (!t) return [...out, h.T(V.busy ? L.scanning : L.not_found, { dim: true })]
266 const m = t.main
267 const rate = rateFor(m.model, cfg)
268 out.push(h.T(`${t.title}`, { bold: true }))
269 out.push(h.T(`${t.repo}${t.branch ? ' · ' + t.branch : ''}`, { dim: true }))
270 out.push(h.section(`${short(m.model)} · ${L.main}`, [
271 h.T(`effort ${effortBars(m.effort)} ${m.effort}`, { color: h.famColor(m.model), bold: true }),
272 h.T(`$${rate.in} / $${rate.out} par 1M (entrée / sortie)`, { dim: true }),
273 h.T(`contexte ${fmtTokens(m.ctx)} / ${fmtTokens(m.window)} (${m.ctxPct} %)`, { color: m.ctxLevel }),
274 h.T(bar(m.ctxPct, lay.bar), { color: m.ctxLevel }),
275 h.T(`coût ${fmtUsd(m.cost)} (${cfg.cost_label || 'estimation'}) · lead seul ${fmtUsd(m.ownCost)}`),
276 t.pr ? h.T(`PR #${t.pr.number} ${t.pr.state || ''} · CI ${t.pr.ci || '?'}`, { color: t.pr.ci === 'failed' ? 'bad' : t.pr.ci === 'success' ? 'ok' : 'dim' }) : h.T('pas encore de PR', { dim: true }),
277 h.T(m.live ? `◐ ${L.agent_states.running}` : (L.states.idle), { color: m.live ? 'running' : 'dim' }),
278 t.waiting ? h.T(L.counters.julian, { color: 'warn', bold: true }) : null,
279 ], { color: family(m.model), key: 'main' }))
280 // sub-conversations
281 if (t.children.length) {
282 out.push(h.T(`│ ${L.subconvs} (${t.children.length})`, { bold: true }))
283 for (const c of t.children) {
284 out.push(h.section(null, [
285 h.row([h.btn(clip(c.title, lay.textMax - 8), () => V.act.go(c.cli))]),
286 h.row([h.T(short(c.model), { color: h.famColor(c.model), bold: true }), h.T(`effort ${effortBars(c.effort)} ${c.effort}`, { color: h.famColor(c.model) }),
287 h.T((L.states || {})[c.state] || c.state, { color: stateColor(c.state) }), h.T(`ctx ${c.ctxPct}%`, { color: c.ctxLevel })]),
288 h.row([h.T(`agents ${c.running}/${c.agents}`), h.T(`${fmtTokens(c.tokens)} tok`), h.T(fmtUsd(c.cost)),
289 c.pr ? h.T(`PR #${c.pr.number} ${c.pr.state} · CI ${c.pr.ci}`, { color: c.pr.ci === 'failed' ? 'bad' : 'dim' }) : null]),
290 c.reason ? h.T(c.reason, { color: stateColor(c.state) }) : null,
291 ], { key: 'child-' + c.cli, color: stateColor(c.state), marginLeft: 2 }))
292 }
293 }
294 // agents and workflows
295 out.push(h.T(`│ agents (${t.running} en cours / ${t.totalAgents})`, { bold: true }))
296 const open = V.canView && V.self && V.scan && V.scan.detail && V.scan.detail.cli === V.self && V.act.openAgent ? (id) => V.act.openAgent(id) : null
297 if (V.canView && V.viewAgent && V.act.backToConv) out.push(h.row([h.btn(L.back_conv || '← Conversation', () => V.act.backToConv(), false, 'back-conv-btn')], { key: 'back-conv' }))
298 const more = (v, indent) => (v.hidden ? h.T(`${' '.repeat(indent)}+ ${v.hidden} plus anciens : ${v.hiddenText}`, { dim: true }) : null)
299 for (const n of t.agentsView.shown) out.push(nodeBox(h, n, cfg, L, lay, 2, false, open))
300 out.push(more(t.agentsView, 2))
301 for (const w of t.workflowsView) {
302 out.push(h.T(`└ ${L.workflow} ${w.name} · ${w.nodes.length} agents, ${w.running} en cours, ${fmtTokens(w.tokens)} tok, ${fmtUsd(w.cost)}`, { bold: true }))
303 for (const n of w.view.shown) out.push(nodeBox(h, n, cfg, L, lay, 4, true, open))
304 out.push(more(w.view, 4))
305 }
306 if (!t.totalAgents) out.push(h.T(` ${L.no_agents}`, { dim: true }))
307 // architect on call
308 const a = t.architect
309 out.push(h.section(L.architect_title, [
310 h.row(a.triggers.map((x) => h.T(`${x.count ? '◆' : '◇'} ${x.label}${x.count ? ' ×' + x.count : ''}`, { color: x.count ? 'architect' : 'dim', bold: Boolean(x.count) }))),
311 h.T(fill(L.architect_calls, { calls: a.calls, tokens: fmtTokens(a.tokens) })),
312 a.last ? h.T(`dernier : ${clip(a.last.task, lay.textMax)}`, { dim: true }) : h.T(L.architect_none, { dim: true }),
313 ], { color: 'architect', key: 'arch' }))
314 // bill
315 out.push(h.section(`${L.bill_title} : ${fmtUsd(t.total)}`, [
316 h.row([h.T(L.bill_every), h.T(fmtUsd(t.billSplit.every), { bold: true })]),
317 h.T(bar(t.total ? (100 * t.billSplit.every) / t.total : 0, lay.bar), { color: family(m.model) }),
318 h.row([h.T(L.bill_on_call), h.T(fmtUsd(t.billSplit.onCall), { bold: true, color: 'architect' })]),
319 h.T(bar(t.total ? (100 * t.billSplit.onCall) / t.total : 0, lay.bar), { color: 'architect' }),
320 ...Object.entries(t.bill).sort((x, y) => y[1].cost - x[1].cost).map(([model, b]) => h.row([h.T(short(model), { color: family(model) }),
321 h.T(fmtUsd(b.cost)), h.T(`${fmtTokens(b.tokens)} tok, ${b.calls} appels`, { dim: true })], { key: 'b-' + model })),
322 ], { key: 'bill' }))
323 // approvals and guards
324 out.push(h.section(`${L.guards_title} (${t.guards.length})`, t.guards.length
325 ? t.guards.map((g, i) => h.T(`${hm(g.ts)} ${g.src} ${g.text}`, { color: 'warn' }))
326 : [h.T(`✓ ${L.guards_none}`, { color: 'ok' })], { key: 'guards', color: t.guards.length ? 'warn' : 'ok' }))
327 // warnings
328 out.push(h.section(`${L.warnings_title} (${t.warnings.length})`, t.warnings.length
329 ? t.warnings.map((w) => h.T(`• ${w.text}`, { color: w.level }))
330 : [h.T(`✓ ${L.warnings_none}`, { color: 'ok' })], { key: 'warnings', color: t.warnings.length ? 'warn' : 'ok' }))
331 // session log
332 out.push(h.section(L.log_title, t.events.map((e, i) => h.row([h.T(hhmm(e[0]), { dim: true }), h.T(e[1], { color: e[1] === 'prompt' ? undefined : 'running', bold: e[1] === 'prompt' }), h.T(e[2])], { key: 'ev' + i, flexWrap: 'nowrap' })), { key: 'log' }))
333 out.push(h.T(t.status, { color: family(m.model), bold: true }))
334 return out
335}
336
337// ---- Pipeline --------------------------------------------------------------------------------------------------------
338
339function drawPipeline(h, V, cfg, L, lay) {
340 const p = pipeline(V.scan, cfg, V.at)
341 const out = [h.T(L.pipeline_title, { bold: true })]
342 out.push(...counterGrid(h, p.stages.map((s) => ({ value: p.totals[s.id], label: s.label, color: p.totals[s.id] ? 'running' : 'dim' })), Math.min(lay.counterCols === 6 ? 5 : lay.counterCols, 5)))
343 for (const r of p.rows) {
344 out.push(h.section(r.repo, p.stages.filter((s) => r.stages[s.id].length).map((s) => h.col([
345 h.T(`${s.label} (${r.stages[s.id].length})`, { bold: true }),
346 ...r.stages[s.id].map((it) => h.row([
347 h.btn(clip(it.title, lay.textMax - 22), () => V.act.go(it.cli)),
348 h.T(`${(L.states || {})[it.state] || it.state}${it.pr ? ' · PR ' + it.pr : ''}`, { color: it.level }),
349 ], { key: 'pi-' + it.cli, alignItems: 'center' })),
350 ], { key: r.repo + s.id })), { key: 'pipe-' + r.repo, color: 'dim' }))
351 }
352 if (!p.rows.length) out.push(h.T(L.nothing, { dim: true }))
353 out.push(h.T(L.pipeline_note, { dim: true }))
354 return out
355}
356
357// ---- Quotas ----------------------------------------------------------------------------------------------------------
358
359function missing(h, L, mod) {
360 return h.section(fill(L.module_missing, { mod }), [h.T(fill(L.module_missing_hint, { mod }), { dim: true })], { color: 'warn', key: 'missing-' + mod })
361}
362
363function drawQuotas(h, V, cfg, L, lay) {
364 const q = quotas(V.scan, cfg, V.at, V.live, V.quotas)
365 const out = [h.T(L.quotas_title, { bold: true })]
366 out.push(h.section('Claude', q.windows.map((w) => w.available ? h.col([
367 h.row([h.T(w.label, { bold: true }), h.T(`${Math.round(w.pct)} %`, { bold: true, color: w.pct >= 80 ? 'bad' : w.pct >= 50 ? 'warn' : 'ok' }),
368 w.reset ? h.T(fill(L.reset, { when: whenText(w.reset) }), { dim: true }) : null]),
369 h.T(bar(w.pct, lay.bar), { color: w.pct >= 80 ? 'bad' : w.pct >= 50 ? 'warn' : 'ok' }),
370 w.forecast ? h.T(w.forecast, { color: /épuisé/.test(w.forecast) ? 'warn' : 'dim' }) : null,
371 ], { key: 'w-' + w.kind, marginBottom: 1 }) : h.T(`${w.label} : ${L.unavailable}`, { dim: true })), { key: 'claude' }))
372 if (q.usage !== 'ok') out.push(missing(h, L, 'usage'))
373 if (q.codex) {
374 out.push(h.section(L.codex, q.codex.available ? [
375 ...q.codex.windows.map((w, i) => h.col([
376 h.row([h.T(w.label, { bold: true }), h.T(`${Math.round(w.pct)} %`, { bold: true, color: w.pct >= 80 ? 'bad' : 'ok' }), w.reset ? h.T(fill(L.reset, { when: whenText(w.reset) }), { dim: true }) : null, w.stale ? h.T('ancienne lecture', { dim: true }) : null]),
377 h.T(bar(w.pct, lay.bar), { color: w.pct >= 80 ? 'bad' : 'ok' }),
378 ], { key: 'cx' + i })),
379 ...(q.codex.missing || []).map((x) => h.T(`${x} : ${L.unavailable}`, { dim: true })),
380 Number.isFinite(q.codex.today) ? h.T(`aujourd’hui ${fmtTokens(q.codex.today)} tokens`, { dim: true }) : null,
381 ] : [h.T(`${L.unavailable} (${q.codex.reason})`, { dim: true })], { key: 'codex' }))
382 }
383 const maxM = Math.max(0.01, ...q.byModel.map((x) => x.cost))
384 out.push(h.section(`${L.cost_model} : ${fmtUsd(q.total)}`, q.byModel.length ? q.byModel.map((x) => h.col([
385 h.row([h.T(short(x.model), { color: x.family, bold: true }), h.T(fmtUsd(x.cost)), h.T(`${fmtTokens(x.tokens)} tok · ${x.calls} appels`, { dim: true })]),
386 h.T(bar((100 * x.cost) / maxM, lay.bar), { color: x.family }),
387 ], { key: 'cm-' + x.model })) : [h.T(L.nothing, { dim: true })], { key: 'cost-model' }))
388 const maxP = Math.max(0.01, ...q.byProject.map((x) => x.cost))
389 out.push(h.section(L.cost_project, q.byProject.length ? q.byProject.map((x) => h.col([
390 h.row([h.T(x.repo, { bold: true }), h.T(fmtUsd(x.cost)), h.T(`${x.sessions} conv. · ${fmtTokens(x.tokens)} tok`, { dim: true })]),
391 h.T(bar((100 * x.cost) / maxP, lay.bar), { color: 'running' }),
392 ], { key: 'cp-' + x.repo })) : [h.T(L.nothing, { dim: true })], { key: 'cost-project' }))
393 out.push(h.T(`$ = ${cfg.cost_label || 'estimation'} (tokens × tarifs de factory.config.json)${V.quotas && V.quotas.note ? ' · ' + V.quotas.note : ''}`, { dim: true }))
394 return out
395}
396
397// ---- Système ---------------------------------------------------------------------------------------------------------
398
399function drawSystem(h, V, cfg, L, lay) {
400 const out = [h.T(L.system_title, { bold: true })]
401 const mc = V.machine || {}
402 if (mc.missing) return [...out, missing(h, L, 'machine')]
403 const s = system(mc.sample, mc.runner)
404 if (!s.available) return [...out, h.T(mc.error ? `machine : ${mc.error}` : L.scanning, { dim: !mc.error, color: mc.error ? 'bad' : undefined })]
405 const lvl = (p) => (p >= 90 ? 'bad' : p >= 70 ? 'warn' : 'ok')
406 const gauge = (label, pct, text, key) => h.col([
407 h.row([h.T(label, { bold: true }), h.T(pct === null || pct === undefined ? L.unavailable : `${Math.round(pct)} %`, { bold: true, color: pct === null ? 'dim' : lvl(pct) }), text ? h.T(text, { dim: true }) : null]),
408 pct === null || pct === undefined ? null : h.T(bar(pct, lay.bar), { color: lvl(pct) }),
409 ], { key, marginBottom: 1 })
410 out.push(h.section(null, [
411 gauge(`${L.cpu} (${s.ncpu} cœurs)`, s.cpu, '', 'cpu'),
412 gauge(L.ram, s.ram ? s.ram.pct : null, s.ram ? s.ram.text : '', 'ram'),
413 ...(s.gpus.length ? s.gpus.map((g, i) => gauge(`${L.gpu} ${g.name}`, g.pct, [g.mem, g.temp ? `${g.temp} °C` : ''].filter(Boolean).join(' · '), 'gpu' + i))
414 : [h.T(`${L.gpu} : ${s.gpuRead ? L.unavailable : 'lecture espacée (gpu_every)'}`, { dim: true })]),
415 ...s.disks.map((d) => gauge(`${L.disk} ${d.drive}`, d.pct, d.text, 'd-' + d.drive)),
416 ], { key: 'machine' }))
417 if (s.families.length) out.push(h.section('Processus par famille', s.families.map((f) => h.T(`${f.name} · ${f.count} · ${f.cpu} % CPU`, { key: 'f-' + f.name })), { key: 'fam' }))
418 out.push(h.section(L.runner, [
419 s.runnerProc ? h.T(`processus ${s.runnerProc.present ? 'présent' : 'absent'} · ${s.runnerProc.children} jobs enfants`, { color: s.runnerProc.present ? 'ok' : 'warn' }) : null,
420 ...s.runners.map((r, i) => {
421 const j = r.jobs && typeof r.jobs === 'object' ? r.jobs : {}
422 const n = r.runners && typeof r.runners === 'object' ? r.runners : {}
423 const q = (v) => (v === null || v === undefined ? '?' : v)
424 return h.T(`${r.label} : ${r.usable === 'yes' || r.usable === true ? 'utilisable' : 'non utilisable'} · jobs ${q(j.running)} en cours, ${q(j.pending)} en attente · runners ${q(n.online)}/${q(n.total)} en ligne${r.concurrent ? ' · max ' + r.concurrent : ''}`,
425 { color: r.usable === 'yes' || r.usable === true ? 'ok' : 'dim' })
426 }),
427 s.runnerError ? h.T(s.runnerError, { dim: true }) : null,
428 !s.runnerProc && !s.runners.length && !s.runnerError ? h.T(L.unavailable, { dim: true }) : null,
429 ], { key: 'runner' }))
430 if (mc.metricsMissing) out.push(missing(h, L, 'metrics'))
431 return out
432}
433
434// ---- Journal ---------------------------------------------------------------------------------------------------------
435
436function drawJournal(h, V, cfg, L, lay) {
437 const j = journal(V.scan, cfg, V.jfilter || 'all', V.jproject || '')
438 const out = [h.T(L.journal_title, { bold: true })]
439 out.push(h.row(JOURNAL_KINDS.map((k) => h.btn(`${(L.journal_kinds || {})[k] || k} (${j.counts[k] || 0})`, () => V.act.jfilter(k), (V.jfilter || 'all') === k)), { marginBottom: 1 }))
440 out.push(h.row([h.btn('tous les projets', () => V.act.jproject(''), !V.jproject), ...j.projects.map((p) => h.btn(p, () => V.act.jproject(p), V.jproject === p))], { marginBottom: 1 }))
441 out.push(h.section(null, j.rows.length ? j.rows.map((r, i) => h.col([
442 h.row([h.T(hm(r.ts), { dim: true }), h.T(r.kind, { color: r.kind === 'error' ? 'bad' : r.kind === 'compact' ? 'warn' : 'running', bold: true }), h.T(`${r.repo} · ${clip(r.title, 36)}`, { dim: true })]),
443 h.T(` ${compactEvents([[r.ts, r.kind, r.text]])[0][2]}`),
444 ], { key: 'j' + i })) : [h.T(L.nothing, { dim: true })], { key: 'journal' }))
445 return out
446}
447
lib/core/estimate.mjs 50 lines
1// Canonical copy: lib/core/estimate.mjs (repo root). Every mods/<mod>/lib/core/estimate.mjs is a byte copy made by
2// scripts/sync-libs.mjs: never edit a copy by hand.
3// One estimate rule for Workflows (factory) and pipelines (ci): from past successful durations, the median and the
4// p25-p75 range, ONLY when there are at least MIN_SAMPLES of them; else a fallback list may serve, else no estimate
5// (« pas assez d'historique »). Pure.
6
7export const MIN_SAMPLES = 3
8
9/** n, median, p25, p75 (linear interpolation; same as factory's workflow.mjs quantiles). */
10export function quantiles(xs) {
11 const v = (xs || []).filter((x) => Number.isFinite(x)).sort((a, b) => a - b)
12 if (!v.length) return { n: 0, median: 0, p25: 0, p75: 0 }
13 const q = (p) => {
14 const i = (v.length - 1) * p
15 const lo = Math.floor(i)
16 return v[lo] + (v[Math.min(v.length - 1, lo + 1)] - v[lo]) * (i - lo)
17 }
18 return { n: v.length, median: q(0.5), p25: q(0.25), p75: q(0.75) }
19}
20
21/**
22 * Duration estimate from past successful runs [{ms, ok}] or plain numbers (ms). The first list with at least
23 * `min` successes wins (basis 'primary' or 'fallback'); else {enough: false, n} with the larger sample size.
24 */
25export function estimateOf(runs, { fallback = [], min = MIN_SAMPLES } = {}) {
26 const ok = (xs) => (xs || []).map((r) => (typeof r === 'number' ? r : r && r.ok !== false ? r.ms : NaN)).filter((x) => Number.isFinite(x) && x >= 0)
27 const a = ok(runs)
28 if (a.length >= min) return { enough: true, basis: 'primary', ...quantiles(a) }
29 const b = ok(fallback)
30 if (b.length >= min) return { enough: true, basis: 'fallback', ...quantiles(b) }
31 return { enough: false, basis: null, n: Math.max(a.length, b.length), median: 0, p25: 0, p75: 0 }
32}
33
34/** What is left after `elapsedMs`: {lo, mid, hi} ms (never negative), overrun once past p75. Null without estimate. */
35export function remaining(est, elapsedMs) {
36 if (!est || est.enough === false) return null
37 const e = Math.max(0, elapsedMs || 0)
38 return {
39 lo: Math.max(0, est.p25 - e), mid: Math.max(0, est.median - e), hi: Math.max(0, est.p75 - e),
40 overrun: e > est.p75, n: est.n,
41 }
42}
43
44/** End times {lo, mid, hi} (epoch ms) of something started at startMs, never before now. Null without estimate. */
45export function etaOf(est, startMs, nowMs) {
46 const r = remaining(est, nowMs - startMs)
47 if (!r) return null
48 return { lo: nowMs + r.lo, mid: nowMs + r.mid, hi: nowMs + r.hi, overrun: r.overrun, n: r.n }
49}
50
lib/core/gantt.mjs 111 lines
1// Canonical copy: lib/core/gantt.mjs (repo root). Every mods/<mod>/lib/core/gantt.mjs is a byte copy made by
2// scripts/sync-libs.mjs: never edit a copy by hand.
3// ONE Gantt renderer for Workflow agents (factory) and pipeline jobs (ci), so both look the same. Pure.
4// Input rows: {label, status, queuedMs, startMs, endMs, estEndMs}; status queued | running | done | success | failed |
5// canceled. Output: per row, text segments of exactly `width` cells with one symbol set:
6// ░ queue █ done ▓ running ▒ failed ┄ estimate │ now · empty
7// svg() draws the same bars as an SVG string: a picture only (not clickable in a mod pane).
8
9export const SYMBOLS = { queue: '░', done: '█', running: '▓', failed: '▒', est: '┄', now: '│', empty: '·' }
10export const LEGEND = { queue: 'file', done: 'fini', running: 'en cours', failed: 'échoué', est: 'estimation', now: 'maintenant' }
11export const COLORS = { queue: '#8b949e', done: '#3fb950', running: '#2f81f7', failed: '#f85149', est: '#8b949e', now: '#d29922', empty: '#8b949e55' }
12
13const fin = (v) => Number.isFinite(v)
14
15/** Kind of the run part of a row. */
16export function runKind(status) {
17 const s = String(status || '').toLowerCase()
18 if (s === 'failed' || s === 'error' || s === 'canceled' || s === 'cancelled') return 'failed'
19 if (s === 'running' || s === 'queued' || s === 'pending') return 'running'
20 return 'done'
21}
22
23const live = (r) => /^(running|queued|pending)$/i.test(String(r.status || ''))
24
25/** Time span shown: earliest queue/start to the latest end, estimated end or now (when something is live). */
26export function span(rows, nowMs) {
27 const starts = rows.flatMap((r) => [r.queuedMs, r.startMs]).filter(fin)
28 const t0 = starts.length ? Math.min(...starts) : nowMs
29 const ends = rows.flatMap((r) => [r.endMs, r.estEndMs, r.startMs]).filter(fin)
30 const t1 = Math.max(t0 + 1000, ...ends, rows.some(live) ? nowMs : t0 + 1000)
31 return { t0, t1 }
32}
33
34/** Rows -> {rows: [{label, status, cells, segs: [{text, kind}]}], t0, t1, width, nowCol}. */
35export function gantt(rows, nowMs, width = 40) {
36 const list = (rows || []).filter((r) => r && (fin(r.queuedMs) || fin(r.startMs)))
37 const w = Math.max(2, Math.floor(width))
38 const { t0, t1 } = span(list, nowMs)
39 const col = (t) => Math.max(0, Math.min(w - 1, Math.floor(((t - t0) / (t1 - t0)) * (w - 1))))
40 const anyLive = list.some(live)
41 const nowCol = anyLive && nowMs >= t0 && nowMs <= t1 ? col(nowMs) : -1
42 const out = list.map((r) => {
43 const kinds = new Array(w).fill('empty')
44 const paint = (a, b, k) => {
45 if (!fin(a) || !fin(b) || b < a) return
46 for (let i = col(a); i <= col(b); i++) kinds[i] = k
47 }
48 const going = live(r)
49 if (fin(r.queuedMs)) paint(r.queuedMs, fin(r.startMs) ? r.startMs : going ? nowMs : r.queuedMs, 'queue')
50 const runEnd = fin(r.endMs) ? r.endMs : going ? nowMs : r.startMs
51 if (fin(r.startMs)) paint(r.startMs, runEnd, runKind(r.status))
52 if (going && fin(r.estEndMs) && r.estEndMs > nowMs) {
53 const from = Math.max(nowMs, fin(runEnd) ? runEnd : nowMs)
54 for (let i = col(from) + 1; i <= col(r.estEndMs); i++) if (kinds[i] === 'empty') kinds[i] = 'est'
55 }
56 if (nowCol >= 0 && kinds[nowCol] === 'empty') kinds[nowCol] = 'now'
57 const segs = []
58 for (const k of kinds) {
59 const last = segs[segs.length - 1]
60 if (last && last.kind === k) last.text += SYMBOLS[k]
61 else segs.push({ text: SYMBOLS[k], kind: k })
62 }
63 return { label: String(r.label ?? ''), status: r.status, cells: kinds, segs }
64 })
65 return { rows: out, t0, t1, width: w, nowCol }
66}
67
68/** The legend line, in symbol order. */
69export function legend(labels = {}) {
70 const L = { ...LEGEND, ...labels }
71 return ['queue', 'done', 'running', 'failed', 'est', 'now'].map((k) => `${SYMBOLS[k]} ${L[k]}`).join(' ')
72}
73
74const clock = (ms) => {
75 const d = new Date(ms)
76 return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
77}
78
79/** Axis line: `pad` spaces (label column), then start and end clock times at both ends of the bar. */
80export function axis(g, pad = 0, fmt = clock) {
81 const a = fmt(g.t0)
82 const b = fmt(g.t1)
83 return ' '.repeat(pad) + a + ' '.repeat(Math.max(1, g.width - a.length - b.length)) + b
84}
85
86const esc = (s) => String(s).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"')
87
88/** The same Gantt as an SVG string (a picture: labels left, one bar per row). */
89export function svg(g, { cell = 6, row = 14, labelW = 120, colors = {} } = {}) {
90 const C = { ...COLORS, ...colors }
91 const W = labelW + g.width * cell
92 const Hh = Math.max(row, g.rows.length * row)
93 const parts = [`<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${Hh}" viewBox="0 0 ${W} ${Hh}">`]
94 g.rows.forEach((r, i) => {
95 const y = i * row
96 parts.push(`<text x="0" y="${y + row - 4}" font-size="${row - 4}" fill="${C.queue}">${esc(r.label)}</text>`)
97 let x = labelW
98 for (const s of r.segs) {
99 const n = [...s.text].length
100 if (s.kind === 'now') parts.push(`<rect x="${x}" y="${y}" width="1" height="${row}" fill="${C.now}"/>`)
101 else if (s.kind !== 'empty') {
102 const dash = s.kind === 'est' ? ' stroke-dasharray="2 2" fill="none" stroke="' + C.est + '"' : ` fill="${C[s.kind]}"`
103 parts.push(`<rect x="${x}" y="${y + 2}" width="${n * cell}" height="${row - 4}"${dash}/>`)
104 }
105 x += n * cell
106 }
107 })
108 parts.push('</svg>')
109 return parts.join('')
110}
111