@burdenoff/microfe-healthybowl 2026.727.3 → 2026.729.1

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,37 +13,22 @@ import { useAssistantApiAccess as S } from "../../hooks/useAssistantApiAccess.js
13
13
  import { isQuotaExhaustedError as C } from "../../utils/quotaUtils.js";
14
14
  import { dispatchAssistantQuotaExhausted as w, notifyAiCreditsUpdated as ae } from "../../utils/aiCredits.js";
15
15
  import { buildPromptForMode as oe } from "../../utils/assistantPrompt.js";
16
- import { isMultimodalBodyRejection as se } from "../../utils/assistantTransportErrors.js";
17
- import { isTurnInFlight as T } from "../../utils/assistantTurnState.js";
18
- import { useCallback as E, useEffect as D, useMemo as ce, useRef as le, useState as ue } from "react";
19
- import { jsx as O, jsxs as de } from "react/jsx-runtime";
20
- import { useGatewayClient as fe } from "@burdenoff/fe-libs/shared/graphql";
21
- import { useAuthToken as pe } from "@burdenoff/fe-libs/shared/providers/shell";
16
+ import { isMultimodalBodyRejection as se, isRecoverableAssistantError as ce } from "../../utils/assistantTransportErrors.js";
17
+ import { isTurnInFlight as le } from "../../utils/assistantTurnState.js";
18
+ import { useCallback as T, useEffect as E, useMemo as ue, useRef as D, useState as de } from "react";
19
+ import { jsx as O, jsxs as fe } from "react/jsx-runtime";
20
+ import { useGatewayClient as pe } from "@burdenoff/fe-libs/shared/graphql";
21
+ import { useAuthToken as me } from "@burdenoff/fe-libs/shared/providers/shell";
22
22
  import { getAssistantMedia as k } from "@burdenoff/fe-libs/shared/assistant";
23
23
  //#region src/components/assistant/AssistantChatArea.tsx
