@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
@@ -105,10 +105,16 @@ import { createRunRegistry, type RunRegistry } from './ai/runs.ts';
105
105
  import { type Api, ASSET_CHUNK_BYTES, ASSET_MAX_BYTES, ASSET_MAX_VIDEO_BYTES } from './api.ts';
106
106
  import { importBrandRequest } from './bin/_brand-site.mjs';
107
107
  import { buildCanvasModule } from './canvas-build.ts';
108
- import { buildCanvasSandboxed, buildStats } from './canvas-build-sandbox.ts';
108
+ import { buildCanvasSandboxed, buildStats, sandboxFailureClass } from './canvas-build-sandbox.ts';
109
109
  import { canvasLibPath } from './canvas-lib-resolver.ts';
110
+ import { budgetFromEnv, createModuleCache, moduleBytes } from './canvas-module-cache.ts';
110
111
  import { TranspileError } from './canvas-pipeline.ts';
111
- import { CanvasBuildError, canvasSourceSig, recordCanvasBuild } from './canvas-source/errors.ts';
112
+ import {
113
+ CanvasBuildError,
114
+ canvasSourceSig,
115
+ recordBuildFailure,
116
+ recordCanvasBuild,
117
+ } from './canvas-source/errors.ts';
112
118
  import { rememberCanvasBuild } from './canvas-source-memo.ts';
113
119
  import { createCloudEndpoints } from './cloud/endpoints.ts';
114
120
  import type { AiActivity } from './collab/ai-activity.ts';
@@ -238,7 +244,7 @@ import { pidOf, projectDir } from './index/snapshot.ts';
238
244
  import { feedVersionsToIndex } from './index/version-feed.ts';
239
245
  import type { InspectRegistry } from './inspect.ts';
240
246
  import { canvasSlug, writeLocator } from './locator.ts';
241
- import { prepareManagedProject } from './managed-projects.ts';
247
+ import { parsePrepareBody, prepareManagedProject } from './managed-projects.ts';
242
248
  import { materializeMissing } from './materialize-client.ts';
243
249
  import { createHubReachability } from './outbox/hub-reachability.ts';
244
250
  import { createOutbox, type GateFacts, type IntentRecord } from './outbox/index.ts';
@@ -294,7 +300,7 @@ import { createLinkGate } from './sync/link-consent.ts';
294
300
  import { createResyncTrace, type ResyncStatusSource } from './sync/resync-trace.ts';
295
301
  import { isFirstAnchorMode, readSyncSettings, writeSyncSettings } from './sync/settings.ts';
296
302
  import { listTrash, pruneTrash, restoreFromTrash } from './sync/trash.ts';
297
- import { signInToWorkspace, workspaceDisclosure } from './sync/workspace-signin.ts';
303
+ import { workspaceDisclosure } from './sync/workspace-signin.ts';
298
304
  import { thumbNotFound, thumbResponse, wantResponse } from './thumbs/routes.ts';
299
305
  import { BOOT_COVERS_DELAY_MS, createThumbService } from './thumbs/service.ts';
300
306
  import { normalizeTreeState } from './tree-state.ts';
@@ -587,6 +593,19 @@ export function sameOriginRead(req: Request): boolean {
587
593
  return site === 'same-origin' || site === 'none';
588
594
  }
589
595
 
596
+ /**
597
+ * Issue #204 — a browser's own top-level navigation (a link, a redirect, a meta refresh), never a
598
+ * fetch, an image or a frame: Fetch Metadata says `navigate` + `document`. Only a table spec that
599
+ * sets `crossSiteNavigation` accepts one from another site (the team-server sign-in return).
600
+ */
601
+ export function isTopLevelNavigation(req: Request): boolean {
602
+ return (
603
+ req.method === 'GET' &&
604
+ req.headers.get('sec-fetch-mode') === 'navigate' &&
605
+ req.headers.get('sec-fetch-dest') === 'document'
606
+ );
607
+ }
608
+
590
609
  /**
591
610
  * Every table route is privileged (migrate rewrites the tree; the outbox lists queued intents):
592
611
  * the same double gate every main-origin route carries — Origin check (reads and writes) +
@@ -597,7 +616,10 @@ export function guardTableRoute(spec: RouteSpec): RouteSpec {
597
616
  return {
598
617
  ...spec,
599
618
  handle: (req, params) => {
600
- const sameOrigin = spec.method === 'GET' ? sameOriginRead(req) : sameOriginWrite(req);
619
+ const sameOrigin =
620
+ spec.method === 'GET'
621
+ ? sameOriginRead(req) || (spec.crossSiteNavigation === true && isTopLevelNavigation(req))
622
+ : sameOriginWrite(req);
601
623
  if (!sameOrigin)
602
624
  return (
603
625
  spec.refuse?.('cross-origin') ?? new Response('cross-origin rejected', { status: 403 })
@@ -764,7 +786,10 @@ interface CanvasCacheEntry {
764
786
  * (DDR-064 collab dogfooding finding, 2026-05-29.) */
