@wix/himalaya-cli 0.1914.0 → 0.1916.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 (51) hide show
  1. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/core/dev-server/src/app-config.d.ts +3 -0
  2. package/dist/browser-plane/assets.json +5 -5
  3. package/dist/browser-plane/preview-deferred/{a5d585737ec0f4d39abdf4a8e7c45350a720c45c62afbba5ae54265cd4d8ec70.bin → 807f139c38f827210737739a18b3f125fa7b48c4a65cef57820a3f4f7502845c.bin} +1 -1
  4. package/dist/browser-plane/sw.js +1 -1
  5. package/dist/cli.mjs +763 -46
  6. package/dist/preview-assets.generated.bin +0 -0
  7. package/package.json +2 -2
  8. package/templates/beauty-salon-owner/tier5-src/_shared/owner-local-db.ts +3 -0
  9. package/templates/beauty-salon-owner/tier5-src/_shared/owner-maestro-availability.ts +24 -1
  10. package/templates/beauty-salon-owner/tier5-src/_shared/owner-maestro-chat.ts +5 -4
  11. package/templates/beauty-salon-owner/tier5-src/himi-owner-lite-sites/index.ts +180 -10
  12. package/templates/community-club-owner/tier5-src/_shared/owner-local-db.ts +3 -0
  13. package/templates/community-club-owner/tier5-src/_shared/owner-maestro-availability.ts +24 -1
  14. package/templates/community-club-owner/tier5-src/_shared/owner-maestro-chat.ts +5 -4
  15. package/templates/community-club-owner/tier5-src/himi-owner-lite-sites/index.ts +180 -10
  16. package/templates/events-meetups-owner/tier5-src/_shared/owner-local-db.ts +3 -0
  17. package/templates/events-meetups-owner/tier5-src/_shared/owner-maestro-availability.ts +24 -1
  18. package/templates/events-meetups-owner/tier5-src/_shared/owner-maestro-chat.ts +5 -4
  19. package/templates/events-meetups-owner/tier5-src/himi-owner-lite-sites/index.ts +180 -10
  20. package/templates/gym-fitness-owner/tier5-src/_shared/owner-local-db.ts +3 -0
  21. package/templates/gym-fitness-owner/tier5-src/_shared/owner-maestro-availability.ts +24 -1
  22. package/templates/gym-fitness-owner/tier5-src/_shared/owner-maestro-chat.ts +5 -4
  23. package/templates/gym-fitness-owner/tier5-src/himi-owner-lite-sites/index.ts +180 -10
  24. package/templates/nonprofit-cause-owner/tier5-src/_shared/owner-local-db.ts +3 -0
  25. package/templates/nonprofit-cause-owner/tier5-src/_shared/owner-maestro-availability.ts +24 -1
  26. package/templates/nonprofit-cause-owner/tier5-src/_shared/owner-maestro-chat.ts +5 -4
  27. package/templates/nonprofit-cause-owner/tier5-src/himi-owner-lite-sites/index.ts +180 -10
  28. package/templates/owner-lite/tier5-src/_shared/owner-local-db.ts +3 -0
  29. package/templates/owner-lite/tier5-src/_shared/owner-maestro-availability.ts +24 -1
  30. package/templates/owner-lite/tier5-src/_shared/owner-maestro-chat.ts +5 -4
  31. package/templates/owner-lite/tier5-src/himi-owner-lite-sites/index.ts +180 -10
  32. package/templates/podcast-creator-owner/tier5-src/_shared/owner-local-db.ts +3 -0
  33. package/templates/podcast-creator-owner/tier5-src/_shared/owner-maestro-availability.ts +24 -1
  34. package/templates/podcast-creator-owner/tier5-src/_shared/owner-maestro-chat.ts +5 -4
  35. package/templates/podcast-creator-owner/tier5-src/himi-owner-lite-sites/index.ts +180 -10
  36. package/templates/portfolio-creative-owner/tier5-src/_shared/owner-local-db.ts +3 -0
  37. package/templates/portfolio-creative-owner/tier5-src/_shared/owner-maestro-availability.ts +24 -1
  38. package/templates/portfolio-creative-owner/tier5-src/_shared/owner-maestro-chat.ts +5 -4
  39. package/templates/portfolio-creative-owner/tier5-src/himi-owner-lite-sites/index.ts +180 -10
  40. package/templates/restaurant-owner/tier5-src/_shared/owner-local-db.ts +3 -0
  41. package/templates/restaurant-owner/tier5-src/_shared/owner-maestro-availability.ts +24 -1
  42. package/templates/restaurant-owner/tier5-src/_shared/owner-maestro-chat.ts +5 -4
  43. package/templates/restaurant-owner/tier5-src/himi-owner-lite-sites/index.ts +180 -10
  44. package/templates/retail-store-owner/tier5-src/_shared/owner-local-db.ts +3 -0
  45. package/templates/retail-store-owner/tier5-src/_shared/owner-maestro-availability.ts +24 -1
  46. package/templates/retail-store-owner/tier5-src/_shared/owner-maestro-chat.ts +5 -4
  47. package/templates/retail-store-owner/tier5-src/himi-owner-lite-sites/index.ts +180 -10
  48. package/templates/yoga-studio-owner/tier5-src/_shared/owner-local-db.ts +3 -0
  49. package/templates/yoga-studio-owner/tier5-src/_shared/owner-maestro-availability.ts +24 -1
  50. package/templates/yoga-studio-owner/tier5-src/_shared/owner-maestro-chat.ts +5 -4
  51. package/templates/yoga-studio-owner/tier5-src/himi-owner-lite-sites/index.ts +180 -10
@@ -10,10 +10,11 @@ import { defineService } from "@himalaya/state";
10
10
  import { querySites, type WixSite } from "@himalaya/wix-site-list";
11
11
  import { ownerLoadError, isOwnerPreviewDemo, ownerDemoFallback } from "../_shared/owner-load-error.js";
12
12
  import { DEMO_SITES, DEMO_NOTE } from "../_shared/owner-preview-demo.js";
