@dexhq/canvas 0.15.0 → 0.16.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 (307) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/app/canvas/activity-parts.tsx +50 -6
  3. package/app/canvas/activity.tsx +2 -3
  4. package/app/canvas/agent-changes.ts +18 -8
  5. package/app/canvas/anchoring.ts +13 -3
  6. package/app/canvas/canvas-context.tsx +6 -2
  7. package/app/canvas/canvas-input.ts +35 -0
  8. package/app/canvas/canvas-model.ts +2 -2
  9. package/app/canvas/canvas-scene.ts +243 -24
  10. package/app/canvas/canvas-ui.ts +11 -2
  11. package/app/canvas/canvas.css +86 -3
  12. package/app/canvas/comments.tsx +66 -29
  13. package/app/canvas/element-link.ts +135 -0
  14. package/app/canvas/element-picker.ts +23 -0
  15. package/app/canvas/export-dialog.tsx +265 -0
  16. package/app/canvas/flow-canvas.tsx +65 -14
  17. package/app/canvas/frame-context-menu.tsx +61 -7
  18. package/app/canvas/frame-node.tsx +10 -11
  19. package/app/canvas/layout.ts +41 -22
  20. package/app/canvas/linked-element.tsx +196 -0
  21. package/app/canvas/live-page.ts +14 -0
  22. package/app/canvas/mentions.tsx +209 -0
  23. package/app/canvas/picked-box.tsx +21 -0
  24. package/app/canvas/removed-views-panel.tsx +4 -4
  25. package/app/canvas/request-node.tsx +151 -0
  26. package/app/canvas/review-panel.tsx +8 -3
  27. package/app/canvas/section-node.tsx +4 -133
  28. package/app/canvas/spec-margin.tsx +4 -1
  29. package/app/canvas/teammates-layer.tsx +205 -0
  30. package/app/canvas/text-layer.tsx +103 -17
  31. package/app/canvas/tool-cursors.ts +7 -6
  32. package/app/canvas/tool-icons.tsx +24 -56
  33. package/app/canvas/typing.ts +12 -0
  34. package/app/canvas/use-agent-changes.tsx +6 -2
  35. package/app/canvas/use-canvas-editor.ts +4 -2
  36. package/app/export/player-model.ts +159 -0
  37. package/app/export/player.tsx +198 -0
  38. package/app/export.html +31 -0
  39. package/app/export.tsx +9 -0
  40. package/app/frame/announce-refreshes.ts +21 -0
  41. package/app/frame/start-frame.tsx +50 -0
  42. package/app/frame/view-loads.ts +161 -0
  43. package/app/frame/views.ts +13 -49
  44. package/app/frame.tsx +2 -38
  45. package/app/i18n/locales/en/messages.po +145 -6
  46. package/app/i18n/locales/en/messages.ts +1 -1
  47. package/app/i18n/locales/pseudo/messages.po +144 -5
  48. package/app/i18n/locales/pseudo/messages.ts +1 -1
  49. package/app/icons/dex-glyphs.tsx +219 -0
  50. package/app/icons/glyphs.tsx +76 -80
  51. package/app/kit/use-flow.ts +2 -1
  52. package/app/live/canvas-teammates.ts +90 -0
  53. package/app/live/studio-api.ts +30 -20
  54. package/app/pages/canvas.tsx +18 -6
  55. package/app/pages/commands-settings.tsx +1 -1
  56. package/app/pages/render.tsx +39 -11
  57. package/app/shell/bell.tsx +15 -5
  58. package/app/shell/presence.tsx +123 -26
  59. package/app/shell/thread-list.tsx +25 -8
  60. package/app/shell/working-on.tsx +35 -3
  61. package/app/ui/prompt-editor.tsx +39 -11
  62. package/app/ui/reference.tsx +21 -8
  63. package/bin/sudio.mjs +1 -1
  64. package/dist/cli/commands/create.d.mts +5 -5
  65. package/dist/cli/commands/create.mjs +4 -4
  66. package/dist/cli/commands/export.d.mts +40 -0
  67. package/dist/cli/commands/export.mjs +66 -0
  68. package/dist/cli/commands/init.d.mts +2 -2
  69. package/dist/cli/commands/upgrade.mjs +1 -1
  70. package/dist/cli/help.d.mts +1 -1
  71. package/dist/cli/help.mjs +13 -7
  72. package/dist/cli/main.d.mts +42 -5
  73. package/dist/cli/main.mjs +1 -0
  74. package/dist/config/load.mjs +14 -2
  75. package/dist/config/project-files.d.mts +5 -0
  76. package/dist/config/project-files.mjs +10 -1
  77. package/dist/config/renamed.d.mts +7 -0
  78. package/dist/config/renamed.mjs +13 -1
  79. package/dist/content/commands.d.mts +11 -9
  80. package/dist/content/commands.mjs +22 -16
  81. package/dist/content/comments-log.mjs +2 -1
  82. package/dist/content/content.d.mts +11 -3
  83. package/dist/content/content.mjs +49 -15
  84. package/dist/content/element-words.d.mts +42 -0
  85. package/dist/content/element-words.mjs +112 -0
  86. package/dist/content/hosted-person.d.mts +31 -0
  87. package/dist/content/hosted-person.mjs +68 -0
  88. package/dist/content/merge-rules.d.mts +5 -0
  89. package/dist/content/merge-rules.mjs +17 -1
  90. package/dist/content/screenshot.mjs +9 -0
  91. package/dist/content/text-edit.d.mts +24 -14
  92. package/dist/content/text-edit.mjs +92 -81
  93. package/dist/content/text-replace.mjs +2 -26
  94. package/dist/content/thread-module.d.mts +2 -4
  95. package/dist/content/thread-module.mjs +4 -5
  96. package/dist/server/agents.d.mts +10 -0
  97. package/dist/server/agents.mjs +21 -6
  98. package/dist/server/canvas-presence.d.mts +22 -0
  99. package/dist/server/canvas-presence.mjs +160 -0
  100. package/dist/server/command-settings.mjs +1 -1
  101. package/dist/server/comments/actions.d.mts +0 -8
  102. package/dist/server/comments/actions.mjs +1 -9
  103. package/dist/server/comments/routes.mjs +10 -31
  104. package/dist/server/dev-server.mjs +35 -13
  105. package/dist/server/export/build.d.mts +15 -0
  106. package/dist/server/export/build.mjs +220 -0
  107. package/dist/server/export/page.d.mts +25 -0
  108. package/dist/server/export/page.mjs +40 -0
  109. package/dist/server/export/plugin.d.mts +31 -0
  110. package/dist/server/export/plugin.mjs +69 -0
  111. package/dist/server/export/run.d.mts +9 -0
  112. package/dist/server/export/run.mjs +61 -0
  113. package/dist/server/export/save.d.mts +7 -0
  114. package/dist/server/export/save.mjs +29 -0
  115. package/dist/server/hosted.d.mts +8 -0
  116. package/dist/server/hosted.mjs +78 -0
  117. package/dist/server/live-mirror.mjs +66 -10
  118. package/dist/server/live.mjs +28 -1
  119. package/dist/server/mcp.mjs +2 -0
  120. package/dist/server/me.d.mts +2 -0
  121. package/dist/server/me.mjs +8 -2
  122. package/dist/server/notices.d.mts +1 -1
  123. package/dist/server/notices.mjs +1 -1
  124. package/dist/server/own-copies.mjs +1 -1
  125. package/dist/server/people.d.mts +7 -2
  126. package/dist/server/people.mjs +6 -2
  127. package/dist/server/pictures.d.mts +1 -1
  128. package/dist/server/pictures.mjs +2 -2
  129. package/dist/server/prebundle.d.mts +32 -0
  130. package/dist/server/prebundle.mjs +115 -0
  131. package/dist/server/problems.d.mts +8 -0
  132. package/dist/server/problems.mjs +13 -0
  133. package/dist/server/requests.mjs +43 -30
  134. package/dist/server/source-stamp.d.mts +4 -3
  135. package/dist/server/source-stamp.mjs +60 -31
  136. package/dist/server/state.d.mts +19 -10
  137. package/dist/server/state.mjs +27 -18
  138. package/dist/server/thread-source.d.mts +8 -0
  139. package/dist/server/thread-source.mjs +24 -5
  140. package/dist/server/tools/export.d.mts +5 -0
  141. package/dist/server/tools/export.mjs +35 -0
  142. package/dist/server/tools/place-frame.mjs +16 -16
  143. package/dist/server/tools/thread-list.mjs +1 -1
  144. package/dist/server/vite.d.mts +9 -4
  145. package/dist/server/vite.mjs +63 -61
  146. package/dist/server/welcome.mjs +2 -1
  147. package/dist/setup/apply.d.mts +4 -0
  148. package/dist/setup/apply.mjs +5 -4
  149. package/dist/setup/create.mjs +5 -5
  150. package/dist/setup/design-system-checks.mjs +1 -6
  151. package/dist/setup/detect/workspace.d.mts +10 -10
  152. package/dist/setup/detect/workspace.mjs +10 -12
  153. package/dist/setup/doctor.d.mts +4 -1
  154. package/dist/setup/doctor.mjs +7 -5
  155. package/dist/setup/migrate/dex-folder.d.mts +61 -0
  156. package/dist/setup/migrate/dex-folder.mjs +544 -0
  157. package/dist/setup/migrate/files-folder.mjs +1 -1
  158. package/dist/setup/migrate/guides.mjs +1 -1
  159. package/dist/setup/migrate/migrations.mjs +4 -0
  160. package/dist/setup/migrate/setup-files.d.mts +5 -0
  161. package/dist/setup/migrate/setup-files.mjs +115 -0
  162. package/dist/setup/migrate/studio-state.d.mts +2 -2
  163. package/dist/setup/migrate/studio-state.mjs +4 -4
  164. package/dist/setup/placement.d.mts +1 -1
  165. package/dist/setup/placement.mjs +5 -4
  166. package/dist/setup/plan.d.mts +5 -5
  167. package/dist/setup/plan.mjs +8 -12
  168. package/dist/setup/project.mjs +1 -1
  169. package/dist/setup/prompts.d.mts +2 -1
  170. package/dist/setup/prompts.mjs +4 -3
  171. package/dist/setup/questions.mjs +3 -2
  172. package/dist/setup/starters.d.mts +1 -1
  173. package/dist/setup/starters.mjs +2 -2
  174. package/dist/setup/write.d.mts +15 -3
  175. package/dist/setup/write.mjs +23 -3
  176. package/dist/shared/canvas-core.d.mts +22 -7
  177. package/dist/shared/canvas-core.mjs +38 -10
  178. package/dist/shared/comments/routes.d.mts +3 -1
  179. package/dist/shared/comments/routes.mjs +4 -2
  180. package/dist/shared/export-core.d.mts +62 -0
  181. package/dist/shared/export-core.mjs +101 -0
  182. package/dist/shared/live-core.d.mts +2 -0
  183. package/dist/shared/live-core.mjs +6 -1
  184. package/dist/shared/live-presence.d.mts +57 -2
  185. package/dist/shared/live-presence.mjs +90 -4
  186. package/dist/shared/page-messages.d.mts +14 -1
  187. package/dist/shared/page-messages.mjs +30 -3
  188. package/dist/shared/people-core.d.mts +28 -0
  189. package/dist/shared/people-core.mjs +27 -1
  190. package/dist/shared/presence-core.d.mts +2 -0
  191. package/dist/shared/references-core.d.mts +4 -0
  192. package/dist/shared/references-core.mjs +12 -4
  193. package/dist/shared/studio-files.d.mts +9 -0
  194. package/dist/shared/studio-files.mjs +11 -2
  195. package/dist/shared/studio-routes.d.mts +13 -1
  196. package/dist/shared/threads-core.d.mts +27 -4
  197. package/dist/shared/threads-core.mjs +67 -12
  198. package/extension/dist/feedback.js +104 -294
  199. package/extension/dist/manifest.json +1 -1
  200. package/extension/dist/picker.js +104 -294
  201. package/package.json +2 -2
  202. package/src/cli/commands/create.ts +4 -4
  203. package/src/cli/commands/export.ts +78 -0
  204. package/src/cli/commands/upgrade.ts +1 -1
  205. package/src/cli/help.ts +13 -7
  206. package/src/cli/main.ts +1 -0
  207. package/src/config/load.ts +26 -2
  208. package/src/config/project-files.ts +15 -0
  209. package/src/config/renamed.ts +19 -1
  210. package/src/content/commands.ts +30 -18
  211. package/src/content/comments-log.ts +4 -1
  212. package/src/content/content.ts +64 -16
  213. package/src/content/element-words.ts +175 -0
  214. package/src/content/hosted-person.ts +107 -0
  215. package/src/content/merge-rules.ts +29 -0
  216. package/src/content/screenshot.ts +14 -0
  217. package/src/content/text-edit.ts +172 -105
  218. package/src/content/text-replace.ts +3 -32
  219. package/src/content/thread-module.ts +2 -4
  220. package/src/content/trash.ts +1 -1
  221. package/src/server/agents.ts +48 -17
  222. package/src/server/canvas-presence.ts +237 -0
  223. package/src/server/channel.ts +1 -1
  224. package/src/server/command-settings.ts +1 -1
  225. package/src/server/comments/actions.ts +0 -19
  226. package/src/server/comments/routes.ts +9 -54
  227. package/src/server/dev-server.ts +66 -26
  228. package/src/server/export/build.ts +310 -0
  229. package/src/server/export/page.ts +85 -0
  230. package/src/server/export/plugin.ts +138 -0
  231. package/src/server/export/run.ts +79 -0
  232. package/src/server/export/save.ts +38 -0
  233. package/src/server/hosted.ts +113 -0
  234. package/src/server/live-mirror.ts +93 -8
  235. package/src/server/live.ts +46 -1
  236. package/src/server/machine-update.ts +3 -3
  237. package/src/server/mcp.ts +2 -0
  238. package/src/server/me.ts +10 -1
  239. package/src/server/notices.ts +2 -2
  240. package/src/server/people.ts +11 -2
  241. package/src/server/pictures.ts +2 -2
  242. package/src/server/prebundle.ts +230 -0
  243. package/src/server/presence.ts +1 -1
  244. package/src/server/problems.ts +11 -0
  245. package/src/server/requests.ts +55 -40
  246. package/src/server/roster.ts +1 -1
  247. package/src/server/saved.ts +1 -1
  248. package/src/server/source-stamp.ts +118 -37
  249. package/src/server/state.ts +53 -31
  250. package/src/server/thread-source.ts +35 -3
  251. package/src/server/tools/export.ts +56 -0
  252. package/src/server/tools/place-frame.ts +23 -15
  253. package/src/server/tools/thread-list.ts +1 -1
  254. package/src/server/updates.ts +2 -2
  255. package/src/server/vite.ts +106 -110
  256. package/src/server/welcome.ts +3 -1
  257. package/src/setup/apply.ts +8 -5
  258. package/src/setup/create.ts +10 -10
  259. package/src/setup/design-system-checks.ts +1 -6
  260. package/src/setup/detect/workspace.ts +20 -21
  261. package/src/setup/doctor.ts +13 -6
  262. package/src/setup/migrate/dex-folder.ts +842 -0
  263. package/src/setup/migrate/files-folder.ts +1 -1
  264. package/src/setup/migrate/guides.ts +3 -1
  265. package/src/setup/migrate/migrations.ts +8 -2
  266. package/src/setup/migrate/setup-files.ts +198 -0
  267. package/src/setup/migrate/studio-state.ts +12 -10
  268. package/src/setup/own-app.ts +1 -1
  269. package/src/setup/placement.ts +7 -6
  270. package/src/setup/plan.ts +13 -18
  271. package/src/setup/project.ts +2 -2
  272. package/src/setup/prompts.ts +5 -4
  273. package/src/setup/questions.ts +6 -3
  274. package/src/setup/starters.ts +3 -3
  275. package/src/setup/write.ts +34 -3
  276. package/src/shared/canvas-core.ts +48 -9
  277. package/src/shared/comments/routes.ts +3 -1
  278. package/src/shared/export-core.ts +198 -0
  279. package/src/shared/live-core.ts +8 -0
  280. package/src/shared/live-presence.ts +171 -2
  281. package/src/shared/page-messages.ts +38 -2
  282. package/src/shared/people-core.ts +44 -0
  283. package/src/shared/presence-core.ts +2 -0
  284. package/src/shared/references-core.ts +22 -3
  285. package/src/shared/studio-files.ts +15 -1
  286. package/src/shared/studio-routes.ts +11 -1
  287. package/src/shared/threads-core.ts +132 -10
  288. package/templates/methods/explore.md +1 -1
  289. package/templates/methods/handoff.md +1 -1
  290. package/templates/methods/review.md +2 -1
  291. package/templates/rules/canvas-frames.md +6 -3
  292. package/templates/rules/commands.md +1 -0
  293. package/templates/rules/prototypes.md +1 -1
  294. package/templates/rules/studio.md +17 -11
  295. package/templates/skills/comprehend/SKILL.md +56 -0
  296. package/templates/skills/distill/SKILL.md +172 -0
  297. package/templates/skills/export-prototype/SKILL.md +35 -0
  298. package/templates/skills/riff/SKILL.md +21 -0
  299. package/templates/skills/riff-deep/SKILL.md +40 -0
  300. package/templates/skills/riff-max/SKILL.md +46 -0
  301. package/templates/skills/riff-state/SKILL.md +45 -0
  302. package/templates/skills/riff-up/SKILL.md +38 -0
  303. package/templates/skills/riff-wide/SKILL.md +40 -0
  304. package/templates/starters/standalone/README.md +1 -1
  305. package/templates/starters/turborepo/README.md +2 -2
  306. package/templates/starters/turborepo/apps/web/src/app.tsx +2 -2
  307. package/templates/starters/vite/README.md +1 -1
