@burdenoff/microfe-healthybowl 2026.729.1 → 2026.731.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -23,6 +23,7 @@ import { getAssistantMedia as k } from "@burdenoff/fe-libs/shared/assistant";
23
23
  //#region src/components/assistant/AssistantChatArea.tsx
24
24
  var he = {
25
25
  general: 18e4,
26
+ assistant: 18e4,
26
27
  "api-calls": 18e4,
27
28
  "vibe-plugins": 6e5
28
29
  }, ge = 18e4;
@@ -74,7 +75,7 @@ var N = () => {
74
75
  E(() => {
75
76
  if (je) return;
76
77
  let e = y.find((e) => e.id === F);
77
- (!e || e.requiresAdmin && !J) && F !== "general" && I("general");
78
+ (!e || e.requiresAdmin && !J) && F !== "assistant" && I("assistant");
78
79
  }, [
79
80
  F,
80
81
  J,
@@ -1 +1 @@
1
- {"version":3,"file":"AssistantChatArea.js","names":[],"sources":["../../../src/components/assistant/AssistantChatArea.tsx"],"sourcesContent":["import { useCallback, useEffect, useMemo, useRef, useState, type FC } from 'react';\nimport { useGatewayClient } from '@burdenoff/fe-libs/shared/graphql';\nimport { useAuthToken } from '@burdenoff/fe-libs/shared/providers/shell';\nimport { AssistantMessageList } from './AssistantMessageList';\nimport { AssistantApiCallsConsentDialog } from './AssistantApiCallsConsentDialog';\nimport { AssistantEmptyState } from './AssistantEmptyState';\nimport { AssistantComposer } from './composer/AssistantComposer';\nimport { useAssistantApiAccess } from '@/hooks/useAssistantApiAccess';\nimport { useAssistantStore } from '@/store/assistantStore';\nimport {\n checkAssistantAiCredits,\n createAssistantSandbox,\n createAssistantSession,\n extendAssistantSandboxTTL,\n findExistingSandbox,\n getAssistantArtifacts,\n getAssistantMessages,\n getAssistantSession,\n reportAssistantAiTokenUsage,\n sendAssistantPromptAsync,\n waitForAssistantServiceReady,\n waitForSandboxReady,\n type AssistantRawMessage,\n type AssistantSandboxAuthContext,\n} from '@/services/assistantApi';\nimport { getAssistantMedia } from '@burdenoff/fe-libs/shared/assistant';\nimport { gatherPageContext } from '@/utils/pageContext';\nimport { getOrganizationId, getWorkspaceId } from '@/utils/assistantContext';\nimport { dispatchAssistantQuotaExhausted, notifyAiCreditsUpdated } from '@/utils/aiCredits';\nimport { isQuotaExhaustedError } from '@/utils/quotaUtils';\nimport { buildPromptForMode } from '@/utils/assistantPrompt';\nimport {\n buildPromptParts,\n buildPromptWithAttachments,\n countInlineImageCandidates,\n countInlinedImageParts,\n toMessageAttachment,\n type AssistantAttachment,\n} from '@/utils/assistantAttachments';\nimport { isMultimodalBodyRejection, isRecoverableAssistantError } from '@/utils/assistantTransportErrors';\nimport { isTurnInFlight } from '@/utils/assistantTurnState';\nimport { useTr } from '../../shared/hooks/useTr';\nimport { ASSISTANT_MODES } from '@/types/assistant';\nimport type { AssistantArtifact, AssistantConversationStatus, AssistantMode, Message } from '@/types/assistant';\n\n// How long the client streams progress before giving up on a turn. Chat replies\n// (general / api-calls) finish in seconds; a vibe-plugins build is a multi-step\n// pipeline (read docs → scaffold → bun install → bun build → checklist) that runs\n// for minutes, so it gets a much larger budget. The sandbox TTL is auto-extended\n// every 30s during the poll loop, so a longer budget never outlives the sandbox.\nconst STREAM_BUDGET_MS: Record<AssistantMode, number> = {\n general: 180_000,\n 'api-calls': 180_000,\n 'vibe-plugins': 600_000,\n};\nconst DEFAULT_STREAM_BUDGET_MS = 180_000;\n\nfunction generateId(): string {\n return `${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;\n}\n\nfunction sanitizeAssistantResponse(response: string): string {\n return response\n .replace(/(Authorization\\s*:\\s*Bearer\\s+)[^\\s\\n]+/gi, '$1[REDACTED]')\n .replace(/(X-Workspace-Authorization\\s*:\\s*Bearer\\s+)[^\\s\\n]+/gi, '$1[REDACTED]')\n .replace(/\\beyJ[A-Za-z0-9_-]+\\.[A-Za-z0-9._-]+\\.[A-Za-z0-9._-]+\\b/g, '[REDACTED_JWT]')\n .replace(/\\bsk-ant-[A-Za-z0-9-]+\\b/g, '[REDACTED_API_KEY]');\n}\n\nfunction getRawMessageCreatedAt(message: AssistantRawMessage): number {\n return message.info?.time?.created ?? 0;\n}\n\nfunction getAssistantText(parts: AssistantRawMessage['parts']): string {\n return (parts ?? [])\n .filter((part) => part.type === 'text' && typeof part.text === 'string')\n .map((part) => part.text?.trim() ?? '')\n .filter(Boolean)\n .join('\\n');\n}\n\nfunction getToolProgress(parts: AssistantRawMessage['parts']): string[] {\n return (parts ?? [])\n .filter((part) => part.type === 'tool' && part.tool)\n .map((part) => {\n const status = part.state?.status ?? 'running';\n const tool = part.tool ?? 'tool';\n if (status === 'completed') return `Completed: ${tool}`;\n if (status === 'failed') return `Failed: ${tool}`;\n return `Running: ${tool}`;\n });\n}\n\nfunction buildAssistantProgress(\n messages: AssistantRawMessage[],\n // The `created` timestamp (sandbox clock) of the newest message that already\n // existed in this session BEFORE the prompt was sent. This turn's reply is the\n // assistant message created strictly after it. Crucially this stays WITHIN the\n // sandbox clock domain: the previous code compared the sandbox-stamped\n // `created` against the browser wall-clock (Date#now), so a reply stamped at\n // prompt-time was silently dropped whenever the sandbox clock lagged the\n // browser — the turn then hung on \"Thinking...\" until the stream budget\n // elapsed. A sandbox-domain floor is immune to clock skew and correct for both\n // fresh and reused (per-conversation) sessions, with no message-window gap.\n priorNewestCreatedMs: number\n): {\n content: string;\n done: boolean;\n tokens?: { input: number; output: number };\n} {\n const relevant = messages\n .filter((message) => message.info?.role === 'assistant' && getRawMessageCreatedAt(message) > priorNewestCreatedMs)\n .sort((left, right) => getRawMessageCreatedAt(left) - getRawMessageCreatedAt(right));\n\n if (relevant.length === 0) {\n return { content: 'Thinking...', done: false };\n }\n\n const latest = relevant[relevant.length - 1]!;\n const text = getAssistantText(latest.parts);\n // Inbound image/file parts, rendered to markdown by the shared helper (which\n // escapes the label and allowlists the protocol — this is model output).\n // Without this, HealthyBowl — the one product that SENDS parts — could not\n // read one back: a media-bearing reply would never satisfy `done` and the\n // turn would poll to a false timeout.\n const media = getAssistantMedia(latest.parts);\n const toolProgress = getToolProgress(latest.parts);\n const content = [text, ...media, ...toolProgress].filter(Boolean).join('\\n\\n') || 'Thinking...';\n\n return {\n content,\n done: Boolean(latest.info?.time?.completed) && (Boolean(text) || media.length > 0 || toolProgress.length > 0),\n tokens: latest.info?.tokens,\n };\n}\n\nfunction getConversationStatusMessage(status: AssistantConversationStatus): string {\n switch (status) {\n case 'provisioning':\n return 'Starting assistant environment...';\n case 'connecting':\n return 'Connecting to assistant...';\n case 'streaming':\n return 'Thinking...';\n default:\n return '';\n }\n}\n\nexport const AssistantChatArea: FC = () => {\n const tr = useTr();\n const apollo = useGatewayClient('workspace');\n const { getAccessToken, getWorkspaceToken, userId } = useAuthToken();\n\n const {\n conversations,\n activeConversationId,\n mode,\n processingByConversationId,\n setMode,\n setConversationMode,\n setActiveConversation,\n createConversation,\n addMessage,\n updateMessage,\n patchMessage,\n setConversationProcessing,\n clearConversationProcessing,\n setBackendSessionId,\n clearBackendSessionId,\n setSandbox,\n clearSandbox,\n acknowledgeApiCalls,\n } = useAssistantStore();\n\n const activeConversation = conversations.find((conversation) => conversation.id === activeConversationId);\n const messages = activeConversation?.messages ?? [];\n const activeProcessing = activeConversationId ? processingByConversationId[activeConversationId] : undefined;\n // Only while the turn is genuinely in flight. `messageId` outlives the turn\n // (setConversationProcessing keeps it on 'complete'/'error'), so keying off it\n // alone left the transcript's aria-busy latched true forever and screen\n // readers stopped announcing new replies.\n const activeIsProcessing = isTurnInFlight(activeProcessing?.status);\n const activeStreamingMessageId = activeIsProcessing ? (activeProcessing?.messageId ?? null) : null;\n // The assistant message whose turn ended in an error — drives the Retry\n // affordance in the transcript.\n const failedMessageId = activeProcessing?.status === 'error' ? activeProcessing.messageId : null;\n\n // ── api-calls (write) mode gating ──────────────────────────────────\n // Only a global Owner/Admin may use api-calls (it mints an OAuth app under the\n // caller identity). Re-read the org scope every render (a cheap localStorage\n // read) so the admin gate reacts to an org switch without the panel\n // remounting; the value is a stable string, so useAssistantApiAccess only\n // re-fetches myRoles when the org actually changes. An empty scope simply\n // hides the mode (it could not provision the sandbox anyway).\n const apiCallsScopeId = getOrganizationId();\n const { canUseApiCalls, loading: apiAccessLoading } = useAssistantApiAccess(apiCallsScopeId);\n const availableModes = useMemo(\n () => ASSISTANT_MODES.filter((modeConfig) => !modeConfig.requiresAdmin || canUseApiCalls),\n [canUseApiCalls]\n );\n\n // Target mode awaiting the one-time consent dialog (null = dialog closed).\n const [pendingConsentMode, setPendingConsentMode] = useState<AssistantMode | null>(null);\n\n // Full attachment payload of the last send, kept so Retry can replay it\n // byte-for-byte (see handleRetry).\n const lastSentAttachmentsRef = useRef<Record<string, AssistantAttachment[]>>({});\n\n // Conversations with a turn already dispatched. Synchronous, unlike the store\n // — see the re-entry guard in handleSend for why that matters.\n const inFlightSendsRef = useRef<Set<string>>(new Set());\n\n // If the active mode is no longer permitted — a non-admin with a persisted\n // api-calls mode, or the master flag turned off — fall back to general, but\n // only AFTER the role check resolves (so an admin's persisted api-calls mode\n // isn't reset during the brief loading window).\n useEffect(() => {\n if (apiAccessLoading) return;\n const activeModeConfig = ASSISTANT_MODES.find((modeConfig) => modeConfig.id === mode);\n const blocked = !activeModeConfig || (activeModeConfig.requiresAdmin && !canUseApiCalls);\n if (blocked && mode !== 'general') {\n setMode('general');\n }\n }, [mode, canUseApiCalls, apiAccessLoading, setMode]);\n\n const updateConversationStage = useCallback(\n (conversationId: string, assistantMessageId: string, status: AssistantConversationStatus, content?: string) => {\n setConversationProcessing(conversationId, status, assistantMessageId, null);\n if (content) {\n updateMessage(conversationId, assistantMessageId, content);\n } else {\n updateMessage(conversationId, assistantMessageId, getConversationStatusMessage(status));\n }\n },\n [setConversationProcessing, updateMessage]\n );\n\n const ensureAssistantRuntime = useCallback(\n async (\n conversationId: string,\n assistantMessageId: string,\n currentMode: AssistantMode,\n workspaceId: string,\n authContext: AssistantSandboxAuthContext\n ): Promise<{ sandboxId: string; sessionId: string }> => {\n let currentSandboxId = useAssistantStore.getState().sandboxesByMode[currentMode]?.sandboxId ?? null;\n\n // Validate that a candidate sandbox (remembered locally or found running on\n // the server) is actually reachable before we reuse it. A sandbox can expire\n // (ttlSeconds) or have its backend pod reclaimed while still being briefly\n // reported RUNNING; proxying to such a dead pod fails with a terminal state\n // (\"Backend resource no longer exists\") or a permanent 502 cf-proxy timeout.\n // Returns true only when the in-sandbox agent responds; false means stale.\n const ensureSandboxReachable = async (candidateId: string): Promise<boolean> => {\n try {\n await waitForSandboxReady(apollo, candidateId, workspaceId, authContext, 300_000, (message) =>\n updateConversationStage(conversationId, assistantMessageId, 'provisioning', message)\n );\n await waitForAssistantServiceReady(apollo, candidateId, workspaceId, authContext, 90_000, (message) =>\n updateConversationStage(conversationId, assistantMessageId, 'connecting', message)\n );\n return true;\n } catch {\n // Stale/expired sandbox — drop it so we provision a fresh one below\n // instead of surfacing \"Internal server error\" to the user.\n return false;\n }\n };\n\n // 1) Try the locally-remembered sandbox, then 2) any running one on the\n // server. Each is only kept if it's actually reachable.\n if (currentSandboxId) {\n setSandbox(currentMode, currentSandboxId, 'provisioning');\n updateConversationStage(conversationId, assistantMessageId, 'provisioning', 'Reusing assistant environment...');\n if (!(await ensureSandboxReachable(currentSandboxId))) {\n setSandbox(currentMode, null, 'provisioning');\n currentSandboxId = null;\n }\n }\n\n if (!currentSandboxId) {\n updateConversationStage(\n conversationId,\n assistantMessageId,\n 'provisioning',\n 'Looking for existing environment...'\n );\n const existingId = await findExistingSandbox(apollo, workspaceId, currentMode, authContext);\n\n if (existingId) {\n setSandbox(currentMode, existingId, 'provisioning');\n updateConversationStage(\n conversationId,\n assistantMessageId,\n 'provisioning',\n 'Reusing assistant environment...'\n );\n if (await ensureSandboxReachable(existingId)) {\n currentSandboxId = existingId;\n } else {\n setSandbox(currentMode, null, 'provisioning');\n }\n }\n }\n\n // 3) No reusable, reachable sandbox — provision a fresh one.\n if (!currentSandboxId) {\n if (currentMode === 'api-calls' && !getAccessToken()) {\n throw new Error('API Calls mode requires an authenticated session. Please sign in again.');\n }\n\n updateConversationStage(\n conversationId,\n assistantMessageId,\n 'provisioning',\n 'Starting assistant environment...'\n );\n setSandbox(currentMode, null, 'provisioning');\n currentSandboxId = await createAssistantSandbox(apollo, currentMode, workspaceId, authContext);\n\n setSandbox(currentMode, currentSandboxId, 'provisioning');\n await waitForSandboxReady(apollo, currentSandboxId, workspaceId, authContext, 300_000, (message) =>\n updateConversationStage(conversationId, assistantMessageId, 'provisioning', message)\n );\n await waitForAssistantServiceReady(apollo, currentSandboxId, workspaceId, authContext, 90_000, (message) =>\n updateConversationStage(conversationId, assistantMessageId, 'connecting', message)\n );\n }\n\n setSandbox(currentMode, currentSandboxId, 'running');\n\n let sessionId =\n useAssistantStore.getState().conversations.find((conversation) => conversation.id === conversationId)\n ?.backendSessionId ?? null;\n\n if (sessionId) {\n try {\n const session = await getAssistantSession(apollo, currentSandboxId, workspaceId, sessionId, authContext);\n if (session.mode !== currentMode) {\n throw new Error(`Session mode mismatch: expected ${currentMode}, received ${session.mode}`);\n }\n } catch {\n clearBackendSessionId(conversationId);\n sessionId = null;\n }\n }\n\n if (!sessionId) {\n updateConversationStage(conversationId, assistantMessageId, 'connecting', 'Preparing session...');\n const result = await createAssistantSession(apollo, currentSandboxId, workspaceId, currentMode, authContext);\n sessionId = result.sessionId;\n setBackendSessionId(conversationId, sessionId);\n }\n\n return {\n sandboxId: currentSandboxId,\n sessionId,\n };\n },\n [apollo, clearBackendSessionId, getAccessToken, setBackendSessionId, setSandbox, updateConversationStage]\n );\n\n const handleSend = useCallback(\n async (content: string, attachments: AssistantAttachment[] = []) => {\n // Only block re-entry while a turn is genuinely in-flight. Earlier code\n // checked for *any* entry in the map, which stuck around as `complete`\n // / `error` after the first turn — making every subsequent message\n // silently disappear (the input cleared but handleSend bailed before\n // adding the user message to the conversation).\n //\n // The store is read LIVE, and that is what makes the guard work. The\n // render-captured `processingByConversationId` is stale by construction —\n // the click that starts a turn and the click that must be rejected can\n // belong to the same render. Reading `activeConversationId` live matters\n // for the same reason: on two racing first-ever sends, the second must see\n // the conversation the first one created a moment ago.\n //\n // Pairs with the synchronous `setConversationProcessing` below: because\n // the status is written before this function ever awaits, a second call —\n // however soon it arrives — always observes 'provisioning'.\n const storeAtEntry = useAssistantStore.getState();\n const guardConversationId = storeAtEntry.activeConversationId ?? activeConversationId;\n if (guardConversationId) {\n if (isTurnInFlight(storeAtEntry.processingByConversationId[guardConversationId]?.status)) return;\n // Second lock, in case a future change moves the status write later:\n // this one cannot be cleared by anything but the turn's own `finally`.\n // Deliberately per-conversation — a global key would keep blocking\n // after the conversation it belonged to was deleted mid-turn, and then\n // silently swallow every subsequent send.\n if (inFlightSendsRef.current.has(guardConversationId)) return;\n }\n\n const selectedMode = storeAtEntry.mode;\n let conversationId = activeConversationId;\n const currentConversation = conversationId\n ? useAssistantStore.getState().conversations.find((conversation) => conversation.id === conversationId)\n : undefined;\n\n if (!conversationId) {\n conversationId = createConversation(undefined, selectedMode);\n } else if (\n currentConversation &&\n currentConversation.mode !== selectedMode &&\n (currentConversation.messages.length > 0 || currentConversation.backendSessionId)\n ) {\n conversationId = createConversation(undefined, selectedMode);\n } else if (currentConversation && currentConversation.mode !== selectedMode) {\n setConversationMode(conversationId, selectedMode);\n }\n\n if (!conversationId) return;\n\n // Keyed by conversation: the ref outlives a conversation switch, and a\n // single global slot meant Retry in one thread replayed another thread's\n // photo onto it.\n lastSentAttachmentsRef.current[conversationId] = attachments;\n\n const workspaceId = getWorkspaceId();\n const authContext: AssistantSandboxAuthContext = {\n accessToken: getAccessToken(),\n workspaceToken: getWorkspaceToken(),\n userId,\n organizationId: getOrganizationId(),\n };\n\n const userMessage: Message = {\n id: generateId(),\n role: 'user',\n content,\n timestamp: new Date().toISOString(),\n // Slim descriptors only — the bubble re-resolves thumbnails from the\n // file id, so the persisted conversation stays small.\n metadata: attachments.length ? { attachments: attachments.map(toMessageAttachment) } : undefined,\n };\n addMessage(conversationId, userMessage);\n\n const assistantMessageId = generateId();\n addMessage(conversationId, {\n id: assistantMessageId,\n role: 'assistant',\n content: '',\n timestamp: new Date().toISOString(),\n });\n\n // Mark the turn in-flight in the STORE right now, synchronously.\n //\n // Until this line the first status write happened inside\n // `ensureAssistantRuntime`, i.e. one await later. During that window\n // `activeIsProcessing` was false and `failedMessageId` still pointed at\n // the PREVIOUS failure — so the composer stayed enabled and, worse, the\n // Retry button (which has no `disabled` of its own) stayed mounted and\n // clickable on top of a turn that had already started.\n //\n // Status only, deliberately no stage copy: `ensureAssistantRuntime` picks\n // the accurate wording a moment later (\"Reusing...\" vs \"Starting...\"), and\n // guessing here would flash the wrong one on every reused sandbox.\n setConversationProcessing(conversationId, 'provisioning', assistantMessageId, null);\n\n const applyAssistantResponse = (\n response: string,\n artifacts?: AssistantArtifact[],\n sessionId?: string,\n sandboxId?: string\n ) => {\n patchMessage(conversationId, assistantMessageId, {\n content: sanitizeAssistantResponse(response),\n metadata:\n artifacts?.length || sessionId || sandboxId\n ? {\n artifacts,\n mode: selectedMode,\n sessionId,\n sandboxId,\n }\n : undefined,\n });\n };\n\n const sendWithRealBackend = async (attempt: 1 | 2 = 1): Promise<void> => {\n // Set when this attempt had to re-send without the image bytes, so the\n // answer can say so rather than quietly reading as if the model looked.\n let imagesDropped = false;\n // Pre-flight AI-credit gate. The wspace gateway's @usage(checkQuota)\n // rejects with 429 QUOTA_EXHAUSTED when the monthly token budget is\n // depleted — block the send (don't provision a sandbox or dispatch the\n // prompt) and surface the upgrade dialog instead of a generic error.\n try {\n await checkAssistantAiCredits(apollo, workspaceId, authContext);\n } catch (creditError) {\n if (isQuotaExhaustedError(creditError)) {\n dispatchAssistantQuotaExhausted('ai-credits');\n applyAssistantResponse(\n \"You've run out of AI credits for this billing cycle. Upgrade your plan to keep chatting.\"\n );\n setConversationProcessing(conversationId, 'error', assistantMessageId, null);\n return;\n }\n // The pre-flight gate exists ONLY to catch a genuine QUOTA_EXHAUSTED\n // rejection. Any other failure here is a transient fault in the\n // credit check itself — e.g. the usage subgraph's getUsageSummary /\n // checkAiCredits intermittently 500s (Postgres/Prisma blip) and the\n // gateway masks it as the opaque \"Unexpected error.\". That is NOT\n // proof the user is out of budget, so it must not abort an otherwise\n // valid send. Fail open and proceed: the wspace gateway's\n // @usage(checkQuota) on createSandbox still enforces the real budget\n // downstream (a truly over-quota caller is stopped there with a 429\n // that surfaces the upgrade dialog via the outer catch).\n console.warn(\n '[assistant] AI-credit pre-flight check failed with a non-quota error; proceeding — gateway @usage(checkQuota) still enforces the real budget downstream',\n creditError\n );\n }\n\n try {\n const { sandboxId, sessionId } = await ensureAssistantRuntime(\n conversationId,\n assistantMessageId,\n selectedMode,\n workspaceId,\n authContext\n );\n\n // Snapshot the newest message timestamp already present in this\n // (possibly reused) session BEFORE sending the prompt, so we can\n // recognise THIS turn's reply as the one created after it — never by\n // comparing the browser clock to the sandbox clock (see\n // buildAssistantProgress). The newest-N window always contains the\n // newest message, so this floor is exact regardless of conversation depth.\n const priorMessages = await getAssistantMessages(\n apollo,\n sandboxId,\n workspaceId,\n sessionId,\n authContext,\n 50\n ).catch((): AssistantRawMessage[] => []);\n const priorNewestCreatedMs = priorMessages.reduce(\n (newest, message) => Math.max(newest, getRawMessageCreatedAt(message)),\n 0\n );\n\n updateConversationStage(conversationId, assistantMessageId, 'streaming', 'Thinking...');\n // Two agent-only wrappers around the raw content, both invisible in\n // the bubble: the soft confirm-before-mutate guard for api-calls mode,\n // and the attachment block (metadata + URLs, with text-like files\n // inlined) that carries this turn's files to the model.\n const promptText = buildPromptForMode(selectedMode, buildPromptWithAttachments(content, attachments));\n // Structured multimodal parts carry the image PIXELS, which no amount\n // of prompt text can. Built from the same `promptText`, so a bridge\n // that ignores `parts` loses nothing; `undefined` for an ordinary text\n // turn keeps the wire body unchanged.\n const promptParts = buildPromptParts(promptText, attachments);\n const inlinedCount = countInlinedImageParts(promptParts);\n const carriesPixels = inlinedCount > 0;\n const pageContext = gatherPageContext();\n\n // `buildPromptParts` may have demoted a photo to a link to keep the\n // body under the gateway's cap — a long message can do that on prompt\n // text alone. That decision is invisible to the user unless we say so,\n // and an answer that reads as if the model looked at a photo it never\n // received is worse than a short note.\n imagesDropped = countInlineImageCandidates(attachments) > inlinedCount;\n\n try {\n await sendAssistantPromptAsync(\n apollo,\n sandboxId,\n workspaceId,\n sessionId,\n promptText,\n selectedMode,\n pageContext,\n authContext,\n promptParts\n );\n } catch (sendError) {\n // `buildPromptParts` already sizes the PARTS to the gateway's cap\n // (the prompt string itself is not bounded here), so reaching this\n // point means something rejected the body anyway — a tighter proxy\n // than we modelled, or a bridge that will not take `parts` at all.\n // Losing the whole question over that is the worst outcome\n // available: re-send it text-only. Only for errors that provably\n // never reached the agent (see isMultimodalBodyRejection) — a blind\n // retry would ask the same question twice and bill it twice.\n //\n // Gated on `parts` existing at all, NOT on it carrying pixels: the\n // array duplicates the whole prompt in `parts[0]`, so a url-only\n // parts array is itself enough to push a long message over the cap.\n // `carriesPixels` only decides whether the user is told something\n // was lost.\n if (!promptParts || !isMultimodalBodyRejection(sendError)) throw sendError;\n await sendAssistantPromptAsync(\n apollo,\n sandboxId,\n workspaceId,\n sessionId,\n promptText,\n selectedMode,\n pageContext,\n authContext,\n undefined\n );\n // Only claim a photo was lost if one actually was — a url-only\n // retry loses nothing the prompt block did not already carry.\n imagesDropped = imagesDropped || carriesPixels;\n }\n\n let result = buildAssistantProgress([], priorNewestCreatedMs);\n const timeoutAt = Date.now() + (STREAM_BUDGET_MS[selectedMode] ?? DEFAULT_STREAM_BUDGET_MS);\n let lastTtlExtensionAt = Date.now();\n\n while (Date.now() < timeoutAt) {\n const sessionMessages = await getAssistantMessages(\n apollo,\n sandboxId,\n workspaceId,\n sessionId,\n authContext,\n 50\n );\n\n result = buildAssistantProgress(sessionMessages, priorNewestCreatedMs);\n patchMessage(conversationId, assistantMessageId, {\n content: sanitizeAssistantResponse(result.content),\n });\n\n if (result.done) break;\n\n if (Date.now() - lastTtlExtensionAt > 30_000) {\n await extendAssistantSandboxTTL(apollo, sandboxId, workspaceId, 600, authContext).catch(() => undefined);\n lastTtlExtensionAt = Date.now();\n }\n\n await new Promise((resolve) => setTimeout(resolve, 1500));\n }\n\n // For non-build modes a timeout is a hard failure. For vibe-plugins the\n // prompt runs async server-side (/sessions/:id/prompt-async) and keeps\n // writing artifacts after the poll budget elapses, so we surface whatever\n // it has produced instead of discarding the turn.\n if (!result.done && selectedMode !== 'vibe-plugins') {\n throw new Error('Assistant response timed out while streaming progress');\n }\n\n const artifacts =\n selectedMode === 'vibe-plugins'\n ? await getAssistantArtifacts(apollo, sandboxId, workspaceId, sessionId, authContext).catch(() => [])\n : undefined;\n\n if (!result.done) {\n // vibe-plugins build still running in the background. Append a note so\n // the user knows the answer is partial and the artifacts will finish.\n result = {\n ...result,\n content: `${result.content}\\n\\n_Still building in the background — any artifacts below will finish shortly. Re-open this conversation to pick up the completed plugin._`,\n };\n }\n\n if (imagesDropped) {\n // Said plainly, because the alternative is an answer that looks like\n // it examined a photo it never received.\n result = {\n ...result,\n content: `${result.content}\\n\\n${tr(\n 'healthybowl.assistant.attachments.imagesNotSent',\n '_Your photo was too large to include with this message, so the answer above is from the text and the file link only. Try a smaller or more tightly cropped photo._'\n )}`,\n };\n }\n\n applyAssistantResponse(result.content, artifacts, sessionId, sandboxId);\n\n if (result.tokens) {\n patchMessage(conversationId, assistantMessageId, { tokens: result.tokens });\n // Charge the real token usage against the AI-credits quota (the\n // gateway records it via @usage(trackUsage)). We AWAIT it before\n // marking the turn complete / re-enabling input: otherwise a rapid\n // follow-up send would run its pre-flight checkAiCredits against a\n // stale balance (this turn's charge still in flight) and could\n // dispatch a prompt that should have been blocked, letting fast\n // sends bypass the credit cap. Still best-effort — a charge failure\n // never blocks the displayed answer.\n try {\n await reportAssistantAiTokenUsage(apollo, workspaceId, sessionId, result.tokens, authContext);\n notifyAiCreditsUpdated();\n } catch {\n // ignore — server-side @usage tracking is the source of truth\n }\n }\n setConversationProcessing(conversationId, 'complete', assistantMessageId, null);\n } catch (error) {\n if (attempt === 1 && isRecoverableAssistantError(error)) {\n clearBackendSessionId(conversationId);\n clearSandbox(selectedMode);\n return sendWithRealBackend(2);\n }\n\n throw error;\n }\n };\n\n // Claim the slot immediately before the first await, and release it in\n // `finally` so every exit — success, quota return, thrown error — frees\n // it. Registering here rather than earlier means a synchronous throw in\n // the setup above can never strand a key and wedge the conversation.\n const turnConversationId = conversationId;\n inFlightSendsRef.current.add(turnConversationId);\n\n try {\n if (!workspaceId) {\n throw new Error('Assistant backend is unavailable without an active workspace context.');\n }\n await sendWithRealBackend();\n } catch (error) {\n // A quota error reaching here is the sandbox-environment wall hit\n // during runtime provisioning (createSandbox @usage). Surface the\n // upgrade dialog instead of a generic failure (the AI-credit wall is\n // already handled by the pre-flight gate above).\n if (isQuotaExhaustedError(error)) {\n dispatchAssistantQuotaExhausted('sandbox');\n applyAssistantResponse(\n \"You've reached your sandbox limit on the current plan. Upgrade to start the AI assistant.\"\n );\n setConversationProcessing(conversationId, 'error', assistantMessageId, null);\n return;\n }\n const errorMessage = error instanceof Error ? error.message : 'Something went wrong';\n setConversationProcessing(conversationId, 'error', assistantMessageId, errorMessage);\n updateMessage(\n conversationId,\n assistantMessageId,\n `Sorry, an error occurred: ${errorMessage}. Please try again.`\n );\n } finally {\n inFlightSendsRef.current.delete(turnConversationId);\n }\n },\n [\n activeConversationId,\n addMessage,\n apollo,\n clearBackendSessionId,\n clearSandbox,\n conversations,\n createConversation,\n ensureAssistantRuntime,\n getAccessToken,\n getWorkspaceToken,\n patchMessage,\n setBackendSessionId,\n setConversationMode,\n setConversationProcessing,\n tr,\n updateConversationStage,\n updateMessage,\n userId,\n ]\n );\n\n const handleSuggestionClick = useCallback(\n (suggestion: string) => {\n void handleSend(suggestion);\n },\n [handleSend]\n );\n\n // Retry re-sends the most recent user prompt through the same transport — the\n // failed assistant turn stays in the transcript, a fresh one is appended.\n // The attachments come from the in-memory ref rather than the message\n // metadata: the persisted descriptors deliberately drop the inlined text of\n // text-like files, so rebuilding from them would silently retry a WEAKER\n // prompt than the one that failed.\n const handleRetry = useCallback(() => {\n const lastUserMessage = [...messages].reverse().find((message) => message.role === 'user');\n const replay = activeConversationId ? (lastSentAttachmentsRef.current[activeConversationId] ?? []) : [];\n if (lastUserMessage) void handleSend(lastUserMessage.content, replay);\n }, [messages, handleSend, activeConversationId]);\n\n // Auto-send any prompt that was queued by `useOpenAssistantHelp` (from\n // the shared GetHelpButton). We keep the latest handleSend in a ref so\n // the subscription effect below doesn't need to tear down on every\n // render — the store subscription lives for the component lifetime and\n // always calls the freshest handler.\n const handleSendRef = useRef(handleSend);\n useEffect(() => {\n handleSendRef.current = handleSend;\n }, [handleSend]);\n\n useEffect(() => {\n // Flush any prompt that was queued before this component mounted.\n const initial = useAssistantStore.getState().consumePendingPrompt();\n if (initial) {\n void handleSendRef.current(initial);\n }\n\n // Watch for new prompts queued while we're already mounted.\n const unsubscribe = useAssistantStore.subscribe((state, prev) => {\n if (state.pendingPrompt && state.pendingPrompt !== prev.pendingPrompt) {\n const queued = useAssistantStore.getState().consumePendingPrompt();\n if (queued) {\n void handleSendRef.current(queued);\n }\n }\n });\n return unsubscribe;\n }, []);\n\n const performModeChange = useCallback(\n (newMode: AssistantMode) => {\n const currentConversation = activeConversationId\n ? useAssistantStore.getState().conversations.find((conversation) => conversation.id === activeConversationId)\n : undefined;\n\n if (currentConversation && (currentConversation.messages.length > 0 || currentConversation.backendSessionId)) {\n if (currentConversation.mode !== newMode) {\n const reusableDraft = useAssistantStore\n .getState()\n .conversations.find(\n (conversation) =>\n conversation.mode === newMode &&\n conversation.messages.length === 0 &&\n !conversation.backendSessionId &&\n !useAssistantStore.getState().processingByConversationId[conversation.id]\n );\n\n if (reusableDraft) {\n setActiveConversation(reusableDraft.id);\n } else {\n createConversation(undefined, newMode);\n }\n }\n } else if (activeConversationId) {\n setConversationMode(activeConversationId, newMode);\n }\n\n setMode(newMode);\n },\n [activeConversationId, createConversation, setActiveConversation, setConversationMode, setMode]\n );\n\n const handleModeChange = useCallback(\n (newMode: AssistantMode) => {\n const target = ASSISTANT_MODES.find((modeConfig) => modeConfig.id === newMode);\n // Gate the FIRST switch into a write-capable mode behind the one-time\n // consent dialog — the dependable confirm-before-mutate guardrail.\n if (target?.writeCapable && !useAssistantStore.getState().apiCallsAcknowledged) {\n setPendingConsentMode(newMode);\n return;\n }\n performModeChange(newMode);\n },\n [performModeChange]\n );\n\n const handleConsentConfirm = useCallback(() => {\n const target = pendingConsentMode;\n setPendingConsentMode(null);\n acknowledgeApiCalls();\n if (target) performModeChange(target);\n }, [pendingConsentMode, acknowledgeApiCalls, performModeChange]);\n\n const handleConsentCancel = useCallback(() => {\n setPendingConsentMode(null);\n }, []);\n\n return (\n <div className=\"flex flex-1 flex-col overflow-hidden\">\n {/* Transcript is always visible now — the old collapse-by-default accordion\n is gone; conversation history lives behind the header button instead. */}\n {messages.length === 0 ? (\n <AssistantEmptyState mode={mode} onSuggestionClick={handleSuggestionClick} />\n ) : (\n <div className=\"flex min-h-0 flex-1 flex-col\">\n <AssistantMessageList\n messages={messages}\n streamingMessageId={activeStreamingMessageId}\n failedMessageId={failedMessageId}\n onRetry={handleRetry}\n />\n </div>\n )}\n\n <AssistantComposer\n onSend={(value, attachments) => void handleSend(value, attachments)}\n disabled={activeIsProcessing}\n placeholder={\n mode === 'api-calls'\n ? tr('healthybowl.assistant.chatArea.placeholderActions', 'What would you like me to do?')\n : tr('healthybowl.assistant.chatArea.placeholderGeneral', 'Ask HealthyBowl anything…')\n }\n mode={mode}\n availableModes={availableModes}\n onModeChange={handleModeChange}\n />\n\n <AssistantApiCallsConsentDialog\n open={pendingConsentMode !== null}\n onConfirm={handleConsentConfirm}\n onCancel={handleConsentCancel}\n />\n </div>\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAkDA,IAAM,KAAkD;CACtD,SAAS;CACT,aAAa;CACb,gBAAgB;CACjB,EACK,KAA2B;AAEjC,SAAS,KAAqB;AAC5B,QAAO,GAAG,KAAK,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AE5B,CAAC,EAAkB,CACpB,EAEK,KAAuB,QAAkB;EAC7C,IAAM,IAAS;AAGf,EAFA,GAAsB,KAAK,EAC3B,IAAqB,EACjB,KAAQ,EAAkB,EAAO;IACpC;EAAC;EAAoB;EAAqB;EAAkB,CAAC,EAE1D,KAAsB,QAAkB;AAC5C,KAAsB,KAAK;IAC1B,EAAE,CAAC;AAEN,QACE,mBAAC,OAAD;EAAK,WAAU;YAAf;GAGG,EAAS,WAAW,IACnB,kBAAC,GAAD;IAA2B;IAAM,mBAAmB;IAAyB,CAAA,GAE7E,kBAAC,OAAD;IAAK,WAAU;cACb,kBAAC,GAAD;KACY;KACV,oBAAoB;KACH;KACjB,SAAS;KACT,CAAA;IACE,CAAA;GAGR,kBAAC,GAAD;IACE,SAAS,GAAO,MAAgB,KAAK,EAAW,GAAO,EAAY;IACnE,UAAU;IACV,aACE,MAAS,cACL,EAAG,qDAAqD,gCAAgC,GACxF,EAAG,qDAAqD,4BAA4B;IAEpF;IACU;IAChB,cAAc;IACd,CAAA;GAEF,kBAAC,GAAD;IACE,MAAM,MAAuB;IAC7B,WAAW;IACX,UAAU;IACV,CAAA;GACE"}
1
+ {"version":3,"file":"AssistantChatArea.js","names":[],"sources":["../../../src/components/assistant/AssistantChatArea.tsx"],"sourcesContent":["import { useCallback, useEffect, useMemo, useRef, useState, type FC } from 'react';\nimport { useGatewayClient } from '@burdenoff/fe-libs/shared/graphql';\nimport { useAuthToken } from '@burdenoff/fe-libs/shared/providers/shell';\nimport { AssistantMessageList } from './AssistantMessageList';\nimport { AssistantApiCallsConsentDialog } from './AssistantApiCallsConsentDialog';\nimport { AssistantEmptyState } from './AssistantEmptyState';\nimport { AssistantComposer } from './composer/AssistantComposer';\nimport { useAssistantApiAccess } from '@/hooks/useAssistantApiAccess';\nimport { useAssistantStore } from '@/store/assistantStore';\nimport {\n checkAssistantAiCredits,\n createAssistantSandbox,\n createAssistantSession,\n extendAssistantSandboxTTL,\n findExistingSandbox,\n getAssistantArtifacts,\n getAssistantMessages,\n getAssistantSession,\n reportAssistantAiTokenUsage,\n sendAssistantPromptAsync,\n waitForAssistantServiceReady,\n waitForSandboxReady,\n type AssistantRawMessage,\n type AssistantSandboxAuthContext,\n} from '@/services/assistantApi';\nimport { getAssistantMedia } from '@burdenoff/fe-libs/shared/assistant';\nimport { gatherPageContext } from '@/utils/pageContext';\nimport { getOrganizationId, getWorkspaceId } from '@/utils/assistantContext';\nimport { dispatchAssistantQuotaExhausted, notifyAiCreditsUpdated } from '@/utils/aiCredits';\nimport { isQuotaExhaustedError } from '@/utils/quotaUtils';\nimport { buildPromptForMode } from '@/utils/assistantPrompt';\nimport {\n buildPromptParts,\n buildPromptWithAttachments,\n countInlineImageCandidates,\n countInlinedImageParts,\n toMessageAttachment,\n type AssistantAttachment,\n} from '@/utils/assistantAttachments';\nimport { isMultimodalBodyRejection, isRecoverableAssistantError } from '@/utils/assistantTransportErrors';\nimport { isTurnInFlight } from '@/utils/assistantTurnState';\nimport { useTr } from '../../shared/hooks/useTr';\nimport { ASSISTANT_MODES } from '@/types/assistant';\nimport type { AssistantArtifact, AssistantConversationStatus, AssistantMode, Message } from '@/types/assistant';\n\n// How long the client streams progress before giving up on a turn. Chat replies\n// (general / api-calls) finish in seconds; a vibe-plugins build is a multi-step\n// pipeline (read docs → scaffold → bun install → bun build → checklist) that runs\n// for minutes, so it gets a much larger budget. The sandbox TTL is auto-extended\n// every 30s during the poll loop, so a longer budget never outlives the sandbox.\nconst STREAM_BUDGET_MS: Record<AssistantMode, number> = {\n general: 180_000,\n assistant: 180_000,\n 'api-calls': 180_000,\n 'vibe-plugins': 600_000,\n};\nconst DEFAULT_STREAM_BUDGET_MS = 180_000;\n\nfunction generateId(): string {\n return `${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;\n}\n\nfunction sanitizeAssistantResponse(response: string): string {\n return response\n .replace(/(Authorization\\s*:\\s*Bearer\\s+)[^\\s\\n]+/gi, '$1[REDACTED]')\n .replace(/(X-Workspace-Authorization\\s*:\\s*Bearer\\s+)[^\\s\\n]+/gi, '$1[REDACTED]')\n .replace(/\\beyJ[A-Za-z0-9_-]+\\.[A-Za-z0-9._-]+\\.[A-Za-z0-9._-]+\\b/g, '[REDACTED_JWT]')\n .replace(/\\bsk-ant-[A-Za-z0-9-]+\\b/g, '[REDACTED_API_KEY]');\n}\n\nfunction getRawMessageCreatedAt(message: AssistantRawMessage): number {\n return message.info?.time?.created ?? 0;\n}\n\nfunction getAssistantText(parts: AssistantRawMessage['parts']): string {\n return (parts ?? [])\n .filter((part) => part.type === 'text' && typeof part.text === 'string')\n .map((part) => part.text?.trim() ?? '')\n .filter(Boolean)\n .join('\\n');\n}\n\nfunction getToolProgress(parts: AssistantRawMessage['parts']): string[] {\n return (parts ?? [])\n .filter((part) => part.type === 'tool' && part.tool)\n .map((part) => {\n const status = part.state?.status ?? 'running';\n const tool = part.tool ?? 'tool';\n if (status === 'completed') return `Completed: ${tool}`;\n if (status === 'failed') return `Failed: ${tool}`;\n return `Running: ${tool}`;\n });\n}\n\nfunction buildAssistantProgress(\n messages: AssistantRawMessage[],\n // The `created` timestamp (sandbox clock) of the newest message that already\n // existed in this session BEFORE the prompt was sent. This turn's reply is the\n // assistant message created strictly after it. Crucially this stays WITHIN the\n // sandbox clock domain: the previous code compared the sandbox-stamped\n // `created` against the browser wall-clock (Date#now), so a reply stamped at\n // prompt-time was silently dropped whenever the sandbox clock lagged the\n // browser — the turn then hung on \"Thinking...\" until the stream budget\n // elapsed. A sandbox-domain floor is immune to clock skew and correct for both\n // fresh and reused (per-conversation) sessions, with no message-window gap.\n priorNewestCreatedMs: number\n): {\n content: string;\n done: boolean;\n tokens?: { input: number; output: number };\n} {\n const relevant = messages\n .filter((message) => message.info?.role === 'assistant' && getRawMessageCreatedAt(message) > priorNewestCreatedMs)\n .sort((left, right) => getRawMessageCreatedAt(left) - getRawMessageCreatedAt(right));\n\n if (relevant.length === 0) {\n return { content: 'Thinking...', done: false };\n }\n\n const latest = relevant[relevant.length - 1]!;\n const text = getAssistantText(latest.parts);\n // Inbound image/file parts, rendered to markdown by the shared helper (which\n // escapes the label and allowlists the protocol — this is model output).\n // Without this, HealthyBowl — the one product that SENDS parts — could not\n // read one back: a media-bearing reply would never satisfy `done` and the\n // turn would poll to a false timeout.\n const media = getAssistantMedia(latest.parts);\n const toolProgress = getToolProgress(latest.parts);\n const content = [text, ...media, ...toolProgress].filter(Boolean).join('\\n\\n') || 'Thinking...';\n\n return {\n content,\n done: Boolean(latest.info?.time?.completed) && (Boolean(text) || media.length > 0 || toolProgress.length > 0),\n tokens: latest.info?.tokens,\n };\n}\n\nfunction getConversationStatusMessage(status: AssistantConversationStatus): string {\n switch (status) {\n case 'provisioning':\n return 'Starting assistant environment...';\n case 'connecting':\n return 'Connecting to assistant...';\n case 'streaming':\n return 'Thinking...';\n default:\n return '';\n }\n}\n\nexport const AssistantChatArea: FC = () => {\n const tr = useTr();\n const apollo = useGatewayClient('workspace');\n const { getAccessToken, getWorkspaceToken, userId } = useAuthToken();\n\n const {\n conversations,\n activeConversationId,\n mode,\n processingByConversationId,\n setMode,\n setConversationMode,\n setActiveConversation,\n createConversation,\n addMessage,\n updateMessage,\n patchMessage,\n setConversationProcessing,\n clearConversationProcessing,\n setBackendSessionId,\n clearBackendSessionId,\n setSandbox,\n clearSandbox,\n acknowledgeApiCalls,\n } = useAssistantStore();\n\n const activeConversation = conversations.find((conversation) => conversation.id === activeConversationId);\n const messages = activeConversation?.messages ?? [];\n const activeProcessing = activeConversationId ? processingByConversationId[activeConversationId] : undefined;\n // Only while the turn is genuinely in flight. `messageId` outlives the turn\n // (setConversationProcessing keeps it on 'complete'/'error'), so keying off it\n // alone left the transcript's aria-busy latched true forever and screen\n // readers stopped announcing new replies.\n const activeIsProcessing = isTurnInFlight(activeProcessing?.status);\n const activeStreamingMessageId = activeIsProcessing ? (activeProcessing?.messageId ?? null) : null;\n // The assistant message whose turn ended in an error — drives the Retry\n // affordance in the transcript.\n const failedMessageId = activeProcessing?.status === 'error' ? activeProcessing.messageId : null;\n\n // ── api-calls (write) mode gating ──────────────────────────────────\n // Only a global Owner/Admin may use api-calls (it mints an OAuth app under the\n // caller identity). Re-read the org scope every render (a cheap localStorage\n // read) so the admin gate reacts to an org switch without the panel\n // remounting; the value is a stable string, so useAssistantApiAccess only\n // re-fetches myRoles when the org actually changes. An empty scope simply\n // hides the mode (it could not provision the sandbox anyway).\n const apiCallsScopeId = getOrganizationId();\n const { canUseApiCalls, loading: apiAccessLoading } = useAssistantApiAccess(apiCallsScopeId);\n const availableModes = useMemo(\n () => ASSISTANT_MODES.filter((modeConfig) => !modeConfig.requiresAdmin || canUseApiCalls),\n [canUseApiCalls]\n );\n\n // Target mode awaiting the one-time consent dialog (null = dialog closed).\n const [pendingConsentMode, setPendingConsentMode] = useState<AssistantMode | null>(null);\n\n // Full attachment payload of the last send, kept so Retry can replay it\n // byte-for-byte (see handleRetry).\n const lastSentAttachmentsRef = useRef<Record<string, AssistantAttachment[]>>({});\n\n // Conversations with a turn already dispatched. Synchronous, unlike the store\n // — see the re-entry guard in handleSend for why that matters.\n const inFlightSendsRef = useRef<Set<string>>(new Set());\n\n // If the active mode is no longer permitted — a non-admin with a persisted\n // api-calls mode, or the master flag turned off — fall back to the read-only\n // `assistant` mode (the default \"Ask\", available to everyone), but only AFTER\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 activeModeConfig = ASSISTANT_MODES.find((modeConfig) => modeConfig.id === mode);\n const blocked = !activeModeConfig || (activeModeConfig.requiresAdmin && !canUseApiCalls);\n if (blocked && mode !== 'assistant') {\n setMode('assistant');\n }\n }, [mode, canUseApiCalls, apiAccessLoading, setMode]);\n\n const updateConversationStage = useCallback(\n (conversationId: string, assistantMessageId: string, status: AssistantConversationStatus, content?: string) => {\n setConversationProcessing(conversationId, status, assistantMessageId, null);\n if (content) {\n updateMessage(conversationId, assistantMessageId, content);\n } else {\n updateMessage(conversationId, assistantMessageId, getConversationStatusMessage(status));\n }\n },\n [setConversationProcessing, updateMessage]\n );\n\n const ensureAssistantRuntime = useCallback(\n async (\n conversationId: string,\n assistantMessageId: string,\n currentMode: AssistantMode,\n workspaceId: string,\n authContext: AssistantSandboxAuthContext\n ): Promise<{ sandboxId: string; sessionId: string }> => {\n let currentSandboxId = useAssistantStore.getState().sandboxesByMode[currentMode]?.sandboxId ?? null;\n\n // Validate that a candidate sandbox (remembered locally or found running on\n // the server) is actually reachable before we reuse it. A sandbox can expire\n // (ttlSeconds) or have its backend pod reclaimed while still being briefly\n // reported RUNNING; proxying to such a dead pod fails with a terminal state\n // (\"Backend resource no longer exists\") or a permanent 502 cf-proxy timeout.\n // Returns true only when the in-sandbox agent responds; false means stale.\n const ensureSandboxReachable = async (candidateId: string): Promise<boolean> => {\n try {\n await waitForSandboxReady(apollo, candidateId, workspaceId, authContext, 300_000, (message) =>\n updateConversationStage(conversationId, assistantMessageId, 'provisioning', message)\n );\n await waitForAssistantServiceReady(apollo, candidateId, workspaceId, authContext, 90_000, (message) =>\n updateConversationStage(conversationId, assistantMessageId, 'connecting', message)\n );\n return true;\n } catch {\n // Stale/expired sandbox — drop it so we provision a fresh one below\n // instead of surfacing \"Internal server error\" to the user.\n return false;\n }\n };\n\n // 1) Try the locally-remembered sandbox, then 2) any running one on the\n // server. Each is only kept if it's actually reachable.\n if (currentSandboxId) {\n setSandbox(currentMode, currentSandboxId, 'provisioning');\n updateConversationStage(conversationId, assistantMessageId, 'provisioning', 'Reusing assistant environment...');\n if (!(await ensureSandboxReachable(currentSandboxId))) {\n setSandbox(currentMode, null, 'provisioning');\n currentSandboxId = null;\n }\n }\n\n if (!currentSandboxId) {\n updateConversationStage(\n conversationId,\n assistantMessageId,\n 'provisioning',\n 'Looking for existing environment...'\n );\n const existingId = await findExistingSandbox(apollo, workspaceId, currentMode, authContext);\n\n if (existingId) {\n setSandbox(currentMode, existingId, 'provisioning');\n updateConversationStage(\n conversationId,\n assistantMessageId,\n 'provisioning',\n 'Reusing assistant environment...'\n );\n if (await ensureSandboxReachable(existingId)) {\n currentSandboxId = existingId;\n } else {\n setSandbox(currentMode, null, 'provisioning');\n }\n }\n }\n\n // 3) No reusable, reachable sandbox — provision a fresh one.\n if (!currentSandboxId) {\n if (currentMode === 'api-calls' && !getAccessToken()) {\n throw new Error('API Calls mode requires an authenticated session. Please sign in again.');\n }\n\n updateConversationStage(\n conversationId,\n assistantMessageId,\n 'provisioning',\n 'Starting assistant environment...'\n );\n setSandbox(currentMode, null, 'provisioning');\n currentSandboxId = await createAssistantSandbox(apollo, currentMode, workspaceId, authContext);\n\n setSandbox(currentMode, currentSandboxId, 'provisioning');\n await waitForSandboxReady(apollo, currentSandboxId, workspaceId, authContext, 300_000, (message) =>\n updateConversationStage(conversationId, assistantMessageId, 'provisioning', message)\n );\n await waitForAssistantServiceReady(apollo, currentSandboxId, workspaceId, authContext, 90_000, (message) =>\n updateConversationStage(conversationId, assistantMessageId, 'connecting', message)\n );\n }\n\n setSandbox(currentMode, currentSandboxId, 'running');\n\n let sessionId =\n useAssistantStore.getState().conversations.find((conversation) => conversation.id === conversationId)\n ?.backendSessionId ?? null;\n\n if (sessionId) {\n try {\n const session = await getAssistantSession(apollo, currentSandboxId, workspaceId, sessionId, authContext);\n if (session.mode !== currentMode) {\n throw new Error(`Session mode mismatch: expected ${currentMode}, received ${session.mode}`);\n }\n } catch {\n clearBackendSessionId(conversationId);\n sessionId = null;\n }\n }\n\n if (!sessionId) {\n updateConversationStage(conversationId, assistantMessageId, 'connecting', 'Preparing session...');\n const result = await createAssistantSession(apollo, currentSandboxId, workspaceId, currentMode, authContext);\n sessionId = result.sessionId;\n setBackendSessionId(conversationId, sessionId);\n }\n\n return {\n sandboxId: currentSandboxId,\n sessionId,\n };\n },\n [apollo, clearBackendSessionId, getAccessToken, setBackendSessionId, setSandbox, updateConversationStage]\n );\n\n const handleSend = useCallback(\n async (content: string, attachments: AssistantAttachment[] = []) => {\n // Only block re-entry while a turn is genuinely in-flight. Earlier code\n // checked for *any* entry in the map, which stuck around as `complete`\n // / `error` after the first turn — making every subsequent message\n // silently disappear (the input cleared but handleSend bailed before\n // adding the user message to the conversation).\n //\n // The store is read LIVE, and that is what makes the guard work. The\n // render-captured `processingByConversationId` is stale by construction —\n // the click that starts a turn and the click that must be rejected can\n // belong to the same render. Reading `activeConversationId` live matters\n // for the same reason: on two racing first-ever sends, the second must see\n // the conversation the first one created a moment ago.\n //\n // Pairs with the synchronous `setConversationProcessing` below: because\n // the status is written before this function ever awaits, a second call —\n // however soon it arrives — always observes 'provisioning'.\n const storeAtEntry = useAssistantStore.getState();\n const guardConversationId = storeAtEntry.activeConversationId ?? activeConversationId;\n if (guardConversationId) {\n if (isTurnInFlight(storeAtEntry.processingByConversationId[guardConversationId]?.status)) return;\n // Second lock, in case a future change moves the status write later:\n // this one cannot be cleared by anything but the turn's own `finally`.\n // Deliberately per-conversation — a global key would keep blocking\n // after the conversation it belonged to was deleted mid-turn, and then\n // silently swallow every subsequent send.\n if (inFlightSendsRef.current.has(guardConversationId)) return;\n }\n\n const selectedMode = storeAtEntry.mode;\n let conversationId = activeConversationId;\n const currentConversation = conversationId\n ? useAssistantStore.getState().conversations.find((conversation) => conversation.id === conversationId)\n : undefined;\n\n if (!conversationId) {\n conversationId = createConversation(undefined, selectedMode);\n } else if (\n currentConversation &&\n currentConversation.mode !== selectedMode &&\n (currentConversation.messages.length > 0 || currentConversation.backendSessionId)\n ) {\n conversationId = createConversation(undefined, selectedMode);\n } else if (currentConversation && currentConversation.mode !== selectedMode) {\n setConversationMode(conversationId, selectedMode);\n }\n\n if (!conversationId) return;\n\n // Keyed by conversation: the ref outlives a conversation switch, and a\n // single global slot meant Retry in one thread replayed another thread's\n // photo onto it.\n lastSentAttachmentsRef.current[conversationId] = attachments;\n\n const workspaceId = getWorkspaceId();\n const authContext: AssistantSandboxAuthContext = {\n accessToken: getAccessToken(),\n workspaceToken: getWorkspaceToken(),\n userId,\n organizationId: getOrganizationId(),\n };\n\n const userMessage: Message = {\n id: generateId(),\n role: 'user',\n content,\n timestamp: new Date().toISOString(),\n // Slim descriptors only — the bubble re-resolves thumbnails from the\n // file id, so the persisted conversation stays small.\n metadata: attachments.length ? { attachments: attachments.map(toMessageAttachment) } : undefined,\n };\n addMessage(conversationId, userMessage);\n\n const assistantMessageId = generateId();\n addMessage(conversationId, {\n id: assistantMessageId,\n role: 'assistant',\n content: '',\n timestamp: new Date().toISOString(),\n });\n\n // Mark the turn in-flight in the STORE right now, synchronously.\n //\n // Until this line the first status write happened inside\n // `ensureAssistantRuntime`, i.e. one await later. During that window\n // `activeIsProcessing` was false and `failedMessageId` still pointed at\n // the PREVIOUS failure — so the composer stayed enabled and, worse, the\n // Retry button (which has no `disabled` of its own) stayed mounted and\n // clickable on top of a turn that had already started.\n //\n // Status only, deliberately no stage copy: `ensureAssistantRuntime` picks\n // the accurate wording a moment later (\"Reusing...\" vs \"Starting...\"), and\n // guessing here would flash the wrong one on every reused sandbox.\n setConversationProcessing(conversationId, 'provisioning', assistantMessageId, null);\n\n const applyAssistantResponse = (\n response: string,\n artifacts?: AssistantArtifact[],\n sessionId?: string,\n sandboxId?: string\n ) => {\n patchMessage(conversationId, assistantMessageId, {\n content: sanitizeAssistantResponse(response),\n metadata:\n artifacts?.length || sessionId || sandboxId\n ? {\n artifacts,\n mode: selectedMode,\n sessionId,\n sandboxId,\n }\n : undefined,\n });\n };\n\n const sendWithRealBackend = async (attempt: 1 | 2 = 1): Promise<void> => {\n // Set when this attempt had to re-send without the image bytes, so the\n // answer can say so rather than quietly reading as if the model looked.\n let imagesDropped = false;\n // Pre-flight AI-credit gate. The wspace gateway's @usage(checkQuota)\n // rejects with 429 QUOTA_EXHAUSTED when the monthly token budget is\n // depleted — block the send (don't provision a sandbox or dispatch the\n // prompt) and surface the upgrade dialog instead of a generic error.\n try {\n await checkAssistantAiCredits(apollo, workspaceId, authContext);\n } catch (creditError) {\n if (isQuotaExhaustedError(creditError)) {\n dispatchAssistantQuotaExhausted('ai-credits');\n applyAssistantResponse(\n \"You've run out of AI credits for this billing cycle. Upgrade your plan to keep chatting.\"\n );\n setConversationProcessing(conversationId, 'error', assistantMessageId, null);\n return;\n }\n // The pre-flight gate exists ONLY to catch a genuine QUOTA_EXHAUSTED\n // rejection. Any other failure here is a transient fault in the\n // credit check itself — e.g. the usage subgraph's getUsageSummary /\n // checkAiCredits intermittently 500s (Postgres/Prisma blip) and the\n // gateway masks it as the opaque \"Unexpected error.\". That is NOT\n // proof the user is out of budget, so it must not abort an otherwise\n // valid send. Fail open and proceed: the wspace gateway's\n // @usage(checkQuota) on createSandbox still enforces the real budget\n // downstream (a truly over-quota caller is stopped there with a 429\n // that surfaces the upgrade dialog via the outer catch).\n console.warn(\n '[assistant] AI-credit pre-flight check failed with a non-quota error; proceeding — gateway @usage(checkQuota) still enforces the real budget downstream',\n creditError\n );\n }\n\n try {\n const { sandboxId, sessionId } = await ensureAssistantRuntime(\n conversationId,\n assistantMessageId,\n selectedMode,\n workspaceId,\n authContext\n );\n\n // Snapshot the newest message timestamp already present in this\n // (possibly reused) session BEFORE sending the prompt, so we can\n // recognise THIS turn's reply as the one created after it — never by\n // comparing the browser clock to the sandbox clock (see\n // buildAssistantProgress). The newest-N window always contains the\n // newest message, so this floor is exact regardless of conversation depth.\n const priorMessages = await getAssistantMessages(\n apollo,\n sandboxId,\n workspaceId,\n sessionId,\n authContext,\n 50\n ).catch((): AssistantRawMessage[] => []);\n const priorNewestCreatedMs = priorMessages.reduce(\n (newest, message) => Math.max(newest, getRawMessageCreatedAt(message)),\n 0\n );\n\n updateConversationStage(conversationId, assistantMessageId, 'streaming', 'Thinking...');\n // Two agent-only wrappers around the raw content, both invisible in\n // the bubble: the soft confirm-before-mutate guard for api-calls mode,\n // and the attachment block (metadata + URLs, with text-like files\n // inlined) that carries this turn's files to the model.\n const promptText = buildPromptForMode(selectedMode, buildPromptWithAttachments(content, attachments));\n // Structured multimodal parts carry the image PIXELS, which no amount\n // of prompt text can. Built from the same `promptText`, so a bridge\n // that ignores `parts` loses nothing; `undefined` for an ordinary text\n // turn keeps the wire body unchanged.\n const promptParts = buildPromptParts(promptText, attachments);\n const inlinedCount = countInlinedImageParts(promptParts);\n const carriesPixels = inlinedCount > 0;\n const pageContext = gatherPageContext();\n\n // `buildPromptParts` may have demoted a photo to a link to keep the\n // body under the gateway's cap — a long message can do that on prompt\n // text alone. That decision is invisible to the user unless we say so,\n // and an answer that reads as if the model looked at a photo it never\n // received is worse than a short note.\n imagesDropped = countInlineImageCandidates(attachments) > inlinedCount;\n\n try {\n await sendAssistantPromptAsync(\n apollo,\n sandboxId,\n workspaceId,\n sessionId,\n promptText,\n selectedMode,\n pageContext,\n authContext,\n promptParts\n );\n } catch (sendError) {\n // `buildPromptParts` already sizes the PARTS to the gateway's cap\n // (the prompt string itself is not bounded here), so reaching this\n // point means something rejected the body anyway — a tighter proxy\n // than we modelled, or a bridge that will not take `parts` at all.\n // Losing the whole question over that is the worst outcome\n // available: re-send it text-only. Only for errors that provably\n // never reached the agent (see isMultimodalBodyRejection) — a blind\n // retry would ask the same question twice and bill it twice.\n //\n // Gated on `parts` existing at all, NOT on it carrying pixels: the\n // array duplicates the whole prompt in `parts[0]`, so a url-only\n // parts array is itself enough to push a long message over the cap.\n // `carriesPixels` only decides whether the user is told something\n // was lost.\n if (!promptParts || !isMultimodalBodyRejection(sendError)) throw sendError;\n await sendAssistantPromptAsync(\n apollo,\n sandboxId,\n workspaceId,\n sessionId,\n promptText,\n selectedMode,\n pageContext,\n authContext,\n undefined\n );\n // Only claim a photo was lost if one actually was — a url-only\n // retry loses nothing the prompt block did not already carry.\n imagesDropped = imagesDropped || carriesPixels;\n }\n\n let result = buildAssistantProgress([], priorNewestCreatedMs);\n const timeoutAt = Date.now() + (STREAM_BUDGET_MS[selectedMode] ?? DEFAULT_STREAM_BUDGET_MS);\n let lastTtlExtensionAt = Date.now();\n\n while (Date.now() < timeoutAt) {\n const sessionMessages = await getAssistantMessages(\n apollo,\n sandboxId,\n workspaceId,\n sessionId,\n authContext,\n 50\n );\n\n result = buildAssistantProgress(sessionMessages, priorNewestCreatedMs);\n patchMessage(conversationId, assistantMessageId, {\n content: sanitizeAssistantResponse(result.content),\n });\n\n if (result.done) break;\n\n if (Date.now() - lastTtlExtensionAt > 30_000) {\n await extendAssistantSandboxTTL(apollo, sandboxId, workspaceId, 600, authContext).catch(() => undefined);\n lastTtlExtensionAt = Date.now();\n }\n\n await new Promise((resolve) => setTimeout(resolve, 1500));\n }\n\n // For non-build modes a timeout is a hard failure. For vibe-plugins the\n // prompt runs async server-side (/sessions/:id/prompt-async) and keeps\n // writing artifacts after the poll budget elapses, so we surface whatever\n // it has produced instead of discarding the turn.\n if (!result.done && selectedMode !== 'vibe-plugins') {\n throw new Error('Assistant response timed out while streaming progress');\n }\n\n const artifacts =\n selectedMode === 'vibe-plugins'\n ? await getAssistantArtifacts(apollo, sandboxId, workspaceId, sessionId, authContext).catch(() => [])\n : undefined;\n\n if (!result.done) {\n // vibe-plugins build still running in the background. Append a note so\n // the user knows the answer is partial and the artifacts will finish.\n result = {\n ...result,\n content: `${result.content}\\n\\n_Still building in the background — any artifacts below will finish shortly. Re-open this conversation to pick up the completed plugin._`,\n };\n }\n\n if (imagesDropped) {\n // Said plainly, because the alternative is an answer that looks like\n // it examined a photo it never received.\n result = {\n ...result,\n content: `${result.content}\\n\\n${tr(\n 'healthybowl.assistant.attachments.imagesNotSent',\n '_Your photo was too large to include with this message, so the answer above is from the text and the file link only. Try a smaller or more tightly cropped photo._'\n )}`,\n };\n }\n\n applyAssistantResponse(result.content, artifacts, sessionId, sandboxId);\n\n if (result.tokens) {\n patchMessage(conversationId, assistantMessageId, { tokens: result.tokens });\n // Charge the real token usage against the AI-credits quota (the\n // gateway records it via @usage(trackUsage)). We AWAIT it before\n // marking the turn complete / re-enabling input: otherwise a rapid\n // follow-up send would run its pre-flight checkAiCredits against a\n // stale balance (this turn's charge still in flight) and could\n // dispatch a prompt that should have been blocked, letting fast\n // sends bypass the credit cap. Still best-effort — a charge failure\n // never blocks the displayed answer.\n try {\n await reportAssistantAiTokenUsage(apollo, workspaceId, sessionId, result.tokens, authContext);\n notifyAiCreditsUpdated();\n } catch {\n // ignore — server-side @usage tracking is the source of truth\n }\n }\n setConversationProcessing(conversationId, 'complete', assistantMessageId, null);\n } catch (error) {\n if (attempt === 1 && isRecoverableAssistantError(error)) {\n clearBackendSessionId(conversationId);\n clearSandbox(selectedMode);\n return sendWithRealBackend(2);\n }\n\n throw error;\n }\n };\n\n // Claim the slot immediately before the first await, and release it in\n // `finally` so every exit — success, quota return, thrown error — frees\n // it. Registering here rather than earlier means a synchronous throw in\n // the setup above can never strand a key and wedge the conversation.\n const turnConversationId = conversationId;\n inFlightSendsRef.current.add(turnConversationId);\n\n try {\n if (!workspaceId) {\n throw new Error('Assistant backend is unavailable without an active workspace context.');\n }\n await sendWithRealBackend();\n } catch (error) {\n // A quota error reaching here is the sandbox-environment wall hit\n // during runtime provisioning (createSandbox @usage). Surface the\n // upgrade dialog instead of a generic failure (the AI-credit wall is\n // already handled by the pre-flight gate above).\n if (isQuotaExhaustedError(error)) {\n dispatchAssistantQuotaExhausted('sandbox');\n applyAssistantResponse(\n \"You've reached your sandbox limit on the current plan. Upgrade to start the AI assistant.\"\n );\n setConversationProcessing(conversationId, 'error', assistantMessageId, null);\n return;\n }\n const errorMessage = error instanceof Error ? error.message : 'Something went wrong';\n setConversationProcessing(conversationId, 'error', assistantMessageId, errorMessage);\n updateMessage(\n conversationId,\n assistantMessageId,\n `Sorry, an error occurred: ${errorMessage}. Please try again.`\n );\n } finally {\n inFlightSendsRef.current.delete(turnConversationId);\n }\n },\n [\n activeConversationId,\n addMessage,\n apollo,\n clearBackendSessionId,\n clearSandbox,\n conversations,\n createConversation,\n ensureAssistantRuntime,\n getAccessToken,\n getWorkspaceToken,\n patchMessage,\n setBackendSessionId,\n setConversationMode,\n setConversationProcessing,\n tr,\n updateConversationStage,\n updateMessage,\n userId,\n ]\n );\n\n const handleSuggestionClick = useCallback(\n (suggestion: string) => {\n void handleSend(suggestion);\n },\n [handleSend]\n );\n\n // Retry re-sends the most recent user prompt through the same transport — the\n // failed assistant turn stays in the transcript, a fresh one is appended.\n // The attachments come from the in-memory ref rather than the message\n // metadata: the persisted descriptors deliberately drop the inlined text of\n // text-like files, so rebuilding from them would silently retry a WEAKER\n // prompt than the one that failed.\n const handleRetry = useCallback(() => {\n const lastUserMessage = [...messages].reverse().find((message) => message.role === 'user');\n const replay = activeConversationId ? (lastSentAttachmentsRef.current[activeConversationId] ?? []) : [];\n if (lastUserMessage) void handleSend(lastUserMessage.content, replay);\n }, [messages, handleSend, activeConversationId]);\n\n // Auto-send any prompt that was queued by `useOpenAssistantHelp` (from\n // the shared GetHelpButton). We keep the latest handleSend in a ref so\n // the subscription effect below doesn't need to tear down on every\n // render — the store subscription lives for the component lifetime and\n // always calls the freshest handler.\n const handleSendRef = useRef(handleSend);\n useEffect(() => {\n handleSendRef.current = handleSend;\n }, [handleSend]);\n\n useEffect(() => {\n // Flush any prompt that was queued before this component mounted.\n const initial = useAssistantStore.getState().consumePendingPrompt();\n if (initial) {\n void handleSendRef.current(initial);\n }\n\n // Watch for new prompts queued while we're already mounted.\n const unsubscribe = useAssistantStore.subscribe((state, prev) => {\n if (state.pendingPrompt && state.pendingPrompt !== prev.pendingPrompt) {\n const queued = useAssistantStore.getState().consumePendingPrompt();\n if (queued) {\n void handleSendRef.current(queued);\n }\n }\n });\n return unsubscribe;\n }, []);\n\n const performModeChange = useCallback(\n (newMode: AssistantMode) => {\n const currentConversation = activeConversationId\n ? useAssistantStore.getState().conversations.find((conversation) => conversation.id === activeConversationId)\n : undefined;\n\n if (currentConversation && (currentConversation.messages.length > 0 || currentConversation.backendSessionId)) {\n if (currentConversation.mode !== newMode) {\n const reusableDraft = useAssistantStore\n .getState()\n .conversations.find(\n (conversation) =>\n conversation.mode === newMode &&\n conversation.messages.length === 0 &&\n !conversation.backendSessionId &&\n !useAssistantStore.getState().processingByConversationId[conversation.id]\n );\n\n if (reusableDraft) {\n setActiveConversation(reusableDraft.id);\n } else {\n createConversation(undefined, newMode);\n }\n }\n } else if (activeConversationId) {\n setConversationMode(activeConversationId, newMode);\n }\n\n setMode(newMode);\n },\n [activeConversationId, createConversation, setActiveConversation, setConversationMode, setMode]\n );\n\n const handleModeChange = useCallback(\n (newMode: AssistantMode) => {\n const target = ASSISTANT_MODES.find((modeConfig) => modeConfig.id === newMode);\n // Gate the FIRST switch into a write-capable mode behind the one-time\n // consent dialog — the dependable confirm-before-mutate guardrail.\n if (target?.writeCapable && !useAssistantStore.getState().apiCallsAcknowledged) {\n setPendingConsentMode(newMode);\n return;\n }\n performModeChange(newMode);\n },\n [performModeChange]\n );\n\n const handleConsentConfirm = useCallback(() => {\n const target = pendingConsentMode;\n setPendingConsentMode(null);\n acknowledgeApiCalls();\n if (target) performModeChange(target);\n }, [pendingConsentMode, acknowledgeApiCalls, performModeChange]);\n\n const handleConsentCancel = useCallback(() => {\n setPendingConsentMode(null);\n }, []);\n\n return (\n <div className=\"flex flex-1 flex-col overflow-hidden\">\n {/* Transcript is always visible now — the old collapse-by-default accordion\n is gone; conversation history lives behind the header button instead. */}\n {messages.length === 0 ? (\n <AssistantEmptyState mode={mode} onSuggestionClick={handleSuggestionClick} />\n ) : (\n <div className=\"flex min-h-0 flex-1 flex-col\">\n <AssistantMessageList\n messages={messages}\n streamingMessageId={activeStreamingMessageId}\n failedMessageId={failedMessageId}\n onRetry={handleRetry}\n />\n </div>\n )}\n\n <AssistantComposer\n onSend={(value, attachments) => void handleSend(value, attachments)}\n disabled={activeIsProcessing}\n placeholder={\n mode === 'api-calls'\n ? tr('healthybowl.assistant.chatArea.placeholderActions', 'What would you like me to do?')\n : tr('healthybowl.assistant.chatArea.placeholderGeneral', 'Ask HealthyBowl anything…')\n }\n mode={mode}\n availableModes={availableModes}\n onModeChange={handleModeChange}\n />\n\n <AssistantApiCallsConsentDialog\n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,EAAQ;IAElB;EAAC;EAAsB;EAAoB;EAAuB;EAAqB;EAAQ,CAChG,EAEK,KAAmB,GACtB,MAA2B;AAI1B,MAHe,EAAgB,MAAM,MAAe,EAAW,OAAO,EAAQ,EAGlE,gBAAgB,CAAC,EAAkB,UAAU,CAAC,sBAAsB;AAC9E,MAAsB,EAAQ;AAC9B;;AAEF,IAAkB,EAAQ;IAE5B,CAAC,EAAkB,CACpB,EAEK,KAAuB,QAAkB;EAC7C,IAAM,IAAS;AAGf,EAFA,GAAsB,KAAK,EAC3B,IAAqB,EACjB,KAAQ,EAAkB,EAAO;IACpC;EAAC;EAAoB;EAAqB;EAAkB,CAAC,EAE1D,KAAsB,QAAkB;AAC5C,KAAsB,KAAK;IAC1B,EAAE,CAAC;AAEN,QACE,mBAAC,OAAD;EAAK,WAAU;YAAf;GAGG,EAAS,WAAW,IACnB,kBAAC,GAAD;IAA2B;IAAM,mBAAmB;IAAyB,CAAA,GAE7E,kBAAC,OAAD;IAAK,WAAU;cACb,kBAAC,GAAD;KACY;KACV,oBAAoB;KACH;KACjB,SAAS;KACT,CAAA;IACE,CAAA;GAGR,kBAAC,GAAD;IACE,SAAS,GAAO,MAAgB,KAAK,EAAW,GAAO,EAAY;IACnE,UAAU;IACV,aACE,MAAS,cACL,EAAG,qDAAqD,gCAAgC,GACxF,EAAG,qDAAqD,4BAA4B;IAEpF;IACU;IAChB,cAAc;IACd,CAAA;GAEF,kBAAC,GAAD;IACE,MAAM,MAAuB;IAC7B,WAAW;IACX,UAAU;IACV,CAAA;GACE"}
@@ -9,6 +9,11 @@ var c = {
9
9
  fallback: "Ask",
10
10
  icon: i
11
11
  },
12
+ assistant: {
13
+ i18nKey: "healthybowl.assistant.mode.ask",
14
+ fallback: "Ask",
15
+ icon: i
16
+ },
12
17
  "api-calls": {
13
18
  i18nKey: "healthybowl.assistant.mode.takeAction",
14
19
  fallback: "Take action",
@@ -1 +1 @@
1
- {"version":3,"file":"AssistantModeSelector.js","names":[],"sources":["../../../../src/components/assistant/composer/AssistantModeSelector.tsx"],"sourcesContent":["import { useCallback, useRef, type FC, type KeyboardEvent } from 'react';\nimport { Sparkles, ShieldCheck, Zap, type LucideIcon } from 'lucide-react';\nimport type { AssistantMode, AssistantModeConfig } from '@/types/assistant';\nimport { useTr } from '../../../shared/hooks/useTr';\n\ninterface Props {\n mode: AssistantMode;\n /** Role-filtered list of modes the user may pick (admin-gated modes removed). */\n availableModes: AssistantModeConfig[];\n onModeChange: (mode: AssistantMode) => void;\n disabled?: boolean;\n}\n\n/**\n * Per-mode presentation metadata. The i18n key + English fallback provide the\n * relabelled display name ('Ask' / 'Take action') while the mode ID stays the\n * transport-level value ('general' / 'api-calls' / 'vibe-plugins').\n */\nexport const ASSISTANT_MODE_META: Record<AssistantMode, { i18nKey: string; fallback: string; icon: LucideIcon }> = {\n general: { i18nKey: 'healthybowl.assistant.mode.ask', fallback: 'Ask', icon: Sparkles },\n 'api-calls': { i18nKey: 'healthybowl.assistant.mode.takeAction', fallback: 'Take action', icon: ShieldCheck },\n 'vibe-plugins': { i18nKey: 'healthybowl.assistant.mode.build', fallback: 'Build', icon: Zap },\n};\n\n/**\n * Where an arrow/Home/End keypress should move within a roving group.\n *\n * Extracted and exported so the wrap-around arithmetic — including the\n * `currentIndex === -1` case, which means \"focus is not on any pill yet\" — is\n * unit-testable in a repo whose test environment has no DOM. Returns null when\n * the key is not one this group handles.\n */\nexport function nextModeIndex(key: string, currentIndex: number, lastIndex: number): number | null {\n switch (key) {\n case 'Home':\n return 0;\n case 'End':\n return lastIndex;\n case 'ArrowRight':\n case 'ArrowDown':\n return currentIndex >= lastIndex ? 0 : currentIndex + 1;\n case 'ArrowLeft':\n case 'ArrowUp':\n // -1 enters the group from the END, which is what the key implies.\n return currentIndex <= 0 ? lastIndex : currentIndex - 1;\n default:\n return null;\n }\n}\n\n/**\n * Segmented \"pill\" mode selector shown BELOW the composer input (per the v2\n * mockups): the active mode is a filled forest-green pill, the others are\n * ghosted outlines. Replaces the old dropdown trigger. HB semantic tokens only.\n *\n * Exposed as a **radiogroup**, not a tablist: these pills pick one option, they\n * do not reveal panels, and a `role=\"tab\"` with no `tabpanel` misdescribes the\n * control to a screen reader. Focus roves — one Tab stop for the group, arrow\n * keys to move between pills — which is what the radio pattern requires and\n * what a keyboard user expects from a segmented control.\n */\nexport const AssistantModeSelector: FC<Props> = ({ mode, availableModes, onModeChange, disabled = false }) => {\n const tr = useTr();\n const groupRef = useRef<HTMLDivElement>(null);\n\n const handleKeyDown = useCallback(\n (event: KeyboardEvent<HTMLDivElement>) => {\n if (disabled) return;\n\n // Move relative to the pill that actually has FOCUS, not to the selected\n // mode. The two normally agree (selection follows focus here), but they\n // come apart whenever the parent has not applied the change yet, or the\n // selected mode is not in `availableModes` at all — a persisted\n // admin-only mode seen by a non-admin, where findIndex returns -1. Keying\n // off the prop in that state made the arrows jump somewhere unrelated.\n // `event.target` is the focused pill, read synchronously from the event\n // that the keypress bubbled up from.\n const focusedId = (event.target as HTMLElement | null)?.closest<HTMLElement>('[data-mode-id]')?.dataset.modeId;\n const focusedIndex = focusedId ? availableModes.findIndex((modeConfig) => modeConfig.id === focusedId) : -1;\n // Still -1 when the group itself has focus: the arithmetic below then\n // enters the group from whichever end the key implies, which is the right\n // behaviour rather than a case to guard.\n const currentIndex = focusedIndex >= 0 ? focusedIndex : availableModes.findIndex((m) => m.id === mode);\n const nextIndex = nextModeIndex(event.key, currentIndex, availableModes.length - 1);\n if (nextIndex === null) return;\n event.preventDefault();\n\n const next = availableModes[nextIndex];\n if (!next) return;\n // Focus always moves, even when the selection does not. Bailing out on\n // `next.id === mode` made the arrow keys a dead no-op in exactly the\n // focus-vs-selection divergence this handler now understands.\n groupRef.current?.querySelector<HTMLButtonElement>(`[data-mode-id=\"${next.id}\"]`)?.focus();\n if (next.id !== mode) onModeChange(next.id);\n },\n [availableModes, disabled, mode, onModeChange]\n );\n\n // Nothing to switch between — hide the control entirely (keeps the composer\n // clean for non-admins who only ever have the single \"Ask\" mode).\n if (availableModes.length < 2) return null;\n\n return (\n <div\n ref={groupRef}\n role=\"radiogroup\"\n aria-label={tr('healthybowl.assistant.modeSelector.ariaLabel', 'Select assistant mode')}\n onKeyDown={handleKeyDown}\n className=\"inline-flex items-center gap-1 rounded-full border border-border-subtle bg-bg-elevated p-1\"\n data-testid=\"assistant-mode-selector\"\n >\n {availableModes.map((modeConfig) => {\n const meta = ASSISTANT_MODE_META[modeConfig.id];\n const Icon = meta.icon;\n const isActive = modeConfig.id === mode;\n return (\n <button\n type=\"button\"\n role=\"radio\"\n key={modeConfig.id}\n aria-checked={isActive}\n tabIndex={isActive ? 0 : -1}\n disabled={disabled}\n onClick={() => onModeChange(modeConfig.id)}\n data-mode-id={modeConfig.id}\n className={`flex items-center gap-1.5 rounded-full px-3 py-1.5 text-[13px] font-medium transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong disabled:opacity-50 ${\n isActive\n ? 'bg-action-primary-bg text-action-primary-text shadow-sm'\n : 'text-text-secondary hover:bg-bg-surface hover:text-text-primary'\n }`}\n data-testid={`assistant-mode-option-${modeConfig.id}`}\n >\n <Icon className=\"size-3.5\" aria-hidden=\"true\" />\n <span>{tr(meta.i18nKey, meta.fallback)}</span>\n </button>\n );\n })}\n </div>\n );\n};\n"],"mappings":";;;;;AAkBA,IAAa,IAAsG;CACjH,SAAS;EAAE,SAAS;EAAkC,UAAU;EAAO,MAAM;EAAU;CACvF,aAAa;EAAE,SAAS;EAAyC,UAAU;EAAe,MAAM;EAAa;CAC7G,gBAAgB;EAAE,SAAS;EAAoC,UAAU;EAAS,MAAM;EAAK;CAC9F;AAUD,SAAgB,EAAc,GAAa,GAAsB,GAAkC;AACjG,SAAQ,GAAR;EACE,KAAK,OACH,QAAO;EACT,KAAK,MACH,QAAO;EACT,KAAK;EACL,KAAK,YACH,QAAO,KAAgB,IAAY,IAAI,IAAe;EACxD,KAAK;EACL,KAAK,UAEH,QAAO,KAAgB,IAAI,IAAY,IAAe;E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;IAEX;EACE,CAAA"}
1
+ {"version":3,"file":"AssistantModeSelector.js","names":[],"sources":["../../../../src/components/assistant/composer/AssistantModeSelector.tsx"],"sourcesContent":["import { useCallback, useRef, type FC, type KeyboardEvent } from 'react';\nimport { Sparkles, ShieldCheck, Zap, type LucideIcon } from 'lucide-react';\nimport type { AssistantMode, AssistantModeConfig } from '@/types/assistant';\nimport { useTr } from '../../../shared/hooks/useTr';\n\ninterface Props {\n mode: AssistantMode;\n /** Role-filtered list of modes the user may pick (admin-gated modes removed). */\n availableModes: AssistantModeConfig[];\n onModeChange: (mode: AssistantMode) => void;\n disabled?: boolean;\n}\n\n/**\n * Per-mode presentation metadata. The i18n key + English fallback provide the\n * relabelled display name ('Ask' / 'Take action') while the mode ID stays the\n * transport-level value ('general' / 'api-calls' / 'vibe-plugins').\n */\nexport const ASSISTANT_MODE_META: Record<AssistantMode, { i18nKey: string; fallback: string; icon: LucideIcon }> = {\n general: { i18nKey: 'healthybowl.assistant.mode.ask', fallback: 'Ask', icon: Sparkles },\n assistant: { i18nKey: 'healthybowl.assistant.mode.ask', fallback: 'Ask', icon: Sparkles },\n 'api-calls': { i18nKey: 'healthybowl.assistant.mode.takeAction', fallback: 'Take action', icon: ShieldCheck },\n 'vibe-plugins': { i18nKey: 'healthybowl.assistant.mode.build', fallback: 'Build', icon: Zap },\n};\n\n/**\n * Where an arrow/Home/End keypress should move within a roving group.\n *\n * Extracted and exported so the wrap-around arithmetic — including the\n * `currentIndex === -1` case, which means \"focus is not on any pill yet\" — is\n * unit-testable in a repo whose test environment has no DOM. Returns null when\n * the key is not one this group handles.\n */\nexport function nextModeIndex(key: string, currentIndex: number, lastIndex: number): number | null {\n switch (key) {\n case 'Home':\n return 0;\n case 'End':\n return lastIndex;\n case 'ArrowRight':\n case 'ArrowDown':\n return currentIndex >= lastIndex ? 0 : currentIndex + 1;\n case 'ArrowLeft':\n case 'ArrowUp':\n // -1 enters the group from the END, which is what the key implies.\n return currentIndex <= 0 ? lastIndex : currentIndex - 1;\n default:\n return null;\n }\n}\n\n/**\n * Segmented \"pill\" mode selector shown BELOW the composer input (per the v2\n * mockups): the active mode is a filled forest-green pill, the others are\n * ghosted outlines. Replaces the old dropdown trigger. HB semantic tokens only.\n *\n * Exposed as a **radiogroup**, not a tablist: these pills pick one option, they\n * do not reveal panels, and a `role=\"tab\"` with no `tabpanel` misdescribes the\n * control to a screen reader. Focus roves — one Tab stop for the group, arrow\n * keys to move between pills — which is what the radio pattern requires and\n * what a keyboard user expects from a segmented control.\n */\nexport const AssistantModeSelector: FC<Props> = ({ mode, availableModes, onModeChange, disabled = false }) => {\n const tr = useTr();\n const groupRef = useRef<HTMLDivElement>(null);\n\n const handleKeyDown = useCallback(\n (event: KeyboardEvent<HTMLDivElement>) => {\n if (disabled) return;\n\n // Move relative to the pill that actually has FOCUS, not to the selected\n // mode. The two normally agree (selection follows focus here), but they\n // come apart whenever the parent has not applied the change yet, or the\n // selected mode is not in `availableModes` at all — a persisted\n // admin-only mode seen by a non-admin, where findIndex returns -1. Keying\n // off the prop in that state made the arrows jump somewhere unrelated.\n // `event.target` is the focused pill, read synchronously from the event\n // that the keypress bubbled up from.\n const focusedId = (event.target as HTMLElement | null)?.closest<HTMLElement>('[data-mode-id]')?.dataset.modeId;\n const focusedIndex = focusedId ? availableModes.findIndex((modeConfig) => modeConfig.id === focusedId) : -1;\n // Still -1 when the group itself has focus: the arithmetic below then\n // enters the group from whichever end the key implies, which is the right\n // behaviour rather than a case to guard.\n const currentIndex = focusedIndex >= 0 ? focusedIndex : availableModes.findIndex((m) => m.id === mode);\n const nextIndex = nextModeIndex(event.key, currentIndex, availableModes.length - 1);\n if (nextIndex === null) return;\n event.preventDefault();\n\n const next = availableModes[nextIndex];\n if (!next) return;\n // Focus always moves, even when the selection does not. Bailing out on\n // `next.id === mode` made the arrow keys a dead no-op in exactly the\n // focus-vs-selection divergence this handler now understands.\n groupRef.current?.querySelector<HTMLButtonElement>(`[data-mode-id=\"${next.id}\"]`)?.focus();\n if (next.id !== mode) onModeChange(next.id);\n },\n [availableModes, disabled, mode, onModeChange]\n );\n\n // Nothing to switch between — hide the control entirely (keeps the composer\n // clean for non-admins who only ever have the single \"Ask\" mode).\n if (availableModes.length < 2) return null;\n\n return (\n <div\n ref={groupRef}\n role=\"radiogroup\"\n aria-label={tr('healthybowl.assistant.modeSelector.ariaLabel', 'Select assistant mode')}\n onKeyDown={handleKeyDown}\n className=\"inline-flex items-center gap-1 rounded-full border border-border-subtle bg-bg-elevated p-1\"\n data-testid=\"assistant-mode-selector\"\n >\n {availableModes.map((modeConfig) => {\n const meta = ASSISTANT_MODE_META[modeConfig.id];\n const Icon = meta.icon;\n const isActive = modeConfig.id === mode;\n return (\n <button\n type=\"button\"\n role=\"radio\"\n key={modeConfig.id}\n aria-checked={isActive}\n tabIndex={isActive ? 0 : -1}\n disabled={disabled}\n onClick={() => onModeChange(modeConfig.id)}\n data-mode-id={modeConfig.id}\n className={`flex items-center gap-1.5 rounded-full px-3 py-1.5 text-[13px] font-medium transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong disabled:opacity-50 ${\n isActive\n ? 'bg-action-primary-bg text-action-primary-text shadow-sm'\n : 'text-text-secondary hover:bg-bg-surface hover:text-text-primary'\n }`}\n data-testid={`assistant-mode-option-${modeConfig.id}`}\n >\n <Icon className=\"size-3.5\" aria-hidden=\"true\" />\n <span>{tr(meta.i18nKey, meta.fallback)}</span>\n </button>\n );\n })}\n </div>\n );\n};\n"],"mappings":";;;;;AAkBA,IAAa,IAAsG;CACjH,SAAS;EAAE,SAAS;EAAkC,UAAU;EAAO,MAAM;EAAU;CACvF,WAAW;EAAE,SAAS;EAAkC,UAAU;EAAO,MAAM;EAAU;CACzF,aAAa;EAAE,SAAS;EAAyC,UAAU;EAAe,MAAM;EAAa;CAC7G,gBAAgB;EAAE,SAAS;EAAoC,UAAU;EAAS,MAAM;EAAK;CAC9F;AAUD,SAAgB,EAAc,GAAa,GAAsB,GAAkC;AACjG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,yBAAyB,EAAW;cAdnD,CAgBE,kBAAC,GAAD;KAAM,WAAU;KAAW,eAAY;KAAS,CAAA,EAChD,kBAAC,QAAD,EAAA,UAAO,EAAG,EAAK,SAAS,EAAK,SAAS,EAAQ,CAAA,CACvC;MAfF,EAAW,GAeT;IAEX;EACE,CAAA"}
@@ -1,12 +1,12 @@
1
1
  //#region src/config/assistantUsecases.ts
2
2
  var e = typeof window < "u", t = {
3
- id: "general",
3
+ id: "assistant",
4
4
  label: "Ask",
5
- description: "General help with HealthyBowl — crops, livestock, the marketplace, and farm operations",
5
+ description: "Ask about HealthyBowl and your own farm data — crops, livestock, weather, finances. Reads your live records; use \"Take action\" to make changes.",
6
6
  suggestions: [
7
- "How do I add a new crop?",
7
+ "List all my livestock",
8
+ "How many crops do I have?",
8
9
  "Explain the livestock health tracker",
9
- "How does the marketplace work?",
10
10
  "What government schemes can I apply for?"
11
11
  ]
12
12
  }, n = e ? [t, {
@@ -1 +1 @@
1
- {"version":3,"file":"assistantUsecases.js","names":[],"sources":["../../src/config/assistantUsecases.ts"],"sourcesContent":["/**\n * HealthyBowl AI Assistant usecases.\n *\n * `AssistantUsecaseId` is the full set of modes the transport/runtime\n * understands — it drives the image/resource switches in `services/assistantApi`.\n * `ASSISTANT_USECASE_CONFIG` is the set of modes the panel KNOWS about; the mode\n * selector further filters them at runtime by the user's role (see\n * `useAssistantApiAccess`) so a write-capable mode only appears for org admins.\n * - `general` — docs Q&A (proxy-token auth, available to everyone).\n * - `api-calls` — WRITE-CAPABLE: the agent executes GraphQL on the user's\n * behalf (app-client-credentials auth). Minting its per-sandbox OAuth app\n * requires a global Owner/Admin actor, so it is gated to admins, guarded by a\n * confirm-before-mutate dialog + a soft agent preamble, and master-flagged.\n * - `vibe-plugins` — a VibeControls-only concept HealthyBowl never exposes.\n */\n\n// Full set of runtime-understood modes. Keep in sync with the image/resource\n// switches in `services/assistantApi.ts`.\nexport type AssistantUsecaseId = 'general' | 'api-calls' | 'vibe-plugins';\n\nexport interface AssistantUsecase {\n id: AssistantUsecaseId;\n label: string;\n description: string;\n suggestions: readonly string[];\n /** Only offered to a global Owner/Admin (minting the OAuth app needs admin). */\n requiresAdmin?: boolean;\n /** Executes mutations on live data → triggers the confirm-before-mutate guard. */\n writeCapable?: boolean;\n}\n\n/**\n * Master switch for the write-capable `api-calls` (\"Actions\") mode. Enabled on\n * ALL environments (alpha + production) as of 2026-06-30, by explicit product\n * decision. The mode remains gated by: (1) the admin check — only org\n * Owners/Admins ever see it (useAssistantApiAccess), (2) a one-time consent\n * dialog, and (3) a describe-and-confirm instruction prepended to the prompt.\n * The in-sandbox agent still auto-executes (no hard server-side confirm yet) —\n * that residual risk was accepted when enabling on prod.\n *\n * `typeof window` keeps it false during any non-browser evaluation; in the\n * browser it's always on (the admin gate is the real boundary).\n */\nexport const API_CALLS_MODE_ENABLED = typeof window !== 'undefined';\n\nconst GENERAL: AssistantUsecase = {\n id: 'general',\n // Display label only — the mode ID stays 'general' (see services/assistantApi).\n label: 'Ask',\n description: 'General help with HealthyBowl — crops, livestock, the marketplace, and farm operations',\n suggestions: [\n 'How do I add a new crop?',\n 'Explain the livestock health tracker',\n 'How does the marketplace work?',\n 'What government schemes can I apply for?',\n ],\n};\n\nconst API_CALLS: AssistantUsecase = {\n id: 'api-calls',\n // Display label only — the mode ID stays 'api-calls' (see services/assistantApi).\n label: 'Take action',\n description:\n 'Let the assistant take actions for you — add crops, log harvests, update records. It describes what it will do and asks before changing anything.',\n suggestions: [\n 'Add a new crop',\n 'Log a harvest for one of my fields',\n 'List all my livestock',\n \"Update a crop's status\",\n ],\n requiresAdmin: true,\n writeCapable: true,\n};\n\n// Modes the panel knows about. Phase 1 = general; phase 2 adds api-calls (admin-\n// gated + guarded). The mode selector filters this further by role at runtime.\nexport const ASSISTANT_USECASE_CONFIG: readonly AssistantUsecase[] = API_CALLS_MODE_ENABLED\n ? [GENERAL, API_CALLS]\n : [GENERAL];\n"],"mappings":";AA2CA,IAAa,IAAyB,OAAO,SAAW,KAElD,IAA4B;CAChC,IAAI;CAEJ,OAAO;CACP,aAAa;CACb,aAAa;EACX;EACA;EACA;EACA;EACD;CACF,EAoBY,IAAwD,IACjE,CAAC,GAnB+B;CAClC,IAAI;CAEJ,OAAO;CACP,aACE;CACF,aAAa;EACX;EACA;EACA;EACA;EACD;CACD,eAAe;CACf,cAAc;CACf,CAKuB,GACpB,CAAC,EAAQ"}
1
+ {"version":3,"file":"assistantUsecases.js","names":[],"sources":["../../src/config/assistantUsecases.ts"],"sourcesContent":["/**\n * HealthyBowl AI Assistant usecases.\n *\n * `AssistantUsecaseId` is the full set of modes the transport/runtime\n * understands — it drives the image/resource switches in `services/assistantApi`.\n * `ASSISTANT_USECASE_CONFIG` is the set of modes the panel KNOWS about; the mode\n * selector further filters them at runtime by the user's role (see\n * `useAssistantApiAccess`) so a write-capable mode only appears for org admins.\n * - `general` — docs Q&A (proxy-token auth, available to everyone).\n * - `api-calls` — WRITE-CAPABLE: the agent executes GraphQL on the user's\n * behalf (app-client-credentials auth). Minting its per-sandbox OAuth app\n * requires a global Owner/Admin actor, so it is gated to admins, guarded by a\n * confirm-before-mutate dialog + a soft agent preamble, and master-flagged.\n * - `vibe-plugins` — a VibeControls-only concept HealthyBowl never exposes.\n */\n\n// Full set of runtime-understood modes. Keep in sync with the image/resource\n// switches in `services/assistantApi.ts`.\nexport type AssistantUsecaseId = 'general' | 'assistant' | 'api-calls' | 'vibe-plugins';\n\nexport interface AssistantUsecase {\n id: AssistantUsecaseId;\n label: string;\n description: string;\n suggestions: readonly string[];\n /** Only offered to a global Owner/Admin (minting the OAuth app needs admin). */\n requiresAdmin?: boolean;\n /** Executes mutations on live data → triggers the confirm-before-mutate guard. */\n writeCapable?: boolean;\n}\n\n/**\n * Master switch for the write-capable `api-calls` (\"Actions\") mode. Enabled on\n * ALL environments (alpha + production) as of 2026-06-30, by explicit product\n * decision. The mode remains gated by: (1) the admin check — only org\n * Owners/Admins ever see it (useAssistantApiAccess), (2) a one-time consent\n * dialog, and (3) a describe-and-confirm instruction prepended to the prompt.\n * The in-sandbox agent still auto-executes (no hard server-side confirm yet) —\n * that residual risk was accepted when enabling on prod.\n *\n * `typeof window` keeps it false during any non-browser evaluation; in the\n * browser it's always on (the admin gate is the real boundary).\n */\nexport const API_CALLS_MODE_ENABLED = typeof window !== 'undefined';\n\n// Default \"Ask\" for EVERY user: docs Q&A + READ-ONLY live data. Unlike\n// `api-calls` it authenticates with the user's OWN forwarded token (no\n// admin-gated OAuth-app mint), and the in-sandbox helper rejects mutations\n// (AI_ASSISTANT_READONLY) — so it needs no admin and answers questions like\n// \"list my livestock\" against real data. Writes live in `api-calls` below.\nconst ASSISTANT: AssistantUsecase = {\n id: 'assistant',\n label: 'Ask',\n description:\n 'Ask about HealthyBowl and your own farm data — crops, livestock, weather, finances. Reads your live records; use \"Take action\" to make changes.',\n suggestions: [\n 'List all my livestock',\n 'How many crops do I have?',\n 'Explain the livestock health tracker',\n 'What government schemes can I apply for?',\n ],\n};\n\nconst API_CALLS: AssistantUsecase = {\n id: 'api-calls',\n // Display label only — the mode ID stays 'api-calls' (see services/assistantApi).\n label: 'Take action',\n description:\n 'Let the assistant take actions for you — add crops, log harvests, update records. It describes what it will do and asks before changing anything.',\n suggestions: [\n 'Add a new crop',\n 'Log a harvest for one of my fields',\n 'List all my livestock',\n \"Update a crop's status\",\n ],\n requiresAdmin: true,\n writeCapable: true,\n};\n\n// Modes the panel knows about. The default \"Ask\" is now the read-only\n// `assistant` mode (docs + live data, available to everyone). `api-calls`\n// (\"Take action\", write) is added when enabled and further filtered to admins\n// at runtime by the mode selector. `general` (docs-only) is retained in the\n// type for back-compat with persisted conversations but no longer surfaced.\nexport const ASSISTANT_USECASE_CONFIG: readonly AssistantUsecase[] = API_CALLS_MODE_ENABLED\n ? [ASSISTANT, API_CALLS]\n : [ASSISTANT];\n"],"mappings":";AA2CA,IAAa,IAAyB,OAAO,SAAW,KAOlD,IAA8B;CAClC,IAAI;CACJ,OAAO;CACP,aACE;CACF,aAAa;EACX;EACA;EACA;EACA;EACD;CACF,EAuBY,IAAwD,IACjE,CAAC,GAtB+B;CAClC,IAAI;CAEJ,OAAO;CACP,aACE;CACF,aAAa;EACX;EACA;EACA;EACA;EACD;CACD,eAAe;CACf,cAAc;CACf,CAQyB,GACtB,CAAC,EAAU"}
@@ -8,7 +8,7 @@ function r() {
8
8
  var i = e()(t((e, t) => ({
9
9
  conversations: [],
10
10
  activeConversationId: null,
11
- mode: "general",
11
+ mode: "assistant",
12
12
  processingByConversationId: {},
13
13
  conversationListOpen: !1,
14
14
  sandboxesByMode: {},
@@ -139,7 +139,7 @@ var i = e()(t((e, t) => ({
139
139
  resetStore: () => e({
140
140
  conversations: [],
141
141
  activeConversationId: null,
142
- mode: "general",
142
+ mode: "assistant",
143
143
  processingByConversationId: {},
144
144
  conversationListOpen: !1,
145
145
  sandboxesByMode: {},
@@ -1 +1 @@
1
- {"version":3,"file":"assistantStore.js","names":[],"sources":["../../src/store/assistantStore.ts"],"sourcesContent":["/**\n * AI Assistant state management.\n *\n * Zustand store with profile-scoped persistence for conversations,\n * active mode, and streaming state. Follows the same pattern as\n * healthybowlStore.ts.\n */\n\nimport { create } from 'zustand';\nimport { persist } from 'zustand/middleware';\nimport { createProfileScopedStorage } from '@burdenoff/fe-libs/shared/utils';\nimport type {\n AssistantConversationProcessing,\n AssistantConversationStatus,\n AssistantMode,\n AssistantSandboxRuntime,\n AssistantSandboxStatus,\n Conversation,\n Message,\n} from '@/types/assistant';\n\ninterface AssistantState {\n conversations: Conversation[];\n activeConversationId: string | null;\n mode: AssistantMode;\n processingByConversationId: Record<string, AssistantConversationProcessing>;\n conversationListOpen: boolean;\n /** Active sandboxes keyed by assistant mode */\n sandboxesByMode: Partial<Record<AssistantMode, AssistantSandboxRuntime>>;\n /**\n * A prompt queued up for auto-submit by the chat area. Used by the\n * `GetHelpButton` / `useOpenAssistantHelp` hook so pages can prompt the\n * assistant contextually from an empty state button without coupling to\n * the chat area internals.\n */\n pendingPrompt: string | null;\n /**\n * Whether the user has acknowledged the api-calls (write) mode consent\n * dialog. Persisted per-profile so the warning shows once, not every switch.\n */\n apiCallsAcknowledged: boolean;\n\n // Actions\n createConversation: (title?: string, mode?: AssistantMode) => string;\n deleteConversation: (id: string) => void;\n renameConversation: (id: string, title: string) => void;\n setActiveConversation: (id: string | null) => void;\n setMode: (mode: AssistantMode) => void;\n setConversationMode: (conversationId: string, mode: AssistantMode) => void;\n addMessage: (conversationId: string, message: Message) => void;\n updateMessage: (conversationId: string, messageId: string, content: string) => void;\n patchMessage: (conversationId: string, messageId: string, patch: Partial<Message>) => void;\n setConversationProcessing: (\n conversationId: string,\n status: AssistantConversationStatus,\n messageId?: string | null,\n error?: string | null\n ) => void;\n clearConversationProcessing: (conversationId: string) => void;\n toggleConversationList: () => void;\n setConversationListOpen: (open: boolean) => void;\n clearConversation: (id: string) => void;\n setBackendSessionId: (conversationId: string, sessionId: string) => void;\n clearBackendSessionId: (conversationId: string) => void;\n setSandbox: (mode: AssistantMode, sandboxId: string | null, status: AssistantSandboxStatus) => void;\n clearSandbox: (mode: AssistantMode) => void;\n resetStore: () => void;\n /** Queue a prompt for the chat area to auto-send on next render. */\n submitPrompt: (text: string) => void;\n /** Returns and clears any queued prompt. */\n consumePendingPrompt: () => string | null;\n /** Mark the api-calls write-mode consent as acknowledged (persisted). */\n acknowledgeApiCalls: () => void;\n}\n\nfunction generateId(): string {\n return `${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;\n}\n\nexport const useAssistantStore = create<AssistantState>()(\n persist(\n (set, get) => ({\n conversations: [],\n activeConversationId: null,\n mode: 'general',\n processingByConversationId: {},\n conversationListOpen: false,\n sandboxesByMode: {},\n pendingPrompt: null,\n apiCallsAcknowledged: false,\n\n createConversation: (title?: string, mode?: AssistantMode) => {\n const id = generateId();\n const now = new Date().toISOString();\n const conversationMode = mode ?? get().mode;\n const conversation: Conversation = {\n id,\n title: title || 'New conversation',\n mode: conversationMode,\n messages: [],\n backendSessionId: null,\n createdAt: now,\n updatedAt: now,\n };\n set((state) => ({\n conversations: [conversation, ...state.conversations],\n activeConversationId: id,\n conversationListOpen: false,\n }));\n return id;\n },\n\n deleteConversation: (id) =>\n set((state) => {\n const filtered = state.conversations.filter((c) => c.id !== id);\n const nextProcessing = { ...state.processingByConversationId };\n delete nextProcessing[id];\n return {\n conversations: filtered,\n processingByConversationId: nextProcessing,\n activeConversationId:\n state.activeConversationId === id ? (filtered[0]?.id ?? null) : state.activeConversationId,\n };\n }),\n\n renameConversation: (id, title) =>\n set((state) => ({\n conversations: state.conversations.map((c) =>\n c.id === id ? { ...c, title, updatedAt: new Date().toISOString() } : c\n ),\n })),\n\n setActiveConversation: (id) =>\n set((state) => {\n const selectedConversation = state.conversations.find((conversation) => conversation.id === id);\n return {\n activeConversationId: id,\n mode: selectedConversation?.mode ?? state.mode,\n conversationListOpen: false,\n };\n }),\n\n setMode: (mode) => set({ mode }),\n\n setConversationMode: (conversationId, mode) =>\n set((state) => ({\n conversations: state.conversations.map((conversation) =>\n conversation.id === conversationId\n ? {\n ...conversation,\n mode,\n updatedAt: new Date().toISOString(),\n }\n : conversation\n ),\n mode: state.activeConversationId === conversationId ? mode : state.mode,\n })),\n\n addMessage: (conversationId, message) =>\n set((state) => ({\n conversations: state.conversations.map((c) =>\n c.id === conversationId\n ? {\n ...c,\n messages: [...c.messages, message],\n updatedAt: new Date().toISOString(),\n // Auto-title from first user message\n title:\n c.messages.length === 0 && message.role === 'user'\n ? message.content.slice(0, 50) + (message.content.length > 50 ? '...' : '')\n : c.title,\n }\n : c\n ),\n })),\n\n updateMessage: (conversationId, messageId, content) =>\n set((state) => ({\n conversations: state.conversations.map((c) =>\n c.id === conversationId\n ? {\n ...c,\n messages: c.messages.map((m) => (m.id === messageId ? { ...m, content } : m)),\n updatedAt: new Date().toISOString(),\n }\n : c\n ),\n })),\n\n patchMessage: (conversationId, messageId, patch) =>\n set((state) => ({\n conversations: state.conversations.map((c) =>\n c.id === conversationId\n ? {\n ...c,\n messages: c.messages.map((m) => (m.id === messageId ? { ...m, ...patch } : m)),\n updatedAt: new Date().toISOString(),\n }\n : c\n ),\n })),\n\n setConversationProcessing: (conversationId, status, messageId = null, error = null) =>\n set((state) => ({\n processingByConversationId: {\n ...state.processingByConversationId,\n [conversationId]: {\n status,\n messageId,\n error,\n updatedAt: new Date().toISOString(),\n },\n },\n })),\n\n clearConversationProcessing: (conversationId) =>\n set((state) => {\n const next = { ...state.processingByConversationId };\n delete next[conversationId];\n return { processingByConversationId: next };\n }),\n\n toggleConversationList: () => set((state) => ({ conversationListOpen: !state.conversationListOpen })),\n\n setConversationListOpen: (open) => set({ conversationListOpen: open }),\n\n clearConversation: (id) =>\n set((state) => ({\n conversations: state.conversations.map((c) =>\n c.id === id\n ? {\n ...c,\n messages: [],\n backendSessionId: null,\n updatedAt: new Date().toISOString(),\n }\n : c\n ),\n processingByConversationId: {\n ...state.processingByConversationId,\n [id]: {\n status: 'idle',\n messageId: null,\n error: null,\n updatedAt: new Date().toISOString(),\n },\n },\n })),\n\n setBackendSessionId: (conversationId, sessionId) =>\n set((state) => ({\n conversations: state.conversations.map((c) =>\n c.id === conversationId\n ? {\n ...c,\n backendSessionId: sessionId,\n }\n : c\n ),\n })),\n\n clearBackendSessionId: (conversationId) =>\n set((state) => ({\n conversations: state.conversations.map((c) =>\n c.id === conversationId ? { ...c, backendSessionId: null } : c\n ),\n })),\n\n setSandbox: (mode, sandboxId, status) =>\n set((state) => {\n if (!sandboxId) {\n const nextSandboxesByMode = { ...state.sandboxesByMode };\n delete nextSandboxesByMode[mode];\n return { sandboxesByMode: nextSandboxesByMode };\n }\n\n return {\n sandboxesByMode: {\n ...state.sandboxesByMode,\n [mode]: {\n sandboxId,\n status,\n },\n },\n };\n }),\n\n clearSandbox: (mode) =>\n set((state) => {\n const nextSandboxesByMode = { ...state.sandboxesByMode };\n delete nextSandboxesByMode[mode];\n return { sandboxesByMode: nextSandboxesByMode };\n }),\n\n resetStore: () =>\n set({\n conversations: [],\n activeConversationId: null,\n mode: 'general',\n processingByConversationId: {},\n conversationListOpen: false,\n sandboxesByMode: {},\n pendingPrompt: null,\n apiCallsAcknowledged: false,\n }),\n\n submitPrompt: (text: string) => set({ pendingPrompt: text }),\n\n consumePendingPrompt: () => {\n const current = get().pendingPrompt;\n if (current !== null) set({ pendingPrompt: null });\n return current;\n },\n\n acknowledgeApiCalls: () => set({ apiCallsAcknowledged: true }),\n }),\n {\n name: 'hb-ai-assistant',\n storage: createProfileScopedStorage(),\n partialize: (state) => ({\n conversations: state.conversations.map(({ ...conversation }) => conversation),\n activeConversationId: state.activeConversationId,\n mode: state.mode,\n conversationListOpen: state.conversationListOpen,\n apiCallsAcknowledged: state.apiCallsAcknowledged,\n }),\n }\n )\n);\n"],"mappings":";;;;AA2EA,SAAS,IAAqB;AAC5B,QAAO,GAAG,KAAK,KAAK,CAAC,GAAG,KAAK,QAAQ,CAAC,SAAS,GAAG,CAAC,MAAM,GAAG,EAAE;;AAGhE,IAAa,IAAoB,GAAwB,CACvD,GACG,GAAK,OAAS;CACb,eAAe,EAAE;CACjB,sBAAsB;CACtB,MAAM;CACN,4BAA4B,EAAE;CAC9B,sBAAsB;CACtB,iBAAiB,EAAE;CACnB,eAAe;CACf,sBAAsB;CAEtB,qBAAqB,GAAgB,MAAyB;EAC5D,IAAM,IAAK,GAAY,EACjB,qBAAM,IAAI,MAAM,EAAC,aAAa,EAC9B,IAAmB,KAAQ,GAAK,CAAC,MACjC,IAA6B;GACjC;GACA,OAAO,KAAS;GAChB,MAAM;GACN,UAAU,EAAE;GACZ,kBAAkB;GAClB,WAAW;GACX,WAAW;GACZ;AAMD,SALA,GAAK,OAAW;GACd,eAAe,CAAC,GAAc,GAAG,EAAM,cAAc;GACrD,sBAAsB;GACtB,sBAAsB;GACvB,EAAE,EACI;;CAGT,qBAAqB,MACnB,GAAK,MAAU;EACb,IAAM,IAAW,EAAM,cAAc,QAAQ,MAAM,EAAE,OAAO,EAA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ourcesContent":["/**\n * AI Assistant state management.\n *\n * Zustand store with profile-scoped persistence for conversations,\n * active mode, and streaming state. Follows the same pattern as\n * healthybowlStore.ts.\n */\n\nimport { create } from 'zustand';\nimport { persist } from 'zustand/middleware';\nimport { createProfileScopedStorage } from '@burdenoff/fe-libs/shared/utils';\nimport type {\n AssistantConversationProcessing,\n AssistantConversationStatus,\n AssistantMode,\n AssistantSandboxRuntime,\n AssistantSandboxStatus,\n Conversation,\n Message,\n} from '@/types/assistant';\n\ninterface AssistantState {\n conversations: Conversation[];\n activeConversationId: string | null;\n mode: AssistantMode;\n processingByConversationId: Record<string, AssistantConversationProcessing>;\n conversationListOpen: boolean;\n /** Active sandboxes keyed by assistant mode */\n sandboxesByMode: Partial<Record<AssistantMode, AssistantSandboxRuntime>>;\n /**\n * A prompt queued up for auto-submit by the chat area. Used by the\n * `GetHelpButton` / `useOpenAssistantHelp` hook so pages can prompt the\n * assistant contextually from an empty state button without coupling to\n * the chat area internals.\n */\n pendingPrompt: string | null;\n /**\n * Whether the user has acknowledged the api-calls (write) mode consent\n * dialog. Persisted per-profile so the warning shows once, not every switch.\n */\n apiCallsAcknowledged: boolean;\n\n // Actions\n createConversation: (title?: string, mode?: AssistantMode) => string;\n deleteConversation: (id: string) => void;\n renameConversation: (id: string, title: string) => void;\n setActiveConversation: (id: string | null) => void;\n setMode: (mode: AssistantMode) => void;\n setConversationMode: (conversationId: string, mode: AssistantMode) => void;\n addMessage: (conversationId: string, message: Message) => void;\n updateMessage: (conversationId: string, messageId: string, content: string) => void;\n patchMessage: (conversationId: string, messageId: string, patch: Partial<Message>) => void;\n setConversationProcessing: (\n conversationId: string,\n status: AssistantConversationStatus,\n messageId?: string | null,\n error?: string | null\n ) => void;\n clearConversationProcessing: (conversationId: string) => void;\n toggleConversationList: () => void;\n setConversationListOpen: (open: boolean) => void;\n clearConversation: (id: string) => void;\n setBackendSessionId: (conversationId: string, sessionId: string) => void;\n clearBackendSessionId: (conversationId: string) => void;\n setSandbox: (mode: AssistantMode, sandboxId: string | null, status: AssistantSandboxStatus) => void;\n clearSandbox: (mode: AssistantMode) => void;\n resetStore: () => void;\n /** Queue a prompt for the chat area to auto-send on next render. */\n submitPrompt: (text: string) => void;\n /** Returns and clears any queued prompt. */\n consumePendingPrompt: () => string | null;\n /** Mark the api-calls write-mode consent as acknowledged (persisted). */\n acknowledgeApiCalls: () => void;\n}\n\nfunction generateId(): string {\n return `${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;\n}\n\nexport const useAssistantStore = create<AssistantState>()(\n persist(\n (set, get) => ({\n conversations: [],\n activeConversationId: null,\n mode: 'assistant',\n processingByConversationId: {},\n conversationListOpen: false,\n sandboxesByMode: {},\n pendingPrompt: null,\n apiCallsAcknowledged: false,\n\n createConversation: (title?: string, mode?: AssistantMode) => {\n const id = generateId();\n const now = new Date().toISOString();\n const conversationMode = mode ?? get().mode;\n const conversation: Conversation = {\n id,\n title: title || 'New conversation',\n mode: conversationMode,\n messages: [],\n backendSessionId: null,\n createdAt: now,\n updatedAt: now,\n };\n set((state) => ({\n conversations: [conversation, ...state.conversations],\n activeConversationId: id,\n conversationListOpen: false,\n }));\n return id;\n },\n\n deleteConversation: (id) =>\n set((state) => {\n const filtered = state.conversations.filter((c) => c.id !== id);\n const nextProcessing = { ...state.processingByConversationId };\n delete nextProcessing[id];\n return {\n conversations: filtered,\n processingByConversationId: nextProcessing,\n activeConversationId:\n state.activeConversationId === id ? (filtered[0]?.id ?? null) : state.activeConversationId,\n };\n }),\n\n renameConversation: (id, title) =>\n set((state) => ({\n conversations: state.conversations.map((c) =>\n c.id === id ? { ...c, title, updatedAt: new Date().toISOString() } : c\n ),\n })),\n\n setActiveConversation: (id) =>\n set((state) => {\n const selectedConversation = state.conversations.find((conversation) => conversation.id === id);\n return {\n activeConversationId: id,\n mode: selectedConversation?.mode ?? state.mode,\n conversationListOpen: false,\n };\n }),\n\n setMode: (mode) => set({ mode }),\n\n setConversationMode: (conversationId, mode) =>\n set((state) => ({\n conversations: state.conversations.map((conversation) =>\n conversation.id === conversationId\n ? {\n ...conversation,\n mode,\n updatedAt: new Date().toISOString(),\n }\n : conversation\n ),\n mode: state.activeConversationId === conversationId ? mode : state.mode,\n })),\n\n addMessage: (conversationId, message) =>\n set((state) => ({\n conversations: state.conversations.map((c) =>\n c.id === conversationId\n ? {\n ...c,\n messages: [...c.messages, message],\n updatedAt: new Date().toISOString(),\n // Auto-title from first user message\n title:\n c.messages.length === 0 && message.role === 'user'\n ? message.content.slice(0, 50) + (message.content.length > 50 ? '...' : '')\n : c.title,\n }\n : c\n ),\n })),\n\n updateMessage: (conversationId, messageId, content) =>\n set((state) => ({\n conversations: state.conversations.map((c) =>\n c.id === conversationId\n ? {\n ...c,\n messages: c.messages.map((m) => (m.id === messageId ? { ...m, content } : m)),\n updatedAt: new Date().toISOString(),\n }\n : c\n ),\n })),\n\n patchMessage: (conversationId, messageId, patch) =>\n set((state) => ({\n conversations: state.conversations.map((c) =>\n c.id === conversationId\n ? {\n ...c,\n messages: c.messages.map((m) => (m.id === messageId ? { ...m, ...patch } : m)),\n updatedAt: new Date().toISOString(),\n }\n : c\n ),\n })),\n\n setConversationProcessing: (conversationId, status, messageId = null, error = null) =>\n set((state) => ({\n processingByConversationId: {\n ...state.processingByConversationId,\n [conversationId]: {\n status,\n messageId,\n error,\n updatedAt: new Date().toISOString(),\n },\n },\n })),\n\n clearConversationProcessing: (conversationId) =>\n set((state) => {\n const next = { ...state.processingByConversationId };\n delete next[conversationId];\n return { processingByConversationId: next };\n }),\n\n toggleConversationList: () => set((state) => ({ conversationListOpen: !state.conversationListOpen })),\n\n setConversationListOpen: (open) => set({ conversationListOpen: open }),\n\n clearConversation: (id) =>\n set((state) => ({\n conversations: state.conversations.map((c) =>\n c.id === id\n ? {\n ...c,\n messages: [],\n backendSessionId: null,\n updatedAt: new Date().toISOString(),\n }\n : c\n ),\n processingByConversationId: {\n ...state.processingByConversationId,\n [id]: {\n status: 'idle',\n messageId: null,\n error: null,\n updatedAt: new Date().toISOString(),\n },\n },\n })),\n\n setBackendSessionId: (conversationId, sessionId) =>\n set((state) => ({\n conversations: state.conversations.map((c) =>\n c.id === conversationId\n ? {\n ...c,\n backendSessionId: sessionId,\n }\n : c\n ),\n })),\n\n clearBackendSessionId: (conversationId) =>\n set((state) => ({\n conversations: state.conversations.map((c) =>\n c.id === conversationId ? { ...c, backendSessionId: null } : c\n ),\n })),\n\n setSandbox: (mode, sandboxId, status) =>\n set((state) => {\n if (!sandboxId) {\n const nextSandboxesByMode = { ...state.sandboxesByMode };\n delete nextSandboxesByMode[mode];\n return { sandboxesByMode: nextSandboxesByMode };\n }\n\n return {\n sandboxesByMode: {\n ...state.sandboxesByMode,\n [mode]: {\n sandboxId,\n status,\n },\n },\n };\n }),\n\n clearSandbox: (mode) =>\n set((state) => {\n const nextSandboxesByMode = { ...state.sandboxesByMode };\n delete nextSandboxesByMode[mode];\n return { sandboxesByMode: nextSandboxesByMode };\n }),\n\n resetStore: () =>\n set({\n conversations: [],\n activeConversationId: null,\n mode: 'assistant',\n processingByConversationId: {},\n conversationListOpen: false,\n sandboxesByMode: {},\n pendingPrompt: null,\n apiCallsAcknowledged: false,\n }),\n\n submitPrompt: (text: string) => set({ pendingPrompt: text }),\n\n consumePendingPrompt: () => {\n const current = get().pendingPrompt;\n if (current !== null) set({ pendingPrompt: null });\n return current;\n },\n\n acknowledgeApiCalls: () => set({ apiCallsAcknowledged: true }),\n }),\n {\n name: 'hb-ai-assistant',\n storage: createProfileScopedStorage(),\n partialize: (state) => ({\n conversations: state.conversations.map(({ ...conversation }) => conversation),\n activeConversationId: state.activeConversationId,\n mode: state.mode,\n conversationListOpen: state.conversationListOpen,\n apiCallsAcknowledged: state.apiCallsAcknowledged,\n }),\n }\n )\n);\n"],"mappings":";;;;AA2EA,SAAS,IAAqB;AAC5B,QAAO,GAAG,KAAK,KAAK,CAAC,GAAG,KAAK,QAAQ,CAAC,SAAS,GAAG,CAAC,MAAM,GAAG,EAAE;;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AE;EACjB,sBAAsB;EACtB,MAAM;EACN,4BAA4B,EAAE;EAC9B,sBAAsB;EACtB,iBAAiB,EAAE;EACnB,eAAe;EACf,sBAAsB;EACvB,CAAC;CAEJ,eAAe,MAAiB,EAAI,EAAE,eAAe,GAAM,CAAC;CAE5D,4BAA4B;EAC1B,IAAM,IAAU,GAAK,CAAC;AAEtB,SADI,MAAY,QAAM,EAAI,EAAE,eAAe,MAAM,CAAC,EAC3C;;CAGT,2BAA2B,EAAI,EAAE,sBAAsB,IAAM,CAAC;CAC/D,GACD;CACE,MAAM;CACN,SAAS,GAA4B;CACrC,aAAa,OAAW;EACtB,eAAe,EAAM,cAAc,KAAK,EAAE,GAAG,QAAmB,EAAa;EAC7E,sBAAsB,EAAM;EAC5B,MAAM,EAAM;EACZ,sBAAsB,EAAM;EAC5B,sBAAsB,EAAM;EAC7B;CACF,CACF,CACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@burdenoff/microfe-healthybowl",
3
- "version": "2026.729.1",
3
+ "version": "2026.731.1",
4
4
  "description": "Burdenoff HealthyBowl Microfrontend - Comprehensive organic farming and agro-foods management platform",
5
5
  "type": "module",
6
6
  "files": [