@wix/himalaya-cli 0.1898.0 → 0.1900.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 (125) hide show
  1. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/core/sdk/app-info/src/index.d.ts +1 -1
  2. package/dist/browser-plane/assets.json +5 -5
  3. package/dist/browser-plane/preview-deferred/{3c8ce407707a87e172345007371329f9c47e65e182a1e2ff617b7f75e6bb95ab.bin → e8580dd7946999b652493628a07600d2e5a0c7864cc0a8a807b8a20903f0698d.bin} +1 -1
  4. package/dist/browser-plane/sw.js +9 -9
  5. package/dist/cli.mjs +75771 -74157
  6. package/dist/preview-assets.generated.bin +0 -0
  7. package/guides/ads.md +91 -0
  8. package/guides/himi-json-output.md +37 -2
  9. package/guides/index.json +6 -0
  10. package/guides/release-notes.md +10 -0
  11. package/package.json +2 -2
  12. package/templates/beauty-salon-owner/config.ts +32 -1
  13. package/templates/beauty-salon-owner/dev/index.ts +565 -1
  14. package/templates/beauty-salon-owner/himalaya.content.json +3 -0
  15. package/templates/beauty-salon-owner/tier5-src/_shared/owner-maestro-availability.ts +14 -0
  16. package/templates/beauty-salon-owner/tier5-src/_shared/owner-maestro-chat.ts +179 -0
  17. package/templates/beauty-salon-owner/tier5-src/_shared/owner-maestro-tab.ts +42 -0
  18. package/templates/beauty-salon-owner/tier5-src/himi-owner-lite-maestro/index.ts +345 -48
  19. package/templates/beauty-salon-owner/tier5-src/himi-owner-lite-maestro-history/index.ts +106 -0
  20. package/templates/beauty-salon-owner/tier5-src/himi-owner-lite-order/index.ts +5 -0
  21. package/templates/beauty-salon-owner/tier5-src/himi-owner-lite-record/index.ts +9 -3
  22. package/templates/beauty-salon-owner/tier5-src/wix-owner-booking/index.ts +9 -3
  23. package/templates/community-club-owner/config.ts +32 -1
  24. package/templates/community-club-owner/dev/index.ts +538 -1
  25. package/templates/community-club-owner/himalaya.content.json +3 -0
  26. package/templates/community-club-owner/tier5-src/_shared/owner-maestro-availability.ts +14 -0
  27. package/templates/community-club-owner/tier5-src/_shared/owner-maestro-chat.ts +179 -0
  28. package/templates/community-club-owner/tier5-src/_shared/owner-maestro-tab.ts +42 -0
  29. package/templates/community-club-owner/tier5-src/himi-owner-lite-maestro/index.ts +345 -48
  30. package/templates/community-club-owner/tier5-src/himi-owner-lite-maestro-history/index.ts +106 -0
  31. package/templates/community-club-owner/tier5-src/himi-owner-lite-order/index.ts +5 -0
  32. package/templates/community-club-owner/tier5-src/himi-owner-lite-record/index.ts +9 -3
  33. package/templates/events-meetups-owner/config.ts +32 -1
  34. package/templates/events-meetups-owner/dev/index.ts +511 -1
  35. package/templates/events-meetups-owner/himalaya.content.json +3 -0
  36. package/templates/events-meetups-owner/tier5-src/_shared/owner-maestro-availability.ts +14 -0
  37. package/templates/events-meetups-owner/tier5-src/_shared/owner-maestro-chat.ts +179 -0
  38. package/templates/events-meetups-owner/tier5-src/_shared/owner-maestro-tab.ts +42 -0
  39. package/templates/events-meetups-owner/tier5-src/himi-owner-lite-maestro/index.ts +345 -48
  40. package/templates/events-meetups-owner/tier5-src/himi-owner-lite-maestro-history/index.ts +106 -0
  41. package/templates/events-meetups-owner/tier5-src/himi-owner-lite-record/index.ts +9 -3
  42. package/templates/gym-fitness-owner/config.ts +32 -1
  43. package/templates/gym-fitness-owner/dev/index.ts +565 -1
  44. package/templates/gym-fitness-owner/himalaya.content.json +3 -0
  45. package/templates/gym-fitness-owner/tier5-src/_shared/owner-maestro-availability.ts +14 -0
  46. package/templates/gym-fitness-owner/tier5-src/_shared/owner-maestro-chat.ts +179 -0
  47. package/templates/gym-fitness-owner/tier5-src/_shared/owner-maestro-tab.ts +42 -0
  48. package/templates/gym-fitness-owner/tier5-src/himi-owner-lite-maestro/index.ts +345 -48
  49. package/templates/gym-fitness-owner/tier5-src/himi-owner-lite-maestro-history/index.ts +106 -0
  50. package/templates/gym-fitness-owner/tier5-src/himi-owner-lite-order/index.ts +5 -0
  51. package/templates/gym-fitness-owner/tier5-src/himi-owner-lite-record/index.ts +9 -3
  52. package/templates/gym-fitness-owner/tier5-src/wix-owner-booking/index.ts +9 -3
  53. package/templates/nonprofit-cause-owner/config.ts +32 -1
  54. package/templates/nonprofit-cause-owner/dev/index.ts +538 -1
  55. package/templates/nonprofit-cause-owner/himalaya.content.json +3 -0
  56. package/templates/nonprofit-cause-owner/tier5-src/_shared/owner-maestro-availability.ts +14 -0
  57. package/templates/nonprofit-cause-owner/tier5-src/_shared/owner-maestro-chat.ts +179 -0
  58. package/templates/nonprofit-cause-owner/tier5-src/_shared/owner-maestro-tab.ts +42 -0
  59. package/templates/nonprofit-cause-owner/tier5-src/himi-owner-lite-maestro/index.ts +345 -48
  60. package/templates/nonprofit-cause-owner/tier5-src/himi-owner-lite-maestro-history/index.ts +106 -0
  61. package/templates/nonprofit-cause-owner/tier5-src/himi-owner-lite-record/index.ts +9 -3
  62. package/templates/nonprofit-cause-owner/tier5-src/wix-owner-booking/index.ts +9 -3
  63. package/templates/owner-lite/config.ts +32 -1
  64. package/templates/owner-lite/dev/index.ts +565 -1
  65. package/templates/owner-lite/himalaya.content.json +3 -0
  66. package/templates/owner-lite/tier5-src/_shared/owner-maestro-availability.ts +14 -0
  67. package/templates/owner-lite/tier5-src/_shared/owner-maestro-chat.ts +179 -0
  68. package/templates/owner-lite/tier5-src/_shared/owner-maestro-tab.ts +42 -0
  69. package/templates/owner-lite/tier5-src/himi-owner-lite-maestro/index.ts +345 -48
  70. package/templates/owner-lite/tier5-src/himi-owner-lite-maestro-history/index.ts +106 -0
  71. package/templates/owner-lite/tier5-src/himi-owner-lite-order/index.ts +5 -0
  72. package/templates/owner-lite/tier5-src/himi-owner-lite-record/index.ts +9 -3
  73. package/templates/owner-lite/tier5-src/wix-owner-booking/index.ts +9 -3
  74. package/templates/podcast-creator-owner/config.ts +32 -1
  75. package/templates/podcast-creator-owner/dev/index.ts +538 -1
  76. package/templates/podcast-creator-owner/himalaya.content.json +3 -0
  77. package/templates/podcast-creator-owner/tier5-src/_shared/owner-maestro-availability.ts +14 -0
  78. package/templates/podcast-creator-owner/tier5-src/_shared/owner-maestro-chat.ts +179 -0
  79. package/templates/podcast-creator-owner/tier5-src/_shared/owner-maestro-tab.ts +42 -0
  80. package/templates/podcast-creator-owner/tier5-src/himi-owner-lite-maestro/index.ts +345 -48
  81. package/templates/podcast-creator-owner/tier5-src/himi-owner-lite-maestro-history/index.ts +106 -0
  82. package/templates/podcast-creator-owner/tier5-src/himi-owner-lite-order/index.ts +5 -0
  83. package/templates/podcast-creator-owner/tier5-src/himi-owner-lite-record/index.ts +9 -3
  84. package/templates/portfolio-creative-owner/config.ts +32 -1
  85. package/templates/portfolio-creative-owner/dev/index.ts +565 -1
  86. package/templates/portfolio-creative-owner/himalaya.content.json +3 -0
  87. package/templates/portfolio-creative-owner/tier5-src/_shared/owner-maestro-availability.ts +14 -0
  88. package/templates/portfolio-creative-owner/tier5-src/_shared/owner-maestro-chat.ts +179 -0
  89. package/templates/portfolio-creative-owner/tier5-src/_shared/owner-maestro-tab.ts +42 -0
  90. package/templates/portfolio-creative-owner/tier5-src/himi-owner-lite-maestro/index.ts +345 -48
  91. package/templates/portfolio-creative-owner/tier5-src/himi-owner-lite-maestro-history/index.ts +106 -0
  92. package/templates/portfolio-creative-owner/tier5-src/himi-owner-lite-order/index.ts +5 -0
  93. package/templates/portfolio-creative-owner/tier5-src/himi-owner-lite-record/index.ts +9 -3
  94. package/templates/portfolio-creative-owner/tier5-src/wix-owner-booking/index.ts +9 -3
  95. package/templates/restaurant-owner/config.ts +32 -1
  96. package/templates/restaurant-owner/dev/index.ts +565 -1
  97. package/templates/restaurant-owner/himalaya.content.json +3 -0
  98. package/templates/restaurant-owner/tier5-src/_shared/owner-maestro-availability.ts +14 -0
  99. package/templates/restaurant-owner/tier5-src/_shared/owner-maestro-chat.ts +179 -0
  100. package/templates/restaurant-owner/tier5-src/_shared/owner-maestro-tab.ts +42 -0
  101. package/templates/restaurant-owner/tier5-src/himi-owner-lite-maestro/index.ts +345 -48
  102. package/templates/restaurant-owner/tier5-src/himi-owner-lite-maestro-history/index.ts +106 -0
  103. package/templates/restaurant-owner/tier5-src/himi-owner-lite-order/index.ts +5 -0
  104. package/templates/restaurant-owner/tier5-src/himi-owner-lite-record/index.ts +9 -3
  105. package/templates/restaurant-owner/tier5-src/wix-owner-booking/index.ts +9 -3
  106. package/templates/retail-store-owner/config.ts +32 -1
  107. package/templates/retail-store-owner/dev/index.ts +538 -1
  108. package/templates/retail-store-owner/himalaya.content.json +3 -0
  109. package/templates/retail-store-owner/tier5-src/_shared/owner-maestro-availability.ts +14 -0
  110. package/templates/retail-store-owner/tier5-src/_shared/owner-maestro-chat.ts +179 -0
  111. package/templates/retail-store-owner/tier5-src/_shared/owner-maestro-tab.ts +42 -0
  112. package/templates/retail-store-owner/tier5-src/himi-owner-lite-maestro/index.ts +345 -48
  113. package/templates/retail-store-owner/tier5-src/himi-owner-lite-maestro-history/index.ts +106 -0
  114. package/templates/retail-store-owner/tier5-src/himi-owner-lite-order/index.ts +5 -0
  115. package/templates/retail-store-owner/tier5-src/himi-owner-lite-record/index.ts +9 -3
  116. package/templates/yoga-studio-owner/config.ts +32 -1
  117. package/templates/yoga-studio-owner/dev/index.ts +538 -1
  118. package/templates/yoga-studio-owner/himalaya.content.json +3 -0
  119. package/templates/yoga-studio-owner/tier5-src/_shared/owner-maestro-availability.ts +14 -0
  120. package/templates/yoga-studio-owner/tier5-src/_shared/owner-maestro-chat.ts +179 -0
  121. package/templates/yoga-studio-owner/tier5-src/_shared/owner-maestro-tab.ts +42 -0
  122. package/templates/yoga-studio-owner/tier5-src/himi-owner-lite-maestro/index.ts +345 -48
  123. package/templates/yoga-studio-owner/tier5-src/himi-owner-lite-maestro-history/index.ts +106 -0
  124. package/templates/yoga-studio-owner/tier5-src/himi-owner-lite-record/index.ts +9 -3
  125. package/templates/yoga-studio-owner/tier5-src/wix-owner-booking/index.ts +9 -3
