@1agh/maude 1.7.1 → 1.9.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.
Files changed (108) hide show
  1. package/apps/studio/acp/bridge.ts +15 -2
  2. package/apps/studio/acp/login-state.ts +1 -0
  3. package/apps/studio/acp/probe.ts +52 -1
  4. package/apps/studio/api.ts +431 -39
  5. package/apps/studio/asset-upload.ts +174 -0
  6. package/apps/studio/assets-s3.ts +37 -2
  7. package/apps/studio/bin/_curl-local.mjs +7 -0
  8. package/apps/studio/bin/_pdf-playwright.mjs +22 -1
  9. package/apps/studio/bin/_png-playwright.mjs +20 -1
  10. package/apps/studio/bin/_region.mjs +92 -0
  11. package/apps/studio/bin/annotate.mjs +16 -7
  12. package/apps/studio/bin/read-annotations.mjs +62 -4
  13. package/apps/studio/canvas-build.ts +59 -4
  14. package/apps/studio/canvas-lib.tsx +48 -1
  15. package/apps/studio/canvas-shell.tsx +28 -4
  16. package/apps/studio/client/app.jsx +441 -15903
  17. package/apps/studio/client/canvas-url.js +9 -0
  18. package/apps/studio/client/dialogs/asset-picker.jsx +331 -0
  19. package/apps/studio/client/dialogs/command-palette.jsx +112 -0
  20. package/apps/studio/client/dialogs/export-dialog.jsx +782 -0
  21. package/apps/studio/client/dialogs/help-modal.jsx +324 -0
  22. package/apps/studio/client/dialogs/shortcuts-overlay.jsx +144 -0
  23. package/apps/studio/client/embed-view.jsx +284 -0
  24. package/apps/studio/client/embed.js +101 -0
  25. package/apps/studio/client/export-center.jsx +2 -0
  26. package/apps/studio/client/github.js +36 -3
  27. package/apps/studio/client/hooks/use-canvas-bridge.jsx +2150 -0
  28. package/apps/studio/client/hooks/use-git-actions.jsx +236 -0
  29. package/apps/studio/client/hooks/use-keyboard-shortcuts.jsx +297 -0
  30. package/apps/studio/client/hooks/use-palette-and-panels.jsx +474 -0
  31. package/apps/studio/client/hooks/use-photo-and-timeline.jsx +901 -0
  32. package/apps/studio/client/hooks/use-project-data.jsx +90 -0
  33. package/apps/studio/client/hooks/use-shell-core.jsx +1212 -0
  34. package/apps/studio/client/hooks/use-tabs.jsx +723 -0
  35. package/apps/studio/client/hooks/use-web-socket.jsx +13 -0
  36. package/apps/studio/client/inspector/artboard-knobs.jsx +456 -0
  37. package/apps/studio/client/inspector/color-picker.jsx +196 -0
  38. package/apps/studio/client/inspector/color.js +92 -0
  39. package/apps/studio/client/inspector/css-knobs.jsx +1720 -0
  40. package/apps/studio/client/inspector/css-vocab.jsx +131 -0
  41. package/apps/studio/client/inspector/ds-tokens.js +90 -0
  42. package/apps/studio/client/inspector/grid-tracks-editor.jsx +97 -0
  43. package/apps/studio/client/inspector/inspect-computed.jsx +68 -0
  44. package/apps/studio/client/inspector/inspector-panel.jsx +769 -0
  45. package/apps/studio/client/inspector/layers.jsx +322 -0
  46. package/apps/studio/client/inspector/selection.js +65 -0
  47. package/apps/studio/client/inspector/token-popover.jsx +301 -0
  48. package/apps/studio/client/menus/menubar.jsx +856 -0
  49. package/apps/studio/client/report-bug.jsx +8 -2
  50. package/apps/studio/client/selection-scope.js +40 -0
  51. package/apps/studio/client/shell/banners.jsx +272 -0
  52. package/apps/studio/client/shell/collapsed-rail.jsx +23 -0
  53. package/apps/studio/client/shell/comments-panel.jsx +177 -0
  54. package/apps/studio/client/shell/constants.js +60 -0
  55. package/apps/studio/client/shell/dock.jsx +131 -0
  56. package/apps/studio/client/shell/icons.jsx +370 -0
  57. package/apps/studio/client/shell/status-bar.jsx +215 -0
  58. package/apps/studio/client/shell/util.js +332 -0
  59. package/apps/studio/client/shell/viewport.jsx +254 -0
  60. package/apps/studio/client/system/system-view.jsx +255 -0
  61. package/apps/studio/client/tree/tree.jsx +1243 -0
  62. package/apps/studio/comments-overlay.tsx +6 -4
  63. package/apps/studio/config.schema.json +5 -0
  64. package/apps/studio/context.ts +20 -0
  65. package/apps/studio/dist/client.bundle.js +2728 -2728
  66. package/apps/studio/dist/comment-mount.js +2 -2
  67. package/apps/studio/embed-origins.ts +52 -0
  68. package/apps/studio/export-dialog.tsx +55 -3
  69. package/apps/studio/exporters/_browser-bundles.ts +21 -2
  70. package/apps/studio/exporters/format-scopes.ts +11 -3
  71. package/apps/studio/exporters/index.ts +17 -2
  72. package/apps/studio/exporters/jobs.ts +91 -23
  73. package/apps/studio/exporters/pdf.ts +10 -2
  74. package/apps/studio/exporters/png.ts +10 -2
  75. package/apps/studio/exporters/scope.ts +89 -15
  76. package/apps/studio/format.ts +296 -0
  77. package/apps/studio/generation/runtime-probe.ts +1 -1
  78. package/apps/studio/git/service.ts +1 -0
  79. package/apps/studio/http.ts +399 -36
  80. package/apps/studio/input-router.tsx +7 -1
  81. package/apps/studio/path-containment.ts +72 -0
  82. package/apps/studio/paths.ts +14 -1
  83. package/apps/studio/read-only-mode.ts +53 -0
  84. package/apps/studio/server.ts +123 -25
  85. package/apps/studio/sync/accepted-link.ts +6 -0
  86. package/apps/studio/sync/agent.ts +9 -1
  87. package/apps/studio/sync/cold-start-apply.ts +29 -4
  88. package/apps/studio/sync/cold-start.ts +78 -0
  89. package/apps/studio/sync/file-plane.ts +61 -1
  90. package/apps/studio/sync/format-sync.ts +160 -0
  91. package/apps/studio/sync/index.ts +208 -23
  92. package/apps/studio/sync/journal-client.ts +25 -5
  93. package/apps/studio/sync/migrate-seed.ts +8 -1
  94. package/apps/studio/sync/park.ts +39 -0
  95. package/apps/studio/sync/presentation.ts +9 -3
  96. package/apps/studio/sync/status.ts +2 -0
  97. package/apps/studio/sync/transaction-client.ts +130 -13
  98. package/apps/studio/sync/writer-registry.ts +5 -0
  99. package/apps/studio/ui-prefs.ts +95 -10
  100. package/apps/studio/use-canvas-media-drop.tsx +8 -28
  101. package/apps/studio/whats-new.json +36 -0
  102. package/apps/studio/ws.ts +19 -4
  103. package/cli/bin/claude-design-server.mjs +0 -0
  104. package/cli/commands/design.mjs +9 -2
  105. package/cli/commands/hub-workspace.mjs +25 -0
  106. package/cli/lib/workspace-plan.mjs +51 -0
  107. package/package.json +11 -9
  108. package/plugins/design/templates/_shell.html +58 -0
