Merge pull request #4079 from ruvnet/codex/console-orbital-theme

feat(console): optional Orbital theme and Theme Studio
This commit is contained in:
rUv authored and GitHub committed 2026-10-12 05:54:51 -07:00
commit 3209ba2667
43 files changed
+1900 -118

No files matched your search

@@ -1,7 +1,7 @@
{
"name": "ruflo-console",
"description": "ruflo's cockpit inside Claude Code and the one /ruflo command for every ruflo mod (function hooks, early access). Views: overview with health alerts, swarm topology graph, claims flow with TTL rings, federation map, plugin health matrix, learning curve and pipeline, MetaHarness radar and audit trend, memory, cost gauge, agent timeline, approvals queue, event stream, a main menu, an x.ruv.io federation board, an AI terminal (codex, claude or both in remembered sessions, streamed), Skills (npx skills), a Hive-Mind view, a MetaHarness lab, agent drill-down; a command palette for confirm-gated actions through the ruflo CLI; a band above the prompt. Reads ruflo's files and the CLI's local JSON; anything not measured reads n/a. The one network call it makes by itself is a daily read of the published plugin.json at github.com/ruvnet/ruflo to offer an update (Settings → Updates: ask, auto, or off); it installs only through Claude Code's own claude plugin update, and never a new major version without asking.",
"version": "0.42.7",
"version": "0.43.0",
"author": {
"name": "ruvnet",
"url": "https://github.com/ruvnet"
@@ -85,17 +85,18 @@
"look": {
"type": "string",
"title": "Look",
"description": "bbs is the neon BBS look: an ASCII-art banner, ▓▒░ section headers and a cyberpunk palette. plain uses your terminal theme colours and plain rules (better on light backgrounds).",
"description": "bbs is the neon BBS look: an ASCII-art banner, ▓▒░ section headers and a cyberpunk palette. plain uses your terminal theme colours and plain rules (better on light backgrounds). orbital uses black telemetry panels, square red borders, muted values and green health indicators; best with a dark terminal.",
"default": "bbs",
"options": [
"bbs",
"plain"
"plain",
"orbital"
]
},
"boot": {
"type": "boolean",
"title": "Boot screen",
"description": "With the bbs look, play a dial-up boot screen (modem connect, the RUFLO logo drawing in, every area of the console coming online in a log, a loading bar for the first ruflo reads) when the cockpit opens. At least 5.4 s, at most 8 s.",
"description": "With the bbs look, play a dial-up boot screen (modem connect, the RUFLO logo drawing in, every area of the console coming online in a log, a loading bar for the first ruflo reads) when the cockpit opens. At least 5.4 s, at most 8 s. Orbital uses a rotating ASCII globe for 1.5 seconds, up to 6 seconds while initial data is pending; fps 0 skips it.",
"default": true
},
"eventsPersist": {
+5
View File
@@ -2,6 +2,11 @@
Newest first. One `## <version> — <date>` heading per version, then `feat:`, `fix:`, `breaking:` and `chore:` bullets (ADR-478). Built from git history; older versions: `git log -- plugins/ruflo-console`.
## 0.43.0 — 2026-10-12
- feat: an optional Orbital look (black telemetry panels, square borders, a rotating globe, a scan sweep and a shaded Ruflo header that stays visible after boot) and Theme Studio: pick Classic BBS, plain or Orbital, six bundled color presets, up to twelve named custom themes, a color picker with a 3:1 minimum contrast, motion layers and speed, and a generate-console-theme skill whose JSON is imported through a strict, size-bounded schema. Classic BBS stays the default; open it from Main Menu → Tools, Settings or /ruflo themes
- fix: Theme Studio has its own boot-log line and help guide, and is reached by name (every hotkey letter is taken)
- chore: the Orbital globe reads a one-degree land mask built once, not nine polygon tests per cell per frame (about a third less time per frame); `scripts/bench-theme.mjs` measures the per-tick cost of every animated picture; 45 adversarial specs pin the theme import (closed schema, control and bidi characters, prototype keys, size bounds, hostile saved stores)
## 0.42.7 — 2026-10-11
- feat: `ruflo tui` has five pages: Overview, Cost, Swarm, Events and Missions (keys 1 to 5, or o c s e m; Tab and Shift-Tab cycle). A page bar shows where you are, a key line says what the keys are, and the terminal redraws on a resize (a short bar under 60 columns, a one-line notice under 40). Room is left out on purpose: it is a message box and Claude sessions this host does not have (ADR-489)
- fix: on the standalone terminal the shared chrome no longer draws what only Claude Code can do: no tab bar, footer buttons, Launch section, Ask Claude buttons or Claude control card, and buttons that nobody can press are not drawn (a state chip such as `● all 0` and a section title are). Under Claude Code nothing changes: every new branch is behind `state.isStandalone`
+61
View File
@@ -83,3 +83,64 @@ An optional **Project Anatole** section on the Security & Doctor page (key `u`)
- **Shows** the mode, the baseline's maturity ("learning 62%"), open alerts by severity, blocked and `degraded`; one row per rule (OWASP refs, severity, an off · notify · block chip, hits and acked share over the last 200 alerts, "changed from default"); the open alerts with `ack` and `allow`. The Findings meter counts open alerts, labelled as Anatole's.
- **Runs** `/protector run` and `/protector replay` into the page's Result panel.
- **Edits** the mode (off, learn, notify, enforce) and per-rule modes through `/protector`; every change asks first and its confirm row starts with `Effect:`. `enforce` is declared an install-class action and `reset-baseline` a delete-class one, so Claude's console tools always wait for you on both (palette ids `anatole-mode`, `anatole-rule`, `anatole-ack`, `anatole-allow`, `anatole-reset`, `anatole-run`, `anatole-replay`).
## Orbital theme
An optional dark telemetry look inspired by compact system monitors: black panel background, square red borders, warm red headings, muted readable values and green health indicators. It uses the existing live views and command palette; no extra polling, simulated metrics or model calls. BBS remains the default.
Choose Settings → ruflo-console → Look → orbital, or run in your shell:
```sh
printf '%s\n' '{"look":"orbital"}' | claude plugin configure ruflo-console@ruflo --values-stdin
```
Reload plugins after changing the option. Select `bbs` or `plain` to restore those looks. A dark terminal background gives the closest match; terminal graphics and host controls keep their existing renderer. Narrow panes retain the existing responsive layout.
Orbital keeps the original Ruflo block mark visible after boot on every page, above navigation. Wide headers use an eight-row composition with a shaded block extrusion, moving highlight, rotating ASCII Earth and travelling scan. Smaller panes retain the original two-row block mark inside a compact header. The optional boot intro uses the same Earth rotation (one turn per 12 seconds), with actual self-check counts below it. It runs for 1.5 seconds when data is ready, at most 6 seconds while data is pending. Set `fps` to `0` for still headers and no boot intro. Existing frame scheduling stops motion in hidden or unfocused panes. The sweep and globe are decoration, not measured activity or a progress percentage.
Orbital adapts to the pane allocation. Below 48 drawing columns or 30 available rows, boot uses a compact check summary of at most nine rows. Failure totals remain near the top, with the first failing area shown when a third row fits. The persistent header uses its expanded layout from 78 drawing columns with eight available header rows. Short panes keep two rows; the native host's text-only mode below 44 pane columns retains a text Ruflo identity. Header width reserves the existing toolbar icon space and is capped at 120 columns. Resize dimensions are recorded before the header is mounted so the animation loop continues at the new size. The existing live topology remains in the Swarm page body; Theme Studio provides the decorative orchestration preview.
### Theme Studio
Open **Main Menu → Tools → Theme Studio**, the **Tools** navigation group, or `/ruflo themes`. Settings also links to the studio. Choose Classic BBS, Terminal plain or Orbital. Studio selections persist and override the plugin's configured look until **Use configured look** is selected.
Six bundled **Color presets** load with one click and persist across sessions. They retain the animated Ruflo header, globe, stars and topology at standard speed. Bundled presets do not consume the twelve custom theme slots. Every primary foreground role meets at least 4.5:1 contrast against its background; decorative shading may be dimmer.
| Preset | Palette |
| --- | --- |
| Arctic | Ice cyan, seafoam and deep navy |
| Synthwave | Orchid, mint and dark violet |
| Amber CRT | Warm amber, parchment and dark bronze |
| Emerald | Jade, pale green and forest black |
| Solar Flare | Peach, gold and dark terracotta |
| Moonlight | Periwinkle, silver and midnight blue |
Select a preset to load it immediately. Edit colors or motion and choose **Save and apply** to create a custom copy; bundled originals remain available. Portable version 1 JSON presets also load through **AI → Import theme JSON**, followed by **Save and apply**. **Use configured look** restores the plugin setting.
### Reproduce the theme workflow demo
The demo drives actual console view handlers through boot, Main Menu, all six presets, custom color and motion, save, fresh state restoration from a local JSON store, portable JSON import, reduced motion, and 80/116 column layouts. It checks each transition and writes `receipt.json`. This is a renderer integration demo, not a native Claude host recording: other console actions are not exercised, the FPS setting is changed by the harness, and no AI provider is invoked.
From the repository root, with Node:
```sh
npx tsx plugins/ruflo-console/scripts/theme-demo.mts /tmp/ruflo-demo-new
```
Use a fresh output directory. The capture refuses to overwrite an existing `demo-session.json`; omitting the directory creates a unique temporary directory and prints its path. Outputs are `frames.json` (the captured terminal cells for every step, with a caption, palette and column count) and `receipt.json` (what was and was not exercised: no native host, no AI provider). Turning the frames into a GIF or video is left to your own renderer; the repository ships none, so no Python or image library is needed.
For a genuine animated vector export of those same captured frames, run (Node only):
```sh
node plugins/ruflo-console/scripts/render-theme-svg.mjs /tmp/ruflo-demo-new
```
`ruflo-console-demo.svg` contains text runs, block rectangles and reusable row symbols (the font is your system monospace), replayed with native SVG discrete animation over the same 38 seconds. It has no embedded images, video, scripts or other external assets. The complete 456-frame replay is approximately 20 MB. It scales through its viewBox; open the file in an SVG animation capable browser when a document preview shows only a still frame.
The terminal color picker provides swatches and exact `#RRGGBB` entry for headings, success, failure, warning, information and background. Preview the globe and swarm motion, adjust speed and decorative layers, then **Save preview and apply**. Up to twelve named custom presets are stored locally through the host; reusing a name replaces that preset. Failed saves leave the active theme unchanged. Settings `fps: 0` still disables animation. Layouts retain the compact/narrow fallbacks.
**Generate with Claude** or **Generate with Codex** runs the bundled `generate-console-theme` skill through AI Terminal with its existing confirmation and model controls. Enter the design brief first, generate a preset, then paste the returned JSON into **Import theme JSON** and review before saving. The generator produces palette and motion variations of the existing Orbital renderer, not executable animation code. No additional API credentials are requested. Installed Claude plugins discover the bundled skill; Codex can read `plugins/ruflo-console/skills/generate-console-theme/SKILL.md` directly in this checkout.
Imports are limited to 4096 characters and a strict version 1 data schema. Status labels and actual check results remain unchanged. Saving requires at least 3:1 foreground/background contrast; the generator aims for 4.5:1.
Theme Studio uses focused Colors, Motion and AI tabs. At 100 content columns it places the editor beside a persistent globe and routing preview; narrower panes stack both panels with a compact routing strip. A single color role picker replaces the repeated swatch lists. Minimum contrast is shown before saving, and Discard draft changes restores the active palette without deleting saved themes.
@@ -52,6 +52,7 @@ export const VIEW_ASK: Record<ViewId, ViewAsk> = {
market: { default: 'Which of these plugins would help most for what I am doing?' },
adrs: { default: 'Which of my project’s ADRs matter for what I am working on, and does anything I have changed cut across an accepted decision?' },
whatsnew: { default: 'Which of these plugin changes matter for how I work, and does any breaking change need action from me?' },
themes: { default: 'Help me design a readable animated console theme with Theme Studio.' },
settings: { default: 'Which of these settings should I change for how I work?' },
agent: { default: 'What is this agent doing, and is anything wrong with it?' },
}
+2
View File
@@ -21,6 +21,7 @@ import { workflowsActions } from './wf-actions'
import { missionActions } from './mission-control'
import { catalogActions } from './plugin-catalog'
import { saveAllowed } from './remember'
import { themeActions } from './themes'
import { pluginNames, settingsActions } from './settings'
import { catalogOf } from './plugin-catalog'
import { wireAnatole } from './anatole'
@@ -408,6 +409,7 @@ export function actionsOf(state: State, host: Host, runner: Runner, steps: Steps
// An rvlite query is MCP-only: it goes to the AI terminal typed, as ▸ edit does, and runs only when sent.
vector: vectorActions(state, runner, text => actions.term.load('claude', text)),
evolve: evolveActions(state, host, text => actions.term.ask('claude', text)),
themes: themeActions(state, host, (agent, text) => actions.term.ask(agent, text)),
settings: settingsActions(state, host, runner, (agent, text) => actions.term.ask(agent, text), () => CLI_PREFIXES[state.options.cli], () => pluginNames(state, (catalogOf(state).plugins ?? []).filter(plugin => plugin.options.length > 0).map(plugin => plugin.name))),
mission: { ...missionActions(state, host, runner), ...claudeActions(state, host, runner) },
ask: askActions(state, host, runner, () => actions),
+3 -6
View File
@@ -20,10 +20,9 @@ import type { Host } from './host'
import { agentLogs } from './ops'
import { landingRefusal } from './model-tools'
import { createRunner, EXPIRY_TIMER, type Runner } from './runner'
import { advance, loadLedger, mcOf } from './mission-control'
import { advance, mcOf } from './mission-control'
import { hasLiveWork } from './mission-list'
import { loadAllowed } from './remember'
import { loadAiPrefs } from './settings'
import { loadSaved } from './startup-loads'
import { openLoaders } from './view-open'
import { listSkills } from './skills'
import { readDrillLogs } from './drill-logs'
@@ -317,9 +316,7 @@ export function createController(state: State, host: Host): Controller {
let lastIdleMs = 0
// The AI terminal's saved model and budget apply from the first turn, not only once Settings was opened.
void loadAiPrefs(state, host)
void loadAllowed(state, host)
void loadLedger(state, host)
loadSaved(state, host)
void host.storeGet(NAV_KEY).then(saved => {
const style = NAV_STYLES.find(candidate => candidate === saved)
+1
View File
@@ -60,6 +60,7 @@ export const BOOT_MODULES: readonly { name: string; note: string }[] = [
{ name: 'AI Terminal', note: 'ruflo, codex, claude' },
{ name: 'ADRs', note: 'decisions your project made' },
{ name: 'What’s new', note: 'changes in your plugins' },
{ name: 'Themes', note: 'look, colors, motion' },
{ name: 'Settings', note: 'every option a button' },
]
const NAME_WIDTH = 15
+401
View File
@@ -0,0 +1,401 @@
/** Orbital cell art: decorative motion, never a simulated health or progress measurement. */
import { ORBITAL_THEME, type ConsoleTheme } from '../themes'
import type { BootCheck } from '../boot-checks'
import { Grid, mix } from './raster'
import { bannerPicture } from './pictures'
const palettes = new WeakMap<ConsoleTheme, ReturnType<typeof paletteOf>>()
/** The theme's colours as numbers, parsed once per theme object (a frame asks for them several times). */
function colors(theme: ConsoleTheme) {
let palette = palettes.get(theme)
if (palette === undefined) palettes.set(theme, palette = paletteOf(theme))
return palette
}
function paletteOf(theme: ConsoleTheme) {
const rgb = (hex: string) => parseInt(hex.slice(1), 16)
return { RED: rgb(theme.palette.head), GREEN: rgb(theme.palette.ok), INK: rgb(theme.palette.info), BLACK: rgb(theme.palette.background), BAD: rgb(theme.palette.bad), DIM: mix(rgb(theme.palette.background), rgb(theme.palette.info), 0.48) }
}
const TAU = Math.PI * 2
/** The planet's fixed tilt and pitch, as the sines and cosines every cell of every frame needs. */
const SPIN = { cosTilt: Math.cos(23.4 * Math.PI / 180), sinTilt: Math.sin(23.4 * Math.PI / 180), cosPitch: Math.cos(0.18), sinPitch: Math.sin(0.18) }
function tint(color: number, brightness: number): number {
const channel = (shift: number) => Math.round(((color >>> shift) & 255) * brightness)
return (channel(16) << 16) | (channel(8) << 8) | channel(0)
}
// Original stylized continent silhouettes in longitude/latitude degrees, for decoration only.
const LAND = [
[[-168,65],[-150,71],[-135,69],[-128,58],[-123,49],[-124,41],[-117,32],[-108,24],[-97,16],[-86,10],[-83,15],[-90,21],[-97,26],[-81,25],[-81,32],[-70,44],[-58,49],[-65,60],[-95,72],[-130,73]],
[[-81,12],[-70,11],[-61,6],[-51,3],[-35,-6],[-39,-19],[-49,-28],[-56,-37],[-68,-56],[-74,-49],[-73,-30],[-80,-5]],
[[-17,35],[-4,36],[10,37],[24,32],[33,30],[43,12],[51,11],[42,0],[35,-12],[32,-27],[18,-35],[12,-20],[9,-3],[-1,5],[-15,11],[-18,22]],
[[-10,36],[-9,44],[1,49],[9,54],[5,59],[20,71],[33,69],[29,58],[44,48],[36,42],[26,39],[21,36],[12,46],[3,43]],
[[29,58],[45,72],[95,77],[140,71],[179,66],[160,55],[143,49],[135,35],[121,30],[109,19],[104,1],[98,7],[91,22],[80,8],[73,20],[64,25],[51,12],[43,14],[35,30],[44,48]],
[[112,-12],[130,-11],[137,-16],[143,-11],[153,-25],[151,-37],[139,-39],[129,-32],[115,-35],[113,-24]],
[[-53,59],[-42,61],[-22,76],[-30,83],[-52,84],[-66,70]],
[[46,-13],[50,-17],[47,-25],[44,-22]],
[[130,31],[136,35],[142,43],[145,44],[141,35]],
[[166,-34],[179,-39],[172,-47],[166,-45]],
] as const
function inPolygons(lon: number, lat: number): boolean {
return LAND.some(poly => {
let inside = false
for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) {
const a = poly[i]!
const b = poly[j]!
if ((a[1] > lat) !== (b[1] > lat) && lon < (b[0] - a[0]) * (lat - a[1]) / (b[1] - a[1]) + a[0]) inside = !inside
}
return inside
})
}
/** One cell per degree, built on the first globe and read for every cell of every later frame (the polygons are tested once, not per cell per tick). */
const MASK_COLUMNS = 360
let landMask: Uint8Array | undefined
function onLand(lon: number, lat: number): boolean {
if (landMask === undefined) {
landMask = new Uint8Array(MASK_COLUMNS * 180)
for (let y = 0; y < 180; y++) for (let x = 0; x < MASK_COLUMNS; x++) landMask[y * MASK_COLUMNS + x] = inPolygons(x - 179.5, y - 89.5) ? 1 : 0
}
const x = Math.min(MASK_COLUMNS - 1, Math.max(0, Math.round(lon + 179.5)))
const y = Math.min(179, Math.max(0, Math.round(lat + 89.5)))
return landMask[y * MASK_COLUMNS + x] === 1
}
function blank(columns: number, rows: number, theme = ORBITAL_THEME): Grid {
const { INK, BLACK } = colors(theme)
const grid = new Grid(Math.max(1, Math.min(200, Math.floor(columns) || 1)), rows)
for (let y = 0; y < rows; y++) for (let x = 0; x < grid.columns; x++) grid.set(x, y, ' ', INK, BLACK)
return grid
}
/** Tilted orthographic Earth with fixed sunlight and a sparse starfield. One turn takes 12 seconds. */
export function orbitalGlobe(columns: number, rows: number, timeMs: number, theme = ORBITAL_THEME): Grid {
const { RED, GREEN, INK, BLACK } = colors(theme)
const height = Math.max(5, Math.min(24, Math.floor(rows) || 5))
const grid = blank(columns, height, theme)
const radius = Math.max(0.25, Math.min((height - 1) / 2, (grid.columns - 1) / 4))
const angle = (Number.isFinite(timeMs) ? timeMs % 12000 : 0) / 12000 * TAU
const { cosTilt, sinTilt, cosPitch, sinPitch } = SPIN
for (let y = 0; y < height; y++) for (let x = 0; x < grid.columns; x++) {
const nx = (x - (grid.columns - 1) / 2) / (radius * 2)
const ny = ((height - 1) / 2 - y) / radius
const r2 = nx * nx + ny * ny
if (r2 > 1) {
// Thin orbital arc behind the planet; the solid sphere occludes the middle.
const ringX = nx * 0.966 + ny * 0.259
const ringY = -nx * 0.259 + ny * 0.966
const ring = ringX * ringX / 3.24 + ringY * ringY / 0.16
if (Math.abs(ring - 1) < 0.09) grid.set(x, y, '.', mix(BLACK, RED, 0.32), BLACK)
// Stable positions, slow brightness changes, and clear space around the limb.
const seed = ((x + 17) * 73856093 ^ (y + 11) * 19349663) >>> 0
if (theme.motion.stars && r2 > 1.2 && seed % 113 === 0) {
const glow = 0.45 + 0.3 * (1 + Math.sin(angle + seed % 31)) / 2
grid.set(x, y, seed % 3 === 0 ? '+' : '.', tint(INK, glow), BLACK)
}
continue
}
const z = Math.sqrt(1 - r2)
// Transform the visible surface into the tilted planet's coordinates before spinning its longitude.
const ax = nx * cosTilt + ny * sinTilt
const ay = -nx * sinTilt + ny * cosTilt
const py = ay * cosPitch + z * sinPitch
const pz = z * cosPitch - ay * sinPitch
const lat = Math.asin(Math.max(-1, Math.min(1, py))) * 180 / Math.PI
const lon = ((Math.atan2(ax, pz) + angle) * 180 / Math.PI + 540) % 360 - 180
const land = onLand(lon, lat)
const sun = Math.max(0, -0.58 * nx + 0.4 * ny + 0.71 * z)
const brightness = 0.28 + 0.72 * sun
const meridian = Math.abs(lon / 30 - Math.round(lon / 30)) < 0.055
const parallel = Math.abs(lat / 30 - Math.round(lat / 30)) < 0.055
const glyph = land ? (sun > 0.65 ? '#' : sun > 0.3 ? '+' : ':') : meridian || parallel ? ':' : '.'
// A coral limb and dim night side keep the sphere readable without filling it solid.
const sweepAngle = (Math.atan2(ny, nx) - angle * 2 + TAU * 3) % TAU
const scanGlow = Math.max(0, 1 - sweepAngle / 0.45) * 0.24
const base = scanGlow > 0.1 ? GREEN : z < 0.28 ? RED : land ? INK : GREEN
const light = land || z < 0.28 ? Math.max(z < 0.28 ? 0.58 : 0, brightness) : brightness * 0.48
grid.set(x, y, glyph, tint(base, Math.min(1, light + scanGlow)), BLACK)
}
// A single marker with a short fading trail follows the orbit, passing behind the planet.
for (let trail = 5; trail >= 0; trail--) {
const phase = angle - trail * 0.07
const rx = 1.8 * Math.cos(phase)
const ry = 0.4 * Math.sin(phase)
const sx = rx * 0.966 - ry * 0.259
const sy = rx * 0.259 + ry * 0.966
if (sx * sx + sy * sy < 1 && Math.sin(phase) < 0) continue
const x = Math.round((grid.columns - 1) / 2 + sx * radius * 2)
const y = Math.round((height - 1) / 2 - sy * radius)
grid.set(x, y, trail === 0 ? '+' : '.', tint(trail === 0 ? INK : RED, 1 - trail * 0.14), BLACK)
}
return grid
}
/** Fixed-height header: red scan line, travelling ASCII pulse and an orbit marker. */
export function orbitalHeader(label: string, columns: number, timeMs: number, maxRows = 16, theme = ORBITAL_THEME): Grid {
const { RED, GREEN, INK, BLACK, DIM } = colors(theme)
const swarm = /swarm/i.test(label)
const expanded = theme.motion.topology && swarm && columns >= 56 && maxRows >= 16
const grid = blank(columns, expanded ? 16 : Math.max(1, Math.min(4, maxRows)), theme)
const tick = Math.floor((Number.isFinite(timeMs) ? timeMs : 0) / 160)
const fullTitle = ` RUFLO / ${label.toUpperCase()} `
const title = columns >= fullTitle.length ? fullTitle : columns >= 12 ? ` RUFLO / ${swarm ? 'SWARM' : label.toUpperCase()}` : ' RUFLO'
grid.text(0, 0, title.slice(0, grid.columns), RED)
grid.text(0, 1, '-'.repeat(grid.columns), DIM)
for (let tail = 4; tail >= 0; tail--) {
const x = (((tick - tail) % grid.columns) + grid.columns) % grid.columns
grid.set(x, 1, tail === 0 ? '>' : '=', tail === 0 ? INK : tail < 3 ? RED : DIM)
}
for (let x = 0; x < grid.columns - 12; x++) {
const phase = ((x - tick) % 19 + 19) % 19
grid.set(x, 2, phase === 9 ? '|' : phase === 8 || phase === 10 ? '/' : phase === 7 || phase === 11 ? '.' : '_', phase >= 7 && phase <= 11 ? GREEN : DIM)
}
grid.text(Math.max(0, grid.columns - 10), 2, `[${'|/-\\'[Math.abs(tick) % 4]}] ORBIT`, RED)
if (expanded) {
// A decorative routing motif, separate from the page's measured swarm topology.
for (let y = 1; y < grid.rows; y++) grid.text(0, y, ' '.repeat(grid.columns), DIM)
const center = { x: Math.floor(grid.columns / 2), y: 5 }
const ms = Number.isFinite(timeMs) ? timeMs : 0
const phase = ms / 12000 * TAU
const icons = ['◇', '□', '△', '◎', '◇', '□', '△', '◎']
const nodes = icons.map((icon, index) => {
const angle = phase + index * TAU / icons.length
const z = Math.sin(angle)
const perspective = 2.8 / (2.8 - z * 0.5)
return { icon, index, z, x: Math.round(center.x + Math.cos(angle) * grid.columns * 0.32 * perspective), y: Math.round(center.y + (Math.sin(angle) * 2.3 + Math.cos(angle) * 0.7) * perspective) }
}).sort((a, b) => a.z - b.z)
const beat = ((ms % 4800) + 4800) % 4800
const stage = Math.floor(beat / 1200)
// Sparse graph mesh and moving edge packets, all illustrative rather than reported traffic.
for (let y = 1; y <= 9; y += 2) for (let x = 3; x < grid.columns - 3; x += 6) grid.set(x, y, '·', mix(BLACK, GREEN, 0.14))
nodes.forEach(node => {
const next = nodes.find(other => other.index === (node.index + 1) % nodes.length)!
const dx = next.x - node.x
const dy = next.y - node.y
const steps = Math.max(1, Math.abs(dx), Math.abs(dy))
const packet = ((ms / 1100 + node.index * 0.19) % 1 + 1) % 1
for (let step = 1; step < steps; step++) {
const f = step / steps
const lit = Math.abs(packet - f) < 0.045
grid.set(Math.round(node.x + dx * f), Math.round(node.y + dy * f), lit ? '•' : '·', lit ? INK : mix(BLACK, GREEN, 0.28))
}
})
// Projected direction vectors extend from the hub, rotating independently of the graph.
for (let axis = 0; axis < 3; axis++) {
const angle = phase * 1.5 + axis * TAU / 3
for (let step = 2; step <= 8; step++) {
const x = center.x + Math.round(Math.cos(angle) * step * Math.min(1.7, grid.columns / 36))
const y = center.y + Math.round(Math.sin(angle) * step * 0.36)
grid.set(x, y, step === 8 ? (Math.cos(angle) < 0 ? '◀' : '▶') : '·', step === 8 ? RED : mix(BLACK, RED, 0.40))
}
}
const drawHub = () => {
grid.text(center.x - 2, center.y + 1, ' ░░░ ', mix(BLACK, RED, 0.25))
grid.text(center.x - 2, center.y, '[ ◈ ]', stage === 2 ? GREEN : INK)
}
let hubDrawn = false
nodes.forEach(node => {
if (!hubDrawn && node.z >= 0) { drawHub(); hubDrawn = true }
const dx = node.x - center.x
const dy = node.y - center.y
const steps = Math.max(Math.abs(dx), Math.abs(dy))
const outbound = ((ms / 1300 + node.index / icons.length) % 1 + 1) % 1
const pulse = stage >= 2 ? 1 - outbound : outbound
for (let step = 3; step < steps; step++) {
const f = step / steps
const x = Math.round(center.x + dx * f)
const y = Math.round(center.y + dy * f)
const lit = pulse - f >= 0 && pulse - f < 0.14
grid.set(x, y, lit ? '•' : '·', lit ? GREEN : node.z < 0 ? mix(BLACK, GREEN, 0.23) : mix(BLACK, GREEN, 0.48))
}
if (node.z > 0) {
grid.text(node.x, node.y + 1, '░░', mix(BLACK, RED, 0.25))
grid.text(node.x - 1, node.y, `[${node.icon}]`, pulse > 0.8 ? INK : RED)
} else grid.set(node.x, node.y, node.icon, DIM)
})
if (!hubDrawn) drawHub()
grid.text(1, 10, ' ◈ HUB ◇ WORKER □ TOOL △ TASK ◎ MEMORY', DIM)
const stages = ['DISPATCH', 'PARALLEL', 'SYNC', 'RETURN']
const lane = Math.max(1, Math.floor((grid.columns - 2) / 4))
stages.forEach((label, index) => {
const x = 1 + index * lane
grid.text(x, 12, `${index === stage ? '▶' : '·'} ${label}`.slice(0, lane), index === stage ? INK : DIM)
const cells = Math.max(1, lane - 2)
for (let i = 0; i < cells; i++) {
const lit = index === stage && i === Math.floor((beat % 1200) / 1200 * cells)
grid.set(x + i, 13, lit ? '▪' : '·', lit ? GREEN : mix(BLACK, GREEN, 0.28))
}
})
grid.text(1, 15, /preview/i.test(label) ? ' Illustrative routing / palette preview' : ' Illustrative orchestration / live graph below', DIM)
} else if (swarm) {
const stages = ['DISPATCH', 'PARALLEL', 'SYNC', 'RETURN']
const stage = Math.floor(Math.max(0, Number.isFinite(timeMs) ? timeMs : 0) / 1200) % 4
grid.text(0, 3, ` ${stages[stage]} / motif`, DIM)
} else if (grid.columns >= 30) grid.text(0, 3, ' ruvnet / agent swarm console', DIM)
return grid
}
/** Map the original banner's neon channels into Orbital's palette, preserving its highlight sweep. */
function orbitalBrandColor(color: number, theme = ORBITAL_THEME): number {
const r = (color >>> 16) & 255
const g = (color >>> 8) & 255
// Original magenta and cyan are mixed with white by the shared banner renderer.
const cyan = Math.max(0, Math.min(1, (255 - r) / 250))
const white = Math.max(0, Math.min(1 - cyan, (g - 42 - 175 * cyan) / 213))
const coral = 1 - cyan - white
const channel = (a: number, z: number, light: number) => Math.round(a * coral + z * cyan + light * white)
const { RED, GREEN, INK } = colors(theme)
const ch = (shift: number) => channel((RED >>> shift) & 255, (GREEN >>> shift) & 255, (INK >>> shift) & 255)
return (ch(16) << 16) | (ch(8) << 8) | ch(0)
}
/** Persistent console identity, using the original half-block logo and its entry/sweep animation. */
export function orbitalMasthead(label: string, columns: number, timeMs: number, maxRows = 8, theme = ORBITAL_THEME, age = Infinity): Grid {
const { RED, GREEN, INK, BLACK, DIM } = colors(theme)
const wide = columns >= 78 && maxRows >= 8
const grid = blank(columns, Math.max(1, Math.min(wide ? 8 : 4, maxRows)), theme)
const ms = Number.isFinite(timeMs) ? Math.max(0, timeMs) : 0
const logo = bannerPicture('', 19, ms, age)
if (wide) {
// Scale the original four pixel rows to eight, keeping terminal half-block resolution.
// A fixed extrusion sits behind the face; only the highlight moves, so the mark stays legible.
const face: { x: number; y: number; glyph: number; color: number }[] = []
for (let y = 0; y < logo.rows; y++) for (let x = 0; x < logo.columns; x++) {
const i = (y * logo.columns + x) * 3
const ch = String.fromCodePoint(logo.cells[i]!)
if (ch === ' ') continue
const color = orbitalBrandColor(logo.cells[i + 1]!, theme)
const halves = ch === '▀' ? [true, false] : ch === '▄' ? [false, true] : [true, true]
for (let half = 0; half < 2; half++) if (halves[half]) for (let dx = 0; dx < 2; dx++) face.push({ x: x * 2 + dx, y: 1 + y * 2 + half, glyph: 0x2588, color })
}
for (const cell of face) grid.set(cell.x + 2, cell.y + 1, '▓', mix(BLACK, RED, 0.33), BLACK)
for (const cell of face) grid.set(cell.x, cell.y, cell.glyph, cell.color, BLACK)
grid.text(0, 0, 'RUFLO / AGENT SWARM CONSOLE', DIM)
grid.text(0, 6, label.toUpperCase().slice(0, 40), INK)
if (theme.motion.globe) {
const globe = orbitalGlobe(Math.min(40, grid.columns - 43), 7, ms, theme)
const left = grid.columns - globe.columns
for (let y = 0; y < globe.rows; y++) for (let x = 0; x < globe.columns; x++) {
const i = (y * globe.columns + x) * 3
grid.set(left + x, y, globe.cells[i]!, globe.cells[i + 1]!, BLACK)
}
}
} else if (grid.columns >= 19 && grid.rows >= 2) {
for (let y = 0; y < logo.rows; y++) for (let x = 0; x < logo.columns; x++) {
const i = (y * logo.columns + x) * 3
grid.set(x, y, logo.cells[i]!, orbitalBrandColor(logo.cells[i + 1]!, theme), BLACK)
}
if (grid.columns >= 34) grid.text(22, 0, label.toUpperCase().slice(0, grid.columns - 22), INK)
if (grid.rows >= 3) grid.text(0, 2, `RUFLO / ${label.toUpperCase()}`.slice(0, grid.columns), DIM)
} else grid.text(0, 0, 'RUFLO'.slice(0, grid.columns), RED)
// This raster is mounted and blitted by the shared frame loop on every page.
if (grid.rows >= 4) {
const y = grid.rows - 1
const tick = Math.floor(ms / 80)
for (let x = 0; x < grid.columns; x++) grid.set(x, y, '·', mix(BLACK, GREEN, 0.3), BLACK)
for (let tail = 0; tail < 7; tail++) {
const x = ((tick - tail) % grid.columns + grid.columns) % grid.columns
grid.set(x, y, tail === 0 ? '▸' : '▪', tail === 0 ? INK : mix(BLACK, GREEN, 1 - tail / 8), BLACK)
}
}
return grid
}
/** Checks are actual self-check results; the globe and sweep are explicitly decorative. */
export function orbitalBoot(project: string, columns: number, timeMs: number, checks?: readonly BootCheck[], maxRows = 30, theme = ORBITAL_THEME): Grid {
const { RED, GREEN, INK, BLACK, DIM, BAD } = colors(theme)
const available = Math.max(1, Math.min(30, Math.floor(maxRows) || 1))
if (columns < 48 || available < 30) {
const grid = blank(columns, Math.min(9, available), theme)
const failed = checks?.filter(check => !check.ok) ?? []
const passed = checks?.filter(check => check.ok).length ?? 0
grid.text(0, 0, 'RUFLO / BOOT', RED)
grid.text(0, 1, checks === undefined ? 'Pending checks' : `${passed} OK ${failed.length} FAIL`, failed.length ? BAD : GREEN)
// Reserve the first detail row for a real failure even in very short panes.
if (grid.rows > 2) grid.text(0, 2, failed.length ? `FAIL ${failed[0]!.area}` : project, failed.length ? BAD : DIM)
if (grid.rows > 3) {
const tick = Math.floor(Math.max(0, Number.isFinite(timeMs) ? timeMs : 0) / 100)
grid.text(0, 3, '.'.repeat(grid.columns), DIM)
grid.set(tick % grid.columns, 3, '>', GREEN)
}
const shown = [...failed, ...(checks?.filter(check => check.ok) ?? [])]
shown.slice(0, Math.max(0, grid.rows - 5)).forEach((check, i) => grid.text(0, 4 + i, `${check.ok ? 'OK' : 'FAIL'} ${check.area}`, check.ok ? GREEN : BAD))
if (grid.rows >= 6) grid.text(0, grid.rows - 1, 'Local checks', DIM)
return grid
}
const grid = blank(columns, 30, theme)
// Reuse the original console banner, including its half-block font and sweep, recolored for Orbital.
const banner = bannerPicture(project, grid.columns, timeMs, Math.max(0, Number.isFinite(timeMs) ? timeMs : 0))
for (let y = 0; y < banner.rows; y++) for (let x = 0; x < banner.columns; x++) {
const i = (y * banner.columns + x) * 3
grid.set(x, y, banner.cells[i]!, orbitalBrandColor(banner.cells[i + 1]!, theme), BLACK)
}
grid.text(0, 3, ` ruvnet / ${theme.name.toUpperCase()}`, DIM)
const globe = theme.motion.globe ? orbitalGlobe(grid.columns, 16, timeMs, theme) : blank(grid.columns, 16, theme)
const intro = Math.max(0, Number.isFinite(timeMs) ? timeMs : 0)
const reveal = Math.min(1, Math.max(0, (intro - 150) / 750))
const eased = 1 - Math.pow(1 - reveal, 3)
const halfWidth = Math.ceil(grid.columns * eased / 2)
const left = Math.floor((grid.columns - globe.columns) / 2)
for (let y = 0; y < globe.rows; y++) for (let x = 0; x < globe.columns; x++) {
if (Math.abs(x - (grid.columns - 1) / 2) > halfWidth) continue
const i = (y * globe.columns + x) * 3
grid.set(left + x, y + 4, globe.cells[i]!, globe.cells[i + 1]!, BLACK)
}
// Acquisition brackets settle inward as the globe resolves; they do not represent data readiness.
const inset = Math.round(2 + 5 * eased)
for (const y of [5, 18]) {
grid.text(inset, y, '+--', RED)
grid.text(Math.max(inset + 3, grid.columns - inset - 3), y, '--+', RED)
}
const loaderWidth = Math.max(1, grid.columns - 4)
const loader = Math.floor((Math.sin(intro / 450) + 1) / 2 * (loaderWidth - 1))
for (let x = 0; x < loaderWidth; x++) grid.set(x + 2, 2, Math.abs(x - loader) < 3 ? '=' : '.', Math.abs(x - loader) < 3 ? GREEN : mix(BLACK, GREEN, 0.25))
grid.text(0, 20, ' LOADING CONSOLE / decorative orbit', RED)
const passed = checks?.filter(c => c.ok).length ?? 0
const failed = checks?.filter(c => !c.ok).length ?? 0
grid.text(0, 21, checks === undefined ? ' Self-check: pending' : ` Self-check: ${passed} passed / ${failed} failed`, failed > 0 ? BAD : GREEN)
const age = Math.max(0, Number.isFinite(timeMs) ? timeMs : 0)
const scan = Math.floor(age / 100) % Math.max(1, grid.columns - 2)
grid.text(0, 22, ' '.repeat(grid.columns), DIM)
grid.text(0, 22, ' MODULE INTEGRITY ', RED)
if (scan >= 18) grid.set(scan, 22, '>', GREEN)
if (checks === undefined) {
grid.text(0, 24, ` [${'|/-\\'[Math.floor(age / 120) % 4]}] Waiting for local self-check results`, DIM)
} else if (checks.length === 0) {
grid.text(0, 24, ' [N/A] No module checks reported', DIM)
} else {
// Keep failures visible first. Cycle successful areas without fabricating execution progress.
const errors = checks.filter(check => !check.ok)
const successes = checks.filter(check => check.ok)
const slots = Math.max(0, 4 - Math.min(4, errors.length))
const page = Math.floor(age / 2200)
const shown = [...errors.slice(0, 4), ...Array.from({ length: Math.min(slots, successes.length) }, (_, i) => successes[(page * slots + i) % successes.length]!)]
shown.forEach((check, i) => {
const reveal = Math.max(0, Math.floor(((age % 2200) - i * 80) / 25))
const name = check.ok ? check.area.toUpperCase().slice(0, reveal) : check.area.toUpperCase()
const status = check.ok ? '[PASS]' : '[FAIL]'
const detail = !check.ok && check.problems.length > 0 ? ` / ${check.problems[0]}` : ''
grid.text(0, 23 + i, ` ${status} ${name}${detail}`.slice(0, check.ok && grid.columns >= 55 ? grid.columns - 14 : grid.columns), check.ok ? GREEN : BAD)
const cursor = 8 + name.length
if (check.ok && reveal < check.area.length && cursor < (grid.columns >= 55 ? grid.columns - 14 : grid.columns)) grid.set(cursor, 23 + i, '_', INK)
if (grid.columns >= 55 && check.ok) {
const phase = ((age % 2200) - i * 80) / 350
const light = phase >= 0 && phase < 1 ? INK : DIM
grid.text(grid.columns - 12, 23 + i, ':: VERIFIED', light)
}
})
grid.text(0, 27, ` ${checks.length} areas / ${errors.length} failures / local registry checks`, DIM)
}
grid.text(0, 29, ' Motion: Settings > fps | Boot: optional', DIM)
return grid
}
+29 -12
View File
@@ -4,6 +4,7 @@
* always fits the mounted Raster. What motion means is said beside each picture: data where it is data, decoration
* where it is not.
*/
import type { ConsoleTheme } from '../themes'
import { Braille, COLOR, Grid, mix, ramp, sparkline } from './raster'
import { bigText } from './font'
import { hash } from './boot-cyber'
@@ -21,12 +22,12 @@ export const FLIGHT_MS = 1400
const isBusy = (status: string) => /busy|active|running|working/i.test(status)
const isDown = (status: string) => /stop|terminat|offline|dead|error|fail/i.test(status)
export function nodeColor(node: TopoNode): number {
if (node.isLeader) return COLOR.accent
if (isDown(node.status)) return /error|fail/i.test(node.status) ? COLOR.bad : COLOR.dim
if (isBusy(node.status)) return COLOR.warn
export function nodeColor(node: TopoNode, colors = COLOR): number {
if (node.isLeader) return colors.accent
if (isDown(node.status)) return /error|fail/i.test(node.status) ? colors.bad : colors.dim
if (isBusy(node.status)) return colors.warn
return COLOR.info
return colors.info
}
/**
@@ -95,10 +96,24 @@ export function edges(model: TopoModel): [number, number][] {
* A dot runs from the leader to a node once each time the console sees an event about that agent (data); the leader's
* slow heartbeat is decoration.
*/
export function topologyPicture(model: TopoModel, columns: number, rows: number, t: number): Grid {
export function topologyPicture(model: TopoModel, columns: number, rows: number, t: number, depth = false, motionTime = t, palette?: ConsoleTheme['palette']): Grid {
const rgb = (hex: string) => parseInt(hex.slice(1), 16)
const colors = palette ? { ...COLOR, accent: rgb(palette.head), info: rgb(palette.info), ok: rgb(palette.ok), bad: rgb(palette.bad), warn: rgb(palette.warn), dim: mix(rgb(palette.background), rgb(palette.info), 0.45), line: mix(rgb(palette.background), rgb(palette.info), 0.3) } : COLOR
const grid = new Grid(columns, rows)
const canvas = new Braille(columns, rows)
const points = layout(model, canvas.width, canvas.height)
// Gentle perspective rocking preserves the model's real edges and labels.
if (depth) {
const yaw = Math.sin(motionTime / 2400) * 0.42
for (const point of points) {
const nx = (point.x - canvas.width / 2) / (canvas.width / 2)
const ny = (point.y - canvas.height / 2) / (canvas.height / 2)
const z = nx * Math.sin(yaw) + ny * 0.18
const scale = 2.5 / (2.5 - z)
point.x = canvas.width / 2 + nx * Math.cos(yaw) * scale * canvas.width * 0.4
point.y = canvas.height / 2 + ny * scale * canvas.height * 0.4
}
}
const links = edges(model)
const leader = points[0]
@@ -106,7 +121,7 @@ export function topologyPicture(model: TopoModel, columns: number, rows: number,
const p = points[a]
const q = points[b]
if (p !== undefined && q !== undefined) canvas.line(p.x, p.y, q.x, q.y, COLOR.line)
if (p !== undefined && q !== undefined) canvas.line(p.x, p.y, q.x, q.y, colors.line)
}
// Work in flight: while ruflo has an agent busy, a dim amber dot keeps travelling down its edge from the leader.
@@ -120,8 +135,8 @@ export function topologyPicture(model: TopoModel, columns: number, rows: number,
const x = leader.x + (q.x - leader.x) * k
const y = leader.y + (q.y - leader.y) * k
canvas.dot(x, y, COLOR.warn)
canvas.dot(x + 1, y, COLOR.warn)
canvas.dot(x, y, colors.warn)
canvas.dot(x + 1, y, colors.warn)
})
model.nodes.forEach((node, i) => {
@@ -153,17 +168,19 @@ export function topologyPicture(model: TopoModel, columns: number, rows: number,
const flash = node.pulseAtMs !== undefined && t - node.pulseAtMs >= 0 && t - node.pulseAtMs < PULSE_MS + 600
// A busy agent breathes (brighter and back, about once every 2 s) so it reads as working, not just coloured.
const breath = !node.isLeader && isBusy(node.status) ? 0.45 * Math.sin(t / 330 + i) ** 2 : 0
const color = flash ? 0xffffff : node.isLeader ? mix(COLOR.accent, 0xffffff, heartbeat) : mix(nodeColor(node), 0xffffff, breath)
const color = flash ? 0xffffff : node.isLeader ? mix(colors.accent, 0xffffff, heartbeat) : mix(nodeColor(node, colors), 0xffffff, breath)
grid.set(cx, cy, node.isLeader ? '★' : isBusy(node.status) ? '◉' : '●', color)
if (depth) grid.set(cx + 1, cy + 1, '░', 0x49332c)
grid.set(cx, cy, depth ? (node.isLeader ? '◈' : isDown(node.status) ? '×' : isBusy(node.status) ? '◉' : '◇') : node.isLeader ? '★' : isBusy(node.status) ? '◉' : '●', color)
if (room >= 5 || node.isLeader) {
const label = node.label.slice(0, Math.max(3, room - 1))
grid.text(Math.max(0, Math.min(columns - label.length, cx - Math.floor(label.length / 2))), Math.min(rows - 1, cy + 1), label, node.isLeader ? COLOR.accent : nodeColor(node))
grid.text(Math.max(0, Math.min(columns - label.length, cx - Math.floor(label.length / 2))), Math.min(rows - 1, cy + 1), label, node.isLeader ? colors.accent : nodeColor(node, colors))
}
})
if (palette) for (let i = 2; i < grid.cells.length; i += 3) grid.cells[i] = rgb(palette.background)
return grid
}
+1
View File
@@ -69,6 +69,7 @@ export const VIEW_TOPIC: Partial<Record<ViewId, string>> = {
settings: 'settings',
whatsnew: 'whatsnew',
adrs: 'adrs',
themes: 'themes',
timeline: 'watch',
events: 'watch',
room: 'room',
@@ -208,7 +208,7 @@ export const MORE_TOPICS: readonly HelpTopic[] = [
summary: 'change how the console looks and behaves, in place',
steps: [
{ text: 'Open Settings (key s). Each row is edited right there.', go: { view: 'settings' } },
{ text: 'look: bbs is the neon look, plain uses your terminal’s own colours. boot turns the intro on or off.' },
{ text: 'look: bbs is neon, plain uses terminal colours, orbital is dark telemetry with square red panels. boot turns the intro on or off.' },
{ text: 'fps sets how fast things move: 0 turns motion off, 12 is the most.' },
{ text: 'panel decides whether the cockpit opens by itself: auto, only on /ruflo, or never.' },
{ text: 'More options (how often the disk is re-read, the band above the prompt) are listed under the plugin’s options.' },
@@ -260,6 +260,22 @@ export const MORE_TOPICS: readonly HelpTopic[] = [
related: ['updates', 'plugins'],
keywords: ['changelog', 'release', 'notes', 'new', 'breaking', 'version', 'changes'],
},
{
id: 'themes',
title: 'Theme Studio: look, colors and motion',
group: 'Console',
summary: 'pick Classic BBS, plain or Orbital, tune colors and motion, save presets',
steps: [
{ text: 'Open Theme Studio (Main Menu → Tools, the TOOLS group, Settings, or /ruflo themes). 01 LOOK picks Classic BBS (the default), Terminal plain or Orbital, and six bundled color presets.', go: { view: 'themes' } },
{ text: '02 CUSTOMIZE has three tabs. Colors: name the theme, pick a role (head, ok, bad, warn, info, background) and type a hex color such as #72c79b. Motion: stars, globe and topology on or off, and speed 0.25x to 2x.' },
{ text: 'Save and apply needs at least 3:1 contrast between each color and the background. Up to twelve named themes are kept; reuse a name to replace one. If saving fails, the active theme is unchanged.' },
{ text: 'Discard draft changes restores the active palette. Use configured look goes back to the look set in Settings.' },
{ text: 'AI tab: describe a theme, press Generate with Claude or Codex, then paste the returned JSON into Import and Save. The generator returns data only; the import accepts a strict schema up to 4096 characters.' },
{ text: 'Motion follows the fps option. Set fps to 0 for a still frame (reduced motion). Colors use the 256-color palette in tmux.' },
],
related: ['settings', 'terminal'],
keywords: ['theme', 'themes', 'color', 'colors', 'orbital', 'look', 'animation', 'motion', 'palette', 'appearance', 'dark'],
},
{
id: 'headless',
title: 'Commands without the pane',
+1 -1
View File
@@ -12,7 +12,7 @@ export const NAV_GROUPS: readonly { title: string; icon: string; rows: readonly
{ title: 'MIND', icon: '🧠', rows: [['learning', 'neural', 'metaharness', 'evolve', 'memory', 'vector']] },
{ title: 'SAFETY', icon: '🛡️', rows: [['secure', 'cost', 'perf', 'timeline', 'events', 'room']] },
{ title: 'NETWORK', icon: '🌐', rows: [['federation', 'xruv', 'sandbox', 'skills', 'market']] },
{ title: 'TOOLS', icon: '🛠️', rows: [['terminal', 'automate', 'devtools', 'plugins'], ['adrs', 'whatsnew', 'settings']] },
{ title: 'TOOLS', icon: '🛠️', rows: [['terminal', 'automate', 'devtools', 'plugins'], ['adrs', 'whatsnew', 'themes', 'settings']] },
]
export const groupOf = (view: ViewId): string | null => NAV_GROUPS.find(group => group.rows.some(row => row.includes(view)))?.title ?? null
+2 -2
View File
@@ -321,6 +321,8 @@ export const register: Register = (on, raw: PluginOptions) => {
state.pane.isFocused = e.props.isFocused === true
state.pane.columns = columns
state.pane.placement = e.props.placement
// Height-dependent art must use this render's allocation before its Raster size is recorded.
state.pane.rows = Math.max(0, Math.floor(Number(e.props.scroll?.bodyRows) || 0))
// A reload while the pane stayed up: timers are gone, so resume them from here.
if (!state.timers.has('watch')) control.resume()
@@ -329,8 +331,6 @@ export const register: Register = (on, raw: PluginOptions) => {
state.mounted = new Map([...pictures].map(([key, grid]) => [key, { columns: grid.columns, rows: grid.rows }]))
control.animate()
state.pane.rows = Math.max(0, Math.floor(Number(e.props.scroll?.bodyRows) || 0))
const tree = paneView({ kit: withClearing(kit, state, control.actions.clearField, { columns, repaint: () => host?.invalidate() }), state, nowMs: Date.now(), columns, pictures, act: control.actions })
state.stats.renders.push(Date.now() - started)
+2 -2
View File
@@ -22,11 +22,11 @@ export const AREA_VIEW: Record<string, ViewId> = {
Missions: 'missions', Overview: 'overview', Swarm: 'swarm', Workflows: 'workflows', 'Hive-Mind': 'hive', Claims: 'claims', Approvals: 'approvals', Automation: 'automate',
Learning: 'learning', Neural: 'neural', 'Vector Lab': 'vector', 'Memory Lab': 'memory', MetaHarness: 'metaharness', 'Self-Evolution': 'evolve',
Security: 'secure', Federation: 'federation', 'x.ruv.io': 'xruv', 'Plugins & Mods': 'plugins', Skills: 'skills', 'Plugin Catalog': 'market',
'Dev Tools': 'devtools', Sandbox: 'sandbox', 'Cost & Budget': 'cost', Timeline: 'timeline', Events: 'events', 'The Room': 'room', Performance: 'perf', 'AI Terminal': 'terminal', 'What’s new': 'whatsnew', ADRs: 'adrs', Settings: 'settings',
'Dev Tools': 'devtools', Sandbox: 'sandbox', 'Cost & Budget': 'cost', Timeline: 'timeline', Events: 'events', 'The Room': 'room', Performance: 'perf', 'AI Terminal': 'terminal', 'What’s new': 'whatsnew', ADRs: 'adrs', Themes: 'themes', Settings: 'settings',
}
/** Pages with no hotkey on purpose (every letter is taken): reached from the menu, the nav, the palette or by name. */
const NAMED_ONLY: ReadonlySet<string> = new Set(['sandbox', 'room', 'workflows', 'whatsnew', 'adrs'])
const NAMED_ONLY: ReadonlySet<string> = new Set(['sandbox', 'room', 'workflows', 'whatsnew', 'adrs', 'themes'])
export type Registries = { secure: readonly SecEntry[]; secureText: readonly SecText[]; perf: readonly PerfEntry[]; dev: readonly DevEntry[]; lab: readonly LabEntry[] }
export const REGISTRIES: Registries = { secure: SECURE, secureText: SECURE_TEXT, perf: PERF, dev: DEV, lab: LAB }
@@ -0,0 +1,14 @@
/** What the controller reads back from host storage when the pane opens: theme, AI terminal prefs, remembered answers and the mission ledger. */
import type { Host } from './host'
import { loadLedger } from './mission-control'
import { loadAllowed } from './remember'
import { loadAiPrefs } from './settings'
import type { State } from './state'
import { loadThemes } from './themes'
export function loadSaved(state: State, host: Host): void {
void loadThemes(state, host)
void loadAiPrefs(state, host)
void loadAllowed(state, host)
void loadLedger(state, host)
}
+11 -6
View File
@@ -28,7 +28,7 @@ export type NavStyle = 'auto' | 'icons' | 'brief' | 'full'
export const NAV_STYLES: readonly NavStyle[] = ['auto', 'icons', 'brief', 'full']
export const NAV_KEY = 'nav-style'
export type ViewId = 'menu' | 'overview' | 'swarm' | 'workflows' | 'hive' | 'claims' | 'federation' | 'plugins' | 'learning' | 'metaharness' | 'memory' | 'cost' | 'timeline' | 'approvals' | 'events' | 'room' | 'missions' | 'xruv' | 'terminal' | 'skills' | 'agent' | 'secure' | 'perf' | 'automate' | 'neural' | 'vector' | 'evolve' | 'devtools' | 'sandbox' | 'market' | 'settings' | 'whatsnew' | 'adrs'
export type ViewId = 'menu' | 'overview' | 'swarm' | 'workflows' | 'hive' | 'claims' | 'federation' | 'plugins' | 'learning' | 'metaharness' | 'memory' | 'cost' | 'timeline' | 'approvals' | 'events' | 'room' | 'missions' | 'xruv' | 'terminal' | 'skills' | 'agent' | 'secure' | 'perf' | 'automate' | 'neural' | 'vector' | 'evolve' | 'devtools' | 'sandbox' | 'market' | 'settings' | 'themes' | 'whatsnew' | 'adrs'
/**
* The views in tab order, each with its hotkey and the inline height it asks for. Digits are the first nine; the three
@@ -73,6 +73,7 @@ export const VIEWS: readonly { id: ViewId; key: string; label: string; short: st
{ id: 'market', key: 'm', label: 'Plugin Catalog', short: 'Cat', icon: '📦', blurb: 'every ruflo plugin, mod and skill: what it ships, install, enable, disable, update, view and use', rows: 50 },
{ id: 'adrs', key: '', label: 'ADRs', short: 'ADR', icon: '📐', blurb: 'your project’s Architecture Decision Records: find, propose, accept and supersede them, attach them to a mission so Claude and the swarm follow what was decided', rows: 44 },
{ id: 'whatsnew', key: '', label: 'What’s new', short: 'New', icon: '🆕', blurb: 'what changed in your ruflo plugins, newest first: from each plugin’s own CHANGELOG, breaking changes pinned until you dismiss them', rows: 40 },
{ id: 'themes', key: '', label: 'Theme Studio', short: 'Themes', icon: '◈', blurb: 'theme selection, color picker, animated palettes and Claude or Codex theme generator', rows: 50 },
{ id: 'settings', key: 's', label: 'Settings', short: 'Set', icon: '⚙️', blurb: 'simple to advanced settings: plugin options, ruflo config, updates, and the AI terminal’s model and budget, each edited in place', rows: 50 },
]
@@ -115,8 +116,8 @@ export type Options = GuardOptions & ConvoOptions & SessionOptions & {
panel: 'auto' | 'command' | 'off'
/** Lets the federation view ask the public relay for the roster. Off by default: no network without consent. */
federationNetwork: boolean
/** `bbs`: the neon ASCII-art look (default); `plain`: the terminal theme's own colours and plain rules. */
look: 'bbs' | 'plain'
/** `bbs`: neon (default); `plain`: terminal colours; `orbital`: dark telemetry panels with red accents. */
look: 'bbs' | 'plain' | 'orbital'
/** With the bbs look, a short dial-up boot screen when the cockpit opens. */
boot: boolean
/** ADR-474: keep the Events and Timeline history in `.claude-flow/console/` (events.jsonl, lanes.jsonl). On by default; masked text only. */
@@ -140,7 +141,7 @@ export function optionsOf(raw: PluginOptions | undefined): Options {
bar: value.bar === 'on' || value.bar === 'off' ? value.bar : 'auto',
panel: value.panel === 'command' || value.panel === 'off' ? value.panel : 'auto',
federationNetwork: value.federationNetwork === true,
look: value.look === 'plain' ? 'plain' : 'bbs',
look: value.look === 'plain' || value.look === 'orbital' ? value.look : 'bbs',
boot: value.boot !== false,
eventsPersist: value.eventsPersist !== false && value.eventsPersist !== 'false',
...guardOptionsOf(raw),
@@ -461,11 +462,15 @@ export const BOOT_MIN_MS = 5_400
export const BOOT_MAX_MS = 8_000
export function isBooting(state: State, nowMs: number): boolean {
if (state.options.look !== 'bbs' || !state.options.boot || state.pane.bootAtMs === 0) return false
if (!['bbs', 'orbital'].includes(state.options.look) || !state.options.boot || state.pane.bootAtMs === 0) return false
// Reduced motion skips Orbital's decorative intro and cannot leave a static loader blocking the page.
if (state.options.look === 'orbital' && state.options.fps === 0) return false
const age = nowMs - state.pane.bootAtMs
return age >= 0 && age < BOOT_MAX_MS && (age < BOOT_MIN_MS || state.snapshot === null)
return state.options.look === 'orbital'
? age >= 0 && age < 6_000 && (age < 1_500 || state.snapshot === null)
: age >= 0 && age < BOOT_MAX_MS && (age < BOOT_MIN_MS || state.snapshot === null)
}
/**
+164
View File
@@ -0,0 +1,164 @@
/** Theme Studio stores data only. Generated presets never load executable code. */
import type { Host } from './host'
import type { State } from './state'
export const COLOR_KEYS = ['head', 'ok', 'bad', 'warn', 'info', 'background'] as const
export type ColorKey = typeof COLOR_KEYS[number]
export type ConsoleTheme = {
version: 1
name: string
palette: Record<ColorKey, string>
motion: { speed: number; stars: boolean; globe: boolean; topology: boolean }
}
export const ORBITAL_THEME: ConsoleTheme = {
version: 1, name: 'Orbital',
palette: { head: '#f06449', ok: '#72c79b', bad: '#ff6868', warn: '#e3ba74', info: '#c6cbc8', background: '#000000' },
motion: { speed: 1, stars: true, globe: true, topology: true },
}
const clone = (theme: ConsoleTheme): ConsoleTheme => ({ ...theme, palette: { ...theme.palette }, motion: { ...theme.motion } })
/** Bundled palettes have stable IDs and do not consume the twelve custom preset slots. */
export const THEME_PRESETS: readonly { id: string; theme: ConsoleTheme }[] = [
{ id: 'arctic', theme: { ...clone(ORBITAL_THEME), name: 'Arctic', palette: { head: '#79dfff', ok: '#8ee6be', bad: '#ff929d', warn: '#ffd486', info: '#d6e9f2', background: '#08131f' } } },
{ id: 'synthwave', theme: { ...clone(ORBITAL_THEME), name: 'Synthwave', palette: { head: '#ed99ff', ok: '#6fe7c5', bad: '#ff899e', warn: '#ffe08a', info: '#e4d9f5', background: '#170d26' } } },
{ id: 'amber-crt', theme: { ...clone(ORBITAL_THEME), name: 'Amber CRT', palette: { head: '#ffcf73', ok: '#c6e58b', bad: '#ff9580', warn: '#ffe3a3', info: '#ead8b7', background: '#171108' } } },
{ id: 'emerald', theme: { ...clone(ORBITAL_THEME), name: 'Emerald', palette: { head: '#69e6af', ok: '#a1edb4', bad: '#ff9191', warn: '#efcf87', info: '#cde5da', background: '#081710' } } },
{ id: 'solar-flare', theme: { ...clone(ORBITAL_THEME), name: 'Solar Flare', palette: { head: '#ffab79', ok: '#b8dc91', bad: '#ff929d', warn: '#ffdf83', info: '#f1ddce', background: '#21100c' } } },
{ id: 'moonlight', theme: { ...clone(ORBITAL_THEME), name: 'Moonlight', palette: { head: '#b6c5ff', ok: '#a2d9c8', bad: '#ffa0b6', warn: '#e8d5a3', info: '#e0e4f2', background: '#101420' } } },
]
const presetOf = (id: string | null) => THEME_PRESETS.find(preset => `preset:${preset.id}` === id)?.theme
export const THEME_STORE_KEY = 'console-themes-v1'
const HEX = /^#[0-9a-f]{6}$/i
const record = (value: unknown): Record<string, unknown> | null => typeof value === 'object' && value !== null && !Array.isArray(value) ? value as Record<string, unknown> : null
const exact = (value: Record<string, unknown>, keys: readonly string[]) => Object.keys(value).length === keys.length && keys.every(key => Object.hasOwn(value, key))
/** Strict, bounded schema; drop no unknown fields silently. */
export function parseTheme(value: unknown): ConsoleTheme | null {
const root = record(value), palette = record(root?.palette), motion = record(root?.motion)
if (!root || !palette || !motion || !exact(root, ['version', 'name', 'palette', 'motion']) || !exact(palette, COLOR_KEYS) || !exact(motion, ['speed', 'stars', 'globe', 'topology'])) return null
if (root.version !== 1 || typeof root.name !== 'string' || !/^[\p{L}\p{N}][\p{L}\p{N} ._-]{0,39}$/u.test(root.name)) return null
if (!COLOR_KEYS.every(key => typeof palette[key] === 'string' && HEX.test(palette[key] as string))) return null
if (typeof motion.speed !== 'number' || !Number.isFinite(motion.speed) || motion.speed < 0.25 || motion.speed > 2 || !['stars', 'globe', 'topology'].every(key => typeof motion[key] === 'boolean')) return null
return { version: 1, name: root.name, palette: Object.fromEntries(COLOR_KEYS.map(key => [key, (palette[key] as string).toLowerCase()])) as ConsoleTheme['palette'], motion: { speed: motion.speed, stars: motion.stars as boolean, globe: motion.globe as boolean, topology: motion.topology as boolean } }
}
export function themeFromText(text: string): ConsoleTheme | null {
if (text.length > 4096) return null
try { return parseTheme(JSON.parse(text.trim().replace(/^```(?:json)?\s*\n([\s\S]*?)\n```$/, '$1'))) } catch { return null }
}
export function contrast(a: string, b: string): number {
const luminance = (hex: string) => {
const rgb = [1, 3, 5].map(i => parseInt(hex.slice(i, i + 2), 16) / 255).map(c => c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4)
return rgb[0]! * 0.2126 + rgb[1]! * 0.7152 + rgb[2]! * 0.0722
}
const x = luminance(a), y = luminance(b)
return (Math.max(x, y) + 0.05) / (Math.min(x, y) + 0.05)
}
export const lowContrast = (theme: ConsoleTheme): ColorKey[] => COLOR_KEYS.filter(key => key !== 'background' && contrast(theme.palette[key], theme.palette.background) < 3)
export const themeLayout = (columns: number) => {
const width = Math.max(1, Math.min(200, Math.floor(columns) || 1))
return { width, wide: width >= 100, controls: width >= 100 ? 38 : width, preview: width >= 100 ? width - 40 : width }
}
export type StudioTab = 'colors' | 'motion' | 'generate'
export type ThemeStudio = { tab: StudioTab; role: ColorKey; saved: ConsoleTheme[]; active: ConsoleTheme | null; draft: ConsoleTheme; selected: string | null; brief: string; message: string; loaded: boolean; revision: number; saving: boolean; initialLook: State['options']['look'] }
const studios = new WeakMap<State, ThemeStudio>()
export function themesOf(state: State): ThemeStudio {
let studio = studios.get(state)
if (!studio) {
studio = { tab: 'colors', role: 'head', saved: [], active: null, draft: clone(ORBITAL_THEME), selected: null, brief: 'A calm cyberpunk theme with readable colors and slow orbital motion', message: '', loaded: false, revision: 0, saving: false, initialLook: state.options.look }
studios.set(state, studio)
}
return studio
}
export const activeTheme = (state: State): ConsoleTheme => themesOf(state).active ?? ORBITAL_THEME
export async function loadThemes(state: State, host: Host): Promise<void> {
const studio = themesOf(state)
if (studio.loaded) return
studio.loaded = true
const revision = studio.revision
try {
const data = record(await host.storeGet(THEME_STORE_KEY))
if (!data || studio.revision !== revision) return
studio.saved = Array.isArray(data.saved) ? data.saved.slice(0, 12).map(parseTheme).filter((t): t is ConsoleTheme => t !== null) : []
const selected = typeof data.selected === 'string' ? data.selected : null
const theme = presetOf(selected) ?? studio.saved.find(t => `custom:${t.name}` === selected)
if (theme) { studio.active = clone(theme); studio.draft = clone(theme); studio.selected = selected; state.options.look = 'orbital' }
else if (selected === 'bbs' || selected === 'plain' || selected === 'orbital') { studio.selected = selected; state.options.look = selected }
host.invalidate()
} catch { studio.message = 'Saved themes could not be read; using the configured look.'; host.invalidate() }
}
export type ThemeActions = {
tab: (tab: StudioTab) => void
role: (role: ColorKey) => void
discard: () => void
select: (id: string) => void
color: (key: ColorKey, value: string) => void
name: (value: string) => void
motion: (key: keyof ConsoleTheme['motion'], value: number | boolean) => void
import: (text: string) => void
save: () => void
reset: () => void
brief: (value: string) => void
generate: (agent: 'claude' | 'codex') => void
}
export function themeActions(state: State, host: Host, ask: (agent: 'claude' | 'codex', prompt: string) => void): ThemeActions {
const studio = themesOf(state)
const tell = (message: string) => { studio.message = message; host.invalidate() }
// Serialize writes and commit in-memory selection only after persistence succeeds.
const persist = async (selected: string | null, saved: ConsoleTheme[], active: ConsoleTheme | null, look: State['options']['look']) => {
if (studio.saving) return tell('A theme is being saved. Try again when it finishes.')
studio.saving = true; studio.revision++; host.invalidate()
try {
await host.storeSet(THEME_STORE_KEY, { selected, saved })
studio.selected = selected; studio.saved = saved; studio.active = active; state.options.look = look
studio.draft = clone(active ?? ORBITAL_THEME)
tell('Theme saved and applied.')
} catch { tell('Could not save the theme. The active theme is unchanged.') }
finally { studio.saving = false; host.invalidate() }
}
return {
tab: tab => { if (['colors', 'motion', 'generate'].includes(tab)) { studio.tab = tab; host.invalidate() } },
role: role => { if (COLOR_KEYS.includes(role)) { studio.role = role; host.invalidate() } },
discard: () => { studio.draft = clone(studio.active ?? ORBITAL_THEME); tell('Draft restored to the active palette.') },
select: id => {
if (id === 'bbs' || id === 'plain' || id === 'orbital') { void persist(id, studio.saved, null, id); return }
const theme = presetOf(id) ?? studio.saved.find(t => `custom:${t.name}` === id)
if (theme) void persist(id, studio.saved, clone(theme), 'orbital')
},
color: (key, value) => {
if (!COLOR_KEYS.includes(key) || !HEX.test(value.trim())) return tell('Enter a six digit hex color, for example #72c79b.')
studio.draft.palette[key] = value.trim().toLowerCase(); tell('Preview updated. Save to apply.')
},
name: value => {
const candidate = parseTheme({ ...studio.draft, name: value.trim() })
if (!candidate) return tell('Use 1 to 40 letters, numbers, spaces, dots or underscores for the name.')
studio.draft = candidate; tell('Preview renamed.')
},
motion: (key, value) => {
const candidate = parseTheme({ ...studio.draft, motion: { ...studio.draft.motion, [key]: value } })
if (!candidate) return tell('Invalid motion setting.')
studio.draft = candidate; tell('Preview updated. Save to apply.')
},
import: text => {
const candidate = themeFromText(text)
if (!candidate) return tell('Invalid theme JSON. Expected version 1, name, six hex colors and motion settings; maximum 4096 characters.')
studio.draft = candidate; tell('Theme imported into preview. Save to apply.')
},
save: () => {
const theme = parseTheme(studio.draft)
if (!theme) return tell('Invalid theme.')
const unreadable = lowContrast(theme)
if (unreadable.length) return tell(`Increase contrast for: ${unreadable.join(', ')}. Each needs at least 3:1 against the background.`)
const saved = studio.saved.filter(t => t.name !== theme.name)
if (saved.length >= 12) return tell('Twelve custom themes are saved. Reuse an existing name to replace it.')
void persist(`custom:${theme.name}`, [...saved, clone(theme)], clone(theme), 'orbital')
},
reset: () => { void persist(null, studio.saved, null, studio.initialLook) },
brief: value => { studio.brief = value.replace(/[\x00-\x1f\x7f]/g, ' ').slice(0, 1200); tell('Design brief ready.') },
generate: agent => {
void Promise.all([host.fs.read(`${host.pluginRoot}/skills/generate-console-theme/SKILL.md`), host.fs.read(`${host.pluginRoot}/skills/generate-console-theme/references/preset.md`)]).then(parts => {
const skill = parts.join('\n\n')
if (skill.length > 16000) return tell('Theme generator skill is too large.')
ask(agent, `${skill}\n\nDesign brief (user input):\n${studio.brief}\n\nReturn one JSON object for Theme Studio import. Do not write files or run commands. Current draft:\n${JSON.stringify(studio.draft)}`)
}, () => tell('The bundled generate-console-theme skill could not be read. Reinstall or update the plugin.'))
},
}
}
+1 -1
View File
@@ -2,4 +2,4 @@
* The console's version, shown on the header so a person can tell which build is running. Kept equal to the plugin's manifest
* (`.claude-plugin/plugin.json`); tests/version.spec.ts fails if the two drift.
*/
export const CONSOLE_VERSION = '0.42.7'
export const CONSOLE_VERSION = '0.43.0'
+2 -2
View File
@@ -8,7 +8,7 @@
* nothing a view clips to its width overflows the frame.
*/
import type { Ctx } from './common'
import { THEME } from './common'
import { isOrbital, THEME } from './common'
import { HEADS, SPACERS } from './marks'
/** Columns a card takes from the page width: border and padding, both sides. */
@@ -42,7 +42,7 @@ export function withCards(kit: Ctx['kit'], accent?: string): Ctx['kit'] {
const out: unknown[] = []
let card: unknown[] | null = null
const close = () => {
if (card !== null) out.push(kit.Box({ key: `card-${made++}`, flexDirection: 'column', borderStyle: 'round', borderColor: accent ?? THEME.info, paddingX: 1, children: card as never }))
if (card !== null) out.push(kit.Box({ key: `card-${made++}`, flexDirection: 'column', borderStyle: isOrbital() ? 'single' : 'round', borderColor: isOrbital() ? THEME.head : accent ?? THEME.info, paddingX: 1, children: card as never }))
card = null
}
+8 -4
View File
@@ -3,6 +3,7 @@
* and the pictures computed for this frame. They call nothing on the engine; buttons call the closures in `ctx.act`.
* Text colours are theme names only, so nothing fades on a light background.
*/
import type { ThemeActions, ConsoleTheme } from '../themes'
import type { AskActions } from '../ask-claude'
import type { OptimizerActions } from '../optimizer'
import { askedBy } from '../data/room'
@@ -143,6 +144,7 @@ export type Actions = {
/** The Workflows page: cursor keys, the inspector's tab, the confirm-gated ruflo agent verbs, and naming a transcript's path. */
workflows: WorkflowsActions
/** Settings: the level, a plugin, an option or ruflo config change (each asks first), AI preferences, and ▸ ask claude/codex. */
themes: ThemeActions
settings: SettingsActions
}
@@ -162,24 +164,26 @@ export type Ctx = {
text?: boolean
}
export type Look = 'bbs' | 'plain'
export type Look = 'bbs' | 'plain' | 'orbital'
/** The terminal theme's own colours: readable on light and dark backgrounds alike. */
const PLAIN = { head: 'claude', ok: 'success', bad: 'error', warn: 'warning', info: 'suggestion' }
/** The BBS look: neon magenta headings, cyan values, matrix-green labels; amber stays for attention. */
const NEON = { head: '#ff2a6d', ok: '#39ff14', bad: '#ff3355', warn: '#ffd319', info: '#05d9e8' }
const ORBITAL = { head: '#f06449', ok: '#72c79b', bad: '#ff6868', warn: '#e3ba74', info: '#c6cbc8' }
const NEON_LABEL = '#2fbf71'
/** The palette every view reads; `setLook` swaps it in place before a render, so callers keep using THEME.x. */
export const THEME: { head: string; ok: string; bad: string; warn: string; info: string } = { ...PLAIN }
let look: Look = 'plain'
export function setLook(next: Look): void {
if (next === look) return
export function setLook(next: Look, palette?: ConsoleTheme['palette']): void {
look = next
Object.assign(THEME, next === 'bbs' ? NEON : PLAIN)
Object.assign(THEME, next === 'bbs' ? NEON : next === 'orbital' ? (palette ?? ORBITAL) : PLAIN)
}
export const isOrbital = (): boolean => look === 'orbital'
export const isBbs = (): boolean => look === 'bbs'
/**
+22 -3
View File
@@ -1,3 +1,4 @@
import { activeTheme, themesOf, themeLayout } from '../themes'
/**
* The pictures of the view in front, by Raster key, for one instant. The render mounts them and the animation loop
* blits them, both through `picturesOf`, so a frame is always the mounted size. Each picture's model is read from the
@@ -7,6 +8,7 @@ import type { AuditTrend, HarnessScore, Intelligence } from '../data/cli'
import { recentByAgent } from '../data/events'
import { agentLabels } from '../data/parse'
import { presentAgents, swarmStatusOf } from '../data/swarm-status'
import { orbitalBoot, orbitalHeader, orbitalGlobe, orbitalMasthead } from '../gfx/orbital'
import { getBootChecks } from '../boot-checks'
import { bootFacts } from '../boot-facts'
import { getBuild } from '../build'
@@ -177,13 +179,15 @@ function titleThatFits(paneColumns: number, names: readonly string[], build: (na
export function picturesOf(state: State, columns: number, nowMs: number, t: number): Map<string, Grid> {
const pictures = new Map<string, Grid>()
const theme = activeTheme(state)
const motionTime = state.options.fps > 0 ? t * theme.motion.speed : 0
// A page in cards (views/card.ts) is narrower by the border and padding: its pictures are drawn to that width, by the render and by the frame loop alike.
const width = Math.max(20, Math.min(200, hasCards(columns, isCompactPane(state)) ? columns - CARD_COLUMNS : columns))
const snapshot = state.snapshot
// The BBS boot screen owns the pane for its first seconds; nothing else is drawn under it.
// The selected boot screen owns the pane for its first seconds; nothing else is drawn under it.
if (isBooting(state, nowMs)) {
pictures.set('boot', bootPicture(state.cwd.split('/').filter(Boolean).at(-1) ?? '', Math.min(width, 90), nowMs - state.pane.bootAtMs, state.probes.size, PROBES.length, state.pane.rows, getBootChecks(), bootFacts(state, CONSOLE_VERSION, getBuild())))
pictures.set('boot', state.options.look === 'orbital' ? orbitalBoot(state.cwd.split('/').filter(Boolean).at(-1) ?? '', Math.max(1, Math.min(columns, width, 90)), state.options.fps > 0 ? (nowMs - state.pane.bootAtMs) * theme.motion.speed : 0, getBootChecks(), state.pane.rows > 0 ? state.pane.rows : 30, theme) : bootPicture(state.cwd.split('/').filter(Boolean).at(-1) ?? '', Math.min(width, 90), nowMs - state.pane.bootAtMs, state.probes.size, PROBES.length, state.pane.rows, getBootChecks(), bootFacts(state, CONSOLE_VERSION, getBuild())))
return pictures
}
@@ -213,6 +217,21 @@ export function picturesOf(state: State, columns: number, nowMs: number, t: numb
pictures.set('title', titleThatFits(columns, names, (candidate, size) => titlePicture(candidate, size, t, headerAge)))
}
if (state.options.look === 'orbital') {
const page = state.isHelp ? 'help' : state.palette.isOpen ? 'commands' : (VIEWS.find(view => view.id === state.view)?.label ?? state.view)
const room = Math.max(1, Math.min(120, columns < 40 ? columns : columns - iconCells(false) - ICON_SLACK))
const rows = state.pane.rows > 0 ? Math.max(1, Math.min(state.pane.rows < 24 ? 2 : 8, state.pane.rows - 12)) : 8
pictures.set(state.view === 'menu' ? 'header' : 'title', orbitalMasthead(page, room, motionTime, rows, theme, headerAge))
}
if (state.view === 'themes') {
const draft = themesOf(state).draft
const layout = themeLayout(Math.min(columns, width))
const previewWidth = Math.max(1, layout.preview - 2)
if (draft.motion.globe) pictures.set('theme-globe', orbitalGlobe(previewWidth, layout.wide ? 14 : 9, state.options.fps > 0 ? t * draft.motion.speed : 0, draft))
pictures.set('theme-preview', orbitalHeader('swarm preview', previewWidth, state.options.fps > 0 ? t * draft.motion.speed : 0, layout.wide ? 16 : 4, draft))
}
switch (state.view) {
case 'overview':
pictures.set('activity', activityPicture([{ label: 'tool calls/5s', values: state.activity }, { label: 'state writes', values: state.writes }], width, t))
@@ -220,7 +239,7 @@ export function picturesOf(state: State, columns: number, nowMs: number, t: numb
case 'swarm': {
const model = topoModelOf(snapshot, recentByAgent(state.events, nowMs, PULSE_MS + 600), nowMs)
if (model !== null) pictures.set('topology', topologyPicture(model, width, topologyRows(width, model.nodes.length), t))
if (model !== null) pictures.set('topology', topologyPicture(model, width, topologyRows(width, model.nodes.length), t, state.options.look === 'orbital' && theme.motion.topology, motionTime, state.options.look === 'orbital' ? theme.palette : undefined))
break
}
case 'hive':
+4 -4
View File
@@ -6,7 +6,7 @@ import type { RenderElement } from 'claude-code'
import { ACCENT, badgesOf, chip, LOUD, MUTED, PALETTE } from '../menu-style'
import { VIEWS, type ViewId } from '../state'
import { barParts } from './bar'
import { button, clip, col, isBbs, picture, row, text, THEME, type Ctx } from './common'
import { button, clip, col, isBbs, isOrbital, picture, row, text, THEME, type Ctx } from './common'
import { missionStrip } from './mission-control'
type Item = { label: string; go: string }
@@ -52,7 +52,7 @@ export const GROUPS: readonly { title: string; sections: readonly { name: string
},
{
title: 'TOOLS',
sections: [{ name: 'tools', items: [{ label: 'AI Terminal', go: 'terminal' }, { label: 'Automation', go: 'automate' }, { label: 'Dev Tools', go: 'devtools' }, { label: 'Plugins & Mods', go: 'plugins' }, { label: 'ADRs', go: 'adrs' }, { label: 'What’s new', go: 'whatsnew' }, { label: 'Settings', go: 'settings' }, { label: 'Command Palette', go: 'palette' }, { label: 'Help', go: 'help' }, { label: 'Log Off', go: 'close' }] }],
sections: [{ name: 'tools', items: [{ label: 'AI Terminal', go: 'terminal' }, { label: 'Automation', go: 'automate' }, { label: 'Dev Tools', go: 'devtools' }, { label: 'Plugins & Mods', go: 'plugins' }, { label: 'ADRs', go: 'adrs' }, { label: 'What’s new', go: 'whatsnew' }, { label: 'Theme Studio', go: 'themes' }, { label: 'Settings', go: 'settings' }, { label: 'Command Palette', go: 'palette' }, { label: 'Help', go: 'help' }, { label: 'Log Off', go: 'close' }] }],
},
]
@@ -101,7 +101,7 @@ export function menuView(ctx: Ctx): RenderElement {
const started = entry === null || entry >= groupStart(gi)
let seen = 0
const accent = ACCENT[group.title] ?? '#d0d0d0'
const title = clip(`▓▒░ ${group.title} ░▒▓`, width - 8)
const title = clip(isOrbital() ? group.title : `▓▒░ ${group.title} ░▒▓`, width - 8)
const isOpen = isGroupOpen(group, gi)
const count = group.sections.reduce((n, section) => n + section.items.filter(isShown).length, 0)
@@ -109,7 +109,7 @@ export function menuView(ctx: Ctx): RenderElement {
flexDirection: 'column',
width,
borderStyle: 'single',
borderColor: bbs && started ? accent : 'inactive',
borderColor: isOrbital() ? THEME.head : bbs && started ? accent : 'inactive',
paddingX: 1,
key: `menu-${group.title}`,
children: [
+2 -2
View File
@@ -13,7 +13,7 @@ import { badgesOf } from '../menu-style'
import { accentOfView, findPages, groupOf, NAV_GROUPS, shownGroup } from '../nav-state'
import { VIEWS, type ViewId } from '../state'
import { CARD_COLUMNS } from './card'
import { isBbs, THEME, type Ctx } from './common'
import { isBbs, isOrbital, THEME, type Ctx } from './common'
type View = (typeof VIEWS)[number]
@@ -109,5 +109,5 @@ export function groupedTabs(ctx: Ctx, hasHotkey: (view: View) => boolean): Rende
const hidden = VIEWS.filter(view => view.id !== 'menu' && view.id !== open && !visible.has(view.id) && hasHotkey(view) && view.key !== '')
const keys = hidden.length === 0 ? [] : [ctx.kit.Box({ key: 'tabs-keys', display: 'none', children: hidden.map(view => ctx.kit.Button({ key: `tab-${view.id}`, label: view.short, hotkey: view.key, plain: true, onPress: () => ctx.act.view(view.id) })) } as never)]
return ctx.kit.Box({ key: 'tabs', flexDirection: 'column', borderStyle: 'round', borderColor: THEME.info, paddingX: 1, children: [head, ...findRow, ...lines, ...note, ...keys] })
return ctx.kit.Box({ key: 'tabs', flexDirection: 'column', borderStyle: isOrbital() ? 'single' : 'round', borderColor: isOrbital() ? THEME.head : THEME.info, paddingX: 1, children: [head, ...findRow, ...lines, ...note, ...keys] })
}
@@ -0,0 +1,53 @@
/** The pane's icon row (menu, palette, help, settings, refresh) and where it sits beside the header art; split out of pane.ts to keep both under 500 lines. */
import type { RenderElement } from 'claude-code'
import { ICON_MARGIN, ICONS, iconsSpellWords } from '../icon-layout'
import { THEME, type Ctx } from './common'
/**
* The icons on one line, at the right of the first row, beside the host's ✕: the main menu, the palette, help, settings and refresh (hooks/icon-layout.ts
* says which glyphs and why). Each says its word as well when the pane is wide and the header art beside it leaves room for the whole row; otherwise it
* is a glyph and a cell. The one for the page you are on is lit: coloured text of exactly the width of a button (a plain Button draws exactly its label).
*/
export function iconRow(ctx: Ctx): RenderElement {
const { state } = ctx
const header = ctx.pictures.get(state.view === 'menu' ? 'header' : 'title')
const withWords = iconsSpellWords(ctx.columns, header?.columns ?? 0)
const press: Record<(typeof ICONS)[number]['id'], { isCurrent: boolean; run: () => void }> = {
menu: { isCurrent: state.view === 'menu' && !state.isHelp && !state.palette.isOpen, run: () => ctx.act.view('menu') },
palette: { isCurrent: state.palette.isOpen, run: () => ctx.act.palette('all') },
help: { isCurrent: state.isHelp, run: ctx.act.help },
settings: { isCurrent: state.view === 'settings' && !state.isHelp && !state.palette.isOpen, run: () => ctx.act.view('settings') },
// Refresh re-reads everything and replays the intro, as the footer's Refresh and the r key do; it is an action, never the page you are on.
refresh: { isCurrent: false, run: ctx.act.restart },
}
return ctx.kit.Box({
flexDirection: 'row',
flexShrink: 0,
key: 'pane-icons',
children: [
...ICONS.map(icon => {
const key = `pane-icon-${icon.id}`
const label = withWords ? `${icon.glyph} ${icon.word} ` : `${icon.glyph} `
const entry = press[icon.id]
return entry.isCurrent
? ctx.kit.Box({ key, flexShrink: 0, children: [ctx.kit.Text({ bold: true, color: THEME.head, children: label })] })
: ctx.kit.Button({ key, label, plain: true, dimColor: true, onPress: entry.run })
}),
ctx.kit.Text({ children: ' '.repeat(ICON_MARGIN) }),
],
})
}
/** Puts the icon row at the right of the first line of the pane, beside the header art and its purpose line; with no header, on a row of its own. */
export function withIcons(ctx: Ctx, parts: RenderElement[], lead: number): RenderElement[] {
if (ctx.columns < 40) return parts
if (lead === 0) {
return [ctx.kit.Box({ flexDirection: 'row', key: 'pane-top', children: [ctx.kit.Box({ flexGrow: 1, key: 'pane-top-gap', children: [ctx.kit.Text({ children: ' ' })] }), iconRow(ctx)] }), ...parts]
}
return [ctx.kit.Box({ flexDirection: 'row', key: 'pane-top', children: [ctx.kit.Box({ flexDirection: 'column', flexGrow: 1, key: 'pane-lead', children: parts.slice(0, lead) }), iconRow(ctx)] }), ...parts.slice(lead)]
}
+14 -57
View File
@@ -21,10 +21,12 @@ import { isBooting, isCompactPane, NAV_STYLES, VIEWS, type ViewId } from '../sta
import { agentView } from './agent'
import { automateResult, automateView } from './automate'
import { claimsView } from './claims'
import { ago, button, clip, col, confirmRow, isBbs, row, setLook, text, THEME, type Ctx } from './common'
import { ago, button, clip, col, confirmRow, isBbs, isOrbital, row, setLook, text, THEME, type Ctx } from './common'
import { costView } from './cost'
import { evolveResult, evolveView } from './evolve'
import { catalogView } from './plugin-catalog'
import { activeTheme } from '../themes'
import { themesView } from './themes'
import { settingsView } from './settings'
import { whatsnewView } from './whatsnew'
import { adrsView } from './adr'
@@ -44,7 +46,7 @@ import { labResult } from './mh-lab'
import { neuralResult, neuralView } from './neural'
import { missionControlView } from './mission-control'
import { overviewView } from './overview'
import { ICON_MARGIN, ICONS, iconsSpellWords } from '../icon-layout'
import { withIcons } from './pane-icons'
import { helpView } from './help'
import { paletteView } from './palette'
import { perfResult, perfView } from './perf'
@@ -96,6 +98,7 @@ export const BODIES: Record<ViewId, (ctx: Ctx) => RenderElement> = {
devtools: devtoolsView,
sandbox: sandboxView,
market: catalogView,
themes: themesView,
settings: settingsView,
whatsnew: whatsnewView, adrs: adrsView,
agent: agentView,
@@ -313,62 +316,14 @@ const RESULT_OF: Partial<Record<ViewId, (ctx: Ctx) => RenderElement[]>> = {
learning: neuralResult,
}
/**
* The icons on one line, at the right of the first row, beside the host's ✕: the main menu, the palette, help, settings and refresh (hooks/icon-layout.ts
* says which glyphs and why). Each says its word as well when the pane is wide and the header art beside it leaves room for the whole row; otherwise it
* is a glyph and a cell. The one for the page you are on is lit: coloured text of exactly the width of a button (a plain Button draws exactly its label).
*/
export function iconRow(ctx: Ctx): RenderElement {
const { state } = ctx
const header = ctx.pictures.get(state.view === 'menu' ? 'header' : 'title')
const withWords = iconsSpellWords(ctx.columns, header?.columns ?? 0)
const press: Record<(typeof ICONS)[number]['id'], { isCurrent: boolean; run: () => void }> = {
menu: { isCurrent: state.view === 'menu' && !state.isHelp && !state.palette.isOpen, run: () => ctx.act.view('menu') },
palette: { isCurrent: state.palette.isOpen, run: () => ctx.act.palette('all') },
help: { isCurrent: state.isHelp, run: ctx.act.help },
settings: { isCurrent: state.view === 'settings' && !state.isHelp && !state.palette.isOpen, run: () => ctx.act.view('settings') },
// Refresh re-reads everything and replays the intro, as the footer's Refresh and the r key do; it is an action, never the page you are on.
refresh: { isCurrent: false, run: ctx.act.restart },
}
return ctx.kit.Box({
flexDirection: 'row',
flexShrink: 0,
key: 'pane-icons',
children: [
...ICONS.map(icon => {
const key = `pane-icon-${icon.id}`
const label = withWords ? `${icon.glyph} ${icon.word} ` : `${icon.glyph} `
const entry = press[icon.id]
return entry.isCurrent
? ctx.kit.Box({ key, flexShrink: 0, children: [ctx.kit.Text({ bold: true, color: THEME.head, children: label })] })
: ctx.kit.Button({ key, label, plain: true, dimColor: true, onPress: entry.run })
}),
ctx.kit.Text({ children: ' '.repeat(ICON_MARGIN) }),
],
})
}
/** Puts the icon row at the right of the first line of the pane, beside the header art and its purpose line; with no header, on a row of its own. */
function withIcons(ctx: Ctx, parts: RenderElement[], lead: number): RenderElement[] {
if (ctx.columns < 40) return parts
if (lead === 0) {
return [ctx.kit.Box({ flexDirection: 'row', key: 'pane-top', children: [ctx.kit.Box({ flexGrow: 1, key: 'pane-top-gap', children: [ctx.kit.Text({ children: ' ' })] }), iconRow(ctx)] }), ...parts]
}
return [ctx.kit.Box({ flexDirection: 'row', key: 'pane-top', children: [ctx.kit.Box({ flexDirection: 'column', flexGrow: 1, key: 'pane-lead', children: parts.slice(0, lead) }), iconRow(ctx)] }), ...parts.slice(lead)]
}
export function paneView(base: Ctx): RenderElement {
setLook(base.state.options.look)
setLook(base.state.options.look, activeTheme(base.state).palette)
// Every Button and Input remembers its key, and a column that holds the origin of the current ask places the confirm and the answer after it.
const attention = newAttention(base.state.origin, [])
const ctx: Ctx = { ...base, kit: wrapKit(base.kit, base.state, attention), attention }
// The BBS boot screen: the first seconds after the pane opens (or until the first read lands, at most 6 s).
// The selected boot screen: a bounded intro while the first snapshot arrives.
if (isBooting(ctx.state, ctx.nowMs)) {
const boot = ctx.pictures.get('boot')
@@ -419,10 +374,12 @@ export function paneView(base: Ctx): RenderElement {
const hasInlineConfirm = attention.keys.get(body)?.has('confirm') === true
const header = ctx.pictures.get('header')
const isCompact = isCompactPane(ctx.state)
const fallbackBrand = isOrbital() && ctx.kit.Raster === undefined ? [text(ctx, 'RUFLO / AGENT SWARM CONSOLE', { bold: true, color: THEME.head, wrap: 'truncate-end' })] : []
// The logo banner leads the main menu in every layout, compact too (the other pages lead with their own title art there).
const title = (!isCompact || ctx.state.view === 'menu') && header !== undefined && ctx.kit.Raster !== undefined ? [ctx.kit.Raster(header.toRaster('header'))] : []
const title = (!isCompact || ctx.state.view === 'menu') && header !== undefined && ctx.kit.Raster !== undefined ? [ctx.kit.Raster(header.toRaster('header'))] : ctx.state.view === 'menu' ? fallbackBrand : []
const about = blurb(ctx)
const bbs = isBbs() ? wildcat(ctx) : { strip: [], art: [] }
const orbitalArt = ctx.pictures.get('title')
const bbs = isBbs() ? wildcat(ctx) : { strip: [], art: isOrbital() && orbitalArt !== undefined && ctx.kit.Raster !== undefined ? [ctx.kit.Raster(orbitalArt.toRaster('title'))] : ctx.state.view !== 'menu' ? fallbackBrand : [] }
// The status row (keys, sync, Palette, Actions) sits above the body, so a tall view cannot push it off the screen; only the main menu keeps it below its prompt, as a BBS does.
const isMenu = ctx.state.view === 'menu'
// The terminal's own Enter-again confirm stays under its field, where the field is.
@@ -432,7 +389,7 @@ export function paneView(base: Ctx): RenderElement {
// Compact keeps every page's title and its line of purpose; only the banner and the spacing go. The title leads, then the tabs, as in the wide layout.
const parts = isCompact
? [...(ctx.state.view === 'menu' && title.length > 0 ? title : bbs.art), ...(about !== null ? [about] : []), tabs(ctx), ...(confirm !== null && !hasInlineConfirm ? [confirm] : []), footer(ctx, attention.placed), body]
: !isMenu && isBbs()
: !isMenu && (isBbs() || isOrbital())
? // Every page but the main menu leads with its own title and purpose line; the welcome line and network links follow, with a blank row between the blocks.
[...bbs.art, ...(about !== null ? [about] : []), ...(cardsOn ? [] : [...gap, ...bbs.strip, ...gap]), tabs(ctx), ...(cardsOn ? [] : gap), footer(ctx, attention.placed), ...(confirm !== null && !isTerminal && !hasInlineConfirm ? [confirm] : []), body, ...(confirm !== null && isTerminal ? [confirm] : [])]
: [...title, ...(isMenu && isBbs() ? [text(ctx, ' ')] : []), ...bbs.strip, ...(isMenu && isBbs() ? [text(ctx, ' ')] : []), ...gap, tabs(ctx), ...gap, ...(isMenu && isBbs() ? [] : [...bbs.art, ...(about !== null ? [about] : [])]), ...gap, ...(isMenu ? [] : [footer(ctx, attention.placed)]), ...(confirm !== null && !isTerminal && !hasInlineConfirm ? [confirm] : []), body, ...(confirm !== null && isTerminal ? [confirm] : []), ...gap, ...(isMenu ? [footer(ctx, attention.placed)] : [])]
@@ -440,11 +397,11 @@ export function paneView(base: Ctx): RenderElement {
// The leading rows that sit beside the icons: the header art (one picture) and the line that says what the page is for; on the menu, the banner and the blank row under it.
const lead = isCompact
? (ctx.state.view === 'menu' && title.length > 0 ? title.length : bbs.art.length) + (about !== null ? 1 : 0)
: !isMenu && isBbs()
: !isMenu && (isBbs() || isOrbital())
? bbs.art.length + (about !== null ? 1 : 0)
: title.length + (isMenu && isBbs() ? 1 : 0)
return ctx.kit.Box({ flexDirection: 'column', children: withIcons(ctx, parts, lead) })
return ctx.kit.Box({ flexDirection: 'column', ...(isOrbital() ? { backgroundColor: activeTheme(ctx.state).palette.background } : {}), children: withIcons(ctx, parts, lead) })
}
type Plain = { type: string; props: { children?: unknown; label?: string } }
@@ -356,6 +356,7 @@ export function settingsView(ctx: Ctx): RenderElement {
const rows: RenderElement[] = [rule(ctx, 'Settings', `${shown.length} shown of ${everything.length} · ${changed} changed`)]
rows.push(button(ctx, 'st-theme-studio', 'Theme Studio: colors and animation', () => ctx.act.view('themes')))
rows.push(
row(
ctx,
@@ -0,0 +1,70 @@
import type { RenderElement } from 'claude-code'
import { activeTheme, COLOR_KEYS, contrast, lowContrast, themeLayout, themesOf, THEME_PRESETS } from '../themes'
import { button, clip, col, picture, row, text, THEME, type Ctx } from './common'
/** One focused editor beside its live preview. Narrow panes stack without shrinking text. */
export function themesView(ctx: Ctx): RenderElement {
const studio = themesOf(ctx.state), act = ctx.act.themes, layout = themeLayout(ctx.columns)
const edit: Ctx = { ...ctx, columns: Math.max(1, layout.controls - 2) }
const preview: Ctx = { ...ctx, columns: Math.max(1, layout.preview - 2) }
const pick = (key: string, label: string, run: () => void) => button(edit, key, clip(label, Math.max(1, edit.columns - 3)), run)
const input = (key: string, label: string, placeholder: string, submit: (value: string) => void) => ctx.kit.Input
? ctx.kit.Input({ key, label: clip(label, edit.columns), placeholder, submitLabel: 'set', onSubmit: submit })
: text(edit, `${label}: text input unavailable`, { dimColor: true })
const panel = (key: string, width: number, rows: RenderElement[]) => ctx.kit.Box({ key, width, flexDirection: 'column', borderStyle: 'single', borderColor: THEME.head, children: rows })
const selected = studio.selected ?? ctx.state.options.look
const choices: RenderElement[] = [text(edit, '01 LOOK', { bold: true, color: THEME.head })]
for (const id of ['bbs', 'plain', 'orbital'] as const) choices.push(pick(`theme-${id}`, `${selected === id ? '●' : '○'} ${id === 'bbs' ? 'Classic BBS' : id === 'plain' ? 'Terminal plain' : 'Orbital'}`, () => act.select(id)))
choices.push(text(edit, 'COLOR PRESETS', { color: THEME.info }))
for (const { id, theme } of THEME_PRESETS) choices.push(row(edit, [
ctx.kit.Text({ color: theme.palette.head, backgroundColor: theme.palette.background, children: ' ▄▄ ' }),
pick(`theme-preset-${id}`, clip(`${selected === `preset:${id}` ? '●' : '○'} ${theme.name}`, Math.max(1, edit.columns - 7)), () => act.select(`preset:${id}`)),
]))
for (const theme of studio.saved) choices.push(pick(`theme-custom-${theme.name}`, `${selected === `custom:${theme.name}` ? '●' : '○'} ${theme.name}`, () => act.select(`custom:${theme.name}`)))
choices.push(text(edit, '02 CUSTOMIZE', { bold: true, color: THEME.head }))
const tabs = (['colors', 'motion', 'generate'] as const).map(tab => pick(`theme-tab-${tab}`, `${studio.tab === tab ? '▸' : '·'} ${tab === 'generate' ? 'AI' : tab}`, () => act.tab(tab)))
choices.push(edit.columns >= 31 ? row(edit, tabs) : col(edit, tabs))
if (studio.tab === 'colors') {
choices.push(input('theme-name', 'Name', studio.draft.name, act.name))
// Each color role is its own labelled swatch. Only the selected role opens an editor.
for (const key of COLOR_KEYS) choices.push(row(edit, [ctx.kit.Text({ color: studio.draft.palette[key], backgroundColor: studio.draft.palette.background, children: ' ▄▄ ' }), pick(`theme-role-${key}`, clip(`${studio.role === key ? '▸' : '·'} ${key.padEnd(10)} ${studio.draft.palette[key]}`, Math.max(1, edit.columns - 7)), () => act.role(key))]))
choices.push(text(edit, `Editing ${studio.role}`, { color: THEME.head }))
const colors = ['#f06449', '#72c79b', '#78c8ff', '#ca9bff', '#ffcf73', '#f2f4f3', '#000000', '#101820']
const perRow = edit.columns >= 24 ? 4 : 2
for (let i = 0; i < colors.length; i += perRow) choices.push(row(edit, colors.slice(i, i + perRow).map((color, j) => col(edit, [ctx.kit.Text({ color, backgroundColor: studio.draft.palette.background, children: ' ▄▄▄ ' }), pick(`theme-swatch-${i + j}`, String(i + j + 1), () => act.color(studio.role, color))]))))
choices.push(input('theme-color', 'Hex color', studio.draft.palette[studio.role], value => act.color(studio.role, value)))
const ratio = Math.min(...COLOR_KEYS.filter(key => key !== 'background').map(key => contrast(studio.draft.palette[key], studio.draft.palette.background)))
choices.push(text(edit, `Minimum contrast ${ratio.toFixed(1)}:1`, { color: ratio >= 3 ? THEME.ok : THEME.warn }))
} else if (studio.tab === 'motion') {
choices.push(text(edit, 'DECORATIVE LAYERS', { color: THEME.info }))
for (const key of ['stars', 'globe', 'topology'] as const) choices.push(pick(`theme-motion-${key}`, `${studio.draft.motion[key] ? '● ON ' : '○ OFF'} ${key}`, () => act.motion(key, !studio.draft.motion[key])))
choices.push(text(edit, 'PLAYBACK SPEED', { color: THEME.info }))
for (const speed of [0.25, 0.5, 1, 2]) choices.push(pick(`theme-speed-${speed}`, `${studio.draft.motion.speed === speed ? '●' : '○'} ${speed}x ${speed === 0.25 ? 'ambient' : speed === 0.5 ? 'calm' : speed === 1 ? 'standard' : 'fast'}`, () => act.motion('speed', speed)))
choices.push(text(edit, ctx.state.options.fps === 0 ? 'Reduced motion: still preview' : 'Set fps to 0 for reduced motion.', { dimColor: true }))
} else {
choices.push(text(edit, 'DESCRIBE YOUR THEME', { color: THEME.info }))
choices.push(input('theme-brief', 'Design brief', studio.brief, act.brief))
choices.push(pick('theme-generate-claude', 'Generate with Claude', () => act.generate('claude')))
choices.push(pick('theme-generate-codex', 'Generate with Codex', () => act.generate('codex')))
choices.push(text(edit, '1. Generate in AI Terminal', { dimColor: true }))
choices.push(text(edit, '2. Import returned JSON', { dimColor: true }))
choices.push(text(edit, '3. Preview and save', { dimColor: true }))
choices.push(input('theme-import', 'Import theme JSON', '{"version":1,...}', act.import))
}
const low = lowContrast(studio.draft)
if (low.length) choices.push(text(edit, `Low contrast: ${low.join(', ')}`, { color: THEME.warn }))
choices.push(text(edit, '03 APPLY', { bold: true, color: THEME.head }))
choices.push(pick('theme-save', studio.saving ? 'Saving…' : 'Save and apply', act.save))
choices.push(pick('theme-discard', 'Discard draft changes', act.discard))
choices.push(pick('theme-reset', 'Use configured look', act.reset))
choices.push(text(edit, studio.message || 'Draft only until saved.', { dimColor: true }))
const stage = [text(preview, `LIVE PREVIEW / ${studio.draft.name}`, { bold: true, color: studio.draft.palette.head }),
...(studio.draft.motion.globe ? [picture(preview, 'theme-globe', 'Globe preview')] : [text(preview, 'Globe layer off', { dimColor: true })]),
picture(preview, 'theme-preview', 'Swarm preview'),
text(preview, `${studio.draft.motion.speed}x motion / ${ctx.state.options.fps === 0 ? 'paused' : 'animated'} / illustrative`, { dimColor: true }),
(preview.columns >= 18 ? row : col)(preview, [text(preview, ' PASS ', { color: studio.draft.palette.ok }), text(preview, ' WARN ', { color: studio.draft.palette.warn }), text(preview, ' FAIL ', { color: studio.draft.palette.bad })]),
]
return col(ctx, [text(ctx, `THEME STUDIO / active: ${studio.active ? activeTheme(ctx.state).name : ctx.state.options.look}`, { bold: true, color: THEME.head }),
ctx.kit.Box({ key: 'theme-layout', flexDirection: layout.wide ? 'row' : 'column', gap: layout.wide ? 2 : 1, children: layout.wide ? [panel('theme-editor', layout.controls, choices), panel('theme-stage', layout.preview, stage)] : [panel('theme-stage', layout.preview, stage), panel('theme-editor', layout.controls, choices)] }),
], 'themes')
}
@@ -0,0 +1,60 @@
// @ts-check
/**
* Per-tick cost of the animated pictures (header strike and sweep, rotating globe, topology preview, boot checks) for the Classic BBS look
* and the Orbital look, narrow to wide, as the frame loop pays it: picturesOf() plus toRaster() for every picture, at the default 8 fps step.
* Median and p99 per tick, and approximate bytes allocated per tick (heapUsed delta over a batch after gc(); run with NODE_OPTIONS=--expose-gc,
* else that column reads n/a). Classic must cost what it did before the Orbital look existed.
* NODE_OPTIONS=--expose-gc npx -y tsx plugins/ruflo-console/scripts/bench-theme.mjs [ticks]
*/
import { newState } from '../hooks/state.ts'
import { picturesOf } from '../hooks/views/frames.ts'
const N = Math.max(60, Number(process.argv[2]) || 600)
const STEP_MS = 125
const ms = (/** @type {bigint} */ start) => Number(process.hrtime.bigint() - start) / 1e6
const gc = /** @type {(() => void) | undefined} */ (globalThis.gc)
const stat = (/** @type {number[]} */ samples) => {
const sorted = [...samples].sort((a, b) => a - b)
const at = (/** @type {number} */ q) => sorted[Math.min(sorted.length - 1, Math.floor(sorted.length * q))] ?? 0
return `median ${at(0.5).toFixed(3)} ms · p99 ${at(0.99).toFixed(3)} ms`
}
const tick = (/** @type {import('../hooks/state.ts').State} */ state, /** @type {number} */ columns, /** @type {number} */ i) => {
const t = i * STEP_MS / 1000
let cells = 0
for (const [id, picture] of picturesOf(state, columns, 1_000_000 + i * STEP_MS, t)) cells += picture.toRaster(id).columns
return cells
}
console.log(`${N} ticks per case at ${STEP_MS} ms steps (8 fps)`)
for (const look of /** @type {const} */ (['bbs', 'orbital'])) {
for (const view of /** @type {const} */ (['menu', 'swarm', 'themes'])) {
for (const columns of [60, 100, 140]) {
const state = newState({ look, boot: false, fps: 8 })
state.view = view
state.pane.viewAtMs = 1
for (let i = 0; i < 40; i++) tick(state, columns, i)
const samples = []
for (let i = 0; i < N; i++) {
const start = process.hrtime.bigint()
tick(state, columns, i + 40)
samples.push(ms(start))
}
let bytes = 'n/a'
if (gc) {
gc()
const before = process.memoryUsage().heapUsed
for (let i = 0; i < 100; i++) tick(state, columns, i + 700)
bytes = `${Math.round((process.memoryUsage().heapUsed - before) / 100 / 1024)} KiB/tick`
}
console.log(`${look.padEnd(7)} ${view.padEnd(6)} ${String(columns).padStart(3)} cols: ${stat(samples)} · ${bytes}`)
}
}
}
@@ -0,0 +1,76 @@
/** Animated vector replay of theme-demo.mts cell frames: native SVG discrete animation, no scripts, images, video or external assets. Node only. */
import { readFileSync, writeFileSync } from 'node:fs'
import { createHash } from 'node:crypto'
import { resolve } from 'node:path'
const root = resolve(process.argv[2] ?? '/tmp/ruflo-console-demo')
const frames = JSON.parse(readFileSync(resolve(root, 'frames.json'), 'utf8'))
const width = 1208
let height = 120 + Math.max(...frames.map(f => f.rows.length)) * 19
height += height % 2
const fps = 12, duration = frames.length / fps
const esc = s => s.replace(/[&<>"]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c])
const FONT = 'font-family="DejaVu Sans Mono, Menlo, Consolas, monospace"'
// Explicit vector icons avoid platform emoji fonts and missing-glyph boxes.
const ICONS = {
"⛭": "M5 5V3M5 17v-2M1 9h2m4 0h2M2 5l1.5 1.5M7 12.5L8.5 14M2 14l1.5-1.5M7 6.5L8.5 5 M5 6a3 3 0 1 0 0 6a3 3 0 1 0 0-6",
"⟳": "M8 8A3.5 4 0 1 0 8 12M8 4v4H4",
"📟": "M1 5h8v10H1zM2.5 7h5v4h-5zM3 13h1m2 0h1",
"🔎": "M4 5a3 3 0 1 0 0 6a3 3 0 1 0 0-6M6 11l3 4",
"💻": "M2 5h6v8H2zM1 15h8l-1-2H2z",
"🤖": "M1 7h8v8H1zM5 7V4M4 4h2M3 10v1m4-1v1M3 13h4",
"🔧": "M7 4L5 6l1 2 2-1 1-2c1 4-1 5-3 5L2 15l-1-1 4-5C2 7 3 4 7 4z",
"🧩": "M1 6h3V4h2v2h3v3H7v2h2v4H6v-2H4v2H1v-4h2V9H1z",
"📐": "M1 4v12h8zM3 10v4h3z",
"🆕": "M1 5h8v10H1zM3 12V8l4 4V8",
"⚙": "M5 5V3M5 17v-2M1 9h2m4 0h2M2 5l1.5 1.5M7 12.5L8.5 14M2 14l1.5-1.5M7 6.5L8.5 5 M5 6a3 3 0 1 0 0 6a3 3 0 1 0 0-6"
}
const rows = new Map()
const rowId = cells => {
const key = JSON.stringify(cells.map(c => [c.ch, c.fg, c.bg ?? null]))
if (rows.has(key)) return rows.get(key).id
const id = `r${rows.size}`, out = []
for (let start = 0, end; start < cells.length; start = end) {
const color = cells[start].bg
for (end = start + 1; end < cells.length && cells[end].bg === color; end++);
if (color) out.push(`<rect fill="${color}" x="${start * 10}" y="0" width="${(end - start) * 10}" height="19"/>`)
}
// Block glyphs are drawn as rectangles so they stay crisp; other characters share one text run per foreground colour.
let run = null
const flush = () => { if (run) out.push(`<text ${FONT} font-size="16" fill="${run.fg}" x="${run.positions.join(' ')}" y="15" xml:space="preserve">${esc(run.text)}</text>`); run = null }
cells.forEach((c, x) => {
if (c.ch === '█' || c.ch === '▀' || c.ch === '▄') {
flush()
const y = c.ch === '▄' ? 9 : 0, h = c.ch === '▀' ? 9 : c.ch === '▄' ? 10 : 19
out.push(`<rect fill="${c.fg}" x="${x * 10}" y="${y}" width="10" height="${h}"/>`)
} else if (Object.hasOwn(ICONS, c.ch)) {
flush()
out.push(`<path transform="translate(${x * 10},0)" d="${ICONS[c.ch]}" fill="none" stroke="${c.fg}" stroke-width="1" stroke-linecap="round" stroke-linejoin="round"/>`)
} else if (c.ch === ' ' || c.ch === '\ufe0f' || c.ch === '\ufe0e') flush()
else if (run && run.fg === c.fg && run.next === x) { run.text += c.ch; run.positions.push(x * 10); run.next = x + 1 }
else { flush(); run = { fg: c.fg, positions: [x * 10], text: c.ch, next: x + 1 } }
})
flush()
rows.set(key, { id, svg: `<g id="${id}">${out.join('')}</g>` })
return id
}
const label = (s, x, y, fg, size = 16) => `<text ${FONT} font-size="${size}" fill="${fg}" x="${x}" y="${y + size - 1}" xml:space="preserve">${esc(s)}</text>`
const parts = frames.map((f, n) => {
const start = n / frames.length, end = (n + 1) / frames.length
const [times, values] = n === 0 ? [`0;${end.toFixed(12)};1`, 'inline;none;none']
: n === frames.length - 1 ? [`0;${start.toFixed(12)};1`, 'none;inline;inline']
: [`0;${start.toFixed(12)};${end.toFixed(12)};1`, 'none;inline;none;none']
const left = 24 + (116 - f.columns) * 5
return `<g id="frame${n}" display="${n === 0 ? 'inline' : 'none'}"><animate attributeName="display" calcMode="discrete" values="${values}" keyTimes="${times}" dur="${duration}s" repeatCount="indefinite"/>`
+ `<rect fill="${f.bg}" width="${width}" height="${height}"/>`
+ label('RUFLO / COMPLETE THEME WORKFLOW', 24, 16, f.accent) + label(f.caption, 24, 45, '#a8b2bd', 12)
+ `<path stroke="${f.accent}" d="M24 68H${width - 24}"/>`
+ f.rows.map((row, y) => `<use href="#${rowId(row)}" x="${left}" y="${78 + y * 19}"/>`).join('')
+ `<path stroke="${f.accent}" stroke-width="2" d="M24 ${height - 35}H${(24 + (width - 48) * (n + 1) / frames.length).toFixed(4)}"/>`
+ label('RENDERER DEMO / real UI actions + disk persistence / native host and AI generation unverified', 24, height - 23, '#a8b2bd', 12) + '</g>'
})
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}" role="img" aria-labelledby="title desc"><title id="title">Ruflo console theme workflow</title><desc id="desc">${Math.round(duration)} second replay of actual renderer frames. Boot, six presets, customization, persistence, JSON import and resize. Native host and AI provider execution are unverified.</desc><defs>${[...rows.values()].map(r => r.svg).join('')}</defs>${parts.join('')}</svg>`
const file = resolve(root, 'ruflo-console-demo.svg')
writeFileSync(file, svg)
console.log(JSON.stringify({ file, bytes: Buffer.byteLength(svg), frames: frames.length, seconds: duration, rowSymbols: rows.size, sha256: createHash('sha256').update(svg).digest('hex') }))
+2 -2
View File
@@ -11,9 +11,9 @@ step() { printf "→ %s ... " "$1"; }
ok() { printf "PASS\n"; PASS=$((PASS+1)); }
bad() { printf "FAIL: %s\n" "$1"; FAIL=$((FAIL+1)); }
step "1. plugin.json declares ruflo-console 0.42.7"
step "1. plugin.json declares ruflo-console 0.43.0"
grep -q '"name": "ruflo-console"' "$ROOT/.claude-plugin/plugin.json" \
&& grep -q '"version": "0.42.7"' "$ROOT/.claude-plugin/plugin.json" && ok || bad "name/version"
&& grep -q '"version": "0.43.0"' "$ROOT/.claude-plugin/plugin.json" && ok || bad "name/version"
step "2. hooks.json names exactly one module and no classic hook commands"
grep -q '"modules": \["./register.ts"\]' "$HOOKS/hooks.json" && ! grep -q '"command"' "$HOOKS/hooks.json" \
@@ -0,0 +1,121 @@
/** Reproducible renderer workflow demo. No native host or model invocation is simulated. */
import { writeFileSync, readFileSync, mkdirSync, mkdtempSync } from 'node:fs'
import { resolve, join } from 'node:path'
import { tmpdir } from 'node:os'
import assert from 'node:assert/strict'
import { newState } from '../hooks/state'
import { themesOf, themeActions, activeTheme, loadThemes, THEME_PRESETS } from '../hooks/themes'
import { paneView } from '../hooks/views/pane'
import { setBootChecks } from '../hooks/boot-checks'
import { selfCheckResults } from '../hooks/self-check'
import { picturesOf } from '../hooks/views/frames'
import { THEME } from '../hooks/views/common'
const output=process.argv[2] ? resolve(process.argv[2]) : mkdtempSync(join(tmpdir(),'ruflo-console-demo-'))
mkdirSync(output,{recursive:true})
const storePath=resolve(output,'demo-session.json')
writeFileSync(storePath,'{}',{flag:'wx'})
const host:any={storeGet:async(key:string)=>JSON.parse(readFileSync(storePath,'utf8'))[key],storeSet:async(key:string,value:unknown)=>{const data=JSON.parse(readFileSync(storePath,'utf8'));data[key]=value;writeFileSync(storePath,JSON.stringify(data,null,2))},invalidate:()=>{}}
const fresh=()=>{const s=newState({look:'orbital',boot:false});Object.assign(s.pane,{rows:70,columns:116,isOpen:true,isShown:true,isFocused:true});s.view='menu';s.cwd='/demo/ruflo';return s}
let state=fresh(),columns=116
let actions=themeActions(state,host,()=>{throw Error('AI provider not connected in this renderer demo')})
setBootChecks(selfCheckResults())
const kit=Object.fromEntries(['Box','Text','Button','Input','Raster'].map(type=>[type,(props:any)=>({type,props})]))
const names:any={success:'#72c79b',error:'#ff6868',warning:'#e3ba74',suggestion:'#c6cbc8',claude:'#f06449'}
type C={ch:string,fg:string,bg?:string};type R=C[][]
let focus=''
const line=(s:string,fg:string,bg?:string):R=>[[...s].map(ch=>({ch,fg,bg}))]
const spaces=(n:number)=>Array.from({length:Math.max(0,n)},()=>({ch:' ',fg:THEME.info}))
function render(el:any,avail=columns):R {
if(!el)return []
if(typeof el==='string')return line(el,THEME.info)
const p=el.props;if(!p||p.display==='none')return []
if(el.type==='Raster'){const b=Buffer.from(p.cells,'base64');return Array.from({length:p.rows},(_,y)=>Array.from({length:p.columns},(_,x)=>{const at=(y*p.columns+x)*12;return {ch:String.fromCodePoint(b.readUInt32LE(at)),fg:'#'+(b.readUInt32LE(at+4)&0xffffff).toString(16).padStart(6,'0'),bg:'#'+(b.readUInt32LE(at+8)&0xffffff).toString(16).padStart(6,'0')}}))}
if(el.type==='Text')return line(String(p.children??'').slice(0,avail),names[p.color]??p.color??THEME.info,p.backgroundColor)
if(el.type==='Button')return line((p.plain?p.label:'['+p.label+'] ')??'',p.key===focus?'#ffffff':THEME.info,p.key===focus?'#41404c':undefined)
if(el.type==='Input')return [...line(p.label,THEME.head),...line(('> '+p.placeholder).slice(0,avail),'#83948f')]
const nodes=(Array.isArray(p.children)?p.children:[p.children]).filter(Boolean)
const border=p.borderStyle?1:0,pad=p.paddingX??0,width=Math.min(avail,p.width??avail),inside=Math.max(1,width-2*border-2*pad)
const kids=nodes.map((n:any)=>render(n,inside));const widths=kids.map(k=>Math.max(0,...k.map(r=>r.length)))
if(p.flexDirection==='row'&&p.flexWrap!=='wrap'){
const shrink=nodes.findIndex((n:any)=>n.props?.flexGrow)
const target=shrink>=0?shrink:nodes.findLastIndex((n:any)=>n.props?.wrap==='truncate-end')
if(target>=0){const room=Math.max(1,inside-widths.reduce((sum,w,i)=>sum+(i===target?0:w),0)-Math.max(0,kids.length-1)*(p.gap??0));kids[target]=render(nodes[target],room);widths[target]=Math.max(0,...kids[target]!.map(r=>r.length))}
}
let rows:R
if(p.flexDirection!=='row')rows=kids.flatMap((k,i)=>[...k,...Array.from({length:i<kids.length-1?p.gap??0:0},()=>[])])
else if(p.flexWrap==='wrap'){
rows=[];let current:R=[];let used=0
kids.forEach((child,i)=>{
const w=widths[i]!,gap=used>0?p.gap??0:0
if(used>0&&used+gap+w>inside){rows.push(...current);current=[];used=0}
const space=used>0?p.gap??0:0
const h=Math.max(current.length,child.length)
current=Array.from({length:h},(_,y)=>[...(current[y]??spaces(used)),...spaces(space),...(child[y]??[]),...spaces(w-(child[y]?.length??0))]);used+=space+w
});rows.push(...current)
} else {
const gap=p.gap??0;let remaining=inside-widths.reduce((a,b)=>a+b,0)-Math.max(0,kids.length-1)*gap
const grow=nodes.findIndex((n:any)=>n.props?.flexGrow);if(grow>=0&&remaining>0)widths[grow]+=remaining
const height=Math.max(0,...kids.map(k=>k.length))
rows=Array.from({length:height},(_,y)=>kids.flatMap((k,i)=>[...(k[y]??[]),...spaces(widths[i]-(k[y]?.length??0)),...spaces(i<kids.length-1?gap:0)]))
}
if(border){const w=p.width?width:Math.min(width,Math.max(0,...rows.map(r=>r.length))+2+2*pad);const color=names[p.borderColor]??p.borderColor??THEME.head;const edge=(ch:string)=>({ch,fg:color});rows=rows.map(r=>[edge('│'),...spaces(pad),...r.slice(0,w-2-pad*2),...spaces(w-2-pad-r.length),edge('│')]);rows=[...line('┌'+'─'.repeat(Math.max(0,w-2))+'┐',color),...rows,...line('└'+'─'.repeat(Math.max(0,w-2))+'┘',color)]}
return [...Array.from({length:p.marginTop??0},()=>[]),...rows]
}
const noop:any=new Proxy(()=>undefined,{get:()=>noop})
const act=new Proxy(noop,{get:(_,key)=>key==='themes'?actions:key==='view'?(view:any)=>{state.view=view;state.pane.viewAtMs=clock}:noop})
const flat=(node:any):any[]=>node&&typeof node==='object'?[node,...(Array.isArray(node.props?.children)?node.props.children.flatMap(flat):flat(node.props?.children))]:[]
let clock=1
const draw=()=>paneView({state,kit,act,columns,nowMs:clock,pictures:picturesOf(state,columns,clock,clock)} as any)
const flush=async()=>{await new Promise(resolve=>setTimeout(resolve,0))}
const evidence:string[]=[]
const click=async(key:string)=>{const el=flat(draw()).find(n=>n.props?.key===key);assert.equal(typeof el?.props.onPress,'function',key);focus=key;el.props.onPress();await flush()}
const submit=async(key:string,value:string)=>{const el=flat(draw()).find(n=>n.props?.key===key);assert.equal(typeof el?.props.onSubmit,'function',key);focus=key;el.props.onSubmit(value);await flush()}
const frames:any[]=[]
function capture(seconds:number,caption:string){
for(let i=0;i<seconds*12;i++){
const rows=render(draw());assert.ok(rows.every(r=>r.length<=columns),`overflow at ${columns}: ${Math.max(...rows.map(r=>r.length))}`)
frames.push({rows,caption,bg:activeTheme(state).palette.background,accent:THEME.head,columns});clock+=1000/12
}
focus=''
}
state.options.boot=true;state.pane.bootAtMs=1
capture(3,'01 / BOOT / actual local self checks')
state.options.boot=false;state.pane.viewAtMs=clock
capture(3,'02 / MAIN MENU / full console navigation')
await click('menu-go-themes');assert.equal(state.view,'themes');evidence.push('Main menu opens Theme Studio')
for(const preset of THEME_PRESETS){
await click(`theme-preset-${preset.id}`)
assert.equal(activeTheme(state).name,preset.theme.name)
capture(2,`03 / LOAD PRESET / ${preset.theme.name}`)
}
evidence.push('All six bundled palettes applied through visible buttons')
await click('theme-preset-synthwave')
await submit('theme-name','Night Shift')
await submit('theme-color','#79dfff')
assert.equal(activeTheme(state).name,'Synthwave');capture(2,'04 / CUSTOMIZE / draft leaves active palette unchanged')
await click('theme-tab-motion');await click('theme-speed-0.5');capture(2,'05 / MOTION / half speed globe and orchestration')
await click('theme-save');assert.equal(activeTheme(state).name,'Night Shift');evidence.push('Custom color and motion persisted to disk')
capture(2,'06 / SAVE / custom Night Shift palette applied')
state=fresh();actions=themeActions(state,host,()=>{});await loadThemes(state,host);state.pane.viewAtMs=clock
assert.equal(activeTheme(state).name,'Night Shift');assert.equal(activeTheme(state).motion.speed,0.5);assert.equal(activeTheme(state).palette.head,'#79dfff');evidence.push('Fresh state restores custom palette and motion from disk')
capture(3,'07 / REOPEN / saved selection restored from disk')
await click('menu-go-themes');await click('theme-tab-generate')
const imported={...THEME_PRESETS[0]!.theme,name:'Imported Arctic'}
await submit('theme-import',JSON.stringify(imported));await click('theme-save');assert.equal(activeTheme(state).name,'Imported Arctic')
evidence.push('Portable JSON imports through input and persists')
capture(2,'08 / IMPORT JSON / portable Arctic preset applied')
await click('theme-tab-motion');state.options.fps=0
const frozen=picturesOf(state,columns,clock,clock).get('title')!.encode()
assert.equal(frozen,picturesOf(state,columns,clock+1000,clock+1000).get('title')!.encode());evidence.push('Reduced motion keeps identical header frames')
capture(2,'09 / REDUCED MOTION / fps 0 freezes graphics')
state.options.fps=12;columns=80;state.pane.columns=80
capture(3,'10 / RESIZE / 80 columns, stacked editor and preview')
columns=116;state.pane.columns=116
capture(2,'11 / RESIZE / 116 columns, editor beside preview')
evidence.push('Renderer bounds verified at 80 and 116 columns; native layout unverified')
await click('tab-menu');assert.equal(state.view,'menu');assert.equal(activeTheme(state).name,'Imported Arctic');capture(2,'12 / MAIN MENU / imported theme retained')
evidence.push('Return to main menu retains imported theme')
writeFileSync(resolve(output,'frames.json'),JSON.stringify(frames))
writeFileSync(resolve(output,'receipt.json'),JSON.stringify({mode:'renderer workflow with actual view handlers and filesystem storage',nativeHost:false,aiProviderInvoked:false,frames:frames.length,fps:12,seconds:frames.length/12,evidence},null,2))
console.log(JSON.stringify({output,frames:frames.length,maxRows:Math.max(...frames.map(f=>f.rows.length)),evidence}))
@@ -0,0 +1,17 @@
---
name: generate-console-theme
description: Generate a data-only animated theme preset for Ruflo Console Theme Studio. Use when the user requests a new console color palette, cyberpunk theme, or variation of Orbital globe, stars, and swarm animation in Claude or Codex.
allowed-tools: Read
---
# Generate a Ruflo console theme
Create one preset from the user's visual direction. Use the current assistant, Claude or Codex, to generate the data; no API key, subprocess, or second model is required.
1. Read [the preset contract and example](references/preset.md).
2. Choose a short theme name and six readable colors. Translate the requested mood into the palette, animation speed, and optional stars, globe, and topology. Reuse the existing Orbital renderer; do not promise new animation geometry from a preset.
3. Keep text and status colors legible against the background. Aim for at least 4.5:1 contrast for every foreground role. Keep failures visually distinct from successes and warnings; preserve the host's status labels. Prefer calm motion and avoid flashing. Honor a request for less visual activity by disabling decorative layers and lowering speed; the host's zero-FPS setting remains authoritative.
4. Check the exact keys, types, bounds, six-digit hex colors, and name length against the contract. Never include scripts, CSS, URLs, escape sequences, extra keys, or invented telemetry. Theme settings must not change boot checks, agent states, or reported failures.
5. Return exactly one JSON object with no Markdown fences or surrounding explanation. Theme Studio accepts the object in its import field; the user can review and save/select the preset there. Do not claim it has been installed or activated merely because JSON was generated.
Use the user's stated preferences directly. When details are absent, choose a dark background, warm readable status colors, all three decorative layers enabled, and speed 1. Do not ask for credentials or make external calls to produce a preset.
@@ -0,0 +1,4 @@
interface:
display_name: "Ruflo Theme Generator"
short_description: "Generate animated Ruflo console theme presets"
default_prompt: "Use $generate-console-theme to create a readable cyberpunk Ruflo console theme with calm globe and swarm motion."
@@ -0,0 +1,46 @@
# Theme preset contract
Return exactly this version 1 object shape. All keys are required; omit additional keys.
| Field | Value |
| --- | --- |
| `version` | Integer `1` |
| `name` | A trimmed name of 1 to 40 characters; start with a Unicode letter or number, then use only Unicode letters, numbers, spaces, dots, underscores, or hyphens |
| `palette.head` | Heading, accent, and border color |
| `palette.ok` | Success color |
| `palette.bad` | Failure color |
| `palette.warn` | Warning color |
| `palette.info` | Main information text color |
| `palette.background` | Background color |
| Every palette value | String matching `#RRGGBB` with six hexadecimal digits |
| `motion.speed` | Finite number from `0.25` through `2`, inclusive; `1` is the standard rate |
| `motion.stars` | Boolean enabling decorative stars |
| `motion.globe` | Boolean enabling the decorative globe |
| `motion.topology` | Boolean enabling decorative topology motion |
These are palette and motion parameters for existing responsive Orbital visuals. They do not add arbitrary renderers, change refresh rate preferences, or provide system health data. The host must preserve reduced-motion settings and actual operational state. Disabled decoration must not hide the live topology's operational information.
## Example: calm violet observatory
```json
{
"version": 1,
"name": "Violet Observatory",
"palette": {
"head": "#C5A3FF",
"ok": "#83D9AB",
"bad": "#FF8C94",
"warn": "#F2CE7E",
"info": "#DBDDE8",
"background": "#0C0D16"
},
"motion": {
"speed": 0.65,
"stars": true,
"globe": true,
"topology": true
}
}
```
Treat the example as a schema illustration; vary its design to match the user's request.
@@ -59,7 +59,7 @@ describe('the cyberpunk log', () => {
expect(text).toContain('RUV.NET // RUVECTOR CONSTELLATION')
expect(text).toContain('rUv · ruflo v0.26.0 · abc123')
expect(text).toContain('ruvector')
expect(text).toMatch(/\[WARN\] READY · 31 of 31 areas verified · \d+ stars? dark/)
expect(text).toMatch(/\[WARN\] READY · 32 of 32 areas verified · \d+ stars? dark/)
expect(text).not.toContain('ALL STARS ALIGNED')
})
@@ -76,7 +76,7 @@ describe('the cyberpunk log', () => {
const failed = textOf(bootPicture('p', 90, 6000, 10, 10, rowsFor, failing, bootFacts(lit, '1', '')))
expect(failed).not.toContain('ALL STARS ALIGNED')
expect(failed).toMatch(/\[FAIL\] READY · 30 of 31 areas verified · 1 failed/)
expect(failed).toMatch(/\[FAIL\] READY · 31 of 32 areas verified · 1 failed/)
})
it('shows the easter egg only in its window, and it decodes to rUv', () => {
@@ -97,7 +97,7 @@ describe('the cyberpunk log', () => {
it('falls back to the plain log in a narrow or short pane', () => {
const facts = bootFacts(withPlugins([]), '1', '')
expect(textOf(bootPicture('p', 44, 6000, 10, 10, rowsFor, allOk, facts))).toContain('[ OK ] READY 31 of 31 areas verified')
expect(textOf(bootPicture('p', 44, 6000, 10, 10, rowsFor, allOk, facts))).toContain('[ OK ] READY 32 of 32 areas verified')
expect(textOf(bootPicture('p', 90, 6000, 10, 10, BOOT_ROWS + 6, allOk, facts))).not.toContain('RUV.NET')
})
})
+2 -1
View File
@@ -139,9 +139,10 @@ describe('BBS look', () => {
expect(on.encode()).not.toBe(off.encode())
})
it('bbs is the default look; plain is the only other value', () => {
it('bbs stays the default; plain and orbital are opt-in', () => {
expect(optionsOf(undefined).look).toBe('bbs')
expect(optionsOf({ look: 'plain' } as never).look).toBe('plain')
expect(optionsOf({ look: 'orbital' } as never).look).toBe('orbital')
expect(optionsOf({ look: 'neon' } as never).look).toBe('bbs')
})
})
+2 -2
View File
@@ -9,11 +9,11 @@ export const CONSOLE_CONFIG = JSON.stringify({
refreshSeconds: { type: 'number', title: 'Disk refresh (seconds)', description: 'How often ruflo’s files are re-read (2 to 60).', default: 3 },
fps: { type: 'number', title: 'Animation frames per second', description: 'Frame cap while the pane is shown (0 to 12).', default: 8 },
panel: { type: 'string', title: 'Cockpit pane', description: 'auto opens the cockpit at session start.', default: 'auto', options: ['auto', 'command', 'off'] },
look: { type: 'string', title: 'Look', description: 'bbs draws ANSI-BBS art; plain is text only.', default: 'bbs', options: ['bbs', 'plain'] },
look: { type: 'string', title: 'Look', description: 'bbs draws ANSI-BBS art; plain is text only.', default: 'bbs', options: ['bbs', 'plain', 'orbital'] },
boot: { type: 'boolean', title: 'Boot screen', description: 'Play the dial-up boot screen when the cockpit opens.', default: true },
},
inputs: { cli: 'npx-offline', refreshSeconds: '', fps: '', panel: 'auto', look: 'bbs', boot: 'true' },
choices: { cli: ['npx-offline', 'npx', 'ruflo', 'claude-flow'], panel: ['auto', 'command', 'off'], look: ['bbs', 'plain'], boot: ['true', 'false'] },
choices: { cli: ['npx-offline', 'npx', 'ruflo', 'claude-flow'], panel: ['auto', 'command', 'off'], look: ['bbs', 'plain', 'orbital'], boot: ['true', 'false'] },
configured: [],
unconfigured: ['cli', 'refreshSeconds', 'fps', 'panel', 'look', 'boot'],
})
+2 -2
View File
@@ -7,12 +7,12 @@ const RESERVED = ['p', 'x', 'r', 'h', 'j', 'k', 'y', 'n', 'o']
describe('main nav hotkeys', () => {
it('every view has one (a single digit or lowercase letter) or none (reached by name), and no two share one', () => {
// Every letter is a view key or reserved, so Sandbox has no key: it is reached from the menu, the nav or by typing `sandbox`.
// Every letter is a view key or reserved, so Sandbox and Theme Studio have no key: they are reached from the menu, the nav or by typing `sandbox` or `themes`.
const keys = VIEWS.map(view => view.key).filter(key => key !== '')
expect(keys.every(key => /^[0-9a-z]$/.test(key))).toBe(true)
expect(new Set(keys).size).toBe(keys.length)
expect(VIEWS.filter(view => view.key === '').map(view => view.id)).toEqual(['workflows', 'room', 'sandbox', 'adrs', 'whatsnew'])
expect(VIEWS.filter(view => view.key === '').map(view => view.id)).toEqual(['workflows', 'room', 'sandbox', 'adrs', 'whatsnew', 'themes'])
})
it('none takes a key the footer, the confirm row, scrolling or the menu prompt owns', () => {
+203
View File
@@ -0,0 +1,203 @@
import { afterEach, describe, expect, it } from 'vitest'
import { optionsOf } from '../hooks/state'
import { isOrbital, setLook, THEME } from '../hooks/views/common'
import { withCards } from '../hooks/views/card'
import { HEADS, mark } from '../hooks/views/marks'
import { parseConfig, setOption, settingsOf } from '../hooks/settings'
import { newState } from '../hooks/state'
import { CONSOLE_CONFIG } from './fixtures/settings'
afterEach(() => setLook('plain'))
describe('orbital theme', () => {
it('uses square red cards and restores the original theme on switch', () => {
setLook('orbital')
expect(isOrbital()).toBe(true)
expect(THEME.head).toBe('#f06449')
const kit = { Box: (props: object) => ({ props }), Text: (props: object) => ({ props }) } as never
const head = mark(HEADS, { props: { children: 'metrics' } })
const tree = withCards(kit).Box({ flexDirection: 'column', children: [head] } as never) as unknown as { props: { children: { props: object }[] } }
expect(tree.props.children[0]?.props).toMatchObject({ borderStyle: 'single', borderColor: '#f06449' })
setLook('bbs')
expect(isOrbital()).toBe(false)
expect(THEME.head).toBe('#ff2a6d')
expect(optionsOf(undefined).look).toBe('bbs')
})
it('accepts the option through the existing settings path', () => {
const state = newState({})
const config = parseConfig('ruflo-console', CONSOLE_CONFIG)
expect(config).not.toBeNull()
settingsOf(state).configs.set('ruflo-console', config!)
expect(setOption(state, 'ruflo-console', 'look', 'orbital', () => undefined)?.stdin).toBe('{"look":"orbital"}')
expect(setOption(state, 'ruflo-console', 'look', 'unknown', () => undefined)).toBeNull()
})
})
import { orbitalGlobe, orbitalHeader, orbitalBoot, orbitalMasthead } from '../hooks/gfx/orbital'
import { isBooting, VIEWS } from '../hooks/state'
import { picturesOf } from '../hooks/views/frames'
import type { Grid } from '../hooks/gfx/raster'
const gridText = (grid: Grid) => Array.from({ length: grid.rows }, (_, y) => Array.from({ length: grid.columns }, (_, x) => String.fromCodePoint(grid.glyph(x, y))).join('')).join('\n')
describe('orbital motion', () => {
it('turns an ASCII globe and returns to the same frame after one revolution', () => {
const initial = orbitalGlobe(38, 14, 0)
expect(gridText(initial)).not.toBe(gridText(orbitalGlobe(38, 14, 3000)))
expect(initial.cells).toEqual(orbitalGlobe(38, 14, 12000).cells)
expect(gridText(initial)).toMatch(/^[\x20-\x7e\n]+$/)
expect(gridText(initial)).toContain('#')
expect(orbitalGlobe(38, 14, NaN).cells).toEqual(initial.cells)
})
it('keeps header dimensions stable while its pulse and scan move', () => {
for (const columns of [20, 44, 72, 200]) {
const first = orbitalHeader('overview', columns, 0)
const next = orbitalHeader('overview', columns, 480)
expect([next.columns, next.rows]).toEqual([columns, 4])
expect(next.cells).not.toEqual(first.cells)
expect(gridText(next).split('\n')[0]).toBe(gridText(first).split('\n')[0])
}
})
it('uses actual boot checks without inventing successes or progress', () => {
expect(gridText(orbitalBoot('project', 72, 0))).toContain('Self-check: pending')
const result = orbitalBoot('project', 72, 1000, [{ area: 'one', ok: true, problems: [] }, { area: 'two', ok: false, problems: ['unavailable'] }])
expect(gridText(result)).toContain('Self-check: 1 passed / 1 failed')
expect(gridText(result)).not.toContain('%')
})
it('bounds the intro and skips it when motion or boot is disabled', () => {
const state = newState({})
state.options.look = 'orbital'
state.options.boot = true
state.options.fps = 12
state.pane.bootAtMs = 1000
expect(isBooting(state, 999)).toBe(false)
expect(isBooting(state, 2499)).toBe(true)
expect(isBooting(state, 6999)).toBe(true)
expect(isBooting(state, 7000)).toBe(false)
state.snapshot = {} as NonNullable<typeof state.snapshot>
expect(isBooting(state, 2500)).toBe(false)
state.options.fps = 0
expect(isBooting(state, 1100)).toBe(false)
state.options.fps = 12
state.options.boot = false
expect(isBooting(state, 1100)).toBe(false)
})
it('provides an animated header on every page and a stable header at fps zero', () => {
const state = newState({})
state.options.look = 'orbital'
state.options.boot = false
for (const view of VIEWS) for (const width of [60, 116, 200]) {
state.view = view.id
const key = view.id === 'menu' ? 'header' : 'title'
state.options.fps = 12
expect(picturesOf(state, width, 1000, 1000).get(key)?.cells).not.toEqual(picturesOf(state, width, 2000, 2000).get(key)?.cells)
state.options.fps = 0
const still = picturesOf(state, width, 1000, 1000).get(key)
expect(still).toBeDefined()
expect(still!.cells).toEqual(picturesOf(state, width, 2000, 2000).get(key)!.cells)
}
})
})
it('shows actual failures immediately while success labels animate', () => {
const checks = [{ area: 'Swarm', ok: true, problems: [] }, { area: 'Security', ok: false, problems: ['missing action'] }]
const first = gridText(orbitalBoot('project', 72, 0, checks))
expect(first).toContain('[FAIL] SECURITY / missing action')
expect(first).toContain('[PASS]')
expect(first).not.toContain('[PASS] SWARM')
expect(gridText(orbitalBoot('project', 72, 700, checks))).toContain('[PASS] SWARM')
expect(gridText(orbitalBoot('project', 72, 0, []))).toContain('[N/A] No module checks reported')
})
it('gives swarm control its own bounded routing animation', () => {
for (const width of [20, 44, 72]) {
const first = orbitalHeader('swarm control', width, 0)
const later = orbitalHeader('swarm control', width, 500)
expect([first.columns, first.rows]).toEqual([width, width >= 56 ? 16 : 4])
expect(first.cells).not.toEqual(later.cells)
if (width >= 56) expect(gridText(first)).toContain('◈')
expect(gridText(first)).not.toContain('agents online')
}
})
import { topologyPicture } from '../hooks/gfx/pictures'
it('preserves real topology labels and statuses in the depth view', () => {
const model = { topology: 'hierarchical', nodes: [
{ id: 'hub', label: 'queen', status: 'leader', isLeader: true },
{ id: 'a', label: 'worker', status: 'busy', isLeader: false },
{ id: 'b', label: 'down', status: 'offline', isLeader: false },
] }
const before = JSON.stringify(model)
const first = topologyPicture(model, 72, 16, 0, true)
const next = topologyPicture(model, 72, 16, 1200, true)
for (const label of ['queen', 'worker', 'down', '◈', '◉', '×']) expect(gridText(next)).toContain(label)
expect(first.cells).not.toEqual(next.cells)
expect(JSON.stringify(model)).toBe(before)
})
it('fits narrow and short allocations without hiding failure totals', () => {
const checks = [{ area: 'Security', ok: false, problems: ['broken registry'] }]
for (const columns of [1, 8, 12, 20, 32, 44, 48, 55, 56, 72, 120, 200]) {
for (const rows of [1, 2, 4, 8, 16, 24, 30, 60]) {
const boot = orbitalBoot('very long project name', columns, 1000, checks, rows)
const header = orbitalHeader('swarm control', columns, 1000, rows)
for (const grid of [boot, header]) {
expect(grid.columns).toBeLessThanOrEqual(columns)
expect(grid.rows).toBeLessThanOrEqual(rows)
expect(grid.cells.length).toBe(grid.columns * grid.rows * 3)
}
if (columns >= 12 && rows >= 2) expect(gridText(boot)).toMatch(/1 FAIL|1 failed/)
}
}
})
it('reserves icon room and switches layouts as the pane is resized', () => {
const state = newState({})
state.options.look = 'orbital'
state.options.boot = false
state.view = 'swarm'
for (const [columns, rows] of [[160, 50], [44, 24], [72, 20], [200, 60], [20, 10]]) {
state.pane.rows = rows!
const header = picturesOf(state, columns!, 1000, 1000).get('title')!
expect(header.columns).toBeLessThanOrEqual(Math.max(1, columns! < 40 ? columns! : columns! - 16))
expect(header.rows).toBeLessThanOrEqual(Math.max(1, rows! - 12))
}
})
it('keeps the original block brand after boot with bounded moving art and optional globe', async () => {
const { ORBITAL_THEME } = await import('../hooks/themes')
for (const columns of [1, 8, 19, 28, 44, 72, 78, 100, 120, 200]) {
for (const rows of [1, 2, 4, 8]) {
const first = orbitalMasthead('Main Menu', columns, 0, rows)
const next = orbitalMasthead('Main Menu', columns, 1400, rows)
expect(first.columns).toBeLessThanOrEqual(columns)
expect(first.rows).toBeLessThanOrEqual(rows)
expect([next.columns, next.rows]).toEqual([first.columns, first.rows])
if (columns >= 19 && rows >= 2) expect(gridText(first)).toMatch(/[█▀▄]/)
if (columns >= 19 && rows >= 4) expect(first.cells).not.toEqual(next.cells)
}
}
const off = { ...ORBITAL_THEME, motion: { ...ORBITAL_THEME.motion, globe: false, topology: false } }
const grid = orbitalMasthead('Theme Studio', 100, 0, 8, off)
expect(gridText(grid)).toContain('THEME STUDIO')
expect(gridText(grid)).toContain('█')
expect(gridText(grid)).not.toContain('#')
expect(grid.cells).not.toEqual(orbitalMasthead('Theme Studio', 100, 0).cells)
})
describe('Orbital header name', () => {
it('says RUFLO in the wide masthead and the narrow fallback, never another name', () => {
const text = (columns: number) => {
const grid = orbitalMasthead('MAIN MENU', columns, 0)
return Array.from({ length: grid.rows }, (_, y) => Array.from({ length: grid.columns }, (_, x) => String.fromCodePoint(grid.glyph(x, y) || 32)).join('')).join('\n')
}
expect(text(140)).toContain('RUFLO / AGENT SWARM CONSOLE')
expect(text(140)).not.toMatch(/RUVNET/)
expect(text(60)).not.toMatch(/RUVNET/)
})
})
@@ -52,6 +52,29 @@ function order(view: ViewId, columns: number, rows: number): { title: number; ta
afterEach(() => setLook('plain'))
describe('the pane\'s order', () => {
it('keeps animated Orbital branding ahead of navigation on every main path', async () => {
const { picturesOf } = await import('../hooks/views/frames')
for (const view of ['menu', 'themes', 'swarm'] as const) {
for (const placement of ['dock', 'inline'] as const) {
for (const [columns, rows] of [[60, 18], [116, 60], [200, 80]]) {
const state = newState({ look: 'orbital', boot: false })
state.view = view
Object.assign(state.pane, { placement, columns, rows })
const pictures = picturesOf(state, columns!, 1000, 1000)
const name = view === 'menu' ? 'header' : 'title'
const grid = pictures.get(name)!
expect(Array.from(grid.cells).some((cell, i) => i % 3 === 0 && [0x2588, 0x2580, 0x2584].includes(cell))).toBe(true)
const nodes = flat(paneView({ kit, state, nowMs: 1000, columns, pictures, act } as unknown as Ctx))
const brand = nodes.findIndex(node => node.kind === 'Raster' && node.props.key === name)
const tabs = nodes.findIndex(node => node.props.key === 'tabs')
expect(brand).toBeGreaterThanOrEqual(0)
expect(brand).toBeLessThan(tabs)
for (const key of ['pane-icons', 'footer']) expect(nodes.some(node => node.props.key === key)).toBe(true)
}
}
}
})
it('leads with the title and then the tabs in the compact layout', () => {
const { title, tabs } = order('swarm', 100, 8)
@@ -54,7 +54,7 @@ const NOISE = /\[object Object\]|\bundefined\b|\bNaN\b/
afterAll(() => setLook('plain'))
describe('every page draws', () => {
for (const look of ['bbs', 'plain'] as const) {
for (const look of ['bbs', 'plain', 'orbital'] as const) {
for (const columns of [44, 60, 100, 160]) {
it(`in the ${look} look at ${columns} columns, empty and busy`, async () => {
setLook(look)
@@ -0,0 +1,267 @@
/**
* Theme Studio, adversarial: what it does with data it did not write (an AI's JSON, a corrupted or hostile saved store) and what a theme can
* never put on the model-facing screen. Colours are six-digit hex only, names are a short allow-list, nothing unknown survives.
* Run with: npx vitest run plugins/ruflo-console/tests/themes-adversarial.spec.ts
*/
import { describe, expect, it, vi } from 'vitest'
import type { Host } from '../hooks/host'
import { activeTheme, loadThemes, ORBITAL_THEME, parseTheme, THEME_STORE_KEY, themeActions, themeFromText, themesOf } from '../hooks/themes'
import { newState, type Actions } from '../hooks/state'
import { viewText } from '../hooks/views/pane'
const flush = async () => { await new Promise(resolve => setTimeout(resolve, 0)) }
const good = () => JSON.parse(JSON.stringify(ORBITAL_THEME)) as typeof ORBITAL_THEME
const hostOf = (store = new Map<string, unknown>()) => ({ storeGet: vi.fn(async (key: string) => store.get(key)), storeSet: vi.fn(async (key: string, value: unknown) => { store.set(key, value) }), invalidate: vi.fn() }) as unknown as Host & { storeSet: ReturnType<typeof vi.fn> }
const act: Actions = (() => {
const proxy: unknown = new Proxy(() => undefined, { get: (_target, key) => (key === 'then' ? undefined : proxy), apply: () => undefined })
return proxy as Actions
})()
// eslint-disable-next-line no-control-regex -- the point of the test: ESC, C0, DEL, C1 and the bidi / invisible format characters.
const UNSAFE = /[\u0000-\u001f\u007f-\u009f​-‏‪-‮⁦-⁩]/
describe('Theme Studio import is a closed schema', () => {
const cases: [string, unknown][] = [
['an extra key at the top', { ...good(), extra: 1 }],
['an extra key in the palette', { ...good(), palette: { ...good().palette, accent: '#ffffff' } }],
['an extra key in motion', { ...good(), motion: { ...good().motion, fps: 60 } }],
['a missing palette role', { ...good(), palette: { head: '#ffffff', ok: '#ffffff', bad: '#ffffff', warn: '#ffffff', info: '#ffffff' } }],
['version 2', { ...good(), version: 2 }],
['a numeric name', { ...good(), name: 5 }],
['an empty name', { ...good(), name: '' }],
['a 41 character name', { ...good(), name: 'a'.repeat(41) }],
['a name starting with a space', { ...good(), name: ' Orbital' }],
['a name with ESC', { ...good(), name: 'Neo\u001b[2J' }],
['a name with a newline', { ...good(), name: 'Neo\nTwo' }],
['a name with NUL', { ...good(), name: 'Neo\u0000' }],
['a name with a right-to-left override', { ...good(), name: 'Neo‮Two' }],
['a name with a zero width joiner', { ...good(), name: 'Neo‍Two' }],
['a name with a C1 control', { ...good(), name: 'Neo\u009bTwo' }],
['a name with markup', { ...good(), name: 'Neo<b>' }],
['a name with a slash', { ...good(), name: 'a/b' }],
['a colour with an escape', { ...good(), palette: { ...good().palette, head: '#ff00\u001b' } }],
['a colour name', { ...good(), palette: { ...good().palette, head: 'red' } }],
['a three digit colour', { ...good(), palette: { ...good().palette, head: '#fff' } }],
['an eight digit colour', { ...good(), palette: { ...good().palette, head: '#ff0000ff' } }],
['a colour with CSS', { ...good(), palette: { ...good().palette, head: 'rgb(1,2,3)' } }],
['a colour that is a number', { ...good(), palette: { ...good().palette, head: 0xff0000 } }],
['speed below the bound', { ...good(), motion: { ...good().motion, speed: 0.1 } }],
['speed above the bound', { ...good(), motion: { ...good().motion, speed: 3 } }],
['speed as a string', { ...good(), motion: { ...good().motion, speed: '1' } }],
['speed as null', { ...good(), motion: { ...good().motion, speed: null } }],
['a layer as a string', { ...good(), motion: { ...good().motion, globe: 'true' } }],
['an array for the root', [good()]],
['an array for the palette', { ...good(), palette: Object.values(good().palette) }],
['null', null],
['a string', 'Orbital'],
['a number', 7],
]
it.each(cases)('rejects %s', (_label, value) => {
expect(parseTheme(value)).toBeNull()
expect(themeFromText(JSON.stringify(value))).toBeNull()
})
it('rejects prototype keys however they arrive, and pollutes nothing', () => {
const texts = [
'{"__proto__":{"polluted":true},"version":1,"name":"P","palette":{"head":"#f06449","ok":"#72c79b","bad":"#ff6868","warn":"#e3ba74","info":"#c6cbc8","background":"#000000"},"motion":{"speed":1,"stars":true,"globe":true,"topology":true}}',
'{"version":1,"name":"P","palette":{"__proto__":"#ffffff","head":"#f06449","ok":"#72c79b","bad":"#ff6868","warn":"#e3ba74","info":"#c6cbc8","background":"#000000"},"motion":{"speed":1,"stars":true,"globe":true,"topology":true}}',
'{"version":1,"name":"P","constructor":{"prototype":{"polluted":true}},"palette":{"head":"#f06449","ok":"#72c79b","bad":"#ff6868","warn":"#e3ba74","info":"#c6cbc8","background":"#000000"},"motion":{"speed":1,"stars":true,"globe":true,"topology":true}}',
'{"version":1,"name":"__proto__","palette":{"head":"#f06449","ok":"#72c79b","bad":"#ff6868","warn":"#e3ba74","info":"#c6cbc8","background":"#000000"},"motion":{"speed":1,"stars":true,"globe":true,"topology":true,"constructor":1}}',
]
for (const text of texts) expect(themeFromText(text)).toBeNull()
expect(({} as Record<string, unknown>).polluted).toBeUndefined()
// A name of "__proto__" is a plain string that passes the name rule, and must still be only data.
const odd = parseTheme({ ...good(), name: 'proto' })
expect(odd?.name).toBe('proto')
expect(Object.getPrototypeOf(odd)).toBe(Object.prototype)
})
it('rejects text over 4096 characters before it is parsed, and survives depth bombs and junk', () => {
const pad = ' '.repeat(4097)
expect(themeFromText(`${JSON.stringify(good())}${pad}`)).toBeNull()
expect(themeFromText(JSON.stringify(good()))).not.toBeNull()
expect(themeFromText(`${'['.repeat(3000)}${']'.repeat(3000)}`)).toBeNull()
expect(themeFromText(`{"a":${'{"a":'.repeat(900)}1${'}'.repeat(901)}`)).toBeNull()
for (const junk of ['', ' ', '{', '}{', 'null', '"x"', '\u0000', '{"version":1,', '```json\n```', '```\n{}\n```', '\u001b[31m{}']) expect(themeFromText(junk)).toBeNull()
})
it('accepts a fenced block and normalises colours to lower case without keeping the original object', () => {
const source = { ...good(), name: 'Fenced', palette: { ...good().palette, head: '#F06449' } }
const theme = themeFromText(`\`\`\`json\n${JSON.stringify(source)}\n\`\`\``)
expect(theme?.palette.head).toBe('#f06449')
expect(theme?.palette).not.toBe(source.palette)
expect(Object.keys(theme ?? {}).sort()).toEqual(['motion', 'name', 'palette', 'version'])
})
})
describe('Theme Studio actions never apply what they refuse', () => {
it('keeps the draft and the active theme when an import is hostile, and says so', async () => {
const state = newState({ look: 'bbs' }), host = hostOf(), a = themeActions(state, host, vi.fn())
const studio = themesOf(state)
const before = JSON.stringify([studio.draft, studio.active, studio.selected, state.options.look])
for (const text of ['{"version":1,"name":"Evil\u001b[2J"}', '{"__proto__":{"x":1}}', 'not json', '{"version":1,'.repeat(400)]) {
a.import(text)
expect(studio.message).toMatch(/Invalid theme JSON/)
}
await flush()
expect(JSON.stringify([studio.draft, studio.active, studio.selected, state.options.look])).toBe(before)
expect(host.storeSet).not.toHaveBeenCalled()
})
it('never lets a name, a colour or a layer edit smuggle a control character into the draft', () => {
const state = newState({}), a = themeActions(state, hostOf(), vi.fn()), studio = themesOf(state)
for (const name of ['A\u001bB', 'A‮B', 'A\nB', 'A\u0000B', '<script>', '', ' ', 'x'.repeat(41)]) {
a.name(name)
expect(studio.draft.name).toBe(ORBITAL_THEME.name)
}
for (const value of ['red', '#12345', '#1234567', '#12345\u001b', '\u001b[31m', '#gggggg', '', '#ffffff\n#000000']) {
a.color('head', value)
expect(studio.draft.palette.head).toBe(ORBITAL_THEME.palette.head)
}
a.color('__proto__' as never, '#ffffff')
a.color('constructor' as never, '#ffffff')
a.motion('speed', 99)
a.motion('speed', Number.NaN)
a.motion('speed', Infinity)
a.motion('extra' as never, true)
expect(studio.draft).toEqual(ORBITAL_THEME)
expect(Object.keys(studio.draft.palette).sort()).toEqual(['background', 'bad', 'head', 'info', 'ok', 'warn'])
})
it('holds the twelve custom slot cap, replaces by name, and never saves an unreadable palette', async () => {
const state = newState({}), host = hostOf(), a = themeActions(state, host, vi.fn()), studio = themesOf(state)
for (let i = 0; i < 12; i++) {
a.name(`Slot ${i}`)
a.save()
await flush()
}
expect(studio.saved).toHaveLength(12)
a.name('Slot 12')
a.save()
await flush()
expect(studio.saved).toHaveLength(12)
expect(studio.message).toMatch(/Twelve custom themes/)
a.name('Slot 3')
a.color('head', '#79dfff')
a.save()
await flush()
expect(studio.saved).toHaveLength(12)
expect(studio.saved.find(t => t.name === 'Slot 3')?.palette.head).toBe('#79dfff')
const stored = (host.storeSet.mock.calls.at(-1) as [string, { saved: unknown[] }])[1]
expect(stored.saved).toHaveLength(12)
a.name('Dim')
a.color('head', '#050505')
const calls = host.storeSet.mock.calls.length
a.save()
await flush()
expect(host.storeSet.mock.calls.length).toBe(calls)
expect(studio.message).toMatch(/Increase contrast/)
})
it('keeps the active theme when the host store throws, and when it never answers a load', async () => {
const state = newState({ look: 'orbital' }), host = hostOf(), a = themeActions(state, host, vi.fn())
a.select('preset:arctic')
await flush()
host.storeSet.mockRejectedValueOnce(new Error('disk full'))
a.name('Fails')
a.save()
await flush()
expect(activeTheme(state).name).toBe('Arctic')
expect(themesOf(state).selected).toBe('preset:arctic')
expect(themesOf(state).message).toMatch(/Could not save/)
expect(themesOf(state).saving).toBe(false)
})
})
describe('Theme Studio reads a store it does not trust', () => {
const load = async (value: unknown) => {
const state = newState({ look: 'bbs' }), store = new Map<string, unknown>([[THEME_STORE_KEY, value]])
await loadThemes(state, hostOf(store))
return state
}
it('ignores a store that is not an object, or throws', async () => {
for (const value of [null, 'x', 5, [], true, undefined]) {
const state = await load(value)
expect(themesOf(state).saved).toEqual([])
expect(state.options.look).toBe('bbs')
}
const state = newState({ look: 'bbs' }), host = hostOf()
host.storeGet = vi.fn(async () => { throw new Error('boom') }) as never
await loadThemes(state, host)
expect(state.options.look).toBe('bbs')
expect(themesOf(state).message).toMatch(/could not be read/)
})
it('keeps at most twelve themes and only the valid ones, and selects nothing it does not hold', async () => {
const saved = [...Array.from({ length: 30 }, (_, i) => ({ ...good(), name: `T${i}` })), { ...good(), name: 'Bad\u001b' }, { ...good(), extra: 1 }, null, 'x', 7]
const state = await load({ selected: 'custom:T25', saved })
expect(themesOf(state).saved.length).toBeLessThanOrEqual(12)
expect(themesOf(state).saved.every(t => parseTheme(t) !== null)).toBe(true)
expect(themesOf(state).selected).toBeNull()
expect(state.options.look).toBe('bbs')
for (const selected of ['preset:../../etc/passwd', 'custom:__proto__', 'custom:', 'preset:', 42, {}, '\u001b[2J']) {
const s = await load({ selected, saved: [] })
expect(themesOf(s).selected).toBeNull()
expect(s.options.look).toBe('bbs')
}
})
it('restores a valid look name and nothing else for the three looks', async () => {
for (const look of ['bbs', 'plain', 'orbital']) expect((await load({ selected: look, saved: [] })).options.look).toBe(look)
expect((await load({ selected: 'matrix', saved: [] })).options.look).toBe('bbs')
})
})
describe('what a theme puts on the model-facing screen', () => {
it('shows names and states on the Theme Studio page, never theme JSON or control characters, in any look', async () => {
for (const look of ['bbs', 'plain', 'orbital'] as const) {
const state = newState({ look, boot: false }), host = hostOf(), a = themeActions(state, host, vi.fn())
a.name('Probe One')
a.color('head', '#79dfff')
a.save()
await flush()
state.view = 'themes'
const text = viewText({ state, nowMs: 5_000, columns: 120, act }, 'themes')
expect(UNSAFE.test(text.replace(/\n/g, ''))).toBe(false)
expect(text).not.toMatch(/"palette"|"version"\s*:|"motion"\s*:/)
// The editor rows name each role's colour (a person edits them there); that is the page's own content, not a JSON dump.
expect(text).toContain('Probe One')
}
})
it('keeps the other pages free of the active palette too', async () => {
const state = newState({ look: 'orbital', boot: false }), a = themeActions(state, hostOf(), vi.fn())
a.name('Probe Two')
a.color('head', '#79dfff')
a.save()
await flush()
for (const view of ['menu', 'overview', 'settings', 'swarm'] as const) {
state.view = view
const text = viewText({ state, nowMs: 5_000, columns: 120, act }, view)
expect(UNSAFE.test(text.replace(/\n/g, ''))).toBe(false)
expect(text).not.toMatch(/#79dfff/i)
}
})
})
+174
View File
@@ -0,0 +1,174 @@
import { describe, expect, it, vi } from 'vitest'
import { activeTheme, COLOR_KEYS, contrast, loadThemes, lowContrast, ORBITAL_THEME, parseTheme, themeActions, themeFromText, themesOf, themeLayout, THEME_PRESETS } from '../hooks/themes'
import { newState } from '../hooks/state'
import type { Host } from '../hooks/host'
import { orbitalBoot, orbitalGlobe, orbitalHeader } from '../hooks/gfx/orbital'
import { picturesOf } from '../hooks/views/frames'
import { groupOf, findPages } from '../hooks/nav-state'
import { paneView } from '../hooks/views/pane'
import { GROUPS } from '../hooks/views/menu'
const flush = async () => { await new Promise(resolve => setTimeout(resolve, 0)) }
const copy = () => JSON.parse(JSON.stringify(ORBITAL_THEME))
const hostOf = (store = new Map<string, unknown>()) => ({ storeGet: vi.fn(async (key: string) => store.get(key)), storeSet: vi.fn(async (key: string, value: unknown) => { store.set(key, value) }), invalidate: vi.fn(), fs: { read: vi.fn(async (path: string) => path.endsWith('SKILL.md') ? 'Generate one preset.' : 'version: 1; six hex colors; motion') }, pluginRoot: '/plugin' }) as unknown as Host
describe('Theme Studio', () => {
it('loads each bundled palette, restores its selection and leaves custom slots free', async () => {
expect(new Set(THEME_PRESETS.map(p => p.id)).size).toBe(THEME_PRESETS.length)
for (const { id, theme } of THEME_PRESETS) {
expect(parseTheme(theme)).toEqual(theme)
for (const key of COLOR_KEYS.filter(k => k !== 'background')) expect(contrast(theme.palette[key], theme.palette.background)).toBeGreaterThanOrEqual(4.5)
const store = new Map(), host = hostOf(store), state = newState({ look: 'bbs' })
const act = themeActions(state, host, vi.fn())
act.select(`preset:${id}`); await flush()
expect(state.options.look).toBe('orbital')
expect(activeTheme(state)).toEqual(theme)
expect(themesOf(state).saved).toHaveLength(0)
const restored = newState({ look: 'plain' }); await loadThemes(restored, host)
expect(activeTheme(restored)).toEqual(theme)
expect(themesOf(restored).selected).toBe(`preset:${id}`)
act.color('head', '#ffffff')
expect(activeTheme(state).palette.head).toBe(theme.palette.head)
act.save(); await flush()
expect(themesOf(state).selected).toBe(`custom:${theme.name}`)
expect(theme.palette.head).not.toBe('#ffffff')
act.select('orbital'); await flush()
expect(themesOf(state).draft).toEqual(ORBITAL_THEME)
}
})
it('leaves selection and draft intact when a bundled selection cannot persist', async () => {
const state = newState({ look: 'orbital' }), host = hostOf(), act = themeActions(state, host, vi.fn())
act.select('preset:arctic'); await flush()
host.storeSet = vi.fn(async () => { throw Error('denied') })
act.select('preset:synthwave'); await flush()
expect(activeTheme(state).name).toBe('Arctic')
expect(themesOf(state).draft.name).toBe('Arctic')
act.select('preset:unknown'); await flush()
expect(themesOf(state).selected).toBe('preset:arctic')
act.reset(); await flush()
expect(themesOf(state).draft.name).toBe('Arctic')
expect(themesOf(state).selected).toBe('preset:arctic')
})
it('is available in main menu and Tools navigation/search', () => {
expect(groupOf('themes')).toBe('TOOLS')
expect(findPages('color')).toContain('themes')
expect(GROUPS.find(g => g.title === 'TOOLS')!.sections.flatMap(s => s.items).some(i => i.go === 'themes')).toBe(true)
})
it('opens from the real main menu and retains the existing console shell', () => {
const state = newState({ look: 'orbital', boot: false }); state.view = 'menu'; state.pane.rows = 60
const noop: any = new Proxy(() => undefined, { get: () => noop })
const act = new Proxy(noop, { get: (_, key) => key === 'view' ? (view: typeof state.view) => { state.view = view } : noop })
const kit = Object.fromEntries(['Box', 'Text', 'Button', 'Input', 'Raster'].map(type => [type, (props: any) => ({ type, props })]))
const flat = (node: any): any[] => node && typeof node === 'object' ? [node, ...(Array.isArray(node.props?.children) ? node.props.children.flatMap(flat) : flat(node.props?.children))] : []
const draw = () => paneView({ state, kit, act, columns: 116, nowMs: 5000, pictures: picturesOf(state, 116, 5000, 5000) } as any)
const entry = flat(draw()).find(node => node.props?.key === 'menu-go-themes')
expect(entry).toBeDefined(); entry.props.onPress()
expect(state.view).toBe('themes')
const keys = flat(draw()).map(node => node.props?.key)
for (const key of ['tabs', 'pane-icons', 'footer', 'theme-layout', 'tab-menu', 'theme-editor', 'theme-stage']) expect(keys).toContain(key)
for (const { id } of THEME_PRESETS) expect(keys).toContain(`theme-preset-${id}`)
flat(draw()).find(node => node.props?.key === 'tab-menu').props.onPress()
expect(state.view).toBe('menu')
})
it('keeps editor and preview within one width at the breakpoint', () => {
for (const width of [12, 20, 44, 72, 99, 100, 120, 160, 240]) {
const layout = themeLayout(width)
expect(layout.wide ? layout.controls + 2 + layout.preview : layout.preview).toBeLessThanOrEqual(width)
expect(layout.wide).toBe(width >= 100)
}
})
it('switches focused editors and discards only unsaved changes', async () => {
const state = newState({ look: 'orbital' }), host = hostOf(), act = themeActions(state, host, vi.fn())
act.tab('motion'); act.role('warn'); act.name('Saved'); act.save(); await flush()
act.color('head', '#ffffff'); act.discard()
expect(themesOf(state).tab).toBe('motion')
expect(themesOf(state).role).toBe('warn')
expect(themesOf(state).draft).toEqual(activeTheme(state))
expect(themesOf(state).saved).toHaveLength(1)
})
it('accepts only bounded data and clones it', () => {
const raw = copy(), parsed = parseTheme(raw)!
expect(parsed).toEqual(raw)
raw.palette.head = '#ffffff'
expect(parsed.palette.head).toBe('#f06449')
for (const patch of [{ version: 2 }, { script: 'eval()' }, { name: '\x1b[31m' }, { name: 'x'.repeat(41) }, { palette: {} }, { motion: { speed: 3, stars: true, globe: true, topology: true } }]) expect(parseTheme({ ...copy(), ...patch })).toBeNull()
for (const color of ['red', '#fff', '#GG0000', '#000000\n']) expect(parseTheme({ ...copy(), palette: { ...copy().palette, head: color } })).toBeNull()
expect(themeFromText('x'.repeat(4097))).toBeNull()
expect(themeFromText('```json\n' + JSON.stringify(copy()) + '\n```')).toEqual(copy())
expect(themeFromText('{}')).toBeNull()
})
it('previews without changing active look, saves, and restores across sessions', async () => {
const store = new Map(), host = hostOf(store), state = newState({ look: 'bbs' }), act = themeActions(state, host, vi.fn())
act.name('Violet'); act.color('head', '#ca9bff'); act.motion('speed', 0.5)
expect(state.options.look).toBe('bbs')
expect(activeTheme(state).palette.head).toBe('#f06449')
act.save(); await flush()
expect(state.options.look).toBe('orbital')
expect(activeTheme(state).palette.head).toBe('#ca9bff')
const restored = newState({ look: 'plain' }); await loadThemes(restored, host)
expect(activeTheme(restored).name).toBe('Violet')
expect(themesOf(restored).saved).toHaveLength(1)
themeActions(restored, host, vi.fn()).reset(); await flush()
expect(restored.options.look).toBe('plain')
})
it('keeps the prior theme on storage failure and rejects invalid/low contrast edits', async () => {
const state = newState({ look: 'bbs' }), host = hostOf()
host.storeSet = vi.fn(async () => { throw Error('denied') })
const act = themeActions(state, host, vi.fn())
act.select('orbital'); await flush(); expect(state.options.look).toBe('bbs')
expect(themesOf(state).message).toContain('Could not save')
act.color('head', 'bad'); expect(themesOf(state).draft.palette.head).toBe('#f06449')
act.motion('speed', NaN); expect(themesOf(state).draft.motion.speed).toBe(1)
act.color('info', '#000000'); act.save()
expect(themesOf(state).message).toContain('contrast')
expect(lowContrast(ORBITAL_THEME)).toEqual([])
})
it('rejects overlapping saves and does not let a late load replace user selection', async () => {
const state = newState({}), host = hostOf(); let resolve!: (v: unknown) => void
host.storeGet = () => new Promise(r => { resolve = r })
const loading = loadThemes(state, host), act = themeActions(state, host, vi.fn())
act.select('plain'); act.select('orbital'); await flush()
resolve({ selected: 'orbital', saved: [] }); await loading
expect(state.options.look).toBe('plain')
expect(host.storeSet).toHaveBeenCalledTimes(1)
})
it('sends the bundled skill and contract to the chosen AI route only on request', async () => {
const state = newState({}), host = hostOf(), ask = vi.fn(), act = themeActions(state, host, ask)
act.brief('Amber stars'); expect(ask).not.toHaveBeenCalled()
act.generate('codex'); await flush()
expect(ask).toHaveBeenCalledWith('codex', expect.stringContaining('Amber stars'))
expect(ask.mock.calls[0]![1]).toContain('six hex colors')
expect(host.storeSet).not.toHaveBeenCalled()
host.fs.read = async () => { throw Error('missing') }
act.generate('claude'); await flush()
expect(ask).toHaveBeenCalledTimes(1)
expect(themesOf(state).message).toContain('could not be read')
})
it('applies palette and decorative layers without losing failure checks', () => {
const theme = copy(); theme.palette.head = '#ca9bff'; theme.palette.bad = '#ffaaaa'
const header = orbitalHeader('swarm', 72, 1200, 16, theme)
expect(header.cells[1]).toBe(0xca9bff)
theme.motion.topology = false
expect(orbitalHeader('swarm', 72, 1200, 16, theme).rows).toBe(4)
const withStars = orbitalGlobe(72, 16, 1000, theme).encode()
theme.motion.stars = false
expect(orbitalGlobe(72, 16, 1000, theme).encode()).not.toBe(withStars)
theme.motion.globe = false
const checks = [{ area: 'module', ok: false, problems: ['missing'] }]
const grid = orbitalBoot('demo', 72, 1500, checks, 30, theme)
const text = Array.from({ length: grid.columns * grid.rows }, (_, i) => String.fromCodePoint(grid.cells[i * 3]!)).join('')
expect(text).toContain('[FAIL] MODULE / missing')
expect(grid.cells[(23 * 72) * 3 + 1]).toBe(0xffaaaa)
})
it('bounds previews across sizes and holds still at fps zero', () => {
const state = newState({ look: 'orbital', fps: 0, boot: false }); state.view = 'themes'
for (const width of [12, 20, 44, 72, 160, 240]) for (const rows of [10, 24, 60]) {
state.pane.rows = rows
const a = picturesOf(state, width, 1000, 1000), b = picturesOf(state, width, 9000, 9000)
for (const key of ['theme-preview', 'theme-globe']) {
expect(a.get(key)!.columns).toBeLessThanOrEqual(width)
expect(a.get(key)!.encode()).toBe(b.get(key)!.encode())
}
}
expect(COLOR_KEYS).toHaveLength(6)
})
})