@@ -13,6 +13,12 @@
13
13
  // 3. A conversation is tied to the business ONCE, at creation: `metadata.wixSiteId`.
14
14
  // 4. A turn is one streamed request (a `_stream` directive with `format: "ndjson"`): the live Symphony
15
15
  // send answers newline-delimited JSON, one {type, data} per line.
16
+ // 5. Two of Symphony's cards are drawn: a decision Maestro is waiting on (approve or decline)
17
+ // and a link that connects a service. No card capability is declared in a turn, so Maestro
18
+ // puts every other card into words.
19
+ //
20
+ // The screen also opens in two other ways: on a past chat (`conversationId`, from the history
21
+ // screen) and about one item of the business (`kind` + `id`, from that item's detail screen).
16
22
  //
17
23
  // (1) or (2) failing is not an error: it is the rule that sends the owner to Aria instead. A new
18
24
  // Symphony account needs a verified phone, so it cannot be created silently from here.
@@ -24,7 +30,12 @@ import { get as appInfo } from "@himalaya/app-info";
24
30
  import { deviceTimeZone } from "../_shared/engine-intl.js";
25
31
  import { copyParam, stashCopy } from "../_shared/himi-copy.js";
26
32
  import { readSelectedSite } from "../_shared/owner-selected-site.js";
