@burdenoff/microfe-healthybowl 2026.710.3 → 2026.710.5
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.
|
@@ -112,26 +112,33 @@ var D = ({ messagesExpanded: C = !1 }) => {
|
|
|
112
112
|
let Y = y((e, t, n, r) => {
|
|
113
113
|
V(e, n, t, null), r ? z(e, t, r) : z(e, t, Se(n));
|
|
114
114
|
}, [V, z]), X = y(async (t, n, a, s, c) => {
|
|
115
|
-
let u = e.getState().sandboxesByMode[a]?.sandboxId ?? null
|
|
116
|
-
|
|
115
|
+
let u = e.getState().sandboxesByMode[a]?.sandboxId ?? null, d = async (e) => {
|
|
116
|
+
try {
|
|
117
|
+
return await p(E, e, s, c, 3e5, (e) => Y(t, n, "provisioning", e)), await f(E, e, s, c, 9e4, (e) => Y(t, n, "connecting", e)), !0;
|
|
118
|
+
} catch {
|
|
119
|
+
return !1;
|
|
120
|
+
}
|
|
121
|
+
};
|
|
122
|
+
if (u && (W(a, u, "provisioning"), Y(t, n, "provisioning", "Reusing assistant environment..."), await d(u) || (W(a, null, "provisioning"), u = null)), !u) {
|
|
117
123
|
Y(t, n, "provisioning", "Looking for existing environment...");
|
|
118
124
|
let e = await o(E, s, a, c);
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
125
|
+
e && (W(a, e, "provisioning"), Y(t, n, "provisioning", "Reusing assistant environment..."), await d(e) ? u = e : W(a, null, "provisioning"));
|
|
126
|
+
}
|
|
127
|
+
if (!u) {
|
|
128
|
+
if (a === "api-calls" && !D()) throw Error("API Calls mode requires an authenticated session. Please sign in again.");
|
|
129
|
+
Y(t, n, "provisioning", "Starting assistant environment..."), W(a, null, "provisioning"), u = await r(E, a, s, c), W(a, u, "provisioning"), await p(E, u, s, c, 3e5, (e) => Y(t, n, "provisioning", e)), await f(E, u, s, c, 9e4, (e) => Y(t, n, "connecting", e));
|
|
124
130
|
}
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
131
|
+
W(a, u, "running");
|
|
132
|
+
let m = e.getState().conversations.find((e) => e.id === t)?.backendSessionId ?? null;
|
|
133
|
+
if (m) try {
|
|
134
|
+
let e = await l(E, u, s, m, c);
|
|
128
135
|
if (e.mode !== a) throw Error(`Session mode mismatch: expected ${a}, received ${e.mode}`);
|
|
129
136
|
} catch {
|
|
130
|
-
U(t),
|
|
137
|
+
U(t), m = null;
|
|
131
138
|
}
|
|
132
|
-
return
|
|
139
|
+
return m || (Y(t, n, "connecting", "Preparing session..."), m = (await i(E, u, s, a, c)).sessionId, H(t, m)), {
|
|
133
140
|
sandboxId: u,
|
|
134
|
-
sessionId:
|
|
141
|
+
sessionId: m
|
|
135
142
|
};
|
|
136
143
|
}, [
|
|
137
144
|
E,
|
|
@@ -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 { Plus } from 'lucide-react';\nimport { useGatewayClient } from '@burdenoff/fe-libs/shared/graphql';\nimport { useAuthToken } from '@burdenoff/fe-libs/shared/providers/shell';\nimport { AssistantChatInput } from './AssistantChatInput';\nimport { AssistantMessageList } from './AssistantMessageList';\nimport { AssistantModeSelector } from './AssistantModeSelector';\nimport { AssistantApiCallsConsentDialog } from './AssistantApiCallsConsentDialog';\nimport { AssistantWelcome } from './AssistantWelcome';\nimport { useAssistantApiAccess } from '@/hooks/useAssistantApiAccess';\nimport { useAssistantStore } from '@/store/assistantStore';\nimport {\n checkAssistantAiCredits,\n createAssistantSandbox,\n createAssistantSession,\n extendAssistantSandboxTTL,\n findExistingSandbox,\n getAssistantArtifacts,\n getAssistantMessages,\n getAssistantSession,\n reportAssistantAiTokenUsage,\n sendAssistantPromptAsync,\n waitForAssistantServiceReady,\n waitForSandboxReady,\n type AssistantRawMessage,\n type AssistantSandboxAuthContext,\n} from '@/services/assistantApi';\nimport { gatherPageContext } from '@/utils/pageContext';\nimport { dispatchAssistantQuotaExhausted, notifyAiCreditsUpdated } from '@/utils/aiCredits';\nimport { isQuotaExhaustedError } from '@/utils/quotaUtils';\nimport { buildPromptForMode } from '@/utils/assistantPrompt';\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 getProfileContextValue(key: 'workspaceId' | 'organizationId'): string {\n try {\n const activeContextKey =\n key === 'workspaceId' ? 'burdenoff-active-context-workspace' : 'burdenoff-active-context-organization';\n // The app shell (fe-libs ActiveContextStorage) keeps the active org/workspace in\n // sessionStorage as the PRIMARY store and actively removes the localStorage copy\n // (writeActiveContextStorageValue / readActiveContextStorageValue migration). So\n // reading localStorage first returned empty once the shell migrated the value —\n // which made getOrganizationId() resolve to '' on any URL WITHOUT an explicit\n // ?org= param. That empty scope hid Actions mode (admin gate fails closed) and\n // broke the sandbox context (\"Something went wrong\"). Read sessionStorage first\n // to match where the shell actually stores it; localStorage stays a legacy fallback.\n const fromSession = sessionStorage.getItem(activeContextKey);\n if (fromSession) return fromSession;\n const fromLocal = localStorage.getItem(activeContextKey);\n if (fromLocal) return fromLocal;\n\n const activeProfileId = sessionStorage.getItem('bf-active-profile');\n if (!activeProfileId) return '';\n const raw = localStorage.getItem(`bf-p-${activeProfileId}-context`);\n if (!raw) return '';\n const context = JSON.parse(raw) as {\n workspaceId?: string;\n organizationId?: string;\n };\n return context[key] ?? '';\n } catch {\n return '';\n }\n}\n\nfunction getWorkspaceId(): string {\n const params = new URLSearchParams(window.location.search);\n return params.get('workspace') ?? getProfileContextValue('workspaceId');\n}\n\nfunction getOrganizationId(): string {\n const params = new URLSearchParams(window.location.search);\n return params.get('org') ?? getProfileContextValue('organizationId');\n}\n\nfunction isRecoverableAssistantError(error: unknown): boolean {\n const message = error instanceof Error ? error.message.toLowerCase() : String(error).toLowerCase();\n\n if (\n message.includes('rate limit exceeded') ||\n message.includes('unauthorized') ||\n message.includes('k8s api error 401')\n ) {\n return false;\n }\n\n return [\n 'sandbox not found',\n 'sandbox is not running',\n 'sandbox service not available yet',\n 'sandbox failed',\n 'sandbox startup timed out',\n 'assistant service did not become healthy',\n 'proxy error: 404',\n 'proxy error: 502',\n 'proxy error: 503',\n 'session mode mismatch',\n ].some((fragment) => message.includes(fragment));\n}\n\nfunction sanitizeAssistantResponse(response: string): string {\n return response\n .replace(/(Authorization\\s*:\\s*Bearer\\s+)[^\\s\\n]+/gi, '$1[REDACTED]')\n .replace(/(X-Workspace-Authorization\\s*:\\s*Bearer\\s+)[^\\s\\n]+/gi, '$1[REDACTED]')\n .replace(/\\beyJ[A-Za-z0-9_-]+\\.[A-Za-z0-9._-]+\\.[A-Za-z0-9._-]+\\b/g, '[REDACTED_JWT]')\n .replace(/\\bsk-ant-[A-Za-z0-9-]+\\b/g, '[REDACTED_API_KEY]');\n}\n\nfunction getRawMessageCreatedAt(message: AssistantRawMessage): number {\n return message.info?.time?.created ?? 0;\n}\n\nfunction getAssistantText(parts: AssistantRawMessage['parts']): string {\n return (parts ?? [])\n .filter((part) => part.type === 'text' && typeof part.text === 'string')\n .map((part) => part.text?.trim() ?? '')\n .filter(Boolean)\n .join('\\n');\n}\n\nfunction getToolProgress(parts: AssistantRawMessage['parts']): string[] {\n return (parts ?? [])\n .filter((part) => part.type === 'tool' && part.tool)\n .map((part) => {\n const status = part.state?.status ?? 'running';\n const tool = part.tool ?? 'tool';\n if (status === 'completed') return `Completed: ${tool}`;\n if (status === 'failed') return `Failed: ${tool}`;\n return `Running: ${tool}`;\n });\n}\n\nfunction buildAssistantProgress(\n messages: AssistantRawMessage[],\n // The `created` timestamp (sandbox clock) of the newest message that already\n // existed in this session BEFORE the prompt was sent. This turn's reply is the\n // assistant message created strictly after it. Crucially this stays WITHIN the\n // sandbox clock domain: the previous code compared the sandbox-stamped\n // `created` against the browser wall-clock (Date#now), so a reply stamped at\n // prompt-time was silently dropped whenever the sandbox clock lagged the\n // browser — the turn then hung on \"Thinking...\" until the stream budget\n // elapsed. A sandbox-domain floor is immune to clock skew and correct for both\n // fresh and reused (per-conversation) sessions, with no message-window gap.\n priorNewestCreatedMs: number\n): {\n content: string;\n done: boolean;\n tokens?: { input: number; output: number };\n} {\n const relevant = messages\n .filter((message) => message.info?.role === 'assistant' && getRawMessageCreatedAt(message) > priorNewestCreatedMs)\n .sort((left, right) => getRawMessageCreatedAt(left) - getRawMessageCreatedAt(right));\n\n if (relevant.length === 0) {\n return { content: 'Thinking...', done: false };\n }\n\n const latest = relevant[relevant.length - 1]!;\n const text = getAssistantText(latest.parts);\n const toolProgress = getToolProgress(latest.parts);\n const content = [text, ...toolProgress].filter(Boolean).join('\\n\\n') || 'Thinking...';\n\n return {\n content,\n done: Boolean(latest.info?.time?.completed) && (Boolean(text) || toolProgress.length > 0),\n tokens: latest.info?.tokens,\n };\n}\n\nfunction getConversationStatusMessage(status: AssistantConversationStatus): string {\n switch (status) {\n case 'provisioning':\n return 'Starting assistant environment...';\n case 'connecting':\n return 'Connecting to assistant...';\n case 'streaming':\n return 'Thinking...';\n default:\n return '';\n }\n}\n\ninterface AssistantChatAreaProps {\n /** Whether the message transcript is expanded (driven by the header accordion). */\n messagesExpanded?: boolean;\n}\n\nexport const AssistantChatArea: FC<AssistantChatAreaProps> = ({ messagesExpanded = false }) => {\n const tr = useTr();\n const apollo = useGatewayClient('workspace');\n const { getAccessToken, getWorkspaceToken, userId } = useAuthToken();\n\n const {\n conversations,\n activeConversationId,\n mode,\n processingByConversationId,\n setMode,\n setConversationMode,\n setActiveConversation,\n createConversation,\n addMessage,\n updateMessage,\n patchMessage,\n setConversationProcessing,\n clearConversationProcessing,\n setBackendSessionId,\n clearBackendSessionId,\n setSandbox,\n clearSandbox,\n acknowledgeApiCalls,\n } = useAssistantStore();\n\n const activeConversation = conversations.find((conversation) => conversation.id === activeConversationId);\n const messages = activeConversation?.messages ?? [];\n const activeProcessing = activeConversationId ? processingByConversationId[activeConversationId] : undefined;\n const activeStreamingMessageId = activeProcessing?.messageId ?? null;\n const activeIsProcessing =\n activeProcessing?.status === 'provisioning' ||\n activeProcessing?.status === 'connecting' ||\n activeProcessing?.status === 'streaming';\n\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 // 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 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 currentSandboxId = existingId;\n setSandbox(currentMode, currentSandboxId, 'provisioning');\n updateConversationStage(\n conversationId,\n assistantMessageId,\n 'provisioning',\n 'Reusing assistant environment...'\n );\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 setSandbox(currentMode, currentSandboxId, 'running');\n } else {\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 setSandbox(currentMode, currentSandboxId, 'running');\n }\n }\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) => {\n // Only block re-entry while a turn is genuinely in-flight. Earlier code\n // checked for *any* entry in the map, which stuck around as `complete`\n // / `error` after the first turn — making every subsequent message\n // silently disappear (the input cleared but handleSend bailed before\n // adding the user message to the conversation).\n if (activeConversationId) {\n const inflightStatus = processingByConversationId[activeConversationId]?.status;\n if (inflightStatus === 'provisioning' || inflightStatus === 'connecting' || inflightStatus === 'streaming') {\n return;\n }\n }\n\n const selectedMode = useAssistantStore.getState().mode;\n let conversationId = activeConversationId;\n const currentConversation = conversationId\n ? useAssistantStore.getState().conversations.find((conversation) => conversation.id === conversationId)\n : undefined;\n\n if (!conversationId) {\n conversationId = createConversation(undefined, selectedMode);\n } else if (\n currentConversation &&\n currentConversation.mode !== selectedMode &&\n (currentConversation.messages.length > 0 || currentConversation.backendSessionId)\n ) {\n conversationId = createConversation(undefined, selectedMode);\n } else if (currentConversation && currentConversation.mode !== selectedMode) {\n setConversationMode(conversationId, selectedMode);\n }\n\n if (!conversationId) return;\n\n 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 };\n addMessage(conversationId, userMessage);\n\n const assistantMessageId = generateId();\n addMessage(conversationId, {\n id: assistantMessageId,\n role: 'assistant',\n content: '',\n timestamp: new Date().toISOString(),\n });\n\n const applyAssistantResponse = (\n response: string,\n artifacts?: AssistantArtifact[],\n sessionId?: string,\n sandboxId?: string\n ) => {\n patchMessage(conversationId, assistantMessageId, {\n content: sanitizeAssistantResponse(response),\n metadata:\n artifacts?.length || sessionId || sandboxId\n ? {\n artifacts,\n mode: selectedMode,\n sessionId,\n sandboxId,\n }\n : undefined,\n });\n };\n\n const sendWithRealBackend = async (attempt: 1 | 2 = 1): Promise<void> => {\n // Pre-flight AI-credit gate. The wspace gateway's @usage(checkQuota)\n // rejects with 429 QUOTA_EXHAUSTED when the monthly token budget is\n // depleted — block the send (don't provision a sandbox or dispatch the\n // prompt) and surface the upgrade dialog instead of a generic error.\n try {\n await checkAssistantAiCredits(apollo, workspaceId, authContext);\n } catch (creditError) {\n if (isQuotaExhaustedError(creditError)) {\n dispatchAssistantQuotaExhausted('ai-credits');\n applyAssistantResponse(\n \"You've run out of AI credits for this billing cycle. Upgrade your plan to keep chatting.\"\n );\n setConversationProcessing(conversationId, 'error', assistantMessageId, null);\n return;\n }\n // The pre-flight gate exists ONLY to catch a genuine QUOTA_EXHAUSTED\n // rejection. Any other failure here is a transient fault in the\n // credit check itself — e.g. the usage subgraph's getUsageSummary /\n // checkAiCredits intermittently 500s (Postgres/Prisma blip) and the\n // gateway masks it as the opaque \"Unexpected error.\". That is NOT\n // proof the user is out of budget, so it must not abort an otherwise\n // valid send. Fail open and proceed: the wspace gateway's\n // @usage(checkQuota) on createSandbox still enforces the real budget\n // downstream (a truly over-quota caller is stopped there with a 429\n // that surfaces the upgrade dialog via the outer catch).\n console.warn(\n '[assistant] AI-credit pre-flight check failed with a non-quota error; proceeding — gateway @usage(checkQuota) still enforces the real budget downstream',\n creditError\n );\n }\n\n try {\n const { sandboxId, sessionId } = await ensureAssistantRuntime(\n conversationId,\n assistantMessageId,\n selectedMode,\n workspaceId,\n authContext\n );\n\n // Snapshot the newest message timestamp already present in this\n // (possibly reused) session BEFORE sending the prompt, so we can\n // recognise THIS turn's reply as the one created after it — never by\n // comparing the browser clock to the sandbox clock (see\n // buildAssistantProgress). The newest-N window always contains the\n // newest message, so this floor is exact regardless of conversation depth.\n const priorMessages = await getAssistantMessages(\n apollo,\n sandboxId,\n workspaceId,\n sessionId,\n authContext,\n 50\n ).catch((): AssistantRawMessage[] => []);\n const priorNewestCreatedMs = priorMessages.reduce(\n (newest, message) => Math.max(newest, getRawMessageCreatedAt(message)),\n 0\n );\n\n updateConversationStage(conversationId, assistantMessageId, 'streaming', 'Thinking...');\n await sendAssistantPromptAsync(\n apollo,\n sandboxId,\n workspaceId,\n sessionId,\n // Prepend the soft confirm-before-mutate guard for api-calls mode.\n // The user-facing bubble (added above) keeps the raw content.\n buildPromptForMode(selectedMode, content),\n selectedMode,\n gatherPageContext(),\n authContext\n );\n\n let result = buildAssistantProgress([], priorNewestCreatedMs);\n const timeoutAt = Date.now() + (STREAM_BUDGET_MS[selectedMode] ?? DEFAULT_STREAM_BUDGET_MS);\n let lastTtlExtensionAt = Date.now();\n\n while (Date.now() < timeoutAt) {\n const sessionMessages = await getAssistantMessages(\n apollo,\n sandboxId,\n workspaceId,\n sessionId,\n authContext,\n 50\n );\n\n result = buildAssistantProgress(sessionMessages, priorNewestCreatedMs);\n patchMessage(conversationId, assistantMessageId, {\n content: sanitizeAssistantResponse(result.content),\n });\n\n if (result.done) break;\n\n if (Date.now() - lastTtlExtensionAt > 30_000) {\n await extendAssistantSandboxTTL(apollo, sandboxId, workspaceId, 600, authContext).catch(() => undefined);\n lastTtlExtensionAt = Date.now();\n }\n\n await new Promise((resolve) => setTimeout(resolve, 1500));\n }\n\n // For non-build modes a timeout is a hard failure. For vibe-plugins the\n // prompt runs async server-side (/sessions/:id/prompt-async) and keeps\n // writing artifacts after the poll budget elapses, so we surface whatever\n // it has produced instead of discarding the turn.\n if (!result.done && selectedMode !== 'vibe-plugins') {\n throw new Error('Assistant response timed out while streaming progress');\n }\n\n const artifacts =\n selectedMode === 'vibe-plugins'\n ? await getAssistantArtifacts(apollo, sandboxId, workspaceId, sessionId, authContext).catch(() => [])\n : undefined;\n\n if (!result.done) {\n // vibe-plugins build still running in the background. Append a note so\n // the user knows the answer is partial and the artifacts will finish.\n result = {\n ...result,\n content: `${result.content}\\n\\n_Still building in the background — any artifacts below will finish shortly. Re-open this conversation to pick up the completed plugin._`,\n };\n }\n\n applyAssistantResponse(result.content, artifacts, sessionId, sandboxId);\n\n if (result.tokens) {\n patchMessage(conversationId, assistantMessageId, { tokens: result.tokens });\n // Charge the real token usage against the AI-credits quota (the\n // gateway records it via @usage(trackUsage)). We AWAIT it before\n // marking the turn complete / re-enabling input: otherwise a rapid\n // follow-up send would run its pre-flight checkAiCredits against a\n // stale balance (this turn's charge still in flight) and could\n // dispatch a prompt that should have been blocked, letting fast\n // sends bypass the credit cap. Still best-effort — a charge failure\n // never blocks the displayed answer.\n try {\n await reportAssistantAiTokenUsage(apollo, workspaceId, sessionId, result.tokens, authContext);\n notifyAiCreditsUpdated();\n } catch {\n // ignore — server-side @usage tracking is the source of truth\n }\n }\n setConversationProcessing(conversationId, 'complete', assistantMessageId, null);\n } catch (error) {\n if (attempt === 1 && isRecoverableAssistantError(error)) {\n clearBackendSessionId(conversationId);\n clearSandbox(selectedMode);\n return sendWithRealBackend(2);\n }\n\n throw error;\n }\n };\n\n try {\n if (!workspaceId) {\n throw new Error('Assistant backend is unavailable without an active workspace context.');\n }\n await sendWithRealBackend();\n } catch (error) {\n // A quota error reaching here is the sandbox-environment wall hit\n // during runtime provisioning (createSandbox @usage). Surface the\n // upgrade dialog instead of a generic failure (the AI-credit wall is\n // already handled by the pre-flight gate above).\n if (isQuotaExhaustedError(error)) {\n dispatchAssistantQuotaExhausted('sandbox');\n applyAssistantResponse(\n \"You've reached your sandbox limit on the current plan. Upgrade to start the AI assistant.\"\n );\n setConversationProcessing(conversationId, 'error', assistantMessageId, null);\n return;\n }\n const errorMessage = error instanceof Error ? error.message : 'Something went wrong';\n setConversationProcessing(conversationId, 'error', assistantMessageId, errorMessage);\n updateMessage(\n conversationId,\n assistantMessageId,\n `Sorry, an error occurred: ${errorMessage}. Please try again.`\n );\n }\n },\n [\n activeConversationId,\n addMessage,\n apollo,\n clearBackendSessionId,\n clearSandbox,\n conversations,\n createConversation,\n ensureAssistantRuntime,\n getAccessToken,\n getWorkspaceToken,\n patchMessage,\n processingByConversationId,\n setBackendSessionId,\n setConversationMode,\n setConversationProcessing,\n updateConversationStage,\n updateMessage,\n userId,\n ]\n );\n\n const handleSuggestionClick = useCallback(\n (suggestion: string) => {\n void handleSend(suggestion);\n },\n [handleSend]\n );\n\n // 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-col flex-1 overflow-hidden\">\n {messages.length === 0 ? (\n <AssistantWelcome mode={mode} onSuggestionClick={handleSuggestionClick} />\n ) : (\n <>\n {/* Collapsible message transcript — animated height + fade. */}\n <div\n className={`grid min-h-0 transition-[grid-template-rows] duration-300 ease-out ${\n messagesExpanded ? 'flex-1' : 'flex-shrink-0'\n }`}\n style={{ gridTemplateRows: messagesExpanded ? '1fr' : '0fr' }}\n // Collapsed transcript is hidden via height/opacity, which don't drop\n // its controls from the tab order — `inert` makes it truly inert.\n inert={!messagesExpanded || undefined}\n data-testid=\"message-transcript\"\n >\n <div\n className={`min-h-0 overflow-hidden transition-opacity duration-300 ${\n messagesExpanded ? 'opacity-100' : 'opacity-0'\n }`}\n >\n <div className=\"flex h-full flex-col\">\n <AssistantMessageList\n messages={messages}\n streamingMessageId={activeStreamingMessageId}\n expanded={messagesExpanded}\n />\n </div>\n </div>\n </div>\n {/* Spacer keeps the composer pinned to the bottom when collapsed. */}\n {!messagesExpanded && <div className=\"flex-1\" />}\n </>\n )}\n\n <AssistantChatInput\n onSend={(value) => void handleSend(value)}\n disabled={activeIsProcessing}\n placeholder={\n mode === 'api-calls'\n ? tr('healthybowl.assistant.chatArea.placeholderActions', 'What would you like to change or create?')\n : tr('healthybowl.assistant.chatArea.placeholderGeneral', 'Ask anything about your farm…')\n }\n toolbarStart={\n <>\n <button\n type=\"button\"\n onClick={() => createConversation()}\n className=\"flex size-7 flex-shrink-0 items-center justify-center rounded-full text-text-secondary transition-colors hover:bg-bg-elevated hover:text-text-primary\"\n aria-label={tr('healthybowl.assistant.chatArea.newConversation', 'New conversation')}\n data-testid=\"composer-new-conversation\"\n >\n <Plus className=\"size-4\" />\n </button>\n <AssistantModeSelector mode={mode} availableModes={availableModes} onModeChange={handleModeChange} />\n </>\n }\n />\n\n <AssistantApiCallsConsentDialog\n open={pendingConsentMode !== null}\n onConfirm={handleConsentConfirm}\n onCancel={handleConsentCancel}\n />\n </div>\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAwCA,IAAM,KAAkD;CACtD,SAAS;CACT,aAAa;CACb,gBAAgB;CACjB,EACK,KAA2B;AAEjC,SAAS,KAAqB;AAC5B,QAAO,GAAG,KAAK,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IAAmB,QAAQ,OAAO;IAG7D,OAAO,CAAC,KAAoB,KAAA;IAC5B,eAAY;cAEZ,kBAAC,OAAD;KACE,WAAW,2DACT,IAAmB,gBAAgB;eAGrC,kBAAC,OAAD;MAAK,WAAU;gBACb,kBAAC,GAAD;OACY;OACV,oBAAoB;OACpB,UAAU;OACV,CAAA;MACE,CAAA;KACF,CAAA;IACF,CAAA,EAEL,CAAC,KAAoB,kBAAC,OAAD,EAAK,WAAU,UAAW,CAAA,CAC/C,EAAA,CAAA;GAGL,kBAAC,GAAD;IACE,SAAS,MAAU,KAAK,EAAW,EAAM;IACzC,UAAU;IACV,aACE,MAAS,cACL,EAAG,qDAAqD,2CAA2C,GACnG,EAAG,qDAAqD,gCAAgC;IAE9F,cACE,kBAAA,IAAA,EAAA,UAAA,CACE,kBAAC,UAAD;KACE,MAAK;KACL,eAAe,GAAoB;KACnC,WAAU;KACV,cAAY,EAAG,kDAAkD,mBAAmB;KACpF,eAAY;eAEZ,kBAAC,IAAD,EAAM,WAAU,UAAW,CAAA;KACpB,CAAA,EACT,kBAAC,GAAD;KAA6B;KAAsB;KAAgB,cAAc;KAAoB,CAAA,CACpG,EAAA,CAAA;IAEL,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 { Plus } from 'lucide-react';\nimport { useGatewayClient } from '@burdenoff/fe-libs/shared/graphql';\nimport { useAuthToken } from '@burdenoff/fe-libs/shared/providers/shell';\nimport { AssistantChatInput } from './AssistantChatInput';\nimport { AssistantMessageList } from './AssistantMessageList';\nimport { AssistantModeSelector } from './AssistantModeSelector';\nimport { AssistantApiCallsConsentDialog } from './AssistantApiCallsConsentDialog';\nimport { AssistantWelcome } from './AssistantWelcome';\nimport { useAssistantApiAccess } from '@/hooks/useAssistantApiAccess';\nimport { useAssistantStore } from '@/store/assistantStore';\nimport {\n checkAssistantAiCredits,\n createAssistantSandbox,\n createAssistantSession,\n extendAssistantSandboxTTL,\n findExistingSandbox,\n getAssistantArtifacts,\n getAssistantMessages,\n getAssistantSession,\n reportAssistantAiTokenUsage,\n sendAssistantPromptAsync,\n waitForAssistantServiceReady,\n waitForSandboxReady,\n type AssistantRawMessage,\n type AssistantSandboxAuthContext,\n} from '@/services/assistantApi';\nimport { gatherPageContext } from '@/utils/pageContext';\nimport { dispatchAssistantQuotaExhausted, notifyAiCreditsUpdated } from '@/utils/aiCredits';\nimport { isQuotaExhaustedError } from '@/utils/quotaUtils';\nimport { buildPromptForMode } from '@/utils/assistantPrompt';\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 getProfileContextValue(key: 'workspaceId' | 'organizationId'): string {\n try {\n const activeContextKey =\n key === 'workspaceId' ? 'burdenoff-active-context-workspace' : 'burdenoff-active-context-organization';\n // The app shell (fe-libs ActiveContextStorage) keeps the active org/workspace in\n // sessionStorage as the PRIMARY store and actively removes the localStorage copy\n // (writeActiveContextStorageValue / readActiveContextStorageValue migration). So\n // reading localStorage first returned empty once the shell migrated the value —\n // which made getOrganizationId() resolve to '' on any URL WITHOUT an explicit\n // ?org= param. That empty scope hid Actions mode (admin gate fails closed) and\n // broke the sandbox context (\"Something went wrong\"). Read sessionStorage first\n // to match where the shell actually stores it; localStorage stays a legacy fallback.\n const fromSession = sessionStorage.getItem(activeContextKey);\n if (fromSession) return fromSession;\n const fromLocal = localStorage.getItem(activeContextKey);\n if (fromLocal) return fromLocal;\n\n const activeProfileId = sessionStorage.getItem('bf-active-profile');\n if (!activeProfileId) return '';\n const raw = localStorage.getItem(`bf-p-${activeProfileId}-context`);\n if (!raw) return '';\n const context = JSON.parse(raw) as {\n workspaceId?: string;\n organizationId?: string;\n };\n return context[key] ?? '';\n } catch {\n return '';\n }\n}\n\nfunction getWorkspaceId(): string {\n const params = new URLSearchParams(window.location.search);\n return params.get('workspace') ?? getProfileContextValue('workspaceId');\n}\n\nfunction getOrganizationId(): string {\n const params = new URLSearchParams(window.location.search);\n return params.get('org') ?? getProfileContextValue('organizationId');\n}\n\nfunction isRecoverableAssistantError(error: unknown): boolean {\n const message = error instanceof Error ? error.message.toLowerCase() : String(error).toLowerCase();\n\n if (\n message.includes('rate limit exceeded') ||\n message.includes('unauthorized') ||\n message.includes('k8s api error 401')\n ) {\n return false;\n }\n\n return [\n 'sandbox not found',\n 'sandbox is not running',\n 'sandbox service not available yet',\n 'sandbox failed',\n 'sandbox startup timed out',\n 'assistant service did not become healthy',\n 'proxy error: 404',\n 'proxy error: 502',\n 'proxy error: 503',\n 'session mode mismatch',\n ].some((fragment) => message.includes(fragment));\n}\n\nfunction sanitizeAssistantResponse(response: string): string {\n return response\n .replace(/(Authorization\\s*:\\s*Bearer\\s+)[^\\s\\n]+/gi, '$1[REDACTED]')\n .replace(/(X-Workspace-Authorization\\s*:\\s*Bearer\\s+)[^\\s\\n]+/gi, '$1[REDACTED]')\n .replace(/\\beyJ[A-Za-z0-9_-]+\\.[A-Za-z0-9._-]+\\.[A-Za-z0-9._-]+\\b/g, '[REDACTED_JWT]')\n .replace(/\\bsk-ant-[A-Za-z0-9-]+\\b/g, '[REDACTED_API_KEY]');\n}\n\nfunction getRawMessageCreatedAt(message: AssistantRawMessage): number {\n return message.info?.time?.created ?? 0;\n}\n\nfunction getAssistantText(parts: AssistantRawMessage['parts']): string {\n return (parts ?? [])\n .filter((part) => part.type === 'text' && typeof part.text === 'string')\n .map((part) => part.text?.trim() ?? '')\n .filter(Boolean)\n .join('\\n');\n}\n\nfunction getToolProgress(parts: AssistantRawMessage['parts']): string[] {\n return (parts ?? [])\n .filter((part) => part.type === 'tool' && part.tool)\n .map((part) => {\n const status = part.state?.status ?? 'running';\n const tool = part.tool ?? 'tool';\n if (status === 'completed') return `Completed: ${tool}`;\n if (status === 'failed') return `Failed: ${tool}`;\n return `Running: ${tool}`;\n });\n}\n\nfunction buildAssistantProgress(\n messages: AssistantRawMessage[],\n // The `created` timestamp (sandbox clock) of the newest message that already\n // existed in this session BEFORE the prompt was sent. This turn's reply is the\n // assistant message created strictly after it. Crucially this stays WITHIN the\n // sandbox clock domain: the previous code compared the sandbox-stamped\n // `created` against the browser wall-clock (Date#now), so a reply stamped at\n // prompt-time was silently dropped whenever the sandbox clock lagged the\n // browser — the turn then hung on \"Thinking...\" until the stream budget\n // elapsed. A sandbox-domain floor is immune to clock skew and correct for both\n // fresh and reused (per-conversation) sessions, with no message-window gap.\n priorNewestCreatedMs: number\n): {\n content: string;\n done: boolean;\n tokens?: { input: number; output: number };\n} {\n const relevant = messages\n .filter((message) => message.info?.role === 'assistant' && getRawMessageCreatedAt(message) > priorNewestCreatedMs)\n .sort((left, right) => getRawMessageCreatedAt(left) - getRawMessageCreatedAt(right));\n\n if (relevant.length === 0) {\n return { content: 'Thinking...', done: false };\n }\n\n const latest = relevant[relevant.length - 1]!;\n const text = getAssistantText(latest.parts);\n const toolProgress = getToolProgress(latest.parts);\n const content = [text, ...toolProgress].filter(Boolean).join('\\n\\n') || 'Thinking...';\n\n return {\n content,\n done: Boolean(latest.info?.time?.completed) && (Boolean(text) || toolProgress.length > 0),\n tokens: latest.info?.tokens,\n };\n}\n\nfunction getConversationStatusMessage(status: AssistantConversationStatus): string {\n switch (status) {\n case 'provisioning':\n return 'Starting assistant environment...';\n case 'connecting':\n return 'Connecting to assistant...';\n case 'streaming':\n return 'Thinking...';\n default:\n return '';\n }\n}\n\ninterface AssistantChatAreaProps {\n /** Whether the message transcript is expanded (driven by the header accordion). */\n messagesExpanded?: boolean;\n}\n\nexport const AssistantChatArea: FC<AssistantChatAreaProps> = ({ messagesExpanded = false }) => {\n const tr = useTr();\n const apollo = useGatewayClient('workspace');\n const { getAccessToken, getWorkspaceToken, userId } = useAuthToken();\n\n const {\n conversations,\n activeConversationId,\n mode,\n processingByConversationId,\n setMode,\n setConversationMode,\n setActiveConversation,\n createConversation,\n addMessage,\n updateMessage,\n patchMessage,\n setConversationProcessing,\n clearConversationProcessing,\n setBackendSessionId,\n clearBackendSessionId,\n setSandbox,\n clearSandbox,\n acknowledgeApiCalls,\n } = useAssistantStore();\n\n const activeConversation = conversations.find((conversation) => conversation.id === activeConversationId);\n const messages = activeConversation?.messages ?? [];\n const activeProcessing = activeConversationId ? processingByConversationId[activeConversationId] : undefined;\n const activeStreamingMessageId = activeProcessing?.messageId ?? null;\n const activeIsProcessing =\n activeProcessing?.status === 'provisioning' ||\n activeProcessing?.status === 'connecting' ||\n activeProcessing?.status === 'streaming';\n\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 // 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) => {\n // Only block re-entry while a turn is genuinely in-flight. Earlier code\n // checked for *any* entry in the map, which stuck around as `complete`\n // / `error` after the first turn — making every subsequent message\n // silently disappear (the input cleared but handleSend bailed before\n // adding the user message to the conversation).\n if (activeConversationId) {\n const inflightStatus = processingByConversationId[activeConversationId]?.status;\n if (inflightStatus === 'provisioning' || inflightStatus === 'connecting' || inflightStatus === 'streaming') {\n return;\n }\n }\n\n const selectedMode = useAssistantStore.getState().mode;\n let conversationId = activeConversationId;\n const currentConversation = conversationId\n ? useAssistantStore.getState().conversations.find((conversation) => conversation.id === conversationId)\n : undefined;\n\n if (!conversationId) {\n conversationId = createConversation(undefined, selectedMode);\n } else if (\n currentConversation &&\n currentConversation.mode !== selectedMode &&\n (currentConversation.messages.length > 0 || currentConversation.backendSessionId)\n ) {\n conversationId = createConversation(undefined, selectedMode);\n } else if (currentConversation && currentConversation.mode !== selectedMode) {\n setConversationMode(conversationId, selectedMode);\n }\n\n if (!conversationId) return;\n\n 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 };\n addMessage(conversationId, userMessage);\n\n const assistantMessageId = generateId();\n addMessage(conversationId, {\n id: assistantMessageId,\n role: 'assistant',\n content: '',\n timestamp: new Date().toISOString(),\n });\n\n const applyAssistantResponse = (\n response: string,\n artifacts?: AssistantArtifact[],\n sessionId?: string,\n sandboxId?: string\n ) => {\n patchMessage(conversationId, assistantMessageId, {\n content: sanitizeAssistantResponse(response),\n metadata:\n artifacts?.length || sessionId || sandboxId\n ? {\n artifacts,\n mode: selectedMode,\n sessionId,\n sandboxId,\n }\n : undefined,\n });\n };\n\n const sendWithRealBackend = async (attempt: 1 | 2 = 1): Promise<void> => {\n // Pre-flight AI-credit gate. The wspace gateway's @usage(checkQuota)\n // rejects with 429 QUOTA_EXHAUSTED when the monthly token budget is\n // depleted — block the send (don't provision a sandbox or dispatch the\n // prompt) and surface the upgrade dialog instead of a generic error.\n try {\n await checkAssistantAiCredits(apollo, workspaceId, authContext);\n } catch (creditError) {\n if (isQuotaExhaustedError(creditError)) {\n dispatchAssistantQuotaExhausted('ai-credits');\n applyAssistantResponse(\n \"You've run out of AI credits for this billing cycle. Upgrade your plan to keep chatting.\"\n );\n setConversationProcessing(conversationId, 'error', assistantMessageId, null);\n return;\n }\n // The pre-flight gate exists ONLY to catch a genuine QUOTA_EXHAUSTED\n // rejection. Any other failure here is a transient fault in the\n // credit check itself — e.g. the usage subgraph's getUsageSummary /\n // checkAiCredits intermittently 500s (Postgres/Prisma blip) and the\n // gateway masks it as the opaque \"Unexpected error.\". That is NOT\n // proof the user is out of budget, so it must not abort an otherwise\n // valid send. Fail open and proceed: the wspace gateway's\n // @usage(checkQuota) on createSandbox still enforces the real budget\n // downstream (a truly over-quota caller is stopped there with a 429\n // that surfaces the upgrade dialog via the outer catch).\n console.warn(\n '[assistant] AI-credit pre-flight check failed with a non-quota error; proceeding — gateway @usage(checkQuota) still enforces the real budget downstream',\n creditError\n );\n }\n\n try {\n const { sandboxId, sessionId } = await ensureAssistantRuntime(\n conversationId,\n assistantMessageId,\n selectedMode,\n workspaceId,\n authContext\n );\n\n // Snapshot the newest message timestamp already present in this\n // (possibly reused) session BEFORE sending the prompt, so we can\n // recognise THIS turn's reply as the one created after it — never by\n // comparing the browser clock to the sandbox clock (see\n // buildAssistantProgress). The newest-N window always contains the\n // newest message, so this floor is exact regardless of conversation depth.\n const priorMessages = await getAssistantMessages(\n apollo,\n sandboxId,\n workspaceId,\n sessionId,\n authContext,\n 50\n ).catch((): AssistantRawMessage[] => []);\n const priorNewestCreatedMs = priorMessages.reduce(\n (newest, message) => Math.max(newest, getRawMessageCreatedAt(message)),\n 0\n );\n\n updateConversationStage(conversationId, assistantMessageId, 'streaming', 'Thinking...');\n await sendAssistantPromptAsync(\n apollo,\n sandboxId,\n workspaceId,\n sessionId,\n // Prepend the soft confirm-before-mutate guard for api-calls mode.\n // The user-facing bubble (added above) keeps the raw content.\n buildPromptForMode(selectedMode, content),\n selectedMode,\n gatherPageContext(),\n authContext\n );\n\n let result = buildAssistantProgress([], priorNewestCreatedMs);\n const timeoutAt = Date.now() + (STREAM_BUDGET_MS[selectedMode] ?? DEFAULT_STREAM_BUDGET_MS);\n let lastTtlExtensionAt = Date.now();\n\n while (Date.now() < timeoutAt) {\n const sessionMessages = await getAssistantMessages(\n apollo,\n sandboxId,\n workspaceId,\n sessionId,\n authContext,\n 50\n );\n\n result = buildAssistantProgress(sessionMessages, priorNewestCreatedMs);\n patchMessage(conversationId, assistantMessageId, {\n content: sanitizeAssistantResponse(result.content),\n });\n\n if (result.done) break;\n\n if (Date.now() - lastTtlExtensionAt > 30_000) {\n await extendAssistantSandboxTTL(apollo, sandboxId, workspaceId, 600, authContext).catch(() => undefined);\n lastTtlExtensionAt = Date.now();\n }\n\n await new Promise((resolve) => setTimeout(resolve, 1500));\n }\n\n // For non-build modes a timeout is a hard failure. For vibe-plugins the\n // prompt runs async server-side (/sessions/:id/prompt-async) and keeps\n // writing artifacts after the poll budget elapses, so we surface whatever\n // it has produced instead of discarding the turn.\n if (!result.done && selectedMode !== 'vibe-plugins') {\n throw new Error('Assistant response timed out while streaming progress');\n }\n\n const artifacts =\n selectedMode === 'vibe-plugins'\n ? await getAssistantArtifacts(apollo, sandboxId, workspaceId, sessionId, authContext).catch(() => [])\n : undefined;\n\n if (!result.done) {\n // vibe-plugins build still running in the background. Append a note so\n // the user knows the answer is partial and the artifacts will finish.\n result = {\n ...result,\n content: `${result.content}\\n\\n_Still building in the background — any artifacts below will finish shortly. Re-open this conversation to pick up the completed plugin._`,\n };\n }\n\n applyAssistantResponse(result.content, artifacts, sessionId, sandboxId);\n\n if (result.tokens) {\n patchMessage(conversationId, assistantMessageId, { tokens: result.tokens });\n // Charge the real token usage against the AI-credits quota (the\n // gateway records it via @usage(trackUsage)). We AWAIT it before\n // marking the turn complete / re-enabling input: otherwise a rapid\n // follow-up send would run its pre-flight checkAiCredits against a\n // stale balance (this turn's charge still in flight) and could\n // dispatch a prompt that should have been blocked, letting fast\n // sends bypass the credit cap. Still best-effort — a charge failure\n // never blocks the displayed answer.\n try {\n await reportAssistantAiTokenUsage(apollo, workspaceId, sessionId, result.tokens, authContext);\n notifyAiCreditsUpdated();\n } catch {\n // ignore — server-side @usage tracking is the source of truth\n }\n }\n setConversationProcessing(conversationId, 'complete', assistantMessageId, null);\n } catch (error) {\n if (attempt === 1 && isRecoverableAssistantError(error)) {\n clearBackendSessionId(conversationId);\n clearSandbox(selectedMode);\n return sendWithRealBackend(2);\n }\n\n throw error;\n }\n };\n\n try {\n if (!workspaceId) {\n throw new Error('Assistant backend is unavailable without an active workspace context.');\n }\n await sendWithRealBackend();\n } catch (error) {\n // A quota error reaching here is the sandbox-environment wall hit\n // during runtime provisioning (createSandbox @usage). Surface the\n // upgrade dialog instead of a generic failure (the AI-credit wall is\n // already handled by the pre-flight gate above).\n if (isQuotaExhaustedError(error)) {\n dispatchAssistantQuotaExhausted('sandbox');\n applyAssistantResponse(\n \"You've reached your sandbox limit on the current plan. Upgrade to start the AI assistant.\"\n );\n setConversationProcessing(conversationId, 'error', assistantMessageId, null);\n return;\n }\n const errorMessage = error instanceof Error ? error.message : 'Something went wrong';\n setConversationProcessing(conversationId, 'error', assistantMessageId, errorMessage);\n updateMessage(\n conversationId,\n assistantMessageId,\n `Sorry, an error occurred: ${errorMessage}. Please try again.`\n );\n }\n },\n [\n activeConversationId,\n addMessage,\n apollo,\n clearBackendSessionId,\n clearSandbox,\n conversations,\n createConversation,\n ensureAssistantRuntime,\n getAccessToken,\n getWorkspaceToken,\n patchMessage,\n processingByConversationId,\n setBackendSessionId,\n setConversationMode,\n setConversationProcessing,\n updateConversationStage,\n updateMessage,\n userId,\n ]\n );\n\n const handleSuggestionClick = useCallback(\n (suggestion: string) => {\n void handleSend(suggestion);\n },\n [handleSend]\n );\n\n // 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-col flex-1 overflow-hidden\">\n {messages.length === 0 ? (\n <AssistantWelcome mode={mode} onSuggestionClick={handleSuggestionClick} />\n ) : (\n <>\n {/* Collapsible message transcript — animated height + fade. */}\n <div\n className={`grid min-h-0 transition-[grid-template-rows] duration-300 ease-out ${\n messagesExpanded ? 'flex-1' : 'flex-shrink-0'\n }`}\n style={{ gridTemplateRows: messagesExpanded ? '1fr' : '0fr' }}\n // Collapsed transcript is hidden via height/opacity, which don't drop\n // its controls from the tab order — `inert` makes it truly inert.\n inert={!messagesExpanded || undefined}\n data-testid=\"message-transcript\"\n >\n <div\n className={`min-h-0 overflow-hidden transition-opacity duration-300 ${\n messagesExpanded ? 'opacity-100' : 'opacity-0'\n }`}\n >\n <div className=\"flex h-full flex-col\">\n <AssistantMessageList\n messages={messages}\n streamingMessageId={activeStreamingMessageId}\n expanded={messagesExpanded}\n />\n </div>\n </div>\n </div>\n {/* Spacer keeps the composer pinned to the bottom when collapsed. */}\n {!messagesExpanded && <div className=\"flex-1\" />}\n </>\n )}\n\n <AssistantChatInput\n onSend={(value) => void handleSend(value)}\n disabled={activeIsProcessing}\n placeholder={\n mode === 'api-calls'\n ? tr('healthybowl.assistant.chatArea.placeholderActions', 'What would you like to change or create?')\n : tr('healthybowl.assistant.chatArea.placeholderGeneral', 'Ask anything about your farm…')\n }\n toolbarStart={\n <>\n <button\n type=\"button\"\n onClick={() => createConversation()}\n className=\"flex size-7 flex-shrink-0 items-center justify-center rounded-full text-text-secondary transition-colors hover:bg-bg-elevated hover:text-text-primary\"\n aria-label={tr('healthybowl.assistant.chatArea.newConversation', 'New conversation')}\n data-testid=\"composer-new-conversation\"\n >\n <Plus className=\"size-4\" />\n </button>\n <AssistantModeSelector mode={mode} availableModes={availableModes} onModeChange={handleModeChange} />\n </>\n }\n />\n\n <AssistantApiCallsConsentDialog\n open={pendingConsentMode !== null}\n onConfirm={handleConsentConfirm}\n onCancel={handleConsentCancel}\n />\n </div>\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAwCA,IAAM,KAAkD;CACtD,SAAS;CACT,aAAa;CACb,gBAAgB;CACjB,EACK,KAA2B;AAEjC,SAAS,KAAqB;AAC5B,QAAO,GAAG,KAAK,KAAK,CAAC,GAAG,KAAK,QAAQ,CAAC,SAAS,GAAG,CAAC,MAAM,GAAG,EAAE;;AAGhE,SAAS,EAAuB,GAA+C;AAC7E,KAAI;EACF,IAAM,IACJ,MAAQ,gBAAgB,uCAAuC,yCAS3D,IAAc,eAAe,QAAQ,EAAiB;AAC5D,MAAI,EAAa,QAAO;EACxB,IAAM,IAAY,aAAa,QAAQ,EAAiB;AACxD,MAAI,EAAW,Q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;IAG7D,OAAO,CAAC,KAAoB,KAAA;IAC5B,eAAY;cAEZ,kBAAC,OAAD;KACE,WAAW,2DACT,IAAmB,gBAAgB;eAGrC,kBAAC,OAAD;MAAK,WAAU;gBACb,kBAAC,GAAD;OACY;OACV,oBAAoB;OACpB,UAAU;OACV,CAAA;MACE,CAAA;KACF,CAAA;IACF,CAAA,EAEL,CAAC,KAAoB,kBAAC,OAAD,EAAK,WAAU,UAAW,CAAA,CAC/C,EAAA,CAAA;GAGL,kBAAC,GAAD;IACE,SAAS,MAAU,KAAK,EAAW,EAAM;IACzC,UAAU;IACV,aACE,MAAS,cACL,EAAG,qDAAqD,2CAA2C,GACnG,EAAG,qDAAqD,gCAAgC;IAE9F,cACE,kBAAA,IAAA,EAAA,UAAA,CACE,kBAAC,UAAD;KACE,MAAK;KACL,eAAe,GAAoB;KACnC,WAAU;KACV,cAAY,EAAG,kDAAkD,mBAAmB;KACpF,eAAY;eAEZ,kBAAC,IAAD,EAAM,WAAU,UAAW,CAAA;KACpB,CAAA,EACT,kBAAC,GAAD;KAA6B;KAAsB;KAAgB,cAAc;KAAoB,CAAA,CACpG,EAAA,CAAA;IAEL,CAAA;GAEF,kBAAC,GAAD;IACE,MAAM,MAAuB;IAC7B,WAAW;IACX,UAAU;IACV,CAAA;GACE"}
|
|
@@ -16,19 +16,19 @@ function w() {
|
|
|
16
16
|
e.id = "leaflet-css", e.rel = "stylesheet", e.href = v, e.integrity = y, e.crossOrigin = "anonymous", document.head.appendChild(e);
|
|
17
17
|
}
|
|
18
18
|
var T = ({ location: e, center: n }) => {
|
|
19
|
-
let { t: v } = l(), { toasts: y, toast: T, dismiss:
|
|
20
|
-
let e =
|
|
21
|
-
|
|
22
|
-
}, []),
|
|
23
|
-
let e =
|
|
24
|
-
|
|
25
|
-
}, []),
|
|
26
|
-
|
|
27
|
-
}, [
|
|
28
|
-
let e =
|
|
19
|
+
let { t: v } = l(), { toasts: y, toast: T, dismiss: ee } = i(), E = s(null), D = s(null), O = s(null), k = s(null), A = s(null), j = s(null), [M, N] = c("loading"), [P, F] = c(!1), [I, L] = c(!1), [R, z] = c(""), [B, V] = c(!1), [H, U] = c(null), [W, G] = c(null), K = v("healthybowl.weather.map.layers.streets", "Streets"), q = v("healthybowl.weather.map.layers.terrain", "Terrain"), J = v("healthybowl.weather.map.layers.radar", "Live radar"), Y = C(n) ? n : null, X = Y ? Y.lat : null, Z = Y ? Y.lng : null, Q = a(() => {
|
|
20
|
+
let e = D.current;
|
|
21
|
+
k.current && e && e.removeLayer(k.current), A.current && e && e.removeLayer(A.current), k.current = null, A.current = null;
|
|
22
|
+
}, []), $ = a(() => {
|
|
23
|
+
let e = D.current;
|
|
24
|
+
j.current && e && e.removeLayer(j.current), j.current = null;
|
|
25
|
+
}, []), te = a(() => {
|
|
26
|
+
$(), U(null);
|
|
27
|
+
}, [$]), ne = a(() => {
|
|
28
|
+
let e = D.current, t = O.current;
|
|
29
29
|
!e || !t || e.flyTo(t, b, { duration: .6 });
|
|
30
|
-
}, []),
|
|
31
|
-
let e =
|
|
30
|
+
}, []), re = a(() => {
|
|
31
|
+
let e = D.current;
|
|
32
32
|
if (e) {
|
|
33
33
|
if (typeof navigator > "u" || !navigator.geolocation) {
|
|
34
34
|
T({
|
|
@@ -38,29 +38,29 @@ var T = ({ location: e, center: n }) => {
|
|
|
38
38
|
});
|
|
39
39
|
return;
|
|
40
40
|
}
|
|
41
|
-
|
|
41
|
+
L(!0), navigator.geolocation.getCurrentPosition((t) => {
|
|
42
42
|
let n = [t.coords.latitude, t.coords.longitude];
|
|
43
|
-
|
|
43
|
+
Q(), A.current = _.default.circle(n, {
|
|
44
44
|
radius: Math.max(10, t.coords.accuracy || 0),
|
|
45
45
|
color: "#2563eb",
|
|
46
46
|
fillColor: "#3b82f6",
|
|
47
47
|
fillOpacity: .12,
|
|
48
48
|
opacity: .45,
|
|
49
49
|
weight: 1
|
|
50
|
-
}).addTo(e),
|
|
50
|
+
}).addTo(e), k.current = _.default.circleMarker(n, {
|
|
51
51
|
radius: 7,
|
|
52
52
|
color: "#ffffff",
|
|
53
53
|
weight: 2,
|
|
54
54
|
fillColor: "#2563eb",
|
|
55
55
|
fillOpacity: 1
|
|
56
|
-
}).addTo(e), e.flyTo(n, Math.max(e.getZoom(), x), { duration: .75 }),
|
|
56
|
+
}).addTo(e), e.flyTo(n, Math.max(e.getZoom(), x), { duration: .75 }), L(!1);
|
|
57
57
|
}, (e) => {
|
|
58
58
|
let t = e.code === e.PERMISSION_DENIED;
|
|
59
59
|
T({
|
|
60
60
|
title: t ? v("healthybowl.weather.map.toast.locationBlocked.title", "Location blocked") : v("healthybowl.weather.map.toast.locationFailed.title", "Could not get location"),
|
|
61
61
|
description: t ? v("healthybowl.weather.map.toast.locationBlocked.description", "Allow location access in the browser, then try again.") : v("healthybowl.weather.map.toast.locationFailed.description", "Make sure GPS is enabled and the page is open over HTTPS."),
|
|
62
62
|
variant: "warning"
|
|
63
|
-
}),
|
|
63
|
+
}), L(!1);
|
|
64
64
|
}, {
|
|
65
65
|
enableHighAccuracy: !0,
|
|
66
66
|
timeout: 12e3,
|
|
@@ -68,12 +68,12 @@ var T = ({ location: e, center: n }) => {
|
|
|
68
68
|
});
|
|
69
69
|
}
|
|
70
70
|
}, [
|
|
71
|
-
|
|
71
|
+
Q,
|
|
72
72
|
v,
|
|
73
73
|
T
|
|
74
|
-
]),
|
|
74
|
+
]), ie = a(async (e) => {
|
|
75
75
|
e.preventDefault();
|
|
76
|
-
let t =
|
|
76
|
+
let t = D.current, n = R.trim();
|
|
77
77
|
if (!n) {
|
|
78
78
|
T({
|
|
79
79
|
title: v("healthybowl.weather.map.toast.searchRequired.title", "Place required"),
|
|
@@ -83,7 +83,7 @@ var T = ({ location: e, center: n }) => {
|
|
|
83
83
|
return;
|
|
84
84
|
}
|
|
85
85
|
if (t) {
|
|
86
|
-
|
|
86
|
+
V(!0);
|
|
87
87
|
try {
|
|
88
88
|
let e = await r(n);
|
|
89
89
|
if (!e) {
|
|
@@ -99,15 +99,15 @@ var T = ({ location: e, center: n }) => {
|
|
|
99
99
|
e.admin1,
|
|
100
100
|
e.country
|
|
101
101
|
].filter(Boolean).join(", ") || n, a = [e.latitude, e.longitude];
|
|
102
|
-
|
|
102
|
+
$();
|
|
103
103
|
let o = document.createElement("span");
|
|
104
|
-
o.textContent = i,
|
|
104
|
+
o.textContent = i, j.current = _.default.circleMarker(a, {
|
|
105
105
|
radius: 8,
|
|
106
106
|
color: "#ffffff",
|
|
107
107
|
weight: 2,
|
|
108
108
|
fillColor: "#0ea5e9",
|
|
109
109
|
fillOpacity: 1
|
|
110
|
-
}).addTo(t).bindPopup(o).openPopup(), t.flyTo(a, Math.max(t.getZoom(), S), { duration: .75 }),
|
|
110
|
+
}).addTo(t).bindPopup(o).openPopup(), t.flyTo(a, Math.max(t.getZoom(), S), { duration: .75 }), U(i);
|
|
111
111
|
} catch (e) {
|
|
112
112
|
T({
|
|
113
113
|
title: v("healthybowl.weather.map.toast.searchFailed.title", "Search failed"),
|
|
@@ -115,75 +115,79 @@ var T = ({ location: e, center: n }) => {
|
|
|
115
115
|
variant: "error"
|
|
116
116
|
});
|
|
117
117
|
} finally {
|
|
118
|
-
|
|
118
|
+
V(!1);
|
|
119
119
|
}
|
|
120
120
|
}
|
|
121
121
|
}, [
|
|
122
|
-
|
|
123
|
-
|
|
122
|
+
$,
|
|
123
|
+
R,
|
|
124
124
|
v,
|
|
125
125
|
T
|
|
126
126
|
]);
|
|
127
127
|
return o(() => {
|
|
128
|
-
let t =
|
|
128
|
+
let t = E.current;
|
|
129
129
|
if (!t) return;
|
|
130
130
|
w();
|
|
131
|
-
let
|
|
132
|
-
return
|
|
133
|
-
let
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
131
|
+
let n = new AbortController(), i, a = !1;
|
|
132
|
+
return N("loading"), F(!1), G(null), U(null), O.current = null, (async () => {
|
|
133
|
+
let o = X !== null && Z !== null ? {
|
|
134
|
+
lat: X,
|
|
135
|
+
lng: Z
|
|
136
|
+
} : null, s = o ? null : await r(e, n.signal), c = o ? [o.lat, o.lng] : s ? [s.latitude, s.longitude] : null;
|
|
137
|
+
if (a || !E.current) return;
|
|
138
|
+
let l = c ?? [20, 0], u = c ? b : 2;
|
|
139
|
+
O.current = c ? _.default.latLng(c[0], c[1]) : null, F(!!c), i = _.default.map(t, {
|
|
140
|
+
center: l,
|
|
141
|
+
zoom: u,
|
|
139
142
|
scrollWheelZoom: !0
|
|
140
|
-
}),
|
|
141
|
-
let
|
|
143
|
+
}), D.current = i;
|
|
144
|
+
let d = _.default.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
|
|
142
145
|
attribution: "© OpenStreetMap contributors",
|
|
143
146
|
maxZoom: 18
|
|
144
|
-
}),
|
|
147
|
+
}), f = _.default.tileLayer("https://{s}.tile.opentopomap.org/{z}/{x}/{y}.png", {
|
|
145
148
|
attribution: "© OpenTopoMap (CC-BY-SA) · © OpenStreetMap contributors",
|
|
146
149
|
maxZoom: 17
|
|
147
150
|
});
|
|
148
|
-
|
|
149
|
-
let
|
|
150
|
-
[
|
|
151
|
-
[
|
|
152
|
-
}, void 0, { collapsed: !1 }).addTo(
|
|
153
|
-
if (_.default.control.scale({ imperial: !1 }).addTo(
|
|
151
|
+
d.addTo(i);
|
|
152
|
+
let p = _.default.control.layers({
|
|
153
|
+
[K]: d,
|
|
154
|
+
[q]: f
|
|
155
|
+
}, void 0, { collapsed: !1 }).addTo(i);
|
|
156
|
+
if (_.default.control.scale({ imperial: !1 }).addTo(i), c) {
|
|
154
157
|
let t = _.default.divIcon({
|
|
155
158
|
className: "hb-weather-marker",
|
|
156
159
|
html: "<div style=\"width:16px;height:16px;border-radius:50% 50% 50% 0;transform:rotate(-45deg);background:var(--color-action-primary-bg, #16a34a);border:2px solid #fff;box-shadow:0 1px 4px rgba(0,0,0,.4)\"></div>",
|
|
157
160
|
iconSize: [16, 16],
|
|
158
161
|
iconAnchor: [8, 16]
|
|
159
162
|
}), n = document.createElement("span");
|
|
160
|
-
n.textContent = e || "Your farm", _.default.marker(
|
|
163
|
+
n.textContent = e || "Your farm", _.default.marker(l, { icon: t }).addTo(i).bindPopup(n);
|
|
161
164
|
}
|
|
162
165
|
try {
|
|
163
|
-
let e = await (await fetch("https://api.rainviewer.com/public/weather-maps.json", { signal:
|
|
164
|
-
if (!
|
|
165
|
-
let t = _.default.tileLayer(`${e.host}${
|
|
166
|
+
let e = await (await fetch("https://api.rainviewer.com/public/weather-maps.json", { signal: n.signal })).json(), t = e.radar?.past ?? [], r = t[t.length - 1];
|
|
167
|
+
if (!a && i && e.host && r?.path) {
|
|
168
|
+
let t = _.default.tileLayer(`${e.host}${r.path}/256/{z}/{x}/{y}/4/1_1.png`, {
|
|
166
169
|
opacity: .55,
|
|
167
170
|
maxZoom: 18,
|
|
168
171
|
maxNativeZoom: 7
|
|
169
|
-
}).addTo(
|
|
170
|
-
|
|
172
|
+
}).addTo(i);
|
|
173
|
+
p.addOverlay(t, J), typeof r.time == "number" && G(/* @__PURE__ */ new Date(r.time * 1e3));
|
|
171
174
|
}
|
|
172
175
|
} catch {}
|
|
173
|
-
|
|
176
|
+
a || (N("ready"), window.setTimeout(() => i?.invalidateSize(), 80));
|
|
174
177
|
})().catch(() => {
|
|
175
|
-
|
|
178
|
+
a || N("error");
|
|
176
179
|
}), () => {
|
|
177
|
-
|
|
180
|
+
a = !0, n.abort(), Q(), $(), i?.remove(), D.current = null, O.current = null;
|
|
178
181
|
};
|
|
179
182
|
}, [
|
|
180
|
-
n,
|
|
181
183
|
X,
|
|
182
|
-
e,
|
|
183
|
-
Y,
|
|
184
184
|
Z,
|
|
185
|
-
|
|
186
|
-
|
|
185
|
+
Q,
|
|
186
|
+
e,
|
|
187
|
+
J,
|
|
188
|
+
$,
|
|
189
|
+
K,
|
|
190
|
+
q
|
|
187
191
|
]), /* @__PURE__ */ h("div", {
|
|
188
192
|
className: "relative",
|
|
189
193
|
children: [
|
|
@@ -191,16 +195,16 @@ var T = ({ location: e, center: n }) => {
|
|
|
191
195
|
className: "mb-3 flex flex-wrap items-center gap-2",
|
|
192
196
|
children: [
|
|
193
197
|
/* @__PURE__ */ h("form", {
|
|
194
|
-
onSubmit:
|
|
198
|
+
onSubmit: ie,
|
|
195
199
|
className: "flex min-w-[min(100%,22rem)] flex-1 flex-wrap items-center gap-2",
|
|
196
200
|
children: [
|
|
197
201
|
/* @__PURE__ */ h("div", {
|
|
198
202
|
className: "relative min-w-[12rem] flex-1",
|
|
199
203
|
children: [/* @__PURE__ */ m(f, { className: "pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-text-secondary" }), /* @__PURE__ */ m("input", {
|
|
200
204
|
type: "search",
|
|
201
|
-
value:
|
|
202
|
-
onChange: (e) =>
|
|
203
|
-
disabled:
|
|
205
|
+
value: R,
|
|
206
|
+
onChange: (e) => z(e.target.value),
|
|
207
|
+
disabled: M !== "ready" || B,
|
|
204
208
|
placeholder: v("healthybowl.weather.map.search.placeholder", "Search city or place..."),
|
|
205
209
|
"aria-label": v("healthybowl.weather.map.search.label", "Search map by place"),
|
|
206
210
|
className: "h-9 w-full rounded-md border border-border-subtle bg-bg-surface py-2 pl-9 pr-3 text-sm text-text-primary placeholder:text-text-secondary focus:outline-none focus:ring-2 focus:ring-[var(--color-focus-ring)] disabled:cursor-not-allowed disabled:opacity-60"
|
|
@@ -210,18 +214,18 @@ var T = ({ location: e, center: n }) => {
|
|
|
210
214
|
type: "submit",
|
|
211
215
|
variant: "outline",
|
|
212
216
|
size: "sm",
|
|
213
|
-
disabled:
|
|
217
|
+
disabled: M !== "ready" || B,
|
|
214
218
|
children: [
|
|
215
219
|
/* @__PURE__ */ m(f, { className: "h-4 w-4" }),
|
|
216
220
|
" ",
|
|
217
|
-
|
|
221
|
+
B ? v("healthybowl.weather.map.search.searching", "Searching...") : v("healthybowl.weather.map.search.action", "Search")
|
|
218
222
|
]
|
|
219
223
|
}),
|
|
220
|
-
|
|
224
|
+
H && /* @__PURE__ */ m(g, {
|
|
221
225
|
type: "button",
|
|
222
226
|
variant: "ghost",
|
|
223
227
|
size: "sm",
|
|
224
|
-
onClick:
|
|
228
|
+
onClick: te,
|
|
225
229
|
"aria-label": v("healthybowl.weather.map.search.clear", "Clear searched place"),
|
|
226
230
|
title: v("healthybowl.weather.map.search.clear", "Clear searched place"),
|
|
227
231
|
children: /* @__PURE__ */ m(p, { className: "h-4 w-4" })
|
|
@@ -231,8 +235,8 @@ var T = ({ location: e, center: n }) => {
|
|
|
231
235
|
/* @__PURE__ */ h(g, {
|
|
232
236
|
variant: "outline",
|
|
233
237
|
size: "sm",
|
|
234
|
-
onClick:
|
|
235
|
-
disabled: !
|
|
238
|
+
onClick: ne,
|
|
239
|
+
disabled: !P || M === "loading",
|
|
236
240
|
title: v("healthybowl.weather.map.actions.focusFarm.title", "Focus the weather map on the farm"),
|
|
237
241
|
"aria-label": v("healthybowl.weather.map.actions.focusFarm.title", "Focus the weather map on the farm"),
|
|
238
242
|
children: [
|
|
@@ -244,31 +248,31 @@ var T = ({ location: e, center: n }) => {
|
|
|
244
248
|
/* @__PURE__ */ h(g, {
|
|
245
249
|
variant: "outline",
|
|
246
250
|
size: "sm",
|
|
247
|
-
onClick:
|
|
248
|
-
disabled:
|
|
251
|
+
onClick: re,
|
|
252
|
+
disabled: I || M !== "ready",
|
|
249
253
|
title: v("healthybowl.weather.map.actions.locateMe.title", "Go to my current location"),
|
|
250
254
|
"aria-label": v("healthybowl.weather.map.actions.locateMe.title", "Go to my current location"),
|
|
251
255
|
children: [
|
|
252
256
|
/* @__PURE__ */ m(u, { className: "h-4 w-4" }),
|
|
253
257
|
" ",
|
|
254
|
-
|
|
258
|
+
I ? v("healthybowl.weather.map.actions.locating", "Locating...") : v("healthybowl.weather.map.actions.locateMe", "My location")
|
|
255
259
|
]
|
|
256
260
|
})
|
|
257
261
|
]
|
|
258
262
|
}),
|
|
259
263
|
/* @__PURE__ */ m("div", {
|
|
260
|
-
ref:
|
|
264
|
+
ref: E,
|
|
261
265
|
className: "h-[60vh] max-h-[460px] w-full overflow-hidden rounded-md border border-border-subtle bg-bg-sunken"
|
|
262
266
|
}),
|
|
263
|
-
|
|
267
|
+
M === "loading" && /* @__PURE__ */ m("div", {
|
|
264
268
|
className: "pointer-events-none absolute inset-0 flex items-center justify-center rounded-md bg-bg-surface/60 text-sm text-text-secondary",
|
|
265
269
|
children: "Loading map…"
|
|
266
270
|
}),
|
|
267
|
-
|
|
271
|
+
M === "error" && /* @__PURE__ */ m("div", {
|
|
268
272
|
className: "pointer-events-none absolute inset-0 flex items-center justify-center rounded-md bg-bg-surface/80 px-4 text-center text-sm text-text-secondary",
|
|
269
273
|
children: "Weather map needs an internet connection and couldn’t load."
|
|
270
274
|
}),
|
|
271
|
-
|
|
275
|
+
M === "ready" && !P && /* @__PURE__ */ m("div", {
|
|
272
276
|
className: "pointer-events-none absolute left-1/2 top-16 z-[400] -translate-x-1/2 rounded-full bg-bg-surface/90 px-3 py-1.5 text-xs text-text-secondary shadow-sm",
|
|
273
277
|
children: v("healthybowl.weather.map.noLocation", "No farm coordinates available")
|
|
274
278
|
}),
|
|
@@ -277,8 +281,8 @@ var T = ({ location: e, center: n }) => {
|
|
|
277
281
|
children: [
|
|
278
282
|
"Live precipitation radar via RainViewer · base map © OpenStreetMap",
|
|
279
283
|
e ? ` · centered on ${e}` : "",
|
|
280
|
-
|
|
281
|
-
|
|
284
|
+
H ? ` · viewing ${H}` : "",
|
|
285
|
+
W ? ` · radar ${W.toLocaleTimeString([], {
|
|
282
286
|
hour: "2-digit",
|
|
283
287
|
minute: "2-digit"
|
|
284
288
|
})}` : ""
|
|
@@ -286,7 +290,7 @@ var T = ({ location: e, center: n }) => {
|
|
|
286
290
|
}),
|
|
287
291
|
/* @__PURE__ */ m(t, {
|
|
288
292
|
toasts: y,
|
|
289
|
-
onDismiss:
|
|
293
|
+
onDismiss: ee
|
|
290
294
|
})
|
|
291
295
|
]
|
|
292
296
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"WeatherMap.js","names":[],"sources":["../../../src/healthybowl/components/WeatherMap.tsx"],"sourcesContent":["import { useCallback, useEffect, useRef, useState, type FC, type FormEvent } from 'react';\nimport L from 'leaflet';\nimport { LocateFixed, MapPinned, Search, X } from 'lucide-react';\nimport { Button } from '@burdenoff/fe-libs/ui';\nimport { useI18n } from '@burdenoff/fe-libs/shared/providers/shell/I18nProvider';\nimport { geocodePlace } from '../utils/geocode';\nimport { useToast } from '../hooks/useToast';\nimport { ToastContainer } from './Toast';\n\ninterface WeatherMapProps {\n /** Resolved place name (from the weather data) used to center the map. */\n location: string;\n /** Backend-resolved farm/weather coordinates. Preferred over client-side geocoding. */\n center?: { lat: number; lng: number } | null;\n}\n\nconst LEAFLET_CSS = 'https://unpkg.com/leaflet@1.9.4/dist/leaflet.css';\n// SRI for leaflet@1.9.4/dist/leaflet.css (immutable versioned URL) — guards against a CDN compromise.\nconst LEAFLET_CSS_SRI = 'sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY=';\nconst FARM_WEATHER_ZOOM = 7;\nconst USER_LOCATION_ZOOM = 10;\nconst SEARCH_LOCATION_ZOOM = 10;\n\nconst isUsableCoordinate = (value?: { lat: number; lng: number } | null): value is { lat: number; lng: number } =>\n Boolean(\n value &&\n Number.isFinite(value.lat) &&\n Number.isFinite(value.lng) &&\n value.lat >= -90 &&\n value.lat <= 90 &&\n value.lng >= -180 &&\n value.lng <= 180 &&\n (value.lat !== 0 || value.lng !== 0)\n );\n\n/**\n * Inject Leaflet's stylesheet at runtime. The MFE library build doesn't deliver\n * a component's bundled CSS to the host shell (the host styles come from its own\n * Tailwind), so we load Leaflet's CSS from a CDN instead — consistent with the\n * map being an inherently online feature (tiles + radar).\n */\nfunction ensureLeafletCss(): void {\n if (document.getElementById('leaflet-css')) return;\n const link = document.createElement('link');\n link.id = 'leaflet-css';\n link.rel = 'stylesheet';\n link.href = LEAFLET_CSS;\n link.integrity = LEAFLET_CSS_SRI;\n link.crossOrigin = 'anonymous';\n document.head.appendChild(link);\n}\n\n/**\n * Interactive weather map: OpenStreetMap base + live precipitation radar overlay\n * (RainViewer, keyless), centered on backend-resolved farm coordinates when\n * available, then client-geocoded from the weather location as a fallback.\n */\nexport const WeatherMap: FC<WeatherMapProps> = ({ location, center }) => {\n const { t } = useI18n();\n const { toasts, toast, dismiss } = useToast();\n const containerRef = useRef<HTMLDivElement>(null);\n const mapRef = useRef<L.Map | null>(null);\n const farmCenterRef = useRef<L.LatLng | null>(null);\n const userLocationMarkerRef = useRef<L.CircleMarker | null>(null);\n const userAccuracyCircleRef = useRef<L.Circle | null>(null);\n const searchedPlaceMarkerRef = useRef<L.CircleMarker | null>(null);\n const [status, setStatus] = useState<'loading' | 'ready' | 'error'>('loading');\n const [hasFarmCenter, setHasFarmCenter] = useState(false);\n const [locating, setLocating] = useState(false);\n const [searchQuery, setSearchQuery] = useState('');\n const [searching, setSearching] = useState(false);\n const [searchedPlace, setSearchedPlace] = useState<string | null>(null);\n const [radarUpdatedAt, setRadarUpdatedAt] = useState<Date | null>(null);\n const streetsLayerLabel = t('healthybowl.weather.map.layers.streets', 'Streets');\n const terrainLayerLabel = t('healthybowl.weather.map.layers.terrain', 'Terrain');\n const radarLayerLabel = t('healthybowl.weather.map.layers.radar', 'Live radar');\n\n const clearUserLocation = useCallback(() => {\n const map = mapRef.current;\n if (userLocationMarkerRef.current && map) map.removeLayer(userLocationMarkerRef.current);\n if (userAccuracyCircleRef.current && map) map.removeLayer(userAccuracyCircleRef.current);\n userLocationMarkerRef.current = null;\n userAccuracyCircleRef.current = null;\n }, []);\n\n const removeSearchedPlaceMarker = useCallback(() => {\n const map = mapRef.current;\n if (searchedPlaceMarkerRef.current && map) map.removeLayer(searchedPlaceMarkerRef.current);\n searchedPlaceMarkerRef.current = null;\n }, []);\n\n const clearSearchedPlace = useCallback(() => {\n removeSearchedPlaceMarker();\n setSearchedPlace(null);\n }, [removeSearchedPlaceMarker]);\n\n const focusFarm = useCallback(() => {\n const map = mapRef.current;\n const farmCenter = farmCenterRef.current;\n if (!map || !farmCenter) return;\n map.flyTo(farmCenter, FARM_WEATHER_ZOOM, { duration: 0.6 });\n }, []);\n\n const handleLocateMe = useCallback(() => {\n const map = mapRef.current;\n if (!map) return;\n if (typeof navigator === 'undefined' || !navigator.geolocation) {\n toast({\n title: t('healthybowl.weather.map.toast.locationUnsupported.title', 'Location unavailable'),\n description: t(\n 'healthybowl.weather.map.toast.locationUnsupported.description',\n 'This browser does not support device location.'\n ),\n variant: 'warning',\n });\n return;\n }\n\n setLocating(true);\n navigator.geolocation.getCurrentPosition(\n (position) => {\n const latlng: L.LatLngExpression = [position.coords.latitude, position.coords.longitude];\n clearUserLocation();\n userAccuracyCircleRef.current = L.circle(latlng, {\n radius: Math.max(10, position.coords.accuracy || 0),\n color: '#2563eb',\n fillColor: '#3b82f6',\n fillOpacity: 0.12,\n opacity: 0.45,\n weight: 1,\n }).addTo(map);\n userLocationMarkerRef.current = L.circleMarker(latlng, {\n radius: 7,\n color: '#ffffff',\n weight: 2,\n fillColor: '#2563eb',\n fillOpacity: 1,\n }).addTo(map);\n map.flyTo(latlng, Math.max(map.getZoom(), USER_LOCATION_ZOOM), { duration: 0.75 });\n setLocating(false);\n },\n (error) => {\n const blocked = error.code === error.PERMISSION_DENIED;\n toast({\n title: blocked\n ? t('healthybowl.weather.map.toast.locationBlocked.title', 'Location blocked')\n : t('healthybowl.weather.map.toast.locationFailed.title', 'Could not get location'),\n description: blocked\n ? t(\n 'healthybowl.weather.map.toast.locationBlocked.description',\n 'Allow location access in the browser, then try again.'\n )\n : t(\n 'healthybowl.weather.map.toast.locationFailed.description',\n 'Make sure GPS is enabled and the page is open over HTTPS.'\n ),\n variant: 'warning',\n });\n setLocating(false);\n },\n { enableHighAccuracy: true, timeout: 12000, maximumAge: 60000 }\n );\n }, [clearUserLocation, t, toast]);\n\n const handleSearchPlace = useCallback(\n async (event: FormEvent<HTMLFormElement>) => {\n event.preventDefault();\n const map = mapRef.current;\n const place = searchQuery.trim();\n if (!place) {\n toast({\n title: t('healthybowl.weather.map.toast.searchRequired.title', 'Place required'),\n description: t(\n 'healthybowl.weather.map.toast.searchRequired.description',\n 'Enter a city, village, district, or region to view it on the map.'\n ),\n variant: 'warning',\n });\n return;\n }\n if (!map) return;\n\n setSearching(true);\n try {\n const hit = await geocodePlace(place);\n if (!hit) {\n toast({\n title: t('healthybowl.weather.map.toast.searchNotFound.title', 'Place not found'),\n description: t(\n 'healthybowl.weather.map.toast.searchNotFound.description',\n 'Try a more specific location name, such as city and state.'\n ),\n variant: 'warning',\n });\n return;\n }\n\n const label = [hit.name, hit.admin1, hit.country].filter(Boolean).join(', ') || place;\n const latlng: L.LatLngExpression = [hit.latitude, hit.longitude];\n removeSearchedPlaceMarker();\n const popupEl = document.createElement('span');\n popupEl.textContent = label;\n searchedPlaceMarkerRef.current = L.circleMarker(latlng, {\n radius: 8,\n color: '#ffffff',\n weight: 2,\n fillColor: '#0ea5e9',\n fillOpacity: 1,\n })\n .addTo(map)\n .bindPopup(popupEl)\n .openPopup();\n map.flyTo(latlng, Math.max(map.getZoom(), SEARCH_LOCATION_ZOOM), { duration: 0.75 });\n setSearchedPlace(label);\n } catch (err) {\n toast({\n title: t('healthybowl.weather.map.toast.searchFailed.title', 'Search failed'),\n description: err instanceof Error ? err.message : String(err),\n variant: 'error',\n });\n } finally {\n setSearching(false);\n }\n },\n [removeSearchedPlaceMarker, searchQuery, t, toast]\n );\n\n useEffect(() => {\n const el = containerRef.current;\n if (!el) return undefined;\n ensureLeafletCss();\n const controller = new AbortController();\n let map: L.Map | undefined;\n let cancelled = false;\n setStatus('loading');\n setHasFarmCenter(false);\n setRadarUpdatedAt(null);\n setSearchedPlace(null);\n farmCenterRef.current = null;\n\n void (async () => {\n const backendCenter = isUsableCoordinate(center) ? center : null;\n const hit = backendCenter ? null : await geocodePlace(location, controller.signal);\n const located: [number, number] | null = backendCenter\n ? [backendCenter.lat, backendCenter.lng]\n : hit\n ? [hit.latitude, hit.longitude]\n : null;\n if (cancelled || !containerRef.current) return;\n const mapCenter: L.LatLngExpression = located ?? [20, 0];\n // z7 keeps the RainViewer radar at its native resolution (it has no tiles past z7)\n // while still framing the farm and its surrounding weather system.\n const zoom = located ? FARM_WEATHER_ZOOM : 2;\n farmCenterRef.current = located ? L.latLng(located[0], located[1]) : null;\n setHasFarmCenter(Boolean(located));\n\n map = L.map(el, { center: mapCenter, zoom, scrollWheelZoom: true });\n mapRef.current = map;\n const streetsLayer = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {\n attribution: '© OpenStreetMap contributors',\n maxZoom: 18,\n });\n const terrainLayer = L.tileLayer('https://{s}.tile.opentopomap.org/{z}/{x}/{y}.png', {\n attribution: '© OpenTopoMap (CC-BY-SA) · © OpenStreetMap contributors',\n maxZoom: 17,\n });\n streetsLayer.addTo(map);\n const layerControl = L.control\n .layers(\n {\n [streetsLayerLabel]: streetsLayer,\n [terrainLayerLabel]: terrainLayer,\n },\n undefined,\n { collapsed: false }\n )\n .addTo(map);\n L.control.scale({ imperial: false }).addTo(map);\n\n if (located) {\n const icon = L.divIcon({\n className: 'hb-weather-marker',\n html:\n '<div style=\"width:16px;height:16px;border-radius:50% 50% 50% 0;transform:rotate(-45deg);' +\n 'background:var(--color-action-primary-bg, #16a34a);border:2px solid #fff;box-shadow:0 1px 4px rgba(0,0,0,.4)\"></div>',\n iconSize: [16, 16],\n iconAnchor: [8, 16],\n });\n // bindPopup treats a string as HTML; pass a text node so the place name\n // can never be interpreted as markup (defense-in-depth against a tainted value).\n const popupEl = document.createElement('span');\n popupEl.textContent = location || 'Your farm';\n L.marker(mapCenter, { icon }).addTo(map).bindPopup(popupEl);\n }\n\n // Live precipitation radar overlay (RainViewer — free, keyless).\n try {\n const res = await fetch('https://api.rainviewer.com/public/weather-maps.json', { signal: controller.signal });\n const data = (await res.json()) as {\n host?: string;\n radar?: { past?: Array<{ path?: string; time?: number }> };\n };\n const frames = data.radar?.past ?? [];\n const latest = frames[frames.length - 1];\n // The map may have been removed during the await — guard before touching it.\n if (!cancelled && map && data.host && latest?.path) {\n // RainViewer radar only has tiles up to z7; cap maxNativeZoom so Leaflet\n // upscales from z7 instead of requesting the \"Zoom Level Not Supported\" placeholder.\n const radarLayer = L.tileLayer(`${data.host}${latest.path}/256/{z}/{x}/{y}/4/1_1.png`, {\n opacity: 0.55,\n maxZoom: 18,\n maxNativeZoom: 7,\n }).addTo(map);\n layerControl.addOverlay(radarLayer, radarLayerLabel);\n if (typeof latest.time === 'number') setRadarUpdatedAt(new Date(latest.time * 1000));\n }\n } catch {\n /* radar overlay is best-effort */\n }\n\n if (!cancelled) {\n setStatus('ready');\n window.setTimeout(() => map?.invalidateSize(), 80);\n }\n })().catch(() => {\n if (!cancelled) setStatus('error');\n });\n\n return () => {\n cancelled = true;\n controller.abort();\n clearUserLocation();\n removeSearchedPlaceMarker();\n map?.remove();\n mapRef.current = null;\n farmCenterRef.current = null;\n };\n }, [\n center,\n clearUserLocation,\n location,\n radarLayerLabel,\n removeSearchedPlaceMarker,\n streetsLayerLabel,\n terrainLayerLabel,\n ]);\n\n return (\n <div className=\"relative\">\n <div className=\"mb-3 flex flex-wrap items-center gap-2\">\n <form onSubmit={handleSearchPlace} className=\"flex min-w-[min(100%,22rem)] flex-1 flex-wrap items-center gap-2\">\n <div className=\"relative min-w-[12rem] flex-1\">\n <Search className=\"pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-text-secondary\" />\n <input\n type=\"search\"\n value={searchQuery}\n onChange={(event) => setSearchQuery(event.target.value)}\n disabled={status !== 'ready' || searching}\n placeholder={t('healthybowl.weather.map.search.placeholder', 'Search city or place...')}\n aria-label={t('healthybowl.weather.map.search.label', 'Search map by place')}\n className=\"h-9 w-full rounded-md border border-border-subtle bg-bg-surface py-2 pl-9 pr-3 text-sm text-text-primary placeholder:text-text-secondary focus:outline-none focus:ring-2 focus:ring-[var(--color-focus-ring)] disabled:cursor-not-allowed disabled:opacity-60\"\n />\n </div>\n <Button type=\"submit\" variant=\"outline\" size=\"sm\" disabled={status !== 'ready' || searching}>\n <Search className=\"h-4 w-4\" />{' '}\n {searching\n ? t('healthybowl.weather.map.search.searching', 'Searching...')\n : t('healthybowl.weather.map.search.action', 'Search')}\n </Button>\n {searchedPlace && (\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"sm\"\n onClick={clearSearchedPlace}\n aria-label={t('healthybowl.weather.map.search.clear', 'Clear searched place')}\n title={t('healthybowl.weather.map.search.clear', 'Clear searched place')}\n >\n <X className=\"h-4 w-4\" />\n </Button>\n )}\n </form>\n <Button\n variant=\"outline\"\n size=\"sm\"\n onClick={focusFarm}\n disabled={!hasFarmCenter || status === 'loading'}\n title={t('healthybowl.weather.map.actions.focusFarm.title', 'Focus the weather map on the farm')}\n aria-label={t('healthybowl.weather.map.actions.focusFarm.title', 'Focus the weather map on the farm')}\n >\n <MapPinned className=\"h-4 w-4\" /> {t('healthybowl.weather.map.actions.focusFarm', 'Farm')}\n </Button>\n <Button\n variant=\"outline\"\n size=\"sm\"\n onClick={handleLocateMe}\n disabled={locating || status !== 'ready'}\n title={t('healthybowl.weather.map.actions.locateMe.title', 'Go to my current location')}\n aria-label={t('healthybowl.weather.map.actions.locateMe.title', 'Go to my current location')}\n >\n <LocateFixed className=\"h-4 w-4\" />{' '}\n {locating\n ? t('healthybowl.weather.map.actions.locating', 'Locating...')\n : t('healthybowl.weather.map.actions.locateMe', 'My location')}\n </Button>\n </div>\n <div\n ref={containerRef}\n className=\"h-[60vh] max-h-[460px] w-full overflow-hidden rounded-md border border-border-subtle bg-bg-sunken\"\n />\n {status === 'loading' && (\n <div className=\"pointer-events-none absolute inset-0 flex items-center justify-center rounded-md bg-bg-surface/60 text-sm text-text-secondary\">\n Loading map…\n </div>\n )}\n {status === 'error' && (\n <div className=\"pointer-events-none absolute inset-0 flex items-center justify-center rounded-md bg-bg-surface/80 px-4 text-center text-sm text-text-secondary\">\n Weather map needs an internet connection and couldn’t load.\n </div>\n )}\n {status === 'ready' && !hasFarmCenter && (\n <div className=\"pointer-events-none absolute left-1/2 top-16 z-[400] -translate-x-1/2 rounded-full bg-bg-surface/90 px-3 py-1.5 text-xs text-text-secondary shadow-sm\">\n {t('healthybowl.weather.map.noLocation', 'No farm coordinates available')}\n </div>\n )}\n <p className=\"mt-2 text-xs text-text-secondary\">\n Live precipitation radar via RainViewer · base map © OpenStreetMap\n {location ? ` · centered on ${location}` : ''}\n {searchedPlace ? ` · viewing ${searchedPlace}` : ''}\n {radarUpdatedAt\n ? ` · radar ${radarUpdatedAt.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}`\n : ''}\n </p>\n <ToastContainer toasts={toasts} onDismiss={dismiss} />\n </div>\n );\n};\n"],"mappings":";;;;;;;;;;;mCAgBM,IAAc,oDAEd,IAAkB,uDAClB,IAAoB,GACpB,IAAqB,IACrB,IAAuB,IAEvB,KAAsB,MAC1B,GACE,KACA,OAAO,SAAS,EAAM,IAAI,IAC1B,OAAO,SAAS,EAAM,IAAI,IAC1B,EAAM,OAAO,OACb,EAAM,OAAO,MACb,EAAM,OAAO,QACb,EAAM,OAAO,QACZ,EAAM,QAAQ,KAAK,EAAM,QAAQ;AAStC,SAAS,IAAyB;AAChC,KAAI,SAAS,eAAe,cAAc,CAAE;CAC5C,IAAM,IAAO,SAAS,cAAc,OAAO;AAM3C,CALA,EAAK,KAAK,eACV,EAAK,MAAM,cACX,EAAK,OAAO,GACZ,EAAK,YAAY,GACjB,EAAK,cAAc,aACnB,SAAS,KAAK,YAAY,EAAK;;AAQjC,IAAa,KAAmC,EAAE,aAAU,gBAAa;CACvE,IAAM,EAAE,SAAM,GAAS,EACjB,EAAE,WAAQ,UAAO,eAAY,GAAU,EACvC,IAAe,EAAuB,KAAK,EAC3C,IAAS,EAAqB,KAAK,EACnC,IAAgB,EAAwB,KAAK,EAC7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sources":["../../../src/healthybowl/components/WeatherMap.tsx"],"sourcesContent":["import { useCallback, useEffect, useRef, useState, type FC, type FormEvent } from 'react';\nimport L from 'leaflet';\nimport { LocateFixed, MapPinned, Search, X } from 'lucide-react';\nimport { Button } from '@burdenoff/fe-libs/ui';\nimport { useI18n } from '@burdenoff/fe-libs/shared/providers/shell/I18nProvider';\nimport { geocodePlace } from '../utils/geocode';\nimport { useToast } from '../hooks/useToast';\nimport { ToastContainer } from './Toast';\n\ninterface WeatherMapProps {\n /** Resolved place name (from the weather data) used to center the map. */\n location: string;\n /** Backend-resolved farm/weather coordinates. Preferred over client-side geocoding. */\n center?: { lat: number; lng: number } | null;\n}\n\nconst LEAFLET_CSS = 'https://unpkg.com/leaflet@1.9.4/dist/leaflet.css';\n// SRI for leaflet@1.9.4/dist/leaflet.css (immutable versioned URL) — guards against a CDN compromise.\nconst LEAFLET_CSS_SRI = 'sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY=';\nconst FARM_WEATHER_ZOOM = 7;\nconst USER_LOCATION_ZOOM = 10;\nconst SEARCH_LOCATION_ZOOM = 10;\n\nconst isUsableCoordinate = (value?: { lat: number; lng: number } | null): value is { lat: number; lng: number } =>\n Boolean(\n value &&\n Number.isFinite(value.lat) &&\n Number.isFinite(value.lng) &&\n value.lat >= -90 &&\n value.lat <= 90 &&\n value.lng >= -180 &&\n value.lng <= 180 &&\n (value.lat !== 0 || value.lng !== 0)\n );\n\n/**\n * Inject Leaflet's stylesheet at runtime. The MFE library build doesn't deliver\n * a component's bundled CSS to the host shell (the host styles come from its own\n * Tailwind), so we load Leaflet's CSS from a CDN instead — consistent with the\n * map being an inherently online feature (tiles + radar).\n */\nfunction ensureLeafletCss(): void {\n if (document.getElementById('leaflet-css')) return;\n const link = document.createElement('link');\n link.id = 'leaflet-css';\n link.rel = 'stylesheet';\n link.href = LEAFLET_CSS;\n link.integrity = LEAFLET_CSS_SRI;\n link.crossOrigin = 'anonymous';\n document.head.appendChild(link);\n}\n\n/**\n * Interactive weather map: OpenStreetMap base + live precipitation radar overlay\n * (RainViewer, keyless), centered on backend-resolved farm coordinates when\n * available, then client-geocoded from the weather location as a fallback.\n */\nexport const WeatherMap: FC<WeatherMapProps> = ({ location, center }) => {\n const { t } = useI18n();\n const { toasts, toast, dismiss } = useToast();\n const containerRef = useRef<HTMLDivElement>(null);\n const mapRef = useRef<L.Map | null>(null);\n const farmCenterRef = useRef<L.LatLng | null>(null);\n const userLocationMarkerRef = useRef<L.CircleMarker | null>(null);\n const userAccuracyCircleRef = useRef<L.Circle | null>(null);\n const searchedPlaceMarkerRef = useRef<L.CircleMarker | null>(null);\n const [status, setStatus] = useState<'loading' | 'ready' | 'error'>('loading');\n const [hasFarmCenter, setHasFarmCenter] = useState(false);\n const [locating, setLocating] = useState(false);\n const [searchQuery, setSearchQuery] = useState('');\n const [searching, setSearching] = useState(false);\n const [searchedPlace, setSearchedPlace] = useState<string | null>(null);\n const [radarUpdatedAt, setRadarUpdatedAt] = useState<Date | null>(null);\n const streetsLayerLabel = t('healthybowl.weather.map.layers.streets', 'Streets');\n const terrainLayerLabel = t('healthybowl.weather.map.layers.terrain', 'Terrain');\n const radarLayerLabel = t('healthybowl.weather.map.layers.radar', 'Live radar');\n\n // Depend on the primitive coordinates, not the `center` object: the parent\n // re-renders on every weather/radar refresh and hands us a fresh {lat,lng}\n // object with identical values. Keying the map-creation effect on the object\n // reference re-created the whole Leaflet map on each refresh, snapping the view\n // back to the farm and wiping any place the user had searched for.\n const usableCenter = isUsableCoordinate(center) ? center : null;\n const centerLat = usableCenter ? usableCenter.lat : null;\n const centerLng = usableCenter ? usableCenter.lng : null;\n\n const clearUserLocation = useCallback(() => {\n const map = mapRef.current;\n if (userLocationMarkerRef.current && map) map.removeLayer(userLocationMarkerRef.current);\n if (userAccuracyCircleRef.current && map) map.removeLayer(userAccuracyCircleRef.current);\n userLocationMarkerRef.current = null;\n userAccuracyCircleRef.current = null;\n }, []);\n\n const removeSearchedPlaceMarker = useCallback(() => {\n const map = mapRef.current;\n if (searchedPlaceMarkerRef.current && map) map.removeLayer(searchedPlaceMarkerRef.current);\n searchedPlaceMarkerRef.current = null;\n }, []);\n\n const clearSearchedPlace = useCallback(() => {\n removeSearchedPlaceMarker();\n setSearchedPlace(null);\n }, [removeSearchedPlaceMarker]);\n\n const focusFarm = useCallback(() => {\n const map = mapRef.current;\n const farmCenter = farmCenterRef.current;\n if (!map || !farmCenter) return;\n map.flyTo(farmCenter, FARM_WEATHER_ZOOM, { duration: 0.6 });\n }, []);\n\n const handleLocateMe = useCallback(() => {\n const map = mapRef.current;\n if (!map) return;\n if (typeof navigator === 'undefined' || !navigator.geolocation) {\n toast({\n title: t('healthybowl.weather.map.toast.locationUnsupported.title', 'Location unavailable'),\n description: t(\n 'healthybowl.weather.map.toast.locationUnsupported.description',\n 'This browser does not support device location.'\n ),\n variant: 'warning',\n });\n return;\n }\n\n setLocating(true);\n navigator.geolocation.getCurrentPosition(\n (position) => {\n const latlng: L.LatLngExpression = [position.coords.latitude, position.coords.longitude];\n clearUserLocation();\n userAccuracyCircleRef.current = L.circle(latlng, {\n radius: Math.max(10, position.coords.accuracy || 0),\n color: '#2563eb',\n fillColor: '#3b82f6',\n fillOpacity: 0.12,\n opacity: 0.45,\n weight: 1,\n }).addTo(map);\n userLocationMarkerRef.current = L.circleMarker(latlng, {\n radius: 7,\n color: '#ffffff',\n weight: 2,\n fillColor: '#2563eb',\n fillOpacity: 1,\n }).addTo(map);\n map.flyTo(latlng, Math.max(map.getZoom(), USER_LOCATION_ZOOM), { duration: 0.75 });\n setLocating(false);\n },\n (error) => {\n const blocked = error.code === error.PERMISSION_DENIED;\n toast({\n title: blocked\n ? t('healthybowl.weather.map.toast.locationBlocked.title', 'Location blocked')\n : t('healthybowl.weather.map.toast.locationFailed.title', 'Could not get location'),\n description: blocked\n ? t(\n 'healthybowl.weather.map.toast.locationBlocked.description',\n 'Allow location access in the browser, then try again.'\n )\n : t(\n 'healthybowl.weather.map.toast.locationFailed.description',\n 'Make sure GPS is enabled and the page is open over HTTPS.'\n ),\n variant: 'warning',\n });\n setLocating(false);\n },\n { enableHighAccuracy: true, timeout: 12000, maximumAge: 60000 }\n );\n }, [clearUserLocation, t, toast]);\n\n const handleSearchPlace = useCallback(\n async (event: FormEvent<HTMLFormElement>) => {\n event.preventDefault();\n const map = mapRef.current;\n const place = searchQuery.trim();\n if (!place) {\n toast({\n title: t('healthybowl.weather.map.toast.searchRequired.title', 'Place required'),\n description: t(\n 'healthybowl.weather.map.toast.searchRequired.description',\n 'Enter a city, village, district, or region to view it on the map.'\n ),\n variant: 'warning',\n });\n return;\n }\n if (!map) return;\n\n setSearching(true);\n try {\n const hit = await geocodePlace(place);\n if (!hit) {\n toast({\n title: t('healthybowl.weather.map.toast.searchNotFound.title', 'Place not found'),\n description: t(\n 'healthybowl.weather.map.toast.searchNotFound.description',\n 'Try a more specific location name, such as city and state.'\n ),\n variant: 'warning',\n });\n return;\n }\n\n const label = [hit.name, hit.admin1, hit.country].filter(Boolean).join(', ') || place;\n const latlng: L.LatLngExpression = [hit.latitude, hit.longitude];\n removeSearchedPlaceMarker();\n const popupEl = document.createElement('span');\n popupEl.textContent = label;\n searchedPlaceMarkerRef.current = L.circleMarker(latlng, {\n radius: 8,\n color: '#ffffff',\n weight: 2,\n fillColor: '#0ea5e9',\n fillOpacity: 1,\n })\n .addTo(map)\n .bindPopup(popupEl)\n .openPopup();\n map.flyTo(latlng, Math.max(map.getZoom(), SEARCH_LOCATION_ZOOM), { duration: 0.75 });\n setSearchedPlace(label);\n } catch (err) {\n toast({\n title: t('healthybowl.weather.map.toast.searchFailed.title', 'Search failed'),\n description: err instanceof Error ? err.message : String(err),\n variant: 'error',\n });\n } finally {\n setSearching(false);\n }\n },\n [removeSearchedPlaceMarker, searchQuery, t, toast]\n );\n\n useEffect(() => {\n const el = containerRef.current;\n if (!el) return undefined;\n ensureLeafletCss();\n const controller = new AbortController();\n let map: L.Map | undefined;\n let cancelled = false;\n setStatus('loading');\n setHasFarmCenter(false);\n setRadarUpdatedAt(null);\n setSearchedPlace(null);\n farmCenterRef.current = null;\n\n void (async () => {\n const backendCenter = centerLat !== null && centerLng !== null ? { lat: centerLat, lng: centerLng } : null;\n const hit = backendCenter ? null : await geocodePlace(location, controller.signal);\n const located: [number, number] | null = backendCenter\n ? [backendCenter.lat, backendCenter.lng]\n : hit\n ? [hit.latitude, hit.longitude]\n : null;\n if (cancelled || !containerRef.current) return;\n const mapCenter: L.LatLngExpression = located ?? [20, 0];\n // z7 keeps the RainViewer radar at its native resolution (it has no tiles past z7)\n // while still framing the farm and its surrounding weather system.\n const zoom = located ? FARM_WEATHER_ZOOM : 2;\n farmCenterRef.current = located ? L.latLng(located[0], located[1]) : null;\n setHasFarmCenter(Boolean(located));\n\n map = L.map(el, { center: mapCenter, zoom, scrollWheelZoom: true });\n mapRef.current = map;\n const streetsLayer = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {\n attribution: '© OpenStreetMap contributors',\n maxZoom: 18,\n });\n const terrainLayer = L.tileLayer('https://{s}.tile.opentopomap.org/{z}/{x}/{y}.png', {\n attribution: '© OpenTopoMap (CC-BY-SA) · © OpenStreetMap contributors',\n maxZoom: 17,\n });\n streetsLayer.addTo(map);\n const layerControl = L.control\n .layers(\n {\n [streetsLayerLabel]: streetsLayer,\n [terrainLayerLabel]: terrainLayer,\n },\n undefined,\n { collapsed: false }\n )\n .addTo(map);\n L.control.scale({ imperial: false }).addTo(map);\n\n if (located) {\n const icon = L.divIcon({\n className: 'hb-weather-marker',\n html:\n '<div style=\"width:16px;height:16px;border-radius:50% 50% 50% 0;transform:rotate(-45deg);' +\n 'background:var(--color-action-primary-bg, #16a34a);border:2px solid #fff;box-shadow:0 1px 4px rgba(0,0,0,.4)\"></div>',\n iconSize: [16, 16],\n iconAnchor: [8, 16],\n });\n // bindPopup treats a string as HTML; pass a text node so the place name\n // can never be interpreted as markup (defense-in-depth against a tainted value).\n const popupEl = document.createElement('span');\n popupEl.textContent = location || 'Your farm';\n L.marker(mapCenter, { icon }).addTo(map).bindPopup(popupEl);\n }\n\n // Live precipitation radar overlay (RainViewer — free, keyless).\n try {\n const res = await fetch('https://api.rainviewer.com/public/weather-maps.json', { signal: controller.signal });\n const data = (await res.json()) as {\n host?: string;\n radar?: { past?: Array<{ path?: string; time?: number }> };\n };\n const frames = data.radar?.past ?? [];\n const latest = frames[frames.length - 1];\n // The map may have been removed during the await — guard before touching it.\n if (!cancelled && map && data.host && latest?.path) {\n // RainViewer radar only has tiles up to z7; cap maxNativeZoom so Leaflet\n // upscales from z7 instead of requesting the \"Zoom Level Not Supported\" placeholder.\n const radarLayer = L.tileLayer(`${data.host}${latest.path}/256/{z}/{x}/{y}/4/1_1.png`, {\n opacity: 0.55,\n maxZoom: 18,\n maxNativeZoom: 7,\n }).addTo(map);\n layerControl.addOverlay(radarLayer, radarLayerLabel);\n if (typeof latest.time === 'number') setRadarUpdatedAt(new Date(latest.time * 1000));\n }\n } catch {\n /* radar overlay is best-effort */\n }\n\n if (!cancelled) {\n setStatus('ready');\n window.setTimeout(() => map?.invalidateSize(), 80);\n }\n })().catch(() => {\n if (!cancelled) setStatus('error');\n });\n\n return () => {\n cancelled = true;\n controller.abort();\n clearUserLocation();\n removeSearchedPlaceMarker();\n map?.remove();\n mapRef.current = null;\n farmCenterRef.current = null;\n };\n }, [\n centerLat,\n centerLng,\n clearUserLocation,\n location,\n radarLayerLabel,\n removeSearchedPlaceMarker,\n streetsLayerLabel,\n terrainLayerLabel,\n ]);\n\n return (\n <div className=\"relative\">\n <div className=\"mb-3 flex flex-wrap items-center gap-2\">\n <form onSubmit={handleSearchPlace} className=\"flex min-w-[min(100%,22rem)] flex-1 flex-wrap items-center gap-2\">\n <div className=\"relative min-w-[12rem] flex-1\">\n <Search className=\"pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-text-secondary\" />\n <input\n type=\"search\"\n value={searchQuery}\n onChange={(event) => setSearchQuery(event.target.value)}\n disabled={status !== 'ready' || searching}\n placeholder={t('healthybowl.weather.map.search.placeholder', 'Search city or place...')}\n aria-label={t('healthybowl.weather.map.search.label', 'Search map by place')}\n className=\"h-9 w-full rounded-md border border-border-subtle bg-bg-surface py-2 pl-9 pr-3 text-sm text-text-primary placeholder:text-text-secondary focus:outline-none focus:ring-2 focus:ring-[var(--color-focus-ring)] disabled:cursor-not-allowed disabled:opacity-60\"\n />\n </div>\n <Button type=\"submit\" variant=\"outline\" size=\"sm\" disabled={status !== 'ready' || searching}>\n <Search className=\"h-4 w-4\" />{' '}\n {searching\n ? t('healthybowl.weather.map.search.searching', 'Searching...')\n : t('healthybowl.weather.map.search.action', 'Search')}\n </Button>\n {searchedPlace && (\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"sm\"\n onClick={clearSearchedPlace}\n aria-label={t('healthybowl.weather.map.search.clear', 'Clear searched place')}\n title={t('healthybowl.weather.map.search.clear', 'Clear searched place')}\n >\n <X className=\"h-4 w-4\" />\n </Button>\n )}\n </form>\n <Button\n variant=\"outline\"\n size=\"sm\"\n onClick={focusFarm}\n disabled={!hasFarmCenter || status === 'loading'}\n title={t('healthybowl.weather.map.actions.focusFarm.title', 'Focus the weather map on the farm')}\n aria-label={t('healthybowl.weather.map.actions.focusFarm.title', 'Focus the weather map on the farm')}\n >\n <MapPinned className=\"h-4 w-4\" /> {t('healthybowl.weather.map.actions.focusFarm', 'Farm')}\n </Button>\n <Button\n variant=\"outline\"\n size=\"sm\"\n onClick={handleLocateMe}\n disabled={locating || status !== 'ready'}\n title={t('healthybowl.weather.map.actions.locateMe.title', 'Go to my current location')}\n aria-label={t('healthybowl.weather.map.actions.locateMe.title', 'Go to my current location')}\n >\n <LocateFixed className=\"h-4 w-4\" />{' '}\n {locating\n ? t('healthybowl.weather.map.actions.locating', 'Locating...')\n : t('healthybowl.weather.map.actions.locateMe', 'My location')}\n </Button>\n </div>\n <div\n ref={containerRef}\n className=\"h-[60vh] max-h-[460px] w-full overflow-hidden rounded-md border border-border-subtle bg-bg-sunken\"\n />\n {status === 'loading' && (\n <div className=\"pointer-events-none absolute inset-0 flex items-center justify-center rounded-md bg-bg-surface/60 text-sm text-text-secondary\">\n Loading map…\n </div>\n )}\n {status === 'error' && (\n <div className=\"pointer-events-none absolute inset-0 flex items-center justify-center rounded-md bg-bg-surface/80 px-4 text-center text-sm text-text-secondary\">\n Weather map needs an internet connection and couldn’t load.\n </div>\n )}\n {status === 'ready' && !hasFarmCenter && (\n <div className=\"pointer-events-none absolute left-1/2 top-16 z-[400] -translate-x-1/2 rounded-full bg-bg-surface/90 px-3 py-1.5 text-xs text-text-secondary shadow-sm\">\n {t('healthybowl.weather.map.noLocation', 'No farm coordinates available')}\n </div>\n )}\n <p className=\"mt-2 text-xs text-text-secondary\">\n Live precipitation radar via RainViewer · base map © OpenStreetMap\n {location ? ` · centered on ${location}` : ''}\n {searchedPlace ? ` · viewing ${searchedPlace}` : ''}\n {radarUpdatedAt\n ? ` · radar ${radarUpdatedAt.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}`\n : ''}\n </p>\n <ToastContainer toasts={toasts} onDismiss={dismiss} />\n </div>\n );\n};\n"],"mappings":";;;;;;;;;;;mCAgBM,IAAc,oDAEd,IAAkB,uDAClB,IAAoB,GACpB,IAAqB,IACrB,IAAuB,IAEvB,KAAsB,MAC1B,GACE,KACA,OAAO,SAAS,EAAM,IAAI,IAC1B,OAAO,SAAS,EAAM,IAAI,IAC1B,EAAM,OAAO,OACb,EAAM,OAAO,MACb,EAAM,OAAO,QACb,EAAM,OAAO,QACZ,EAAM,QAAQ,KAAK,EAAM,QAAQ;AAStC,SAAS,IAAyB;AAChC,KAAI,SAAS,eAAe,cAAc,CAAE;CAC5C,IAAM,IAAO,SAAS,cAAc,OAAO;AAM3C,CALA,EAAK,KAAK,eACV,EAAK,MAAM,cACX,EAAK,OAAO,GACZ,EAAK,YAAY,GACjB,EAAK,cAAc,aACnB,S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