@burdenoff/microfe-healthybowl 2026.902.9 → 2026.902.10
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/dist/components/assistant/AssistantSpeechProvider.js +79 -73
- package/dist/components/assistant/AssistantSpeechProvider.js.map +1 -1
- package/dist/healthybowl/hooks/useConsultationPayments.js +59 -0
- package/dist/healthybowl/hooks/useConsultationPayments.js.map +1 -0
- package/dist/healthybowl/hooks/useHealthyBowlData.js +15 -0
- package/dist/healthybowl/hooks/useHealthyBowlData.js.map +1 -1
- package/dist/healthybowl/offline/graphql.js.map +1 -1
- package/dist/healthybowl/offline/syncEngine.js +2 -1
- package/dist/healthybowl/offline/syncEngine.js.map +1 -1
- package/dist/healthybowl/offline/types.js.map +1 -1
- package/dist/healthybowl/pages/government-schemes/ApplicationTrackingPage.js +228 -188
- package/dist/healthybowl/pages/government-schemes/ApplicationTrackingPage.js.map +1 -1
- package/dist/healthybowl/pages/government-schemes/SchemeDetailsPage.js +261 -191
- package/dist/healthybowl/pages/government-schemes/SchemeDetailsPage.js.map +1 -1
- package/dist/healthybowl/pages/government-schemes/schemeApplicationTransitions.js +49 -0
- package/dist/healthybowl/pages/government-schemes/schemeApplicationTransitions.js.map +1 -0
- package/dist/healthybowl/pages/government-schemes/schemeDocumentSlots.js +48 -0
- package/dist/healthybowl/pages/government-schemes/schemeDocumentSlots.js.map +1 -0
- package/dist/healthybowl/pages/government-schemes/useSchemeApplicationTransition.js +54 -0
- package/dist/healthybowl/pages/government-schemes/useSchemeApplicationTransition.js.map +1 -0
- package/dist/healthybowl/pages/network/ExpertsPage.js +520 -419
- package/dist/healthybowl/pages/network/ExpertsPage.js.map +1 -1
- package/dist/hooks/useVoiceSession.js +69 -70
- package/dist/hooks/useVoiceSession.js.map +1 -1
- package/package.json +1 -1
|
@@ -38,7 +38,9 @@ var ue = {
|
|
|
38
38
|
toggle: () => {},
|
|
39
39
|
stop: () => {},
|
|
40
40
|
autoSpeakEnabled: !1,
|
|
41
|
-
setAutoSpeak: () => {}
|
|
41
|
+
setAutoSpeak: () => {},
|
|
42
|
+
sessionSpeaking: !1,
|
|
43
|
+
setSessionSpeaking: () => {}
|
|
42
44
|
});
|
|
43
45
|
function S() {
|
|
44
46
|
return g(x);
|
|
@@ -46,20 +48,20 @@ function S() {
|
|
|
46
48
|
var C = ({ children: m, visible: g = !0, engine: S = e() }) => {
|
|
47
49
|
let C = n(), { locale: w } = ce(), [T, E] = se(ie, re), [D, O] = b(() => S.listVoices()), [k, A] = b(!1), [j, M] = b(() => /* @__PURE__ */ new Map()), N = y(0), P = y(null), F = y(() => {}), I = h(() => {
|
|
48
50
|
P.current?.(), P.current = null;
|
|
49
|
-
}, []), L = t((e) => e.autoSpeakEnabled), R = t((e) => e.setAutoSpeak), de = t((e) => e.activeConversationId),
|
|
51
|
+
}, []), L = t((e) => e.autoSpeakEnabled), R = t((e) => e.setAutoSpeak), [z, de] = b(!1), fe = t((e) => e.activeConversationId), B = v(() => S.isSupported(), [S]);
|
|
50
52
|
_(() => {
|
|
51
|
-
if (!
|
|
53
|
+
if (!B) return;
|
|
52
54
|
let e = () => {
|
|
53
55
|
O(S.listVoices()), M((e) => e.size === 0 ? e : /* @__PURE__ */ new Map());
|
|
54
56
|
};
|
|
55
57
|
return e(), S.subscribeVoices(e);
|
|
56
|
-
}, [S,
|
|
57
|
-
let
|
|
58
|
-
|
|
58
|
+
}, [S, B]);
|
|
59
|
+
let V = t((e) => e.assistantLanguage), H = t((e) => e.preferredVoices), U = t((e) => e.setPreferredVoice), W = v(() => ne(V, w), [V, w]), G = W.code, K = h((e) => f(e)?.tag ?? l(e), []), q = h((e) => f(e)?.rate ?? .9, []), J = v(() => u(B, D, W.tag, k), [
|
|
60
|
+
B,
|
|
59
61
|
D,
|
|
60
|
-
|
|
62
|
+
W,
|
|
61
63
|
k
|
|
62
|
-
]),
|
|
64
|
+
]), Y = v(() => ({
|
|
63
65
|
codeBlock: C("healthybowl.assistant.speech.codeBlock", "Code block"),
|
|
64
66
|
image: C("healthybowl.assistant.speech.image", "image"),
|
|
65
67
|
link: C("healthybowl.assistant.speech.link", "link"),
|
|
@@ -68,9 +70,9 @@ var C = ({ children: m, visible: g = !0, engine: S = e() }) => {
|
|
|
68
70
|
nestedItem: C("healthybowl.assistant.speech.nestedItem", "Sub-item {{ordinal}}"),
|
|
69
71
|
emailAt: C("healthybowl.assistant.speech.emailAt", "at"),
|
|
70
72
|
emailDot: C("healthybowl.assistant.speech.emailDot", "dot")
|
|
71
|
-
}), [C]),
|
|
73
|
+
}), [C]), X = h(() => {
|
|
72
74
|
I(), S.cancel(), E({ type: "stop" });
|
|
73
|
-
}, [I, S]),
|
|
75
|
+
}, [I, S]), Z = h((e) => j.get(e) ?? null, [j]), pe = h((e, t, n) => {
|
|
74
76
|
I();
|
|
75
77
|
let r = !1, i = () => {}, a = (a) => {
|
|
76
78
|
if (!r) {
|
|
@@ -84,20 +86,20 @@ var C = ({ children: m, visible: g = !0, engine: S = e() }) => {
|
|
|
84
86
|
i = S.subscribeVoices(() => a(S.listVoices())), P.current = () => {
|
|
85
87
|
r || (r = !0, clearTimeout(s), i(), P.current = null);
|
|
86
88
|
};
|
|
87
|
-
}, [I, S]),
|
|
89
|
+
}, [I, S]), Q = h((e, t, n, i) => {
|
|
88
90
|
let a = n;
|
|
89
91
|
if (a.length === 0) {
|
|
90
92
|
let e = S.listVoices();
|
|
91
93
|
e.length > 0 && (a = e, O(e));
|
|
92
94
|
}
|
|
93
|
-
let o =
|
|
95
|
+
let o = K(i), l = ee(u(!0, a, i, k));
|
|
94
96
|
if (l === "block") {
|
|
95
97
|
let t = C("healthybowl.assistant.speech.noVoiceForReply", "This reply is in {{language}}, and no {{language}} voice is installed on this device.", { language: s(o, w) });
|
|
96
98
|
M((n) => new Map(n).set(e, t));
|
|
97
99
|
return;
|
|
98
100
|
}
|
|
99
101
|
if (l === "wait-for-voices") {
|
|
100
|
-
|
|
102
|
+
pe(e, t, i);
|
|
101
103
|
return;
|
|
102
104
|
}
|
|
103
105
|
M((t) => {
|
|
@@ -111,9 +113,9 @@ var C = ({ children: m, visible: g = !0, engine: S = e() }) => {
|
|
|
111
113
|
messageId: e,
|
|
112
114
|
requestId: d
|
|
113
115
|
}), S.speak(r(t), {
|
|
114
|
-
voice: c(a, o,
|
|
116
|
+
voice: c(a, o, H[i]),
|
|
115
117
|
lang: o,
|
|
116
|
-
rate:
|
|
118
|
+
rate: q(i)
|
|
117
119
|
}, {
|
|
118
120
|
onEnd: () => E({
|
|
119
121
|
type: "finished",
|
|
@@ -127,51 +129,51 @@ var C = ({ children: m, visible: g = !0, engine: S = e() }) => {
|
|
|
127
129
|
}, [
|
|
128
130
|
S,
|
|
129
131
|
w,
|
|
130
|
-
|
|
132
|
+
H,
|
|
133
|
+
q,
|
|
131
134
|
K,
|
|
132
|
-
G,
|
|
133
135
|
C,
|
|
134
136
|
k,
|
|
135
|
-
|
|
137
|
+
pe
|
|
136
138
|
]);
|
|
137
139
|
_(() => {
|
|
138
|
-
F.current =
|
|
139
|
-
}, [
|
|
140
|
-
let
|
|
141
|
-
if (!
|
|
142
|
-
let r = te(i(t, { labels: ue }), n ??
|
|
143
|
-
o &&
|
|
140
|
+
F.current = Q;
|
|
141
|
+
}, [Q]);
|
|
142
|
+
let $ = h((e, t, n) => {
|
|
143
|
+
if (!B) return;
|
|
144
|
+
let r = te(i(t, { labels: ue }), n ?? G), o = i(t, { labels: a(r, Y) });
|
|
145
|
+
o && Q(e, o, D, r);
|
|
144
146
|
}, [
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
147
|
+
B,
|
|
148
|
+
Y,
|
|
149
|
+
G,
|
|
150
|
+
Q,
|
|
149
151
|
D
|
|
150
|
-
]),
|
|
152
|
+
]), me = h((e, t, n) => {
|
|
151
153
|
if (p(T, e)) {
|
|
152
|
-
|
|
154
|
+
X();
|
|
153
155
|
return;
|
|
154
156
|
}
|
|
155
|
-
|
|
157
|
+
$(e, t, n);
|
|
156
158
|
}, [
|
|
157
159
|
T,
|
|
158
|
-
|
|
159
|
-
|
|
160
|
+
$,
|
|
161
|
+
X
|
|
160
162
|
]);
|
|
161
163
|
_(() => {
|
|
162
|
-
g ||
|
|
163
|
-
}, [g,
|
|
164
|
-
|
|
165
|
-
}, [
|
|
166
|
-
M((e) => e.size === 0 ? e : /* @__PURE__ */ new Map()),
|
|
167
|
-
}, [
|
|
164
|
+
g || X();
|
|
165
|
+
}, [g, X]), _(() => {
|
|
166
|
+
X(), M(/* @__PURE__ */ new Map());
|
|
167
|
+
}, [fe, X]), _(() => {
|
|
168
|
+
M((e) => e.size === 0 ? e : /* @__PURE__ */ new Map()), X();
|
|
169
|
+
}, [G, X]), _(() => () => {
|
|
168
170
|
P.current?.(), P.current = null, S.cancel();
|
|
169
171
|
}, [S]), _(() => {
|
|
170
172
|
if (typeof window > "u") return;
|
|
171
173
|
let e = () => S.cancel();
|
|
172
174
|
return window.addEventListener("pagehide", e), () => window.removeEventListener("pagehide", e);
|
|
173
175
|
}, [S]), _(() => {
|
|
174
|
-
if (typeof document > "u" || !
|
|
176
|
+
if (typeof document > "u" || !B) return;
|
|
175
177
|
let e = () => {
|
|
176
178
|
if (document.visibilityState !== "visible") return;
|
|
177
179
|
let e = S.listVoices();
|
|
@@ -183,13 +185,13 @@ var C = ({ children: m, visible: g = !0, engine: S = e() }) => {
|
|
|
183
185
|
}, [
|
|
184
186
|
I,
|
|
185
187
|
S,
|
|
186
|
-
|
|
188
|
+
B
|
|
187
189
|
]);
|
|
188
|
-
let
|
|
190
|
+
let he = y($);
|
|
189
191
|
_(() => {
|
|
190
|
-
|
|
191
|
-
}, [
|
|
192
|
-
if (!(!L || !g || !
|
|
192
|
+
he.current = $;
|
|
193
|
+
}, [$]), _(() => {
|
|
194
|
+
if (!(!L && !z || !g || !B)) return t.subscribe((e, t) => {
|
|
193
195
|
let n = e.activeConversationId;
|
|
194
196
|
if (!n || n !== t.activeConversationId) return;
|
|
195
197
|
let r = e.processingByConversationId[n], i = t.processingByConversationId[n];
|
|
@@ -199,52 +201,56 @@ var C = ({ children: m, visible: g = !0, engine: S = e() }) => {
|
|
|
199
201
|
let o = e.conversations.find((e) => e.id === n)?.messages.find((e) => e.id === a);
|
|
200
202
|
if (!o || o.role !== "assistant") return;
|
|
201
203
|
let { text: s } = oe(o.content);
|
|
202
|
-
s.trim() &&
|
|
204
|
+
s.trim() && he.current(a, s, o.metadata?.lang);
|
|
203
205
|
});
|
|
204
206
|
}, [
|
|
205
207
|
L,
|
|
206
208
|
z,
|
|
209
|
+
B,
|
|
207
210
|
g
|
|
208
211
|
]);
|
|
209
|
-
let
|
|
212
|
+
let ge = v(() => d(D, W.tag), [D, W]), _e = v(() => c(D, W.tag, H[G]), [
|
|
210
213
|
D,
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
]),
|
|
215
|
-
isSupported:
|
|
216
|
-
availability:
|
|
217
|
-
isBlocked:
|
|
218
|
-
disabledReason:
|
|
219
|
-
blockedFor:
|
|
220
|
-
voiceChoices:
|
|
221
|
-
activeVoiceName:
|
|
222
|
-
preferredVoiceName:
|
|
223
|
-
setVoice: (e) =>
|
|
214
|
+
W,
|
|
215
|
+
H,
|
|
216
|
+
G
|
|
217
|
+
]), ve = v(() => ({
|
|
218
|
+
isSupported: B,
|
|
219
|
+
availability: J,
|
|
220
|
+
isBlocked: J === "no-voices",
|
|
221
|
+
disabledReason: J === "no-voices" ? C("healthybowl.assistant.speech.noVoicesOnDevice", "This device has no speech voices installed. Add one in your device speech or accessibility settings.") : null,
|
|
222
|
+
blockedFor: Z,
|
|
223
|
+
voiceChoices: ge,
|
|
224
|
+
activeVoiceName: _e?.name ?? null,
|
|
225
|
+
preferredVoiceName: H[G] ?? null,
|
|
226
|
+
setVoice: (e) => U(G, e),
|
|
224
227
|
speakingMessageId: T.status === "speaking" ? T.messageId : null,
|
|
225
228
|
isSpeaking: (e) => p(T, e),
|
|
226
|
-
toggle:
|
|
227
|
-
stop:
|
|
229
|
+
toggle: me,
|
|
230
|
+
stop: X,
|
|
228
231
|
autoSpeakEnabled: L,
|
|
229
|
-
setAutoSpeak: R
|
|
232
|
+
setAutoSpeak: R,
|
|
233
|
+
sessionSpeaking: z,
|
|
234
|
+
setSessionSpeaking: de
|
|
230
235
|
}), [
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
V,
|
|
236
|
+
B,
|
|
237
|
+
J,
|
|
238
|
+
Z,
|
|
239
|
+
ge,
|
|
240
|
+
_e,
|
|
237
241
|
H,
|
|
238
|
-
|
|
242
|
+
U,
|
|
243
|
+
G,
|
|
239
244
|
T,
|
|
240
|
-
|
|
241
|
-
|
|
245
|
+
me,
|
|
246
|
+
X,
|
|
242
247
|
L,
|
|
243
248
|
R,
|
|
249
|
+
z,
|
|
244
250
|
C
|
|
245
251
|
]);
|
|
246
252
|
return /* @__PURE__ */ le(x.Provider, {
|
|
247
|
-
value:
|
|
253
|
+
value: ve,
|
|
248
254
|
children: m
|
|
249
255
|
});
|
|
250
256
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AssistantSpeechProvider.js","names":[],"sources":["../../../src/components/assistant/AssistantSpeechProvider.tsx"],"sourcesContent":["/**\n * Speech-output context for the assistant panel (BOFF-6290).\n *\n * The assistant could already hear (`useVoiceInput`); this is the other half —\n * it can now answer out loud. That matters for a farming product where the user\n * is outdoors with dirty hands, a phone in a pocket and sun on the screen, and\n * it is a plain accessibility win everywhere else.\n *\n * Everything stateful about playback lives here, once, so that:\n *\n * - **playback is never orphaned.** A voice that keeps talking after the UI is\n * gone is a bug, so speech is cancelled when the panel hides, when the\n * conversation changes, on unmount, and on `pagehide` (Chrome keeps speaking\n * across a navigation otherwise);\n * - **only one message speaks at a time.** Starting a new playback cancels the\n * previous one — enforced by the engine and by the request-id guard in\n * `speechPlaybackReducer`;\n * - **nothing ever autoplays.** Playback starts from a button press. The\n * persisted auto-speak preference defaults OFF and is opt-in from the header.\n *\n * Components consume this through `useAssistantSpeech()`, which falls back to an\n * inert value when there is no provider (Storybook, a header rendered on its\n * own) rather than throwing.\n */\n\nimport {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useReducer,\n useRef,\n useState,\n type FC,\n type ReactNode,\n} from 'react';\nimport { useI18n } from '@burdenoff/fe-libs/shared/providers/shell/I18nProvider';\nimport { useAssistantStore } from '@/store/assistantStore';\nimport { getSpeechEngine } from '../../services/speech';\nimport type { SpeechEngine, SpeechVoiceLike } from '../../services/speech';\nimport { chunkForSpeech, toSpeakableText, type SpeakableLabels } from '../../utils/speakableText';\nimport { speechLabelsFor } from '../../config/speechLabels';\n\n/**\n * The speakable transformation with nothing of ours added — used ONLY to decide\n * the reply's language.\n *\n * Detection needs the prose that will be spoken: code blocks and URLs stripped\n * (they are never read aloud, and their Latin identifiers would outvote short\n * non-Latin prose), but no substitute wording introduced either (that would let\n * our own app-locale words vote instead).\n */\nconst SILENT_LABELS: SpeakableLabels = {\n codeBlock: '',\n image: '',\n link: '',\n largeTable: '',\n truncated: '',\n emailAt: 'at',\n emailDot: 'dot',\n nestedItem: '',\n};\nimport {\n VOICE_LIST_TIMEOUT_MS,\n languageDisplayName,\n selectVoiceForLocale,\n voicesForLocale,\n speechGate,\n speechLangForLocale,\n voiceAvailability,\n type VoiceAvailability,\n} from '../../utils/speechVoices';\nimport { resolveSpeechLocale } from '../../utils/replyLanguage';\nimport { DEFAULT_SPEECH_RATE, findAssistantLanguage, resolveAssistantLanguage } from '../../config/assistantLanguages';\nimport { IDLE_PLAYBACK, isSpeakingMessage, speechPlaybackReducer } from '../../utils/speechPlayback';\nimport { isTurnInFlight } from '../../utils/assistantTurnState';\nimport { parseToolActivity } from './AssistantToolActivity';\nimport { useTr } from '../../shared/hooks/useTr';\n\nexport interface AssistantSpeechContextValue {\n /** False when the platform has no speech output — hide the control entirely. */\n isSupported: boolean;\n availability: VoiceAvailability;\n /**\n * True when nothing can be spoken in the app language, so every control that\n * starts playback — the per-message button AND the header toggle — must be\n * inert. `pending` is not blocked: see `speechGate`.\n */\n isBlocked: boolean;\n /** Explains a disabled control (no installed voice for the app language). */\n disabledReason: string | null;\n /**\n * Why THIS message cannot be spoken, when the app language is fine but the\n * reply is not in it — a Tamil answer in an English UI on a device with no\n * Tamil voice. `isBlocked` cannot see that: it is computed before any reply\n * exists. Without this the control looks enabled and silently refuses, which\n * is the dead-button bug all over again (BOFF-7106).\n */\n blockedFor: (messageId: string) => string | null;\n /**\n * Every installed voice that can read the language the user speaks, best\n * first. Empty when there is no choice to offer — the picker hides itself\n * rather than showing a one-item dropdown.\n */\n voiceChoices: readonly SpeechVoiceLike[];\n /** The voice that will actually be used, resolved from the pick + ranking. */\n activeVoiceName: string | null;\n /**\n * The RAW stored pick: `null` means \"use the ranked default\".\n *\n * The picker must be driven by this rather than by `activeVoiceName`, or the\n * two states collapse — with nothing stored, the ranked winner is already the\n * shown option, so choosing it fires no change event and the pick can never\n * be made. The user's voice would then silently move the next time the device\n * installs a higher-ranked one. Same trap as the language selector.\n */\n preferredVoiceName: string | null;\n /** `null` restores the ranked default for the current language. */\n setVoice: (voiceName: string | null) => void;\n /** The message currently being spoken, if any. */\n speakingMessageId: string | null;\n isSpeaking: (messageId: string) => boolean;\n /**\n * Speak this message, or stop if it is already the one speaking.\n *\n * `turnLocale` is the language the reply was GENERATED under, from the\n * message's own metadata. It matters because script detection cannot separate\n * Latin-script languages, so without it an old French reply would be read\n * with whatever voice the CURRENT preference selects.\n */\n toggle: (messageId: string, markdown: string, turnLocale?: string) => void;\n stop: () => void;\n autoSpeakEnabled: boolean;\n setAutoSpeak: (enabled: boolean) => void;\n}\n\nconst INERT_SPEECH: AssistantSpeechContextValue = {\n isSupported: false,\n availability: 'unsupported',\n isBlocked: true,\n disabledReason: null,\n blockedFor: () => null,\n voiceChoices: [],\n activeVoiceName: null,\n preferredVoiceName: null,\n setVoice: () => {},\n speakingMessageId: null,\n isSpeaking: () => false,\n toggle: () => {},\n stop: () => {},\n autoSpeakEnabled: false,\n setAutoSpeak: () => {},\n};\n\nconst AssistantSpeechContext = createContext<AssistantSpeechContextValue>(INERT_SPEECH);\n\nexport function useAssistantSpeech(): AssistantSpeechContextValue {\n return useContext(AssistantSpeechContext);\n}\n\ninterface Props {\n children: ReactNode;\n /** Panel visibility. Hiding the panel stops the voice. */\n visible?: boolean;\n /**\n * Injectable for tests and local experiments. The default routes between the\n * device engine and the hosted one; with hosted TTS unconfigured it IS the\n * device engine, unchanged.\n */\n engine?: SpeechEngine;\n}\n\nexport const AssistantSpeechProvider: FC<Props> = ({ children, visible = true, engine = getSpeechEngine() }) => {\n const tr = useTr();\n const { locale } = useI18n();\n const [playback, dispatch] = useReducer(speechPlaybackReducer, IDLE_PLAYBACK);\n const [voices, setVoices] = useState<SpeechVoiceLike[]>(() => engine.listVoices());\n /**\n * True once we have waited out the voice list and it was still empty.\n *\n * Turns an indefinite `pending` into a terminal `no-voices`, which is what\n * lets the control be disabled with a reason instead of silently doing\n * nothing on every press.\n */\n const [voiceProbeSettled, setVoiceProbeSettled] = useState(false);\n /**\n * Every message we have refused, and why — keyed by id (see `blockedFor`).\n *\n * A single record could only describe one refusal: refusing a second reply\n * silently re-enabled the first, whose voice was still just as missing, so\n * pressing the buttons walked the disabled state around the transcript.\n */\n const [unspeakable, setUnspeakable] = useState<ReadonlyMap<string, string>>(() => new Map());\n const requestRef = useRef(0);\n /** Cancels a playback that is waiting for the engine's voice list, if any. */\n const pendingRef = useRef<(() => void) | null>(null);\n const speakWithRef = useRef<\n (messageId: string, text: string, voices: readonly SpeechVoiceLike[], speechLocale: string) => void\n >(() => {});\n\n const cancelPending = useCallback(() => {\n pendingRef.current?.();\n pendingRef.current = null;\n }, []);\n\n const autoSpeakEnabled = useAssistantStore((state) => state.autoSpeakEnabled);\n const setAutoSpeak = useAssistantStore((state) => state.setAutoSpeak);\n const activeConversationId = useAssistantStore((state) => state.activeConversationId);\n\n const isSupported = useMemo(() => engine.isSupported(), [engine]);\n\n // getVoices() is empty on the first call in Chrome and only fills in when\n // 'voiceschanged' fires; Safari populates it synchronously and may never fire\n // the event. Read eagerly AND subscribe, so both engines end up correct.\n useEffect(() => {\n if (!isSupported) return;\n const sync = () => {\n setVoices(engine.listVoices());\n // Every recorded refusal was \"no voice for this language\". A new voice\n // list may well have supplied one — most likely because the user just\n // followed our instructions and installed it. Keeping the refusals would\n // leave those buttons disabled with no way back except a reload.\n setUnspeakable((current) => (current.size === 0 ? current : new Map()));\n };\n sync();\n return engine.subscribeVoices(sync);\n }, [engine, isSupported]);\n\n // The language the user chose to converse in — not the interface language.\n // Completes the \"one selection drives three things\" promise: recogniser,\n // reply, and the voice that reads it (BOFF-7108).\n const assistantLanguage = useAssistantStore((state) => state.assistantLanguage);\n const preferredVoices = useAssistantStore((state) => state.preferredVoices);\n const setPreferredVoice = useAssistantStore((state) => state.setPreferredVoice);\n const spokenLanguage = useMemo(\n () => resolveAssistantLanguage(assistantLanguage, locale),\n [assistantLanguage, locale]\n );\n const spokenLocale = spokenLanguage.code;\n\n /**\n * BCP-47 tag to ask the engine for, given a resolved language CODE.\n *\n * Resolved through the catalogue for ANY known code, not merely the currently\n * selected one — a historical Bengali reply must still get `bn-IN` after the\n * user switches to Tamil, or with both `bn-IN` and `bn-BD` installed the\n * engine's own order decides, and picks the wrong country.\n *\n * Falls back to the generic table for codes the catalogue does not carry.\n */\n const tagFor = useCallback((code: string) => findAssistantLanguage(code)?.tag ?? speechLangForLocale(code), []);\n\n /** Speaking rate for a resolved language code — see `AssistantLanguage.rate`. */\n const rateFor = useCallback((code: string) => findAssistantLanguage(code)?.rate ?? DEFAULT_SPEECH_RATE, []);\n\n const availability = useMemo(\n () => voiceAvailability(isSupported, voices, spokenLanguage.tag, voiceProbeSettled),\n [isSupported, voices, spokenLanguage, voiceProbeSettled]\n );\n\n // Spoken placeholders follow the app locale like the rest of the copy; the\n // transformation itself stays a pure function by taking them as arguments.\n const labels = useMemo<SpeakableLabels>(\n () => ({\n codeBlock: tr('healthybowl.assistant.speech.codeBlock', 'Code block'),\n image: tr('healthybowl.assistant.speech.image', 'image'),\n link: tr('healthybowl.assistant.speech.link', 'link'),\n largeTable: tr('healthybowl.assistant.speech.largeTable', 'Table with {{rows}} rows and {{columns}} columns'),\n truncated: tr('healthybowl.assistant.speech.truncated', 'The rest of this message is not read aloud'),\n nestedItem: tr('healthybowl.assistant.speech.nestedItem', 'Sub-item {{ordinal}}'),\n emailAt: tr('healthybowl.assistant.speech.emailAt', 'at'),\n emailDot: tr('healthybowl.assistant.speech.emailDot', 'dot'),\n }),\n [tr]\n );\n\n const stop = useCallback(() => {\n cancelPending();\n engine.cancel();\n dispatch({ type: 'stop' });\n }, [cancelPending, engine]);\n\n const blockedFor = useCallback((messageId: string) => unspeakable.get(messageId) ?? null, [unspeakable]);\n\n /**\n * Hold one playback until the engine publishes its voice list.\n *\n * Bounded: on timeout we take one last look and decide with whatever is\n * there, so an engine that never fires `voiceschanged` costs a two-second\n * wait rather than a control that is disabled forever. Nothing is spoken from\n * here unless a list actually arrives — an empty list means the engine would\n * pick its own default voice, which is the cross-language read this feature\n * promises never to do.\n */\n const waitForVoices = useCallback(\n (messageId: string, text: string, speechLocale: string) => {\n cancelPending();\n\n let settled = false;\n let unsubscribe = () => {};\n const finish = (available: SpeechVoiceLike[]) => {\n if (settled) return;\n settled = true;\n pendingRef.current = null;\n clearTimeout(timer);\n unsubscribe();\n if (available.length === 0) {\n // We waited and looked again: this device has no voices at all.\n // Record it so `availability` becomes `no-voices` and the control\n // explains itself, instead of returning silently every press.\n setVoiceProbeSettled(true);\n return;\n }\n setVoices(available);\n speakWithRef.current(messageId, text, available, speechLocale);\n };\n\n const timer = setTimeout(() => finish(engine.listVoices()), VOICE_LIST_TIMEOUT_MS);\n unsubscribe = engine.subscribeVoices(() => finish(engine.listVoices()));\n\n pendingRef.current = () => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n unsubscribe();\n pendingRef.current = null;\n };\n },\n [cancelPending, engine]\n );\n\n /**\n * Speak text against a KNOWN voice list.\n *\n * Every playback path funnels through here — the per-message button, the\n * header toggle's auto-speak, the store subscription — so the language gate\n * cannot be bypassed by any of them. Reading a Tamil reply with an English\n * voice is confident nonsense; it has to be impossible, not merely unlikely.\n */\n const speakWith = useCallback(\n (messageId: string, text: string, available: readonly SpeechVoiceLike[], speechLocale: string) => {\n let known = available;\n\n // Chrome answers the FIRST getVoices() with [] and fills the list in\n // asynchronously. One more synchronous read usually settles it.\n if (known.length === 0) {\n const refreshed = engine.listVoices();\n if (refreshed.length > 0) {\n known = refreshed;\n setVoices(refreshed);\n }\n }\n\n const speechLang = tagFor(speechLocale);\n\n const gate = speechGate(voiceAvailability(true, known, speechLocale, voiceProbeSettled));\n if (gate === 'block') {\n // Recorded for THIS message, always. Availability is resolved per reply\n // now, so a global \"your language has no voice\" cannot stand in for it:\n // the language the user chose to converse in says nothing about the one\n // this particular reply came back in.\n const reason = tr(\n 'healthybowl.assistant.speech.noVoiceForReply',\n 'This reply is in {{language}}, and no {{language}} voice is installed on this device.',\n { language: languageDisplayName(speechLang, locale) }\n );\n setUnspeakable((current) => new Map(current).set(messageId, reason));\n return;\n }\n if (gate === 'wait-for-voices') {\n waitForVoices(messageId, text, speechLocale);\n return;\n }\n\n setUnspeakable((current) => {\n if (!current.has(messageId)) return current;\n const next = new Map(current);\n next.delete(messageId);\n return next;\n });\n\n const requestId = requestRef.current + 1;\n requestRef.current = requestId;\n dispatch({ type: 'start', messageId, requestId });\n\n engine.speak(\n chunkForSpeech(text),\n // The TAG, not the code — so exact regional matching gets its chance\n // before the same-language fallback. `rate` had never been passed at\n // all, so every reply was read at the engine default.\n {\n voice: selectVoiceForLocale(known, speechLang, preferredVoices[speechLocale]),\n lang: speechLang,\n rate: rateFor(speechLocale),\n },\n {\n onEnd: () => dispatch({ type: 'finished', requestId }),\n // Includes the 'cancelled' every queued utterance reports when we\n // pre-empt a batch; the request-id guard drops those as stale.\n onError: () => dispatch({ type: 'failed', requestId }),\n }\n );\n },\n [engine, locale, preferredVoices, rateFor, tagFor, tr, voiceProbeSettled, waitForVoices]\n );\n\n // `waitForVoices` resumes through this ref, so the two do not become a\n // circular hook dependency.\n useEffect(() => {\n speakWithRef.current = speakWith;\n }, [speakWith]);\n\n const speak = useCallback(\n (messageId: string, markdown: string, turnLocale?: string) => {\n if (!isSupported) return;\n\n // Resolve the reply's language BEFORE building the spoken text, because\n // the stand-in words must be in that language. Detection deliberately runs\n // on a SILENT_LABELS pass — our own words must not vote on which language\n // the reply is in — so it does not depend on the labels chosen here.\n const replyLocale = resolveSpeechLocale(\n toSpeakableText(markdown, { labels: SILENT_LABELS }),\n turnLocale ?? spokenLocale\n );\n\n // ★ Labels in the REPLY's language, not the interface's. An English\n // interface reading a Tamil answer used to say \"Code block\" and \"image\" in\n // English, mid-Tamil-sentence — the same defect the email `at`/`dot` fix\n // addressed and did not generalise.\n const text = toSpeakableText(markdown, { labels: speechLabelsFor(replyLocale, labels) });\n if (!text) return;\n\n // Detect on the text that will actually be SPOKEN, with our own words\n // removed — neither the raw markdown nor the finished transformation.\n //\n // The transformation injects app-locale placeholders (\"Code block\"), which\n // let English chrome outvote short non-Latin prose. The raw markdown keeps\n // fenced code, whose Latin identifiers do the same thing — and that code is\n // never spoken at all. Running the same transformation with EMPTY labels\n // strips the unspoken constructs while contributing no words of its own,\n // which is exactly the denominator the decision needs.\n // The turn's OWN language first — the preference is only a stand-in for\n // replies that predate it. Resolved above, and reused rather than\n // recomputed.\n speakWith(messageId, text, voices, replyLocale);\n },\n [isSupported, labels, spokenLocale, speakWith, voices]\n );\n\n const toggle = useCallback(\n (messageId: string, markdown: string, turnLocale?: string) => {\n if (isSpeakingMessage(playback, messageId)) {\n stop();\n return;\n }\n speak(messageId, markdown, turnLocale);\n },\n [playback, speak, stop]\n );\n\n // ── Never leave a voice talking to an empty room ─────────────────────────\n useEffect(() => {\n if (!visible) stop();\n }, [visible, stop]);\n\n useEffect(() => {\n // Switching (or creating) a conversation abandons the reply being read —\n // and the refusal explained a message that is no longer on screen.\n stop();\n setUnspeakable(new Map());\n }, [activeConversationId, stop]);\n\n useEffect(() => {\n // Every refusal was decided against the locale in force at the time, which\n // is what a Latin-script reply falls back to. Change the locale and those\n // verdicts may simply be wrong — an English reply refused on a\n // Spanish-only device would stay disabled forever after switching the UI to\n // Spanish, with the voice that could read it already installed.\n setUnspeakable((current) => (current.size === 0 ? current : new Map()));\n // And stop anything mid-sentence. The new language can make this message\n // unspeakable, which disables its button — leaving it reading \"Stop\" with no\n // way to actually stop, short of closing the panel.\n stop();\n }, [spokenLocale, stop]);\n\n useEffect(() => {\n return () => {\n pendingRef.current?.();\n pendingRef.current = null;\n engine.cancel();\n };\n }, [engine]);\n\n useEffect(() => {\n if (typeof window === 'undefined') return;\n // Chrome carries speech across a same-tab navigation and a bfcache restore\n // would otherwise come back mid-sentence.\n const handlePageHide = () => engine.cancel();\n window.addEventListener('pagehide', handlePageHide);\n return () => window.removeEventListener('pagehide', handlePageHide);\n }, [engine]);\n\n // ── One timeout is not a life sentence ───────────────────────────────────\n //\n // `no-voices` disables the control, and a disabled control can never reach\n // `speakWith` — the only path that re-reads `engine.listVoices()`. So without\n // this, a user who follows our own advice, leaves to install a voice and comes\n // back stays blocked until a reload: we would be telling them how to fix it\n // and then refusing to notice that they had.\n //\n // Returning to the tab is exactly when that happens, and it costs one\n // synchronous read of an already-populated list.\n useEffect(() => {\n if (typeof document === 'undefined' || !isSupported) return;\n const reprobe = () => {\n if (document.visibilityState !== 'visible') return;\n // Adopt the list UNCONDITIONALLY, including an empty one. Keeping the old\n // cache on an empty read means a user who uninstalled their last voice\n // stays `ready`, and playback then hands the engine a voice object that no\n // longer exists instead of explaining the problem.\n //\n // Safe to accept an empty read here precisely because the probe verdict is\n // cleared on the next line: empty + unsettled is `pending`, which leaves\n // the control ENABLED and defers the real decision to the next press.\n const available = engine.listVoices();\n // A Listen press may still be inside its two-second wait. Adopting voices\n // here flips the control to `ready`, so the user can press again and start\n // playback — and then the original timer fires, calls back into\n // `speakWith` for the same message, and the engine cancels and restarts it\n // mid-sentence. Retire the waiter as part of adopting the list.\n if (available.length > 0) cancelPending();\n setVoices(available);\n setVoiceProbeSettled(false);\n // Same reason the `voiceschanged` path clears them: every refusal meant\n // \"no voice for this language\", and this is the moment a user who went\n // away to install one comes back. `subscribeVoices` does not fire on an\n // eventless engine, which is precisely why this re-probe exists — so it\n // has to expire the refusals too.\n setUnspeakable((current) => (current.size === 0 ? current : new Map()));\n };\n document.addEventListener('visibilitychange', reprobe);\n window.addEventListener('focus', reprobe);\n return () => {\n document.removeEventListener('visibilitychange', reprobe);\n window.removeEventListener('focus', reprobe);\n };\n }, [cancelPending, engine, isSupported]);\n\n // ── Opt-in auto-speak ────────────────────────────────────────────────────\n const speakRef = useRef(speak);\n useEffect(() => {\n speakRef.current = speak;\n }, [speak]);\n\n useEffect(() => {\n // `isBlocked` is the same gate the per-message button uses. Without it the\n // subscription fires on a device with no voice for the app language and the\n // engine reads a Tamil reply in English — the one thing this feature says\n // it will never do. `pending` is allowed through because `speakWith` waits\n // for the list before deciding.\n // NOT gated on `isSpeechBlocked(availability)` any more: that is the APP\n // language's availability, and it would suppress auto-speak for a reply in\n // a language this device CAN speak. `speakWith` resolves the reply's own\n // language and refuses safely there, which is the only place that can know.\n if (!autoSpeakEnabled || !visible || !isSupported) return;\n\n // Deliberately a store subscription keyed on the processing TRANSITION\n // rather than an effect over the message list: it fires only on the\n // in-flight → complete edge of the active conversation, so mounting the\n // panel, loading history or switching chats can never start talking.\n return useAssistantStore.subscribe((next, previous) => {\n const conversationId = next.activeConversationId;\n if (!conversationId || conversationId !== previous.activeConversationId) return;\n\n const current = next.processingByConversationId[conversationId];\n const before = previous.processingByConversationId[conversationId];\n if (current?.status !== 'complete' || !isTurnInFlight(before?.status)) return;\n\n const messageId = current.messageId ?? before?.messageId ?? null;\n if (!messageId) return;\n\n const message = next.conversations\n .find((conversation) => conversation.id === conversationId)\n ?.messages.find((candidate) => candidate.id === messageId);\n if (!message || message.role !== 'assistant') return;\n\n // Same split the transcript uses: speak the prose, not the tool log.\n const { text } = parseToolActivity(message.content);\n if (!text.trim()) return;\n\n speakRef.current(messageId, text, (message.metadata as { lang?: string } | undefined)?.lang);\n });\n }, [autoSpeakEnabled, isSupported, visible]);\n\n // The candidates for the language the user SPEAKS — the picker is a setting,\n // so it must not follow whatever language the last reply happened to be in.\n const voiceChoices = useMemo(() => voicesForLocale(voices, spokenLanguage.tag), [voices, spokenLanguage]);\n const activeVoice = useMemo(\n () => selectVoiceForLocale(voices, spokenLanguage.tag, preferredVoices[spokenLocale]),\n [voices, spokenLanguage, preferredVoices, spokenLocale]\n );\n\n const value = useMemo<AssistantSpeechContextValue>(\n () => ({\n isSupported,\n availability,\n // ONLY `no-voices` — a device with no voices at all can never speak\n // anything. `missing-voice` means the APP language has none, which says\n // nothing about the language a given reply came back in; that case is\n // resolved per message by `blockedFor`.\n isBlocked: availability === 'no-voices',\n // Both blocked states are the user's device, not our bug — so the copy\n // names the language and says where to fix it. \"Nothing happened\" was\n // the old behaviour and it read as a broken feature.\n disabledReason:\n availability === 'no-voices'\n ? tr(\n 'healthybowl.assistant.speech.noVoicesOnDevice',\n 'This device has no speech voices installed. Add one in your device speech or accessibility settings.'\n )\n : null,\n blockedFor,\n voiceChoices,\n activeVoiceName: activeVoice?.name ?? null,\n preferredVoiceName: preferredVoices[spokenLocale] ?? null,\n setVoice: (voiceName: string | null) => setPreferredVoice(spokenLocale, voiceName),\n speakingMessageId: playback.status === 'speaking' ? playback.messageId : null,\n isSpeaking: (messageId: string) => isSpeakingMessage(playback, messageId),\n toggle,\n stop,\n autoSpeakEnabled,\n setAutoSpeak,\n }),\n [\n isSupported,\n availability,\n blockedFor,\n voiceChoices,\n activeVoice,\n preferredVoices,\n setPreferredVoice,\n spokenLocale,\n playback,\n toggle,\n stop,\n autoSpeakEnabled,\n setAutoSpeak,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K,cAClB,MAAM,MAAiB,EAAa,OAAO,CAAc,GACxD,SAAS,MAAM,MAAc,EAAU,OAAO,CAAS;GAC3D,IAAI,CAAC,KAAW,EAAQ,SAAS,aAAa;GAG9C,IAAM,EAAE,YAAS,GAAkB,EAAQ,OAAO;GAC7C,EAAK,KAAK,KAEf,GAAS,QAAQ,GAAW,GAAO,EAAQ,UAA4C,IAAI;EAC7F,CAAC;CACH,GAAG;EAAC;EAAkB;EAAa;CAAO,CAAC;CAI3C,IAAM,KAAe,QAAc,EAAgB,GAAQ,EAAe,GAAG,GAAG,CAAC,GAAQ,CAAc,CAAC,GAClG,IAAc,QACZ,EAAqB,GAAQ,EAAe,KAAK,EAAgB,EAAa,GACpF;EAAC;EAAQ;EAAgB;EAAiB;CAAY,CACxD,GAEM,KAAQ,SACL;EACL;EACA;EAKA,WAAW,MAAiB;EAI5B,gBACE,MAAiB,cACb,EACE,iDACA,sGACF,IACA;EACN;EACA;EACA,iBAAiB,GAAa,QAAQ;EACtC,oBAAoB,EAAgB,MAAiB;EACrD,WAAW,MAA6B,EAAkB,GAAc,CAAS;EACjF,mBAAmB,EAAS,WAAW,aAAa,EAAS,YAAY;EACzE,aAAa,MAAsB,EAAkB,GAAU,CAAS;EACxE;EACA;EACA;EACA;CACF,IACA;EACE;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF,CACF;CAEA,OAAO,mBAAC,EAAuB,UAAxB;EAAwC;EAAQ;CAA0C,CAAA;AACnG"}
|
|
1
|
+
{"version":3,"file":"AssistantSpeechProvider.js","names":[],"sources":["../../../src/components/assistant/AssistantSpeechProvider.tsx"],"sourcesContent":["/**\n * Speech-output context for the assistant panel (BOFF-6290).\n *\n * The assistant could already hear (`useVoiceInput`); this is the other half —\n * it can now answer out loud. That matters for a farming product where the user\n * is outdoors with dirty hands, a phone in a pocket and sun on the screen, and\n * it is a plain accessibility win everywhere else.\n *\n * Everything stateful about playback lives here, once, so that:\n *\n * - **playback is never orphaned.** A voice that keeps talking after the UI is\n * gone is a bug, so speech is cancelled when the panel hides, when the\n * conversation changes, on unmount, and on `pagehide` (Chrome keeps speaking\n * across a navigation otherwise);\n * - **only one message speaks at a time.** Starting a new playback cancels the\n * previous one — enforced by the engine and by the request-id guard in\n * `speechPlaybackReducer`;\n * - **nothing ever autoplays.** Playback starts from a button press. The\n * persisted auto-speak preference defaults OFF and is opt-in from the header.\n *\n * Components consume this through `useAssistantSpeech()`, which falls back to an\n * inert value when there is no provider (Storybook, a header rendered on its\n * own) rather than throwing.\n */\n\nimport {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useReducer,\n useRef,\n useState,\n type FC,\n type ReactNode,\n} from 'react';\nimport { useI18n } from '@burdenoff/fe-libs/shared/providers/shell/I18nProvider';\nimport { useAssistantStore } from '@/store/assistantStore';\nimport { getSpeechEngine } from '../../services/speech';\nimport type { SpeechEngine, SpeechVoiceLike } from '../../services/speech';\nimport { chunkForSpeech, toSpeakableText, type SpeakableLabels } from '../../utils/speakableText';\nimport { speechLabelsFor } from '../../config/speechLabels';\n\n/**\n * The speakable transformation with nothing of ours added — used ONLY to decide\n * the reply's language.\n *\n * Detection needs the prose that will be spoken: code blocks and URLs stripped\n * (they are never read aloud, and their Latin identifiers would outvote short\n * non-Latin prose), but no substitute wording introduced either (that would let\n * our own app-locale words vote instead).\n */\nconst SILENT_LABELS: SpeakableLabels = {\n codeBlock: '',\n image: '',\n link: '',\n largeTable: '',\n truncated: '',\n emailAt: 'at',\n emailDot: 'dot',\n nestedItem: '',\n};\nimport {\n VOICE_LIST_TIMEOUT_MS,\n languageDisplayName,\n selectVoiceForLocale,\n voicesForLocale,\n speechGate,\n speechLangForLocale,\n voiceAvailability,\n type VoiceAvailability,\n} from '../../utils/speechVoices';\nimport { resolveSpeechLocale } from '../../utils/replyLanguage';\nimport { DEFAULT_SPEECH_RATE, findAssistantLanguage, resolveAssistantLanguage } from '../../config/assistantLanguages';\nimport { IDLE_PLAYBACK, isSpeakingMessage, speechPlaybackReducer } from '../../utils/speechPlayback';\nimport { isTurnInFlight } from '../../utils/assistantTurnState';\nimport { parseToolActivity } from './AssistantToolActivity';\nimport { useTr } from '../../shared/hooks/useTr';\n\nexport interface AssistantSpeechContextValue {\n /** False when the platform has no speech output — hide the control entirely. */\n isSupported: boolean;\n availability: VoiceAvailability;\n /**\n * True when nothing can be spoken in the app language, so every control that\n * starts playback — the per-message button AND the header toggle — must be\n * inert. `pending` is not blocked: see `speechGate`.\n */\n isBlocked: boolean;\n /** Explains a disabled control (no installed voice for the app language). */\n disabledReason: string | null;\n /**\n * Why THIS message cannot be spoken, when the app language is fine but the\n * reply is not in it — a Tamil answer in an English UI on a device with no\n * Tamil voice. `isBlocked` cannot see that: it is computed before any reply\n * exists. Without this the control looks enabled and silently refuses, which\n * is the dead-button bug all over again (BOFF-7106).\n */\n blockedFor: (messageId: string) => string | null;\n /**\n * Every installed voice that can read the language the user speaks, best\n * first. Empty when there is no choice to offer — the picker hides itself\n * rather than showing a one-item dropdown.\n */\n voiceChoices: readonly SpeechVoiceLike[];\n /** The voice that will actually be used, resolved from the pick + ranking. */\n activeVoiceName: string | null;\n /**\n * The RAW stored pick: `null` means \"use the ranked default\".\n *\n * The picker must be driven by this rather than by `activeVoiceName`, or the\n * two states collapse — with nothing stored, the ranked winner is already the\n * shown option, so choosing it fires no change event and the pick can never\n * be made. The user's voice would then silently move the next time the device\n * installs a higher-ranked one. Same trap as the language selector.\n */\n preferredVoiceName: string | null;\n /** `null` restores the ranked default for the current language. */\n setVoice: (voiceName: string | null) => void;\n /** The message currently being spoken, if any. */\n speakingMessageId: string | null;\n isSpeaking: (messageId: string) => boolean;\n /**\n * Speak this message, or stop if it is already the one speaking.\n *\n * `turnLocale` is the language the reply was GENERATED under, from the\n * message's own metadata. It matters because script detection cannot separate\n * Latin-script languages, so without it an old French reply would be read\n * with whatever voice the CURRENT preference selects.\n */\n toggle: (messageId: string, markdown: string, turnLocale?: string) => void;\n stop: () => void;\n autoSpeakEnabled: boolean;\n setAutoSpeak: (enabled: boolean) => void;\n /**\n * Speak replies for the duration of a live voice session, WITHOUT touching the\n * user's saved preference.\n *\n * ★ Live Voice used to force `autoSpeakEnabled` true and restore it on exit.\n * That field is PERSISTED (assistantStore partialize), and the restore only\n * ran on a clean `end()` — so a reload, a closed tab or a backgrounded webview\n * during a session left auto-speak switched ON for the user permanently, in\n * normal typed chat, with the toggle showing a state they never chose. The\n * default was never wrong; the session was overwriting it.\n *\n * Session-scoped React state instead: it cannot outlive the page, so there is\n * nothing to restore and nothing to leak.\n */\n sessionSpeaking: boolean;\n setSessionSpeaking: (enabled: boolean) => void;\n}\n\nconst INERT_SPEECH: AssistantSpeechContextValue = {\n isSupported: false,\n availability: 'unsupported',\n isBlocked: true,\n disabledReason: null,\n blockedFor: () => null,\n voiceChoices: [],\n activeVoiceName: null,\n preferredVoiceName: null,\n setVoice: () => {},\n speakingMessageId: null,\n isSpeaking: () => false,\n toggle: () => {},\n stop: () => {},\n autoSpeakEnabled: false,\n setAutoSpeak: () => {},\n sessionSpeaking: false,\n setSessionSpeaking: () => {},\n};\n\nconst AssistantSpeechContext = createContext<AssistantSpeechContextValue>(INERT_SPEECH);\n\nexport function useAssistantSpeech(): AssistantSpeechContextValue {\n return useContext(AssistantSpeechContext);\n}\n\ninterface Props {\n children: ReactNode;\n /** Panel visibility. Hiding the panel stops the voice. */\n visible?: boolean;\n /**\n * Injectable for tests and local experiments. The default routes between the\n * device engine and the hosted one; with hosted TTS unconfigured it IS the\n * device engine, unchanged.\n */\n engine?: SpeechEngine;\n}\n\nexport const AssistantSpeechProvider: FC<Props> = ({ children, visible = true, engine = getSpeechEngine() }) => {\n const tr = useTr();\n const { locale } = useI18n();\n const [playback, dispatch] = useReducer(speechPlaybackReducer, IDLE_PLAYBACK);\n const [voices, setVoices] = useState<SpeechVoiceLike[]>(() => engine.listVoices());\n /**\n * True once we have waited out the voice list and it was still empty.\n *\n * Turns an indefinite `pending` into a terminal `no-voices`, which is what\n * lets the control be disabled with a reason instead of silently doing\n * nothing on every press.\n */\n const [voiceProbeSettled, setVoiceProbeSettled] = useState(false);\n /**\n * Every message we have refused, and why — keyed by id (see `blockedFor`).\n *\n * A single record could only describe one refusal: refusing a second reply\n * silently re-enabled the first, whose voice was still just as missing, so\n * pressing the buttons walked the disabled state around the transcript.\n */\n const [unspeakable, setUnspeakable] = useState<ReadonlyMap<string, string>>(() => new Map());\n const requestRef = useRef(0);\n /** Cancels a playback that is waiting for the engine's voice list, if any. */\n const pendingRef = useRef<(() => void) | null>(null);\n const speakWithRef = useRef<\n (messageId: string, text: string, voices: readonly SpeechVoiceLike[], speechLocale: string) => void\n >(() => {});\n\n const cancelPending = useCallback(() => {\n pendingRef.current?.();\n pendingRef.current = null;\n }, []);\n\n const autoSpeakEnabled = useAssistantStore((state) => state.autoSpeakEnabled);\n const setAutoSpeak = useAssistantStore((state) => state.setAutoSpeak);\n // Not in the store on purpose — see `sessionSpeaking` on the context type.\n const [sessionSpeaking, setSessionSpeaking] = useState(false);\n const activeConversationId = useAssistantStore((state) => state.activeConversationId);\n\n const isSupported = useMemo(() => engine.isSupported(), [engine]);\n\n // getVoices() is empty on the first call in Chrome and only fills in when\n // 'voiceschanged' fires; Safari populates it synchronously and may never fire\n // the event. Read eagerly AND subscribe, so both engines end up correct.\n useEffect(() => {\n if (!isSupported) return;\n const sync = () => {\n setVoices(engine.listVoices());\n // Every recorded refusal was \"no voice for this language\". A new voice\n // list may well have supplied one — most likely because the user just\n // followed our instructions and installed it. Keeping the refusals would\n // leave those buttons disabled with no way back except a reload.\n setUnspeakable((current) => (current.size === 0 ? current : new Map()));\n };\n sync();\n return engine.subscribeVoices(sync);\n }, [engine, isSupported]);\n\n // The language the user chose to converse in — not the interface language.\n // Completes the \"one selection drives three things\" promise: recogniser,\n // reply, and the voice that reads it (BOFF-7108).\n const assistantLanguage = useAssistantStore((state) => state.assistantLanguage);\n const preferredVoices = useAssistantStore((state) => state.preferredVoices);\n const setPreferredVoice = useAssistantStore((state) => state.setPreferredVoice);\n const spokenLanguage = useMemo(\n () => resolveAssistantLanguage(assistantLanguage, locale),\n [assistantLanguage, locale]\n );\n const spokenLocale = spokenLanguage.code;\n\n /**\n * BCP-47 tag to ask the engine for, given a resolved language CODE.\n *\n * Resolved through the catalogue for ANY known code, not merely the currently\n * selected one — a historical Bengali reply must still get `bn-IN` after the\n * user switches to Tamil, or with both `bn-IN` and `bn-BD` installed the\n * engine's own order decides, and picks the wrong country.\n *\n * Falls back to the generic table for codes the catalogue does not carry.\n */\n const tagFor = useCallback((code: string) => findAssistantLanguage(code)?.tag ?? speechLangForLocale(code), []);\n\n /** Speaking rate for a resolved language code — see `AssistantLanguage.rate`. */\n const rateFor = useCallback((code: string) => findAssistantLanguage(code)?.rate ?? DEFAULT_SPEECH_RATE, []);\n\n const availability = useMemo(\n () => voiceAvailability(isSupported, voices, spokenLanguage.tag, voiceProbeSettled),\n [isSupported, voices, spokenLanguage, voiceProbeSettled]\n );\n\n // Spoken placeholders follow the app locale like the rest of the copy; the\n // transformation itself stays a pure function by taking them as arguments.\n const labels = useMemo<SpeakableLabels>(\n () => ({\n codeBlock: tr('healthybowl.assistant.speech.codeBlock', 'Code block'),\n image: tr('healthybowl.assistant.speech.image', 'image'),\n link: tr('healthybowl.assistant.speech.link', 'link'),\n largeTable: tr('healthybowl.assistant.speech.largeTable', 'Table with {{rows}} rows and {{columns}} columns'),\n truncated: tr('healthybowl.assistant.speech.truncated', 'The rest of this message is not read aloud'),\n nestedItem: tr('healthybowl.assistant.speech.nestedItem', 'Sub-item {{ordinal}}'),\n emailAt: tr('healthybowl.assistant.speech.emailAt', 'at'),\n emailDot: tr('healthybowl.assistant.speech.emailDot', 'dot'),\n }),\n [tr]\n );\n\n const stop = useCallback(() => {\n cancelPending();\n engine.cancel();\n dispatch({ type: 'stop' });\n }, [cancelPending, engine]);\n\n const blockedFor = useCallback((messageId: string) => unspeakable.get(messageId) ?? null, [unspeakable]);\n\n /**\n * Hold one playback until the engine publishes its voice list.\n *\n * Bounded: on timeout we take one last look and decide with whatever is\n * there, so an engine that never fires `voiceschanged` costs a two-second\n * wait rather than a control that is disabled forever. Nothing is spoken from\n * here unless a list actually arrives — an empty list means the engine would\n * pick its own default voice, which is the cross-language read this feature\n * promises never to do.\n */\n const waitForVoices = useCallback(\n (messageId: string, text: string, speechLocale: string) => {\n cancelPending();\n\n let settled = false;\n let unsubscribe = () => {};\n const finish = (available: SpeechVoiceLike[]) => {\n if (settled) return;\n settled = true;\n pendingRef.current = null;\n clearTimeout(timer);\n unsubscribe();\n if (available.length === 0) {\n // We waited and looked again: this device has no voices at all.\n // Record it so `availability` becomes `no-voices` and the control\n // explains itself, instead of returning silently every press.\n setVoiceProbeSettled(true);\n return;\n }\n setVoices(available);\n speakWithRef.current(messageId, text, available, speechLocale);\n };\n\n const timer = setTimeout(() => finish(engine.listVoices()), VOICE_LIST_TIMEOUT_MS);\n unsubscribe = engine.subscribeVoices(() => finish(engine.listVoices()));\n\n pendingRef.current = () => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n unsubscribe();\n pendingRef.current = null;\n };\n },\n [cancelPending, engine]\n );\n\n /**\n * Speak text against a KNOWN voice list.\n *\n * Every playback path funnels through here — the per-message button, the\n * header toggle's auto-speak, the store subscription — so the language gate\n * cannot be bypassed by any of them. Reading a Tamil reply with an English\n * voice is confident nonsense; it has to be impossible, not merely unlikely.\n */\n const speakWith = useCallback(\n (messageId: string, text: string, available: readonly SpeechVoiceLike[], speechLocale: string) => {\n let known = available;\n\n // Chrome answers the FIRST getVoices() with [] and fills the list in\n // asynchronously. One more synchronous read usually settles it.\n if (known.length === 0) {\n const refreshed = engine.listVoices();\n if (refreshed.length > 0) {\n known = refreshed;\n setVoices(refreshed);\n }\n }\n\n const speechLang = tagFor(speechLocale);\n\n const gate = speechGate(voiceAvailability(true, known, speechLocale, voiceProbeSettled));\n if (gate === 'block') {\n // Recorded for THIS message, always. Availability is resolved per reply\n // now, so a global \"your language has no voice\" cannot stand in for it:\n // the language the user chose to converse in says nothing about the one\n // this particular reply came back in.\n const reason = tr(\n 'healthybowl.assistant.speech.noVoiceForReply',\n 'This reply is in {{language}}, and no {{language}} voice is installed on this device.',\n { language: languageDisplayName(speechLang, locale) }\n );\n setUnspeakable((current) => new Map(current).set(messageId, reason));\n return;\n }\n if (gate === 'wait-for-voices') {\n waitForVoices(messageId, text, speechLocale);\n return;\n }\n\n setUnspeakable((current) => {\n if (!current.has(messageId)) return current;\n const next = new Map(current);\n next.delete(messageId);\n return next;\n });\n\n const requestId = requestRef.current + 1;\n requestRef.current = requestId;\n dispatch({ type: 'start', messageId, requestId });\n\n engine.speak(\n chunkForSpeech(text),\n // The TAG, not the code — so exact regional matching gets its chance\n // before the same-language fallback. `rate` had never been passed at\n // all, so every reply was read at the engine default.\n {\n voice: selectVoiceForLocale(known, speechLang, preferredVoices[speechLocale]),\n lang: speechLang,\n rate: rateFor(speechLocale),\n },\n {\n onEnd: () => dispatch({ type: 'finished', requestId }),\n // Includes the 'cancelled' every queued utterance reports when we\n // pre-empt a batch; the request-id guard drops those as stale.\n onError: () => dispatch({ type: 'failed', requestId }),\n }\n );\n },\n [engine, locale, preferredVoices, rateFor, tagFor, tr, voiceProbeSettled, waitForVoices]\n );\n\n // `waitForVoices` resumes through this ref, so the two do not become a\n // circular hook dependency.\n useEffect(() => {\n speakWithRef.current = speakWith;\n }, [speakWith]);\n\n const speak = useCallback(\n (messageId: string, markdown: string, turnLocale?: string) => {\n if (!isSupported) return;\n\n // Resolve the reply's language BEFORE building the spoken text, because\n // the stand-in words must be in that language. Detection deliberately runs\n // on a SILENT_LABELS pass — our own words must not vote on which language\n // the reply is in — so it does not depend on the labels chosen here.\n const replyLocale = resolveSpeechLocale(\n toSpeakableText(markdown, { labels: SILENT_LABELS }),\n turnLocale ?? spokenLocale\n );\n\n // ★ Labels in the REPLY's language, not the interface's. An English\n // interface reading a Tamil answer used to say \"Code block\" and \"image\" in\n // English, mid-Tamil-sentence — the same defect the email `at`/`dot` fix\n // addressed and did not generalise.\n const text = toSpeakableText(markdown, { labels: speechLabelsFor(replyLocale, labels) });\n if (!text) return;\n\n // Detect on the text that will actually be SPOKEN, with our own words\n // removed — neither the raw markdown nor the finished transformation.\n //\n // The transformation injects app-locale placeholders (\"Code block\"), which\n // let English chrome outvote short non-Latin prose. The raw markdown keeps\n // fenced code, whose Latin identifiers do the same thing — and that code is\n // never spoken at all. Running the same transformation with EMPTY labels\n // strips the unspoken constructs while contributing no words of its own,\n // which is exactly the denominator the decision needs.\n // The turn's OWN language first — the preference is only a stand-in for\n // replies that predate it. Resolved above, and reused rather than\n // recomputed.\n speakWith(messageId, text, voices, replyLocale);\n },\n [isSupported, labels, spokenLocale, speakWith, voices]\n );\n\n const toggle = useCallback(\n (messageId: string, markdown: string, turnLocale?: string) => {\n if (isSpeakingMessage(playback, messageId)) {\n stop();\n return;\n }\n speak(messageId, markdown, turnLocale);\n },\n [playback, speak, stop]\n );\n\n // ── Never leave a voice talking to an empty room ─────────────────────────\n useEffect(() => {\n if (!visible) stop();\n }, [visible, stop]);\n\n useEffect(() => {\n // Switching (or creating) a conversation abandons the reply being read —\n // and the refusal explained a message that is no longer on screen.\n stop();\n setUnspeakable(new Map());\n }, [activeConversationId, stop]);\n\n useEffect(() => {\n // Every refusal was decided against the locale in force at the time, which\n // is what a Latin-script reply falls back to. Change the locale and those\n // verdicts may simply be wrong — an English reply refused on a\n // Spanish-only device would stay disabled forever after switching the UI to\n // Spanish, with the voice that could read it already installed.\n setUnspeakable((current) => (current.size === 0 ? current : new Map()));\n // And stop anything mid-sentence. The new language can make this message\n // unspeakable, which disables its button — leaving it reading \"Stop\" with no\n // way to actually stop, short of closing the panel.\n stop();\n }, [spokenLocale, stop]);\n\n useEffect(() => {\n return () => {\n pendingRef.current?.();\n pendingRef.current = null;\n engine.cancel();\n };\n }, [engine]);\n\n useEffect(() => {\n if (typeof window === 'undefined') return;\n // Chrome carries speech across a same-tab navigation and a bfcache restore\n // would otherwise come back mid-sentence.\n const handlePageHide = () => engine.cancel();\n window.addEventListener('pagehide', handlePageHide);\n return () => window.removeEventListener('pagehide', handlePageHide);\n }, [engine]);\n\n // ── One timeout is not a life sentence ───────────────────────────────────\n //\n // `no-voices` disables the control, and a disabled control can never reach\n // `speakWith` — the only path that re-reads `engine.listVoices()`. So without\n // this, a user who follows our own advice, leaves to install a voice and comes\n // back stays blocked until a reload: we would be telling them how to fix it\n // and then refusing to notice that they had.\n //\n // Returning to the tab is exactly when that happens, and it costs one\n // synchronous read of an already-populated list.\n useEffect(() => {\n if (typeof document === 'undefined' || !isSupported) return;\n const reprobe = () => {\n if (document.visibilityState !== 'visible') return;\n // Adopt the list UNCONDITIONALLY, including an empty one. Keeping the old\n // cache on an empty read means a user who uninstalled their last voice\n // stays `ready`, and playback then hands the engine a voice object that no\n // longer exists instead of explaining the problem.\n //\n // Safe to accept an empty read here precisely because the probe verdict is\n // cleared on the next line: empty + unsettled is `pending`, which leaves\n // the control ENABLED and defers the real decision to the next press.\n const available = engine.listVoices();\n // A Listen press may still be inside its two-second wait. Adopting voices\n // here flips the control to `ready`, so the user can press again and start\n // playback — and then the original timer fires, calls back into\n // `speakWith` for the same message, and the engine cancels and restarts it\n // mid-sentence. Retire the waiter as part of adopting the list.\n if (available.length > 0) cancelPending();\n setVoices(available);\n setVoiceProbeSettled(false);\n // Same reason the `voiceschanged` path clears them: every refusal meant\n // \"no voice for this language\", and this is the moment a user who went\n // away to install one comes back. `subscribeVoices` does not fire on an\n // eventless engine, which is precisely why this re-probe exists — so it\n // has to expire the refusals too.\n setUnspeakable((current) => (current.size === 0 ? current : new Map()));\n };\n document.addEventListener('visibilitychange', reprobe);\n window.addEventListener('focus', reprobe);\n return () => {\n document.removeEventListener('visibilitychange', reprobe);\n window.removeEventListener('focus', reprobe);\n };\n }, [cancelPending, engine, isSupported]);\n\n // ── Opt-in auto-speak ────────────────────────────────────────────────────\n const speakRef = useRef(speak);\n useEffect(() => {\n speakRef.current = speak;\n }, [speak]);\n\n useEffect(() => {\n // `isBlocked` is the same gate the per-message button uses. Without it the\n // subscription fires on a device with no voice for the app language and the\n // engine reads a Tamil reply in English — the one thing this feature says\n // it will never do. `pending` is allowed through because `speakWith` waits\n // for the list before deciding.\n // NOT gated on `isSpeechBlocked(availability)` any more: that is the APP\n // language's availability, and it would suppress auto-speak for a reply in\n // a language this device CAN speak. `speakWith` resolves the reply's own\n // language and refuses safely there, which is the only place that can know.\n // Either the user's own preference, or a live voice session — which speaks\n // by definition and must not have to change that preference to do it.\n if ((!autoSpeakEnabled && !sessionSpeaking) || !visible || !isSupported) return;\n\n // Deliberately a store subscription keyed on the processing TRANSITION\n // rather than an effect over the message list: it fires only on the\n // in-flight → complete edge of the active conversation, so mounting the\n // panel, loading history or switching chats can never start talking.\n return useAssistantStore.subscribe((next, previous) => {\n const conversationId = next.activeConversationId;\n if (!conversationId || conversationId !== previous.activeConversationId) return;\n\n const current = next.processingByConversationId[conversationId];\n const before = previous.processingByConversationId[conversationId];\n if (current?.status !== 'complete' || !isTurnInFlight(before?.status)) return;\n\n const messageId = current.messageId ?? before?.messageId ?? null;\n if (!messageId) return;\n\n const message = next.conversations\n .find((conversation) => conversation.id === conversationId)\n ?.messages.find((candidate) => candidate.id === messageId);\n if (!message || message.role !== 'assistant') return;\n\n // Same split the transcript uses: speak the prose, not the tool log.\n const { text } = parseToolActivity(message.content);\n if (!text.trim()) return;\n\n speakRef.current(messageId, text, (message.metadata as { lang?: string } | undefined)?.lang);\n });\n }, [autoSpeakEnabled, sessionSpeaking, isSupported, visible]);\n\n // The candidates for the language the user SPEAKS — the picker is a setting,\n // so it must not follow whatever language the last reply happened to be in.\n const voiceChoices = useMemo(() => voicesForLocale(voices, spokenLanguage.tag), [voices, spokenLanguage]);\n const activeVoice = useMemo(\n () => selectVoiceForLocale(voices, spokenLanguage.tag, preferredVoices[spokenLocale]),\n [voices, spokenLanguage, preferredVoices, spokenLocale]\n );\n\n const value = useMemo<AssistantSpeechContextValue>(\n () => ({\n isSupported,\n availability,\n // ONLY `no-voices` — a device with no voices at all can never speak\n // anything. `missing-voice` means the APP language has none, which says\n // nothing about the language a given reply came back in; that case is\n // resolved per message by `blockedFor`.\n isBlocked: availability === 'no-voices',\n // Both blocked states are the user's device, not our bug — so the copy\n // names the language and says where to fix it. \"Nothing happened\" was\n // the old behaviour and it read as a broken feature.\n disabledReason:\n availability === 'no-voices'\n ? tr(\n 'healthybowl.assistant.speech.noVoicesOnDevice',\n 'This device has no speech voices installed. Add one in your device speech or accessibility settings.'\n )\n : null,\n blockedFor,\n voiceChoices,\n activeVoiceName: activeVoice?.name ?? null,\n preferredVoiceName: preferredVoices[spokenLocale] ?? null,\n setVoice: (voiceName: string | null) => setPreferredVoice(spokenLocale, voiceName),\n speakingMessageId: playback.status === 'speaking' ? playback.messageId : null,\n isSpeaking: (messageId: string) => isSpeakingMessage(playback, messageId),\n toggle,\n stop,\n autoSpeakEnabled,\n setAutoSpeak,\n sessionSpeaking,\n setSessionSpeaking,\n }),\n [\n isSupported,\n availability,\n blockedFor,\n voiceChoices,\n activeVoice,\n preferredVoices,\n setPreferredVoice,\n spokenLocale,\n playback,\n toggle,\n stop,\n autoSpeakEnabled,\n setAutoSpeak,\n sessionSpeaking,\n tr,\n ]\n );\n\n return <AssistantSpeechContext.Provider value={value}>{children}</AssistantSpeechContext.Provider>;\n};\n"],"mappings":";;;;;;;;;;;;;;;;AAqDA,IAAM,KAAiC;CACrC,WAAW;CACX,OAAO;CACP,MAAM;CACN,YAAY;CACZ,WAAW;CACX,SAAS;CACT,UAAU;CACV,YAAY;AACd,GA+GM,IAAyB,EAA2C;CAnBxE,aAAa;CACb,cAAc;CACd,WAAW;CACX,gBAAgB;CAChB,kBAAkB;CAClB,cAAc,CAAC;CACf,iBAAiB;CACjB,oBAAoB;CACpB,gBAAgB,CAAC;CACjB,mBAAmB;CACnB,kBAAkB;CAClB,cAAc,CAAC;CACf,YAAY,CAAC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,EAAe,GAAG,GAAG,CAAC,GAAQ,CAAc,CAAC,GAClG,KAAc,QACZ,EAAqB,GAAQ,EAAe,KAAK,EAAgB,EAAa,GACpF;EAAC;EAAQ;EAAgB;EAAiB;CAAY,CACxD,GAEM,KAAQ,SACL;EACL;EACA;EAKA,WAAW,MAAiB;EAI5B,gBACE,MAAiB,cACb,EACE,iDACA,sGACF,IACA;EACN;EACA;EACA,iBAAiB,IAAa,QAAQ;EACtC,oBAAoB,EAAgB,MAAiB;EACrD,WAAW,MAA6B,EAAkB,GAAc,CAAS;EACjF,mBAAmB,EAAS,WAAW,aAAa,EAAS,YAAY;EACzE,aAAa,MAAsB,EAAkB,GAAU,CAAS;EACxE;EACA;EACA;EACA;EACA;EACA;CACF,IACA;EACE;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF,CACF;CAEA,OAAO,mBAAC,EAAuB,UAAxB;EAAwC;EAAQ;CAA0C,CAAA;AACnG"}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { loadRazorpayCheckout as e } from "./useOrderPayments.js";
|
|
2
|
+
import { useCallback as t, useMemo as n } from "react";
|
|
3
|
+
import { gql as r } from "@apollo/client";
|
|
4
|
+
import { useMutation as i } from "@apollo/client/react";
|
|
5
|
+
//#region src/healthybowl/hooks/useConsultationPayments.ts
|
|
6
|
+
var a = r`
|
|
7
|
+
mutation CheckoutHealthyBowlConsultation($consultationId: ID!, $context: ContextInput!) {
|
|
8
|
+
checkoutHealthyBowlConsultation(consultationId: $consultationId, context: $context) {
|
|
9
|
+
consultationId
|
|
10
|
+
billingOrderId
|
|
11
|
+
provider
|
|
12
|
+
providerOrderId
|
|
13
|
+
razorpayKeyId
|
|
14
|
+
clientSecret
|
|
15
|
+
subtotal
|
|
16
|
+
taxAmount
|
|
17
|
+
total
|
|
18
|
+
currency
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
`, o = r`
|
|
22
|
+
mutation SyncHealthyBowlConsultationPayment($consultationId: ID!, $context: ContextInput!) {
|
|
23
|
+
syncHealthyBowlConsultationPayment(consultationId: $consultationId, context: $context) {
|
|
24
|
+
id
|
|
25
|
+
status
|
|
26
|
+
paymentStatus
|
|
27
|
+
paymentProvider
|
|
28
|
+
paymentReference
|
|
29
|
+
paidAmount
|
|
30
|
+
paidAt
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
`;
|
|
34
|
+
function s() {
|
|
35
|
+
let r = n(() => ({}), []), [s] = i(a), [c] = i(o);
|
|
36
|
+
return {
|
|
37
|
+
checkoutConsultation: t(async (e) => {
|
|
38
|
+
let t = (await s({ variables: {
|
|
39
|
+
consultationId: e,
|
|
40
|
+
context: r
|
|
41
|
+
} })).data?.checkoutHealthyBowlConsultation;
|
|
42
|
+
if (!t) throw Error("Checkout did not return a payment session");
|
|
43
|
+
return t;
|
|
44
|
+
}, [s, r]),
|
|
45
|
+
syncConsultationPayment: t(async (e) => {
|
|
46
|
+
let t = (await c({ variables: {
|
|
47
|
+
consultationId: e,
|
|
48
|
+
context: r
|
|
49
|
+
} })).data?.syncHealthyBowlConsultationPayment;
|
|
50
|
+
if (!t) throw Error("Payment sync did not return the consultation");
|
|
51
|
+
return t;
|
|
52
|
+
}, [r, c]),
|
|
53
|
+
loadRazorpay: e
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
//#endregion
|
|
57
|
+
export { s as useConsultationPayments };
|
|
58
|
+
|
|
59
|
+
//# sourceMappingURL=useConsultationPayments.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"useConsultationPayments.js","names":[],"sources":["../../../src/healthybowl/hooks/useConsultationPayments.ts"],"sourcesContent":["/**\n * Real expert-consultation payments (BOFF-6030, slice B).\n *\n * The client starts checkout and asks HealthyBowl to settle afterwards. HealthyBowl re-reads the\n * authoritative Payment from global-billing, so this MFE never decides that money arrived or handles\n * card data. The documents stay inline because the committed workspace SDL snapshot predates these\n * operations; adding them under `src/operations/wspace` would make codegen validate them too early.\n */\nimport { gql } from '@apollo/client';\nimport { useMutation } from '@apollo/client/react';\nimport { useCallback, useMemo } from 'react';\nimport type { Consultation } from '../types';\nimport { loadRazorpayCheckout } from './useOrderPayments';\n\n/** Everything the client needs to open the payment provider's checkout for one consultation. */\nexport interface ConsultationCheckout {\n consultationId: string;\n billingOrderId: string;\n /** RAZORPAY / STRIPE — selected by platform billing. */\n provider: string;\n /** Razorpay `order_xxx`; absent when billing routes to another provider. */\n providerOrderId?: string | null;\n /** Publishable Razorpay key returned at runtime by billing, never hard-coded. */\n razorpayKeyId?: string | null;\n /** Stripe client secret; this MFE does not implement the Stripe checkout path yet. */\n clientSecret?: string | null;\n subtotal: number;\n taxAmount: number;\n total: number;\n currency: string;\n}\n\n/** Payment details mirrored by HealthyBowl only after it settles against platform billing. */\nexport type ConsultationPayment = Pick<\n Consultation,\n 'id' | 'status' | 'paymentStatus' | 'paymentProvider' | 'paymentReference' | 'paidAmount' | 'paidAt'\n>;\n\nconst CHECKOUT_CONSULTATION = gql`\n mutation CheckoutHealthyBowlConsultation($consultationId: ID!, $context: ContextInput!) {\n checkoutHealthyBowlConsultation(consultationId: $consultationId, context: $context) {\n consultationId\n billingOrderId\n provider\n providerOrderId\n razorpayKeyId\n clientSecret\n subtotal\n taxAmount\n total\n currency\n }\n }\n`;\n\nconst SYNC_CONSULTATION_PAYMENT = gql`\n mutation SyncHealthyBowlConsultationPayment($consultationId: ID!, $context: ContextInput!) {\n syncHealthyBowlConsultationPayment(consultationId: $consultationId, context: $context) {\n id\n status\n paymentStatus\n paymentProvider\n paymentReference\n paidAmount\n paidAt\n }\n }\n`;\n\ninterface CheckoutConsultationData {\n checkoutHealthyBowlConsultation: ConsultationCheckout;\n}\n\ninterface SyncConsultationPaymentData {\n syncHealthyBowlConsultationPayment: ConsultationPayment;\n}\n\ninterface ConsultationCheckoutVariables {\n consultationId: string;\n context: Record<string, never>;\n}\n\ninterface SyncConsultationPaymentVariables {\n consultationId: string;\n context: Record<string, never>;\n}\n\n/**\n * Starts idempotent platform-billing checkout sessions and settles their authoritative result.\n * `loadRazorpay` deliberately delegates to the shared lazy script loader, so marketplace and\n * consultation checkout inject at most one provider script per page.\n */\nexport function useConsultationPayments() {\n // Wspace identity is gateway-authoritative; this required GraphQL input intentionally carries no\n // client-held workspace id.\n const context = useMemo<Record<string, never>>(() => ({}), []);\n const [checkoutMutation] = useMutation<CheckoutConsultationData, ConsultationCheckoutVariables>(\n CHECKOUT_CONSULTATION\n );\n const [syncMutation] = useMutation<SyncConsultationPaymentData, SyncConsultationPaymentVariables>(\n SYNC_CONSULTATION_PAYMENT\n );\n\n const checkoutConsultation = useCallback(\n async (consultationId: string): Promise<ConsultationCheckout> => {\n const result = await checkoutMutation({ variables: { consultationId, context } });\n const checkout = result.data?.checkoutHealthyBowlConsultation;\n if (!checkout) throw new Error('Checkout did not return a payment session');\n return checkout;\n },\n [checkoutMutation, context]\n );\n\n const syncConsultationPayment = useCallback(\n async (consultationId: string): Promise<ConsultationPayment> => {\n const result = await syncMutation({ variables: { consultationId, context } });\n const consultation = result.data?.syncHealthyBowlConsultationPayment;\n if (!consultation) throw new Error('Payment sync did not return the consultation');\n return consultation;\n },\n [context, syncMutation]\n );\n\n const loadRazorpay = loadRazorpayCheckout;\n\n return { checkoutConsultation, syncConsultationPayment, loadRazorpay };\n}\n"],"mappings":";;;;;AAsCA,IAAM,IAAwB,CAAG;;;;;;;;;;;;;;;GAiB3B,IAA4B,CAAG;;;;;;;;;;;;;AAqCrC,SAAgB,IAA0B;CAGxC,IAAM,IAAU,SAAsC,CAAC,IAAI,CAAC,CAAC,GACvD,CAAC,KAAoB,EACzB,CACF,GACM,CAAC,KAAgB,EACrB,CACF;CAwBA,OAAO;EAAE,sBAtBoB,EAC3B,OAAO,MAA0D;GAE/D,IAAM,KAAW,MADI,EAAiB,EAAE,WAAW;IAAE;IAAgB;GAAQ,EAAE,CAAC,GACxD,MAAM;GAC9B,IAAI,CAAC,GAAU,MAAU,MAAM,2CAA2C;GAC1E,OAAO;EACT,GACA,CAAC,GAAkB,CAAO,CAenB;EAAsB,yBAZC,EAC9B,OAAO,MAAyD;GAE9D,IAAM,KAAe,MADA,EAAa,EAAE,WAAW;IAAE;IAAgB;GAAQ,EAAE,CAAC,GAChD,MAAM;GAClC,IAAI,CAAC,GAAc,MAAU,MAAM,8CAA8C;GACjF,OAAO;EACT,GACA,CAAC,GAAS,CAAY,CAKO;EAAyB,cAAA;CAAa;AACvE"}
|
|
@@ -289,6 +289,11 @@ var Dt = a`
|
|
|
289
289
|
notes
|
|
290
290
|
fee
|
|
291
291
|
status
|
|
292
|
+
paymentStatus
|
|
293
|
+
paymentProvider
|
|
294
|
+
paymentReference
|
|
295
|
+
paidAmount
|
|
296
|
+
paidAt
|
|
292
297
|
createdAt
|
|
293
298
|
}
|
|
294
299
|
}
|
|
@@ -305,6 +310,11 @@ var Dt = a`
|
|
|
305
310
|
notes
|
|
306
311
|
fee
|
|
307
312
|
status
|
|
313
|
+
paymentStatus
|
|
314
|
+
paymentProvider
|
|
315
|
+
paymentReference
|
|
316
|
+
paidAmount
|
|
317
|
+
paidAt
|
|
308
318
|
createdAt
|
|
309
319
|
}
|
|
310
320
|
}
|
|
@@ -321,6 +331,11 @@ var Dt = a`
|
|
|
321
331
|
notes
|
|
322
332
|
fee
|
|
323
333
|
status
|
|
334
|
+
paymentStatus
|
|
335
|
+
paymentProvider
|
|
336
|
+
paymentReference
|
|
337
|
+
paidAmount
|
|
338
|
+
paidAt
|
|
324
339
|
createdAt
|
|
325
340
|
}
|
|
326
341
|
}
|