27
- import { forSymphonyAccount, maestroAvailability } from "../_shared/owner-maestro-availability.js";
33
+ import { forSymphonyAccount, hostCannotRunMaestro, maestroAvailability, type HostCannotRunMaestro } from "../_shared/owner-maestro-availability.js";
34
+ import {
35
+ chatDecisions, chatMessages, decisionIdsOf, linkCardOf, replyText, sendVerdict,
36
+ type Decision, type LinkCard, type Verdict,
37
+ } from "../_shared/owner-maestro-chat.js";
38
+ import { open as openUrl } from "@himalaya/open-url";
28
39
 
29
40
  const SERVICE = "himiOwnerLiteMaestro";
30
41
  /** The screen this worker paints: message rows are stamped `<screen>.message_<id>`. */
@@ -49,22 +60,101 @@ function activeSiteId(): string {
49
60
  }
50
61
 
51
62
 
63
+ /** One transcript row: the owner's turn, Maestro's reply, the thinking line, or a card. The
64
+ * `*Hidden` flags pick which part of the one row template shows. */
52
65
  export interface Bubble {
53
66
  id: string;
54
67
  content: string;
55
68
  userHidden: string;
56
69
  assistantHidden: string;
57
70
  thinkingHidden: string;
71
+ cardHidden: string;
72
+ cardTitle: string;
73
+ cardText: string;
74
+ /** How a card ended, or why it cannot be answered here ("" collapses the line). */
75
+ cardStatus: string;
76
+ primaryLabel: string;
77
+ primaryHidden: string;
78
+ secondaryLabel: string;
79
+ secondaryHidden: string;
80
+ /** A link card's target. */
81
+ url: string;
82
+ /** A decision card's decision, the id its answer is sent under, and the plan it was read at. */
83
+ decisionId: string;
84
+ verdictId: string;
85
+ planVersion: string;
86
+ }
87
+ const NO_CARD = {
88
+ cardHidden: "true", cardTitle: "", cardText: "", cardStatus: "", primaryLabel: "", primaryHidden: "true",
89
+ secondaryLabel: "", secondaryHidden: "true", url: "", decisionId: "", verdictId: "", planVersion: "",
90
+ } as const;
91
+ const userBubble = (id: string, content: string): Bubble => ({ ...NO_CARD, id, content, userHidden: "false", assistantHidden: "true", thinkingHidden: "true" });
92
+ const assistantBubble = (id: string, content: string): Bubble => ({ ...NO_CARD, id, content, userHidden: "true", assistantHidden: "false", thinkingHidden: "true" });
93
+ const thinkingBubble = (): Bubble => ({ ...NO_CARD, id: THINKING_ID, content: "", userHidden: "true", assistantHidden: "true", thinkingHidden: "false" });
94
+ const cardBubble = (id: string, card: Partial<Bubble>): Bubble =>
95
+ ({ ...NO_CARD, id, content: "", userHidden: "true", assistantHidden: "true", thinkingHidden: "true", cardHidden: "false", ...card });
96
+
97
+ const linkRowId = (link: LinkCard): string => `link_${link.url}`;
98
+ function linkBubble(link: LinkCard): Bubble {
99
+ return cardBubble(linkRowId(link), {
100
+ cardTitle: copy.connectTitle(link.name), cardText: copy.connectText(),
101
+ primaryLabel: copy.connect(), primaryHidden: "false", url: link.url,
102
+ });
103
+ }
104
+
105
+ const decisionRowId = (decisionId: string): string => `decision_${decisionId}`;
106
+ /** A decision as a card. `verdictId` survives a redraw, so a retry sends the same one. */
107
+ function decisionBubble(d: Decision, verdictId: string): Bubble {
108
+ const answerable = d.open && !d.hasOptions;
109
+ const status = !d.open ? (d.resolution === "ACCEPTED" ? copy.approved() : d.resolution === "REFUSED" ? copy.declined() : copy.settled())
110
+ : d.hasOptions ? copy.answerInSymphony() : "";
111
+ return cardBubble(decisionRowId(d.id), {
112
+ cardTitle: d.question || copy.decisionTitle(), cardText: d.detail, cardStatus: status,
113
+ primaryLabel: copy.approve(), primaryHidden: answerable ? "false" : "true",
114
+ secondaryLabel: copy.decline(), secondaryHidden: answerable ? "false" : "true",
115
+ decisionId: d.id, verdictId, planVersion: d.planVersion,
116
+ });
117
+ }
118
+ /** A decision whose question could not be read: it is named, and answered in Symphony. */
119
+ function unreadDecisionBubble(decisionId: string): Bubble {
120
+ return cardBubble(decisionRowId(decisionId), { cardTitle: copy.decisionTitle(), cardStatus: copy.decisionUnread(), decisionId });
121
+ }
122
+
123
+ /** An id in the shape Symphony's own clients mint for a verdict. */
124
+ function newVerdictId(): string {
125
+ const hex = (n: number): string => Array.from({ length: n }, () => Math.floor(Math.random() * 16).toString(16)).join("");
126
+ return `${hex(8)}-${hex(4)}-4${hex(3)}-a${hex(3)}-${hex(12)}`;
127
+ }
128
+
129
+ /** Add the cards a turn or a past message named, replacing a card already drawn for the same
130
+ * decision or link. */
131
+ function withCards(messages: Bubble[], cards: Bubble[]): Bubble[] {
132
+ const fresh = new Map(cards.map((c) => [c.id, c]));
133
+ const kept = messages.map((b) => {
134
+ const next = fresh.get(b.id);
135
+ if (!next) return b;
136
+ fresh.delete(b.id);
137
+ return next.decisionId ? { ...next, verdictId: b.verdictId || next.verdictId } : next;
138
+ });
139
+ return [...kept, ...fresh.values()];
140
+ }
141
+
142
+ /** The decision cards for `ids`, read from Symphony. A read that fails still names each one. */
143
+ async function decisionCards(api: WixApi, conversationId: string, ids: string[]): Promise<Bubble[]> {
144
+ if (!ids.length) return [];
145
+ try {
146
+ const byId = new Map((await chatDecisions(api, conversationId)).map((d) => [d.id, d]));
147
+ return ids.map((id) => { const d = byId.get(id); return d ? decisionBubble(d, newVerdictId()) : unreadDecisionBubble(id); });
148
+ } catch {
149
+ return ids.map(unreadDecisionBubble);
150
+ }
58
151
  }