765
787
  sig: string;
766
788
  etag: string;
767
- js: string;
789
+ /** The built module as UTF-8 bytes (issue #204 — half a JS string's size, off the heap). */
790
+ body: Uint8Array<ArrayBuffer>;
791
+ /** What the byte budget counts. */
792
+ bytes: number;
768
793
  /** Absolute paths of the relative imports inlined into this build (`.css` +
769
794
  * local `.tsx/.ts` modules, incl. unresolved extensionless candidates) —
770
795
  * re-statted each request to recompute `sig` without re-reading the source. */
@@ -772,7 +797,19 @@ interface CanvasCacheEntry {
772
797
  /** gate-b-c4e — every file the build inlined (absolute), held to the frame's closure on serve. */
773
798
  inputs: readonly string[];
774
799
  }
775
- const canvasCache = new Map<string, CanvasCacheEntry>();
800
+ // Issue #204 — byte-bounded: every module bundles the shared chrome (~2 MB), and covers alone build
801
+ // every canvas of a project once, so a per-path Map with no bound held them all for good.
802
+ let canvasCache = createModuleCache<CanvasCacheEntry>({
803
+ maxBytes: budgetFromEnv('MAUDE_CANVAS_MODULE_CACHE_MB', 64),
804
+ });
805
+
806
+ /** Test seam (issue #204): what the live module cache holds, and a budget to hold it to. */
807
+ export function _canvasModuleCache(budgetBytes?: number): { size: number; bytes: number } {
808
+ if (budgetBytes !== undefined) {
809
+ canvasCache = createModuleCache<CanvasCacheEntry>({ maxBytes: budgetBytes });
810
+ }
811
+ return { size: canvasCache.size, bytes: canvasCache.bytes };
812
+ }
776
813
 
777
814
  /**
778
815
  * gate-b-c4e — may THIS request receive a module built from `inputs` (absolute paths)? null = yes.
@@ -907,7 +944,36 @@ export async function serveCanvasTsx(
907
944
  canvasAbs: absPath,
908
945
  assetUrlBase: designRootUrlBase(ctx.paths),
909
946
  });
947
+ if (!built.ok && built.kind === 'building') {
948
+ // 2.0.4 task P — the wait ran out and the build goes on (to the sandbox's hard ceiling). Its
949
+ // outcome is recorded when it settles, for `/_api/canvas-errors`; a success is in the
950
+ // sandbox's cache, so the client's next open is a hit. While it runs, canvas-errors answers
951
+ // `building` (`sandboxBuildRunning`) and the card says so instead of "can't be drawn".
952
+ const sig = canvasSourceSig(source);
953
+ void built.settled?.then((r) => {
954
+ if (r.ok) recordCanvasBuild(absPath, sig, null);
955
+ else if (r.kind !== 'building') {
956
+ const failure = sandboxFailureClass(r);
957
+ if (failure) recordBuildFailure(absPath, sig, failure);
958
+ else recordCanvasBuild(absPath, sig, null);
959
+ }
960
+ });
961
+ // The frame's own canvas (the path gate and the closure's `before` ran already), so saying
962
+ // "not yet" tells it nothing a refusal would hide (gate-b-c4m).
963
+ return new Response('This canvas is still being built.', {
964
+ status: 503,
965
+ headers: {
966
+ 'Content-Type': 'text/plain; charset=utf-8',
967
+ 'Cache-Control': 'no-store',
968
+ 'Retry-After': '5',
969
+ },
970
+ });
971
+ }
910
972
  if (!built.ok) {
973
+ // #189 — why it stopped, as OUR class (never the build's text) for /_api/canvas-errors
974
+ const failure = sandboxFailureClass(built);
975
+ if (failure) recordBuildFailure(absPath, canvasSourceSig(source), failure);
976
+ else recordCanvasBuild(absPath, canvasSourceSig(source), null);
911
977
  // gate-b-c4m (defender L-B) — a frame's failed build answers like a refused one: Bun
912
978
  // resolves imports the closure walk does not follow (a CSS `url()`), and "Could not resolve"
913
979
  // beside the refusal's 403 was an existence oracle. A syntax error in the canvas's own source
@@ -928,10 +994,12 @@ export async function serveCanvasTsx(
928
994
  // cache entry, no remembered source and no locator file (the sandbox caches the build).
929
995
  const refusedHere = inputsGate?.(result.inputs, absPath);
930
996
  if (refusedHere) return refusedHere;
997
+ const body = moduleBytes(result.js);
931
998
  cached = {
932
999
  sig: builtSig,
933
1000
  etag: `${result.etag}-${RUNTIME_BOOT_ID}-${CHROME_EPOCH}`,
934
- js: result.js,
1001
+ body,
1002
+ bytes: body.byteLength,
935
1003
  deps,
936
1004
  inputs: result.inputs,
937
1005
  };
@@ -959,6 +1027,9 @@ export async function serveCanvasTsx(
959
1027
  canvasSourceSig(source),
960
1028
  err instanceof CanvasBuildError ? (err.errors[0] ?? null) : null
961
1029
  );
1030
+ // #189 — neither the canvas's syntax nor its build log: the engine itself failed
1031
+ if (!(err instanceof CanvasBuildError) && !(err instanceof TranspileError))
1032
+ recordBuildFailure(absPath, canvasSourceSig(source), { class: 'engine' });
962
1033
  if (err instanceof TranspileError) {
963
1034
  return new Response(`Transpile error: ${err.message}`, {
964
1035
  status: 500,
@@ -976,13 +1047,15 @@ export async function serveCanvasTsx(
976
1047
  if (refusedHere) return refusedHere;
977
1048
  // The signature against the freshly-parsed deps — this very edit may have
978
1049
  // added or removed a `.css` import — stamped before the build (above).
1050
+ const body = moduleBytes(result.js);
979
1051
  cached = {
980
1052
  sig: builtSig,
981
1053
  // Fold in the boot id (restart) + chrome epoch (live edit) so a chrome
982
1054
  // change busts the browser's cached transpile even when the canvas source
983
1055
  // (hence result.etag) is unchanged. See RUNTIME_BOOT_ID / CHROME_EPOCH.
984
1056
  etag: `${result.etag}-${RUNTIME_BOOT_ID}-${CHROME_EPOCH}`,
985
- js: result.js,
1057
+ body,
1058
+ bytes: body.byteLength,
986
1059
  deps,
987
1060
  inputs: result.inputs,
988
1061
  };
@@ -1003,7 +1076,10 @@ export async function serveCanvasTsx(
1003
1076
  /** The conditional-GET half of serving a built canvas module. Shared by the
1004
1077
  * in-process (desktop) and sandboxed (cell) build paths so the two cannot
1005
1078
  * disagree about caching semantics. */
