@engenty/wizards-runtime 0.9.8 → 0.10.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 (73) hide show
  1. package/apps/runtime/dist/app.js +18 -1
  2. package/apps/runtime/dist/auth/index.js +10 -1
  3. package/apps/runtime/dist/db/client.js +9 -1
  4. package/apps/runtime/dist/db/migrations/tenant/0022_sync.sql +247 -0
  5. package/apps/runtime/dist/db/migrations/tenant/meta/0022_snapshot.json +3792 -0
  6. package/apps/runtime/dist/db/migrations/tenant/meta/_journal.json +7 -0
  7. package/apps/runtime/dist/db/schema.js +60 -0
  8. package/apps/runtime/dist/docs/user-guide/cloud-sync.md +85 -0
  9. package/apps/runtime/dist/docs/user-guide/data.md +4 -4
  10. package/apps/runtime/dist/docs/user-guide/meta.json +1 -0
  11. package/apps/runtime/dist/docs/user-guide/test-and-share.md +4 -14
  12. package/apps/runtime/dist/files/blobs.js +13 -0
  13. package/apps/runtime/dist/index.js +7 -1
  14. package/apps/runtime/dist/plugins/jobs.js +7 -0
  15. package/apps/runtime/dist/routes/api.js +107 -0
  16. package/apps/runtime/dist/routes/studio.js +62 -0
  17. package/apps/runtime/dist/services/cloud.js +39 -5
  18. package/apps/runtime/dist/services/projects.js +11 -0
  19. package/apps/runtime/dist/sync/apply.js +39 -0
  20. package/apps/runtime/dist/sync/client.js +828 -0
  21. package/apps/runtime/dist/sync/hub.js +324 -0
  22. package/apps/runtime/dist/sync/log.js +74 -0
  23. package/apps/runtime/dist/sync/records.js +943 -0
  24. package/apps/runtime/dist/sync/state.js +17 -0
  25. package/apps/web/dist/assets/{AboutDialog-B_Ixp_Tb.js → AboutDialog-D1YHT0jc.js} +1 -1
  26. package/apps/web/dist/assets/{ChangelogDialog-BpEIbAZ8.js → ChangelogDialog-Bv02g8av.js} +1 -1
  27. package/apps/web/dist/assets/{EditorPage-CKHY4hn4.js → EditorPage-BThoZwqO.js} +4 -4
  28. package/apps/web/dist/assets/{FlowPreview-APXdRflR.js → FlowPreview-dc5C92kK.js} +1 -1
  29. package/apps/web/dist/assets/{Harness-BsGXMlLg.js → Harness-D0nFOIVx.js} +1 -1
  30. package/apps/web/dist/assets/{Marketplace-Dr-Qnb-F.js → Marketplace-Cnd8BF3q.js} +2 -2
  31. package/apps/web/dist/assets/{NewWizardChannels-0JrRdUFd.js → NewWizardChannels-i62Y_2DZ.js} +1 -1
  32. package/apps/web/dist/assets/{NewWizardPage-9igFL5O8.js → NewWizardPage-BcpRA1fx.js} +1 -1
  33. package/apps/web/dist/assets/{OnboardingPage-BcK9FUnU.js → OnboardingPage-BcMDEXNq.js} +1 -1
  34. package/apps/web/dist/assets/PreviewPane-GHcVV2Hu.js +4 -0
  35. package/apps/web/dist/assets/ProjectPage-TDywzUOd.js +1 -0
  36. package/apps/web/dist/assets/{PublicRunner-CZR1ziQ4.js → PublicRunner-B6JINLpR.js} +1 -1
  37. package/apps/web/dist/assets/{ReadOnly-BraZbEG_.js → ReadOnly-Mv5M2OV9.js} +1 -1
  38. package/apps/web/dist/assets/SettingsPage-B-F1dLgt.js +2 -0
  39. package/apps/web/dist/assets/{SetupPage-CvkE2aKx.js → SetupPage-CVdsdVBW.js} +1 -1
  40. package/apps/web/dist/assets/{SharePage-Dk7zC5Zo.js → SharePage-CBSRK0wF.js} +1 -1
  41. package/apps/web/dist/assets/changelog-BR1lxaWv.js +1 -0
  42. package/apps/web/dist/assets/{coins-391m1e4_.js → coins-BGZKYmu6.js} +1 -1
  43. package/apps/web/dist/assets/index-D3-kv1WF.js +14 -0
  44. package/apps/web/dist/assets/{phone-DvgrtyNO.js → phone-BzHhwehj.js} +1 -1
  45. package/apps/web/dist/assets/{runners-4OBelIgF.js → runners-C1-zIlry.js} +1 -1
  46. package/apps/web/dist/assets/{session-DvnGHbDz.js → session-B_JeZnJ0.js} +1 -1
  47. package/apps/web/dist/assets/{settings-menu-xK9A-gaP.js → settings-menu-BZRGhsIO.js} +1 -1
  48. package/apps/web/dist/assets/{theme-D3yDT4QT.js → theme-HcCfZDzS.js} +2 -2
  49. package/apps/web/dist/assets/{ui-BVQk2DtW.js → ui-BI1RPFWT.js} +1 -1
  50. package/apps/web/dist/assets/{upload-BgXbzG6C.js → upload-CwT8oMz0.js} +1 -1
  51. package/apps/web/dist/assets/{useMutation-DkwSQWoD.js → useMutation-byk81dDj.js} +1 -1
  52. package/apps/web/dist/assets/{volume-2-DHGoe3Cg.js → volume-2-B1Pz6Iwt.js} +1 -1
  53. package/apps/web/dist/assets/{wrench-Cf_aE3O0.js → wrench-CvzXRbWN.js} +1 -1
  54. package/apps/web/dist/index.html +7 -7
  55. package/apps/web/dist/mcp/flow.html +1 -1
  56. package/node_modules/@engenty/wizards-shared/dist/feature-flags.d.ts +6 -0
  57. package/node_modules/@engenty/wizards-shared/dist/feature-flags.js +6 -0
  58. package/node_modules/@engenty/wizards-shared/dist/run.d.ts +6 -0
  59. package/node_modules/@engenty/wizards-shared/dist/run.js +12 -0
  60. package/node_modules/@engenty/wizards-shared/dist/sync-merge.d.ts +55 -0
  61. package/node_modules/@engenty/wizards-shared/dist/sync-merge.js +214 -0
  62. package/node_modules/@engenty/wizards-shared/dist/sync.d.ts +166 -0
  63. package/node_modules/@engenty/wizards-shared/dist/sync.js +40 -0
  64. package/node_modules/@engenty/wizards-shared/dist/text-merge.d.ts +14 -0
  65. package/node_modules/@engenty/wizards-shared/dist/text-merge.js +137 -0
  66. package/package.json +1 -1
  67. package/plugin/.claude-plugin/plugin.json +1 -1
  68. package/plugin/plugin.json +1 -1
  69. package/apps/web/dist/assets/PreviewPane-X4LBqA0D.js +0 -4
  70. package/apps/web/dist/assets/ProjectPage-CG0i-KhR.js +0 -1
  71. package/apps/web/dist/assets/SettingsPage-Bw4tdoV7.js +0 -2
  72. package/apps/web/dist/assets/changelog-DDXnAaHm.js +0 -1
  73. package/apps/web/dist/assets/index-BTUtot4r.js +0 -14
