@burdenoff/microfe-healthybowl 2026.725.6 → 2026.725.7

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.
@@ -13,20 +13,21 @@ import { useAssistantApiAccess as re } from "../../hooks/useAssistantApiAccess.j
13
13
  import { isQuotaExhaustedError as ie } from "../../utils/quotaUtils.js";
14
14
  import { dispatchAssistantQuotaExhausted as ae, notifyAiCreditsUpdated as oe } from "../../utils/aiCredits.js";
15
15
  import { buildPromptForMode as se } from "../../utils/assistantPrompt.js";
16
- import { useCallback as S, useEffect as C, useMemo as ce, useRef as w, useState as le } from "react";
17
- import { jsx as T, jsxs as ue } from "react/jsx-runtime";
18
- import { useGatewayClient as de } from "@burdenoff/fe-libs/shared/graphql";
19
- import { useAuthToken as fe } from "@burdenoff/fe-libs/shared/providers/shell";
16
+ import { useCallback as S, useEffect as C, useMemo as ce, useRef as le, useState as ue } from "react";
17
+ import { jsx as w, jsxs as de } from "react/jsx-runtime";
18
+ import { useGatewayClient as fe } from "@burdenoff/fe-libs/shared/graphql";
19
+ import { useAuthToken as pe } from "@burdenoff/fe-libs/shared/providers/shell";
20
+ import { getAssistantMedia as T } from "@burdenoff/fe-libs/shared/assistant";
20
21
  //#region src/components/assistant/AssistantChatArea.tsx
