@1agh/maude 2.0.2 → 2.0.4

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.
Files changed (154) hide show
  1. package/README.md +6 -5
  2. package/apps/studio/access/request.ts +0 -1
  3. package/apps/studio/acp/adapter-stderr.ts +43 -13
  4. package/apps/studio/acp/background-tasks.ts +155 -0
  5. package/apps/studio/acp/bridge.ts +44 -5
  6. package/apps/studio/acp/connected-fact.ts +15 -4
  7. package/apps/studio/acp/index.ts +14 -5
  8. package/apps/studio/actions/agents.ts +5 -0
  9. package/apps/studio/actions/defs/view.ts +12 -0
  10. package/apps/studio/actions.manifest.json +13 -1
  11. package/apps/studio/actions.parity.json +7 -1
  12. package/apps/studio/api.ts +31 -24
  13. package/apps/studio/asset-placeholder.tsx +157 -62
  14. package/apps/studio/bin/_png-playwright.mjs +10 -1
  15. package/apps/studio/bin/_pw-launch.mjs +14 -0
  16. package/apps/studio/bin/_thumbs-playwright.mjs +4 -1
  17. package/apps/studio/boot-progress.ts +31 -0
  18. package/apps/studio/bridge/dgn-protocol.ts +34 -4
  19. package/apps/studio/canvas-build-sandbox.ts +275 -42
  20. package/apps/studio/canvas-build-worker.ts +10 -0
  21. package/apps/studio/canvas-create.ts +24 -0
  22. package/apps/studio/canvas-module-cache.ts +93 -0
  23. package/apps/studio/canvas-source/errors.ts +39 -0
  24. package/apps/studio/canvas-source/waiting.ts +290 -0
  25. package/apps/studio/client/actions/shell-key-handlers.js +5 -0
  26. package/apps/studio/client/app.jsx +22 -9
  27. package/apps/studio/client/github.js +23 -3
  28. package/apps/studio/client/home/home-api.js +30 -19
  29. package/apps/studio/client/hooks/use-git-actions.jsx +2 -1
  30. package/apps/studio/client/hooks/use-shell-core.jsx +3 -0
  31. package/apps/studio/client/hooks/use-tabs.jsx +64 -35
  32. package/apps/studio/client/index-loader.ts +23 -3
  33. package/apps/studio/client/panels/ChatPanel.jsx +22 -37
  34. package/apps/studio/client/panels/DiffView.jsx +314 -248
  35. package/apps/studio/client/panels/TeamProjects.jsx +119 -69
  36. package/apps/studio/client/panels/acp-runtime.js +25 -0
  37. package/apps/studio/client/panels/chat-finish.js +66 -0
  38. package/apps/studio/client/shell/frame-cap.js +53 -0
  39. package/apps/studio/client/shell/viewport.jsx +9 -0
  40. package/apps/studio/client/styles/_index.css +2 -0
  41. package/apps/studio/client/tree/tree.jsx +48 -21
  42. package/apps/studio/client/v2/ai/BackgroundStrip.jsx +120 -0
  43. package/apps/studio/client/v2/ai/StoppedDivider.jsx +2 -1
  44. package/apps/studio/client/v2/ai/ai-run.css +87 -3
  45. package/apps/studio/client/v2/ai/background-model.js +113 -0
  46. package/apps/studio/client/v2/ai/needs-you-store.js +2 -1
  47. package/apps/studio/client/v2/ai/run-api.js +7 -3
  48. package/apps/studio/client/v2/ai/runs-store.js +2 -1
  49. package/apps/studio/client/v2/annotations/vote-store.js +11 -5
  50. package/apps/studio/client/v2/assets/asset-state-lane.js +176 -8
  51. package/apps/studio/client/v2/assets/assets-bus.js +10 -8
  52. package/apps/studio/client/v2/assets/browse-view.jsx +2 -0
  53. package/apps/studio/client/v2/assets/ds-library-view.jsx +47 -0
  54. package/apps/studio/client/v2/assets/missing-frame.jsx +8 -4
  55. package/apps/studio/client/v2/assets/spotlight-model.js +75 -0
  56. package/apps/studio/client/v2/assets/spotlight.css +153 -0
  57. package/apps/studio/client/v2/assets/spotlight.jsx +199 -0
  58. package/apps/studio/client/v2/assets/tile-menu.jsx +3 -1
  59. package/apps/studio/client/v2/assets/tile.jsx +3 -0
  60. package/apps/studio/client/v2/assets/use-assets.js +2 -1
  61. package/apps/studio/client/v2/canvases/canvases-panel.jsx +13 -2
  62. package/apps/studio/client/v2/canvases/covers.js +11 -5
  63. package/apps/studio/client/v2/canvases/folder-ask.js +139 -0
  64. package/apps/studio/client/v2/canvases/folder-dialogs.jsx +150 -0
  65. package/apps/studio/client/v2/canvases/trash-canvas.js +10 -2
  66. package/apps/studio/client/v2/canvases/trash-queue.js +152 -0
  67. package/apps/studio/client/v2/canvases/use-canvas-index.js +42 -18
  68. package/apps/studio/client/v2/canvases/use-pins.js +2 -1
  69. package/apps/studio/client/v2/code/canvas-error-card.jsx +70 -5
  70. package/apps/studio/client/v2/code/canvas-waiting-card.jsx +128 -0
  71. package/apps/studio/client/v2/code/canvas-waiting.js +164 -0
  72. package/apps/studio/client/v2/code/code.css +67 -0
  73. package/apps/studio/client/v2/code/use-canvas-source.js +19 -4
  74. package/apps/studio/client/v2/create/NameDialog.jsx +4 -2
  75. package/apps/studio/client/v2/create/name-dialog.css +10 -0
  76. package/apps/studio/client/v2/ds/advanced-host.jsx +5 -2
  77. package/apps/studio/client/v2/ds/make-host.jsx +5 -2
  78. package/apps/studio/client/v2/ds/off-system-host.jsx +5 -2
  79. package/apps/studio/client/v2/ds/truth-host.jsx +5 -2
  80. package/apps/studio/client/v2/empty/arriving.jsx +29 -12
  81. package/apps/studio/client/v2/empty/empty-host.jsx +8 -2
  82. package/apps/studio/client/v2/empty/not-local.jsx +31 -1
  83. package/apps/studio/client/v2/empty/use-empty-canvas.js +10 -1
  84. package/apps/studio/client/v2/export/last-finished.js +2 -1
  85. package/apps/studio/client/v2/export/native-save.js +44 -0
  86. package/apps/studio/client/v2/history/git-model.js +18 -4
  87. package/apps/studio/client/v2/history/git-parts.jsx +60 -42
  88. package/apps/studio/client/v2/history/history.css +6 -0
  89. package/apps/studio/client/v2/left-panel/assets-panel.jsx +87 -10
  90. package/apps/studio/client/v2/left-panel/use-trash.js +2 -1
  91. package/apps/studio/client/v2/onboarding/AdvancedSheets.jsx +100 -33
  92. package/apps/studio/client/v2/onboarding/HubSheet.jsx +51 -83
  93. package/apps/studio/client/v2/onboarding/onboarding-model.js +10 -6
  94. package/apps/studio/client/v2/present/order-notes-artboards.js +2 -1
  95. package/apps/studio/client/v2/search/search-recent.js +3 -1
  96. package/apps/studio/client/v2/search/search-remote.js +6 -4
  97. package/apps/studio/client/v2/settings/connections-model.js +1 -1
  98. package/apps/studio/client/v2/shell/menu-runner.js +1 -0
  99. package/apps/studio/client/v2/shell/occlusion-insets.js +14 -2
  100. package/apps/studio/client/v2/shell/recovery-store.js +2 -1
  101. package/apps/studio/client/v2/shell/served-routes.js +120 -0
  102. package/apps/studio/client/v2/shell/share-cluster-host.jsx +2 -1
  103. package/apps/studio/client/v2/shell/shell-activity.js +19 -0
  104. package/apps/studio/client/v2/shell/use-occluded-insets.js +3 -0
  105. package/apps/studio/client/v2/sync-states/conflict-card.jsx +7 -2
  106. package/apps/studio/client/v2/undo/use-undo-projection.jsx +3 -1
  107. package/apps/studio/cloud/endpoints.ts +23 -1
  108. package/apps/studio/dist/client.bundle.js +798 -801
  109. package/apps/studio/dist/comment-mount.js +2 -2
  110. package/apps/studio/dist/styles.css +1 -1
  111. package/apps/studio/ds-assets.ts +138 -48
  112. package/apps/studio/editing/minimap-context.tsx +3 -3
  113. package/apps/studio/editing/page-activity.ts +251 -0
  114. package/apps/studio/editing/rotate-handle.tsx +9 -5
  115. package/apps/studio/editing/sticky-name.tsx +4 -4
  116. package/apps/studio/history/restore-artboard-action.ts +40 -0
  117. package/apps/studio/home/hub.ts +77 -175
  118. package/apps/studio/home/routes.ts +47 -8
  119. package/apps/studio/http.ts +117 -66
  120. package/apps/studio/index-flight.ts +40 -0
  121. package/apps/studio/managed-projects.ts +52 -24
  122. package/apps/studio/migrate/hub.ts +7 -1
  123. package/apps/studio/routes/asset-state.ts +12 -0
  124. package/apps/studio/routes/canvas-source.ts +44 -2
  125. package/apps/studio/routes/ds-assets.ts +8 -0
  126. package/apps/studio/routes/history.ts +28 -5
  127. package/apps/studio/routes/hub-signin.ts +115 -0
  128. package/apps/studio/routes/index.ts +4 -0
  129. package/apps/studio/routes/table.ts +7 -0
  130. package/apps/studio/routes/trash.ts +3 -0
  131. package/apps/studio/server.ts +11 -0
  132. package/apps/studio/sync/accepted-cold-start.ts +26 -3
  133. package/apps/studio/sync/accepted-link.ts +9 -4
  134. package/apps/studio/sync/asset-push.ts +8 -1
  135. package/apps/studio/sync/asset-state.ts +27 -2
  136. package/apps/studio/sync/code-module-consent.ts +74 -0
  137. package/apps/studio/sync/file-ledger.ts +35 -0
  138. package/apps/studio/sync/file-plane.ts +479 -84
  139. package/apps/studio/sync/hub-browser-signin.ts +377 -0
  140. package/apps/studio/sync/hub-text-undo.ts +30 -10
  141. package/apps/studio/sync/index.ts +73 -11
  142. package/apps/studio/sync/lfs-pointer.ts +137 -0
  143. package/apps/studio/sync/projection.ts +44 -2
  144. package/apps/studio/sync/pull-pacer.ts +160 -0
  145. package/apps/studio/sync/pull-priority.ts +119 -0
  146. package/apps/studio/sync/seed-progress.ts +47 -3
  147. package/apps/studio/sync/transaction-client.ts +71 -6
  148. package/apps/studio/sync/workspace-signin.ts +6 -256
  149. package/apps/studio/sync/writer-registry.ts +5 -1
  150. package/apps/studio/video-links-overlay.tsx +3 -2
  151. package/apps/studio/whats-new.json +63 -0
  152. package/cli/lib/design-help.gen.mjs +1 -1
  153. package/cli/lib/workspace-plan.mjs +14 -0
  154. package/package.json +8 -8