59
- const userBubble = (id: string, content: string): Bubble => ({ id, content, userHidden: "false", assistantHidden: "true", thinkingHidden: "true" });
60
- const assistantBubble = (id: string, content: string): Bubble => ({ id, content, userHidden: "true", assistantHidden: "false", thinkingHidden: "true" });
61
- const thinkingBubble = (): Bubble => ({ id: THINKING_ID, content: "", userHidden: "true", assistantHidden: "true", thinkingHidden: "false" });
62
152
 
63
153
  export interface QuickReply { id: string; label: string; askId: string }
64
154
  export interface Prompt { id: string; title: string; text: string }
65
155
 
66
156
  /** Why Maestro cannot be used here. Each one sends the owner to Aria. */
67
- type Unavailable = "" | "no_site" | "no_account" | "not_connected" | "unreachable" | "needs_update";
157
+ type Unavailable = "" | "no_site" | "no_account" | "not_connected" | "unreachable" | "needs_update" | "not_on_web";
68
158
 
69
159
  export interface MaestroState {
70
160
  /** `checking` until the account and the Space are known. */
@@ -87,6 +177,8 @@ export interface MaestroState {
87
177
  idle: boolean;
88
178
  /** What Maestro is doing right now ("" collapses the line). */
89
179
  statusText: string;
180
+ /** The item this chat was opened about ("" collapses the line). */
181
+ contextLabel: string;
90
182
  error: string;
91
183
  /** Changes on every send: the host's transcript scroll follows the new turn. */
92
184
  scrollSend: string;
@@ -100,13 +192,41 @@ export interface MaestroState {
100
192
  /** Role of the segment currently streaming, and the bubble it appends to. */
101
193
  _role: string;
102
194
  _openId: string;
195
+ /** The open reply as Maestro streamed it, before it is made drawable. */
196
+ _openRaw: string;
103
197
  _turn: number;
198
+ /** What a turn tells Maestro about the item on screen: prose only the model reads. */
199
+ _context: string;
200
+ /** Decisions this turn named. Read once the turn ends, since reading them takes a call. */
201
+ _decisionIds: string[];
202
+ /** The past chat this one was opened on, and the item it was opened about ("" for neither). */
203
+ _resumedId: string;
204
+ _askKey: string;
104
205
  }
105
206
 
106
207
  const copy = {
107
208
  greeting: () => copyParam("ownerMaestro.greeting", "Hi, I'm Maestro. Ask me to check on your business or to get something done."),
108
209
  thinking: () => copyParam("ownerMaestro.thinking", "Maestro is working on it…"),
109
210
  failed: () => copyParam("ownerMaestro.failed", "Maestro couldn't answer. Try again in a moment."),
211
+ historyFailed: () => copyParam("ownerMaestro.historyFailed", "That conversation couldn't be opened. Try again in a moment."),
212
+ connectTitle: (name: string) => copyParam("ownerMaestro.connect.title", "Connect {name}").replace("{name}", name),
213
+ connectText: () => copyParam("ownerMaestro.connect.text", "Maestro needs this connection to continue."),
214
+ connect: () => copyParam("ownerMaestro.connect.action", "Connect"),
215
+ decisionTitle: () => copyParam("ownerMaestro.decision.title", "Maestro is waiting on your decision"),
216
+ decisionUnread: () => copyParam("ownerMaestro.decision.unread", "This decision couldn't be loaded here. Answer it in Symphony."),
217
+ answerInSymphony: () => copyParam("ownerMaestro.decision.inSymphony", "This one has several options. Answer it in Symphony."),
218
+ approve: () => copyParam("ownerMaestro.decision.approve", "Approve"),
219
+ decline: () => copyParam("ownerMaestro.decision.decline", "Decline"),
220
+ approved: () => copyParam("ownerMaestro.decision.approved", "Approved"),
221
+ declined: () => copyParam("ownerMaestro.decision.declined", "Declined"),
222
+ settled: () => copyParam("ownerMaestro.decision.settled", "Already answered"),
223
+ verdictFailed: () => copyParam("ownerMaestro.decision.failed", "Maestro didn't get your answer. Try again."),
224
+ about: (kind: string, subject: string) => {
225
+ const what = kind === "order" ? copyParam("ownerMaestro.about.order", "this order")
226
+ : kind === "booking" ? copyParam("ownerMaestro.about.booking", "this booking")
227
+ : copyParam("ownerMaestro.about.contact", "this contact");
228
+ return copyParam("ownerMaestro.about", "About {item}").replace("{item}", subject || what);
229
+ },
110
230
  unavailable: (why: Unavailable): { title: string; text: string } => {
111
231
  if (why === "not_connected") {
112
232
  return {
@@ -126,6 +246,12 @@ const copy = {
126
246
  text: copyParam("ownerMaestro.needsUpdate.text", "This version of the app can't show Maestro's replies. Until you update, Aria can help."),
127
247
  };
128
248
  }
249
+ if (why === "not_on_web") {
250
+ return {
251
+ title: copyParam("ownerMaestro.notOnWeb.title", "Maestro isn't in the web app yet"),
252
+ text: copyParam("ownerMaestro.notOnWeb.text", "Use Maestro in the mobile app. Here, Aria can help."),
253
+ };
254
+ }
129
255
  if (why === "unreachable") {
130
256
  return {
131
257
  title: copyParam("ownerMaestro.unreachable.title", "Maestro can't be reached right now"),
@@ -151,19 +277,46 @@ const initial: MaestroState = {
151
277
  phase: "checking", checkingHidden: "false", chatHidden: "true", unavailableHidden: "true",
152
278
  unavailableTitle: "", unavailableText: "",
153
279
  messages: [], emptyHidden: "false", prompts: [], quickReplies: [], quickRepliesHidden: "true",
154
- input: "", hasInput: false, noInput: true, busy: false, idle: true, statusText: "", error: "", scrollSend: "", scrollAnchor: "", ok: false,
155
- _site: "", _account: "", _convId: "", _role: "", _openId: "", _turn: 0,
280
+ input: "", hasInput: false, noInput: true, busy: false, idle: true, statusText: "", contextLabel: "", error: "", scrollSend: "", scrollAnchor: "", ok: false,
281
+ _site: "", _account: "", _convId: "", _role: "", _openId: "", _openRaw: "", _turn: 0, _context: "", _decisionIds: [], _resumedId: "", _askKey: "",
282
+ };
283
+
284
+ const inputString = (key: string): string => {
285
+ const v = host().input?.[key];
286
+ return typeof v === "string" ? v.trim() : "";
156
287
  };
157
288
 
158
- /** Whether this host can read a streamed turn. `unknown` when the host could not be asked this
159
- * time: that is not a "no", and it is asked again on the next load. */
160
- type ReadsTurns = "yes" | "no" | "unknown";
161
- let readsTurns: "yes" | "no" | undefined;
162
- async function hostReadsTurns(): Promise<ReadsTurns> {
163
- if (readsTurns === undefined) {
164
- try { readsTurns = (await appInfo()).ndjsonStreamAvailable === true ? "yes" : "no"; } catch { return "unknown"; }
289
+ /** The item a detail screen opened this chat about. Only an order, a booking or a contact, and
290
+ * only with an id: the id is what Maestro looks the item up by. */
291
+ function askedAbout(): { key: string; label: string; context: string } | null {
292
+ const kind = inputString("kind");
293
+ const id = inputString("id");
294
+ if (!id || (kind !== "order" && kind !== "booking" && kind !== "contact")) return null;
295
+ const subject = inputString("subject").slice(0, 80);
296
+ return {
297
+ key: `${kind}:${id}`,
298
+ label: copy.about(kind, subject),
299
+ context: `The owner opened this chat from the Owner app's ${kind} screen. It is about the ${kind} with id ${id}${subject ? ` ("${subject}")` : ""}. Unless they say otherwise, their questions are about that ${kind}.`,
300
+ };
301
+ }
302
+
303
+ // What the owner left with New chat. A screen pushed from history or from an item keeps its
304
+ // input for as long as it lives, and `load` runs on every appear: without these the chat they
305
+ // left would come back the next time the screen appeared. What the screen is showing is in the
306
+ // state (`_resumedId`, `_askKey`), not here: `load` also runs once as the bundle boots, and both
307
+ // runs must reach the same answer.
308
+ let leftPastChat = "";
309
+ let leftAsk = "";
310
+
311
+ /** Whether this host can run a turn, and why not when it cannot. `unknown` when the host could
312
+ * not be asked this time: that is not a "no", and it is asked again on the next load. */
313
+ type RunsTurns = HostCannotRunMaestro | "unknown";
314
+ let runsTurns: HostCannotRunMaestro | undefined;
315
+ async function hostRunsTurns(): Promise<RunsTurns> {
316
+ if (runsTurns === undefined) {
317
+ try { runsTurns = hostCannotRunMaestro(await appInfo()); } catch { return "unknown"; }
165
318
  }
166
- return readsTurns;
319
+ return runsTurns;
167
320
  }
168
321
 
169
322
  function unavailable(s: MaestroState, why: Unavailable): MaestroState {
@@ -174,9 +327,12 @@ function unavailable(s: MaestroState, why: Unavailable): MaestroState {
174
327
  };
175
328
  }
176
329
 
177
- async function createConversation(api: WixApi, account: string, site: string): Promise<string> {
330
+ /** A chat is named after its first message, which is what the history list shows. */
331
+ const chatName = (firstMessage: string): string => firstMessage.replace(/\s+/g, " ").trim().slice(0, 60) || "Owner app";
332
+
333
+ async function createConversation(api: WixApi, account: string, site: string, firstMessage: string): Promise<string> {
178
334
  const res = (await api.call("POST", CONVERSATIONS, {
179
- conversation: { source: "SCHEDULER", communicationChannel: "APP", name: "Owner app", metadata: { wixSiteId: site } },
335
+ conversation: { source: "SCHEDULER", communicationChannel: "APP", name: chatName(firstMessage), metadata: { wixSiteId: site } },
180
336
  }, forSymphonyAccount(account))) as { conversation?: { id?: string } } | null;
181
337
  const id = res?.conversation?.id;
182
338
  return typeof id === "string" ? id : "";
@@ -196,6 +352,7 @@ function streamDirective(s: MaestroState, text: string, choice?: { askId: string
196
352
  conversationId: s._convId, messageText: text, role: "USER", clientCapabilities: [],
197
353
  deviceTimeZone: deviceTimeZone(), adoptsConversationId: true, communicationChannel: "APP",
198
354
  ...(choice ? { choiceAnswer: choice } : {}),
355
+ ...(s._context ? { context: s._context } : {}),
199
356
  },
200
357
  },
201
358
  onEvent: "streamEvent",
@@ -210,6 +367,13 @@ const settled = (messages: Bubble[]): Bubble[] => messages.filter((b) => b.id !=
210
367
  // awaits its conversation before `busy` can be stored, so a second send dispatched meanwhile
211
368
  // would pass the `busy` guard and open a second conversation. This flag closes that window.
212
369
  let opening = false;
370
+ // The same window for a card: its answer awaits Symphony, and a send dispatched meanwhile would
371
+ // be overwritten by the card's result.
372
+ let deciding = false;
373
+ // And for a read that ends in a result built from the state it started with: a past chat being
374
+ // opened, or a finished turn's decision cards. Counted, since two can overlap (Stop, then the
375
+ // stream's own end). While it is above zero no send and no card answer starts.
376
+ let reading = 0;
213
377
  // What the owner did while that conversation was being opened. The send's result is built from
214
378
  // the state it was dispatched with, so a draft typed or a New chat tapped meanwhile would be
215
379
  // overwritten by it; these let the result be rebased onto them (as Aria's `draftSeq` does).
@@ -220,13 +384,17 @@ let chatSeq = 0;
220
384
  const freshChat = (s: MaestroState, input = ""): MaestroState => ({
221
385
  ...s, messages: [], emptyHidden: "false", quickReplies: [], quickRepliesHidden: "true",
222
386
  input, hasInput: input.trim().length > 0, noInput: input.trim().length === 0,
223
- busy: false, idle: true, statusText: "", error: "", scrollSend: "", scrollAnchor: "",
224
- _convId: "", _role: "", _openId: "",
387
+ busy: false, idle: true, statusText: "", contextLabel: "", error: "", scrollSend: "", scrollAnchor: "",
388
+ _convId: "", _role: "", _openId: "", _openRaw: "", _context: "", _decisionIds: [], _resumedId: "", _askKey: "",
225
389
  });
226
390
 
391
+ /** `s` with the draft the owner typed while an action was waiting on Symphony. */
392
+ const withDraftSince = (s: MaestroState, seq: number): MaestroState =>
393
+ (draftSeq === seq ? s : { ...s, input: draft, hasInput: draft.trim().length > 0, noInput: draft.trim().length === 0 });
394
+
227
395
  async function send(s: MaestroState, raw: string, choice?: { askId: string; optionId: string }): Promise<MaestroState & { _stream?: unknown }> {
228
396
  const text = (raw ?? "").trim();
229
- if (!text || s.busy || opening || s.phase !== "ready") return s;
397
+ if (!text || s.busy || opening || deciding || reading || s.phase !== "ready") return s;
230
398
  const api = host().wixApi;
231
399
  if (!api) return { ...s, error: copy.failed() };
232
400
  let convId = s._convId;
@@ -234,7 +402,7 @@ async function send(s: MaestroState, raw: string, choice?: { askId: string; opti
234
402
  const chatAtSend = chatSeq;
235
403
  if (!convId) {
236
404
  opening = true;
237
- try { convId = await createConversation(api, s._account, s._site); } catch { convId = ""; } finally { opening = false; }
405
+ try { convId = await createConversation(api, s._account, s._site, text); } catch { convId = ""; } finally { opening = false; }
238
406
  // New chat was tapped while this one was opening: the owner left it, so no turn starts.
239
407
  if (chatSeq !== chatAtSend) return freshChat(s, draft);
240
408
  const typed = draftSeq !== draftAtSend ? { input: draft, hasInput: draft.trim().length > 0, noInput: draft.trim().length === 0 } : {};
@@ -243,7 +411,7 @@ async function send(s: MaestroState, raw: string, choice?: { askId: string; opti
243
411
  const typedMeanwhile = draftSeq !== draftAtSend;
244
412
  const turn = s._turn + 1;
245
413
  const next: MaestroState = {
246
- ...s, _convId: convId, _turn: turn, _role: "", _openId: "",
414
+ ...s, _convId: convId, _turn: turn, _role: "", _openId: "", _openRaw: "", _decisionIds: [],
247
415
  messages: [...settled(s.messages), userBubble(`u${turn}`, text), thinkingBubble()],
248
416
  emptyHidden: "true", quickReplies: [], quickRepliesHidden: "true",
249
417
  input: "", hasInput: false, noInput: true, busy: true, idle: false,
@@ -260,7 +428,7 @@ interface StreamEvent {
260
428
  data?: {
261
429
  role?: string; deltaText?: string; text?: string; conversationId?: string;
262
430
  choices?: { askId?: string; options?: Array<{ id?: string; label?: string }> };
263
- };
431
+ } & Record<string, unknown>;
264
432
  }
265
433
 
266
434
  function quickRepliesOf(data: StreamEvent["data"]): QuickReply[] {
@@ -272,9 +440,86 @@ function quickRepliesOf(data: StreamEvent["data"]): QuickReply[] {
272
440
  }
273
441
 
274
442
  const finished = (s: MaestroState): MaestroState => ({
275
- ...s, messages: settled(s.messages), busy: false, idle: true, statusText: "", _role: "", _openId: "",
443
+ ...s, messages: settled(s.messages), busy: false, idle: true, statusText: "", _role: "", _openId: "", _openRaw: "", _decisionIds: [],
276
444
  });
277
445
 
446
+ /** End the turn in flight, however it ended: finished, failed or stopped. A decision Maestro
447
+ * raised before the end is still waiting on the owner, so its card is read and drawn in all
448
+ * three. `reading` keeps a send from starting meanwhile: this result would overwrite it. */
449
+ async function endTurn(s: MaestroState, error = ""): Promise<MaestroState> {
450
+ const ended = { ...finished(s), error: error || s.error };
451
+ const api = host().wixApi;
452
+ if (!s._decisionIds.length || !api) return ended;
453
+ const chatAtStart = chatSeq;
454
+ const draftAtStart = draftSeq;
455
+ reading += 1;
456
+ let cards: Bubble[];
457
+ try { cards = await decisionCards(api, s._convId, s._decisionIds); } finally { reading -= 1; }
458
+ if (chatSeq !== chatAtStart) return freshChat(s, draft);
459
+ const next = withDraftSince(ended, draftAtStart);
460
+ return { ...next, messages: withCards(next.messages, cards) };
461
+ }
462
+
463
+ /** The cards one event names: a link is drawn at once, a decision is noted for the turn's end. */
464
+ function withEventCards(s: MaestroState, data: Record<string, unknown>): MaestroState {
465
+ const link = linkCardOf(data);
466
+ const ids = decisionIdsOf(data).filter((id) => !s._decisionIds.includes(id));
467
+ if (!link && !ids.length) return s;
468
+ return {
469
+ ...s,
470
+ messages: link ? withCards(s.messages, [linkBubble(link)]) : s.messages,
471
+ _decisionIds: [...s._decisionIds, ...ids],
472
+ };
473
+ }
474
+
475
+ /** Open a past chat: its turns and replies, and the cards its messages carried. */
476
+ async function resume(api: WixApi, s: MaestroState, conversationId: string): Promise<MaestroState> {
477
+ const past = await chatMessages(api, conversationId);
478
+ let messages: Bubble[] = [];
479
+ const decisionIds: string[] = [];
480
+ for (const m of past) {
481
+ if (m.text.trim()) messages.push(m.role === "USER" ? userBubble(`h_${m.id}`, m.text) : assistantBubble(`h_${m.id}`, replyText(m.text)));
482
+ if (m.link) messages = withCards(messages, [linkBubble(m.link)]);
483
+ for (const id of m.decisionIds) if (!decisionIds.includes(id)) decisionIds.push(id);
484
+ }
485
+ messages = withCards(messages, await decisionCards(api, conversationId, decisionIds));
486
+ return { ...freshChat(s), _convId: conversationId, messages, emptyHidden: messages.length ? "true" : "false" };
487
+ }
488
+
489
+ /** Answer a decision card. Refused while a turn streams: the card's result is built from the
490
+ * state it was dispatched with and would overwrite what the turn streamed meanwhile. */
491
+ async function decide(s: MaestroState, id: string, resolution: Verdict): Promise<MaestroState> {
492
+ const card = s.messages.find((b) => b.id === id);
493
+ if (!card?.decisionId || card.primaryHidden === "true" || s.busy || opening || deciding || reading) return s;
494
+ const api = host().wixApi;
495
+ if (!api) return { ...s, error: copy.verdictFailed() };
496
+ const draftAtStart = draftSeq;
497
+ const chatAtStart = chatSeq;
498
+ deciding = true;
499
+ let settledAs: Decision | null = null;
500
+ let failed = false;
501
+ let reread: Bubble | undefined;
502
+ try {
503
+ settledAs = await sendVerdict(api, {
504
+ decisionId: card.decisionId, verdictId: card.verdictId, resolution, planVersion: card.planVersion, conversationId: s._convId,
505
+ });
506
+ // Symphony refused the answer: the decision moved on (a newer plan, or settled elsewhere).
507
+ // The same answer would be refused again, so the card is read anew and gets a new verdict id.
508
+ if (!settledAs) [reread] = await decisionCards(api, s._convId, [card.decisionId]);
509
+ } catch { failed = true; } finally { deciding = false; }
510
+ // New chat was tapped meanwhile: the card is gone, and the answer already went to Symphony.
511
+ if (chatSeq !== chatAtStart) return freshChat(s, draft);
512
+ const base = withDraftSince(s, draftAtStart);
513
+ if (failed) return { ...base, error: copy.verdictFailed() };
514
+ if (!settledAs) {
515
+ // A re-read that failed names the decision only: the card on screen says more, so it stays.
516
+ const usable = reread && reread.cardStatus !== copy.decisionUnread();
517
+ return { ...base, error: copy.verdictFailed(), messages: usable ? base.messages.map((b) => (b.id === id ? reread! : b)) : base.messages };
518
+ }
519
+ const shown: Decision = { ...settledAs, question: settledAs.question || card.cardTitle, detail: settledAs.detail || card.cardText, open: false, resolution: settledAs.resolution || resolution };
520
+ return { ...base, error: "", messages: withCards(base.messages, [decisionBubble(shown, card.verdictId)]) };
521
+ }
522
+
278
523
  type Arg = string | { value?: unknown; message?: string; text?: string; id?: string } | undefined;
279
524
  const textOf = (arg: Arg): string => {
280
525
  if (typeof arg === "string") return arg;
@@ -290,6 +535,8 @@ const svc = defineService<MaestroState, {
290
535
  answer: (s: MaestroState, arg?: Arg) => Promise<MaestroState>;
291
536
  stop: (s: MaestroState) => Promise<MaestroState>;
292
537
  newChat: (s: MaestroState) => Promise<MaestroState>;
538
+ cardPrimary: (s: MaestroState, arg?: Arg) => Promise<MaestroState>;
539
+ cardSecondary: (s: MaestroState, arg?: Arg) => Promise<MaestroState>;
293
540
  streamEvent: (s: MaestroState, ev?: StreamEvent) => Promise<MaestroState>;
294
541
  streamDone: (s: MaestroState) => Promise<MaestroState>;
295
542
  streamFailed: (s: MaestroState) => Promise<MaestroState>;
@@ -297,7 +544,7 @@ const svc = defineService<MaestroState, {
297
544
  state: initial,
298
545
  // A turn lives only as long as its stream. Restored after an app kill, `busy` and the thinking
299
546
  // bubble would describe a stream that no longer exists and the composer would refuse every send.
300
- notHydrated: ["busy", "idle", "statusText", "error", "scrollSend", "scrollAnchor", "_role", "_openId", "quickReplies", "quickRepliesHidden"],
547
+ notHydrated: ["busy", "idle", "statusText", "error", "scrollSend", "scrollAnchor", "_role", "_openId", "_openRaw", "_decisionIds", "quickReplies", "quickRepliesHidden"],
301
548
  actions: {
302
549
  // Runs on every appear. A conversation belongs to one business, so a switch starts over;
303
550
  // returning to the same business keeps the transcript.
@@ -305,27 +552,59 @@ const svc = defineService<MaestroState, {
305
552
  stashCopy(arg);
306
553
  const site = activeSiteId();
307
554
  const fresh: MaestroState = { ...initial, _site: site, prompts: prompts() };
308
- // A turn arrives as a stream of JSON lines. A host built before it could read one delivers
309
- // nothing, so every send would end in the failure message: say so instead of offering a chat.
555
+ // A turn arrives as a stream of JSON lines. On a host that cannot run one every send would
556
+ // end in the failure message: say so instead of offering a chat.
310
557
  // Asked before a stored `ready` is trusted: an old host may have saved one.
311
- const reads = await hostReadsTurns();
312
- if (reads === "no") return unavailable(fresh, "needs_update");
558
+ const reads = await hostRunsTurns();
559
+ if (reads === "old_host") return unavailable(fresh, "needs_update");
560
+ if (reads === "deployed_web") return unavailable(fresh, "not_on_web");
561
+ const api = host().wixApi;
562
+ let ready: MaestroState;
313
563
  if (s.phase === "ready" && s._site === site && site) {
314
564
  // No turn in flight means no thinking bubble: one restored from a killed run is dropped.
315
- return { ...s, prompts: prompts(), messages: s.busy ? s.messages : settled(s.messages) };
565
+ // A chat saved by a build without cards has rows with no card fields, and a missing
566
+ // "hidden" reads as shown: each row is completed so no empty card is drawn.
567
+ const rows = (s.busy ? s.messages : settled(s.messages)).map((b) => ({ ...NO_CARD, ...b }));
568
+ ready = { ...s, prompts: prompts(), messages: rows };
569
+ } else {
570
+ // The host could not say. A chat already open is kept (above); a new one is not opened.
571
+ if (reads === "unknown") return unavailable(fresh, "unreachable");
572
+ if (!site) return unavailable(fresh, "no_site");
573
+ if (!api) return unavailable(fresh, "unreachable");
574
+ try {
575
+ const answer = await maestroAvailability(api, site);
576
+ if (!answer.available) return unavailable(fresh, answer.why);
577
+ ready = { ...fresh, phase: "ready", checkingHidden: "true", chatHidden: "false", _account: answer.account };
578
+ } catch {
579
+ return unavailable(fresh, "unreachable");
580
+ }
316
581
  }
317
- // The host could not say. A chat already open is kept (above); a new one is not opened.
318
- if (reads === "unknown") return unavailable(fresh, "unreachable");
319
- if (!site) return unavailable(fresh, "no_site");
320
- const api = host().wixApi;
321
- if (!api) return unavailable(fresh, "unreachable");
322
- try {
323
- const answer = await maestroAvailability(api, site);
324
- if (!answer.available) return unavailable(fresh, answer.why);
325
- return { ...fresh, phase: "ready", checkingHidden: "true", chatHidden: "false", _account: answer.account };
326
- } catch {
327
- return unavailable(fresh, "unreachable");
582
+ // Opened on a past chat, or about one item. A chat already showing it is kept, and one the
583
+ // owner left with New chat does not come back. Neither interrupts a turn that is streaming.
584
+ if (ready.busy || opening || deciding) return ready;
585
+ // One request to open a past chat: History stamps each list it shows, so tapping the same
586
+ // chat again is a new request, while the screen appearing again is the same one. A request
587
+ // is acted on once, whether it opened the chat or failed to.
588
+ const past = inputString("conversationId");
589
+ const pastKey = past ? `${past}#${inputString("n")}` : "";
590
+ if (past && pastKey !== leftPastChat && pastKey !== ready._resumedId) {
591
+ if (!api) return { ...ready, _resumedId: pastKey, error: copy.historyFailed() };
592
+ const chatAtStart = chatSeq;
593
+ const draftAtStart = draftSeq;
594
+ // No send or card answer starts while the chat is read: this result would overwrite it.
595
+ reading += 1;
596
+ try {
597
+ const opened = { ...(await resume(api, ready, past)), _resumedId: pastKey };
598
+ return chatSeq !== chatAtStart ? freshChat(ready, draft) : withDraftSince(opened, draftAtStart);
599
+ } catch {
600
+ return chatSeq !== chatAtStart ? freshChat(ready, draft) : { ...withDraftSince(ready, draftAtStart), _resumedId: pastKey, error: copy.historyFailed() };
601
+ } finally { reading -= 1; }
602
+ }
603
+ const ask = past ? null : askedAbout();
604
+ if (ask && ask.key !== leftAsk && ask.key !== ready._askKey) {
605
+ return { ...freshChat(ready, ready.input), contextLabel: ask.label, _context: ask.context, _askKey: ask.key };
328
606
  }
607
+ return ready;
329
608
  },
330
609
  setInput: async (s, arg) => {
331
610
  const input = textOf(arg);
@@ -348,14 +627,29 @@ const svc = defineService<MaestroState, {
348
627
  },
349
628
  // Local only, as in the Symphony iOS app: the turn keeps running on the server, and what it
350
629
  // still streams is dropped because nothing is in flight here any more.
351
- stop: async (s) => (s.busy ? finished(s) : s),
630
+ stop: async (s) => (s.busy ? endTurn(s) : s),
352
631
  newChat: async (s) => {
353
632
  if (s.phase !== "ready") return s;
354
633
  chatSeq += 1;
355
634
  draftSeq += 1;
356
635
  draft = "";
636
+ leftPastChat = s._resumedId || leftPastChat;
637
+ leftAsk = s._askKey || leftAsk;
357
638
  return freshChat(s);
358
639
  },
640
+ // A card's one or two buttons. What they do depends on the card.
641
+ cardPrimary: async (s, arg) => {
642
+ const id = typeof arg === "object" ? arg?.id ?? "" : "";
643
+ const card = s.messages.find((b) => b.id === id);
644
+ if (!card) return s;
645
+ if (card.url) {
646
+ // Opening a link changes nothing here: Maestro learns of the connection on its side.
647
+ try { await openUrl(card.url); } catch { /* the host refused to open it: the card stays */ }
648
+ return s;
649
+ }
650
+ return decide(s, id, "ACCEPTED");
651
+ },
652
+ cardSecondary: async (s, arg) => decide(s, typeof arg === "object" ? arg?.id ?? "" : "", "REFUSED"),
359
653
  streamEvent: async (s, ev) => {
360
654
  if (!s.busy) return s; // stopped, or a turn that already ended
361
655
  const data = ev?.data ?? {};
@@ -380,20 +674,23 @@ const svc = defineService<MaestroState, {
380
674
  const messages = settled(s.messages);
381
675
  const open = messages.findIndex((b) => b.id === s._openId);
382
676
  if (open >= 0) {
383
- messages[open] = { ...messages[open], content: messages[open].content + delta };
384
- return { ...s, messages, statusText: "" };
677
+ const raw = s._openRaw + delta;
678
+ messages[open] = { ...messages[open], content: replyText(raw) };
679
+ return { ...s, messages, _openRaw: raw, statusText: "" };
385
680
  }
386
681
  const id = `a${s._turn}_${messages.length}`;
387
- return { ...s, messages: [...messages, assistantBubble(id, delta)], _openId: id, statusText: "" };
682
+ return { ...s, messages: [...messages, assistantBubble(id, replyText(delta))], _openId: id, _openRaw: delta, statusText: "" };
388
683
  }
389
684
  if (ev?.type === "messageEnd") {
390
685
  const replies = quickRepliesOf(data);
391
- return { ...s, _openId: "", quickReplies: replies, quickRepliesHidden: replies.length ? "false" : "true" };
686
+ return withEventCards({ ...s, _openId: "", _openRaw: "", quickReplies: replies, quickRepliesHidden: replies.length ? "false" : "true" }, data);
392
687
  }
688
+ // The same cards, sent ahead of the reply.
689
+ if (ev?.type === "cards") return withEventCards(s, data);
393
690
  return s;
394
691
  },
395
- streamDone: async (s) => (s.busy ? finished(s) : s),
396
- streamFailed: async (s) => (s.busy ? { ...finished(s), error: copy.failed() } : s),
692
+ streamDone: async (s) => (s.busy ? endTurn(s) : s),
693
+ streamFailed: async (s) => (s.busy ? endTurn(s, copy.failed()) : s),
397
694
  },
398
695
  });
399
696