@@ -125,9 +125,10 @@ import {
125
125
  import { createHistory } from './history.ts';
126
126
  import { clearLocatorSlug, readLocator, writeLocator } from './locator.ts';
127
127
  import { listMaterializable } from './materialize-client.ts';
128
+ import { resolveUrlPathUnder } from './path-containment.ts';
128
129
  import { STICKERS_DIR } from './paths.ts';
129
130
  import { getPaperPreset, MAX_PRINT_MM } from './print/units.ts';
130
- import { sessionDir } from './session-scope.ts';
131
+ import { currentSession, normalizeSessionKey, sessionDir } from './session-scope.ts';
131
132
  import { describeSourceOp } from './sync/source-ops.ts';
132
133
  import { normalizeTreeState, type TreeState } from './tree-state.ts';
133
134
  import { isWorkspaceMode } from './workspace-mode.ts';
@@ -561,6 +562,22 @@ export interface Api {
561
562
  /** DDR-148 — streaming variant for the HTTP route (100 MB video without a
562
563
  * full in-RAM buffer). Sniffs + caps + content-addresses like saveAsset. */
563
564
  saveAssetFromStream(stream: ReadableStream<Uint8Array>): Promise<SaveAssetResult>;
565
+ /** Issue #126 — chunked upload for video/audio past the one-shot cap. */
566
+ startAssetChunkSession(
567
+ totalSize: unknown
568
+ ): Promise<
569
+ | { ok: true; session: string; chunkBytes: number; chunkCount: number }
570
+ | { ok: false; status: number; error: string }
571
+ >;
572
+ writeAssetChunk(
573
+ sessionId: unknown,
574
+ index: unknown,
575
+ stream: ReadableStream<Uint8Array>
576
+ ): Promise<{ ok: true } | { ok: false; status: number; error: string }>;
577
+ finishAssetChunkSession(sessionId: unknown): Promise<SaveAssetResult>;
578
+ abortAssetChunkSession(
579
+ sessionId: unknown
580
+ ): Promise<{ ok: true } | { ok: false; status: number; error: string }>;
564
581
  // Persist a clipboard-pasted ACP composer image → runtime `_chat/attachments/`,
565
582
  // returns an absolute path (Phase 31 follow-up — POST /_api/acp/attachment).
566
583
  saveChatAttachment(bytes: Uint8Array): Promise<SaveAssetResult>;
@@ -885,7 +902,8 @@ export interface Api {
885
902
  dir?: unknown;
886
903
  }): Promise<ReorderRevertResult>;
887
904
  // Aggregate data
888
- buildIndexData(): Promise<unknown>;
905
+ /** `viewer.role` — the proxy-vouched role in a cell (`null` on a desktop). */
906
+ buildIndexData(viewer?: { role?: string | null }): Promise<unknown>;
889
907
  buildSystemData(dsName?: string | null): Promise<unknown>;
890
908
  }
891
909
 