@@ -24,14 +24,89 @@ import { existsSync, readFileSync, statSync } from 'node:fs';
24
24
  import { dirname, join, resolve, sep } from 'node:path';
25
25
 
26
26
  import { bothForms } from './access/frame.ts';
27
+ import { budgetFromEnv, createModuleCache } from './canvas-module-cache.ts';
27
28
  import { DEV_SERVER_ROOT } from './paths.ts';
28
29
 
29
- /** Wall clock a single canvas build may take. */
30
- export const BUILD_TIMEOUT_MS = Number(process.env.MAUDE_CANVAS_BUILD_TIMEOUT_MS ?? 20_000);
30
+ const warnedKnobs = new Set<string>();
31
+
32
+ /**
33
+ * One sandbox ceiling from the environment: a whole number inside `[min, max]`. Anything that is not
34
+ * a number falls back to `def`; a number outside the range is clamped. Either is said once per
35
+ * process — an operator who typed `90s` must learn it was ignored, but a request loop must not
36
+ * repeat it. (`Number('')` is 0 and `Number('abc')` is NaN: both used to reach `setTimeout` as-is,
37
+ * and a NaN deadline fires at once — every build "timed out" immediately.)
38
+ */
39
+ export function sandboxKnob(
40
+ env: NodeJS.ProcessEnv,
41
+ name: string,
42
+ def: number,
43
+ min: number,
44
+ max: number
45
+ ): number {
46
+ const raw = env[name];
47
+ if (raw === undefined || raw === '') return def;
48
+ const n = Number(raw.trim());
49
+ const say = (msg: string) => {
50
+ if (warnedKnobs.has(name)) return;
51
+ warnedKnobs.add(name);
52
+ console.warn(`[canvas-build] ${name} ${msg}`);
53
+ };
54
+ if (!/^\d+$/.test(raw.trim()) || !Number.isSafeInteger(n)) {
55
+ say(`is not a whole number; using ${def}`);
56
+ return def;
57
+ }
58
+ if (n < min || n > max) {
59
+ const c = Math.min(max, Math.max(min, n));
60
+ say(`${n} is outside ${min}–${max}; using ${c}`);
61
+ return c;
62
+ }
63
+ return n;
64
+ }
65
+
66
+ /**
67
+ * The HARD ceiling: wall clock a build may run before it is stopped, whether or not anyone is still
68
+ * waiting for it (2.0.4 task P). It was 20 s and was also the request's wait, so a design system
69
+ * board that needs 30 s on a shared host was killed on every open and — a timed-out build is never
70
+ * cached — never drew. A build now outlives its request up to this ceiling and is cached; one per
71
+ * canvas at a time (a newer source supersedes it), so the ceiling bounds the CPU a canvas can hold.
72
+ */
73
+ export const BUILD_TIMEOUT_MS = sandboxKnob(
74
+ process.env,
75
+ 'MAUDE_CANVAS_BUILD_TIMEOUT_MS',
76
+ 90_000,
77
+ 5_000,
78
+ 600_000
79
+ );
80
+ /**
81
+ * How long a REQUEST waits for its build. Past it the request answers "still building" (503 +
82
+ * Retry-After) and the build goes on; the next open is a cache hit. Never longer than the ceiling.
83
+ */
84
+ export const BUILD_WAIT_MS = Math.min(
85
+ BUILD_TIMEOUT_MS,
86
+ sandboxKnob(process.env, 'MAUDE_CANVAS_BUILD_WAIT_MS', 20_000, 1_000, 120_000)
87
+ );
31
88
  /** Resident memory a build process may reach before it is killed. */
