@neta-art/cohub-cli 10.20.0 → 10.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,6 +2,7 @@ import { type BoardMediaSpan, type BoardMediaState } from "@neta-art/cohub/board
2
2
  export declare function createBoardMediaFiles(spaceId: string, dir: string, signal?: AbortSignal): {
3
3
  path(src: string, kind: "video" | "audio"): Promise<string>;
4
4
  audible(src: string, kind: "video" | "audio"): Promise<boolean>;
5
+ duration(src: string): Promise<number>;
5
6
  };
6
7
  export type BoardMediaFiles = ReturnType<typeof createBoardMediaFiles>;
7
8
  export declare function createBoardVideoFrames(files: BoardMediaFiles, dir: string, options: {
@@ -22,6 +22,7 @@ async function ffmpeg(args, signal) {
22
22
  export function createBoardMediaFiles(spaceId, dir, signal) {
23
23
  const files = new Map();
24
24
  const audible = new Map();
25
+ const durations = new Map();
25
26
  const client = createClient();
26
27
  return {
27
28
  path(src, kind) {
@@ -53,6 +54,17 @@ export function createBoardMediaFiles(spaceId, dir, signal) {
53
54
  }
54
55
  return pending;
55
56
  },
57
+ async duration(src) {
58
+ let pending = durations.get(src);
59
+ if (!pending) {
60
+ pending = this.path(src, "video").then(async (path) => {
61
+ const { stdout } = await execFile("ffprobe", ["-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", path], { signal });
62
+ return Math.max(0, Number(stdout.trim()) * 1000 || 0);
63
+ }).catch(() => 0);
64
+ durations.set(src, pending);
65
+ }
66
+ return pending;
67
+ },
56
68
  };
57
69
  }
58
70
  export function createBoardVideoFrames(files, dir, options) {
@@ -85,6 +97,11 @@ export function createBoardVideoFrames(files, dir, options) {
85
97
  }
86
98
  return {
87
99
  async frame(state, rate, edge) {
100
+ if (state.loop) {
101
+ const duration = await files.duration(state.src);
102
+ if (duration > 0)
103
+ state = { ...state, time: state.time % duration };
104
+ }
88
105
  const current = chunks.get(state.id);
89
106
  let file = current?.src === state.src ? lookup(current, state.time, edge) : null;
90
107
  if (!file)
@@ -1,4 +1,4 @@
1
- import type { BoardDocument, BoardExportRegion } from "@neta-art/cohub/board";
1
+ import { type BoardDocument, type BoardExportRegion } from "@neta-art/cohub/board";
2
2
  import { type BoardGpuProfile } from "./board-gpu/index.js";
3
3
  export type BoardProfile = BoardGpuProfile & {
4
4
  hints: string[];
@@ -14,6 +14,8 @@ export declare function profileBoard(options: {
14
14
  height: number;
15
15
  };
16
16
  frames: number;
17
+ rounds: number;
18
+ budgetMs: number;
17
19
  withImages: boolean;
18
20
  }): Promise<BoardProfile>;
19
21
  export declare function boardProfileHints(document: BoardDocument, profile: BoardGpuProfile): string[];
@@ -1,3 +1,4 @@
1
+ import { boardModelFormat } from "@neta-art/cohub/board";
1
2
  import { gpuResources, loadBoardDocument } from "./board-export.js";
2
3
  import { openBoardGpu } from "./board-gpu/daemon.js";
3
4
  import { findBoardGpuBrowser } from "./board-gpu/index.js";
@@ -7,6 +8,7 @@ import { settleBoardDocument } from "./board-media.js";
7
8
  const LARGE_OWNER = 4000;
8
9
  const LARGE_STATE = 512 * 512;
9
10
  const MANY_EFFECTS = 16;
11
+ const LARGE_MODEL = 8 * 1024 ** 2;
10
12
  export async function profileBoard(options) {
11
13
  const browser = findBoardGpuBrowser();
12
14
  if (!browser)
@@ -26,6 +28,8 @@ export async function profileBoard(options) {
26
28
  region: options.region,
27
29
  scale,
28
30
  frames: options.frames,
31
+ rounds: options.rounds,
32
+ budgetMs: options.budgetMs,
29
33
  withImages: options.withImages,
30
34
  imageMemory: BOARD_EXPORT_IMAGE_MEMORY_MIB * 1024 ** 2,
31
35
  });
@@ -44,9 +48,19 @@ export function boardProfileHints(document, profile) {
44
48
  const item = document.items[owner.id];
45
49
  if (item && "size" in item && Math.max(item.size.width, item.size.height) > LARGE_OWNER)
46
50
  hints.push(`${owner.id} is larger than any view, so its shaders never leave the screen; a Board script, or shaders on the smaller items, draw only what shows.`);
51
+ if (owner.boxes && share(owner.ms) > 0.1)
52
+ hints.push(`${owner.id} shades every pixel of its box; if its picture changes only every few units, as pixel art or a map does, give the pass texel so it shades once per texel.`);
47
53
  if (owner.state && owner.state.width * owner.state.height > LARGE_STATE)
48
54
  hints.push(`${owner.id} steps a ${owner.state.width}×${owner.state.height} state 60 times a second and replays it from the start in exports; keep it as small as reads well.`);
49
55
  }
56
+ const noisy = profile.owners.filter((owner) => owner.ms > 1 && owner.range[1] - owner.range[0] > owner.ms);
57
+ if (noisy.length)
58
+ hints.push(`${noisy.map((owner) => owner.id).join(", ")} varied more between rounds than ${noisy.length === 1 ? "its" : "their"} median; compare the frame time, or raise --rounds.`);
59
+ for (const [id, item] of Object.entries(document.items)) {
60
+ const size = item.type === "file" && boardModelFormat(item.props.src, item.props.snapshot?.mimeType) ? (item.props.snapshot?.size ?? 0) : 0;
61
+ if (size > LARGE_MODEL)
62
+ hints.push(`${id} is a ${(size / 1024 ** 2).toFixed(0)} MB model every viewer downloads for its card, and phones skip past 16 MB; compress it (meshopt or Draco geometry, KTX2 textures).`);
63
+ }
50
64
  if (profile.effects > MANY_EFFECTS)
51
65
  hints.push(`${profile.effects} items draw with shadows, blurs or color filters, each in its own offscreen pass; present them only while they change, and drop neutral values.`);
52
66
  return hints;
@@ -1,6 +1,6 @@
1
1
  import type { BoardExportRegion, BoardThemeId } from "@neta-art/cohub/board";
2
2
  import type { BoardNodeExportFormat } from "@neta-art/cohub/board/export/node";
3
- import type { BoardScriptHarnessPointer } from "@neta-art/cohub/board/testing";
3
+ import type { BoardScriptHarnessPointer, BoardScriptHarnessPress } from "@neta-art/cohub/board/testing";
4
4
  declare const TOOLS: readonly ["select", "hand", "text", "shape", "draw", "arrow", "frame"];
5
5
  type Point = {
6
6
  x: number;
@@ -29,11 +29,16 @@ export type BoardSimulationStep = {
29
29
  select: string[];
30
30
  };
31
31
  export declare function parseBoardSimulationSteps(value: unknown): BoardSimulationStep[];
32
+ export type BoardSimulationPress = BoardScriptHarnessPress & {
33
+ step: number;
34
+ };
32
35
  export type BoardSimulationResult = {
33
36
  time: number;
34
37
  commits: number;
35
38
  changes: Record<string, unknown>;
36
39
  errors: Record<string, string>;
40
+ presses: BoardSimulationPress[];
41
+ warnings: string[];
37
42
  shaders?: {
38
43
  count: number;
39
44
  compiled: boolean;
@@ -44,11 +49,13 @@ export type BoardSimulationResult = {
44
49
  height: number;
45
50
  };
46
51
  };
52
+ export declare const BOARD_SIMULATION_TIMEOUT_MS = 120000;
47
53
  export declare function runBoardSimulation(options: {
48
54
  spaceId: string;
49
55
  target: string;
50
56
  steps: readonly BoardSimulationStep[];
51
57
  leader: boolean;
58
+ timeoutMs?: number;
52
59
  image?: {
53
60
  region: BoardExportRegion;
54
61
  scale: number;
@@ -2,7 +2,7 @@ import { diffMergePatch } from "@neta-art/cohub/board";
2
2
  import { gpuResources, loadBoardDocument, readSpaceFileBytes, resolveBundledFonts, runBoardExport } from "./board-export.js";
3
3
  import { openBoardGpu } from "./board-gpu/daemon.js";
4
4
  import { findBoardGpuBrowser } from "./board-gpu/index.js";
5
- import { boardScriptAttachments, boardShaderParameters, buildBoardScene, checkBoardShader, createBoardScriptHarness, createNodeBoardRenderer, itemBounds, planBoardExport, rectsIntersect, } from "./board-kernel.js";
5
+ import { boardScriptAttachments, boardShaderParameters, buildBoardScene, checkBoardShader, createBoardScriptHarness, createNodeBoardRenderer, describeBoardScriptLanes, itemBounds, planBoardExport, rectsIntersect, } from "./board-kernel.js";
6
6
  import { settleBoardDocument } from "./board-media.js";
7
7
  import { parseBoardTime } from "./board-time.js";
8
8
  import { createClient } from "./client.js";
@@ -86,28 +86,46 @@ function parseStep(entry, index) {
86
86
  }
87
87
  throw new Error(`${name} must be one of wait, tool, tap, drag, move, pointer, key or select`);
88
88
  }
89
- async function run(harness, steps) {
90
- for (const step of steps) {
89
+ async function run(harness, steps, progress, presses) {
90
+ for (const [index, step] of steps.entries()) {
91
+ progress.step = index;
92
+ let press = null;
91
93
  if ("wait" in step)
92
94
  await harness.advance(step.wait);
93
95
  else if ("tool" in step)
94
96
  harness.tool = step.tool;
95
97
  else if ("tap" in step)
96
- await harness.tap(step.tap, step.input);
98
+ press = await harness.tap(step.tap, step.input);
97
99
  else if ("drag" in step)
98
- await harness.drag(step.drag, step.input);
100
+ press = await harness.drag(step.drag, step.input);
99
101
  else if ("move" in step)
100
102
  await harness.move(step.move, step.input);
101
103
  else if ("pointer" in step)
102
- await harness.pointer(step.pointer, step.at, step.input);
104
+ press = await harness.pointer(step.pointer, step.at, step.input);
103
105
  else if ("key" in step) {
104
106
  await harness.key("keydown", step.key);
105
107
  await harness.key("keyup", step.key);
106
108
  }
107
109
  else
108
110
  await harness.select(step.select);
111
+ if (press)
112
+ presses.push({ step: index, ...press });
109
113
  }
110
114
  }
115
+ export const BOARD_SIMULATION_TIMEOUT_MS = 120_000;
116
+ function shadersOf(harness) {
117
+ const errors = {};
118
+ const shaders = [];
119
+ for (const { id } of boardScriptAttachments(harness.document)) {
120
+ const message = harness.error(id);
121
+ const output = harness.output(id);
122
+ if (message)
123
+ errors[id] = message;
124
+ else if (output?.shader)
125
+ shaders.push({ id, shader: output.shader, ...(output.parameters ? { parameters: output.parameters } : {}) });
126
+ }
127
+ return { shaders, errors };
128
+ }
111
129
  async function checkShaders(shaders, spaceId, document) {
112
130
  const browser = findBoardGpuBrowser();
113
131
  const exporter = browser ? await openBoardGpu(gpuResources(spaceId, document), { browser }).catch(() => null) : null;
@@ -134,42 +152,77 @@ export async function runBoardSimulation(options) {
134
152
  const client = createClient();
135
153
  const document = await settleBoardDocument(options.spaceId, (await loadBoardDocument(options.spaceId, options.target)).document);
136
154
  const renderer = await createNodeBoardRenderer({ fonts: resolveBundledFonts() });
137
- const harness = await createBoardScriptHarness({
138
- document,
139
- renderer,
140
- leader: options.leader,
141
- readModule: async (path) => new TextDecoder().decode((await readSpaceFileBytes(client, options.spaceId, path)).bytes),
155
+ const progress = { step: -1, phase: "starting the scripts" };
156
+ let harness = null;
157
+ let timer;
158
+ const timeoutMs = options.timeoutMs ?? BOARD_SIMULATION_TIMEOUT_MS;
159
+ let stopped = false;
160
+ const expired = new Promise((_resolve, reject) => {
161
+ timer = setTimeout(() => {
162
+ stopped = true;
163
+ const busy = harness ? describeBoardScriptLanes(harness.status()) : [];
164
+ const at = harness ? ` at ${Math.round(harness.time)} ms of simulated time` : "";
165
+ const step = progress.step >= 0 ? `, step ${progress.step + 1} of ${options.steps.length}` : "";
166
+ reject(new Error([
167
+ `The simulation did not finish in ${timeoutMs / 1000} s${at}${step}, while ${progress.phase}.`,
168
+ ...busy.map((line) => ` ${line}`),
169
+ ...(!busy.length && progress.phase === "running the steps" ? [" No script was busy: the scripts keep handing each other work, or a step waits on something else."] : []),
170
+ ].join("\n")));
171
+ }, timeoutMs);
142
172
  });
143
- try {
144
- await run(harness, options.steps);
145
- await harness.flush();
146
- const shown = options.image ? await harness.shown(options.image.scale) : null;
147
- const errors = {};
148
- const shaders = [];
149
- for (const { id } of boardScriptAttachments(harness.document)) {
150
- const message = harness.error(id);
151
- const output = harness.output(id);
152
- if (message)
153
- errors[id] = message;
154
- else if (output?.shader)
155
- shaders.push({ id, shader: output.shader, ...(output.parameters ? { parameters: output.parameters } : {}) });
173
+ const work = async () => {
174
+ harness = await createBoardScriptHarness({
175
+ document,
176
+ renderer,
177
+ leader: options.leader,
178
+ readModule: async (path) => new TextDecoder().decode((await readSpaceFileBytes(client, options.spaceId, path)).bytes),
179
+ });
180
+ const current = harness;
181
+ if (stopped) {
182
+ current.destroy();
183
+ throw new Error("The simulation timed out.");
184
+ }
185
+ progress.phase = "compiling shaders";
186
+ const initial = shadersOf(current);
187
+ const early = initial.shaders.length ? await checkShaders(initial.shaders, options.spaceId, current.document) : null;
188
+ const presses = [];
189
+ if (early && Object.keys(early.errors).length) {
190
+ return {
191
+ time: Math.round(current.time), commits: 0, changes: {}, errors: { ...initial.errors, ...early.errors }, presses,
192
+ warnings: ["Stopped before the steps: fix the shader errors first."],
193
+ shaders: { count: initial.shaders.length, compiled: early.compiled },
194
+ };
156
195
  }
157
- const checked = shaders.length ? await checkShaders(shaders, options.spaceId, harness.document) : null;
158
- Object.assign(errors, checked?.errors);
196
+ progress.phase = "running the steps";
197
+ await run(current, options.steps, progress, presses);
198
+ progress.phase = "settling the scripts";
199
+ await current.flush();
200
+ const { shaders, errors } = shadersOf(current);
201
+ const checked = new Set(initial.shaders.map(({ id }) => id));
202
+ const added = shaders.filter(({ id }) => !checked.has(id));
203
+ progress.phase = "compiling shaders";
204
+ const late = added.length ? await checkShaders(added, options.spaceId, current.document) : null;
205
+ Object.assign(errors, late?.errors);
206
+ const compiled = (early?.compiled ?? true) && (late?.compiled ?? true);
207
+ const warnings = [...current.emitFailures].map(([id, message]) => `${id}: ${message}`);
159
208
  const result = {
160
- time: Math.round(harness.time),
161
- commits: harness.commits.length,
162
- changes: diffMergePatch(document, harness.document) ?? {},
209
+ time: Math.round(current.time),
210
+ commits: current.commits.length,
211
+ changes: diffMergePatch(document, current.document) ?? {},
163
212
  errors,
164
- ...(checked ? { shaders: { count: shaders.length, compiled: checked.compiled } } : {}),
213
+ presses,
214
+ warnings,
215
+ ...(shaders.length ? { shaders: { count: shaders.length, compiled } } : {}),
165
216
  };
166
- if (options.image && shown) {
167
- const gpu = checked?.compiled && !Object.keys(checked.errors).length && shaderShown(harness.document, shaders, options.image.region);
217
+ if (options.image) {
218
+ progress.phase = "rendering the image";
219
+ const shown = await current.shown(options.image.scale);
220
+ const gpu = compiled && shaders.length > 0 && !Object.keys(errors).length && shaderShown(current.document, shaders, options.image.region);
168
221
  const exported = await runBoardExport({
169
222
  spaceId: options.spaceId,
170
223
  target: options.target,
171
224
  ...(gpu
172
- ? { document: harness.document, snapshots: await harness.snapshot(), renderer: "gpu" }
225
+ ? { document: current.document, snapshots: await current.snapshot(), renderer: "gpu" }
173
226
  : { document: shown.document, ...(shown.scripts ? { scripts: shown.scripts } : {}) }),
174
227
  region: options.image.region,
175
228
  scale: options.image.scale,
@@ -181,11 +234,16 @@ export async function runBoardSimulation(options) {
181
234
  const frame = exported?.frames[0];
182
235
  if (frame)
183
236
  result.image = { bytes: frame.bytes, width: frame.width, height: frame.height };
237
+ warnings.push(...(exported?.warnings ?? []));
184
238
  }
185
239
  return result;
240
+ };
241
+ try {
242
+ return await Promise.race([work(), expired]);
186
243
  }
187
244
  finally {
188
- harness.destroy();
245
+ clearTimeout(timer);
246
+ harness?.destroy();
189
247
  renderer.destroy();
190
248
  }
191
249
  }
@@ -0,0 +1 @@
1
+ {"commit":"b2e3ef6"}
@@ -188,6 +188,7 @@ function registerExportCommand(boards) {
188
188
  .option("--no-images", "Draw placeholders instead of downloading images")
189
189
  .option("--renderer <renderer>", "auto draws in Node and uses local Chrome for shaders; canvas or gpu forces one", "auto")
190
190
  .option("--force", "Replace existing output files")
191
+ .option("--timeout <time>", "Fail a frame that takes longer, naming the scripts still running", "2m")
191
192
  .option("--async", "Run as a Task in the Space's sandbox and return at once; paths are Space paths"))
192
193
  .addHelpText("after", `
193
194
  Shaders draw in a shared headless Chrome that stays up a few minutes between calls;
@@ -198,7 +199,11 @@ Examples:
198
199
  cohub boards export plan.board --animation intro --at 0:20s:40ms -o intro.mp4 --async
199
200
  cohub boards export plan.board --frame s2 -o slide-2.png
200
201
  cohub boards export plan.board --animation lecture --at 4.5s -o moment.png
201
- cohub boards export plan.board --animation lecture --at 0:6s:40ms -o frames/%04d.png`)
202
+ cohub boards export plan.board --animation lecture --at 0:6s:40ms -o frames/%04d.png
203
+
204
+ Scripts see the exported area as their view (viewchange), and emit() between them is
205
+ delivered within the same moment, in document order. --frame draws the frame as a
206
+ page: its fill and shaders, without its outline and label.`)
202
207
  .action(async (target, options) => {
203
208
  if (options.async)
204
209
  return runExportTask(boards, options);
@@ -246,6 +251,7 @@ Examples:
246
251
  spaceId: await resolveSpace(boards),
247
252
  target,
248
253
  camera,
254
+ timeoutMs: parseBoardTime(options.timeout ?? "2m", "--timeout"),
249
255
  onProgress: progress,
250
256
  onPlan,
251
257
  imageMemoryMiB,
@@ -283,6 +289,7 @@ Examples:
283
289
  spaceId: await resolveSpace(boards),
284
290
  target,
285
291
  camera,
292
+ timeoutMs: parseBoardTime(options.timeout ?? "2m", "--timeout"),
286
293
  onProgress: progress,
287
294
  onPlan,
288
295
  imageMemoryMiB,
@@ -331,6 +338,7 @@ function registerSimulateCommand(boards) {
331
338
  .option("-i, --input <file>", "Steps JSON; - for stdin")
332
339
  .option("-o, --out <file>", "Also render the result, screen UI included; the extension picks the format")
333
340
  .option("--follower", "Simulate an editor that does not write autonomous commits")
341
+ .option("--timeout <time>", "Give up after this long and report what is still running", "2m")
334
342
  .option("--frame <item-id>", "Render one frame")
335
343
  .option("--items <ids>", "Render comma-separated item ids")
336
344
  .option("--rect <rect>", "Render a world rect as x,y,width,height")
@@ -343,8 +351,10 @@ Steps are {"steps": [...]}, points in board coordinates, run on a virtual clock:
343
351
  {"wait": "500ms"} {"tool": "draw"} {"tap": [x, y]} {"drag": [[x, y], ...], "pointerType": "pen"}
344
352
  {"pointer": "down", "at": [x, y]} {"key": "Enter"} {"select": ["id"]}
345
353
 
346
- Shaders are compiled with a local Chrome, Chromium or Edge when one is found, and
347
- their errors join the scripts' errors.
354
+ Shaders are compiled with a local Chrome, Chromium or Edge when one is found, before
355
+ the steps run; their errors join the scripts' errors and stop the run.
356
+ Each tap and drag reports where it landed (a script's hit region, a selection handle,
357
+ an item, or empty board) and what took it (a script, move, resize, rotate, select box).
348
358
 
349
359
  Examples:
350
360
  cohub boards simulate farm.board '{"steps":[{"wait":"2s"}]}' -o farm.png
@@ -366,6 +376,7 @@ Examples:
366
376
  target,
367
377
  steps,
368
378
  leader: !options.follower,
379
+ timeoutMs: parseBoardTime(options.timeout ?? "2m", "--timeout"),
369
380
  ...(out ? { image: {
370
381
  region: parseExportRegion(options),
371
382
  scale: parseNumber(options.scale ?? "2", "--scale", { min: 0.01, max: 16 }),
@@ -383,8 +394,12 @@ Examples:
383
394
  return outJson({ ...summary, ...(out && image ? { file: out, width: image.width, height: image.height } : {}) });
384
395
  const changed = Object.keys(result.changes.items ?? {}).length;
385
396
  ok(`Simulated ${formatBoardTime(result.time)}: ${result.commits} commit${result.commits === 1 ? "" : "s"}, ${changed} item${changed === 1 ? "" : "s"} changed (not saved)`);
397
+ for (const press of result.presses)
398
+ console.log(` step ${press.step + 1}: ${describePress(press)}`);
386
399
  for (const [id, message] of Object.entries(result.errors))
387
400
  console.log(` ! ${id}: ${message.split("\n")[0]}`);
401
+ for (const warning of result.warnings)
402
+ console.log(` ! ${warning}`);
388
403
  if (result.shaders && !result.shaders.compiled)
389
404
  console.log(" Shaders were checked but not compiled; install Chrome, Chromium or Edge, or set COHUB_CHROME, to compile them.");
390
405
  if (out && image)
@@ -397,6 +412,13 @@ Examples:
397
412
  }
398
413
  });
399
414
  }
415
+ function describePress({ down, taken }) {
416
+ const where = down.on === "script" ? `script ${down.owner}/${down.target}`
417
+ : down.on === "handle" ? `${down.handle} handle`
418
+ : down.on === "item" ? `${down.type} ${down.id}`
419
+ : `empty board${down.under ? ` over ${down.under}` : ""}`;
420
+ return `pressed on ${where}, taken by ${taken}`;
421
+ }
400
422
  function registerProfileCommand(boards) {
401
423
  withJson(boards.command("profile <board>")
402
424
  .description("Measure what a Board costs to draw, shader by shader, and say what to change")
@@ -407,10 +429,13 @@ function registerProfileCommand(boards) {
407
429
  .option("--rect <rect>", "Profile a world rect as x,y,width,height")
408
430
  .option("--size <widthxheight>", "Fit the region into this many pixels, like a screen", "1600x900")
409
431
  .option("--frames <count>", "Frames to time per measurement", "5")
432
+ .option("--rounds <count>", "Measurements per shader owner; reports their median and range", "3")
433
+ .option("--budget <time>", "Time the measurements may take; past it, size and frames go down", "60s")
410
434
  .option("--no-images", "Draw placeholders instead of downloading images"))
411
435
  .addHelpText("after", `
412
- Draws in a headless Chrome; without a GPU it uses software WebGL, so compare the
413
- numbers with each other rather than with a real display.
436
+ Draws in a headless Chrome; without a GPU it uses software WebGL (reported as
437
+ "software"), so compare the numbers with each other rather than with a real display.
438
+ Scripts receive the profiled view as viewchange, as on a screen of --size.
414
439
 
415
440
  Examples:
416
441
  cohub boards profile demo.board
@@ -426,15 +451,21 @@ Examples:
426
451
  region: parseExportRegion(options),
427
452
  size: parseSize(options.size ?? "1600x900"),
428
453
  frames: parseNumber(options.frames ?? "5", "--frames", { min: 3, max: 240, integer: true }),
454
+ rounds: parseNumber(options.rounds ?? "3", "--rounds", { min: 1, max: 20, integer: true }),
455
+ budgetMs: parseBoardTime(options.budget ?? "60s", "--budget"),
429
456
  withImages: options.images !== false,
430
457
  });
431
458
  if (jsonRequested(options))
432
459
  return outJson(profile);
433
460
  const ms = (value) => `${value.toFixed(1)} ms`;
434
- ok(`${profile.width}×${profile.height} in ${profile.renderer}: ${ms(profile.frame.p50)} a frame (p95 ${ms(profile.frame.p95)}), ${profile.items} items`);
461
+ ok(`${profile.width}×${profile.height} on ${profile.gpu} WebGL (${profile.renderer}): ${ms(profile.frame.p50)} a frame (p95 ${ms(profile.frame.p95)}), ${profile.items} items`);
462
+ if (profile.reduced)
463
+ console.log(` ! ${profile.reduced.width}×${profile.reduced.height} × ${profile.reduced.frames} frames took ${ms(profile.reduced.frameMs)} a frame, past the budget; measured ${profile.width}×${profile.height} × ${profile.frames} frames instead.`);
464
+ console.log(` ${profile.rounds} round${profile.rounds === 1 ? "" : "s"} × ${profile.frames} frames in ${(profile.elapsedMs / 1000).toFixed(1)} s; owner cost is the median, with the range across rounds`);
435
465
  for (const owner of profile.owners) {
436
466
  const traits = [owner.filter !== "none" && `filter ${owner.filter}`, owner.sprites && `${owner.sprites} sprites`, owner.state && `state ${owner.state.width}×${owner.state.height}`].filter(Boolean);
437
- console.log(` ${owner.id.padEnd(24)} ${ms(owner.ms).padStart(9)}${traits.length ? ` ${traits.join(", ")}` : ""}`);
467
+ const range = profile.rounds > 1 ? ` (${owner.range[0].toFixed(0)}–${owner.range[1].toFixed(0)})` : "";
468
+ console.log(` ${owner.id.padEnd(24)} ${ms(owner.ms).padStart(9)}${range.padEnd(12)}${traits.length ? ` ${traits.join(", ")}` : ""}`);
438
469
  }
439
470
  for (const hint of profile.hints)
440
471
  console.log(` ! ${hint}`);
@@ -470,6 +501,7 @@ A Board is one JSON document: { board, items, animations }.
470
501
  play shared playback; also pause, resume, next, seek, stop
471
502
  watch stream changes and playback
472
503
  history list versions, or restore one
504
+ diff what changed between two versions
473
505
  Times are milliseconds; 500ms, 12.5s and 2m also work on the command line.`);
474
506
  withJson(boards.command("create <path>")
475
507
  .description("Create a Board file, optionally with an initial document")
@@ -629,6 +661,42 @@ Times are milliseconds; 500ms, 12.5s and 2m also work on the command line.`);
629
661
  handleHttp(cause);
630
662
  }
631
663
  });
664
+ withJson(boards.command("diff <board>")
665
+ .description("List what changed between two versions, element by element")
666
+ .requiredOption("--from <version>", "The version to compare from")
667
+ .option("--to <version>", "The version to compare to; the latest by default"))
668
+ .addHelpText("after", `
669
+ Before rewriting a Board with apply --replace, see what others changed since the version you read:
670
+ cohub boards diff plan.board --from 41
671
+ cohub boards diff plan.board --from 41 --to 44 --json`)
672
+ .action(async (target, options) => {
673
+ try {
674
+ const board = await boardClient(boards, target);
675
+ const result = await board.diff(parseNumber(options.from, "--from", { min: 0, integer: true }), options.to === undefined ? undefined : parseNumber(options.to, "--to", { min: 1, integer: true }));
676
+ if (jsonRequested(options))
677
+ return outJson(result);
678
+ const by = new Map();
679
+ for (const { kind } of result.versions)
680
+ by.set(kind, (by.get(kind) ?? 0) + 1);
681
+ ok(`v${result.from} → v${result.to}: ${result.changes.length} element${result.changes.length === 1 ? "" : "s"} changed in ${result.versions.length} version${result.versions.length === 1 ? "" : "s"}${by.size ? ` (${[...by].map(([kind, count]) => `${count} by ${kind}`).join(", ")})` : ""}`);
682
+ const show = (value) => {
683
+ const text = value === undefined ? "∅" : JSON.stringify(value);
684
+ return text.length > 60 ? `${text.slice(0, 57)}…` : text;
685
+ };
686
+ for (const change of result.changes) {
687
+ const sign = change.change === "added" ? "+" : change.change === "removed" ? "-" : "~";
688
+ const name = change.kind === "board" ? "board" : `${change.kind} ${change.id}${change.type ? ` (${change.type})` : ""}`;
689
+ console.log(` ${sign} ${name}`);
690
+ for (const field of change.fields.slice(0, 12))
691
+ console.log(` ${field.path}: ${show(field.from)} → ${show(field.to)}`);
692
+ if (change.fields.length > 12)
693
+ console.log(` … ${change.fields.length - 12} more fields; --json lists them all`);
694
+ }
695
+ }
696
+ catch (cause) {
697
+ handleHttp(cause);
698
+ }
699
+ });
632
700
  boards.command("schema [target]")
633
701
  .description("Print JSON Schema for a part of a Board")
634
702
  .option("--field <path>", "Print one field, e.g. props.decoration or props.geometry")
@@ -2,6 +2,7 @@ import { openAsBlob } from "node:fs";
2
2
  import { stat } from "node:fs/promises";
3
3
  import { arch, platform, release } from "node:os";
4
4
  import { basename, resolve } from "node:path";
5
+ import { cliCommit } from "../version.js";
5
6
  import { mimeTypeForPath, readRequestSourceFromEnv, resolveApiBaseUrl, resolveCohubEnvironment } from "@neta-art/cohub";
6
7
  import { authSource } from "../auth.js";
7
8
  import { createClient } from "../client.js";
@@ -100,6 +101,7 @@ Examples:
100
101
  const extra = {
101
102
  user_uuid: userUuid,
102
103
  cli_version: program.version() ?? null,
104
+ cli_commit: cliCommit(),
103
105
  node: process.versions.node,
104
106
  os: `${platform()} ${release()}`,
105
107
  arch: arch(),
@@ -0,0 +1,2 @@
1
+ import type { Command } from "commander";
2
+ export declare function registerVersion(program: Command): void;
@@ -0,0 +1,21 @@
1
+ import { describeCli } from "../about.js";
2
+ import { json, jsonRequested } from "../output.js";
3
+ import { isNewerVersion } from "../self-update.js";
4
+ import { currentIdentityKey } from "../space.js";
5
+ export function registerVersion(program) {
6
+ program
7
+ .command("version")
8
+ .description("This CLI, the cohub on PATH, and the versions running Runtimes serve")
9
+ .option("--json", "JSON output")
10
+ .action(async (options) => {
11
+ const about = await describeCli(process.env, currentIdentityKey());
12
+ if (jsonRequested(options))
13
+ return json(about);
14
+ const rows = [
15
+ `cohub ${about.version}${about.commit ? ` (${about.commit})` : ""} · Node ${about.node}`,
16
+ `PATH ${about.path ? `${about.path.path} · ${about.path.version ?? "unknown"}` : "No cohub on PATH"}`,
17
+ ...about.runtimes.map((runtime, index) => `${index ? " " : "Runtimes "} ${runtime.version ?? "older"} · ${runtime.root}${isNewerVersion(about.version, runtime.version ?? undefined) ? " (reconnect to update)" : ""}`),
18
+ ];
19
+ process.stdout.write(`${rows.join("\n")}\n`);
20
+ });
21
+ }
@@ -1,6 +1,7 @@
1
1
  import { createInterface } from "node:readline";
2
2
  import { fileURLToPath } from "node:url";
3
- import { HOST_BRIDGE_ERROR, HOST_BRIDGE_METHODS, HOST_SERVICE_VERSION, HOST_SERVICE_WORKSPACE_ENDPOINT, HostBridgeErrorClass, hostBridgeRequestSchema, } from "@neta-art/cohub/host-bridge";
3
+ import { HOST_BRIDGE_ERROR, HOST_BRIDGE_METHODS, HOST_SERVICE_CLI_ABOUT, HOST_SERVICE_VERSION, HOST_SERVICE_WORKSPACE_ENDPOINT, HostBridgeErrorClass, hostBridgeRequestSchema, } from "@neta-art/cohub/host-bridge";
4
+ import { describeCli } from "../about.js";
4
5
  import { findLocalWorkspace } from "../runtime/local-workspace.js";
5
6
  import { currentIdentityKey } from "../space.js";
6
7
  import { HostAuth } from "./auth.js";
@@ -16,9 +17,11 @@ const write = (message) => process.stdout.write(`${JSON.stringify(message)}\n`);
16
17
  export async function serveHost(entry = fileURLToPath(new URL("../../bin/cohub.js", import.meta.url))) {
17
18
  const emit = (name, payload) => write({ type: "event", name, ...(payload === undefined ? {} : { payload }) });
18
19
  let environment = null;
20
+ const env = () => (environment ??= loginShellEnv());
21
+ const about = async () => describeCli(await env(), currentIdentityKey());
19
22
  const runtime = new DeviceRuntimeHost(emit, {
20
23
  cli: entry,
21
- env: () => (environment ??= loginShellEnv()),
24
+ env,
22
25
  account: currentIdentityKey,
23
26
  });
24
27
  const auth = new HostAuth(emit, () => {
@@ -47,8 +50,9 @@ export async function serveHost(entry = fileURLToPath(new URL("../../bin/cohub.j
47
50
  } : {}),
48
51
  "workspace.call": (params) => callLocalWorkspace(String(params.spaceId), String(params.method), params.params),
49
52
  };
50
- // Asked by the shell itself to proxy file URLs; absent from hello, so a page can never reach it.
53
+ // Asked by the shell itself; absent from hello, so a page can never reach them.
51
54
  const shellHandlers = {
55
+ [HOST_SERVICE_CLI_ABOUT]: about,
52
56
  [HOST_SERVICE_WORKSPACE_ENDPOINT]: (params) => {
53
57
  const spaceId = String(params.spaceId ?? "");
54
58
  if (!SPACE_ID.test(spaceId))
@@ -101,6 +105,8 @@ export async function serveHost(entry = fileURLToPath(new URL("../../bin/cohub.j
101
105
  write(hello);
102
106
  auth.watch();
103
107
  runtime.watch();
108
+ // Probed once off the start-up path, so an About panel opens with its answer ready.
109
+ setTimeout(() => void about().catch(() => undefined), 3_000).unref();
104
110
  const input = createInterface({ input: process.stdin, crlfDelay: Infinity });
105
111
  input.on("line", (line) => { if (line.length <= MAX_LINE)
106
112
  void answer(line); });
package/dist/index.js CHANGED
@@ -1,6 +1,5 @@
1
1
  #!/usr/bin/env node
2
2
  import { Command } from "commander";
3
- import { readFileSync } from "node:fs";
4
3
  import { registerEndpointOptions } from "./endpoint-options.js";
5
4
  import { registerAuth } from "./commands/auth.js";
6
5
  import { registerBoards } from "./commands/boards.js";
@@ -23,24 +22,17 @@ import { registerRuntime } from "./commands/runtime.js";
23
22
  import { registerTasks } from "./commands/tasks.js";
24
23
  import { registerDesktop, registerLegacyUi } from "./commands/desktop.js";
25
24
  import { registerHost } from "./commands/host.js";
25
+ import { registerVersion } from "./commands/version.js";
26
26
  import { registerApps } from "./commands/apps.js";
27
27
  import { registerRooms } from "./commands/rooms.js";
28
28
  import { formatUnknownCommandError, resolveHelpPath } from "./help-path.js";
29
- const VERSION = (() => {
30
- try {
31
- const pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf-8"));
32
- return pkg.version;
33
- }
34
- catch {
35
- return "1.0.0";
36
- }
37
- })();
29
+ import { CLI_VERSION } from "./version.js";
38
30
  const program = registerEndpointOptions(new Command("cohub"));
39
31
  program
40
32
  .name("cohub")
41
33
  .summary("Work with Cohub from your terminal")
42
34
  .description("Send prompts, manage Space files, and publish public output.")
43
- .version(VERSION, "-v, --version", "Show version")
35
+ .version(CLI_VERSION, "-v, --version", "Show version")
44
36
  .option("-s, --space <space>", "Target Space: ID, slug, or username/slug")
45
37
  .option("--json", "Print machine-readable JSON when supported")
46
38
  .helpOption("-h, --help", "Show help")
@@ -116,6 +108,7 @@ registerFeedback(program);
116
108
  registerDesktop(program);
117
109
  registerLegacyUi(program);
118
110
  registerHost(program);
111
+ registerVersion(program);
119
112
  const argv = process.argv.slice(2);
120
113
  const help = resolveHelpPath(program, argv);
121
114
  if (help.kind === "help") {