@wix/himalaya-cli 0.1936.0 → 0.1938.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.
- package/package.json +2 -2
- package/templates/beauty-salon-owner/config.ts +12 -2
- package/templates/beauty-salon-owner/dev/index.ts +1200 -69
- package/templates/beauty-salon-owner/tier5-src/_shared/owner-maestro-chat.ts +168 -16
- package/templates/beauty-salon-owner/tier5-src/_shared/owner-maestro-kinds.ts +28 -0
- package/templates/beauty-salon-owner/tier5-src/_shared/owner-maestro-tab.ts +47 -4
- package/templates/beauty-salon-owner/tier5-src/himi-owner-lite-maestro/index.ts +529 -70
- package/templates/beauty-salon-owner/tier5-src/himi-owner-lite-maestro-history/index.ts +147 -17
- package/templates/beauty-salon-owner/tier5-src/himi-owner-lite-post/index.ts +12 -1
- package/templates/beauty-salon-owner/tier5-src/himi-owner-lite-product/index.ts +12 -1
- package/templates/beauty-salon-owner/tier5-src/himi-owner-lite-record/index.ts +3 -3
- package/templates/beauty-salon-owner/tier5-src/himi-owner-lite-service/index.ts +12 -1
- package/templates/community-club-owner/config.ts +12 -2
- package/templates/community-club-owner/dev/index.ts +1200 -69
- package/templates/community-club-owner/tier5-src/_shared/owner-maestro-chat.ts +168 -16
- package/templates/community-club-owner/tier5-src/_shared/owner-maestro-kinds.ts +28 -0
- package/templates/community-club-owner/tier5-src/_shared/owner-maestro-tab.ts +47 -4
- package/templates/community-club-owner/tier5-src/himi-owner-lite-event/index.ts +12 -1
- package/templates/community-club-owner/tier5-src/himi-owner-lite-maestro/index.ts +529 -70
- package/templates/community-club-owner/tier5-src/himi-owner-lite-maestro-history/index.ts +147 -17
- package/templates/community-club-owner/tier5-src/himi-owner-lite-post/index.ts +12 -1
- package/templates/community-club-owner/tier5-src/himi-owner-lite-product/index.ts +12 -1
- package/templates/community-club-owner/tier5-src/himi-owner-lite-record/index.ts +3 -3
- package/templates/events-meetups-owner/config.ts +12 -2
- package/templates/events-meetups-owner/dev/index.ts +1178 -69
- package/templates/events-meetups-owner/tier5-src/_shared/owner-maestro-chat.ts +168 -16
- package/templates/events-meetups-owner/tier5-src/_shared/owner-maestro-kinds.ts +28 -0
- package/templates/events-meetups-owner/tier5-src/_shared/owner-maestro-tab.ts +47 -4
- package/templates/events-meetups-owner/tier5-src/himi-owner-lite-event/index.ts +12 -1
- package/templates/events-meetups-owner/tier5-src/himi-owner-lite-maestro/index.ts +529 -70
- package/templates/events-meetups-owner/tier5-src/himi-owner-lite-maestro-history/index.ts +147 -17
- package/templates/events-meetups-owner/tier5-src/himi-owner-lite-post/index.ts +12 -1
- package/templates/events-meetups-owner/tier5-src/himi-owner-lite-record/index.ts +3 -3
- package/templates/gym-fitness-owner/config.ts +12 -2
- package/templates/gym-fitness-owner/dev/index.ts +1222 -69
- package/templates/gym-fitness-owner/tier5-src/_shared/owner-maestro-chat.ts +168 -16
- package/templates/gym-fitness-owner/tier5-src/_shared/owner-maestro-kinds.ts +28 -0
- package/templates/gym-fitness-owner/tier5-src/_shared/owner-maestro-tab.ts +47 -4
- package/templates/gym-fitness-owner/tier5-src/himi-owner-lite-event/index.ts +12 -1
- package/templates/gym-fitness-owner/tier5-src/himi-owner-lite-maestro/index.ts +529 -70
- package/templates/gym-fitness-owner/tier5-src/himi-owner-lite-maestro-history/index.ts +147 -17
- package/templates/gym-fitness-owner/tier5-src/himi-owner-lite-post/index.ts +12 -1
- package/templates/gym-fitness-owner/tier5-src/himi-owner-lite-product/index.ts +12 -1
- package/templates/gym-fitness-owner/tier5-src/himi-owner-lite-record/index.ts +3 -3
- package/templates/gym-fitness-owner/tier5-src/himi-owner-lite-service/index.ts +12 -1
- package/templates/nonprofit-cause-owner/config.ts +12 -2
- package/templates/nonprofit-cause-owner/dev/index.ts +1200 -69
- package/templates/nonprofit-cause-owner/tier5-src/_shared/owner-maestro-chat.ts +168 -16
- package/templates/nonprofit-cause-owner/tier5-src/_shared/owner-maestro-kinds.ts +28 -0
- package/templates/nonprofit-cause-owner/tier5-src/_shared/owner-maestro-tab.ts +47 -4
- package/templates/nonprofit-cause-owner/tier5-src/himi-owner-lite-event/index.ts +12 -1
- package/templates/nonprofit-cause-owner/tier5-src/himi-owner-lite-maestro/index.ts +529 -70
- package/templates/nonprofit-cause-owner/tier5-src/himi-owner-lite-maestro-history/index.ts +147 -17
- package/templates/nonprofit-cause-owner/tier5-src/himi-owner-lite-post/index.ts +12 -1
- package/templates/nonprofit-cause-owner/tier5-src/himi-owner-lite-record/index.ts +3 -3
- package/templates/nonprofit-cause-owner/tier5-src/himi-owner-lite-service/index.ts +12 -1
- package/templates/owner-lite/config.ts +12 -2
- package/templates/owner-lite/dev/index.ts +1222 -69
- package/templates/owner-lite/tier5-src/_shared/owner-maestro-chat.ts +168 -16
- package/templates/owner-lite/tier5-src/_shared/owner-maestro-kinds.ts +28 -0
- package/templates/owner-lite/tier5-src/_shared/owner-maestro-tab.ts +47 -4
- package/templates/owner-lite/tier5-src/himi-owner-lite-event/index.ts +12 -1
- package/templates/owner-lite/tier5-src/himi-owner-lite-maestro/index.ts +529 -70
- package/templates/owner-lite/tier5-src/himi-owner-lite-maestro-history/index.ts +147 -17
- package/templates/owner-lite/tier5-src/himi-owner-lite-post/index.ts +12 -1
- package/templates/owner-lite/tier5-src/himi-owner-lite-product/index.ts +12 -1
- package/templates/owner-lite/tier5-src/himi-owner-lite-record/index.ts +3 -3
- package/templates/owner-lite/tier5-src/himi-owner-lite-service/index.ts +12 -1
- package/templates/podcast-creator-owner/config.ts +12 -2
- package/templates/podcast-creator-owner/dev/index.ts +1200 -69
- package/templates/podcast-creator-owner/tier5-src/_shared/owner-maestro-chat.ts +168 -16
- package/templates/podcast-creator-owner/tier5-src/_shared/owner-maestro-kinds.ts +28 -0
- package/templates/podcast-creator-owner/tier5-src/_shared/owner-maestro-tab.ts +47 -4
- package/templates/podcast-creator-owner/tier5-src/himi-owner-lite-event/index.ts +12 -1
- package/templates/podcast-creator-owner/tier5-src/himi-owner-lite-maestro/index.ts +529 -70
- package/templates/podcast-creator-owner/tier5-src/himi-owner-lite-maestro-history/index.ts +147 -17
- package/templates/podcast-creator-owner/tier5-src/himi-owner-lite-post/index.ts +12 -1
- package/templates/podcast-creator-owner/tier5-src/himi-owner-lite-product/index.ts +12 -1
- package/templates/podcast-creator-owner/tier5-src/himi-owner-lite-record/index.ts +3 -3
- package/templates/portfolio-creative-owner/config.ts +12 -2
- package/templates/portfolio-creative-owner/dev/index.ts +1200 -69
- package/templates/portfolio-creative-owner/tier5-src/_shared/owner-maestro-chat.ts +168 -16
- package/templates/portfolio-creative-owner/tier5-src/_shared/owner-maestro-kinds.ts +28 -0
- package/templates/portfolio-creative-owner/tier5-src/_shared/owner-maestro-tab.ts +47 -4
- package/templates/portfolio-creative-owner/tier5-src/himi-owner-lite-maestro/index.ts +529 -70
- package/templates/portfolio-creative-owner/tier5-src/himi-owner-lite-maestro-history/index.ts +147 -17
- package/templates/portfolio-creative-owner/tier5-src/himi-owner-lite-post/index.ts +12 -1
- package/templates/portfolio-creative-owner/tier5-src/himi-owner-lite-product/index.ts +12 -1
- package/templates/portfolio-creative-owner/tier5-src/himi-owner-lite-record/index.ts +3 -3
- package/templates/portfolio-creative-owner/tier5-src/himi-owner-lite-service/index.ts +12 -1
- package/templates/restaurant-owner/config.ts +12 -2
- package/templates/restaurant-owner/dev/index.ts +1222 -69
- package/templates/restaurant-owner/tier5-src/_shared/owner-maestro-chat.ts +168 -16
- package/templates/restaurant-owner/tier5-src/_shared/owner-maestro-kinds.ts +28 -0
- package/templates/restaurant-owner/tier5-src/_shared/owner-maestro-tab.ts +47 -4
- package/templates/restaurant-owner/tier5-src/himi-owner-lite-event/index.ts +12 -1
- package/templates/restaurant-owner/tier5-src/himi-owner-lite-maestro/index.ts +529 -70
- package/templates/restaurant-owner/tier5-src/himi-owner-lite-maestro-history/index.ts +147 -17
- package/templates/restaurant-owner/tier5-src/himi-owner-lite-post/index.ts +12 -1
- package/templates/restaurant-owner/tier5-src/himi-owner-lite-product/index.ts +12 -1
- package/templates/restaurant-owner/tier5-src/himi-owner-lite-record/index.ts +3 -3
- package/templates/restaurant-owner/tier5-src/himi-owner-lite-service/index.ts +12 -1
- package/templates/retail-store-owner/config.ts +12 -2
- package/templates/retail-store-owner/dev/index.ts +1178 -69
- package/templates/retail-store-owner/tier5-src/_shared/owner-maestro-chat.ts +168 -16
- package/templates/retail-store-owner/tier5-src/_shared/owner-maestro-kinds.ts +28 -0
- package/templates/retail-store-owner/tier5-src/_shared/owner-maestro-tab.ts +47 -4
- package/templates/retail-store-owner/tier5-src/himi-owner-lite-maestro/index.ts +529 -70
- package/templates/retail-store-owner/tier5-src/himi-owner-lite-maestro-history/index.ts +147 -17
- package/templates/retail-store-owner/tier5-src/himi-owner-lite-post/index.ts +12 -1
- package/templates/retail-store-owner/tier5-src/himi-owner-lite-product/index.ts +12 -1
- package/templates/retail-store-owner/tier5-src/himi-owner-lite-record/index.ts +3 -3
- package/templates/yoga-studio-owner/config.ts +12 -2
- package/templates/yoga-studio-owner/dev/index.ts +1200 -69
- package/templates/yoga-studio-owner/tier5-src/_shared/owner-maestro-chat.ts +168 -16
- package/templates/yoga-studio-owner/tier5-src/_shared/owner-maestro-kinds.ts +28 -0
- package/templates/yoga-studio-owner/tier5-src/_shared/owner-maestro-tab.ts +47 -4
- package/templates/yoga-studio-owner/tier5-src/himi-owner-lite-event/index.ts +12 -1
- package/templates/yoga-studio-owner/tier5-src/himi-owner-lite-maestro/index.ts +529 -70
- package/templates/yoga-studio-owner/tier5-src/himi-owner-lite-maestro-history/index.ts +147 -17
- package/templates/yoga-studio-owner/tier5-src/himi-owner-lite-post/index.ts +12 -1
- package/templates/yoga-studio-owner/tier5-src/himi-owner-lite-record/index.ts +3 -3
- package/templates/yoga-studio-owner/tier5-src/himi-owner-lite-service/index.ts +12 -1
|
@@ -31,12 +31,19 @@ import { deviceTimeZone } from "../_shared/engine-intl.js";
|
|
|
31
31
|
import { copyParam, stashCopy } from "../_shared/himi-copy.js";
|
|
32
32
|
import { currentBusinessId } from "../_shared/owner-selected-site.js";
|
|
33
33
|
import { forSymphonyAccount, hostCannotRunMaestro, maestroAvailability, type HostCannotRunMaestro } from "../_shared/owner-maestro-availability.js";
|
|
34
|
-
import { clearAskRequest, isAskMaestroKind, pendingAskRequest, type AskMaestroKind } from "../_shared/owner-maestro-tab.js";
|
|
34
|
+
import { ASK_MAESTRO_NOUNS, askForRecount, clearAskRequest, wasDeleted, isAskMaestroKind, pendingAskRequest, type AskMaestroKind } from "../_shared/owner-maestro-tab.js";
|
|
35
35
|
import {
|
|
36
|
-
chatDecisions,
|
|
37
|
-
type Decision, type LinkCard, type Verdict,
|
|
36
|
+
chatDecisions, chatIsRunning, chatPage, decisionIdsOf, isHttpsUrl, linkCardOf, mintUpload, pastChats, replyText, sendVerdict, stopTurn, uploadedFile, waitingOnOwner,
|
|
37
|
+
type Decision, type LinkCard, type PastMessage, type TurnAttachment, type Verdict, type WaitingAsk,
|
|
38
38
|
} from "../_shared/owner-maestro-chat.js";
|
|
39
39
|
import { open as openUrl } from "@himalaya/open-url";
|
|
40
|
+
import { writeText } from "@himalaya/clipboard";
|
|
41
|
+
import { pickDetailed as pickPhotos } from "@himalaya/photos";
|
|
42
|
+
import { pickDetailed as pickFiles } from "@himalaya/file-picker";
|
|
43
|
+
import { putFile } from "@himalaya/presigned-upload";
|
|
44
|
+
import type { FileHandle } from "@himalaya/sdk-types";
|
|
45
|
+
import { recognizeOnce, stop as stopSpeech } from "@himalaya/speech";
|
|
46
|
+
import { remove as removeFile } from "@himalaya/files";
|
|
40
47
|
|
|
41
48
|
const SERVICE = "himiOwnerLiteMaestro";
|
|
42
49
|
/** The screen this worker paints: message rows are stamped `<screen>.message_<id>`. */
|
|
@@ -83,10 +90,15 @@ export interface Bubble {
|
|
|
83
90
|
decisionId: string;
|
|
84
91
|
verdictId: string;
|
|
85
92
|
planVersion: string;
|
|
93
|
+
/** One option of a decision that asks the owner to choose: a row of its own under the card,
|
|
94
|
+
* with the option's label in `content` and the id an answer names here. */
|
|
95
|
+
optionHidden: string;
|
|
96
|
+
optionId: string;
|
|
86
97
|
}
|
|
87
98
|
const NO_CARD = {
|
|
88
99
|
noteHidden: "true", cardHidden: "true", cardTitle: "", cardText: "", cardStatus: "", primaryLabel: "", primaryHidden: "true",
|
|
89
100
|
secondaryLabel: "", secondaryHidden: "true", url: "", decisionId: "", verdictId: "", planVersion: "",
|
|
101
|
+
optionHidden: "true", optionId: "",
|
|
90
102
|
} as const;
|
|
91
103
|
const userBubble = (id: string, content: string): Bubble => ({ ...NO_CARD, id, content, userHidden: "false", assistantHidden: "true", thinkingHidden: "true" });
|
|
92
104
|
const assistantBubble = (id: string, content: string): Bubble => ({ ...NO_CARD, id, content, userHidden: "true", assistantHidden: "false", thinkingHidden: "true" });
|
|
@@ -105,17 +117,36 @@ function linkBubble(link: LinkCard): Bubble {
|
|
|
105
117
|
}
|
|
106
118
|
|
|
107
119
|
const decisionRowId = (decisionId: string): string => `decision_${decisionId}`;
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
120
|
+
const isOptionRow = (b: Bubble): boolean => b.optionHidden === "false";
|
|
121
|
+
|
|
122
|
+
/** How a decision is answered here. `yesNo`: Approve and Decline. `choose`: one of its options,
|
|
123
|
+
* or Decline. `elsewhere`: it wants the owner's own words, or it names no option that can be
|
|
124
|
+
* answered, so it is answered in Symphony. */
|
|
125
|
+
function answerMode(d: Decision): "yesNo" | "choose" | "elsewhere" {
|
|
126
|
+
if (d.kind === "ANSWER") return "elsewhere";
|
|
127
|
+
if (d.kind === "CHOOSE" || d.hasOptions) return d.options.length ? "choose" : "elsewhere";
|
|
128
|
+
return "yesNo";
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** A decision as rows: its card, then one row per option when it asks the owner to choose.
|
|
132
|
+
* `verdictId` survives a redraw, so a retry sends the same one. */
|
|
133
|
+
function decisionRows(d: Decision, verdictId: string): Bubble[] {
|
|
134
|
+
const mode = d.open ? answerMode(d) : "yesNo";
|
|
135
|
+
const settledAs = d.resolution === "REFUSED" ? copy.declined()
|
|
136
|
+
: d.chosen ? copy.chose(d.chosen)
|
|
137
|
+
: d.resolution === "ACCEPTED" ? copy.approved() : copy.settled();
|
|
138
|
+
const status = !d.open ? settledAs : mode === "elsewhere" ? copy.answerInSymphony() : mode === "choose" ? copy.chooseOne() : "";
|
|
139
|
+
const card = cardBubble(decisionRowId(d.id), {
|
|
114
140
|
cardTitle: d.question || copy.decisionTitle(), cardText: d.detail, cardStatus: status,
|
|
115
|
-
primaryLabel: copy.approve(), primaryHidden:
|
|
116
|
-
secondaryLabel: copy.decline(), secondaryHidden:
|
|
141
|
+
primaryLabel: copy.approve(), primaryHidden: d.open && mode === "yesNo" ? "false" : "true",
|
|
142
|
+
secondaryLabel: copy.decline(), secondaryHidden: d.open && mode !== "elsewhere" ? "false" : "true",
|
|
117
143
|
decisionId: d.id, verdictId, planVersion: d.planVersion,
|
|
118
144
|
});
|
|
145
|
+
if (!d.open || mode !== "choose") return [card];
|
|
146
|
+
return [card, ...d.options.map((o, index): Bubble => ({
|
|
147
|
+
...NO_CARD, id: `option_${d.id}_${index}`, content: o.label, userHidden: "true", assistantHidden: "true", thinkingHidden: "true",
|
|
148
|
+
optionHidden: "false", optionId: o.id, decisionId: d.id, verdictId, planVersion: d.planVersion,
|
|
149
|
+
}))];
|
|
119
150
|
}
|
|
120
151
|
/** A decision whose question could not be read: it is named, and answered in Symphony. */
|
|
121
152
|
function unreadDecisionBubble(decisionId: string): Bubble {
|
|
@@ -129,16 +160,24 @@ function newVerdictId(): string {
|
|
|
129
160
|
}
|
|
130
161
|
|
|
131
162
|
/** Add the cards a turn or a past message named, replacing a card already drawn for the same
|
|
132
|
-
* decision or link.
|
|
163
|
+
* decision or link. A decision's option rows always follow its card, and the rows of an
|
|
164
|
+
* earlier drawing of the same decision go. */
|
|
133
165
|
function withCards(messages: Bubble[], cards: Bubble[]): Bubble[] {
|
|
134
|
-
const fresh = new Map(cards.map((c) => [c.id, c]));
|
|
135
|
-
const
|
|
166
|
+
const fresh = new Map(cards.filter((c) => !isOptionRow(c)).map((c) => [c.id, c]));
|
|
167
|
+
const optionsOf = (decisionId: string): Bubble[] => cards.filter((c) => isOptionRow(c) && c.decisionId === decisionId);
|
|
168
|
+
const redrawn = new Set([...fresh.values()].map((c) => c.decisionId).filter(Boolean));
|
|
169
|
+
const out: Bubble[] = [];
|
|
170
|
+
for (const b of messages) {
|
|
171
|
+
if (isOptionRow(b) && redrawn.has(b.decisionId)) continue;
|
|
136
172
|
const next = fresh.get(b.id);
|
|
137
|
-
if (!next)
|
|
173
|
+
if (!next) { out.push(b); continue; }
|
|
138
174
|
fresh.delete(b.id);
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
175
|
+
// The verdict id of the card on screen is kept, on the card and on its options alike.
|
|
176
|
+
const verdictId = next.decisionId ? b.verdictId || next.verdictId : next.verdictId;
|
|
177
|
+
out.push({ ...next, verdictId }, ...optionsOf(next.decisionId).map((o) => ({ ...o, verdictId })));
|
|
178
|
+
}
|
|
179
|
+
for (const card of fresh.values()) out.push(card, ...(card.decisionId ? optionsOf(card.decisionId) : []));
|
|
180
|
+
return out;
|
|
142
181
|
}
|
|
143
182
|
|
|
144
183
|
/** The decision cards for `ids`, read from Symphony. A read that fails still names each one. */
|
|
@@ -146,13 +185,25 @@ async function decisionCards(api: WixApi, conversationId: string, ids: string[])
|
|
|
146
185
|
if (!ids.length) return [];
|
|
147
186
|
try {
|
|
148
187
|
const byId = new Map((await chatDecisions(api, conversationId)).map((d) => [d.id, d]));
|
|
149
|
-
return ids.
|
|
188
|
+
return ids.flatMap((id) => { const d = byId.get(id); return d ? decisionRows(d, newVerdictId()) : [unreadDecisionBubble(id)]; });
|
|
150
189
|
} catch {
|
|
151
190
|
return ids.map(unreadDecisionBubble);
|
|
152
191
|
}
|
|
153
192
|
}
|
|
154
193
|
|
|
155
|
-
|
|
194
|
+
/** A reply Maestro offers as a chip. One with a `url` opens that link and sends nothing. */
|
|
195
|
+
/** One picked file: uploading, ready to go with the next message, or failed. `file` is set once
|
|
196
|
+
* it is uploaded. `statusText` is "" when ready. */
|
|
197
|
+
export interface AttachmentChip {
|
|
198
|
+
id: string; name: string; statusText: string; state: "uploading" | "ready" | "failed";
|
|
199
|
+
file: TurnAttachment | null;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** How many files one message carries, and how big one may be (the app's own upload bound). */
|
|
203
|
+
const MAX_ATTACHMENTS = 4;
|
|
204
|
+
const MAX_ATTACHMENT_BYTES = 32 * 1024 * 1024;
|
|
205
|
+
|
|
206
|
+
export interface QuickReply { id: string; label: string; askId: string; url: string }
|
|
156
207
|
export interface Prompt { id: string; title: string; text: string }
|
|
157
208
|
|
|
158
209
|
/** Why Maestro cannot be used here. Each one sends the owner to Aria. */
|
|
@@ -206,12 +257,41 @@ export interface MaestroState {
|
|
|
206
257
|
/** The past chat this one was opened on, and the item it was opened about ("" for neither). */
|
|
207
258
|
_resumedId: string;
|
|
208
259
|
_askKey: string;
|
|
260
|
+
/** Whether the turn in flight has shown any sign of running on Symphony's side (an event
|
|
261
|
+
* after the first `metadata`). Symphony can only be told to stop a turn that has started. */
|
|
262
|
+
_started: boolean;
|
|
263
|
+
/** The chat whose turn the owner stopped before it had started: Symphony is told as soon as
|
|
264
|
+
* that turn shows it is running. "" when there is none. */
|
|
265
|
+
_stopPending: string;
|
|
266
|
+
/** Earlier messages of a past chat: the cursor of the page before the oldest one shown ("" =
|
|
267
|
+
* none), and whether the control that loads it shows. */
|
|
268
|
+
_older: string;
|
|
269
|
+
olderHidden: string;
|
|
270
|
+
/** Copy, under the last reply: whether it shows, the reply it last copied, and what it says. */
|
|
271
|
+
copyHidden: string;
|
|
272
|
+
copyNote: string;
|
|
273
|
+
_copied: string;
|
|
274
|
+
/** Dictation: whether the device is listening, and the row that says so (with Done). What is
|
|
275
|
+
* heard lands in the composer for the owner to read and send; it is never sent for them. */
|
|
276
|
+
listening: boolean;
|
|
277
|
+
listeningHidden: string;
|
|
278
|
+
/** Files picked for the next message, as chips above the composer. */
|
|
279
|
+
attachments: AttachmentChip[];
|
|
280
|
+
attachmentsHidden: string;
|
|
281
|
+
/** What Maestro is waiting on the owner for, shown on an empty chat: each opens the chat it is
|
|
282
|
+
* asked in. Symphony keeps these per account, so they are not only this business's. */
|
|
283
|
+
waiting: WaitingAsk[];
|
|
284
|
+
waitingHidden: string;
|
|
285
|
+
/** A past chat Maestro was still working on when it was opened: looked at again until it is
|
|
286
|
+
* done. The chat, and how many looks are left. */
|
|
287
|
+
_watching: string;
|
|
288
|
+
_watchLeft: number;
|
|
209
289
|
}
|
|
210
290
|
|
|
211
291
|
const copy = {
|
|
212
292
|
greeting: () => copyParam("ownerMaestro.greeting", "Hi, I'm Maestro. Ask me to check on your business or to get something done."),
|
|
213
293
|
thinking: () => copyParam("ownerMaestro.working", "Working on it…"),
|
|
214
|
-
stopped: () => copyParam("ownerMaestro.stopped", "You stopped
|
|
294
|
+
stopped: () => copyParam("ownerMaestro.stopped", "You stopped this reply. A step Maestro had already started may still finish."),
|
|
215
295
|
failed: () => copyParam("ownerMaestro.failed", "Maestro couldn't answer. Try again in a moment."),
|
|
216
296
|
historyFailed: () => copyParam("ownerMaestro.historyFailed", "That conversation couldn't be opened. Try again in a moment."),
|
|
217
297
|
connectTitle: (name: string) => copyParam("ownerMaestro.connect.title", "Connect {name}").replace("{name}", name),
|
|
@@ -219,19 +299,27 @@ const copy = {
|
|
|
219
299
|
connect: () => copyParam("ownerMaestro.connect.action", "Connect"),
|
|
220
300
|
decisionTitle: () => copyParam("ownerMaestro.decision.title", "Maestro is waiting on your decision"),
|
|
221
301
|
decisionUnread: () => copyParam("ownerMaestro.decision.unread", "This decision couldn't be loaded here. Answer it in Symphony."),
|
|
222
|
-
answerInSymphony: () => copyParam("ownerMaestro.decision.inSymphony", "This one
|
|
302
|
+
answerInSymphony: () => copyParam("ownerMaestro.decision.inSymphony", "This one needs an answer in your own words. Answer it in Symphony."),
|
|
303
|
+
chooseOne: () => copyParam("ownerMaestro.decision.choose", "Choose one:"),
|
|
304
|
+
copied: () => copyParam("ownerMaestro.copied", "Copied"),
|
|
305
|
+
uploading: () => copyParam("ownerMaestro.attach.uploading", "Uploading…"),
|
|
306
|
+
uploadFailed: () => copyParam("ownerMaestro.attach.failed", "Couldn't upload"),
|
|
307
|
+
tooMany: () => copyParam("ownerMaestro.attach.tooMany", "A message can carry up to {n} files.").replace("{n}", String(MAX_ATTACHMENTS)),
|
|
308
|
+
tooBig: () => copyParam("ownerMaestro.attach.tooBig", "That file is too big to attach."),
|
|
309
|
+
stillUploading: () => copyParam("ownerMaestro.attach.wait", "Wait for the upload to finish, or remove the file."),
|
|
310
|
+
attached: (name: string) => copyParam("ownerMaestro.attach.line", "Attached: {name}").replace("{name}", name),
|
|
311
|
+
stillWorking: () => copyParam("ownerMaestro.stillWorking", "Maestro is still working on this…"),
|
|
312
|
+
olderFailed: () => copyParam("ownerMaestro.olderFailed", "Earlier messages couldn't be loaded. Try again."),
|
|
313
|
+
chose: (label: string) => copyParam("ownerMaestro.decision.chose", "You chose: {option}").replace("{option}", label),
|
|
223
314
|
approve: () => copyParam("ownerMaestro.decision.approve", "Approve"),
|
|
224
315
|
decline: () => copyParam("ownerMaestro.decision.decline", "Decline"),
|
|
225
316
|
approved: () => copyParam("ownerMaestro.decision.approved", "Approved"),
|
|
226
317
|
declined: () => copyParam("ownerMaestro.decision.declined", "Declined"),
|
|
227
318
|
settled: () => copyParam("ownerMaestro.decision.settled", "Already answered"),
|
|
228
319
|
verdictFailed: () => copyParam("ownerMaestro.decision.failed", "Maestro didn't get your answer. Try again."),
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
: copyParam("ownerMaestro.about.contact", "this contact");
|
|
233
|
-
return copyParam("ownerMaestro.about", "About {item}").replace("{item}", subject || what);
|
|
234
|
-
},
|
|
320
|
+
/** The words for one kind of item: "this invoice". Each can be retitled by a copy pack. */
|
|
321
|
+
thisItem: (kind: AskKind) => copyParam(`ownerMaestro.about.${kind}`, `this ${ASK_MAESTRO_NOUNS[kind]}`),
|
|
322
|
+
about: (kind: AskKind, subject: string) => copyParam("ownerMaestro.about", "About {item}").replace("{item}", subject || copy.thisItem(kind)),
|
|
235
323
|
unavailable: (why: Unavailable): { title: string; text: string } => {
|
|
236
324
|
if (why === "not_connected") {
|
|
237
325
|
return {
|
|
@@ -295,6 +383,15 @@ function prompts(kind: AskKind | "" = ""): Prompt[] {
|
|
|
295
383
|
{ id: "p3", title: copyParam("ownerMaestro.contact.p3.title", "Draft a message to them"), text: copyParam("ownerMaestro.contact.p3.text", "Draft a message to this contact and show it to me before sending.") },
|
|
296
384
|
];
|
|
297
385
|
}
|
|
386
|
+
if (kind) {
|
|
387
|
+
// Any other item: the same three questions, in its own words.
|
|
388
|
+
const item = copy.thisItem(kind);
|
|
389
|
+
return [
|
|
390
|
+
{ id: "p1", title: copyParam("ownerMaestro.item.p1.title", "Summarize {item}").replace("{item}", item), text: copyParam("ownerMaestro.item.p1.text", "Summarize {item} for me.").replace("{item}", item) },
|
|
391
|
+
{ id: "p2", title: copyParam("ownerMaestro.item.p2.title", "What does it still need?"), text: copyParam("ownerMaestro.item.p2.text", "What does {item} still need from me?").replace("{item}", item) },
|
|
392
|
+
{ id: "p3", title: copyParam("ownerMaestro.item.p3.title", "What should I do next?"), text: copyParam("ownerMaestro.item.p3.text", "What would you do next about {item}? Show me before doing anything.").replace("{item}", item) },
|
|
393
|
+
];
|
|
394
|
+
}
|
|
298
395
|
return [
|
|
299
396
|
{ id: "p1", title: copyParam("ownerMaestro.p1.title", "Catch me up"), text: copyParam("ownerMaestro.p1.text", "Catch me up on what happened in my business since yesterday.") },
|
|
300
397
|
{ id: "p2", title: copyParam("ownerMaestro.p2.title", "What needs me today?"), text: copyParam("ownerMaestro.p2.text", "What needs my attention today?") },
|
|
@@ -307,7 +404,9 @@ const initial: MaestroState = {
|
|
|
307
404
|
unavailableTitle: "", unavailableText: "",
|
|
308
405
|
messages: [], emptyHidden: "false", prompts: [], quickReplies: [], quickRepliesHidden: "true",
|
|
309
406
|
input: "", hasInput: false, noInput: true, busy: false, idle: true, statusText: "", contextLabel: "", contextHidden: "true", error: "", scrollSend: "", scrollAnchor: "", ok: false,
|
|
310
|
-
_site: "", _account: "", _convId: "", _role: "", _openId: "", _openRaw: "", _turn: 0, _context: "", _decisionIds: [], _resumedId: "", _askKey: "",
|
|
407
|
+
_site: "", _account: "", _convId: "", _role: "", _openId: "", _openRaw: "", _turn: 0, _context: "", _decisionIds: [], _resumedId: "", _askKey: "", _started: false, _stopPending: "",
|
|
408
|
+
_older: "", olderHidden: "true", copyHidden: "true", copyNote: "", _copied: "", _watching: "", _watchLeft: 0,
|
|
409
|
+
waiting: [], waitingHidden: "true", attachments: [], attachmentsHidden: "true", listening: false, listeningHidden: "true",
|
|
311
410
|
};
|
|
312
411
|
|
|
313
412
|
const inputString = (key: string): string => {
|
|
@@ -346,8 +445,10 @@ function dropAskRequest(askKey: string): void {
|
|
|
346
445
|
}
|
|
347
446
|
|
|
348
447
|
const askLabel = (ask: Ask, subject: string): string => copy.about(ask.kind, subject);
|
|
349
|
-
const askContext = (ask: Ask, subject: string): string =>
|
|
350
|
-
|
|
448
|
+
const askContext = (ask: Ask, subject: string): string => {
|
|
449
|
+
const noun = ASK_MAESTRO_NOUNS[ask.kind];
|
|
450
|
+
return `The owner opened this chat from the Owner app's ${noun} screen. It is about the ${noun} with id ${ask.id}${subject ? ` ("${subject}")` : ""}. Unless they say otherwise, their questions are about that ${noun}.`;
|
|
451
|
+
};
|
|
351
452
|
|
|
352
453
|
/** A contact's name, for a chat opened about one. A detail screen never passes it: on the web
|
|
353
454
|
* host a screen's params are part of the address. Read here instead, from the business on
|
|
@@ -404,7 +505,7 @@ async function createConversation(api: WixApi, account: string, site: string, fi
|
|
|
404
505
|
return typeof id === "string" ? id : "";
|
|
405
506
|
}
|
|
406
507
|
|
|
407
|
-
function streamDirective(s: MaestroState, text: string, choice?: { askId: string; optionId: string }): unknown {
|
|
508
|
+
function streamDirective(s: MaestroState, text: string, choice?: { askId: string; optionId: string }, files: TurnAttachment[] = []): unknown {
|
|
408
509
|
return {
|
|
409
510
|
id: STREAM_ID,
|
|
410
511
|
request: {
|
|
@@ -418,6 +519,7 @@ function streamDirective(s: MaestroState, text: string, choice?: { askId: string
|
|
|
418
519
|
conversationId: s._convId, messageText: text, role: "USER", clientCapabilities: [],
|
|
419
520
|
deviceTimeZone: deviceTimeZone(), adoptsConversationId: true, communicationChannel: "APP",
|
|
420
521
|
...(choice ? { choiceAnswer: choice } : {}),
|
|
522
|
+
...(files.length ? { attachments: files } : {}),
|
|
421
523
|
...(s._context ? { context: s._context } : {}),
|
|
422
524
|
},
|
|
423
525
|
},
|
|
@@ -446,12 +548,37 @@ let reading = 0;
|
|
|
446
548
|
let draftSeq = 0;
|
|
447
549
|
let draft = "";
|
|
448
550
|
let chatSeq = 0;
|
|
551
|
+
// The files picked for the next message, and what Maestro is waiting on the owner for. Kept
|
|
552
|
+
// here, not only in the state: uploads and the waiting read finish on their own, while other
|
|
553
|
+
// actions are still waiting on Symphony with an older state in hand. `derived` puts these two
|
|
554
|
+
// onto every result, so no such action can undo them.
|
|
555
|
+
let chips: AttachmentChip[] = [];
|
|
556
|
+
let waitingAsks: WaitingAsk[] = [];
|
|
557
|
+
// The dictation session in flight: a new one, or leaving the chat, makes an older one's words nobody's.
|
|
558
|
+
let dictation = 0;
|
|
559
|
+
// Whether a session is listening now. Kept here, not in an action's snapshot: a result that started
|
|
560
|
+
// before the session did must not hide the row while the microphone is on.
|
|
561
|
+
let listeningNow = false;
|
|
562
|
+
// The waiting-list read in flight: a newer one, or another business, makes an older one's answer stale.
|
|
563
|
+
let waitingSeq = 0;
|
|
564
|
+
|
|
565
|
+
/** The chat on screen is being left: for a new one, a past one, or another business. What was
|
|
566
|
+
* picked or being dictated for it does not follow the owner into the next. */
|
|
567
|
+
function leaveChat(): void {
|
|
568
|
+
chips = [];
|
|
569
|
+
dictation += 1;
|
|
570
|
+
// Only this worker's own session is stopped: the recognizer is the app's, and another screen may be using it.
|
|
571
|
+
if (!listeningNow) return;
|
|
572
|
+
listeningNow = false;
|
|
573
|
+
void (async () => { try { await stopSpeech(); } catch { /* nothing was listening */ } })();
|
|
574
|
+
}
|
|
449
575
|
|
|
450
576
|
const freshChat = (s: MaestroState, input = ""): MaestroState => ({
|
|
451
577
|
...s, messages: [], emptyHidden: "false", prompts: prompts(), quickReplies: [], quickRepliesHidden: "true",
|
|
452
578
|
input, hasInput: input.trim().length > 0, noInput: input.trim().length === 0,
|
|
453
579
|
busy: false, idle: true, statusText: "", contextLabel: "", contextHidden: "true", error: "", scrollSend: "", scrollAnchor: "",
|
|
454
580
|
_convId: "", _role: "", _openId: "", _openRaw: "", _context: "", _decisionIds: [], _resumedId: "", _askKey: "",
|
|
581
|
+
_older: "", _copied: "", _watching: "", _watchLeft: 0,
|
|
455
582
|
});
|
|
456
583
|
|
|
457
584
|
/** `s` with the draft the owner typed while an action was waiting on Symphony. */
|
|
@@ -461,6 +588,11 @@ const withDraftSince = (s: MaestroState, seq: number): MaestroState =>
|
|
|
461
588
|
async function send(s: MaestroState, raw: string, choice?: { askId: string; optionId: string }): Promise<MaestroState & { _stream?: unknown }> {
|
|
462
589
|
const text = (raw ?? "").trim();
|
|
463
590
|
if (!text || s.busy || opening || deciding || reading || s.phase !== "ready") return s;
|
|
591
|
+
// A file still on its way would be left behind: say so instead of sending without it.
|
|
592
|
+
if (chips.some((c) => c.state === "uploading")) return { ...s, error: copy.stillUploading() };
|
|
593
|
+
// Taken now: once the conversation is being opened, what is picked belongs to the next message.
|
|
594
|
+
const files = chips.flatMap((c) => (c.state === "ready" && c.file ? [c.file] : []));
|
|
595
|
+
const sentChips = chips;
|
|
464
596
|
const api = host().wixApi;
|
|
465
597
|
if (!api) return { ...s, error: copy.failed() };
|
|
466
598
|
let convId = s._convId;
|
|
@@ -475,12 +607,15 @@ async function send(s: MaestroState, raw: string, choice?: { askId: string; opti
|
|
|
475
607
|
if (!convId) return { ...s, ...typed, error: copy.failed() };
|
|
476
608
|
}
|
|
477
609
|
const typedMeanwhile = draftSeq !== draftAtSend;
|
|
610
|
+
// The chips go with the message. One picked while the conversation was opening stays.
|
|
611
|
+
chips = chips.filter((c) => !sentChips.includes(c));
|
|
478
612
|
// The chat a detail screen asked for is in use: the request has done its work.
|
|
479
613
|
dropAskRequest(s._askKey);
|
|
480
614
|
const turn = s._turn + 1;
|
|
481
615
|
const next: MaestroState = {
|
|
482
|
-
...s, _convId: convId, _turn: turn, _role: "", _openId: "", _openRaw: "", _decisionIds: [],
|
|
483
|
-
|
|
616
|
+
...s, _convId: convId, _turn: turn, _role: "", _openId: "", _openRaw: "", _decisionIds: [], _started: false, _stopPending: "",
|
|
617
|
+
// The owner's message says what went with it: the files are not drawn in the transcript.
|
|
618
|
+
messages: [...settled(s.messages), userBubble(`u${turn}`, [text, ...files.map((f) => copy.attached(f.fileName))].join("\n")), thinkingBubble()],
|
|
484
619
|
emptyHidden: "true", quickReplies: [], quickRepliesHidden: "true",
|
|
485
620
|
input: "", hasInput: false, noInput: true, busy: true, idle: false,
|
|
486
621
|
statusText: "", error: "", scrollSend: `turn-${turn}`, scrollAnchor: `${SCREEN}.message_u${turn}`, ok: false,
|
|
@@ -488,14 +623,14 @@ async function send(s: MaestroState, raw: string, choice?: { askId: string; opti
|
|
|
488
623
|
const kept: MaestroState = typedMeanwhile
|
|
489
624
|
? { ...next, input: draft, hasInput: draft.trim().length > 0, noInput: draft.trim().length === 0 }
|
|
490
625
|
: next;
|
|
491
|
-
return { ...kept, _stream: streamDirective(kept, text, choice) };
|
|
626
|
+
return { ...kept, _stream: streamDirective(kept, text, choice, files) };
|
|
492
627
|
}
|
|
493
628
|
|
|
494
629
|
interface StreamEvent {
|
|
495
630
|
type?: string;
|
|
496
631
|
data?: {
|
|
497
632
|
role?: string; deltaText?: string; text?: string; conversationId?: string;
|
|
498
|
-
choices?: { askId?: string; options?: Array<{ id?: string; label?: string }> };
|
|
633
|
+
choices?: { askId?: string; options?: Array<{ id?: string; label?: string; url?: string }> };
|
|
499
634
|
} & Record<string, unknown>;
|
|
500
635
|
}
|
|
501
636
|
|
|
@@ -503,8 +638,9 @@ function quickRepliesOf(data: StreamEvent["data"]): QuickReply[] {
|
|
|
503
638
|
const askId = data?.choices?.askId;
|
|
504
639
|
if (typeof askId !== "string" || !askId) return [];
|
|
505
640
|
return (data?.choices?.options ?? [])
|
|
506
|
-
.filter((o): o is { id: string; label: string } => typeof o?.id === "string" && typeof o?.label === "string" && !!o.label)
|
|
507
|
-
|
|
641
|
+
.filter((o): o is { id: string; label: string; url?: string } => typeof o?.id === "string" && typeof o?.label === "string" && !!o.label)
|
|
642
|
+
// Only an https link is kept as one: the app opens it.
|
|
643
|
+
.map((o) => ({ id: o.id, label: o.label, askId, url: typeof o.url === "string" && isHttpsUrl(o.url.trim()) ? o.url.trim() : "" }));
|
|
508
644
|
}
|
|
509
645
|
|
|
510
646
|
const finished = (s: MaestroState): MaestroState => ({
|
|
@@ -548,29 +684,100 @@ function withEventCards(s: MaestroState, data: Record<string, unknown>): Maestro
|
|
|
548
684
|
};
|
|
549
685
|
}
|
|
550
686
|
|
|
551
|
-
/**
|
|
552
|
-
async function
|
|
553
|
-
const past = await chatMessages(api, conversationId);
|
|
687
|
+
/** One page of a past chat as rows: its turns and replies, and the cards its messages carried. */
|
|
688
|
+
async function pageRows(api: WixApi, conversationId: string, past: PastMessage[]): Promise<Bubble[]> {
|
|
554
689
|
let messages: Bubble[] = [];
|
|
555
690
|
const decisionIds: string[] = [];
|
|
556
691
|
for (const m of past) {
|
|
692
|
+
if (m.role === "STOPPED") { messages.push(noteBubble(`h_${m.id}`, copy.stopped())); continue; }
|
|
557
693
|
if (m.text.trim()) messages.push(m.role === "USER" ? userBubble(`h_${m.id}`, m.text) : assistantBubble(`h_${m.id}`, replyText(m.text)));
|
|
558
694
|
if (m.link) messages = withCards(messages, [linkBubble(m.link)]);
|
|
559
695
|
for (const id of m.decisionIds) if (!decisionIds.includes(id)) decisionIds.push(id);
|
|
560
696
|
}
|
|
561
|
-
|
|
697
|
+
return withCards(messages, await decisionCards(api, conversationId, decisionIds));
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
/** Open a past chat on its latest page. `_older` is the cursor of the page before it. */
|
|
701
|
+
async function resume(api: WixApi, s: MaestroState, conversationId: string): Promise<MaestroState> {
|
|
702
|
+
const page = await chatPage(api, conversationId);
|
|
703
|
+
const messages = await pageRows(api, conversationId, page.messages);
|
|
562
704
|
// A past chat opens on its latest message: a new token with no row to pin follows the end.
|
|
563
705
|
return {
|
|
564
706
|
...freshChat(s), _convId: conversationId, messages, emptyHidden: messages.length ? "true" : "false",
|
|
565
707
|
scrollSend: messages.length ? `open-${conversationId}-${messages.length}` : "", scrollAnchor: "",
|
|
708
|
+
_older: page.older,
|
|
566
709
|
};
|
|
567
710
|
}
|
|
568
711
|
|
|
569
|
-
/**
|
|
570
|
-
*
|
|
712
|
+
/** Upload one picked file: ask Symphony where to put it, put it there, and report the result to
|
|
713
|
+
* the `uploaded` action. Never throws: a failure is a result too. */
|
|
714
|
+
async function upload(chipId: string, handle: FileHandle): Promise<void> {
|
|
715
|
+
const api = host().wixApi;
|
|
716
|
+
const file = { fileName: handle.name || "file", mimeType: handle.mimeType || "application/octet-stream", size: handle.sizeBytes ?? 0 };
|
|
717
|
+
let done: TurnAttachment | null = null;
|
|
718
|
+
try {
|
|
719
|
+
if (api) {
|
|
720
|
+
const target = await mintUpload(api, file);
|
|
721
|
+
const result = await putFile(target.url, handle, { contentType: target.contentType });
|
|
722
|
+
done = result.ok ? uploadedFile(result.body, file) : null;
|
|
723
|
+
}
|
|
724
|
+
} catch { done = null; }
|
|
725
|
+
// The picker copied the file into the app's own store for the upload: it is not needed after it.
|
|
726
|
+
try { await removeFile(handle); } catch { /* already gone, or this host keeps no copy */ }
|
|
727
|
+
await (svc as unknown as { uploaded?: (r: { id: string; file: TurnAttachment | null }) => Promise<unknown> }).uploaded?.({ id: chipId, file: done });
|
|
728
|
+
}
|
|
729
|
+
|
|
730
|
+
/** What every action's result is finished with: the flags that follow from the rest of the
|
|
731
|
+
* state, so no action has to remember them. */
|
|
732
|
+
function derived<T extends MaestroState>(s: T): T {
|
|
733
|
+
const last = s.messages[s.messages.length - 1];
|
|
734
|
+
const copyable = !s.busy && s.phase === "ready" && !!last && last.assistantHidden === "false" && !!last.content;
|
|
735
|
+
const olderHidden = s._older && !s.busy ? "false" : "true";
|
|
736
|
+
const copyHidden = copyable ? "false" : "true";
|
|
737
|
+
// "Copied" is about one reply: it goes when that reply is no longer the last thing said.
|
|
738
|
+
const copyNote = copyable && s._copied === last.id ? copy.copied() : "";
|
|
739
|
+
// Only on an empty chat, where the greeting and the prompts are.
|
|
740
|
+
const waitingHidden = s.phase === "ready" && s.emptyHidden === "false" && waitingAsks.length > 0 ? "false" : "true";
|
|
741
|
+
// The same object when nothing follows differently: an action that changed nothing still says so.
|
|
742
|
+
const attachmentsHidden = chips.length > 0 ? "false" : "true";
|
|
743
|
+
const listeningHidden = listeningNow ? "false" : "true";
|
|
744
|
+
if (s.olderHidden === olderHidden && s.copyHidden === copyHidden && s.copyNote === copyNote && s.waitingHidden === waitingHidden
|
|
745
|
+
&& s.attachmentsHidden === attachmentsHidden && s.listeningHidden === listeningHidden && s.listening === listeningNow && s.attachments === chips && s.waiting === waitingAsks) return s;
|
|
746
|
+
return { ...s, attachments: chips, waiting: waitingAsks, listening: listeningNow, olderHidden, copyHidden, copyNote, waitingHidden, attachmentsHidden, listeningHidden };
|
|
747
|
+
}
|
|
748
|
+
|
|
749
|
+
/** The state as it is now, for a result that must not undo what happened while an action waited. */
|
|
750
|
+
const liveState = (fallback: MaestroState): MaestroState =>
|
|
751
|
+
(svc as unknown as { getState?: () => MaestroState }).getState?.() ?? fallback;
|
|
752
|
+
|
|
753
|
+
/** Every action, with its result finished by `derived`. */
|
|
754
|
+
function finishing(actions: MaestroActions): MaestroActions {
|
|
755
|
+
const out: Record<string, unknown> = {};
|
|
756
|
+
for (const [name, action] of Object.entries(actions as unknown as Record<string, (s: MaestroState, arg?: unknown) => Promise<MaestroState>>)) {
|
|
757
|
+
out[name] = async (s: MaestroState, arg?: unknown) => derived(await action(s, arg));
|
|
758
|
+
}
|
|
759
|
+
return out as unknown as MaestroActions;
|
|
760
|
+
}
|
|
761
|
+
|
|
762
|
+
const ACTIVITY_POLL = "maestro-activity";
|
|
763
|
+
const ACTIVITY_POLL_MS = 5_000;
|
|
764
|
+
/** How many times a chat Maestro is still working on is looked at again before the app stops
|
|
765
|
+
* looking: ten minutes. The owner can reopen it from History after that. */
|
|
766
|
+
const ACTIVITY_POLL_MAX = 120;
|
|
767
|
+
|
|
768
|
+
/** Answer a decision: Approve or Decline on its card (`id` is the card's row), or one of its
|
|
769
|
+
* options (`id` is the option's row). Refused while a turn streams: the result is built from
|
|
770
|
+
* the state it was dispatched with and would overwrite what the turn streamed meanwhile. */
|
|
571
771
|
async function decide(s: MaestroState, id: string, resolution: Verdict): Promise<MaestroState> {
|
|
572
|
-
const
|
|
573
|
-
if (!
|
|
772
|
+
const tapped = s.messages.find((b) => b.id === id);
|
|
773
|
+
if (!tapped?.decisionId || s.busy || opening || deciding || reading) return s;
|
|
774
|
+
const option = isOptionRow(tapped) ? tapped : undefined;
|
|
775
|
+
const cardId = decisionRowId(tapped.decisionId);
|
|
776
|
+
const card = s.messages.find((b) => b.id === cardId);
|
|
777
|
+
if (!card) return s;
|
|
778
|
+
// A button that is not on the card answers nothing: Approve on a card that asks to choose,
|
|
779
|
+
// or anything on one that has settled.
|
|
780
|
+
if (!option && (resolution === "ACCEPTED" ? card.primaryHidden : card.secondaryHidden) === "true") return s;
|
|
574
781
|
const api = host().wixApi;
|
|
575
782
|
if (!api) return { ...s, error: copy.verdictFailed() };
|
|
576
783
|
const draftAtStart = draftSeq;
|
|
@@ -578,14 +785,16 @@ async function decide(s: MaestroState, id: string, resolution: Verdict): Promise
|
|
|
578
785
|
deciding = true;
|
|
579
786
|
let settledAs: Decision | null = null;
|
|
580
787
|
let failed = false;
|
|
581
|
-
let reread: Bubble
|
|
788
|
+
let reread: Bubble[] = [];
|
|
582
789
|
try {
|
|
583
790
|
settledAs = await sendVerdict(api, {
|
|
584
791
|
decisionId: card.decisionId, verdictId: card.verdictId, resolution, planVersion: card.planVersion, conversationId: s._convId,
|
|
792
|
+
...(option ? { choice: option.optionId } : {}),
|
|
585
793
|
});
|
|
586
|
-
// Symphony refused the answer: the decision moved on (a newer plan,
|
|
587
|
-
// The same answer would be refused again, so
|
|
588
|
-
|
|
794
|
+
// Symphony refused the answer: the decision moved on (a newer plan, other options, or
|
|
795
|
+
// settled elsewhere). The same answer would be refused again, so it is read anew and gets a
|
|
796
|
+
// new verdict id.
|
|
797
|
+
if (!settledAs) reread = await decisionCards(api, s._convId, [card.decisionId]);
|
|
589
798
|
} catch { failed = true; } finally { deciding = false; }
|
|
590
799
|
// New chat was tapped meanwhile: the card is gone, and the answer already went to Symphony.
|
|
591
800
|
if (chatSeq !== chatAtStart) return freshChat(s, draft);
|
|
@@ -593,11 +802,25 @@ async function decide(s: MaestroState, id: string, resolution: Verdict): Promise
|
|
|
593
802
|
if (failed) return { ...base, error: copy.verdictFailed() };
|
|
594
803
|
if (!settledAs) {
|
|
595
804
|
// A re-read that failed names the decision only: the card on screen says more, so it stays.
|
|
596
|
-
const usable = reread && reread.cardStatus !== copy.decisionUnread();
|
|
597
|
-
return { ...base, error: copy.verdictFailed()
|
|
805
|
+
const usable = reread.length > 0 && reread[0].cardStatus !== copy.decisionUnread();
|
|
806
|
+
if (!usable) return { ...base, error: copy.verdictFailed() };
|
|
807
|
+
// Drawn as read, with its new verdict id: the one on screen was spent on the refused answer.
|
|
808
|
+
const replaced = base.messages.filter((b) => !(isOptionRow(b) && b.decisionId === card.decisionId));
|
|
809
|
+
const at = replaced.findIndex((b) => b.id === cardId);
|
|
810
|
+
return { ...base, error: copy.verdictFailed(), messages: [...replaced.slice(0, at), ...reread, ...replaced.slice(at + 1)] };
|
|
598
811
|
}
|
|
599
|
-
const shown: Decision = {
|
|
600
|
-
|
|
812
|
+
const shown: Decision = {
|
|
813
|
+
...settledAs, question: settledAs.question || card.cardTitle, detail: settledAs.detail || card.cardText, open: false,
|
|
814
|
+
resolution: settledAs.resolution || resolution,
|
|
815
|
+
// Symphony stores the chosen option's id: the label the owner tapped is what the card says.
|
|
816
|
+
chosen: option && resolution === "ACCEPTED" ? option.content : settledAs.chosen,
|
|
817
|
+
};
|
|
818
|
+
// One thing less is waiting on the owner: the tab's badge and the list are out of date.
|
|
819
|
+
askForRecount();
|
|
820
|
+
waitingAsks = waitingAsks.filter((a) => a.conversationId !== s._convId);
|
|
821
|
+
// A read asked before this answer would list it again.
|
|
822
|
+
waitingSeq += 1;
|
|
823
|
+
return { ...base, error: "", messages: withCards(base.messages, decisionRows(shown, card.verdictId)) };
|
|
601
824
|
}
|
|
602
825
|
|
|
603
826
|
type Arg = string | { value?: unknown; message?: string; text?: string; id?: string } | undefined;
|
|
@@ -607,7 +830,7 @@ const textOf = (arg: Arg): string => {
|
|
|
607
830
|
return "";
|
|
608
831
|
};
|
|
609
832
|
|
|
610
|
-
|
|
833
|
+
type MaestroActions = {
|
|
611
834
|
load: (s: MaestroState, arg?: unknown) => Promise<MaestroState>;
|
|
612
835
|
setInput: (s: MaestroState, arg?: Arg) => Promise<MaestroState>;
|
|
613
836
|
submit: (s: MaestroState, arg?: Arg) => Promise<MaestroState>;
|
|
@@ -617,15 +840,29 @@ const svc = defineService<MaestroState, {
|
|
|
617
840
|
newChat: (s: MaestroState) => Promise<MaestroState>;
|
|
618
841
|
cardPrimary: (s: MaestroState, arg?: Arg) => Promise<MaestroState>;
|
|
619
842
|
cardSecondary: (s: MaestroState, arg?: Arg) => Promise<MaestroState>;
|
|
843
|
+
cardOption: (s: MaestroState, arg?: Arg) => Promise<MaestroState>;
|
|
844
|
+
copyReply: (s: MaestroState) => Promise<MaestroState>;
|
|
845
|
+
loadOlder: (s: MaestroState) => Promise<MaestroState>;
|
|
846
|
+
watch: (s: MaestroState) => Promise<MaestroState>;
|
|
847
|
+
loadWaiting: (s: MaestroState) => Promise<MaestroState>;
|
|
848
|
+
attach: (s: MaestroState, arg?: unknown) => Promise<MaestroState>;
|
|
849
|
+
removeAttachment: (s: MaestroState, arg?: Arg) => Promise<MaestroState>;
|
|
850
|
+
uploaded: (s: MaestroState, arg?: unknown) => Promise<MaestroState>;
|
|
851
|
+
dictate: (s: MaestroState) => Promise<MaestroState>;
|
|
852
|
+
finishDictation: (s: MaestroState) => Promise<MaestroState>;
|
|
853
|
+
dictated: (s: MaestroState, arg?: unknown) => Promise<MaestroState>;
|
|
854
|
+
openWaiting: (s: MaestroState, arg?: Arg) => Promise<MaestroState>;
|
|
620
855
|
streamEvent: (s: MaestroState, ev?: StreamEvent) => Promise<MaestroState>;
|
|
621
856
|
streamDone: (s: MaestroState) => Promise<MaestroState>;
|
|
622
857
|
streamFailed: (s: MaestroState) => Promise<MaestroState>;
|
|
623
|
-
}
|
|
858
|
+
};
|
|
859
|
+
|
|
860
|
+
const svc = defineService<MaestroState, MaestroActions>(SERVICE, {
|
|
624
861
|
state: initial,
|
|
625
862
|
// A turn lives only as long as its stream. Restored after an app kill, `busy` and the thinking
|
|
626
863
|
// bubble would describe a stream that no longer exists and the composer would refuse every send.
|
|
627
|
-
notHydrated: ["busy", "idle", "statusText", "error", "scrollSend", "scrollAnchor", "_role", "_openId", "_openRaw", "_decisionIds", "quickReplies", "quickRepliesHidden"],
|
|
628
|
-
actions: {
|
|
864
|
+
notHydrated: ["busy", "idle", "statusText", "error", "scrollSend", "scrollAnchor", "_role", "_openId", "_openRaw", "_decisionIds", "quickReplies", "quickRepliesHidden", "_started", "_stopPending", "_watching", "_watchLeft", "_copied", "copyNote", "waiting", "waitingHidden", "attachments", "attachmentsHidden", "listening", "listeningHidden"],
|
|
865
|
+
actions: finishing({
|
|
629
866
|
// Runs on every appear. A conversation belongs to one business, so a switch starts over;
|
|
630
867
|
// returning to the same business keeps the transcript.
|
|
631
868
|
load: async (s, arg) => {
|
|
@@ -646,7 +883,19 @@ const svc = defineService<MaestroState, {
|
|
|
646
883
|
// "hidden" reads as shown: each row is completed so no empty card is drawn.
|
|
647
884
|
const rows = (s.busy ? s.messages : settled(s.messages)).map((b) => ({ ...NO_CARD, ...b }));
|
|
648
885
|
ready = { ...s, prompts: prompts(askKindOf(s._askKey)), messages: rows, contextHidden: s.contextLabel ? "false" : "true" };
|
|
886
|
+
// The chat on screen was deleted from History: nothing more is written into it.
|
|
887
|
+
if (ready._convId && !ready.busy && wasDeleted(ready._convId)) {
|
|
888
|
+
// As New chat does: an action still reading the deleted chat must not put it back.
|
|
889
|
+
chatSeq += 1;
|
|
890
|
+
leftPastChat = ready._resumedId || leftPastChat;
|
|
891
|
+
leaveChat();
|
|
892
|
+
ready = freshChat(ready, ready.input);
|
|
893
|
+
}
|
|
649
894
|
} else {
|
|
895
|
+
// Another business, or another owner: nothing picked, dictated or listed for the last one stays.
|
|
896
|
+
leaveChat();
|
|
897
|
+
waitingAsks = [];
|
|
898
|
+
waitingSeq += 1;
|
|
650
899
|
// The host could not say. A chat already open is kept (above); a new one is not opened.
|
|
651
900
|
if (reads === "unknown") return unavailable(fresh, "unreachable");
|
|
652
901
|
if (!site) return unavailable(fresh, "no_site");
|
|
@@ -667,7 +916,8 @@ const svc = defineService<MaestroState, {
|
|
|
667
916
|
// is acted on once, whether it opened the chat or failed to.
|
|
668
917
|
const past = inputString("conversationId");
|
|
669
918
|
const pastKey = past ? `${past}#${inputString("n")}` : "";
|
|
670
|
-
|
|
919
|
+
// A chat History has since deleted is not opened again, however the screen was reached.
|
|
920
|
+
if (past && pastKey !== leftPastChat && pastKey !== ready._resumedId && !wasDeleted(past)) {
|
|
671
921
|
if (!api) return { ...ready, _resumedId: pastKey, error: copy.historyFailed() };
|
|
672
922
|
const chatAtStart = chatSeq;
|
|
673
923
|
const draftAtStart = draftSeq;
|
|
@@ -675,11 +925,23 @@ const svc = defineService<MaestroState, {
|
|
|
675
925
|
reading += 1;
|
|
676
926
|
try {
|
|
677
927
|
const opened = { ...(await resume(api, ready, past)), _resumedId: pastKey };
|
|
678
|
-
|
|
928
|
+
// A turn the owner left before it ended keeps running: say so, and look again until it is done.
|
|
929
|
+
const running = await chatIsRunning(api, ready._account, past);
|
|
930
|
+
if (chatSeq !== chatAtStart) return freshChat(ready, draft);
|
|
931
|
+
// The chat on screen is left for this one: only now, when its read is the one that counts.
|
|
932
|
+
if (past !== ready._convId) leaveChat();
|
|
933
|
+
const shown = withDraftSince(opened, draftAtStart);
|
|
934
|
+
if (!running) return shown;
|
|
935
|
+
return {
|
|
936
|
+
...shown, statusText: copy.stillWorking(), _watching: past, _watchLeft: ACTIVITY_POLL_MAX,
|
|
937
|
+
_poll: { id: ACTIVITY_POLL, intervalMs: ACTIVITY_POLL_MS, action: `${SERVICE}.watch`, immediate: false },
|
|
938
|
+
} as MaestroState;
|
|
679
939
|
} catch {
|
|
680
940
|
return chatSeq !== chatAtStart ? freshChat(ready, draft) : { ...withDraftSince(ready, draftAtStart), _resumedId: pastKey, error: copy.historyFailed() };
|
|
681
941
|
} finally { reading -= 1; }
|
|
682
942
|
}
|
|
943
|
+
// Not awaited: the list fills in when Symphony answers.
|
|
944
|
+
if (!past) void (svc as unknown as { loadWaiting?: () => Promise<unknown> }).loadWaiting?.();
|
|
683
945
|
const ask = past ? null : askedAbout();
|
|
684
946
|
if (ask && ask.key !== leftAsk && ask.key !== ready._askKey) {
|
|
685
947
|
let subject = ask.subject;
|
|
@@ -692,6 +954,8 @@ const svc = defineService<MaestroState, {
|
|
|
692
954
|
if (chatSeq !== chatAtStart) return freshChat(ready, draft);
|
|
693
955
|
ready = withDraftSince(ready, draftAtStart);
|
|
694
956
|
}
|
|
957
|
+
// The chat on screen is left for one about this item.
|
|
958
|
+
leaveChat();
|
|
695
959
|
return {
|
|
696
960
|
...freshChat(ready, ready.input), prompts: prompts(ask.kind),
|
|
697
961
|
contextLabel: askLabel(ask, subject), contextHidden: "false", _context: askContext(ask, subject), _askKey: ask.key,
|
|
@@ -716,15 +980,31 @@ const svc = defineService<MaestroState, {
|
|
|
716
980
|
answer: async (s, arg) => {
|
|
717
981
|
const id = typeof arg === "object" ? arg?.id : "";
|
|
718
982
|
const reply = s.quickReplies.find((q) => q.id === id);
|
|
719
|
-
|
|
983
|
+
if (!reply) return s;
|
|
984
|
+
// A chip that is a link opens it and sends nothing, as in Symphony's own clients.
|
|
985
|
+
if (reply.url) {
|
|
986
|
+
try { await openUrl(reply.url); } catch { /* the host refused to open it: the chip stays */ }
|
|
987
|
+
return s;
|
|
988
|
+
}
|
|
989
|
+
return send(s, reply.label, { askId: reply.askId, optionId: reply.id });
|
|
720
990
|
},
|
|
721
|
-
//
|
|
722
|
-
//
|
|
991
|
+
// Stops listening here at once, and tells Symphony to stop the turn. Symphony can only stop
|
|
992
|
+
// a turn that has started, so one stopped earlier is told as soon as it shows it is running
|
|
993
|
+
// (`_stopPending`, in `streamEvent`). What the turn still streams is dropped: nothing is in
|
|
994
|
+
// flight here any more.
|
|
723
995
|
// The transcript says so, since nothing else would: without the note a stopped turn looks
|
|
724
996
|
// like a message Maestro ignored.
|
|
725
|
-
stop: async (s) =>
|
|
726
|
-
|
|
727
|
-
|
|
997
|
+
stop: async (s) => {
|
|
998
|
+
if (!s.busy) return s;
|
|
999
|
+
const api = host().wixApi;
|
|
1000
|
+
const tellNow = s._started && !!api;
|
|
1001
|
+
// Not awaited: the chat stops listening whether or not Symphony could be told.
|
|
1002
|
+
if (tellNow) void stopTurn(api, s._account, s._convId);
|
|
1003
|
+
return endTurn({
|
|
1004
|
+
...s, _stopPending: tellNow ? "" : s._convId,
|
|
1005
|
+
messages: [...settled(s.messages), noteBubble(`stopped_${s._turn}`, copy.stopped())],
|
|
1006
|
+
});
|
|
1007
|
+
},
|
|
728
1008
|
newChat: async (s) => {
|
|
729
1009
|
if (s.phase !== "ready") return s;
|
|
730
1010
|
chatSeq += 1;
|
|
@@ -732,6 +1012,7 @@ const svc = defineService<MaestroState, {
|
|
|
732
1012
|
draft = "";
|
|
733
1013
|
leftPastChat = s._resumedId || leftPastChat;
|
|
734
1014
|
leftAsk = s._askKey || leftAsk;
|
|
1015
|
+
leaveChat();
|
|
735
1016
|
// The chat a detail screen asked for was left: a worker started later must not reopen it.
|
|
736
1017
|
dropAskRequest(s._askKey);
|
|
737
1018
|
return freshChat(s);
|
|
@@ -749,8 +1030,185 @@ const svc = defineService<MaestroState, {
|
|
|
749
1030
|
return decide(s, id, "ACCEPTED");
|
|
750
1031
|
},
|
|
751
1032
|
cardSecondary: async (s, arg) => decide(s, typeof arg === "object" ? arg?.id ?? "" : "", "REFUSED"),
|
|
1033
|
+
// Copy the last reply, as Maestro wrote it for the screen.
|
|
1034
|
+
copyReply: async (s) => {
|
|
1035
|
+
const last = s.messages[s.messages.length - 1];
|
|
1036
|
+
if (s.busy || !last || last.assistantHidden !== "false" || !last.content) return s;
|
|
1037
|
+
// Emphasis marks are for the renderer: what is copied is the words.
|
|
1038
|
+
try { await writeText(last.content.replace(/\*\*/g, "")); } catch { return s; }
|
|
1039
|
+
const live = liveState(s);
|
|
1040
|
+
return { ...live, _copied: last.id };
|
|
1041
|
+
},
|
|
1042
|
+
// The page before the oldest message shown, put above it.
|
|
1043
|
+
loadOlder: async (s) => {
|
|
1044
|
+
const api = host().wixApi;
|
|
1045
|
+
if (!s._older || !s._convId || s.busy || opening || deciding || reading || !api) return s;
|
|
1046
|
+
const chatAtStart = chatSeq;
|
|
1047
|
+
const draftAtStart = draftSeq;
|
|
1048
|
+
const conversationId = s._convId;
|
|
1049
|
+
reading += 1;
|
|
1050
|
+
try {
|
|
1051
|
+
const page = await chatPage(api, conversationId, s._older);
|
|
1052
|
+
const rows = await pageRows(api, conversationId, page.messages);
|
|
1053
|
+
if (chatSeq !== chatAtStart) return freshChat(s, draft);
|
|
1054
|
+
const base = withDraftSince(s, draftAtStart);
|
|
1055
|
+
const shown = new Set(base.messages.map((b) => b.id));
|
|
1056
|
+
return { ...base, error: "", _older: page.older, messages: [...rows.filter((b) => !shown.has(b.id)), ...base.messages] };
|
|
1057
|
+
} catch {
|
|
1058
|
+
return chatSeq !== chatAtStart ? freshChat(s, draft) : { ...withDraftSince(s, draftAtStart), error: copy.olderFailed() };
|
|
1059
|
+
} finally { reading -= 1; }
|
|
1060
|
+
},
|
|
1061
|
+
// The tick that looks again at a past chat Maestro was still working on. It ends itself:
|
|
1062
|
+
// when the work is done (the chat is read again), when the owner moved on, or after
|
|
1063
|
+
// `ACTIVITY_POLL_MAX` looks.
|
|
1064
|
+
watch: async (s) => {
|
|
1065
|
+
const stop = (state: MaestroState): MaestroState =>
|
|
1066
|
+
({ ...state, _watching: "", _watchLeft: 0, statusText: state.statusText === copy.stillWorking() ? "" : state.statusText, _poll: { id: ACTIVITY_POLL, stop: true } }) as MaestroState;
|
|
1067
|
+
const api = host().wixApi;
|
|
1068
|
+
const watching = s._watching;
|
|
1069
|
+
if (!watching || watching !== s._convId || s.busy || !api || s._watchLeft <= 0) return stop(s);
|
|
1070
|
+
if (opening || deciding || reading) return s;
|
|
1071
|
+
const chatAtStart = chatSeq;
|
|
1072
|
+
const draftAtStart = draftSeq;
|
|
1073
|
+
reading += 1;
|
|
1074
|
+
try {
|
|
1075
|
+
if (await chatIsRunning(api, s._account, watching)) {
|
|
1076
|
+
if (chatSeq !== chatAtStart) return stop(freshChat(s, draft));
|
|
1077
|
+
const live = liveState(s);
|
|
1078
|
+
return live._watching === watching ? { ...live, _watchLeft: live._watchLeft - 1 } : live;
|
|
1079
|
+
}
|
|
1080
|
+
const reread = await resume(api, s, watching);
|
|
1081
|
+
if (chatSeq !== chatAtStart) return stop(freshChat(s, draft));
|
|
1082
|
+
return stop(withDraftSince({ ...reread, _resumedId: s._resumedId, input: s.input, hasInput: s.hasInput, noInput: s.noInput }, draftAtStart));
|
|
1083
|
+
} catch {
|
|
1084
|
+
// Could not be read this time: the next tick looks again.
|
|
1085
|
+
return chatSeq !== chatAtStart ? stop(freshChat(s, draft)) : { ...s, _watchLeft: s._watchLeft - 1 };
|
|
1086
|
+
} finally { reading -= 1; }
|
|
1087
|
+
},
|
|
1088
|
+
// Dictation, on the device's own recognizer: no audio crosses the bridge, only the words.
|
|
1089
|
+
// The listen is not awaited: the screen says "Listening…" while the owner speaks, and
|
|
1090
|
+
// `dictated` lands what was heard. One session at a time.
|
|
1091
|
+
dictate: async (s) => {
|
|
1092
|
+
if (listeningNow || s.phase !== "ready") return s;
|
|
1093
|
+
const session = ++dictation;
|
|
1094
|
+
listeningNow = true;
|
|
1095
|
+
void (async () => {
|
|
1096
|
+
let heard = "";
|
|
1097
|
+
try { heard = (await recognizeOnce()).transcript; } catch { heard = ""; }
|
|
1098
|
+
// A session the owner ended and started over is not this one's to report.
|
|
1099
|
+
if (session !== dictation) return;
|
|
1100
|
+
await (svc as unknown as { dictated?: (r: { transcript: string }) => Promise<unknown> }).dictated?.({ transcript: heard });
|
|
1101
|
+
})();
|
|
1102
|
+
return { ...s, error: "" };
|
|
1103
|
+
},
|
|
1104
|
+
// Done: stop listening. What was heard so far still arrives through `dictated`.
|
|
1105
|
+
finishDictation: async (s) => {
|
|
1106
|
+
try { await stopSpeech(); } catch { /* nothing was listening */ }
|
|
1107
|
+
return liveState(s);
|
|
1108
|
+
},
|
|
1109
|
+
// What was heard goes after what is already typed, for the owner to read and send.
|
|
1110
|
+
dictated: async (s, arg) => {
|
|
1111
|
+
const heard = String((arg as { transcript?: unknown } | undefined)?.transcript ?? "").replace(/\s+/g, " ").trim();
|
|
1112
|
+
listeningNow = false;
|
|
1113
|
+
if (!heard) return s;
|
|
1114
|
+
const input = [s.input.trimEnd(), heard].filter(Boolean).join(" ");
|
|
1115
|
+
draftSeq += 1;
|
|
1116
|
+
draft = input;
|
|
1117
|
+
return { ...s, input, hasInput: true, noInput: false };
|
|
1118
|
+
},
|
|
1119
|
+
// Pick photos or files for the next message. Each becomes a chip at once and uploads on its
|
|
1120
|
+
// own: the composer stays usable, and `uploaded` lands each result on the state as it is then.
|
|
1121
|
+
attach: async (s, arg) => {
|
|
1122
|
+
if (s.phase !== "ready") return s;
|
|
1123
|
+
const source = (arg as { source?: unknown } | undefined)?.source === "document" ? "document" : "library";
|
|
1124
|
+
const room = MAX_ATTACHMENTS - chips.length;
|
|
1125
|
+
if (room <= 0) return { ...s, error: copy.tooMany() };
|
|
1126
|
+
let picked: FileHandle[];
|
|
1127
|
+
let refused = false;
|
|
1128
|
+
try {
|
|
1129
|
+
const result = source === "document"
|
|
1130
|
+
? await pickFiles({ multiple: true, maxItems: room, maxBytes: MAX_ATTACHMENT_BYTES })
|
|
1131
|
+
: await pickPhotos({ type: "images", limit: room, maxBytes: MAX_ATTACHMENT_BYTES });
|
|
1132
|
+
picked = result.items.slice(0, room);
|
|
1133
|
+
refused = result.rejected.length > 0;
|
|
1134
|
+
} catch {
|
|
1135
|
+
// The picker could not be shown on this host: nothing was picked.
|
|
1136
|
+
return liveState(s);
|
|
1137
|
+
}
|
|
1138
|
+
const live = liveState(s);
|
|
1139
|
+
if (!picked.length) return refused ? { ...live, error: copy.tooBig() } : live;
|
|
1140
|
+
const added: AttachmentChip[] = picked.map((h, index) => ({
|
|
1141
|
+
id: `f${Date.now().toString(36)}${index}`, name: h.name || "file", statusText: copy.uploading(), state: "uploading", file: null,
|
|
1142
|
+
}));
|
|
1143
|
+
chips = [...chips, ...added];
|
|
1144
|
+
picked.forEach((handle, index) => { void upload(added[index].id, handle); });
|
|
1145
|
+
return { ...live, error: refused ? copy.tooBig() : "" };
|
|
1146
|
+
},
|
|
1147
|
+
removeAttachment: async (s, arg) => {
|
|
1148
|
+
const id = typeof arg === "object" ? arg?.id ?? "" : "";
|
|
1149
|
+
chips = chips.filter((c) => c.id !== id);
|
|
1150
|
+
return { ...s, error: "" };
|
|
1151
|
+
},
|
|
1152
|
+
// One upload's result. A chip the owner removed meanwhile, or sent away with a new chat, is gone.
|
|
1153
|
+
uploaded: async (s, arg) => {
|
|
1154
|
+
const r = arg as { id?: string; file?: TurnAttachment | null } | undefined;
|
|
1155
|
+
chips = chips.map((c) => (c.id !== r?.id ? c
|
|
1156
|
+
: r.file ? { ...c, state: "ready" as const, statusText: "", file: r.file }
|
|
1157
|
+
: { ...c, state: "failed" as const, statusText: copy.uploadFailed() }));
|
|
1158
|
+
return s;
|
|
1159
|
+
},
|
|
1160
|
+
// What Maestro is waiting on the owner for. Asked apart from `load`, so the chat never waits
|
|
1161
|
+
// on it; a read that fails leaves the list as it was.
|
|
1162
|
+
loadWaiting: async (s) => {
|
|
1163
|
+
const api = host().wixApi;
|
|
1164
|
+
const site = activeSiteId();
|
|
1165
|
+
if (!api || !site) return s;
|
|
1166
|
+
const seq = ++waitingSeq;
|
|
1167
|
+
try {
|
|
1168
|
+
const [waiting, chats] = await Promise.all([waitingOnOwner(api), pastChats(api, site)]);
|
|
1169
|
+
// Symphony keeps these for the whole account: only the ones asked in a chat of this
|
|
1170
|
+
// business are listed, since a row opens that chat here.
|
|
1171
|
+
const mine = new Set(chats.map((c) => c.id));
|
|
1172
|
+
// A newer read, or another business meanwhile: this answer is for a screen that is gone.
|
|
1173
|
+
if (seq === waitingSeq && activeSiteId() === site) {
|
|
1174
|
+
waitingAsks = waiting.asks.filter((a) => mine.has(a.conversationId)).slice(0, 5);
|
|
1175
|
+
}
|
|
1176
|
+
} catch { /* could not be read: the list stays as it was */ }
|
|
1177
|
+
// `derived` puts the list on whatever the state is now.
|
|
1178
|
+
return liveState(s);
|
|
1179
|
+
},
|
|
1180
|
+
// Open the chat one of them is asked in.
|
|
1181
|
+
openWaiting: async (s, arg) => {
|
|
1182
|
+
const ask = waitingAsks.find((w) => w.id === (typeof arg === "object" ? arg?.id : ""));
|
|
1183
|
+
const api = host().wixApi;
|
|
1184
|
+
if (!ask || s.busy || opening || deciding || reading || !api) return s;
|
|
1185
|
+
const chatAtStart = chatSeq;
|
|
1186
|
+
const draftAtStart = draftSeq;
|
|
1187
|
+
reading += 1;
|
|
1188
|
+
try {
|
|
1189
|
+
const opened = await resume(api, s, ask.conversationId);
|
|
1190
|
+
if (chatSeq !== chatAtStart) return freshChat(s, draft);
|
|
1191
|
+
if (ask.conversationId !== s._convId) leaveChat();
|
|
1192
|
+
// A chat about an item was left for this one: the next appear must not put it back.
|
|
1193
|
+
leftAsk = s._askKey || leftAsk;
|
|
1194
|
+
dropAskRequest(s._askKey);
|
|
1195
|
+
return withDraftSince({ ...opened, _resumedId: `${ask.conversationId}#waiting` }, draftAtStart);
|
|
1196
|
+
} catch {
|
|
1197
|
+
return chatSeq !== chatAtStart ? freshChat(s, draft) : { ...withDraftSince(s, draftAtStart), error: copy.historyFailed() };
|
|
1198
|
+
} finally { reading -= 1; }
|
|
1199
|
+
},
|
|
1200
|
+
// One option of a decision that asks the owner to choose.
|
|
1201
|
+
cardOption: async (s, arg) => decide(s, typeof arg === "object" ? arg?.id ?? "" : "", "ACCEPTED"),
|
|
752
1202
|
streamEvent: async (s, ev) => {
|
|
753
|
-
if (!s.busy)
|
|
1203
|
+
if (!s.busy) {
|
|
1204
|
+
// Stopped, or a turn that already ended. A turn stopped before it had started is told to
|
|
1205
|
+
// stop now that it shows it is running, once.
|
|
1206
|
+
if (!s._stopPending || ev?.type === "metadata") return s;
|
|
1207
|
+
const api = host().wixApi;
|
|
1208
|
+
if (api) void stopTurn(api, s._account, s._stopPending);
|
|
1209
|
+
return { ...s, _stopPending: "" };
|
|
1210
|
+
}
|
|
1211
|
+
if (ev?.type !== "metadata" && !s._started) s = { ...s, _started: true };
|
|
754
1212
|
const data = ev?.data ?? {};
|
|
755
1213
|
if (ev?.type === "metadata") {
|
|
756
1214
|
return typeof data.conversationId === "string" && data.conversationId ? { ...s, _convId: data.conversationId } : s;
|
|
@@ -782,9 +1240,10 @@ const svc = defineService<MaestroState, {
|
|
|
782
1240
|
if (ev?.type === "cards") return withEventCards(s, data);
|
|
783
1241
|
return s;
|
|
784
1242
|
},
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
1243
|
+
// A stopped turn that ended by itself is not told to stop: there is nothing left to stop.
|
|
1244
|
+
streamDone: async (s) => (s.busy ? endTurn(s) : s._stopPending ? { ...s, _stopPending: "" } : s),
|
|
1245
|
+
streamFailed: async (s) => (s.busy ? endTurn(s, copy.failed()) : s._stopPending ? { ...s, _stopPending: "" } : s),
|
|
1246
|
+
}),
|
|
788
1247
|
});
|
|
789
1248
|
|
|
790
1249
|
svc.load();
|