@@ -155,6 +155,13 @@
155
155
  "when": 1792568616734,
156
156
  "tag": "0021_model_classes",
157
157
  "breakpoints": true
158
+ },
159
+ {
160
+ "idx": 22,
161
+ "version": "6",
162
+ "when": 1792580809821,
163
+ "tag": "0022_sync",
164
+ "breakpoints": true
158
165
  }
159
166
  ]
160
167
  }
@@ -625,3 +625,63 @@ export const pluginConnection = sqliteTable("plugin_connection", {
625
625
  createdAt: createdAt(),
626
626
  updatedAt: updatedAt(),
627
627
  }, (t) => [index("plugin_connection_space").on(t.plugin, t.projectId)]);
628
+ // --- The two-way sync -----------------------------------------------------------
629
+ // A space that syncs with the organization in the cloud (docs/plans/tenant-sync.md). Triggers
630
+ // on the synced tables note every write in `sync_change` (see the migration); the cloud numbers
631
+ // its changes there, an install finds there what it has not pushed yet.
632
+ /** One change of an item: which space, which kind of item, which one. */
633
+ export const syncChange = sqliteTable("sync_change", {
634
+ seq: integer("seq").primaryKey({ autoIncrement: true }),
635
+ projectId: text("project_id").notNull(),
636
+ kind: text("kind").notNull(),
637
+ item: text("item").notNull(),
638
+ at: integer("at", { mode: "timestamp_ms" }).notNull().default(now),
639
+ }, (t) => [
640
+ index("sync_change_item").on(t.kind, t.item),
641
+ index("sync_change_project").on(t.projectId, t.seq),
642
+ ]);
643
+ /** One row: `applying` is 1 while an install writes what it pulled, so the triggers note none of it. */
644
+ export const syncGuard = sqliteTable("sync_guard", {
645
+ id: integer("id").primaryKey(),
646
+ applying: integer("applying").notNull().default(0),
647
+ });
648
+ /**
649
+ * The version of an item both sides last agreed on, with the cloud's number of it: the common
650
+ * ancestor a three-way merge starts from. Kept by an install.
651
+ */
652
+ export const syncBase = sqliteTable("sync_base", {
653
+ kind: text("kind").notNull(),
654
+ item: text("item").notNull(),
655
+ projectId: text("project_id").notNull(),
656
+ seq: integer("seq").notNull(),
657
+ record: text("record", { mode: "json" }).$type(),
658
+ }, (t) => [primaryKey({ columns: [t.kind, t.item] }), index("sync_base_project").on(t.projectId)]);
659
+ /** An item both sides changed, where the merge was not clean: it waits for the person. */
660
+ export const syncConflict = sqliteTable("sync_conflict", {
661
+ id: text("id").primaryKey(),
662
+ projectId: text("project_id").notNull(),
663
+ kind: text("kind").notNull(),
664
+ item: text("item").notNull(),
665
+ /** The cloud's number of its version. */
666
+ seq: integer("seq").notNull(),
667
+ base: text("base", { mode: "json" }).$type(),
668
+ local: text("local", { mode: "json" }).$type(),
669
+ remote: text("remote", { mode: "json" }).$type(),
670
+ createdAt: createdAt(),
671
+ }, (t) => [uniqueIndex("sync_conflict_item").on(t.kind, t.item)]);
672
+ /** A merge the sync made by itself: the notice on the item, and what undoes it. */
673
+ export const syncMerge = sqliteTable("sync_merge", {
674
+ id: text("id").primaryKey(),
675
+ projectId: text("project_id").notNull(),
676
+ kind: text("kind").notNull(),
677
+ item: text("item").notNull(),
678
+ /** Labels of the places each side changed. */
679
+ local: text("local", { mode: "json" }).$type().notNull(),
680
+ remote: text("remote", { mode: "json" }).$type().notNull(),
681
+ /** Both sides before the merge. */
682
+ before: text("before", { mode: "json" })
683
+ .$type()
684
+ .notNull(),
685
+ seen: integer("seen", { mode: "boolean" }).notNull().default(false),
686
+ createdAt: createdAt(),
687
+ }, (t) => [index("sync_merge_item").on(t.kind, t.item, t.createdAt)]);
@@ -0,0 +1,85 @@
1
+ ---
2
+ title: Spaces in the cloud
3
+ description: How engenty wizards on your computer keeps its spaces the same as your organization’s spaces at engenty.ai, both ways, and what happens when both sides change the same thing.
4
+ version: 0.9.8
5
+ ---
6
+
7
+ With an account signed in, engenty wizards on your computer keeps its spaces the same as your
8
+ organization’s spaces at engenty.ai. What you change on your computer arrives in the cloud, and
9
+ what someone changes in the cloud’s studio arrives on your computer. You can work offline: your
10
+ changes wait and go up once the cloud can be reached.
11
+
12
+ A computer is signed in to one organization. Everything on it syncs with that organization. To
13
+ work in another one, sign in again and pick it (Settings → Account, or
14
+ `wizards account sign-in` in the terminal).
15
+
16
+ ## What syncs
17
+
18
+ | Syncs both ways | Stays where it was made |
19
+ |---|---|
20
+ | The space: name, what it says about itself, brand, facts, themes, its public page | Runs and results |
21
+ | Wizards: the draft, its files, translations and the chat you built it with | Chats with the studio’s assistant |
22
+ | Knowledge: pages, tables and their rows, categories | What wizards keep for people: their lists, files and sign-ins |
23
+ | The space’s files | Connected accounts and keys |
24
+ | Connectors | The model settings, and the headers of connected systems |
25
+
26
+ Publishing on your computer publishes the wizard here, then in the cloud, as its next version
27
+ there. Its address at engenty.ai stays the same. If the cloud can’t be reached, the studio
28
+ publishes there again by itself later.
29
+
30
+ ## When it syncs
31
+
32
+ engenty wizards syncs when you save, when you open a wizard, page, table or space, and once a
33
+ minute in between. Nothing changes about how you save.
34
+
35
+ Settings → Spaces in the cloud lists every space with a switch, “Keep the same as in the cloud”.
36
+ It shows each space’s state:
37
+
38
+ | It shows | Means |
39
+ |---|---|
40
+ | Up to date | Both sides are the same. “Last arrived” says when the last change came down |
41
+ | 3 changes wait | They go up at the next sync. “Check now” syncs right away |
42
+ | Only on this computer | The switch is off, and the space stays here |
43
+ | Only in the cloud | The switch is off for a space of the cloud. Switch it on to have it here |
44
+ | The cloud runs a newer version | The sync waits until you update engenty wizards (`wizards update`) |
45
+ | This computer runs a newer version than the cloud | Your changes go up once the cloud is updated |
46
+ | The cloud can’t be reached right now | Your changes wait here |
47
+
48
+ New spaces, made here or in the cloud, sync without you switching them on.
49
+
50
+ ## When both sides changed the same thing
51
+
52
+ Usually the two changes fit together. Say you changed a page’s first paragraph and someone in the
53
+ cloud changed its last one. The studio then merges them by itself, and the page shows “Merged with
54
+ changes from the cloud”, with what changed where. “Undo, keep mine” or “Undo, keep the cloud’s”
55
+ takes one side back.
56
+
57
+ When both sides changed the same place, for example a wizard’s title, the studio asks which
58
+ version stays. You see it on the wizard, page or table, in the bar above every page, and under
59
+ Settings → Spaces in the cloud:
60
+
61
+ | Choice | Does |
62
+ |---|---|
63
+ | Keep the cloud’s version | Your change here is replaced |
64
+ | Keep this computer’s version | Your change goes up and replaces the cloud’s |
65
+ | Choose place by place | Shows each place that differs, and you pick a side for each |
66
+ | Ask AI for a proposal | The AI writes a version with both changes. Nothing changes until you take it |
67
+
68
+ Until you decide, each side keeps its own version, and the published version keeps running.
69
+
70
+ ## Who can change what
71
+
72
+ Your role in the organization counts on your computer too. Owners and admins change everything.
73
+ Members change wizards, knowledge and files, but they don’t add or delete wizards, and they don’t
74
+ change the space’s settings or its connectors. The cloud refuses what your role doesn’t allow, and
75
+ Settings → Spaces in the cloud says which changes it didn’t take.
76
+
77
+ ## Switch it off
78
+
79
+ To keep a space on your computer alone, turn its switch off under Settings → Spaces in the cloud.
80
+ To keep everything here, sign out under Settings → Account. To turn the sync off on this computer
81
+ but keep the account, add this line to `~/.engenty/wizards/.features`:
82
+
83
+ ```bash
84
+ twoWaySync=off
85
+ ```
@@ -39,10 +39,10 @@ After an update, engenty wizards brings your data up to date the next time it st
39
39
  on your computer.