32
- export const BUILD_RSS_LIMIT_MB = Number(process.env.MAUDE_CANVAS_BUILD_RSS_MB ?? 768);
33
- /** How many built modules to keep. Each is a string; canvases are ~100–400 kB. */
34
- export const CACHE_MAX_ENTRIES = Number(process.env.MAUDE_CANVAS_CACHE_ENTRIES ?? 64);
89
+ export const BUILD_RSS_LIMIT_MB = sandboxKnob(
90
+ process.env,
91
+ 'MAUDE_CANVAS_BUILD_RSS_MB',
92
+ 768,
93
+ 128,
94
+ 8_192
95
+ );
96
+ /** How many built modules to keep. Each is a string that bundles the shared chrome — ~2 MB of
97
+ * text however small the canvas (issue #204), so the byte bound below is the one that bites. */
98
+ export const CACHE_MAX_ENTRIES = sandboxKnob(
99
+ process.env,
100
+ 'MAUDE_CANVAS_CACHE_ENTRIES',
101
+ 64,
102
+ 1,
103
+ 1_024
104
+ );
105
+ /** Issue #204 — what the kept modules may weigh in all, counted at two bytes a character (a JS
106
+ * string holding any non-Latin-1 character). The module route keeps its own byte-bounded copy in
107
+ * front of this one (http.ts `canvasCache`), so this cache only saves a rebuild after that one
108
+ * evicted; 64 two-megabyte strings held here were ~270 MB of a cell's heap. */
109
+ export const CACHE_MAX_BYTES = budgetFromEnv('MAUDE_CANVAS_SANDBOX_CACHE_MB', 32);
35
110
 
