@burdenoff/microfe-healthybowl 2026.904.22 → 2026.904.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (146) hide show
  1. package/dist/components/assistant/AssistantChatArea.js +13 -11
  2. package/dist/components/assistant/AssistantChatArea.js.map +1 -1
  3. package/dist/healthybowl/HealthyBowlRoot.js +57 -56
  4. package/dist/healthybowl/HealthyBowlRoot.js.map +1 -1
  5. package/dist/healthybowl/HealthyBowlRoutes.js +48 -36
  6. package/dist/healthybowl/HealthyBowlRoutes.js.map +1 -1
  7. package/dist/healthybowl/components/CreateFarmTaskButton.js.map +1 -1
  8. package/dist/healthybowl/components/PageLayout.js +11 -10
  9. package/dist/healthybowl/components/PageLayout.js.map +1 -1
  10. package/dist/healthybowl/context/HealthyBowlContext.js +7 -7
  11. package/dist/healthybowl/context/HealthyBowlContext.js.map +1 -1
  12. package/dist/healthybowl/hooks/useAgronomyDecisions.js +79 -0
  13. package/dist/healthybowl/hooks/useAgronomyDecisions.js.map +1 -0
  14. package/dist/healthybowl/hooks/useAnalyticsReports.js +173 -0
  15. package/dist/healthybowl/hooks/useAnalyticsReports.js.map +1 -0
  16. package/dist/healthybowl/hooks/useComplianceExports.js +74 -0
  17. package/dist/healthybowl/hooks/useComplianceExports.js.map +1 -0
  18. package/dist/healthybowl/hooks/useConsultationPayments.js +59 -0
  19. package/dist/healthybowl/hooks/useConsultationPayments.js.map +1 -0
  20. package/dist/healthybowl/hooks/useHealthyBowlCompliance.js +157 -141
  21. package/dist/healthybowl/hooks/useHealthyBowlCompliance.js.map +1 -1
  22. package/dist/healthybowl/hooks/useHealthyBowlData.js +18 -0
  23. package/dist/healthybowl/hooks/useHealthyBowlData.js.map +1 -1
  24. package/dist/healthybowl/hooks/useHealthyBowlDistribution.js +52 -37
  25. package/dist/healthybowl/hooks/useHealthyBowlDistribution.js.map +1 -1
  26. package/dist/healthybowl/hooks/useHealthyBowlLivestockDepth.js +135 -78
  27. package/dist/healthybowl/hooks/useHealthyBowlLivestockDepth.js.map +1 -1
  28. package/dist/healthybowl/hooks/useIrrigationAutomation.js +1 -1
  29. package/dist/healthybowl/hooks/useIrrigationAutomation.js.map +1 -1
  30. package/dist/healthybowl/hooks/usePlantingEstimate.js +88 -0
  31. package/dist/healthybowl/hooks/usePlantingEstimate.js.map +1 -0
  32. package/dist/healthybowl/hooks/useSuccessionPlanning.js +1 -1
  33. package/dist/healthybowl/hooks/useSuccessionPlanning.js.map +1 -1
  34. package/dist/healthybowl/hooks/useWeatherIntelligence.js +1 -1
  35. package/dist/healthybowl/hooks/useWeatherIntelligence.js.map +1 -1
  36. package/dist/healthybowl/offline/HeaderOfflinePill.js +28 -0
  37. package/dist/healthybowl/offline/HeaderOfflinePill.js.map +1 -0
  38. package/dist/healthybowl/offline/OfflineStatusPill.js +40 -21
  39. package/dist/healthybowl/offline/OfflineStatusPill.js.map +1 -1
  40. package/dist/healthybowl/offline/OfflineSyncProvider.js +153 -130
  41. package/dist/healthybowl/offline/OfflineSyncProvider.js.map +1 -1
  42. package/dist/healthybowl/offline/captureCache.js +30 -0
  43. package/dist/healthybowl/offline/captureCache.js.map +1 -0
  44. package/dist/healthybowl/offline/graphql.js.map +1 -1
  45. package/dist/healthybowl/offline/headerSlot.js +24 -0
  46. package/dist/healthybowl/offline/headerSlot.js.map +1 -0
  47. package/dist/healthybowl/offline/store.js +1 -1
  48. package/dist/healthybowl/offline/syncEngine.js +2 -1
  49. package/dist/healthybowl/offline/syncEngine.js.map +1 -1
  50. package/dist/healthybowl/offline/types.js.map +1 -1
  51. package/dist/healthybowl/pages/GettingStartedPage.js +1 -0
  52. package/dist/healthybowl/pages/GettingStartedPage.js.map +1 -1
  53. package/dist/healthybowl/pages/ai/AiDecisionsPage.js +287 -0
  54. package/dist/healthybowl/pages/ai/AiDecisionsPage.js.map +1 -0
  55. package/dist/healthybowl/pages/analytics/InsightsPage.js +2 -2
  56. package/dist/healthybowl/pages/analytics/InsightsPage.js.map +1 -1
  57. package/dist/healthybowl/pages/analytics/ReportsPage.js +136 -99
  58. package/dist/healthybowl/pages/analytics/ReportsPage.js.map +1 -1
  59. package/dist/healthybowl/pages/compliance/ComplianceOverviewPage.js +204 -162
  60. package/dist/healthybowl/pages/compliance/ComplianceOverviewPage.js.map +1 -1
  61. package/dist/healthybowl/pages/compliance/IcsGroupDetailPage.js +196 -178
  62. package/dist/healthybowl/pages/compliance/IcsGroupDetailPage.js.map +1 -1
  63. package/dist/healthybowl/pages/compliance/IcsGrowerDetailPage.js +142 -141
  64. package/dist/healthybowl/pages/compliance/IcsGrowerDetailPage.js.map +1 -1
  65. package/dist/healthybowl/pages/compliance/ResidueTestsPage.js +291 -0
  66. package/dist/healthybowl/pages/compliance/ResidueTestsPage.js.map +1 -0
  67. package/dist/healthybowl/pages/compliance/SubstanceRulesPage.js +300 -0
  68. package/dist/healthybowl/pages/compliance/SubstanceRulesPage.js.map +1 -0
  69. package/dist/healthybowl/pages/compliance/substanceRuleForm.js +135 -0
  70. package/dist/healthybowl/pages/compliance/substanceRuleForm.js.map +1 -0
  71. package/dist/healthybowl/pages/crops/CropFieldsPage.js +2 -0
  72. package/dist/healthybowl/pages/crops/CropFieldsPage.js.map +1 -1
  73. package/dist/healthybowl/pages/crops/CropHarvestPage.js +316 -272
  74. package/dist/healthybowl/pages/crops/CropHarvestPage.js.map +1 -1
  75. package/dist/healthybowl/pages/crops/CropPlanningPage.js +6 -0
  76. package/dist/healthybowl/pages/crops/CropPlanningPage.js.map +1 -1
  77. package/dist/healthybowl/pages/crops/FieldDetailsPage.js +871 -846
  78. package/dist/healthybowl/pages/crops/FieldDetailsPage.js.map +1 -1
  79. package/dist/healthybowl/pages/crops/HarvestDetailsPage.js +376 -334
  80. package/dist/healthybowl/pages/crops/HarvestDetailsPage.js.map +1 -1
  81. package/dist/healthybowl/pages/distribution/CsaPlanDetailPage.js +415 -188
  82. package/dist/healthybowl/pages/distribution/CsaPlanDetailPage.js.map +1 -1
  83. package/dist/healthybowl/pages/distribution/labels.js +10 -2
  84. package/dist/healthybowl/pages/distribution/labels.js.map +1 -1
  85. package/dist/healthybowl/pages/farm/FarmProfilePage.js +1 -0
  86. package/dist/healthybowl/pages/farm/FarmProfilePage.js.map +1 -1
  87. package/dist/healthybowl/pages/field-capture/CaptureObservationForm.js +8 -8
  88. package/dist/healthybowl/pages/fields/FieldMapPage.js +2 -0
  89. package/dist/healthybowl/pages/fields/FieldMapPage.js.map +1 -1
  90. package/dist/healthybowl/pages/financial/FinancialReportsPage.js +92 -107
  91. package/dist/healthybowl/pages/financial/FinancialReportsPage.js.map +1 -1
  92. package/dist/healthybowl/pages/government-schemes/ApplicationTrackingPage.js +228 -188
  93. package/dist/healthybowl/pages/government-schemes/ApplicationTrackingPage.js.map +1 -1
  94. package/dist/healthybowl/pages/government-schemes/SchemeDetailsPage.js +261 -191
  95. package/dist/healthybowl/pages/government-schemes/SchemeDetailsPage.js.map +1 -1
  96. package/dist/healthybowl/pages/government-schemes/schemeApplicationTransitions.js +49 -0
  97. package/dist/healthybowl/pages/government-schemes/schemeApplicationTransitions.js.map +1 -0
  98. package/dist/healthybowl/pages/government-schemes/schemeDocumentSlots.js +48 -0
  99. package/dist/healthybowl/pages/government-schemes/schemeDocumentSlots.js.map +1 -0
  100. package/dist/healthybowl/pages/government-schemes/useSchemeApplicationTransition.js +54 -0
  101. package/dist/healthybowl/pages/government-schemes/useSchemeApplicationTransition.js.map +1 -0
  102. package/dist/healthybowl/pages/inputs-insurance/InputsInsuranceOverviewPage.js +14 -14
  103. package/dist/healthybowl/pages/inputs-insurance/InputsInsuranceOverviewPage.js.map +1 -1
  104. package/dist/healthybowl/pages/irrigation/IrrigationPage.js +338 -307
  105. package/dist/healthybowl/pages/irrigation/IrrigationPage.js.map +1 -1
  106. package/dist/healthybowl/pages/livestock/AnimalDepthFormModal.js +126 -102
  107. package/dist/healthybowl/pages/livestock/AnimalDepthFormModal.js.map +1 -1
  108. package/dist/healthybowl/pages/livestock/AnimalDepthPage.js +257 -215
  109. package/dist/healthybowl/pages/livestock/AnimalDepthPage.js.map +1 -1
  110. package/dist/healthybowl/pages/livestock/GrazingPage.js +1 -0
  111. package/dist/healthybowl/pages/livestock/GrazingPage.js.map +1 -1
  112. package/dist/healthybowl/pages/livestock/HerdDepthPage.js +4 -0
  113. package/dist/healthybowl/pages/livestock/HerdDepthPage.js.map +1 -1
  114. package/dist/healthybowl/pages/livestock/PedigreeTree.js +154 -0
  115. package/dist/healthybowl/pages/livestock/PedigreeTree.js.map +1 -0
  116. package/dist/healthybowl/pages/livestock/eidTagInput.js +39 -0
  117. package/dist/healthybowl/pages/livestock/eidTagInput.js.map +1 -0
  118. package/dist/healthybowl/pages/livestock/grazing/RecordGrazingMoveModal.js +8 -9
  119. package/dist/healthybowl/pages/livestock/grazing/RecordGrazingMoveModal.js.map +1 -1
  120. package/dist/healthybowl/pages/livestock/pedigreeLayout.js +68 -0
  121. package/dist/healthybowl/pages/livestock/pedigreeLayout.js.map +1 -0
  122. package/dist/healthybowl/pages/network/ExpertsPage.js +520 -419
  123. package/dist/healthybowl/pages/network/ExpertsPage.js.map +1 -1
  124. package/dist/healthybowl/pages/weather/WeatherAlertHistoryPage.js +129 -130
  125. package/dist/healthybowl/pages/weather/WeatherAlertHistoryPage.js.map +1 -1
  126. package/dist/healthybowl/pages/weather/WeatherSettingsPage.js +285 -237
  127. package/dist/healthybowl/pages/weather/WeatherSettingsPage.js.map +1 -1
  128. package/dist/healthybowl/pages/weather/alertDelivery.js +105 -0
  129. package/dist/healthybowl/pages/weather/alertDelivery.js.map +1 -0
  130. package/dist/healthybowl/utils/icsInspection.js +18 -0
  131. package/dist/healthybowl/utils/icsInspection.js.map +1 -0
  132. package/dist/healthybowl/utils/plantingCapacity.js +10 -10
  133. package/dist/healthybowl/utils/plantingCapacity.js.map +1 -1
  134. package/dist/hooks/useWorkspaceWriteAccess.js +6 -38
  135. package/dist/hooks/useWorkspaceWriteAccess.js.map +1 -1
  136. package/dist/node_modules/fast-equals/dist/es/index.js +74 -86
  137. package/dist/node_modules/fast-equals/dist/es/index.js.map +1 -1
  138. package/dist/services/assistantApi.js +59 -30
  139. package/dist/services/assistantApi.js.map +1 -1
  140. package/dist/utils/aiCredits.js +7 -9
  141. package/dist/utils/aiCredits.js.map +1 -1
  142. package/dist/utils/pageContext.js +15 -1
  143. package/dist/utils/pageContext.js.map +1 -1
  144. package/dist/utils/quotaUtils.js +2 -38
  145. package/package.json +2 -2
  146. package/dist/utils/quotaUtils.js.map +0 -1