21
- var pe = {
22
+ var me = {
22
23
  general: 18e4,
23
24
  "api-calls": 18e4,
24
25
  "vibe-plugins": 6e5
25
- }, me = 18e4;
26
- function he() {
26
+ }, he = 18e4;
27
+ function ge() {
27
28
  return `${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;
28
29
  }
29
- function ge(e) {
30
+ function _e(e) {
30
31
  let t = e instanceof Error ? e.message.toLowerCase() : String(e).toLowerCase();
31
32
  return t.includes("rate limit exceeded") || t.includes("unauthorized") || t.includes("k8s api error 401") ? !1 : [
32
33
  "sandbox not found",
@@ -41,7 +42,7 @@ function ge(e) {
41
42
  "session mode mismatch"
42
43
  ].some((e) => t.includes(e));
43
44
  }
44
- function _e(e) {
45
+ function ve(e) {
45
46
  return e.replace(/(Authorization\s*:\s*Bearer\s+)[^\s\n]+/gi, "$1[REDACTED]").replace(/(X-Workspace-Authorization\s*:\s*Bearer\s+)[^\s\n]+/gi, "$1[REDACTED]").replace(/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9._-]+\.[A-Za-z0-9._-]+\b/g, "[REDACTED_JWT]").replace(/\bsk-ant-[A-Za-z0-9-]+\b/g, "[REDACTED_API_KEY]");
46
47
  }
47
48
  function E(e) {
@@ -56,16 +57,20 @@ function O(e) {
56
57
  return t === "completed" ? `Completed: ${n}` : t === "failed" ? `Failed: ${n}` : `Running: ${n}`;
57
58
  });
58
59
  }
59
- function ve(e, t) {
60
+ function k(e, t) {
60
61
  let n = e.filter((e) => e.info?.role === "assistant" && E(e) > t).sort((e, t) => E(e) - E(t));
61
62
  if (n.length === 0) return {
62
63
  content: "Thinking...",
63
64
  done: !1
64
65
  };
65
- let r = n[n.length - 1], i = D(r.parts), a = O(r.parts);
66
+ let r = n[n.length - 1], i = D(r.parts), a = T(r.parts), o = O(r.parts);
66
67
  return {
67
- content: [i, ...a].filter(Boolean).join("\n\n") || "Thinking...",
68
- done: !!r.info?.time?.completed && (!!i || a.length > 0),
68
+ content: [
69
+ i,
70
+ ...a,
71
+ ...o
72
+ ].filter(Boolean).join("\n\n") || "Thinking...",
73
+ done: !!r.info?.time?.completed && (!!i || a.length > 0 || o.length > 0),
69
74
  tokens: r.info?.tokens
70
75
  };
71
76
  }
@@ -77,8 +82,8 @@ function ye(e) {
77
82
  default: return "";
78
83
  }
79
84
  }
80
- var k = () => {
81
- let D = t(), O = de("workspace"), { getAccessToken: k, getWorkspaceToken: be, userId: A } = fe(), { conversations: j, activeConversationId: M, mode: N, processingByConversationId: P, setMode: F, setConversationMode: I, setActiveConversation: xe, createConversation: L, addMessage: R, updateMessage: z, patchMessage: B, setConversationProcessing: V, clearConversationProcessing: Se, setBackendSessionId: H, clearBackendSessionId: U, setSandbox: W, clearSandbox: Ce, acknowledgeApiCalls: we } = e(), G = j.find((e) => e.id === M)?.messages ?? [], K = M ? P[M] : void 0, Te = K?.messageId ?? null, Ee = K?.status === "provisioning" || K?.status === "connecting" || K?.status === "streaming", De = K?.status === "error" ? K.messageId : null, { canUseApiCalls: q, loading: Oe } = re(h()), ke = ce(() => b.filter((e) => !e.requiresAdmin || q), [q]), [J, Y] = le(null), Ae = w([]);
85
+ var A = () => {
86
+ let T = t(), D = fe("workspace"), { getAccessToken: O, getWorkspaceToken: A, userId: j } = pe(), { conversations: be, activeConversationId: M, mode: N, processingByConversationId: P, setMode: F, setConversationMode: I, setActiveConversation: xe, createConversation: L, addMessage: R, updateMessage: z, patchMessage: B, setConversationProcessing: V, clearConversationProcessing: Se, setBackendSessionId: H, clearBackendSessionId: U, setSandbox: W, clearSandbox: Ce, acknowledgeApiCalls: we } = e(), G = be.find((e) => e.id === M)?.messages ?? [], K = M ? P[M] : void 0, Te = K?.status === "provisioning" || K?.status === "connecting" || K?.status === "streaming" ? K.messageId ?? null : null, Ee = K?.status === "provisioning" || K?.status === "connecting" || K?.status === "streaming", De = K?.status === "error" ? K.messageId : null, { canUseApiCalls: q, loading: Oe } = re(h()), ke = ce(() => b.filter((e) => !e.requiresAdmin || q), [q]), [J, Y] = ue(null), Ae = le({});
82
87
  C(() => {
83
88
  if (Oe) return;
84
89
  let e = b.find((e) => e.id === N);
@@ -94,36 +99,36 @@ var k = () => {
94
99
  }, [V, z]), je = S(async (t, n, a, s, c) => {
95
100
  let u = e.getState().sandboxesByMode[a]?.sandboxId ?? null, d = async (e) => {
96
101
  try {
97
- return await p(O, e, s, c, 3e5, (e) => X(t, n, "provisioning", e)), await f(O, e, s, c, 9e4, (e) => X(t, n, "connecting", e)), !0;
102
+ return await p(D, e, s, c, 3e5, (e) => X(t, n, "provisioning", e)), await f(D, e, s, c, 9e4, (e) => X(t, n, "connecting", e)), !0;
98
103
  } catch {
99
104
  return !1;
100
105
  }
101
106
  };
102
107
  if (u && (W(a, u, "provisioning"), X(t, n, "provisioning", "Reusing assistant environment..."), await d(u) || (W(a, null, "provisioning"), u = null)), !u) {
103
108
  X(t, n, "provisioning", "Looking for existing environment...");
104
- let e = await o(O, s, a, c);
109
+ let e = await o(D, s, a, c);
105
110
  e && (W(a, e, "provisioning"), X(t, n, "provisioning", "Reusing assistant environment..."), await d(e) ? u = e : W(a, null, "provisioning"));
106
111
  }
107
112
  if (!u) {
108
- if (a === "api-calls" && !k()) throw Error("API Calls mode requires an authenticated session. Please sign in again.");
109
- X(t, n, "provisioning", "Starting assistant environment..."), W(a, null, "provisioning"), u = await r(O, a, s, c), W(a, u, "provisioning"), await p(O, u, s, c, 3e5, (e) => X(t, n, "provisioning", e)), await f(O, u, s, c, 9e4, (e) => X(t, n, "connecting", e));
113
+ if (a === "api-calls" && !O()) throw Error("API Calls mode requires an authenticated session. Please sign in again.");
114
+ X(t, n, "provisioning", "Starting assistant environment..."), W(a, null, "provisioning"), u = await r(D, a, s, c), W(a, u, "provisioning"), await p(D, u, s, c, 3e5, (e) => X(t, n, "provisioning", e)), await f(D, u, s, c, 9e4, (e) => X(t, n, "connecting", e));
110
115
  }
111
116
  W(a, u, "running");
112
117
  let m = e.getState().conversations.find((e) => e.id === t)?.backendSessionId ?? null;
113
118
  if (m) try {
114
- let e = await l(O, u, s, m, c);
119
+ let e = await l(D, u, s, m, c);
115
120
  if (e.mode !== a) throw Error(`Session mode mismatch: expected ${a}, received ${e.mode}`);
116
121
  } catch {
117
122
  U(t), m = null;
118
123
  }
119
- return m || (X(t, n, "connecting", "Preparing session..."), m = (await i(O, u, s, a, c)).sessionId, H(t, m)), {
124
+ return m || (X(t, n, "connecting", "Preparing session..."), m = (await i(D, u, s, a, c)).sessionId, H(t, m)), {
120
125
  sandboxId: u,
121
126
  sessionId: m
122
127
  };
123
128
  }, [
124
- O,
129
+ D,
125
130
  U,
126
- k,
131
+ O,
127
132
  H,
128
133
  W,
129
134
  X
@@ -134,21 +139,21 @@ var k = () => {
134
139
  }
135
140
  let i = e.getState().mode, o = M, l = o ? e.getState().conversations.find((e) => e.id === o) : void 0;
136
141
  if (o ? l && l.mode !== i && (l.messages.length > 0 || l.backendSessionId) ? o = L(void 0, i) : l && l.mode !== i && I(o, i) : o = L(void 0, i), !o) return;
137
- Ae.current = r;
142
+ Ae.current[o] = r;
138
143
  let f = g(), p = {
139
- accessToken: k(),
140
- workspaceToken: be(),
141
- userId: A,
144
+ accessToken: O(),
145
+ workspaceToken: A(),
146
+ userId: j,
142
147
  organizationId: h()
143
148
  }, v = {
144
- id: he(),
149
+ id: ge(),
145
150
  role: "user",
146
151
  content: t,
147
152
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
148
153
  metadata: r.length ? { attachments: r.map(_) } : void 0
149
154
  };
150
155
  R(o, v);
151
- let y = he();
156
+ let y = ge();
152
157
  R(o, {
153
158
  id: y,
154
159
  role: "assistant",
@@ -157,7 +162,7 @@ var k = () => {
157
162
  });
158
163
  let b = (e, t, n, r) => {
159
164
  B(o, y, {
160
- content: _e(e),
165
+ content: ve(e),
161
166
  metadata: t?.length || n || r ? {
162
167
  artifacts: t,
163
168
  mode: i,
@@ -167,7 +172,7 @@ var k = () => {
167
172
  });
168
173
  }, x = async (e = 1) => {
169
174
  try {
170
- await n(O, f, p);
175
+ await n(D, f, p);
171
176
  } catch (e) {
172
177
  if (ie(e)) {
173
178
  ae("ai-credits"), b("You've run out of AI credits for this billing cycle. Upgrade your plan to keep chatting."), V(o, "error", y, null);
@@ -176,26 +181,26 @@ var k = () => {
176
181
  console.warn("[assistant] AI-credit pre-flight check failed with a non-quota error; proceeding — gateway @usage(checkQuota) still enforces the real budget downstream", e);
177
182
  }
178
183
  try {
179
- let { sandboxId: e, sessionId: n } = await je(o, y, i, f, p), l = (await c(O, e, f, n, p, 50).catch(() => [])).reduce((e, t) => Math.max(e, E(t)), 0);
184
+ let { sandboxId: e, sessionId: n } = await je(o, y, i, f, p), l = (await c(D, e, f, n, p, 50).catch(() => [])).reduce((e, t) => Math.max(e, E(t)), 0);
180
185
  X(o, y, "streaming", "Thinking...");
181
186
  let h = se(i, te(t, r));
182
- await d(O, e, f, n, h, i, m(), p, ee(h, r));
183
- let g = ve([], l), _ = Date.now() + (pe[i] ?? me), v = Date.now();
184
- for (; Date.now() < _ && (g = ve(await c(O, e, f, n, p, 50), l), B(o, y, { content: _e(g.content) }), !g.done);) Date.now() - v > 3e4 && (await a(O, e, f, 600, p).catch(() => void 0), v = Date.now()), await new Promise((e) => setTimeout(e, 1500));
187
+ await d(D, e, f, n, h, i, m(), p, ee(h, r));
188
+ let g = k([], l), _ = Date.now() + (me[i] ?? he), v = Date.now();
189
+ for (; Date.now() < _ && (g = k(await c(D, e, f, n, p, 50), l), B(o, y, { content: ve(g.content) }), !g.done);) Date.now() - v > 3e4 && (await a(D, e, f, 600, p).catch(() => void 0), v = Date.now()), await new Promise((e) => setTimeout(e, 1500));
185
190
  if (!g.done && i !== "vibe-plugins") throw Error("Assistant response timed out while streaming progress");
186
- let x = i === "vibe-plugins" ? await s(O, e, f, n, p).catch(() => []) : void 0;
191
+ let x = i === "vibe-plugins" ? await s(D, e, f, n, p).catch(() => []) : void 0;
187
192
  if (g.done || (g = {
188
193
  ...g,
189
194
  content: `${g.content}\n\n_Still building in the background — any artifacts below will finish shortly. Re-open this conversation to pick up the completed plugin._`
190
195
  }), b(g.content, x, n, e), g.tokens) {
191
196
  B(o, y, { tokens: g.tokens });
192
197
  try {
193
- await u(O, f, n, g.tokens, p), oe();
198
+ await u(D, f, n, g.tokens, p), oe();
194
199
  } catch {}
195
200
  }
196
201
  V(o, "complete", y, null);
197
202
  } catch (t) {
198
- if (e === 1 && ge(t)) return U(o), Ce(i), x(2);
203
+ if (e === 1 && _e(t)) return U(o), Ce(i), x(2);
199
204
  throw t;
200
205
  }
201
206
  };
@@ -213,14 +218,14 @@ var k = () => {
213
218
  }, [
214
219
  M,
215
220
  R,
216
- O,
221
+ D,
217
222
  U,
218
223
  Ce,
219
- j,
224
+ be,
220
225
  L,
221
226
  je,
222
- k,
223
- be,
227
+ O,
228
+ A,
224
229
  B,
225
230
  P,
226
231
  H,
@@ -228,13 +233,17 @@ var k = () => {
228
233
  V,
229
234
  X,
230
235
  z,
231
- A
236
+ j
232
237
  ]), Me = S((e) => {
233
238
  Z(e);
234
239
  }, [Z]), Ne = S(() => {
235
- let e = [...G].reverse().find((e) => e.role === "user");
236
- e && Z(e.content, Ae.current);
237
- }, [G, Z]), Q = w(Z);
240
+ let e = [...G].reverse().find((e) => e.role === "user"), t = M ? Ae.current[M] ?? [] : [];
241
+ e && Z(e.content, t);
242
+ }, [
243
+ G,
244
+ Z,
245
+ M
246
+ ]), Q = le(Z);
238
247
  C(() => {
239
248
  Q.current = Z;
240
249
  }, [Z]), C(() => {
@@ -277,30 +286,30 @@ var k = () => {
277
286
  ]), Ie = S(() => {
278
287
  Y(null);
279
288
  }, []);
280
- return /* @__PURE__ */ ue("div", {
289
+ return /* @__PURE__ */ de("div", {
281
290
  className: "flex flex-1 flex-col overflow-hidden",
282
291
  children: [
283
- G.length === 0 ? /* @__PURE__ */ T(x, {
292
+ G.length === 0 ? /* @__PURE__ */ w(x, {
284
293
  mode: N,
285
294
  onSuggestionClick: Me
286
- }) : /* @__PURE__ */ T("div", {
295
+ }) : /* @__PURE__ */ w("div", {
287
296
  className: "flex min-h-0 flex-1 flex-col",
288
- children: /* @__PURE__ */ T(v, {
297
+ children: /* @__PURE__ */ w(v, {
289
298
  messages: G,
290
299
  streamingMessageId: Te,
291
300
  failedMessageId: De,
292
301
  onRetry: Ne
293
302
  })
294
303
  }),
295
- /* @__PURE__ */ T(ne, {
304
+ /* @__PURE__ */ w(ne, {
296
305
  onSend: (e, t) => void Z(e, t),
297
306
  disabled: Ee,
298
- placeholder: N === "api-calls" ? D("healthybowl.assistant.chatArea.placeholderActions", "What would you like me to do?") : D("healthybowl.assistant.chatArea.placeholderGeneral", "Ask HealthyBowl anything…"),
307
+ placeholder: N === "api-calls" ? T("healthybowl.assistant.chatArea.placeholderActions", "What would you like me to do?") : T("healthybowl.assistant.chatArea.placeholderGeneral", "Ask HealthyBowl anything…"),
299
308
  mode: N,
300
309
  availableModes: ke,
301
310
  onModeChange: Pe
302
311
  }),
303
- /* @__PURE__ */ T(y, {
312
+ /* @__PURE__ */ w(y, {
304
313
  open: J !== null,
305
314
  onConfirm: Fe,
306
315
  onCancel: Ie
@@ -309,6 +318,6 @@ var k = () => {
309
318
  });
310
319
  };
311
320
  //#endregion
312
- export { k as AssistantChatArea };
321
+ export { A as AssistantChatArea };
313
322
 
314
323
  //# sourceMappingURL=AssistantChatArea.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"AssistantChatArea.js","names":[],"sources":["../../../src/components/assistant/AssistantChatArea.tsx"],"sourcesContent":["import { useCallback, useEffect, useMemo, useRef, useState, type FC } from 'react';\nimport { useGatewayClient } from '@burdenoff/fe-libs/shared/graphql';\nimport { useAuthToken } from '@burdenoff/fe-libs/shared/providers/shell';\nimport { AssistantMessageList } from './AssistantMessageList';\nimport { AssistantApiCallsConsentDialog } from './AssistantApiCallsConsentDialog';\nimport { AssistantEmptyState } from './AssistantEmptyState';\nimport { AssistantComposer } from './composer/AssistantComposer';\nimport { useAssistantApiAccess } from '@/hooks/useAssistantApiAccess';\nimport { useAssistantStore } from '@/store/assistantStore';\nimport {\n checkAssistantAiCredits,\n createAssistantSandbox,\n createAssistantSession,\n extendAssistantSandboxTTL,\n findExistingSandbox,\n getAssistantArtifacts,\n getAssistantMessages,\n getAssistantSession,\n reportAssistantAiTokenUsage,\n sendAssistantPromptAsync,\n waitForAssistantServiceReady,\n waitForSandboxReady,\n type AssistantRawMessage,\n type AssistantSandboxAuthContext,\n} from '@/services/assistantApi';\nimport { gatherPageContext } from '@/utils/pageContext';\nimport { getOrganizationId, getWorkspaceId } from '@/utils/assistantContext';\nimport { dispatchAssistantQuotaExhausted, notifyAiCreditsUpdated } from '@/utils/aiCredits';\nimport { isQuotaExhaustedError } from '@/utils/quotaUtils';\nimport { buildPromptForMode } from '@/utils/assistantPrompt';\nimport {\n buildPromptParts,\n buildPromptWithAttachments,\n toMessageAttachment,\n type AssistantAttachment,\n} from '@/utils/assistantAttachments';\nimport { useTr } from '../../shared/hooks/useTr';\nimport { ASSISTANT_MODES } from '@/types/assistant';\nimport type { AssistantArtifact, AssistantConversationStatus, AssistantMode, Message } from '@/types/assistant';\n\n// How long the client streams progress before giving up on a turn. Chat replies\n// (general / api-calls) finish in seconds; a vibe-plugins build is a multi-step\n// pipeline (read docs → scaffold → bun install → bun build → checklist) that runs\n// for minutes, so it gets a much larger budget. The sandbox TTL is auto-extended\n// every 30s during the poll loop, so a longer budget never outlives the sandbox.\nconst STREAM_BUDGET_MS: Record<AssistantMode, number> = {\n general: 180_000,\n 'api-calls': 180_000,\n 'vibe-plugins': 600_000,\n};\nconst DEFAULT_STREAM_BUDGET_MS = 180_000;\n\nfunction generateId(): string {\n return `${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;\n}\n\nfunction isRecoverableAssistantError(error: unknown): boolean {\n const message = error instanceof Error ? error.message.toLowerCase() : String(error).toLowerCase();\n\n if (\n message.includes('rate limit exceeded') ||\n message.includes('unauthorized') ||\n message.includes('k8s api error 401')\n ) {\n return false;\n }\n\n return [\n 'sandbox not found',\n 'sandbox is not running',\n 'sandbox service not available yet',\n 'sandbox failed',\n 'sandbox startup timed out',\n 'assistant service did not become healthy',\n 'proxy error: 404',\n 'proxy error: 502',\n 'proxy error: 503',\n 'session mode mismatch',\n ].some((fragment) => message.includes(fragment));\n}\n\nfunction sanitizeAssistantResponse(response: string): string {\n return response\n .replace(/(Authorization\\s*:\\s*Bearer\\s+)[^\\s\\n]+/gi, '$1[REDACTED]')\n .replace(/(X-Workspace-Authorization\\s*:\\s*Bearer\\s+)[^\\s\\n]+/gi, '$1[REDACTED]')\n .replace(/\\beyJ[A-Za-z0-9_-]+\\.[A-Za-z0-9._-]+\\.[A-Za-z0-9._-]+\\b/g, '[REDACTED_JWT]')\n .replace(/\\bsk-ant-[A-Za-z0-9-]+\\b/g, '[REDACTED_API_KEY]');\n}\n\nfunction getRawMessageCreatedAt(message: AssistantRawMessage): number {\n return message.info?.time?.created ?? 0;\n}\n\nfunction getAssistantText(parts: AssistantRawMessage['parts']): string {\n return (parts ?? [])\n .filter((part) => part.type === 'text' && typeof part.text === 'string')\n .map((part) => part.text?.trim() ?? '')\n .filter(Boolean)\n .join('\\n');\n}\n\nfunction getToolProgress(parts: AssistantRawMessage['parts']): string[] {\n return (parts ?? [])\n .filter((part) => part.type === 'tool' && part.tool)\n .map((part) => {\n const status = part.state?.status ?? 'running';\n const tool = part.tool ?? 'tool';\n if (status === 'completed') return `Completed: ${tool}`;\n if (status === 'failed') return `Failed: ${tool}`;\n return `Running: ${tool}`;\n });\n}\n\nfunction buildAssistantProgress(\n messages: AssistantRawMessage[],\n // The `created` timestamp (sandbox clock) of the newest message that already\n // existed in this session BEFORE the prompt was sent. This turn's reply is the\n // assistant message created strictly after it. Crucially this stays WITHIN the\n // sandbox clock domain: the previous code compared the sandbox-stamped\n // `created` against the browser wall-clock (Date#now), so a reply stamped at\n // prompt-time was silently dropped whenever the sandbox clock lagged the\n // browser — the turn then hung on \"Thinking...\" until the stream budget\n // elapsed. A sandbox-domain floor is immune to clock skew and correct for both\n // fresh and reused (per-conversation) sessions, with no message-window gap.\n priorNewestCreatedMs: number\n): {\n content: string;\n done: boolean;\n tokens?: { input: number; output: number };\n} {\n const relevant = messages\n .filter((message) => message.info?.role === 'assistant' && getRawMessageCreatedAt(message) > priorNewestCreatedMs)\n .sort((left, right) => getRawMessageCreatedAt(left) - getRawMessageCreatedAt(right));\n\n if (relevant.length === 0) {\n return { content: 'Thinking...', done: false };\n }\n\n const latest = relevant[relevant.length - 1]!;\n const text = getAssistantText(latest.parts);\n const toolProgress = getToolProgress(latest.parts);\n const content = [text, ...toolProgress].filter(Boolean).join('\\n\\n') || 'Thinking...';\n\n return {\n content,\n done: Boolean(latest.info?.time?.completed) && (Boolean(text) || toolProgress.length > 0),\n tokens: latest.info?.tokens,\n };\n}\n\nfunction getConversationStatusMessage(status: AssistantConversationStatus): string {\n switch (status) {\n case 'provisioning':\n return 'Starting assistant environment...';\n case 'connecting':\n return 'Connecting to assistant...';\n case 'streaming':\n return 'Thinking...';\n default:\n return '';\n }\n}\n\nexport const AssistantChatArea: FC = () => {\n const tr = useTr();\n const apollo = useGatewayClient('workspace');\n const { getAccessToken, getWorkspaceToken, userId } = useAuthToken();\n\n const {\n conversations,\n activeConversationId,\n mode,\n processingByConversationId,\n setMode,\n setConversationMode,\n setActiveConversation,\n createConversation,\n addMessage,\n updateMessage,\n patchMessage,\n setConversationProcessing,\n clearConversationProcessing,\n setBackendSessionId,\n clearBackendSessionId,\n setSandbox,\n clearSandbox,\n acknowledgeApiCalls,\n } = useAssistantStore();\n\n const activeConversation = conversations.find((conversation) => conversation.id === activeConversationId);\n const messages = activeConversation?.messages ?? [];\n const activeProcessing = activeConversationId ? processingByConversationId[activeConversationId] : undefined;\n const activeStreamingMessageId = activeProcessing?.messageId ?? null;\n const activeIsProcessing =\n activeProcessing?.status === 'provisioning' ||\n activeProcessing?.status === 'connecting' ||\n activeProcessing?.status === 'streaming';\n // The assistant message whose turn ended in an error — drives the Retry\n // affordance in the transcript.\n const failedMessageId = activeProcessing?.status === 'error' ? activeProcessing.messageId : null;\n\n // ── api-calls (write) mode gating ──────────────────────────────────\n // Only a global Owner/Admin may use api-calls (it mints an OAuth app under the\n // caller identity). Re-read the org scope every render (a cheap localStorage\n // read) so the admin gate reacts to an org switch without the panel\n // remounting; the value is a stable string, so useAssistantApiAccess only\n // re-fetches myRoles when the org actually changes. An empty scope simply\n // hides the mode (it could not provision the sandbox anyway).\n const apiCallsScopeId = getOrganizationId();\n const { canUseApiCalls, loading: apiAccessLoading } = useAssistantApiAccess(apiCallsScopeId);\n const availableModes = useMemo(\n () => ASSISTANT_MODES.filter((modeConfig) => !modeConfig.requiresAdmin || canUseApiCalls),\n [canUseApiCalls]\n );\n\n // Target mode awaiting the one-time consent dialog (null = dialog closed).\n const [pendingConsentMode, setPendingConsentMode] = useState<AssistantMode | null>(null);\n\n // Full attachment payload of the last send, kept so Retry can replay it\n // byte-for-byte (see handleRetry).\n const lastSentAttachmentsRef = useRef<AssistantAttachment[]>([]);\n\n // If the active mode is no longer permitted — a non-admin with a persisted\n // api-calls mode, or the master flag turned off — fall back to general, but\n // only AFTER the role check resolves (so an admin's persisted api-calls mode\n // isn't reset during the brief loading window).\n useEffect(() => {\n if (apiAccessLoading) return;\n const activeModeConfig = ASSISTANT_MODES.find((modeConfig) => modeConfig.id === mode);\n const blocked = !activeModeConfig || (activeModeConfig.requiresAdmin && !canUseApiCalls);\n if (blocked && mode !== 'general') {\n setMode('general');\n }\n }, [mode, canUseApiCalls, apiAccessLoading, setMode]);\n\n const updateConversationStage = useCallback(\n (conversationId: string, assistantMessageId: string, status: AssistantConversationStatus, content?: string) => {\n setConversationProcessing(conversationId, status, assistantMessageId, null);\n if (content) {\n updateMessage(conversationId, assistantMessageId, content);\n } else {\n updateMessage(conversationId, assistantMessageId, getConversationStatusMessage(status));\n }\n },\n [setConversationProcessing, updateMessage]\n );\n\n const ensureAssistantRuntime = useCallback(\n async (\n conversationId: string,\n assistantMessageId: string,\n currentMode: AssistantMode,\n workspaceId: string,\n authContext: AssistantSandboxAuthContext\n ): Promise<{ sandboxId: string; sessionId: string }> => {\n let currentSandboxId = useAssistantStore.getState().sandboxesByMode[currentMode]?.sandboxId ?? null;\n\n // Validate that a candidate sandbox (remembered locally or found running on\n // the server) is actually reachable before we reuse it. A sandbox can expire\n // (ttlSeconds) or have its backend pod reclaimed while still being briefly\n // reported RUNNING; proxying to such a dead pod fails with a terminal state\n // (\"Backend resource no longer exists\") or a permanent 502 cf-proxy timeout.\n // Returns true only when the in-sandbox agent responds; false means stale.\n const ensureSandboxReachable = async (candidateId: string): Promise<boolean> => {\n try {\n await waitForSandboxReady(apollo, candidateId, workspaceId, authContext, 300_000, (message) =>\n updateConversationStage(conversationId, assistantMessageId, 'provisioning', message)\n );\n await waitForAssistantServiceReady(apollo, candidateId, workspaceId, authContext, 90_000, (message) =>\n updateConversationStage(conversationId, assistantMessageId, 'connecting', message)\n );\n return true;\n } catch {\n // Stale/expired sandbox — drop it so we provision a fresh one below\n // instead of surfacing \"Internal server error\" to the user.\n return false;\n }\n };\n\n // 1) Try the locally-remembered sandbox, then 2) any running one on the\n // server. Each is only kept if it's actually reachable.\n if (currentSandboxId) {\n setSandbox(currentMode, currentSandboxId, 'provisioning');\n updateConversationStage(conversationId, assistantMessageId, 'provisioning', 'Reusing assistant environment...');\n if (!(await ensureSandboxReachable(currentSandboxId))) {\n setSandbox(currentMode, null, 'provisioning');\n currentSandboxId = null;\n }\n }\n\n if (!currentSandboxId) {\n updateConversationStage(\n conversationId,\n assistantMessageId,\n 'provisioning',\n 'Looking for existing environment...'\n );\n const existingId = await findExistingSandbox(apollo, workspaceId, currentMode, authContext);\n\n if (existingId) {\n setSandbox(currentMode, existingId, 'provisioning');\n updateConversationStage(\n conversationId,\n assistantMessageId,\n 'provisioning',\n 'Reusing assistant environment...'\n );\n if (await ensureSandboxReachable(existingId)) {\n currentSandboxId = existingId;\n } else {\n setSandbox(currentMode, null, 'provisioning');\n }\n }\n }\n\n // 3) No reusable, reachable sandbox — provision a fresh one.\n if (!currentSandboxId) {\n if (currentMode === 'api-calls' && !getAccessToken()) {\n throw new Error('API Calls mode requires an authenticated session. Please sign in again.');\n }\n\n updateConversationStage(\n conversationId,\n assistantMessageId,\n 'provisioning',\n 'Starting assistant environment...'\n );\n setSandbox(currentMode, null, 'provisioning');\n currentSandboxId = await createAssistantSandbox(apollo, currentMode, workspaceId, authContext);\n\n setSandbox(currentMode, currentSandboxId, 'provisioning');\n await waitForSandboxReady(apollo, currentSandboxId, workspaceId, authContext, 300_000, (message) =>\n updateConversationStage(conversationId, assistantMessageId, 'provisioning', message)\n );\n await waitForAssistantServiceReady(apollo, currentSandboxId, workspaceId, authContext, 90_000, (message) =>\n updateConversationStage(conversationId, assistantMessageId, 'connecting', message)\n );\n }\n\n setSandbox(currentMode, currentSandboxId, 'running');\n\n let sessionId =\n useAssistantStore.getState().conversations.find((conversation) => conversation.id === conversationId)\n ?.backendSessionId ?? null;\n\n if (sessionId) {\n try {\n const session = await getAssistantSession(apollo, currentSandboxId, workspaceId, sessionId, authContext);\n if (session.mode !== currentMode) {\n throw new Error(`Session mode mismatch: expected ${currentMode}, received ${session.mode}`);\n }\n } catch {\n clearBackendSessionId(conversationId);\n sessionId = null;\n }\n }\n\n if (!sessionId) {\n updateConversationStage(conversationId, assistantMessageId, 'connecting', 'Preparing session...');\n const result = await createAssistantSession(apollo, currentSandboxId, workspaceId, currentMode, authContext);\n sessionId = result.sessionId;\n setBackendSessionId(conversationId, sessionId);\n }\n\n return {\n sandboxId: currentSandboxId,\n sessionId,\n };\n },\n [apollo, clearBackendSessionId, getAccessToken, setBackendSessionId, setSandbox, updateConversationStage]\n );\n\n const handleSend = useCallback(\n async (content: string, attachments: AssistantAttachment[] = []) => {\n // Only block re-entry while a turn is genuinely in-flight. Earlier code\n // checked for *any* entry in the map, which stuck around as `complete`\n // / `error` after the first turn — making every subsequent message\n // silently disappear (the input cleared but handleSend bailed before\n // adding the user message to the conversation).\n if (activeConversationId) {\n const inflightStatus = processingByConversationId[activeConversationId]?.status;\n if (inflightStatus === 'provisioning' || inflightStatus === 'connecting' || inflightStatus === 'streaming') {\n return;\n }\n }\n\n const selectedMode = useAssistantStore.getState().mode;\n let conversationId = activeConversationId;\n const currentConversation = conversationId\n ? useAssistantStore.getState().conversations.find((conversation) => conversation.id === conversationId)\n : undefined;\n\n if (!conversationId) {\n conversationId = createConversation(undefined, selectedMode);\n } else if (\n currentConversation &&\n currentConversation.mode !== selectedMode &&\n (currentConversation.messages.length > 0 || currentConversation.backendSessionId)\n ) {\n conversationId = createConversation(undefined, selectedMode);\n } else if (currentConversation && currentConversation.mode !== selectedMode) {\n setConversationMode(conversationId, selectedMode);\n }\n\n if (!conversationId) return;\n\n lastSentAttachmentsRef.current = attachments;\n\n const workspaceId = getWorkspaceId();\n const authContext: AssistantSandboxAuthContext = {\n accessToken: getAccessToken(),\n workspaceToken: getWorkspaceToken(),\n userId,\n organizationId: getOrganizationId(),\n };\n\n const userMessage: Message = {\n id: generateId(),\n role: 'user',\n content,\n timestamp: new Date().toISOString(),\n // Slim descriptors only — the bubble re-resolves thumbnails from the\n // file id, so the persisted conversation stays small.\n metadata: attachments.length ? { attachments: attachments.map(toMessageAttachment) } : undefined,\n };\n addMessage(conversationId, userMessage);\n\n const assistantMessageId = generateId();\n addMessage(conversationId, {\n id: assistantMessageId,\n role: 'assistant',\n content: '',\n timestamp: new Date().toISOString(),\n });\n\n const applyAssistantResponse = (\n response: string,\n artifacts?: AssistantArtifact[],\n sessionId?: string,\n sandboxId?: string\n ) => {\n patchMessage(conversationId, assistantMessageId, {\n content: sanitizeAssistantResponse(response),\n metadata:\n artifacts?.length || sessionId || sandboxId\n ? {\n artifacts,\n mode: selectedMode,\n sessionId,\n sandboxId,\n }\n : undefined,\n });\n };\n\n const sendWithRealBackend = async (attempt: 1 | 2 = 1): Promise<void> => {\n // Pre-flight AI-credit gate. The wspace gateway's @usage(checkQuota)\n // rejects with 429 QUOTA_EXHAUSTED when the monthly token budget is\n // depleted — block the send (don't provision a sandbox or dispatch the\n // prompt) and surface the upgrade dialog instead of a generic error.\n try {\n await checkAssistantAiCredits(apollo, workspaceId, authContext);\n } catch (creditError) {\n if (isQuotaExhaustedError(creditError)) {\n dispatchAssistantQuotaExhausted('ai-credits');\n applyAssistantResponse(\n \"You've run out of AI credits for this billing cycle. Upgrade your plan to keep chatting.\"\n );\n setConversationProcessing(conversationId, 'error', assistantMessageId, null);\n return;\n }\n // The pre-flight gate exists ONLY to catch a genuine QUOTA_EXHAUSTED\n // rejection. Any other failure here is a transient fault in the\n // credit check itself — e.g. the usage subgraph's getUsageSummary /\n // checkAiCredits intermittently 500s (Postgres/Prisma blip) and the\n // gateway masks it as the opaque \"Unexpected error.\". That is NOT\n // proof the user is out of budget, so it must not abort an otherwise\n // valid send. Fail open and proceed: the wspace gateway's\n // @usage(checkQuota) on createSandbox still enforces the real budget\n // downstream (a truly over-quota caller is stopped there with a 429\n // that surfaces the upgrade dialog via the outer catch).\n console.warn(\n '[assistant] AI-credit pre-flight check failed with a non-quota error; proceeding — gateway @usage(checkQuota) still enforces the real budget downstream',\n creditError\n );\n }\n\n try {\n const { sandboxId, sessionId } = await ensureAssistantRuntime(\n conversationId,\n assistantMessageId,\n selectedMode,\n workspaceId,\n authContext\n );\n\n // Snapshot the newest message timestamp already present in this\n // (possibly reused) session BEFORE sending the prompt, so we can\n // recognise THIS turn's reply as the one created after it — never by\n // comparing the browser clock to the sandbox clock (see\n // buildAssistantProgress). The newest-N window always contains the\n // newest message, so this floor is exact regardless of conversation depth.\n const priorMessages = await getAssistantMessages(\n apollo,\n sandboxId,\n workspaceId,\n sessionId,\n authContext,\n 50\n ).catch((): AssistantRawMessage[] => []);\n const priorNewestCreatedMs = priorMessages.reduce(\n (newest, message) => Math.max(newest, getRawMessageCreatedAt(message)),\n 0\n );\n\n updateConversationStage(conversationId, assistantMessageId, 'streaming', 'Thinking...');\n // Two agent-only wrappers around the raw content, both invisible in\n // the bubble: the soft confirm-before-mutate guard for api-calls mode,\n // and the attachment block (metadata + URLs, with text-like files\n // inlined) that carries this turn's files to the model.\n const promptText = buildPromptForMode(selectedMode, buildPromptWithAttachments(content, attachments));\n await sendAssistantPromptAsync(\n apollo,\n sandboxId,\n workspaceId,\n sessionId,\n promptText,\n selectedMode,\n gatherPageContext(),\n authContext,\n // Structured multimodal parts carry the image PIXELS, which no\n // amount of prompt text can. Built from the same `promptText`, so a\n // bridge that ignores `parts` loses nothing; `undefined` for an\n // ordinary text turn keeps the wire body unchanged.\n buildPromptParts(promptText, attachments)\n );\n\n let result = buildAssistantProgress([], priorNewestCreatedMs);\n const timeoutAt = Date.now() + (STREAM_BUDGET_MS[selectedMode] ?? DEFAULT_STREAM_BUDGET_MS);\n let lastTtlExtensionAt = Date.now();\n\n while (Date.now() < timeoutAt) {\n const sessionMessages = await getAssistantMessages(\n apollo,\n sandboxId,\n workspaceId,\n sessionId,\n authContext,\n 50\n );\n\n result = buildAssistantProgress(sessionMessages, priorNewestCreatedMs);\n patchMessage(conversationId, assistantMessageId, {\n content: sanitizeAssistantResponse(result.content),\n });\n\n if (result.done) break;\n\n if (Date.now() - lastTtlExtensionAt > 30_000) {\n await extendAssistantSandboxTTL(apollo, sandboxId, workspaceId, 600, authContext).catch(() => undefined);\n lastTtlExtensionAt = Date.now();\n }\n\n await new Promise((resolve) => setTimeout(resolve, 1500));\n }\n\n // For non-build modes a timeout is a hard failure. For vibe-plugins the\n // prompt runs async server-side (/sessions/:id/prompt-async) and keeps\n // writing artifacts after the poll budget elapses, so we surface whatever\n // it has produced instead of discarding the turn.\n if (!result.done && selectedMode !== 'vibe-plugins') {\n throw new Error('Assistant response timed out while streaming progress');\n }\n\n const artifacts =\n selectedMode === 'vibe-plugins'\n ? await getAssistantArtifacts(apollo, sandboxId, workspaceId, sessionId, authContext).catch(() => [])\n : undefined;\n\n if (!result.done) {\n // vibe-plugins build still running in the background. Append a note so\n // the user knows the answer is partial and the artifacts will finish.\n result = {\n ...result,\n content: `${result.content}\\n\\n_Still building in the background — any artifacts below will finish shortly. Re-open this conversation to pick up the completed plugin._`,\n };\n }\n\n applyAssistantResponse(result.content, artifacts, sessionId, sandboxId);\n\n if (result.tokens) {\n patchMessage(conversationId, assistantMessageId, { tokens: result.tokens });\n // Charge the real token usage against the AI-credits quota (the\n // gateway records it via @usage(trackUsage)). We AWAIT it before\n // marking the turn complete / re-enabling input: otherwise a rapid\n // follow-up send would run its pre-flight checkAiCredits against a\n // stale balance (this turn's charge still in flight) and could\n // dispatch a prompt that should have been blocked, letting fast\n // sends bypass the credit cap. Still best-effort — a charge failure\n // never blocks the displayed answer.\n try {\n await reportAssistantAiTokenUsage(apollo, workspaceId, sessionId, result.tokens, authContext);\n notifyAiCreditsUpdated();\n } catch {\n // ignore — server-side @usage tracking is the source of truth\n }\n }\n setConversationProcessing(conversationId, 'complete', assistantMessageId, null);\n } catch (error) {\n if (attempt === 1 && isRecoverableAssistantError(error)) {\n clearBackendSessionId(conversationId);\n clearSandbox(selectedMode);\n return sendWithRealBackend(2);\n }\n\n throw error;\n }\n };\n\n try {\n if (!workspaceId) {\n throw new Error('Assistant backend is unavailable without an active workspace context.');\n }\n await sendWithRealBackend();\n } catch (error) {\n // A quota error reaching here is the sandbox-environment wall hit\n // during runtime provisioning (createSandbox @usage). Surface the\n // upgrade dialog instead of a generic failure (the AI-credit wall is\n // already handled by the pre-flight gate above).\n if (isQuotaExhaustedError(error)) {\n dispatchAssistantQuotaExhausted('sandbox');\n applyAssistantResponse(\n \"You've reached your sandbox limit on the current plan. Upgrade to start the AI assistant.\"\n );\n setConversationProcessing(conversationId, 'error', assistantMessageId, null);\n return;\n }\n const errorMessage = error instanceof Error ? error.message : 'Something went wrong';\n setConversationProcessing(conversationId, 'error', assistantMessageId, errorMessage);\n updateMessage(\n conversationId,\n assistantMessageId,\n `Sorry, an error occurred: ${errorMessage}. Please try again.`\n );\n }\n },\n [\n activeConversationId,\n addMessage,\n apollo,\n clearBackendSessionId,\n clearSandbox,\n conversations,\n createConversation,\n ensureAssistantRuntime,\n getAccessToken,\n getWorkspaceToken,\n patchMessage,\n processingByConversationId,\n setBackendSessionId,\n setConversationMode,\n setConversationProcessing,\n updateConversationStage,\n updateMessage,\n userId,\n ]\n );\n\n const handleSuggestionClick = useCallback(\n (suggestion: string) => {\n void handleSend(suggestion);\n },\n [handleSend]\n );\n\n // Retry re-sends the most recent user prompt through the same transport — the\n // failed assistant turn stays in the transcript, a fresh one is appended.\n // The attachments come from the in-memory ref rather than the message\n // metadata: the persisted descriptors deliberately drop the inlined text of\n // text-like files, so rebuilding from them would silently retry a WEAKER\n // prompt than the one that failed.\n const handleRetry = useCallback(() => {\n const lastUserMessage = [...messages].reverse().find((message) => message.role === 'user');\n if (lastUserMessage) void handleSend(lastUserMessage.content, lastSentAttachmentsRef.current);\n }, [messages, handleSend]);\n\n // Auto-send any prompt that was queued by `useOpenAssistantHelp` (from\n // the shared GetHelpButton). We keep the latest handleSend in a ref so\n // the subscription effect below doesn't need to tear down on every\n // render — the store subscription lives for the component lifetime and\n // always calls the freshest handler.\n const handleSendRef = useRef(handleSend);\n useEffect(() => {\n handleSendRef.current = handleSend;\n }, [handleSend]);\n\n useEffect(() => {\n // Flush any prompt that was queued before this component mounted.\n const initial = useAssistantStore.getState().consumePendingPrompt();\n if (initial) {\n void handleSendRef.current(initial);\n }\n\n // Watch for new prompts queued while we're already mounted.\n const unsubscribe = useAssistantStore.subscribe((state, prev) => {\n if (state.pendingPrompt && state.pendingPrompt !== prev.pendingPrompt) {\n const queued = useAssistantStore.getState().consumePendingPrompt();\n if (queued) {\n void handleSendRef.current(queued);\n }\n }\n });\n return unsubscribe;\n }, []);\n\n const performModeChange = useCallback(\n (newMode: AssistantMode) => {\n const currentConversation = activeConversationId\n ? useAssistantStore.getState().conversations.find((conversation) => conversation.id === activeConversationId)\n : undefined;\n\n if (currentConversation && (currentConversation.messages.length > 0 || currentConversation.backendSessionId)) {\n if (currentConversation.mode !== newMode) {\n const reusableDraft = useAssistantStore\n .getState()\n .conversations.find(\n (conversation) =>\n conversation.mode === newMode &&\n conversation.messages.length === 0 &&\n !conversation.backendSessionId &&\n !useAssistantStore.getState().processingByConversationId[conversation.id]\n );\n\n if (reusableDraft) {\n setActiveConversation(reusableDraft.id);\n } else {\n createConversation(undefined, newMode);\n }\n }\n } else if (activeConversationId) {\n setConversationMode(activeConversationId, newMode);\n }\n\n setMode(newMode);\n },\n [activeConversationId, createConversation, setActiveConversation, setConversationMode, setMode]\n );\n\n const handleModeChange = useCallback(\n (newMode: AssistantMode) => {\n const target = ASSISTANT_MODES.find((modeConfig) => modeConfig.id === newMode);\n // Gate the FIRST switch into a write-capable mode behind the one-time\n // consent dialog — the dependable confirm-before-mutate guardrail.\n if (target?.writeCapable && !useAssistantStore.getState().apiCallsAcknowledged) {\n setPendingConsentMode(newMode);\n return;\n }\n performModeChange(newMode);\n },\n [performModeChange]\n );\n\n const handleConsentConfirm = useCallback(() => {\n const target = pendingConsentMode;\n setPendingConsentMode(null);\n acknowledgeApiCalls();\n if (target) performModeChange(target);\n }, [pendingConsentMode, acknowledgeApiCalls, performModeChange]);\n\n const handleConsentCancel = useCallback(() => {\n setPendingConsentMode(null);\n }, []);\n\n return (\n <div className=\"flex flex-1 flex-col overflow-hidden\">\n {/* Transcript is always visible now — the old collapse-by-default accordion\n is gone; conversation history lives behind the header button instead. */}\n {messages.length === 0 ? (\n <AssistantEmptyState mode={mode} onSuggestionClick={handleSuggestionClick} />\n ) : (\n <div className=\"flex min-h-0 flex-1 flex-col\">\n <AssistantMessageList\n messages={messages}\n streamingMessageId={activeStreamingMessageId}\n failedMessageId={failedMessageId}\n onRetry={handleRetry}\n />\n </div>\n )}\n\n <AssistantComposer\n onSend={(value, attachments) => void handleSend(value, attachments)}\n disabled={activeIsProcessing}\n placeholder={\n mode === 'api-calls'\n ? tr('healthybowl.assistant.chatArea.placeholderActions', 'What would you like me to do?')\n : tr('healthybowl.assistant.chatArea.placeholderGeneral', 'Ask HealthyBowl anything…')\n }\n mode={mode}\n availableModes={availableModes}\n onModeChange={handleModeChange}\n />\n\n <AssistantApiCallsConsentDialog\n open={pendingConsentMode !== null}\n onConfirm={handleConsentConfirm}\n onCancel={handleConsentCancel}\n />\n </div>\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AA6CA,IAAM,KAAkD;CACtD,SAAS;CACT,aAAa;CACb,gBAAgB;CACjB,EACK,KAA2B;AAEjC,SAAS,KAAqB;AAC5B,QAAO,GAAG,KAAK,KAAK,CAAC,GAAG,KAAK,QAAQ,CAAC,SAAS,GAAG,CAAC,MAAM,GAAG,EAAE;;AAGhE,SAAS,GAA4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GAAO,MAAgB,KAAK,EAAW,GAAO,EAAY;IACnE,UAAU;IACV,aACE,MAAS,cACL,EAAG,qDAAqD,gCAAgC,GACxF,EAAG,qDAAqD,4BAA4B;IAEpF;IACU;IAChB,cAAc;IACd,CAAA;GAEF,kBAAC,GAAD;IACE,MAAM,MAAuB;IAC7B,WAAW;IACX,UAAU;IACV,CAAA;GACE"}
1
+ {"version":3,"file":"AssistantChatArea.js","names":[],"sources":["../../../src/components/assistant/AssistantChatArea.tsx"],"sourcesContent":["import { useCallback, useEffect, useMemo, useRef, useState, type FC } from 'react';\nimport { useGatewayClient } from '@burdenoff/fe-libs/shared/graphql';\nimport { useAuthToken } from '@burdenoff/fe-libs/shared/providers/shell';\nimport { AssistantMessageList } from './AssistantMessageList';\nimport { AssistantApiCallsConsentDialog } from './AssistantApiCallsConsentDialog';\nimport { AssistantEmptyState } from './AssistantEmptyState';\nimport { AssistantComposer } from './composer/AssistantComposer';\nimport { useAssistantApiAccess } from '@/hooks/useAssistantApiAccess';\nimport { useAssistantStore } from '@/store/assistantStore';\nimport {\n checkAssistantAiCredits,\n createAssistantSandbox,\n createAssistantSession,\n extendAssistantSandboxTTL,\n findExistingSandbox,\n getAssistantArtifacts,\n getAssistantMessages,\n getAssistantSession,\n reportAssistantAiTokenUsage,\n sendAssistantPromptAsync,\n waitForAssistantServiceReady,\n waitForSandboxReady,\n type AssistantRawMessage,\n type AssistantSandboxAuthContext,\n} from '@/services/assistantApi';\nimport { getAssistantMedia } from '@burdenoff/fe-libs/shared/assistant';\nimport { gatherPageContext } from '@/utils/pageContext';\nimport { getOrganizationId, getWorkspaceId } from '@/utils/assistantContext';\nimport { dispatchAssistantQuotaExhausted, notifyAiCreditsUpdated } from '@/utils/aiCredits';\nimport { isQuotaExhaustedError } from '@/utils/quotaUtils';\nimport { buildPromptForMode } from '@/utils/assistantPrompt';\nimport {\n buildPromptParts,\n buildPromptWithAttachments,\n toMessageAttachment,\n type AssistantAttachment,\n} from '@/utils/assistantAttachments';\nimport { useTr } from '../../shared/hooks/useTr';\nimport { ASSISTANT_MODES } from '@/types/assistant';\nimport type { AssistantArtifact, AssistantConversationStatus, AssistantMode, Message } from '@/types/assistant';\n\n// How long the client streams progress before giving up on a turn. Chat replies\n// (general / api-calls) finish in seconds; a vibe-plugins build is a multi-step\n// pipeline (read docs → scaffold → bun install → bun build → checklist) that runs\n// for minutes, so it gets a much larger budget. The sandbox TTL is auto-extended\n// every 30s during the poll loop, so a longer budget never outlives the sandbox.\nconst STREAM_BUDGET_MS: Record<AssistantMode, number> = {\n general: 180_000,\n 'api-calls': 180_000,\n 'vibe-plugins': 600_000,\n};\nconst DEFAULT_STREAM_BUDGET_MS = 180_000;\n\nfunction generateId(): string {\n return `${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;\n}\n\nfunction isRecoverableAssistantError(error: unknown): boolean {\n const message = error instanceof Error ? error.message.toLowerCase() : String(error).toLowerCase();\n\n if (\n message.includes('rate limit exceeded') ||\n message.includes('unauthorized') ||\n message.includes('k8s api error 401')\n ) {\n return false;\n }\n\n return [\n 'sandbox not found',\n 'sandbox is not running',\n 'sandbox service not available yet',\n 'sandbox failed',\n 'sandbox startup timed out',\n 'assistant service did not become healthy',\n 'proxy error: 404',\n 'proxy error: 502',\n 'proxy error: 503',\n 'session mode mismatch',\n ].some((fragment) => message.includes(fragment));\n}\n\nfunction sanitizeAssistantResponse(response: string): string {\n return response\n .replace(/(Authorization\\s*:\\s*Bearer\\s+)[^\\s\\n]+/gi, '$1[REDACTED]')\n .replace(/(X-Workspace-Authorization\\s*:\\s*Bearer\\s+)[^\\s\\n]+/gi, '$1[REDACTED]')\n .replace(/\\beyJ[A-Za-z0-9_-]+\\.[A-Za-z0-9._-]+\\.[A-Za-z0-9._-]+\\b/g, '[REDACTED_JWT]')\n .replace(/\\bsk-ant-[A-Za-z0-9-]+\\b/g, '[REDACTED_API_KEY]');\n}\n\nfunction getRawMessageCreatedAt(message: AssistantRawMessage): number {\n return message.info?.time?.created ?? 0;\n}\n\nfunction getAssistantText(parts: AssistantRawMessage['parts']): string {\n return (parts ?? [])\n .filter((part) => part.type === 'text' && typeof part.text === 'string')\n .map((part) => part.text?.trim() ?? '')\n .filter(Boolean)\n .join('\\n');\n}\n\nfunction getToolProgress(parts: AssistantRawMessage['parts']): string[] {\n return (parts ?? [])\n .filter((part) => part.type === 'tool' && part.tool)\n .map((part) => {\n const status = part.state?.status ?? 'running';\n const tool = part.tool ?? 'tool';\n if (status === 'completed') return `Completed: ${tool}`;\n if (status === 'failed') return `Failed: ${tool}`;\n return `Running: ${tool}`;\n });\n}\n\nfunction buildAssistantProgress(\n messages: AssistantRawMessage[],\n // The `created` timestamp (sandbox clock) of the newest message that already\n // existed in this session BEFORE the prompt was sent. This turn's reply is the\n // assistant message created strictly after it. Crucially this stays WITHIN the\n // sandbox clock domain: the previous code compared the sandbox-stamped\n // `created` against the browser wall-clock (Date#now), so a reply stamped at\n // prompt-time was silently dropped whenever the sandbox clock lagged the\n // browser — the turn then hung on \"Thinking...\" until the stream budget\n // elapsed. A sandbox-domain floor is immune to clock skew and correct for both\n // fresh and reused (per-conversation) sessions, with no message-window gap.\n priorNewestCreatedMs: number\n): {\n content: string;\n done: boolean;\n tokens?: { input: number; output: number };\n} {\n const relevant = messages\n .filter((message) => message.info?.role === 'assistant' && getRawMessageCreatedAt(message) > priorNewestCreatedMs)\n .sort((left, right) => getRawMessageCreatedAt(left) - getRawMessageCreatedAt(right));\n\n if (relevant.length === 0) {\n return { content: 'Thinking...', done: false };\n }\n\n const latest = relevant[relevant.length - 1]!;\n const text = getAssistantText(latest.parts);\n // Inbound image/file parts, rendered to markdown by the shared helper (which\n // escapes the label and allowlists the protocol — this is model output).\n // Without this, HealthyBowl — the one product that SENDS parts — could not\n // read one back: a media-bearing reply would never satisfy `done` and the\n // turn would poll to a false timeout.\n const media = getAssistantMedia(latest.parts);\n const toolProgress = getToolProgress(latest.parts);\n const content = [text, ...media, ...toolProgress].filter(Boolean).join('\\n\\n') || 'Thinking...';\n\n return {\n content,\n done: Boolean(latest.info?.time?.completed) && (Boolean(text) || media.length > 0 || toolProgress.length > 0),\n tokens: latest.info?.tokens,\n };\n}\n\nfunction getConversationStatusMessage(status: AssistantConversationStatus): string {\n switch (status) {\n case 'provisioning':\n return 'Starting assistant environment...';\n case 'connecting':\n return 'Connecting to assistant...';\n case 'streaming':\n return 'Thinking...';\n default:\n return '';\n }\n}\n\nexport const AssistantChatArea: FC = () => {\n const tr = useTr();\n const apollo = useGatewayClient('workspace');\n const { getAccessToken, getWorkspaceToken, userId } = useAuthToken();\n\n const {\n conversations,\n activeConversationId,\n mode,\n processingByConversationId,\n setMode,\n setConversationMode,\n setActiveConversation,\n createConversation,\n addMessage,\n updateMessage,\n patchMessage,\n setConversationProcessing,\n clearConversationProcessing,\n setBackendSessionId,\n clearBackendSessionId,\n setSandbox,\n clearSandbox,\n acknowledgeApiCalls,\n } = useAssistantStore();\n\n const activeConversation = conversations.find((conversation) => conversation.id === activeConversationId);\n const messages = activeConversation?.messages ?? [];\n const activeProcessing = activeConversationId ? processingByConversationId[activeConversationId] : undefined;\n // Only while the turn is genuinely in flight. `messageId` outlives the turn\n // (setConversationProcessing keeps it on 'complete'/'error'), so keying off it\n // alone left the transcript's aria-busy latched true forever and screen\n // readers stopped announcing new replies.\n const activeStreamingMessageId =\n activeProcessing?.status === 'provisioning' ||\n activeProcessing?.status === 'connecting' ||\n activeProcessing?.status === 'streaming'\n ? (activeProcessing.messageId ?? null)\n : null;\n const activeIsProcessing =\n activeProcessing?.status === 'provisioning' ||\n activeProcessing?.status === 'connecting' ||\n activeProcessing?.status === 'streaming';\n // The assistant message whose turn ended in an error — drives the Retry\n // affordance in the transcript.\n const failedMessageId = activeProcessing?.status === 'error' ? activeProcessing.messageId : null;\n\n // ── api-calls (write) mode gating ──────────────────────────────────\n // Only a global Owner/Admin may use api-calls (it mints an OAuth app under the\n // caller identity). Re-read the org scope every render (a cheap localStorage\n // read) so the admin gate reacts to an org switch without the panel\n // remounting; the value is a stable string, so useAssistantApiAccess only\n // re-fetches myRoles when the org actually changes. An empty scope simply\n // hides the mode (it could not provision the sandbox anyway).\n const apiCallsScopeId = getOrganizationId();\n const { canUseApiCalls, loading: apiAccessLoading } = useAssistantApiAccess(apiCallsScopeId);\n const availableModes = useMemo(\n () => ASSISTANT_MODES.filter((modeConfig) => !modeConfig.requiresAdmin || canUseApiCalls),\n [canUseApiCalls]\n );\n\n // Target mode awaiting the one-time consent dialog (null = dialog closed).\n const [pendingConsentMode, setPendingConsentMode] = useState<AssistantMode | null>(null);\n\n // Full attachment payload of the last send, kept so Retry can replay it\n // byte-for-byte (see handleRetry).\n const lastSentAttachmentsRef = useRef<Record<string, AssistantAttachment[]>>({});\n\n // If the active mode is no longer permitted — a non-admin with a persisted\n // api-calls mode, or the master flag turned off — fall back to general, but\n // only AFTER the role check resolves (so an admin's persisted api-calls mode\n // isn't reset during the brief loading window).\n useEffect(() => {\n if (apiAccessLoading) return;\n const activeModeConfig = ASSISTANT_MODES.find((modeConfig) => modeConfig.id === mode);\n const blocked = !activeModeConfig || (activeModeConfig.requiresAdmin && !canUseApiCalls);\n if (blocked && mode !== 'general') {\n setMode('general');\n }\n }, [mode, canUseApiCalls, apiAccessLoading, setMode]);\n\n const updateConversationStage = useCallback(\n (conversationId: string, assistantMessageId: string, status: AssistantConversationStatus, content?: string) => {\n setConversationProcessing(conversationId, status, assistantMessageId, null);\n if (content) {\n updateMessage(conversationId, assistantMessageId, content);\n } else {\n updateMessage(conversationId, assistantMessageId, getConversationStatusMessage(status));\n }\n },\n [setConversationProcessing, updateMessage]\n );\n\n const ensureAssistantRuntime = useCallback(\n async (\n conversationId: string,\n assistantMessageId: string,\n currentMode: AssistantMode,\n workspaceId: string,\n authContext: AssistantSandboxAuthContext\n ): Promise<{ sandboxId: string; sessionId: string }> => {\n let currentSandboxId = useAssistantStore.getState().sandboxesByMode[currentMode]?.sandboxId ?? null;\n\n // Validate that a candidate sandbox (remembered locally or found running on\n // the server) is actually reachable before we reuse it. A sandbox can expire\n // (ttlSeconds) or have its backend pod reclaimed while still being briefly\n // reported RUNNING; proxying to such a dead pod fails with a terminal state\n // (\"Backend resource no longer exists\") or a permanent 502 cf-proxy timeout.\n // Returns true only when the in-sandbox agent responds; false means stale.\n const ensureSandboxReachable = async (candidateId: string): Promise<boolean> => {\n try {\n await waitForSandboxReady(apollo, candidateId, workspaceId, authContext, 300_000, (message) =>\n updateConversationStage(conversationId, assistantMessageId, 'provisioning', message)\n );\n await waitForAssistantServiceReady(apollo, candidateId, workspaceId, authContext, 90_000, (message) =>\n updateConversationStage(conversationId, assistantMessageId, 'connecting', message)\n );\n return true;\n } catch {\n // Stale/expired sandbox — drop it so we provision a fresh one below\n // instead of surfacing \"Internal server error\" to the user.\n return false;\n }\n };\n\n // 1) Try the locally-remembered sandbox, then 2) any running one on the\n // server. Each is only kept if it's actually reachable.\n if (currentSandboxId) {\n setSandbox(currentMode, currentSandboxId, 'provisioning');\n updateConversationStage(conversationId, assistantMessageId, 'provisioning', 'Reusing assistant environment...');\n if (!(await ensureSandboxReachable(currentSandboxId))) {\n setSandbox(currentMode, null, 'provisioning');\n currentSandboxId = null;\n }\n }\n\n if (!currentSandboxId) {\n updateConversationStage(\n conversationId,\n assistantMessageId,\n 'provisioning',\n 'Looking for existing environment...'\n );\n const existingId = await findExistingSandbox(apollo, workspaceId, currentMode, authContext);\n\n if (existingId) {\n setSandbox(currentMode, existingId, 'provisioning');\n updateConversationStage(\n conversationId,\n assistantMessageId,\n 'provisioning',\n 'Reusing assistant environment...'\n );\n if (await ensureSandboxReachable(existingId)) {\n currentSandboxId = existingId;\n } else {\n setSandbox(currentMode, null, 'provisioning');\n }\n }\n }\n\n // 3) No reusable, reachable sandbox — provision a fresh one.\n if (!currentSandboxId) {\n if (currentMode === 'api-calls' && !getAccessToken()) {\n throw new Error('API Calls mode requires an authenticated session. Please sign in again.');\n }\n\n updateConversationStage(\n conversationId,\n assistantMessageId,\n 'provisioning',\n 'Starting assistant environment...'\n );\n setSandbox(currentMode, null, 'provisioning');\n currentSandboxId = await createAssistantSandbox(apollo, currentMode, workspaceId, authContext);\n\n setSandbox(currentMode, currentSandboxId, 'provisioning');\n await waitForSandboxReady(apollo, currentSandboxId, workspaceId, authContext, 300_000, (message) =>\n updateConversationStage(conversationId, assistantMessageId, 'provisioning', message)\n );\n await waitForAssistantServiceReady(apollo, currentSandboxId, workspaceId, authContext, 90_000, (message) =>\n updateConversationStage(conversationId, assistantMessageId, 'connecting', message)\n );\n }\n\n setSandbox(currentMode, currentSandboxId, 'running');\n\n let sessionId =\n useAssistantStore.getState().conversations.find((conversation) => conversation.id === conversationId)\n ?.backendSessionId ?? null;\n\n if (sessionId) {\n try {\n const session = await getAssistantSession(apollo, currentSandboxId, workspaceId, sessionId, authContext);\n if (session.mode !== currentMode) {\n throw new Error(`Session mode mismatch: expected ${currentMode}, received ${session.mode}`);\n }\n } catch {\n clearBackendSessionId(conversationId);\n sessionId = null;\n }\n }\n\n if (!sessionId) {\n updateConversationStage(conversationId, assistantMessageId, 'connecting', 'Preparing session...');\n const result = await createAssistantSession(apollo, currentSandboxId, workspaceId, currentMode, authContext);\n sessionId = result.sessionId;\n setBackendSessionId(conversationId, sessionId);\n }\n\n return {\n sandboxId: currentSandboxId,\n sessionId,\n };\n },\n [apollo, clearBackendSessionId, getAccessToken, setBackendSessionId, setSandbox, updateConversationStage]\n );\n\n const handleSend = useCallback(\n async (content: string, attachments: AssistantAttachment[] = []) => {\n // Only block re-entry while a turn is genuinely in-flight. Earlier code\n // checked for *any* entry in the map, which stuck around as `complete`\n // / `error` after the first turn — making every subsequent message\n // silently disappear (the input cleared but handleSend bailed before\n // adding the user message to the conversation).\n if (activeConversationId) {\n const inflightStatus = processingByConversationId[activeConversationId]?.status;\n if (inflightStatus === 'provisioning' || inflightStatus === 'connecting' || inflightStatus === 'streaming') {\n return;\n }\n }\n\n const selectedMode = useAssistantStore.getState().mode;\n let conversationId = activeConversationId;\n const currentConversation = conversationId\n ? useAssistantStore.getState().conversations.find((conversation) => conversation.id === conversationId)\n : undefined;\n\n if (!conversationId) {\n conversationId = createConversation(undefined, selectedMode);\n } else if (\n currentConversation &&\n currentConversation.mode !== selectedMode &&\n (currentConversation.messages.length > 0 || currentConversation.backendSessionId)\n ) {\n conversationId = createConversation(undefined, selectedMode);\n } else if (currentConversation && currentConversation.mode !== selectedMode) {\n setConversationMode(conversationId, selectedMode);\n }\n\n if (!conversationId) return;\n\n // Keyed by conversation: the ref outlives a conversation switch, and a\n // single global slot meant Retry in one thread replayed another thread's\n // photo onto it.\n lastSentAttachmentsRef.current[conversationId] = attachments;\n\n const workspaceId = getWorkspaceId();\n const authContext: AssistantSandboxAuthContext = {\n accessToken: getAccessToken(),\n workspaceToken: getWorkspaceToken(),\n userId,\n organizationId: getOrganizationId(),\n };\n\n const userMessage: Message = {\n id: generateId(),\n role: 'user',\n content,\n timestamp: new Date().toISOString(),\n // Slim descriptors only — the bubble re-resolves thumbnails from the\n // file id, so the persisted conversation stays small.\n metadata: attachments.length ? { attachments: attachments.map(toMessageAttachment) } : undefined,\n };\n addMessage(conversationId, userMessage);\n\n const assistantMessageId = generateId();\n addMessage(conversationId, {\n id: assistantMessageId,\n role: 'assistant',\n content: '',\n timestamp: new Date().toISOString(),\n });\n\n const applyAssistantResponse = (\n response: string,\n artifacts?: AssistantArtifact[],\n sessionId?: string,\n sandboxId?: string\n ) => {\n patchMessage(conversationId, assistantMessageId, {\n content: sanitizeAssistantResponse(response),\n metadata:\n artifacts?.length || sessionId || sandboxId\n ? {\n artifacts,\n mode: selectedMode,\n sessionId,\n sandboxId,\n }\n : undefined,\n });\n };\n\n const sendWithRealBackend = async (attempt: 1 | 2 = 1): Promise<void> => {\n // Pre-flight AI-credit gate. The wspace gateway's @usage(checkQuota)\n // rejects with 429 QUOTA_EXHAUSTED when the monthly token budget is\n // depleted — block the send (don't provision a sandbox or dispatch the\n // prompt) and surface the upgrade dialog instead of a generic error.\n try {\n await checkAssistantAiCredits(apollo, workspaceId, authContext);\n } catch (creditError) {\n if (isQuotaExhaustedError(creditError)) {\n dispatchAssistantQuotaExhausted('ai-credits');\n applyAssistantResponse(\n \"You've run out of AI credits for this billing cycle. Upgrade your plan to keep chatting.\"\n );\n setConversationProcessing(conversationId, 'error', assistantMessageId, null);\n return;\n }\n // The pre-flight gate exists ONLY to catch a genuine QUOTA_EXHAUSTED\n // rejection. Any other failure here is a transient fault in the\n // credit check itself — e.g. the usage subgraph's getUsageSummary /\n // checkAiCredits intermittently 500s (Postgres/Prisma blip) and the\n // gateway masks it as the opaque \"Unexpected error.\". That is NOT\n // proof the user is out of budget, so it must not abort an otherwise\n // valid send. Fail open and proceed: the wspace gateway's\n // @usage(checkQuota) on createSandbox still enforces the real budget\n // downstream (a truly over-quota caller is stopped there with a 429\n // that surfaces the upgrade dialog via the outer catch).\n console.warn(\n '[assistant] AI-credit pre-flight check failed with a non-quota error; proceeding — gateway @usage(checkQuota) still enforces the real budget downstream',\n creditError\n );\n }\n\n try {\n const { sandboxId, sessionId } = await ensureAssistantRuntime(\n conversationId,\n assistantMessageId,\n selectedMode,\n workspaceId,\n authContext\n );\n\n // Snapshot the newest message timestamp already present in this\n // (possibly reused) session BEFORE sending the prompt, so we can\n // recognise THIS turn's reply as the one created after it — never by\n // comparing the browser clock to the sandbox clock (see\n // buildAssistantProgress). The newest-N window always contains the\n // newest message, so this floor is exact regardless of conversation depth.\n const priorMessages = await getAssistantMessages(\n apollo,\n sandboxId,\n workspaceId,\n sessionId,\n authContext,\n 50\n ).catch((): AssistantRawMessage[] => []);\n const priorNewestCreatedMs = priorMessages.reduce(\n (newest, message) => Math.max(newest, getRawMessageCreatedAt(message)),\n 0\n );\n\n updateConversationStage(conversationId, assistantMessageId, 'streaming', 'Thinking...');\n // Two agent-only wrappers around the raw content, both invisible in\n // the bubble: the soft confirm-before-mutate guard for api-calls mode,\n // and the attachment block (metadata + URLs, with text-like files\n // inlined) that carries this turn's files to the model.\n const promptText = buildPromptForMode(selectedMode, buildPromptWithAttachments(content, attachments));\n await sendAssistantPromptAsync(\n apollo,\n sandboxId,\n workspaceId,\n sessionId,\n promptText,\n selectedMode,\n gatherPageContext(),\n authContext,\n // Structured multimodal parts carry the image PIXELS, which no\n // amount of prompt text can. Built from the same `promptText`, so a\n // bridge that ignores `parts` loses nothing; `undefined` for an\n // ordinary text turn keeps the wire body unchanged.\n buildPromptParts(promptText, attachments)\n );\n\n let result = buildAssistantProgress([], priorNewestCreatedMs);\n const timeoutAt = Date.now() + (STREAM_BUDGET_MS[selectedMode] ?? DEFAULT_STREAM_BUDGET_MS);\n let lastTtlExtensionAt = Date.now();\n\n while (Date.now() < timeoutAt) {\n const sessionMessages = await getAssistantMessages(\n apollo,\n sandboxId,\n workspaceId,\n sessionId,\n authContext,\n 50\n );\n\n result = buildAssistantProgress(sessionMessages, priorNewestCreatedMs);\n patchMessage(conversationId, assistantMessageId, {\n content: sanitizeAssistantResponse(result.content),\n });\n\n if (result.done) break;\n\n if (Date.now() - lastTtlExtensionAt > 30_000) {\n await extendAssistantSandboxTTL(apollo, sandboxId, workspaceId, 600, authContext).catch(() => undefined);\n lastTtlExtensionAt = Date.now();\n }\n\n await new Promise((resolve) => setTimeout(resolve, 1500));\n }\n\n // For non-build modes a timeout is a hard failure. For vibe-plugins the\n // prompt runs async server-side (/sessions/:id/prompt-async) and keeps\n // writing artifacts after the poll budget elapses, so we surface whatever\n // it has produced instead of discarding the turn.\n if (!result.done && selectedMode !== 'vibe-plugins') {\n throw new Error('Assistant response timed out while streaming progress');\n }\n\n const artifacts =\n selectedMode === 'vibe-plugins'\n ? await getAssistantArtifacts(apollo, sandboxId, workspaceId, sessionId, authContext).catch(() => [])\n : undefined;\n\n if (!result.done) {\n // vibe-plugins build still running in the background. Append a note so\n // the user knows the answer is partial and the artifacts will finish.\n result = {\n ...result,\n content: `${result.content}\\n\\n_Still building in the background — any artifacts below will finish shortly. Re-open this conversation to pick up the completed plugin._`,\n };\n }\n\n applyAssistantResponse(result.content, artifacts, sessionId, sandboxId);\n\n if (result.tokens) {\n patchMessage(conversationId, assistantMessageId, { tokens: result.tokens });\n // Charge the real token usage against the AI-credits quota (the\n // gateway records it via @usage(trackUsage)). We AWAIT it before\n // marking the turn complete / re-enabling input: otherwise a rapid\n // follow-up send would run its pre-flight checkAiCredits against a\n // stale balance (this turn's charge still in flight) and could\n // dispatch a prompt that should have been blocked, letting fast\n // sends bypass the credit cap. Still best-effort — a charge failure\n // never blocks the displayed answer.\n try {\n await reportAssistantAiTokenUsage(apollo, workspaceId, sessionId, result.tokens, authContext);\n notifyAiCreditsUpdated();\n } catch {\n // ignore — server-side @usage tracking is the source of truth\n }\n }\n setConversationProcessing(conversationId, 'complete', assistantMessageId, null);\n } catch (error) {\n if (attempt === 1 && isRecoverableAssistantError(error)) {\n clearBackendSessionId(conversationId);\n clearSandbox(selectedMode);\n return sendWithRealBackend(2);\n }\n\n throw error;\n }\n };\n\n try {\n if (!workspaceId) {\n throw new Error('Assistant backend is unavailable without an active workspace context.');\n }\n await sendWithRealBackend();\n } catch (error) {\n // A quota error reaching here is the sandbox-environment wall hit\n // during runtime provisioning (createSandbox @usage). Surface the\n // upgrade dialog instead of a generic failure (the AI-credit wall is\n // already handled by the pre-flight gate above).\n if (isQuotaExhaustedError(error)) {\n dispatchAssistantQuotaExhausted('sandbox');\n applyAssistantResponse(\n \"You've reached your sandbox limit on the current plan. Upgrade to start the AI assistant.\"\n );\n setConversationProcessing(conversationId, 'error', assistantMessageId, null);\n return;\n }\n const errorMessage = error instanceof Error ? error.message : 'Something went wrong';\n setConversationProcessing(conversationId, 'error', assistantMessageId, errorMessage);\n updateMessage(\n conversationId,\n assistantMessageId,\n `Sorry, an error occurred: ${errorMessage}. Please try again.`\n );\n }\n },\n [\n activeConversationId,\n addMessage,\n apollo,\n clearBackendSessionId,\n clearSandbox,\n conversations,\n createConversation,\n ensureAssistantRuntime,\n getAccessToken,\n getWorkspaceToken,\n patchMessage,\n processingByConversationId,\n setBackendSessionId,\n setConversationMode,\n setConversationProcessing,\n updateConversationStage,\n updateMessage,\n userId,\n ]\n );\n\n const handleSuggestionClick = useCallback(\n (suggestion: string) => {\n void handleSend(suggestion);\n },\n [handleSend]\n );\n\n // Retry re-sends the most recent user prompt through the same transport — the\n // failed assistant turn stays in the transcript, a fresh one is appended.\n // The attachments come from the in-memory ref rather than the message\n // metadata: the persisted descriptors deliberately drop the inlined text of\n // text-like files, so rebuilding from them would silently retry a WEAKER\n // prompt than the one that failed.\n const handleRetry = useCallback(() => {\n const lastUserMessage = [...messages].reverse().find((message) => message.role === 'user');\n const replay = activeConversationId ? (lastSentAttachmentsRef.current[activeConversationId] ?? []) : [];\n if (lastUserMessage) void handleSend(lastUserMessage.content, replay);\n }, [messages, handleSend, activeConversationId]);\n\n // Auto-send any prompt that was queued by `useOpenAssistantHelp` (from\n // the shared GetHelpButton). We keep the latest handleSend in a ref so\n // the subscription effect below doesn't need to tear down on every\n // render — the store subscription lives for the component lifetime and\n // always calls the freshest handler.\n const handleSendRef = useRef(handleSend);\n useEffect(() => {\n handleSendRef.current = handleSend;\n }, [handleSend]);\n\n useEffect(() => {\n // Flush any prompt that was queued before this component mounted.\n const initial = useAssistantStore.getState().consumePendingPrompt();\n if (initial) {\n void handleSendRef.current(initial);\n }\n\n // Watch for new prompts queued while we're already mounted.\n const unsubscribe = useAssistantStore.subscribe((state, prev) => {\n if (state.pendingPrompt && state.pendingPrompt !== prev.pendingPrompt) {\n const queued = useAssistantStore.getState().consumePendingPrompt();\n if (queued) {\n void handleSendRef.current(queued);\n }\n }\n });\n return unsubscribe;\n }, []);\n\n const performModeChange = useCallback(\n (newMode: AssistantMode) => {\n const currentConversation = activeConversationId\n ? useAssistantStore.getState().conversations.find((conversation) => conversation.id === activeConversationId)\n : undefined;\n\n if (currentConversation && (currentConversation.messages.length > 0 || currentConversation.backendSessionId)) {\n if (currentConversation.mode !== newMode) {\n const reusableDraft = useAssistantStore\n .getState()\n .conversations.find(\n (conversation) =>\n conversation.mode === newMode &&\n conversation.messages.length === 0 &&\n !conversation.backendSessionId &&\n !useAssistantStore.getState().processingByConversationId[conversation.id]\n );\n\n if (reusableDraft) {\n setActiveConversation(reusableDraft.id);\n } else {\n createConversation(undefined, newMode);\n }\n }\n } else if (activeConversationId) {\n setConversationMode(activeConversationId, newMode);\n }\n\n setMode(newMode);\n },\n [activeConversationId, createConversation, setActiveConversation, setConversationMode, setMode]\n );\n\n const handleModeChange = useCallback(\n (newMode: AssistantMode) => {\n const target = ASSISTANT_MODES.find((modeConfig) => modeConfig.id === newMode);\n // Gate the FIRST switch into a write-capable mode behind the one-time\n // consent dialog — the dependable confirm-before-mutate guardrail.\n if (target?.writeCapable && !useAssistantStore.getState().apiCallsAcknowledged) {\n setPendingConsentMode(newMode);\n return;\n }\n performModeChange(newMode);\n },\n [performModeChange]\n );\n\n const handleConsentConfirm = useCallback(() => {\n const target = pendingConsentMode;\n setPendingConsentMode(null);\n acknowledgeApiCalls();\n if (target) performModeChange(target);\n }, [pendingConsentMode, acknowledgeApiCalls, performModeChange]);\n\n const handleConsentCancel = useCallback(() => {\n setPendingConsentMode(null);\n }, []);\n\n return (\n <div className=\"flex flex-1 flex-col overflow-hidden\">\n {/* Transcript is always visible now — the old collapse-by-default accordion\n is gone; conversation history lives behind the header button instead. */}\n {messages.length === 0 ? (\n <AssistantEmptyState mode={mode} onSuggestionClick={handleSuggestionClick} />\n ) : (\n <div className=\"flex min-h-0 flex-1 flex-col\">\n <AssistantMessageList\n messages={messages}\n streamingMessageId={activeStreamingMessageId}\n failedMessageId={failedMessageId}\n onRetry={handleRetry}\n />\n </div>\n )}\n\n <AssistantComposer\n onSend={(value, attachments) => void handleSend(value, attachments)}\n disabled={activeIsProcessing}\n placeholder={\n mode === 'api-calls'\n ? tr('healthybowl.assistant.chatArea.placeholderActions', 'What would you like me to do?')\n : tr('healthybowl.assistant.chatArea.placeholderGeneral', 'Ask HealthyBowl anything…')\n }\n mode={mode}\n availableModes={availableModes}\n onModeChange={handleModeChange}\n />\n\n <AssistantApiCallsConsentDialog\n open={pendingConsentMode !== null}\n onConfirm={handleConsentConfirm}\n onCancel={handleConsentCancel}\n />\n </div>\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA8CA,IAAM,KAAkD;CACtD,SAAS;CACT,aAAa;CACb,gBAAgB;CACjB,EACK,KAA2B;AAEjC,SAAS,KAAqB;AAC5B,QAAO,GAAG,KAAK,KAAK,CAAC,GAAG,KAAK,QAAQ,CAAC,SAAS,GAAG,CAAC,MAAM,GAAG,EAAE;;AAGhE,SAAS,GAA4B,GAAyB;CAC5D,IAAM,IAAU,aAAiB,QAAQ,EAAM,QAAQ,aAAa,GAAG,OAAO,EAAM,CAAC,aAAa;AAUlG,QAPE,EAAQ,SAAS,sBAAsB,IACvC,EAAQ,SAAS,eAAe,IAChC,EAAQ,SAAS,oBAAoB,GAE9B,KAGF;EACL;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACD,CAAC,MAAM,MAAa,EAAQ,SAAS,EAAS,CAAC;;AAGlD,SAAS,GAA0B,GAA0B;AAC3D,QAAO,EACJ,QAAQ,6CAA6C,eAAe,CACpE,QAAQ,yDAAyD,eAAe,CAChF,QAAQ,4DAA4D,iBAAiB,CACrF,QAAQ,6BAA6B,qBAAqB;;AAG/D,SAAS,EAAuB,GAAsC;AACpE,QAAO,EAAQ,MAAM,MAAM,WAAW;;AAGxC,SAAS,EAAiB,GAA6C;AACrE,SAAQ,KAAS,EAAE,EAChB,QAAQ,MAAS,EAAK,SAAS,UAAU,OAAO,EAAK,QAAS,SAAS,CACvE,KAAK,MAAS,EAAK,MAAM,MAAM,IAAI,GAAG,CACtC,OAAO,QAAQ,CACf,KAAK,KAAK;;AAGf,SAAS,EAAgB,GAA+C;AACtE,SAAQ,KAAS,EAAE,EAChB,QAAQ,MAAS,EAAK,SAAS,UAAU,EAAK,KAAK,CACnD,KAAK,MAAS;EACb,IAAM,IAAS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E,gBAAgB,CAAC,EAAkB,UAAU,CAAC,sBAAsB;AAC9E,KAAsB,EAAQ;AAC9B;;AAEF,IAAkB,EAAQ;IAE5B,CAAC,EAAkB,CACpB,EAEK,KAAuB,QAAkB;EAC7C,IAAM,IAAS;AAGf,EAFA,EAAsB,KAAK,EAC3B,IAAqB,EACjB,KAAQ,EAAkB,EAAO;IACpC;EAAC;EAAoB;EAAqB;EAAkB,CAAC,EAE1D,KAAsB,QAAkB;AAC5C,IAAsB,KAAK;IAC1B,EAAE,CAAC;AAEN,QACE,mBAAC,OAAD;EAAK,WAAU;YAAf;GAGG,EAAS,WAAW,IACnB,kBAAC,GAAD;IAA2B;IAAM,mBAAmB;IAAyB,CAAA,GAE7E,kBAAC,OAAD;IAAK,WAAU;cACb,kBAAC,GAAD;KACY;KACV,oBAAoB;KACH;KACjB,SAAS;KACT,CAAA;IACE,CAAA;GAGR,kBAAC,IAAD;IACE,SAAS,GAAO,MAAgB,KAAK,EAAW,GAAO,EAAY;IACnE,UAAU;IACV,aACE,MAAS,cACL,EAAG,qDAAqD,gCAAgC,GACxF,EAAG,qDAAqD,4BAA4B;IAEpF;IACU;IAChB,cAAc;IACd,CAAA;GAEF,kBAAC,GAAD;IACE,MAAM,MAAuB;IAC7B,WAAW;IACX,UAAU;IACV,CAAA;GACE"}
@@ -1,17 +1,17 @@
1
1
  import { getWorkspaceId as e } from "../utils/assistantContext.js";
2
- import { MAX_INLINE_CHARS_PER_FILE as t, classifyAttachment as n, truncateForInline as r, validateFile as i } from "../utils/assistantAttachments.js";
3
- import { downscaleImage as a } from "../healthybowl/utils/imageDownscale.js";
4
- import { useCallback as o, useEffect as s, useRef as c, useState as l } from "react";
5
- import { useSaveToFiles as u } from "@burdenoff/fe-libs/storage";
6
- import { graphqlFetch as d } from "@burdenoff/fe-libs/shared/graphql";
2
+ import { MAX_INLINE_CHARS_PER_FILE as t, classifyAttachment as n, hasAttachmentWorkInFlight as r, truncateForInline as i, validateFile as a } from "../utils/assistantAttachments.js";
3
+ import { downscaleImage as o } from "../healthybowl/utils/imageDownscale.js";
4
+ import { useCallback as s, useEffect as c, useRef as l, useState as u } from "react";
5
+ import { useSaveToFiles as d } from "@burdenoff/fe-libs/storage";
6
+ import { graphqlFetch as f } from "@burdenoff/fe-libs/shared/graphql";
7
7
  //#region src/hooks/useAssistantAttachments.ts
8
- var f = "/HealthyBowl/AI Assistant/Attachments", p = "\n query HealthyBowlAssistantAttachmentUrl($id: ID!) {\n getFileDownloadUrl(id: $id)\n }\n";
9
- async function m(e, t) {
8
+ var p = "/HealthyBowl/AI Assistant/Attachments", m = "\n query HealthyBowlAssistantAttachmentUrl($id: ID!) {\n getFileDownloadUrl(id: $id)\n }\n";
9
+ async function h(e, t) {
10
10
  if (!e || !t) return null;
11
11
  try {
12
- return (await d({
12
+ return (await f({
13
13
  gateway: "workspace",
14
- query: p,
14
+ query: m,
15
15
  variables: { id: e },
16
16
  workspaceToken: !0,
17
17
  workspaceId: t,
@@ -21,72 +21,72 @@ async function m(e, t) {
21
21
  return null;
22
22
  }
23
23
  }
24
- var h = 0;
25
- function g() {
26
- return h += 1, `att-${Date.now()}-${h}`;
24
+ var g = 0;
25
+ function _() {
26
+ return g += 1, `att-${Date.now()}-${g}`;
27
27
  }
28
- async function _(e) {
29
- let i = n(e.type, e.name), o = {
30
- id: g(),
28
+ async function v(e) {
29
+ let r = n(e.type, e.name), a = {
30
+ id: _(),
31
31
  status: "pending"
32
32
  };
33
- if (i === "image") {
34
- let t = await a(e);
33
+ if (r === "image") {
34
+ let t = await o(e);
35
35
  return {
36
36
  attachment: {
37
- ...o,
37
+ ...a,
38
38
  filename: t.filename,
39
39
  mimeType: t.mimeType,
40
40
  size: t.blob.size,
41
- kind: i,
41
+ kind: r,
42
42
  previewUrl: t.dataUrl
43
43
  },
44
44
  blob: t.blob
45
45
  };
46
46
  }
47
- if (i === "text") {
48
- let { text: n, truncated: a } = r(await e.text(), t);
47
+ if (r === "text") {
48
+ let { text: n, truncated: o } = i(await e.text(), t);
49
49
  return {
50
50
  attachment: {
51
- ...o,
51
+ ...a,
52
52
  filename: e.name,
53
53
  mimeType: e.type || "text/plain",
54
54
  size: e.size,
55
- kind: i,
55
+ kind: r,
56
56
  textContent: n,
57
- textTruncated: a
57
+ textTruncated: o
58
58
  },
59
59
  blob: e
60
60
  };
61
61
  }
62
62
  return {
63
63
  attachment: {
64
- ...o,
64
+ ...a,
65
65
  filename: e.name,
66
66
  mimeType: e.type || "application/octet-stream",
67
67
  size: e.size,
68
- kind: i
68
+ kind: r
69
69
  },
70
70
  blob: e
71
71
  };
72
72
  }
73
- function v() {
74
- let { save: t } = u(), [n, r] = l([]), [a, d] = l(null), p = c(Promise.resolve()), h = c(/* @__PURE__ */ new Map()), g = c(/* @__PURE__ */ new Set()), v = c(0), y = c(!0);
75
- s(() => () => {
76
- y.current = !1;
73
+ function y() {
74
+ let { save: t } = d(), [n, i] = u([]), [o, f] = u(null), m = l(Promise.resolve()), [g, _] = u(0), y = l(0), b = l(/* @__PURE__ */ new Map()), x = l(/* @__PURE__ */ new Set()), S = l(0), C = l(!0);
75
+ c(() => () => {
76
+ C.current = !1;
77
77
  }, []);
78
- let b = c([]);
79
- s(() => {
80
- b.current = n;
78
+ let w = l([]);
79
+ c(() => {
80
+ w.current = n;
81
81
  }, [n]);
82
- let x = o((e, t) => {
83
- y.current && r((n) => n.map((n) => n.id === e ? {
82
+ let T = s((e, t) => {
83
+ C.current && i((n) => n.map((n) => n.id === e ? {
84
84
  ...n,
85
85
  ...t
86
86
  } : n));
87
- }, []), S = o(async ({ attachment: n, blob: r }) => {
88
- if (!g.current.has(n.id)) {
89
- x(n.id, { status: "uploading" });
87
+ }, []), E = s(async ({ attachment: n, blob: r }) => {
88
+ if (!x.current.has(n.id)) {
89
+ T(n.id, { status: "uploading" });
90
90
  try {
91
91
  let i = await t({
92
92
  source: {
@@ -99,60 +99,71 @@ function v() {
99
99
  mimeType: n.mimeType
100
100
  })
101
101
  },
102
- folderPath: f
102
+ folderPath: p
103
103
  });
104
- if (g.current.has(n.id)) return;
105
- let a = i?.id ? await m(i.id, e()) : null;
106
- if (g.current.has(n.id)) return;
107
- x(n.id, {
104
+ if (x.current.has(n.id)) return;
105
+ let a = i?.id ? await h(i.id, e()) : null;
106
+ if (x.current.has(n.id)) return;
107
+ T(n.id, {
108
108
  status: "ready",
109
109
  fileId: i?.id,
110
110
  downloadUrl: a ?? void 0
111
111
  });
112
112
  } catch (e) {
113
- if (g.current.has(n.id)) return;
113
+ if (x.current.has(n.id)) return;
114
114
  if (n.kind === "text") {
115
- x(n.id, { status: "ready" });
115
+ T(n.id, { status: "ready" });
116
116
  return;
117
117
  }
118
- x(n.id, {
118
+ T(n.id, {
119
119
  status: "error",
120
120
  error: e instanceof Error ? e.message : "Upload failed"
121
121
  });
122
122
  }
123
123
  }
124
- }, [x, t]), C = o((e) => {
124
+ }, [T, t]), D = s((e) => {
125
125
  if (!e) return;
126
126
  let t = Array.from(e);
127
127
  if (t.length === 0) return;
128
- d(null);
128
+ f(null);
129
129
  let n = [];
130
130
  for (let e of t) {
131
- let t = i(e, v.current);
131
+ let t = a(e, S.current);
132
132
  if (t) {
133
- d(t);
133
+ f(t);
134
134
  continue;
135
135
  }
136
- n.push(e), v.current += 1;
136
+ n.push(e), S.current += 1;
137
137
  }
138
- if (n.length !== 0) for (let e of n) p.current = p.current.then(async () => {
139
- let t;
140
- try {
141
- t = await _(e);
142
- } catch {
143
- v.current = Math.max(0, v.current - 1), y.current && d("unreadable");
144
- return;
138
+ if (n.length !== 0) {
139
+ _((e) => e + n.length);
140
+ for (let e of n) {
141
+ let t = y.current;
142
+ m.current = m.current.then(async () => {
143
+ let n = null;
144
+ try {
145
+ n = await v(e);
146
+ } catch {
147
+ S.current = Math.max(0, S.current - 1), C.current && f("unreadable");
148
+ }
149
+ if (!C.current || (_((e) => Math.max(0, e - 1)), !n)) return;
150
+ if (t !== y.current) {
151
+ S.current = Math.max(0, S.current - 1);
152
+ return;
153
+ }
154
+ let r = n;
155
+ b.current.set(r.attachment.id, r.blob), i((e) => [...e, r.attachment]), await E(r);
156
+ });
145
157
  }
146
- y.current && (h.current.set(t.attachment.id, t.blob), r((e) => [...e, t.attachment]), await S(t));
147
- });
148
- }, [S]), w = o((e) => {
149
- g.current.add(e), h.current.delete(e), v.current = Math.max(0, v.current - 1), r((t) => t.filter((t) => t.id !== e));
150
- }, []), T = o((e) => {
151
- let t = b.current.find((t) => t.id === e), n = h.current.get(e);
152
- !t || t.status !== "error" || !n || (g.current.delete(e), x(e, {
158
+ }
159
+ }, [E]), O = s((e) => {
160
+ x.current.add(e), b.current.delete(e), S.current = Math.max(0, S.current - 1), i((t) => t.filter((t) => t.id !== e));
161
+ }, []), k = s((e) => {
162
+ let t = w.current.find((t) => t.id === e), n = b.current.get(e);
163
+ !t || t.status !== "error" || !n || (x.current.delete(e), T(e, {
153
164
  status: "pending",
154
165
  error: void 0
155
- }), p.current = p.current.then(() => S({
166
+ }), m.current = m.current.then(() => E({
156
167
  attachment: {
157
168
  ...t,
158
169
  status: "pending",
@@ -160,22 +171,22 @@ function v() {
160
171
  },
161
172
  blob: n
162
173
  })));
163
- }, [x, S]), E = o(() => {
164
- v.current = 0, b.current.forEach((e) => g.current.add(e.id)), h.current.clear(), r([]);
174
+ }, [T, E]), A = s(() => {
175
+ y.current += 1, S.current = 0, w.current.forEach((e) => x.current.add(e.id)), b.current.clear(), i([]);
165
176
  }, []);
166
177
  return {
167
178
  attachments: n,
168
- isBusy: n.some((e) => e.status === "pending" || e.status === "uploading"),
169
- rejection: a,
170
- addFiles: C,
171
- remove: w,
172
- retry: T,
173
- clear: E,
174
- clearRejection: o(() => d(null), []),
175
- canAddMore: n.length < 5
179
+ isBusy: r(g, n),
180
+ rejection: o,
181
+ addFiles: D,
182
+ remove: O,
183
+ retry: k,
184
+ clear: A,
185
+ clearRejection: s(() => f(null), []),
186
+ canAddMore: S.current < 5
176
187
  };
177
188
  }
178
189
  //#endregion
179
- export { v as useAssistantAttachments };
190
+ export { y as useAssistantAttachments };
180
191
 
181
192
  //# sourceMappingURL=useAssistantAttachments.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"useAssistantAttachments.js","names":[],"sources":["../../src/hooks/useAssistantAttachments.ts"],"sourcesContent":["/**\n * Draft-attachment state for the assistant composer (Workstream 3).\n *\n * Owns the whole lifecycle of a file the user attached but has not sent yet:\n * validate → (images) downscale → preview → upload to the workspace file\n * library → resolve a presigned URL → ready. Each attachment carries its own\n * status, so one slow or failed upload never blocks the others.\n *\n * Uploads run **sequentially**. `useSaveToFiles` exposes a single shared\n * `isPending`/`progress` pair, so firing several at once would leave that state\n * last-write-wins; a queue also keeps a farmer on a rural connection from having\n * five uploads compete for the same narrow uplink.\n *\n * Text-like files degrade gracefully: their content is inlined into the prompt,\n * so a failed upload still leaves a usable attachment (it just has no URL).\n * Images and binaries have nothing to fall back on and are marked failed.\n */\n\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport { useSaveToFiles } from '@burdenoff/fe-libs/storage';\nimport { graphqlFetch } from '@burdenoff/fe-libs/shared/graphql';\nimport { downscaleImage } from '@/healthybowl/utils/imageDownscale';\nimport { getWorkspaceId } from '@/utils/assistantContext';\nimport {\n MAX_ATTACHMENTS,\n MAX_INLINE_CHARS_PER_FILE,\n classifyAttachment,\n truncateForInline,\n validateFile,\n type AssistantAttachment,\n type AttachmentRejection,\n} from '@/utils/assistantAttachments';\n\n/** Where assistant attachments land in the workspace file library. */\nconst ATTACHMENT_FOLDER = '/HealthyBowl/AI Assistant/Attachments';\n\nconst DOWNLOAD_URL_QUERY = `\n query HealthyBowlAssistantAttachmentUrl($id: ID!) {\n getFileDownloadUrl(id: $id)\n }\n`;\n\nasync function resolveDownloadUrl(fileId: string, workspaceId: string): Promise<string | null> {\n if (!fileId || !workspaceId) return null;\n try {\n const res = await graphqlFetch<{ getFileDownloadUrl?: string | null }>({\n gateway: 'workspace',\n query: DOWNLOAD_URL_QUERY,\n variables: { id: fileId },\n workspaceToken: true,\n workspaceId,\n suppressGlobalErrorEvent: true,\n });\n return res.data?.getFileDownloadUrl ?? null;\n } catch {\n return null;\n }\n}\n\nlet attachmentSeq = 0;\nfunction nextAttachmentId(): string {\n attachmentSeq += 1;\n return `att-${Date.now()}-${attachmentSeq}`;\n}\n\ninterface PreparedFile {\n attachment: AssistantAttachment;\n /** Bytes to upload — the downscaled JPEG for images, the original otherwise. */\n blob: Blob;\n}\n\nasync function prepareFile(file: File): Promise<PreparedFile> {\n const kind = classifyAttachment(file.type, file.name);\n const base = {\n id: nextAttachmentId(),\n status: 'pending' as const,\n };\n\n if (kind === 'image') {\n // Reuses the pest-scan downscaler: a phone photo goes from several MB to a\n // ~1280px JPEG, which keeps the upload quick on a field connection.\n const down = await downscaleImage(file);\n return {\n attachment: {\n ...base,\n filename: down.filename,\n mimeType: down.mimeType,\n size: down.blob.size,\n kind,\n previewUrl: down.dataUrl,\n },\n blob: down.blob,\n };\n }\n\n if (kind === 'text') {\n const raw = await file.text();\n const { text, truncated } = truncateForInline(raw, MAX_INLINE_CHARS_PER_FILE);\n return {\n attachment: {\n ...base,\n filename: file.name,\n mimeType: file.type || 'text/plain',\n size: file.size,\n kind,\n textContent: text,\n textTruncated: truncated,\n },\n blob: file,\n };\n }\n\n return {\n attachment: {\n ...base,\n filename: file.name,\n mimeType: file.type || 'application/octet-stream',\n size: file.size,\n kind,\n },\n blob: file,\n };\n}\n\nexport interface UseAssistantAttachmentsResult {\n attachments: AssistantAttachment[];\n /** True while any attachment is still being prepared or uploaded. */\n isBusy: boolean;\n /** Most recent rejection, for a transient inline message. */\n rejection: AttachmentRejection | null;\n addFiles: (files: FileList | File[] | null | undefined) => void;\n remove: (id: string) => void;\n /** Re-upload a single failed attachment, reusing the bytes already prepared. */\n retry: (id: string) => void;\n clear: () => void;\n clearRejection: () => void;\n canAddMore: boolean;\n}\n\nexport function useAssistantAttachments(): UseAssistantAttachmentsResult {\n const { save } = useSaveToFiles();\n const [attachments, setAttachments] = useState<AssistantAttachment[]>([]);\n const [rejection, setRejection] = useState<AttachmentRejection | null>(null);\n\n // Serialises uploads: each new batch chains onto the tail of this promise.\n const uploadChainRef = useRef<Promise<void>>(Promise.resolve());\n // Prepared bytes kept by id so a failed upload can be retried WITHOUT asking\n // the user to pick the file again — re-reading it is impossible anyway, the\n // original File handle is gone once the picker closes.\n const blobsRef = useRef<Map<string, Blob>>(new Map());\n // Ids dropped while their upload was in flight — the result is discarded so a\n // removed attachment never reappears as 'ready'.\n const removedIdsRef = useRef<Set<string>>(new Set());\n // Authoritative slot count for validation. `attachments.length` lags: a file\n // is accepted synchronously but only appears once its async prepare (image\n // downscale / text read) resolves, so counting rendered rows would let a\n // multi-file drop overshoot MAX_ATTACHMENTS.\n const countRef = useRef(0);\n const mountedRef = useRef(true);\n useEffect(\n () => () => {\n mountedRef.current = false;\n },\n []\n );\n\n // Render-value mirror, so `clear()` can cancel in-flight uploads without\n // reaching for their ids from inside a state updater (updaters must be pure).\n const attachmentsRef = useRef<AssistantAttachment[]>([]);\n useEffect(() => {\n attachmentsRef.current = attachments;\n }, [attachments]);\n\n const patch = useCallback((id: string, changes: Partial<AssistantAttachment>) => {\n if (!mountedRef.current) return;\n setAttachments((current) =>\n current.map((attachment) => (attachment.id === id ? { ...attachment, ...changes } : attachment))\n );\n }, []);\n\n const upload = useCallback(\n async ({ attachment, blob }: PreparedFile): Promise<void> => {\n if (removedIdsRef.current.has(attachment.id)) return;\n patch(attachment.id, { status: 'uploading' });\n\n try {\n const saved = await save({\n source: {\n kind: 'blob',\n filename: attachment.filename,\n mimeType: attachment.mimeType,\n getBlob: async () => ({\n blob,\n filename: attachment.filename,\n mimeType: attachment.mimeType,\n }),\n },\n folderPath: ATTACHMENT_FOLDER,\n });\n if (removedIdsRef.current.has(attachment.id)) return;\n\n const downloadUrl = saved?.id ? await resolveDownloadUrl(saved.id, getWorkspaceId()) : null;\n if (removedIdsRef.current.has(attachment.id)) return;\n\n patch(attachment.id, {\n status: 'ready',\n fileId: saved?.id,\n downloadUrl: downloadUrl ?? undefined,\n });\n } catch (error) {\n if (removedIdsRef.current.has(attachment.id)) return;\n // A text file's content is already inlined in the prompt, so losing the\n // upload costs only the URL — still worth sending. Anything else is dead\n // weight without its bytes.\n if (attachment.kind === 'text') {\n patch(attachment.id, { status: 'ready' });\n return;\n }\n patch(attachment.id, {\n status: 'error',\n error: error instanceof Error ? error.message : 'Upload failed',\n });\n }\n },\n [patch, save]\n );\n\n const addFiles = useCallback(\n (files: FileList | File[] | null | undefined) => {\n if (!files) return;\n const incoming = Array.from(files);\n if (incoming.length === 0) return;\n\n setRejection(null);\n\n // Take the accepted prefix of the batch: dropping six files at once keeps\n // the first five and reports the overflow, rather than rejecting the drop.\n const accepted: File[] = [];\n for (const file of incoming) {\n const problem = validateFile(file, countRef.current);\n if (problem) {\n setRejection(problem);\n continue;\n }\n accepted.push(file);\n countRef.current += 1;\n }\n if (accepted.length === 0) return;\n\n // Preparation (downscale / text read) is async; each file appends itself\n // as soon as it is prepared, then uploads in turn.\n for (const file of accepted) {\n uploadChainRef.current = uploadChainRef.current.then(async () => {\n let prepared: PreparedFile;\n try {\n prepared = await prepareFile(file);\n } catch {\n countRef.current = Math.max(0, countRef.current - 1);\n if (mountedRef.current) setRejection('unreadable');\n return;\n }\n if (!mountedRef.current) return;\n blobsRef.current.set(prepared.attachment.id, prepared.blob);\n setAttachments((list) => [...list, prepared.attachment]);\n await upload(prepared);\n });\n }\n },\n [upload]\n );\n\n const remove = useCallback((id: string) => {\n removedIdsRef.current.add(id);\n blobsRef.current.delete(id);\n countRef.current = Math.max(0, countRef.current - 1);\n setAttachments((current) => current.filter((attachment) => attachment.id !== id));\n }, []);\n\n const retry = useCallback(\n (id: string) => {\n const attachment = attachmentsRef.current.find((candidate) => candidate.id === id);\n const blob = blobsRef.current.get(id);\n if (!attachment || attachment.status !== 'error' || !blob) return;\n\n // A previous `clear()` may have tombstoned this id; un-tombstone it or the\n // retry would upload successfully and then discard its own result.\n removedIdsRef.current.delete(id);\n patch(id, { status: 'pending', error: undefined });\n uploadChainRef.current = uploadChainRef.current.then(() =>\n upload({ attachment: { ...attachment, status: 'pending', error: undefined }, blob })\n );\n },\n [patch, upload]\n );\n\n const clear = useCallback(() => {\n countRef.current = 0;\n attachmentsRef.current.forEach((attachment) => removedIdsRef.current.add(attachment.id));\n blobsRef.current.clear();\n setAttachments([]);\n }, []);\n\n const isBusy = attachments.some((attachment) => attachment.status === 'pending' || attachment.status === 'uploading');\n\n return {\n attachments,\n isBusy,\n rejection,\n addFiles,\n remove,\n retry,\n clear,\n clearRejection: useCallback(() => setRejection(null), []),\n canAddMore: attachments.length < MAX_ATTACHMENTS,\n };\n}\n"],"mappings":";;;;;;;AAkCA,IAAM,IAAoB,yCAEpB,IAAqB;AAM3B,eAAe,EAAmB,GAAgB,GAA6C;AAC7F,KAAI,CAAC,KAAU,CAAC,EAAa,QAAO;AACpC,KAAI;AASF,UARY,MAAM,EAAqD;GACrE,SAAS;GACT,OAAO;GACP,WAAW,EAAE,IAAI,GAAQ;GACzB,gBAAgB;GAChB;GACA,0BAA0B;GAC3B,CAAC,EACS,MAAM,sBAAsB;SACjC;AACN,SAAO;;;AAIX,IAAI,IAAgB;AACpB,SAAS,IAA2B;AAElC,QADA,KAAiB,GACV,OAAO,KAAK,KAAK,CAAC,GAAG;;AAS9B,eAAe,EAAY,GAAmC;CAC5D,IAAM,IAAO,EAAmB,EAAK,MAAM,EAAK,KAAK,EAC/C,IAAO;EACX,IAAI,GAAkB;EACtB,QAAQ;EACT;AAED,KAAI,MAAS,SAAS;EAGpB,IAAM,IAAO,MAAM,EAAe,EAAK;AACvC,SAAO;GACL,YAAY;IACV,GAAG;IACH,UAAU,EAAK;IACf,UAAU,EAAK;IACf,MAAM,EAAK,KAAK;IAChB;IACA,YAAY,EAAK;IAClB;GACD,MAAM,EAAK;GACZ;;AAGH,KAAI,MAAS,QAAQ;EAEnB,IAAM,EAAE,SAAM,iBAAc,EADhB,MAAM,EAA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D,MAAM,EAAO,EAAS;IACtB;IAGN,CAAC,EAAO,CACT,EAEK,IAAS,GAAa,MAAe;AAIzC,EAHA,EAAc,QAAQ,IAAI,EAAG,EAC7B,EAAS,QAAQ,OAAO,EAAG,EAC3B,EAAS,UAAU,KAAK,IAAI,GAAG,EAAS,UAAU,EAAE,EACpD,GAAgB,MAAY,EAAQ,QAAQ,MAAe,EAAW,OAAO,EAAG,CAAC;IAChF,EAAE,CAAC,EAEA,IAAQ,GACX,MAAe;EACd,IAAM,IAAa,EAAe,QAAQ,MAAM,MAAc,EAAU,OAAO,EAAG,EAC5E,IAAO,EAAS,QAAQ,IAAI,EAAG;AACjC,GAAC,KAAc,EAAW,WAAW,WAAW,CAAC,MAIrD,EAAc,QAAQ,OAAO,EAAG,EAChC,EAAM,GAAI;GAAE,QAAQ;GAAW,OAAO,KAAA;GAAW,CAAC,EAClD,EAAe,UAAU,EAAe,QAAQ,WAC9C,EAAO;GAAE,YAAY;IAAE,GAAG;IAAY,QAAQ;IAAW,OAAO,KAAA;IAAW;GAAE;GAAM,CAAC,CACrF;IAEH,CAAC,GAAO,EAAO,CAChB,EAEK,IAAQ,QAAkB;AAI9B,EAHA,EAAS,UAAU,GACnB,EAAe,QAAQ,SAAS,MAAe,EAAc,QAAQ,IAAI,EAAW,GAAG,CAAC,EACxF,EAAS,QAAQ,OAAO,EACxB,EAAe,EAAE,CAAC;IACjB,EAAE,CAAC;AAIN,QAAO;EACL;EACA,QAJa,EAAY,MAAM,MAAe,EAAW,WAAW,aAAa,EAAW,WAAW,YAAY;EAKnH;EACA;EACA;EACA;EACA;EACA,gBAAgB,QAAkB,EAAa,KAAK,EAAE,EAAE,CAAC;EACzD,YAAY,EAAY,SAAA;EACzB"}
1
+ {"version":3,"file":"useAssistantAttachments.js","names":[],"sources":["../../src/hooks/useAssistantAttachments.ts"],"sourcesContent":["/**\n * Draft-attachment state for the assistant composer (Workstream 3).\n *\n * Owns the whole lifecycle of a file the user attached but has not sent yet:\n * validate → (images) downscale → preview → upload to the workspace file\n * library → resolve a presigned URL → ready. Each attachment carries its own\n * status, so one slow or failed upload never blocks the others.\n *\n * Uploads run **sequentially**. `useSaveToFiles` exposes a single shared\n * `isPending`/`progress` pair, so firing several at once would leave that state\n * last-write-wins; a queue also keeps a farmer on a rural connection from having\n * five uploads compete for the same narrow uplink.\n *\n * Text-like files degrade gracefully: their content is inlined into the prompt,\n * so a failed upload still leaves a usable attachment (it just has no URL).\n * Images and binaries have nothing to fall back on and are marked failed.\n */\n\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport { useSaveToFiles } from '@burdenoff/fe-libs/storage';\nimport { graphqlFetch } from '@burdenoff/fe-libs/shared/graphql';\nimport { downscaleImage } from '@/healthybowl/utils/imageDownscale';\nimport { getWorkspaceId } from '@/utils/assistantContext';\nimport {\n MAX_ATTACHMENTS,\n MAX_INLINE_CHARS_PER_FILE,\n classifyAttachment,\n hasAttachmentWorkInFlight,\n truncateForInline,\n validateFile,\n type AssistantAttachment,\n type AttachmentRejection,\n} from '@/utils/assistantAttachments';\n\n/** Where assistant attachments land in the workspace file library. */\nconst ATTACHMENT_FOLDER = '/HealthyBowl/AI Assistant/Attachments';\n\nconst DOWNLOAD_URL_QUERY = `\n query HealthyBowlAssistantAttachmentUrl($id: ID!) {\n getFileDownloadUrl(id: $id)\n }\n`;\n\nasync function resolveDownloadUrl(fileId: string, workspaceId: string): Promise<string | null> {\n if (!fileId || !workspaceId) return null;\n try {\n const res = await graphqlFetch<{ getFileDownloadUrl?: string | null }>({\n gateway: 'workspace',\n query: DOWNLOAD_URL_QUERY,\n variables: { id: fileId },\n workspaceToken: true,\n workspaceId,\n suppressGlobalErrorEvent: true,\n });\n return res.data?.getFileDownloadUrl ?? null;\n } catch {\n return null;\n }\n}\n\nlet attachmentSeq = 0;\nfunction nextAttachmentId(): string {\n attachmentSeq += 1;\n return `att-${Date.now()}-${attachmentSeq}`;\n}\n\ninterface PreparedFile {\n attachment: AssistantAttachment;\n /** Bytes to upload — the downscaled JPEG for images, the original otherwise. */\n blob: Blob;\n}\n\nasync function prepareFile(file: File): Promise<PreparedFile> {\n const kind = classifyAttachment(file.type, file.name);\n const base = {\n id: nextAttachmentId(),\n status: 'pending' as const,\n };\n\n if (kind === 'image') {\n // Reuses the pest-scan downscaler: a phone photo goes from several MB to a\n // ~1280px JPEG, which keeps the upload quick on a field connection.\n const down = await downscaleImage(file);\n return {\n attachment: {\n ...base,\n filename: down.filename,\n mimeType: down.mimeType,\n size: down.blob.size,\n kind,\n previewUrl: down.dataUrl,\n },\n blob: down.blob,\n };\n }\n\n if (kind === 'text') {\n const raw = await file.text();\n const { text, truncated } = truncateForInline(raw, MAX_INLINE_CHARS_PER_FILE);\n return {\n attachment: {\n ...base,\n filename: file.name,\n mimeType: file.type || 'text/plain',\n size: file.size,\n kind,\n textContent: text,\n textTruncated: truncated,\n },\n blob: file,\n };\n }\n\n return {\n attachment: {\n ...base,\n filename: file.name,\n mimeType: file.type || 'application/octet-stream',\n size: file.size,\n kind,\n },\n blob: file,\n };\n}\n\nexport interface UseAssistantAttachmentsResult {\n attachments: AssistantAttachment[];\n /** True while any attachment is still being prepared or uploaded. */\n isBusy: boolean;\n /** Most recent rejection, for a transient inline message. */\n rejection: AttachmentRejection | null;\n addFiles: (files: FileList | File[] | null | undefined) => void;\n remove: (id: string) => void;\n /** Re-upload a single failed attachment, reusing the bytes already prepared. */\n retry: (id: string) => void;\n clear: () => void;\n clearRejection: () => void;\n canAddMore: boolean;\n}\n\nexport function useAssistantAttachments(): UseAssistantAttachmentsResult {\n const { save } = useSaveToFiles();\n const [attachments, setAttachments] = useState<AssistantAttachment[]>([]);\n const [rejection, setRejection] = useState<AttachmentRejection | null>(null);\n\n // Serialises uploads: each new batch chains onto the tail of this promise.\n const uploadChainRef = useRef<Promise<void>>(Promise.resolve());\n // Files accepted but not yet PREPARED (image downscale / text read). They have\n // no id and no row yet, so nothing else can see them — which is exactly why\n // they need their own counter: without it `isBusy` reads false, the composer\n // lets the user send, and the file lands on the NEXT message instead.\n const [preparingCount, setPreparingCount] = useState(0);\n // Bumped by `clear()`. A queued prepare closure captures the epoch it was\n // enqueued under and bails if it no longer matches, so a file whose draft was\n // already sent can never append itself afterwards.\n const epochRef = useRef(0);\n // Prepared bytes kept by id so a failed upload can be retried WITHOUT asking\n // the user to pick the file again — re-reading it is impossible anyway, the\n // original File handle is gone once the picker closes.\n const blobsRef = useRef<Map<string, Blob>>(new Map());\n // Ids dropped while their upload was in flight — the result is discarded so a\n // removed attachment never reappears as 'ready'.\n const removedIdsRef = useRef<Set<string>>(new Set());\n // Authoritative slot count for validation. `attachments.length` lags: a file\n // is accepted synchronously but only appears once its async prepare (image\n // downscale / text read) resolves, so counting rendered rows would let a\n // multi-file drop overshoot MAX_ATTACHMENTS.\n const countRef = useRef(0);\n const mountedRef = useRef(true);\n useEffect(\n () => () => {\n mountedRef.current = false;\n },\n []\n );\n\n // Render-value mirror, so `clear()` can cancel in-flight uploads without\n // reaching for their ids from inside a state updater (updaters must be pure).\n const attachmentsRef = useRef<AssistantAttachment[]>([]);\n useEffect(() => {\n attachmentsRef.current = attachments;\n }, [attachments]);\n\n const patch = useCallback((id: string, changes: Partial<AssistantAttachment>) => {\n if (!mountedRef.current) return;\n setAttachments((current) =>\n current.map((attachment) => (attachment.id === id ? { ...attachment, ...changes } : attachment))\n );\n }, []);\n\n const upload = useCallback(\n async ({ attachment, blob }: PreparedFile): Promise<void> => {\n if (removedIdsRef.current.has(attachment.id)) return;\n patch(attachment.id, { status: 'uploading' });\n\n try {\n const saved = await save({\n source: {\n kind: 'blob',\n filename: attachment.filename,\n mimeType: attachment.mimeType,\n getBlob: async () => ({\n blob,\n filename: attachment.filename,\n mimeType: attachment.mimeType,\n }),\n },\n folderPath: ATTACHMENT_FOLDER,\n });\n if (removedIdsRef.current.has(attachment.id)) return;\n\n const downloadUrl = saved?.id ? await resolveDownloadUrl(saved.id, getWorkspaceId()) : null;\n if (removedIdsRef.current.has(attachment.id)) return;\n\n patch(attachment.id, {\n status: 'ready',\n fileId: saved?.id,\n downloadUrl: downloadUrl ?? undefined,\n });\n } catch (error) {\n if (removedIdsRef.current.has(attachment.id)) return;\n // A text file's content is already inlined in the prompt, so losing the\n // upload costs only the URL — still worth sending. Anything else is dead\n // weight without its bytes.\n if (attachment.kind === 'text') {\n patch(attachment.id, { status: 'ready' });\n return;\n }\n patch(attachment.id, {\n status: 'error',\n error: error instanceof Error ? error.message : 'Upload failed',\n });\n }\n },\n [patch, save]\n );\n\n const addFiles = useCallback(\n (files: FileList | File[] | null | undefined) => {\n if (!files) return;\n const incoming = Array.from(files);\n if (incoming.length === 0) return;\n\n setRejection(null);\n\n // Take the accepted prefix of the batch: dropping six files at once keeps\n // the first five and reports the overflow, rather than rejecting the drop.\n const accepted: File[] = [];\n for (const file of incoming) {\n const problem = validateFile(file, countRef.current);\n if (problem) {\n setRejection(problem);\n continue;\n }\n accepted.push(file);\n countRef.current += 1;\n }\n if (accepted.length === 0) return;\n\n // Preparation (downscale / text read) is async; each file appends itself\n // as soon as it is prepared, then uploads in turn. Count them as busy NOW\n // rather than when they finish preparing — otherwise send stays live\n // through the whole downscale and the photo silently misses the message it\n // was attached to.\n setPreparingCount((count) => count + accepted.length);\n\n for (const file of accepted) {\n const epoch = epochRef.current;\n uploadChainRef.current = uploadChainRef.current.then(async () => {\n let prepared: PreparedFile | null = null;\n try {\n prepared = await prepareFile(file);\n } catch {\n countRef.current = Math.max(0, countRef.current - 1);\n if (mountedRef.current) setRejection('unreadable');\n }\n if (!mountedRef.current) return;\n setPreparingCount((count) => Math.max(0, count - 1));\n if (!prepared) return;\n // The draft this file belonged to has already been sent or cleared.\n if (epoch !== epochRef.current) {\n countRef.current = Math.max(0, countRef.current - 1);\n return;\n }\n const ready = prepared;\n blobsRef.current.set(ready.attachment.id, ready.blob);\n setAttachments((list) => [...list, ready.attachment]);\n await upload(ready);\n });\n }\n },\n [upload]\n );\n\n const remove = useCallback((id: string) => {\n removedIdsRef.current.add(id);\n blobsRef.current.delete(id);\n countRef.current = Math.max(0, countRef.current - 1);\n setAttachments((current) => current.filter((attachment) => attachment.id !== id));\n }, []);\n\n const retry = useCallback(\n (id: string) => {\n const attachment = attachmentsRef.current.find((candidate) => candidate.id === id);\n const blob = blobsRef.current.get(id);\n if (!attachment || attachment.status !== 'error' || !blob) return;\n\n // A previous `clear()` may have tombstoned this id; un-tombstone it or the\n // retry would upload successfully and then discard its own result.\n removedIdsRef.current.delete(id);\n patch(id, { status: 'pending', error: undefined });\n uploadChainRef.current = uploadChainRef.current.then(() =>\n upload({ attachment: { ...attachment, status: 'pending', error: undefined }, blob })\n );\n },\n [patch, upload]\n );\n\n const clear = useCallback(() => {\n // Invalidate every prepare still in flight: those files belong to the draft\n // being cleared, not to whatever the user types next.\n epochRef.current += 1;\n countRef.current = 0;\n attachmentsRef.current.forEach((attachment) => removedIdsRef.current.add(attachment.id));\n blobsRef.current.clear();\n setAttachments([]);\n }, []);\n\n const isBusy = hasAttachmentWorkInFlight(preparingCount, attachments);\n\n return {\n attachments,\n isBusy,\n rejection,\n addFiles,\n remove,\n retry,\n clear,\n clearRejection: useCallback(() => setRejection(null), []),\n // countRef is authoritative — unlike `attachments`, it already counts files\n // that are still being prepared.\n canAddMore: countRef.current < MAX_ATTACHMENTS,\n };\n}\n"],"mappings":";;;;;;;AAmCA,IAAM,IAAoB,yCAEpB,IAAqB;AAM3B,eAAe,EAAmB,GAAgB,GAA6C;AAC7F,KAAI,CAAC,KAAU,CAAC,EAAa,QAAO;AACpC,KAAI;AASF,UARY,MAAM,EAAqD;GACrE,SAAS;GACT,OAAO;GACP,WAAW,EAAE,IAAI,GAAQ;GACzB,gBAAgB;GAChB;GACA,0BAA0B;GAC3B,CAAC,EACS,MAAM,sBAAsB;SACjC;AACN,SAAO;;;AAIX,IAAI,IAAgB;AACpB,SAAS,IAA2B;AAElC,QADA,KAAiB,GACV,OAAO,KAAK,KAAK,CAAC,GAAG;;AAS9B,eAAe,EAAY,G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AQ;GAAW,OAAO,KAAA;GAAW,CAAC,EAClD,EAAe,UAAU,EAAe,QAAQ,WAC9C,EAAO;GAAE,YAAY;IAAE,GAAG;IAAY,QAAQ;IAAW,OAAO,KAAA;IAAW;GAAE;GAAM,CAAC,CACrF;IAEH,CAAC,GAAO,EAAO,CAChB,EAEK,IAAQ,QAAkB;AAO9B,EAJA,EAAS,WAAW,GACpB,EAAS,UAAU,GACnB,EAAe,QAAQ,SAAS,MAAe,EAAc,QAAQ,IAAI,EAAW,GAAG,CAAC,EACxF,EAAS,QAAQ,OAAO,EACxB,EAAe,EAAE,CAAC;IACjB,EAAE,CAAC;AAIN,QAAO;EACL;EACA,QAJa,EAA0B,GAAgB,EAAY;EAKnE;EACA;EACA;EACA;EACA;EACA,gBAAgB,QAAkB,EAAa,KAAK,EAAE,EAAE,CAAC;EAGzD,YAAY,EAAS,UAAA;EACtB"}
@@ -28,30 +28,34 @@ function s(e) {
28
28
  }
29
29
  }
30
30
  function c({ onFinalize: c }) {
31
- let { locale: l } = i(), [u, d] = r(!1), [f, p] = r(""), [m, h] = r(null), g = n(null), _ = n(c);
31
+ let { locale: l } = i(), [u, d] = r(!1), [f, p] = r(""), [m, h] = r(null), g = n(null), _ = n(0), v = n(c);
32
32
  t(() => {
33
- _.current = c;
33
+ v.current = c;
34
34
  }, [c]);
35
- let v = o() !== null;
35
+ let y = o() !== null;
36
36
  t(() => () => {
37
37
  g.current?.abort(), g.current = null;
38
38
  }, []);
39
- let y = e(() => {
39
+ let b = e(() => {
40
40
  let e = o();
41
41
  if (!e || g.current) return;
42
42
  let t = new e();
43
- t.continuous = !0, t.interimResults = !0, t.lang = a[l] ?? "en-US", t.onresult = (e) => {
44
- let t = "", n = "";
45
- for (let r = e.resultIndex; r < e.results.length; r += 1) {
46
- let i = e.results[r], a = i[0]?.transcript ?? "";
47
- i.isFinal ? t += a : n += a;
43
+ t.continuous = !0, t.interimResults = !0, t.lang = a[l] ?? "en-US";
44
+ let n = _.current;
45
+ t.onresult = (e) => {
46
+ if (n !== _.current) return;
47
+ let t = "", r = "";
48
+ for (let n = e.resultIndex; n < e.results.length; n += 1) {
49
+ let i = e.results[n], a = i[0]?.transcript ?? "";
50
+ i.isFinal ? t += a : r += a;
48
51
  }
49
- t.trim() && _.current(t.trim()), p(n.trim());
52
+ t.trim() && v.current(t.trim()), p(r.trim());
50
53
  }, t.onerror = (e) => {
54
+ if (n !== _.current) return;
51
55
  let t = s(e.error);
52
56
  t !== "no-speech" && h(t);
53
57
  }, t.onend = () => {
54
- g.current = null, d(!1), p("");
58
+ n === _.current && (g.current = null, d(!1), p(""));
55
59
  };
56
60
  try {
57
61
  t.start();
@@ -60,22 +64,23 @@ function c({ onFinalize: c }) {
60
64
  return;
61
65
  }
62
66
  g.current = t, h(null), p(""), d(!0);
63
- }, [l]), b = e(() => {
64
- g.current?.stop(), d(!1), p("");
67
+ }, [l]), x = e(() => {
68
+ let e = g.current;
69
+ g.current = null, _.current += 1, e?.stop(), d(!1), p("");
65
70
  }, []);
66
71
  return {
67
- isSupported: v,
72
+ isSupported: y,
68
73
  isListening: u,
69
74
  interim: f,
70
75
  error: m,
71
- start: y,
72
- stop: b,
76
+ start: b,
77
+ stop: x,
73
78
  toggle: e(() => {
74
- u ? b() : y();
79
+ u ? x() : b();
75
80
  }, [
76
81
  u,
77
- y,
78
- b
82
+ b,
83
+ x
79
84
  ]),
80
85
  clearError: e(() => h(null), [])
81
86
  };
@@ -1 +1 @@
1
- {"version":3,"file":"useVoiceInput.js","names":[],"sources":["../../src/hooks/useVoiceInput.ts"],"sourcesContent":["/**\n * Speech-to-text for the assistant composer (Workstream 2 of the AI Assistant\n * V2 multimodal effort).\n *\n * Input-only, browser-native (Web Speech API) — no audio ever leaves the device\n * through us, and there is no text-to-speech here by design (the assistant does\n * not read replies aloud). It degrades gracefully: `isSupported` is false on\n * engines without SpeechRecognition (notably Firefox), and the composer hides\n * the mic entirely in that case rather than showing a dead control.\n *\n * Differences from the fe-libs `assistantWidget/useVoiceInput` this is modelled\n * on, all of which the composer needs:\n * - **interim results are exposed**, so the user sees words appear while\n * speaking instead of staring at a silent button until a phrase finalises;\n * - **errors are surfaced** (`error`) so a denied mic permission can be\n * explained rather than looking like a no-op;\n * - **the recogniser language follows the app locale** (a Tamil or Hindi\n * farmer dictating into an `en-US` recogniser gets garbage);\n * - **`stop()` resolves the final transcript** through `onFinalize`, so the\n * composer can commit exactly once when the user stops.\n */\n\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport { useI18n } from '@burdenoff/fe-libs/shared/providers/shell/I18nProvider';\nimport type { Locale } from '@burdenoff/fe-libs/shared/providers/shell/I18nProvider';\n\ninterface SpeechRecognitionEventLike extends Event {\n results: SpeechRecognitionResultList;\n resultIndex: number;\n}\n\ninterface SpeechRecognitionErrorEventLike extends Event {\n error: string;\n message: string;\n}\n\ninterface SpeechRecognitionInstance extends EventTarget {\n continuous: boolean;\n interimResults: boolean;\n lang: string;\n start(): void;\n stop(): void;\n abort(): void;\n onresult: ((event: SpeechRecognitionEventLike) => void) | null;\n onerror: ((event: SpeechRecognitionErrorEventLike) => void) | null;\n onend: (() => void) | null;\n}\n\ntype SpeechRecognitionConstructor = new () => SpeechRecognitionInstance;\n\n/**\n * BCP-47 tag for the recogniser, per app locale. Regional choices follow where\n * HealthyBowl actually operates (India for ta/hi) rather than a generic tag,\n * because the recogniser's acoustic model is region-specific.\n */\nconst RECOGNITION_LANG: Record<Locale, string> = {\n en: 'en-US',\n es: 'es-ES',\n fr: 'fr-FR',\n de: 'de-DE',\n ja: 'ja-JP',\n zh: 'zh-CN',\n ta: 'ta-IN',\n hi: 'hi-IN',\n ar: 'ar-SA',\n};\n\nfunction getSpeechRecognitionConstructor(): SpeechRecognitionConstructor | null {\n if (typeof window === 'undefined') return null;\n const win = window as unknown as Record<string, unknown>;\n return (\n (win.SpeechRecognition as SpeechRecognitionConstructor | undefined) ??\n (win.webkitSpeechRecognition as SpeechRecognitionConstructor | undefined) ??\n null\n );\n}\n\nexport type VoiceInputError = 'not-allowed' | 'no-speech' | 'audio-capture' | 'network' | 'unknown';\n\n/**\n * Map the spec's `SpeechRecognitionErrorEvent.error` codes onto the four cases\n * the UI actually distinguishes. Anything else is 'unknown' (generic copy).\n */\nfunction toVoiceInputError(code: string): VoiceInputError {\n switch (code) {\n case 'not-allowed':\n case 'service-not-allowed':\n return 'not-allowed';\n case 'no-speech':\n return 'no-speech';\n case 'audio-capture':\n return 'audio-capture';\n case 'network':\n return 'network';\n default:\n return 'unknown';\n }\n}\n\nexport interface UseVoiceInputOptions {\n /**\n * Called with each newly finalised phrase. The composer appends it to the\n * draft; keeping the committed text in the caller (rather than accumulating\n * here) means the user can freely edit while dictation continues.\n */\n onFinalize: (text: string) => void;\n}\n\nexport interface UseVoiceInputResult {\n isSupported: boolean;\n isListening: boolean;\n /** Words recognised but not yet finalised — render as a live hint. */\n interim: string;\n error: VoiceInputError | null;\n start: () => void;\n stop: () => void;\n /** Start if idle, stop if listening — what the mic button binds to. */\n toggle: () => void;\n clearError: () => void;\n}\n\nexport function useVoiceInput({ onFinalize }: UseVoiceInputOptions): UseVoiceInputResult {\n const { locale } = useI18n();\n const [isListening, setIsListening] = useState(false);\n const [interim, setInterim] = useState('');\n const [error, setError] = useState<VoiceInputError | null>(null);\n const recognitionRef = useRef<SpeechRecognitionInstance | null>(null);\n\n // Keep the newest callback reachable from the recogniser's long-lived event\n // handlers without re-creating the recogniser on every parent render.\n const onFinalizeRef = useRef(onFinalize);\n useEffect(() => {\n onFinalizeRef.current = onFinalize;\n }, [onFinalize]);\n\n const isSupported = getSpeechRecognitionConstructor() !== null;\n\n // Abort (not stop) on unmount: the panel is closing, so a trailing final\n // result would be committed into a draft nobody can see.\n useEffect(() => {\n return () => {\n recognitionRef.current?.abort();\n recognitionRef.current = null;\n };\n }, []);\n\n const start = useCallback(() => {\n const Ctor = getSpeechRecognitionConstructor();\n if (!Ctor || recognitionRef.current) return;\n\n const recognition = new Ctor();\n recognition.continuous = true;\n recognition.interimResults = true;\n recognition.lang = RECOGNITION_LANG[locale] ?? 'en-US';\n\n recognition.onresult = (event) => {\n let finalText = '';\n let interimText = '';\n for (let index = event.resultIndex; index < event.results.length; index += 1) {\n const result = event.results[index];\n const alternative = result[0]?.transcript ?? '';\n if (result.isFinal) {\n finalText += alternative;\n } else {\n interimText += alternative;\n }\n }\n if (finalText.trim()) onFinalizeRef.current(finalText.trim());\n setInterim(interimText.trim());\n };\n\n recognition.onerror = (event) => {\n const mapped = toVoiceInputError(event.error);\n // 'no-speech' fires routinely during a natural pause and the recogniser\n // keeps running — surfacing it would flash a scary message mid-sentence.\n if (mapped !== 'no-speech') setError(mapped);\n };\n\n recognition.onend = () => {\n recognitionRef.current = null;\n setIsListening(false);\n setInterim('');\n };\n\n try {\n recognition.start();\n } catch {\n // start() throws if a recogniser is somehow already running — treat the\n // session as not started rather than leaving the button stuck \"live\".\n recognitionRef.current = null;\n setIsListening(false);\n return;\n }\n\n recognitionRef.current = recognition;\n setError(null);\n setInterim('');\n setIsListening(true);\n }, [locale]);\n\n const stop = useCallback(() => {\n // stop() (not abort()) so the engine flushes the phrase in progress as a\n // final result — the last few words the user said are not thrown away.\n recognitionRef.current?.stop();\n setIsListening(false);\n setInterim('');\n }, []);\n\n const toggle = useCallback(() => {\n if (isListening) stop();\n else start();\n }, [isListening, start, stop]);\n\n const clearError = useCallback(() => setError(null), []);\n\n return { isSupported, isListening, interim, error, start, stop, toggle, clearError };\n}\n"],"mappings":";;;AAuDA,IAAM,IAA2C;CAC/C,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACL;AAED,SAAS,IAAuE;AAC9E,KAAI,OAAO,SAAW,IAAa,QAAO;CAC1C,IAAM,IAAM;AACZ,QACG,EAAI,qBACJ,EAAI,2BACL;;AAUJ,SAAS,EAAkB,GAA+B;AACxD,SAAQ,GAAR;EACE,KAAK;EACL,KAAK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Y,OAAO;UACb;AAIN,GADA,EAAe,UAAU,MACzB,EAAe,GAAM;AACrB;;AAMF,EAHA,EAAe,UAAU,GACzB,EAAS,KAAK,EACd,EAAW,GAAG,EACd,EAAe,GAAK;IACnB,CAAC,EAAO,CAAC,EAEN,IAAO,QAAkB;AAK7B,EAFA,EAAe,SAAS,MAAM,EAC9B,EAAe,GAAM,EACrB,EAAW,GAAG;IACb,EAAE,CAAC;AASN,QAAO;EAAE;EAAa;EAAa;EAAS;EAAO;EAAO;EAAM,QAPjD,QAAkB;AAC/B,GAAI,IAAa,GAAM,GAClB,GAAO;KACX;GAAC;GAAa;GAAO;GAAK,CAAC;EAI0C,YAFrD,QAAkB,EAAS,KAAK,EAAE,EAAE,CAAC;EAE4B"}
1
+ {"version":3,"file":"useVoiceInput.js","names":[],"sources":["../../src/hooks/useVoiceInput.ts"],"sourcesContent":["/**\n * Speech-to-text for the assistant composer (Workstream 2 of the AI Assistant\n * V2 multimodal effort).\n *\n * Input-only, browser-native (Web Speech API) — no audio ever leaves the device\n * through us, and there is no text-to-speech here by design (the assistant does\n * not read replies aloud). It degrades gracefully: `isSupported` is false on\n * engines without SpeechRecognition (notably Firefox), and the composer hides\n * the mic entirely in that case rather than showing a dead control.\n *\n * Differences from the fe-libs `assistantWidget/useVoiceInput` this is modelled\n * on, all of which the composer needs:\n * - **interim results are exposed**, so the user sees words appear while\n * speaking instead of staring at a silent button until a phrase finalises;\n * - **errors are surfaced** (`error`) so a denied mic permission can be\n * explained rather than looking like a no-op;\n * - **the recogniser language follows the app locale** (a Tamil or Hindi\n * farmer dictating into an `en-US` recogniser gets garbage);\n * - **`stop()` resolves the final transcript** through `onFinalize`, so the\n * composer can commit exactly once when the user stops.\n */\n\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport { useI18n } from '@burdenoff/fe-libs/shared/providers/shell/I18nProvider';\nimport type { Locale } from '@burdenoff/fe-libs/shared/providers/shell/I18nProvider';\n\ninterface SpeechRecognitionEventLike extends Event {\n results: SpeechRecognitionResultList;\n resultIndex: number;\n}\n\ninterface SpeechRecognitionErrorEventLike extends Event {\n error: string;\n message: string;\n}\n\ninterface SpeechRecognitionInstance extends EventTarget {\n continuous: boolean;\n interimResults: boolean;\n lang: string;\n start(): void;\n stop(): void;\n abort(): void;\n onresult: ((event: SpeechRecognitionEventLike) => void) | null;\n onerror: ((event: SpeechRecognitionErrorEventLike) => void) | null;\n onend: (() => void) | null;\n}\n\ntype SpeechRecognitionConstructor = new () => SpeechRecognitionInstance;\n\n/**\n * BCP-47 tag for the recogniser, per app locale. Regional choices follow where\n * HealthyBowl actually operates (India for ta/hi) rather than a generic tag,\n * because the recogniser's acoustic model is region-specific.\n */\nconst RECOGNITION_LANG: Record<Locale, string> = {\n en: 'en-US',\n es: 'es-ES',\n fr: 'fr-FR',\n de: 'de-DE',\n ja: 'ja-JP',\n zh: 'zh-CN',\n ta: 'ta-IN',\n hi: 'hi-IN',\n ar: 'ar-SA',\n};\n\nfunction getSpeechRecognitionConstructor(): SpeechRecognitionConstructor | null {\n if (typeof window === 'undefined') return null;\n const win = window as unknown as Record<string, unknown>;\n return (\n (win.SpeechRecognition as SpeechRecognitionConstructor | undefined) ??\n (win.webkitSpeechRecognition as SpeechRecognitionConstructor | undefined) ??\n null\n );\n}\n\nexport type VoiceInputError = 'not-allowed' | 'no-speech' | 'audio-capture' | 'network' | 'unknown';\n\n/**\n * Map the spec's `SpeechRecognitionErrorEvent.error` codes onto the four cases\n * the UI actually distinguishes. Anything else is 'unknown' (generic copy).\n */\nfunction toVoiceInputError(code: string): VoiceInputError {\n switch (code) {\n case 'not-allowed':\n case 'service-not-allowed':\n return 'not-allowed';\n case 'no-speech':\n return 'no-speech';\n case 'audio-capture':\n return 'audio-capture';\n case 'network':\n return 'network';\n default:\n return 'unknown';\n }\n}\n\nexport interface UseVoiceInputOptions {\n /**\n * Called with each newly finalised phrase. The composer appends it to the\n * draft; keeping the committed text in the caller (rather than accumulating\n * here) means the user can freely edit while dictation continues.\n */\n onFinalize: (text: string) => void;\n}\n\nexport interface UseVoiceInputResult {\n isSupported: boolean;\n isListening: boolean;\n /** Words recognised but not yet finalised — render as a live hint. */\n interim: string;\n error: VoiceInputError | null;\n start: () => void;\n stop: () => void;\n /** Start if idle, stop if listening — what the mic button binds to. */\n toggle: () => void;\n clearError: () => void;\n}\n\nexport function useVoiceInput({ onFinalize }: UseVoiceInputOptions): UseVoiceInputResult {\n const { locale } = useI18n();\n const [isListening, setIsListening] = useState(false);\n const [interim, setInterim] = useState('');\n const [error, setError] = useState<VoiceInputError | null>(null);\n const recognitionRef = useRef<SpeechRecognitionInstance | null>(null);\n // Incremented on every stop. Handlers capture the session they were created\n // under and ignore events that arrive after it ends.\n const sessionRef = useRef(0);\n\n // Keep the newest callback reachable from the recogniser's long-lived event\n // handlers without re-creating the recogniser on every parent render.\n const onFinalizeRef = useRef(onFinalize);\n useEffect(() => {\n onFinalizeRef.current = onFinalize;\n }, [onFinalize]);\n\n const isSupported = getSpeechRecognitionConstructor() !== null;\n\n // Abort (not stop) on unmount: the panel is closing, so a trailing final\n // result would be committed into a draft nobody can see.\n useEffect(() => {\n return () => {\n recognitionRef.current?.abort();\n recognitionRef.current = null;\n };\n }, []);\n\n const start = useCallback(() => {\n const Ctor = getSpeechRecognitionConstructor();\n if (!Ctor || recognitionRef.current) return;\n\n const recognition = new Ctor();\n recognition.continuous = true;\n recognition.interimResults = true;\n recognition.lang = RECOGNITION_LANG[locale] ?? 'en-US';\n\n const session = sessionRef.current;\n\n recognition.onresult = (event) => {\n if (session !== sessionRef.current) return;\n let finalText = '';\n let interimText = '';\n for (let index = event.resultIndex; index < event.results.length; index += 1) {\n const result = event.results[index];\n const alternative = result[0]?.transcript ?? '';\n if (result.isFinal) {\n finalText += alternative;\n } else {\n interimText += alternative;\n }\n }\n if (finalText.trim()) onFinalizeRef.current(finalText.trim());\n setInterim(interimText.trim());\n };\n\n recognition.onerror = (event) => {\n if (session !== sessionRef.current) return;\n const mapped = toVoiceInputError(event.error);\n // 'no-speech' fires routinely during a natural pause and the recogniser\n // keeps running — surfacing it would flash a scary message mid-sentence.\n if (mapped !== 'no-speech') setError(mapped);\n };\n\n recognition.onend = () => {\n if (session !== sessionRef.current) return;\n recognitionRef.current = null;\n setIsListening(false);\n setInterim('');\n };\n\n try {\n recognition.start();\n } catch {\n // start() throws if a recogniser is somehow already running — treat the\n // session as not started rather than leaving the button stuck \"live\".\n recognitionRef.current = null;\n setIsListening(false);\n return;\n }\n\n recognitionRef.current = recognition;\n setError(null);\n setInterim('');\n setIsListening(true);\n }, [locale]);\n\n const stop = useCallback(() => {\n // Detach BEFORE stopping. `onend` is what used to clear this ref, but it\n // arrives asynchronously — so a user who tapped stop and immediately tapped\n // the mic again hit `start()`'s `if (recognitionRef.current) return` guard\n // and got a silent no-op. Bumping the session also makes any trailing final\n // phrase the engine flushes on stop land on a dead session, instead of\n // reappearing in a draft the composer has already sent and cleared.\n const recognition = recognitionRef.current;\n recognitionRef.current = null;\n sessionRef.current += 1;\n recognition?.stop();\n setIsListening(false);\n setInterim('');\n }, []);\n\n const toggle = useCallback(() => {\n if (isListening) stop();\n else start();\n }, [isListening, start, stop]);\n\n const clearError = useCallback(() => setError(null), []);\n\n return { isSupported, isListening, interim, error, start, stop, toggle, clearError };\n}\n"],"mappings":";;;AAuDA,IAAM,IAA2C;CAC/C,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACL;AAED,SAAS,IAAuE;AAC9E,KAAI,OAAO,SAAW,IAAa,QAAO;CAC1C,IAAM,IAAM;AACZ,QACG,EAAI,qBACJ,EAAI,2BACL;;AAUJ,SAAS,EAAkB,GAA+B;AACxD,SAAQ,GAAR;EACE,KAAK;EACL,KAAK,sBACH,QAAO;EACT,KAAK,YACH,QAAO;EACT,KAAK,gBACH,QAAO;EACT,KAAK,UACH,QAAO;EACT,QACE,QAAO;;;AA0Bb,S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AGhB,MAAI;AACF,KAAY,OAAO;UACb;AAIN,GADA,EAAe,UAAU,MACzB,EAAe,GAAM;AACrB;;AAMF,EAHA,EAAe,UAAU,GACzB,EAAS,KAAK,EACd,EAAW,GAAG,EACd,EAAe,GAAK;IACnB,CAAC,EAAO,CAAC,EAEN,IAAO,QAAkB;EAO7B,IAAM,IAAc,EAAe;AAKnC,EAJA,EAAe,UAAU,MACzB,EAAW,WAAW,GACtB,GAAa,MAAM,EACnB,EAAe,GAAM,EACrB,EAAW,GAAG;IACb,EAAE,CAAC;AASN,QAAO;EAAE;EAAa;EAAa;EAAS;EAAO;EAAO;EAAM,QAPjD,QAAkB;AAC/B,GAAI,IAAa,GAAM,GAClB,GAAO;KACX;GAAC;GAAa;GAAO;GAAK,CAAC;EAI0C,YAFrD,QAAkB,EAAS,KAAK,EAAE,EAAE,CAAC;EAE4B"}
@@ -44,9 +44,12 @@ function o(e) {
44
44
  return e < 1024 ? `${e} B` : e < 1024 * 1024 ? `${(e / 1024).toFixed(1)} KB` : `${(e / (1024 * 1024)).toFixed(1)} MB`;
45
45
  }
46
46
  function s(e, t) {
47
- return t >= 5 ? "too-many" : e.size === 0 ? "empty" : e.size > 10485760 && !e.type.startsWith("image/") ? "too-large" : null;
47
+ return e > 0 || t.some((e) => e.status === "pending" || e.status === "uploading");
48
48
  }
49
49
  function c(e, t) {
50
+ return t >= 5 ? "too-many" : e.size === 0 ? "empty" : e.size > 10485760 && !e.type.startsWith("image/") ? "too-large" : null;
51
+ }
52
+ function l(e, t) {
50
53
  if (e.length <= t) return {
51
54
  text: e,
52
55
  truncated: !1
@@ -57,11 +60,11 @@ function c(e, t) {
57
60
  truncated: !0
58
61
  };
59
62
  }
60
- function l(e, t) {
63
+ function u(e, t) {
61
64
  let n = [`[${t + 1}] ${e.filename} — ${e.mimeType}, ${o(e.size)}`];
62
65
  return e.downloadUrl && n.push(` URL: ${e.downloadUrl}`), e.kind === "text" && e.textContent ? n.push(e.textTruncated ? ` Contents (first ${e.textContent.length} characters of ${o(e.size)}; truncated):` : " Contents:", " ```", ...e.textContent.split("\n").map((e) => ` ${e}`), " ```") : e.kind === "image" ? n.push(" If this image is attached to the message as an image you can view, answer from what you see in it.", " If you cannot view attached images, say so plainly and ask the user to describe it — never guess.") : e.kind === "text" ? n.push(" Text file — contents omitted because this turn ran out of inline budget, not because they are", " unavailable. Fetch the URL above if you can; otherwise ask the user which part matters so they", " can re-send just that section.") : n.push(" Binary file — contents not inlined. Fetch the URL above if you can; otherwise ask the user", " to paste the relevant section as text."), n.join("\n");
63
66
  }
64
- function u(e) {
67
+ function d(e) {
65
68
  let n = e.filter((e) => e.status === "ready");
66
69
  if (n.length === 0) return "";
67
70
  let r = t, i = n.map((e) => {
@@ -71,7 +74,7 @@ function u(e) {
71
74
  textContent: void 0,
72
75
  textTruncated: !0
73
76
  };
74
- let { text: t, truncated: n } = c(e.textContent, r);
77
+ let { text: t, truncated: n } = l(e.textContent, r);
75
78
  return r -= t.length, {
76
79
  ...e,
77
80
  textContent: t,
@@ -82,28 +85,28 @@ function u(e) {
82
85
  "",
83
86
  `--- Attachments (${n.length}) ---`,
84
87
  "The user attached the following file(s) to this message.",
85
- ...i.map(l),
88
+ ...i.map(u),
86
89
  "--- End attachments ---"
87
90
  ].join("\n");
88
91
  }
89
- function d(e, t) {
90
- let n = u(t);
92
+ function f(e, t) {
93
+ let n = d(t);
91
94
  return n ? e ? `${e}\n${n}` : n.trimStart() : e;
92
95
  }
93
- function f(e) {
96
+ function p(e) {
94
97
  let t = /^data:([a-z0-9.+/-]+);base64,(.*)$/i.exec(e);
95
98
  return t ? {
96
99
  mimeType: t[1],
97
100
  base64: t[2]
98
101
  } : null;
99
102
  }
100
- function p(e, t) {
103
+ function m(e, t) {
101
104
  let n = t.filter((e) => e.status === "ready");
102
105
  if (n.length === 0) return;
103
106
  let r = [], i = 0, a = 0;
104
107
  for (let e of n) {
105
108
  if (e.kind === "image") {
106
- let t = e.previewUrl ? f(e.previewUrl) : null;
109
+ let t = e.previewUrl ? p(e.previewUrl) : null;
107
110
  if (t !== null && i < 3 && a + t.base64.length <= 15e5 && t) {
108
111
  i += 1, a += t.base64.length, r.push({
109
112
  type: "image",
@@ -135,6 +138,6 @@ function p(e, t) {
135
138
  }, ...r];
136
139
  }
137
140
  //#endregion
138
- export { e as MAX_INLINE_CHARS_PER_FILE, p as buildPromptParts, d as buildPromptWithAttachments, a as classifyAttachment, o as formatBytes, n as toMessageAttachment, c as truncateForInline, s as validateFile };
141
+ export { e as MAX_INLINE_CHARS_PER_FILE, m as buildPromptParts, f as buildPromptWithAttachments, a as classifyAttachment, o as formatBytes, s as hasAttachmentWorkInFlight, n as toMessageAttachment, l as truncateForInline, c as validateFile };
139
142
 
140
143
  //# sourceMappingURL=assistantAttachments.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"assistantAttachments.js","names":[],"sources":["../../src/utils/assistantAttachments.ts"],"sourcesContent":["/**\n * Attachment model for the assistant composer (Workstream 3 of the AI Assistant\n * V2 multimodal effort) — pure logic, no React, so it is unit-testable.\n *\n * ## How an attachment reaches the model today\n *\n * The sandbox transport carries exactly one user-authored field per turn:\n * a `prompt` **string** (`POST /sessions/:id/prompt-async`). The in-sandbox\n * agent's message parts are `text | tool` only. So there is no native file or\n * image part to put bytes into, and adding one means changing the out-of-repo\n * `ai-assistant-*` bridge image — that is Workstream 4, and it is not shipped.\n *\n * What this module does instead is the honest L1: every attachment is uploaded\n * to the workspace file library (wspace-files-svc) so it durably exists and has\n * a URL, and a compact, clearly-delimited block describing the attachments is\n * appended to the outgoing prompt. For **text-like** files the actual content is\n * inlined (bounded), which makes them fully usable by the model right now. For\n * images and binaries only the metadata and a presigned URL go across, and the\n * block says plainly that the bytes were not inlined — so the assistant asks\n * rather than hallucinating a description of a photo it cannot see.\n *\n * Whether the sandbox can egress to the presigned URL is **not verified** — the\n * wording therefore makes fetching conditional (\"if you can fetch URLs\") rather\n * than promising it. Vision on the image itself lands with Workstream 4.\n */\n\n/** Hard cap on attachments per message — keeps the prompt block bounded. */\nexport const MAX_ATTACHMENTS = 5;\n\n/** Per-file ceiling before downscaling (images) / rejection (everything else). */\nexport const MAX_FILE_BYTES = 10 * 1024 * 1024;\n\n/** Per-file inline budget for text-like content, in characters. */\nexport const MAX_INLINE_CHARS_PER_FILE = 8_000;\n\n/** Total inline budget across all attachments in one turn. */\nexport const MAX_INLINE_CHARS_TOTAL = 20_000;\n\nexport type AssistantAttachmentKind = 'image' | 'text' | 'document';\n\nexport type AssistantAttachmentStatus = 'pending' | 'uploading' | 'ready' | 'error';\n\nexport interface AssistantAttachment {\n /** Client-side id; stable for the lifetime of the draft + the sent message. */\n id: string;\n filename: string;\n mimeType: string;\n /** Size of the bytes we actually kept (post-downscale for images). */\n size: number;\n kind: AssistantAttachmentKind;\n status: AssistantAttachmentStatus;\n /** Object/data URL for the composer thumbnail. Images only; never persisted. */\n previewUrl?: string;\n /** wspace-files-svc id, once the upload lands. */\n fileId?: string;\n /** Short-lived presigned URL, resolved at send time. */\n downloadUrl?: string;\n /** Extracted UTF-8 content for text-like files (already truncated). */\n textContent?: string;\n /** True when `textContent` is a prefix of a longer file. */\n textTruncated?: boolean;\n /** Human-readable failure reason when `status === 'error'`. */\n error?: string;\n}\n\n/**\n * The slice of an attachment that is safe to keep on a sent message.\n *\n * Conversations are persisted to (profile-scoped) localStorage by the assistant\n * store, so the heavy fields — the base64 `previewUrl` and the inlined\n * `textContent` — MUST NOT travel here: five 1280px JPEG data URLs would exhaust\n * the ~5 MB quota on their own and take the whole conversation history down with\n * them. The bubble re-resolves a thumbnail from `fileId` on demand instead, the\n * same way the pest-scan list does.\n */\nexport interface AssistantMessageAttachment {\n id: string;\n filename: string;\n mimeType: string;\n size: number;\n kind: AssistantAttachmentKind;\n fileId?: string;\n}\n\nexport function toMessageAttachment(attachment: AssistantAttachment): AssistantMessageAttachment {\n return {\n id: attachment.id,\n filename: attachment.filename,\n mimeType: attachment.mimeType,\n size: attachment.size,\n kind: attachment.kind,\n fileId: attachment.fileId,\n };\n}\n\n/**\n * Extensions we treat as text even when the browser reports a useless MIME type\n * (`application/octet-stream` is common for `.log`, `.yml`, `.env` on Windows).\n */\nconst TEXT_EXTENSIONS = new Set([\n 'txt',\n 'md',\n 'markdown',\n 'csv',\n 'tsv',\n 'json',\n 'yaml',\n 'yml',\n 'xml',\n 'log',\n 'sql',\n 'html',\n 'css',\n 'js',\n 'ts',\n 'tsx',\n 'jsx',\n 'py',\n 'sh',\n 'ini',\n 'toml',\n 'conf',\n]);\n\nexport function getExtension(filename: string): string {\n const dot = filename.lastIndexOf('.');\n return dot >= 0 ? filename.slice(dot + 1).toLowerCase() : '';\n}\n\nexport function classifyAttachment(mimeType: string, filename: string): AssistantAttachmentKind {\n if (mimeType.startsWith('image/')) return 'image';\n if (\n mimeType.startsWith('text/') ||\n mimeType === 'application/json' ||\n mimeType === 'application/xml' ||\n mimeType === 'application/x-yaml' ||\n TEXT_EXTENSIONS.has(getExtension(filename))\n ) {\n return 'text';\n }\n return 'document';\n}\n\nexport function formatBytes(bytes: number): string {\n if (bytes < 1024) return `${bytes} B`;\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;\n return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;\n}\n\nexport type AttachmentRejection = 'too-many' | 'too-large' | 'empty' | 'unreadable';\n\n/**\n * Gate a candidate file. Images over the ceiling are still accepted — the\n * composer downscales them before upload, so a 12 MB phone photo is fine while\n * a 12 MB PDF is not.\n */\nexport function validateFile(file: File, currentCount: number): AttachmentRejection | null {\n if (currentCount >= MAX_ATTACHMENTS) return 'too-many';\n if (file.size === 0) return 'empty';\n if (file.size > MAX_FILE_BYTES && !file.type.startsWith('image/')) return 'too-large';\n return null;\n}\n\n/**\n * Truncate on a line boundary where possible, so an inlined CSV/JSON prefix ends\n * at a row rather than mid-token (which reads as corrupt data to the model).\n */\nexport function truncateForInline(content: string, limit: number): { text: string; truncated: boolean } {\n if (content.length <= limit) return { text: content, truncated: false };\n const head = content.slice(0, limit);\n const lastNewline = head.lastIndexOf('\\n');\n return { text: lastNewline > limit * 0.5 ? head.slice(0, lastNewline) : head, truncated: true };\n}\n\nfunction describeAttachment(attachment: AssistantAttachment, index: number): string {\n const lines = [`[${index + 1}] ${attachment.filename} — ${attachment.mimeType}, ${formatBytes(attachment.size)}`];\n\n if (attachment.downloadUrl) {\n lines.push(` URL: ${attachment.downloadUrl}`);\n }\n\n if (attachment.kind === 'text' && attachment.textContent) {\n lines.push(\n attachment.textTruncated\n ? ` Contents (first ${attachment.textContent.length} characters of ${formatBytes(attachment.size)}; truncated):`\n : ' Contents:',\n ' ```',\n ...attachment.textContent.split('\\n').map((line) => ` ${line}`),\n ' ```'\n );\n } else if (attachment.kind === 'image') {\n // Deliberately regime-neutral wording. This same block is sent whether or\n // not the bridge understands `parts`, so it must not assert either that the\n // model CAN see the image (it would then invent a description on the old\n // bridge) or that it CANNOT (it would then refuse to look on the new one).\n lines.push(\n ' If this image is attached to the message as an image you can view, answer from what you see in it.',\n ' If you cannot view attached images, say so plainly and ask the user to describe it — never guess.'\n );\n } else if (attachment.kind === 'text') {\n // A text file with no `textContent` did not lose its type — it lost its slot\n // in the shared inline budget. Calling it \"binary\" here had the assistant ask\n // the farmer to paste text it already knew was text.\n lines.push(\n ' Text file — contents omitted because this turn ran out of inline budget, not because they are',\n ' unavailable. Fetch the URL above if you can; otherwise ask the user which part matters so they',\n ' can re-send just that section.'\n );\n } else {\n lines.push(\n ' Binary file — contents not inlined. Fetch the URL above if you can; otherwise ask the user',\n ' to paste the relevant section as text.'\n );\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Render the attachment block appended to the outgoing prompt. Returns '' when\n * there is nothing to say, so callers can concatenate unconditionally.\n *\n * Attachments that failed to upload are omitted: the user already sees the\n * failure in the composer, and a half-described file only confuses the model.\n */\nexport function buildAttachmentPromptBlock(attachments: AssistantAttachment[]): string {\n const usable = attachments.filter((attachment) => attachment.status === 'ready');\n if (usable.length === 0) return '';\n\n // Apply the shared inline budget in order, so the first files keep their\n // content and later ones degrade to metadata-only rather than every file\n // being trimmed to uselessness.\n let remaining = MAX_INLINE_CHARS_TOTAL;\n const budgeted = usable.map((attachment) => {\n if (attachment.kind !== 'text' || !attachment.textContent) return attachment;\n if (remaining <= 0) {\n return { ...attachment, textContent: undefined, textTruncated: true };\n }\n const { text, truncated } = truncateForInline(attachment.textContent, remaining);\n remaining -= text.length;\n return { ...attachment, textContent: text, textTruncated: attachment.textTruncated || truncated };\n });\n\n return [\n '',\n `--- Attachments (${usable.length}) ---`,\n 'The user attached the following file(s) to this message.',\n ...budgeted.map(describeAttachment),\n '--- End attachments ---',\n ].join('\\n');\n}\n\n/**\n * Compose the text actually sent to the agent: the user's words, then the\n * attachment block. The user-facing bubble keeps the raw text (attachments are\n * rendered as chips there), matching how `buildPromptForMode` already separates\n * agent-only preamble from displayed content.\n */\nexport function buildPromptWithAttachments(content: string, attachments: AssistantAttachment[]): string {\n const block = buildAttachmentPromptBlock(attachments);\n if (!block) return content;\n return content ? `${content}\\n${block}` : block.trimStart();\n}\n\n// ── Multimodal parts (Workstream 4, client half) ─────────────────────────────\n\n/**\n * Structural mirror of fe-libs' `AssistantPromptPart`\n * (`@burdenoff/fe-libs/shared/assistant`). Declared locally so this module —\n * and its tests — stay pure and importable without the transport, and so the\n * builder compiles against a fe-libs pin that predates the widening. The\n * assignment at the call site is what proves the two agree.\n */\nexport type AssistantPromptPart =\n | { type: 'text'; text: string }\n | { type: 'image'; mimeType: string; url?: string; data?: string; name?: string }\n | { type: 'file'; mimeType: string; url?: string; data?: string; name?: string };\n\n/**\n * How many images may travel INLINE in one turn, and the total base64 budget.\n *\n * Inline bytes are what make vision work without the sandbox needing egress to\n * our storage, but they ride inside a GraphQL variable through the public\n * gateway — so the turn has to stay a sane size. A 1280px JPEG at q0.72 is\n * typically 150-400 KB, i.e. 200-530 KB of base64; three of them sit\n * comfortably under the cap. Images beyond the budget still travel, by URL\n * only, and the prompt block still describes them.\n */\nexport const MAX_INLINE_IMAGE_PARTS = 3;\nexport const MAX_INLINE_IMAGE_BASE64_CHARS = 1_500_000;\n\n/** Split a `data:<mime>;base64,<payload>` URL. Returns null for anything else. */\nexport function parseDataUrl(dataUrl: string): { mimeType: string; base64: string } | null {\n const match = /^data:([a-z0-9.+/-]+);base64,(.*)$/i.exec(dataUrl);\n return match ? { mimeType: match[1], base64: match[2] } : null;\n}\n\n/**\n * Build the structured multimodal turn.\n *\n * `promptText` MUST be the exact string also sent as `prompt`, so the two\n * channels are equivalent: a bridge that understands `parts` sees everything a\n * text-only bridge sees, plus the images. Returns `undefined` when there is\n * nothing an image/file part could add, which keeps the wire body byte-identical\n * to a pre-multimodal client for every ordinary text turn.\n */\nexport function buildPromptParts(\n promptText: string,\n attachments: AssistantAttachment[]\n): AssistantPromptPart[] | undefined {\n const usable = attachments.filter((attachment) => attachment.status === 'ready');\n if (usable.length === 0) return undefined;\n\n const media: AssistantPromptPart[] = [];\n let inlined = 0;\n let inlineChars = 0;\n\n for (const attachment of usable) {\n if (attachment.kind === 'image') {\n const parsed = attachment.previewUrl ? parseDataUrl(attachment.previewUrl) : null;\n const withinBudget =\n parsed !== null &&\n inlined < MAX_INLINE_IMAGE_PARTS &&\n inlineChars + parsed.base64.length <= MAX_INLINE_IMAGE_BASE64_CHARS;\n\n if (withinBudget && parsed) {\n inlined += 1;\n inlineChars += parsed.base64.length;\n media.push({\n type: 'image',\n mimeType: parsed.mimeType,\n data: parsed.base64,\n // Sent alongside the bytes: a bridge that would rather fetch than\n // carry base64 through its own pipeline can, and the reference\n // outlives this turn.\n ...(attachment.downloadUrl ? { url: attachment.downloadUrl } : {}),\n name: attachment.filename,\n });\n continue;\n }\n\n if (attachment.downloadUrl) {\n media.push({\n type: 'image',\n mimeType: attachment.mimeType,\n url: attachment.downloadUrl,\n name: attachment.filename,\n });\n }\n continue;\n }\n\n // Documents are never inlined: a PDF is not an image, and making it useful\n // needs an extraction/retrieval step on the agent side. A reference is the\n // honest maximum from here. Text-like files already have their content in\n // the prompt block, so a missing URL costs nothing.\n if (attachment.downloadUrl) {\n media.push({\n type: 'file',\n mimeType: attachment.mimeType,\n url: attachment.downloadUrl,\n name: attachment.filename,\n });\n }\n }\n\n if (media.length === 0) return undefined;\n return [{ type: 'text', text: promptText }, ...media];\n}\n"],"mappings":"AAiCA,IAAa,IAA4B,KAG5B,IAAyB;AAgDtC,SAAgB,EAAoB,GAA6D;AAC/F,QAAO;EACL,IAAI,EAAW;EACf,UAAU,EAAW;EACrB,UAAU,EAAW;EACrB,MAAM,EAAW;EACjB,MAAM,EAAW;EACjB,QAAQ,EAAW;EACpB;;AAOH,IAAM,IAAkB,IAAI,IAAI;CAC9B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD,CAAC;AAEF,SAAgB,EAAa,GAA0B;CACrD,IAAM,IAAM,EAAS,YAAY,IAAI;AACrC,QAAO,KAAO,IAAI,EAAS,MAAM,IAAM,EAAE,CAAC,aAAa,GAAG;;AAG5D,SAAgB,EAAmB,GAAkB,GAA2C;AAW9F,QAVI,EAAS,WAAW,SAAS,GAAS,UAExC,EAAS,WAAW,QAAQ,IAC5B,MAAa,sBACb,MAAa,qBACb,MAAa,wBACb,EAAgB,IAAI,EAAa,EAAS,CAAC,GAEpC,SAEF;;AAGT,SAAgB,EAAY,GAAuB;AAGjD,QAFI,IAAQ,OAAa,GAAG,EAAM,MAC9B,IAAQ,OAAO,OAAa,IAAI,IAAQ,MAAM,QAAQ,EAAE,CAAC,OACtD,IAAI,KAAS,OAAO,OAAO,QAAQ,EAAE,CAAC;;AAU/C,SAAgB,EAAa,GAAY,GAAkD;AAIzF,QAHI,KAAA,IAAwC,aACxC,EAAK,SAAS,IAAU,UACxB,EAAK,OAAA,YAAyB,CAAC,EAAK,KAAK,WAAW,SAAS,GAAS,cACnE;;AAOT,SAAgB,EAAkB,GAAiB,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AO,CAAC;EAAE,MAAM;EAAQ,MAAM;EAAY,EAAE,GAAG,EAAM"}
1
+ {"version":3,"file":"assistantAttachments.js","names":[],"sources":["../../src/utils/assistantAttachments.ts"],"sourcesContent":["/**\n * Attachment model for the assistant composer (Workstream 3 of the AI Assistant\n * V2 multimodal effort) — pure logic, no React, so it is unit-testable.\n *\n * ## How an attachment reaches the model today\n *\n * The sandbox transport carries exactly one user-authored field per turn:\n * a `prompt` **string** (`POST /sessions/:id/prompt-async`). The in-sandbox\n * agent's message parts are `text | tool` only. So there is no native file or\n * image part to put bytes into, and adding one means changing the out-of-repo\n * `ai-assistant-*` bridge image — that is Workstream 4, and it is not shipped.\n *\n * What this module does instead is the honest L1: every attachment is uploaded\n * to the workspace file library (wspace-files-svc) so it durably exists and has\n * a URL, and a compact, clearly-delimited block describing the attachments is\n * appended to the outgoing prompt. For **text-like** files the actual content is\n * inlined (bounded), which makes them fully usable by the model right now. For\n * images and binaries only the metadata and a presigned URL go across, and the\n * block says plainly that the bytes were not inlined — so the assistant asks\n * rather than hallucinating a description of a photo it cannot see.\n *\n * Whether the sandbox can egress to the presigned URL is **not verified** — the\n * wording therefore makes fetching conditional (\"if you can fetch URLs\") rather\n * than promising it. Vision on the image itself lands with Workstream 4.\n */\n\n/** Hard cap on attachments per message — keeps the prompt block bounded. */\nexport const MAX_ATTACHMENTS = 5;\n\n/** Per-file ceiling before downscaling (images) / rejection (everything else). */\nexport const MAX_FILE_BYTES = 10 * 1024 * 1024;\n\n/** Per-file inline budget for text-like content, in characters. */\nexport const MAX_INLINE_CHARS_PER_FILE = 8_000;\n\n/** Total inline budget across all attachments in one turn. */\nexport const MAX_INLINE_CHARS_TOTAL = 20_000;\n\nexport type AssistantAttachmentKind = 'image' | 'text' | 'document';\n\nexport type AssistantAttachmentStatus = 'pending' | 'uploading' | 'ready' | 'error';\n\nexport interface AssistantAttachment {\n /** Client-side id; stable for the lifetime of the draft + the sent message. */\n id: string;\n filename: string;\n mimeType: string;\n /** Size of the bytes we actually kept (post-downscale for images). */\n size: number;\n kind: AssistantAttachmentKind;\n status: AssistantAttachmentStatus;\n /** Object/data URL for the composer thumbnail. Images only; never persisted. */\n previewUrl?: string;\n /** wspace-files-svc id, once the upload lands. */\n fileId?: string;\n /** Short-lived presigned URL, resolved at send time. */\n downloadUrl?: string;\n /** Extracted UTF-8 content for text-like files (already truncated). */\n textContent?: string;\n /** True when `textContent` is a prefix of a longer file. */\n textTruncated?: boolean;\n /** Human-readable failure reason when `status === 'error'`. */\n error?: string;\n}\n\n/**\n * The slice of an attachment that is safe to keep on a sent message.\n *\n * Conversations are persisted to (profile-scoped) localStorage by the assistant\n * store, so the heavy fields — the base64 `previewUrl` and the inlined\n * `textContent` — MUST NOT travel here: five 1280px JPEG data URLs would exhaust\n * the ~5 MB quota on their own and take the whole conversation history down with\n * them. The bubble re-resolves a thumbnail from `fileId` on demand instead, the\n * same way the pest-scan list does.\n */\nexport interface AssistantMessageAttachment {\n id: string;\n filename: string;\n mimeType: string;\n size: number;\n kind: AssistantAttachmentKind;\n fileId?: string;\n}\n\nexport function toMessageAttachment(attachment: AssistantAttachment): AssistantMessageAttachment {\n return {\n id: attachment.id,\n filename: attachment.filename,\n mimeType: attachment.mimeType,\n size: attachment.size,\n kind: attachment.kind,\n fileId: attachment.fileId,\n };\n}\n\n/**\n * Extensions we treat as text even when the browser reports a useless MIME type\n * (`application/octet-stream` is common for `.log`, `.yml`, `.env` on Windows).\n */\nconst TEXT_EXTENSIONS = new Set([\n 'txt',\n 'md',\n 'markdown',\n 'csv',\n 'tsv',\n 'json',\n 'yaml',\n 'yml',\n 'xml',\n 'log',\n 'sql',\n 'html',\n 'css',\n 'js',\n 'ts',\n 'tsx',\n 'jsx',\n 'py',\n 'sh',\n 'ini',\n 'toml',\n 'conf',\n]);\n\nexport function getExtension(filename: string): string {\n const dot = filename.lastIndexOf('.');\n return dot >= 0 ? filename.slice(dot + 1).toLowerCase() : '';\n}\n\nexport function classifyAttachment(mimeType: string, filename: string): AssistantAttachmentKind {\n if (mimeType.startsWith('image/')) return 'image';\n if (\n mimeType.startsWith('text/') ||\n mimeType === 'application/json' ||\n mimeType === 'application/xml' ||\n mimeType === 'application/x-yaml' ||\n TEXT_EXTENSIONS.has(getExtension(filename))\n ) {\n return 'text';\n }\n return 'document';\n}\n\nexport function formatBytes(bytes: number): string {\n if (bytes < 1024) return `${bytes} B`;\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;\n return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;\n}\n\n/**\n * Is there attachment work in flight that must block sending?\n *\n * `preparingCount` counts files the user has ALREADY dropped/picked but whose\n * image-downscale or text-read has not resolved yet. Those files have no id and\n * no row in `attachments`, so a check that looked only at `attachments` reported\n * \"idle\" during the whole preparation window — the composer stayed sendable, the\n * turn went out without the photo, and the photo then attached itself to the\n * user's NEXT message. Both halves must be counted.\n */\nexport function hasAttachmentWorkInFlight(preparingCount: number, attachments: AssistantAttachment[]): boolean {\n return (\n preparingCount > 0 ||\n attachments.some((attachment) => attachment.status === 'pending' || attachment.status === 'uploading')\n );\n}\n\nexport type AttachmentRejection = 'too-many' | 'too-large' | 'empty' | 'unreadable';\n\n/**\n * Gate a candidate file. Images over the ceiling are still accepted — the\n * composer downscales them before upload, so a 12 MB phone photo is fine while\n * a 12 MB PDF is not.\n */\nexport function validateFile(file: File, currentCount: number): AttachmentRejection | null {\n if (currentCount >= MAX_ATTACHMENTS) return 'too-many';\n if (file.size === 0) return 'empty';\n if (file.size > MAX_FILE_BYTES && !file.type.startsWith('image/')) return 'too-large';\n return null;\n}\n\n/**\n * Truncate on a line boundary where possible, so an inlined CSV/JSON prefix ends\n * at a row rather than mid-token (which reads as corrupt data to the model).\n */\nexport function truncateForInline(content: string, limit: number): { text: string; truncated: boolean } {\n if (content.length <= limit) return { text: content, truncated: false };\n const head = content.slice(0, limit);\n const lastNewline = head.lastIndexOf('\\n');\n return { text: lastNewline > limit * 0.5 ? head.slice(0, lastNewline) : head, truncated: true };\n}\n\nfunction describeAttachment(attachment: AssistantAttachment, index: number): string {\n const lines = [`[${index + 1}] ${attachment.filename} — ${attachment.mimeType}, ${formatBytes(attachment.size)}`];\n\n if (attachment.downloadUrl) {\n lines.push(` URL: ${attachment.downloadUrl}`);\n }\n\n if (attachment.kind === 'text' && attachment.textContent) {\n lines.push(\n attachment.textTruncated\n ? ` Contents (first ${attachment.textContent.length} characters of ${formatBytes(attachment.size)}; truncated):`\n : ' Contents:',\n ' ```',\n ...attachment.textContent.split('\\n').map((line) => ` ${line}`),\n ' ```'\n );\n } else if (attachment.kind === 'image') {\n // Deliberately regime-neutral wording. This same block is sent whether or\n // not the bridge understands `parts`, so it must not assert either that the\n // model CAN see the image (it would then invent a description on the old\n // bridge) or that it CANNOT (it would then refuse to look on the new one).\n lines.push(\n ' If this image is attached to the message as an image you can view, answer from what you see in it.',\n ' If you cannot view attached images, say so plainly and ask the user to describe it — never guess.'\n );\n } else if (attachment.kind === 'text') {\n // A text file with no `textContent` did not lose its type — it lost its slot\n // in the shared inline budget. Calling it \"binary\" here had the assistant ask\n // the farmer to paste text it already knew was text.\n lines.push(\n ' Text file — contents omitted because this turn ran out of inline budget, not because they are',\n ' unavailable. Fetch the URL above if you can; otherwise ask the user which part matters so they',\n ' can re-send just that section.'\n );\n } else {\n lines.push(\n ' Binary file — contents not inlined. Fetch the URL above if you can; otherwise ask the user',\n ' to paste the relevant section as text.'\n );\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Render the attachment block appended to the outgoing prompt. Returns '' when\n * there is nothing to say, so callers can concatenate unconditionally.\n *\n * Attachments that failed to upload are omitted: the user already sees the\n * failure in the composer, and a half-described file only confuses the model.\n */\nexport function buildAttachmentPromptBlock(attachments: AssistantAttachment[]): string {\n const usable = attachments.filter((attachment) => attachment.status === 'ready');\n if (usable.length === 0) return '';\n\n // Apply the shared inline budget in order, so the first files keep their\n // content and later ones degrade to metadata-only rather than every file\n // being trimmed to uselessness.\n let remaining = MAX_INLINE_CHARS_TOTAL;\n const budgeted = usable.map((attachment) => {\n if (attachment.kind !== 'text' || !attachment.textContent) return attachment;\n if (remaining <= 0) {\n return { ...attachment, textContent: undefined, textTruncated: true };\n }\n const { text, truncated } = truncateForInline(attachment.textContent, remaining);\n remaining -= text.length;\n return { ...attachment, textContent: text, textTruncated: attachment.textTruncated || truncated };\n });\n\n return [\n '',\n `--- Attachments (${usable.length}) ---`,\n 'The user attached the following file(s) to this message.',\n ...budgeted.map(describeAttachment),\n '--- End attachments ---',\n ].join('\\n');\n}\n\n/**\n * Compose the text actually sent to the agent: the user's words, then the\n * attachment block. The user-facing bubble keeps the raw text (attachments are\n * rendered as chips there), matching how `buildPromptForMode` already separates\n * agent-only preamble from displayed content.\n */\nexport function buildPromptWithAttachments(content: string, attachments: AssistantAttachment[]): string {\n const block = buildAttachmentPromptBlock(attachments);\n if (!block) return content;\n return content ? `${content}\\n${block}` : block.trimStart();\n}\n\n// ── Multimodal parts (Workstream 4, client half) ─────────────────────────────\n\n/**\n * Structural mirror of fe-libs' `AssistantPromptPart`\n * (`@burdenoff/fe-libs/shared/assistant`). Declared locally so this module —\n * and its tests — stay pure and importable without the transport, and so the\n * builder compiles against a fe-libs pin that predates the widening. The\n * assignment at the call site is what proves the two agree.\n */\nexport type AssistantPromptPart =\n | { type: 'text'; text: string }\n | { type: 'image'; mimeType: string; url?: string; data?: string; name?: string }\n | { type: 'file'; mimeType: string; url?: string; data?: string; name?: string };\n\n/**\n * How many images may travel INLINE in one turn, and the total base64 budget.\n *\n * Inline bytes are what make vision work without the sandbox needing egress to\n * our storage, but they ride inside a GraphQL variable through the public\n * gateway — so the turn has to stay a sane size. A 1280px JPEG at q0.72 is\n * typically 150-400 KB, i.e. 200-530 KB of base64; three of them sit\n * comfortably under the cap. Images beyond the budget still travel, by URL\n * only, and the prompt block still describes them.\n */\nexport const MAX_INLINE_IMAGE_PARTS = 3;\nexport const MAX_INLINE_IMAGE_BASE64_CHARS = 1_500_000;\n\n/** Split a `data:<mime>;base64,<payload>` URL. Returns null for anything else. */\nexport function parseDataUrl(dataUrl: string): { mimeType: string; base64: string } | null {\n const match = /^data:([a-z0-9.+/-]+);base64,(.*)$/i.exec(dataUrl);\n return match ? { mimeType: match[1], base64: match[2] } : null;\n}\n\n/**\n * Build the structured multimodal turn.\n *\n * `promptText` MUST be the exact string also sent as `prompt`, so the two\n * channels are equivalent: a bridge that understands `parts` sees everything a\n * text-only bridge sees, plus the images. Returns `undefined` when there is\n * nothing an image/file part could add, which keeps the wire body byte-identical\n * to a pre-multimodal client for every ordinary text turn.\n */\nexport function buildPromptParts(\n promptText: string,\n attachments: AssistantAttachment[]\n): AssistantPromptPart[] | undefined {\n const usable = attachments.filter((attachment) => attachment.status === 'ready');\n if (usable.length === 0) return undefined;\n\n const media: AssistantPromptPart[] = [];\n let inlined = 0;\n let inlineChars = 0;\n\n for (const attachment of usable) {\n if (attachment.kind === 'image') {\n const parsed = attachment.previewUrl ? parseDataUrl(attachment.previewUrl) : null;\n const withinBudget =\n parsed !== null &&\n inlined < MAX_INLINE_IMAGE_PARTS &&\n inlineChars + parsed.base64.length <= MAX_INLINE_IMAGE_BASE64_CHARS;\n\n if (withinBudget && parsed) {\n inlined += 1;\n inlineChars += parsed.base64.length;\n media.push({\n type: 'image',\n mimeType: parsed.mimeType,\n data: parsed.base64,\n // Sent alongside the bytes: a bridge that would rather fetch than\n // carry base64 through its own pipeline can, and the reference\n // outlives this turn.\n ...(attachment.downloadUrl ? { url: attachment.downloadUrl } : {}),\n name: attachment.filename,\n });\n continue;\n }\n\n if (attachment.downloadUrl) {\n media.push({\n type: 'image',\n mimeType: attachment.mimeType,\n url: attachment.downloadUrl,\n name: attachment.filename,\n });\n }\n continue;\n }\n\n // Documents are never inlined: a PDF is not an image, and making it useful\n // needs an extraction/retrieval step on the agent side. A reference is the\n // honest maximum from here. Text-like files already have their content in\n // the prompt block, so a missing URL costs nothing.\n if (attachment.downloadUrl) {\n media.push({\n type: 'file',\n mimeType: attachment.mimeType,\n url: attachment.downloadUrl,\n name: attachment.filename,\n });\n }\n }\n\n if (media.length === 0) return undefined;\n return [{ type: 'text', text: promptText }, ...media];\n}\n"],"mappings":"AAiCA,IAAa,IAA4B,KAG5B,IAAyB;AAgDtC,SAAgB,EAAoB,GAA6D;AAC/F,QAAO;EACL,IAAI,EAAW;EACf,UAAU,EAAW;EACrB,UAAU,EAAW;EACrB,MAAM,EAAW;EACjB,MAAM,EAAW;EACjB,QAAQ,EAAW;EACpB;;AAOH,IAAM,IAAkB,IAAI,IAAI;CAC9B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD,CAAC;AAEF,SAAgB,EAAa,GAA0B;CACrD,IAAM,IAAM,EAAS,YAAY,IAAI;AACrC,QAAO,KAAO,IAAI,EAAS,MAAM,IAAM,EAAE,CAAC,aAAa,GAAG;;AAG5D,SAAgB,EAAmB,GAAkB,GAA2C;AAW9F,QAVI,EAAS,WAAW,SAAS,GAAS,UAExC,EAAS,WAAW,QAAQ,IAC5B,MAAa,sBACb,MAAa,qBACb,MAAa,wBACb,EAAgB,IAAI,EAAa,EAAS,CAAC,GAEpC,SAEF;;AAGT,SAAgB,EAAY,GAAuB;AAGjD,QAFI,IAAQ,OAAa,GAAG,EAAM,MAC9B,IAAQ,OAAO,OAAa,IAAI,IAAQ,MAAM,QAAQ,EAAE,CAAC,OACtD,IAAI,KAAS,OAAO,OAAO,QAAQ,EAAE,CAAC;;AAa/C,SAAgB,EAA0B,GAAwB,GAA6C;AAC7G,QACE,IAAiB,KACjB,EAAY,MAAM,MAAe,EAAW,WAAW,aAAa,EAAW,WAAW,YAAY;;AAW1G,SAAgB,EAAa,GAAY,GAAkD;AAIzF,QAHI,KAAA,IAAwC,aACxC,EAAK,SAAS,IAAU,UACxB,EAAK,OAAA,YAAyB,CAAC,EAAK,KAAK,WAAW,SAAS,GAAS,cACn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AC;;AAIF,OAAM,WAAW,EACrB,QAAO,CAAC;EAAE,MAAM;EAAQ,MAAM;EAAY,EAAE,GAAG,EAAM"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@burdenoff/microfe-healthybowl",
3
- "version": "2026.725.6",
3
+ "version": "2026.725.7",
4
4
  "description": "Burdenoff HealthyBowl Microfrontend - Comprehensive organic farming and agro-foods management platform",
5
5
  "type": "module",
6
6
  "files": [