36
111
  export interface SandboxBuildOk {
37
112
  ok: true;
@@ -45,11 +120,18 @@ export interface SandboxBuildOk {
45
120
  export interface SandboxBuildFail {
46
121
  ok: false;
47
122
  error: string;
48
- kind: 'build' | 'timeout' | 'memory' | 'runtime';
123
+ /**
124
+ * `building` is not a failure: the request's wait ran out while the build goes on (task P), or a
125
+ * newer source superseded it. `settled` is the build itself, for whoever records its outcome.
126
+ */
127
+ kind: 'build' | 'timeout' | 'memory' | 'runtime' | 'building';
128
+ settled?: Promise<SandboxBuildResult>;
49
129
  /** How many imports the allowlist refused. A COUNT — never the specifiers. */
50
130
  rejectedImports?: number;
51
131
  /** gate-b-c4m — the canvas's own source did not parse (a `TranspileError`), nothing it imports. */
52
132
  transpile?: boolean;
133
+ /** #189 — the worker stopped before its build engine loaded (Maude's side, never the canvas's). */
134
+ engine?: boolean;
53
135
  }
54
136
  export type SandboxBuildResult = SandboxBuildOk | SandboxBuildFail;
55
137
 
@@ -72,6 +154,8 @@ const counters = {
72
154
  memoryKills: 0,
73
155
  /** Imports the allowlist refused. The COUNT only — see buildStats(). */
74
156
  rejectedImports: 0,
157
+ /** Requests whose wait ran out while their build went on (task P). */
158
+ stillBuilding: 0,
75
159
  /** Summed wall-clock of completed builds, the closest thing to Active-CPU
76
160
  * this side of the boundary can honestly report. */
77
161
  cpuMsTotal: 0,
@@ -92,6 +176,7 @@ function rollWindow(now: number): void {
92
176
  counters.timeouts = 0;
93
177
  counters.memoryKills = 0;
94
178
  counters.rejectedImports = 0;
179
+ counters.stillBuilding = 0;
95
180
  counters.cpuMsTotal = 0;
96
181
  counters.largestGraphBytes = 0;
97
182
  counters.durationsMs = [];
@@ -135,6 +220,9 @@ export function buildStats() {
135
220
  timeouts: counters.timeouts,
136
221
  memoryKills: counters.memoryKills,
137
222
  rejectedImports: counters.rejectedImports,
223
+ stillBuilding: counters.stillBuilding,
224
+ /** Builds running right now (a gauge, not windowed). */
225
+ inFlight: inflight.size,
138
226
  cpuMsTotal: counters.cpuMsTotal,
139
227
  largestGraphBytes: counters.largestGraphBytes,
140
228
  p50Ms: p(0.5),
@@ -155,11 +243,40 @@ export function noteRejectedImport(): void {
155
243
  export function _resetBuildStats(): void {
156
244
  rollWindow(Date.now());
157
245
  cache.clear();
246
+ for (const run of inflight.values()) run.stop(SUPERSEDED);
247
+ inflight.clear();
158
248
  }
159
249
 
160
250
  type CachedBuild = { js: string; locator: unknown; etag: string; inputs: string[] };
161
- /** key → { js, locator, etag, inputs } */
162
- const cache = new Map<string, CachedBuild>();
251
+ /** key → { js, locator, etag, inputs }, LRU under both bounds. */
252
+ const cache = createModuleCache<{ bytes: number; build: CachedBuild }>({
253
+ maxBytes: CACHE_MAX_BYTES,
254
+ maxEntries: CACHE_MAX_ENTRIES,
255
+ });
256
+
257
+ /** A build that is running: who it is for, its outcome, and how to stop it early. */
258
+ interface Inflight {
259
+ key: string;
260
+ promise: Promise<SandboxBuildResult>;
261
+ stop: (outcome: SandboxBuildFail) => void;
262
+ }
263
+ /**
264
+ * canvas (absolute) → its ONE running build (task P). Concurrent opens of the same source share it;
265
+ * a request for a newer source of the same canvas stops it first, so a canvas never holds more than
266
+ * one build's CPU and memory, however many people open it or however fast it is edited.
267
+ */
268
+ const inflight = new Map<string, Inflight>();
269
+
270
+ const SUPERSEDED: SandboxBuildFail = {
271
+ ok: false,
272
+ kind: 'building',
273
+ error: 'a newer version of this canvas is being built.',
274
+ };
275
+
276
+ /** Whether a build of this canvas is running now — what `/_api/canvas-errors` says as `building`. */
277
+ export function sandboxBuildRunning(canvasAbs: string): boolean {
278
+ return inflight.has(resolve(canvasAbs));
279
+ }
163
280
 
164
281
  /**
165
282
  * The cache key: the canvas source plus every sibling source it could pull in.
@@ -238,11 +355,7 @@ function graphBytes(designRoot: string, canvasAbs: string): number {
238
355
  }
239
356
 
240
357
  function remember(key: string, value: CachedBuild): void {
241
- cache.set(key, value);
242
- while (cache.size > CACHE_MAX_ENTRIES) {
243
- const oldest = cache.keys().next().value as string;
244
- cache.delete(oldest);
245
- }
358
+ cache.set(key, { bytes: value.js.length * 2, build: value });
246
359
  }
247
360
 
248
361
  /**
@@ -337,21 +450,80 @@ export async function buildCanvasSandboxed({
337
450
  canvasAbs,
338
451
  assetUrlBase,
339
452
  env = process.env,
453
+ waitMs,
454
+ ceilingMs,
340
455
  }: {
341
456
  designRoot: string;
342
457
  canvasAbs: string;
343
458
  /** BuildCanvasOptions.assetUrlBase, passed to the worker as argv[4]. */
344
459
  assetUrlBase?: string;
345
460
  env?: NodeJS.ProcessEnv;
461
+ /** How long this request waits (default `BUILD_WAIT_MS`); the build itself may run to the ceiling. */
462
+ waitMs?: number;
463
+ /** The hard ceiling for a build this call starts (default `BUILD_TIMEOUT_MS`). */
464
+ ceilingMs?: number;
346
465
  }): Promise<SandboxBuildResult> {
347
466
  maybeRoll();
348
467
  const key = cacheKeyFor(designRoot, canvasAbs);
349
- const hit = cache.get(key);
468
+ const hit = cache.get(key)?.build;
350
469
  if (hit) {
351
470
  counters.cacheHits++;
352
471
  return { ...hit, ok: true, cached: true };
353
472
  }
354
- counters.cacheMisses++;
473
+ const id = resolve(canvasAbs);
474
+ let run = inflight.get(id);
475
+ if (run && run.key !== key) {
476
+ // The source moved on: the running build can only produce a module nobody will be served.
477
+ run.stop(SUPERSEDED);
478
+ run = undefined;
479
+ }
480
+ if (!run) {
481
+ counters.cacheMisses++;
482
+ run = startBuild({
483
+ id,
484
+ key,
485
+ designRoot,
486
+ canvasAbs,
487
+ assetUrlBase,
488
+ env,
489
+ ceilingMs: ceilingMs ?? BUILD_TIMEOUT_MS,
490
+ });
491
+ }
492
+ const wait = Math.max(0, Math.min(waitMs ?? BUILD_WAIT_MS, ceilingMs ?? BUILD_TIMEOUT_MS));
493
+ let timer: ReturnType<typeof setTimeout> | undefined;
494
+ const waited = new Promise<null>((done) => {
495
+ timer = setTimeout(() => done(null), wait);
496
+ });
497
+ const result = await Promise.race([run.promise, waited]);
498
+ clearTimeout(timer);
499
+ if (result !== null) return result;
500
+ counters.stillBuilding++;
501
+ return {
502
+ ok: false,
503
+ kind: 'building',
504
+ error: 'this canvas is still being built.',
505
+ settled: run.promise,
506
+ };
507
+ }
508
+
509
+ /** Start the one build of `key` for canvas `id`, registered until it settles. */
510
+ function startBuild({
511
+ id,
512
+ key,
513
+ designRoot,
514
+ canvasAbs,
515
+ assetUrlBase,
516
+ env,
517
+ ceilingMs,
518
+ }: {
519
+ id: string;
520
+ key: string;
521
+ designRoot: string;
522
+ canvasAbs: string;
523
+ assetUrlBase?: string;
524
+ env: NodeJS.ProcessEnv;
525
+ ceilingMs: number;
526
+ }): Inflight {
355
527
  // The pathological-canvas signal, measured rather than argued: a huge import
356
528
  // graph burns our Active-CPU while the tenant pays a flat rate. Bytes, never
357
529
  // filenames.
@@ -359,30 +531,61 @@ export async function buildCanvasSandboxed({
359
531
  counters.largestGraphBytes,
360
532
  graphBytes(designRoot, canvasAbs)
361
533
  );
362
-
534
+ let stopEarly: ((outcome: SandboxBuildFail) => void) | null = null;
535
+ let stoppedWith: SandboxBuildFail | null = null;
536
+ const entry: Inflight = {
537
+ key,
538
+ stop: (outcome) => {
539
+ stoppedWith ??= outcome;
540
+ stopEarly?.(outcome);
541
+ },
542
+ promise: Promise.resolve(null as unknown as SandboxBuildResult),
543
+ };
363
544
  const started = Date.now();
364
- const result = await runWorker({ designRoot, canvasAbs, assetUrlBase, env });
365
- const elapsed = Date.now() - started;
366
- counters.cpuMsTotal += elapsed;
367
- counters.durationsMs.push(elapsed);
368
- if (counters.durationsMs.length > 200) counters.durationsMs.shift();
369
-
370
- if (result.ok) {
371
- counters.builds++;
372
- const value = {
373
- js: result.js,
374
- locator: result.locator,
375
- etag: result.etag,
376
- inputs: result.inputs,
377
- };
378
- remember(key, value);
379
- return { ...value, ok: true, cached: false };
380
- }
381
- counters.failures++;
382
- if (result.kind === 'timeout') counters.timeouts++;
383
- if (result.kind === 'memory') counters.memoryKills++;
384
- counters.rejectedImports += result.rejectedImports ?? 0;
385
- return result;
545
+ entry.promise = (async (): Promise<SandboxBuildResult> => {
546
+ try {
547
+ const result = stoppedWith
548
+ ? stoppedWith
549
+ : await runWorker({
550
+ designRoot,
551
+ canvasAbs,
552
+ assetUrlBase,
553
+ env,
554
+ ceilingMs,
555
+ onStart: (stop) => {
556
+ stopEarly = stop;
557
+ if (stoppedWith) stop(stoppedWith);
558
+ },
559
+ });
560
+ const elapsed = Date.now() - started;
561
+ counters.cpuMsTotal += elapsed;
562
+ counters.durationsMs.push(elapsed);
563
+ if (counters.durationsMs.length > 200) counters.durationsMs.shift();
564
+ if (result.ok) {
565
+ counters.builds++;
566
+ const value = {
567
+ js: result.js,
568
+ locator: result.locator,
569
+ etag: result.etag,
570
+ inputs: result.inputs,
571
+ };
572
+ // Cached whether or not the request that started it is still waiting: that is the point —
573
+ // the client that gave up gets this on its next open.
574
+ remember(key, value);
575
+ return { ...value, ok: true, cached: false };
576
+ }
577
+ if (result.kind === 'building') return result; // superseded — not a failure of this canvas
578
+ counters.failures++;
579
+ if (result.kind === 'timeout') counters.timeouts++;
580
+ if (result.kind === 'memory') counters.memoryKills++;
581
+ counters.rejectedImports += result.rejectedImports ?? 0;
582
+ return result;
583
+ } finally {
584
+ if (inflight.get(id) === entry) inflight.delete(id);
585
+ }
586
+ })();
587
+ inflight.set(id, entry);
588
+ return entry;
386
589
  }
387
590
 
388
591
  async function runWorker({
@@ -390,11 +593,16 @@ async function runWorker({
390
593
  canvasAbs,
391
594
  assetUrlBase,
392
595
  env,
596
+ ceilingMs = BUILD_TIMEOUT_MS,
597
+ onStart,
393
598
  }: {
394
599
  designRoot: string;
395
600
  canvasAbs: string;
396
601
  assetUrlBase?: string;
397
602
  env: NodeJS.ProcessEnv;
603
+ ceilingMs?: number;
604
+ /** Hands the caller a way to stop this build early with a given outcome (supersede). */
605
+ onStart?: (stop: (outcome: SandboxBuildFail) => void) => void;
398
606
  }): Promise<SandboxBuildResult> {
399
607
  const bun = resolveBunPath(env);
400
608
  let child: Bun.Subprocess<'ignore', 'pipe', 'pipe'>;
@@ -419,15 +627,19 @@ async function runWorker({
419
627
  }
420
628
 
421
629
  let outcome: SandboxBuildFail | null = null;
630
+ onStart?.((early) => {
631
+ outcome ??= early;
632
+ child.kill('SIGKILL');
633
+ });
422
634
 
423
635
  const deadline = setTimeout(() => {
424
- outcome = {
636
+ outcome ??= {
425
637
  ok: false,
426
638
  kind: 'timeout',
427
- error: `this canvas took longer than ${Math.round(BUILD_TIMEOUT_MS / 1000)}s to build and was stopped.`,
639
+ error: `this canvas took longer than ${Math.round(ceilingMs / 1000)}s to build and was stopped.`,
428
640
  };
429
641
  child.kill('SIGKILL');
430
- }, BUILD_TIMEOUT_MS);
642
+ }, ceilingMs);
431
643
 
432
644
  // RSS ceiling. A hard `ulimit -v` is the obvious alternative and does not
433
645
  // work: JS runtimes reserve enormous virtual address space and would die
@@ -436,7 +648,7 @@ async function runWorker({
436
648
  const rssPoll = setInterval(() => {
437
649
  const mb = rssMb(child.pid);
438
650
  if (mb !== null && mb > BUILD_RSS_LIMIT_MB) {
439
- outcome = {
651
+ outcome ??= {
440
652
  ok: false,
441
653
  kind: 'memory',
442
654
  error: `this canvas needed more than ${BUILD_RSS_LIMIT_MB} MB to build and was stopped.`,
@@ -491,6 +703,7 @@ async function runWorker({
491
703
  error: String(parsed.error),
492
704
  rejectedImports: Number(parsed.rejectedImports ?? 0) || 0,
493
705
  transpile: parsed.transpile === true,
706
+ ...(parsed.stage === 'engine' ? { engine: true } : {}),
494
707
  };
495
708
  } catch {
496
709
  return {
@@ -512,3 +725,23 @@ function rssMb(pid: number | undefined): number | null {
512
725
  return null; // macOS dev boxes: the wall-clock ceiling still applies
513
726
  }
514
727
  }
728
+
729
+ /**
730
+ * #189 — why a sandboxed build stopped, as a class the card may show, or null when the reason is
731
+ * the canvas's own code (a syntax error, which `/_api/canvas-errors` re-reads from the file; or a
732
+ * build error the sandbox keeps illegible, gate-b-c4m). From the host's own fields only — `kind`,
733
+ * the worker's stage flag and the refusal COUNT — never from `error`, which quotes the build.
734
+ */
735
+ export function sandboxFailureClass(
736
+ built: SandboxBuildFail
737
+ ): import('./canvas-source/errors.ts').BuildFailure | null {
738
+ if (built.kind === 'building') return null; // still running — /_api/canvas-errors says `building`
739
+ if (built.kind === 'timeout') return { class: 'timed-out' };
740
+ if (built.kind === 'memory') return { class: 'memory' };
741
+ if (built.kind === 'runtime') return { class: 'engine' };
742
+ if (built.transpile) return null;
743
+ if (built.engine) return { class: 'engine' };
744
+ const n = Number(built.rejectedImports ?? 0);
745
+ if (Number.isFinite(n) && n > 0) return { class: 'imports-refused', count: Math.floor(n) };
746
+ return null;
747
+ }
@@ -67,6 +67,14 @@ function studioDir(): string {
67
67
  */
68
68
  let isTranspileError: (err: unknown) => boolean = () => false;
69
69
 
70
+ /**
71
+ * #189 — where the failure happened, by OUR control flow: `engine` until the build engine has
72
+ * loaded (a missing studio module — the 2.0.0 `Cannot find module …` — is Maude's, never the
73
+ * canvas's), `build` once the canvas's own build starts. The host turns it into a class; the
74
+ * message never decides it.
75
+ */
76
+ let stage: 'engine' | 'build' = 'engine';
77
+
70
78
  async function main() {
71
79
  const pipeline = (await import(join(studioDir(), 'canvas-pipeline.ts'))) as {
72
80
  TranspileError: abstract new (...args: never[]) => Error;
@@ -77,6 +85,7 @@ async function main() {
77
85
  process.exit(2);
78
86
  }
79
87
  const { buildCanvasModule } = await import(join(studioDir(), 'canvas-build.ts'));
88
+ stage = 'build';
80
89
  const source = await Bun.file(canvasAbs).text();
81
90
  const built = await buildCanvasModule(canvasAbs, source, {
82
91
  designRoot,
@@ -110,6 +119,7 @@ main().catch((err) => {
110
119
  // gate-b-c4m — a syntax error in the canvas's own source (the host keeps only that legible
111
120
  // to a frame; any other failure answers like a refusal).
112
121
  transpile: isTranspileError(err),
122
+ stage,
113
123
  })
114
124
  );
115
125
  process.exit(1);
@@ -61,6 +61,30 @@ export function underscoreRefusal(suggestion?: string | null): string {
61
61
  : 'Names can’t start with _. Try another name.';
62
62
  }
63
63
 
64
+ /**
65
+ * #195 (2.0.4) — the words a refused folder create / rename / move / trash says, CONTRACT §4 (what happened ·
66
+ * what is safe · one verb). The tree's folder dialogs show the server's words as they are, so these replace
67
+ * the old lower-case developer strings ("parent must be inside a managed canvas group", "the project did not
68
+ * accept this folder (code)") the person used to read in a toast. Containment refusals a UI cannot reach
69
+ * (traversal, symlinks) keep their technical words.
70
+ */
71
+ export const FOLDER_WORDS = Object.freeze({
72
+ /** a parent outside every non-design-system canvas folder */
73
+ notHere: 'Folders go among your canvases, not in the design system. Nothing was changed.',
74
+ /** the name is already used by a folder or file beside it */
75
+ taken: (name: string) => `There is already something called “${name}” here. Try another name.`,
76
+ /** a project that saves through accepted revisions refused the folder action */
77
+ refused: 'The project did not take this folder change. Nothing was changed. Try again.',
78
+ intoItself: 'A folder can’t go inside itself. Nothing was changed.',
79
+ /** a canvas group's own root (the top of the canvas tree) */
80
+ groupRoot: 'This folder holds all your canvases. It can’t be moved or renamed.',
81
+ tooMany: (name: string, count: number, max: number) =>
82
+ `“${name}” holds ${count} canvases; up to ${max} move together. Move some out first.`,
83
+ /** a canvas inside is pinned to a live shared session */
84
+ live: (canvas: string) => `“${canvas}” is open in a live session. Try again in a moment.`,
85
+ gone: 'That folder is not here any more. Nothing was changed.',
86
+ });
87
+
64
88
  /**
65
89
  * The typed name folded to the allowed set: — – and kin become `-`, letters lose their accents (NFD, then
66
90
  * strip the marks, so č→c), every other character is dropped, runs of spaces collapse, and the ends are
@@ -0,0 +1,93 @@
1
+ // A byte-bounded LRU for built canvas modules (issue #204).
2
+ //
3
+ // A canvas module BUNDLES the shared chrome (canvas-lib and everything it pulls in), so every built
4
+ // canvas is ~2 MB of JavaScript however small its own source is — measured 2.1 MB on the first-sync
5
+ // bench's canvases. The module route kept one per canvas path for the life of the process, with no
6
+ // bound: a project's server builds every canvas once just to render its cover (thumbs
7
+ // `bootCovers`), so after a first sync of 111 canvases it held ~230 MB of module text, which a JS
8
+ // string with any non-Latin-1 character stores at two bytes a character — ~460 MB of heap that was
9
+ // never released (the reported `[mem] rss > warn … heapUsed ~317 MB` on an idle synced desktop),
10
+ // and ~1.3 GB on a 311-canvas cell. Modules are kept here as UTF-8 bytes (half the size, and off
11
+ // the JS heap) under a byte budget; a miss only costs a rebuild, which the route already handles.
12
+
13
+ /** What a cached module costs. */
14
+ export interface Sized {
15
+ /** Bytes this entry holds — what the budget counts. */
16
+ readonly bytes: number;
17
+ }
18
+
19
+ export interface ModuleCache<V extends Sized> {
20
+ get(key: string): V | undefined;
21
+ /** Insert or replace `key`, then evict least-recently-used entries until the budget holds.
22
+ * The entry just set is never evicted by its own insert, even when it alone is over budget —
23
+ * the request that built it is about to serve it. */
24
+ set(key: string, value: V): void;
25
+ delete(key: string): void;
26
+ clear(): void;
27
+ readonly size: number;
28
+ /** Total `bytes` of what is held now. */
29
+ readonly bytes: number;
30
+ }
31
+
32
+ export interface ModuleCacheOptions {
33
+ maxBytes: number;
34
+ /** An additional count bound (the historical-version cache keeps its old one). */
35
+ maxEntries?: number;
36
+ }
37
+
38
+ export function createModuleCache<V extends Sized>(o: ModuleCacheOptions): ModuleCache<V> {
39
+ const map = new Map<string, V>();
40
+ let total = 0;
41
+ const maxEntries = o.maxEntries ?? Number.POSITIVE_INFINITY;
42
+
43
+ function drop(key: string): void {
44
+ const v = map.get(key);
45
+ if (v === undefined) return;
46
+ total -= v.bytes;
47
+ map.delete(key);
48
+ }
49
+
50
+ return {
51
+ get(key) {
52
+ const v = map.get(key);
53
+ if (v === undefined) return undefined;
54
+ // Most recently used goes last: Map iteration order is insertion order.
55
+ map.delete(key);
56
+ map.set(key, v);
57
+ return v;
58
+ },
59
+ set(key, value) {
60
+ drop(key);
61
+ map.set(key, value);
62
+ total += value.bytes;
63
+ for (const oldest of map.keys()) {
64
+ if (total <= o.maxBytes && map.size <= maxEntries) break;
65
+ if (oldest === key) break;
66
+ drop(oldest);
67
+ }
68
+ },
69
+ delete: drop,
70
+ clear() {
71
+ map.clear();
72
+ total = 0;
73
+ },
74
+ get size() {
75
+ return map.size;
76
+ },
77
+ get bytes() {
78
+ return total;
79
+ },
80
+ };
81
+ }
82
+
83
+ /** UTF-8 bytes of a built module, the form the caches keep it in. */
84
+ export function moduleBytes(js: string): Uint8Array<ArrayBuffer> {
85
+ return new TextEncoder().encode(js) as Uint8Array<ArrayBuffer>;
86
+ }
87
+
88
+ /** The env knob, in MB, with a floor so a typo cannot turn the cache off entirely. */
89
+ export function budgetFromEnv(name: string, defaultMb: number): number {
90
+ const raw = Number(process.env[name]);
91
+ const mb = Number.isFinite(raw) && raw >= 4 ? raw : defaultMb;
92
+ return mb * 1024 * 1024;
93
+ }
@@ -291,6 +291,7 @@ const recorded = new Map<string, { sig: string; error: CanvasError }>();
291
291
  */
292
292
  export function recordCanvasBuild(absPath: string, sig: string, error: CanvasError | null): void {
293
293
  recorded.delete(absPath);
294
+ failures.delete(absPath);
294
295
  if (!error) return;
295
296
  recorded.set(absPath, { sig, error });
296
297
  if (recorded.size > MAX_RECORDED) {
@@ -307,6 +308,44 @@ export function recalledCanvasError(absPath: string, sig: string): CanvasError |
307
308
 
308
309
  export function forgetCanvasErrors(): void {
309
310
  recorded.clear();
311
+ failures.clear();
312
+ }
313
+
314
+ /**
315
+ * #189 — a build that stopped for a reason that is NOT in the canvas's code, as a class WE chose
316
+ * from the host's own control flow (the sandbox's kind, the worker's stage, a refusal COUNT) — never
317
+ * read out of an error string. gate-b-c4m holds: no message, path or specifier rides here, so the
318
+ * card can say why without handing a frame (or a person) build internals.
319
+ *
320
+ * engine the build engine could not start or load (a missing module in the sandbox, no result)
321
+ * timed-out it ran past the wall-clock ceiling and was stopped
322
+ * memory it ran past the memory ceiling and was stopped
323
+ * imports-refused the import allowlist refused `count` imports
324
+ */
325
+ export type BuildFailureClass = 'engine' | 'timed-out' | 'memory' | 'imports-refused';
326
+ export interface BuildFailure {
327
+ class: BuildFailureClass;
328
+ /** `imports-refused` only: how many. */
329
+ count?: number;
330
+ }
331
+
332
+ const failures = new Map<string, { sig: string; failure: BuildFailure }>();
333
+
334
+ /** Record why the live build of `absPath` (source signature `sig`) stopped outside its code. */
335
+ export function recordBuildFailure(absPath: string, sig: string, failure: BuildFailure): void {
336
+ recorded.delete(absPath);
337
+ failures.delete(absPath);
338
+ failures.set(absPath, { sig, failure });
339
+ if (failures.size > MAX_RECORDED) {
340
+ const oldest = failures.keys().next().value;
341
+ if (oldest !== undefined) failures.delete(oldest);
342
+ }
343
+ }
344
+
345
+ /** The recorded build failure of `absPath`, only while its source is still the one that failed. */
346
+ export function recalledBuildFailure(absPath: string, sig: string): BuildFailure | null {
347
+ const hit = failures.get(absPath);
348
+ return hit && hit.sig === sig ? hit.failure : null;
310
349
  }
311
350
 
312
351
  /** The signature a recorded error is keyed on: the source's own bytes. */