24
- var me = {
24
+ var he = {
25
25
  general: 18e4,
26
26
  "api-calls": 18e4,
27
27
  "vibe-plugins": 6e5
28
- }, he = 18e4;
29
- function ge() {
28
+ }, ge = 18e4;
29
+ function _e() {
30
30
  return `${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;
31
31
  }
32
- function _e(e) {
33
- let t = e instanceof Error ? e.message.toLowerCase() : String(e).toLowerCase();
34
- return t.includes("rate limit exceeded") || t.includes("unauthorized") || t.includes("k8s api error 401") ? !1 : [
35
- "sandbox not found",
36
- "sandbox is not running",
37
- "sandbox service not available yet",
38
- "sandbox failed",
39
- "sandbox startup timed out",
40
- "assistant service did not become healthy",
41
- "proxy error: 404",
42
- "proxy error: 502",
43
- "proxy error: 503",
44
- "session mode mismatch"
45
- ].some((e) => t.includes(e));
46
- }
47
32
  function ve(e) {
48
33
  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]");
49
34
  }
@@ -85,8 +70,8 @@ function be(e) {
85
70
  }
86
71
  }
87
72
  var N = () => {
88
- let k = t(), j = fe("workspace"), { getAccessToken: M, getWorkspaceToken: N, userId: xe } = pe(), { conversations: Se, activeConversationId: P, mode: F, processingByConversationId: Ce, setMode: I, setConversationMode: L, setActiveConversation: we, createConversation: R, addMessage: z, updateMessage: B, patchMessage: V, setConversationProcessing: H, clearConversationProcessing: Te, setBackendSessionId: U, clearBackendSessionId: W, setSandbox: G, clearSandbox: Ee, acknowledgeApiCalls: De } = e(), K = Se.find((e) => e.id === P)?.messages ?? [], q = P ? Ce[P] : void 0, Oe = T(q?.status), ke = Oe ? q?.messageId ?? null : null, Ae = q?.status === "error" ? q.messageId : null, { canUseApiCalls: J, loading: je } = S(h()), Me = ce(() => y.filter((e) => !e.requiresAdmin || J), [J]), [Ne, Pe] = ue(null), Fe = le({}), Y = le(/* @__PURE__ */ new Set());
89
- D(() => {
73
+ let k = t(), j = pe("workspace"), { getAccessToken: M, getWorkspaceToken: N, userId: xe } = me(), { conversations: Se, activeConversationId: P, mode: F, processingByConversationId: Ce, setMode: I, setConversationMode: L, setActiveConversation: we, createConversation: R, addMessage: z, updateMessage: B, patchMessage: V, setConversationProcessing: H, clearConversationProcessing: Te, setBackendSessionId: U, clearBackendSessionId: W, setSandbox: G, clearSandbox: Ee, acknowledgeApiCalls: De } = e(), K = Se.find((e) => e.id === P)?.messages ?? [], q = P ? Ce[P] : void 0, Oe = le(q?.status), ke = Oe ? q?.messageId ?? null : null, Ae = q?.status === "error" ? q.messageId : null, { canUseApiCalls: J, loading: je } = S(h()), Me = ue(() => y.filter((e) => !e.requiresAdmin || J), [J]), [Y, Ne] = de(null), Pe = D({}), Fe = D(/* @__PURE__ */ new Set());
74
+ E(() => {
90
75
  if (je) return;
91
76
  let e = y.find((e) => e.id === F);
92
77
  (!e || e.requiresAdmin && !J) && F !== "general" && I("general");
@@ -96,9 +81,9 @@ var N = () => {
96
81
  je,
97
82
  I
98
83
  ]);
99
- let X = E((e, t, n, r) => {
84
+ let X = T((e, t, n, r) => {
100
85
  H(e, n, t, null), r ? B(e, t, r) : B(e, t, be(n));
101
- }, [H, B]), Ie = E(async (t, n, a, s, c) => {
86
+ }, [H, B]), Ie = T(async (t, n, a, s, c) => {
102
87
  let u = e.getState().sandboxesByMode[a]?.sandboxId ?? null, d = async (e) => {
103
88
  try {
104
89
  return await p(j, e, s, c, 3e5, (e) => X(t, n, "provisioning", e)), await f(j, e, s, c, 9e4, (e) => X(t, n, "connecting", e)), !0;
@@ -134,26 +119,26 @@ var N = () => {
134
119
  U,
135
120
  G,
136
121
  X
137
- ]), Z = E(async (t, r = []) => {
122
+ ]), Z = T(async (t, r = []) => {
138
123
  let i = e.getState(), o = i.activeConversationId ?? P;
139
- if (o && (T(i.processingByConversationId[o]?.status) || Y.current.has(o))) return;
124
+ if (o && (le(i.processingByConversationId[o]?.status) || Fe.current.has(o))) return;
140
125
  let l = i.mode, f = P, p = f ? e.getState().conversations.find((e) => e.id === f) : void 0;
141
126
  if (f ? p && p.mode !== l && (p.messages.length > 0 || p.backendSessionId) ? f = R(void 0, l) : p && p.mode !== l && L(f, l) : f = R(void 0, l), !f) return;
142
- Fe.current[f] = r;
127
+ Pe.current[f] = r;
143
128
  let _ = g(), v = {
144
129
  accessToken: M(),
145
130
  workspaceToken: N(),
146
131
  userId: xe,
147
132
  organizationId: h()
148
133
  }, y = {
149
- id: ge(),
134
+ id: _e(),
150
135
  role: "user",
151
136
  content: t,
152
137
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
153
138
  metadata: r.length ? { attachments: r.map(ie) } : void 0
154
139
  };
155
140
  z(f, y);
156
- let b = ge();
141
+ let b = _e();
157
142
  z(f, {
158
143
  id: b,
159
144
  role: "assistant",
@@ -192,17 +177,17 @@ var N = () => {
192
177
  if (!h || !se(t)) throw t;
193
178
  await d(j, e, _, n, p, l, y, v, void 0), i ||= ie;
194
179
  }
195
- let S = ye([], o), C = Date.now() + (me[l] ?? he), w = Date.now();
180
+ let S = ye([], o), C = Date.now() + (he[l] ?? ge), w = Date.now();
196
181
  for (; Date.now() < C && (S = ye(await c(j, e, _, n, v, 50), o), V(f, b, { content: ve(S.content) }), !S.done);) Date.now() - w > 3e4 && (await a(j, e, _, 600, v).catch(() => void 0), w = Date.now()), await new Promise((e) => setTimeout(e, 1500));
197
182
  if (!S.done && l !== "vibe-plugins") throw Error("Assistant response timed out while streaming progress");
198
- let T = l === "vibe-plugins" ? await s(j, e, _, n, v).catch(() => []) : void 0;
183
+ let ce = l === "vibe-plugins" ? await s(j, e, _, n, v).catch(() => []) : void 0;
199
184
  if (S.done || (S = {
200
185
  ...S,
201
186
  content: `${S.content}\n\n_Still building in the background — any artifacts below will finish shortly. Re-open this conversation to pick up the completed plugin._`
202
187
  }), i && (S = {
203
188
  ...S,
204
189
  content: `${S.content}\n\n${k("healthybowl.assistant.attachments.imagesNotSent", "_Your photo was too large to include with this message, so the answer above is from the text and the file link only. Try a smaller or more tightly cropped photo._")}`
205
- }), x(S.content, T, n, e), S.tokens) {
190
+ }), x(S.content, ce, n, e), S.tokens) {
206
191
  V(f, b, { tokens: S.tokens });
207
192
  try {
208
193
  await u(j, _, n, S.tokens, v), ae();
@@ -210,11 +195,11 @@ var N = () => {
210
195
  }
211
196
  H(f, "complete", b, null);
212
197
  } catch (t) {
213
- if (e === 1 && _e(t)) return W(f), Ee(l), S(2);
198
+ if (e === 1 && ce(t)) return W(f), Ee(l), S(2);
214
199
  throw t;
215
200
  }
216
- }, E = f;
217
- Y.current.add(E);
201
+ }, T = f;
202
+ Fe.current.add(T);
218
203
  try {
219
204
  if (!_) throw Error("Assistant backend is unavailable without an active workspace context.");
220
205
  await S();
@@ -226,7 +211,7 @@ var N = () => {
226
211
  let t = e instanceof Error ? e.message : "Something went wrong";
227
212
  H(f, "error", b, t), B(f, b, `Sorry, an error occurred: ${t}. Please try again.`);
228
213
  } finally {
229
- Y.current.delete(E);
214
+ Fe.current.delete(T);
230
215
  }
231
216
  }, [
232
217
  P,
@@ -247,19 +232,19 @@ var N = () => {
247
232
  X,
248
233
  B,
249
234
  xe
250
- ]), Le = E((e) => {
235
+ ]), Le = T((e) => {
251
236
  Z(e);
252
- }, [Z]), Re = E(() => {
253
- let e = [...K].reverse().find((e) => e.role === "user"), t = P ? Fe.current[P] ?? [] : [];
237
+ }, [Z]), Re = T(() => {
238
+ let e = [...K].reverse().find((e) => e.role === "user"), t = P ? Pe.current[P] ?? [] : [];
254
239
  e && Z(e.content, t);
255
240
  }, [
256
241
  K,
257
242
  Z,
258
243
  P
259
- ]), Q = le(Z);
260
- D(() => {
244
+ ]), Q = D(Z);
245
+ E(() => {
261
246
  Q.current = Z;
262
- }, [Z]), D(() => {
247
+ }, [Z]), E(() => {
263
248
  let t = e.getState().consumePendingPrompt();
264
249
  return t && Q.current(t), e.subscribe((t, n) => {
265
250
  if (t.pendingPrompt && t.pendingPrompt !== n.pendingPrompt) {
@@ -268,7 +253,7 @@ var N = () => {
268
253
  }
269
254
  });
270
255
  }, []);
271
- let $ = E((t) => {
256
+ let $ = T((t) => {
272
257
  let n = P ? e.getState().conversations.find((e) => e.id === P) : void 0;
273
258
  if (n && (n.messages.length > 0 || n.backendSessionId)) {
274
259
  if (n.mode !== t) {
@@ -283,23 +268,23 @@ var N = () => {
283
268
  we,
284
269
  L,
285
270
  I
286
- ]), ze = E((t) => {
271
+ ]), ze = T((t) => {
287
272
  if (y.find((e) => e.id === t)?.writeCapable && !e.getState().apiCallsAcknowledged) {
288
- Pe(t);
273
+ Ne(t);
289
274
  return;
290
275
  }
291
276
  $(t);
292
- }, [$]), Be = E(() => {
293
- let e = Ne;
294
- Pe(null), De(), e && $(e);
277
+ }, [$]), Be = T(() => {
278
+ let e = Y;
279
+ Ne(null), De(), e && $(e);
295
280
  }, [
296
- Ne,
281
+ Y,
297
282
  De,
298
283
  $
299
- ]), Ve = E(() => {
300
- Pe(null);
284
+ ]), Ve = T(() => {
285
+ Ne(null);
301
286
  }, []);
302
- return /* @__PURE__ */ de("div", {
287
+ return /* @__PURE__ */ fe("div", {
303
288
  className: "flex flex-1 flex-col overflow-hidden",
304
289
  children: [
305
290
  K.length === 0 ? /* @__PURE__ */ O(b, {
@@ -323,7 +308,7 @@ var N = () => {
323
308
  onModeChange: ze
324
309
  }),
325
310
  /* @__PURE__ */ O(v, {
326
- open: Ne !== null,
311
+ open: Y !== null,
327
312
  onConfirm: Be,
328
313
  onCancel: Ve
329
314
  })
@@ -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 { 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 countInlineImageCandidates,\n countInlinedImageParts,\n toMessageAttachment,\n type AssistantAttachment,\n} from '@/utils/assistantAttachments';\nimport { isMultimodalBodyRejection } from '@/utils/assistantTransportErrors';\nimport { isTurnInFlight } from '@/utils/assistantTurnState';\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 activeIsProcessing = isTurnInFlight(activeProcessing?.status);\n const activeStreamingMessageId = activeIsProcessing ? (activeProcessing?.messageId ?? null) : null;\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 // Conversations with a turn already dispatched. Synchronous, unlike the store\n // — see the re-entry guard in handleSend for why that matters.\n const inFlightSendsRef = useRef<Set<string>>(new Set());\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 //\n // The store is read LIVE, and that is what makes the guard work. The\n // render-captured `processingByConversationId` is stale by construction —\n // the click that starts a turn and the click that must be rejected can\n // belong to the same render. Reading `activeConversationId` live matters\n // for the same reason: on two racing first-ever sends, the second must see\n // the conversation the first one created a moment ago.\n //\n // Pairs with the synchronous `setConversationProcessing` below: because\n // the status is written before this function ever awaits, a second call —\n // however soon it arrives — always observes 'provisioning'.\n const storeAtEntry = useAssistantStore.getState();\n const guardConversationId = storeAtEntry.activeConversationId ?? activeConversationId;\n if (guardConversationId) {\n if (isTurnInFlight(storeAtEntry.processingByConversationId[guardConversationId]?.status)) return;\n // Second lock, in case a future change moves the status write later:\n // this one cannot be cleared by anything but the turn's own `finally`.\n // Deliberately per-conversation — a global key would keep blocking\n // after the conversation it belonged to was deleted mid-turn, and then\n // silently swallow every subsequent send.\n if (inFlightSendsRef.current.has(guardConversationId)) return;\n }\n\n const selectedMode = storeAtEntry.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 // Mark the turn in-flight in the STORE right now, synchronously.\n //\n // Until this line the first status write happened inside\n // `ensureAssistantRuntime`, i.e. one await later. During that window\n // `activeIsProcessing` was false and `failedMessageId` still pointed at\n // the PREVIOUS failure — so the composer stayed enabled and, worse, the\n // Retry button (which has no `disabled` of its own) stayed mounted and\n // clickable on top of a turn that had already started.\n //\n // Status only, deliberately no stage copy: `ensureAssistantRuntime` picks\n // the accurate wording a moment later (\"Reusing...\" vs \"Starting...\"), and\n // guessing here would flash the wrong one on every reused sandbox.\n setConversationProcessing(conversationId, 'provisioning', assistantMessageId, null);\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 // Set when this attempt had to re-send without the image bytes, so the\n // answer can say so rather than quietly reading as if the model looked.\n let imagesDropped = false;\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 // Structured multimodal parts carry the image PIXELS, which no amount\n // of prompt text can. Built from the same `promptText`, so a bridge\n // that ignores `parts` loses nothing; `undefined` for an ordinary text\n // turn keeps the wire body unchanged.\n const promptParts = buildPromptParts(promptText, attachments);\n const inlinedCount = countInlinedImageParts(promptParts);\n const carriesPixels = inlinedCount > 0;\n const pageContext = gatherPageContext();\n\n // `buildPromptParts` may have demoted a photo to a link to keep the\n // body under the gateway's cap — a long message can do that on prompt\n // text alone. That decision is invisible to the user unless we say so,\n // and an answer that reads as if the model looked at a photo it never\n // received is worse than a short note.\n imagesDropped = countInlineImageCandidates(attachments) > inlinedCount;\n\n try {\n await sendAssistantPromptAsync(\n apollo,\n sandboxId,\n workspaceId,\n sessionId,\n promptText,\n selectedMode,\n pageContext,\n authContext,\n promptParts\n );\n } catch (sendError) {\n // `buildPromptParts` already sizes the PARTS to the gateway's cap\n // (the prompt string itself is not bounded here), so reaching this\n // point means something rejected the body anyway — a tighter proxy\n // than we modelled, or a bridge that will not take `parts` at all.\n // Losing the whole question over that is the worst outcome\n // available: re-send it text-only. Only for errors that provably\n // never reached the agent (see isMultimodalBodyRejection) — a blind\n // retry would ask the same question twice and bill it twice.\n //\n // Gated on `parts` existing at all, NOT on it carrying pixels: the\n // array duplicates the whole prompt in `parts[0]`, so a url-only\n // parts array is itself enough to push a long message over the cap.\n // `carriesPixels` only decides whether the user is told something\n // was lost.\n if (!promptParts || !isMultimodalBodyRejection(sendError)) throw sendError;\n await sendAssistantPromptAsync(\n apollo,\n sandboxId,\n workspaceId,\n sessionId,\n promptText,\n selectedMode,\n pageContext,\n authContext,\n undefined\n );\n // Only claim a photo was lost if one actually was — a url-only\n // retry loses nothing the prompt block did not already carry.\n imagesDropped = imagesDropped || carriesPixels;\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 if (imagesDropped) {\n // Said plainly, because the alternative is an answer that looks like\n // it examined a photo it never received.\n result = {\n ...result,\n content: `${result.content}\\n\\n${tr(\n 'healthybowl.assistant.attachments.imagesNotSent',\n '_Your photo was too large to include with this message, so the answer above is from the text and the file link only. Try a smaller or more tightly cropped photo._'\n )}`,\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 // Claim the slot immediately before the first await, and release it in\n // `finally` so every exit — success, quota return, thrown error — frees\n // it. Registering here rather than earlier means a synchronous throw in\n // the setup above can never strand a key and wedge the conversation.\n const turnConversationId = conversationId;\n inFlightSendsRef.current.add(turnConversationId);\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 } finally {\n inFlightSendsRef.current.delete(turnConversationId);\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 setBackendSessionId,\n setConversationMode,\n setConversationProcessing,\n tr,\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":";;;;;;;;;;;;;;;;;;;;;;;AAkDA,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,GAAs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AAK,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,GAAD;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,OAAuB;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 countInlineImageCandidates,\n countInlinedImageParts,\n toMessageAttachment,\n type AssistantAttachment,\n} from '@/utils/assistantAttachments';\nimport { isMultimodalBodyRejection, isRecoverableAssistantError } from '@/utils/assistantTransportErrors';\nimport { isTurnInFlight } from '@/utils/assistantTurnState';\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 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 activeIsProcessing = isTurnInFlight(activeProcessing?.status);\n const activeStreamingMessageId = activeIsProcessing ? (activeProcessing?.messageId ?? null) : null;\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 // Conversations with a turn already dispatched. Synchronous, unlike the store\n // — see the re-entry guard in handleSend for why that matters.\n const inFlightSendsRef = useRef<Set<string>>(new Set());\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 //\n // The store is read LIVE, and that is what makes the guard work. The\n // render-captured `processingByConversationId` is stale by construction —\n // the click that starts a turn and the click that must be rejected can\n // belong to the same render. Reading `activeConversationId` live matters\n // for the same reason: on two racing first-ever sends, the second must see\n // the conversation the first one created a moment ago.\n //\n // Pairs with the synchronous `setConversationProcessing` below: because\n // the status is written before this function ever awaits, a second call —\n // however soon it arrives — always observes 'provisioning'.\n const storeAtEntry = useAssistantStore.getState();\n const guardConversationId = storeAtEntry.activeConversationId ?? activeConversationId;\n if (guardConversationId) {\n if (isTurnInFlight(storeAtEntry.processingByConversationId[guardConversationId]?.status)) return;\n // Second lock, in case a future change moves the status write later:\n // this one cannot be cleared by anything but the turn's own `finally`.\n // Deliberately per-conversation — a global key would keep blocking\n // after the conversation it belonged to was deleted mid-turn, and then\n // silently swallow every subsequent send.\n if (inFlightSendsRef.current.has(guardConversationId)) return;\n }\n\n const selectedMode = storeAtEntry.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 // Mark the turn in-flight in the STORE right now, synchronously.\n //\n // Until this line the first status write happened inside\n // `ensureAssistantRuntime`, i.e. one await later. During that window\n // `activeIsProcessing` was false and `failedMessageId` still pointed at\n // the PREVIOUS failure — so the composer stayed enabled and, worse, the\n // Retry button (which has no `disabled` of its own) stayed mounted and\n // clickable on top of a turn that had already started.\n //\n // Status only, deliberately no stage copy: `ensureAssistantRuntime` picks\n // the accurate wording a moment later (\"Reusing...\" vs \"Starting...\"), and\n // guessing here would flash the wrong one on every reused sandbox.\n setConversationProcessing(conversationId, 'provisioning', assistantMessageId, null);\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 // Set when this attempt had to re-send without the image bytes, so the\n // answer can say so rather than quietly reading as if the model looked.\n let imagesDropped = false;\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 // Structured multimodal parts carry the image PIXELS, which no amount\n // of prompt text can. Built from the same `promptText`, so a bridge\n // that ignores `parts` loses nothing; `undefined` for an ordinary text\n // turn keeps the wire body unchanged.\n const promptParts = buildPromptParts(promptText, attachments);\n const inlinedCount = countInlinedImageParts(promptParts);\n const carriesPixels = inlinedCount > 0;\n const pageContext = gatherPageContext();\n\n // `buildPromptParts` may have demoted a photo to a link to keep the\n // body under the gateway's cap — a long message can do that on prompt\n // text alone. That decision is invisible to the user unless we say so,\n // and an answer that reads as if the model looked at a photo it never\n // received is worse than a short note.\n imagesDropped = countInlineImageCandidates(attachments) > inlinedCount;\n\n try {\n await sendAssistantPromptAsync(\n apollo,\n sandboxId,\n workspaceId,\n sessionId,\n promptText,\n selectedMode,\n pageContext,\n authContext,\n promptParts\n );\n } catch (sendError) {\n // `buildPromptParts` already sizes the PARTS to the gateway's cap\n // (the prompt string itself is not bounded here), so reaching this\n // point means something rejected the body anyway — a tighter proxy\n // than we modelled, or a bridge that will not take `parts` at all.\n // Losing the whole question over that is the worst outcome\n // available: re-send it text-only. Only for errors that provably\n // never reached the agent (see isMultimodalBodyRejection) — a blind\n // retry would ask the same question twice and bill it twice.\n //\n // Gated on `parts` existing at all, NOT on it carrying pixels: the\n // array duplicates the whole prompt in `parts[0]`, so a url-only\n // parts array is itself enough to push a long message over the cap.\n // `carriesPixels` only decides whether the user is told something\n // was lost.\n if (!promptParts || !isMultimodalBodyRejection(sendError)) throw sendError;\n await sendAssistantPromptAsync(\n apollo,\n sandboxId,\n workspaceId,\n sessionId,\n promptText,\n selectedMode,\n pageContext,\n authContext,\n undefined\n );\n // Only claim a photo was lost if one actually was — a url-only\n // retry loses nothing the prompt block did not already carry.\n imagesDropped = imagesDropped || carriesPixels;\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 if (imagesDropped) {\n // Said plainly, because the alternative is an answer that looks like\n // it examined a photo it never received.\n result = {\n ...result,\n content: `${result.content}\\n\\n${tr(\n 'healthybowl.assistant.attachments.imagesNotSent',\n '_Your photo was too large to include with this message, so the answer above is from the text and the file link only. Try a smaller or more tightly cropped photo._'\n )}`,\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 // Claim the slot immediately before the first await, and release it in\n // `finally` so every exit — success, quota return, thrown error — frees\n // it. Registering here rather than earlier means a synchronous throw in\n // the setup above can never strand a key and wedge the conversation.\n const turnConversationId = conversationId;\n inFlightSendsRef.current.add(turnConversationId);\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 } finally {\n inFlightSendsRef.current.delete(turnConversationId);\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 setBackendSessionId,\n setConversationMode,\n setConversationProcessing,\n tr,\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":";;;;;;;;;;;;;;;;;;;;;;;AAkDA,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;;A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,GAAsB,KAAK,EAC3B,IAAqB,EACjB,KAAQ,EAAkB,EAAO;IACpC;EAAC;EAAoB;EAAqB;EAAkB,CAAC,EAE1D,KAAsB,QAAkB;AAC5C,KAAsB,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,GAAD;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"}
@@ -4,14 +4,15 @@ import { PageLayout as i } from "../components/PageLayout.js";
4
4
  import { StatusBadge as a } from "../components/StatusBadge.js";
5
5
  import { EmptyState as o } from "../components/EmptyState.js";
6
6
  import { ErrorState as s } from "../components/ErrorState.js";
7
- import { PageLoader as c } from "../components/PageLoader.js";
7
+ import { PageLoader as ee } from "../components/PageLoader.js";
8
8
  import "../components/index.js";
9
- import { useHealthyBowlData as l } from "../hooks/useHealthyBowlData.js";
9
+ import { useHealthyBowlData as c } from "../hooks/useHealthyBowlData.js";
10
+ import { hasWeatherObservation as l } from "../utils/weatherPresence.js";
10
11
  import { useCallback as u, useMemo as d } from "react";
11
- import { useI18n as f } from "@burdenoff/fe-libs/shared/providers/shell/I18nProvider";
12
- import { AlertTriangle as p, ArrowUpRight as m, BarChart3 as h, CalendarClock as ee, CheckCircle2 as g, ChevronRight as _, ClipboardList as te, Cloud as v, Droplets as y, Eye as b, MapPin as x, PawPrint as ne, Plus as S, ShieldCheck as C, Sprout as w, Thermometer as T, Wallet as E, Wind as re } from "lucide-react";
13
- import { useNavigate as D } from "react-router-dom";
14
- import { jsx as O, jsxs as k } from "react/jsx-runtime";
12
+ import { useI18n as te } from "@burdenoff/fe-libs/shared/providers/shell/I18nProvider";
13
+ import { AlertTriangle as f, ArrowUpRight as p, BarChart3 as ne, CalendarClock as m, CheckCircle2 as h, ChevronRight as g, ClipboardList as _, Cloud as v, CloudOff as y, Droplets as re, Eye as ie, MapPin as b, PawPrint as x, Plus as S, ShieldCheck as C, Sprout as w, Thermometer as T, Wallet as E, Wind as ae } from "lucide-react";
14
+ import { useNavigate as oe } from "react-router-dom";
15
+ import { Fragment as D, jsx as O, jsxs as k } from "react/jsx-runtime";
15
16
  import { EmphasisPanel as A, GlassCard as j } from "@burdenoff/fe-libs/ui";
16
17
  //#region src/healthybowl/pages/HomePage.tsx
17
18
  var M = {
@@ -64,7 +65,7 @@ var M = {
64
65
  }),
65
66
  /* @__PURE__ */ k("span", {
66
67
  className: "mt-auto inline-flex items-center gap-1 text-xs font-medium text-text-secondary transition-colors group-hover:text-text-primary",
67
- children: [o, /* @__PURE__ */ O(m, { className: "size-3.5" })]
68
+ children: [o, /* @__PURE__ */ O(p, { className: "size-3.5" })]
68
69
  })
69
70
  ]
70
71
  })
@@ -167,29 +168,20 @@ var M = {
167
168
  children: r
168
169
  }), /* @__PURE__ */ k("span", {
169
170
  className: "inline-flex shrink-0 items-center gap-0.5 font-medium transition-colors group-hover:text-text-primary",
170
- children: [i, /* @__PURE__ */ O(_, { className: "size-3.5" })]
171
+ children: [i, /* @__PURE__ */ O(g, { className: "size-3.5" })]
171
172
  })]
172
173
  })
173
174
  ]
174
175
  }) }), H = () => {
175
- let { dashboardStats: a, alerts: m, crops: _, weatherData: M, markAlertRead: N, farm: F, loadings: I, errors: L, refetch: H } = l(), U = D(), { t: W } = f(), G = u((e, t, n) => W(e, t, n), [W]), { buildPath: K } = r(), q = a, J = {
176
+ let { dashboardStats: a, alerts: p, crops: g, weatherData: M, markAlertRead: N, farm: F, loadings: I, errors: L, refetch: H } = c(), U = oe(), { t: W } = te(), G = u((e, t, n) => W(e, t, n), [W]), { buildPath: K } = r(), q = a, J = {
176
177
  location: M?.location ?? "",
177
- current: M?.current ?? {
178
- temperature: 0,
179
- condition: "N/A",
180
- feelsLike: 0,
181
- humidity: 0,
182
- windSpeed: 0,
183
- uvIndex: 0,
184
- pressure: 0,
185
- visibility: 0
186
- },
178
+ current: M?.current,
187
179
  forecast: M?.forecast ?? []
188
- }, Y = d(() => (/* @__PURE__ */ new Date()).toLocaleDateString(void 0, {
180
+ }, se = l(J.current), Y = d(() => (/* @__PURE__ */ new Date()).toLocaleDateString(void 0, {
189
181
  weekday: "long",
190
182
  day: "numeric",
191
183
  month: "long"
192
- }), []), X = d(() => [...m].sort((e, t) => P[e.severity] - P[t.severity]), [m]), ie = X.slice(0, 5), Z = m.length, ae = d(() => [..._].sort((e, t) => (e.daysToHarvest ?? 2 ** 53 - 1) - (t.daysToHarvest ?? 2 ** 53 - 1)), [_]).slice(0, 6), Q = d(() => q.totalRevenue === 0 ? null : Math.round(q.totalExpenses / q.totalRevenue * 100 * 10) / 10, [q.totalExpenses, q.totalRevenue]), oe = u((e) => {
184
+ }), []), X = d(() => [...p].sort((e, t) => P[e.severity] - P[t.severity]), [p]), ce = X.slice(0, 5), Z = p.length, le = d(() => [...g].sort((e, t) => (e.daysToHarvest ?? 2 ** 53 - 1) - (t.daysToHarvest ?? 2 ** 53 - 1)), [g]).slice(0, 6), Q = d(() => q.totalRevenue === 0 ? null : Math.round(q.totalExpenses / q.totalRevenue * 100 * 10) / 10, [q.totalExpenses, q.totalRevenue]), ue = u((e) => {
193
185
  let t = new Date(e).getTime();
194
186
  if (Number.isNaN(t)) return "";
195
187
  let n = Math.max(0, Math.floor((Date.now() - t) / 6e4));
@@ -199,9 +191,9 @@ var M = {
199
191
  if (r < 24) return G("healthybowl.home.time.hours", "{{n}}h ago", { n: r });
200
192
  let i = Math.floor(r / 24);
201
193
  return i < 7 ? G("healthybowl.home.time.days", "{{n}}d ago", { n: i }) : G("healthybowl.home.time.weeks", "{{n}}w ago", { n: Math.floor(i / 7) });
202
- }, [G]), se = u((e) => e === "critical" ? G("healthybowl.home.needsAttention.review", "Review") : e === "warning" ? G("healthybowl.home.needsAttention.open", "Open") : G("healthybowl.home.needsAttention.view", "View"), [G]), ce = u((e) => {
194
+ }, [G]), de = u((e) => e === "critical" ? G("healthybowl.home.needsAttention.review", "Review") : e === "warning" ? G("healthybowl.home.needsAttention.open", "Open") : G("healthybowl.home.needsAttention.view", "View"), [G]), fe = u((e) => {
203
195
  N(e.id, !0), e.actionUrl && U(e.actionUrl);
204
- }, [N, U]), le = q.netProfit > 0 ? "success" : q.netProfit < 0 ? "danger" : "neutral", ue = m.some((e) => e.severity === "critical"), de = m.some((e) => e.severity === "warning"), $ = Z === 0 ? "success" : ue ? "danger" : de ? "warning" : "neutral", fe = [
196
+ }, [N, U]), pe = q.netProfit > 0 ? "success" : q.netProfit < 0 ? "danger" : "neutral", me = p.some((e) => e.severity === "critical"), he = p.some((e) => e.severity === "warning"), $ = Z === 0 ? "success" : me ? "danger" : he ? "warning" : "neutral", ge = [
205
197
  {
206
198
  label: G("healthybowl.home.quickActions.addCrop.label", "Add crop"),
207
199
  icon: w,
@@ -209,12 +201,12 @@ var M = {
209
201
  },
210
202
  {
211
203
  label: G("healthybowl.home.quickActions.recordHarvest.label", "Record harvest"),
212
- icon: te,
204
+ icon: _,
213
205
  path: K("crops/harvest")
214
206
  },
215
207
  {
216
208
  label: G("healthybowl.home.quickActions.viewFields.label", "View fields"),
217
- icon: x,
209
+ icon: b,
218
210
  path: K("crops/fields")
219
211
  },
220
212
  {
@@ -224,10 +216,10 @@ var M = {
224
216
  },
225
217
  {
226
218
  label: G("healthybowl.home.quickActions.analytics.label", "Analytics"),
227
- icon: h,
219
+ icon: ne,
228
220
  path: K("analytics")
229
221
  }
230
- ], pe = Z === 0 ? G("healthybowl.home.header.allClear", "You're all caught up") : Z === 1 ? G("healthybowl.home.header.needsAttentionOne", "1 item needs your attention") : G("healthybowl.home.header.needsAttentionOther", "{{count}} items need your attention", { count: Z }), me = F?.name ? `${Y} · ${F.name}` : Y, he = /* @__PURE__ */ k("button", {
222
+ ], _e = Z === 0 ? G("healthybowl.home.header.allClear", "You're all caught up") : Z === 1 ? G("healthybowl.home.header.needsAttentionOne", "1 item needs your attention") : G("healthybowl.home.header.needsAttentionOther", "{{count}} items need your attention", { count: Z }), ve = F?.name ? `${Y} · ${F.name}` : Y, ye = /* @__PURE__ */ k("button", {
231
223
  type: "button",
232
224
  onClick: () => U(K("crops")),
233
225
  className: "inline-flex min-h-[40px] items-center gap-2 rounded-md bg-action-primary-bg px-4 py-2 text-sm font-medium text-action-primary-text transition-colors hover:bg-action-primary-bg/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border-focus focus-visible:ring-offset-2 focus-visible:ring-offset-bg-canvas",
@@ -235,14 +227,14 @@ var M = {
235
227
  });
236
228
  return /* @__PURE__ */ O(i, {
237
229
  title: G("healthybowl.home.title", "Farm Dashboard"),
238
- description: me,
239
- actions: he,
240
- children: I.dashboard ? /* @__PURE__ */ O(c, {}) : L.dashboard ? /* @__PURE__ */ O(s, { onRetry: H }) : /* @__PURE__ */ k("div", {
230
+ description: ve,
231
+ actions: ye,
232
+ children: I.dashboard ? /* @__PURE__ */ O(ee, {}) : L.dashboard ? /* @__PURE__ */ O(s, { onRetry: H }) : /* @__PURE__ */ k("div", {
241
233
  className: "space-y-6",
242
234
  children: [
243
235
  /* @__PURE__ */ k("div", {
244
236
  className: e("inline-flex items-center gap-1.5 rounded-full px-3 py-1 text-sm font-medium", Z === 0 ? "bg-status-success-bg text-status-success-text" : "bg-status-warning-bg text-status-warning-text"),
245
- children: [O(Z === 0 ? g : p, { className: "size-4" }), pe]
237
+ children: [O(Z === 0 ? h : f, { className: "size-4" }), _e]
246
238
  }),
247
239
  !F?.id && /* @__PURE__ */ k(A, {
248
240
  className: "flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",
@@ -261,7 +253,7 @@ var M = {
261
253
  }),
262
254
  /* @__PURE__ */ O("div", {
263
255
  className: "flex flex-wrap gap-2",
264
- children: fe.map(({ label: e, icon: t, path: n }) => /* @__PURE__ */ k("button", {
256
+ children: ge.map(({ label: e, icon: t, path: n }) => /* @__PURE__ */ k("button", {
265
257
  type: "button",
266
258
  onClick: () => U(n),
267
259
  className: "inline-flex min-h-[40px] items-center gap-2 rounded-full border border-border-subtle bg-bg-surface px-3.5 py-2 text-sm font-medium text-text-secondary transition-colors hover:border-border-default hover:bg-bg-sunken hover:text-text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border-focus focus-visible:ring-offset-2 focus-visible:ring-offset-bg-canvas",
@@ -283,7 +275,7 @@ var M = {
283
275
  /* @__PURE__ */ O(R, {
284
276
  label: G("healthybowl.home.kpi.harvestDue", "Harvest due"),
285
277
  value: String(q.harvestDue),
286
- icon: /* @__PURE__ */ O(ee, {}),
278
+ icon: /* @__PURE__ */ O(m, {}),
287
279
  drillLabel: G("healthybowl.home.kpi.viewHarvest", "View harvest"),
288
280
  onClick: () => U(K("crops/harvest"))
289
281
  }),
@@ -291,14 +283,14 @@ var M = {
291
283
  label: G("healthybowl.home.kpi.netProfit", "Net profit"),
292
284
  value: t(q.netProfit),
293
285
  icon: /* @__PURE__ */ O(E, {}),
294
- tone: le,
286
+ tone: pe,
295
287
  drillLabel: G("healthybowl.home.kpi.viewFinance", "View finances"),
296
288
  onClick: () => U(K("financial"))
297
289
  }),
298
290
  /* @__PURE__ */ O(R, {
299
291
  label: G("healthybowl.home.kpi.needsAttention", "Needs attention"),
300
292
  value: String(Z),
301
- icon: /* @__PURE__ */ O(p, {}),
293
+ icon: /* @__PURE__ */ O(f, {}),
302
294
  tone: $,
303
295
  glow: $ === "danger" || $ === "warning",
304
296
  drillLabel: G("healthybowl.home.kpi.viewAlerts", "View alerts"),
@@ -321,7 +313,7 @@ var M = {
321
313
  }), /* @__PURE__ */ O("div", {
322
314
  className: "flex-1 px-4 pb-4",
323
315
  children: X.length === 0 ? /* @__PURE__ */ O(o, {
324
- icon: /* @__PURE__ */ O(g, { className: "h-8 w-8 text-status-success-text" }),
316
+ icon: /* @__PURE__ */ O(h, { className: "h-8 w-8 text-status-success-text" }),
325
317
  title: G("healthybowl.home.needsAttention.empty.title", "You're all caught up"),
326
318
  description: G("healthybowl.home.needsAttention.empty.description", "No urgent farm alerts right now."),
327
319
  action: /* @__PURE__ */ O("button", {
@@ -332,11 +324,11 @@ var M = {
332
324
  })
333
325
  }) : /* @__PURE__ */ O("ul", {
334
326
  className: "divide-y divide-border-subtle",
335
- children: ie.map((e) => /* @__PURE__ */ O(B, {
327
+ children: ce.map((e) => /* @__PURE__ */ O(B, {
336
328
  alert: e,
337
- ctaLabel: se(e.severity),
338
- relTime: oe(e.timestamp),
339
- onOpen: () => ce(e)
329
+ ctaLabel: de(e.severity),
330
+ relTime: ue(e.timestamp),
331
+ onOpen: () => fe(e)
340
332
  }, e.id))
341
333
  })
342
334
  })]
@@ -359,9 +351,9 @@ var M = {
359
351
  children: G("healthybowl.home.cropsAnchor.title", "Crop overview")
360
352
  }), /* @__PURE__ */ O("p", {
361
353
  className: "text-xs text-text-secondary",
362
- children: _.length === 1 ? G("healthybowl.home.cropsAnchor.subtitleOne", "1 crop in progress") : G("healthybowl.home.cropsAnchor.subtitleOther", "{{count}} crops in progress", { count: _.length })
354
+ children: g.length === 1 ? G("healthybowl.home.cropsAnchor.subtitleOne", "1 crop in progress") : G("healthybowl.home.cropsAnchor.subtitleOther", "{{count}} crops in progress", { count: g.length })
363
355
  })] })]
364
- }), _.length > 0 && /* @__PURE__ */ O("button", {
356
+ }), g.length > 0 && /* @__PURE__ */ O("button", {
365
357
  type: "button",
366
358
  onClick: () => U(K("crops")),
367
359
  className: "text-xs font-medium text-text-secondary transition-colors hover:text-text-primary focus-visible:text-text-primary focus-visible:outline-none",
@@ -369,7 +361,7 @@ var M = {
369
361
  })]
370
362
  }), /* @__PURE__ */ O("div", {
371
363
  className: "flex-1 px-3 pb-3",
372
- children: _.length === 0 ? /* @__PURE__ */ O(o, {
364
+ children: g.length === 0 ? /* @__PURE__ */ O(o, {
373
365
  icon: /* @__PURE__ */ O(w, { className: "h-8 w-8 text-primary" }),
374
366
  title: G("healthybowl.home.cropsAnchor.empty.title", "No active crops"),
375
367
  description: G("healthybowl.home.cropsAnchor.empty.description", "Register your first crop to track growth, health and harvest here."),
@@ -381,7 +373,7 @@ var M = {
381
373
  })
382
374
  }) : /* @__PURE__ */ O("ul", {
383
375
  className: "divide-y divide-border-subtle",
384
- children: ae.map((e) => {
376
+ children: le.map((e) => {
385
377
  let t = (e.growthStage || e.status || "").replace(/_/g, " ").trim();
386
378
  return /* @__PURE__ */ O(V, {
387
379
  crop: e,
@@ -408,7 +400,7 @@ var M = {
408
400
  }), /* @__PURE__ */ k("div", {
409
401
  className: "flex flex-1 flex-col gap-4 px-4 pb-4",
410
402
  children: [
411
- /* @__PURE__ */ k("div", {
403
+ se ? /* @__PURE__ */ k(D, { children: [/* @__PURE__ */ k("div", {
412
404
  className: "flex items-center justify-between",
413
405
  children: [/* @__PURE__ */ k("div", { children: [
414
406
  /* @__PURE__ */ k("p", {
@@ -435,13 +427,12 @@ var M = {
435
427
  children: ["UV ", J.current.uvIndex]
436
428
  })]
437
429
  })]
438
- }),
439
- /* @__PURE__ */ k("div", {
430
+ }), /* @__PURE__ */ k("div", {
440
431
  className: "grid grid-cols-2 gap-3 border-t border-border-subtle pt-3",
441
432
  children: [
442
433
  /* @__PURE__ */ k("div", {
443
434
  className: "flex items-center gap-2 text-sm text-text-secondary",
444
- children: [/* @__PURE__ */ O(y, { className: "h-4 w-4" }), /* @__PURE__ */ k("span", { children: [
435
+ children: [/* @__PURE__ */ O(re, { className: "h-4 w-4" }), /* @__PURE__ */ k("span", { children: [
445
436
  J.current.humidity,
446
437
  "% ",
447
438
  G("healthybowl.home.weatherCard.humidity", "Humidity")
@@ -449,7 +440,7 @@ var M = {
449
440
  }),
450
441
  /* @__PURE__ */ k("div", {
451
442
  className: "flex items-center gap-2 text-sm text-text-secondary",
452
- children: [/* @__PURE__ */ O(re, { className: "h-4 w-4" }), /* @__PURE__ */ k("span", { children: [J.current.windSpeed, " km/h"] })]
443
+ children: [/* @__PURE__ */ O(ae, { className: "h-4 w-4" }), /* @__PURE__ */ k("span", { children: [J.current.windSpeed, " km/h"] })]
453
444
  }),
454
445
  /* @__PURE__ */ k("div", {
455
446
  className: "flex items-center gap-2 text-sm text-text-secondary",
@@ -457,9 +448,19 @@ var M = {
457
448
  }),
458
449
  /* @__PURE__ */ k("div", {
459
450
  className: "flex items-center gap-2 text-sm text-text-secondary",
460
- children: [/* @__PURE__ */ O(b, { className: "h-4 w-4" }), /* @__PURE__ */ k("span", { children: [J.current.visibility, " km"] })]
451
+ children: [/* @__PURE__ */ O(ie, { className: "h-4 w-4" }), /* @__PURE__ */ k("span", { children: [J.current.visibility, " km"] })]
461
452
  })
462
453
  ]
454
+ })] }) : /* @__PURE__ */ O(o, {
455
+ icon: /* @__PURE__ */ O(y, { className: "h-8 w-8 text-text-muted" }),
456
+ title: L.weather ? G("healthybowl.home.weatherCard.error.title", "Weather unavailable") : G("healthybowl.home.weatherCard.empty.title", "No weather yet"),
457
+ description: L.weather ? G("healthybowl.home.weatherCard.error.description", "We couldn't load conditions for your farm just now.") : G("healthybowl.home.weatherCard.empty.description", "Set your farm location to see local conditions here."),
458
+ action: /* @__PURE__ */ O("button", {
459
+ type: "button",
460
+ onClick: () => L.weather ? H() : U(K("farm")),
461
+ className: "inline-flex min-h-[40px] items-center gap-2 rounded-md border border-border-default px-4 py-2 text-sm font-medium text-text-primary transition-colors hover:bg-bg-elevated focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border-focus",
462
+ children: L.weather ? G("healthybowl.home.weatherCard.error.retry", "Try again") : G("healthybowl.home.weatherCard.empty.action", "Set farm location")
463
+ })
463
464
  }),
464
465
  J.forecast.length > 0 && /* @__PURE__ */ O("div", {
465
466
  className: "grid grid-cols-4 gap-2 border-t border-border-subtle pt-3",
@@ -505,14 +506,14 @@ var M = {
505
506
  label: G("healthybowl.home.glance.fields", "Fields"),
506
507
  value: String(q.totalFields),
507
508
  hint: q.totalFields > 0 ? G("healthybowl.home.glance.fieldsHint", "Monitored") : G("healthybowl.home.glance.fieldsEmpty", "No fields yet"),
508
- icon: /* @__PURE__ */ O(x, {}),
509
+ icon: /* @__PURE__ */ O(b, {}),
509
510
  onClick: () => U(K("crops/fields"))
510
511
  }),
511
512
  /* @__PURE__ */ O(z, {
512
513
  label: G("healthybowl.home.glance.livestock", "Livestock"),
513
514
  value: String(q.totalAnimals),
514
515
  hint: q.totalAnimals > 0 ? G("healthybowl.home.glance.livestockHint", "Under management") : G("healthybowl.home.glance.livestockEmpty", "No livestock added"),
515
- icon: /* @__PURE__ */ O(ne, {}),
516
+ icon: /* @__PURE__ */ O(x, {}),
516
517
  onClick: () => U(K("livestock"))
517
518
  }),
518
519
  /* @__PURE__ */ O(z, {
@@ -1 +1 @@
1
- {"version":3,"file":"HomePage.js","names":[],"sources":["../../../src/healthybowl/pages/HomePage.tsx"],"sourcesContent":["import { useMemo, useCallback, type FC, type ReactNode } from 'react';\nimport { useNavigate } from 'react-router-dom';\nimport { useI18n } from '@burdenoff/fe-libs/shared/providers/shell/I18nProvider';\nimport {\n Sprout,\n CalendarClock,\n Wallet,\n AlertTriangle,\n Plus,\n ClipboardList,\n BarChart3,\n MapPin,\n Thermometer,\n ArrowUpRight,\n ChevronRight,\n CheckCircle2,\n Cloud,\n Droplets,\n Wind,\n Eye,\n PawPrint,\n ShieldCheck,\n} from 'lucide-react';\nimport { EmphasisPanel, GlassCard } from '@burdenoff/fe-libs/ui';\nimport { PageLayout, StatusBadge, EmptyState, ErrorState, PageLoader } from '../components';\nimport { useHealthyBowlData } from '../hooks/useHealthyBowlData';\nimport { useBasePath } from '../hooks/useBasePath';\nimport { cn, formatCurrency, formatDateOnly } from '../utils/helpers';\nimport type { Alert, Crop } from '../types';\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Semantic maps — colour carries meaning, always paired with a label. Tokens only.\n// ─────────────────────────────────────────────────────────────────────────────\n\ntype Tone = 'neutral' | 'success' | 'warning' | 'danger';\n\nconst toneValueClass: Record<Tone, string> = {\n neutral: 'text-text-primary',\n success: 'text-status-success-text',\n warning: 'text-status-warning-text',\n danger: 'text-status-error-text',\n};\n\nconst toneChipClass: Record<Tone, string> = {\n neutral: 'bg-[var(--color-accent-soft)] text-text-primary',\n success: 'bg-status-success-bg text-status-success-text',\n warning: 'bg-status-warning-bg text-status-warning-text',\n danger: 'bg-status-error-bg text-status-error-text',\n};\n\nconst severityRank: Record<Alert['severity'], number> = { critical: 0, warning: 1, info: 2 };\n\nconst severityDotClass: Record<Alert['severity'], string> = {\n critical: 'bg-status-error-text',\n warning: 'bg-status-warning-text',\n info: 'bg-status-info-text',\n};\n\nconst healthVariant = (status: string) => {\n switch (status) {\n case 'excellent':\n return 'success' as const;\n case 'good':\n return 'info' as const;\n case 'fair':\n return 'warning' as const;\n default:\n return 'error' as const;\n }\n};\n\nconst clampPercent = (n: number) => Math.max(0, Math.min(100, Math.round(n)));\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Presentational sub-components (module-level so they don't remount each render)\n// ─────────────────────────────────────────────────────────────────────────────\n\ninterface KpiTileProps {\n label: string;\n value: string;\n icon: ReactNode;\n tone?: Tone;\n /** Featured accent glow — reserve for the single focal KPI (needs-attention). */\n glow?: boolean;\n drillLabel: string;\n onClick: () => void;\n}\n\n/** Primary KPI card — big real value + tone-coded chip + drill-down. No fabricated trend/sparkline. */\nconst KpiTile: FC<KpiTileProps> = ({ label, value, icon, tone = 'neutral', glow = false, drillLabel, onClick }) => (\n <button type=\"button\" onClick={onClick} className=\"group block text-left focus-visible:outline-none\">\n <GlassCard\n treatment=\"metric\"\n glow={glow}\n className=\"flex h-full flex-col gap-3 border-border-seam p-4 transition-shadow group-hover:shadow-pop group-focus-visible:ring-2 group-focus-visible:ring-border-focus group-focus-visible:ring-offset-2 group-focus-visible:ring-offset-bg-canvas\"\n >\n <div className=\"flex items-center justify-between\">\n <span className=\"text-sm font-medium text-text-secondary\">{label}</span>\n <span className={cn('flex size-8 items-center justify-center rounded-lg [&>svg]:size-4', toneChipClass[tone])}>\n {icon}\n </span>\n </div>\n <span className={cn('text-3xl font-semibold tabular-nums', toneValueClass[tone])}>{value}</span>\n <span className=\"mt-auto inline-flex items-center gap-1 text-xs font-medium text-text-secondary transition-colors group-hover:text-text-primary\">\n {drillLabel}\n <ArrowUpRight className=\"size-3.5\" />\n </span>\n </GlassCard>\n </button>\n);\n\ninterface MiniStatProps {\n label: string;\n value: string;\n hint?: string;\n icon: ReactNode;\n onClick: () => void;\n}\n\n/** Secondary \"at a glance\" tile — quieter than a KPI, honest zero-state hints. */\nconst MiniStat: FC<MiniStatProps> = ({ label, value, hint, icon, onClick }) => (\n <button type=\"button\" onClick={onClick} className=\"group block text-left focus-visible:outline-none\">\n <GlassCard className=\"flex h-full items-center justify-between gap-3 border-border-seam p-3 transition-shadow group-hover:shadow-pop group-focus-visible:ring-2 group-focus-visible:ring-border-focus group-focus-visible:ring-offset-2 group-focus-visible:ring-offset-bg-canvas\">\n <div className=\"min-w-0\">\n <p className=\"text-xs font-medium text-text-secondary\">{label}</p>\n <p className=\"mt-0.5 truncate text-lg font-semibold tabular-nums text-text-primary\">{value}</p>\n {hint && <p className=\"mt-0.5 truncate text-xs text-text-secondary\">{hint}</p>}\n </div>\n <span className=\"flex size-8 shrink-0 items-center justify-center rounded-lg bg-[var(--color-accent-soft)] text-text-secondary [&>svg]:size-4\">\n {icon}\n </span>\n </GlassCard>\n </button>\n);\n\ninterface AlertRowProps {\n alert: Alert;\n ctaLabel: string;\n relTime: string;\n onOpen: () => void;\n}\n\n/** One needs-attention row: severity dot + title + message + relative time + CTA. */\nconst AlertRow: FC<AlertRowProps> = ({ alert, ctaLabel, relTime, onOpen }) => (\n <li className=\"flex items-start gap-3 py-3\">\n <span className={cn('mt-1.5 size-2.5 shrink-0 rounded-full', severityDotClass[alert.severity])} aria-hidden />\n <div className=\"min-w-0 flex-1\">\n <div className=\"flex items-baseline justify-between gap-3\">\n <p className=\"truncate text-sm font-medium text-text-primary\">{alert.title}</p>\n <button\n type=\"button\"\n onClick={onOpen}\n className=\"shrink-0 text-xs font-medium text-action-primary-bg transition-colors hover:underline focus-visible:underline focus-visible:outline-none\"\n >\n {ctaLabel}\n </button>\n </div>\n <p className=\"mt-0.5 truncate text-xs text-text-secondary\">{alert.message}</p>\n <p className=\"mt-0.5 text-xs text-text-muted\">{relTime}</p>\n </div>\n </li>\n);\n\ninterface CropRowProps {\n crop: Crop;\n metaLabel: string;\n healthLabel: string;\n harvestLabel: string;\n openLabel: string;\n onOpen: () => void;\n}\n\n/** Rich crop row — name, field · stage, health, progress bar, expected harvest, open. */\nconst CropRow: FC<CropRowProps> = ({ crop, metaLabel, healthLabel, harvestLabel, openLabel, onOpen }) => (\n <li>\n <button\n type=\"button\"\n onClick={onOpen}\n className=\"group block w-full rounded-lg p-3 text-left transition-colors hover:bg-bg-sunken/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border-focus\"\n >\n <div className=\"flex items-center justify-between gap-2\">\n <div className=\"min-w-0\">\n <p className=\"truncate text-sm font-medium text-text-primary\">{crop.name}</p>\n <p className=\"truncate text-xs text-text-secondary\">{metaLabel}</p>\n </div>\n <StatusBadge label={healthLabel} variant={healthVariant(crop.healthStatus)} dot />\n </div>\n <div className=\"mt-2 flex items-center gap-3\">\n <div className=\"h-1.5 flex-1 overflow-hidden rounded-full bg-bg-sunken\">\n <div\n className=\"h-full rounded-full bg-action-primary-bg\"\n style={{ width: `${clampPercent(crop.progress)}%` }}\n />\n </div>\n <span className=\"w-9 shrink-0 text-right text-xs font-medium tabular-nums text-text-secondary\">\n {clampPercent(crop.progress)}%\n </span>\n </div>\n <div className=\"mt-1.5 flex items-center justify-between text-xs text-text-secondary\">\n <span className=\"truncate\">{harvestLabel}</span>\n <span className=\"inline-flex shrink-0 items-center gap-0.5 font-medium transition-colors group-hover:text-text-primary\">\n {openLabel}\n <ChevronRight className=\"size-3.5\" />\n </span>\n </div>\n </button>\n </li>\n);\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Dashboard\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport const HomePage: FC = () => {\n const { dashboardStats, alerts, crops, weatherData, markAlertRead, farm, loadings, errors, refetch } =\n useHealthyBowlData();\n\n const navigate = useNavigate();\n const { t: translate } = useI18n();\n // Local wrapper preserves the (key, fallback) call style used across HB pages\n // while forwarding interpolation params to the shared i18n `t` (for {{count}} etc.).\n const t = useCallback(\n (key: string, fallback: string, params?: Record<string, string | number>): string =>\n translate(key, fallback, params),\n [translate]\n );\n const { buildPath } = useBasePath();\n const stats = dashboardStats;\n\n const defaultCurrent = {\n temperature: 0,\n condition: 'N/A',\n feelsLike: 0,\n humidity: 0,\n windSpeed: 0,\n uvIndex: 0,\n pressure: 0,\n visibility: 0,\n };\n const weather = {\n location: weatherData?.location ?? '',\n current: weatherData?.current ?? defaultCurrent,\n forecast: weatherData?.forecast ?? [],\n };\n\n // Today's date, localised — \"Friday, 25 July\" style.\n const todayLabel = useMemo(\n () => new Date().toLocaleDateString(undefined, { weekday: 'long', day: 'numeric', month: 'long' }),\n []\n );\n\n // Alerts sorted by severity (critical → warning → info); capped for the panel.\n const sortedAlerts = useMemo(\n () => [...alerts].sort((a, b) => severityRank[a.severity] - severityRank[b.severity]),\n [alerts]\n );\n const visibleAlerts = sortedAlerts.slice(0, 5);\n const attentionCount = alerts.length;\n\n // Crops ordered by nearest harvest first; capped so the anchor stays scannable.\n const sortedCrops = useMemo(\n () =>\n [...crops].sort(\n (a, b) => (a.daysToHarvest ?? Number.MAX_SAFE_INTEGER) - (b.daysToHarvest ?? Number.MAX_SAFE_INTEGER)\n ),\n [crops]\n );\n const visibleCrops = sortedCrops.slice(0, 6);\n\n // Expenses as a share of revenue — honest ratio, null when there's no revenue to compare against.\n const expenseRatioPercent = useMemo(() => {\n if (stats.totalRevenue === 0) return null;\n return Math.round((stats.totalExpenses / stats.totalRevenue) * 100 * 10) / 10;\n }, [stats.totalExpenses, stats.totalRevenue]);\n\n // Compact relative-time (minutes/hours/days/weeks), i18n'd.\n const relTime = useCallback(\n (iso: string): string => {\n const then = new Date(iso).getTime();\n if (Number.isNaN(then)) return '';\n const diffMin = Math.max(0, Math.floor((Date.now() - then) / 60000));\n if (diffMin < 1) return t('healthybowl.home.time.now', 'just now');\n if (diffMin < 60) return t('healthybowl.home.time.minutes', '{{n}}m ago', { n: diffMin });\n const diffHr = Math.floor(diffMin / 60);\n if (diffHr < 24) return t('healthybowl.home.time.hours', '{{n}}h ago', { n: diffHr });\n const diffDay = Math.floor(diffHr / 24);\n if (diffDay < 7) return t('healthybowl.home.time.days', '{{n}}d ago', { n: diffDay });\n return t('healthybowl.home.time.weeks', '{{n}}w ago', { n: Math.floor(diffDay / 7) });\n },\n [t]\n );\n\n // Per-alert CTA label by severity — mirrors Review / Open / View in the design.\n const alertCta = useCallback(\n (severity: Alert['severity']): string => {\n if (severity === 'critical') return t('healthybowl.home.needsAttention.review', 'Review');\n if (severity === 'warning') return t('healthybowl.home.needsAttention.open', 'Open');\n return t('healthybowl.home.needsAttention.view', 'View');\n },\n [t]\n );\n\n const openAlert = useCallback(\n (alert: Alert) => {\n void markAlertRead(alert.id, true);\n if (alert.actionUrl) navigate(alert.actionUrl);\n },\n [markAlertRead, navigate]\n );\n\n // ── Real-field-backed KPI derivations ──\n const netProfitTone: Tone = stats.netProfit > 0 ? 'success' : stats.netProfit < 0 ? 'danger' : 'neutral';\n const hasCritical = alerts.some((a) => a.severity === 'critical');\n const hasWarning = alerts.some((a) => a.severity === 'warning');\n const attentionTone: Tone =\n attentionCount === 0 ? 'success' : hasCritical ? 'danger' : hasWarning ? 'warning' : 'neutral';\n\n const quickActions = [\n {\n label: t('healthybowl.home.quickActions.addCrop.label', 'Add crop'),\n icon: Sprout,\n path: buildPath('crops'),\n },\n {\n label: t('healthybowl.home.quickActions.recordHarvest.label', 'Record harvest'),\n icon: ClipboardList,\n path: buildPath('crops/harvest'),\n },\n {\n label: t('healthybowl.home.quickActions.viewFields.label', 'View fields'),\n icon: MapPin,\n path: buildPath('crops/fields'),\n },\n {\n label: t('healthybowl.home.quickActions.viewWeather.label', 'View weather'),\n icon: Thermometer,\n path: buildPath('weather'),\n },\n {\n label: t('healthybowl.home.quickActions.analytics.label', 'Analytics'),\n icon: BarChart3,\n path: buildPath('analytics'),\n },\n ];\n\n // Compact header subline: date · farm + a live needs-attention summary.\n const attentionSummary =\n attentionCount === 0\n ? t('healthybowl.home.header.allClear', \"You're all caught up\")\n : attentionCount === 1\n ? t('healthybowl.home.header.needsAttentionOne', '1 item needs your attention')\n : t('healthybowl.home.header.needsAttentionOther', '{{count}} items need your attention', {\n count: attentionCount,\n });\n\n // PageLayout's `description` is a plain string; the date + farm reads as the subline.\n const headerSubline = farm?.name ? `${todayLabel} · ${farm.name}` : todayLabel;\n\n const headerActions = (\n <button\n type=\"button\"\n onClick={() => navigate(buildPath('crops'))}\n className=\"inline-flex min-h-[40px] items-center gap-2 rounded-md bg-action-primary-bg px-4 py-2 text-sm font-medium text-action-primary-text transition-colors hover:bg-action-primary-bg/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border-focus focus-visible:ring-offset-2 focus-visible:ring-offset-bg-canvas\"\n >\n <Plus className=\"h-4 w-4\" />\n {t('healthybowl.home.primaryAction', 'Add')}\n </button>\n );\n\n return (\n <PageLayout\n title={t('healthybowl.home.title', 'Farm Dashboard')}\n description={headerSubline}\n actions={headerActions}\n >\n {loadings.dashboard ? (\n <PageLoader />\n ) : errors.dashboard ? (\n <ErrorState onRetry={refetch} />\n ) : (\n <div className=\"space-y-6\">\n {/* Live needs-attention summary — reads directly under the compact header */}\n <div\n className={cn(\n 'inline-flex items-center gap-1.5 rounded-full px-3 py-1 text-sm font-medium',\n attentionCount === 0\n ? 'bg-status-success-bg text-status-success-text'\n : 'bg-status-warning-bg text-status-warning-text'\n )}\n >\n {attentionCount === 0 ? <CheckCircle2 className=\"size-4\" /> : <AlertTriangle className=\"size-4\" />}\n {attentionSummary}\n </div>\n\n {/* First-run onboarding — only once data has settled and there's no farm yet */}\n {!farm?.id && (\n <EmphasisPanel className=\"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between\">\n <div>\n <p className=\"text-base font-semibold text-text-primary\">\n {t('healthybowl.home.onboarding.title', 'Welcome to HealthyBowl')}\n </p>\n <p className=\"text-sm text-text-secondary\">\n {t(\n 'healthybowl.home.onboarding.description',\n 'Set up your farm to start tracking crops, livestock, finances, and more.'\n )}\n </p>\n </div>\n <button\n type=\"button\"\n onClick={() => navigate(buildPath('getting-started'))}\n className=\"inline-flex min-h-[44px] items-center gap-2 self-start rounded-md bg-action-primary-bg px-4 py-2 text-sm font-medium text-action-primary-text transition-colors hover:bg-action-primary-bg/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border-focus focus-visible:ring-offset-2 focus-visible:ring-offset-bg-canvas sm:self-auto\"\n >\n <Plus className=\"h-4 w-4\" />\n {t('healthybowl.home.onboarding.action', 'Set up your farm')}\n </button>\n </EmphasisPanel>\n )}\n\n {/* Quick-action strip — compact row, existing wired targets */}\n <div className=\"flex flex-wrap gap-2\">\n {quickActions.map(({ label, icon: Icon, path }) => (\n <button\n key={label}\n type=\"button\"\n onClick={() => navigate(path)}\n className=\"inline-flex min-h-[40px] items-center gap-2 rounded-full border border-border-subtle bg-bg-surface px-3.5 py-2 text-sm font-medium text-text-secondary transition-colors hover:border-border-default hover:bg-bg-sunken hover:text-text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border-focus focus-visible:ring-offset-2 focus-visible:ring-offset-bg-canvas\"\n >\n <Icon className=\"size-4\" />\n {label}\n </button>\n ))}\n </div>\n\n {/* Primary row — 4 real-field KPIs + needs-attention panel above the fold */}\n <div className=\"grid grid-cols-1 gap-6 lg:grid-cols-3\">\n <div className=\"grid grid-cols-2 gap-4 lg:col-span-2\">\n <KpiTile\n label={t('healthybowl.home.kpi.activeCrops', 'Active crops')}\n value={String(stats.activeCrops)}\n icon={<Sprout />}\n drillLabel={t('healthybowl.home.kpi.viewCrops', 'View crops')}\n onClick={() => navigate(buildPath('crops'))}\n />\n <KpiTile\n label={t('healthybowl.home.kpi.harvestDue', 'Harvest due')}\n value={String(stats.harvestDue)}\n icon={<CalendarClock />}\n drillLabel={t('healthybowl.home.kpi.viewHarvest', 'View harvest')}\n onClick={() => navigate(buildPath('crops/harvest'))}\n />\n <KpiTile\n label={t('healthybowl.home.kpi.netProfit', 'Net profit')}\n value={formatCurrency(stats.netProfit)}\n icon={<Wallet />}\n tone={netProfitTone}\n drillLabel={t('healthybowl.home.kpi.viewFinance', 'View finances')}\n onClick={() => navigate(buildPath('financial'))}\n />\n <KpiTile\n label={t('healthybowl.home.kpi.needsAttention', 'Needs attention')}\n value={String(attentionCount)}\n icon={<AlertTriangle />}\n tone={attentionTone}\n glow={attentionTone === 'danger' || attentionTone === 'warning'}\n drillLabel={t('healthybowl.home.kpi.viewAlerts', 'View alerts')}\n onClick={() => navigate(buildPath('weather/alerts'))}\n />\n </div>\n\n {/* Needs attention */}\n <GlassCard className=\"flex h-full flex-col border-border-seam p-0\">\n <div className=\"flex items-center justify-between px-4 pb-1 pt-4\">\n <h3 className=\"text-sm font-semibold text-text-primary\">\n {t('healthybowl.home.needsAttention.title', 'Needs attention')}\n </h3>\n {sortedAlerts.length > 0 && (\n <button\n type=\"button\"\n onClick={() => navigate(buildPath('weather/alerts'))}\n className=\"text-xs font-medium text-text-secondary transition-colors hover:text-text-primary focus-visible:text-text-primary focus-visible:outline-none\"\n >\n {t('healthybowl.home.needsAttention.viewAll', 'View all')}\n </button>\n )}\n </div>\n <div className=\"flex-1 px-4 pb-4\">\n {sortedAlerts.length === 0 ? (\n <EmptyState\n icon={<CheckCircle2 className=\"h-8 w-8 text-status-success-text\" />}\n title={t('healthybowl.home.needsAttention.empty.title', \"You're all caught up\")}\n description={t(\n 'healthybowl.home.needsAttention.empty.description',\n 'No urgent farm alerts right now.'\n )}\n action={\n <button\n type=\"button\"\n onClick={() => navigate(buildPath('weather/alert-rules'))}\n className=\"inline-flex min-h-[40px] items-center gap-2 rounded-md border border-border-subtle px-3 py-2 text-sm font-medium text-text-primary transition-colors hover:bg-bg-sunken focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border-focus\"\n >\n {t('healthybowl.home.needsAttention.empty.action', 'Manage alert rules')}\n </button>\n }\n />\n ) : (\n <ul className=\"divide-y divide-border-subtle\">\n {visibleAlerts.map((alert) => (\n <AlertRow\n key={alert.id}\n alert={alert}\n ctaLabel={alertCta(alert.severity)}\n relTime={relTime(alert.timestamp)}\n onOpen={() => openAlert(alert)}\n />\n ))}\n </ul>\n )}\n </div>\n </GlassCard>\n </div>\n\n {/* Anchor row — crop overview (strongest) + compact weather */}\n <div className=\"grid grid-cols-1 gap-6 lg:grid-cols-3\">\n {/* Crop overview — the farm-specific anchor */}\n <GlassCard glow className=\"flex h-full flex-col border-border-seam p-0 lg:col-span-2\">\n <div className=\"flex items-center justify-between px-5 pb-2 pt-5\">\n <div className=\"flex items-center gap-2\">\n <span className=\"flex size-8 items-center justify-center rounded-lg bg-[var(--color-accent-soft)] text-primary [&>svg]:size-4\">\n <Sprout />\n </span>\n <div>\n <h2 className=\"text-base font-semibold text-text-primary\">\n {t('healthybowl.home.cropsAnchor.title', 'Crop overview')}\n </h2>\n <p className=\"text-xs text-text-secondary\">\n {crops.length === 1\n ? t('healthybowl.home.cropsAnchor.subtitleOne', '1 crop in progress')\n : t('healthybowl.home.cropsAnchor.subtitleOther', '{{count}} crops in progress', {\n count: crops.length,\n })}\n </p>\n </div>\n </div>\n {crops.length > 0 && (\n <button\n type=\"button\"\n onClick={() => navigate(buildPath('crops'))}\n className=\"text-xs font-medium text-text-secondary transition-colors hover:text-text-primary focus-visible:text-text-primary focus-visible:outline-none\"\n >\n {t('healthybowl.home.cropsAnchor.viewAll', 'View all crops')}\n </button>\n )}\n </div>\n <div className=\"flex-1 px-3 pb-3\">\n {crops.length === 0 ? (\n <EmptyState\n icon={<Sprout className=\"h-8 w-8 text-primary\" />}\n title={t('healthybowl.home.cropsAnchor.empty.title', 'No active crops')}\n description={t(\n 'healthybowl.home.cropsAnchor.empty.description',\n 'Register your first crop to track growth, health and harvest here.'\n )}\n action={\n <button\n type=\"button\"\n onClick={() => navigate(buildPath('crops'))}\n className=\"inline-flex min-h-[40px] items-center gap-2 rounded-md bg-action-primary-bg px-4 py-2 text-sm font-medium text-action-primary-text transition-colors hover:bg-action-primary-bg/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border-focus\"\n >\n <Plus className=\"h-4 w-4\" />\n {t('healthybowl.home.quickActions.addCrop.label', 'Add crop')}\n </button>\n }\n />\n ) : (\n <ul className=\"divide-y divide-border-subtle\">\n {visibleCrops.map((crop) => {\n const stage = (crop.growthStage || crop.status || '').replace(/_/g, ' ').trim();\n const metaLabel = [crop.fieldName, stage].filter(Boolean).join(' · ');\n return (\n <CropRow\n key={crop.id}\n crop={crop}\n metaLabel={metaLabel || t('healthybowl.home.cropsAnchor.noField', 'Unassigned')}\n healthLabel={(crop.healthStatus || 'unknown').replace(/_/g, ' ')}\n harvestLabel={\n crop.expectedHarvestDate\n ? t('healthybowl.home.cropsAnchor.harvest', 'Harvest {{date}}', {\n date: formatDateOnly(crop.expectedHarvestDate),\n })\n : t('healthybowl.home.cropsAnchor.harvestUnknown', 'Harvest date TBD')\n }\n openLabel={t('healthybowl.home.cropsAnchor.open', 'Open')}\n onOpen={() => navigate(buildPath(`crops/${crop.id}`))}\n />\n );\n })}\n </ul>\n )}\n </div>\n </GlassCard>\n\n {/* Weather — secondary */}\n <GlassCard className=\"flex h-full flex-col border-border-seam p-0\">\n <div className=\"px-4 pb-1 pt-4\">\n <h3 className=\"text-sm font-semibold text-text-primary\">\n {t('healthybowl.home.weatherCard.title', 'Current weather')}\n </h3>\n {weather.location && <p className=\"text-xs text-text-secondary\">{weather.location}</p>}\n </div>\n <div className=\"flex flex-1 flex-col gap-4 px-4 pb-4\">\n <div className=\"flex items-center justify-between\">\n <div>\n <p className=\"text-4xl font-bold text-text-primary\">{weather.current.temperature}&deg;C</p>\n <p className=\"text-sm text-text-secondary\">{weather.current.condition}</p>\n <p className=\"mt-1 text-xs text-text-secondary\">\n {t('healthybowl.home.weatherCard.feelsLike', 'Feels like')} {weather.current.feelsLike}&deg;C\n </p>\n </div>\n <div className=\"flex flex-col items-center\">\n <Cloud className=\"h-12 w-12 text-text-secondary\" />\n <span className=\"mt-1 text-xs text-text-secondary\">UV {weather.current.uvIndex}</span>\n </div>\n </div>\n\n <div className=\"grid grid-cols-2 gap-3 border-t border-border-subtle pt-3\">\n <div className=\"flex items-center gap-2 text-sm text-text-secondary\">\n <Droplets className=\"h-4 w-4\" />\n <span>\n {weather.current.humidity}% {t('healthybowl.home.weatherCard.humidity', 'Humidity')}\n </span>\n </div>\n <div className=\"flex items-center gap-2 text-sm text-text-secondary\">\n <Wind className=\"h-4 w-4\" />\n <span>{weather.current.windSpeed} km/h</span>\n </div>\n <div className=\"flex items-center gap-2 text-sm text-text-secondary\">\n <Thermometer className=\"h-4 w-4\" />\n <span>{weather.current.pressure} hPa</span>\n </div>\n <div className=\"flex items-center gap-2 text-sm text-text-secondary\">\n <Eye className=\"h-4 w-4\" />\n <span>{weather.current.visibility} km</span>\n </div>\n </div>\n\n {weather.forecast.length > 0 && (\n <div className=\"grid grid-cols-4 gap-2 border-t border-border-subtle pt-3\">\n {weather.forecast.slice(0, 4).map((day) => (\n <div key={day.date} className=\"rounded-md bg-bg-sunken/50 p-2 text-center\">\n <p className=\"text-xs font-medium text-text-secondary\">\n {new Date(day.date).toLocaleDateString('en-US', { weekday: 'short' })}\n </p>\n <p className=\"mt-1 text-sm font-semibold text-text-primary\">{day.high}&deg;</p>\n <p className=\"text-xs text-text-secondary\">{day.low}&deg;</p>\n <p className=\"mt-0.5 text-xs text-text-secondary\">{day.precipitation}%</p>\n </div>\n ))}\n </div>\n )}\n\n <button\n type=\"button\"\n onClick={() => navigate(buildPath('weather'))}\n className=\"mt-auto w-full rounded-md border border-border-subtle py-2 text-sm text-text-primary transition-colors hover:bg-bg-sunken/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border-focus\"\n >\n {t('healthybowl.home.weatherCard.viewForecast', 'View full forecast')}\n </button>\n </div>\n </GlassCard>\n </div>\n\n {/* At a glance — demoted secondary metrics with honest zero-states */}\n <section>\n <h3 className=\"mb-2 text-xs font-medium uppercase tracking-wide text-text-secondary\">\n {t('healthybowl.home.glance.title', 'At a glance')}\n </h3>\n <div className=\"grid grid-cols-2 gap-3 sm:grid-cols-4\">\n <MiniStat\n label={t('healthybowl.home.glance.fields', 'Fields')}\n value={String(stats.totalFields)}\n hint={\n stats.totalFields > 0\n ? t('healthybowl.home.glance.fieldsHint', 'Monitored')\n : t('healthybowl.home.glance.fieldsEmpty', 'No fields yet')\n }\n icon={<MapPin />}\n onClick={() => navigate(buildPath('crops/fields'))}\n />\n <MiniStat\n label={t('healthybowl.home.glance.livestock', 'Livestock')}\n value={String(stats.totalAnimals)}\n hint={\n stats.totalAnimals > 0\n ? t('healthybowl.home.glance.livestockHint', 'Under management')\n : t('healthybowl.home.glance.livestockEmpty', 'No livestock added')\n }\n icon={<PawPrint />}\n onClick={() => navigate(buildPath('livestock'))}\n />\n <MiniStat\n label={t('healthybowl.home.glance.organic', 'Organic score')}\n value={\n stats.organicScore > 0\n ? `${stats.organicScore}%`\n : t('healthybowl.home.glance.organicEmpty', 'Not configured')\n }\n hint={stats.organicScore > 0 ? t('healthybowl.home.glance.organicHint', 'Compliance') : undefined}\n icon={<ShieldCheck />}\n onClick={() => navigate(buildPath('compliance'))}\n />\n <MiniStat\n label={t('healthybowl.home.glance.expenses', 'Expenses')}\n value={formatCurrency(stats.totalExpenses)}\n hint={\n expenseRatioPercent != null\n ? t('healthybowl.home.glance.expensesRatio', '{{pct}}% of revenue', { pct: expenseRatioPercent })\n : t('healthybowl.home.glance.noRevenue', 'No revenue yet')\n }\n icon={<Wallet />}\n onClick={() => navigate(buildPath('financial'))}\n />\n </div>\n </section>\n </div>\n )}\n </PageLayout>\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;AAoCA,IAAM,IAAuC;CAC3C,SAAS;CACT,SAAS;CACT,SAAS;CACT,QAAQ;CACT,EAEK,IAAsC;CAC1C,SAAS;CACT,SAAS;CACT,SAAS;CACT,QAAQ;CACT,EAEK,IAAkD;CAAE,UAAU;CAAG,SAAS;CAAG,MAAM;CAAG,EAEtF,IAAsD;CAC1D,UAAU;CACV,SAAS;CACT,MAAM;CACP,EAEK,KAAiB,MAAmB;AACxC,SAAQ,GAAR;EACE,KAAK,YACH,QAAO;EACT,KAAK,OACH,QAAO;EACT,KAAK,OACH,QAAO;EACT,QACE,QAAO;;GAIP,KAAgB,MAAc,KAAK,IAAI,GAAG,KAAK,IAAI,KAAK,KAAK,MAAM,EAAE,CAAC,CAAC,EAkBvE,KAA6B,EAAE,UAAO,UAAO,SAAM,UAAO,WAAW,UAAO,IAAO,eAAY,iBACnG,kBAAC,UAAD;CAAQ,MAAK;CAAkB;CAAS,WAAU;WAChD,kBAAC,GAAD;EACE,WAAU;EACJ;EACN,WAAU;YAHZ;GAKE,kBAAC,OAAD;IAAK,WAAU;cAAf,CACE,kBAAC,QAAD;KAAM,WAAU;eAA2C;KAAa,CAAA,EACxE,kBAAC,QAAD;KAAM,WAAW,EAAG,qEAAqE,EAAc,GAAM;eAC1G;KACI,CAAA,CACH;;GACN,kBAAC,QAAD;IAAM,WAAW,EAAG,uCAAuC,EAAe,GAAM;cAAG;IAAa,CAAA;GAChG,kBAAC,QAAD;IAAM,WAAU;cAAhB,CACG,GACD,kBAAC,GAAD,EAAc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AyC,uBAAuB,EAAE,KAAK,GAAqB,CAAC;OAGrG,MAAM,kBAAC,GAAD,EAAU,CAAA;OAChB,eAAe,EAAS,EAAU,YAAY,CAAC;OAC/C,CAAA;MACE;OACE,EAAA,CAAA;IACN;;EAEG,CAAA"}
1
+ {"version":3,"file":"HomePage.js","names":[],"sources":["../../../src/healthybowl/pages/HomePage.tsx"],"sourcesContent":["import { useMemo, useCallback, type FC, type ReactNode } from 'react';\nimport { useNavigate } from 'react-router-dom';\nimport { useI18n } from '@burdenoff/fe-libs/shared/providers/shell/I18nProvider';\nimport {\n Sprout,\n CalendarClock,\n Wallet,\n AlertTriangle,\n Plus,\n ClipboardList,\n BarChart3,\n MapPin,\n Thermometer,\n ArrowUpRight,\n ChevronRight,\n CheckCircle2,\n Cloud,\n CloudOff,\n Droplets,\n Wind,\n Eye,\n PawPrint,\n ShieldCheck,\n} from 'lucide-react';\nimport { EmphasisPanel, GlassCard } from '@burdenoff/fe-libs/ui';\nimport { PageLayout, StatusBadge, EmptyState, ErrorState, PageLoader } from '../components';\nimport { useHealthyBowlData } from '../hooks/useHealthyBowlData';\nimport { useBasePath } from '../hooks/useBasePath';\nimport { cn, formatCurrency, formatDateOnly } from '../utils/helpers';\nimport { hasWeatherObservation } from '../utils/weatherPresence';\nimport type { Alert, Crop } from '../types';\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Semantic maps — colour carries meaning, always paired with a label. Tokens only.\n// ─────────────────────────────────────────────────────────────────────────────\n\ntype Tone = 'neutral' | 'success' | 'warning' | 'danger';\n\nconst toneValueClass: Record<Tone, string> = {\n neutral: 'text-text-primary',\n success: 'text-status-success-text',\n warning: 'text-status-warning-text',\n danger: 'text-status-error-text',\n};\n\nconst toneChipClass: Record<Tone, string> = {\n neutral: 'bg-[var(--color-accent-soft)] text-text-primary',\n success: 'bg-status-success-bg text-status-success-text',\n warning: 'bg-status-warning-bg text-status-warning-text',\n danger: 'bg-status-error-bg text-status-error-text',\n};\n\nconst severityRank: Record<Alert['severity'], number> = { critical: 0, warning: 1, info: 2 };\n\nconst severityDotClass: Record<Alert['severity'], string> = {\n critical: 'bg-status-error-text',\n warning: 'bg-status-warning-text',\n info: 'bg-status-info-text',\n};\n\nconst healthVariant = (status: string) => {\n switch (status) {\n case 'excellent':\n return 'success' as const;\n case 'good':\n return 'info' as const;\n case 'fair':\n return 'warning' as const;\n default:\n return 'error' as const;\n }\n};\n\nconst clampPercent = (n: number) => Math.max(0, Math.min(100, Math.round(n)));\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Presentational sub-components (module-level so they don't remount each render)\n// ─────────────────────────────────────────────────────────────────────────────\n\ninterface KpiTileProps {\n label: string;\n value: string;\n icon: ReactNode;\n tone?: Tone;\n /** Featured accent glow — reserve for the single focal KPI (needs-attention). */\n glow?: boolean;\n drillLabel: string;\n onClick: () => void;\n}\n\n/** Primary KPI card — big real value + tone-coded chip + drill-down. No fabricated trend/sparkline. */\nconst KpiTile: FC<KpiTileProps> = ({ label, value, icon, tone = 'neutral', glow = false, drillLabel, onClick }) => (\n <button type=\"button\" onClick={onClick} className=\"group block text-left focus-visible:outline-none\">\n <GlassCard\n treatment=\"metric\"\n glow={glow}\n className=\"flex h-full flex-col gap-3 border-border-seam p-4 transition-shadow group-hover:shadow-pop group-focus-visible:ring-2 group-focus-visible:ring-border-focus group-focus-visible:ring-offset-2 group-focus-visible:ring-offset-bg-canvas\"\n >\n <div className=\"flex items-center justify-between\">\n <span className=\"text-sm font-medium text-text-secondary\">{label}</span>\n <span className={cn('flex size-8 items-center justify-center rounded-lg [&>svg]:size-4', toneChipClass[tone])}>\n {icon}\n </span>\n </div>\n <span className={cn('text-3xl font-semibold tabular-nums', toneValueClass[tone])}>{value}</span>\n <span className=\"mt-auto inline-flex items-center gap-1 text-xs font-medium text-text-secondary transition-colors group-hover:text-text-primary\">\n {drillLabel}\n <ArrowUpRight className=\"size-3.5\" />\n </span>\n </GlassCard>\n </button>\n);\n\ninterface MiniStatProps {\n label: string;\n value: string;\n hint?: string;\n icon: ReactNode;\n onClick: () => void;\n}\n\n/** Secondary \"at a glance\" tile — quieter than a KPI, honest zero-state hints. */\nconst MiniStat: FC<MiniStatProps> = ({ label, value, hint, icon, onClick }) => (\n <button type=\"button\" onClick={onClick} className=\"group block text-left focus-visible:outline-none\">\n <GlassCard className=\"flex h-full items-center justify-between gap-3 border-border-seam p-3 transition-shadow group-hover:shadow-pop group-focus-visible:ring-2 group-focus-visible:ring-border-focus group-focus-visible:ring-offset-2 group-focus-visible:ring-offset-bg-canvas\">\n <div className=\"min-w-0\">\n <p className=\"text-xs font-medium text-text-secondary\">{label}</p>\n <p className=\"mt-0.5 truncate text-lg font-semibold tabular-nums text-text-primary\">{value}</p>\n {hint && <p className=\"mt-0.5 truncate text-xs text-text-secondary\">{hint}</p>}\n </div>\n <span className=\"flex size-8 shrink-0 items-center justify-center rounded-lg bg-[var(--color-accent-soft)] text-text-secondary [&>svg]:size-4\">\n {icon}\n </span>\n </GlassCard>\n </button>\n);\n\ninterface AlertRowProps {\n alert: Alert;\n ctaLabel: string;\n relTime: string;\n onOpen: () => void;\n}\n\n/** One needs-attention row: severity dot + title + message + relative time + CTA. */\nconst AlertRow: FC<AlertRowProps> = ({ alert, ctaLabel, relTime, onOpen }) => (\n <li className=\"flex items-start gap-3 py-3\">\n <span className={cn('mt-1.5 size-2.5 shrink-0 rounded-full', severityDotClass[alert.severity])} aria-hidden />\n <div className=\"min-w-0 flex-1\">\n <div className=\"flex items-baseline justify-between gap-3\">\n <p className=\"truncate text-sm font-medium text-text-primary\">{alert.title}</p>\n <button\n type=\"button\"\n onClick={onOpen}\n className=\"shrink-0 text-xs font-medium text-action-primary-bg transition-colors hover:underline focus-visible:underline focus-visible:outline-none\"\n >\n {ctaLabel}\n </button>\n </div>\n <p className=\"mt-0.5 truncate text-xs text-text-secondary\">{alert.message}</p>\n <p className=\"mt-0.5 text-xs text-text-muted\">{relTime}</p>\n </div>\n </li>\n);\n\ninterface CropRowProps {\n crop: Crop;\n metaLabel: string;\n healthLabel: string;\n harvestLabel: string;\n openLabel: string;\n onOpen: () => void;\n}\n\n/** Rich crop row — name, field · stage, health, progress bar, expected harvest, open. */\nconst CropRow: FC<CropRowProps> = ({ crop, metaLabel, healthLabel, harvestLabel, openLabel, onOpen }) => (\n <li>\n <button\n type=\"button\"\n onClick={onOpen}\n className=\"group block w-full rounded-lg p-3 text-left transition-colors hover:bg-bg-sunken/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border-focus\"\n >\n <div className=\"flex items-center justify-between gap-2\">\n <div className=\"min-w-0\">\n <p className=\"truncate text-sm font-medium text-text-primary\">{crop.name}</p>\n <p className=\"truncate text-xs text-text-secondary\">{metaLabel}</p>\n </div>\n <StatusBadge label={healthLabel} variant={healthVariant(crop.healthStatus)} dot />\n </div>\n <div className=\"mt-2 flex items-center gap-3\">\n <div className=\"h-1.5 flex-1 overflow-hidden rounded-full bg-bg-sunken\">\n <div\n className=\"h-full rounded-full bg-action-primary-bg\"\n style={{ width: `${clampPercent(crop.progress)}%` }}\n />\n </div>\n <span className=\"w-9 shrink-0 text-right text-xs font-medium tabular-nums text-text-secondary\">\n {clampPercent(crop.progress)}%\n </span>\n </div>\n <div className=\"mt-1.5 flex items-center justify-between text-xs text-text-secondary\">\n <span className=\"truncate\">{harvestLabel}</span>\n <span className=\"inline-flex shrink-0 items-center gap-0.5 font-medium transition-colors group-hover:text-text-primary\">\n {openLabel}\n <ChevronRight className=\"size-3.5\" />\n </span>\n </div>\n </button>\n </li>\n);\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Dashboard\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport const HomePage: FC = () => {\n const { dashboardStats, alerts, crops, weatherData, markAlertRead, farm, loadings, errors, refetch } =\n useHealthyBowlData();\n\n const navigate = useNavigate();\n const { t: translate } = useI18n();\n // Local wrapper preserves the (key, fallback) call style used across HB pages\n // while forwarding interpolation params to the shared i18n `t` (for {{count}} etc.).\n const t = useCallback(\n (key: string, fallback: string, params?: Record<string, string | number>): string =>\n translate(key, fallback, params),\n [translate]\n );\n const { buildPath } = useBasePath();\n const stats = dashboardStats;\n\n const weather = {\n location: weatherData?.location ?? '',\n current: weatherData?.current,\n forecast: weatherData?.forecast ?? [],\n };\n // The data hook substitutes an all-zero EMPTY_WEATHER when there is nothing to\n // show, so presence has to come from a named condition — never from the\n // numbers, because 0 °C / 0 km/h / UV 0 is a real (and frost-relevant) reading.\n const hasWeather = hasWeatherObservation(weather.current);\n\n // Today's date, localised — \"Friday, 25 July\" style.\n const todayLabel = useMemo(\n () => new Date().toLocaleDateString(undefined, { weekday: 'long', day: 'numeric', month: 'long' }),\n []\n );\n\n // Alerts sorted by severity (critical → warning → info); capped for the panel.\n const sortedAlerts = useMemo(\n () => [...alerts].sort((a, b) => severityRank[a.severity] - severityRank[b.severity]),\n [alerts]\n );\n const visibleAlerts = sortedAlerts.slice(0, 5);\n const attentionCount = alerts.length;\n\n // Crops ordered by nearest harvest first; capped so the anchor stays scannable.\n const sortedCrops = useMemo(\n () =>\n [...crops].sort(\n (a, b) => (a.daysToHarvest ?? Number.MAX_SAFE_INTEGER) - (b.daysToHarvest ?? Number.MAX_SAFE_INTEGER)\n ),\n [crops]\n );\n const visibleCrops = sortedCrops.slice(0, 6);\n\n // Expenses as a share of revenue — honest ratio, null when there's no revenue to compare against.\n const expenseRatioPercent = useMemo(() => {\n if (stats.totalRevenue === 0) return null;\n return Math.round((stats.totalExpenses / stats.totalRevenue) * 100 * 10) / 10;\n }, [stats.totalExpenses, stats.totalRevenue]);\n\n // Compact relative-time (minutes/hours/days/weeks), i18n'd.\n const relTime = useCallback(\n (iso: string): string => {\n const then = new Date(iso).getTime();\n if (Number.isNaN(then)) return '';\n const diffMin = Math.max(0, Math.floor((Date.now() - then) / 60000));\n if (diffMin < 1) return t('healthybowl.home.time.now', 'just now');\n if (diffMin < 60) return t('healthybowl.home.time.minutes', '{{n}}m ago', { n: diffMin });\n const diffHr = Math.floor(diffMin / 60);\n if (diffHr < 24) return t('healthybowl.home.time.hours', '{{n}}h ago', { n: diffHr });\n const diffDay = Math.floor(diffHr / 24);\n if (diffDay < 7) return t('healthybowl.home.time.days', '{{n}}d ago', { n: diffDay });\n return t('healthybowl.home.time.weeks', '{{n}}w ago', { n: Math.floor(diffDay / 7) });\n },\n [t]\n );\n\n // Per-alert CTA label by severity — mirrors Review / Open / View in the design.\n const alertCta = useCallback(\n (severity: Alert['severity']): string => {\n if (severity === 'critical') return t('healthybowl.home.needsAttention.review', 'Review');\n if (severity === 'warning') return t('healthybowl.home.needsAttention.open', 'Open');\n return t('healthybowl.home.needsAttention.view', 'View');\n },\n [t]\n );\n\n const openAlert = useCallback(\n (alert: Alert) => {\n void markAlertRead(alert.id, true);\n if (alert.actionUrl) navigate(alert.actionUrl);\n },\n [markAlertRead, navigate]\n );\n\n // ── Real-field-backed KPI derivations ──\n const netProfitTone: Tone = stats.netProfit > 0 ? 'success' : stats.netProfit < 0 ? 'danger' : 'neutral';\n const hasCritical = alerts.some((a) => a.severity === 'critical');\n const hasWarning = alerts.some((a) => a.severity === 'warning');\n const attentionTone: Tone =\n attentionCount === 0 ? 'success' : hasCritical ? 'danger' : hasWarning ? 'warning' : 'neutral';\n\n const quickActions = [\n {\n label: t('healthybowl.home.quickActions.addCrop.label', 'Add crop'),\n icon: Sprout,\n path: buildPath('crops'),\n },\n {\n label: t('healthybowl.home.quickActions.recordHarvest.label', 'Record harvest'),\n icon: ClipboardList,\n path: buildPath('crops/harvest'),\n },\n {\n label: t('healthybowl.home.quickActions.viewFields.label', 'View fields'),\n icon: MapPin,\n path: buildPath('crops/fields'),\n },\n {\n label: t('healthybowl.home.quickActions.viewWeather.label', 'View weather'),\n icon: Thermometer,\n path: buildPath('weather'),\n },\n {\n label: t('healthybowl.home.quickActions.analytics.label', 'Analytics'),\n icon: BarChart3,\n path: buildPath('analytics'),\n },\n ];\n\n // Compact header subline: date · farm + a live needs-attention summary.\n const attentionSummary =\n attentionCount === 0\n ? t('healthybowl.home.header.allClear', \"You're all caught up\")\n : attentionCount === 1\n ? t('healthybowl.home.header.needsAttentionOne', '1 item needs your attention')\n : t('healthybowl.home.header.needsAttentionOther', '{{count}} items need your attention', {\n count: attentionCount,\n });\n\n // PageLayout's `description` is a plain string; the date + farm reads as the subline.\n const headerSubline = farm?.name ? `${todayLabel} · ${farm.name}` : todayLabel;\n\n const headerActions = (\n <button\n type=\"button\"\n onClick={() => navigate(buildPath('crops'))}\n className=\"inline-flex min-h-[40px] items-center gap-2 rounded-md bg-action-primary-bg px-4 py-2 text-sm font-medium text-action-primary-text transition-colors hover:bg-action-primary-bg/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border-focus focus-visible:ring-offset-2 focus-visible:ring-offset-bg-canvas\"\n >\n <Plus className=\"h-4 w-4\" />\n {t('healthybowl.home.primaryAction', 'Add')}\n </button>\n );\n\n return (\n <PageLayout\n title={t('healthybowl.home.title', 'Farm Dashboard')}\n description={headerSubline}\n actions={headerActions}\n >\n {loadings.dashboard ? (\n <PageLoader />\n ) : errors.dashboard ? (\n <ErrorState onRetry={refetch} />\n ) : (\n <div className=\"space-y-6\">\n {/* Live needs-attention summary — reads directly under the compact header */}\n <div\n className={cn(\n 'inline-flex items-center gap-1.5 rounded-full px-3 py-1 text-sm font-medium',\n attentionCount === 0\n ? 'bg-status-success-bg text-status-success-text'\n : 'bg-status-warning-bg text-status-warning-text'\n )}\n >\n {attentionCount === 0 ? <CheckCircle2 className=\"size-4\" /> : <AlertTriangle className=\"size-4\" />}\n {attentionSummary}\n </div>\n\n {/* First-run onboarding — only once data has settled and there's no farm yet */}\n {!farm?.id && (\n <EmphasisPanel className=\"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between\">\n <div>\n <p className=\"text-base font-semibold text-text-primary\">\n {t('healthybowl.home.onboarding.title', 'Welcome to HealthyBowl')}\n </p>\n <p className=\"text-sm text-text-secondary\">\n {t(\n 'healthybowl.home.onboarding.description',\n 'Set up your farm to start tracking crops, livestock, finances, and more.'\n )}\n </p>\n </div>\n <button\n type=\"button\"\n onClick={() => navigate(buildPath('getting-started'))}\n className=\"inline-flex min-h-[44px] items-center gap-2 self-start rounded-md bg-action-primary-bg px-4 py-2 text-sm font-medium text-action-primary-text transition-colors hover:bg-action-primary-bg/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border-focus focus-visible:ring-offset-2 focus-visible:ring-offset-bg-canvas sm:self-auto\"\n >\n <Plus className=\"h-4 w-4\" />\n {t('healthybowl.home.onboarding.action', 'Set up your farm')}\n </button>\n </EmphasisPanel>\n )}\n\n {/* Quick-action strip — compact row, existing wired targets */}\n <div className=\"flex flex-wrap gap-2\">\n {quickActions.map(({ label, icon: Icon, path }) => (\n <button\n key={label}\n type=\"button\"\n onClick={() => navigate(path)}\n className=\"inline-flex min-h-[40px] items-center gap-2 rounded-full border border-border-subtle bg-bg-surface px-3.5 py-2 text-sm font-medium text-text-secondary transition-colors hover:border-border-default hover:bg-bg-sunken hover:text-text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border-focus focus-visible:ring-offset-2 focus-visible:ring-offset-bg-canvas\"\n >\n <Icon className=\"size-4\" />\n {label}\n </button>\n ))}\n </div>\n\n {/* Primary row — 4 real-field KPIs + needs-attention panel above the fold */}\n <div className=\"grid grid-cols-1 gap-6 lg:grid-cols-3\">\n <div className=\"grid grid-cols-2 gap-4 lg:col-span-2\">\n <KpiTile\n label={t('healthybowl.home.kpi.activeCrops', 'Active crops')}\n value={String(stats.activeCrops)}\n icon={<Sprout />}\n drillLabel={t('healthybowl.home.kpi.viewCrops', 'View crops')}\n onClick={() => navigate(buildPath('crops'))}\n />\n <KpiTile\n label={t('healthybowl.home.kpi.harvestDue', 'Harvest due')}\n value={String(stats.harvestDue)}\n icon={<CalendarClock />}\n drillLabel={t('healthybowl.home.kpi.viewHarvest', 'View harvest')}\n onClick={() => navigate(buildPath('crops/harvest'))}\n />\n <KpiTile\n label={t('healthybowl.home.kpi.netProfit', 'Net profit')}\n value={formatCurrency(stats.netProfit)}\n icon={<Wallet />}\n tone={netProfitTone}\n drillLabel={t('healthybowl.home.kpi.viewFinance', 'View finances')}\n onClick={() => navigate(buildPath('financial'))}\n />\n <KpiTile\n label={t('healthybowl.home.kpi.needsAttention', 'Needs attention')}\n value={String(attentionCount)}\n icon={<AlertTriangle />}\n tone={attentionTone}\n glow={attentionTone === 'danger' || attentionTone === 'warning'}\n drillLabel={t('healthybowl.home.kpi.viewAlerts', 'View alerts')}\n onClick={() => navigate(buildPath('weather/alerts'))}\n />\n </div>\n\n {/* Needs attention */}\n <GlassCard className=\"flex h-full flex-col border-border-seam p-0\">\n <div className=\"flex items-center justify-between px-4 pb-1 pt-4\">\n <h3 className=\"text-sm font-semibold text-text-primary\">\n {t('healthybowl.home.needsAttention.title', 'Needs attention')}\n </h3>\n {sortedAlerts.length > 0 && (\n <button\n type=\"button\"\n onClick={() => navigate(buildPath('weather/alerts'))}\n className=\"text-xs font-medium text-text-secondary transition-colors hover:text-text-primary focus-visible:text-text-primary focus-visible:outline-none\"\n >\n {t('healthybowl.home.needsAttention.viewAll', 'View all')}\n </button>\n )}\n </div>\n <div className=\"flex-1 px-4 pb-4\">\n {sortedAlerts.length === 0 ? (\n <EmptyState\n icon={<CheckCircle2 className=\"h-8 w-8 text-status-success-text\" />}\n title={t('healthybowl.home.needsAttention.empty.title', \"You're all caught up\")}\n description={t(\n 'healthybowl.home.needsAttention.empty.description',\n 'No urgent farm alerts right now.'\n )}\n action={\n <button\n type=\"button\"\n onClick={() => navigate(buildPath('weather/alert-rules'))}\n className=\"inline-flex min-h-[40px] items-center gap-2 rounded-md border border-border-subtle px-3 py-2 text-sm font-medium text-text-primary transition-colors hover:bg-bg-sunken focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border-focus\"\n >\n {t('healthybowl.home.needsAttention.empty.action', 'Manage alert rules')}\n </button>\n }\n />\n ) : (\n <ul className=\"divide-y divide-border-subtle\">\n {visibleAlerts.map((alert) => (\n <AlertRow\n key={alert.id}\n alert={alert}\n ctaLabel={alertCta(alert.severity)}\n relTime={relTime(alert.timestamp)}\n onOpen={() => openAlert(alert)}\n />\n ))}\n </ul>\n )}\n </div>\n </GlassCard>\n </div>\n\n {/* Anchor row — crop overview (strongest) + compact weather */}\n <div className=\"grid grid-cols-1 gap-6 lg:grid-cols-3\">\n {/* Crop overview — the farm-specific anchor */}\n <GlassCard glow className=\"flex h-full flex-col border-border-seam p-0 lg:col-span-2\">\n <div className=\"flex items-center justify-between px-5 pb-2 pt-5\">\n <div className=\"flex items-center gap-2\">\n <span className=\"flex size-8 items-center justify-center rounded-lg bg-[var(--color-accent-soft)] text-primary [&>svg]:size-4\">\n <Sprout />\n </span>\n <div>\n <h2 className=\"text-base font-semibold text-text-primary\">\n {t('healthybowl.home.cropsAnchor.title', 'Crop overview')}\n </h2>\n <p className=\"text-xs text-text-secondary\">\n {crops.length === 1\n ? t('healthybowl.home.cropsAnchor.subtitleOne', '1 crop in progress')\n : t('healthybowl.home.cropsAnchor.subtitleOther', '{{count}} crops in progress', {\n count: crops.length,\n })}\n </p>\n </div>\n </div>\n {crops.length > 0 && (\n <button\n type=\"button\"\n onClick={() => navigate(buildPath('crops'))}\n className=\"text-xs font-medium text-text-secondary transition-colors hover:text-text-primary focus-visible:text-text-primary focus-visible:outline-none\"\n >\n {t('healthybowl.home.cropsAnchor.viewAll', 'View all crops')}\n </button>\n )}\n </div>\n <div className=\"flex-1 px-3 pb-3\">\n {crops.length === 0 ? (\n <EmptyState\n icon={<Sprout className=\"h-8 w-8 text-primary\" />}\n title={t('healthybowl.home.cropsAnchor.empty.title', 'No active crops')}\n description={t(\n 'healthybowl.home.cropsAnchor.empty.description',\n 'Register your first crop to track growth, health and harvest here.'\n )}\n action={\n <button\n type=\"button\"\n onClick={() => navigate(buildPath('crops'))}\n className=\"inline-flex min-h-[40px] items-center gap-2 rounded-md bg-action-primary-bg px-4 py-2 text-sm font-medium text-action-primary-text transition-colors hover:bg-action-primary-bg/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border-focus\"\n >\n <Plus className=\"h-4 w-4\" />\n {t('healthybowl.home.quickActions.addCrop.label', 'Add crop')}\n </button>\n }\n />\n ) : (\n <ul className=\"divide-y divide-border-subtle\">\n {visibleCrops.map((crop) => {\n const stage = (crop.growthStage || crop.status || '').replace(/_/g, ' ').trim();\n const metaLabel = [crop.fieldName, stage].filter(Boolean).join(' · ');\n return (\n <CropRow\n key={crop.id}\n crop={crop}\n metaLabel={metaLabel || t('healthybowl.home.cropsAnchor.noField', 'Unassigned')}\n healthLabel={(crop.healthStatus || 'unknown').replace(/_/g, ' ')}\n harvestLabel={\n crop.expectedHarvestDate\n ? t('healthybowl.home.cropsAnchor.harvest', 'Harvest {{date}}', {\n date: formatDateOnly(crop.expectedHarvestDate),\n })\n : t('healthybowl.home.cropsAnchor.harvestUnknown', 'Harvest date TBD')\n }\n openLabel={t('healthybowl.home.cropsAnchor.open', 'Open')}\n onOpen={() => navigate(buildPath(`crops/${crop.id}`))}\n />\n );\n })}\n </ul>\n )}\n </div>\n </GlassCard>\n\n {/* Weather — secondary */}\n <GlassCard className=\"flex h-full flex-col border-border-seam p-0\">\n <div className=\"px-4 pb-1 pt-4\">\n <h3 className=\"text-sm font-semibold text-text-primary\">\n {t('healthybowl.home.weatherCard.title', 'Current weather')}\n </h3>\n {weather.location && <p className=\"text-xs text-text-secondary\">{weather.location}</p>}\n </div>\n <div className=\"flex flex-1 flex-col gap-4 px-4 pb-4\">\n {!hasWeather ? (\n // No observation. Say so, rather than printing 0 °C / 0% / 0 hPa\n // — fabricated readings are worse than none on a farm dashboard.\n <EmptyState\n icon={<CloudOff className=\"h-8 w-8 text-text-muted\" />}\n title={\n errors.weather\n ? t('healthybowl.home.weatherCard.error.title', 'Weather unavailable')\n : t('healthybowl.home.weatherCard.empty.title', 'No weather yet')\n }\n description={\n errors.weather\n ? t(\n 'healthybowl.home.weatherCard.error.description',\n \"We couldn't load conditions for your farm just now.\"\n )\n : t(\n 'healthybowl.home.weatherCard.empty.description',\n 'Set your farm location to see local conditions here.'\n )\n }\n action={\n <button\n type=\"button\"\n onClick={() => (errors.weather ? refetch() : navigate(buildPath('farm')))}\n className=\"inline-flex min-h-[40px] items-center gap-2 rounded-md border border-border-default px-4 py-2 text-sm font-medium text-text-primary transition-colors hover:bg-bg-elevated focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border-focus\"\n >\n {errors.weather\n ? t('healthybowl.home.weatherCard.error.retry', 'Try again')\n : t('healthybowl.home.weatherCard.empty.action', 'Set farm location')}\n </button>\n }\n />\n ) : (\n <>\n <div className=\"flex items-center justify-between\">\n <div>\n <p className=\"text-4xl font-bold text-text-primary\">{weather.current.temperature}&deg;C</p>\n <p className=\"text-sm text-text-secondary\">{weather.current.condition}</p>\n <p className=\"mt-1 text-xs text-text-secondary\">\n {t('healthybowl.home.weatherCard.feelsLike', 'Feels like')} {weather.current.feelsLike}&deg;C\n </p>\n </div>\n <div className=\"flex flex-col items-center\">\n <Cloud className=\"h-12 w-12 text-text-secondary\" />\n <span className=\"mt-1 text-xs text-text-secondary\">UV {weather.current.uvIndex}</span>\n </div>\n </div>\n\n <div className=\"grid grid-cols-2 gap-3 border-t border-border-subtle pt-3\">\n <div className=\"flex items-center gap-2 text-sm text-text-secondary\">\n <Droplets className=\"h-4 w-4\" />\n <span>\n {weather.current.humidity}% {t('healthybowl.home.weatherCard.humidity', 'Humidity')}\n </span>\n </div>\n <div className=\"flex items-center gap-2 text-sm text-text-secondary\">\n <Wind className=\"h-4 w-4\" />\n <span>{weather.current.windSpeed} km/h</span>\n </div>\n <div className=\"flex items-center gap-2 text-sm text-text-secondary\">\n <Thermometer className=\"h-4 w-4\" />\n <span>{weather.current.pressure} hPa</span>\n </div>\n <div className=\"flex items-center gap-2 text-sm text-text-secondary\">\n <Eye className=\"h-4 w-4\" />\n <span>{weather.current.visibility} km</span>\n </div>\n </div>\n </>\n )}\n\n {weather.forecast.length > 0 && (\n <div className=\"grid grid-cols-4 gap-2 border-t border-border-subtle pt-3\">\n {weather.forecast.slice(0, 4).map((day) => (\n <div key={day.date} className=\"rounded-md bg-bg-sunken/50 p-2 text-center\">\n <p className=\"text-xs font-medium text-text-secondary\">\n {new Date(day.date).toLocaleDateString('en-US', { weekday: 'short' })}\n </p>\n <p className=\"mt-1 text-sm font-semibold text-text-primary\">{day.high}&deg;</p>\n <p className=\"text-xs text-text-secondary\">{day.low}&deg;</p>\n <p className=\"mt-0.5 text-xs text-text-secondary\">{day.precipitation}%</p>\n </div>\n ))}\n </div>\n )}\n\n <button\n type=\"button\"\n onClick={() => navigate(buildPath('weather'))}\n className=\"mt-auto w-full rounded-md border border-border-subtle py-2 text-sm text-text-primary transition-colors hover:bg-bg-sunken/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border-focus\"\n >\n {t('healthybowl.home.weatherCard.viewForecast', 'View full forecast')}\n </button>\n </div>\n </GlassCard>\n </div>\n\n {/* At a glance — demoted secondary metrics with honest zero-states */}\n <section>\n <h3 className=\"mb-2 text-xs font-medium uppercase tracking-wide text-text-secondary\">\n {t('healthybowl.home.glance.title', 'At a glance')}\n </h3>\n <div className=\"grid grid-cols-2 gap-3 sm:grid-cols-4\">\n <MiniStat\n label={t('healthybowl.home.glance.fields', 'Fields')}\n value={String(stats.totalFields)}\n hint={\n stats.totalFields > 0\n ? t('healthybowl.home.glance.fieldsHint', 'Monitored')\n : t('healthybowl.home.glance.fieldsEmpty', 'No fields yet')\n }\n icon={<MapPin />}\n onClick={() => navigate(buildPath('crops/fields'))}\n />\n <MiniStat\n label={t('healthybowl.home.glance.livestock', 'Livestock')}\n value={String(stats.totalAnimals)}\n hint={\n stats.totalAnimals > 0\n ? t('healthybowl.home.glance.livestockHint', 'Under management')\n : t('healthybowl.home.glance.livestockEmpty', 'No livestock added')\n }\n icon={<PawPrint />}\n onClick={() => navigate(buildPath('livestock'))}\n />\n <MiniStat\n label={t('healthybowl.home.glance.organic', 'Organic score')}\n value={\n stats.organicScore > 0\n ? `${stats.organicScore}%`\n : t('healthybowl.home.glance.organicEmpty', 'Not configured')\n }\n hint={stats.organicScore > 0 ? t('healthybowl.home.glance.organicHint', 'Compliance') : undefined}\n icon={<ShieldCheck />}\n onClick={() => navigate(buildPath('compliance'))}\n />\n <MiniStat\n label={t('healthybowl.home.glance.expenses', 'Expenses')}\n value={formatCurrency(stats.totalExpenses)}\n hint={\n expenseRatioPercent != null\n ? t('healthybowl.home.glance.expensesRatio', '{{pct}}% of revenue', { pct: expenseRatioPercent })\n : t('healthybowl.home.glance.noRevenue', 'No revenue yet')\n }\n icon={<Wallet />}\n onClick={() => navigate(buildPath('financial'))}\n />\n </div>\n </section>\n </div>\n )}\n </PageLayout>\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;AAsCA,IAAM,IAAuC;CAC3C,SAAS;CACT,SAAS;CACT,SAAS;CACT,QAAQ;CACT,EAEK,IAAsC;CAC1C,SAAS;CACT,SAAS;CACT,SAAS;CACT,QAAQ;CACT,EAEK,IAAkD;CAAE,UAAU;CAAG,SAAS;CAAG,MAAM;CAAG,EAEtF,IAAsD;CAC1D,UAAU;CACV,SAAS;CACT,MAAM;CACP,EAEK,KAAiB,MAAmB;AACxC,SAAQ,GAAR;EACE,KAAK,YACH,QAAO;EACT,KAAK,OACH,QAAO;EACT,KAAK,OACH,QAAO;EACT,QACE,QAAO;;GAIP,KAAgB,MAAc,KAAK,IAAI,GAAG,KAAK,IAAI,KAAK,KAAK,MAAM,EAAE,CAAC,CAAC,EAkBvE,KAA6B,EAAE,UAAO,UAAO,SAAM,UAAO,WAAW,UAAO,IAAO,eAAY,iBACnG,kBAAC,UAAD;CAAQ,MAAK;CAAkB;CAAS,WAAU;WAChD,kBAAC,GAAD;EACE,WAAU;EACJ;EACN,WAAU;YAHZ;GAKE,kBAAC,OAAD;IAAK,WAAU;cAAf,CACE,kBAAC,QAAD;KAAM,WAAU;eAA2C;KAAa,CAAA,EACxE,kB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O,EAAM,aAAa;OACjC,MACE,EAAM,eAAe,IACjB,EAAE,yCAAyC,mBAAmB,GAC9D,EAAE,0CAA0C,qBAAqB;OAEvE,MAAM,kBAAC,GAAD,EAAY,CAAA;OAClB,eAAe,EAAS,EAAU,YAAY,CAAC;OAC/C,CAAA;MACF,kBAAC,GAAD;OACE,OAAO,EAAE,mCAAmC,gBAAgB;OAC5D,OACE,EAAM,eAAe,IACjB,GAAG,EAAM,aAAa,KACtB,EAAE,wCAAwC,iBAAiB;OAEjE,MAAM,EAAM,eAAe,IAAI,EAAE,uCAAuC,aAAa,GAAG,KAAA;OACxF,MAAM,kBAAC,GAAD,EAAe,CAAA;OACrB,eAAe,EAAS,EAAU,aAAa,CAAC;OAChD,CAAA;MACF,kBAAC,GAAD;OACE,OAAO,EAAE,oCAAoC,WAAW;OACxD,OAAO,EAAe,EAAM,cAAc;OAC1C,MACE,KAAuB,OAEnB,EAAE,qCAAqC,iBAAiB,GADxD,EAAE,yCAAyC,uBAAuB,EAAE,KAAK,GAAqB,CAAC;OAGrG,MAAM,kBAAC,GAAD,EAAU,CAAA;OAChB,eAAe,EAAS,EAAU,YAAY,CAAC;OAC/C,CAAA;MACE;OACE,EAAA,CAAA;IACN;;EAEG,CAAA"}
@@ -0,0 +1,8 @@
1
+ //#region src/healthybowl/utils/weatherPresence.ts
2
+ function e(e) {
3
+ return !!e?.condition?.trim();
4
+ }
5
+ //#endregion
6
+ export { e as hasWeatherObservation };
7
+
8
+ //# sourceMappingURL=weatherPresence.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"weatherPresence.js","names":[],"sources":["../../../src/healthybowl/utils/weatherPresence.ts"],"sourcesContent":["/**\n * Is there a real weather observation to show?\n *\n * `useHealthyBowlData` substitutes `EMPTY_WEATHER` — every numeric field 0,\n * every string '' — whenever the weather query has no value, so `current` is\n * ALWAYS an object and \"no data\" cannot be detected by a missing one.\n *\n * It also cannot be detected from the numbers. **0 is a legitimate reading**:\n * 0 °C is a frosty morning, 0 km/h is still air, 0 UV is night. Treating zero as\n * \"no data\" would blank the card exactly when a frost warning matters most —\n * which is the opposite of useful on a farm.\n *\n * What separates the two is `condition`: a real observation always names one\n * (\"Clear\", \"Light rain\"), and the empty fallback leaves it blank. That is the\n * only field whose emptiness cannot also be a valid measurement.\n */\nexport function hasWeatherObservation(current?: { condition?: string | null } | null): boolean {\n return Boolean(current?.condition?.trim());\n}\n"],"mappings":";AAgBA,SAAgB,EAAsB,GAAyD;AAC7F,QAAO,EAAQ,GAAS,WAAW,MAAM"}
@@ -26,7 +26,29 @@ function n(n) {
26
26
  let r = (n instanceof Error ? n.message : String(n)).toLowerCase();
27
27
  return e.some((e) => r.includes(e)) ? !1 : t.some((e) => r.includes(e));
28
28
  }
29
+ var r = [
30
+ "rate limit exceeded",
31
+ "unauthorized",
32
+ "k8s api error 401"
33
+ ], i = [
34
+ "sandbox not found",
35
+ "sandbox is not running",
36
+ "sandbox service not available yet",
37
+ "sandbox failed",
38
+ "sandbox startup timed out",
39
+ "assistant service did not become healthy",
40
+ "proxy error: 404",
41
+ "proxy error: 502",
42
+ "proxy error: 503",
43
+ "session mode mismatch",
44
+ "unable to connect",
45
+ "able to access the url"
46
+ ];
47
+ function a(e) {
48
+ let t = (e instanceof Error ? e.message : String(e)).toLowerCase();
49
+ return r.some((e) => t.includes(e)) ? !1 : i.some((e) => t.includes(e));
50
+ }
29
51
  //#endregion
30
- export { n as isMultimodalBodyRejection };
52
+ export { n as isMultimodalBodyRejection, a as isRecoverableAssistantError };
31
53
 
32
54
  //# sourceMappingURL=assistantTransportErrors.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"assistantTransportErrors.js","names":[],"sources":["../../src/utils/assistantTransportErrors.ts"],"sourcesContent":["/**\n * Deciding whether a failed turn is worth re-sending WITHOUT its images.\n *\n * The multimodal turn carries image bytes inside the `proxySandboxRequest` body.\n * Two things can refuse that body before the model ever sees it:\n *\n * 1. `wspace-public-gateway` enforces `MAX_REQUEST_BODY_SIZE` (256kb in alpha\n * and prod). It compares `Content-Length` and answers **413 before\n * authenticating and before forwarding anything**.\n * 2. The in-sandbox bridge can reject the body itself, which surfaces through\n * fe-libs as `Proxy error: <status>`.\n *\n * In both cases the prompt provably did not reach the agent, so re-sending it\n * text-only is safe and is strictly better than losing the turn.\n *\n * ## Why this is substring matching and not a status check\n *\n * fe-libs' `graphqlFetch` maps a non-2xx response to a human sentence and throws\n * that — `throw Error(friendlyMessage(response))` — keeping no status code, no\n * `extensions`, nothing structured. Every 4xx that is not 401/403/404/429\n * collapses to one sentence. So the sentence IS the signal; there is nothing\n * better to key on from here.\n *\n * ## Why the deny-list comes first\n *\n * Retrying something that may have LANDED would double-charge the user and give\n * the agent the same question twice — the session is stateful and the prompt\n * POST carries no idempotency key. Anything that could have failed on the\n * RESPONSE leg (network drops, timeouts, 5xx) is therefore excluded outright,\n * including the shapes fe-libs' own `executeSandboxGraphQL` has already retried\n * three times before we ever see them.\n */\n\n/** Failures that may have reached the agent. Never re-send these. */\nconst MAY_HAVE_LANDED = [\n 'failed to fetch',\n 'networkerror',\n 'network request failed',\n 'load failed',\n 'aborted',\n 'took too long',\n 'timed out',\n 'timeout',\n 'too many requests',\n 'the server is having trouble',\n 'unexpected error',\n];\n\n/** Failures that provably rejected the body before it was forwarded. */\nconst REJECTED_BEFORE_FORWARDING = [\n // The generic 4xx sentence from fe-libs `graphqlFetch`. For a POST whose\n // GraphQL document is known-good, the reachable cases are the gateway's 413\n // body cap and a 400-class rejection of the body — both pre-forward.\n 'the request could not be processed',\n // Direct 413 wording, in case a proxy answers with its own body.\n 'payload too large',\n 'request body exceeds maximum size',\n 'request entity too large',\n 'content too large',\n // The bridge rejected the body (fe-libs `Proxy error: <status>`).\n 'proxy error: 400',\n 'proxy error: 413',\n 'proxy error: 415',\n 'proxy error: 422',\n];\n\n/**\n * Is this error a rejection of the request BODY that we should retry without\n * the multimodal parts?\n */\nexport function isMultimodalBodyRejection(error: unknown): boolean {\n const message = (error instanceof Error ? error.message : String(error)).toLowerCase();\n if (MAY_HAVE_LANDED.some((fragment) => message.includes(fragment))) return false;\n return REJECTED_BEFORE_FORWARDING.some((fragment) => message.includes(fragment));\n}\n"],"mappings":";AAkCA,IAAM,IAAkB;CACtB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD,EAGK,IAA6B;CAIjC;CAEA;CACA;CACA;CACA;CAEA;CACA;CACA;CACA;CACD;AAMD,SAAgB,EAA0B,GAAyB;CACjE,IAAM,KAAW,aAAiB,QAAQ,EAAM,UAAU,OAAO,EAAM,EAAE,aAAa;AAEtF,QADI,EAAgB,MAAM,MAAa,EAAQ,SAAS,EAAS,CAAC,GAAS,KACpE,EAA2B,MAAM,MAAa,EAAQ,SAAS,EAAS,CAAC"}
1
+ {"version":3,"file":"assistantTransportErrors.js","names":[],"sources":["../../src/utils/assistantTransportErrors.ts"],"sourcesContent":["/**\n * Deciding whether a failed turn is worth re-sending WITHOUT its images.\n *\n * The multimodal turn carries image bytes inside the `proxySandboxRequest` body.\n * Two things can refuse that body before the model ever sees it:\n *\n * 1. `wspace-public-gateway` enforces `MAX_REQUEST_BODY_SIZE` (256kb in alpha\n * and prod). It compares `Content-Length` and answers **413 before\n * authenticating and before forwarding anything**.\n * 2. The in-sandbox bridge can reject the body itself, which surfaces through\n * fe-libs as `Proxy error: <status>`.\n *\n * In both cases the prompt provably did not reach the agent, so re-sending it\n * text-only is safe and is strictly better than losing the turn.\n *\n * ## Why this is substring matching and not a status check\n *\n * fe-libs' `graphqlFetch` maps a non-2xx response to a human sentence and throws\n * that — `throw Error(friendlyMessage(response))` — keeping no status code, no\n * `extensions`, nothing structured. Every 4xx that is not 401/403/404/429\n * collapses to one sentence. So the sentence IS the signal; there is nothing\n * better to key on from here.\n *\n * ## Why the deny-list comes first\n *\n * Retrying something that may have LANDED would double-charge the user and give\n * the agent the same question twice — the session is stateful and the prompt\n * POST carries no idempotency key. Anything that could have failed on the\n * RESPONSE leg (network drops, timeouts, 5xx) is therefore excluded outright,\n * including the shapes fe-libs' own `executeSandboxGraphQL` has already retried\n * three times before we ever see them.\n */\n\n/** Failures that may have reached the agent. Never re-send these. */\nconst MAY_HAVE_LANDED = [\n 'failed to fetch',\n 'networkerror',\n 'network request failed',\n 'load failed',\n 'aborted',\n 'took too long',\n 'timed out',\n 'timeout',\n 'too many requests',\n 'the server is having trouble',\n 'unexpected error',\n];\n\n/** Failures that provably rejected the body before it was forwarded. */\nconst REJECTED_BEFORE_FORWARDING = [\n // The generic 4xx sentence from fe-libs `graphqlFetch`. For a POST whose\n // GraphQL document is known-good, the reachable cases are the gateway's 413\n // body cap and a 400-class rejection of the body — both pre-forward.\n 'the request could not be processed',\n // Direct 413 wording, in case a proxy answers with its own body.\n 'payload too large',\n 'request body exceeds maximum size',\n 'request entity too large',\n 'content too large',\n // The bridge rejected the body (fe-libs `Proxy error: <status>`).\n 'proxy error: 400',\n 'proxy error: 413',\n 'proxy error: 415',\n 'proxy error: 422',\n];\n\n/**\n * Is this error a rejection of the request BODY that we should retry without\n * the multimodal parts?\n */\nexport function isMultimodalBodyRejection(error: unknown): boolean {\n const message = (error instanceof Error ? error.message : String(error)).toLowerCase();\n if (MAY_HAVE_LANDED.some((fragment) => message.includes(fragment))) return false;\n return REJECTED_BEFORE_FORWARDING.some((fragment) => message.includes(fragment));\n}\n\n/**\n * Faults where the whole turn is worth replaying against a FRESH sandbox and\n * session (the caller drops the remembered sandbox + backend session, then\n * re-runs once).\n *\n * Lives next to `isMultimodalBodyRejection` on purpose: both decide whether to\n * re-send a prompt, and a change to one is nearly always a change to the other.\n */\nconst NEVER_RECOVERABLE = ['rate limit exceeded', 'unauthorized', 'k8s api error 401'];\n\nconst RECOVERABLE_WITH_FRESH_SANDBOX = [\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 // ── The reaped-sandbox signature ──────────────────────────────────────────\n // A sandbox is destroyed at create + ttlSeconds, and keep-alive extensions did\n // not reach the runtime that enforces it, so a panel left open outlives its\n // own sandbox. Requests afterwards report the in-container service as\n // unreachable (\"assistant service not available: Unable to connect. Is the\n // computer able to access the url?\"), and until now that matched nothing here\n // — so the turn died with a raw error instead of provisioning a new sandbox,\n // and stayed dead for every later turn in that conversation.\n //\n // Matching the CONNECTION-REFUSED wording specifically, not the generic\n // \"assistant service not available\" prefix, which is also used for a 9s fetch\n // timeout — a timeout may mean the prompt DID land, and replaying that would\n // ask the model the same question twice. Refused provably delivered nothing.\n // Same wording the sandbox proxy itself treats as \"container not reachable\".\n 'unable to connect',\n 'able to access the url',\n];\n\nexport function isRecoverableAssistantError(error: unknown): boolean {\n const message = (error instanceof Error ? error.message : String(error)).toLowerCase();\n if (NEVER_RECOVERABLE.some((fragment) => message.includes(fragment))) return false;\n return RECOVERABLE_WITH_FRESH_SANDBOX.some((fragment) => message.includes(fragment));\n}\n"],"mappings":";AAkCA,IAAM,IAAkB;CACtB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD,EAGK,IAA6B;CAIjC;CAEA;CACA;CACA;CACA;CAEA;CACA;CACA;CACA;CACD;AAMD,SAAgB,EAA0B,GAAyB;CACjE,IAAM,KAAW,aAAiB,QAAQ,EAAM,UAAU,OAAO,EAAM,EAAE,aAAa;AAEtF,QADI,EAAgB,MAAM,MAAa,EAAQ,SAAS,EAAS,CAAC,GAAS,KACpE,EAA2B,MAAM,MAAa,EAAQ,SAAS,EAAS,CAAC;;AAWlF,IAAM,IAAoB;CAAC;CAAuB;CAAgB;CAAoB,EAEhF,IAAiC;CACrC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAeA;CACA;CACD;AAED,SAAgB,EAA4B,GAAyB;CACnE,IAAM,KAAW,aAAiB,QAAQ,EAAM,UAAU,OAAO,EAAM,EAAE,aAAa;AAEtF,QADI,EAAkB,MAAM,MAAa,EAAQ,SAAS,EAAS,CAAC,GAAS,KACtE,EAA+B,MAAM,MAAa,EAAQ,SAAS,EAAS,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@burdenoff/microfe-healthybowl",
3
- "version": "2026.727.3",
3
+ "version": "2026.729.1",
4
4
  "description": "Burdenoff HealthyBowl Microfrontend - Comprehensive organic farming and agro-foods management platform",
5
5
  "type": "module",
6
6
  "files": [