@@ -0,0 +1,138 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { join, relative, sep } from "node:path";
3
+ import type { Plugin } from "vite";
4
+ import { APP_DIR, posix } from "../../paths.ts";
5
+ import { CONTENT_GLOBAL } from "../../shared/export-core.ts";
6
+
7
+ // What an export's build changes in the frame page's (export/build.ts):
8
+ // - the views it can show are the exported ones, keyed without whose they
9
+ // are, so nobody's name goes out in the bundle;
10
+ // - Dex's own sheets (studio-view.tsx: the components prototype, the note
11
+ // for no view) are left out, and with them the interface's stylesheet,
12
+ // which would restyle the design if it were bundled in;
13
+ // - a content pack's content.json files are read from content.js, so they
14
+ // can be edited without building again;
15
+ // - the prototype's files the bundle took are noted, for a source pack.
16
+
17
+ const VIEW_FILES = join(APP_DIR, "frame", "view-files.ts");
18
+ const STUDIO_VIEW = join(APP_DIR, "frame", "studio-view.tsx");
19
+ const CONTENT_FILE = "content.json";
20
+ const CONTENT_ID = "\0dex-export-content:";
21
+ // Not ".json" at the end, or Vite's JSON plugin reads the module as JSON.
22
+ const CONTENT_SUFFIX = ".content.js";
23
+ const contentFile = (id: string) =>
24
+ id.slice(CONTENT_ID.length, -CONTENT_SUFFIX.length);
25
+
26
+ /** A view the export shows, by name, and its file. */
27
+ export interface ExportedView {
28
+ file: string;
29
+ name: string;
30
+ }
31
+
32
+ export interface ExportPluginOptions {
33
+ /** Read content.json from content.js. */
34
+ content: boolean;
35
+ /** The interface's stylesheet, which must never be in the bundle. */
36
+ interfaceCss: string;
37
+ /** The people whose views are exported, in order: content keys number them. */
38
+ people: string[];
39
+ /** The prototype's folder: what a source pack and content keys are relative to. */
40
+ prototypeDir: string;
41
+ slug: string;
42
+ views: ExportedView[];
43
+ }
44
+
45
+ /** What the build found, for the export to write beside the bundle. */
46
+ export interface ExportFound {
47
+ /** Each content.json the bundle reads, by its path in the prototype. */
48
+ content: Map<string, unknown>;
49
+ /** The prototype's files the bundle took, relative to its folder. */
50
+ sources: string[];
51
+ }
52
+
53
+ /** The module that lists the views, with only the exported ones in it. */
54
+ const viewFilesModule = (slug: string, views: ExportedView[]): string => {
55
+ const entries = views.map(
56
+ ({ file, name }) =>
57
+ // views.ts reads a key's prototype and name, never its person.
58
+ ` ${JSON.stringify(`/files/${slug}/people/_/views/${name}.tsx`)}: () => import(${JSON.stringify(posix(file))}),`
59
+ );
60
+ return `export const viewFiles = {\n${entries.join("\n")}\n};\n`;
61
+ };
62
+
63
+ const STUDIO_VIEW_STUB =
64
+ "// Left out of an export: only exported views show.\nexport default function StudioView() { return null; }\n";
65
+
66
+ const within = (folder: string, file: string) => {
67
+ const path = relative(folder, file);
68
+ return path && !path.startsWith("..") && !path.startsWith(sep)
69
+ ? posix(path)
70
+ : undefined;
71
+ };
72
+
73
+ /**
74
+ * A content.json's key in content.js: its path in the file, each person's
75
+ * folder numbered rather than named, so nobody's name goes out.
76
+ */
77
+ const contentKey = (options: ExportPluginOptions, file: string): string => {
78
+ const path = within(options.prototypeDir, file) ?? "content.json";
79
+ const [people, person, ...rest] = path.split("/");
80
+ const number = options.people.indexOf(person ?? "") + 1;
81
+ return people === "people" && number > 0
82
+ ? ["people", String(number), ...rest].join("/")
83
+ : path;
84
+ };
85
+
86
+ export function exportPlugin(options: ExportPluginOptions): {
87
+ found: ExportFound;
88
+ plugin: Plugin;
89
+ } {
90
+ const found: ExportFound = { content: new Map(), sources: [] };
91
+ const plugin: Plugin = {
92
+ name: "dex:export",
93
+ enforce: "pre",
94
+ async resolveId(source, importer) {
95
+ if (!(options.content && importer && source.endsWith(CONTENT_FILE))) {
96
+ return;
97
+ }
98
+ const resolved = await this.resolve(source, importer, { skipSelf: true });
99
+ const path = resolved && within(options.prototypeDir, resolved.id);
100
+ return path ? `${CONTENT_ID}${resolved.id}${CONTENT_SUFFIX}` : undefined;
101
+ },
102
+ async load(id) {
103
+ if (id === VIEW_FILES) {
104
+ return viewFilesModule(options.slug, options.views);
105
+ }
106
+ if (id === STUDIO_VIEW) {
107
+ return STUDIO_VIEW_STUB;
108
+ }
109
+ if (id.startsWith(CONTENT_ID)) {
110
+ const file = contentFile(id);
111
+ const key = contentKey(options, file);
112
+ found.content.set(key, JSON.parse(await readFile(file, "utf8")));
113
+ return `export default window[${JSON.stringify(CONTENT_GLOBAL)}][${JSON.stringify(key)}];\n`;
114
+ }
115
+ return;
116
+ },
117
+ generateBundle() {
118
+ const ids = [...this.getModuleIds()];
119
+ if (ids.some((id) => id.split("?")[0] === options.interfaceCss)) {
120
+ this.error(
121
+ "Dex's own stylesheet ended up in the export, where it would restyle the design."
122
+ );
123
+ }
124
+ found.sources = ids
125
+ .map((id) =>
126
+ within(
127
+ options.prototypeDir,
128
+ id.startsWith(CONTENT_ID)
129
+ ? contentFile(id)
130
+ : (id.split("?")[0] ?? id)
131
+ )
132
+ )
133
+ .filter((path): path is string => Boolean(path))
134
+ .sort();
135
+ },
136
+ };
137
+ return { found, plugin };
138
+ }
@@ -0,0 +1,79 @@
1
+ import { execFile } from "node:child_process";
2
+ import { mkdtemp, readFile, rm } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import { basename, join } from "node:path";
5
+ import { PACKAGE_ROOT } from "../../paths.ts";
6
+ import {
7
+ type ExportChoice,
8
+ exportChoiceProblems,
9
+ } from "../../shared/export-core.ts";
10
+ import { Problems } from "../problems.ts";
11
+ import type { ExportResult } from "./build.ts";
12
+
13
+ // An export from Dex as it runs (the dialog's route, the MCP tool) runs
14
+ // `dex export` in a process of its own: a build takes seconds and much
15
+ // memory, which the development server and the agent's tools keep for
16
+ // themselves.
17
+
18
+ const DEX = join(PACKAGE_ROOT, "bin", "dex.mjs");
19
+ /** Longer than any export takes, so a stuck build gives up. */
20
+ const EXPORT_TIMEOUT_MS = 5 * 60_000;
21
+ const OUTPUT_BYTES = 16 * 1024 * 1024;
22
+
23
+ const lastLine = (text: string) => text.trim().split("\n").at(-1) ?? "";
24
+
25
+ const flags = (choice: ExportChoice): string[] => [
26
+ "--kind",
27
+ choice.kind,
28
+ ...(choice.frames?.length ? ["--frames", choice.frames.join(",")] : []),
29
+ ...(choice.sections?.length ? ["--sections", choice.sections.join(",")] : []),
30
+ ...(choice.flows ? ["--flows"] : []),
31
+ ];
32
+
33
+ /**
34
+ * Export a file's frames as `body` asks, in a process of its own. Throws
35
+ * Problems: 400 for a body that isn't an export's, 422 with why when the
36
+ * export can't be made.
37
+ */
38
+ export async function exportInChild(
39
+ root: string,
40
+ slug: string,
41
+ body: unknown
42
+ ): Promise<ExportResult> {
43
+ const problems = exportChoiceProblems(body);
44
+ if (problems.length > 0) {
45
+ throw new Problems(400, problems);
46
+ }
47
+ const out = await mkdtemp(join(tmpdir(), "dex-export-zip-"));
48
+ try {
49
+ const args = [
50
+ DEX,
51
+ "export",
52
+ "--slug",
53
+ slug,
54
+ ...flags(body as ExportChoice),
55
+ "--out",
56
+ out,
57
+ "--json",
58
+ ];
59
+ const stdout = await new Promise<string>((resolve, reject) => {
60
+ execFile(
61
+ process.execPath,
62
+ args,
63
+ {
64
+ cwd: root,
65
+ maxBuffer: OUTPUT_BYTES,
66
+ timeout: EXPORT_TIMEOUT_MS,
67
+ },
68
+ (error, output, errors) =>
69
+ error
70
+ ? reject(new Problems(422, [lastLine(errors) || error.message]))
71
+ : resolve(output)
72
+ );
73
+ });
74
+ const { path } = JSON.parse(lastLine(stdout)) as { path: string };
75
+ return { name: basename(path), bytes: await readFile(path) };
76
+ } finally {
77
+ await rm(out, { recursive: true, force: true });
78
+ }
79
+ }
@@ -0,0 +1,38 @@
1
+ import { existsSync } from "node:fs";
2
+ import { mkdir, writeFile } from "node:fs/promises";
3
+ import { homedir } from "node:os";
4
+ import { extname, join, resolve } from "node:path";
5
+ import type { ExportResult } from "./build.ts";
6
+
7
+ /** Downloads, where an export goes unless told otherwise; else here. */
8
+ export const downloadsFolder = (): string => {
9
+ const downloads = join(homedir(), "Downloads");
10
+ return existsSync(downloads) ? downloads : process.cwd();
11
+ };
12
+
13
+ /** A name in `folder` nothing has yet: "board.zip", then "board (2).zip". */
14
+ const freeName = (folder: string, name: string): string => {
15
+ const extension = extname(name);
16
+ const stem = name.slice(0, name.length - extension.length);
17
+ for (let count = 1; ; count += 1) {
18
+ const path = join(
19
+ folder,
20
+ count === 1 ? name : `${stem} (${count})${extension}`
21
+ );
22
+ if (!existsSync(path)) {
23
+ return path;
24
+ }
25
+ }
26
+ };
27
+
28
+ /** Save an export in `folder` (Downloads by default), never over a file; returns its path. */
29
+ export async function saveExport(
30
+ exported: ExportResult,
31
+ folder: string = downloadsFolder()
32
+ ): Promise<string> {
33
+ const into = resolve(folder);
34
+ await mkdir(into, { recursive: true });
35
+ const path = freeName(into, exported.name);
36
+ await writeFile(path, exported.bytes, { flag: "wx" });
37
+ return path;
38
+ }
@@ -0,0 +1,113 @@
1
+ // Dex hosted for a workspace, in people's browsers (STUDIO_HOSTED; see
2
+ // content/hosted-person.ts). Every request runs as the person the preview
3
+ // host says it is from, and nobody reaches what belongs to the machine Dex
4
+ // runs on: its git, its updates, restarting it, its own agents and apps.
5
+ // Viewers look, comment and move about; only editors change the files.
6
+
7
+ import type { IncomingMessage, ServerResponse } from "node:http";
8
+ import type { Plugin } from "vite";
9
+ import {
10
+ asPerson,
11
+ CAPTURE_HEADER,
12
+ CAPTURE_PERSON,
13
+ type HostedPerson,
14
+ isCapture,
15
+ isHosted,
16
+ personFromHeader,
17
+ } from "../content/hosted-person.ts";
18
+ import { PERSON_HEADER } from "../shared/live-presence.ts";
19
+
20
+ const PREFIX = "/__studio/";
21
+ const READS = new Set(["GET", "HEAD", "OPTIONS"]);
22
+
23
+ /** What only the person at the machine may do: nobody, hosted. */
24
+ const MACHINE_ROUTES = new Set([
25
+ "agent-launch",
26
+ "agent-setup",
27
+ "agent-stop",
28
+ "desktop-app",
29
+ "extension",
30
+ "git",
31
+ "git-branches",
32
+ "git-checks",
33
+ "git-pull-base",
34
+ "git-saved",
35
+ "git-settings",
36
+ "git-sync",
37
+ "machine-update",
38
+ "other-dexes",
39
+ "restart",
40
+ "update",
41
+ "watch",
42
+ ]);
43
+
44
+ /** What a viewer may still send: their comments, focus and preferences. */
45
+ const VIEWER_WRITES = new Set(["threads", "focus", "preferences", "welcome"]);
46
+
47
+ /** Vite's own launcher, which opens a file in the machine's editor. */
48
+ const OPEN_IN_EDITOR = "/__open-in-editor";
49
+
50
+ /**
51
+ * A request's path as the server answers it: dot segments resolved, as
52
+ * requests.ts reads it, so `/__studio/x/../git` is `git` here too.
53
+ */
54
+ const pathOf = (url: string | undefined): string =>
55
+ new URL(url ?? "/", "http://dex.local").pathname;
56
+
57
+ /** The route a path is for, under /__studio/, if any. */
58
+ const routeOf = (path: string): string | undefined =>
59
+ path.startsWith(PREFIX) ? path.slice(PREFIX.length).split("/")[0] : undefined;
60
+
61
+ /** Why `person` may not make this request, or undefined when they may. */
62
+ export function hostedRefusal(
63
+ person: HostedPerson,
64
+ method: string | undefined,
65
+ url: string | undefined
66
+ ): string | undefined {
67
+ const path = pathOf(url);
68
+ const route = routeOf(path);
69
+ if (path.startsWith(OPEN_IN_EDITOR) || (route && MACHINE_ROUTES.has(route))) {
70
+ return "Dex in the browser runs for the whole workspace: this is for Dex on your own machine.";
71
+ }
72
+ if (
73
+ route &&
74
+ person.role === "viewer" &&
75
+ !READS.has(method ?? "GET") &&
76
+ !VIEWER_WRITES.has(route)
77
+ ) {
78
+ return "Viewers cannot change the files. Ask an owner to make you an editor.";
79
+ }
80
+ }
81
+
82
+ const refuse = (response: ServerResponse, status: number, message: string) => {
83
+ // In the shape Dex's pages read a refusal in (studio-request.ts).
84
+ response.writeHead(status, { "Content-Type": "application/json" });
85
+ response.end(JSON.stringify({ problems: [message] }));
86
+ };
87
+
88
+ /** Each request as its person; what nobody hosted may do, refused. */
89
+ export const hostedPeople = (): Plugin => ({
90
+ name: "dex-hosted-people",
91
+ configureServer(server) {
92
+ if (!isHosted()) {
93
+ return;
94
+ }
95
+ server.middlewares.use(
96
+ (request: IncomingMessage, response: ServerResponse, next) => {
97
+ const person = isCapture(request.headers[CAPTURE_HEADER])
98
+ ? CAPTURE_PERSON
99
+ : personFromHeader(request.headers[PERSON_HEADER]);
100
+ if (!person) {
101
+ refuse(response, 401, "Open Dex from your workspace to sign in.");
102
+ return;
103
+ }
104
+ const refusal = hostedRefusal(person, request.method, request.url);
105
+ if (refusal) {
106
+ refuse(response, 403, refusal);
107
+ return;
108
+ }
109
+ asPerson(person, next);
110
+ }
111
+ );
112
+ },
113
+ });
@@ -13,6 +13,12 @@
13
13
  // The first time a studio meets a workspace that already has a file it has