1006
- function respondWithCanvasModule(req: Request, cached: { js: string; etag: string }): Response {
1079
+ function respondWithCanvasModule(
1080
+ req: Request,
1081
+ cached: { body: Uint8Array<ArrayBuffer>; etag: string }
1082
+ ): Response {
1007
1083
  const ifNoneMatch = req.headers.get('if-none-match');
1008
1084
  if (ifNoneMatch === cached.etag) {
1009
1085
  return new Response(null, {
@@ -1011,7 +1087,7 @@ function respondWithCanvasModule(req: Request, cached: { js: string; etag: strin
1011
1087
  headers: { ETag: cached.etag, 'Cache-Control': 'no-cache' },
1012
1088
  });
1013
1089
  }
1014
- return new Response(cached.js, {
1090
+ return new Response(cached.body, {
1015
1091
  status: 200,
1016
1092
  headers: {
1017
1093
  'Content-Type': 'application/javascript; charset=utf-8',
@@ -1031,11 +1107,14 @@ function respondWithCanvasModule(req: Request, cached: { js: string; etag: strin
1031
1107
  // otherwise OOM the sidecar (security review — ethical-hacker, Finding 1).
1032
1108
  // `cssSig`: today's same-name CSS file as the build saw it — set only when the version had no CSS
1033
1109
  // lane of its own (the build then used today's file), so such an entry goes stale with that file.
1034
- const historicalCanvasCache = new Map<
1035
- string,
1036
- { js: string; etag: string; cssSig: string | null; inputs: readonly string[] }
1037
- >();
1038
- const HIST_MAX_CACHE = 96;
1110
+ // Issue #204 — and byte-bounded like the live cache: 96 two-megabyte modules is ~200 MB.
1111
+ const historicalCanvasCache = createModuleCache<{
1112
+ body: Uint8Array<ArrayBuffer>;
1113
+ bytes: number;
1114
+ etag: string;
1115
+ cssSig: string | null;
1116
+ inputs: readonly string[];
1117
+ }>({ maxBytes: budgetFromEnv('MAUDE_CANVAS_VERSION_CACHE_MB', 32), maxEntries: 96 });
1039
1118
  // Rate-limit the EXPENSIVE miss path (git show + Bun.build, or a non-resolving
1040
1119
  // git lookup) so a distinct-sha spray from the canvas origin can't starve the
1041
1120
  // event loop. Cache HITS are free; only a NEW (path,sha) build consumes budget.
@@ -1173,11 +1252,7 @@ async function serveHistoricalCanvas(
1173
1252
  historicalCanvasCache.delete(key);
1174
1253
  cached = undefined;
1175
1254
  }
1176
- if (cached) {
1177
- // LRU touch — re-insert so the hot entry isn't the next eviction victim.
1178
- historicalCanvasCache.delete(key);
1179
- historicalCanvasCache.set(key, cached);
1180
- } else {
1255
+ if (!cached) {
1181
1256
  if (!historicalBuildAllowed()) {
1182
1257
  return new Response('Too many version previews — try again in a moment.', {
1183
1258
  status: 429,
@@ -1252,17 +1327,16 @@ async function serveHistoricalCanvas(
1252
1327
  restrictImportsTo: ctx.paths.designRoot,
1253
1328
  assetUrlBase: designRootUrlBase(ctx.paths),
1254
1329
  });
1330
+ const body = moduleBytes(result.js);
1255
1331
  cached = {
1256
- js: result.js,
1332
+ body,
1333
+ bytes: body.byteLength,
1257
1334
  etag: `${result.etag}-${sha}-${RUNTIME_BOOT_ID}-${CHROME_EPOCH}`,
1258
1335
  cssSig,
1259
1336
  inputs: result.inputs,
1260
1337
  };
1338
+ // LRU with both bounds (count + bytes); `get` above is the touch.
1261
1339
  historicalCanvasCache.set(key, cached);
1262
- if (historicalCanvasCache.size > HIST_MAX_CACHE) {
1263
- const oldest = historicalCanvasCache.keys().next().value;
1264
- if (oldest !== undefined) historicalCanvasCache.delete(oldest);
1265
- }
1266
1340
  } catch (err) {
1267
1341
  // gate-b-c4l (L-b) — a past version is not what the closure walked: to a gated session
1268
1342
  // (a frame) a failed build answers like a refused one, so it probes nothing.
@@ -1278,7 +1352,7 @@ async function serveHistoricalCanvas(
1278
1352
  headers: { ETag: cached.etag, 'Cache-Control': 'no-cache' },
1279
1353
  });
1280
1354
  }
1281
- return new Response(cached.js, {
1355
+ return new Response(cached.body, {
1282
1356
  status: 200,
1283
1357
  headers: {
1284
1358
  'Content-Type': 'application/javascript; charset=utf-8',
@@ -2603,6 +2677,10 @@ export function createHttp(
2603
2677
  cloudPlan: { cloud: cloudApi },
2604
2678
  // S11.14 — GET /_api/connections/hub (routes/connections.ts): main origin only, the hub credential.
2605
2679
  connections: { designRoot: ctx.paths.designRoot },
2680
+ hubSignin: {
2681
+ linkedHubUrl: () => ctx.cfg.linkedHub?.url,
2682
+ restartSync: () => ctx.syncControl?.restart(),
2683
+ },
2606
2684
  }).map(guardTableRoute);
2607
2685
  // p8-a1-claims — outside the gates: a write that names an AI chat answers inside its run's claim
2608
2686
  // (in place, so every consumer of the table — the mount, the local gate — sees the same specs)
@@ -4815,56 +4893,29 @@ export function createHttp(
4815
4893
  return gitJson(await linkHub(body));
4816
4894
  },
4817
4895
 
4818
- // Cloud Phase 3 Task 3 — "Sign in to workspace". The person-facing
4819
- // counterpart to /_api/hub/link: an address plus an email and password,
4820
- // rather than a token to paste. Same gates as the link route (MAIN ORIGIN
4821
- // only, loopback, POST CSRF) for the same reason — this handler receives a
4822
- // PASSWORD, so the untrusted canvas origin must never be able to reach it.
4823
- // MANAGED PROJECTS (T21/T22): sign in / open, store the credential and
4824
- // describe the project, so the native shell can create its own copy.
4825
- // Main origin only — this mints and stores a credential.
4896
+ // MANAGED PROJECTS (T21/T22): open with the credential this computer holds (Maude Cloud, a
4897
+ // handoff code, or a team server the browser sign-in stored) and describe the project, so the
4898
+ // native shell can create its own copy. Main origin only. No email or password is accepted.
4826
4899
  '/_api/projects/prepare': async (req: Request) => {
4827
4900
  if (req.method !== 'POST') return new Response('Method not allowed', { status: 405 });
4828
4901
  if (!sameOriginWrite(req))
4829
4902
  return new Response('cross-origin write rejected', { status: 403 });
4830
4903
  if (!isTrustedRequestHost(req))
4831
4904
  return new Response('local request required', { status: 403 });
4832
- const body = (await readJson<Record<string, unknown>>(req, 8 * 1024)) ?? {};
4833
- const kind = body.kind;
4834
- const str = (v: unknown) => (typeof v === 'string' ? v : '');
4835
- const input =
4836
- kind === 'cloud'
4837
- ? { kind, projectId: str(body.projectId) }
4838
- : kind === 'handoff'
4839
- ? { kind, code: str(body.code), claimedProject: str(body.claimedProject) || undefined }
4840
- : kind === 'hub'
4841
- ? { kind, url: str(body.url), email: str(body.email), password: str(body.password) }
4842
- : kind === 'known-hub'
4843
- ? { kind, url: str(body.url) }
4844
- : null;
4845
- if (!input) return new Response('unknown kind', { status: 400 });
4846
- const r = await prepareManagedProject(
4847
- ctx,
4848
- input as Parameters<typeof prepareManagedProject>[1]
4849
- );
4905
+ // Issue #204: the desktop owns no team-server login — a body carrying an email or a password
4906
+ // (or the retired `hub` kind) is a plain 400 and is never forwarded anywhere.
4907
+ const parsed = parsePrepareBody(await readJson<unknown>(req, 8 * 1024));
4908
+ if (!parsed.ok)
4909
+ return Response.json(
4910
+ { ok: false, error: parsed.error, reason: parsed.reason },
4911
+ { status: parsed.status, headers: { 'Cache-Control': 'no-store' } }
4912
+ );
4913
+ const r = await prepareManagedProject(ctx, parsed.input);
4850
4914
  return Response.json(r, {
4851
4915
  status: r.ok ? 200 : r.status,
4852
4916
  headers: { 'Cache-Control': 'no-store' },
4853
4917
  });
4854
4918
  },
4855
- '/_api/workspace/sign-in': async (req: Request) => {
4856
- if (req.method !== 'POST') return new Response('Method not allowed', { status: 405 });
4857
- if (!sameOriginWrite(req))
4858
- return new Response('cross-origin write rejected', { status: 403 });
4859
- if (!isTrustedRequestHost(req))
4860
- return new Response('local request required', { status: 403 });
4861
- const body = await readJson<unknown>(req, 8 * 1024);
4862
- const result = await signInToWorkspace((body ?? {}) as Record<string, unknown>);
4863
- return Response.json(result.json, {
4864
- status: result.status,
4865
- headers: { 'Cache-Control': 'no-store' },
4866
- });
4867
- },
4868
4919
 
4869
4920
  // The DDR-054 trust model in plain words, for the panel that replaces
4870
4921
  // DDR-079's terminal banner (DDR-192 §6). Read-only and main-origin — the
@@ -0,0 +1,40 @@
1
+ // apps/studio/index-flight.ts — #204: one project-index build at a time per reader.
2
+ //
3
+ // `/_index-data` walks every canvas group, reads each canvas's sidecar and its import closure: on a
4
+ // ~311-canvas, 7612-file workspace on a small cell that took longer than the client's timeout. The
5
+ // client aborted and asked again, but an aborted fetch does not stop the build on the server, so
6
+ // every retry started ANOTHER full build next to the one still running — each slower than the last.
7
+ //
8
+ // A request that arrives while a build for the same reader is in flight joins it, as long as the
9
+ // tree has not changed since that build started (`bump()` on every file event). A change after it
10
+ // started means its answer would be stale, so the next caller starts a fresh one.
11
+
12
+ export interface SingleFlight<T> {
13
+ run(key: string, build: () => Promise<T>): Promise<T>;
14
+ /** The tree changed: builds started before now must not be shared with later callers. */
15
+ bump(): void;
16
+ /** In-flight builds (for tests). */
17
+ size(): number;
18
+ }
19
+
20
+ export function createSingleFlight<T>(): SingleFlight<T> {
21
+ let gen = 0;
22
+ const flights = new Map<string, { gen: number; promise: Promise<T> }>();
23
+ return {
24
+ run(key, build) {
25
+ const hit = flights.get(key);
26
+ if (hit && hit.gen === gen) return hit.promise;
27
+ const entry = { gen, promise: Promise.resolve().then(build) };
28
+ flights.set(key, entry);
29
+ const clear = () => {
30
+ if (flights.get(key) === entry) flights.delete(key);
31
+ };
32
+ entry.promise.then(clear, clear);
33
+ return entry.promise;
34
+ },
35
+ bump() {
36
+ gen++;
37
+ },
38
+ size: () => flights.size,
39
+ };
40
+ }
@@ -5,9 +5,12 @@
5
5
  // two halves:
6
6
  //
7
7
  // 1. HERE (the running studio, which holds the Maude Cloud device session or
8
- // takes a team-server sign-in): obtain and store the hub credential, then
9
- // ask the project what it looks like (its bootstrap) — name, canvas
10
- // groups — so the local copy can be declared correctly before it exists.
8
+ // a team-server credential the browser sign-in already stored): obtain the
9
+ // hub credential, then ask the project what it looks like (its bootstrap)
10
+ // — name, canvas groups — so the local copy can be declared correctly
11
+ // before it exists. Issue #204: the desktop owns NO login method for a
12
+ // team server — no email, no password. A team server is signed in to on
13
+ // its OWN page (routes/hub-signin.ts); `known-hub` opens what that stored.
11
14
  // 2. The native shell (`managed_project_open`) creates the project's own
12
15
  // copy under the app's data directory from exactly what this returns,
13
16
  // and switches to it; the sync runtime then brings everything down.
@@ -16,17 +19,54 @@
16
19
 
17
20
  import { createCloudEndpoints } from './cloud/endpoints.ts';
18
21
  import type { Context } from './context.ts';
19
- import { saveHubCredential } from './sync/hub-link.ts';
20
22
  import { getHubRecord, normalizeUrl } from './sync/hubs-config.ts';
21
- import { signInToWorkspace } from './sync/workspace-signin.ts';
22
23
 
23
24
  export type PrepareInput =
24
25
  | { kind: 'cloud'; projectId: string }
25
26
  | { kind: 'handoff'; code: string; claimedProject?: string }
26
- | { kind: 'hub'; url: string; email: string; password: string }
27
- /** A team server this machine already holds a credential for. */
27
+ /** A team server this machine already holds a credential for (the browser sign-in stored it). */
28
28
  | { kind: 'known-hub'; url: string };
29
29
 
30
+ /** The words for an email or password sent to open a team-server project — the app takes neither
31
+ * (issue #204). Signing in is the hub's own page; the one fallback is the pasted access token. */
32
+ export const NO_PASSWORD_WORDS = "Sign in on the team server's own page — press Sign in.";
33
+
34
+ export type PrepareBody =
35
+ | { ok: true; input: PrepareInput }
36
+ | { ok: false; status: 400; error: string; reason?: 'password-retired' };
37
+
38
+ /** True for a body that carries a team-server email or password, or the retired `hub` kind. */
39
+ function carriesPassword(b: Record<string, unknown>): boolean {
40
+ return b.email !== undefined || b.password !== undefined || b.kind === 'hub';
41
+ }
42
+
43
+ /** `POST /_api/projects/prepare` body → a typed input, or a plain 400. Anything carrying an email
44
+ * or a password is refused for EVERY kind before an input is built — the secret is never read,
45
+ * forwarded or echoed. */
46
+ export function parsePrepareBody(body: unknown): PrepareBody {
47
+ const b = (body && typeof body === 'object' ? body : {}) as Record<string, unknown>;
48
+ if (carriesPassword(b))
49
+ return { ok: false, status: 400, reason: 'password-retired', error: NO_PASSWORD_WORDS };
50
+ const str = (v: unknown) => (typeof v === 'string' ? v : '');
51
+ switch (b.kind) {
52
+ case 'cloud':
53
+ return { ok: true, input: { kind: 'cloud', projectId: str(b.projectId) } };
54
+ case 'handoff':
55
+ return {
56
+ ok: true,
57
+ input: {
58
+ kind: 'handoff',
59
+ code: str(b.code),
60
+ claimedProject: str(b.claimedProject) || undefined,
61
+ },
62
+ };
63
+ case 'known-hub':
64
+ return { ok: true, input: { kind: 'known-hub', url: str(b.url) } };
65
+ default:
66
+ return { ok: false, status: 400, error: 'unknown kind' };
67
+ }
68
+ }
69
+
30
70
  export interface PreparedProject {
31
71
  ok: true;
32
72
  serverUrl: string;
@@ -119,9 +159,13 @@ export async function prepareManagedProject(
119
159
  /** `hubsConfigPath`: where the hub credential is stored and read back (N-H1 — Home prepares
120
160
  * for one profile at a time, so never the process-global file for another profile).
121
161
  * `fetchImpl` (S6.6): every request to a team server goes through it — Home passes one that
122
- * refuses redirects, so a 307 can never carry the password or the token to another host. */
162
+ * refuses redirects, so a 307 can never carry the token to another host. */
123
163
  opts: { cloudConfigPath?: string; hubsConfigPath?: string; fetchImpl?: typeof fetch } = {}
124
164
  ): Promise<PrepareResult> {
165
+ // A caller outside the types can still hand over a retired shape (an email, a password, the old
166
+ // `hub` kind): refused before any request, here as well as at the route.
167
+ if (carriesPassword(input as unknown as Record<string, unknown>))
168
+ return { ok: false, error: NO_PASSWORD_WORDS, status: 400 };
125
169
  let serverUrl: string;
126
170
  let projectId: string | null = null;
127
171
  let role: string | null = null;
@@ -161,22 +205,6 @@ export async function prepareManagedProject(
161
205
  projectId = j.project ?? (input.kind === 'cloud' ? input.projectId : null);
162
206
  role = j.role ?? null;
163
207
  name = projectId;
164
- } else if (input.kind === 'hub') {
165
- const hubsPath = opts.hubsConfigPath;
166
- const r = await signInToWorkspace(
167
- { url: input.url, email: input.email, password: input.password },
168
- {
169
- fetchImpl: opts.fetchImpl,
170
- // S6.6: the credential goes to the SAME hubs.json it is read back from below — before,
171
- // a non-default profile stored it in the process-global file and then could not find it
172
- save: hubsPath
173
- ? (u, t, role, exp, account) => saveHubCredential(u, t, role, exp, hubsPath, account)
174
- : undefined,
175
- }
176
- );
177
- if (!r.json.ok) return { ok: false, error: r.json.error, status: r.status };
178
- serverUrl = r.json.url;
179
- role = r.json.user.role;
180
208
  } else {
181
209
  try {
182
210
  serverUrl = normalizeUrl(input.url);
@@ -149,7 +149,13 @@ export function createHubFormatClient(
149
149
  const res = await fetchImpl(`${base}${MODE_PATH}`, {
150
150
  method: 'POST',
151
151
  headers: { 'content-type': 'application/json', authorization: `Bearer ${hub.token}` },
152
- body: JSON.stringify({ mode, expectEpoch, ...(dryRun ? { dryRun: true } : {}) }),
152
+ // #166 (2.0.4): a dry run here reads only the blockers, so it asks for them alone —
153
+ // the hub's full preview imports (opens) every document. An older hub ignores the flag.
154
+ body: JSON.stringify({
155
+ mode,
156
+ expectEpoch,
157
+ ...(dryRun ? { dryRun: true, preview: false } : {}),
158
+ }),
153
159
  // The switch answers after it imported every document (T30) — a big project takes a
154
160
  // while. A timeout is not a refusal: the hub may finish, and the next run reads it.
155
161
  signal: AbortSignal.timeout(dryRun ? 30_000 : 180_000),
@@ -67,6 +67,9 @@ export function assetStateDepsFor(opts: {
67
67
  const inCell = (opts.env ?? process.env).MAUDE_WORKSPACE_MODE === '1';
68
68
  const service = createAssetStateService({
69
69
  designRoot: opts.designRoot,
70
+ // The project root is designRoot minus designRel (`.design`): where the Git LFS store is looked
71
+ // for. The server's own paths, never a request's.
72
+ projectRoot: projectRootOf(opts.designRoot, opts.designRel),
70
73
  hub: () => opts.runtime()?.assetPresenceAsker?.() ?? null,
71
74
  uploading: () => opts.runtime()?.assetUploading?.() ?? null,
72
75
  });
@@ -78,6 +81,15 @@ export function assetStateDepsFor(opts: {
78
81
  };
79
82
  }
80
83
 
84
+ /** `<repo>/.design` + `.design` → `<repo>`. */
85
+ export function projectRootOf(designRoot: string, designRel: string): string {
86
+ const ups = designRel
87
+ .split(/[\\/]+/)
88
+ .filter((s) => s && s !== '.')
89
+ .map(() => '..');
90
+ return path.resolve(designRoot, ...ups);
91
+ }
92
+
81
93
  function canvasRels(deps: AssetStateRouteDeps, file: string): string[] | null {
82
94
  if (!deps.designRoot || deps.designRel === undefined) return null;
83
95
  const rel = resolveCanvasRel(deps.designRoot, deps.designRel, file);
@@ -39,13 +39,17 @@ import path from 'node:path';
39
39
 
40
40
  import { currentAccess, notInScopeResponse, toDesignRel } from '../access/request.ts';
41
41
  import type { Access } from '../access/scope.ts';
42
+ import { sandboxBuildRunning } from '../canvas-build-sandbox.ts';
42
43
  import {
44
+ type BuildFailure,
43
45
  type CanvasError,
44
46
  canvasSourceSig,
45
47
  checkCanvasSyntax,
48
+ recalledBuildFailure,
46
49
  recalledCanvasError,
47
50
  } from '../canvas-source/errors.ts';
48
51
  import { canvasSourceMap } from '../canvas-source/source-map.ts';
52
+ import { canvasWaiting, type LedgerView, readLedgerView } from '../canvas-source/waiting.ts';
49
53
  import { isUnderOrEqual } from '../path-containment.ts';
50
54
  import type { RouteSpec } from './table.ts';
51
55
 
@@ -65,6 +69,14 @@ export interface CanvasSourceRouteDeps {
65
69
  historicalSource?: (repoRel: string, ref: string) => Promise<string | null | 'busy'>;
66
70
  /** The DNS-rebinding guard (http.ts `isTrustedRequestHost`); absent = every Host passes. */
67
71
  trustedHost?: (req: Request) => boolean;
72
+ /**
73
+ * 2.0.4 — the file plane's ledger, for "what is this canvas still waiting for"
74
+ * (`canvas-source/waiting.ts`). Default: the ledger file this Mac's plane persists under
75
+ * `<designRoot>/_state/file-ledger/` (none in a cell, or before a project links).
76
+ */
77
+ ledger?: () => LedgerView | null;
78
+ /** 2.0.4 task P — whether a sandboxed build of this canvas is running. Default: the sandbox's own. */
79
+ buildRunning?: (canvasAbs: string) => boolean;
68
80
  }
69
81
 
70
82
  const json = (status: number, body: unknown) =>
@@ -179,6 +191,17 @@ function errorsOfFile(deps: CanvasSourceRouteDeps, abs: string): CanvasError[] |
179
191
  return built ? [built] : [];
180
192
  }
181
193
 
194
+ /** #189 — the last build's failure class, while the source is still the one that failed. */
195
+ function buildFailureOfFile(abs: string): BuildFailure | null {
196
+ try {
197
+ const st = statSync(abs);
198
+ if (st.size > MAX_SOURCE_BYTES) return null;
199
+ return recalledBuildFailure(abs, canvasSourceSig(readFileSync(abs, 'utf8')));
200
+ } catch {
201
+ return null;
202
+ }
203
+ }
204
+
182
205
  /** Every canvas under the design root (design-root-relative, sorted), runtime folders skipped. */
183
206
  export function listCanvases(designRoot: string): string[] {
184
207
  const out: string[] = [];
@@ -282,9 +305,28 @@ export function createCanvasSourceRoutes(deps: CanvasSourceRouteDeps): RouteSpec
282
305
  if (refused) return refused;
283
306
  const file = canvasFile(deps.designRoot, rel);
284
307
  const list = file ? errorsOfFile(deps, file) : null;
285
- if (list === null)
308
+ if (list === null || !file)
286
309
  return access.canvasOnly ? notInScopeResponse() : json(404, { error: 'not-found' });
287
- return json(200, { canvas: repoRelOf(deps.designRel, rel), errors: list });
310
+ // 2.0.4 — what it is still waiting for (an import this Mac does not hold yet, or holds back),
311
+ // and why the last build stopped when the reason is not in its code (#189). Both are our own
312
+ // words and numbers: no file content, no build text, no specifier.
313
+ const waiting = canvasWaiting({
314
+ designRoot: deps.designRoot,
315
+ canvasAbs: file,
316
+ ledger: (deps.ledger ?? (() => readLedgerView(deps.designRoot)))(),
317
+ project: !access.canvasOnly,
318
+ });
319
+ // 2.0.4 task P — a sandboxed build of it is still running (it outlived the request that
320
+ // started it): not a failure, and the last failure on record is about to be replaced.
321
+ const building = !list.length && (deps.buildRunning ?? sandboxBuildRunning)(file);
322
+ const buildFailure = list.length || building ? null : buildFailureOfFile(file);
323
+ return json(200, {
324
+ canvas: repoRelOf(deps.designRel, rel),
325
+ errors: list,
326
+ ...(waiting ? { waiting } : {}),
327
+ ...(building ? { building: true } : {}),
328
+ ...(buildFailure ? { buildFailure } : {}),
329
+ });
288
330
  }
289
331
  const canvases: Array<{ canvas: string; errors: CanvasError[] }> = [];
290
332
  for (const rel of listCanvases(deps.designRoot)) {
@@ -15,9 +15,14 @@
15
15
  // MAIN ORIGIN ONLY, never canvas-safe (a shell panel's read; absent from both canvas allowlists). Reads only, for
16
16
  // every role that can read the project. A canvas-only session is answered from its closure alone (`filterAssetListing`'s
17
17
  // rule for `/_api/assets`): the files its canvases' closure reads, and no folder without one.
18
+ //
19
+ // ON A MATERIALIZING CELL (2.0.3) the system's media is in the hub's journal, not on the checkout (DDR-243): the hub's
20
+ // inert-media listing (`listMaterializable` — the file tree's and the closure's source) joins the disk, so the folders
21
+ // carry their counts and files again. Off a cell it answers `null` at once and the disk alone is listed, as before.
18
22
 
19
23
  import type { Visibility } from '../access/filters.ts';
20
24
  import { listDsAssets } from '../ds-assets.ts';
25
+ import { listMaterializable } from '../materialize-client.ts';
21
26
  import type { RouteSpec } from './table.ts';
22
27
 
23
28
  const json = (status: number, body: unknown) =>
@@ -29,6 +34,8 @@ export interface DsAssetsRouteDeps {
29
34
  systems: () => ReadonlyArray<{ name: string; path: string }>;
30
35
  /** The session's visibility (http.ts `visOf`). */
31
36
  visibility: (req: Request) => Visibility;
37
+ /** A materializing cell's journal media (designRoot-relative); `null` off a cell. Default `listMaterializable`. */
38
+ journalMedia?: () => Promise<readonly string[] | null>;
32
39
  }
33
40
 
34
41
  export function createDsAssetsRoutes(deps: DsAssetsRouteDeps): RouteSpec[] {
@@ -58,6 +65,7 @@ export function createDsAssetsRoutes(deps: DsAssetsRouteDeps): RouteSpec[] {
58
65
  cursor: q.get('cursor'),
59
66
  limit: q.get('limit'),
60
67
  ...(candidates ? { candidates } : {}),
68
+ journal: await (deps.journalMedia ?? listMaterializable)(),
61
69
  });
62
70
  if (!page.ok) return json(page.status, { ok: false, reason: page.reason });
63
71
  // a canvas-only session that sees nothing of this library is told it is not there