40
40
  - **Steps that use the web** send what they search for, open or call.
41
41
  - **Connected services** get what a wizard’s actions send them.
42
- - **Published wizards**, with an account signed in: when you publish, engenty.ai receives the
43
- published version and its files, the space’s name, title, “About”, colours, facts and main logo,
44
- and the pages and tables of Knowledge ([Test and share](./test-and-share.md#in-the-cloud)).
45
- Documents, drafts, runs and connected accounts stay on your computer.
42
+ - **Your spaces**, with an account signed in: their wizards, drafts included, their knowledge,
43
+ files and connectors sync with your organization at engenty.ai
44
+ ([Spaces in the cloud](./cloud-sync.md)). Runs, results, connected accounts and keys stay on
45
+ your computer.
46
46
  - **Templates** come from the marketplace at engenty.ai. `MARKETPLACE_URL=off` in the settings file
47
47
  turns that off.
48
48
  - **The update check** asks GitHub for the newest release.
@@ -15,6 +15,7 @@
15
15
  "test-and-share",
16
16
  "run",
17
17
  "space",
18
+ "cloud-sync",
18
19
  "---Settings---",
19
20
  "connectors",
20
21
  "models",
@@ -111,20 +111,10 @@ Without an account, the dialog says that the wizard runs only on this computer (
111
111
  computer” under “Access”). It greys out the ways others reach it and offers “Sign in” and “Create
112
112
  account”.
113
113
 
114
- What goes to the cloud and what stays:
115
-
116
- | Goes to the cloud | Stays on your computer |
117
- |---|---|
118
- | The published version and its files | Drafts and the chat with the assistant |
119
- | The space’s name, what it says about itself, its colours, facts and logo | Runs and results on your computer |
120
- | The pages and tables of Knowledge, with their categories | What the wizards keep: their lists and notes |
121
- | How the link is shared: on or off, runs a day, page or chat | Connected accounts, keys, the space’s documents and its connected systems |
122
-
123
- At engenty.ai/studio you see the space and its runs there. A small laptop icon marks the space,
124
- and a note says “You edit this space in engenty wizards on your computer.” The studio there
125
- doesn’t edit it. An account holds one space from one computer. On a new computer, the share
126
- dialog offers “Replace that space”, which removes the old computer’s wizards and their links from
127
- the cloud.
114
+ Your spaces, their wizards with their drafts, and their knowledge and files sync both ways with
115
+ your organization at engenty.ai: what you change here arrives there, and what someone changes in
116
+ the studio there arrives here. Runs and results, connected accounts and keys stay on the side
117
+ where they were made. See [Spaces in the cloud](./cloud-sync.md).
128
118
 
129
119
  When you delete a wizard here, its copy in the cloud is deleted too. When you switch its link
130
120
  off here, it is switched off there as well.
@@ -20,3 +20,16 @@ export async function getBlob(hash) {
20
20
  }
21
21
  return data;
22
22
  }
23
+ /** Whether the store has the bytes of this hash. */
24
+ export async function hasBlob(hash) {
25
+ return /^[a-f0-9]{64}$/.test(hash) && objects.has(blobKey(hash));
26
+ }
27
+ /** Keeps bytes that arrived for a hash, after checking they are what the hash says. */
28
+ export async function putBlobOf(hash, data) {
29
+ if (createHash("sha256").update(data).digest("hex") !== hash) {
30
+ throw new Error("blob does not match its hash");
31
+ }
32
+ if (!(await objects.has(blobKey(hash)))) {
33
+ await objects.put(blobKey(hash), data);
34
+ }
35
+ }
@@ -18,6 +18,7 @@ import { clearRunning, writeRunning } from "./running.js";
18
18
  import { syncMarketplace } from "./services/marketplace.js";
19
19
  import { purgeExpiredRuns } from "./services/shares.js";
20
20
  import { purgeUnusedStores } from "./store/index.js";
21
+ import { compactLog } from "./sync/log.js";
21
22
  import { forgetRunner, registerRunner } from "./tenants/control.js";
22
23
  import { LOCAL_TENANT } from "./tenants/tenant.js";
23
24
  import { onRestart, RESTART_EXIT, startUpdateChecks } from "./update.js";
@@ -93,7 +94,7 @@ if (env.serves.runner) {
93
94
  async function purge() {
94
95
  await purgeSessions();
95
96
  for (const id of await knownTenants()) {
96
- await withTenant(id, () => Promise.all([purgeExpiredRuns(), purgeUnusedStores()])).catch((err) => console.error(`[retention ${id}]`, err));
97
+ await withTenant(id, () => Promise.all([purgeExpiredRuns(), purgeUnusedStores(), compactLog()])).catch((err) => console.error(`[retention ${id}]`, err));
97
98
  }
98
99
  }
99
100
  void purge().catch((err) => console.error("[retention]", err));
@@ -103,6 +104,11 @@ if (!managed) {
103
104
  const { retryFailedSends } = await import("./services/cloud.js");
104
105
  const retry = () => withTenant(LOCAL_TENANT, () => retryFailedSends("local")).catch((err) => console.error("[cloud] retry failed:", err));
105
106
  setInterval(() => void retry(), 60_000).unref();
107
+ // The two-way sync of the spaces with the account's organization (sync/client.ts).
108
+ const { syncAll } = await import("./sync/client.js");
109
+ const twoWay = () => withTenant(LOCAL_TENANT, () => syncAll()).catch((err) => console.error("[sync]", err));
110
+ setTimeout(() => void twoWay(), 5_000).unref();
111
+ setInterval(() => void twoWay(), 60_000).unref();
106
112
  }
107
113
  async function shutdown(code = 0) {
108
114
  clearRunning(env.dataDir);
@@ -1,6 +1,8 @@
1
1
  import { and, eq } from "drizzle-orm";
2
2
  import { control, controlDb, withTenant } from "../db/client.js";
3
3
  import { env } from "../env.js";
4
+ import { twoWayActive } from "../sync/state.js";
5
+ import { LOCAL_TENANT } from "../tenants/tenant.js";
4
6
  import { loadedPlugins, pluginIdsOf } from "./registry.js";
5
7
  /**
6
8
  * Plugins' jobs (`server.every`). A tick looks once a minute which job is due for which tenant
@@ -21,6 +23,11 @@ export async function runDueJobs(now = new Date()) {
21
23
  });
22
24
  const started = [];
23
25
  for (const tenant of tenants) {
26
+ // An install whose spaces sync both ways leaves the jobs to the cloud: both would write the
27
+ // same items of the same spaces (docs/plans/tenant-sync.md).
28
+ if (twoWayActive() && tenant.id === LOCAL_TENANT) {
29
+ continue;
30
+ }
24
31
  const has = await pluginIdsOf(tenant.id);
25
32
  for (const { plugin, name, job } of jobs) {
26
33
  const id = plugin.source.id;
@@ -1,4 +1,5 @@
1
1
  import { note } from "@engenty/wizards-shared/run";
2
+ import { blobHash, missingBlobsSchema, pushSchema } from "@engenty/wizards-shared/sync";
2
3
  import { PACKAGE_MIME } from "@engenty/wizards-shared/wizard-package";
3
4
  import { Hono } from "hono";
4
5
  import { bodyLimit } from "hono/body-limit";
@@ -19,6 +20,7 @@ import { exportWizard } from "../services/package.js";
19
20
  import { siteJob, siteSchema, startSiteJob } from "../services/site.js";
20
21
  import { checkOnServer, checkSchema, listSyncedSpaces, patchSyncedWizard, removeSyncedSpace, removeSyncedWizard, rotateSyncedLink, syncDataSchema, syncSettingsSchema, syncSpaceData, syncWizard, syncWizardSchema, } from "../services/spaces.js";
21
22
  import { createWizard, ownedWizard, publishWizard, writeDraft } from "../services/wizards.js";
23
+ import { adoptSpace, blobBytes, missingBlobs, publishSynced, pullChanges, pushChanges, rotateSynced, syncOverview, takeBlob, } from "../sync/hub.js";
22
24
  import { codeOf, tenantStatus } from "../tenants/control.js";
23
25
  import { notFoundAnswer, say } from "./lang.js";
24
26
  import { dispatchAs } from "./plugins.js";
@@ -67,6 +69,21 @@ async function caller(c, scopes) {
67
69
  }
68
70
  return who;
69
71
  }
72
+ /**
73
+ * The two-way sync follows the studio's saves: an install pushes a space at most every few
74
+ * seconds while someone edits, and pulls when a page opens.
75
+ */
76
+ const TWO_WAY_LIMITS = { push: 1200, pull: 3600 };
77
+ function withinTwoWayLimit(c, who, what) {
78
+ return allowed(`two-way-${what}:${who.tenantId}`, TWO_WAY_LIMITS[what], HOUR)
79
+ ? null
80
+ : c.json({ error: say(c, "tooManyTransfersTry"), code: "rate_limited" }, 429);
81
+ }
82
+ /** What one push carries: records, without the files' bytes (they go one by one). */
83
+ const twoWayBody = bodyLimit({
84
+ maxSize: 16 * 1024 * 1024,
85
+ onError: (c) => c.json({ error: "The request is too large.", code: "too_large" }, 413),
86
+ });
70
87
  /** A local install sends when it publishes: more than this an hour is not an install at work. */
71
88
  function withinSyncLimit(c, who) {
72
89
  return allowed(`sync:${who.tenantId}`, 240, HOUR)
@@ -382,6 +399,96 @@ export const apiRoutes = new Hono()
382
399
  return who;
383
400
  }
384
401
  return inTenantAs(who, async () => c.json(await removeSyncedSpace(c.req.param("spaceId"))));
402
+ })
403
+ // --- the two-way sync of a space (docs/manage-contract.md, "Two-way sync of a space") ---
404
+ .get("/sync", async (c) => {
405
+ const who = await caller(c, ["wizards:read"]);
406
+ if (who instanceof Response) {
407
+ return who;
408
+ }
409
+ return inTenantAs(who, async () => c.json(await syncOverview()));
410
+ })
411
+ .get("/sync/spaces/:spaceId/changes", async (c) => {
412
+ const who = await caller(c, ["wizards:read"]);
413
+ if (who instanceof Response) {
414
+ return who;
415
+ }
416
+ const limited = withinTwoWayLimit(c, who, "pull");
417
+ if (limited) {
418
+ return limited;
419
+ }
420
+ const since = Math.max(0, Number.parseInt(c.req.query("since") ?? "0", 10) || 0);
421
+ const cursor = c.req.query("cursor") || undefined;
422
+ return inTenantAs(who, async () => c.json(await pullChanges(c.req.param("spaceId"), since, cursor)));
423
+ })
424
+ .post("/sync/spaces/:spaceId/changes", twoWayBody, async (c) => {
425
+ const who = await caller(c, ["wizards:write"]);
426
+ if (who instanceof Response) {
427
+ return who;
428
+ }
429
+ const limited = withinTwoWayLimit(c, who, "push");
430
+ if (limited) {
431
+ return limited;
432
+ }
433
+ const body = pushSchema.parse(await c.req.json());
434
+ return inTenantAs(who, async () => c.json(await pushChanges(c.req.param("spaceId"), body)));
435
+ })
436
+ .post("/sync/spaces/:spaceId/blobs/missing", async (c) => {
437
+ const who = await caller(c, ["wizards:write"]);
438
+ if (who instanceof Response) {
439
+ return who;
440
+ }
441
+ const body = missingBlobsSchema.parse(await c.req.json());
442
+ return inTenantAs(who, async () => c.json({ missing: await missingBlobs(body.hashes) }));
443
+ })
444
+ .put("/sync/spaces/:spaceId/blobs/:hash", tooLarge, async (c) => {
445
+ const who = await caller(c, ["wizards:write"]);
446
+ if (who instanceof Response) {
447
+ return who;
448
+ }
449
+ const hash = blobHash.parse(c.req.param("hash"));
450
+ const data = new Uint8Array(await c.req.arrayBuffer());
451
+ return inTenantAs(who, async () => {
452
+ await takeBlob(hash, data).catch(() => {
453
+ throw new ServiceError("invalid", "The bytes do not match their hash.");
454
+ });
455
+ return c.json({ ok: true });
456
+ });
457
+ })
458
+ .get("/sync/spaces/:spaceId/blobs/:hash", async (c) => {
459
+ const who = await caller(c, ["wizards:read"]);
460
+ if (who instanceof Response) {
461
+ return who;
462
+ }
463
+ const hash = blobHash.parse(c.req.param("hash"));
464
+ return inTenantAs(who, async () => {
465
+ const data = await blobBytes(hash).catch(() => null);
466
+ if (!data) {
467
+ return c.json({ error: "There are no such bytes here.", code: "not_found" }, 404);
468
+ }
469
+ return c.body(new Uint8Array(data), 200, { "content-type": "application/octet-stream" });
470
+ });
471
+ })
472
+ .post("/sync/spaces/:spaceId/wizards/:wizardId/publish", async (c) => {
473
+ const who = await caller(c, ["wizards:write", "wizards:publish"]);
474
+ if (who instanceof Response) {
475
+ return who;
476
+ }
477
+ return inTenantAs(who, async () => c.json(await publishSynced(who.userId, c.req.param("spaceId"), c.req.param("wizardId"))));
478
+ })
479
+ .post("/sync/spaces/:spaceId/wizards/:wizardId/rotate-link", async (c) => {
480
+ const who = await caller(c, ["wizards:publish"]);
481
+ if (who instanceof Response) {
482
+ return who;
483
+ }
484
+ return inTenantAs(who, async () => c.json(await rotateSynced(who.userId, c.req.param("spaceId"), c.req.param("wizardId"))));
485
+ })
486
+ .post("/sync/spaces/:spaceId/adopt", async (c) => {
487
+ const who = await caller(c, ["wizards:write"]);
488
+ if (who instanceof Response) {
489
+ return who;
490
+ }
491
+ return inTenantAs(who, async () => c.json(await adoptSpace(c.req.param("spaceId"))));
385
492
  })
386
493
  .post("/wizards/import", tooLarge, async (c) => {
387
494
  const authInfo = await authenticate(c.req.raw);
@@ -66,6 +66,7 @@ import { draftWidgetPreview } from "../services/widgets.js";
66
66
  import { createWizard, deleteWizard, draftChanges, duplicateWizard, listWizards, ownedWizard, rotateShareLink, updateWizardSettings, wizardMessages, wizardState, writableWizard, writeDraft, } from "../services/wizards.js";
67
67
  import { deleteSetting, readSetting, writeSetting } from "../settings.js";
68
68
  import { projectShareTargets, sharePreview } from "../sharing/index.js";
69
+ import { keepCloudForAll, mergesSeen, proposeMerge, resolveConflict, startSpace, stopSpace, syncAll, syncView, undoMerge, } from "../sync/client.js";
69
70
  import { codeOf } from "../tenants/control.js";
70
71
  import { currentTenant } from "../tenants/tenant.js";
71
72
  import { serverText } from "../texts.js";
@@ -216,6 +217,18 @@ const terminalSize = z.object({
216
217
  cols: z.number().int().min(10).max(500).optional(),
217
218
  rows: z.number().int().min(4).max(200).optional(),
218
219
  });
220
+ /** How the person settled a conflict: one side, a choice per place, or a version of their own. */
221
+ const resolutionSchema = z.union([
222
+ z.object({ take: z.enum(["local", "remote"]) }),
223
+ z.object({
224
+ choices: z.array(z.union([
225
+ z.object({ take: z.enum(["local", "remote"]) }),
226
+ z.object({ value: z.unknown() }),
227
+ z.null(),
228
+ ])),
229
+ }),
230
+ z.object({ record: z.record(z.string(), z.unknown()) }),
231
+ ]);
219
232
  export const studio = new Hono()
220
233
  .get("/me", async (c) => {
221
234
  const user = c.get("user");
@@ -1195,6 +1208,55 @@ export const studio = new Hono()
1195
1208
  return c.notFound();
1196
1209
  }
1197
1210
  return c.json(await checkForCloud(c.get("user").id, c.req.param("id")));
1211
+ })
1212
+ // --- the two-way sync of the spaces with the account's organization (sync/client.ts) ---
1213
+ .get("/sync", async (c) => (managed ? c.notFound() : c.json(await syncView())))
1214
+ .post("/sync/now", async (c) => {
1215
+ if (managed) {
1216
+ return c.notFound();
1217
+ }
1218
+ await syncAll();
1219
+ return c.json(await syncView());
1220
+ })
1221
+ .put("/sync/spaces/:id", async (c) => {
1222
+ if (managed) {
1223
+ return c.notFound();
1224
+ }
1225
+ const { on } = z.object({ on: z.boolean() }).parse(await c.req.json());
1226
+ await (on ? startSpace(c.req.param("id")) : stopSpace(c.req.param("id")));
1227
+ return c.json(await syncView());
1228
+ })
1229
+ .post("/sync/spaces/:id/keep-cloud", async (c) => {
1230
+ if (managed) {
1231
+ return c.notFound();
1232
+ }
1233
+ await keepCloudForAll(c.req.param("id"));
1234
+ return c.json(await syncView());
1235
+ })
1236
+ .post("/sync/conflicts/:id/resolve", async (c) => {
1237
+ if (managed) {
1238
+ return c.notFound();
1239
+ }
1240
+ const body = resolutionSchema.parse(await c.req.json());
1241
+ await resolveConflict(c.req.param("id"), body);
1242
+ return c.json(await syncView());
1243
+ })
1244
+ .post("/sync/conflicts/:id/propose", async (c) => managed ? c.notFound() : c.json(await proposeMerge(c.req.param("id"))))
1245
+ .post("/sync/merges/:id/undo", async (c) => {
1246
+ if (managed) {
1247
+ return c.notFound();
1248
+ }
1249
+ const { take } = z.object({ take: z.enum(["local", "remote"]) }).parse(await c.req.json());
1250
+ await undoMerge(c.req.param("id"), take);
1251
+ return c.json(await syncView());
1252
+ })
1253
+ .post("/sync/merges/seen", async (c) => {
1254
+ if (managed) {
1255
+ return c.notFound();
1256
+ }
1257
+ const { ids } = z.object({ ids: z.array(z.string()).max(200) }).parse(await c.req.json());
1258
+ await mergesSeen(ids);
1259
+ return c.json({ ok: true });
1198
1260
  })
1199
1261
  // The projects of local installs the account's cloud holds.
1200
1262
  .get("/cloud/spaces", async (c) => {
@@ -7,6 +7,7 @@ import { env } from "../env.js";
7
7
  import { getBlob } from "../files/blobs.js";
8
8
  import { managed } from "../manage.js";
9
9
  import { deleteSetting, readSetting, writeSetting } from "../settings.js";
10
+ import { forgetTwoWay, publishInCloud, rotateInCloudSpace, spaceSyncs } from "../sync/client.js";
10
11
  import { currentTenant } from "../tenants/tenant.js";
11
12
  import { mainLogoId } from "./brand.js";
12
13
  import { ServiceError } from "./errors.js";
@@ -218,7 +219,26 @@ export async function syncToCloud(userId, wizardId) {
218
219
  throw new ServiceError("refused", note("publishWizardFirst"));
219
220
  }
220
221
  const before = await cloudState(w.id);
222
+ const twoWay = await spaceSyncs(w.projectId);
221
223
  try {
224
+ if (twoWay) {
225
+ // The space syncs both ways: its draft goes up with the space, then the cloud publishes it.
226
+ const published = await publishInCloud(w.projectId, w.id);
227
+ const state = {
228
+ copy: {
229
+ shareUrl: published.shareUrl,
230
+ code: published.code,
231
+ version: version.version,
232
+ publishedVersion: published.publishedVersion,
233
+ runnable: true,
234
+ problems: [],
235
+ syncedAt: new Date().toISOString(),
236
+ },
237
+ error: null,
238
+ };
239
+ await writeSetting(key(w.id), state);
240
+ return state;
241
+ }
222
242
  const files = await Promise.all(version.files.map(async (f) => ({
223
243
  path: f.path,
224
244
  mime: f.mime,
@@ -286,6 +306,11 @@ export async function pushSharing(userId, wizardId) {
286
306
  if (!(await cloudLinked())) {
287
307
  return;
288
308
  }
309
+ // A space that syncs both ways takes the settings along with the wizard.
310
+ const own = await ownedWizard(userId, wizardId).catch(() => null);
311
+ if (own && (await spaceSyncs(own.projectId))) {
312
+ return;
313
+ }
289
314
  const state = await cloudState(wizardId);
290
315
  if (!state.copy) {
291
316
  return;
@@ -311,13 +336,20 @@ export async function rotateInCloud(userId, wizardId) {
311
336
  return state;
312
337
  }
313
338
  const w = await ownedWizard(userId, wizardId);
314
- const answer = await call("POST", `/spaces/${w.projectId}/wizards/${w.id}/rotate-link`);
315
- if (!answer.ok || !answer.body.shareUrl) {
316
- throw refusal(answer, "The link in the cloud could not be renewed.");
339
+ let link;
340
+ if (await spaceSyncs(w.projectId)) {
341
+ link = await rotateInCloudSpace(w.projectId, w.id);
342
+ }
343
+ else {
344
+ const answer = await call("POST", `/spaces/${w.projectId}/wizards/${w.id}/rotate-link`);
345
+ if (!answer.ok || !answer.body.shareUrl) {
346
+ throw refusal(answer, "The link in the cloud could not be renewed.");
347
+ }
348
+ link = answer.body;
317
349
  }
318
350
  const next = {
319
351
  ...state,
320
- copy: { ...state.copy, shareUrl: answer.body.shareUrl, code: answer.body.code },
352
+ copy: { ...state.copy, shareUrl: link.shareUrl, code: link.code },
321
353
  };
322
354
  await writeSetting(key(w.id), next);
323
355
  return next;
@@ -330,7 +362,8 @@ export async function removeFromCloud(userId, wizardId) {
330
362
  }
331
363
  const w = await ownedWizard(userId, wizardId).catch(() => null);
332
364
  await deleteSetting(key(wizardId));
333
- if (!w || !state.copy || !(await cloudLinked())) {
365
+ // A space that syncs both ways deletes the copy with the next push.
366
+ if (!w || !state.copy || !(await cloudLinked()) || (await spaceSyncs(w.projectId))) {
334
367
  return;
335
368
  }
336
369
  await call("DELETE", `/spaces/${w.projectId}/wizards/${w.id}`).catch((err) => console.error("[cloud] copy not removed:", err.message));
@@ -370,6 +403,7 @@ export async function retryFailedSends(userId) {
370
403
  export async function forgetCloud() {
371
404
  await controlDb.delete(control.setting).where(like(control.setting.key, "cloud:%"));
372
405
  await forgetSentData();
406
+ await forgetTwoWay();
373
407
  }
374
408
  /** The space's data counts as not sent: the next wizard takes it along again. */
375
409
  async function forgetSentData() {
@@ -7,6 +7,7 @@ import { db, schema } from "../db/client.js";
7
7
  import { env } from "../env.js";
8
8
  import { managed, tenantInfo } from "../manage.js";
9
9
  import { spaceChanged } from "../plugins/events.js";
10
+ import { cloudSpaceLimit, twoWayActive } from "../sync/state.js";
10
11
  import { putLink } from "../tenants/control.js";
11
12
  import { currentTenant } from "../tenants/tenant.js";
12
13
  import { serverText } from "../texts.js";
@@ -162,6 +163,16 @@ export async function projectLimit() {
162
163
  return info.limits.projects;
163
164
  }
164
165
  }
166
+ // A local install that syncs both ways has the organization's spaces: its number counts.
167
+ if (twoWayActive()) {
168
+ const limit = cloudSpaceLimit();
169
+ if (limit === null) {
170
+ return Number.POSITIVE_INFINITY;
171
+ }
172
+ if (limit !== undefined) {
173
+ return Math.max(1, limit);
174
+ }
175
+ }
165
176
  return Math.max(1, env.limits.projects);
166
177
  }
167
178
  /** The number for the studio: null where there is no limit (JSON has no infinity). */
@@ -0,0 +1,39 @@
1
+ import { sql } from "drizzle-orm";
2
+ import { db, inTransaction } from "../db/client.js";
3
+ import { asSync } from "../services/access.js";
4
+ import { quietly } from "./log.js";
5
+ import { KIND_ORDER, KINDS, letDanglingGo } from "./records.js";
6
+ /**
7
+ * Writes a batch of items in one transaction, in an order where what one points to comes
8
+ * first; what still points nowhere at the end is let go. `quiet`: an install writing what it
9
+ * pulled, which the triggers must not note as its own change. What follows a write (links,
10
+ * events, the index) runs after the commit.
11
+ */
12
+ export async function applyItems(items, options) {
13
+ if (!items.length) {
14
+ return;
15
+ }
16
+ const sorted = [...items].sort((a, b) => KIND_ORDER.indexOf(a.kind) - KIND_ORDER.indexOf(b.kind));
17
+ const afters = await asSync(() => inTransaction(async () => {
18
+ const write = async () => {
19
+ // Points between the items of the batch are checked at the commit, not one by one.
20
+ await db.run(sql `PRAGMA defer_foreign_keys = ON`);
21
+ const done = [];
22
+ for (const x of sorted) {
23
+ const def = KINDS[x.kind];
24
+ const after = x.record
25
+ ? await def.write(x.projectId, x.item, x.record)
26
+ : await def.remove(x.projectId, x.item);
27
+ if (after) {
28
+ done.push(after);
29
+ }
30
+ }
31
+ await letDanglingGo();
32
+ return done;
33
+ };
34
+ return options.quiet ? quietly(write) : write();
35
+ }));
36
+ for (const after of afters) {
37
+ await Promise.resolve(after()).catch((err) => console.error("[sync] after a write:", err));
38
+ }
39
+ }