@@ -18,8 +18,8 @@ import { useVoiceSession as ue } from "../../hooks/useVoiceSession.js";
18
18
  import { useAssistantApiAccess as de } from "../../hooks/useAssistantApiAccess.js";
19
19
  import { useWorkspaceWriteAccess as fe } from "../../hooks/useWorkspaceWriteAccess.js";
20
20
  import { useConversationTurns as pe } from "../../hooks/useConversationTurns.js";
21
- import { isQuotaExhaustedError as me } from "../../utils/quotaUtils.js";
22
- import { dispatchAssistantQuotaExhausted as he, notifyAiCreditsUpdated as ge } from "../../utils/aiCredits.js";
21
+ import { dispatchAssistantQuotaExhausted as me, notifyAiCreditsUpdated as he } from "../../utils/aiCredits.js";
22
+ import { isQuotaExhaustedError as ge } from "../../utils/quotaUtils.js";
23
23
  import { buildPromptForMode as _e } from "../../utils/assistantPrompt.js";
24
24
  import { isMultimodalBodyRejection as ve, isRecoverableAssistantError as ye } from "../../utils/assistantTransportErrors.js";
25
25
  import { isTurnInFlight as be } from "../../utils/assistantTurnState.js";
@@ -66,15 +66,17 @@ function We(e, t) {
66
66
  content: "Thinking...",
67
67
  done: !1
68
68
  };
69
- let r = n[n.length - 1], i = A(r.parts), a = O(r.parts), o = j(r.parts), ee = Ce(r.parts);
69
+ let r = n[n.length - 1], i = A(r.parts), a = O(r.parts), o = j(r.parts), ee = Ce(r.parts), s = [
70
+ i,
71
+ ...a,
72
+ ...o
73
+ ].filter(Boolean).join("\n\n") || "Thinking...", c = r.info?.providerID, l = r.info?.modelID;
70
74
  return {
71
- content: [
72
- i,
73
- ...a,
74
- ...o
75
- ].filter(Boolean).join("\n\n") || "Thinking...",
75
+ content: s,
76
76
  done: !!r.info?.time?.completed && (!!i || a.length > 0 || o.length > 0),
77
77
  tokens: r.info?.tokens,
78
+ messageId: r.info?.id,
79
+ ...c && l ? { model: `${c}/${l}` } : {},
78
80
  ...ee ? { pendingWrite: ee } : {}
79
81
  };
80
82
  }
@@ -208,7 +210,7 @@ var Ke = ({ visible: Ce = !0 }) => {
208
210
  }), te(x.content, le, l, e), x.tokens) {
209
211
  R(p, v, { tokens: x.tokens });
210
212
  try {
211
- await s(A, h, l, x.tokens, g), ge();
213
+ await s(A, h, l, x.messageId, x.model, x.tokens, g), he();
212
214
  } catch {}
213
215
  }
214
216
  z(p, "complete", v, null);
