Skyward for Claude Code: the `/sky` panel over the daemon's computes, an MCP server (`sky mcp`) whose tools read and operate them, and a skill for the Python…

<img src="https://github.com/gabfssilva/skyward/blob/main/docs/logo.svg?raw=true" alt="Skyward" width="140">
Run Python functions on cloud accelerators with automatic provisioning and cleanup.
<a href="https://github.com/gabfssilva/skyward/actions/workflows/tests.yml"><img src="https://github.com/gabfssilva/skyward/actions/workflows/tests.yml/badge.svg" alt="CI"></a> <a href="https://pypi.org/project/skyward/"><img src="https://img.shields.io/pypi/v/skyward" alt="PyPI"></a> <a href="https://pypi.org/project/skyward/"><img src="https://img.shields.io/pypi/pyversions/skyward" alt="Python"></a> <a href="https://github.com/gabfssilva/skyward/blob/main/LICENSE"><img src="https://img.shields.io/github/license/gabfssilva/skyward" alt="License"></a>
<img src="https://github.com/gabfssilva/skyward/blob/main/docs/demo.gif?raw=true" alt="Skyward Demo" width="800">
# pi.py
import skyward as sky
@sky.app(
provider=sky.RunPod(),
accelerator=sky.accelerators.RTX_3090(),
image=sky.Image(pip=["torch", "numpy"]),
)
def estimate_pi(n: int = 100_000_000) -> dict[str, str | float]:
"""Estimate pi from N random points, on a GPU."""
import torch
points = torch.rand(2, n, device="cuda")
inside = (points[0] ** 2 + points[1] ** 2 <= 1).sum().item()
return {"gpu": torch.cuda.get_device_name(), "pi": 4 * inside / n}
sky server start
sky run -f pi.py --n 500000000
uv add "skyward[all]"
all includes every optional extra. For a smaller installation, combine only what you need, e.g. uv add "skyward[client,server,cli,aws]". See available extras.
Full documentation at gabfssilva.github.io/skyward.
hooks/register.tsx 1397 lines1import type { EngineInterface, HttpInit, HttpResponse, Register, RenderElement, Timer } from 'claude-code'
2
3const DAEMON = 'http://127.0.0.1:17590'
4const PANE_ID = 'skyward'
5const REFRESH_MS = 3000
6const LOG_LINES = 20
7const SPARK_STEP_MS = 30_000
8const SPARK_BUCKETS = 20
9const SPARK_GLYPHS = '▁▂▃▄▅▆▇█'
10const NO_SAMPLES: readonly null[] = Array.from({ length: SPARK_BUCKETS }, () => null)
11const NODES_PER_PAGE = 4
12const IDLE_GPU_PCT = 5
13// Four buckets of 30s: a gap between two tasks is not idleness.
14const IDLE_BUCKETS = 4
15const NODE_STAGES = ['requested', 'provisioning', 'connecting', 'bootstrapping', 'ready', 'draining', 'lost', 'deleting', 'deleted', 'failed']
16// The states the daemon counts a node alive in; a node in any other is already on its way out.
17const DRAINABLE = new Set(['requested', 'provisioning', 'connecting', 'bootstrapping', 'ready'])
18// The states a task is still in flight in; a cancel of one that finished is answered and changes nothing.
19const CANCELLABLE = new Set(['queued', 'running'])
20const TASKS_PER_PAGE = 5
21const WRITE_ATTEMPTS = 5
22const NAME_WIDTH = 16
23// The frame names of the events that are a failure, and how far back and how many of them are read.
24const FAILURES = ['compute.degraded', 'compute.deletion_failed', 'node.lost', 'node.failed', 'task.failed', 'task.timed_out']
25const FAILURE_WINDOW_MS = 24 * 60 * 60 * 1000
26const FAILURE_SAMPLE = 200
27const SEEN_KEY = 'seen'
28const MARQUEE_MS = 250
29const MARQUEE_PAUSE_FRAMES = 8
30
31type Compute = {
32 id: string
33 name: string | null
34 state: string
35 nodes: Node[]
36 nodesReady: number
37 nodesTotal: number
38 provider: string
39 accelerator: string | null
40 acceleratorCount: number
41 rate: number
42 createdAt: number
43 ended: boolean
44 cost: number | null
45 bounds: Bounds
46 /** Each node's newest reading of each metric, keyed node/name — present when the read asked for it. */
47 latest: Map<string, number>
48}
49
50// `spec.nodes`, with an unset `min` or `max` read as `initial`, as the reconciler reads it.
51type Bounds = { initial: number; min: number; max: number }
52
53type Node = {
54 id: string
55 rank: number
56 state: string
57 address: string | null
58 machine: string | null
59 market: string | null
60 price: number | null
61 launchedAt: number | null
62 terminatedAt: number | null
63 lastError: string | null
64}
65
66type LogLine = { at: number; node: string | null; type: string; text: string; error: boolean }
67
68// `cursors` is the way back from the newest page: the log only pages toward older entries.
69type LogFilter = { node: string | null; task: string | null; term: string; cursors: readonly string[] }
70type LogPage = { path: string; lines: LogLine[]; next: string | null }
71
72type Failure = { sequence: number; compute: string; kind: string; reason: string | null; at: number }
73// The failures of one kind on one compute for one reason, the newest first: a rank lost five times is one notice.
74type Notice = { compute: string; kind: string; reason: string | null; sequences: number[]; at: number }
75// What was seen, by sequence, and when it was: what was seen a window ago failed earlier still, and is forgotten.
76type Seen = ReadonlyMap<number, number>
77
78// `node` and `startedAt` come from the latest attempt. `cancelling` is an attempt in `cancel_requested`: its worker was
79// asked to stop it and has not said it did, so the task is still running.
80type Task = {
81 id: string
82 sha: string
83 name: string | null
84 state: string
85 node: string | null
86 attempts: number
87 submittedAt: number
88 startedAt: number | null
89 finishedAt: number | null
90 cancelling: boolean
91}
92
93type TaskOrder = 'state' | 'submitted' | 'finished'
94// Tasks also page forward only, so `cursors` is the way back to the first page.
95type TaskQuery = { order: TaskOrder; fn: string | null; cursors: readonly string[] }
96type TaskPage = { items: Task[]; total: number | null; next: string | null; counts: Map<string, number> }
97
98// What the compute is as a whole: its nodes counted by stage, the mean of each metric over the nodes still
99// alive, and whether it is doing anything. `idle` is null when no node reported gpu_util in the window, and
100// `capped` means the whole window was idle, so it began before the window did.
101type Fleet = {
102 stages: readonly (readonly [string, number])[]
103 averages: ReadonlyMap<string, number>
104 running: number
105 idle: { since: number; capped: boolean } | null
106}
107
108// `listed` is `nodes` cut to `group`, and what `page` and `pageCount` count.
109type Detail = {
110 compute: Compute
111 fleet: Fleet
112 nodes: Node[]
113 group: NodeGroup | null
114 listed: Node[]
115 page: number
116 pageCount: number
117 latest: Map<string, number>
118 sparks: Map<string, (number | null)[]>
119 tasks: TaskPage
120 log: LogPage
121 failures: Failure[]
122}
123
124type DetailView = { kind: 'detail'; id: string; page: number; group: NodeGroup | null; expanded: ReadonlySet<string>; tasks: TaskQuery; log: LogFilter }
125type View = { kind: 'list' } | DetailView
126
127type Step = { step: 'asking' } | { step: 'sending' } | { step: 'failed'; reason: string }
128// One confirmation or form is open at a time, so asking for one closes the other. A kill's `id` is the node's, a
129// cancel's the task's; a scale's `min` and `max` are what was typed, empty for the bound it was opened on.
130type Action = ({ kind: 'delete'; id: string } | { kind: 'kill'; id: string } | { kind: 'cancel'; id: string } | { kind: 'scale'; id: string; min: string; max: string; invalid: boolean }) & Step
131
132// A write outlives the drawing that pressed it, so it goes through the command's engine rather than the render's.
133type Writes = {
134 remove: (id: string) => Promise<void>
135 scale: (c: Compute, min: number, max: number) => Promise<void>
136 drain: (compute: string, node: string) => Promise<void>
137 cancel: (task: string) => Promise<void>
138 seen: (seen: Seen) => Promise<void>
139}
140
141type Snapshot =
142 | { kind: 'loading' }
143 | { kind: 'down'; reason: string }
144 | { kind: 'list'; live: Compute[]; recent: Compute[]; failures: Failure[]; at: number }
145 | { kind: 'detail'; detail: Detail; at: number }
146
147const STATE_COLORS = new Map([
148 ['requested', 'yellow'],
149 ['provisioning', 'yellow'],
150 ['connecting', 'yellow'],
151 ['bootstrapping', 'yellow'],
152 ['ready', 'green'],
153 ['degraded', 'red'],
154 ['draining', 'magenta'],
155 ['deleting', 'magenta'],
156])
157
158// Dark enough for white text on light and dark themes; no pure green, red or yellow, which the states use.
159const RANK_COLORS = ['#3b6fd8', '#8e5bd6', '#1f8f8f', '#c7702a', '#c2427a', '#6b8e23', '#546e7a', '#8d6e63']
160const RANK_WIDTH = 5
161
162const NEXT_TASK_ORDER: Record<TaskOrder, TaskOrder> = { state: 'submitted', submitted: 'finished', finished: 'state' }
163// The rest (cancelled, timed_out, indeterminate) is shown as what the total leaves over.
164const COUNTED_TASK_STATES = ['running', 'queued', 'succeeded', 'failed']
165const TASK_GLYPHS = new Map([
166 ['running', '●'],
167 ['queued', '◌'],
168 ['succeeded', '✓'],
169 ['failed', '✗'],
170 ['timed_out', '✗'],
171 ['cancelled', '○'],
172 ['indeterminate', '?'],
173])
174const TASK_COLORS = new Map([
175 ['running', 'green'],
176 ['failed', 'red'],
177 ['timed_out', 'red'],
178 ['indeterminate', 'magenta'],
179])
180
181const STATE_GLYPHS = new Map([
182 ['requested', '◌'],
183 ['provisioning', '◐'],
184 ['ready', '●'],
185 ['degraded', '●'],
186 ['deleting', '◑'],
187 ['deleted', '○'],
188])
189
190const at = (value: unknown, ...path: string[]): unknown =>
191 path.reduce<unknown>((current, key) => {
192 if (typeof current !== 'object' || current === null) return undefined
193 const field: unknown = Object.getOwnPropertyDescriptor(current, key)?.value
194 return field
195 }, value)
196const str = (value: unknown): string | undefined => (typeof value === 'string' ? value : undefined)
197const num = (value: unknown): number | undefined => (typeof value === 'number' ? value : undefined)
198const list = (value: unknown): unknown[] => (Array.isArray(value) ? value : [])
199const time = (value: unknown): number | null => {
200 const ms = Date.parse(str(value) ?? '')
201 return Number.isNaN(ms) ? null : ms
202}
203const items = <T,>(body: unknown, parse: (item: unknown) => T | undefined): T[] =>
204 list(at(body, 'items')).flatMap((item) => {
205 const parsed = parse(item)
206 return parsed === undefined ? [] : [parsed]
207 })
208// The engine refuses a whole tree when a Text holds an escape sequence, and a node prints them: tqdm moves the cursor
209// up over its bars and redraws each after `\r`. A line keeps what a terminal would leave of it, and no control
210// character but tab and newline.
211const ESCAPE = /\x1b(?:\[[0-?]*[ -/]*[@-~]|\][^\x07\x1b]*(?:\x07|\x1b\\)?|[ -/]*[0-~])?/g
212const CONTROL = /[\x00-\x08\x0b-\x1f\x7f-\x9f]/g
213const printable = (text: string): string =>
214 text
215 .replace(ESCAPE, '')
216 .split('\n')
217 .map((line) => line.split('\r').findLast((part) => part !== '') ?? '')
218 .join('\n')
219 .replace(CONTROL, '')
220const metricKey = (node: string, name: string): string => `${node}/${name}`
221const metricNode = (key: string): string => key.slice(0, key.lastIndexOf('/'))
222
223function parseCompute(item: unknown): Compute | undefined {
224 const id = str(at(item, 'id'))
225 const state = str(at(item, 'status', 'state'))
226 const createdAt = time(at(item, 'created_at'))
227 if (id === undefined || state === undefined || createdAt === null) return undefined
228
229 const spec = at(item, 'spec', 'specs', '0')
230 // A compute carries the node holding each rank, and the ones that held one before when the read asked for them.
231 const nodes = list(at(item, 'nodes'))
232 .flatMap((node) => {
233 const parsed = parseNode(node)
234 return parsed === undefined ? [] : [parsed]
235 })
236 .sort((a, b) => Number(a.terminatedAt !== null) - Number(b.terminatedAt !== null) || a.rank - b.rank)
237 const alive = nodes.filter((node) => node.terminatedAt === null)
238 const initial = num(at(item, 'spec', 'nodes', 'initial')) ?? 0
239 return {
240 id,
241 state,
242 nodes,
243 nodesReady: alive.filter((node) => node.state === 'ready').length,
244 nodesTotal: alive.length,
245 createdAt,
246 name: str(at(item, 'name')) ?? null,
247 provider: str(at(item, 'provider', 'name')) ?? str(at(spec, 'provider', 'name')) ?? '?',
248 accelerator: str(at(item, 'offer', 'accelerator')) ?? str(at(spec, 'accelerator')) ?? null,
249 acceleratorCount: num(at(item, 'offer', 'accelerator_count')) ?? num(at(spec, 'accelerator_count')) ?? 1,
250 rate: num(at(item, 'rate')) ?? 0,
251 ended: time(at(item, 'ended', 'at')) !== null,
252 cost: num(at(item, 'cost')) ?? null,
253 bounds: { initial, min: num(at(item, 'spec', 'nodes', 'min')) ?? initial, max: num(at(item, 'spec', 'nodes', 'max')) ?? initial },
254 latest: new Map(
255 list(at(item, 'nodes')).flatMap((node) => {
256 const id = str(at(node, 'id'))
257 const metrics = at(node, 'metrics')
258 if (id === undefined || typeof metrics !== 'object' || metrics === null) return []
259 return Object.entries(metrics).flatMap(([name, gauge]): [string, number][] => {
260 const value = num(at(gauge, 'value'))
261 return value === undefined ? [] : [[metricKey(id, name), value]]
262 })
263 }),
264 ),
265 }
266}
267
268function parseNode(item: unknown): Node | undefined {
269 const id = str(at(item, 'id'))
270 const rank = num(at(item, 'rank'))
271 const state = str(at(item, 'state'))
272 if (id === undefined || rank === undefined || state === undefined) return undefined
273 return {
274 id,
275 rank,
276 state,
277 address: str(at(item, 'address')) ?? null,
278 machine: str(at(item, 'machine')) ?? null,
279 market: str(at(item, 'market')) ?? null,
280 price: num(at(item, 'price_per_hour')) ?? null,
281 launchedAt: time(at(item, 'launched_at')),
282 terminatedAt: time(at(item, 'terminated_at')),
283 lastError: str(at(item, 'last_error', 'message')) ?? null,
284 }
285}
286
287function parseLogLine(item: unknown): LogLine | undefined {
288 const type = str(at(item, 'type'))
289 const when = time(at(item, 'at'))
290 if (type === undefined || when === null) return undefined
291 const data = at(item, 'data')
292 const raw = str(at(data, 'error'))
293 const error = raw === undefined ? undefined : printable(raw)
294 const content = str(at(data, 'content')) ?? ''
295 const shown = printable(content)
296 // A line that only moved the cursor leaves nothing to read.
297 if (type === 'node.console' && content !== '' && shown === '') return undefined
298 const text =
299 type === 'node.console'
300 ? shown
301 : type === 'node.phase'
302 ? `${str(at(data, 'phase')) ?? '?'} ${str(at(data, 'event')) ?? '?'}`
303 : type
304 return {
305 at: when,
306 type,
307 node: str(at(data, 'node')) ?? null,
308 text: error === undefined ? text : `${text}: ${error}`,
309 error: error !== undefined,
310 }
311}
312
313function parseTask(item: unknown): Task | undefined {
314 const id = str(at(item, 'id'))
315 const sha = str(at(item, 'function', 'sha256'))
316 const state = str(at(item, 'state'))
317 const submittedAt = time(at(item, 'submitted_at'))
318 if (id === undefined || sha === undefined || state === undefined || submittedAt === null) return undefined
319 const executions = list(at(item, 'executions'))
320 const latest = executions.at(-1)
321 return {
322 id,
323 sha,
324 state,
325 submittedAt,
326 name: str(at(item, 'function', 'name')) ?? null,
327 node: str(at(latest, 'node_id')) ?? null,
328 attempts: executions.length,
329 startedAt: time(at(latest, 'started_at')),
330 finishedAt: time(at(item, 'finished_at')),
331 cancelling: executions.some((execution) => str(at(execution, 'state')) === 'cancel_requested'),
332 }
333}
334
335function parseFailure(item: unknown): Failure | undefined {
336 const sequence = num(at(item, 'sequence'))
337 const kind = str(at(item, 'type'))
338 const when = time(at(item, 'at'))
339 const compute = str(at(item, 'data', 'compute'))
340 if (sequence === undefined || kind === undefined || when === null || compute === undefined) return undefined
341 const reason = str(at(item, 'data', 'error'))
342 return { sequence, kind, compute, at: when, reason: reason === undefined ? null : printable(reason) }
343}
344
345// Failures arrive newest first, so the first of each group is its newest.
346function unseen(failures: Failure[], seen: Seen): Notice[] {
347 const groups = new Map<string, Notice>()
348 for (const f of failures) {
349 if (seen.has(f.sequence)) continue
350 const key = JSON.stringify([f.compute, f.kind, f.reason])
351 const group = groups.get(key)
352 if (group === undefined) groups.set(key, { compute: f.compute, kind: f.kind, reason: f.reason, sequences: [f.sequence], at: f.at })
353 else group.sequences.push(f.sequence)
354 }
355 return [...groups.values()].sort((a, b) => b.at - a.at)
356}
357
358const described = (kind: string): string => kind.replace(/^compute\./, '').replace(/[._]/g, ' ')
359
360const seenOf = (stored: unknown): Seen =>
361 new Map(
362 Object.entries(typeof stored === 'object' && stored !== null ? stored : {}).flatMap(([sequence, when]): [number, number][] =>
363 typeof when === 'number' && /^\d+$/.test(sequence) ? [[Number(sequence), when]] : [],
364 ),
365 )
366
367const age = (ms: number): string => {
368 if (ms < 60_000) return `${Math.max(0, Math.floor(ms / 1000))}s`
369 const minutes = Math.floor(ms / 60_000)
370 if (minutes < 60) return `${minutes}m`
371 const hours = Math.floor(minutes / 60)
372 return hours < 48 ? `${hours}h` : `${Math.floor(hours / 24)}d`
373}
374const price = (value: number | null): string => (value === null ? '-' : `$${value.toFixed(2)}/h`)
375const gib = (mb: number): string => (mb / 1024).toFixed(1)
376const rate = (kbps: number): string => (kbps >= 1000 ? `${(kbps / 1000).toFixed(1)}Mb/s` : `${Math.round(kbps)}kb/s`)
377const spark = (buckets: (number | null)[]): string =>
378 buckets
379 .map((value) => (value === null ? ' ' : SPARK_GLYPHS.charAt(Math.max(0, Math.min(7, Math.floor((value / 100) * 8))))))
380 .join('')
381const clock = (ms: number): string => new Date(ms).toTimeString().slice(0, 8)
382const money = (value: number | null): string => (value === null ? '—' : value.toFixed(2))
383const gpu = (c: Compute): string =>
384 c.accelerator === null ? '—' : c.acceleratorCount > 1 ? `${c.acceleratorCount}×${c.accelerator}` : c.accelerator
385const deletable = (c: Compute): boolean => !c.ended && c.state !== 'deleting' && c.state !== 'deleted'
386const NODE_GROUPS = ['active', 'bootstrapping', 'stopping', 'stopped', 'failed'] as const
387type NodeGroup = (typeof NODE_GROUPS)[number]
388// A node given up on keeps the error that condemned it through `deleting` and `deleted`, so on the way out the error,
389// not the state, tells a failure from a node that was drained or scaled away.
390const nodeGroup = (n: Node): NodeGroup => {
391 switch (n.state) {
392 case 'ready':
393 return 'active'
394 case 'requested':
395 case 'provisioning':
396 case 'connecting':
397 case 'bootstrapping':
398 return 'bootstrapping'
399 case 'lost':
400 case 'failed':
401 return 'failed'
402 default:
403 return n.lastError !== null ? 'failed' : n.state === 'deleted' ? 'stopped' : 'stopping'
404 }
405}
406// Without a group the list is the nodes still alive; the machines that ended are listed by picking their group.
407const inGroup = (nodes: Node[], group: NodeGroup | null): Node[] => nodes.filter((n) => (group === null ? n.terminatedAt === null : nodeGroup(n) === group))
408// The group filtered on is kept at zero, so the one way back to every node stays drawn.
409const nodeCounts = (nodes: Node[], filtered: NodeGroup | null): (readonly [NodeGroup, number])[] =>
410 NODE_GROUPS.map((group) => [group, inGroup(nodes, group).length] as const).filter(([group, count]) => count > 0 || group === filtered)
411const hourly = (c: Compute): number | null => (c.ended ? null : c.rate)
412const averaged = (f: Fleet): string => {
413 const mean = (name: string): number | undefined => f.averages.get(name)
414 const pct = (name: string, label: string): string | null => {
415 const value = mean(name)
416 return value === undefined ? null : `${label} ${Math.round(value)}%`
417 }
418 const used = mean('mem_used_mb')
419 const total = mean('mem_total_mb')
420 return [
421 pct('cpu', 'cpu'),
422 pct('gpu_util', 'gpu'),
423 used === undefined || total === undefined ? null : `mem ${gib(used)}/${gib(total)} GB`,
424 pct('disk_used_pct', 'disk'),
425 ]
426 .filter((part) => part !== null)
427 .join(' · ')
428}
429// An empty field keeps the bound the form was opened on.
430const count = (text: string, current: number): number | null => {
431 const typed = text.trim()
432 if (typed === '') return current
433 return /^\d+$/.test(typed) ? Number(typed) : null
434}
435const sum = (values: (number | null)[]): number | null =>
436 values.reduce<number | null>((total, value) => (total === null || value === null ? null : total + value), 0)
437
438// Pauses at both ends, so a name reads from its start before it scrolls and rests on its end before jumping back.
439const marquee = (text: string, width: number, now: number): string => {
440 const overflow = text.length - width
441 if (overflow <= 0) return text
442 const frame = Math.floor(now / MARQUEE_MS) % (overflow + 2 * MARQUEE_PAUSE_FRAMES)
443 const offset = Math.min(overflow, Math.max(0, frame - MARQUEE_PAUSE_FRAMES))
444 return text.slice(offset, offset + width)
445}
446
447type Column = {
448 title: string
449 width: number
450 right: boolean
451 // Lower ranks stay longest when the pane is too narrow for every column.
452 rank: number
453 cell: (c: Compute) => { text: string; color?: string }
454 total?: (live: Compute[]) => string
455}
456
457const COLUMNS: Column[] = [
458 {
459 title: 'STATE',
460 // A glyph and up to 100/100 nodes.
461 width: 9,
462 right: false,
463 rank: 1,
464 cell: (c) => ({
465 text: c.ended ? STATE_GLYPHS.get('deleted') ?? '○' : `${STATE_GLYPHS.get(c.state) ?? '●'} ${c.nodesReady}/${c.nodesTotal}`,
466 color: STATE_COLORS.get(c.state),
467 }),
468 },
469 { title: 'GPU', width: 10, right: false, rank: 2, cell: (c) => ({ text: gpu(c) }) },
470 { title: 'PROVIDER', width: 9, right: false, rank: 6, cell: (c) => ({ text: c.provider }) },
471 { title: '$/H', width: 7, right: true, rank: 4, cell: (c) => ({ text: money(hourly(c)) }), total: (live) => money(sum(live.map(hourly))) },
472 { title: 'COST', width: 7, right: true, rank: 3, cell: (c) => ({ text: money(c.cost) }), total: (live) => money(sum(live.map((c) => c.cost))) },
473 { title: 'AGE', width: 4, right: true, rank: 5, cell: (c) => ({ text: age(Date.now() - c.createdAt) }) },
474]
475
476const TABLE_GAP = 2
477
478const fitColumns = (columns: number): Column[] => {
479 const kept = new Set<Column>()
480 let used = NAME_WIDTH
481 for (const column of [...COLUMNS].sort((a, b) => a.rank - b.rank)) {
482 if (used + TABLE_GAP + column.width > columns) break
483 used += TABLE_GAP + column.width
484 kept.add(column)
485 }
486 return COLUMNS.filter((column) => kept.has(column))
487}
488
489// The daemon refuses with `{code, message}`; a body without a message is shown as it came.
490function refusal(response: HttpResponse): Error {
491 let body: unknown
492 try {
493 body = JSON.parse(response.text)
494 } catch {
495 body = undefined
496 }
497 return new Error(`HTTP ${response.status} ${printable(str(at(body, 'message')) ?? response.text.slice(0, 200))}`)
498}
499
500async function getJson($: EngineInterface, path: string): Promise<unknown> {
501 const response = await $.http.fetch(`${DAEMON}${path}`)
502 if (!response.ok) throw refusal(response)
503 const body: unknown = JSON.parse(response.text)
504 return body
505}
506
507async function loadFailures($: EngineInterface, compute?: string): Promise<Failure[]> {
508 const types = FAILURES.map((type) => `&types=${type}`).join('')
509 const body = await getJson($, `/v1/events/log?limit=${FAILURE_SAMPLE}${types}${compute === undefined ? '' : `&compute=${compute}`}`)
510 const since = Date.now() - FAILURE_WINDOW_MS
511 return items(body, parseFailure).filter((f) => f.at >= since)
512}
513
514async function loadList($: EngineInterface): Promise<Snapshot> {
515 const [live, recent, failures] = await Promise.all([getJson($, '/v1/computes?live=true'), getJson($, '/v1/computes?live=false&limit=5'), loadFailures($)])
516 return { kind: 'list', live: items(live, parseCompute), recent: items(recent, parseCompute), failures, at: Date.now() }
517}
518
519const logPath = (id: string, filter: LogFilter): string => {
520 const cursor = filter.cursors.at(-1)
521 return [
522 `/v1/events/log?compute=${id}&limit=${LOG_LINES}`,
523 filter.node === null ? '' : `&node=${filter.node}`,
524 filter.task === null ? '' : `&task=${filter.task}`,
525 filter.term === '' ? '' : `&contains=${encodeURIComponent(filter.term)}`,
526 cursor === undefined ? '' : `&cursor=${cursor}`,
527 ].join('')
528}
529
530async function loadLog($: EngineInterface, path: string): Promise<LogPage> {
531 const body = await getJson($, path)
532 return { path, lines: items(body, parseLogLine), next: str(at(body, 'next_cursor')) ?? null }
533}
534
535async function loadTasks($: EngineInterface, id: string, query: TaskQuery): Promise<TaskPage> {
536 const filter = `/v1/tasks?compute=${id}${query.fn === null ? '' : `&function=${encodeURIComponent(query.fn)}`}`
537 const cursor = query.cursors.at(-1)
538 const [pageBody, ...countBodies] = await Promise.all([
539 getJson($, `${filter}&limit=${TASKS_PER_PAGE}&order=${query.order}${cursor === undefined ? '' : `&cursor=${cursor}`}`),
540 ...COUNTED_TASK_STATES.map((state) => getJson($, `${filter}&state=${state}&limit=1`)),
541 ])
542 const parsed = items(pageBody, parseTask)
543 const total = num(at(pageBody, 'total')) ?? null
544 // A last page exactly TASKS_PER_PAGE long still carries a cursor, and it leads to an empty page.
545 const last = total !== null && query.cursors.length * TASKS_PER_PAGE + parsed.length >= total
546 return {
547 items: parsed,
548 total,
549 next: last ? null : str(at(pageBody, 'next_cursor')) ?? null,
550 counts: new Map(COUNTED_TASK_STATES.map((state, i) => [state, num(at(countBodies[i], 'total')) ?? 0])),
551 }
552}
553
554async function loadDetail($: EngineInterface, target: DetailView, shown: LogPage | undefined): Promise<Snapshot> {
555 const { id, page: requestedPage } = target
556 const start = (Math.floor(Date.now() / SPARK_STEP_MS) - (SPARK_BUCKETS - 1)) * SPARK_STEP_MS
557 const base = `/v1/computes/${id}`
558 const path = logPath(id, target.log)
559 // The log is append-only, so a page behind a cursor never changes and only the newest page is fetched again.
560 const unchanged = target.log.cursors.length > 0 && shown?.path === path ? shown : undefined
561 // One read is the compute, the node holding each rank, the ones replaced before them, and each node's newest gauges.
562 const [computeBody, tasks, log, failures] = await Promise.all([
563 getJson($, `${base}?include=nodes.replaced,nodes.metrics`),
564 loadTasks($, id, target.tasks),
565 unchanged ?? loadLog($, path),
566 loadFailures($, id),
567 ])
568 const compute = parseCompute(computeBody)
569 if (compute === undefined) throw new Error(`unexpected compute payload for ${id}`)
570
571 // The nodes are filtered and cut into pages here. The metrics are the whole compute's rather than the page's: the
572 // header averages them and reads idleness off the window, and a page's sparklines read the same two maps.
573 const nodes = compute.nodes
574 const listed = inGroup(nodes, target.group)
575 const latest = compute.latest
576 const pageCount = Math.max(1, Math.ceil(listed.length / NODES_PER_PAGE))
577 const page = Math.min(requestedPage, pageCount - 1)
578 const seriesBody = nodes.length === 0 ? undefined : await getJson($, `${base}/metrics?since=${start}&step=${SPARK_STEP_MS}&agg=avg&name=cpu&name=gpu_util`)
579
580 const sparks = new Map<string, (number | null)[]>()
581 for (const series of list(at(seriesBody, 'series'))) {
582 const node = str(at(series, 'node'))
583 const name = str(at(series, 'name'))
584 if (node === undefined || name === undefined) continue
585 const values = list(at(series, 'values'))
586 const buckets = Array.from({ length: SPARK_BUCKETS }, (): number | null => null)
587 list(at(series, 'at')).forEach((bucketAt, i) => {
588 const ms = num(bucketAt)
589 const value = num(values[i])
590 if (ms === undefined || value === undefined) return
591 const index = Math.floor((ms - start) / SPARK_STEP_MS)
592 if (index >= 0 && index < SPARK_BUCKETS) buckets[index] = value
593 })
594 sparks.set(metricKey(node, name), buckets)
595 }
596
597 const alive = nodes.filter((n) => n.terminatedAt === null)
598 const across = (pick: (node: Node) => number | null | undefined): number | undefined => {
599 const values = alive.flatMap((n) => {
600 const value = pick(n)
601 return value === undefined || value === null ? [] : [value]
602 })
603 return values.length === 0 ? undefined : values.reduce((total, value) => total + value, 0) / values.length
604 }
605
606 const averages = new Map<string, number>()
607 for (const name of new Set([...latest.keys()].map((key) => key.slice(key.lastIndexOf('/') + 1)))) {
608 const value = across((n) => latest.get(metricKey(n.id, name)))
609 if (value !== undefined) averages.set(name, value)
610 }
611
612 // The window is the sparkline's own: the last bucket to reach the threshold is when the fleet last did work, and
613 // no bucket reaching it means the idleness began before the window did.
614 const window = Array.from({ length: SPARK_BUCKETS }, (_, i) => across((n) => sparks.get(metricKey(n.id, 'gpu_util'))?.[i]))
615 const busy = window.reduce<number>((found, value, i) => (value !== undefined && value >= IDLE_GPU_PCT ? i : found), -1)
616 const idle =
617 window.every((value) => value === undefined) || SPARK_BUCKETS - 1 - busy < IDLE_BUCKETS
618 ? null
619 : { since: start + (busy + 1) * SPARK_STEP_MS, capped: busy < 0 }
620
621 const fleet: Fleet = {
622 stages: NODE_STAGES.map((state) => [state, alive.filter((n) => n.state === state).length] as const).filter(([, count]) => count > 0),
623 averages,
624 running: tasks.counts.get('running') ?? 0,
625 idle,
626 }
627
628 return {
629 kind: 'detail',
630 detail: { compute, fleet, nodes, group: target.group, listed, page, pageCount, latest, sparks, tasks, log, failures },
631 at: Date.now(),
632 }
633}
634
635// The reconciler's own writes also move the revision, so a refused If-Match is read again and sent again, under the same
636// key when the write carries one.
637async function writeCompute($: EngineInterface, id: string, init: HttpInit): Promise<void> {
638 for (let attempt = 1; ; attempt++) {
639 const revision = num(at(await getJson($, `/v1/computes/${id}`), 'revision'))
640 if (revision === undefined) throw new Error(`unexpected compute payload for ${id}`)
641 const response = await $.http.fetch(`${DAEMON}/v1/computes/${id}`, { ...init, headers: { ...init.headers, 'If-Match': `"${revision}"` } })
642 if (response.ok) return
643 if (response.status !== 412 || attempt === WRITE_ATTEMPTS) throw refusal(response)
644 }
645}
646
647const deleteCompute = ($: EngineInterface, id: string): Promise<void> =>
648 writeCompute($, id, { method: 'DELETE', headers: { 'Idempotency-Key': crypto.randomUUID() } })
649
650// `initial` goes back as it was: it is the size the pool opened at, which only its creation decides.
651const scaleCompute = ($: EngineInterface, c: Compute, min: number, max: number): Promise<void> =>
652 writeCompute($, c.id, {
653 method: 'PATCH',
654 headers: { 'Content-Type': 'application/json' },
655 body: JSON.stringify({ nodes: { initial: c.bounds.initial, min, max } }),
656 })
657
658async function drainNode($: EngineInterface, compute: string, node: string): Promise<void> {
659 const response = await $.http.fetch(`${DAEMON}/v1/computes/${compute}/nodes/${node}`, {
660 method: 'DELETE',
661 headers: { 'Idempotency-Key': crypto.randomUUID() },
662 })
663 if (!response.ok) throw refusal(response)
664}
665
666async function cancelTask($: EngineInterface, task: string): Promise<void> {
667 const response = await $.http.fetch(`${DAEMON}/v1/tasks/${task}`, {
668 method: 'DELETE',
669 headers: { 'Idempotency-Key': crypto.randomUUID() },
670 })
671 if (!response.ok) throw refusal(response)
672}
673
674export const register: Register = (on) => {
675 let view: View = { kind: 'list' }
676 let snapshot: Snapshot = { kind: 'loading' }
677 let loading: View | undefined
678 let timers: Timer[] = []
679 let refresh: (() => void) | undefined
680 let writes: Writes | undefined
681 let focusKey: string | undefined
682 let notice: string | undefined
683 let scrolling = false
684 let action: Action | undefined
685 let seen: Seen = new Map()
686
687 on('session.start', async ($, e, next) => {
688 await $.command.register({ name: 'sky', description: 'Skyward computes panel' })
689 return next(e)
690 })
691
692 on('command.run', { command: 'sky' }, async ($) => {
693 if (timers.length > 0) {
694 await $.ui.close({ id: PANE_ID })
695 return { text: 'Skyward panel hidden' }
696 }
697 await $.ui.open({ id: PANE_ID, title: 'Skyward' })
698 seen = seenOf(await $.store.get(SEEN_KEY))
699 const tick = async () => {
700 const target = view
701 if (loading === target) return
702 loading = target
703 const result = await (target.kind === 'list' ? loadList($) : loadDetail($, target, snapshot.kind === 'detail' ? snapshot.detail.log : undefined))
704 .catch((error: unknown): Snapshot => ({ kind: 'down', reason: error instanceof Error ? error.message : String(error) }))
705 .finally(() => {
706 if (loading === target) loading = undefined
707 })
708 if (view !== target) return
709 snapshot = result
710 $.ui.invalidate('ui.render')
711 }
712 refresh = () => void tick()
713 writes = {
714 remove: (id) => deleteCompute($, id),
715 scale: (c, min, max) => scaleCompute($, c, min, max),
716 drain: (compute, node) => drainNode($, compute, node),
717 cancel: (task) => cancelTask($, task),
718 seen: (next) => $.store.set(SEEN_KEY, Object.fromEntries(next)),
719 }
720 timers = [
721 $.clock.every(REFRESH_MS, refresh),
722 $.clock.every(MARQUEE_MS, () => {
723 if (scrolling) $.ui.invalidate('ui.render')
724 }),
725 ]
726 refresh()
727 return { text: 'Skyward panel shown' }
728 })
729
730 on('ui.close', { id: PANE_ID }, async ($, e, next) => {
731 const result = await next(e)
732 timers.forEach((timer) => timer.cancel())
733 timers = []
734 refresh = undefined
735 writes = undefined
736 view = { kind: 'list' }
737 snapshot = { kind: 'loading' }
738 action = undefined
739 return result
740 })
741
742 on('ui.render', { component: 'Pane', requestId: PANE_ID }, ($, e) => {
743 const { Box, Button, Text } = $.ui.resolve(e)
744 const now = Date.now()
745
746 const show = (next: View, focus: string) => {
747 view = next
748 snapshot = { kind: 'loading' }
749 focusKey = focus
750 notice = undefined
751 action = undefined
752 refresh?.()
753 $.ui.invalidate('ui.render')
754 }
755
756 const open = (id: string) =>
757 show({ kind: 'detail', id, page: 0, group: null, expanded: new Set(), tasks: { order: 'state', fn: null, cursors: [] }, log: { node: null, task: null, term: '', cursors: [] } }, 'back')
758
759 // Drawn at once rather than at the next read; the ring goes to what is left of the section, or out of it.
760 const markSeen = (sequences: number[], focus: string | undefined) => {
761 const daemon = writes
762 if (daemon === undefined) return
763 const since = now - FAILURE_WINDOW_MS
764 seen = new Map([...[...seen].filter(([, when]) => when >= since), ...sequences.map((sequence): [number, number] => [sequence, now])])
765 focusKey = focus
766 $.ui.invalidate('ui.render')
767 void daemon.seen(seen)
768 }
769
770 // Keeps the current snapshot on screen until the page arrives, and both buttons drawn so the focus ring stays put.
771 const turnPage = (page: number, pageCount: number) => {
772 if (view.kind !== 'detail' || page < 0 || page >= pageCount) return
773 view = { ...view, page }
774 refresh?.()
775 }
776
777 const filterLog = (log: LogFilter, at?: { page: number; group: NodeGroup | null }) => {
778 if (view.kind !== 'detail') return
779 if (at !== undefined && (at.page !== view.page || at.group !== view.group)) focusKey = 'log-node'
780 view = { ...view, log, ...at }
781 notice = undefined
782 refresh?.()
783 $.ui.invalidate('ui.render')
784 }
785
786 // Like a page turn, the list changes when the next read arrives, and the buttons pressed stay drawn meanwhile.
787 const filterNodes = (group: NodeGroup) => {
788 if (view.kind !== 'detail') return
789 view = { ...view, group: view.group === group ? null : group, page: 0 }
790 refresh?.()
791 $.ui.invalidate('ui.render')
792 }
793
794 const updateTasks = (tasks: TaskQuery) => {
795 if (view.kind !== 'detail') return
796 view = { ...view, tasks }
797 refresh?.()
798 $.ui.invalidate('ui.render')
799 }
800
801 const toggleLogTask = (taskId: string) => {
802 if (view.kind !== 'detail') return
803 filterLog({ ...view.log, task: view.log.task === taskId ? null : taskId, cursors: [] })
804 }
805
806 const toggleLogNode = (nodeId: string) => {
807 if (view.kind !== 'detail') return
808 filterLog({ ...view.log, node: view.log.node === nodeId ? null : nodeId, cursors: [] })
809 }
810
811 const toggleNode = (nodeId: string) => {
812 if (view.kind !== 'detail') return
813 const expanded = new Set(view.expanded)
814 if (!expanded.delete(nodeId)) expanded.add(nodeId)
815 view = { ...view, expanded }
816 refresh?.()
817 $.ui.invalidate('ui.render')
818 }
819
820 const setAction = (next: Action | undefined, focus?: string) => {
821 action = next
822 if (focus !== undefined) focusKey = focus
823 $.ui.invalidate('ui.render')
824 }
825
826 // A deleted compute, a drained node and a cancelled task lose their controls once the next read shows it, so those
827 // stay in `sending` until then; a scaled compute keeps its controls and is let go at once.
828 const perform = (sending: Action, focus: string, write: (daemon: Writes) => Promise<void>) => {
829 const daemon = writes
830 if (daemon === undefined) return
831 setAction(sending, focus)
832 write(daemon).then(
833 () => {
834 if (action === sending && sending.kind === 'scale') action = undefined
835 refresh?.()
836 },
837 (error: unknown) => {
838 if (action !== sending) return
839 action = { ...sending, step: 'failed', reason: error instanceof Error ? error.message : String(error) }
840 $.ui.invalidate('ui.render')
841 },
842 )
843 }
844
845 // The first press only asks, with the ring on cancel, so a second Enter does not delete.
846 const removeControls = (c: Compute): RenderElement | null => {
847 if (!deletable(c)) return null
848 const pending = action?.kind === 'delete' && action.id === c.id ? action : undefined
849 if (pending?.step === 'asking') {
850 return (
851 <Box flexDirection="row" flexWrap="wrap" columnGap={1}>
852 <Text color="red">delete this compute?</Text>
853 <Button key="delete-confirm" label="yes, delete" onPress={() => perform({ kind: 'delete', id: c.id, step: 'sending' }, 'back', (daemon) => daemon.remove(c.id))} />
854 <Button key="delete-cancel" label="cancel" onPress={() => setAction(undefined, 'delete')} />
855 </Box>
856 )
857 }
858 if (pending?.step === 'sending') return <Text dimColor>deleting…</Text>
859 return <Button key="delete" label="delete" onPress={() => setAction({ kind: 'delete', id: c.id, step: 'asking' }, 'delete-cancel')} />
860 }
861
862 // Reads the drafts from `action` as it is now, not as it was drawn: two fields typed into between draws would
863 // otherwise each write back the other's stale text.
864 const draftScale = (typed: { min?: string; max?: string }) => {
865 if (action?.kind !== 'scale' || action.step !== 'asking') return
866 action = { ...action, ...typed }
867 }
868
869 const applyScale = (c: Compute, typed: { min?: string; max?: string }) => {
870 if (action?.kind !== 'scale' || action.id !== c.id || action.step !== 'asking') return
871 const asked = { ...action, ...typed }
872 const min = count(asked.min, c.bounds.min)
873 const max = count(asked.max, c.bounds.max)
874 if (min === null || max === null || min > max) return setAction({ ...asked, invalid: true })
875 if (min === c.bounds.min && max === c.bounds.max) return setAction(undefined, 'scale')
876 perform({ ...asked, step: 'sending' }, 'back', (daemon) => daemon.scale(c, min, max))
877 }
878
879 // Mobile has no Input, so a compute is scaled there from the CLI or the web console. A field empties on Enter, so
880 // one holding text that was refused shows it back as its placeholder.
881 const scaleControls = (c: Compute): RenderElement | null => {
882 if (!deletable(c) || e.surface === 'mobile') return null
883 const pending = action?.kind === 'scale' && action.id === c.id ? action : undefined
884 if (pending?.step === 'sending') return <Text dimColor>scaling…</Text>
885 if (pending?.step !== 'asking') {
886 return <Button key="scale" label="scale" onPress={() => setAction({ kind: 'scale', id: c.id, min: '', max: '', invalid: false, step: 'asking' }, 'scale-min')} />
887 }
888 const { Input } = $.ui.resolve(e)
889 return (
890 <Box flexDirection="row" flexWrap="wrap" columnGap={1}>
891 <Input key="scale-min" label="min" placeholder={pending.min === '' ? String(c.bounds.min) : pending.min} submitLabel="scale" onInput={(text) => draftScale({ min: text })} onSubmit={(text) => applyScale(c, { min: text })} />
892 <Input key="scale-max" label="max" placeholder={pending.max === '' ? String(c.bounds.max) : pending.max} submitLabel="scale" onInput={(text) => draftScale({ max: text })} onSubmit={(text) => applyScale(c, { max: text })} />
893 <Button key="scale-apply" label="apply" onPress={() => applyScale(c, {})} />
894 <Button key="scale-cancel" label="cancel" onPress={() => setAction(undefined, 'scale')} />
895 {pending.invalid ? <Text color="red">whole numbers, min ≤ max</Text> : null}
896 </Box>
897 )
898 }
899
900 scrolling = false
901 const columns = fitColumns(e.props.bodyColumns)
902 const tableWidth = columns.reduce((width, column) => width + TABLE_GAP + column.width, NAME_WIDTH)
903
904 const cell = (column: Column, text: string, props: { color?: string; dim?: boolean; bold?: boolean }): RenderElement => (
905 <Box width={column.width} flexShrink={0}>
906 <Text wrap="truncate" color={props.color} dimColor={props.dim} bold={props.bold}>
907 {column.right ? text.padStart(column.width) : text}
908 </Text>
909 </Box>
910 )
911
912 const tableRow = (name: RenderElement, cells: RenderElement[]): RenderElement => (
913 <Box flexDirection="row" gap={TABLE_GAP}>
914 <Box width={NAME_WIDTH} flexShrink={0}>{name}</Box>
915 {cells}
916 </Box>
917 )
918
919 const computeRow = (c: Compute): RenderElement => {
920 const name = c.name ?? c.id
921 if (name.length > NAME_WIDTH) scrolling = true
922 return (
923 <Box flexDirection="column">
924 {tableRow(
925 <Button key={c.id} plain label={marquee(name, NAME_WIDTH, now)} dimColor={c.ended} onPress={() => open(c.id)} />,
926 columns.map((column) => {
927 const { text, color } = column.cell(c)
928 return cell(column, text, { color: c.ended ? undefined : color, dim: c.ended })
929 }),
930 )}
931 </Box>
932 )
933 }
934
935 const rule = (): RenderElement => <Text dimColor>{'─'.repeat(tableWidth)}</Text>
936
937 const computeTable = (live: Compute[], recent: Compute[]): RenderElement => (
938 <Box flexDirection="column">
939 {tableRow(<Text dimColor>NAME</Text>, columns.map((column) => cell(column, column.title, { dim: true })))}
940 {rule()}
941 {live.length === 0 ? <Text dimColor>no live computes</Text> : live.map(computeRow)}
942 {live.length === 0
943 ? null
944 : [
945 rule(),
946 tableRow(
947 <Text dimColor>total</Text>,
948 columns.map((column) => cell(column, column.total?.(live) ?? '', { bold: true })),
949 ),
950 ]}
951 {recent.length === 0 ? null : [<Text> </Text>, tableRow(<Text dimColor>recent</Text>, []), ...recent.map(computeRow)]}
952 </Box>
953 )
954
955 // `names` is given on the list, where each notice says its compute and opens it; a compute's own leaves it out.
956 // `after` is where the ring goes once the last notice is seen.
957 const noticesSection = (failures: Failure[], names: Map<string, string> | null, after: string | undefined): RenderElement | null => {
958 const notices = unseen(failures, seen)
959 if (notices.length === 0) return null
960 const rest = notices.length > 1 ? 'notices-all' : after
961 return (
962 <Box flexDirection="column">
963 <Box flexDirection="row" gap={2}>
964 <Text bold>{`Notifications (${notices.length})`}</Text>
965 <Button key="notices-all" plain label="mark all seen" onPress={() => markSeen(notices.flatMap((n) => n.sequences), after)} />
966 </Box>
967 {notices.map((n) => (
968 <Box flexDirection="column">
969 <Box flexDirection="row" flexWrap="wrap" columnGap={1}>
970 <Text color="red">✗</Text>
971 {names === null ? null : <Button key={`notice-open:${n.sequences[0]}`} plain label={names.get(n.compute) ?? n.compute} onPress={() => open(n.compute)} />}
972 <Text color="red">{`${described(n.kind)}${n.sequences.length > 1 ? ` ×${n.sequences.length}` : ''}`}</Text>
973 <Text dimColor>{`${age(now - n.at)} ago`}</Text>
974 <Button key={`notice-seen:${n.sequences[0]}`} plain label="seen" onPress={() => markSeen(n.sequences, rest)} />
975 </Box>
976 {n.reason === null ? null : (
977 <Box paddingLeft={2}>
978 <Text wrap="wrap">{n.reason}</Text>
979 </Box>
980 )}
981 </Box>
982 ))}
983 </Box>
984 )
985 }
986
987 const computeHeader = (c: Compute, f: Fleet): RenderElement => {
988 const means = averaged(f)
989 const quiet = f.idle === null ? null : `${f.idle.capped ? '≥' : ''}${age(now - f.idle.since)}`
990 const tasks = f.running === 0 ? 'no task' : `${f.running} running`
991 // A compute whose gpu is working, or that has no gpu to read, is only called idle by its tasks.
992 const idleness =
993 c.ended || (quiet === null && (f.running > 0 || f.averages.has('gpu_util')))
994 ? null
995 : quiet === null
996 ? { text: `idle · ${tasks}`, color: 'yellow' }
997 : f.running > 0
998 ? { text: `gpu idle ${quiet} · ${tasks}`, color: 'red' }
999 : { text: `idle ${quiet} · ${tasks}`, color: 'yellow' }
1000 return (
1001 <Box flexDirection="column">
1002 <Box flexDirection="row" gap={2}>
1003 <Text bold wrap="truncate">{c.name ?? c.id}</Text>
1004 <Text color={STATE_COLORS.get(c.state)}>{`${STATE_GLYPHS.get(c.state) ?? '●'} ${c.state}`}</Text>
1005 </Box>
1006 <Text dimColor wrap="truncate">
1007 {[
1008 f.stages.length === 0 ? `${c.nodesReady}/${c.nodesTotal} nodes` : f.stages.map(([state, count]) => `${count} ${state}`).join(', '),
1009 c.accelerator === null ? c.provider : `${c.provider} ${gpu(c)}`,
1010 c.ended ? `cost $${money(c.cost)}` : `$${money(c.cost)} spent`,
1011 c.ended ? null : `$${money(hourly(c))}/h`,
1012 age(now - c.createdAt),
1013 ]
1014 .filter((part) => part !== null)
1015 .join(' · ')}
1016 </Text>
1017 {means === '' ? null : <Text dimColor wrap="truncate">{`avg ${means}`}</Text>}
1018 {idleness === null ? null : <Text color={idleness.color} wrap="truncate">{idleness.text}</Text>}
1019 </Box>
1020 )
1021 }
1022
1023 const rankBadge = (rank: number | undefined, muted = false): RenderElement =>
1024 rank === undefined || muted ? (
1025 <Text dimColor>{rank === undefined ? ' #? ' : ` #${rank} `}</Text>
1026 ) : (
1027 <Text bold color="#ffffff" backgroundColor={RANK_COLORS[rank % RANK_COLORS.length]}>{` #${rank} `}</Text>
1028 )
1029
1030 const nodeBlock = (n: Node, d: Detail, sparkStart: number, open: boolean, logging: boolean): RenderElement => {
1031 const terminated = n.terminatedAt !== null
1032 const metric = (name: string) => d.latest.get(metricKey(n.id, name))
1033 const both = (a: number | undefined, b: number | undefined, f: (a: number, b: number) => string) =>
1034 a === undefined || b === undefined ? null : f(a, b)
1035 const one = (a: number | undefined, f: (a: number) => string) => (a === undefined ? null : f(a))
1036
1037 const stats = (parts: [string, string | null][], indent = 4): RenderElement => (
1038 <Box flexDirection="row" flexWrap="wrap" columnGap={2} paddingLeft={indent}>
1039 {parts.map(([label, value]) =>
1040 value === null ? null : (
1041 <Box flexShrink={0}>
1042 <Text><Text dimColor>{`${label} `}</Text>{value}</Text>
1043 </Box>
1044 ),
1045 )}
1046 </Box>
1047 )
1048
1049 const trend = (label: string, name: string, parts: [string, string | null][]): RenderElement | null =>
1050 metric(name) === undefined ? null : (
1051 <Box flexDirection="row" gap={2}>
1052 <Box flexShrink={0}>
1053 <Text>{` ${label} ${spark((d.sparks.get(metricKey(n.id, name)) ?? NO_SAMPLES).slice(sparkStart))}`}</Text>
1054 </Box>
1055 <Box flexShrink={1}>{stats(parts, 0)}</Box>
1056 </Box>
1057 )
1058
1059 const life =
1060 n.launchedAt === null ? null : n.terminatedAt === null ? `up ${age(now - n.launchedAt)}` : `ran ${age(n.terminatedAt - n.launchedAt)}`
1061 const tail = [life, n.price === null ? null : `@ ${price(n.price)}`, n.market === null ? null : `(${n.market.replace('_', ' ')})`]
1062 .filter((part) => part !== null)
1063 .join(' ')
1064
1065 const killing = action?.kind === 'kill' && action.id === n.id ? action : undefined
1066 const kill = terminated || !DRAINABLE.has(n.state) ? null : killing?.step === 'sending' ? (
1067 <Text dimColor>killing…</Text>
1068 ) : (
1069 <Button key={`kill:${n.id}`} plain label="kill" dimColor={killing?.step !== 'asking'} onPress={() => setAction({ kind: 'kill', id: n.id, step: 'asking' }, `kill-cancel:${n.id}`)} />
1070 )
1071
1072 return (
1073 <Box flexDirection="column">
1074 <Box flexDirection="row" gap={1}>
1075 <Button key={`node:${n.id}`} plain label={open ? '▾' : '▸'} onPress={() => toggleNode(n.id)} />
1076 <Box flexShrink={0}>{rankBadge(n.rank, terminated)}</Box>
1077 <Text>
1078 <Text dimColor>is </Text>
1079 <Text color={terminated ? undefined : STATE_COLORS.get(n.state)} dimColor={terminated}>{n.state}</Text>
1080 <Text dimColor>{tail === '' ? '' : ` ${tail}`}</Text>
1081 </Text>
1082 <Box flexShrink={0} paddingLeft={1}>
1083 <Button key={`logs:${n.id}`} plain label="logs" dimColor={!logging} onPress={() => toggleLogNode(n.id)} />
1084 </Box>
1085 {kill === null ? null : <Box flexShrink={0} paddingLeft={1}>{kill}</Box>}
1086 </Box>
1087 {killing?.step === 'asking' ? (
1088 <Box flexDirection="row" flexWrap="wrap" columnGap={1} paddingLeft={4}>
1089 <Text color="red">{`kill #${n.rank}?`}</Text>
1090 <Button key={`kill-confirm:${n.id}`} label="yes, kill" onPress={() => perform({ kind: 'kill', id: n.id, step: 'sending' }, `logs:${n.id}`, (daemon) => daemon.drain(d.compute.id, n.id))} />
1091 <Button key={`kill-cancel:${n.id}`} label="cancel" onPress={() => setAction(undefined, `kill:${n.id}`)} />
1092 <Text dimColor>it drains first, and a new node takes its rank if the compute still wants it</Text>
1093 </Box>
1094 ) : null}
1095 {killing?.step === 'failed' ? <Text color="red">{` kill failed: ${killing.reason}`}</Text> : null}
1096 {terminated
1097 ? null
1098 : stats([
1099 ['cpu', one(metric('cpu'), (v) => `${Math.round(v)}%`)],
1100 ['gpu', one(metric('gpu_util'), (v) => `${Math.round(v)}%`)],
1101 ['memory', both(metric('mem_used_mb'), metric('mem_total_mb'), (used, total) => `${gib(used)}/${gib(total)} GB`)],
1102 ['disk', one(metric('disk_used_pct'), (v) => `${Math.round(v)}%`)],
1103 ])}
1104 {open && !terminated
1105 ? [
1106 trend('cpu', 'cpu', [['net', both(metric('net_rx_kbps'), metric('net_tx_kbps'), (rx, tx) => `↓${rate(rx)} ↑${rate(tx)}`)]]),
1107 trend('gpu', 'gpu_util', [
1108 ['vram', both(metric('gpu_mem_mb'), metric('gpu_mem_total_mb'), (used, total) => `${gib(used)}/${gib(total)} GB`)],
1109 ['temp', one(metric('gpu_temp_c'), (v) => `${Math.round(v)}°C`)],
1110 ['power', one(metric('gpu_power_w'), (v) => `${Math.round(v)} W`)],
1111 ]),
1112 ]
1113 : null}
1114 {open ? (
1115 <Box paddingLeft={4}>
1116 <Text dimColor>{[n.address, n.id, n.machine === null ? null : `machine ${n.machine}`].filter((part) => part !== null).join(' · ')}</Text>
1117 </Box>
1118 ) : null}
1119 </Box>
1120 )
1121 }
1122
1123 const body = (): RenderElement => {
1124 switch (snapshot.kind) {
1125 case 'loading':
1126 return <Text dimColor>loading…</Text>
1127 case 'down':
1128 return (
1129 <Box flexDirection="column">
1130 <Text color="red" wrap="truncate">{`daemon request failed at ${DAEMON}: ${snapshot.reason}`}</Text>
1131 <Text dimColor>sky server start</Text>
1132 </Box>
1133 )
1134 case 'list': {
1135 const listed = [...snapshot.live, ...snapshot.recent]
1136 return (
1137 <Box flexDirection="column" gap={1}>
1138 <Text dimColor>{`${DAEMON} · updated ${clock(snapshot.at)}`}</Text>
1139 {noticesSection(snapshot.failures, new Map(listed.map((c) => [c.id, c.name ?? c.id])), listed[0]?.id)}
1140 {computeTable(snapshot.live, snapshot.recent)}
1141 </Box>
1142 )
1143 }
1144 case 'detail': {
1145 const d = snapshot.detail
1146 const ranks = new Map(d.nodes.map((n) => [n.id, n.rank]))
1147 const first = d.page * NODES_PER_PAGE
1148 const pageNodes = d.listed.slice(first, first + NODES_PER_PAGE)
1149 const counts = nodeCounts(d.nodes, d.group)
1150 // Columns before any node on the page had a sample are blank for all of them, so they are dropped.
1151 const onPage = new Set(pageNodes.map((n) => n.id))
1152 const sparkStart = Math.min(
1153 SPARK_BUCKETS,
1154 ...[...d.sparks]
1155 .filter(([key]) => onPage.has(metricNode(key)))
1156 .map(([, buckets]) => buckets.findIndex((value) => value !== null))
1157 .filter((i) => i >= 0),
1158 )
1159 return (
1160 <Box flexDirection="column" gap={1}>
1161 <Box flexDirection="column">
1162 {computeHeader(d.compute, d.fleet)}
1163 <Text dimColor>{`${d.compute.id} · updated ${clock(snapshot.at)}`}</Text>
1164 </Box>
1165 {noticesSection(d.failures, null, 'back')}
1166 <Box flexDirection="column">
1167 <Box flexDirection="row" gap={2}>
1168 {counts.length === 0 ? (
1169 <Text bold>Nodes (0)</Text>
1170 ) : (
1171 <Box flexDirection="row" flexWrap="wrap">
1172 <Text bold>Nodes (</Text>
1173 {counts.map(([group, count], i) => [
1174 i === 0 ? null : <Text bold> · </Text>,
1175 <Button key={`nodes-group:${group}`} plain label={`${count} ${group}${d.group === group ? ' ✕' : ''}`} dimColor={d.group !== null && d.group !== group} onPress={() => filterNodes(group)} />,
1176 ])}
1177 <Text bold>)</Text>
1178 </Box>
1179 )}
1180 {d.pageCount > 1 ? (
1181 <Box flexDirection="row" gap={1}>
1182 <Button key="nodes-prev" plain label="‹ prev" dimColor={d.page === 0} onPress={() => turnPage(d.page - 1, d.pageCount)} />
1183 <Text dimColor>{`${first + 1}–${first + pageNodes.length} of ${d.listed.length}`}</Text>
1184 <Button key="nodes-next" plain label="next ›" dimColor={d.page === d.pageCount - 1} onPress={() => turnPage(d.page + 1, d.pageCount)} />
1185 </Box>
1186 ) : null}
1187 </Box>
1188 {d.listed.length === 0 ? <Text dimColor>{d.group === null ? 'no live nodes' : `no ${d.group} nodes`}</Text> : pageNodes.map((n) => nodeBlock(n, d, sparkStart, view.kind === 'detail' && view.expanded.has(n.id), view.kind === 'detail' && view.log.node === n.id))}
1189 </Box>
1190 {view.kind === 'detail' ? tasksSection(d, view, ranks) : null}
1191 {view.kind === 'detail' ? logSection(d, view, ranks) : null}
1192 </Box>
1193 )
1194 }
1195 }
1196 }
1197
1198 const taskRow = (t: Task, query: TaskQuery, ranks: Map<string, number>, logging: boolean): RenderElement => {
1199 const state = t.state.replace('_', ' ')
1200 const took = t.startedAt === null ? null : age((t.finishedAt ?? now) - t.startedAt)