@@ -1004,10 +1022,11 @@ export const ASSET_MAX_BYTES = (() => {
1004
1022
  */
1005
1023
  export const ASSET_SESSION_BUDGET = (() => {
1006
1024
  const env = Number(process.env.MAUDE_ASSET_SESSION_BUDGET);
1007
- // DDR-148 — raised 256 MB → 1 GB now that the route accepts video/audio (one
1008
- // 100 MB clip would blow a 256 MB budget after a couple of drops). Still an
1009
- // aggregate per-server-instance disk-fill bound; env-overridable.
1010
- return Number.isFinite(env) && env > 0 ? env : 1024 * 1024 * 1024;
1025
+ // DDR-148 raised 256 MB → 1 GB for video/audio; issue #126 raised it to 4 GB
1026
+ // once chunked upload allowed 512 MB clips (1 GB = two drops, then 429 until
1027
+ // restart). Still an aggregate per-server-instance disk-fill bound, now also
1028
+ // charged up front by chunk-session reservations; env-overridable.
1029
+ return Number.isFinite(env) && env > 0 ? env : 4 * 1024 * 1024 * 1024;
1011
1030
  })();
1012
1031
 
1013
1032
  /**
@@ -1127,14 +1146,55 @@ export function assetCapForCategory(category: AssetCategory): number {
1127
1146
  return category === 'image' ? ASSET_MAX_BYTES : ASSET_MAX_VIDEO_BYTES;
1128
1147
  }
1129
1148
 
1149
+ function envBytes(name: string, fallback: number): number {
1150
+ const env = Number(process.env[name]);
1151
+ return Number.isFinite(env) && env > 0 ? env : fallback;
1152
+ }
1153
+
1154
+ /**
1155
+ * Issue #126 — chunked upload for video/audio past {@link ASSET_MAX_VIDEO_BYTES}.
1156
+ * Each request carries one fixed-size chunk, so Bun's global body ceiling
1157
+ * (`MAX_REQUEST_BODY`, server.ts) never has to rise; only the reassembled file
1158
+ * may be larger. The default ceiling equals the desktop sync lane's 512 MiB
1159
+ * push/pull cap (sync/asset-push.ts) — a bigger clip would land locally and
1160
+ * silently never reach a peer.
1161
+ */
1162
+ // Whole bytes, and never above the one-shot cap: a chunk must always fit under
1163
+ // the global request ceiling (`MAX_REQUEST_BODY`) that this whole design keeps.
1164
+ export const ASSET_CHUNK_BYTES = Math.min(
1165
+ Math.floor(envBytes('MAUDE_ASSET_CHUNK_BYTES', 16 * 1024 * 1024)),
1166
+ ASSET_MAX_VIDEO_BYTES
1167
+ );
1168
+ export const ASSET_MAX_CHUNKED_BYTES = Math.floor(
1169
+ envBytes('MAUDE_ASSET_MAX_CHUNKED_BYTES', 512 * 1024 * 1024)
1170
+ );
1171
+ /** Idle time after which an unfinished chunk session is swept. */
1172
+ export const ASSET_CHUNK_SESSION_TTL_MS = envBytes(
1173
+ 'MAUDE_ASSET_CHUNK_SESSION_TTL_MS',
1174
+ 30 * 60 * 1000
1175
+ );
1176
+ /** A session that never received a chunk holds a slot + reservation for no
1177
+ * reason — a blind cross-site or scripted start must not pin it for the TTL. */
1178
+ export const ASSET_CHUNK_EMPTY_SESSION_TTL_MS = envBytes(
1179
+ 'MAUDE_ASSET_CHUNK_EMPTY_SESSION_TTL_MS',
1180
+ 60 * 1000
1181
+ );
1182
+ /** Absolute age cap — re-sending a chunk keeps a session idle-fresh, not alive forever. */
1183
+ export const ASSET_CHUNK_SESSION_MAX_AGE_MS = envBytes(
1184
+ 'MAUDE_ASSET_CHUNK_SESSION_MAX_AGE_MS',
1185
+ 2 * 60 * 60 * 1000
1186
+ );
1187
+ /** Open chunk sessions per server instance — bounds dirs/fds beyond the byte budget. */
1188
+ export const ASSET_CHUNK_MAX_SESSIONS = Math.floor(envBytes('MAUDE_ASSET_CHUNK_MAX_SESSIONS', 4));
1189
+
1130
1190
  const UNSUPPORTED_ASSET_MSG =
1131
1191
  'unsupported media type — png/jpeg/gif/webp images or mp4/mov/webm/mp3/wav/m4a media only (SVG/script rejected)';
1132
1192
 
1133
- function capError(category?: AssetCategory): string {
1193
+ function capError(category: AssetCategory | undefined, mediaCap = ASSET_MAX_VIDEO_BYTES): string {
1134
1194
  if (category === 'image') {
1135
1195
  return `image exceeds the ${Math.round(ASSET_MAX_BYTES / (1024 * 1024))} MB cap`;
1136
1196
  }
1137
- const mb = Math.round(ASSET_MAX_VIDEO_BYTES / (1024 * 1024));
1197
+ const mb = Math.round(mediaCap / (1024 * 1024));
1138
1198
  return `media exceeds the ${mb} MB cap`;
1139
1199
  }
1140
1200
 
@@ -1455,6 +1515,7 @@ export function createApi(ctx: Context, hooks: ApiHooks): Api {
1455
1515
  try {
1456
1516
  const proc = Bun.spawn(['git', 'config', 'user.name'], {
1457
1517
  cwd: paths.repoRoot,
1518
+ windowsHide: true,
1458
1519
  stdout: 'pipe',
1459
1520
  stderr: 'pipe',
1460
1521
  });
@@ -1478,6 +1539,7 @@ export function createApi(ctx: Context, hooks: ApiHooks): Api {
1478
1539
  try {
1479
1540
  const proc = Bun.spawn(['git', 'shortlog', '-sne', 'HEAD'], {
1480
1541
  cwd: paths.repoRoot,
1542
+ windowsHide: true,
1481
1543
  stdout: 'pipe',
1482
1544
  stderr: 'pipe',
1483
1545
  });
@@ -1799,8 +1861,10 @@ export function createApi(ctx: Context, hooks: ApiHooks): Api {
1799
1861
  /* ignore */
1800
1862
  }
1801
1863
  if (p.includes('..')) return null;
1802
- const abs = path.join(paths.repoRoot, p);
1803
- if (!abs.startsWith(`${paths.repoRoot}/`)) return null;
1864
+ // #145 — the static route's resolver, so both agree on Windows (`:` would
1865
+ // name an NTFS stream, `\\` a separator the canvas gate never saw).
1866
+ const abs = resolveUrlPathUnder(`/${p}`, paths.repoRoot);
1867
+ if (!abs || abs === paths.repoRoot) return null;
1804
1868
  const ext = path.extname(abs).toLowerCase();
1805
1869
  if (ext !== '.tsx' && ext !== '.html') return null;
1806
1870
  return abs;
@@ -2468,14 +2532,27 @@ export function createApi(ctx: Context, hooks: ApiHooks): Api {
2468
2532
  ctx.bus.emit('fs:any', rel);
2469
2533
  }
2470
2534
 
2471
- async function saveAssetFromStream(stream: ReadableStream<Uint8Array>): Promise<SaveAssetResult> {
2535
+ interface ConsumeAssetOpts {
2536
+ /** Ceiling for video/audio; images always get {@link ASSET_MAX_BYTES}. */
2537
+ mediaCap: number;
2538
+ /** 'reserved' — a chunk session already charged the budget at chunk-start. */
2539
+ budget: 'check' | 'reserved';
2540
+ allowImages: boolean;
2541
+ }
2542
+
2543
+ async function consumeAssetStream(
2544
+ stream: ReadableStream<Uint8Array>,
2545
+ opts: ConsumeAssetOpts
2546
+ ): Promise<SaveAssetResult> {
2472
2547
  const assetsDir = path.join(paths.designRoot, 'assets');
2473
2548
  const tmpName = `.tmp-${crypto.randomBytes(8).toString('hex')}`;
2474
2549
  const tmpAbs = path.join(assetsDir, tmpName);
2475
2550
  const hash = crypto.createHash('sha256');
2476
2551
  let sink: Bun.FileSink | null = null;
2477
2552
  let typeInfo: AssetTypeInfo | null = null;
2478
- let cap = ASSET_MAX_VIDEO_BYTES; // provisional max until the head is sniffed
2553
+ let cap = opts.mediaCap; // provisional max until the head is sniffed
2554
+ const capFor = (info: AssetTypeInfo) =>
2555
+ info.category === 'image' ? ASSET_MAX_BYTES : opts.mediaCap;
2479
2556
  let total = 0;
2480
2557
  const headChunks: Uint8Array[] = [];
2481
2558
  let headLen = 0;
@@ -2515,21 +2592,17 @@ export function createApi(ctx: Context, hooks: ApiHooks): Api {
2515
2592
  total += chunk.length;
2516
2593
  if (total > cap) {
2517
2594
  await cleanup();
2518
- return { ok: false, status: 413, error: capError(typeInfo?.category) };
2595
+ return { ok: false, status: 413, error: capError(typeInfo?.category, opts.mediaCap) };
2519
2596
  }
2520
2597
  if (!typeInfo) {
2521
2598
  headChunks.push(chunk);
2522
2599
  headLen += chunk.length;
2523
2600
  if (headLen >= 12) {
2524
2601
  typeInfo = sniffAssetType(concatBytes(headChunks));
2525
- if (!typeInfo) {
2602
+ const refused = acceptType(typeInfo);
2603
+ if (refused) {
2526
2604
  await cleanup(); // nothing written yet — no temp file to remove
2527
- return { ok: false, status: 415, error: UNSUPPORTED_ASSET_MSG };
2528
- }
2529
- cap = assetCapForCategory(typeInfo.category);
2530
- if (total > cap) {
2531
- await cleanup();
2532
- return { ok: false, status: 413, error: capError(typeInfo.category) };
2605
+ return refused;
2533
2606
  }
2534
2607
  sink = Bun.file(tmpAbs).writer();
2535
2608
  flushHead();
@@ -2547,21 +2620,19 @@ export function createApi(ctx: Context, hooks: ApiHooks): Api {
2547
2620
  // A body shorter than 12 bytes never triggered the mid-stream sniff.
2548
2621
  if (!typeInfo) {
2549
2622
  typeInfo = sniffAssetType(concatBytes(headChunks));
2550
- if (!typeInfo) {
2551
- await cleanup();
2552
- return { ok: false, status: 415, error: UNSUPPORTED_ASSET_MSG };
2553
- }
2554
- cap = assetCapForCategory(typeInfo.category);
2555
- if (total > cap) {
2623
+ const refused = acceptType(typeInfo);
2624
+ if (refused) {
2556
2625
  await cleanup();
2557
- return { ok: false, status: 413, error: capError(typeInfo.category) };
2626
+ return refused;
2558
2627
  }
2559
2628
  sink = Bun.file(tmpAbs).writer();
2560
2629
  flushHead();
2561
2630
  }
2631
+ if (!typeInfo) throw new Error('unreachable: asset type unresolved');
2562
2632
  if (sink) await sink.end();
2563
2633
 
2564
- const sha8 = hash.digest('hex').slice(0, 8);
2634
+ const digest = hash.digest('hex');
2635
+ const sha8 = digest.slice(0, 8);
2565
2636
  const name = `${sha8}.${typeInfo.ext}`;
2566
2637
  const fileAbs = path.join(assetsDir, name);
2567
2638
  // Containment backstop — the name is content-addressed (sha8 hex + sniffed
@@ -2576,8 +2647,13 @@ export function createApi(ctx: Context, hooks: ApiHooks): Api {
2576
2647
  return { ok: true, path: `assets/${name}` };
2577
2648
  }
2578
2649
  // Aggregate write budget — bounds a scripted disk-fill loop from the
2579
- // untrusted canvas origin. Only a genuinely NEW file counts.
2580
- if (assetBytesWritten + total > ASSET_SESSION_BUDGET) {
2650
+ // untrusted canvas origin. Only a genuinely NEW file counts. Bytes held by
2651
+ // open chunk sessions count too, or one-shot writes could oversubscribe
2652
+ // what those sessions were promised.
2653
+ if (
2654
+ opts.budget === 'check' &&
2655
+ assetBytesWritten + assetBytesReserved + total > ASSET_SESSION_BUDGET
2656
+ ) {
2581
2657
  await rm(tmpAbs, { force: true });
2582
2658
  return {
2583
2659
  ok: false,
@@ -2590,13 +2666,13 @@ export function createApi(ctx: Context, hooks: ApiHooks): Api {
2590
2666
  const rel = `assets/${name}`;
2591
2667
  announceWritten(rel);
2592
2668
  // S3/R2 lane (Cloud Phase 3) — mirror the bytes so a second machine can
2593
- // resolve them without the file riding git. Deliberately awaited but
2594
- // never able to fail the save: the asset is already on disk, the mirror
2595
- // is the redundant copy, and `maude hub asset-check` reconciles a miss.
2596
- // Only a genuinely NEW file reaches here, so this is not re-uploading on
2597
- // every dedupe hit.
2669
+ // resolve them without the file riding git. Never able to fail the save:
2670
+ // the asset is already on disk, the mirror is the redundant copy, and
2671
+ // `maude hub asset-check` reconciles a miss. Streamed from disk — a 512 MB
2672
+ // clip must not be read whole into RAM. Only a genuinely NEW file reaches
2673
+ // here, so this is not re-uploading on every dedupe hit.
2598
2674
  if (assetMirror.configured) {
2599
- void assetMirror.push(rel, new Uint8Array(await Bun.file(fileAbs).arrayBuffer()));
2675
+ void assetMirror.pushFile(rel, fileAbs, digest);
2600
2676
  }
2601
2677
  return { ok: true, path: rel };
2602
2678
  } catch (err) {
@@ -2609,6 +2685,304 @@ export function createApi(ctx: Context, hooks: ApiHooks): Api {
2609
2685
  /* already released */
2610
2686
  }
2611
2687
  }
2688
+
2689
+ function acceptType(info: AssetTypeInfo | null): SaveAssetResult | null {
2690
+ if (!info) return { ok: false, status: 415, error: UNSUPPORTED_ASSET_MSG };
2691
+ if (info.category === 'image' && !opts.allowImages) {
2692
+ return { ok: false, status: 415, error: 'images upload in one request, not in chunks' };
2693
+ }
2694
+ cap = capFor(info);
2695
+ if (total > cap) {
2696
+ return { ok: false, status: 413, error: capError(info.category, opts.mediaCap) };
2697
+ }
2698
+ return null;
2699
+ }
2700
+ }
2701
+
2702
+ /** DDR-148 — the one-shot streamed write behind `POST /_api/asset`. */
2703
+ function saveAssetFromStream(stream: ReadableStream<Uint8Array>): Promise<SaveAssetResult> {
2704
+ return consumeAssetStream(stream, {
2705
+ mediaCap: ASSET_MAX_VIDEO_BYTES,
2706
+ budget: 'check',
2707
+ allowImages: true,
2708
+ });
2709
+ }
2710
+
2711
+ // Issue #126 — chunked upload. Same untrusted canvas origin as the one-shot
2712
+ // route, so: fixed chunk sizes (bounded file count per session), a cap on open
2713
+ // sessions, the byte budget charged at chunk-start before any byte is
2714
+ // accepted, one write in flight per session, idle / empty / over-age sessions
2715
+ // swept, and the sniff run on the REASSEMBLED stream by the shared core —
2716
+ // never per chunk. Session scratch lives under the runtime `_state/` tree,
2717
+ // never the versioned + synced `assets/`. See DDR-248.
2718
+ interface ChunkSession {
2719
+ id: string;
2720
+ dir: string;
2721
+ totalSize: number;
2722
+ chunkCount: number;
2723
+ received: Set<number>;
2724
+ createdAt: number;
2725
+ lastActivity: number;
2726
+ /** A chunk write is streaming — a second write or a finish is refused (409). */
2727
+ writing: boolean;
2728
+ /** Set once finish/abort starts — later chunk writes are refused. */
2729
+ closing: boolean;
2730
+ }
2731
+ const CHUNK_SESSION_ID = /^[0-9a-f]{32}$/;
2732
+ const chunkSessions = new Map<string, ChunkSession>();
2733
+ let assetBytesReserved = 0;
2734
+ const chunkRoot = () => path.join(paths.designRoot, '_state', 'asset-chunks');
2735
+
2736
+ /** Unregister + release synchronously; the directory removal is best-effort. */
2737
+ async function dropChunkSession(s: ChunkSession): Promise<void> {
2738
+ if (chunkSessions.get(s.id) === s) {
2739
+ chunkSessions.delete(s.id);
2740
+ assetBytesReserved = Math.max(0, assetBytesReserved - s.totalSize);
2741
+ }
2742
+ try {
2743
+ await rm(s.dir, { recursive: true, force: true });
2744
+ } catch {
2745
+ /* a racing write recreated a temp file — the orphan sweep collects it */
2746
+ }
2747
+ }
2748
+
2749
+ function chunkSessionExpired(s: ChunkSession, now: number): boolean {
2750
+ if (s.closing || s.writing) return false;
2751
+ if (now - s.createdAt > ASSET_CHUNK_SESSION_MAX_AGE_MS) return true;
2752
+ if (s.received.size === 0 && now - s.createdAt > ASSET_CHUNK_EMPTY_SESSION_TTL_MS) return true;
2753
+ return now - s.lastActivity > ASSET_CHUNK_SESSION_TTL_MS;
2754
+ }
2755
+
2756
+ /**
2757
+ * Drop expired sessions (idle, never fed, or past their absolute age), and
2758
+ * orphan dirs left by an earlier process (its sessions died with it). An
2759
+ * orphan is only removed once it is itself idle past the TTL, so a second
2760
+ * server on the same project is never undercut mid-upload.
2761
+ */
2762
+ async function sweepStaleChunkSessions(now = Date.now()): Promise<void> {
2763
+ for (const s of [...chunkSessions.values()]) {
2764
+ if (chunkSessionExpired(s, now)) await dropChunkSession(s);
2765
+ }
2766
+ let names: string[];
2767
+ try {
2768
+ names = await readdir(chunkRoot());
2769
+ } catch {
2770
+ return; // nothing ever chunked here
2771
+ }
2772
+ for (const name of names) {
2773
+ if (chunkSessions.has(name)) continue;
2774
+ const dir = path.join(chunkRoot(), name);
2775
+ try {
2776
+ const st = await statp(dir);
2777
+ if (now - st.mtimeMs > ASSET_CHUNK_SESSION_TTL_MS) {
2778
+ await rm(dir, { recursive: true, force: true });
2779
+ }
2780
+ } catch {
2781
+ /* raced with another sweep */
2782
+ }
2783
+ }
2784
+ }
2785
+ void sweepStaleChunkSessions();
2786
+
2787
+ function chunkSessionFor(
2788
+ id: unknown
2789
+ ): { session: ChunkSession } | { ok: false; status: number; error: string } {
2790
+ if (typeof id !== 'string' || !CHUNK_SESSION_ID.test(id)) {
2791
+ return { ok: false, status: 400, error: 'invalid upload session' };
2792
+ }
2793
+ const session = chunkSessions.get(id);
2794
+ if (!session) return { ok: false, status: 404, error: 'upload session not found or expired' };
2795
+ if (session.closing) return { ok: false, status: 409, error: 'upload session is closing' };
2796
+ return { session };
2797
+ }
2798
+
2799
+ async function startAssetChunkSession(
2800
+ totalSize: unknown
2801
+ ): Promise<
2802
+ | { ok: true; session: string; chunkBytes: number; chunkCount: number }
2803
+ | { ok: false; status: number; error: string }
2804
+ > {
2805
+ if (typeof totalSize !== 'number' || !Number.isSafeInteger(totalSize) || totalSize <= 0) {
2806
+ return { ok: false, status: 400, error: 'totalSize must be a positive integer' };
2807
+ }
2808
+ if (totalSize > ASSET_MAX_CHUNKED_BYTES) {
2809
+ return { ok: false, status: 413, error: capError('video', ASSET_MAX_CHUNKED_BYTES) };
2810
+ }
2811
+ await sweepStaleChunkSessions();
2812
+ // Check, register and reserve with NO await in between: concurrent
2813
+ // chunk-starts must each see the ones before them, or N parallel requests
2814
+ // all pass the session cap and the budget against the same empty state.
2815
+ if (chunkSessions.size >= ASSET_CHUNK_MAX_SESSIONS) {
2816
+ return { ok: false, status: 429, error: 'too many uploads in progress — try again shortly' };
2817
+ }
2818
+ if (assetBytesWritten + assetBytesReserved + totalSize > ASSET_SESSION_BUDGET) {
2819
+ return {
2820
+ ok: false,
2821
+ status: 429,
2822
+ error: 'asset write budget exceeded for this server session',
2823
+ };
2824
+ }
2825
+ const id = crypto.randomBytes(16).toString('hex');
2826
+ const dir = path.join(chunkRoot(), id);
2827
+ if (path.resolve(dir) !== path.join(path.resolve(chunkRoot()), id)) {
2828
+ return { ok: false, status: 400, error: 'resolved chunk dir escapes _state' };
2829
+ }
2830
+ const now = Date.now();
2831
+ const session: ChunkSession = {
2832
+ id,
2833
+ dir,
2834
+ totalSize,
2835
+ chunkCount: Math.ceil(totalSize / ASSET_CHUNK_BYTES),
2836
+ received: new Set(),
2837
+ createdAt: now,
2838
+ lastActivity: now,
2839
+ writing: false,
2840
+ closing: false,
2841
+ };
2842
+ chunkSessions.set(id, session);
2843
+ assetBytesReserved += totalSize;
2844
+ try {
2845
+ await mkdir(dir, { recursive: true });
2846
+ } catch (err) {
2847
+ await dropChunkSession(session);
2848
+ return { ok: false, status: 500, error: err instanceof Error ? err.message : 'mkdir failed' };
2849
+ }
2850
+ return { ok: true, session: id, chunkBytes: ASSET_CHUNK_BYTES, chunkCount: session.chunkCount };
2851
+ }
2852
+
2853
+ async function writeAssetChunk(
2854
+ sessionId: unknown,
2855
+ indexRaw: unknown,
2856
+ stream: ReadableStream<Uint8Array>
2857
+ ): Promise<{ ok: true } | { ok: false; status: number; error: string }> {
2858
+ const found = chunkSessionFor(sessionId);
2859
+ if (!('session' in found)) return found;
2860
+ const s = found.session;
2861
+ if (typeof indexRaw !== 'string' || !/^\d{1,9}$/.test(indexRaw)) {
2862
+ return { ok: false, status: 400, error: 'invalid chunk index' };
2863
+ }
2864
+ const index = Number(indexRaw);
2865
+ if (index >= s.chunkCount) return { ok: false, status: 400, error: 'chunk index out of range' };
2866
+ // One write at a time per session: the client is sequential, and parallel
2867
+ // writes would each hold an uncounted temp file + fd outside the budget.
2868
+ if (s.writing) return { ok: false, status: 409, error: 'another chunk is still uploading' };
2869
+ s.writing = true;
2870
+ const expected =
2871
+ index === s.chunkCount - 1 ? s.totalSize - index * ASSET_CHUNK_BYTES : ASSET_CHUNK_BYTES;
2872
+
2873
+ // Written under a unique temp name, then renamed — a retried chunk can
2874
+ // never leave a torn `.part` behind.
2875
+ const partAbs = path.join(s.dir, `${index}.part`);
2876
+ const tmpAbs = path.join(s.dir, `${index}.part.tmp-${crypto.randomBytes(6).toString('hex')}`);
2877
+ const reader = stream.getReader();
2878
+ let got = 0;
2879
+ let failure: { ok: false; status: number; error: string } | null = null;
2880
+ try {
2881
+ const sink = Bun.file(tmpAbs).writer();
2882
+ for (;;) {
2883
+ const { done, value } = await reader.read();
2884
+ if (done) break;
2885
+ if (!value || value.length === 0) continue;
2886
+ got += value.length;
2887
+ if (got > expected) {
2888
+ failure = { ok: false, status: 413, error: `chunk exceeds its ${expected}-byte size` };
2889
+ break;
2890
+ }
2891
+ sink.write(value);
2892
+ }
2893
+ await sink.end();
2894
+ if (!failure && got !== expected) {
2895
+ failure = { ok: false, status: 400, error: `chunk must be exactly ${expected} bytes` };
2896
+ }
2897
+ if (!failure && s.closing) {
2898
+ failure = { ok: false, status: 409, error: 'upload session is closing' };
2899
+ }
2900
+ if (failure) {
2901
+ await rm(tmpAbs, { force: true });
2902
+ return failure;
2903
+ }
2904
+ await rename(tmpAbs, partAbs);
2905
+ s.received.add(index);
2906
+ s.lastActivity = Date.now();
2907
+ return { ok: true };
2908
+ } catch (err) {
2909
+ await rm(tmpAbs, { force: true }).catch(() => undefined);
2910
+ return { ok: false, status: 500, error: err instanceof Error ? err.message : 'write failed' };
2911
+ } finally {
2912
+ s.writing = false;
2913
+ try {
2914
+ reader.releaseLock();
2915
+ } catch {
2916
+ /* already released */
2917
+ }
2918
+ }
2919
+ }
2920
+
2921
+ /** The session's `.part` files, in index order, as one byte stream. */
2922
+ function reassembledStream(s: ChunkSession): ReadableStream<Uint8Array> {
2923
+ let index = 0;
2924
+ let current: ReadableStreamDefaultReader<Uint8Array> | null = null;
2925
+ return new ReadableStream<Uint8Array>({
2926
+ async pull(controller) {
2927
+ for (;;) {
2928
+ if (!current) {
2929
+ if (index >= s.chunkCount) {
2930
+ controller.close();
2931
+ return;
2932
+ }
2933
+ const part = Bun.file(path.join(s.dir, `${index}.part`)).stream();
2934
+ current = part.getReader() as ReadableStreamDefaultReader<Uint8Array>;
2935
+ index += 1;
2936
+ }
2937
+ const { done, value } = await current.read();
2938
+ if (done) {
2939
+ current = null;
2940
+ continue;
2941
+ }
2942
+ controller.enqueue(value);
2943
+ return;
2944
+ }
2945
+ },
2946
+ async cancel() {
2947
+ await current?.cancel();
2948
+ },
2949
+ });
2950
+ }
2951
+
2952
+ async function finishAssetChunkSession(sessionId: unknown): Promise<SaveAssetResult> {
2953
+ const found = chunkSessionFor(sessionId);
2954
+ if (!('session' in found)) return found;
2955
+ const s = found.session;
2956
+ if (s.writing) return { ok: false, status: 409, error: 'a chunk is still uploading' };
2957
+ s.closing = true;
2958
+ try {
2959
+ if (s.received.size !== s.chunkCount) {
2960
+ return {
2961
+ ok: false,
2962
+ status: 400,
2963
+ error: `incomplete upload — ${s.received.size} of ${s.chunkCount} chunks received`,
2964
+ };
2965
+ }
2966
+ // The reservation covers this write; releasing it happens in finally, on
2967
+ // success, dedupe and failure alike.
2968
+ return await consumeAssetStream(reassembledStream(s), {
2969
+ mediaCap: ASSET_MAX_CHUNKED_BYTES,
2970
+ budget: 'reserved',
2971
+ allowImages: false,
2972
+ });
2973
+ } finally {
2974
+ await dropChunkSession(s);
2975
+ }
2976
+ }
2977
+
2978
+ async function abortAssetChunkSession(
2979
+ sessionId: unknown
2980
+ ): Promise<{ ok: true } | { ok: false; status: number; error: string }> {
2981
+ const found = chunkSessionFor(sessionId);
2982
+ if (!('session' in found)) return found;
2983
+ found.session.closing = true;
2984
+ await dropChunkSession(found.session);
2985
+ return { ok: true };
2612
2986
  }
2613
2987
 
2614
2988
  async function saveAsset(bytes: Uint8Array): Promise<SaveAssetResult> {
@@ -2947,7 +3321,7 @@ export function createApi(ctx: Context, hooks: ApiHooks): Api {
2947
3321
  }
2948
3322
  try {
2949
3323
  if (!(await Bun.file(fileAbs).exists())) {
2950
- if (assetBytesWritten + bytes.length > ASSET_SESSION_BUDGET) {
3324
+ if (assetBytesWritten + assetBytesReserved + bytes.length > ASSET_SESSION_BUDGET) {
2951
3325
  return {
2952
3326
  ok: false,
2953
3327
  status: 429,
@@ -6469,7 +6843,7 @@ export function createApi(ctx: Context, hooks: ApiHooks): Api {
6469
6843
 
6470
6844
  // ---------- Index data + System data ----------
6471
6845
 
6472
- async function buildIndexData() {
6846
+ async function buildIndexData(viewer?: { role?: string | null }) {
6473
6847
  const groups = [];
6474
6848
 
6475
6849
  // DDR-093 — per-canvas design-system map (repo-relative canvas path → DS
@@ -6624,12 +6998,26 @@ export function createApi(ctx: Context, hooks: ApiHooks): Api {
6624
6998
  // RUNTIME — gitignored state files (_active.json, _server.json) +
6625
6999
  // pointers to _history/ and _comments/ dirs. Visible but inert in the
6626
7000
  // sidebar; matches the CV-08 mock's bottom section.
7001
+ //
7002
+ // V2-2.8 S7 (V2-1.16 L8 "everyone-fix") — in a cell this listing named
7003
+ // every member's session file (`_active.<session>.json`, Cloud Phase 27
7004
+ // D3) to every member. Non-owners get no Runtime group at all; the owner's
7005
+ // keeps the shared entries and their OWN session file, never another
7006
+ // member's. A desktop has no roles or sessions, so its list is unchanged.
7007
+ const workspace = isWorkspaceMode();
7008
+ const showRuntime = !workspace || viewer?.role === 'owner';
7009
+ const mySession = currentSession();
6627
7010
  const runtimeFiles: string[] = [];
6628
7011
  try {
6629
- const entries = await readdir(paths.designRoot, { withFileTypes: true });
7012
+ const entries = showRuntime ? await readdir(paths.designRoot, { withFileTypes: true }) : [];
6630
7013
  entries.sort((a, b) => a.name.localeCompare(b.name));
6631
7014
  for (const e of entries) {
6632
7015
  if (!e.name.startsWith('_')) continue;
7016
+ if (workspace) {
7017
+ // `_<stem>.<session>.json` is one member's sibling of a singleton.
7018
+ const keyed = /^_[^.]+\.([^.]+)\.json$/.exec(e.name)?.[1];
7019
+ if (keyed && normalizeSessionKey(keyed) === keyed && keyed !== mySession) continue;
7020
+ }
6633
7021
  runtimeFiles.push(path.posix.join(paths.designRel, e.name));
6634
7022
  }
6635
7023
  } catch {}
@@ -6880,6 +7268,10 @@ export function createApi(ctx: Context, hooks: ApiHooks): Api {
6880
7268
  searchAudioLibrary,
6881
7269
  listStickers,
6882
7270
  saveAssetFromStream,
7271
+ startAssetChunkSession,
7272
+ writeAssetChunk,
7273
+ finishAssetChunkSession,
7274
+ abortAssetChunkSession,
6883
7275
  saveChatAttachment,
6884
7276
  resolveChatAttachment,
6885
7277
  createCanvas,