@burdenoff/microfe-healthybowl 2026.727.2 → 2026.727.3
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.
- package/dist/healthybowl/pages/pest-management/AiPestDetectionPage.js +289 -262
- package/dist/healthybowl/pages/pest-management/AiPestDetectionPage.js.map +1 -1
- package/dist/utils/assistantAttachments.js +38 -37
- package/dist/utils/assistantAttachments.js.map +1 -1
- package/dist/utils/gatewayLimits.js +6 -0
- package/dist/utils/gatewayLimits.js.map +1 -0
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AiPestDetectionPage.js","names":[],"sources":["../../../../src/healthybowl/pages/pest-management/AiPestDetectionPage.tsx"],"sourcesContent":["import { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport { Camera, Upload, ScanSearch, Sparkles, Leaf, AlertTriangle, Loader2, ClipboardList } from 'lucide-react';\nimport { PageLayout, Modal, ErrorState, ToastContainer, EmptyState } from '../../components';\nimport { Button, Select, SelectTrigger, SelectValue, SelectContent, SelectItem } from '@burdenoff/fe-libs/ui';\nimport { useSaveToFiles } from '@burdenoff/fe-libs/storage';\nimport { useI18n } from '@burdenoff/fe-libs/shared/providers/shell/I18nProvider';\nimport { useHealthyBowl } from '../../context/HealthyBowlContext';\nimport { useHealthyBowlData } from '../../hooks/useHealthyBowlData';\nimport { useToast } from '../../hooks/useToast';\nimport { downscaleImage, type DownscaledImage } from '../../utils/imageDownscale';\nimport {\n usePlantScans,\n resolvePlantScanImageUrl,\n type PlantScan,\n type PlantDiagnosisCandidate,\n} from '../../hooks/usePlantScans';\nimport { formatDate } from '../../utils/helpers';\n\nconst INPUT_CLASS =\n 'w-full rounded-lg border border-border-subtle bg-bg-surface px-3 py-2 text-sm text-text-primary placeholder:text-text-tertiary focus:outline-none focus:ring-2 focus:ring-[var(--color-focus-ring)]';\n\nconst SEVERITY_STYLES: Record<string, string> = {\n LOW: 'bg-status-success-bgSubtle text-status-success-text',\n MEDIUM: 'bg-status-warning-bgSubtle text-status-warning-text',\n MODERATE: 'bg-status-warning-bgSubtle text-status-warning-text',\n HIGH: 'bg-status-error-bg/10 text-status-error-text',\n CRITICAL: 'bg-status-error-bg/10 text-status-error-text',\n NONE: 'bg-bg-sunken text-text-secondary',\n};\n\nfunction severityLabel(sev: string | null | undefined, t: (k: string, d: string) => string): string {\n const up = (sev ?? '').toUpperCase();\n if (up === 'MEDIUM') return t('healthybowl.plantScan.severity.moderate', 'Moderate');\n if (up === 'LOW') return t('healthybowl.plantScan.severity.low', 'Low');\n if (up === 'HIGH') return t('healthybowl.plantScan.severity.high', 'High');\n if (up === 'CRITICAL') return t('healthybowl.plantScan.severity.critical', 'Critical');\n return t('healthybowl.plantScan.severity.none', 'None');\n}\n\nfunction severityClass(sev: string | null | undefined): string {\n return SEVERITY_STYLES[(sev ?? 'NONE').toUpperCase()] ?? SEVERITY_STYLES['NONE'];\n}\n\n/** Thumbnail that lazily resolves an opaque files-svc id to a presigned URL. */\nfunction ScanThumbnail({ fileId, alt }: { fileId?: string | null; alt: string }): React.JSX.Element {\n const { workspaceId } = useHealthyBowl();\n const [url, setUrl] = useState<string | null>(null);\n useEffect(() => {\n let active = true;\n if (fileId && workspaceId) {\n void resolvePlantScanImageUrl(fileId, workspaceId).then((u) => {\n if (active) setUrl(u);\n });\n }\n return () => {\n active = false;\n };\n }, [fileId, workspaceId]);\n\n return (\n <div className=\"h-12 w-12 shrink-0 overflow-hidden rounded-lg bg-bg-sunken\">\n {url ? (\n <img src={url} alt={alt} className=\"h-full w-full object-cover\" loading=\"lazy\" />\n ) : (\n <div className=\"flex h-full w-full items-center justify-center text-text-tertiary\">\n <Leaf size={18} />\n </div>\n )}\n </div>\n );\n}\n\nfunction ConfidenceBar({ value }: { value: number }): React.JSX.Element {\n const pct = Math.max(0, Math.min(100, Math.round(value)));\n return (\n <div className=\"h-2 w-24 overflow-hidden rounded-full bg-bg-sunken\" aria-hidden>\n <div className=\"h-full rounded-full bg-action-primary-bg\" style={{ width: `${pct}%` }} />\n </div>\n );\n}\n\nexport function AiPestDetectionPage(): React.JSX.Element {\n const { t } = useI18n();\n const { fields, crops } = useHealthyBowlData();\n const { data, loading, error, refetch, diagnose, logToPest } = usePlantScans();\n const { save: saveToFiles } = useSaveToFiles();\n const { toasts, toast, dismiss } = useToast();\n\n const fileInputRef = useRef<HTMLInputElement>(null);\n\n const [image, setImage] = useState<DownscaledImage | null>(null);\n const [fieldId, setFieldId] = useState<string>('');\n const [cropId, setCropId] = useState<string>('');\n const [notes, setNotes] = useState<string>('');\n const [analyzing, setAnalyzing] = useState(false);\n const [scan, setScan] = useState<PlantScan | null>(null);\n\n const [logOpen, setLogOpen] = useState(false);\n\n const selectedField = useMemo(() => fields.find((f) => f.id === fieldId), [fields, fieldId]);\n const selectedCrop = useMemo(() => crops.find((c) => c.id === cropId), [crops, cropId]);\n // Crops are scoped to the chosen field when one is picked.\n const cropOptions = useMemo(() => (fieldId ? crops.filter((c) => c.field === fieldId) : crops), [crops, fieldId]);\n\n const onPickFile = useCallback(\n async (file: File | undefined | null) => {\n if (!file) return;\n try {\n const down = await downscaleImage(file);\n setImage(down);\n setScan(null);\n } catch {\n toast({\n title: t('healthybowl.plantScan.readError', 'Could not read that image. Try another photo.'),\n variant: 'error',\n });\n }\n },\n [t, toast]\n );\n\n const handleDiagnose = useCallback(async () => {\n if (!image) {\n toast({ title: t('healthybowl.plantScan.needPhoto', 'Take or upload a plant photo first.'), variant: 'error' });\n return;\n }\n setAnalyzing(true);\n try {\n // Persist the photo to the workspace file library (best-effort — a failure here\n // must not block the diagnosis, which also carries the image inline).\n let photoFileId: string | null = null;\n try {\n const saved = await saveToFiles({\n source: {\n kind: 'blob',\n filename: image.filename,\n mimeType: image.mimeType,\n getBlob: async () => ({ blob: image.blob, filename: image.filename, mimeType: image.mimeType }),\n },\n folderPath: '/HealthyBowl/PestScan',\n });\n photoFileId = saved?.id ?? null;\n } catch {\n photoFileId = null;\n }\n\n const result = await diagnose({\n fieldId: fieldId || null,\n fieldName: selectedField?.name ?? null,\n cropName: selectedCrop?.name ?? null,\n photoFileId,\n imageBase64: image.base64,\n notes: notes.trim() || null,\n });\n setScan(result);\n await refetch();\n toast({\n title: t('healthybowl.plantScan.done', 'Diagnosis ready'),\n description: result.topDiagnosis ?? '',\n variant: 'success',\n });\n } catch (err) {\n toast({\n title: t('healthybowl.plantScan.failed', 'Diagnosis failed'),\n description: err instanceof Error ? err.message : String(err),\n variant: 'error',\n });\n } finally {\n setAnalyzing(false);\n }\n }, [image, saveToFiles, diagnose, fieldId, selectedField, selectedCrop, notes, refetch, toast, t]);\n\n const stats = data?.stats;\n const recentScans = data?.scans ?? [];\n\n return (\n <PageLayout\n title={t('healthybowl.plantScan.title', 'AI Pest & Disease Detection')}\n titleAccent={t('healthybowl.plantScan.titleAccent', 'AI')}\n description={t(\n 'healthybowl.plantScan.subtitle',\n 'Photograph a plant — AI names the likely pest or disease, with organic-safe next steps.'\n )}\n hero\n purpose={t(\n 'healthybowl.plantScan.purpose',\n 'Snap or upload a leaf photo and get an AI second opinion — the most likely pest or disease with a confidence score, ranked alternatives, and organic-safe actions. Log it to Pest Issues in one tap to start tracking it.'\n )}\n actions={\n scan ? (\n <Button onClick={() => setLogOpen(true)} className=\"gap-2\">\n <ClipboardList size={16} /> {t('healthybowl.plantScan.logToIssues', 'Log to Pest Issues')}\n </Button>\n ) : undefined\n }\n >\n <input\n ref={fileInputRef}\n type=\"file\"\n accept=\"image/*\"\n capture=\"environment\"\n className=\"hidden\"\n onChange={(e) => void onPickFile(e.target.files?.[0])}\n />\n\n <div className=\"grid grid-cols-1 gap-6 lg:grid-cols-3\">\n {/* ── Scan a Plant ─────────────────────────────────────────── */}\n <section className=\"rounded-2xl border border-border-subtle bg-bg-surface p-5\">\n <h2 className=\"mb-4 text-lg font-semibold text-text-primary\">\n {t('healthybowl.plantScan.scanCard', 'Scan a Plant')}\n </h2>\n\n <div className=\"mb-4 flex aspect-square w-full items-center justify-center overflow-hidden rounded-xl bg-bg-sunken\">\n {image ? (\n <img\n src={image.dataUrl}\n alt={t('healthybowl.plantScan.previewAlt', 'Plant to diagnose')}\n className=\"h-full w-full object-cover\"\n />\n ) : (\n <div className=\"flex flex-col items-center gap-2 p-6 text-center text-text-tertiary\">\n <ScanSearch size={40} />\n <span className=\"text-sm\">\n {t('healthybowl.plantScan.previewHint', 'Take or upload a photo of the affected leaf')}\n </span>\n </div>\n )}\n </div>\n\n <div className=\"grid grid-cols-2 gap-3\">\n <Button\n variant=\"outline\"\n className=\"gap-2\"\n onClick={() => fileInputRef.current?.click()}\n disabled={analyzing}\n >\n <Camera size={16} /> {t('healthybowl.plantScan.takePhoto', 'Take Photo')}\n </Button>\n <Button\n variant=\"outline\"\n className=\"gap-2\"\n onClick={() => fileInputRef.current?.click()}\n disabled={analyzing}\n >\n <Upload size={16} /> {t('healthybowl.plantScan.upload', 'Upload Image')}\n </Button>\n </div>\n\n <div className=\"mt-4 grid grid-cols-1 gap-3 sm:grid-cols-2\">\n <div>\n <label className=\"mb-1 block text-xs font-medium text-text-secondary\">\n {t('healthybowl.plantScan.field', 'Field')}\n </label>\n <Select\n value={fieldId}\n onValueChange={(v) => {\n setFieldId(v);\n setCropId('');\n }}\n >\n <SelectTrigger className=\"w-full\">\n <SelectValue placeholder={t('healthybowl.plantScan.selectField', 'Select field')} />\n </SelectTrigger>\n <SelectContent>\n {fields.map((f) => (\n <SelectItem key={f.id} value={f.id}>\n {f.name}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n </div>\n <div>\n <label className=\"mb-1 block text-xs font-medium text-text-secondary\">\n {t('healthybowl.plantScan.crop', 'Crop')}\n </label>\n <Select value={cropId} onValueChange={setCropId}>\n <SelectTrigger className=\"w-full\">\n <SelectValue placeholder={t('healthybowl.plantScan.selectCrop', 'Select crop')} />\n </SelectTrigger>\n <SelectContent>\n {cropOptions.map((c) => (\n <SelectItem key={c.id} value={c.id}>\n {c.name}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n </div>\n </div>\n\n <div className=\"mt-3\">\n <label className=\"mb-1 block text-xs font-medium text-text-secondary\">\n {t('healthybowl.plantScan.notes', 'Symptoms (optional)')}\n </label>\n <textarea\n value={notes}\n onChange={(e) => setNotes(e.target.value)}\n rows={2}\n placeholder={t('healthybowl.plantScan.notesPlaceholder', 'e.g. brown spots spreading on lower leaves')}\n className=\"w-full rounded-lg border border-border-subtle bg-bg-surface px-3 py-2 text-sm text-text-primary placeholder:text-text-tertiary focus:outline-none focus:ring-2 focus:ring-[var(--color-focus-ring)]\"\n />\n </div>\n\n <Button onClick={() => void handleDiagnose()} disabled={!image || analyzing} className=\"mt-4 w-full gap-2\">\n {analyzing ? (\n <>\n <Loader2 size={16} className=\"animate-spin\" /> {t('healthybowl.plantScan.analyzing', 'Analyzing…')}\n </>\n ) : (\n <>\n <Sparkles size={16} /> {t('healthybowl.plantScan.diagnose', 'Diagnose with AI')}\n </>\n )}\n </Button>\n </section>\n\n {/* ── AI Diagnosis ─────────────────────────────────────────── */}\n <section className=\"rounded-2xl border border-border-subtle bg-bg-surface p-5\">\n <h2 className=\"mb-4 text-lg font-semibold text-text-primary\">\n {t('healthybowl.plantScan.diagnosisCard', 'AI Diagnosis')}\n </h2>\n {scan ? (\n <DiagnosisPanel scan={scan} t={t} />\n ) : (\n <div className=\"flex h-64 flex-col items-center justify-center gap-2 text-center text-text-tertiary\">\n <Sparkles size={32} />\n <p className=\"text-sm\">\n {t(\n 'healthybowl.plantScan.diagnosisEmpty',\n 'Your AI diagnosis will appear here after you scan a plant.'\n )}\n </p>\n </div>\n )}\n </section>\n\n {/* ── Recent Scans ─────────────────────────────────────────── */}\n <section className=\"space-y-4\">\n <div className=\"rounded-2xl border border-border-subtle bg-bg-surface p-5\">\n <h2 className=\"mb-4 text-lg font-semibold text-text-primary\">\n {t('healthybowl.plantScan.recentScans', 'Recent Scans')}\n </h2>\n {loading ? (\n <div className=\"flex h-32 items-center justify-center text-text-tertiary\">\n <Loader2 size={20} className=\"animate-spin\" />\n </div>\n ) : error ? (\n <ErrorState onRetry={() => void refetch()} />\n ) : recentScans.length === 0 ? (\n <EmptyState\n icon={<ScanSearch size={28} />}\n title={t('healthybowl.plantScan.noScans', 'No scans yet')}\n description={t(\n 'healthybowl.plantScan.noScansHint',\n 'Point your phone at a sick-looking plant and let HealthyBowl AI name the likely pest or disease.'\n )}\n />\n ) : (\n <ul className=\"divide-y divide-border-subtle\">\n {recentScans.slice(0, 8).map((s) => (\n <li key={s.id}>\n <button\n type=\"button\"\n onClick={() => setScan(s)}\n className=\"flex w-full items-center gap-3 py-3 text-start hover:opacity-80\"\n >\n <ScanThumbnail fileId={s.photoFileIds?.[0]} alt={s.topDiagnosis ?? 'scan'} />\n <div className=\"min-w-0 flex-1\">\n <p className=\"truncate text-sm font-medium text-text-primary\">\n {s.cropName || t('healthybowl.plantScan.unknownCrop', 'Unknown crop')}\n {s.topDiagnosis ? ` · ${s.topDiagnosis}` : ''}\n </p>\n <p className=\"text-xs text-text-tertiary\">{formatDate(s.createdAt)}</p>\n </div>\n {s.loggedPestIssueId ? (\n <span className=\"rounded-full bg-status-success-bgSubtle px-2 py-0.5 text-[11px] font-medium text-status-success-text\">\n {t('healthybowl.plantScan.logged', 'Logged')}\n </span>\n ) : null}\n </button>\n </li>\n ))}\n </ul>\n )}\n </div>\n\n {stats ? (\n <div className=\"rounded-2xl border border-border-subtle bg-bg-surface p-5\">\n <p className=\"text-sm text-text-secondary\">\n <span className=\"text-lg font-semibold text-text-primary\">{stats.scansThisSeason}</span>{' '}\n {t('healthybowl.plantScan.statScans', 'scans this season')} ·{' '}\n <span className=\"text-lg font-semibold text-text-primary\">{stats.issuesCaughtEarly}</span>{' '}\n {t('healthybowl.plantScan.statIssues', 'issues caught early')}\n </p>\n {stats.avgConfidence > 0 ? (\n <p className=\"mt-1 text-xs text-text-tertiary\">\n {t('healthybowl.plantScan.statAvg', 'Average confidence')} {Math.round(stats.avgConfidence)}%\n </p>\n ) : null}\n </div>\n ) : null}\n </section>\n </div>\n\n {scan ? (\n <LogToIssueModal\n open={logOpen}\n onClose={() => setLogOpen(false)}\n scan={scan}\n fields={fields}\n defaultFieldId={fieldId}\n t={t}\n onSubmit={async (payload) => {\n try {\n await logToPest(payload);\n await refetch();\n setScan((prev) => (prev ? { ...prev, loggedPestIssueId: 'logged' } : prev));\n setLogOpen(false);\n toast({ title: t('healthybowl.plantScan.loggedToast', 'Logged to Pest Issues'), variant: 'success' });\n } catch (err) {\n toast({\n title: t('healthybowl.plantScan.logFailed', 'Could not log the issue'),\n description: err instanceof Error ? err.message : String(err),\n variant: 'error',\n });\n }\n }}\n />\n ) : null}\n\n <ToastContainer toasts={toasts} onDismiss={dismiss} />\n </PageLayout>\n );\n}\n\n// ── AI Diagnosis panel ─────────────────────────────────────────────────────────\nfunction DiagnosisPanel({ scan, t }: { scan: PlantScan; t: (k: string, d: string) => string }): React.JSX.Element {\n const candidates: PlantDiagnosisCandidate[] = scan.candidates ?? [];\n const top = candidates[0];\n const alternatives = candidates.slice(1);\n const isModel = scan.advisorySource === 'MODEL';\n\n return (\n <div className=\"space-y-4\">\n <div className=\"rounded-xl bg-status-success-bgSubtle p-4\">\n <div className=\"flex items-start justify-between gap-3\">\n <div className=\"min-w-0\">\n <p className=\"text-lg font-bold text-text-primary\">{scan.topDiagnosis ?? top?.name ?? '—'}</p>\n {scan.topScientificName ? (\n <p className=\"text-sm italic text-text-secondary\">{scan.topScientificName}</p>\n ) : null}\n </div>\n {scan.topConfidence != null ? (\n <div className=\"shrink-0 rounded-lg bg-action-primary-bg px-3 py-1.5 text-center text-action-primary-text\">\n <p className=\"text-[10px] uppercase leading-none opacity-80\">\n {t('healthybowl.plantScan.confidence', 'Confidence')}\n </p>\n <p className=\"text-lg font-bold leading-tight\">{Math.round(scan.topConfidence)}%</p>\n </div>\n ) : null}\n </div>\n <span\n className={`mt-3 inline-block rounded-full px-3 py-1 text-xs font-semibold ${severityClass(scan.severity)}`}\n >\n {t('healthybowl.plantScan.severityLabel', 'Severity')}: {severityLabel(scan.severity, t)}\n </span>\n </div>\n\n {alternatives.length > 0 ? (\n <div className=\"space-y-2\">\n <p className=\"text-xs font-medium uppercase tracking-wide text-text-tertiary\">\n {t('healthybowl.plantScan.alternatives', 'Alternative candidates')}\n </p>\n {alternatives.map((c, i) => (\n <div key={`${c.name}-${i}`} className=\"flex items-center gap-3 text-sm\">\n <span className=\"flex h-5 w-5 items-center justify-center rounded-full bg-bg-sunken text-xs text-text-secondary\">\n {i + 1}\n </span>\n <span className=\"flex-1 truncate text-text-primary\">{c.name}</span>\n <ConfidenceBar value={c.confidence} />\n <span className=\"w-10 text-end text-text-secondary\">{Math.round(c.confidence)}%</span>\n </div>\n ))}\n </div>\n ) : null}\n\n <div className=\"rounded-xl border border-border-subtle p-4\">\n <p className=\"mb-2 text-sm font-semibold text-text-primary\">\n {t('healthybowl.plantScan.recommendedAction', 'Recommended Action')}{' '}\n <span className=\"font-normal text-text-tertiary\">\n ({t('healthybowl.plantScan.organicSafe', 'organic-safe')})\n </span>\n </p>\n {scan.recommendedActions?.length ? (\n <ul className=\"space-y-1.5\">\n {scan.recommendedActions.map((a, i) => (\n <li key={i} className=\"flex gap-2 text-sm text-text-secondary\">\n <Leaf size={16} className=\"mt-0.5 shrink-0 text-accent-teal\" />\n <span>{a}</span>\n </li>\n ))}\n </ul>\n ) : (\n <p className=\"text-sm text-text-tertiary\">{scan.advisoryText ?? '—'}</p>\n )}\n <p className=\"mt-3 border-t border-border-subtle pt-2 text-xs text-text-tertiary\">\n {isModel ? (\n <>\n <Sparkles size={12} className=\"mr-1 inline\" />\n {t('healthybowl.plantScan.aiAttribution', 'AI diagnosis')}\n {scan.modelName ? ` · ${scan.modelName}` : ''}\n </>\n ) : (\n <>\n <AlertTriangle size={12} className=\"mr-1 inline\" />\n {t('healthybowl.plantScan.ruleAttribution', 'Rule-based estimate (not AI) — confirm before treating')}\n </>\n )}\n {scan.processingMs ? ` · ${(scan.processingMs / 1000).toFixed(1)}s` : ''}\n </p>\n </div>\n </div>\n );\n}\n\n// ── Log to Pest Issue modal ─────────────────────────────────────────────────────\ninterface LogPayload {\n scanId: string;\n fieldId: string;\n pestName: string;\n type: string;\n cropAffected: string;\n severity: string;\n status: string;\n treatment: string;\n notes: string;\n attachPhoto: boolean;\n}\n\nconst PEST_TYPES = ['DISEASE', 'FUNGUS', 'INSECT', 'WEED'];\nconst PEST_STATUSES = ['ACTIVE', 'MONITORING', 'TREATING', 'RESOLVED'];\nconst SEVERITY_CHOICES = ['LOW', 'MEDIUM', 'HIGH', 'CRITICAL'];\n\nfunction toPestType(scanType: string | null | undefined): string {\n const up = (scanType ?? '').toUpperCase();\n return PEST_TYPES.includes(up) ? up : 'DISEASE';\n}\n\nfunction LogToIssueModal({\n open,\n onClose,\n scan,\n fields,\n defaultFieldId,\n t,\n onSubmit,\n}: {\n open: boolean;\n onClose: () => void;\n scan: PlantScan;\n fields: Array<{ id: string; name: string }>;\n defaultFieldId: string;\n t: (k: string, d: string) => string;\n onSubmit: (payload: LogPayload) => Promise<void>;\n}): React.JSX.Element {\n const [form, setForm] = useState<LogPayload>(() => buildInitial(scan, defaultFieldId));\n const [submitting, setSubmitting] = useState(false);\n\n useEffect(() => {\n if (open) setForm(buildInitial(scan, defaultFieldId));\n }, [open, scan, defaultFieldId]);\n\n const set = <K extends keyof LogPayload>(k: K, v: LogPayload[K]): void => setForm((prev) => ({ ...prev, [k]: v }));\n\n const handleSubmit = async (): Promise<void> => {\n setSubmitting(true);\n try {\n await onSubmit(form);\n } finally {\n setSubmitting(false);\n }\n };\n\n const canSubmit = Boolean(form.fieldId) && Boolean(form.pestName.trim());\n\n return (\n <Modal\n open={open}\n onClose={onClose}\n title={t('healthybowl.plantScan.logModalTitle', 'Log to Pest Issues')}\n size=\"lg\"\n footer={\n <div className=\"flex justify-end gap-2\">\n <Button variant=\"outline\" onClick={onClose}>\n {t('common.cancel', 'Cancel')}\n </Button>\n <Button onClick={() => void handleSubmit()} disabled={!canSubmit || submitting} className=\"gap-2\">\n {submitting ? <Loader2 size={16} className=\"animate-spin\" /> : <ClipboardList size={16} />}\n {t('healthybowl.plantScan.createIssue', 'Create Pest Issue')}\n </Button>\n </div>\n }\n >\n <div className=\"rounded-lg bg-status-success-bgSubtle px-3 py-2 text-sm text-status-success-text\">\n {t('healthybowl.plantScan.prefill', 'Pre-filled from AI scan')} — {scan.topDiagnosis ?? '—'}\n {scan.topConfidence != null\n ? `, ${Math.round(scan.topConfidence)}% ${t('healthybowl.plantScan.confidenceLower', 'confidence')}`\n : ''}\n </div>\n\n <div className=\"mt-4 grid grid-cols-1 gap-4 sm:grid-cols-2\">\n <Field label={t('healthybowl.plantScan.pestDisease', 'Pest / Disease')}>\n <input value={form.pestName} onChange={(e) => set('pestName', e.target.value)} className={INPUT_CLASS} />\n </Field>\n <Field label={t('healthybowl.plantScan.type', 'Type')}>\n <Select value={form.type} onValueChange={(v) => set('type', v)}>\n <SelectTrigger className=\"w-full\">\n <SelectValue />\n </SelectTrigger>\n <SelectContent>\n {PEST_TYPES.map((ty) => (\n <SelectItem key={ty} value={ty}>\n {ty}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n </Field>\n <Field label={t('healthybowl.plantScan.affectedCrop', 'Affected Crop')}>\n <input\n value={form.cropAffected}\n onChange={(e) => set('cropAffected', e.target.value)}\n className={INPUT_CLASS}\n />\n </Field>\n <Field label={t('healthybowl.plantScan.fieldLocation', 'Field / Location')}>\n <Select value={form.fieldId} onValueChange={(v) => set('fieldId', v)}>\n <SelectTrigger className=\"w-full\">\n <SelectValue placeholder={t('healthybowl.plantScan.selectField', 'Select field')} />\n </SelectTrigger>\n <SelectContent>\n {fields.map((f) => (\n <SelectItem key={f.id} value={f.id}>\n {f.name}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n </Field>\n <Field label={t('healthybowl.plantScan.severityLabel', 'Severity')}>\n <Select value={form.severity} onValueChange={(v) => set('severity', v)}>\n <SelectTrigger className=\"w-full\">\n <SelectValue />\n </SelectTrigger>\n <SelectContent>\n {SEVERITY_CHOICES.map((s) => (\n <SelectItem key={s} value={s}>\n {s}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n </Field>\n <Field label={t('healthybowl.plantScan.status', 'Status')}>\n <Select value={form.status} onValueChange={(v) => set('status', v)}>\n <SelectTrigger className=\"w-full\">\n <SelectValue />\n </SelectTrigger>\n <SelectContent>\n {PEST_STATUSES.map((s) => (\n <SelectItem key={s} value={s}>\n {s}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n </Field>\n </div>\n\n <div className=\"mt-4\">\n <Field\n label={\n <>\n {t('healthybowl.plantScan.suggestedTreatment', 'Suggested Treatment')}{' '}\n <span className=\"rounded bg-status-success-bgSubtle px-1.5 py-0.5 text-[11px] text-status-success-text\">\n {t('healthybowl.plantScan.aiSuggested', 'AI-suggested (organic-safe)')}\n </span>\n </>\n }\n >\n <textarea\n value={form.treatment}\n onChange={(e) => set('treatment', e.target.value)}\n rows={2}\n className={INPUT_CLASS}\n />\n </Field>\n </div>\n <div className=\"mt-4\">\n <Field label={t('healthybowl.plantScan.notesField', 'Notes')}>\n <textarea\n value={form.notes}\n onChange={(e) => set('notes', e.target.value)}\n rows={2}\n placeholder={t('healthybowl.plantScan.addObservations', 'Add any observations…')}\n className={INPUT_CLASS}\n />\n </Field>\n </div>\n <label className=\"mt-4 flex items-center gap-2 text-sm text-text-secondary\">\n <input type=\"checkbox\" checked={form.attachPhoto} onChange={(e) => set('attachPhoto', e.target.checked)} />\n {t('healthybowl.plantScan.attachPhoto', 'Attach scan photo to this issue')}\n </label>\n </Modal>\n );\n}\n\nfunction Field({ label, children }: { label: React.ReactNode; children: React.ReactNode }): React.JSX.Element {\n return (\n <div>\n <label className=\"mb-1 flex items-center gap-2 text-xs font-medium text-text-secondary\">{label}</label>\n {children}\n </div>\n );\n}\n\nfunction buildInitial(scan: PlantScan, defaultFieldId: string): LogPayload {\n return {\n scanId: scan.id,\n fieldId: scan.fieldId ?? defaultFieldId ?? '',\n pestName: scan.topScientificName\n ? `${scan.topDiagnosis ?? ''} (${scan.topScientificName})`.trim()\n : (scan.topDiagnosis ?? ''),\n type: toPestType(scan.topType),\n cropAffected: scan.cropName ?? '',\n severity:\n (scan.severity ?? 'MEDIUM').toUpperCase() === 'MODERATE' ? 'MEDIUM' : (scan.severity ?? 'MEDIUM').toUpperCase(),\n status: 'ACTIVE',\n treatment: (scan.recommendedActions ?? []).join('; '),\n notes: '',\n attachPhoto: true,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAkBA,IAAM,IACJ,uMAEI,IAA0C;CAC9C,KAAK;CACL,QAAQ;CACR,UAAU;CACV,MAAM;CACN,UAAU;CACV,MAAM;CACP;AAED,SAAS,EAAc,GAAgC,GAA6C;CAClG,IAAM,KAAM,KAAO,IAAI,aAAa;AAKpC,QAJI,MAAO,WAAiB,EAAE,2CAA2C,WAAW,GAChF,MAAO,QAAc,EAAE,sCAAsC,MAAM,GACnE,MAAO,SAAe,EAAE,uCAAuC,OAAO,GACtE,MAAO,aAAmB,EAAE,2CAA2C,WAAW,GAC/E,EAAE,uCAAuC,OAAO;;AAGzD,SAAS,EAAc,GAAwC;AAC7D,QAAO,GAAiB,KAAO,QAAQ,aAAa,KAAK,EAAgB;;AAI3E,SAAS,GAAc,EAAE,WAAQ,UAAmE;CAClG,IAAM,EAAE,mBAAgB,GAAgB,EAClC,CAAC,GAAK,KAAU,EAAwB,KAAK;AAanD,QAZA,QAAgB;EACd,IAAI,IAAS;AAMb,SALI,KAAU,KACP,EAAyB,GAAQ,EAAY,CAAC,MAAM,MAAM;AAC7D,GAAI,KAAQ,EAAO,EAAE;IACrB,QAES;AACX,OAAS;;IAEV,CAAC,GAAQ,EAAY,CAAC,EAGvB,kBAAC,OAAD;EAAK,WAAU;YACZ,IACC,kBAAC,OAAD;GAAK,KAAK;GAAU;GAAK,WAAU;GAA6B,SAAQ;GAAS,CAAA,GA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M,EAAI,SAAS,EAAE,OAAO,MAAM;MAC7C,MAAM;MACN,aAAa,EAAE,yCAAyC,wBAAwB;MAChF,WAAW;MACX,CAAA;KACI,CAAA;IACJ,CAAA;GACN,kBAAC,SAAD;IAAO,WAAU;cAAjB,CACE,kBAAC,SAAD;KAAO,MAAK;KAAW,SAAS,EAAK;KAAa,WAAW,MAAM,EAAI,eAAe,EAAE,OAAO,QAAQ;KAAI,CAAA,EAC1G,EAAE,qCAAqC,kCAAkC,CACpE;;GACF;;;AAIZ,SAAS,EAAM,EAAE,UAAO,eAAsF;AAC5G,QACE,kBAAC,OAAD,EAAA,UAAA,CACE,kBAAC,SAAD;EAAO,WAAU;YAAwE;EAAc,CAAA,EACtG,EACG,EAAA,CAAA;;AAIV,SAAS,EAAa,GAAiB,GAAoC;AACzE,QAAO;EACL,QAAQ,EAAK;EACb,SAAS,EAAK,WAAW,KAAkB;EAC3C,UAAU,EAAK,oBACX,GAAG,EAAK,gBAAgB,GAAG,IAAI,EAAK,kBAAkB,GAAG,MAAM,GAC9D,EAAK,gBAAgB;EAC1B,MAAM,EAAW,EAAK,QAAQ;EAC9B,cAAc,EAAK,YAAY;EAC/B,WACG,EAAK,YAAY,UAAU,aAAa,KAAK,aAAa,YAAY,EAAK,YAAY,UAAU,aAAa;EACjH,QAAQ;EACR,YAAY,EAAK,sBAAsB,EAAE,EAAE,KAAK,KAAK;EACrD,OAAO;EACP,aAAa;EACd"}
|
|
1
|
+
{"version":3,"file":"AiPestDetectionPage.js","names":[],"sources":["../../../../src/healthybowl/pages/pest-management/AiPestDetectionPage.tsx"],"sourcesContent":["import { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport { Camera, Upload, ScanSearch, Sparkles, Leaf, AlertTriangle, Loader2, ClipboardList } from 'lucide-react';\nimport { PageLayout, Modal, ErrorState, ToastContainer, EmptyState } from '../../components';\nimport { Button, Select, SelectTrigger, SelectValue, SelectContent, SelectItem } from '@burdenoff/fe-libs/ui';\nimport { useSaveToFiles } from '@burdenoff/fe-libs/storage';\nimport { useI18n } from '@burdenoff/fe-libs/shared/providers/shell/I18nProvider';\nimport { useHealthyBowl } from '../../context/HealthyBowlContext';\nimport { useHealthyBowlData } from '../../hooks/useHealthyBowlData';\nimport { useToast } from '../../hooks/useToast';\nimport { downscaleImage, type DownscaledImage } from '../../utils/imageDownscale';\nimport { MAX_INLINE_IMAGE_BASE64_BYTES } from '../../../utils/gatewayLimits';\nimport {\n usePlantScans,\n resolvePlantScanImageUrl,\n type PlantScan,\n type PlantDiagnosisCandidate,\n} from '../../hooks/usePlantScans';\nimport { formatDate } from '../../utils/helpers';\n\n/**\n * Ceiling on what we will accept from the picker.\n *\n * `downscaleImage` normally makes size a non-issue — a 12 MP photo comes back as\n * a few hundred KB. But when the browser cannot RASTERISE the file it hands back\n * the original bytes untouched (HEIC from an iPhone is the real case: neither\n * Chrome nor Firefox decodes it), and this screen sits behind\n * `accept=\"image/*\" capture=\"environment\"` — the camera. Without this check a\n * 25 MB HEIC was base64-encoded and pinned in React state, backing a preview the\n * browser cannot even render.\n */\nconst MAX_SOURCE_BYTES = 10 * 1024 * 1024;\n\n/**\n * The diagnosis mutation carries the photo INLINE, so it is sized against the\n * gateway's body cap rather than against the upload. The stored copy stays at\n * the primary 1280px encode — the farmer's file library should not be degraded\n * to the transport's budget — while `inline` produces a second, smaller encode\n * from the SAME decode for the wire.\n */\nconst INLINE_ENCODE = { maxDim: 768, quality: 0.6 } as const;\n\n/** Bare base64 out of a `data:<mime>;base64,<payload>` URL. */\nfunction base64FromDataUrl(dataUrl: string): string {\n const comma = dataUrl.indexOf(',');\n return comma >= 0 ? dataUrl.slice(comma + 1) : dataUrl;\n}\n\n/**\n * The payload the mutation should carry: the transport encode when we have one,\n * otherwise the primary. Returns '' when neither is usable.\n */\nexport function selectInlineBase64(image: DownscaledImage): string {\n return image.inlineDataUrl ? base64FromDataUrl(image.inlineDataUrl) : image.base64;\n}\n\nconst INPUT_CLASS =\n 'w-full rounded-lg border border-border-subtle bg-bg-surface px-3 py-2 text-sm text-text-primary placeholder:text-text-tertiary focus:outline-none focus:ring-2 focus:ring-[var(--color-focus-ring)]';\n\nconst SEVERITY_STYLES: Record<string, string> = {\n LOW: 'bg-status-success-bgSubtle text-status-success-text',\n MEDIUM: 'bg-status-warning-bgSubtle text-status-warning-text',\n MODERATE: 'bg-status-warning-bgSubtle text-status-warning-text',\n HIGH: 'bg-status-error-bg/10 text-status-error-text',\n CRITICAL: 'bg-status-error-bg/10 text-status-error-text',\n NONE: 'bg-bg-sunken text-text-secondary',\n};\n\nfunction severityLabel(sev: string | null | undefined, t: (k: string, d: string) => string): string {\n const up = (sev ?? '').toUpperCase();\n if (up === 'MEDIUM') return t('healthybowl.plantScan.severity.moderate', 'Moderate');\n if (up === 'LOW') return t('healthybowl.plantScan.severity.low', 'Low');\n if (up === 'HIGH') return t('healthybowl.plantScan.severity.high', 'High');\n if (up === 'CRITICAL') return t('healthybowl.plantScan.severity.critical', 'Critical');\n return t('healthybowl.plantScan.severity.none', 'None');\n}\n\nfunction severityClass(sev: string | null | undefined): string {\n return SEVERITY_STYLES[(sev ?? 'NONE').toUpperCase()] ?? SEVERITY_STYLES['NONE'];\n}\n\n/** Thumbnail that lazily resolves an opaque files-svc id to a presigned URL. */\nfunction ScanThumbnail({ fileId, alt }: { fileId?: string | null; alt: string }): React.JSX.Element {\n const { workspaceId } = useHealthyBowl();\n const [url, setUrl] = useState<string | null>(null);\n useEffect(() => {\n let active = true;\n if (fileId && workspaceId) {\n void resolvePlantScanImageUrl(fileId, workspaceId).then((u) => {\n if (active) setUrl(u);\n });\n }\n return () => {\n active = false;\n };\n }, [fileId, workspaceId]);\n\n return (\n <div className=\"h-12 w-12 shrink-0 overflow-hidden rounded-lg bg-bg-sunken\">\n {url ? (\n <img src={url} alt={alt} className=\"h-full w-full object-cover\" loading=\"lazy\" />\n ) : (\n <div className=\"flex h-full w-full items-center justify-center text-text-tertiary\">\n <Leaf size={18} />\n </div>\n )}\n </div>\n );\n}\n\nfunction ConfidenceBar({ value }: { value: number }): React.JSX.Element {\n const pct = Math.max(0, Math.min(100, Math.round(value)));\n return (\n <div className=\"h-2 w-24 overflow-hidden rounded-full bg-bg-sunken\" aria-hidden>\n <div className=\"h-full rounded-full bg-action-primary-bg\" style={{ width: `${pct}%` }} />\n </div>\n );\n}\n\nexport function AiPestDetectionPage(): React.JSX.Element {\n const { t } = useI18n();\n const { fields, crops } = useHealthyBowlData();\n const { data, loading, error, refetch, diagnose, logToPest } = usePlantScans();\n const { save: saveToFiles } = useSaveToFiles();\n const { toasts, toast, dismiss } = useToast();\n\n const fileInputRef = useRef<HTMLInputElement>(null);\n\n const [image, setImage] = useState<DownscaledImage | null>(null);\n const [fieldId, setFieldId] = useState<string>('');\n const [cropId, setCropId] = useState<string>('');\n const [notes, setNotes] = useState<string>('');\n const [analyzing, setAnalyzing] = useState(false);\n const [scan, setScan] = useState<PlantScan | null>(null);\n\n const [logOpen, setLogOpen] = useState(false);\n\n const selectedField = useMemo(() => fields.find((f) => f.id === fieldId), [fields, fieldId]);\n const selectedCrop = useMemo(() => crops.find((c) => c.id === cropId), [crops, cropId]);\n // Crops are scoped to the chosen field when one is picked.\n const cropOptions = useMemo(() => (fieldId ? crops.filter((c) => c.field === fieldId) : crops), [crops, fieldId]);\n\n const onPickFile = useCallback(\n async (file: File | undefined | null) => {\n if (!file) return;\n try {\n const down = await downscaleImage(file, { inline: INLINE_ENCODE });\n\n // `downscaled: false` means the browser could not rasterise it, so\n // nothing was resized and `blob` is still the original file. Re-apply\n // the ceiling the picker's `accept=\"image/*\"` waived on the promise of\n // a downscale that did not happen.\n if (!down.downscaled && down.blob.size > MAX_SOURCE_BYTES) {\n toast({\n title: t(\n 'healthybowl.plantScan.tooLarge',\n 'That photo is too large to analyse. Try a JPEG or PNG, or a smaller photo.'\n ),\n variant: 'error',\n });\n return;\n }\n\n // Everything after this point assumes the image can actually reach the\n // server; say so here rather than letting the gateway answer 413 with a\n // message that mentions nothing about size.\n if (selectInlineBase64(down).length > MAX_INLINE_IMAGE_BASE64_BYTES) {\n toast({\n title: t(\n 'healthybowl.plantScan.tooLargeToSend',\n 'That photo is too detailed to send for analysis. Try a smaller photo.'\n ),\n variant: 'error',\n });\n return;\n }\n\n setImage(down);\n setScan(null);\n } catch {\n toast({\n title: t('healthybowl.plantScan.readError', 'Could not read that image. Try another photo.'),\n variant: 'error',\n });\n }\n },\n [t, toast]\n );\n\n const handleDiagnose = useCallback(async () => {\n if (!image) {\n toast({ title: t('healthybowl.plantScan.needPhoto', 'Take or upload a plant photo first.'), variant: 'error' });\n return;\n }\n setAnalyzing(true);\n try {\n // Persist the photo to the workspace file library (best-effort — a failure here\n // must not block the diagnosis, which also carries the image inline).\n let photoFileId: string | null = null;\n try {\n const saved = await saveToFiles({\n source: {\n kind: 'blob',\n filename: image.filename,\n mimeType: image.mimeType,\n getBlob: async () => ({ blob: image.blob, filename: image.filename, mimeType: image.mimeType }),\n },\n folderPath: '/HealthyBowl/PestScan',\n });\n photoFileId = saved?.id ?? null;\n } catch {\n photoFileId = null;\n }\n\n const result = await diagnose({\n fieldId: fieldId || null,\n fieldName: selectedField?.name ?? null,\n cropName: selectedCrop?.name ?? null,\n photoFileId,\n // The transport encode (768px/q0.6, ~92 KB of base64) — NOT the 1280px\n // `base64`, which measures ~360 KB and is 1.37x the gateway's cap.\n imageBase64: selectInlineBase64(image),\n notes: notes.trim() || null,\n });\n setScan(result);\n await refetch();\n toast({\n title: t('healthybowl.plantScan.done', 'Diagnosis ready'),\n description: result.topDiagnosis ?? '',\n variant: 'success',\n });\n } catch (err) {\n toast({\n title: t('healthybowl.plantScan.failed', 'Diagnosis failed'),\n description: err instanceof Error ? err.message : String(err),\n variant: 'error',\n });\n } finally {\n setAnalyzing(false);\n }\n }, [image, saveToFiles, diagnose, fieldId, selectedField, selectedCrop, notes, refetch, toast, t]);\n\n const stats = data?.stats;\n const recentScans = data?.scans ?? [];\n\n return (\n <PageLayout\n title={t('healthybowl.plantScan.title', 'AI Pest & Disease Detection')}\n titleAccent={t('healthybowl.plantScan.titleAccent', 'AI')}\n description={t(\n 'healthybowl.plantScan.subtitle',\n 'Photograph a plant — AI names the likely pest or disease, with organic-safe next steps.'\n )}\n hero\n purpose={t(\n 'healthybowl.plantScan.purpose',\n 'Snap or upload a leaf photo and get an AI second opinion — the most likely pest or disease with a confidence score, ranked alternatives, and organic-safe actions. Log it to Pest Issues in one tap to start tracking it.'\n )}\n actions={\n scan ? (\n <Button onClick={() => setLogOpen(true)} className=\"gap-2\">\n <ClipboardList size={16} /> {t('healthybowl.plantScan.logToIssues', 'Log to Pest Issues')}\n </Button>\n ) : undefined\n }\n >\n <input\n ref={fileInputRef}\n type=\"file\"\n accept=\"image/*\"\n capture=\"environment\"\n className=\"hidden\"\n onChange={(e) => void onPickFile(e.target.files?.[0])}\n />\n\n <div className=\"grid grid-cols-1 gap-6 lg:grid-cols-3\">\n {/* ── Scan a Plant ─────────────────────────────────────────── */}\n <section className=\"rounded-2xl border border-border-subtle bg-bg-surface p-5\">\n <h2 className=\"mb-4 text-lg font-semibold text-text-primary\">\n {t('healthybowl.plantScan.scanCard', 'Scan a Plant')}\n </h2>\n\n <div className=\"mb-4 flex aspect-square w-full items-center justify-center overflow-hidden rounded-xl bg-bg-sunken\">\n {image ? (\n <img\n src={image.dataUrl}\n alt={t('healthybowl.plantScan.previewAlt', 'Plant to diagnose')}\n className=\"h-full w-full object-cover\"\n />\n ) : (\n <div className=\"flex flex-col items-center gap-2 p-6 text-center text-text-tertiary\">\n <ScanSearch size={40} />\n <span className=\"text-sm\">\n {t('healthybowl.plantScan.previewHint', 'Take or upload a photo of the affected leaf')}\n </span>\n </div>\n )}\n </div>\n\n <div className=\"grid grid-cols-2 gap-3\">\n <Button\n variant=\"outline\"\n className=\"gap-2\"\n onClick={() => fileInputRef.current?.click()}\n disabled={analyzing}\n >\n <Camera size={16} /> {t('healthybowl.plantScan.takePhoto', 'Take Photo')}\n </Button>\n <Button\n variant=\"outline\"\n className=\"gap-2\"\n onClick={() => fileInputRef.current?.click()}\n disabled={analyzing}\n >\n <Upload size={16} /> {t('healthybowl.plantScan.upload', 'Upload Image')}\n </Button>\n </div>\n\n <div className=\"mt-4 grid grid-cols-1 gap-3 sm:grid-cols-2\">\n <div>\n <label className=\"mb-1 block text-xs font-medium text-text-secondary\">\n {t('healthybowl.plantScan.field', 'Field')}\n </label>\n <Select\n value={fieldId}\n onValueChange={(v) => {\n setFieldId(v);\n setCropId('');\n }}\n >\n <SelectTrigger className=\"w-full\">\n <SelectValue placeholder={t('healthybowl.plantScan.selectField', 'Select field')} />\n </SelectTrigger>\n <SelectContent>\n {fields.map((f) => (\n <SelectItem key={f.id} value={f.id}>\n {f.name}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n </div>\n <div>\n <label className=\"mb-1 block text-xs font-medium text-text-secondary\">\n {t('healthybowl.plantScan.crop', 'Crop')}\n </label>\n <Select value={cropId} onValueChange={setCropId}>\n <SelectTrigger className=\"w-full\">\n <SelectValue placeholder={t('healthybowl.plantScan.selectCrop', 'Select crop')} />\n </SelectTrigger>\n <SelectContent>\n {cropOptions.map((c) => (\n <SelectItem key={c.id} value={c.id}>\n {c.name}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n </div>\n </div>\n\n <div className=\"mt-3\">\n <label className=\"mb-1 block text-xs font-medium text-text-secondary\">\n {t('healthybowl.plantScan.notes', 'Symptoms (optional)')}\n </label>\n <textarea\n value={notes}\n onChange={(e) => setNotes(e.target.value)}\n rows={2}\n placeholder={t('healthybowl.plantScan.notesPlaceholder', 'e.g. brown spots spreading on lower leaves')}\n className=\"w-full rounded-lg border border-border-subtle bg-bg-surface px-3 py-2 text-sm text-text-primary placeholder:text-text-tertiary focus:outline-none focus:ring-2 focus:ring-[var(--color-focus-ring)]\"\n />\n </div>\n\n <Button onClick={() => void handleDiagnose()} disabled={!image || analyzing} className=\"mt-4 w-full gap-2\">\n {analyzing ? (\n <>\n <Loader2 size={16} className=\"animate-spin\" /> {t('healthybowl.plantScan.analyzing', 'Analyzing…')}\n </>\n ) : (\n <>\n <Sparkles size={16} /> {t('healthybowl.plantScan.diagnose', 'Diagnose with AI')}\n </>\n )}\n </Button>\n </section>\n\n {/* ── AI Diagnosis ─────────────────────────────────────────── */}\n <section className=\"rounded-2xl border border-border-subtle bg-bg-surface p-5\">\n <h2 className=\"mb-4 text-lg font-semibold text-text-primary\">\n {t('healthybowl.plantScan.diagnosisCard', 'AI Diagnosis')}\n </h2>\n {scan ? (\n <DiagnosisPanel scan={scan} t={t} />\n ) : (\n <div className=\"flex h-64 flex-col items-center justify-center gap-2 text-center text-text-tertiary\">\n <Sparkles size={32} />\n <p className=\"text-sm\">\n {t(\n 'healthybowl.plantScan.diagnosisEmpty',\n 'Your AI diagnosis will appear here after you scan a plant.'\n )}\n </p>\n </div>\n )}\n </section>\n\n {/* ── Recent Scans ─────────────────────────────────────────── */}\n <section className=\"space-y-4\">\n <div className=\"rounded-2xl border border-border-subtle bg-bg-surface p-5\">\n <h2 className=\"mb-4 text-lg font-semibold text-text-primary\">\n {t('healthybowl.plantScan.recentScans', 'Recent Scans')}\n </h2>\n {loading ? (\n <div className=\"flex h-32 items-center justify-center text-text-tertiary\">\n <Loader2 size={20} className=\"animate-spin\" />\n </div>\n ) : error ? (\n <ErrorState onRetry={() => void refetch()} />\n ) : recentScans.length === 0 ? (\n <EmptyState\n icon={<ScanSearch size={28} />}\n title={t('healthybowl.plantScan.noScans', 'No scans yet')}\n description={t(\n 'healthybowl.plantScan.noScansHint',\n 'Point your phone at a sick-looking plant and let HealthyBowl AI name the likely pest or disease.'\n )}\n />\n ) : (\n <ul className=\"divide-y divide-border-subtle\">\n {recentScans.slice(0, 8).map((s) => (\n <li key={s.id}>\n <button\n type=\"button\"\n onClick={() => setScan(s)}\n className=\"flex w-full items-center gap-3 py-3 text-start hover:opacity-80\"\n >\n <ScanThumbnail fileId={s.photoFileIds?.[0]} alt={s.topDiagnosis ?? 'scan'} />\n <div className=\"min-w-0 flex-1\">\n <p className=\"truncate text-sm font-medium text-text-primary\">\n {s.cropName || t('healthybowl.plantScan.unknownCrop', 'Unknown crop')}\n {s.topDiagnosis ? ` · ${s.topDiagnosis}` : ''}\n </p>\n <p className=\"text-xs text-text-tertiary\">{formatDate(s.createdAt)}</p>\n </div>\n {s.loggedPestIssueId ? (\n <span className=\"rounded-full bg-status-success-bgSubtle px-2 py-0.5 text-[11px] font-medium text-status-success-text\">\n {t('healthybowl.plantScan.logged', 'Logged')}\n </span>\n ) : null}\n </button>\n </li>\n ))}\n </ul>\n )}\n </div>\n\n {stats ? (\n <div className=\"rounded-2xl border border-border-subtle bg-bg-surface p-5\">\n <p className=\"text-sm text-text-secondary\">\n <span className=\"text-lg font-semibold text-text-primary\">{stats.scansThisSeason}</span>{' '}\n {t('healthybowl.plantScan.statScans', 'scans this season')} ·{' '}\n <span className=\"text-lg font-semibold text-text-primary\">{stats.issuesCaughtEarly}</span>{' '}\n {t('healthybowl.plantScan.statIssues', 'issues caught early')}\n </p>\n {stats.avgConfidence > 0 ? (\n <p className=\"mt-1 text-xs text-text-tertiary\">\n {t('healthybowl.plantScan.statAvg', 'Average confidence')} {Math.round(stats.avgConfidence)}%\n </p>\n ) : null}\n </div>\n ) : null}\n </section>\n </div>\n\n {scan ? (\n <LogToIssueModal\n open={logOpen}\n onClose={() => setLogOpen(false)}\n scan={scan}\n fields={fields}\n defaultFieldId={fieldId}\n t={t}\n onSubmit={async (payload) => {\n try {\n await logToPest(payload);\n await refetch();\n setScan((prev) => (prev ? { ...prev, loggedPestIssueId: 'logged' } : prev));\n setLogOpen(false);\n toast({ title: t('healthybowl.plantScan.loggedToast', 'Logged to Pest Issues'), variant: 'success' });\n } catch (err) {\n toast({\n title: t('healthybowl.plantScan.logFailed', 'Could not log the issue'),\n description: err instanceof Error ? err.message : String(err),\n variant: 'error',\n });\n }\n }}\n />\n ) : null}\n\n <ToastContainer toasts={toasts} onDismiss={dismiss} />\n </PageLayout>\n );\n}\n\n// ── AI Diagnosis panel ─────────────────────────────────────────────────────────\nfunction DiagnosisPanel({ scan, t }: { scan: PlantScan; t: (k: string, d: string) => string }): React.JSX.Element {\n const candidates: PlantDiagnosisCandidate[] = scan.candidates ?? [];\n const top = candidates[0];\n const alternatives = candidates.slice(1);\n const isModel = scan.advisorySource === 'MODEL';\n\n return (\n <div className=\"space-y-4\">\n <div className=\"rounded-xl bg-status-success-bgSubtle p-4\">\n <div className=\"flex items-start justify-between gap-3\">\n <div className=\"min-w-0\">\n <p className=\"text-lg font-bold text-text-primary\">{scan.topDiagnosis ?? top?.name ?? '—'}</p>\n {scan.topScientificName ? (\n <p className=\"text-sm italic text-text-secondary\">{scan.topScientificName}</p>\n ) : null}\n </div>\n {scan.topConfidence != null ? (\n <div className=\"shrink-0 rounded-lg bg-action-primary-bg px-3 py-1.5 text-center text-action-primary-text\">\n <p className=\"text-[10px] uppercase leading-none opacity-80\">\n {t('healthybowl.plantScan.confidence', 'Confidence')}\n </p>\n <p className=\"text-lg font-bold leading-tight\">{Math.round(scan.topConfidence)}%</p>\n </div>\n ) : null}\n </div>\n <span\n className={`mt-3 inline-block rounded-full px-3 py-1 text-xs font-semibold ${severityClass(scan.severity)}`}\n >\n {t('healthybowl.plantScan.severityLabel', 'Severity')}: {severityLabel(scan.severity, t)}\n </span>\n </div>\n\n {alternatives.length > 0 ? (\n <div className=\"space-y-2\">\n <p className=\"text-xs font-medium uppercase tracking-wide text-text-tertiary\">\n {t('healthybowl.plantScan.alternatives', 'Alternative candidates')}\n </p>\n {alternatives.map((c, i) => (\n <div key={`${c.name}-${i}`} className=\"flex items-center gap-3 text-sm\">\n <span className=\"flex h-5 w-5 items-center justify-center rounded-full bg-bg-sunken text-xs text-text-secondary\">\n {i + 1}\n </span>\n <span className=\"flex-1 truncate text-text-primary\">{c.name}</span>\n <ConfidenceBar value={c.confidence} />\n <span className=\"w-10 text-end text-text-secondary\">{Math.round(c.confidence)}%</span>\n </div>\n ))}\n </div>\n ) : null}\n\n <div className=\"rounded-xl border border-border-subtle p-4\">\n <p className=\"mb-2 text-sm font-semibold text-text-primary\">\n {t('healthybowl.plantScan.recommendedAction', 'Recommended Action')}{' '}\n <span className=\"font-normal text-text-tertiary\">\n ({t('healthybowl.plantScan.organicSafe', 'organic-safe')})\n </span>\n </p>\n {scan.recommendedActions?.length ? (\n <ul className=\"space-y-1.5\">\n {scan.recommendedActions.map((a, i) => (\n <li key={i} className=\"flex gap-2 text-sm text-text-secondary\">\n <Leaf size={16} className=\"mt-0.5 shrink-0 text-accent-teal\" />\n <span>{a}</span>\n </li>\n ))}\n </ul>\n ) : (\n <p className=\"text-sm text-text-tertiary\">{scan.advisoryText ?? '—'}</p>\n )}\n <p className=\"mt-3 border-t border-border-subtle pt-2 text-xs text-text-tertiary\">\n {isModel ? (\n <>\n <Sparkles size={12} className=\"mr-1 inline\" />\n {t('healthybowl.plantScan.aiAttribution', 'AI diagnosis')}\n {scan.modelName ? ` · ${scan.modelName}` : ''}\n </>\n ) : (\n <>\n <AlertTriangle size={12} className=\"mr-1 inline\" />\n {t('healthybowl.plantScan.ruleAttribution', 'Rule-based estimate (not AI) — confirm before treating')}\n </>\n )}\n {scan.processingMs ? ` · ${(scan.processingMs / 1000).toFixed(1)}s` : ''}\n </p>\n </div>\n </div>\n );\n}\n\n// ── Log to Pest Issue modal ─────────────────────────────────────────────────────\ninterface LogPayload {\n scanId: string;\n fieldId: string;\n pestName: string;\n type: string;\n cropAffected: string;\n severity: string;\n status: string;\n treatment: string;\n notes: string;\n attachPhoto: boolean;\n}\n\nconst PEST_TYPES = ['DISEASE', 'FUNGUS', 'INSECT', 'WEED'];\nconst PEST_STATUSES = ['ACTIVE', 'MONITORING', 'TREATING', 'RESOLVED'];\nconst SEVERITY_CHOICES = ['LOW', 'MEDIUM', 'HIGH', 'CRITICAL'];\n\nfunction toPestType(scanType: string | null | undefined): string {\n const up = (scanType ?? '').toUpperCase();\n return PEST_TYPES.includes(up) ? up : 'DISEASE';\n}\n\nfunction LogToIssueModal({\n open,\n onClose,\n scan,\n fields,\n defaultFieldId,\n t,\n onSubmit,\n}: {\n open: boolean;\n onClose: () => void;\n scan: PlantScan;\n fields: Array<{ id: string; name: string }>;\n defaultFieldId: string;\n t: (k: string, d: string) => string;\n onSubmit: (payload: LogPayload) => Promise<void>;\n}): React.JSX.Element {\n const [form, setForm] = useState<LogPayload>(() => buildInitial(scan, defaultFieldId));\n const [submitting, setSubmitting] = useState(false);\n\n useEffect(() => {\n if (open) setForm(buildInitial(scan, defaultFieldId));\n }, [open, scan, defaultFieldId]);\n\n const set = <K extends keyof LogPayload>(k: K, v: LogPayload[K]): void => setForm((prev) => ({ ...prev, [k]: v }));\n\n const handleSubmit = async (): Promise<void> => {\n setSubmitting(true);\n try {\n await onSubmit(form);\n } finally {\n setSubmitting(false);\n }\n };\n\n const canSubmit = Boolean(form.fieldId) && Boolean(form.pestName.trim());\n\n return (\n <Modal\n open={open}\n onClose={onClose}\n title={t('healthybowl.plantScan.logModalTitle', 'Log to Pest Issues')}\n size=\"lg\"\n footer={\n <div className=\"flex justify-end gap-2\">\n <Button variant=\"outline\" onClick={onClose}>\n {t('common.cancel', 'Cancel')}\n </Button>\n <Button onClick={() => void handleSubmit()} disabled={!canSubmit || submitting} className=\"gap-2\">\n {submitting ? <Loader2 size={16} className=\"animate-spin\" /> : <ClipboardList size={16} />}\n {t('healthybowl.plantScan.createIssue', 'Create Pest Issue')}\n </Button>\n </div>\n }\n >\n <div className=\"rounded-lg bg-status-success-bgSubtle px-3 py-2 text-sm text-status-success-text\">\n {t('healthybowl.plantScan.prefill', 'Pre-filled from AI scan')} — {scan.topDiagnosis ?? '—'}\n {scan.topConfidence != null\n ? `, ${Math.round(scan.topConfidence)}% ${t('healthybowl.plantScan.confidenceLower', 'confidence')}`\n : ''}\n </div>\n\n <div className=\"mt-4 grid grid-cols-1 gap-4 sm:grid-cols-2\">\n <Field label={t('healthybowl.plantScan.pestDisease', 'Pest / Disease')}>\n <input value={form.pestName} onChange={(e) => set('pestName', e.target.value)} className={INPUT_CLASS} />\n </Field>\n <Field label={t('healthybowl.plantScan.type', 'Type')}>\n <Select value={form.type} onValueChange={(v) => set('type', v)}>\n <SelectTrigger className=\"w-full\">\n <SelectValue />\n </SelectTrigger>\n <SelectContent>\n {PEST_TYPES.map((ty) => (\n <SelectItem key={ty} value={ty}>\n {ty}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n </Field>\n <Field label={t('healthybowl.plantScan.affectedCrop', 'Affected Crop')}>\n <input\n value={form.cropAffected}\n onChange={(e) => set('cropAffected', e.target.value)}\n className={INPUT_CLASS}\n />\n </Field>\n <Field label={t('healthybowl.plantScan.fieldLocation', 'Field / Location')}>\n <Select value={form.fieldId} onValueChange={(v) => set('fieldId', v)}>\n <SelectTrigger className=\"w-full\">\n <SelectValue placeholder={t('healthybowl.plantScan.selectField', 'Select field')} />\n </SelectTrigger>\n <SelectContent>\n {fields.map((f) => (\n <SelectItem key={f.id} value={f.id}>\n {f.name}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n </Field>\n <Field label={t('healthybowl.plantScan.severityLabel', 'Severity')}>\n <Select value={form.severity} onValueChange={(v) => set('severity', v)}>\n <SelectTrigger className=\"w-full\">\n <SelectValue />\n </SelectTrigger>\n <SelectContent>\n {SEVERITY_CHOICES.map((s) => (\n <SelectItem key={s} value={s}>\n {s}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n </Field>\n <Field label={t('healthybowl.plantScan.status', 'Status')}>\n <Select value={form.status} onValueChange={(v) => set('status', v)}>\n <SelectTrigger className=\"w-full\">\n <SelectValue />\n </SelectTrigger>\n <SelectContent>\n {PEST_STATUSES.map((s) => (\n <SelectItem key={s} value={s}>\n {s}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n </Field>\n </div>\n\n <div className=\"mt-4\">\n <Field\n label={\n <>\n {t('healthybowl.plantScan.suggestedTreatment', 'Suggested Treatment')}{' '}\n <span className=\"rounded bg-status-success-bgSubtle px-1.5 py-0.5 text-[11px] text-status-success-text\">\n {t('healthybowl.plantScan.aiSuggested', 'AI-suggested (organic-safe)')}\n </span>\n </>\n }\n >\n <textarea\n value={form.treatment}\n onChange={(e) => set('treatment', e.target.value)}\n rows={2}\n className={INPUT_CLASS}\n />\n </Field>\n </div>\n <div className=\"mt-4\">\n <Field label={t('healthybowl.plantScan.notesField', 'Notes')}>\n <textarea\n value={form.notes}\n onChange={(e) => set('notes', e.target.value)}\n rows={2}\n placeholder={t('healthybowl.plantScan.addObservations', 'Add any observations…')}\n className={INPUT_CLASS}\n />\n </Field>\n </div>\n <label className=\"mt-4 flex items-center gap-2 text-sm text-text-secondary\">\n <input type=\"checkbox\" checked={form.attachPhoto} onChange={(e) => set('attachPhoto', e.target.checked)} />\n {t('healthybowl.plantScan.attachPhoto', 'Attach scan photo to this issue')}\n </label>\n </Modal>\n );\n}\n\nfunction Field({ label, children }: { label: React.ReactNode; children: React.ReactNode }): React.JSX.Element {\n return (\n <div>\n <label className=\"mb-1 flex items-center gap-2 text-xs font-medium text-text-secondary\">{label}</label>\n {children}\n </div>\n );\n}\n\nfunction buildInitial(scan: PlantScan, defaultFieldId: string): LogPayload {\n return {\n scanId: scan.id,\n fieldId: scan.fieldId ?? defaultFieldId ?? '',\n pestName: scan.topScientificName\n ? `${scan.topDiagnosis ?? ''} (${scan.topScientificName})`.trim()\n : (scan.topDiagnosis ?? ''),\n type: toPestType(scan.topType),\n cropAffected: scan.cropName ?? '',\n severity:\n (scan.severity ?? 'MEDIUM').toUpperCase() === 'MODERATE' ? 'MEDIUM' : (scan.severity ?? 'MEDIUM').toUpperCase(),\n status: 'ACTIVE',\n treatment: (scan.recommendedActions ?? []).join('; '),\n notes: '',\n attachPhoto: true,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AA8BA,IAAM,KAAmB,KAAK,OAAO,MAS/B,KAAgB;CAAE,QAAQ;CAAK,SAAS;CAAK;AAGnD,SAAS,EAAkB,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;cACb,kBAAC,GAAD;KAAO,OAAO,EAAE,oCAAoC,QAAQ;eAC1D,kBAAC,YAAD;MACE,OAAO,EAAK;MACZ,WAAW,MAAM,EAAI,SAAS,EAAE,OAAO,MAAM;MAC7C,MAAM;MACN,aAAa,EAAE,yCAAyC,wBAAwB;MAChF,WAAW;MACX,CAAA;KACI,CAAA;IACJ,CAAA;GACN,kBAAC,SAAD;IAAO,WAAU;cAAjB,CACE,kBAAC,SAAD;KAAO,MAAK;KAAW,SAAS,EAAK;KAAa,WAAW,MAAM,EAAI,eAAe,EAAE,OAAO,QAAQ;KAAI,CAAA,EAC1G,EAAE,qCAAqC,kCAAkC,CACpE;;GACF;;;AAIZ,SAAS,EAAM,EAAE,UAAO,eAAsF;AAC5G,QACE,kBAAC,OAAD,EAAA,UAAA,CACE,kBAAC,SAAD;EAAO,WAAU;YAAwE;EAAc,CAAA,EACtG,EACG,EAAA,CAAA;;AAIV,SAAS,EAAa,GAAiB,GAAoC;AACzE,QAAO;EACL,QAAQ,EAAK;EACb,SAAS,EAAK,WAAW,KAAkB;EAC3C,UAAU,EAAK,oBACX,GAAG,EAAK,gBAAgB,GAAG,IAAI,EAAK,kBAAkB,GAAG,MAAM,GAC9D,EAAK,gBAAgB;EAC1B,MAAM,EAAW,EAAK,QAAQ;EAC9B,cAAc,EAAK,YAAY;EAC/B,WACG,EAAK,YAAY,UAAU,aAAa,KAAK,aAAa,YAAY,EAAK,YAAY,UAAU,aAAa;EACjH,QAAQ;EACR,YAAY,EAAK,sBAAsB,EAAE,EAAE,KAAK,KAAK;EACrD,OAAO;EACP,aAAa;EACd"}
|
|
@@ -1,9 +1,10 @@
|
|
|
1
|
-
|
|
1
|
+
import { MAX_REQUEST_BODY_BYTES as e } from "./gatewayLimits.js";
|
|
2
|
+
var t = 10 * 1024 * 1024, n = 8e3, r = 2e4, i = class extends Error {
|
|
2
3
|
constructor(e) {
|
|
3
4
|
super(e), this.reason = e, this.name = "AttachmentRejectedError";
|
|
4
5
|
}
|
|
5
6
|
};
|
|
6
|
-
function
|
|
7
|
+
function a(e) {
|
|
7
8
|
return {
|
|
8
9
|
id: e.id,
|
|
9
10
|
filename: e.filename,
|
|
@@ -13,7 +14,7 @@ function i(e) {
|
|
|
13
14
|
fileId: e.fileId
|
|
14
15
|
};
|
|
15
16
|
}
|
|
16
|
-
var
|
|
17
|
+
var o = new Set([
|
|
17
18
|
"txt",
|
|
18
19
|
"md",
|
|
19
20
|
"markdown",
|
|
@@ -37,23 +38,23 @@ var a = new Set([
|
|
|
37
38
|
"toml",
|
|
38
39
|
"conf"
|
|
39
40
|
]);
|
|
40
|
-
function
|
|
41
|
+
function s(e) {
|
|
41
42
|
let t = e.lastIndexOf(".");
|
|
42
43
|
return t >= 0 ? e.slice(t + 1).toLowerCase() : "";
|
|
43
44
|
}
|
|
44
|
-
function
|
|
45
|
-
return e.startsWith("image/") ? "image" : e.startsWith("text/") || e === "application/json" || e === "application/xml" || e === "application/x-yaml" ||
|
|
45
|
+
function c(e, t) {
|
|
46
|
+
return e.startsWith("image/") ? "image" : e.startsWith("text/") || e === "application/json" || e === "application/xml" || e === "application/x-yaml" || o.has(s(t)) ? "text" : "document";
|
|
46
47
|
}
|
|
47
|
-
function
|
|
48
|
+
function l(e) {
|
|
48
49
|
return e < 1024 ? `${e} B` : e < 1024 * 1024 ? `${(e / 1024).toFixed(1)} KB` : `${(e / (1024 * 1024)).toFixed(1)} MB`;
|
|
49
50
|
}
|
|
50
|
-
function
|
|
51
|
+
function u(e, t) {
|
|
51
52
|
return e > 0 || t.some((e) => e.status === "pending" || e.status === "uploading");
|
|
52
53
|
}
|
|
53
|
-
function
|
|
54
|
+
function d(e, t) {
|
|
54
55
|
return t >= 5 ? "too-many" : e.size === 0 ? "empty" : e.size > 10485760 && !e.type.startsWith("image/") ? "too-large" : null;
|
|
55
56
|
}
|
|
56
|
-
function
|
|
57
|
+
function f(e, t) {
|
|
57
58
|
if (e.length <= t) return {
|
|
58
59
|
text: e,
|
|
59
60
|
truncated: !1
|
|
@@ -64,69 +65,69 @@ function d(e, t) {
|
|
|
64
65
|
truncated: !0
|
|
65
66
|
};
|
|
66
67
|
}
|
|
67
|
-
function
|
|
68
|
-
let n = [`[${t + 1}] ${e.filename} — ${e.mimeType}, ${
|
|
69
|
-
return e.downloadUrl && n.push(` URL: ${e.downloadUrl}`), e.kind === "text" && e.textContent ? n.push(e.textTruncated ? ` Contents (first ${e.textContent.length} characters of ${
|
|
68
|
+
function p(e, t) {
|
|
69
|
+
let n = [`[${t + 1}] ${e.filename} — ${e.mimeType}, ${l(e.size)}`];
|
|
70
|
+
return e.downloadUrl && n.push(` URL: ${e.downloadUrl}`), e.kind === "text" && e.textContent ? n.push(e.textTruncated ? ` Contents (first ${e.textContent.length} characters of ${l(e.size)}; truncated):` : " Contents:", " ```", ...e.textContent.split("\n").map((e) => ` ${e}`), " ```") : e.kind === "image" ? n.push(" If this image is attached to the message as an image you can view, answer from what you see in it.", " If you cannot view attached images, say so plainly and ask the user to describe it — never guess.") : e.kind === "text" ? n.push(" Text file — contents omitted because this turn ran out of inline budget, not because they are", " unavailable. Fetch the URL above if you can; otherwise ask the user which part matters so they", " can re-send just that section.") : n.push(" Binary file — contents not inlined. Fetch the URL above if you can; otherwise ask the user", " to paste the relevant section as text."), n.join("\n");
|
|
70
71
|
}
|
|
71
|
-
function
|
|
72
|
+
function m(e) {
|
|
72
73
|
let t = e.filter((e) => e.status === "ready");
|
|
73
74
|
if (t.length === 0) return "";
|
|
74
|
-
let
|
|
75
|
+
let n = r, i = t.map((e) => {
|
|
75
76
|
if (e.kind !== "text" || !e.textContent) return e;
|
|
76
|
-
if (
|
|
77
|
+
if (n <= 0) return {
|
|
77
78
|
...e,
|
|
78
79
|
textContent: void 0,
|
|
79
80
|
textTruncated: !0
|
|
80
81
|
};
|
|
81
|
-
let { text: t, truncated:
|
|
82
|
-
return
|
|
82
|
+
let { text: t, truncated: r } = f(e.textContent, n);
|
|
83
|
+
return n -= t.length, {
|
|
83
84
|
...e,
|
|
84
85
|
textContent: t,
|
|
85
|
-
textTruncated: e.textTruncated ||
|
|
86
|
+
textTruncated: e.textTruncated || r
|
|
86
87
|
};
|
|
87
88
|
});
|
|
88
89
|
return [
|
|
89
90
|
"",
|
|
90
91
|
`--- Attachments (${t.length}) ---`,
|
|
91
92
|
"The user attached the following file(s) to this message.",
|
|
92
|
-
...i.map(
|
|
93
|
+
...i.map(p),
|
|
93
94
|
"--- End attachments ---"
|
|
94
95
|
].join("\n");
|
|
95
96
|
}
|
|
96
|
-
function
|
|
97
|
-
let n =
|
|
97
|
+
function h(e, t) {
|
|
98
|
+
let n = m(t);
|
|
98
99
|
return n ? e ? `${e}\n${n}` : n.trimStart() : e;
|
|
99
100
|
}
|
|
100
|
-
var
|
|
101
|
-
function
|
|
102
|
-
return
|
|
101
|
+
var g = e - 32768, _ = .6, v = typeof TextEncoder == "function" ? new TextEncoder() : null;
|
|
102
|
+
function y(e) {
|
|
103
|
+
return v ? v.encode(e).length : e.length;
|
|
103
104
|
}
|
|
104
|
-
function
|
|
105
|
-
return
|
|
105
|
+
function b(e, t) {
|
|
106
|
+
return y(JSON.stringify({
|
|
106
107
|
prompt: e,
|
|
107
108
|
parts: t ?? []
|
|
108
109
|
}));
|
|
109
110
|
}
|
|
110
|
-
function
|
|
111
|
+
function x(e) {
|
|
111
112
|
return e.filter((e) => e.status === "ready" && e.kind === "image" && !!(e.inlineDataUrl ?? e.previewUrl)).length;
|
|
112
113
|
}
|
|
113
|
-
function
|
|
114
|
+
function S(e) {
|
|
114
115
|
return (e ?? []).filter((e) => e.type === "image" && !!e.data).length;
|
|
115
116
|
}
|
|
116
|
-
function
|
|
117
|
+
function C(e) {
|
|
117
118
|
let t = /^data:([a-z0-9.+/-]+);base64,(.*)$/i.exec(e);
|
|
118
119
|
return t ? {
|
|
119
120
|
mimeType: t[1],
|
|
120
121
|
base64: t[2]
|
|
121
122
|
} : null;
|
|
122
123
|
}
|
|
123
|
-
function
|
|
124
|
+
function w(e, t) {
|
|
124
125
|
let n = t.filter((e) => e.status === "ready");
|
|
125
126
|
if (n.length === 0) return;
|
|
126
127
|
let r = [], i = [], a = 0, o = 0;
|
|
127
128
|
for (let e of n) {
|
|
128
129
|
if (e.kind === "image") {
|
|
129
|
-
let t = e.inlineDataUrl ?? e.previewUrl, n = t ?
|
|
130
|
+
let t = e.inlineDataUrl ?? e.previewUrl, n = t ? C(t) : null;
|
|
130
131
|
if (n !== null && a < 3 && o + n.base64.length <= 15e5 && n) {
|
|
131
132
|
a += 1, o += n.base64.length, i.push(r.length), r.push({
|
|
132
133
|
type: "image",
|
|
@@ -153,10 +154,10 @@ function S(e, t) {
|
|
|
153
154
|
});
|
|
154
155
|
}
|
|
155
156
|
if (r.length !== 0) {
|
|
156
|
-
for (; i.length > 0 &&
|
|
157
|
+
for (; i.length > 0 && b(e, [{
|
|
157
158
|
type: "text",
|
|
158
159
|
text: e
|
|
159
|
-
}, ...r]) >
|
|
160
|
+
}, ...r]) > g;) {
|
|
160
161
|
let e = i.pop();
|
|
161
162
|
if (e === void 0) break;
|
|
162
163
|
let t = r[e];
|
|
@@ -167,16 +168,16 @@ function S(e, t) {
|
|
|
167
168
|
name: t.name
|
|
168
169
|
} : r.splice(e, 1));
|
|
169
170
|
}
|
|
170
|
-
if (r.length !== 0 && !(
|
|
171
|
+
if (r.length !== 0 && !(b(e, [{
|
|
171
172
|
type: "text",
|
|
172
173
|
text: e
|
|
173
|
-
}, ...r]) >
|
|
174
|
+
}, ...r]) > g)) return [{
|
|
174
175
|
type: "text",
|
|
175
176
|
text: e
|
|
176
177
|
}, ...r];
|
|
177
178
|
}
|
|
178
179
|
}
|
|
179
180
|
//#endregion
|
|
180
|
-
export {
|
|
181
|
+
export { i as AttachmentRejectedError, _ as INLINE_IMAGE_QUALITY, t as MAX_FILE_BYTES, n as MAX_INLINE_CHARS_PER_FILE, w as buildPromptParts, h as buildPromptWithAttachments, c as classifyAttachment, x as countInlineImageCandidates, S as countInlinedImageParts, l as formatBytes, u as hasAttachmentWorkInFlight, a as toMessageAttachment, f as truncateForInline, d as validateFile };
|
|
181
182
|
|
|
182
183
|
//# sourceMappingURL=assistantAttachments.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"assistantAttachments.js","names":[],"sources":["../../src/utils/assistantAttachments.ts"],"sourcesContent":["/**\n * Attachment model for the assistant composer (Workstream 3 of the AI Assistant\n * V2 multimodal effort) — pure logic, no React, so it is unit-testable.\n *\n * ## How an attachment reaches the model today\n *\n * The sandbox transport carries exactly one user-authored field per turn:\n * a `prompt` **string** (`POST /sessions/:id/prompt-async`). The in-sandbox\n * agent's message parts are `text | tool` only. So there is no native file or\n * image part to put bytes into, and adding one means changing the out-of-repo\n * `ai-assistant-*` bridge image — that is Workstream 4, and it is not shipped.\n *\n * What this module does instead is the honest L1: every attachment is uploaded\n * to the workspace file library (wspace-files-svc) so it durably exists and has\n * a URL, and a compact, clearly-delimited block describing the attachments is\n * appended to the outgoing prompt. For **text-like** files the actual content is\n * inlined (bounded), which makes them fully usable by the model right now. For\n * images and binaries only the metadata and a presigned URL go across, and the\n * block says plainly that the bytes were not inlined — so the assistant asks\n * rather than hallucinating a description of a photo it cannot see.\n *\n * Whether the sandbox can egress to the presigned URL is **not verified** — the\n * wording therefore makes fetching conditional (\"if you can fetch URLs\") rather\n * than promising it. Vision on the image itself lands with Workstream 4.\n */\n\n/** Hard cap on attachments per message — keeps the prompt block bounded. */\nexport const MAX_ATTACHMENTS = 5;\n\n/** Per-file ceiling before downscaling (images) / rejection (everything else). */\nexport const MAX_FILE_BYTES = 10 * 1024 * 1024;\n\n/** Per-file inline budget for text-like content, in characters. */\nexport const MAX_INLINE_CHARS_PER_FILE = 8_000;\n\n/** Total inline budget across all attachments in one turn. */\nexport const MAX_INLINE_CHARS_TOTAL = 20_000;\n\nexport type AssistantAttachmentKind = 'image' | 'text' | 'document';\n\nexport type AssistantAttachmentStatus = 'pending' | 'uploading' | 'ready' | 'error';\n\nexport type AttachmentRejection = 'too-many' | 'too-large' | 'empty' | 'unreadable' | 'unsupported-image';\n\n/**\n * Thrown while PREPARING a file (after it passed `validateFile`) to reject it\n * with a specific reason rather than the generic 'unreadable'.\n *\n * `validateFile` runs before the bytes have been touched, so it cannot know\n * whether an oversized image will actually survive the downscale — that verdict\n * only exists once the browser has tried to rasterise it.\n */\nexport class AttachmentRejectedError extends Error {\n constructor(readonly reason: AttachmentRejection) {\n super(reason);\n this.name = 'AttachmentRejectedError';\n }\n}\n\nexport interface AssistantAttachment {\n /** Client-side id; stable for the lifetime of the draft + the sent message. */\n id: string;\n filename: string;\n mimeType: string;\n /** Size of the bytes we actually kept (post-downscale for images). */\n size: number;\n kind: AssistantAttachmentKind;\n status: AssistantAttachmentStatus;\n /** Object/data URL for the composer thumbnail. Images only; never persisted. */\n previewUrl?: string;\n /**\n * A smaller `data:` URL of the same image, sized for the request body rather\n * than for the eye. Preferred over `previewUrl` when building the multimodal\n * parts; see `MAX_TURN_BODY_BYTES`. Images only; never persisted.\n */\n inlineDataUrl?: string;\n /** wspace-files-svc id, once the upload lands. */\n fileId?: string;\n /** Short-lived presigned URL, resolved at send time. */\n downloadUrl?: string;\n /** Extracted UTF-8 content for text-like files (already truncated). */\n textContent?: string;\n /** True when `textContent` is a prefix of a longer file. */\n textTruncated?: boolean;\n /** Human-readable failure reason when `status === 'error'`. */\n error?: string;\n}\n\n/**\n * The slice of an attachment that is safe to keep on a sent message.\n *\n * Conversations are persisted to (profile-scoped) localStorage by the assistant\n * store, so the heavy fields — the base64 `previewUrl` and the inlined\n * `textContent` — MUST NOT travel here: five 1280px JPEG data URLs would exhaust\n * the ~5 MB quota on their own and take the whole conversation history down with\n * them. The bubble re-resolves a thumbnail from `fileId` on demand instead, the\n * same way the pest-scan list does.\n */\nexport interface AssistantMessageAttachment {\n id: string;\n filename: string;\n mimeType: string;\n size: number;\n kind: AssistantAttachmentKind;\n fileId?: string;\n}\n\nexport function toMessageAttachment(attachment: AssistantAttachment): AssistantMessageAttachment {\n return {\n id: attachment.id,\n filename: attachment.filename,\n mimeType: attachment.mimeType,\n size: attachment.size,\n kind: attachment.kind,\n fileId: attachment.fileId,\n };\n}\n\n/**\n * Extensions we treat as text even when the browser reports a useless MIME type\n * (`application/octet-stream` is common for `.log`, `.yml`, `.env` on Windows).\n */\nconst TEXT_EXTENSIONS = new Set([\n 'txt',\n 'md',\n 'markdown',\n 'csv',\n 'tsv',\n 'json',\n 'yaml',\n 'yml',\n 'xml',\n 'log',\n 'sql',\n 'html',\n 'css',\n 'js',\n 'ts',\n 'tsx',\n 'jsx',\n 'py',\n 'sh',\n 'ini',\n 'toml',\n 'conf',\n]);\n\nexport function getExtension(filename: string): string {\n const dot = filename.lastIndexOf('.');\n return dot >= 0 ? filename.slice(dot + 1).toLowerCase() : '';\n}\n\nexport function classifyAttachment(mimeType: string, filename: string): AssistantAttachmentKind {\n if (mimeType.startsWith('image/')) return 'image';\n if (\n mimeType.startsWith('text/') ||\n mimeType === 'application/json' ||\n mimeType === 'application/xml' ||\n mimeType === 'application/x-yaml' ||\n TEXT_EXTENSIONS.has(getExtension(filename))\n ) {\n return 'text';\n }\n return 'document';\n}\n\nexport function formatBytes(bytes: number): string {\n if (bytes < 1024) return `${bytes} B`;\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;\n return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;\n}\n\n/**\n * Is there attachment work in flight that must block sending?\n *\n * `preparingCount` counts files the user has ALREADY dropped/picked but whose\n * image-downscale or text-read has not resolved yet. Those files have no id and\n * no row in `attachments`, so a check that looked only at `attachments` reported\n * \"idle\" during the whole preparation window — the composer stayed sendable, the\n * turn went out without the photo, and the photo then attached itself to the\n * user's NEXT message. Both halves must be counted.\n */\nexport function hasAttachmentWorkInFlight(preparingCount: number, attachments: AssistantAttachment[]): boolean {\n return (\n preparingCount > 0 ||\n attachments.some((attachment) => attachment.status === 'pending' || attachment.status === 'uploading')\n );\n}\n\n/**\n * Gate a candidate file. Images over the ceiling are still accepted — the\n * composer downscales them before upload, so a 12 MB phone photo is fine while\n * a 12 MB PDF is not.\n *\n * That exemption is a PROMISE, not a fact: it holds only if the browser can\n * actually rasterise the image. When it cannot (HEIC), `prepareFile` re-applies\n * this ceiling to the original bytes and rejects there instead.\n */\nexport function validateFile(file: File, currentCount: number): AttachmentRejection | null {\n if (currentCount >= MAX_ATTACHMENTS) return 'too-many';\n if (file.size === 0) return 'empty';\n if (file.size > MAX_FILE_BYTES && !file.type.startsWith('image/')) return 'too-large';\n return null;\n}\n\n/**\n * Truncate on a line boundary where possible, so an inlined CSV/JSON prefix ends\n * at a row rather than mid-token (which reads as corrupt data to the model).\n */\nexport function truncateForInline(content: string, limit: number): { text: string; truncated: boolean } {\n if (content.length <= limit) return { text: content, truncated: false };\n const head = content.slice(0, limit);\n const lastNewline = head.lastIndexOf('\\n');\n return { text: lastNewline > limit * 0.5 ? head.slice(0, lastNewline) : head, truncated: true };\n}\n\nfunction describeAttachment(attachment: AssistantAttachment, index: number): string {\n const lines = [`[${index + 1}] ${attachment.filename} — ${attachment.mimeType}, ${formatBytes(attachment.size)}`];\n\n if (attachment.downloadUrl) {\n lines.push(` URL: ${attachment.downloadUrl}`);\n }\n\n if (attachment.kind === 'text' && attachment.textContent) {\n lines.push(\n attachment.textTruncated\n ? ` Contents (first ${attachment.textContent.length} characters of ${formatBytes(attachment.size)}; truncated):`\n : ' Contents:',\n ' ```',\n ...attachment.textContent.split('\\n').map((line) => ` ${line}`),\n ' ```'\n );\n } else if (attachment.kind === 'image') {\n // Deliberately regime-neutral wording. This same block is sent whether or\n // not the bridge understands `parts`, so it must not assert either that the\n // model CAN see the image (it would then invent a description on the old\n // bridge) or that it CANNOT (it would then refuse to look on the new one).\n lines.push(\n ' If this image is attached to the message as an image you can view, answer from what you see in it.',\n ' If you cannot view attached images, say so plainly and ask the user to describe it — never guess.'\n );\n } else if (attachment.kind === 'text') {\n // A text file with no `textContent` did not lose its type — it lost its slot\n // in the shared inline budget. Calling it \"binary\" here had the assistant ask\n // the farmer to paste text it already knew was text.\n lines.push(\n ' Text file — contents omitted because this turn ran out of inline budget, not because they are',\n ' unavailable. Fetch the URL above if you can; otherwise ask the user which part matters so they',\n ' can re-send just that section.'\n );\n } else {\n lines.push(\n ' Binary file — contents not inlined. Fetch the URL above if you can; otherwise ask the user',\n ' to paste the relevant section as text.'\n );\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Render the attachment block appended to the outgoing prompt. Returns '' when\n * there is nothing to say, so callers can concatenate unconditionally.\n *\n * Attachments that failed to upload are omitted: the user already sees the\n * failure in the composer, and a half-described file only confuses the model.\n */\nexport function buildAttachmentPromptBlock(attachments: AssistantAttachment[]): string {\n const usable = attachments.filter((attachment) => attachment.status === 'ready');\n if (usable.length === 0) return '';\n\n // Apply the shared inline budget in order, so the first files keep their\n // content and later ones degrade to metadata-only rather than every file\n // being trimmed to uselessness.\n let remaining = MAX_INLINE_CHARS_TOTAL;\n const budgeted = usable.map((attachment) => {\n if (attachment.kind !== 'text' || !attachment.textContent) return attachment;\n if (remaining <= 0) {\n return { ...attachment, textContent: undefined, textTruncated: true };\n }\n const { text, truncated } = truncateForInline(attachment.textContent, remaining);\n remaining -= text.length;\n return { ...attachment, textContent: text, textTruncated: attachment.textTruncated || truncated };\n });\n\n return [\n '',\n `--- Attachments (${usable.length}) ---`,\n 'The user attached the following file(s) to this message.',\n ...budgeted.map(describeAttachment),\n '--- End attachments ---',\n ].join('\\n');\n}\n\n/**\n * Compose the text actually sent to the agent: the user's words, then the\n * attachment block. The user-facing bubble keeps the raw text (attachments are\n * rendered as chips there), matching how `buildPromptForMode` already separates\n * agent-only preamble from displayed content.\n */\nexport function buildPromptWithAttachments(content: string, attachments: AssistantAttachment[]): string {\n const block = buildAttachmentPromptBlock(attachments);\n if (!block) return content;\n return content ? `${content}\\n${block}` : block.trimStart();\n}\n\n// ── Multimodal parts (Workstream 4, client half) ─────────────────────────────\n\n/**\n * Structural mirror of fe-libs' `AssistantPromptPart`\n * (`@burdenoff/fe-libs/shared/assistant`). Declared locally so this module —\n * and its tests — stay pure and importable without the transport, and so the\n * builder compiles against a fe-libs pin that predates the widening. The\n * assignment at the call site is what proves the two agree.\n */\nexport type AssistantPromptPart =\n | { type: 'text'; text: string }\n | { type: 'image'; mimeType: string; url?: string; data?: string; name?: string }\n | { type: 'file'; mimeType: string; url?: string; data?: string; name?: string };\n\n/**\n * How many images may travel INLINE in one turn.\n *\n * Inline bytes are what make vision work without the sandbox needing egress to\n * our storage. Images beyond the budget still travel, by URL only, and the\n * prompt block still describes them.\n */\nexport const MAX_INLINE_IMAGE_PARTS = 3;\n\n/**\n * Belt-and-braces per-turn ceiling on base64 characters.\n *\n * Kept as a cheap guard against a pathological single image, but it is NO\n * LONGER the operative limit — `MAX_TURN_BODY_BYTES` is. See below for why the\n * previous 1.5M-character budget was a fiction.\n */\nexport const MAX_INLINE_IMAGE_BASE64_CHARS = 1_500_000;\n\n/**\n * The real ceiling: what the gateway will accept as a request body.\n *\n * `wspace-public-gateway` enforces `MAX_REQUEST_BODY_SIZE`, and both the alpha\n * and prod configs set it to **256kb** (`burdenoff-gitops`\n * `apps/config-workspace{,-prod}/wspace-public-gateway-config.yaml`). It is\n * checked against `Content-Length` before authentication and before anything is\n * forwarded, and it answers 413 with a JSON body — which fe-libs' `graphqlFetch`\n * maps to the generic 4xx sentence, discarding the status. So an oversized turn\n * does not degrade: it dies, and the user is told to refresh.\n *\n * The old budget (1.5M base64 characters ≈ 1.43 MB) was ~5.7x that cap, so a\n * single ordinary 1280px photo — 150-400 KB, i.e. 200-530 KB of base64 — was\n * enough to lose the whole turn. Measure the body instead of guessing at it.\n */\nexport const MAX_TURN_BODY_BYTES = 262_144;\n\n/**\n * Headroom left for everything `estimateTurnBodyBytes` does not model: the\n * GraphQL query document, the operation name, the sandbox id / path / method,\n * the context input and the page context.\n *\n * Measured, that overhead is under 1 KB — the ProxySandboxRequest document is\n * ~150 bytes and the page context a few hundred. 32 KB is therefore deliberately\n * ~30x the real figure, because the two ways of being wrong are not\n * symmetrical: reserve too much and one photo travels as a link instead of as\n * pixels; reserve too little and the entire turn is rejected and the farmer's\n * question is lost.\n */\nexport const TURN_BODY_HEADROOM_BYTES = 32_768;\n\n/** What the modelled part of the body must fit inside. */\nexport const MAX_INLINE_TURN_BODY_BYTES = MAX_TURN_BODY_BYTES - TURN_BODY_HEADROOM_BYTES;\n\n/**\n * Encode settings for the copy of an image that travels INSIDE the turn.\n *\n * Separate from the upload encode (1280px / q0.72) on purpose: the file that\n * lands in the farmer's file library should not be degraded to fit a transport\n * limit. At 768px / q0.6 a photo is typically 40-90 KB — 53-120 KB of base64 —\n * so one image fits inside `MAX_INLINE_TURN_BODY_BYTES` with room for the\n * prompt, and often two do. Vision models downsample to roughly this size\n * anyway, so the diagnostic detail that matters survives.\n */\nexport const INLINE_IMAGE_MAX_DIM = 768;\nexport const INLINE_IMAGE_QUALITY = 0.6;\n\n/** Reused across calls — the demotion loop measures the body once per image. */\nconst textEncoder = typeof TextEncoder === 'function' ? new TextEncoder() : null;\n\n/** UTF-8 byte length, with a graceful degradation where TextEncoder is absent. */\nfunction utf8ByteLength(value: string): number {\n return textEncoder ? textEncoder.encode(value).length : value.length;\n}\n\n/**\n * Estimate the bytes the prompt + parts will occupy in the POSTed body.\n *\n * Shaped like the JSON fe-libs actually builds (`{ mode, prompt, pageContext,\n * parts }` inside `proxySandboxRequest.body`), so the number tracks the thing\n * being limited rather than a proxy for it. Deliberately an UNDER-estimate of\n * the full request — `TURN_BODY_HEADROOM_BYTES` covers the difference.\n */\nexport function estimateTurnBodyBytes(promptText: string, parts?: AssistantPromptPart[]): number {\n return utf8ByteLength(JSON.stringify({ prompt: promptText, parts: parts ?? [] }));\n}\n\n/**\n * How many attachments COULD have travelled as pixels — i.e. are ready images\n * that have a `data:` URL to inline.\n *\n * Compared against how many actually did, this is what tells the user their\n * photo was demoted to a link. Without it the deterministic budget path is\n * silent, and only the transport-rejection path ever admits to anything.\n */\nexport function countInlineImageCandidates(attachments: AssistantAttachment[]): number {\n return attachments.filter(\n (attachment) =>\n attachment.status === 'ready' &&\n attachment.kind === 'image' &&\n Boolean(attachment.inlineDataUrl ?? attachment.previewUrl)\n ).length;\n}\n\n/** How many parts actually carry image bytes. */\nexport function countInlinedImageParts(parts: AssistantPromptPart[] | undefined): number {\n return (parts ?? []).filter((part) => part.type === 'image' && Boolean(part.data)).length;\n}\n\n/** Split a `data:<mime>;base64,<payload>` URL. Returns null for anything else. */\nexport function parseDataUrl(dataUrl: string): { mimeType: string; base64: string } | null {\n const match = /^data:([a-z0-9.+/-]+);base64,(.*)$/i.exec(dataUrl);\n return match ? { mimeType: match[1], base64: match[2] } : null;\n}\n\n/**\n * Build the structured multimodal turn.\n *\n * `promptText` MUST be the exact string also sent as `prompt`, so the two\n * channels are equivalent: a bridge that understands `parts` sees everything a\n * text-only bridge sees, plus the images. Returns `undefined` when there is\n * nothing an image/file part could add, which keeps the wire body byte-identical\n * to a pre-multimodal client for every ordinary text turn.\n */\nexport function buildPromptParts(\n promptText: string,\n attachments: AssistantAttachment[]\n): AssistantPromptPart[] | undefined {\n const usable = attachments.filter((attachment) => attachment.status === 'ready');\n if (usable.length === 0) return undefined;\n\n const media: AssistantPromptPart[] = [];\n // Positions in `media` that carry inline bytes, in the order they were added.\n // Demotion pops from the END, so the first photo — the one the farmer's\n // question is usually about — is the last to lose its pixels.\n const inlinedIndices: number[] = [];\n let inlined = 0;\n let inlineChars = 0;\n\n for (const attachment of usable) {\n if (attachment.kind === 'image') {\n // The transport-sized encode when there is one, else the thumbnail.\n const inlineSource = attachment.inlineDataUrl ?? attachment.previewUrl;\n const parsed = inlineSource ? parseDataUrl(inlineSource) : null;\n const withinBudget =\n parsed !== null &&\n inlined < MAX_INLINE_IMAGE_PARTS &&\n inlineChars + parsed.base64.length <= MAX_INLINE_IMAGE_BASE64_CHARS;\n\n if (withinBudget && parsed) {\n inlined += 1;\n inlineChars += parsed.base64.length;\n inlinedIndices.push(media.length);\n media.push({\n type: 'image',\n mimeType: parsed.mimeType,\n data: parsed.base64,\n // Sent alongside the bytes: a bridge that would rather fetch than\n // carry base64 through its own pipeline can, and the reference\n // outlives this turn.\n ...(attachment.downloadUrl ? { url: attachment.downloadUrl } : {}),\n name: attachment.filename,\n });\n continue;\n }\n\n if (attachment.downloadUrl) {\n media.push({\n type: 'image',\n mimeType: attachment.mimeType,\n url: attachment.downloadUrl,\n name: attachment.filename,\n });\n }\n continue;\n }\n\n // Documents are never inlined: a PDF is not an image, and making it useful\n // needs an extraction/retrieval step on the agent side. A reference is the\n // honest maximum from here. Text-like files already have their content in\n // the prompt block, so a missing URL costs nothing.\n if (attachment.downloadUrl) {\n media.push({\n type: 'file',\n mimeType: attachment.mimeType,\n url: attachment.downloadUrl,\n name: attachment.filename,\n });\n }\n }\n\n if (media.length === 0) return undefined;\n\n // ── Fit the body ───────────────────────────────────────────────────────────\n // Everything above decides what we WANT to send; this decides what the\n // gateway will accept. Demote inline images to url-only (dropping the part\n // entirely if it has no URL to fall back to) until the modelled body fits.\n // Doing it here, deterministically, is what keeps the 413 fallback in\n // AssistantChatArea a genuine safety net rather than the normal path.\n while (\n inlinedIndices.length > 0 &&\n estimateTurnBodyBytes(promptText, [{ type: 'text', text: promptText }, ...media]) > MAX_INLINE_TURN_BODY_BYTES\n ) {\n const index = inlinedIndices.pop();\n if (index === undefined) break;\n const part = media[index];\n if (!part || part.type === 'text') continue;\n if (part.url) {\n media[index] = { type: part.type, mimeType: part.mimeType, url: part.url, name: part.name };\n } else {\n // Safe to splice: we always pop the highest remaining index, so no index\n // still in `inlinedIndices` can be shifted by this removal.\n media.splice(index, 1);\n }\n }\n\n if (media.length === 0) return undefined;\n\n // Nothing left to demote and still over the cap. Sending anyway would be a\n // CERTAIN 413, and `parts[0]` duplicates the whole prompt — so a long message\n // with one attachment can exceed the cap on prompt text alone, in a case\n // where the identical message with no attachment would have gone through.\n // Drop the parts entirely: the attachment block and its URLs are still in the\n // prompt, so the model keeps everything except the pixels.\n if (estimateTurnBodyBytes(promptText, [{ type: 'text', text: promptText }, ...media]) > MAX_INLINE_TURN_BODY_BYTES) {\n return undefined;\n }\n\n return [{ type: 'text', text: promptText }, ...media];\n}\n"],"mappings":"AA8BA,IAAa,IAAiB,KAAK,OAAO,MAG7B,IAA4B,KAG5B,IAAyB,KAgBzB,IAAb,cAA6C,MAAM;CACjD,YAAY,GAAsC;AAEhD,EADA,MAAM,EAAO,EADM,KAAA,SAAA,GAEnB,KAAK,OAAO;;;AAoDhB,SAAgB,EAAoB,GAA6D;AAC/F,QAAO;EACL,IAAI,EAAW;EACf,UAAU,EAAW;EACrB,UAAU,EAAW;EACrB,MAAM,EAAW;EACjB,MAAM,EAAW;EACjB,QAAQ,EAAW;EACpB;;AAOH,IAAM,IAAkB,IAAI,IAAI;CAC9B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD,CAAC;AAEF,SAAgB,EAAa,GAA0B;CACrD,IAAM,IAAM,EAAS,YAAY,IAAI;AACrC,QAAO,KAAO,IAAI,EAAS,MAAM,IAAM,EAAE,CAAC,aAAa,GAAG;;AAG5D,SAAgB,EAAmB,GAAkB,GAA2C;AAW9F,QAVI,EAAS,WAAW,SAAS,GAAS,UAExC,EAAS,WAAW,QAAQ,IAC5B,MAAa,sBACb,MAAa,qBACb,MAAa,wBACb,EAAgB,IAAI,EAAa,EAAS,CAAC,GAEpC,SAEF;;AAGT,SAAgB,EAAY,GAAuB;AAGjD,QAFI,IAAQ,OAAa,GAAG,EAAM,MAC9B,IAAQ,OAAO,OAAa,IAAI,IAAQ,MAAM,QAAQ,EAAE,CAAC,OACtD,IAAI,KAAS,OAAO,OAAO,QAAQ,EAAE,CAAC;;AAa/C,SAAgB,EAA0B,GAAwB,GAA6C;AAC7G,QACE,IAAiB,KACjB,EAAY,MAAM,MAAe,EAAW,WA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AAQ,MAAM;GAAY,EAAE,GAAG,EAAM,CAAC,GAAA,QAIrF,QAAO,CAAC;GAAE,MAAM;GAAQ,MAAM;GAAY,EAAE,GAAG,EAAM"}
|
|
1
|
+
{"version":3,"file":"assistantAttachments.js","names":[],"sources":["../../src/utils/assistantAttachments.ts"],"sourcesContent":["/**\n * Attachment model for the assistant composer (Workstream 3 of the AI Assistant\n * V2 multimodal effort) — pure logic, no React, so it is unit-testable.\n *\n * ## How an attachment reaches the model today\n *\n * The sandbox transport carries exactly one user-authored field per turn:\n * a `prompt` **string** (`POST /sessions/:id/prompt-async`). The in-sandbox\n * agent's message parts are `text | tool` only. So there is no native file or\n * image part to put bytes into, and adding one means changing the out-of-repo\n * `ai-assistant-*` bridge image — that is Workstream 4, and it is not shipped.\n *\n * What this module does instead is the honest L1: every attachment is uploaded\n * to the workspace file library (wspace-files-svc) so it durably exists and has\n * a URL, and a compact, clearly-delimited block describing the attachments is\n * appended to the outgoing prompt. For **text-like** files the actual content is\n * inlined (bounded), which makes them fully usable by the model right now. For\n * images and binaries only the metadata and a presigned URL go across, and the\n * block says plainly that the bytes were not inlined — so the assistant asks\n * rather than hallucinating a description of a photo it cannot see.\n *\n * Whether the sandbox can egress to the presigned URL is **not verified** — the\n * wording therefore makes fetching conditional (\"if you can fetch URLs\") rather\n * than promising it. Vision on the image itself lands with Workstream 4.\n */\n\n/** Hard cap on attachments per message — keeps the prompt block bounded. */\nimport { MAX_REQUEST_BODY_BYTES } from './gatewayLimits';\n\nexport const MAX_ATTACHMENTS = 5;\n\n/** Per-file ceiling before downscaling (images) / rejection (everything else). */\nexport const MAX_FILE_BYTES = 10 * 1024 * 1024;\n\n/** Per-file inline budget for text-like content, in characters. */\nexport const MAX_INLINE_CHARS_PER_FILE = 8_000;\n\n/** Total inline budget across all attachments in one turn. */\nexport const MAX_INLINE_CHARS_TOTAL = 20_000;\n\nexport type AssistantAttachmentKind = 'image' | 'text' | 'document';\n\nexport type AssistantAttachmentStatus = 'pending' | 'uploading' | 'ready' | 'error';\n\nexport type AttachmentRejection = 'too-many' | 'too-large' | 'empty' | 'unreadable' | 'unsupported-image';\n\n/**\n * Thrown while PREPARING a file (after it passed `validateFile`) to reject it\n * with a specific reason rather than the generic 'unreadable'.\n *\n * `validateFile` runs before the bytes have been touched, so it cannot know\n * whether an oversized image will actually survive the downscale — that verdict\n * only exists once the browser has tried to rasterise it.\n */\nexport class AttachmentRejectedError extends Error {\n constructor(readonly reason: AttachmentRejection) {\n super(reason);\n this.name = 'AttachmentRejectedError';\n }\n}\n\nexport interface AssistantAttachment {\n /** Client-side id; stable for the lifetime of the draft + the sent message. */\n id: string;\n filename: string;\n mimeType: string;\n /** Size of the bytes we actually kept (post-downscale for images). */\n size: number;\n kind: AssistantAttachmentKind;\n status: AssistantAttachmentStatus;\n /** Object/data URL for the composer thumbnail. Images only; never persisted. */\n previewUrl?: string;\n /**\n * A smaller `data:` URL of the same image, sized for the request body rather\n * than for the eye. Preferred over `previewUrl` when building the multimodal\n * parts; see `MAX_TURN_BODY_BYTES`. Images only; never persisted.\n */\n inlineDataUrl?: string;\n /** wspace-files-svc id, once the upload lands. */\n fileId?: string;\n /** Short-lived presigned URL, resolved at send time. */\n downloadUrl?: string;\n /** Extracted UTF-8 content for text-like files (already truncated). */\n textContent?: string;\n /** True when `textContent` is a prefix of a longer file. */\n textTruncated?: boolean;\n /** Human-readable failure reason when `status === 'error'`. */\n error?: string;\n}\n\n/**\n * The slice of an attachment that is safe to keep on a sent message.\n *\n * Conversations are persisted to (profile-scoped) localStorage by the assistant\n * store, so the heavy fields — the base64 `previewUrl` and the inlined\n * `textContent` — MUST NOT travel here: five 1280px JPEG data URLs would exhaust\n * the ~5 MB quota on their own and take the whole conversation history down with\n * them. The bubble re-resolves a thumbnail from `fileId` on demand instead, the\n * same way the pest-scan list does.\n */\nexport interface AssistantMessageAttachment {\n id: string;\n filename: string;\n mimeType: string;\n size: number;\n kind: AssistantAttachmentKind;\n fileId?: string;\n}\n\nexport function toMessageAttachment(attachment: AssistantAttachment): AssistantMessageAttachment {\n return {\n id: attachment.id,\n filename: attachment.filename,\n mimeType: attachment.mimeType,\n size: attachment.size,\n kind: attachment.kind,\n fileId: attachment.fileId,\n };\n}\n\n/**\n * Extensions we treat as text even when the browser reports a useless MIME type\n * (`application/octet-stream` is common for `.log`, `.yml`, `.env` on Windows).\n */\nconst TEXT_EXTENSIONS = new Set([\n 'txt',\n 'md',\n 'markdown',\n 'csv',\n 'tsv',\n 'json',\n 'yaml',\n 'yml',\n 'xml',\n 'log',\n 'sql',\n 'html',\n 'css',\n 'js',\n 'ts',\n 'tsx',\n 'jsx',\n 'py',\n 'sh',\n 'ini',\n 'toml',\n 'conf',\n]);\n\nexport function getExtension(filename: string): string {\n const dot = filename.lastIndexOf('.');\n return dot >= 0 ? filename.slice(dot + 1).toLowerCase() : '';\n}\n\nexport function classifyAttachment(mimeType: string, filename: string): AssistantAttachmentKind {\n if (mimeType.startsWith('image/')) return 'image';\n if (\n mimeType.startsWith('text/') ||\n mimeType === 'application/json' ||\n mimeType === 'application/xml' ||\n mimeType === 'application/x-yaml' ||\n TEXT_EXTENSIONS.has(getExtension(filename))\n ) {\n return 'text';\n }\n return 'document';\n}\n\nexport function formatBytes(bytes: number): string {\n if (bytes < 1024) return `${bytes} B`;\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;\n return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;\n}\n\n/**\n * Is there attachment work in flight that must block sending?\n *\n * `preparingCount` counts files the user has ALREADY dropped/picked but whose\n * image-downscale or text-read has not resolved yet. Those files have no id and\n * no row in `attachments`, so a check that looked only at `attachments` reported\n * \"idle\" during the whole preparation window — the composer stayed sendable, the\n * turn went out without the photo, and the photo then attached itself to the\n * user's NEXT message. Both halves must be counted.\n */\nexport function hasAttachmentWorkInFlight(preparingCount: number, attachments: AssistantAttachment[]): boolean {\n return (\n preparingCount > 0 ||\n attachments.some((attachment) => attachment.status === 'pending' || attachment.status === 'uploading')\n );\n}\n\n/**\n * Gate a candidate file. Images over the ceiling are still accepted — the\n * composer downscales them before upload, so a 12 MB phone photo is fine while\n * a 12 MB PDF is not.\n *\n * That exemption is a PROMISE, not a fact: it holds only if the browser can\n * actually rasterise the image. When it cannot (HEIC), `prepareFile` re-applies\n * this ceiling to the original bytes and rejects there instead.\n */\nexport function validateFile(file: File, currentCount: number): AttachmentRejection | null {\n if (currentCount >= MAX_ATTACHMENTS) return 'too-many';\n if (file.size === 0) return 'empty';\n if (file.size > MAX_FILE_BYTES && !file.type.startsWith('image/')) return 'too-large';\n return null;\n}\n\n/**\n * Truncate on a line boundary where possible, so an inlined CSV/JSON prefix ends\n * at a row rather than mid-token (which reads as corrupt data to the model).\n */\nexport function truncateForInline(content: string, limit: number): { text: string; truncated: boolean } {\n if (content.length <= limit) return { text: content, truncated: false };\n const head = content.slice(0, limit);\n const lastNewline = head.lastIndexOf('\\n');\n return { text: lastNewline > limit * 0.5 ? head.slice(0, lastNewline) : head, truncated: true };\n}\n\nfunction describeAttachment(attachment: AssistantAttachment, index: number): string {\n const lines = [`[${index + 1}] ${attachment.filename} — ${attachment.mimeType}, ${formatBytes(attachment.size)}`];\n\n if (attachment.downloadUrl) {\n lines.push(` URL: ${attachment.downloadUrl}`);\n }\n\n if (attachment.kind === 'text' && attachment.textContent) {\n lines.push(\n attachment.textTruncated\n ? ` Contents (first ${attachment.textContent.length} characters of ${formatBytes(attachment.size)}; truncated):`\n : ' Contents:',\n ' ```',\n ...attachment.textContent.split('\\n').map((line) => ` ${line}`),\n ' ```'\n );\n } else if (attachment.kind === 'image') {\n // Deliberately regime-neutral wording. This same block is sent whether or\n // not the bridge understands `parts`, so it must not assert either that the\n // model CAN see the image (it would then invent a description on the old\n // bridge) or that it CANNOT (it would then refuse to look on the new one).\n lines.push(\n ' If this image is attached to the message as an image you can view, answer from what you see in it.',\n ' If you cannot view attached images, say so plainly and ask the user to describe it — never guess.'\n );\n } else if (attachment.kind === 'text') {\n // A text file with no `textContent` did not lose its type — it lost its slot\n // in the shared inline budget. Calling it \"binary\" here had the assistant ask\n // the farmer to paste text it already knew was text.\n lines.push(\n ' Text file — contents omitted because this turn ran out of inline budget, not because they are',\n ' unavailable. Fetch the URL above if you can; otherwise ask the user which part matters so they',\n ' can re-send just that section.'\n );\n } else {\n lines.push(\n ' Binary file — contents not inlined. Fetch the URL above if you can; otherwise ask the user',\n ' to paste the relevant section as text.'\n );\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Render the attachment block appended to the outgoing prompt. Returns '' when\n * there is nothing to say, so callers can concatenate unconditionally.\n *\n * Attachments that failed to upload are omitted: the user already sees the\n * failure in the composer, and a half-described file only confuses the model.\n */\nexport function buildAttachmentPromptBlock(attachments: AssistantAttachment[]): string {\n const usable = attachments.filter((attachment) => attachment.status === 'ready');\n if (usable.length === 0) return '';\n\n // Apply the shared inline budget in order, so the first files keep their\n // content and later ones degrade to metadata-only rather than every file\n // being trimmed to uselessness.\n let remaining = MAX_INLINE_CHARS_TOTAL;\n const budgeted = usable.map((attachment) => {\n if (attachment.kind !== 'text' || !attachment.textContent) return attachment;\n if (remaining <= 0) {\n return { ...attachment, textContent: undefined, textTruncated: true };\n }\n const { text, truncated } = truncateForInline(attachment.textContent, remaining);\n remaining -= text.length;\n return { ...attachment, textContent: text, textTruncated: attachment.textTruncated || truncated };\n });\n\n return [\n '',\n `--- Attachments (${usable.length}) ---`,\n 'The user attached the following file(s) to this message.',\n ...budgeted.map(describeAttachment),\n '--- End attachments ---',\n ].join('\\n');\n}\n\n/**\n * Compose the text actually sent to the agent: the user's words, then the\n * attachment block. The user-facing bubble keeps the raw text (attachments are\n * rendered as chips there), matching how `buildPromptForMode` already separates\n * agent-only preamble from displayed content.\n */\nexport function buildPromptWithAttachments(content: string, attachments: AssistantAttachment[]): string {\n const block = buildAttachmentPromptBlock(attachments);\n if (!block) return content;\n return content ? `${content}\\n${block}` : block.trimStart();\n}\n\n// ── Multimodal parts (Workstream 4, client half) ─────────────────────────────\n\n/**\n * Structural mirror of fe-libs' `AssistantPromptPart`\n * (`@burdenoff/fe-libs/shared/assistant`). Declared locally so this module —\n * and its tests — stay pure and importable without the transport, and so the\n * builder compiles against a fe-libs pin that predates the widening. The\n * assignment at the call site is what proves the two agree.\n */\nexport type AssistantPromptPart =\n | { type: 'text'; text: string }\n | { type: 'image'; mimeType: string; url?: string; data?: string; name?: string }\n | { type: 'file'; mimeType: string; url?: string; data?: string; name?: string };\n\n/**\n * How many images may travel INLINE in one turn.\n *\n * Inline bytes are what make vision work without the sandbox needing egress to\n * our storage. Images beyond the budget still travel, by URL only, and the\n * prompt block still describes them.\n */\nexport const MAX_INLINE_IMAGE_PARTS = 3;\n\n/**\n * Belt-and-braces per-turn ceiling on base64 characters.\n *\n * Kept as a cheap guard against a pathological single image, but it is NO\n * LONGER the operative limit — `MAX_TURN_BODY_BYTES` is. See below for why the\n * previous 1.5M-character budget was a fiction.\n */\nexport const MAX_INLINE_IMAGE_BASE64_CHARS = 1_500_000;\n\n/**\n * The real ceiling: what the gateway will accept as a request body.\n *\n * `wspace-public-gateway` enforces `MAX_REQUEST_BODY_SIZE`, and both the alpha\n * and prod configs set it to **256kb** (`burdenoff-gitops`\n * `apps/config-workspace{,-prod}/wspace-public-gateway-config.yaml`). It is\n * checked against `Content-Length` before authentication and before anything is\n * forwarded, and it answers 413 with a JSON body — which fe-libs' `graphqlFetch`\n * maps to the generic 4xx sentence, discarding the status. So an oversized turn\n * does not degrade: it dies, and the user is told to refresh.\n *\n * The old budget (1.5M base64 characters ≈ 1.43 MB) was ~5.7x that cap, so a\n * single ordinary 1280px photo — 150-400 KB, i.e. 200-530 KB of base64 — was\n * enough to lose the whole turn. Measure the body instead of guessing at it.\n */\nexport const MAX_TURN_BODY_BYTES = MAX_REQUEST_BODY_BYTES;\n\n/**\n * Headroom left for everything `estimateTurnBodyBytes` does not model: the\n * GraphQL query document, the operation name, the sandbox id / path / method,\n * the context input and the page context.\n *\n * Measured, that overhead is under 1 KB — the ProxySandboxRequest document is\n * ~150 bytes and the page context a few hundred. 32 KB is therefore deliberately\n * ~30x the real figure, because the two ways of being wrong are not\n * symmetrical: reserve too much and one photo travels as a link instead of as\n * pixels; reserve too little and the entire turn is rejected and the farmer's\n * question is lost.\n */\nexport const TURN_BODY_HEADROOM_BYTES = 32_768;\n\n/** What the modelled part of the body must fit inside. */\nexport const MAX_INLINE_TURN_BODY_BYTES = MAX_TURN_BODY_BYTES - TURN_BODY_HEADROOM_BYTES;\n\n/**\n * Encode settings for the copy of an image that travels INSIDE the turn.\n *\n * Separate from the upload encode (1280px / q0.72) on purpose: the file that\n * lands in the farmer's file library should not be degraded to fit a transport\n * limit. At 768px / q0.6 a photo is typically 40-90 KB — 53-120 KB of base64 —\n * so one image fits inside `MAX_INLINE_TURN_BODY_BYTES` with room for the\n * prompt, and often two do. Vision models downsample to roughly this size\n * anyway, so the diagnostic detail that matters survives.\n */\nexport const INLINE_IMAGE_MAX_DIM = 768;\nexport const INLINE_IMAGE_QUALITY = 0.6;\n\n/** Reused across calls — the demotion loop measures the body once per image. */\nconst textEncoder = typeof TextEncoder === 'function' ? new TextEncoder() : null;\n\n/** UTF-8 byte length, with a graceful degradation where TextEncoder is absent. */\nfunction utf8ByteLength(value: string): number {\n return textEncoder ? textEncoder.encode(value).length : value.length;\n}\n\n/**\n * Estimate the bytes the prompt + parts will occupy in the POSTed body.\n *\n * Shaped like the JSON fe-libs actually builds (`{ mode, prompt, pageContext,\n * parts }` inside `proxySandboxRequest.body`), so the number tracks the thing\n * being limited rather than a proxy for it. Deliberately an UNDER-estimate of\n * the full request — `TURN_BODY_HEADROOM_BYTES` covers the difference.\n */\nexport function estimateTurnBodyBytes(promptText: string, parts?: AssistantPromptPart[]): number {\n return utf8ByteLength(JSON.stringify({ prompt: promptText, parts: parts ?? [] }));\n}\n\n/**\n * How many attachments COULD have travelled as pixels — i.e. are ready images\n * that have a `data:` URL to inline.\n *\n * Compared against how many actually did, this is what tells the user their\n * photo was demoted to a link. Without it the deterministic budget path is\n * silent, and only the transport-rejection path ever admits to anything.\n */\nexport function countInlineImageCandidates(attachments: AssistantAttachment[]): number {\n return attachments.filter(\n (attachment) =>\n attachment.status === 'ready' &&\n attachment.kind === 'image' &&\n Boolean(attachment.inlineDataUrl ?? attachment.previewUrl)\n ).length;\n}\n\n/** How many parts actually carry image bytes. */\nexport function countInlinedImageParts(parts: AssistantPromptPart[] | undefined): number {\n return (parts ?? []).filter((part) => part.type === 'image' && Boolean(part.data)).length;\n}\n\n/** Split a `data:<mime>;base64,<payload>` URL. Returns null for anything else. */\nexport function parseDataUrl(dataUrl: string): { mimeType: string; base64: string } | null {\n const match = /^data:([a-z0-9.+/-]+);base64,(.*)$/i.exec(dataUrl);\n return match ? { mimeType: match[1], base64: match[2] } : null;\n}\n\n/**\n * Build the structured multimodal turn.\n *\n * `promptText` MUST be the exact string also sent as `prompt`, so the two\n * channels are equivalent: a bridge that understands `parts` sees everything a\n * text-only bridge sees, plus the images. Returns `undefined` when there is\n * nothing an image/file part could add, which keeps the wire body byte-identical\n * to a pre-multimodal client for every ordinary text turn.\n */\nexport function buildPromptParts(\n promptText: string,\n attachments: AssistantAttachment[]\n): AssistantPromptPart[] | undefined {\n const usable = attachments.filter((attachment) => attachment.status === 'ready');\n if (usable.length === 0) return undefined;\n\n const media: AssistantPromptPart[] = [];\n // Positions in `media` that carry inline bytes, in the order they were added.\n // Demotion pops from the END, so the first photo — the one the farmer's\n // question is usually about — is the last to lose its pixels.\n const inlinedIndices: number[] = [];\n let inlined = 0;\n let inlineChars = 0;\n\n for (const attachment of usable) {\n if (attachment.kind === 'image') {\n // The transport-sized encode when there is one, else the thumbnail.\n const inlineSource = attachment.inlineDataUrl ?? attachment.previewUrl;\n const parsed = inlineSource ? parseDataUrl(inlineSource) : null;\n const withinBudget =\n parsed !== null &&\n inlined < MAX_INLINE_IMAGE_PARTS &&\n inlineChars + parsed.base64.length <= MAX_INLINE_IMAGE_BASE64_CHARS;\n\n if (withinBudget && parsed) {\n inlined += 1;\n inlineChars += parsed.base64.length;\n inlinedIndices.push(media.length);\n media.push({\n type: 'image',\n mimeType: parsed.mimeType,\n data: parsed.base64,\n // Sent alongside the bytes: a bridge that would rather fetch than\n // carry base64 through its own pipeline can, and the reference\n // outlives this turn.\n ...(attachment.downloadUrl ? { url: attachment.downloadUrl } : {}),\n name: attachment.filename,\n });\n continue;\n }\n\n if (attachment.downloadUrl) {\n media.push({\n type: 'image',\n mimeType: attachment.mimeType,\n url: attachment.downloadUrl,\n name: attachment.filename,\n });\n }\n continue;\n }\n\n // Documents are never inlined: a PDF is not an image, and making it useful\n // needs an extraction/retrieval step on the agent side. A reference is the\n // honest maximum from here. Text-like files already have their content in\n // the prompt block, so a missing URL costs nothing.\n if (attachment.downloadUrl) {\n media.push({\n type: 'file',\n mimeType: attachment.mimeType,\n url: attachment.downloadUrl,\n name: attachment.filename,\n });\n }\n }\n\n if (media.length === 0) return undefined;\n\n // ── Fit the body ───────────────────────────────────────────────────────────\n // Everything above decides what we WANT to send; this decides what the\n // gateway will accept. Demote inline images to url-only (dropping the part\n // entirely if it has no URL to fall back to) until the modelled body fits.\n // Doing it here, deterministically, is what keeps the 413 fallback in\n // AssistantChatArea a genuine safety net rather than the normal path.\n while (\n inlinedIndices.length > 0 &&\n estimateTurnBodyBytes(promptText, [{ type: 'text', text: promptText }, ...media]) > MAX_INLINE_TURN_BODY_BYTES\n ) {\n const index = inlinedIndices.pop();\n if (index === undefined) break;\n const part = media[index];\n if (!part || part.type === 'text') continue;\n if (part.url) {\n media[index] = { type: part.type, mimeType: part.mimeType, url: part.url, name: part.name };\n } else {\n // Safe to splice: we always pop the highest remaining index, so no index\n // still in `inlinedIndices` can be shifted by this removal.\n media.splice(index, 1);\n }\n }\n\n if (media.length === 0) return undefined;\n\n // Nothing left to demote and still over the cap. Sending anyway would be a\n // CERTAIN 413, and `parts[0]` duplicates the whole prompt — so a long message\n // with one attachment can exceed the cap on prompt text alone, in a case\n // where the identical message with no attachment would have gone through.\n // Drop the parts entirely: the attachment block and its URLs are still in the\n // prompt, so the model keeps everything except the pixels.\n if (estimateTurnBodyBytes(promptText, [{ type: 'text', text: promptText }, ...media]) > MAX_INLINE_TURN_BODY_BYTES) {\n return undefined;\n }\n\n return [{ type: 'text', text: promptText }, ...media];\n}\n"],"mappings":";AAgCA,IAAa,IAAiB,KAAK,OAAO,MAG7B,IAA4B,KAG5B,IAAyB,KAgBzB,IAAb,cAA6C,MAAM;CACjD,YAAY,GAAsC;AAEhD,EADA,MAAM,EAAO,EADM,KAAA,SAAA,GAEnB,KAAK,OAAO;;;AAoDhB,SAAgB,EAAoB,GAA6D;AAC/F,QAAO;EACL,IAAI,EAAW;EACf,UAAU,EAAW;EACrB,UAAU,EAAW;EACrB,MAAM,EAAW;EACjB,MAAM,EAAW;EACjB,QAAQ,EAAW;EACpB;;AAOH,IAAM,IAAkB,IAAI,IAAI;CAC9B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD,CAAC;AAEF,SAAgB,EAAa,GAA0B;CACrD,IAAM,IAAM,EAAS,YAAY,IAAI;AACrC,QAAO,KAAO,IAAI,EAAS,MAAM,IAAM,EAAE,CAAC,aAAa,GAAG;;AAG5D,SAAgB,EAAmB,GAAkB,GAA2C;AAW9F,QAVI,EAAS,WAAW,SAAS,GAAS,UAExC,EAAS,WAAW,QAAQ,IAC5B,MAAa,sBACb,MAAa,qBACb,MAAa,wBACb,EAAgB,IAAI,EAAa,EAAS,CAAC,GAEpC,SAEF;;AAGT,SAAgB,EAAY,GAAuB;AAGjD,QAFI,IAAQ,OAAa,GAAG,EAAM,MAC9B,IAAQ,OAAO,OAAa,IAAI,IAAQ,MAAM,QAAQ,EAAE,CAAC,OACtD,IAAI,KAAS,OAAO,OAAO,QAAQ,EAAE,CAAC;;AAa/C,SAAgB,EAA0B,GAAwB,GAA6C;AAC7G,Q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EAAE;;AAItB,QAAM,WAAW,KAQjB,IAAsB,GAAY,CAAC;GAAE,MAAM;GAAQ,MAAM;GAAY,EAAE,GAAG,EAAM,CAAC,GAAG,GAIxF,QAAO,CAAC;GAAE,MAAM;GAAQ,MAAM;GAAY,EAAE,GAAG,EAAM"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"gatewayLimits.js","names":[],"sources":["../../src/utils/gatewayLimits.ts"],"sourcesContent":["/**\n * Hard limits imposed by the gateways this app talks to.\n *\n * These are not our numbers — they are deployment facts, and getting them wrong\n * is expensive because the failure is opaque. `wspace-public-gateway` sets\n * `MAX_REQUEST_BODY_SIZE: 256kb` in BOTH environments (burdenoff-gitops,\n * `apps/config-workspace/wspace-public-gateway-config.yaml:21` and\n * `apps/config-workspace-prod/…:21`). It compares Content-Length and answers\n * 413 *before* authenticating and before forwarding, and fe-libs' `graphqlFetch`\n * discards the status — so the user is told \"The request could not be processed.\n * Please refresh and try again.\" with nothing in it to suggest the payload was\n * simply too big.\n *\n * Anything that POSTs base64 from the browser has to be sized against this.\n */\nexport const MAX_REQUEST_BODY_BYTES = 262_144;\n\n/**\n * What is left for a base64 image once the rest of a GraphQL request is paid\n * for: the query document, operation name, variables, and the workspace/org\n * context envelope. 32 KB is deliberately generous — the point is to fail in\n * OUR code with a sentence the user can act on, rather than at the gateway with\n * one they cannot.\n */\nexport const MAX_INLINE_IMAGE_BASE64_BYTES = MAX_REQUEST_BODY_BYTES - 32_768;\n"],"mappings":";AAeA,IAAa,IAAyB,QASzB,IAAgC,IAAyB"}
|
package/package.json
CHANGED