@@ -222,8 +224,8 @@ var Ke = ({ visible: Ce = !0 }) => {
222
224
  if (!h) throw Error("Assistant backend is unavailable without an active workspace context.");
223
225
  await b();
224
226
  } catch (t) {
225
- if (q.current.invalidate(e.getState().sandboxesByMode[f]?.sandboxId ?? null), me(t)) {
226
- he("sandbox"), te("You've reached your sandbox limit on the current plan. Upgrade to start the AI assistant.", void 0, void 0, void 0, "en"), z(p, "error", v, null);
227
+ if (q.current.invalidate(e.getState().sandboxesByMode[f]?.sandboxId ?? null), ge(t)) {
228
+ me("sandbox"), te("You've reached your sandbox limit on the current plan. Upgrade to start the AI assistant.", void 0, void 0, void 0, "en"), z(p, "error", v, null);
227
229
  return;
228
230
  }
229
231
  let n = t instanceof Error ? t.message : "Something went wrong";
@@ -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 { useI18n } from '@burdenoff/fe-libs/shared/providers/shell/I18nProvider';\nimport { resolveAssistantLanguage } from '@/config/assistantLanguages';\nimport { resolveLanguagePair } from '@/config/assistantLanguagePair';\nimport { AssistantMessageList } from './AssistantMessageList';\nimport { AssistantApiCallsConsentDialog } from './AssistantApiCallsConsentDialog';\nimport { AssistantEmptyState } from './AssistantEmptyState';\nimport { AssistantSpokenTurnsNotice } from './AssistantSpokenTurnsNotice';\nimport { VoiceTranscriptDrawer } from './voice/VoiceTranscriptDrawer';\nimport { AssistantComposer } from './composer/AssistantComposer';\nimport { AssistantVoiceSession } from './voice/AssistantVoiceSession';\nimport { parseToolActivity } from './AssistantToolActivity';\nimport { useVoiceSession } from '../../hooks/useVoiceSession';\nimport { useAssistantApiAccess } from '@/hooks/useAssistantApiAccess';\nimport { useWorkspaceWriteAccess } from '@/hooks/useWorkspaceWriteAccess';\nimport { useAssistantAttachments } from '@/hooks/useAssistantAttachments';\nimport { useConversationTurns } from '@/hooks/useConversationTurns';\nimport { useAssistantStore } from '@/store/assistantStore';\nimport {\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 { getActorId, 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 getSendableAttachments,\n toMessageAttachment,\n type AssistantAttachment,\n} from '@/utils/assistantAttachments';\nimport { isMultimodalBodyRejection, isRecoverableAssistantError } from '@/utils/assistantTransportErrors';\nimport { isTurnInFlight } from '@/utils/assistantTurnState';\nimport { useAssistantTr } from '@burdenoff/fe-libs/shared/assistant';\nimport { ASSISTANT_MODES } from '@/types/assistant';\nimport type { AssistantArtifact, AssistantConversationStatus, AssistantMode, Message } from '@/types/assistant';\nimport { pollDelayMs } from '../../utils/assistantPollSchedule';\nimport { findPendingWrite, type PendingWrite } from '../../utils/pendingWrite';\nimport { toCaptionText } from '../../utils/captionText';\nimport {\n buildContinuedFromVoiceNote,\n buildVoiceTranscriptMarkdown,\n voiceTranscriptFilename,\n} from '../../utils/voiceTranscript';\nimport { downloadFile } from '@/services/assistantExportService';\nimport { isVoiceTurn, voiceMarker, voiceSessionIdOf } from '../../utils/voiceTurnVisibility';\nimport { createReadinessTracker } from '../../utils/sandboxReadiness';\n// ★★ The SHARED credential redactor, not a local copy. The two were byte-identical:\n// the same four patterns stripping Bearer tokens, JWTs and `sk-ant-` keys from model\n// output before it renders. A redactor duplicated across repos is the worst kind of\n// duplicate — add a fifth pattern to one and the other keeps leaking, with nothing\n// failing to say so.\nimport { sanitize as sanitizeAssistantResponse } from '@burdenoff/fe-libs/shared/assistant/progress';\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 assistant: 180_000,\n 'api-calls': 180_000,\n 'vibe-plugins': 600_000,\n};\nconst DEFAULT_STREAM_BUDGET_MS = 180_000;\n\n/**\n * How long a spoken turn waits for its attachments to finish uploading.\n *\n * Long enough for a photo on a slow rural connection; short enough that a stuck\n * upload does not hold a question hostage. On timeout the turn goes without it\n * and the draft is cleared, so the miss is visible rather than deferred onto the\n * next question.\n */\nconst ATTACHMENT_SETTLE_TIMEOUT_MS = 20_000;\n\nfunction generateId(): string {\n return `${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;\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 /** A write the sandbox refused pending approval, if this turn produced one. */\n pendingWrite?: PendingWrite;\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 // ★ From the SAME message the content came from. Reaching for the last element\n // of `messages` instead is a second, different guess at which message this turn\n // produced — and on a session with trailing history it is the wrong one.\n const pendingWrite = findPendingWrite(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 // ★ Read from the SAME message the content came from. Picking the last\n // element of `messages` instead would be a second, different guess at which\n // message this turn produced — and on a session with trailing history it is\n // the wrong one.\n ...(pendingWrite ? { pendingWrite } : {}),\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\n/**\n * `visible` is false when the host HIDES the panel without unmounting it, which\n * is what the supported `visible` prop does. That distinction matters here: a\n * live voice session would otherwise keep the microphone open and the silence\n * timer running behind an invisible panel.\n */\ninterface AssistantChatAreaProps {\n visible?: boolean;\n}\n\nexport const AssistantChatArea: FC<AssistantChatAreaProps> = ({ visible = true }) => {\n const tr = useAssistantTr();\n const apollo = useGatewayClient('workspace');\n const { getAccessToken, getWorkspaceToken, userId } = useAuthToken();\n const { locale } = useI18n();\n const assistantLanguage = useAssistantStore((state) => state.assistantLanguage);\n // The language the user chose to SPEAK, which is not necessarily the one the\n // interface is in — that is the whole point of the preference (BOFF-7108).\n // Named in ENGLISH deliberately: the preamble around it is English, so\n // \"Answer in Tamil.\" reads as an instruction, where a bare tag (\"ta\") invites\n // the model to answer *about* the code instead of *in* the language.\n const replyLanguage = useAssistantStore((state) => state.replyLanguage);\n const languagePair = useMemo(\n () => resolveLanguagePair(assistantLanguage, replyLanguage, locale),\n [assistantLanguage, replyLanguage, locale]\n );\n const replyLanguageName = languagePair.reply.english;\n // A stored preference is a deliberate choice; `null` is only the interface\n // language standing in as a default. The directive treats the two differently\n // — see `buildLanguagePreamble`.\n //\n // Resolved, not merely non-null: a stale persisted code from a build that\n // offered more languages is DISCARDED by `resolveAssistantLanguage`, and\n // treating that discarded value as deliberate would tell the model the user\n // had chosen the interface language on purpose — suppressing the typed-language\n // override on the strength of a preference the selector does not even show.\n // ★ Whether a HUMAN picked this reply language or it was guessed from the\n // interface — true if EITHER field was pinned, since inheriting from a\n // deliberate input choice is still deliberate. `buildLanguagePreamble` uses it\n // to suppress the \"what they wrote in wins\" clause, which would otherwise make\n // the setting inert for everyone who types rather than dictates.\n const languageIsExplicit = languagePair.replyIsExplicit;\n const replyLanguageCode = languagePair.reply.code;\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 mergeMessageMetadata,\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 // ★ One place decides which turns belong to which surface. `messages` stays\n // available for questions about the CONVERSATION (is it used at all?), but it\n // is readonly, so it cannot reach a component that draws a message list.\n const turns = useConversationTurns(activeConversation);\n const messages = turns.all;\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 /**\n * ★ A SECOND, different question — and deliberately not a second gate.\n *\n * The check above asks whether this person may USE the write mode (org scope).\n * Writes then execute at WORKSPACE scope, where a separate decision is made,\n * so an org owner could plan a change, confirm it, and only then be refused.\n * This asks the execution question up front so the warning arrives before the\n * effort rather than after it.\n *\n * It does NOT hide or disable the mode. Measured against prod on 2026-09-02,\n * workspace scopes have no roles provisioned at all, so gating on this would\n * delete Take-action from the product until an ops task lands — a far worse\n * outcome than the confusion it would fix. It self-corrects with no code\n * change the moment roles exist.\n */\n const writeAccess = useWorkspaceWriteAccess(getActorId(), getWorkspaceId() || null);\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 // Read-only transcript, reachable when NO session is live. The drawer used to\n // be mounted only inside `AssistantVoiceSession`, so pressing End destroyed the\n // only way to read back what was said.\n const [transcriptOpen, setTranscriptOpen] = useState(false);\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 /**\n * Per-sandbox record of \"last proven reachable\", so a warm sandbox is not\n * re-probed on every turn. Invalidated by any failure — see both catches.\n */\n const sandboxReadiness = useRef(createReadinessTracker());\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 the read-only\n // `assistant` mode (the default \"Ask\", available to everyone), but only AFTER\n /** The config for the mode in play — read by the reset effect and by render. */\n const activeModeConfig = useMemo(() => ASSISTANT_MODES.find((modeConfig) => modeConfig.id === mode), [mode]);\n\n // the role check resolves (so an admin's persisted api-calls mode isn't reset\n // during the brief loading window).\n useEffect(() => {\n if (apiAccessLoading) return;\n const blocked = !activeModeConfig || (activeModeConfig.requiresAdmin && !canUseApiCalls);\n if (blocked && mode !== 'assistant') {\n setMode('assistant');\n }\n }, [mode, activeModeConfig, 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 // ★ Skip a proof we already have. This ran two network waits before the\n // model saw the prompt on EVERY turn, including turns seconds after the\n // last one succeeded — a constant tax, felt most in voice where it sits\n // between the user finishing a sentence and hearing anything.\n //\n // Safe only because every failure path below invalidates: see the catch\n // here and the turn-level catch. A cache that were only ever written on\n // success would pin a dead sandbox and turn a recoverable error into a\n // loop.\n if (sandboxReadiness.current.isFresh(candidateId)) return true;\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 sandboxReadiness.current.markVerified(candidateId);\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 sandboxReadiness.current.invalidate(candidateId);\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 (\n content: string,\n attachments: AssistantAttachment[] = [],\n // ★ The live voice session's id, present only when this turn was spoken.\n // It replaced a `dictated` boolean: two fields meaning almost the same\n // thing let a turn be marked spoken while recording no session, a state\n // with no meaning that only the transcript would ever notice.\n options: { voiceSessionId?: string } = {}\n ) => {\n // Spoken-ness is now DERIVED, so it cannot disagree with the session.\n const dictated = options.voiceSessionId !== undefined;\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 // ★ `voice` marks a turn that happened in the live voice session, so the\n // chat panel can leave it out. Both surfaces share one conversation, so\n // without it every spoken exchange showed up in the typed thread.\n metadata: {\n ...(attachments.length ? { attachments: attachments.map(toMessageAttachment) } : {}),\n ...voiceMarker(options.voiceSessionId),\n },\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 // Stamped now, not read later: this is the language the reply is being\n // generated in, and the preference may have moved on by the time\n // somebody presses Listen.\n // Carries the voice marker too: a reply to a spoken question belongs to\n // the voice session, not to the typed thread.\n metadata: { lang: replyLanguageCode, ...voiceMarker(options.voiceSessionId) },\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 // Our own hard-coded copy is English regardless of what the user picked.\n // Stamping it with their language makes playback read an English quota\n // message in a Tamil voice — Latin text cannot be script-detected, so\n // this metadata is trusted absolutely.\n lang: string = replyLanguageCode\n ) => {\n // `patchMessage` REPLACES metadata rather than merging it, so anything\n // omitted here is destroyed — which is how the turn-language stamp set\n // at creation was being wiped the moment the response completed,\n // silently undoing per-message language resolution. Always re-assert it.\n //\n // ★ The voice marker was being lost the same way, and it was worse: this\n // runs on every completed turn, and the reply is only handed to the voice\n // session AFTER it runs, so NO spoken answer could ever stay a voice\n // turn. Each one jumped into the typed thread — under a question that\n // had been correctly hidden, so chat showed orphaned answers — and\n // vanished from the transcript drawer at the same instant.\n // ★ TWO calls, and the split is the point. `patchMessage` REPLACES\n // `metadata`, so rebuilding the object here silently drops every key the\n // turn added along the way. That is not hypothetical: it destroyed the\n // voice marker once (see above), and it then destroyed `pendingWrite` —\n // the poll loop recorded the refused write moments earlier and this line\n // wiped it before the card could ever render, shipping a feature that was\n // inert in production.\n //\n // Re-asserting each marker by hand is what failed twice. Merging cannot\n // fail that way: keys this turn set stay set, and the ones below still\n // win where they overlap.\n patchMessage(conversationId, assistantMessageId, {\n content: sanitizeAssistantResponse(response),\n });\n mergeMessageMetadata(conversationId, assistantMessageId, {\n lang,\n ...(artifacts?.length ? { artifacts } : {}),\n ...(artifacts?.length || sessionId || sandboxId ? { mode: selectedMode } : {}),\n ...(sessionId ? { sessionId } : {}),\n ...(sandboxId ? { sandboxId } : {}),\n ...voiceMarker(options.voiceSessionId),\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 // ★★ There is deliberately NO pre-flight AI-credit gate here.\n //\n // This block used to call `checkAssistantAiCredits` inside a try/catch\n // that surfaced the upgrade dialog on a 429 QUOTA_EXHAUSTED. The catch\n // could never run: `services/assistantApi.checkAssistantAiCredits` is a\n // documented no-op returning `Promise.resolve(true)`, so it cannot\n // reject. Thirty-four lines of code and prose described a live quota\n // gate that was structurally unreachable — the most expensive kind of\n // comment, because the next person reads it and believes HealthyBowl\n // gates on credits.\n //\n // The no-op is the RIGHT product decision, not an oversight: HB is\n // metered per input token against a Free allowance of 500, so a real\n // pre-flight gate would refuse ordinary chats. It is recorded in the\n // api adapter, where the decision belongs.\n //\n // The budget IS still enforced, downstream and for real: the wspace\n // gateway's @usage(checkQuota) on createSandbox rejects an over-quota\n // caller with a 429, and the outer catch below turns that into the\n // upgrade dialog. That path is live and reachable.\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 // …and the language directive, so the reply comes back in the user's\n // language rather than defaulting to the language of the docs the\n // model grounds on. The FE is the only layer that knows the locale —\n // it is not on the wire and `pageContext` silently drops unknown keys.\n const promptText = buildPromptForMode(\n selectedMode,\n buildPromptWithAttachments(content, attachments),\n replyLanguageName,\n languageIsExplicit,\n dictated\n );\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 const pollStartedAt = Date.now();\n while (Date.now() < timeoutAt) {\n // ★ Delta poll. `priorNewestCreatedMs` is fixed for the whole turn and\n // is already the floor `buildAssistantProgress` filters on (`>`), so\n // asking the agent for `>=` the same value returns exactly the window\n // that function keeps — and nothing else. The result is identical; what\n // changes is that this stops re-downloading 50 full messages, plus the\n // injected page context, every 600-1500ms for the length of a turn.\n //\n // No merge or high-water bookkeeping is needed precisely BECAUSE the\n // floor is constant and progress is recomputed from scratch each poll.\n // A cursor that advanced would break `done` detection, since the\n // in-flight message would drop out of its own window.\n const sessionMessages = await getAssistantMessages(\n apollo,\n sandboxId,\n workspaceId,\n sessionId,\n authContext,\n 50,\n priorNewestCreatedMs\n );\n\n result = buildAssistantProgress(sessionMessages, priorNewestCreatedMs);\n patchMessage(conversationId, assistantMessageId, {\n content: sanitizeAssistantResponse(result.content),\n });\n\n // ★ The write the agent REFUSED, taken from its own tool result.\n // Without this the user approves the model's PARAGRAPH about the\n // change — written by the same model that wants the write to go\n // through, and reconciled against the payload by nothing.\n //\n // `mergeMessageMetadata`, never `patchMessage`: the latter REPLACES\n // metadata, and this message already carries `lang` and may carry the\n // voice marker. That exact mistake has shipped here before.\n if (result.pendingWrite) {\n mergeMessageMetadata(conversationId, assistantMessageId, { pendingWrite: result.pendingWrite });\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 // Fast early, backing off after — see assistantPollSchedule. This is\n // the granularity of the whole turn: it bounds how late the answer\n // appears AND how late speech can start, because auto-speak only\n // fires once a poll observes the reply completed.\n await new Promise((resolve) => setTimeout(resolve, pollDelayMs(Date.now() - pollStartedAt)));\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 '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 // ★ Any failed turn drops the readiness proof for the sandbox it used,\n // so the NEXT turn re-probes instead of trusting a cache entry that a\n // dead pod would otherwise keep alive until the TTL lapsed. This is the\n // half that makes the short-circuit above safe.\n sandboxReadiness.current.invalidate(\n useAssistantStore.getState().sandboxesByMode[selectedMode]?.sandboxId ?? null\n );\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 undefined,\n undefined,\n undefined,\n 'en'\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 // Same reason: English copy must not inherit the turn's language stamp.\n // The voice marker still has to survive though — a failed spoken turn\n // belongs to the session that asked. Without it the failure surfaced as\n // a bare \"Sorry, an error occurred\" in the typed thread with no question\n // above it, while the voice session showed nothing at all.\n // Same split as the success path, and for the same reason: rebuilding\n // `metadata` here would erase a `pendingWrite` recorded moments earlier,\n // so a turn that failed AFTER the agent refused a write would lose the\n // record of what it had been about to do.\n patchMessage(conversationId, assistantMessageId, {\n content: `Sorry, an error occurred: ${errorMessage}. Please try again.`,\n });\n mergeMessageMetadata(conversationId, assistantMessageId, {\n lang: 'en',\n ...voiceMarker(options.voiceSessionId),\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 // Without this, switching language mid-conversation keeps sending the\n // previous language's directive until something else re-creates the\n // callback.\n languageIsExplicit,\n replyLanguageCode,\n replyLanguageName,\n setBackendSessionId,\n setConversationMode,\n setConversationProcessing,\n tr,\n updateConversationStage,\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 // ★ Search the TYPED thread, not the raw array. Retry is a chat-panel\n // affordance, so on a conversation whose last turn was spoken this picked up\n // the spoken prompt and re-sent it WITHOUT `dictated` — quietly converting a\n // voice turn into a chat turn and undoing the separation everywhere else.\n const lastUserMessage = [...turns.chat].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 /**\n * The newest assistant reply, as the voice session's advance signal.\n *\n * Keyed on the message ID rather than the text: two consecutive answers can be\n * word-for-word identical, and text alone would then never advance the second\n * turn.\n */\n const latestAssistantReply = useMemo(() => {\n // ★ Only once the turn is COMPLETE. While it is in flight the pending\n // assistant message is patched with progress text — 'Starting assistant\n // environment...', 'Thinking...' — and exposing that would make the voice\n // session consume the message id, enter `speaking` on a placeholder, and\n // then be unable to advance when the real answer replaced it.\n if (activeIsProcessing) return null;\n for (let i = messages.length - 1; i >= 0; i -= 1) {\n const message = messages[i];\n if (message?.role !== 'assistant') continue;\n // ★ SPOKEN replies only. Both consumers of this value are the voice\n // session — the caption it paints and the reply it advances on — so\n // scanning the raw array let a TYPED reply that happened to complete\n // during a live session be captioned and read aloud as the answer to a\n // spoken question. Reachable without the user typing anything: a host\n // page queues work through `pendingPrompt`, which is store-driven and so\n // fires straight past the overlay.\n //\n // `start`'s id-claim was the only thing holding this shut, and it covers\n // just the reply that existed when the session opened — not one that\n // arrives mid-session.\n if (!isVoiceTurn(message)) continue;\n // Tool-activity markup is stripped so the session captions and speaks the\n // answer, not the machinery that produced it.\n const text = parseToolActivity(message.content).text.trim();\n return text ? { id: message.id, text } : null;\n }\n return null;\n }, [messages, activeIsProcessing]);\n\n /**\n * The same reply, with its Markdown markers removed, for the on-screen caption.\n *\n * ★ Deliberately a SEPARATE memo rather than a change to the one above, whose\n * `text` is not just display: it is the echo reference the recogniser compares\n * against while the answer is being spoken, and the payload of the session's\n * `reply` dispatch. Stripping it there would silently shift what counts as an\n * echo of our own voice. The audio path keeps its own transform\n * (`toSpeakableText`) — the two want genuinely different output, which is why\n * they are two functions and not one.\n */\n const voiceCaption = useMemo(\n () => (latestAssistantReply ? toCaptionText(latestAssistantReply.text) : null),\n [latestAssistantReply]\n );\n\n /**\n * The last few exchanges, for the session's on-screen transcript.\n *\n * Voice turns already go through the normal send path, so they are ordinary\n * conversation messages — this only surfaces them INSIDE the session, which\n * is what makes a second question in the same session make sense.\n */\n /**\n * What the CHAT panel shows: everything that was not spoken.\n *\n * Voice and chat share one conversation, so without this split every spoken\n * exchange appeared in the typed thread.\n */\n const chatMessages = turns.chat;\n\n const voiceTurns = useMemo(\n () =>\n // ★ SPOKEN turns only — but this conversation's, not this session's.\n //\n // It used to take the last six messages of the WHOLE conversation, so\n // opening voice on an existing thread painted typed replies: the wall of\n // raw `##` and `**` in the operator's screenshot, because the voice panel\n // renders plain text. Filtering by channel fixed that.\n //\n // What it does NOT do is scope to the current session, and two comments\n // used to claim it did. `metadata.voice` is a boolean, so a second voice\n // session sees the first one's turns. Showing the conversation's whole\n // spoken history is the more useful of the two behaviours, so the wording\n // is what changed — but a genuine session scope needs a session id on the\n // message, not a flag.\n turns.voice\n .filter((message) => message.role === 'user' || message.role === 'assistant')\n .map((message) => ({\n id: message.id,\n role: message.role as 'user' | 'assistant',\n text: parseToolActivity(message.content).text.trim(),\n // Which spoken exchange this belongs to, so the transcript can show\n // where one ended and the next began. `undefined` for turns recorded\n // before session ids existed — real history, just unattributed.\n sessionId: voiceSessionIdOf(message),\n timestamp: message.timestamp,\n }))\n .filter((turn) => turn.text.length > 0),\n [turns.voice]\n );\n\n const handleSaveTranscript = useCallback(() => {\n if (voiceTurns.length === 0) return;\n const now = new Date();\n downloadFile(\n buildVoiceTranscriptMarkdown(\n voiceTurns,\n {\n title: tr('voiceSession.transcript', 'Voice conversation'),\n savedAt: tr('voiceSession.savedAt', 'Saved'),\n session: tr('voiceSession.sessionLabel', 'Session'),\n earlier: tr('voiceSession.earlierLabel', 'Earlier'),\n you: tr('voiceSession.speakerYou', 'You'),\n assistant: tr('voiceSession.speakerAssistant', 'Assistant'),\n },\n now\n ),\n voiceTranscriptFilename(now),\n 'text/markdown'\n );\n }, [voiceTurns, tr]);\n\n /**\n * The attachment draft for the VOICE surface.\n *\n * ★ Its own instance, not the composer's. A photo taken during a spoken\n * exchange belongs to the question about to be asked aloud — not to whatever\n * half-typed message is sitting in the text box behind the overlay, and not\n * the other way round either. Two drafts, two surfaces, same rule as the turns\n * themselves.\n */\n const voiceAttachments = useAssistantAttachments();\n // A ref so `submitVoiceTurn` keeps its stable identity — `useVoiceSession`\n // deliberately does not depend on `onSubmit`, and the same idiom is already\n // used for `handleSendRef` just below.\n const voiceAttachmentsRef = useRef(voiceAttachments);\n voiceAttachmentsRef.current = voiceAttachments;\n\n const submitVoiceTurn = useCallback((text: string, voiceSessionId: string) => {\n // ★ Only the voice SESSION is unambiguously dictated. The composer's\n // microphone also produces a transcript, but the user reads and edits it in\n // the box before sending, so treating that as dictated would tell the model\n // to second-guess words the user had already approved.\n // ★★ WAIT for uploads to settle before sending.\n //\n // The composer can disable its send button while an upload runs\n // (`sendBlocker`). Voice has no button — the turn fires on a silence timer —\n // so without this a photo that is still uploading is simply absent from the\n // question it belongs to, and the assistant answers about a leaf it was never\n // shown. Worse, the upload then finishes and the photo attaches itself to the\n // NEXT, unrelated spoken question.\n //\n // Deferring is the direct analogue of grey-ing out the send button: the turn\n // goes when its attachments are ready.\n const send = () => {\n const draft = voiceAttachmentsRef.current;\n const ready = getSendableAttachments(draft.attachments);\n void handleSendRef.current(text, ready, { voiceSessionId });\n // ★ ALWAYS clear, even when nothing was ready. A leftover attachment does\n // not wait politely for a related question — it rides whatever is asked\n // next. Dropping it is visible (the chip disappears); carrying it forward\n // is not.\n draft.clear();\n };\n\n if (!voiceAttachmentsRef.current.isBusy) {\n send();\n return;\n }\n\n // Polled rather than awaited: the hook exposes `isBusy`, not a promise, and\n // the alternative is threading upload plumbing through the voice session for\n // one caller. Capped, because a cold files service retries for ~51s and a\n // spoken question must not hang on it indefinitely.\n const startedAt = Date.now();\n const poll = window.setInterval(() => {\n const stillBusy = voiceAttachmentsRef.current.isBusy;\n if (stillBusy && Date.now() - startedAt < ATTACHMENT_SETTLE_TIMEOUT_MS) return;\n window.clearInterval(poll);\n send();\n }, 200);\n }, []);\n\n const voiceSession = useVoiceSession({\n onSubmit: submitVoiceTurn,\n latestReply: latestAssistantReply,\n // The language the user SPEAKS, not the interface language — the same\n // preference the composer's dictation and the reply language already use.\n language: resolveAssistantLanguage(assistantLanguage, locale).tag,\n });\n\n /**\n * End the spoken exchange and leave a record of it in the typed thread.\n *\n * ★ The note tells the MODEL nothing, and does not need to: the client sends\n * no history, so the shared backend session already holds every spoken turn.\n * It exists so the HUMAN can see in the thread what was discussed — without\n * it the conversation continues against a page that looks empty.\n *\n * ★ Written as `role: 'system'`, which renders as a centred note. As a user\n * turn it would claim they typed it; as an assistant turn it would claim the\n * model said it. It is neither.\n */\n const handleContinueInChat = useCallback(() => {\n const conversationId = useAssistantStore.getState().activeConversationId;\n if (!conversationId || voiceTurns.length === 0) return;\n\n addMessage(conversationId, {\n id: generateId(),\n role: 'system',\n content: buildContinuedFromVoiceNote(voiceTurns, {\n intro: tr('voiceSession.continuedIntro', 'Continued from a voice conversation. You asked about:'),\n nothing: tr('voiceSession.continuedNothing', 'Continued from a voice conversation.'),\n more: (count) => tr('voiceSession.continuedMore', '…and {{count}} more', { count }),\n }),\n timestamp: new Date().toISOString(),\n // ★ No voice marker: the note belongs to the TYPED thread. That is the\n // whole point of the action — marking it would hide it in the surface the\n // user is leaving.\n });\n\n setTranscriptOpen(false);\n voiceSession.end();\n }, [voiceTurns, addMessage, tr]);\n\n // Hiding the panel must end a live voice session. The host may set `visible`\n // false WITHOUT unmounting, and an unmount-only cleanup would then leave the\n // microphone recording behind an invisible panel — a privacy problem, not\n // just a leak.\n useEffect(() => {\n if (!visible && voiceSession.active) voiceSession.end();\n }, [visible, voiceSession]);\n\n /**\n * A photo attached but never spoken does not outlive the session.\n *\n * ★ Otherwise it waits, invisibly, for the NEXT voice conversation and rides\n * along with whatever is asked then — a picture of last week's leaf answering\n * this week's question. Same rule as the turns themselves: a voice draft\n * belongs to the exchange that produced it.\n */\n useEffect(() => {\n if (voiceSession.active) return;\n // ★ UNCONDITIONAL. Guarding on `attachments.length > 0` looked like avoiding\n // pointless work and instead created the exact leak this effect prevents: a\n // photo still inside `prepareFile` (a 12MP downscale takes real time) has no\n // row yet, so the list is empty, so `clear()` was skipped — and `clear()` is\n // the only thing that bumps the epoch that cancels an in-flight prepare. The\n // file then landed in the draft AFTER its session ended and rode the next\n // one. Clearing an already-empty draft costs nothing.\n voiceAttachmentsRef.current.clear();\n }, [voiceSession.active]);\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 // `relative` so the DOCKED voice session can position itself against the\n // assistant panel rather than the viewport. Without it the docked overlay\n // would anchor to the page and cover the whole app, which is the very thing\n // docking exists to avoid.\n <div className=\"relative flex flex-1 flex-col overflow-hidden\">\n {/* Everything the voice overlay covers is made `inert` while a session is\n open. Docked, the overlay hides the transcript and composer but does\n NOT cover the page, so a full focus trap would wrongly imprison the\n user — yet leaving these focusable lets them Shift+Tab into controls\n they cannot see and operate them blind. `inert` is the precise tool:\n the page stays reachable, the covered controls do not. */}\n <div className=\"contents\" inert={voiceSession.active || undefined}>\n {/* ★ Says out loud that this thread is not showing everything the\n assistant remembers. Both surfaces share one backend session, so a\n spoken turn stays in the model's context whether or not it is drawn\n here — silence about that is what produces a reply referring to\n something the user cannot see. Hidden during a live session, where\n the overlay already IS the voice surface. */}\n {voiceTurns.length > 0 && !voiceSession.active ? (\n <AssistantSpokenTurnsNotice count={voiceTurns.length} onOpenTranscript={() => setTranscriptOpen(true)} />\n ) : null}\n\n {/* Transcript is always visible now — the old collapse-by-default accordion\n is gone; conversation history lives behind the header button instead. */}\n {chatMessages.length === 0 ? (\n <AssistantEmptyState mode={mode} onSuggestionClick={handleSuggestionClick} />\n ) : (\n <div className=\"flex min-h-0 flex-1 flex-col\">\n <AssistantMessageList\n messages={chatMessages}\n streamingMessageId={activeStreamingMessageId}\n failedMessageId={failedMessageId}\n onRetry={handleRetry}\n />\n </div>\n )}\n\n <AssistantComposer\n // ★ Ask-mode only, and enforced here rather than merely documented.\n // In `api-calls` mode the assistant WRITES to farm data behind a consent\n // gate, and BOFF-6377 (\"confirm-before-write cannot prove a human\n // approved\") is still open — a spoken \"yes, do it\" is exactly the case\n // that ticket is about. Voice control of writes is the NEXT phase, not\n // this one, so the launcher is simply absent in that mode.\n onStartVoiceSession={voiceSession.available && mode !== 'api-calls' ? voiceSession.start : undefined}\n onSend={(value, attachments) => void handleSend(value, attachments)}\n disabled={activeIsProcessing}\n placeholder={\n mode === 'api-calls'\n ? tr('chatArea.placeholderActions', 'What would you like me to do?')\n : tr('chatArea.placeholderGeneral', 'Ask HealthyBowl anything…')\n }\n mode={mode}\n writeAccessDenied={writeAccess === 'denied' && Boolean(activeModeConfig?.writeCapable)}\n availableModes={availableModes}\n onModeChange={handleModeChange}\n />\n </div>\n\n {/* Read-only, and only when no session is live — a live session mounts its\n own copy inside the overlay. Same component either way, so the two can\n never drift apart. */}\n {transcriptOpen && !voiceSession.active ? (\n <VoiceTranscriptDrawer\n turns={voiceTurns}\n onClose={() => setTranscriptOpen(false)}\n onSave={handleSaveTranscript}\n // No \"continue in chat\" here: this mount opens FROM the chat panel, so\n // the user is already where that button would take them.\n />\n ) : null}\n\n {voiceSession.active && (\n <AssistantVoiceSession\n session={voiceSession.session}\n notice={voiceSession.notice}\n capturing={voiceSession.capturing}\n interrupting={voiceSession.interrupting}\n awaitingEndpoint={voiceSession.awaitingEndpoint}\n turns={voiceTurns}\n spokenChunks={voiceSession.spokenChunks}\n attachments={voiceAttachments.attachments}\n onAttachFiles={voiceAttachments.addFiles}\n onRemoveAttachment={voiceAttachments.remove}\n onRetryAttachment={voiceAttachments.retry}\n canAttachMore={voiceAttachments.canAddMore}\n preparingAttachments={voiceAttachments.preparingCount}\n onSaveTranscript={handleSaveTranscript}\n onContinueInChat={handleContinueInChat}\n onInterrupt={voiceSession.interrupt}\n spoken={voiceCaption}\n onToggleMute={voiceSession.toggleMute}\n onEnd={voiceSession.end}\n />\n )}\n\n <AssistantApiCallsConsentDialog\n open={pendingConsentMode !== null}\n onConfirm={handleConsentConfirm}\n onCancel={handleConsentCancel}\n />\n </div>\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8EA,IAAM,KAAkD;CACtD,SAAS;CACT,WAAW;CACX,aAAa;CACb,gBAAgB;AAClB,GACM,KAA2B,MAU3B,KAA+B;AAErC,SAAS,KAAqB;CAC5B,OAAO,GAAG,KAAK,IAAI,EAAE,GAAG,KAAK,OAAO,EAAE,SAAS,EAAE,EAAE,MAAM,GAAG,CAAC;AAC/D;AAEA,SAAS,EAAuB,GAAsC;CACpE,OAAO,EAAQ,MAAM,MAAM,WAAW;AACxC;AAEA,SAAS,EAAiB,GAA6C;CACrE,QAAQ,KAAS,CAAC,GACf,QAAQ,MAAS,EAAK,SAAS,UAAU,OAAO,EAAK,QAAS,QAAQ,EACtE,KAAK,MAAS,EAAK,MAAM,KAAK,KAAK,EAAE,EACrC,OAAO,OAAO,EACd,KAAK,IAAI;AACd;AAEA,SAAS,EAAgB,GAA+C;CACtE,QAAQ,K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MAA2B;MAAM,mBAAmB;KAAwB,CAAA,IAE5E,kBAAC,OAAD;MAAK,WAAU;gBACb,kBAAC,GAAD;OACE,UAAU;OACV,oBAAoB;OACH;OACjB,SAAS;MACV,CAAA;KACE,CAAA;KAGP,kBAAC,IAAD;MAOE,qBAAqB,EAAa,aAAa,MAAS,cAAc,EAAa,QAAQ,KAAA;MAC3F,SAAS,GAAO,MAAgB,KAAK,EAAW,GAAO,CAAW;MAClE,UAAU;MACV,aACE,MAAS,cACL,EAAG,+BAA+B,+BAA+B,IACjE,EAAG,+BAA+B,2BAA2B;MAE7D;MACN,mBAAmB,OAAgB,YAAY,EAAQ,IAAkB;MACzD;MAChB,cAAc;KACf,CAAA;IACE;;GAKJ,MAAkB,CAAC,EAAa,SAC/B,kBAAC,GAAD;IACE,OAAO;IACP,eAAe,GAAkB,EAAK;IACtC,QAAQ;GAGT,CAAA,IACC;GAEH,EAAa,UACZ,kBAAC,IAAD;IACE,SAAS,EAAa;IACtB,QAAQ,EAAa;IACrB,WAAW,EAAa;IACxB,cAAc,EAAa;IAC3B,kBAAkB,EAAa;IAC/B,OAAO;IACP,cAAc,EAAa;IAC3B,aAAa,EAAiB;IAC9B,eAAe,EAAiB;IAChC,oBAAoB,EAAiB;IACrC,mBAAmB,EAAiB;IACpC,eAAe,EAAiB;IAChC,sBAAsB,EAAiB;IACvC,kBAAkB;IAClB,kBAAkB;IAClB,aAAa,EAAa;IAC1B,QAAQ;IACR,cAAc,EAAa;IAC3B,OAAO,EAAa;GACrB,CAAA;GAGH,kBAAC,GAAD;IACE,MAAM,OAAuB;IAC7B,WAAW;IACX,UAAU;GACX,CAAA;EACE;;AAET"}
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 { useI18n } from '@burdenoff/fe-libs/shared/providers/shell/I18nProvider';\nimport { resolveAssistantLanguage } from '@/config/assistantLanguages';\nimport { resolveLanguagePair } from '@/config/assistantLanguagePair';\nimport { AssistantMessageList } from './AssistantMessageList';\nimport { AssistantApiCallsConsentDialog } from './AssistantApiCallsConsentDialog';\nimport { AssistantEmptyState } from './AssistantEmptyState';\nimport { AssistantSpokenTurnsNotice } from './AssistantSpokenTurnsNotice';\nimport { VoiceTranscriptDrawer } from './voice/VoiceTranscriptDrawer';\nimport { AssistantComposer } from './composer/AssistantComposer';\nimport { AssistantVoiceSession } from './voice/AssistantVoiceSession';\nimport { parseToolActivity } from './AssistantToolActivity';\nimport { useVoiceSession } from '../../hooks/useVoiceSession';\nimport { useAssistantApiAccess } from '@/hooks/useAssistantApiAccess';\nimport { useWorkspaceWriteAccess } from '@/hooks/useWorkspaceWriteAccess';\nimport { useAssistantAttachments } from '@/hooks/useAssistantAttachments';\nimport { useConversationTurns } from '@/hooks/useConversationTurns';\nimport { useAssistantStore } from '@/store/assistantStore';\nimport {\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 { getActorId, 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 getSendableAttachments,\n toMessageAttachment,\n type AssistantAttachment,\n} from '@/utils/assistantAttachments';\nimport { isMultimodalBodyRejection, isRecoverableAssistantError } from '@/utils/assistantTransportErrors';\nimport { isTurnInFlight } from '@/utils/assistantTurnState';\nimport { useAssistantTr } from '@burdenoff/fe-libs/shared/assistant';\nimport { ASSISTANT_MODES } from '@/types/assistant';\nimport type { AssistantArtifact, AssistantConversationStatus, AssistantMode, Message } from '@/types/assistant';\nimport { pollDelayMs } from '../../utils/assistantPollSchedule';\nimport { findPendingWrite, type PendingWrite } from '../../utils/pendingWrite';\nimport { toCaptionText } from '../../utils/captionText';\nimport {\n buildContinuedFromVoiceNote,\n buildVoiceTranscriptMarkdown,\n voiceTranscriptFilename,\n} from '../../utils/voiceTranscript';\nimport { downloadFile } from '@/services/assistantExportService';\nimport { isVoiceTurn, voiceMarker, voiceSessionIdOf } from '../../utils/voiceTurnVisibility';\nimport { createReadinessTracker } from '../../utils/sandboxReadiness';\n// ★★ The SHARED credential redactor, not a local copy. The two were byte-identical:\n// the same four patterns stripping Bearer tokens, JWTs and `sk-ant-` keys from model\n// output before it renders. A redactor duplicated across repos is the worst kind of\n// duplicate — add a fifth pattern to one and the other keeps leaking, with nothing\n// failing to say so.\nimport { sanitize as sanitizeAssistantResponse } from '@burdenoff/fe-libs/shared/assistant/progress';\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 assistant: 180_000,\n 'api-calls': 180_000,\n 'vibe-plugins': 600_000,\n};\nconst DEFAULT_STREAM_BUDGET_MS = 180_000;\n\n/**\n * How long a spoken turn waits for its attachments to finish uploading.\n *\n * Long enough for a photo on a slow rural connection; short enough that a stuck\n * upload does not hold a question hostage. On timeout the turn goes without it\n * and the draft is cleared, so the miss is visible rather than deferred onto the\n * next question.\n */\nconst ATTACHMENT_SETTLE_TIMEOUT_MS = 20_000;\n\nfunction generateId(): string {\n return `${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;\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 * Identity + model of the message these tokens came from, needed to charge the\n * turn: `messageId` is half the server's idempotency hash and `model` selects the\n * per-token prices. Read from the SAME message as `tokens`, never guessed from\n * the tail of `messages` — on a session with trailing history that is a different\n * message, and mis-attributing a charge is worse than missing one.\n */\n messageId?: string;\n model?: string;\n /** A write the sandbox refused pending approval, if this turn produced one. */\n pendingWrite?: PendingWrite;\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 // ★ From the SAME message the content came from. Reaching for the last element\n // of `messages` instead is a second, different guess at which message this turn\n // produced — and on a session with trailing history it is the wrong one.\n const pendingWrite = findPendingWrite(latest.parts);\n const content = [text, ...media, ...toolProgress].filter(Boolean).join('\\n\\n') || 'Thinking...';\n\n const providerId = latest.info?.providerID;\n const modelId = latest.info?.modelID;\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 messageId: latest.info?.id,\n // \"provider/model\", matching the id shape billing's per-model price table is\n // keyed on. Omitted entirely when either half is missing — a half-formed id\n // would silently fall back to the `*default*` price and mis-cost the turn.\n ...(providerId && modelId ? { model: `${providerId}/${modelId}` } : {}),\n // ★ Read from the SAME message the content came from. Picking the last\n // element of `messages` instead would be a second, different guess at which\n // message this turn produced — and on a session with trailing history it is\n // the wrong one.\n ...(pendingWrite ? { pendingWrite } : {}),\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\n/**\n * `visible` is false when the host HIDES the panel without unmounting it, which\n * is what the supported `visible` prop does. That distinction matters here: a\n * live voice session would otherwise keep the microphone open and the silence\n * timer running behind an invisible panel.\n */\ninterface AssistantChatAreaProps {\n visible?: boolean;\n}\n\nexport const AssistantChatArea: FC<AssistantChatAreaProps> = ({ visible = true }) => {\n const tr = useAssistantTr();\n const apollo = useGatewayClient('workspace');\n const { getAccessToken, getWorkspaceToken, userId } = useAuthToken();\n const { locale } = useI18n();\n const assistantLanguage = useAssistantStore((state) => state.assistantLanguage);\n // The language the user chose to SPEAK, which is not necessarily the one the\n // interface is in — that is the whole point of the preference (BOFF-7108).\n // Named in ENGLISH deliberately: the preamble around it is English, so\n // \"Answer in Tamil.\" reads as an instruction, where a bare tag (\"ta\") invites\n // the model to answer *about* the code instead of *in* the language.\n const replyLanguage = useAssistantStore((state) => state.replyLanguage);\n const languagePair = useMemo(\n () => resolveLanguagePair(assistantLanguage, replyLanguage, locale),\n [assistantLanguage, replyLanguage, locale]\n );\n const replyLanguageName = languagePair.reply.english;\n // A stored preference is a deliberate choice; `null` is only the interface\n // language standing in as a default. The directive treats the two differently\n // — see `buildLanguagePreamble`.\n //\n // Resolved, not merely non-null: a stale persisted code from a build that\n // offered more languages is DISCARDED by `resolveAssistantLanguage`, and\n // treating that discarded value as deliberate would tell the model the user\n // had chosen the interface language on purpose — suppressing the typed-language\n // override on the strength of a preference the selector does not even show.\n // ★ Whether a HUMAN picked this reply language or it was guessed from the\n // interface — true if EITHER field was pinned, since inheriting from a\n // deliberate input choice is still deliberate. `buildLanguagePreamble` uses it\n // to suppress the \"what they wrote in wins\" clause, which would otherwise make\n // the setting inert for everyone who types rather than dictates.\n const languageIsExplicit = languagePair.replyIsExplicit;\n const replyLanguageCode = languagePair.reply.code;\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 mergeMessageMetadata,\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 // ★ One place decides which turns belong to which surface. `messages` stays\n // available for questions about the CONVERSATION (is it used at all?), but it\n // is readonly, so it cannot reach a component that draws a message list.\n const turns = useConversationTurns(activeConversation);\n const messages = turns.all;\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 /**\n * ★ A SECOND, different question — and deliberately not a second gate.\n *\n * The check above asks whether this person may USE the write mode (org scope).\n * Writes then execute at WORKSPACE scope, where a separate decision is made,\n * so an org owner could plan a change, confirm it, and only then be refused.\n * This asks the execution question up front so the warning arrives before the\n * effort rather than after it.\n *\n * It does NOT hide or disable the mode. Measured against prod on 2026-09-02,\n * workspace scopes have no roles provisioned at all, so gating on this would\n * delete Take-action from the product until an ops task lands — a far worse\n * outcome than the confusion it would fix. It self-corrects with no code\n * change the moment roles exist.\n */\n const writeAccess = useWorkspaceWriteAccess(getActorId(), getWorkspaceId() || null);\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 // Read-only transcript, reachable when NO session is live. The drawer used to\n // be mounted only inside `AssistantVoiceSession`, so pressing End destroyed the\n // only way to read back what was said.\n const [transcriptOpen, setTranscriptOpen] = useState(false);\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 /**\n * Per-sandbox record of \"last proven reachable\", so a warm sandbox is not\n * re-probed on every turn. Invalidated by any failure — see both catches.\n */\n const sandboxReadiness = useRef(createReadinessTracker());\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 the read-only\n // `assistant` mode (the default \"Ask\", available to everyone), but only AFTER\n /** The config for the mode in play — read by the reset effect and by render. */\n const activeModeConfig = useMemo(() => ASSISTANT_MODES.find((modeConfig) => modeConfig.id === mode), [mode]);\n\n // the role check resolves (so an admin's persisted api-calls mode isn't reset\n // during the brief loading window).\n useEffect(() => {\n if (apiAccessLoading) return;\n const blocked = !activeModeConfig || (activeModeConfig.requiresAdmin && !canUseApiCalls);\n if (blocked && mode !== 'assistant') {\n setMode('assistant');\n }\n }, [mode, activeModeConfig, 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 // ★ Skip a proof we already have. This ran two network waits before the\n // model saw the prompt on EVERY turn, including turns seconds after the\n // last one succeeded — a constant tax, felt most in voice where it sits\n // between the user finishing a sentence and hearing anything.\n //\n // Safe only because every failure path below invalidates: see the catch\n // here and the turn-level catch. A cache that were only ever written on\n // success would pin a dead sandbox and turn a recoverable error into a\n // loop.\n if (sandboxReadiness.current.isFresh(candidateId)) return true;\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 sandboxReadiness.current.markVerified(candidateId);\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 sandboxReadiness.current.invalidate(candidateId);\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 (\n content: string,\n attachments: AssistantAttachment[] = [],\n // ★ The live voice session's id, present only when this turn was spoken.\n // It replaced a `dictated` boolean: two fields meaning almost the same\n // thing let a turn be marked spoken while recording no session, a state\n // with no meaning that only the transcript would ever notice.\n options: { voiceSessionId?: string } = {}\n ) => {\n // Spoken-ness is now DERIVED, so it cannot disagree with the session.\n const dictated = options.voiceSessionId !== undefined;\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 // ★ `voice` marks a turn that happened in the live voice session, so the\n // chat panel can leave it out. Both surfaces share one conversation, so\n // without it every spoken exchange showed up in the typed thread.\n metadata: {\n ...(attachments.length ? { attachments: attachments.map(toMessageAttachment) } : {}),\n ...voiceMarker(options.voiceSessionId),\n },\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 // Stamped now, not read later: this is the language the reply is being\n // generated in, and the preference may have moved on by the time\n // somebody presses Listen.\n // Carries the voice marker too: a reply to a spoken question belongs to\n // the voice session, not to the typed thread.\n metadata: { lang: replyLanguageCode, ...voiceMarker(options.voiceSessionId) },\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 // Our own hard-coded copy is English regardless of what the user picked.\n // Stamping it with their language makes playback read an English quota\n // message in a Tamil voice — Latin text cannot be script-detected, so\n // this metadata is trusted absolutely.\n lang: string = replyLanguageCode\n ) => {\n // `patchMessage` REPLACES metadata rather than merging it, so anything\n // omitted here is destroyed — which is how the turn-language stamp set\n // at creation was being wiped the moment the response completed,\n // silently undoing per-message language resolution. Always re-assert it.\n //\n // ★ The voice marker was being lost the same way, and it was worse: this\n // runs on every completed turn, and the reply is only handed to the voice\n // session AFTER it runs, so NO spoken answer could ever stay a voice\n // turn. Each one jumped into the typed thread — under a question that\n // had been correctly hidden, so chat showed orphaned answers — and\n // vanished from the transcript drawer at the same instant.\n // ★ TWO calls, and the split is the point. `patchMessage` REPLACES\n // `metadata`, so rebuilding the object here silently drops every key the\n // turn added along the way. That is not hypothetical: it destroyed the\n // voice marker once (see above), and it then destroyed `pendingWrite` —\n // the poll loop recorded the refused write moments earlier and this line\n // wiped it before the card could ever render, shipping a feature that was\n // inert in production.\n //\n // Re-asserting each marker by hand is what failed twice. Merging cannot\n // fail that way: keys this turn set stay set, and the ones below still\n // win where they overlap.\n patchMessage(conversationId, assistantMessageId, {\n content: sanitizeAssistantResponse(response),\n });\n mergeMessageMetadata(conversationId, assistantMessageId, {\n lang,\n ...(artifacts?.length ? { artifacts } : {}),\n ...(artifacts?.length || sessionId || sandboxId ? { mode: selectedMode } : {}),\n ...(sessionId ? { sessionId } : {}),\n ...(sandboxId ? { sandboxId } : {}),\n ...voiceMarker(options.voiceSessionId),\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 // ★★ There is deliberately NO pre-flight AI-credit gate here.\n //\n // This block used to call `checkAssistantAiCredits` inside a try/catch\n // that surfaced the upgrade dialog on a 429 QUOTA_EXHAUSTED. The catch\n // could never run: `services/assistantApi.checkAssistantAiCredits` is a\n // documented no-op returning `Promise.resolve(true)`, so it cannot\n // reject. Thirty-four lines of code and prose described a live quota\n // gate that was structurally unreachable — the most expensive kind of\n // comment, because the next person reads it and believes HealthyBowl\n // gates on credits.\n //\n // The no-op is the RIGHT product decision, not an oversight: HB is\n // metered per input token against a Free allowance of 500, so a real\n // pre-flight gate would refuse ordinary chats. It is recorded in the\n // api adapter, where the decision belongs.\n //\n // The budget IS still enforced, downstream and for real: the wspace\n // gateway's @usage(checkQuota) on createSandbox rejects an over-quota\n // caller with a 429, and the outer catch below turns that into the\n // upgrade dialog. That path is live and reachable.\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 // …and the language directive, so the reply comes back in the user's\n // language rather than defaulting to the language of the docs the\n // model grounds on. The FE is the only layer that knows the locale —\n // it is not on the wire and `pageContext` silently drops unknown keys.\n const promptText = buildPromptForMode(\n selectedMode,\n buildPromptWithAttachments(content, attachments),\n replyLanguageName,\n languageIsExplicit,\n dictated\n );\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 const pollStartedAt = Date.now();\n while (Date.now() < timeoutAt) {\n // ★ Delta poll. `priorNewestCreatedMs` is fixed for the whole turn and\n // is already the floor `buildAssistantProgress` filters on (`>`), so\n // asking the agent for `>=` the same value returns exactly the window\n // that function keeps — and nothing else. The result is identical; what\n // changes is that this stops re-downloading 50 full messages, plus the\n // injected page context, every 600-1500ms for the length of a turn.\n //\n // No merge or high-water bookkeeping is needed precisely BECAUSE the\n // floor is constant and progress is recomputed from scratch each poll.\n // A cursor that advanced would break `done` detection, since the\n // in-flight message would drop out of its own window.\n const sessionMessages = await getAssistantMessages(\n apollo,\n sandboxId,\n workspaceId,\n sessionId,\n authContext,\n 50,\n priorNewestCreatedMs\n );\n\n result = buildAssistantProgress(sessionMessages, priorNewestCreatedMs);\n patchMessage(conversationId, assistantMessageId, {\n content: sanitizeAssistantResponse(result.content),\n });\n\n // ★ The write the agent REFUSED, taken from its own tool result.\n // Without this the user approves the model's PARAGRAPH about the\n // change — written by the same model that wants the write to go\n // through, and reconciled against the payload by nothing.\n //\n // `mergeMessageMetadata`, never `patchMessage`: the latter REPLACES\n // metadata, and this message already carries `lang` and may carry the\n // voice marker. That exact mistake has shipped here before.\n if (result.pendingWrite) {\n mergeMessageMetadata(conversationId, assistantMessageId, { pendingWrite: result.pendingWrite });\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 // Fast early, backing off after — see assistantPollSchedule. This is\n // the granularity of the whole turn: it bounds how late the answer\n // appears AND how late speech can start, because auto-speak only\n // fires once a poll observes the reply completed.\n await new Promise((resolve) => setTimeout(resolve, pollDelayMs(Date.now() - pollStartedAt)));\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 '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 turn against healthybowl.ai.credits (BOFF-7126).\n //\n // ★ The previous comment here claimed \"the gateway records it via\n // @usage(trackUsage)\". That was false: this call was a no-op stub and\n // nothing was recorded anywhere, which is how the assistant became the\n // only uncapped model spend in the product. The charge is now real and\n // happens server-side, priced from billing's per-model table.\n //\n // Still awaited before the turn is marked complete, so a rapid\n // follow-up send sees a settled balance rather than one with this\n // turn's charge still in flight. Best-effort on both sides — a metering\n // failure never blocks the answer that was already displayed.\n try {\n await reportAssistantAiTokenUsage(\n apollo,\n workspaceId,\n sessionId,\n result.messageId,\n result.model,\n result.tokens,\n authContext\n );\n notifyAiCreditsUpdated();\n } catch {\n // ignore — the charge is idempotent server-side, so a dropped\n // report is a missing datapoint, never a double charge.\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 // ★ Any failed turn drops the readiness proof for the sandbox it used,\n // so the NEXT turn re-probes instead of trusting a cache entry that a\n // dead pod would otherwise keep alive until the TTL lapsed. This is the\n // half that makes the short-circuit above safe.\n sandboxReadiness.current.invalidate(\n useAssistantStore.getState().sandboxesByMode[selectedMode]?.sandboxId ?? null\n );\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 undefined,\n undefined,\n undefined,\n 'en'\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 // Same reason: English copy must not inherit the turn's language stamp.\n // The voice marker still has to survive though — a failed spoken turn\n // belongs to the session that asked. Without it the failure surfaced as\n // a bare \"Sorry, an error occurred\" in the typed thread with no question\n // above it, while the voice session showed nothing at all.\n // Same split as the success path, and for the same reason: rebuilding\n // `metadata` here would erase a `pendingWrite` recorded moments earlier,\n // so a turn that failed AFTER the agent refused a write would lose the\n // record of what it had been about to do.\n patchMessage(conversationId, assistantMessageId, {\n content: `Sorry, an error occurred: ${errorMessage}. Please try again.`,\n });\n mergeMessageMetadata(conversationId, assistantMessageId, {\n lang: 'en',\n ...voiceMarker(options.voiceSessionId),\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 // Without this, switching language mid-conversation keeps sending the\n // previous language's directive until something else re-creates the\n // callback.\n languageIsExplicit,\n replyLanguageCode,\n replyLanguageName,\n setBackendSessionId,\n setConversationMode,\n setConversationProcessing,\n tr,\n updateConversationStage,\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 // ★ Search the TYPED thread, not the raw array. Retry is a chat-panel\n // affordance, so on a conversation whose last turn was spoken this picked up\n // the spoken prompt and re-sent it WITHOUT `dictated` — quietly converting a\n // voice turn into a chat turn and undoing the separation everywhere else.\n const lastUserMessage = [...turns.chat].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 /**\n * The newest assistant reply, as the voice session's advance signal.\n *\n * Keyed on the message ID rather than the text: two consecutive answers can be\n * word-for-word identical, and text alone would then never advance the second\n * turn.\n */\n const latestAssistantReply = useMemo(() => {\n // ★ Only once the turn is COMPLETE. While it is in flight the pending\n // assistant message is patched with progress text — 'Starting assistant\n // environment...', 'Thinking...' — and exposing that would make the voice\n // session consume the message id, enter `speaking` on a placeholder, and\n // then be unable to advance when the real answer replaced it.\n if (activeIsProcessing) return null;\n for (let i = messages.length - 1; i >= 0; i -= 1) {\n const message = messages[i];\n if (message?.role !== 'assistant') continue;\n // ★ SPOKEN replies only. Both consumers of this value are the voice\n // session — the caption it paints and the reply it advances on — so\n // scanning the raw array let a TYPED reply that happened to complete\n // during a live session be captioned and read aloud as the answer to a\n // spoken question. Reachable without the user typing anything: a host\n // page queues work through `pendingPrompt`, which is store-driven and so\n // fires straight past the overlay.\n //\n // `start`'s id-claim was the only thing holding this shut, and it covers\n // just the reply that existed when the session opened — not one that\n // arrives mid-session.\n if (!isVoiceTurn(message)) continue;\n // Tool-activity markup is stripped so the session captions and speaks the\n // answer, not the machinery that produced it.\n const text = parseToolActivity(message.content).text.trim();\n return text ? { id: message.id, text } : null;\n }\n return null;\n }, [messages, activeIsProcessing]);\n\n /**\n * The same reply, with its Markdown markers removed, for the on-screen caption.\n *\n * ★ Deliberately a SEPARATE memo rather than a change to the one above, whose\n * `text` is not just display: it is the echo reference the recogniser compares\n * against while the answer is being spoken, and the payload of the session's\n * `reply` dispatch. Stripping it there would silently shift what counts as an\n * echo of our own voice. The audio path keeps its own transform\n * (`toSpeakableText`) — the two want genuinely different output, which is why\n * they are two functions and not one.\n */\n const voiceCaption = useMemo(\n () => (latestAssistantReply ? toCaptionText(latestAssistantReply.text) : null),\n [latestAssistantReply]\n );\n\n /**\n * The last few exchanges, for the session's on-screen transcript.\n *\n * Voice turns already go through the normal send path, so they are ordinary\n * conversation messages — this only surfaces them INSIDE the session, which\n * is what makes a second question in the same session make sense.\n */\n /**\n * What the CHAT panel shows: everything that was not spoken.\n *\n * Voice and chat share one conversation, so without this split every spoken\n * exchange appeared in the typed thread.\n */\n const chatMessages = turns.chat;\n\n const voiceTurns = useMemo(\n () =>\n // ★ SPOKEN turns only — but this conversation's, not this session's.\n //\n // It used to take the last six messages of the WHOLE conversation, so\n // opening voice on an existing thread painted typed replies: the wall of\n // raw `##` and `**` in the operator's screenshot, because the voice panel\n // renders plain text. Filtering by channel fixed that.\n //\n // What it does NOT do is scope to the current session, and two comments\n // used to claim it did. `metadata.voice` is a boolean, so a second voice\n // session sees the first one's turns. Showing the conversation's whole\n // spoken history is the more useful of the two behaviours, so the wording\n // is what changed — but a genuine session scope needs a session id on the\n // message, not a flag.\n turns.voice\n .filter((message) => message.role === 'user' || message.role === 'assistant')\n .map((message) => ({\n id: message.id,\n role: message.role as 'user' | 'assistant',\n text: parseToolActivity(message.content).text.trim(),\n // Which spoken exchange this belongs to, so the transcript can show\n // where one ended and the next began. `undefined` for turns recorded\n // before session ids existed — real history, just unattributed.\n sessionId: voiceSessionIdOf(message),\n timestamp: message.timestamp,\n }))\n .filter((turn) => turn.text.length > 0),\n [turns.voice]\n );\n\n const handleSaveTranscript = useCallback(() => {\n if (voiceTurns.length === 0) return;\n const now = new Date();\n downloadFile(\n buildVoiceTranscriptMarkdown(\n voiceTurns,\n {\n title: tr('voiceSession.transcript', 'Voice conversation'),\n savedAt: tr('voiceSession.savedAt', 'Saved'),\n session: tr('voiceSession.sessionLabel', 'Session'),\n earlier: tr('voiceSession.earlierLabel', 'Earlier'),\n you: tr('voiceSession.speakerYou', 'You'),\n assistant: tr('voiceSession.speakerAssistant', 'Assistant'),\n },\n now\n ),\n voiceTranscriptFilename(now),\n 'text/markdown'\n );\n }, [voiceTurns, tr]);\n\n /**\n * The attachment draft for the VOICE surface.\n *\n * ★ Its own instance, not the composer's. A photo taken during a spoken\n * exchange belongs to the question about to be asked aloud — not to whatever\n * half-typed message is sitting in the text box behind the overlay, and not\n * the other way round either. Two drafts, two surfaces, same rule as the turns\n * themselves.\n */\n const voiceAttachments = useAssistantAttachments();\n // A ref so `submitVoiceTurn` keeps its stable identity — `useVoiceSession`\n // deliberately does not depend on `onSubmit`, and the same idiom is already\n // used for `handleSendRef` just below.\n const voiceAttachmentsRef = useRef(voiceAttachments);\n voiceAttachmentsRef.current = voiceAttachments;\n\n const submitVoiceTurn = useCallback((text: string, voiceSessionId: string) => {\n // ★ Only the voice SESSION is unambiguously dictated. The composer's\n // microphone also produces a transcript, but the user reads and edits it in\n // the box before sending, so treating that as dictated would tell the model\n // to second-guess words the user had already approved.\n // ★★ WAIT for uploads to settle before sending.\n //\n // The composer can disable its send button while an upload runs\n // (`sendBlocker`). Voice has no button — the turn fires on a silence timer —\n // so without this a photo that is still uploading is simply absent from the\n // question it belongs to, and the assistant answers about a leaf it was never\n // shown. Worse, the upload then finishes and the photo attaches itself to the\n // NEXT, unrelated spoken question.\n //\n // Deferring is the direct analogue of grey-ing out the send button: the turn\n // goes when its attachments are ready.\n const send = () => {\n const draft = voiceAttachmentsRef.current;\n const ready = getSendableAttachments(draft.attachments);\n void handleSendRef.current(text, ready, { voiceSessionId });\n // ★ ALWAYS clear, even when nothing was ready. A leftover attachment does\n // not wait politely for a related question — it rides whatever is asked\n // next. Dropping it is visible (the chip disappears); carrying it forward\n // is not.\n draft.clear();\n };\n\n if (!voiceAttachmentsRef.current.isBusy) {\n send();\n return;\n }\n\n // Polled rather than awaited: the hook exposes `isBusy`, not a promise, and\n // the alternative is threading upload plumbing through the voice session for\n // one caller. Capped, because a cold files service retries for ~51s and a\n // spoken question must not hang on it indefinitely.\n const startedAt = Date.now();\n const poll = window.setInterval(() => {\n const stillBusy = voiceAttachmentsRef.current.isBusy;\n if (stillBusy && Date.now() - startedAt < ATTACHMENT_SETTLE_TIMEOUT_MS) return;\n window.clearInterval(poll);\n send();\n }, 200);\n }, []);\n\n const voiceSession = useVoiceSession({\n onSubmit: submitVoiceTurn,\n latestReply: latestAssistantReply,\n // The language the user SPEAKS, not the interface language — the same\n // preference the composer's dictation and the reply language already use.\n language: resolveAssistantLanguage(assistantLanguage, locale).tag,\n });\n\n /**\n * End the spoken exchange and leave a record of it in the typed thread.\n *\n * ★ The note tells the MODEL nothing, and does not need to: the client sends\n * no history, so the shared backend session already holds every spoken turn.\n * It exists so the HUMAN can see in the thread what was discussed — without\n * it the conversation continues against a page that looks empty.\n *\n * ★ Written as `role: 'system'`, which renders as a centred note. As a user\n * turn it would claim they typed it; as an assistant turn it would claim the\n * model said it. It is neither.\n */\n const handleContinueInChat = useCallback(() => {\n const conversationId = useAssistantStore.getState().activeConversationId;\n if (!conversationId || voiceTurns.length === 0) return;\n\n addMessage(conversationId, {\n id: generateId(),\n role: 'system',\n content: buildContinuedFromVoiceNote(voiceTurns, {\n intro: tr('voiceSession.continuedIntro', 'Continued from a voice conversation. You asked about:'),\n nothing: tr('voiceSession.continuedNothing', 'Continued from a voice conversation.'),\n more: (count) => tr('voiceSession.continuedMore', '…and {{count}} more', { count }),\n }),\n timestamp: new Date().toISOString(),\n // ★ No voice marker: the note belongs to the TYPED thread. That is the\n // whole point of the action — marking it would hide it in the surface the\n // user is leaving.\n });\n\n setTranscriptOpen(false);\n voiceSession.end();\n }, [voiceTurns, addMessage, tr]);\n\n // Hiding the panel must end a live voice session. The host may set `visible`\n // false WITHOUT unmounting, and an unmount-only cleanup would then leave the\n // microphone recording behind an invisible panel — a privacy problem, not\n // just a leak.\n useEffect(() => {\n if (!visible && voiceSession.active) voiceSession.end();\n }, [visible, voiceSession]);\n\n /**\n * A photo attached but never spoken does not outlive the session.\n *\n * ★ Otherwise it waits, invisibly, for the NEXT voice conversation and rides\n * along with whatever is asked then — a picture of last week's leaf answering\n * this week's question. Same rule as the turns themselves: a voice draft\n * belongs to the exchange that produced it.\n */\n useEffect(() => {\n if (voiceSession.active) return;\n // ★ UNCONDITIONAL. Guarding on `attachments.length > 0` looked like avoiding\n // pointless work and instead created the exact leak this effect prevents: a\n // photo still inside `prepareFile` (a 12MP downscale takes real time) has no\n // row yet, so the list is empty, so `clear()` was skipped — and `clear()` is\n // the only thing that bumps the epoch that cancels an in-flight prepare. The\n // file then landed in the draft AFTER its session ended and rode the next\n // one. Clearing an already-empty draft costs nothing.\n voiceAttachmentsRef.current.clear();\n }, [voiceSession.active]);\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 // `relative` so the DOCKED voice session can position itself against the\n // assistant panel rather than the viewport. Without it the docked overlay\n // would anchor to the page and cover the whole app, which is the very thing\n // docking exists to avoid.\n <div className=\"relative flex flex-1 flex-col overflow-hidden\">\n {/* Everything the voice overlay covers is made `inert` while a session is\n open. Docked, the overlay hides the transcript and composer but does\n NOT cover the page, so a full focus trap would wrongly imprison the\n user — yet leaving these focusable lets them Shift+Tab into controls\n they cannot see and operate them blind. `inert` is the precise tool:\n the page stays reachable, the covered controls do not. */}\n <div className=\"contents\" inert={voiceSession.active || undefined}>\n {/* ★ Says out loud that this thread is not showing everything the\n assistant remembers. Both surfaces share one backend session, so a\n spoken turn stays in the model's context whether or not it is drawn\n here — silence about that is what produces a reply referring to\n something the user cannot see. Hidden during a live session, where\n the overlay already IS the voice surface. */}\n {voiceTurns.length > 0 && !voiceSession.active ? (\n <AssistantSpokenTurnsNotice count={voiceTurns.length} onOpenTranscript={() => setTranscriptOpen(true)} />\n ) : null}\n\n {/* Transcript is always visible now — the old collapse-by-default accordion\n is gone; conversation history lives behind the header button instead. */}\n {chatMessages.length === 0 ? (\n <AssistantEmptyState mode={mode} onSuggestionClick={handleSuggestionClick} />\n ) : (\n <div className=\"flex min-h-0 flex-1 flex-col\">\n <AssistantMessageList\n messages={chatMessages}\n streamingMessageId={activeStreamingMessageId}\n failedMessageId={failedMessageId}\n onRetry={handleRetry}\n />\n </div>\n )}\n\n <AssistantComposer\n // ★ Ask-mode only, and enforced here rather than merely documented.\n // In `api-calls` mode the assistant WRITES to farm data behind a consent\n // gate, and BOFF-6377 (\"confirm-before-write cannot prove a human\n // approved\") is still open — a spoken \"yes, do it\" is exactly the case\n // that ticket is about. Voice control of writes is the NEXT phase, not\n // this one, so the launcher is simply absent in that mode.\n onStartVoiceSession={voiceSession.available && mode !== 'api-calls' ? voiceSession.start : undefined}\n onSend={(value, attachments) => void handleSend(value, attachments)}\n disabled={activeIsProcessing}\n placeholder={\n mode === 'api-calls'\n ? tr('chatArea.placeholderActions', 'What would you like me to do?')\n : tr('chatArea.placeholderGeneral', 'Ask HealthyBowl anything…')\n }\n mode={mode}\n writeAccessDenied={writeAccess === 'denied' && Boolean(activeModeConfig?.writeCapable)}\n availableModes={availableModes}\n onModeChange={handleModeChange}\n />\n </div>\n\n {/* Read-only, and only when no session is live — a live session mounts its\n own copy inside the overlay. Same component either way, so the two can\n never drift apart. */}\n {transcriptOpen && !voiceSession.active ? (\n <VoiceTranscriptDrawer\n turns={voiceTurns}\n onClose={() => setTranscriptOpen(false)}\n onSave={handleSaveTranscript}\n // No \"continue in chat\" here: this mount opens FROM the chat panel, so\n // the user is already where that button would take them.\n />\n ) : null}\n\n {voiceSession.active && (\n <AssistantVoiceSession\n session={voiceSession.session}\n notice={voiceSession.notice}\n capturing={voiceSession.capturing}\n interrupting={voiceSession.interrupting}\n awaitingEndpoint={voiceSession.awaitingEndpoint}\n turns={voiceTurns}\n spokenChunks={voiceSession.spokenChunks}\n attachments={voiceAttachments.attachments}\n onAttachFiles={voiceAttachments.addFiles}\n onRemoveAttachment={voiceAttachments.remove}\n onRetryAttachment={voiceAttachments.retry}\n canAttachMore={voiceAttachments.canAddMore}\n preparingAttachments={voiceAttachments.preparingCount}\n onSaveTranscript={handleSaveTranscript}\n onContinueInChat={handleContinueInChat}\n onInterrupt={voiceSession.interrupt}\n spoken={voiceCaption}\n onToggleMute={voiceSession.toggleMute}\n onEnd={voiceSession.end}\n />\n )}\n\n <AssistantApiCallsConsentDialog\n open={pendingConsentMode !== null}\n onConfirm={handleConsentConfirm}\n onCancel={handleConsentCancel}\n />\n </div>\n );\n};\n"],"mappings":";;;;;;;;;;;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