14
14
  // too, but different, the workspace's version wins and yours is backed up.
15
15
  //
16
+ // An agent saves the file it read a moment ago: when a teammate's change
17
+ // reached disk in between, the save is merged from the version it was made
18
+ // from (one of the last few both sides agreed on), so the teammate's change
19
+ // stays. And a save that lands while the mirror writes the workspace's
20
+ // version is never written over: the mirror checks the file just before.
21
+ //
16
22
  // Only live paths (live-core.ts) are ever read or written, and every path is
17
23
  // checked to stay inside the studio's folder.
18
24
 
@@ -34,6 +40,7 @@ import type { AbstractType, Doc, Transaction, YEvent } from "yjs";
34
40
  import { mergeContributors } from "../shared/contributors-merge.ts";
35
41
  import {
36
42
  changedPaths,
43
+ editDistance,
37
44
  filesOf,
38
45
  isLivePath,
39
46
  LIVE_FILES,
@@ -89,6 +96,12 @@ const DEBOUNCE_MS = 60;
89
96
  const SAVE_STATE_MS = 400;
90
97
  /** Files reconciled at once when starting. */
91
98
  const START_CONCURRENCY = 16;
99
+ /**
100
+ * How long, and how many, earlier agreed versions of a file are kept, so an
101
+ * agent's save from one of them merges instead of undoing what came since.
102
+ */
103
+ const RECENT_MS = 30_000;
104
+ const RECENT_COUNT = 4;
92
105
 
93
106
  const liveCacheDir = (): string =>
94
107
  join(process.env.XDG_CACHE_HOME ?? join(homedir(), ".cache"), "dex", "live");
@@ -164,11 +177,24 @@ async function readLocal(file: string): Promise<Text | undefined> {
164
177
  }
165
178
  }