13
- import { stashCopy, copyParam } from "../_shared/himi-copy.js";
14
- import { getAll, upsert, type DbEntity } from "../_shared/owner-local-db.js";
13
+ import { stashCopy, copyParam, copyTemplate } from "../_shared/himi-copy.js";
14
+ import { getAll, upsert, batch, principal, type DbEntity } from "../_shared/owner-local-db.js";
15
15
  import { pickSite, pickedSite } from "../_shared/owner-site-pick.js";
16
16
  import { readSelectedSite } from "../_shared/owner-selected-site.js";
17
+ import { spaceWebsites, type MaestroWixApi, type SpaceWebsite } from "../_shared/owner-maestro-availability.js";
17
18
 
18
19
  // Offline-first (data-offline): the owner's last-synced businesses are the
19
20
  // READ-THROUGH cache for the `sites` entity — paint them instantly (works
@@ -26,8 +27,13 @@ const ENTITY = "sites";
26
27
  async function readCachedRows(): Promise<SiteRow[]> {
27
28
  try { return (await getAll(ENTITY)) as unknown as SiteRow[]; } catch { return []; }
28
29
  }
29
- async function writeCachedRows(rows: SiteRow[]): Promise<void> {
30
- try { for (const r of rows) await upsert(ENTITY, r as unknown as DbEntity); } catch { /* capability not granted → online-only */ }
30
+ /** `bound` is the local-db partition the rows were read for (`principal()`). The rows land in that
31
+ * owner's partition or nowhere: an owner who signed out or switched account while the list loaded
32
+ * must not find these businesses in their cache. */
33
+ async function writeCachedRows(rows: SiteRow[], bound: string): Promise<void> {
34
+ try {
35
+ await batch(rows.map((r) => ({ op: "upsert" as const, entity: ENTITY, object: r as unknown as DbEntity })), { expectPrincipal: bound });
36
+ } catch { /* capability not granted, or the partition changed owner → nothing cached */ }
31
37
  }
32
38
 
33
39
  interface SiteRow {
@@ -37,6 +43,8 @@ interface SiteRow {
37
43
  /** A complete, useful spoken name for the row's tap target. */
38
44
  spokenLabel: string;
39
45
  initial: string;
46
+ /** A Space's website, read from Symphony and not from the account's site list. */
47
+ space?: boolean;
40
48
  }
41
49
 
42
50
  interface SitesState {
@@ -55,6 +63,8 @@ interface SitesState {
55
63
  /** Non-empty when showing owner-preview-demo sample data (web preview, no owner bridge). */
56
64
  demoNote: string;
57
65
  notDemo: boolean;
66
+ /** The account has more businesses than were read: the count line says so. */
67
+ _more: boolean;
58
68
  }
59
69
 
60
70
  function normalize(raw: WixSite): SiteRow {
@@ -69,6 +79,94 @@ function normalize(raw: WixSite): SiteRow {
69
79
  };
70
80
  }
71
81
 
82
+ /** A Space's website as a row. It is not in the account's site list, so it has no Wix row to normalize. */
83
+ function spaceRow(site: SpaceWebsite): SiteRow {
84
+ const name = site.name || copyParam("ownerSites.unnamedBusiness", "Business");
85
+ const meta = copyParam("ownerSites.spaceWebsite", "Space website");
86
+ return { id: site.id, name, meta, spokenLabel: [name, meta].join(", "), initial: (name.trim()[0] || "S").toUpperCase(), space: true };
87
+ }
88
+
89
+ /** Most pages the list reads. Wix serves at most 100 sites a page (a larger limit is refused with
90
+ * 400), so this is 1,000 businesses; the result line says when an account has more. */
91
+ const MAX_PAGES = 10;
92
+ const PAGE_SIZE = 100;
93
+
94
+ /** Every business of the account, page by page. `more` is true when the account has more than
95
+ * were read. Throws when the first page cannot be read; a later page that fails ends the list
96
+ * with what was read, marked `more`, so one bad page does not hide every business. */
97
+ async function allSites(): Promise<{ sites: WixSite[]; more: boolean }> {
98
+ const sites: WixSite[] = [];
99
+ let cursor = "";
100
+ for (let page = 0; page < MAX_PAGES; page++) {
101
+ let res: Awaited<ReturnType<typeof querySites>>;
102
+ try {
103
+ res = await querySites({ query: { cursorPaging: cursor ? { limit: PAGE_SIZE, cursor } : { limit: PAGE_SIZE } } });
104
+ } catch (e) {
105
+ if (page === 0) throw e;
106
+ return { sites, more: true };
107
+ }
108
+ sites.push(...(res.sites ?? []));
109
+ const meta = res.metadata as { hasNext?: boolean; cursors?: { next?: string } } | undefined;
110
+ if (!meta?.hasNext) return { sites, more: false };
111
+ const next = typeof meta.cursors?.next === "string" ? meta.cursors.next : "";
112
+ // More is promised with no way to reach it (no cursor, or the same one again): the list is partial.
113
+ if (!next || next === cursor) return { sites, more: true };
114
+ cursor = next;
115
+ }
116
+ return { sites, more: true };
117
+ }
118
+
119
+ type SpaceAnswer = { ok: true; rows: SiteRow[] } | { ok: false; reason: string };
120
+
121
+ /** The owner's Space websites as rows. A failure is its own answer, never an empty list: that
122
+ * Symphony could not be asked says nothing about which Spaces the owner has, so the caller keeps
123
+ * the rows it already shows. */
124
+ async function spaceRows(): Promise<SpaceAnswer> {
125
+ const api = (globalThis as { himalaya?: { wixApi?: MaestroWixApi } }).himalaya?.wixApi;
126
+ if (!api) return { ok: false, reason: "no Wix bridge" };
127
+ try {
128
+ return { ok: true, rows: (await spaceWebsites(api)).map(spaceRow) };
129
+ } catch (e) {
130
+ return { ok: false, reason: String((e as Error)?.message ?? e) };
131
+ }
132
+ }
133
+
134
+ /** Symphony's answer to the latest load, or null while it has given none. */
135
+ let answeredSpaces: SiteRow[] | null = null;
136
+ /** Counts loads: an answer to an earlier load (a retry overtook it, or the session changed) is dropped. */
137
+ let loadGeneration = 0;
138
+ /** The latest load that has returned its list. While a load is still running its own result will
139
+ * carry Symphony's answer, and an action dispatched beside it would be computed from the state
140
+ * the load started with. */
141
+ let settledGeneration = 0;
142
+ /** The local-db partition the latest load read its cache from: where its rows may be cached. */
143
+ let loadPrincipal: string | null = null;
144
+
145
+ /** Space websites first: they are few, and they are the businesses Maestro works for. A site the
146
+ * account's own list also holds is shown once, as the account lists it. */
147
+ function withSpaces(spaces: SiteRow[], own: SiteRow[]): SiteRow[] {
148
+ return [...spaces.filter((w) => !own.some((r) => r.id === w.id)), ...own];
149
+ }
150
+
151
+ /** The line under the search field. */
152
+ function summaryLine(count: number, query: string, more: boolean): string {
153
+ if (query.trim()) return `${count} matching`;
154
+ if (more) return copyTemplate("ownerSites.firstOfMany", "First {count} businesses", { count });
155
+ return `${count} ${count === 1 ? "business" : "businesses"}`;
156
+ }
157
+
158
+ /** A host that cannot bind writes (an older binary, no per-member partition) keeps the write it
159
+ * had before the list was paged: row by row, finished before the list is shown, so it is no
160
+ * likelier than it was to outlive a sign-out. Offline, that host still opens on its businesses. */
161
+ async function writeCachedRowsUnbound(rows: SiteRow[]): Promise<void> {
162
+ try { for (const r of rows) await upsert(ENTITY, r as unknown as DbEntity); } catch { /* capability not granted → online-only */ }
163
+ }
164
+
165
+ /** Bound: best effort and never awaited, so a list of a thousand rows does not wait for its cache. */
166
+ function cacheRows(rows: SiteRow[], bound: string): void {
167
+ void writeCachedRows(rows, bound);
168
+ }
169
+
72
170
  function applySearch(rows: SiteRow[], query: string): SiteRow[] {
73
171
  const q = query.trim().toLowerCase();
74
172
  return q ? rows.filter((r) => r.name.toLowerCase().includes(q)) : rows;
@@ -125,6 +223,7 @@ function shape(s: Partial<SitesState>): SitesState {
125
223
  hideContent: status !== "ready" || sites.length === 0,
126
224
  demoNote: s.demoNote ?? "",
127
225
  notDemo: !s.demoNote,
226
+ _more: s._more === true,
128
227
  };
129
228
  }
130
229
 
@@ -147,8 +246,21 @@ function demoList(s: SitesState): SitesState {
147
246
  });
148
247
  }
149
248
 
249
+ /** One load of the list. A load that a newer one replaced while it ran changes nothing: its
250
+ * result would otherwise land after the newer list and take its place (two loads overlap on
251
+ * every open, the worker's own and the screen's). */
150
252
  async function loadList(s: SitesState): Promise<SitesState> {
151
253
  if (isOwnerPreviewDemo()) return demoList(s);
254
+ const generation = ++loadGeneration;
255
+ const result = await loadGenerationOf(s, generation);
256
+ if (generation === loadGeneration) return result;
257
+ return (svc as unknown as { getState?: () => SitesState }).getState?.() ?? result;
258
+ }
259
+
260
+ async function loadGenerationOf(s: SitesState, generation: number): Promise<SitesState> {
261
+ answeredSpaces = null;
262
+ const bound = await principal();
263
+ if (generation === loadGeneration) loadPrincipal = bound;
152
264
  // 1) Instant paint from the on-device cache (offline-safe; empty on first-ever run).
153
265
  const cached = await readCachedRows();
154
266
  const selected = readSelectedSite();
@@ -156,15 +268,59 @@ async function loadList(s: SitesState): Promise<SitesState> {
156
268
  const base = repairedCache.length
157
269
  ? shape({ ...s, status: "ready", allSites: repairedCache, sites: applySearch(repairedCache, s.searchQuery), error: "", demoNote: "" })
158
270
  : s;
271
+ // The Space websites already on screen (a restored state) or last cached: they stay until
272
+ // Symphony answers, so a list that had them never shrinks and grows back.
273
+ const onScreen = (s.allSites ?? []).filter((r) => r.space === true);
274
+ const shownSpaces = onScreen.length ? onScreen : repairedCache.filter((r) => r.space === true);
159
275
  // 2) Revalidate from Wix and refresh the cache.
160
276
  try {
161
- const res = await querySites({ query: { cursorPaging: { limit: 50 } } });
162
- const rows = (res.sites ?? []).filter((r: WixSite) => r?.id).map(normalize);
163
- await writeCachedRows(rows);
164
- return shape({ ...s, status: "ready", allSites: rows, sites: applySearch(rows, s.searchQuery), resultSummary: `${rows.length} ${rows.length === 1 ? "business" : "businesses"}`, error: "", demoNote: "" });
277
+ // Symphony is asked beside the account's list and never waited for: most owners do not use it,
278
+ // and their businesses must not load slower, or fail, because of it. Its answer arrives as
279
+ // `spacesLoaded`. Until then the Space websites this device last saw stay where they were.
280
+ // It can answer before the account's pages are read or after, so it is kept here for this load
281
+ // to use and also delivered as an action for a list already on screen.
282
+ void spaceRows().then((answer) => {
283
+ if (!answer.ok || generation !== loadGeneration) return;
284
+ const spaces = answer.rows;
285
+ answeredSpaces = spaces;
286
+ // Nothing to add and nothing shown to take away: most owners, who have no Space.
287
+ if (settledGeneration !== generation) return; // the running load returns them itself
288
+ if (spaces.length || shownSpaces.length) void svc.spacesLoaded(spaces);
289
+ });
290
+ const listed = await allSites();
291
+ // A newer load took over while the account was read: this one writes nothing and marks
292
+ // nothing, or the newer load's Space answer would be measured against the wrong load.
293
+ if (generation !== loadGeneration) return s;
294
+ const own = listed.sites.filter((r: WixSite) => r?.id).map(normalize);
295
+ let rows = withSpaces(answeredSpaces ?? shownSpaces, own);
296
+ if (bound === null) {
297
+ await writeCachedRowsUnbound(rows);
298
+ if (generation !== loadGeneration) return s;
299
+ // Symphony may have answered during that write: the list returned below must hold its answer,
300
+ // because nothing after this line waits, and an answer from here on arrives as `spacesLoaded`.
301
+ rows = withSpaces(answeredSpaces ?? shownSpaces, own);
302
+ } else {
303
+ cacheRows(rows, bound);
304
+ }
305
+ const sites = applySearch(rows, s.searchQuery);
306
+ settledGeneration = generation;
307
+ return shape({ ...s, status: "ready", allSites: rows, sites, resultSummary: summaryLine(sites.length, s.searchQuery, listed.more), error: "", demoNote: "", _more: listed.more });
165
308
  } catch (e) {
166
309
  // Offline / fetch failure: keep the last-synced cache BEFORE the demo/error fallbacks.
167
- if (repairedCache.length) return base;
310
+ if (repairedCache.length) {
311
+ // Symphony can still answer when the account's list cannot be read. An answer already here
312
+ // goes into the cached list now, and a later one arrives as `spacesLoaded`.
313
+ // Only for the load that is still the current one: `answeredSpaces` and the settled mark
314
+ // belong to the newest load, and an older one failing late must not take or move them.
315
+ if (generation !== loadGeneration) return base;
316
+ settledGeneration = generation;
317
+ if (answeredSpaces === null) return base;
318
+ const rows = withSpaces(answeredSpaces, repairedCache.filter((r) => r.space !== true));
319
+ if (bound !== null) cacheRows(rows, bound);
320
+ const sites = applySearch(rows, s.searchQuery);
321
+ // A cached list that was partial stays partial: `_more` came with the state.
322
+ return shape({ ...base, allSites: rows, sites, resultSummary: summaryLine(sites.length, s.searchQuery, base._more), emptyText: undefined });
323
+ }
168
324
  if (ownerDemoFallback(e)) return demoList(s);
169
325
  return shape({ ...s, status: "error", allSites: [], sites: [], error: ownerLoadError(e) });
170
326
  }
@@ -179,6 +335,7 @@ const svc = defineService<SitesState, {
179
335
  load: (s: SitesState, arg?: unknown) => Promise<SitesState>;
180
336
  retry: (s: SitesState) => Promise<SitesState>;
181
337
  search: (s: SitesState, arg?: unknown) => Promise<SitesState>;
338
+ spacesLoaded: (s: SitesState, arg?: unknown) => SitesState;
182
339
  pick: (s: SitesState, arg?: unknown) => SitesState;
183
340
  }>("himiOwnerLiteSites", {
184
341
  state: shape({ status: "loading" }),
@@ -197,7 +354,20 @@ const svc = defineService<SitesState, {
197
354
  search: async (s, arg) => {
198
355
  const q = typeof arg === "string" ? arg : String((arg as { value?: string; query?: string })?.value ?? (arg as { query?: string })?.query ?? "");
199
356
  const sites = applySearch(s.allSites, q);
200
- return shape({ ...s, searchQuery: q, sites, resultSummary: q.trim() ? `${sites.length} matching` : `${sites.length} ${sites.length === 1 ? "business" : "businesses"}`, emptyText: sites.length ? "" : emptyFor(q) });
357
+ return shape({ ...s, searchQuery: q, sites, resultSummary: summaryLine(sites.length, q, s._more), emptyText: sites.length ? "" : emptyFor(q) });
358
+ },
359
+ // Symphony's answer to `load`: the owner's Space websites, replacing the ones shown so far.
360
+ // Ignored while the list is not the account's own (still loading, failed, or sample data).
361
+ spacesLoaded: (s, arg) => {
362
+ if (s.status !== "ready" || s.demoNote) return s;
363
+ const spaces = (Array.isArray(arg) ? arg : []) as SiteRow[];
364
+ const rows = withSpaces(spaces, s.allSites.filter((r) => r.space !== true));
365
+ if (rows.length === s.allSites.length && rows.every((r, i) => r.id === s.allSites[i].id && r.name === s.allSites[i].name)) return s;
366
+ // Only a bound write: this arrives after the list is shown, when an unbound one could land
367
+ // in the next owner's cache. An unbindable host caches the Space rows on its next load.
368
+ if (loadPrincipal !== null) cacheRows(rows, loadPrincipal);
369
+ const sites = applySearch(rows, s.searchQuery);
370
+ return shape({ ...s, allSites: rows, sites, resultSummary: summaryLine(sites.length, s.searchQuery, s._more), emptyText: sites.length ? "" : emptyFor(s.searchQuery) });
201
371
  },
202
372
  },
203
373
  });
@@ -11,3 +11,6 @@ export const get: typeof db.get = async (...args) => isOwnerPreviewLive() ? null
11
11
  export const upsert: typeof db.upsert = async (...args) => { if (!isOwnerPreviewLive()) await db.upsert(...args); };
12
12
  export const remove: typeof db.remove = async (...args) => { if (!isOwnerPreviewLive()) await db.remove(...args); };
13
13
  export const enqueue: typeof db.enqueue = async (...args) => { if (!isOwnerPreviewLive()) await db.enqueue(...args); };
14
+
15
+ export const batch: typeof db.batch = async (...args) => { if (!isOwnerPreviewLive()) await db.batch(...args); };
16
+ export const principal: typeof db.principal = async () => db.principal();
@@ -18,7 +18,7 @@ export const forSymphonyAccount = (metaSiteId: string): Record<string, string> =
18
18
  ({ "wix-site-id": metaSiteId, "Content-Type": "application/json" });
19
19
 
20
20
  interface Recipient { recipient?: { metaSiteId?: string } | null }
21
- interface Spaces { workspaces?: Array<{ website?: { metaSiteId?: string } | null }> }
21
+ interface Spaces { workspaces?: Array<{ name?: string; website?: { metaSiteId?: string; name?: string } | null }> }
22
22
 
23
23
  /** The owner's Symphony metasite, or "" when they have no Symphony account. Throws when the
24
24
  * service could not be asked. */
@@ -34,6 +34,29 @@ export async function isSpaceWebsite(api: MaestroWixApi, account: string, site:
34
34
  return (res?.workspaces ?? []).some((w) => w?.website?.metaSiteId === site);
35
35
  }
36
36
 
37
+ export interface SpaceWebsite { id: string; name: string; space: string }
38
+
39
+ /** The websites of the owner's Spaces, one per site. Empty when they have no Symphony account.
40
+ * Throws when it could not be asked.
41
+ *
42
+ * A Space's website belongs to the Symphony account, not to the owner's own Wix account, so the
43
+ * account's site list never holds it (measured live 2026-11-27: 142 sites listed, neither Space
44
+ * website among them). */
45
+ export async function spaceWebsites(api: MaestroWixApi): Promise<SpaceWebsite[]> {
46
+ const account = await symphonyAccount(api);
47
+ if (!account) return [];
48
+ const res = (await api.call("POST", SPACES, {}, forSymphonyAccount(account))) as Spaces | null;
49
+ const out: SpaceWebsite[] = [];
50
+ for (const w of res?.workspaces ?? []) {
51
+ const id = typeof w?.website?.metaSiteId === "string" ? w.website.metaSiteId.trim() : "";
52
+ if (!id || out.some((s) => s.id === id)) continue;
53
+ const space = typeof w?.name === "string" ? w.name.trim() : "";
54
+ const name = typeof w.website?.name === "string" ? w.website.name.trim() : "";
55
+ out.push({ id, name: name || space, space });
56
+ }
57
+ return out;
58
+ }
59
+
37
60
  /** Why a host cannot run a Maestro turn, or "" when it can.
38
61
  *
39
62
  * `old_host`: built before it could read a stream of JSON lines, so a turn delivers nothing.
@@ -6,6 +6,7 @@
6
6
  // credential. Shared by the Maestro screen and its history screen.
7
7
 
8
8
  import type { MaestroWixApi } from "./owner-maestro-availability.js";
9
+ import { uuidV4 } from "./chat-live.js";
9
10
 
10
11
  const NATIVE_DATA = "https://manage.wix.com/_serverless/ai-scheduling-assistant-server/native-data";
11
12
 
@@ -101,11 +102,11 @@ export async function chatMessages(api: MaestroWixApi, conversationId: string):
101
102
  return out;
102
103
  }
103
104
 
104
- let requestSeq = 0;
105
- /** Unique per request within this worker: Symphony uses it to drop a repeated read. */
105
+ /** Unique per request: Symphony uses it to drop a repeated read. It must be a UUID. Any other
106
+ * text is refused with 400 `invalid_chat_window` (measured live 2026-11-27), which the screen
107
+ * can only show as a chat that will not open. */
106
108
  function requestId(): string {
107
- requestSeq += 1;
108
- return `owner-lite-${Date.now().toString(36)}-${requestSeq}`;
109
+ return uuidV4();
109
110
  }
110
111
 
111
112
  export interface Decision {
@@ -10,10 +10,11 @@ import { defineService } from "@himalaya/state";
10
10
  import { querySites, type WixSite } from "@himalaya/wix-site-list";
11
11
  import { ownerLoadError, isOwnerPreviewDemo, ownerDemoFallback } from "../_shared/owner-load-error.js";
12
12
  import { DEMO_SITES, DEMO_NOTE } from "../_shared/owner-preview-demo.js";
13
- import { stashCopy, copyParam } from "../_shared/himi-copy.js";
14
- import { getAll, upsert, type DbEntity } from "../_shared/owner-local-db.js";
13
+ import { stashCopy, copyParam, copyTemplate } from "../_shared/himi-copy.js";
14
+ import { getAll, upsert, batch, principal, type DbEntity } from "../_shared/owner-local-db.js";
15
15
  import { pickSite, pickedSite } from "../_shared/owner-site-pick.js";
16
16
  import { readSelectedSite } from "../_shared/owner-selected-site.js";
17
+ import { spaceWebsites, type MaestroWixApi, type SpaceWebsite } from "../_shared/owner-maestro-availability.js";
17
18
 
18
19
  // Offline-first (data-offline): the owner's last-synced businesses are the
19
20
  // READ-THROUGH cache for the `sites` entity — paint them instantly (works
@@ -26,8 +27,13 @@ const ENTITY = "sites";
26
27
  async function readCachedRows(): Promise<SiteRow[]> {
27
28
  try { return (await getAll(ENTITY)) as unknown as SiteRow[]; } catch { return []; }
28
29
  }
29
- async function writeCachedRows(rows: SiteRow[]): Promise<void> {
30
- try { for (const r of rows) await upsert(ENTITY, r as unknown as DbEntity); } catch { /* capability not granted → online-only */ }
30
+ /** `bound` is the local-db partition the rows were read for (`principal()`). The rows land in that
31
+ * owner's partition or nowhere: an owner who signed out or switched account while the list loaded
32
+ * must not find these businesses in their cache. */
33
+ async function writeCachedRows(rows: SiteRow[], bound: string): Promise<void> {
34
+ try {
35
+ await batch(rows.map((r) => ({ op: "upsert" as const, entity: ENTITY, object: r as unknown as DbEntity })), { expectPrincipal: bound });
36
+ } catch { /* capability not granted, or the partition changed owner → nothing cached */ }
31
37
  }
32
38
 
33
39
  interface SiteRow {
@@ -37,6 +43,8 @@ interface SiteRow {
37
43
  /** A complete, useful spoken name for the row's tap target. */
38
44
  spokenLabel: string;
39
45
  initial: string;
46
+ /** A Space's website, read from Symphony and not from the account's site list. */
47
+ space?: boolean;
40
48
  }
41
49
 
42
50
  interface SitesState {
@@ -55,6 +63,8 @@ interface SitesState {
55
63
  /** Non-empty when showing owner-preview-demo sample data (web preview, no owner bridge). */
56
64
  demoNote: string;
57
65
  notDemo: boolean;
66
+ /** The account has more businesses than were read: the count line says so. */
67
+ _more: boolean;
58
68
  }
59
69
 
60
70
  function normalize(raw: WixSite): SiteRow {
@@ -69,6 +79,94 @@ function normalize(raw: WixSite): SiteRow {
69
79
  };
70
80
  }
71
81
 
82
+ /** A Space's website as a row. It is not in the account's site list, so it has no Wix row to normalize. */
83
+ function spaceRow(site: SpaceWebsite): SiteRow {
84
+ const name = site.name || copyParam("ownerSites.unnamedBusiness", "Business");
85
+ const meta = copyParam("ownerSites.spaceWebsite", "Space website");
86
+ return { id: site.id, name, meta, spokenLabel: [name, meta].join(", "), initial: (name.trim()[0] || "S").toUpperCase(), space: true };
87
+ }
88
+
89
+ /** Most pages the list reads. Wix serves at most 100 sites a page (a larger limit is refused with
90
+ * 400), so this is 1,000 businesses; the result line says when an account has more. */
91
+ const MAX_PAGES = 10;
92
+ const PAGE_SIZE = 100;
93
+
94
+ /** Every business of the account, page by page. `more` is true when the account has more than
95
+ * were read. Throws when the first page cannot be read; a later page that fails ends the list
96
+ * with what was read, marked `more`, so one bad page does not hide every business. */
97
+ async function allSites(): Promise<{ sites: WixSite[]; more: boolean }> {
98
+ const sites: WixSite[] = [];
99
+ let cursor = "";
100
+ for (let page = 0; page < MAX_PAGES; page++) {
101
+ let res: Awaited<ReturnType<typeof querySites>>;
102
+ try {
103
+ res = await querySites({ query: { cursorPaging: cursor ? { limit: PAGE_SIZE, cursor } : { limit: PAGE_SIZE } } });
104
+ } catch (e) {
105
+ if (page === 0) throw e;
106
+ return { sites, more: true };
107
+ }
108
+ sites.push(...(res.sites ?? []));
109
+ const meta = res.metadata as { hasNext?: boolean; cursors?: { next?: string } } | undefined;
110
+ if (!meta?.hasNext) return { sites, more: false };
111
+ const next = typeof meta.cursors?.next === "string" ? meta.cursors.next : "";
112
+ // More is promised with no way to reach it (no cursor, or the same one again): the list is partial.
113
+ if (!next || next === cursor) return { sites, more: true };
114
+ cursor = next;
115
+ }
116
+ return { sites, more: true };
117
+ }
118
+
119
+ type SpaceAnswer = { ok: true; rows: SiteRow[] } | { ok: false; reason: string };
120
+
121
+ /** The owner's Space websites as rows. A failure is its own answer, never an empty list: that
122
+ * Symphony could not be asked says nothing about which Spaces the owner has, so the caller keeps
123
+ * the rows it already shows. */
124
+ async function spaceRows(): Promise<SpaceAnswer> {
125
+ const api = (globalThis as { himalaya?: { wixApi?: MaestroWixApi } }).himalaya?.wixApi;
126
+ if (!api) return { ok: false, reason: "no Wix bridge" };
127
+ try {
128
+ return { ok: true, rows: (await spaceWebsites(api)).map(spaceRow) };
129
+ } catch (e) {
130
+ return { ok: false, reason: String((e as Error)?.message ?? e) };
131
+ }
132
+ }
133
+
134
+ /** Symphony's answer to the latest load, or null while it has given none. */
135
+ let answeredSpaces: SiteRow[] | null = null;
136
+ /** Counts loads: an answer to an earlier load (a retry overtook it, or the session changed) is dropped. */
137
+ let loadGeneration = 0;
138
+ /** The latest load that has returned its list. While a load is still running its own result will
139
+ * carry Symphony's answer, and an action dispatched beside it would be computed from the state
140
+ * the load started with. */
141
+ let settledGeneration = 0;
142
+ /** The local-db partition the latest load read its cache from: where its rows may be cached. */
143
+ let loadPrincipal: string | null = null;
144
+
145
+ /** Space websites first: they are few, and they are the businesses Maestro works for. A site the
146
+ * account's own list also holds is shown once, as the account lists it. */
147
+ function withSpaces(spaces: SiteRow[], own: SiteRow[]): SiteRow[] {
148
+ return [...spaces.filter((w) => !own.some((r) => r.id === w.id)), ...own];
149
+ }
150
+
151
+ /** The line under the search field. */
152
+ function summaryLine(count: number, query: string, more: boolean): string {
153
+ if (query.trim()) return `${count} matching`;
154
+ if (more) return copyTemplate("ownerSites.firstOfMany", "First {count} businesses", { count });
155
+ return `${count} ${count === 1 ? "business" : "businesses"}`;
156
+ }
157
+
158
+ /** A host that cannot bind writes (an older binary, no per-member partition) keeps the write it
159
+ * had before the list was paged: row by row, finished before the list is shown, so it is no
160
+ * likelier than it was to outlive a sign-out. Offline, that host still opens on its businesses. */
161
+ async function writeCachedRowsUnbound(rows: SiteRow[]): Promise<void> {
162
+ try { for (const r of rows) await upsert(ENTITY, r as unknown as DbEntity); } catch { /* capability not granted → online-only */ }
163
+ }
164
+
165
+ /** Bound: best effort and never awaited, so a list of a thousand rows does not wait for its cache. */
166
+ function cacheRows(rows: SiteRow[], bound: string): void {
167
+ void writeCachedRows(rows, bound);
168
+ }
169
+
72
170
  function applySearch(rows: SiteRow[], query: string): SiteRow[] {
73
171
  const q = query.trim().toLowerCase();
74
172
  return q ? rows.filter((r) => r.name.toLowerCase().includes(q)) : rows;
@@ -125,6 +223,7 @@ function shape(s: Partial<SitesState>): SitesState {
125
223
  hideContent: status !== "ready" || sites.length === 0,
126
224
  demoNote: s.demoNote ?? "",
127
225
  notDemo: !s.demoNote,
226
+ _more: s._more === true,
128
227
  };
129
228
  }
130
229
 
@@ -147,8 +246,21 @@ function demoList(s: SitesState): SitesState {
147
246
  });
148
247
  }
149
248
 
249
+ /** One load of the list. A load that a newer one replaced while it ran changes nothing: its
250
+ * result would otherwise land after the newer list and take its place (two loads overlap on
251
+ * every open, the worker's own and the screen's). */
150
252
  async function loadList(s: SitesState): Promise<SitesState> {
151
253
  if (isOwnerPreviewDemo()) return demoList(s);
254
+ const generation = ++loadGeneration;
255
+ const result = await loadGenerationOf(s, generation);
256
+ if (generation === loadGeneration) return result;
257
+ return (svc as unknown as { getState?: () => SitesState }).getState?.() ?? result;
258
+ }
259
+
260
+ async function loadGenerationOf(s: SitesState, generation: number): Promise<SitesState> {
261
+ answeredSpaces = null;
262
+ const bound = await principal();
263
+ if (generation === loadGeneration) loadPrincipal = bound;
152
264
  // 1) Instant paint from the on-device cache (offline-safe; empty on first-ever run).
153
265
  const cached = await readCachedRows();
154
266
  const selected = readSelectedSite();
@@ -156,15 +268,59 @@ async function loadList(s: SitesState): Promise<SitesState> {
156
268
  const base = repairedCache.length
157
269
  ? shape({ ...s, status: "ready", allSites: repairedCache, sites: applySearch(repairedCache, s.searchQuery), error: "", demoNote: "" })
158
270
  : s;
271
+ // The Space websites already on screen (a restored state) or last cached: they stay until
272
+ // Symphony answers, so a list that had them never shrinks and grows back.
273
+ const onScreen = (s.allSites ?? []).filter((r) => r.space === true);
274
+ const shownSpaces = onScreen.length ? onScreen : repairedCache.filter((r) => r.space === true);
159
275
  // 2) Revalidate from Wix and refresh the cache.
160
276
  try {
161
- const res = await querySites({ query: { cursorPaging: { limit: 50 } } });
162
- const rows = (res.sites ?? []).filter((r: WixSite) => r?.id).map(normalize);
163
- await writeCachedRows(rows);
164
- return shape({ ...s, status: "ready", allSites: rows, sites: applySearch(rows, s.searchQuery), resultSummary: `${rows.length} ${rows.length === 1 ? "business" : "businesses"}`, error: "", demoNote: "" });
277
+ // Symphony is asked beside the account's list and never waited for: most owners do not use it,
278
+ // and their businesses must not load slower, or fail, because of it. Its answer arrives as
279
+ // `spacesLoaded`. Until then the Space websites this device last saw stay where they were.
280
+ // It can answer before the account's pages are read or after, so it is kept here for this load
281
+ // to use and also delivered as an action for a list already on screen.
282
+ void spaceRows().then((answer) => {
283
+ if (!answer.ok || generation !== loadGeneration) return;
284
+ const spaces = answer.rows;
285
+ answeredSpaces = spaces;
286
+ // Nothing to add and nothing shown to take away: most owners, who have no Space.
287
+ if (settledGeneration !== generation) return; // the running load returns them itself
288
+ if (spaces.length || shownSpaces.length) void svc.spacesLoaded(spaces);
289
+ });
290
+ const listed = await allSites();
291
+ // A newer load took over while the account was read: this one writes nothing and marks
292
+ // nothing, or the newer load's Space answer would be measured against the wrong load.
293
+ if (generation !== loadGeneration) return s;
294
+ const own = listed.sites.filter((r: WixSite) => r?.id).map(normalize);
295
+ let rows = withSpaces(answeredSpaces ?? shownSpaces, own);
296
+ if (bound === null) {
297
+ await writeCachedRowsUnbound(rows);
298
+ if (generation !== loadGeneration) return s;
299
+ // Symphony may have answered during that write: the list returned below must hold its answer,
300
+ // because nothing after this line waits, and an answer from here on arrives as `spacesLoaded`.
301
+ rows = withSpaces(answeredSpaces ?? shownSpaces, own);
302
+ } else {
303
+ cacheRows(rows, bound);
304
+ }
305
+ const sites = applySearch(rows, s.searchQuery);
306
+ settledGeneration = generation;
307
+ return shape({ ...s, status: "ready", allSites: rows, sites, resultSummary: summaryLine(sites.length, s.searchQuery, listed.more), error: "", demoNote: "", _more: listed.more });
165
308
  } catch (e) {
166
309
  // Offline / fetch failure: keep the last-synced cache BEFORE the demo/error fallbacks.
167
- if (repairedCache.length) return base;
310
+ if (repairedCache.length) {
311
+ // Symphony can still answer when the account's list cannot be read. An answer already here
312
+ // goes into the cached list now, and a later one arrives as `spacesLoaded`.
313
+ // Only for the load that is still the current one: `answeredSpaces` and the settled mark
314
+ // belong to the newest load, and an older one failing late must not take or move them.
315
+ if (generation !== loadGeneration) return base;
316
+ settledGeneration = generation;
317
+ if (answeredSpaces === null) return base;
318
+ const rows = withSpaces(answeredSpaces, repairedCache.filter((r) => r.space !== true));
319
+ if (bound !== null) cacheRows(rows, bound);
320
+ const sites = applySearch(rows, s.searchQuery);
321
+ // A cached list that was partial stays partial: `_more` came with the state.
322
+ return shape({ ...base, allSites: rows, sites, resultSummary: summaryLine(sites.length, s.searchQuery, base._more), emptyText: undefined });
323
+ }
168
324
  if (ownerDemoFallback(e)) return demoList(s);
169
325
  return shape({ ...s, status: "error", allSites: [], sites: [], error: ownerLoadError(e) });
170
326
  }
@@ -179,6 +335,7 @@ const svc = defineService<SitesState, {
179
335
  load: (s: SitesState, arg?: unknown) => Promise<SitesState>;
180
336
  retry: (s: SitesState) => Promise<SitesState>;
181
337
  search: (s: SitesState, arg?: unknown) => Promise<SitesState>;
338
+ spacesLoaded: (s: SitesState, arg?: unknown) => SitesState;
182
339
  pick: (s: SitesState, arg?: unknown) => SitesState;
183
340
  }>("himiOwnerLiteSites", {
184
341
  state: shape({ status: "loading" }),
@@ -197,7 +354,20 @@ const svc = defineService<SitesState, {
197
354
  search: async (s, arg) => {
198
355
  const q = typeof arg === "string" ? arg : String((arg as { value?: string; query?: string })?.value ?? (arg as { query?: string })?.query ?? "");
199
356
  const sites = applySearch(s.allSites, q);
200
- return shape({ ...s, searchQuery: q, sites, resultSummary: q.trim() ? `${sites.length} matching` : `${sites.length} ${sites.length === 1 ? "business" : "businesses"}`, emptyText: sites.length ? "" : emptyFor(q) });
357
+ return shape({ ...s, searchQuery: q, sites, resultSummary: summaryLine(sites.length, q, s._more), emptyText: sites.length ? "" : emptyFor(q) });
358
+ },
359
+ // Symphony's answer to `load`: the owner's Space websites, replacing the ones shown so far.
360
+ // Ignored while the list is not the account's own (still loading, failed, or sample data).
361
+ spacesLoaded: (s, arg) => {
362
+ if (s.status !== "ready" || s.demoNote) return s;
363
+ const spaces = (Array.isArray(arg) ? arg : []) as SiteRow[];
364
+ const rows = withSpaces(spaces, s.allSites.filter((r) => r.space !== true));
365
+ if (rows.length === s.allSites.length && rows.every((r, i) => r.id === s.allSites[i].id && r.name === s.allSites[i].name)) return s;
366
+ // Only a bound write: this arrives after the list is shown, when an unbound one could land
367
+ // in the next owner's cache. An unbindable host caches the Space rows on its next load.
368
+ if (loadPrincipal !== null) cacheRows(rows, loadPrincipal);
369
+ const sites = applySearch(rows, s.searchQuery);
370
+ return shape({ ...s, allSites: rows, sites, resultSummary: summaryLine(sites.length, s.searchQuery, s._more), emptyText: sites.length ? "" : emptyFor(s.searchQuery) });
201
371
  },
202
372
  },
203
373
  });
@@ -11,3 +11,6 @@ export const get: typeof db.get = async (...args) => isOwnerPreviewLive() ? null
11
11
  export const upsert: typeof db.upsert = async (...args) => { if (!isOwnerPreviewLive()) await db.upsert(...args); };
12
12
  export const remove: typeof db.remove = async (...args) => { if (!isOwnerPreviewLive()) await db.remove(...args); };
13
13
  export const enqueue: typeof db.enqueue = async (...args) => { if (!isOwnerPreviewLive()) await db.enqueue(...args); };
14
+
15
+ export const batch: typeof db.batch = async (...args) => { if (!isOwnerPreviewLive()) await db.batch(...args); };
16
+ export const principal: typeof db.principal = async () => db.principal();
@@ -18,7 +18,7 @@ export const forSymphonyAccount = (metaSiteId: string): Record<string, string> =
18
18
  ({ "wix-site-id": metaSiteId, "Content-Type": "application/json" });
19
19
 
20
20
  interface Recipient { recipient?: { metaSiteId?: string } | null }
21
- interface Spaces { workspaces?: Array<{ website?: { metaSiteId?: string } | null }> }
21
+ interface Spaces { workspaces?: Array<{ name?: string; website?: { metaSiteId?: string; name?: string } | null }> }
22
22
 
23
23
  /** The owner's Symphony metasite, or "" when they have no Symphony account. Throws when the
24
24
  * service could not be asked. */
@@ -34,6 +34,29 @@ export async function isSpaceWebsite(api: MaestroWixApi, account: string, site:
34
34
  return (res?.workspaces ?? []).some((w) => w?.website?.metaSiteId === site);
35
35
  }
36
36
 
37
+ export interface SpaceWebsite { id: string; name: string; space: string }
38
+
39
+ /** The websites of the owner's Spaces, one per site. Empty when they have no Symphony account.
40
+ * Throws when it could not be asked.
41
+ *
42
+ * A Space's website belongs to the Symphony account, not to the owner's own Wix account, so the
43
+ * account's site list never holds it (measured live 2026-11-27: 142 sites listed, neither Space
44
+ * website among them). */
45
+ export async function spaceWebsites(api: MaestroWixApi): Promise<SpaceWebsite[]> {
46
+ const account = await symphonyAccount(api);
47
+ if (!account) return [];
48
+ const res = (await api.call("POST", SPACES, {}, forSymphonyAccount(account))) as Spaces | null;
49
+ const out: SpaceWebsite[] = [];
50
+ for (const w of res?.workspaces ?? []) {
51
+ const id = typeof w?.website?.metaSiteId === "string" ? w.website.metaSiteId.trim() : "";
52
+ if (!id || out.some((s) => s.id === id)) continue;
53
+ const space = typeof w?.name === "string" ? w.name.trim() : "";
54
+ const name = typeof w.website?.name === "string" ? w.website.name.trim() : "";
55
+ out.push({ id, name: name || space, space });
56
+ }
57
+ return out;
58
+ }
59
+
37
60
  /** Why a host cannot run a Maestro turn, or "" when it can.
38
61
  *
39
62
  * `old_host`: built before it could read a stream of JSON lines, so a turn delivers nothing.