166
179
 
167
- async function writeLocal(file: string, text: string): Promise<void> {
180
+ /**
181
+ * Write a file, unless it no longer holds `expected` (something saved it
182
+ * meanwhile): then nothing is written and it returns false.
183
+ */
184
+ async function writeLocal(
185
+ file: string,
186
+ text: string,
187
+ expected: Text
188
+ ): Promise<boolean> {
168
189
  await mkdir(dirname(file), { recursive: true });
169
190
  const temporary = join(dirname(file), `.${hash(file)}.studio-live`);
170
191
  await writeFileOnDisk(temporary, text);
192
+ if ((await readLocal(file)) !== expected) {
193
+ await rm(temporary, { force: true });
194
+ return false;
195
+ }
171
196
  await rename(temporary, file);
197
+ return true;
172
198
  }
173
199
 
174
200
  /** Remove a file, and the folders it leaves empty, up to the live folder. */
@@ -209,6 +235,8 @@ export function createMirror({
209
235
  }: MirrorOptions) {
210
236
  const files = filesOf(doc);
211
237
  let base: Record<string, string> = {};
238
+ /** Earlier agreed versions of each file, newest last, this run only. */
239
+ const recent = new Map<string, { at: number; text: string }[]>();
212
240
  const timers = new Map<string, NodeJS.Timeout>();
213
241
  const queues = new Map<string, Promise<void>>();
214
242
  const watchers: FSWatcher[] = [];
@@ -268,6 +296,39 @@ export function createMirror({
268
296
  return remote;
269
297
  };
270
298
 
299
+ /**
300
+ * The earlier agreed version a save on disk was made from, when it was not
301
+ * the latest: the one closest to the save, if closer than the latest is.
302
+ * A save identical to an earlier version is taken as meant (an agent
303
+ * putting a line back), never as stale.
304
+ */
305
+ const savedFrom = (
306
+ path: string,
307
+ disk: Text,
308
+ known: Text
309
+ ): Text | undefined => {
310
+ if (disk === null || known === null) {
311
+ return;
312
+ }
313
+ const now = Date.now();
314
+ const earlier = (recent.get(path) ?? []).filter(
315
+ (entry) => now - entry.at < RECENT_MS && entry.text !== known
316
+ );
317
+ if (earlier.length === 0 || earlier.some((entry) => entry.text === disk)) {
318
+ return;
319
+ }
320
+ let best: string | undefined;
321
+ let bestDistance = editDistance(known, disk);
322
+ for (const { text } of earlier) {
323
+ const distance = editDistance(text, disk);
324
+ if (distance < bestDistance) {
325
+ best = text;
326
+ bestDistance = distance;
327
+ }
328
+ }
329
+ return best;
330
+ };
331
+
271
332
  /** Both sides changed since they last agreed. */
272
333
  const resolveBothChanged = async (
273
334
  path: string,
@@ -316,6 +377,10 @@ export function createMirror({
316
377
  if (readOnly) {
317
378
  return keepRemote(path, disk, remote, known);
318
379
  }
380
+ const from = savedFrom(path, disk, known);
381
+ if (from !== undefined && disk !== remote) {
382
+ return resolveBothChanged(path, disk, remote, from);
383
+ }
319
384
  if (remote !== known && disk !== remote) {
320
385
  return resolveBothChanged(path, disk, remote, known);
321
386
  }
@@ -326,18 +391,26 @@ export function createMirror({
326
391
  return disk;
327
392
  };
328
393
 
394
+ /** Write `next` to disk; false when the file changed since it held `disk`. */
329
395
  const writeDisk = async (
330
396
  path: string,
331
397
  file: string,
332
- next: Text
333
- ): Promise<void> => {
398
+ next: Text,
399
+ disk: Text
400
+ ): Promise<boolean> => {
334
401
  if (next === null) {
402
+ if ((await readLocal(file)) !== disk) {
403
+ return false;
404
+ }
335
405
  await removeLocal(root, file);
336
406
  onEvent({ type: "deleted", path, local: true });
337
- } else {
338
- await writeLocal(file, next);
339
- onEvent({ type: "received", path });
407
+ return true;
340
408
  }
409
+ if (!(await writeLocal(file, next, disk))) {
410
+ return false;
411
+ }
412
+ onEvent({ type: "received", path });
413
+ return true;
341
414
  };
342
415
 
343
416
  /** Remember the text both sides now agree on, saving only on a change. */
@@ -345,6 +418,15 @@ export function createMirror({
345
418
  if (text === base[path]) {
346
419
  return;
347
420
  }
421
+ const earlier = base[path];
422
+ if (earlier !== undefined) {
423
+ const now = Date.now();
424
+ const kept = (recent.get(path) ?? []).filter(
425
+ (entry) => now - entry.at < RECENT_MS
426
+ );
427
+ kept.push({ at: now, text: earlier });
428
+ recent.set(path, kept.slice(-RECENT_COUNT));
429
+ }
348
430
  if (text === undefined) {
349
431
  delete base[path];
350
432
  } else {
@@ -369,8 +451,11 @@ export function createMirror({
369
451
  if (disk !== known) {
370
452
  next = await resolveLocalChange(path, disk, next, known);
371
453
  }
372
- if (next !== disk) {
373
- await writeDisk(path, file, next);
454
+ if (next !== disk && !(await writeDisk(path, file, next, disk))) {
455
+ // Saved again meanwhile: what was sent stands, and the new save is
456
+ // read next, against what both sides last agreed on.
457
+ schedule(path);
458
+ return;
374
459
  }
375
460
  // A view-only studio's own files (the room has never had them) are not
376
461
  // in step with anything, so a later event cannot read as a deletion.
@@ -16,12 +16,19 @@ import {
16
16
  type HocuspocusProviderConfiguration,
17
17
  } from "@hocuspocus/provider";
18
18
  import { Doc } from "yjs";
19
+ import { isHosted } from "../content/hosted-person.ts";
19
20
  import {
21
+ canvasTeammates,
20
22
  type LivePresence,
21
23
  type PresenceUser,
22
24
  roomAgents,
23
25
  teammateEntries,
24
26
  } from "../shared/live-presence.ts";
27
+ import {
28
+ onCanvasPlaces,
29
+ roomCanvas,
30
+ setCanvasTeammates,
31
+ } from "./canvas-presence.ts";
25
32
  import {
26
33
  type CloudClient,
27
34
  cloudClient,
@@ -51,6 +58,8 @@ interface LiveConnection {
51
58
  }
52
59
 
53
60
  const PRESENCE_EVERY_MS = 15_000;
61
+ /** How often a moving pointer goes to the room, at most. */
62
+ const CANVAS_EVERY_MS = 40;
54
63
 
55
64
  const print = (text = "") => process.stdout.write(`${text}\n`);
56
65
 
@@ -192,6 +201,38 @@ export async function live(
192
201
  provider.setAwarenessField("user", self);
193
202
  provider.setAwarenessField("kind", "studio");
194
203
 
204
+ // The canvas: where you point and what you select goes to the room, at
205
+ // most every CANVAS_EVERY_MS, the last place always; teammates' come back.
206
+ const hosted = isHosted();
207
+ let canvasTimer: NodeJS.Timeout | undefined;
208
+ let canvasSent = 0;
209
+ const sendCanvas = () => {
210
+ canvasTimer = undefined;
211
+ canvasSent = Date.now();
212
+ const { canvas, people } = roomCanvas();
213
+ if (hosted) {
214
+ provider.setAwarenessField("people", people);
215
+ }
216
+ provider.setAwarenessField("canvas", canvas);
217
+ };
218
+ const stopCanvas = onCanvasPlaces(() => {
219
+ if (canvasTimer) {
220
+ return;
221
+ }
222
+ const wait = canvasSent + CANVAS_EVERY_MS - Date.now();
223
+ if (wait <= 0) {
224
+ sendCanvas();
225
+ } else {
226
+ canvasTimer = setTimeout(sendCanvas, wait);
227
+ }
228
+ });
229
+ sendCanvas();
230
+ const showCanvasTeammates = () =>
231
+ setCanvasTeammates(
232
+ canvasTeammates(states(), self.id, provider.awareness?.clientID)
233
+ );
234
+ provider.awareness?.on("change", showCanvasTeammates);
235
+
195
236
  await new Promise((resolve, reject) => {
196
237
  provider.on("synced", resolve);
197
238
  provider.on("authenticationFailed", ({ reason }: { reason: string }) =>
@@ -256,12 +297,16 @@ export async function live(
256
297
  shareAgents().catch(() => undefined);
257
298
  }
258
299
  });
259
- // Someone deleted .studio: the timer above still shares agents.
300
+ // Someone deleted .local: the timer above still shares agents.
260
301
  presenceWatcher.on("error", () => undefined);
261
302
 
262
303
  await new Promise<void>((resolve) => {
263
304
  const stop = async () => {
264
305
  clearInterval(presenceTimer);
306
+ clearTimeout(canvasTimer);
307
+ stopCanvas();
308
+ provider.awareness?.off("change", showCanvasTeammates);
309
+ setCanvasTeammates([]);
265
310
  presenceWatcher.close();
266
311
  await started.stop();
267
312
  await presence.replaceTeammates([]).catch(() => undefined);
@@ -11,8 +11,8 @@
11
11
  // Every trigger runs the same update, inside the repository's turn
12
12
  // (queueSync): Sync, Pull from base, `dex dev` starting, and Update, which
13
13
  // moves the project to npm's newer Dex through it. Where it stands is kept
14
- // in the machine journal, `.studio/machine.json`, with a timestamped line
15
- // per step in `.studio/machine.log`; pressing again carries on from there.
14
+ // in the machine journal, `.local/machine.json`, with a timestamped line
15
+ // per step in `.local/machine.log`; pressing again carries on from there.
16
16
 
17
17
  import { existsSync } from "node:fs";
18
18
  import { appendFile, readFile, writeFile } from "node:fs/promises";
@@ -52,7 +52,7 @@ export interface MachinePlace {
52
52
  root: string;
53
53
  }
54
54
 
55
- /** What `.studio/machine.json` holds. */
55
+ /** What `.local/machine.json` holds. */
56
56
  interface Journal extends Partial<MachineVersions> {
57
57
  /** The lockfiles node_modules was last installed from (lockfilePrint). */
58
58
  lockfiles?: string;
package/src/server/mcp.ts CHANGED
@@ -45,6 +45,7 @@ import { registerCommentTools } from "./comments/tools.ts";
45
45
  import { HANDOVER, type Handover, registerHandover } from "./mcp-handover.ts";
46
46
  import { type StudioFor, studioFor } from "./studio-for.ts";
47
47
  import { openToolContext } from "./tools/context.ts";
48
+ import { registerExportTool } from "./tools/export.ts";
48
49
  import { registerFeedbackTool } from "./tools/feedback.ts";
49
50
  import { registerPlaceFrameTool } from "./tools/place-frame.ts";
50
51
  import { registerReadingTools } from "./tools/reading.ts";
@@ -215,6 +216,7 @@ export function createStudio(
215
216
  registerPlaceFrameTool(server, context);
216
217
  registerShowTool(server, context, findStudio);
217
218
  registerSnapshotTool(server, context, findStudio);
219
+ registerExportTool(server, context);
218
220
  registerFeedbackTool(server, context, feedbackRelay);
219
221
 
220
222
  return { handover, receipt, server, session };