- - {/* Header with title */} - - {toolName} - - {t('landing.tagline')} - - - - {actionButtons} - - {/* Features Grid - 2 columns, 4 rows */} - - {features.map((feature, index) => ( - - {/* Text Content */} - - - {feature.title} - - - {feature.description} - - - - {/* Media Content */} - - {feature.mediaType === 'video' ? ( - - ) : ( - - )} - - - ))} - - - - - {t('about.dataHandling')} {t('about.dataHandlingText')} - - - {t('about.researchPrototype')} - - - - - {/* Footer */} - - - - ) -} diff --git a/src/views/AgentChatInput.tsx b/src/views/AgentChatInput.tsx index dc707bc73..acda88de0 100644 --- a/src/views/AgentChatInput.tsx +++ b/src/views/AgentChatInput.tsx @@ -4,8 +4,7 @@ // Shared chat-style input box for agent surfaces. Renders a rounded // border with focus glow, an inline image-preview row, a file-attach // affordance, a multiline `InputBase`, and a send/stop button. Used by -// both the in-chat `DataLoadingChat` and the landing-page Data Loading -// Agent quick-start box so they look and behave identically (paste +// the landing-page and upload-menu quick-start boxes (paste // image, drag attach, Shift+Enter, etc.). import * as React from 'react'; @@ -19,15 +18,17 @@ import { alpha, useTheme, } from '@mui/material'; -import AddIcon from '@mui/icons-material/Add'; +import AttachFileIcon from '@mui/icons-material/AttachFile'; import CloseIcon from '@mui/icons-material/Close'; import InsertDriveFileOutlinedIcon from '@mui/icons-material/InsertDriveFileOutlined'; -import UploadFileIcon from '@mui/icons-material/UploadFile'; import ArrowUpwardRoundedIcon from '@mui/icons-material/ArrowUpwardRounded'; import StopIcon from '@mui/icons-material/Stop'; import { useTranslation } from 'react-i18next'; -import { borderColor, transition, radius } from '../app/tokens'; +import { borderColor, transition, ambientShadow, cardRadius, ink } from '../app/tokens'; +import { inputFocusShadow } from '../app/look'; import { iconVar, textVar } from '../app/layout'; +import { pastedTextFile } from '../app/pastedText'; +import { FileDropOverlay, useFileDrop } from '../components/FileDrop'; export interface AgentChatInputProps { value: string; @@ -50,6 +51,7 @@ export interface AgentChatInputProps { * non-image files are silently ignored (image-only mode). */ onNonImageFile?: (file: File) => void; + onFileCreated?: () => void; /** * Optional list of attached non-image files (e.g. uploaded Excel/CSV). * Rendered as removable chips above the input — mirrors the @@ -73,6 +75,8 @@ export interface AgentChatInputProps { * instead of, or in addition to, the attach affordance. */ leadingSlot?: React.ReactNode; + /** Rendered right after the attach button, as in the chat box (e.g. the Tools chip). */ + trailingSlot?: React.ReactNode; /** * If false, the attach button is hidden (paste of images still works). */ @@ -141,6 +145,7 @@ export const AgentChatInput: React.FC = ({ minRows, maxRows = 8, leadingSlot, + trailingSlot, showAttachButton = true, layout = 'inline', topSlot, @@ -166,7 +171,7 @@ export const AgentChatInput: React.FC = ({ }, []); - const canSend = (value.trim().length > 0 || images.length > 0) && !inProgress && !disabled; + const canSend = (value.trim().length > 0 || images.length > 0 || !!attachments?.length) && !inProgress && !disabled; // Shared file intake: images become inline previews, everything else is // handed to `onNonImageFile` (scratch upload → attachment chip). Used by @@ -186,38 +191,20 @@ export const AgentChatInput: React.FC = ({ }); }; - const [isDragActive, setIsDragActive] = useState(false); - - const dragHasFiles = (e: React.DragEvent) => - Array.from(e.dataTransfer?.types ?? []).includes('Files'); - - const handleDragOver = (e: React.DragEvent) => { - if (!dragHasFiles(e) || inProgress || disabled) return; - e.preventDefault(); - e.dataTransfer.dropEffect = 'copy'; - }; - - const handleDragEnter = (e: React.DragEvent) => { - if (!dragHasFiles(e) || inProgress || disabled) return; - e.preventDefault(); - setIsDragActive(true); - }; - - const handleDragLeave = (e: React.DragEvent) => { - // Ignore leaves that bubble up from child elements. - if (e.currentTarget.contains(e.relatedTarget as Node)) return; - setIsDragActive(false); - }; - - const handleDrop = (e: React.DragEvent) => { - if (!dragHasFiles(e) || inProgress || disabled) return; - e.preventDefault(); - setIsDragActive(false); - const files = e.dataTransfer?.files; - if (files && files.length > 0) processFiles(Array.from(files)); - }; + const { active: isDragActive, handlers: dropHandlers } = useFileDrop({ enabled: !inProgress && !disabled, onFiles: processFiles }); + const pasteCount = useRef(0); const handlePaste = (e: React.ClipboardEvent) => { + // A large text paste is attached as a document when this surface accepts files (see pastedText.ts). + if (!e.clipboardData?.files?.length && onNonImageFile) { + const pasted = pastedTextFile(e.clipboardData?.getData('text/plain') ?? '', pasteCount.current + 1); + if (pasted) { + e.preventDefault(); + pasteCount.current += 1; + onNonImageFile(pasted); + return; + } + } if (e.clipboardData?.files?.length) { const imageFiles = Array.from(e.clipboardData.files).filter(f => f.type.startsWith('image/')); if (imageFiles.length > 0) { @@ -253,12 +240,13 @@ export const AgentChatInput: React.FC = ({ }; const attachButton = showAttachButton ? ( - - fileInputRef.current?.click()} - disabled={inProgress || disabled} - sx={{ color: 'text.secondary' }}> - - + + + fileInputRef.current?.click()}> + + + ) : null; @@ -337,23 +325,20 @@ export const AgentChatInput: React.FC = ({ return ( = ({ ...sx, }} > - {/* Drag-and-drop overlay — shown while a file is dragged over - the composer. Uses the Data Formulator drop-zone language - (2px dashed primary, tinted fill) inset from the container - edge so it nests cleanly inside the border. Pointer events - are disabled so the drop still lands on the container. */} - {isDragActive && ( - - - - {t('dataLoading.dropToAttach', { defaultValue: 'Drop file to attach' })} - - - )} + {/* Top slot (e.g. data-source chip bar) sits flush with the input area below — no divider, same background. */} {topSlot && ( @@ -414,8 +370,8 @@ export const AgentChatInput: React.FC = ({ sx={{ position: 'absolute', top: -4, right: -4, width: 18, height: 18, - bgcolor: 'rgba(0,0,0,0.55)', color: 'white', - '&:hover': { bgcolor: 'rgba(0,0,0,0.75)' }, + bgcolor: ink(0.55), color: 'white', + '&:hover': { bgcolor: ink(0.75) }, }}> @@ -469,7 +425,7 @@ export const AgentChatInput: React.FC = ({ {inputField} - {/* Bottom toolbar: leading slot + attach on the left, send on the right. */} + {/* Bottom toolbar: leading slot, attach, trailing slot on the left; send on the right. */} = ({ pt: 0.25, gap: 0.5, }}> - + {leadingSlot} {attachButton} + {trailingSlot} {sendButton} @@ -495,6 +452,7 @@ export const AgentChatInput: React.FC = ({ {showAttachButton && ( {attachButton} )} + {trailingSlot} {inputField} {sendButton} @@ -514,7 +472,7 @@ export const AgentChatInput: React.FC = ({ left: 0, right: 0, zIndex: 20, - borderRadius: '12px', + borderRadius: 3, border: `1px solid ${borderColor.divider}`, bgcolor: theme.palette.background.paper, boxShadow: '0 4px 16px rgba(32, 33, 36, 0.16), 0 2px 6px rgba(32, 33, 36, 0.08)', diff --git a/src/views/AgentPausePanel.tsx b/src/views/AgentPausePanel.tsx index 56772e9d6..5ab15ed6f 100644 --- a/src/views/AgentPausePanel.tsx +++ b/src/views/AgentPausePanel.tsx @@ -16,19 +16,36 @@ * only spot of color is the header icon's badge (`?` / `i`). * Keeping them in one file makes shared styling/layout tweaks (header * spacing, palette use, collapse animation) trivial to maintain. + * + * Long text scrolls inside a height cap. When it is taller than a small + * minimum, a grip on the panel's top edge lets the user drag that cap (from the + * minimum up to the content, at most 70% of the window); the chosen height is + * remembered for later panels, and double-clicking the grip restores the default. */ -import React, { FC, ReactNode, useEffect, useRef, useState } from 'react'; +import React, { FC, ReactNode, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react'; import { - Box, Button, IconButton, InputAdornment, Radio, TextField, Tooltip, Typography, useTheme, + Box, Button, ButtonBase, CircularProgress, Collapse, IconButton, InputAdornment, Radio, TextField, Tooltip, Typography, useTheme, } from '@mui/material'; import { alpha } from '@mui/material/styles'; import CloseRoundedIcon from '@mui/icons-material/CloseRounded'; import ArrowForwardRoundedIcon from '@mui/icons-material/ArrowForwardRounded'; import CheckRoundedIcon from '@mui/icons-material/CheckRounded'; +import DeleteOutlineRoundedIcon from '@mui/icons-material/DeleteOutlineRounded'; +import ErrorOutlineRoundedIcon from '@mui/icons-material/ErrorOutlineRounded'; +import ReplayRoundedIcon from '@mui/icons-material/ReplayRounded'; +import CodeIcon from '@mui/icons-material/Code'; +import TerminalIcon from '@mui/icons-material/Terminal'; +import ChevronLeftIcon from '@mui/icons-material/ChevronLeft'; +import ChevronRightIcon from '@mui/icons-material/ChevronRight'; +import OpenInFullIcon from '@mui/icons-material/OpenInFull'; +import TravelExploreRoundedIcon from '@mui/icons-material/TravelExploreRounded'; +import LinkRoundedIcon from '@mui/icons-material/LinkRounded'; +import UploadFileRoundedIcon from '@mui/icons-material/UploadFileRounded'; import { useTranslation } from 'react-i18next'; import { AgentToyIcon } from './AgentToyIcon'; import { + ClarificationOptionIcon, ClarificationQuestion, ClarificationResponse, } from '../components/ComponentType'; @@ -36,11 +53,121 @@ import { renderFieldHighlights, CompactMarkdown } from './InteractionEntryCard'; import { iconVar, textVar } from '../app/layout'; import { DataOperationCard } from '../components/DataOperationCard'; import type { DataOperation } from '../dataOperations/models'; +import { ExecutionCodeBlock, TerminalExecutionView, TerminalMessageContent } from '../components/TerminalApprovalDialog'; +import type { TerminalExecution, CodeExecution } from '../components/ComponentType'; +import { weight } from '../app/tokens'; // --------------------------------------------------------------------------- // Shared shell // --------------------------------------------------------------------------- +/** Below this the panel's text needs no resizing: shorter content just fits. */ +export const PAUSE_REGION_MIN_HEIGHT = 80; +const PAUSE_HEIGHT_KEY = 'df.pausePanelHeight'; +const PAUSE_HEIGHT_STEP = 16; + +const readPauseHeight = (): number | undefined => { + try { + const value = Number(window.localStorage.getItem(PAUSE_HEIGHT_KEY)); + return Number.isFinite(value) && value >= PAUSE_REGION_MIN_HEIGHT ? value : undefined; + } catch { return undefined; } +}; +const writePauseHeight = (value: number | undefined) => { + try { + if (value === undefined) window.localStorage.removeItem(PAUSE_HEIGHT_KEY); + else window.localStorage.setItem(PAUSE_HEIGHT_KEY, String(value)); + } catch { /* storage unavailable: the height lasts until the panel closes */ } +}; + +/** The panel's height cap chosen by the user, and how its scrolling regions report their content. */ +const PauseRegionContext = React.createContext<{ height?: number; register: (element: HTMLElement) => () => void } | null>(null); + +/** + * A scrolling text region of a pause panel. It is capped at `defaultMaxHeight` + * until the user drags the panel's grip; then every region follows that height. + */ +const PauseScrollRegion: FC<{ defaultMaxHeight: string; sx?: Record; children: ReactNode }> = ({ defaultMaxHeight, sx, children }) => { + const region = useContext(PauseRegionContext); + const register = region?.register; + const ref = useRef(null); + useEffect(() => (ref.current && register ? register(ref.current) : undefined), [register]); + return + {children} + ; +}; + +/** Track the panel's scrolling regions and the height the user chose for them. */ +const usePauseRegionHeight = () => { + const [height, setHeight] = useState(readPauseHeight); + const [contentHeight, setContentHeight] = useState(0); + const regions = useRef(new Set()); + const measure = useCallback(() => setContentHeight(Math.max(0, ...[...regions.current].map(element => element.scrollHeight))), []); + const observer = useMemo(() => typeof ResizeObserver === 'undefined' ? undefined : new ResizeObserver(measure), [measure]); + useEffect(() => () => observer?.disconnect(), [observer]); + const register = useCallback((element: HTMLElement) => { + regions.current.add(element); + // The region is clipped at its cap, so watch its content to see it grow. + const content = [element, ...Array.from(element.children)]; + content.forEach(node => observer?.observe(node)); + measure(); + return () => { + regions.current.delete(element); + content.forEach(node => observer?.unobserve(node)); + measure(); + }; + }, [observer, measure]); + // From the minimum up to the full content, leaving room for the thread above. + const clamp = (value: number) => Math.round(Math.max(PAUSE_REGION_MIN_HEIGHT, + Math.min(value, contentHeight, window.innerHeight * 0.7))); + const current = () => Math.max(PAUSE_REGION_MIN_HEIGHT, ...[...regions.current].map(element => element.clientHeight)); + return { height, setHeight, contentHeight, register, clamp, current }; +}; + +/** Drag (or arrow keys) on the panel's top edge sets its text height; double-click restores the default. */ +const PauseResizeGrip: FC<{ resize: ReturnType }> = ({ resize }) => { + const { t } = useTranslation(); + const theme = useTheme(); + const { height, setHeight, contentHeight, clamp, current } = resize; + const commit = (value: number | undefined) => { setHeight(value); writePauseHeight(value); }; + const onPointerDown = (event: React.PointerEvent) => { + if (event.button !== 0) return; + event.preventDefault(); + const startY = event.clientY; + const start = current(); + let last = height ?? start; + const move = (moveEvent: PointerEvent) => { last = clamp(start + startY - moveEvent.clientY); setHeight(last); }; + const end = () => { + window.removeEventListener('pointermove', move); + window.removeEventListener('pointerup', end); + window.removeEventListener('pointercancel', end); + writePauseHeight(last); + }; + window.addEventListener('pointermove', move); + window.addEventListener('pointerup', end); + window.addEventListener('pointercancel', end); + }; + const onKeyDown = (event: React.KeyboardEvent) => { + const value = height ?? current(); + const next = event.key === 'ArrowUp' ? value + PAUSE_HEIGHT_STEP : event.key === 'ArrowDown' ? value - PAUSE_HEIGHT_STEP + : event.key === 'Home' ? PAUSE_REGION_MIN_HEIGHT : event.key === 'End' ? contentHeight : undefined; + if (next === undefined) return; + event.preventDefault(); + commit(clamp(next)); + }; + return commit(undefined)} + sx={{ position: 'absolute', top: 0, left: 0, right: 0, height: 7, zIndex: 1, cursor: 'ns-resize', touchAction: 'none', + display: 'flex', justifyContent: 'center', alignItems: 'flex-start', pt: '2px', + '&::after': { content: '""', width: 28, height: 3, borderRadius: 2, bgcolor: alpha(theme.palette.text.primary, 0.18), + opacity: 0, transition: 'opacity 0.15s' }, + '&:hover::after, &:focus-visible::after': { opacity: 1 }, + '&:focus-visible': { outline: 'none' } }} />; +}; + interface AgentPauseShellProps { /** Localized header label. */ title: string; @@ -67,6 +194,8 @@ interface AgentPauseShellProps { onClose: () => void; /** Deprecated: delete is handled from the thread card directly. */ onDelete?: () => void; + /** Controls beside the close button. */ + headerActions?: ReactNode; children: ReactNode; } @@ -76,6 +205,7 @@ const AgentPauseShell: FC = ({ icon, accentColor, onClose, + headerActions, children, }) => { const theme = useTheme(); @@ -88,9 +218,13 @@ const AgentPauseShell: FC = ({ const panelBg = alpha(fillAccent, 0.05); const panelBorder = alpha(fillAccent, 0.18); const primaryColor = theme.palette.primary.main; + const resize = usePauseRegionHeight(); + const region = useMemo(() => ({ height: resize.height, register: resize.register }), [resize.height, resize.register]); return ( + = ({ overflow: 'hidden', mx: '-10px', mt: '-8px', mb: '4px', }}> + {resize.contentHeight > PAUSE_REGION_MIN_HEIGHT && } = ({ {icon} {title} + {headerActions} = ({ {children} + + ); +}; + +interface ResponseOptionButtonProps { + children: ReactNode; + accentColor: string; + selected?: boolean; + disabled?: boolean; + onClick: () => void; +} + +export const ResponseOptionButton: FC = ({ + children, + accentColor, + selected = false, + disabled = false, + onClick, +}) => { + const theme = useTheme(); + return ( + + + {children} + + ); }; @@ -141,6 +330,15 @@ const AgentPauseShell: FC = ({ // ClarificationPanel (also handles `variant="explain"`) // --------------------------------------------------------------------------- +/** Options shown before a long list collapses behind "+N more". */ +const OPTION_PREVIEW_COUNT = 8; + +const OPTION_ICONS: Record = { + search_web: TravelExploreRoundedIcon, + connect: LinkRoundedIcon, + upload: UploadFileRoundedIcon, +}; + interface ClarificationPanelProps { questions: ClarificationQuestion[]; dataOperation?: DataOperation; @@ -172,14 +370,14 @@ interface ClarificationPanelProps { /** Close: de-highlight the pause and switch focus to the previous chart. */ onClose: () => void; /** Delete: remove this pending pause block. */ - onDelete: () => void; + onDelete?: () => void; } export const ClarificationPanel: FC = ({ questions, dataOperation, variant = 'clarify', - selectedAnswers, + selectedAnswers: controlledAnswers, onSelectAnswer, onClearAnswer, onSubmit, @@ -194,26 +392,26 @@ export const ClarificationPanel: FC = ({ // they answer. A question's own index holds its typed text; the sentinel // key -1 holds the explain variant's panel-level custom-followup override. const [freeTexts, setFreeTexts] = useState>({}); + const [localAnswers, setLocalAnswers] = useState>({}); + const [hasUsedSkip, setHasUsedSkip] = useState(false); + const [expandedOptions, setExpandedOptions] = useState>({}); + const selectedAnswers = controlledAnswers ?? localAnswers; useEffect(() => { submittedRef.current = false; setFreeTexts({}); + setLocalAnswers({}); + setHasUsedSkip(false); + setExpandedOptions({}); }, [questions]); const setFreeText = (key: number, value: string) => setFreeTexts(prev => ({ ...prev, [key]: value })); const isExplain = variant === 'explain'; - // Two-context color scheme, kept gentle. Each pause carries its own - // semantic hue (clarify=warning, explain=info) so the two read as distinct - // moments — but the hue only tints the quiet chrome (panel wash, border, - // chips, focus underline, field highlights, badge). The strong CTA (submit - // button) stays in the neutral brand primary so a clarify panel never - // shouts in aggressive amber. `chromeAccent` = the variant hue, used - // everywhere except the submit button (`submitAccent`). - const chromeAccent = isExplain - ? theme.palette.info.main - : theme.palette.warning.main; + // One quiet agent style for every message: questions and explanations share + // the brand hue (panel wash, border, chips, focus underline, highlights). + const chromeAccent = theme.palette.primary.main; const badgeAccent = chromeAccent; const submitAccent = theme.palette.primary.main; // Field highlights (`**name**` tokens) follow the variant hue too. @@ -239,12 +437,13 @@ export const ClarificationPanel: FC = ({ // A clarify panel auto-submits (on the click that completes it) only when // EVERY answer is a clicked option — a pure "click your way through" flow. // The moment any text answer is in play (a free_text question, or the user - // typed into a single_choice's "type your own" field), we show an explicit + // typed into a single_choice's "type your own" field), or a multi_choice + // question needs an explicit "done", we show an explicit // shared submit button instead, so a stray option click can never sweep up // an unfinished typed answer. The button belongs to the panel, not a row. - const hasFreeTextQuestion = !isExplain && questions.some(q => q.responseType === 'free_text'); + const needsExplicitSubmit = !isExplain && questions.some(q => q.responseType === 'free_text' || q.responseType === 'multi_choice'); const anyTextTyped = questions.some((_q, idx) => (freeTexts[idx] || '').trim().length > 0); - const showPanelSubmit = !isExplain && (hasFreeTextQuestion || anyTextTyped); + const showPanelSubmit = !isExplain && (needsExplicitSubmit || anyTextTyped || hasUsedSkip); // Gather the reply: each question's clicked option, else its typed // free-text; plus (explain only) the optional panel-level custom override. @@ -272,6 +471,11 @@ export const ClarificationPanel: FC = ({ // pick is invalidated the moment the user starts typing. const recordFreeText = (idx: number, value: string) => { setFreeText(idx, value); + setLocalAnswers(previous => { + const next = { ...previous }; + delete next[idx]; + return next; + }); const typed = value.trim(); if (typed) { onSelectAnswer?.(idx, { question_index: idx, answer: typed, source: 'free_text' }, false); @@ -308,9 +512,10 @@ export const ClarificationPanel: FC = ({ // sits at the end of the input line via an InputAdornment for tight // spacing rather than floating in its own column. const hasTypedAnswer = (freeTexts[idx] || '').trim().length > 0; + const isSkipped = selectedAnswers[idx]?.source === 'skip'; return ( - + recordFreeText(idx, e.target.value)} @@ -337,6 +542,45 @@ export const ClarificationPanel: FC = ({ sx={freeTextSx} /> + {questions[idx]?.responseType === 'free_text' && } {trailing && {trailing}} ); @@ -406,13 +650,40 @@ export const ClarificationPanel: FC = ({ setFreeText(response.question_index, ''); } if (onSelectAnswer) { - onSelectAnswer(response.question_index, response); + if (showPanelSubmit) onSelectAnswer(response.question_index, response, false); + else onSelectAnswer(response.question_index, response); + return; + } + if (showPanelSubmit) { + setLocalAnswers(previous => ({ ...previous, [response.question_index]: response })); return; } submitResponses([response]); }; - const title = t(isExplain ? 'chartRec.explanationTitle' : 'chartRec.clarificationTitle'); + // multi_choice: each click toggles one option; the answer lists the picks in option order. + const toggleMultiOption = (idx: number, label: string) => { + const current = selectedAnswers?.[idx]; + const picked = new Set(current?.source === 'option' ? current.selections ?? [] : []); + if (picked.has(label)) picked.delete(label); + else picked.add(label); + const selections = (questions[idx]?.options || []).map(option => option.label).filter(item => picked.has(item)); + if ((freeTexts[idx] || '').length > 0) setFreeText(idx, ''); + if (selections.length === 0) { + setLocalAnswers(previous => { + const next = { ...previous }; + delete next[idx]; + return next; + }); + onClearAnswer?.(idx); + return; + } + const response: ClarificationResponse = { question_index: idx, answer: selections.join(', '), selections, source: 'option' }; + setLocalAnswers(previous => ({ ...previous, [idx]: response })); + onSelectAnswer?.(idx, response, false); + }; + + const title = t('chartRec.agentTitle', { defaultValue: 'Agent' }); const selectedOperationResponse = dataOperation ? selectedAnswers?.[0] : undefined; const selectedPlanId = dataOperation?.plans.some( plan => plan.id === selectedOperationResponse?.value, @@ -431,10 +702,7 @@ export const ClarificationPanel: FC = ({ }; return ( } + icon={} accentColor={chromeAccent} title={title} closeTooltip={t('chartRec.pauseClose')} @@ -448,16 +716,11 @@ export const ClarificationPanel: FC = ({ {/* The finding that motivates the options; bounded like a question so long prose can't push them off-screen. */} {(dataOperation.description || questions[0]?.text) && ( - + {renderFieldHighlights(dataOperation.description || questions[0].text, accentColor)} - + )} = ({ {/* Text portion is height-bounded and scrollable so very long explanations don't push options off-screen. Options remain fixed below the scrolling region. */} - + {!isExplain && questions.length > 1 && ( <> @@ -512,7 +771,7 @@ export const ClarificationPanel: FC = ({ )} {renderFieldHighlights(question.text, accentColor)} - + {isFreeTextOnly ? ( // A free_text question is answered right here, with @@ -520,63 +779,71 @@ export const ClarificationPanel: FC = ({ renderQuestionField(questionIndex, t('chartRec.freeTextClarificationPlaceholder'), fieldTrailing) ) : ( - {showChips && (question.options || []).length > 0 && ( - <> - {isExplain && ( + {showChips && (question.options || []).length > 0 && (() => { + const options = question.options || []; + const isMulti = !isExplain && question.responseType === 'multi_choice'; + const selected = selectedAnswers?.[questionIndex]; + const isOptionSelected = (option: typeof options[number]) => selected?.source === 'option' + && (isMulti ? !!selected.selections?.includes(option.label) + : option.value ? selected.value === option.value : selected.answer === option.label); + // Collapse only when it hides at least two options; picks stay visible. + const collapsible = options.length > OPTION_PREVIEW_COUNT + 1; + const expanded = !collapsible || !!expandedOptions[questionIndex]; + const visible = expanded ? options + : options.filter((option, index) => index < OPTION_PREVIEW_COUNT || isOptionSelected(option)); + return <> + {(isExplain || isMulti) && ( - {t('chartRec.explanationFollowupsLabel')} + {isExplain ? t('chartRec.explanationFollowupsLabel') + : t('chartRec.multiChoiceLabel', { defaultValue: 'Select all that apply' })} )} - - {(question.options || []).map((option, optionIndex) => { - const selected = selectedAnswers?.[questionIndex]; - const isSelected = selected?.source === 'option' - && (option.value - ? selected.value === option.value - : selected.answer === option.label); - return ( - - handleAnswer({ - question_index: questionIndex, - answer: option.label, - ...(option.value ? { value: option.value } : {}), - source: 'option', - })} - sx={{ - position: 'relative', zIndex: 1, - px: '8px', py: '4px', - borderRadius: '6px', - border: `1px solid ${isSelected ? alpha(accentColor, 0.6) : alpha(theme.palette.text.primary, 0.12)}`, - backgroundColor: isSelected ? alpha(accentColor, 0.12) : theme.palette.background.paper, - cursor: 'pointer', - fontSize: textVar.xs, - fontWeight: isSelected ? 600 : 400, - display: 'inline-block', - whiteSpace: 'normal', - wordBreak: 'break-word', - lineHeight: 1.4, - color: theme.palette.text.primary, - textAlign: 'left', - fontFamily: theme.typography.fontFamily, - '&:hover': { backgroundColor: alpha(accentColor, isSelected ? 0.16 : 0.08) }, - }} - > - {renderFieldHighlights(option.label, accentColor)} - - - ); - })} + + {visible.map(option => ( + isMulti + ? toggleMultiOption(questionIndex, option.label) + : handleAnswer({ + question_index: questionIndex, + answer: option.label, + ...(option.value ? { value: option.value } : {}), + source: 'option', + })} + > + {isMulti && isOptionSelected(option) && } + {option.icon && (() => { + const OptionIcon = OPTION_ICONS[option.icon]; + return ; + })()} + {renderFieldHighlights(option.label, accentColor)} + + ))} + {collapsible && ( + setExpandedOptions(previous => ({ ...previous, [questionIndex]: !expanded }))} + sx={{ + px: '8px', py: '4px', borderRadius: 1.5, fontSize: textVar.xs, lineHeight: 1.4, + color: theme.palette.text.secondary, fontFamily: theme.typography.fontFamily, + '&:hover': { color: theme.palette.text.primary, textDecoration: 'underline' }, + }} + > + {expanded ? t('chartRec.showFewerOptions', { defaultValue: 'Show fewer' }) + : t('chartRec.showMoreOptions', { defaultValue: '+{{count}} more', count: options.length - visible.length })} + + )} - - )} + ; + })()} {/* single_choice questions also accept a typed answer (chips are shortcuts, not the only option). explain has no per-question freeform. */} @@ -631,8 +898,12 @@ interface ExplanationPanelProps { content: string; /** Close: de-highlight the panel and switch focus to the previous chart. */ onClose: () => void; - /** Delete: remove this explanation block from the thread. */ - onDelete: () => void; + /** Delete: remove this explanation block from the thread (absent while the answer is still being written). */ + onDelete?: () => void; + /** Open the message in the chat view, where a long answer reads in full. */ + onOpen?: () => void; + /** What the user answers under the message, inside the panel (a sign-in, design-docs/72). */ + children?: ReactNode; } /** @@ -642,30 +913,152 @@ interface ExplanationPanelProps { * but carries no inputs or actions — it's purely "here's what I said", * dismissible by the header's delete button or by focusing another item. */ -export const ExplanationPanel: FC = ({ content, onClose, onDelete }) => { +export const StepToolCall: FC<{ execution: TerminalExecution | CodeExecution }> = ({ execution }) => { + const { t } = useTranslation(); + const isCode = 'code' in execution; + const purpose = execution.purpose || t(isCode ? 'tool.pythonCode' : 'terminal.command', { + defaultValue: isCode ? 'Python code' : 'Command', + }); + // Expanded code and output read at the panel's body size, like an explanation. + return + {purpose} + + {t(`terminal.status.${execution.status}`, { defaultValue: execution.status })} + + {isCode ? + : } + ; +}; + +/** One tool call's code or command and result; steps through the other calls of its step. */ +export const ToolActivityPanel: FC<{ + execution: TerminalExecution | CodeExecution; + calls?: (TerminalExecution | CodeExecution)[]; + onSelect?: (execution: TerminalExecution | CodeExecution) => void; + onClose: () => void; +}> = ({ execution, calls = [], onSelect, onClose }) => { + const theme = useTheme(); + const { t } = useTranslation(); + const isCode = 'code' in execution; + const position = calls.findIndex(call => call.id === execution.id); + const step = (offset: number) => calls[position + offset] && onSelect?.(calls[position + offset]); + const navSx = { p: 0, width: 16, height: 16, color: theme.palette.text.secondary, '&:hover': { color: theme.palette.primary.main } }; + const headerActions = calls.length > 1 && position >= 0 && onSelect ? + step(-1)} sx={navSx} + aria-label={t('tool.previousCall', { defaultValue: 'Previous call' })}> + + + + {position + 1}/{calls.length} + + step(1)} sx={navSx} + aria-label={t('tool.nextCall', { defaultValue: 'Next call' })}> + + + : undefined; + + return + : } + accentColor={theme.palette.primary.main} + title={t(isCode ? 'tool.pythonCode' : 'terminal.command', { defaultValue: isCode ? 'Python code' : 'Command' })} + closeTooltip={t('chartRec.pauseClose')} + onClose={onClose} + headerActions={headerActions} + > + + + + ; +}; + +export const ExplanationPanel: FC = ({ content, onClose, onDelete, onOpen, children }) => { const theme = useTheme(); const { t } = useTranslation(); return ( } + icon={} accentColor={theme.palette.primary.main} - title={t('chartRec.explanationTitle')} + title={t('chartRec.agentTitle', { defaultValue: 'Agent' })} closeTooltip={t('chartRec.pauseClose')} deleteTooltip={t('chartRec.pauseDelete')} onClose={onClose} onDelete={onDelete} + headerActions={onOpen && + + + + } > - - + + + + {/* Outside the scroll region, so the controls stay in view under a long message; in the message's text size. */} + {children && {children}} + + ); +}; + +interface FailedDraftPanelProps { + prompt?: string; + error: string; + onClose: () => void; + onRetry: () => void; + retryDisabled?: boolean; + retryLabel?: string; +} + +/** Focused view for a retained failed analysis round. */ +export const FailedDraftPanel: FC = ({ + prompt, + error, + onClose, + onRetry, + retryDisabled = false, + retryLabel, +}) => { + const theme = useTheme(); + const { t } = useTranslation(); + const accent = theme.palette.error.main; + + return ( + } + accentColor={accent} + title={t('chartRec.interruptedTitle', { defaultValue: 'Interrupted' })} + closeTooltip={t('chartRec.pauseClose')} + onClose={onClose} + > + + {prompt && ( + + {prompt} + + )} + + {error} + + + + + {retryLabel || t('messages.retry', { defaultValue: 'Retry' })} + + ); diff --git a/src/views/AgentRulesDialog.tsx b/src/views/AgentRulesDialog.tsx deleted file mode 100644 index 84483975c..000000000 --- a/src/views/AgentRulesDialog.tsx +++ /dev/null @@ -1,392 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * AgentRulesDialog — knowledge-backed rules editor. - * - * Previously stored rules as plain text in Redux state. Now reads/writes - * rules as individual Markdown files via the Knowledge API. - * - * Each rule is a `.md` file under `knowledge/rules/`. - */ - -import React, { useState, useEffect, useCallback } from 'react'; -import { useTranslation } from 'react-i18next'; -import { useDispatch } from 'react-redux'; -import { - Button, - Typography, - Box, - DialogTitle, - Dialog, - DialogContent, - DialogActions, - IconButton, - useTheme, - Badge, - alpha, - CircularProgress, - List, - ListItemButton, - ListItemText, - ListItemSecondaryAction, - TextField, - Tooltip, -} from '@mui/material'; -import RuleIcon from '@mui/icons-material/Rule'; -import CloseIcon from '@mui/icons-material/Close'; -import AddIcon from '@mui/icons-material/Add'; -import DeleteOutlineIcon from '@mui/icons-material/DeleteOutline'; - -import { dfActions } from '../app/dfSlice'; -import { AppDispatch } from '../app/store'; -import { MarkdownEditor } from '../components/MarkdownEditor'; -import { radius, borderColor } from '../app/tokens'; -import { dialogHeight, iconVar, textVar } from '../app/layout'; -import { - listKnowledge, - readKnowledge, - writeKnowledge, - deleteKnowledge, - type KnowledgeItem, -} from '../api/knowledgeApi'; - -export const AgentRulesDialog: React.FC<{ - externalOpen?: boolean; - onExternalClose?: () => void; -}> = ({ externalOpen, onExternalClose }) => { - const { t } = useTranslation(); - const theme = useTheme(); - const dispatch = useDispatch(); - const [internalOpen, setInternalOpen] = useState(false); - const open = externalOpen !== undefined ? externalOpen : internalOpen; - - // Rules list - const [rules, setRules] = useState([]); - const [loading, setLoading] = useState(false); - const [ruleCount, setRuleCount] = useState(0); - - // Editor state - const [selectedRule, setSelectedRule] = useState(null); - const [editorContent, setEditorContent] = useState(''); - const [editorDirty, setEditorDirty] = useState(false); - const [originalContent, setOriginalContent] = useState(''); - const [editorLoading, setEditorLoading] = useState(false); - const [saving, setSaving] = useState(false); - - // Create new rule - const [creating, setCreating] = useState(false); - const [newFileName, setNewFileName] = useState(''); - - const fetchRules = useCallback(async () => { - setLoading(true); - try { - const items = await listKnowledge('rules'); - setRules(items); - setRuleCount(items.length); - } catch { - // best-effort - } finally { - setLoading(false); - } - }, []); - - useEffect(() => { - if (open) { - fetchRules(); - setSelectedRule(null); - setEditorContent(''); - setEditorDirty(false); - setCreating(false); - } - }, [open, fetchRules]); - - const handleSelectRule = useCallback(async (item: KnowledgeItem) => { - setSelectedRule(item); - setCreating(false); - setEditorLoading(true); - try { - const content = await readKnowledge('rules', item.path); - setEditorContent(content); - setOriginalContent(content); - setEditorDirty(false); - } catch { - setEditorContent(''); - setOriginalContent(''); - } finally { - setEditorLoading(false); - } - }, []); - - const handleSave = useCallback(async () => { - if (!selectedRule && !creating) return; - setSaving(true); - try { - const path = creating - ? (newFileName.endsWith('.md') ? newFileName : `${newFileName}.md`) - : selectedRule!.path; - await writeKnowledge('rules', path, editorContent); - dispatch(dfActions.addMessages({ - timestamp: Date.now(), - type: 'success', - component: 'agent-rules', - value: t('knowledge.saved'), - })); - setEditorDirty(false); - setOriginalContent(editorContent); - if (creating) { - setCreating(false); - setNewFileName(''); - } - await fetchRules(); - } catch { - dispatch(dfActions.addMessages({ - timestamp: Date.now(), - type: 'error', - component: 'agent-rules', - value: t('knowledge.failedToSave'), - })); - } finally { - setSaving(false); - } - }, [selectedRule, creating, newFileName, editorContent, fetchRules, dispatch, t]); - - const handleDeleteRule = useCallback(async (item: KnowledgeItem, e: React.MouseEvent) => { - e.stopPropagation(); - try { - await deleteKnowledge('rules', item.path); - dispatch(dfActions.addMessages({ - timestamp: Date.now(), - type: 'success', - component: 'agent-rules', - value: t('knowledge.deleted'), - })); - if (selectedRule?.path === item.path) { - setSelectedRule(null); - setEditorContent(''); - setEditorDirty(false); - } - await fetchRules(); - } catch { - dispatch(dfActions.addMessages({ - timestamp: Date.now(), - type: 'error', - component: 'agent-rules', - value: t('knowledge.failedToDelete'), - })); - } - }, [selectedRule, fetchRules, dispatch, t]); - - const handleStartCreate = useCallback(() => { - setCreating(true); - setSelectedRule(null); - setNewFileName(''); - setEditorContent(''); - setOriginalContent(''); - setEditorDirty(false); - }, []); - - const handleClose = () => { - if (onExternalClose) { - onExternalClose(); - } else { - setInternalOpen(false); - } - }; - - const codingPlaceholder = `# Rule Title - -Write your rule content here in Markdown. - -## Examples -- ROI should be computed as (revenue - cost) / cost. -- Date format should be YYYY-MM-DD. -`; - - return ( - <> - {externalOpen === undefined && ( - - - - )} - - - {t('agentRules.title')} - theme.palette.grey[500] }} - > - - - - - {/* Rules list */} - - - - {t('knowledge.rules')} - - - - - - - - {loading ? ( - - - - ) : ( - - {rules.map(rule => ( - handleSelectRule(rule)} - sx={{ - borderRadius: 1, py: 0.5, px: 1, mb: 0.25, - '&.Mui-selected': { - bgcolor: 'rgba(25, 118, 210, 0.08)', - boxShadow: 'inset 2px 0 0 rgba(25, 118, 210, 0.8)', - }, - '&:hover': { bgcolor: 'rgba(0, 0, 0, 0.045)' }, - }} - > - - - handleDeleteRule(rule, e)} - sx={{ p: 0.25, opacity: 0, '.MuiListItemButton-root:hover &': { opacity: 1 }, '&:hover': { color: 'error.main' } }} - > - - - - - ))} - {rules.length === 0 && !loading && ( - - {t('knowledge.noItems')} - - )} - - )} - - - {/* Editor */} - - {creating && ( - setNewFileName(e.target.value)} - sx={{ mb: 1, '& .MuiInputBase-input': { fontSize: textVar.sm } }} - slotProps={{ inputLabel: { sx: { fontSize: textVar.sm } } }} - /> - )} - {selectedRule && ( - - {selectedRule.title} - - {selectedRule.path} - - - )} - {editorLoading ? ( - - - - ) : (selectedRule || creating) ? ( - - { - setEditorContent(code); - setEditorDirty(code !== originalContent); - }} - placeholder={codingPlaceholder} - /> - - ) : ( - - - {t('knowledge.emptyState')} - - - )} - - - - - {(selectedRule || creating) && ( - - )} - - - - ); -}; diff --git a/src/views/AgentViewHost.tsx b/src/views/AgentViewHost.tsx new file mode 100644 index 000000000..6745181e6 --- /dev/null +++ b/src/views/AgentViewHost.tsx @@ -0,0 +1,183 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +/** + * Draws what the agent asked to `view` (the workspace skill's action), as the user sees it, and hands the pictures + * back: a chart's picture from the chart render service, a map drawn offscreen as for reports, an app run offscreen + * and captured from inside its frame. The run resumes with them (SimpleChartRecBox). + */ + +import React, { FC, Suspense, useEffect, useMemo, useRef, useState } from 'react'; +import { createPortal } from 'react-dom'; +import { Box } from '@mui/material'; +import { useSelector } from 'react-redux'; + +import { dfSelectors } from '../app/dfSlice'; +import { getCachedChart } from '../app/chartCache'; +import { readWorkspaceTextFile } from '../app/workspaceService'; +import type { AppCapture } from './AppSandbox'; +import type { ViewRequest, ViewResult } from './agentView'; +import { renderChartPng } from './ChartRenderService'; + +const MapSnapshot = React.lazy(() => import('../maps/MapSnapshot')); +const ReactAppPreview = React.lazy(() => import('./ReactAppPreview')); +const HtmlAppPreview = React.lazy(() => import('./HtmlAppPreview')); + +/** The size apps are run at for their picture, a laptop window. */ +const APP_WIDTH = 1280; +const APP_HEIGHT = 800; +/** A chart's picture counts as current once it has stopped changing for this long. */ +const CHART_SETTLE_MS = 800; +const CHART_TIMEOUT_MS = 20_000; +/** Everything is answered by then, drawn or not. */ +const VIEW_TIMEOUT_MS = 60_000; +/** Pictures are kept within this size (longest side) and length, so a run's request stays reasonable. */ +const MAX_SIDE = 1600; +const MAX_URL_CHARS = 3_000_000; +/** Sharper pictures (a `scale`, for sharing) are kept within this longest side. */ +const SHARP_MAX_SIDE = 4800; +/** Maps drawn sharper (for sharing) are drawn larger too, so the map has room beside its title and legends. */ +const SHARP_MAP_WIDTH = 960; +const SHARP_MAP_HEIGHT = 640; + +const message = (error: unknown) => error instanceof Error ? error.message : String(error); + +const toDataUrl = (url: string) => url.startsWith('data:') ? Promise.resolve(url) : fetch(url).then(response => response.blob()) + .then(blob => new Promise((resolve, reject) => { + const reader = new FileReader(); + reader.onload = () => resolve(String(reader.result)); + reader.onerror = () => reject(reader.error); + reader.readAsDataURL(blob); + })); + +/** A picture small enough to send: large ones are scaled down and, if still large, saved as JPEG. */ +async function fit(url: string): Promise<{ image: string; shrink: number }> { + const image = new Image(); + await new Promise((resolve, reject) => { image.onload = () => resolve(); image.onerror = reject; image.src = url; }); + const scale = Math.min(1, MAX_SIDE / Math.max(image.width, image.height, 1)); + if (scale === 1 && url.length <= MAX_URL_CHARS) return { image: url, shrink: 1 }; + const canvas = document.createElement('canvas'); + canvas.width = Math.max(1, Math.round(image.width * scale)); + canvas.height = Math.max(1, Math.round(image.height * scale)); + const context = canvas.getContext('2d')!; + context.fillStyle = '#ffffff'; + context.fillRect(0, 0, canvas.width, canvas.height); + context.drawImage(image, 0, 0, canvas.width, canvas.height); + const png = canvas.toDataURL('image/png'); + return { image: png.length <= MAX_URL_CHARS ? png : canvas.toDataURL('image/jpeg', 0.85), shrink: scale }; +} + +type Report = (result: Omit) => void; + +/** A chart's picture, once the render service has drawn its current version (drawn again at `scale`, if given). */ +const ChartShot: FC<{ id: string; report: Report; scale?: number }> = ({ id, report, scale }) => { + const chart = useSelector(dfSelectors.getAllCharts).find(item => item.id === id); + const drawable = !!chart && !['Table', 'Auto', '?'].includes(chart.chartType); + useEffect(() => { + if (!drawable) { + report({ error: chart ? `a ${chart.chartType} chart has no picture` : 'the chart is not in the session' }); + return; + } + let last: string | undefined; + let changed = 0; + // Only time the page is visible counts: a hidden page does not draw. + let elapsed = 0; + const timer = window.setInterval(() => { + if (document.visibilityState !== 'visible') return; + elapsed += 200; + const url = getCachedChart(id)?.fullPngDataUrl; + if (url !== last) { last = url; changed = elapsed; } + if (url && elapsed - changed >= CHART_SETTLE_MS) { + window.clearInterval(timer); + const entry = getCachedChart(id); + if (!scale || !entry?.spec) { report({ image: url, density: 2 }); return; } + const sharp = Math.min(scale, SHARP_MAX_SIDE / Math.max(entry.naturalWidth, entry.naturalHeight, 1)); + renderChartPng(entry.spec, sharp).then(image => report({ image, density: sharp }), + () => report({ image: url, density: 2 })); + } else if (elapsed > CHART_TIMEOUT_MS) { + window.clearInterval(timer); + report({ error: 'the chart was not drawn (its data may be missing)' }); + } + }, 200); + return () => window.clearInterval(timer); + }, [id, drawable]); + return null; +}; + +/** An app, run offscreen at a window's size and captured from inside its frame once it settles. */ +const AppShot: FC<{ name: string; report: Report; scale?: number }> = ({ name, report, scale }) => { + const [source, setSource] = useState(null); + const [script, setScript] = useState(null); + useEffect(() => { + let cancelled = false; + Promise.all([ + readWorkspaceTextFile(name).then(file => file.content), + import('../../node_modules/html-to-image/dist/html-to-image.js?raw').then(module => module.default as string), + ]).then(([content, library]) => { if (!cancelled) { setSource(content); setScript(library); } }, + error => { if (!cancelled) report({ error: message(error) }); }); + return () => { cancelled = true; }; + }, [name]); + const capture = useMemo(() => script ? { + script, scale, onImage: image => report({ image, density: scale ?? 1 }), onError: error => report({ error }), + } : undefined, [script, scale]); + if (source === null || !capture) return null; + const preview = name.toLowerCase().endsWith('.html') + ? + : ; + return createPortal( + + {preview} + , + document.body, + ); +}; + +/** + * Draws each item of a view request once, then answers with every result (in the request's order). With a + * `scale` (pixels per CSS pixel, for sharing) pictures are drawn that sharp and kept larger. + */ +export const AgentViewHost: FC<{ request: ViewRequest; onDone: (results: ViewResult[]) => void; scale?: number }> = ({ request, onDone, scale }) => { + const [results, setResults] = useState>({}); + const done = useRef(false); + const reporters = useMemo(() => Object.fromEntries(request.targets.map(target => [target.path, (result: Omit) => { + const settle = (value: Omit) => setResults(previous => previous[target.path] + ? previous : { ...previous, [target.path]: { path: target.path, ...value } }); + if (!result.image) settle(result); + else if (scale) toDataUrl(result.image).then(image => settle({ ...result, image }), error => settle({ error: message(error) })); + else toDataUrl(result.image).then(fit).then(({ image, shrink }) => settle({ image, ...(result.density ? { density: result.density * shrink } : {}) }), + error => settle({ error: message(error) })); + }])) as Record, [request, scale]); + useEffect(() => { + // Only time the page is visible counts (a hidden page does not draw). + let elapsed = 0; + const timer = window.setInterval(() => { + if (document.visibilityState === 'visible') elapsed += 500; + if (elapsed < VIEW_TIMEOUT_MS) return; + window.clearInterval(timer); + setResults(previous => Object.fromEntries(request.targets.map(target => + [target.path, previous[target.path] ?? { path: target.path, error: 'it did not finish drawing' }]))); + }, 500); + return () => window.clearInterval(timer); + }, [request]); + useEffect(() => { + if (done.current || !request.targets.every(target => results[target.path])) return; + done.current = true; + onDone(request.targets.map(target => results[target.path])); + }, [results, request, onDone]); + return + {request.targets.filter(target => !results[target.path]).map(target => target.kind === 'chart' && target.id + ? + : target.kind === 'map' + ? reporters[target.path]({ image: image.url, density: scale ? Math.min(scale, 3) : 2 })} + onError={error => reporters[target.path]({ error })} /> + : )} + ; +}; + +export default AgentViewHost; diff --git a/src/views/AllSessions.tsx b/src/views/AllSessions.tsx new file mode 100644 index 000000000..045993c6d --- /dev/null +++ b/src/views/AllSessions.tsx @@ -0,0 +1,345 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +/** + * Every session in a searchable dialog, behind a trigger each place draws its own way (`AllSessions`): the sidebar's + * "View all sessions" and the session name in the top bar. Also the pieces the sidebar's session list shares with + * it: day grouping, compact times, sorting, and the actions on a session (`useSessionActions`). + */ + +import React, { useCallback, useEffect, useMemo, useState } from 'react'; +import { Box, CircularProgress, Dialog, DialogContent, DialogTitle, IconButton, InputAdornment, TextField, Tooltip, + Typography } from '@mui/material'; +import CloseIcon from '@mui/icons-material/Close'; +import DeleteIcon from '@mui/icons-material/Delete'; +import DownloadIcon from '@mui/icons-material/Download'; +import EditIcon from '@mui/icons-material/Edit'; +import OpenInNewIcon from '@mui/icons-material/OpenInNew'; +import ScheduleOutlinedIcon from '@mui/icons-material/ScheduleOutlined'; +import SearchIcon from '@mui/icons-material/Search'; +import StarBorderRoundedIcon from '@mui/icons-material/StarBorderRounded'; +import StarRoundedIcon from '@mui/icons-material/StarRounded'; +import type { TFunction } from 'i18next'; +import { useTranslation } from 'react-i18next'; +import { useDispatch, useSelector } from 'react-redux'; +import i18n from '../i18n'; +import { AppDispatch } from '../app/store'; +import { DataFormulatorState, dfActions } from '../app/dfSlice'; +import { iconVar, textVar } from '../app/layout'; +import { metaText, weight } from '../app/tokens'; +import { openSession, renameSession } from '../app/sessionThunks'; +import { openSessionInNewTab } from '../app/sessionTabs'; +import { requestWormholeDialog } from '../app/wormholeService'; +import { deleteWorkspace, exportWorkspace, listWorkspaces, onWorkspaceListChanged, setWorkspaceStarred, + type WorkspaceSummary } from '../app/workspaceService'; +import { ItemCard, ItemCardAction, itemCardGridSx, StarAction, starredColor } from '../components/ItemCard'; +import { useProgressiveCount } from '../components/useProgressiveCount'; +import { WormholeReceiveIcon, WormholeSendIcon } from '../icons'; + +// Compact relative time for sidebar rows: "2m", "3h", "yesterday", +// "May 5", "May 5, 24". Designed to stay <= ~10 chars so it fits in +// the narrow sidebar without truncating session names. +export function formatCompactTime(iso: string | null | undefined): string { + if (!iso) return ''; + const then = new Date(iso); + const ts = then.getTime(); + if (Number.isNaN(ts)) return ''; + const now = Date.now(); + const diffSec = Math.max(0, Math.round((now - ts) / 1000)); + if (diffSec < 60) return i18n.t('sidebar.timeJustNow'); + const diffMin = Math.round(diffSec / 60); + if (diffMin < 60) return i18n.t('sidebar.timeMinutes', { count: diffMin }); + const diffHr = Math.round(diffMin / 60); + if (diffHr < 24) return i18n.t('sidebar.timeHours', { count: diffHr }); + const startOfToday = new Date(); startOfToday.setHours(0, 0, 0, 0); + const diffDays = Math.floor((startOfToday.getTime() - then.getTime()) / 86400000) + 1; + if (diffDays === 1) return i18n.t('sidebar.timeYesterday'); + if (diffDays < 7) return i18n.t('sidebar.timeDays', { count: diffDays }); + const sameYear = then.getFullYear() === new Date().getFullYear(); + return then.toLocaleDateString(undefined, sameYear + ? { month: 'short', day: 'numeric' } + : { month: 'short', day: 'numeric', year: '2-digit' }); +} + +export type SessionDateGroup = 'today' | 'yesterday' | 'week' | 'month' | 'older'; + +export function sessionDateGroup(iso: string | null | undefined): SessionDateGroup { + const ts = iso ? new Date(iso).getTime() : NaN; + if (Number.isNaN(ts)) return 'older'; + const startOfToday = new Date(); startOfToday.setHours(0, 0, 0, 0); + const days = Math.floor((startOfToday.getTime() - ts) / 86400000) + 1; + return days <= 0 ? 'today' : days === 1 ? 'yesterday' : days < 7 ? 'week' : days < 30 ? 'month' : 'older'; +} + +export const sessionGroupLabelsFor = (t: TFunction): Record => ({ + today: t('sidebar.groupToday', { defaultValue: 'Today' }), + yesterday: t('sidebar.groupYesterday', { defaultValue: 'Yesterday' }), + week: t('sidebar.groupWeek', { defaultValue: 'Previous 7 days' }), + month: t('sidebar.groupMonth', { defaultValue: 'Previous 30 days' }), + older: t('sidebar.groupOlder', { defaultValue: 'Older' }), +}); + +export const sessionGroupHeaderSx = { m: 0, pb: 0.5, fontWeight: weight(600), color: 'text.disabled', + ...metaText({ fontSize: textVar.xxs, textTransform: 'uppercase', letterSpacing: '0.04em' }) } as const; + +/** + * All sessions in a searchable dialog. With `groupTime`, sessions (already sorted by that time) + * fall under day ranges; without it (name order) they render as one grid. A star button filters to starred + * sessions once any session is starred; `starredOnly` opens with it on. + */ +export const SessionsDialog: React.FC<{ open: boolean; onClose: () => void; title: string; sessions: WorkspaceSummary[]; + groupTime?: (session: WorkspaceSummary) => string | null | undefined; renderCard: (session: WorkspaceSummary) => React.ReactNode; + starredOnly?: boolean; loading?: boolean }> + = ({ open, onClose, title, sessions, groupTime, renderCard, starredOnly: initialStarredOnly = false, loading = false }) => { + const { t } = useTranslation(); + const wormholeAvailable = useSelector((state: DataFormulatorState) => state.serverConfig?.SESSION_WORMHOLE_AVAILABLE === true); + const [query, setQuery] = useState(''); + const [starredOnly, setStarredOnly] = useState(initialStarredOnly); + useEffect(() => { if (open) setStarredOnly(initialStarredOnly); }, [open, initialStarredOnly]); + const anyStarred = sessions.some(s => s.starred); + const terms = query.trim().toLowerCase().split(/\s+/).filter(Boolean); + const matches = sessions.filter(s => (!starredOnly || !anyStarred || s.starred) + && terms.every(term => `${s.display_name} ${s.scheduled_run?.scheduleName ?? ''}`.toLowerCase().includes(term))); + const labels = sessionGroupLabelsFor(t); + // Cards are built only while the dialog shows (including its closing transition), not on every sidebar render. + const [shown, setShown] = useState(open); + if (open && !shown) setShown(true); + // Hundreds of cards would make opening and closing the dialog crawl; render them as the user scrolls. + const { count, sentinel } = useProgressiveCount(matches.length, { initial: 36, step: 36, resetKey: `${shown}|${starredOnly}|${query}` }); + const groups = (shown ? matches.slice(0, count) : []).reduce<{ group: SessionDateGroup | null; sessions: WorkspaceSummary[] }[]>((all, s) => { + const group = groupTime ? sessionDateGroup(groupTime(s)) : null; + const last = all[all.length - 1]; + if (last && last.group === group) last.sessions.push(s); + else all.push({ group, sessions: [s] }); + return all; + }, []); + return { setQuery(''); setShown(false); } } }}> + + {title} + {/* A received session lands in this list, so the dialog stays open behind the wormhole one. */} + {wormholeAvailable && + requestWormholeDialog({ kind: 'receive' })} + sx={{ color: 'text.secondary', ml: -1 }}> + + + } + + {anyStarred && + setStarredOnly(value => !value)} sx={{ color: starredOnly ? starredColor : 'text.disabled' }}> + {starredOnly ? : } + + } + setQuery(event.target.value)} + placeholder={t('sidebar.searchSessions', { defaultValue: 'Search sessions' })} + slotProps={{ htmlInput: { 'aria-label': t('sidebar.searchSessions', { defaultValue: 'Search sessions' }) }, + input: { startAdornment: } }} + sx={{ width: 260, '& .MuiInputBase-root': { fontSize: textVar.sm } }} /> + + + + + + {loading && sessions.length === 0 + ? + + + : matches.length === 0 + ? + {t('sidebar.noMatchingSessions', { defaultValue: 'No matching sessions' })} + : groups.map(({ group, sessions: groupSessions }, groupIndex) => + {group && {labels[group]}} + {groupSessions.map(renderCard)} + )} + {sentinel} + + ; +}; + +// ── Sorting ────────────────────────────────────────────────────────────────── + +/** Creation order by default, so auto-saves do not move older sessions; modified time is an explicit choice. */ +export type SessionSortKey = 'created_desc' | 'created_asc' | 'updated_desc' | 'name_asc'; + +export function sortSessions(sessions: WorkspaceSummary[], sort: SessionSortKey): WorkspaceSummary[] { + const cmpDate = (a: string | null | undefined, b: string | null | undefined): number => { + if (!a && !b) return 0; + if (!a) return 1; + if (!b) return -1; + return a.localeCompare(b); + }; + const copy = [...sessions]; + switch (sort) { + case 'created_desc': return copy.sort((a, b) => cmpDate(b.created_at, a.created_at)); + case 'created_asc': return copy.sort((a, b) => cmpDate(a.created_at, b.created_at)); + case 'updated_desc': return copy.sort((a, b) => + cmpDate(b.saved_at || b.created_at, a.saved_at || a.created_at) || cmpDate(b.created_at, a.created_at)); + case 'name_asc': return copy.sort((a, b) => (a.display_name || '').localeCompare(b.display_name || '')); + default: return copy; + } +} + +/** The time a sort orders by; time sorts group under day ranges, name order keeps a stamp per session. */ +export const sessionTimeFor = (sort: SessionSortKey) => (s: WorkspaceSummary) => + sort === 'created_desc' || sort === 'created_asc' ? s.created_at : (s.saved_at || s.created_at); + +export const sessionCountsText = (t: TFunction, s: WorkspaceSummary) => [ + s.table_count != null ? t('sidebar.tableCount', { count: s.table_count }) : '', + s.chart_count ? t('sidebar.chartCount', { count: s.chart_count }) : '', +].filter(Boolean).join(' · '); + +export const SessionBadges: React.FC<{ session: WorkspaceSummary }> = ({ session }) => <> + {session.scheduled_run && !session.scheduled_run.forked && + + } +; + +// ── Actions ────────────────────────────────────────────────────────────────── + +/** Open, star, rename, export and delete a session, for a list kept in `setSessions` (changed at once; `refresh` + * restores it when the server refuses). Deleting the open session opens the next one, or leaves for the landing + * page when none is left. */ +export function useSessionActions(setSessions: React.Dispatch>, refresh: () => void) { + const { t } = useTranslation(); + const dispatch = useDispatch(); + const activeWorkspace = useSelector((state: DataFormulatorState) => state.activeWorkspace); + const error = useCallback((value: string) => dispatch(dfActions.addMessages({ + timestamp: Date.now(), type: 'error', component: 'data-source-sidebar', value })), [dispatch]); + + const open = useCallback(async (sessionId: string, metaDisplayName?: string) => { + await dispatch(openSession(sessionId, metaDisplayName)); + }, [dispatch]); + + const rename = useCallback(async (id: string, next: string) => { + setSessions(prev => prev.map(s => (s.id === id ? { ...s, display_name: next } : s))); + try { + await dispatch(renameSession(id, next)); + } catch { + error(t('sidebar.failedRenameSession')); + refresh(); + } + }, [dispatch, error, refresh, setSessions, t]); + + const toggleStar = useCallback(async (session: WorkspaceSummary) => { + const starred = !session.starred; + setSessions(prev => prev.map(s => (s.id === session.id ? { ...s, starred } : s))); + try { + await setWorkspaceStarred(session.id, starred); + } catch { + error(t('workspace.starFailed')); + refresh(); + } + }, [error, refresh, setSessions, t]); + + const exportSession = useCallback(async (id: string, displayName: string) => { + try { + const blob = await exportWorkspace(id); + const a = document.createElement('a'); + a.href = URL.createObjectURL(blob); + a.download = `${displayName || id}.zip`; + a.click(); + URL.revokeObjectURL(a.href); + } catch { + error(t('sidebar.exportFailed')); + } + }, [error, t]); + + const remove = useCallback(async (sessionId: string) => { + try { + await deleteWorkspace(sessionId); + setSessions(prev => { + const updated = prev.filter(s => s.id !== sessionId); + // Deleting the open session switches to the next one up the list. + if (activeWorkspace?.id === sessionId) { + const deletedIndex = prev.findIndex(s => s.id === sessionId); + const nextSession = updated[Math.min(deletedIndex, updated.length - 1)]; + if (nextSession) void open(nextSession.id, nextSession.display_name); + else dispatch(dfActions.resetState()); + } + return updated; + }); + dispatch(dfActions.addMessages({ timestamp: Date.now(), type: 'success', component: 'data source sidebar', + value: t('sidebar.sessionDeleted') })); + } catch { + error(t('sidebar.failedDeleteSession')); + } + }, [activeWorkspace, dispatch, error, open, setSessions, t]); + + return { open, rename, toggleStar, exportSession, remove }; +} + +// ── All sessions ───────────────────────────────────────────────────────────── + +/** Every session in a dialog, opened by the caller's own `trigger`; it fetches the list when it opens, in `sort`'s + * order. */ +export const AllSessions: React.FC<{ trigger: (open: () => void) => React.ReactNode; sort?: SessionSortKey }> + = ({ trigger, sort = 'created_desc' }) => { + const { t } = useTranslation(); + const activeWorkspace = useSelector((state: DataFormulatorState) => state.activeWorkspace); + const wormholeAvailable = useSelector((state: DataFormulatorState) => state.serverConfig?.SESSION_WORMHOLE_AVAILABLE === true); + const [open, setOpen] = useState(false); + const [sessions, setSessions] = useState([]); + const [loading, setLoading] = useState(false); + const refresh = useCallback(() => { + setLoading(true); + listWorkspaces().then(setSessions).catch(() => { /* the list is best-effort */ }).finally(() => setLoading(false)); + }, []); + useEffect(() => { + if (!open) return; + refresh(); + return onWorkspaceListChanged(refresh); + }, [open, refresh]); + const actions = useSessionActions(setSessions, refresh); + const [renaming, setRenaming] = useState<{ id: string; draft: string } | null>(null); + const commitRename = () => { + const current = renaming && sessions.find(s => s.id === renaming.id); + const next = renaming?.draft.trim(); + setRenaming(null); + if (current && next && next !== current.display_name) void actions.rename(current.id, next); + }; + const sorted = useMemo(() => sortSessions(sessions, sort), [sessions, sort]); + const grouped = sort !== 'name_asc'; + const sessionTime = sessionTimeFor(sort); + const close = () => { setRenaming(null); setOpen(false); }; + + return <> + {trigger(() => setOpen(true))} + { + const isCurrent = activeWorkspace?.id === s.id; + return { close(); void actions.open(s.id, s.display_name); }} + onOpenInNewTab={() => openSessionInNewTab(s.id)} + rename={renaming?.id === s.id ? { value: renaming.draft, label: t('sidebar.rename', { defaultValue: 'Rename' }), + onChange: draft => setRenaming({ id: s.id, draft }), onCommit: commitRename, + onCancel: () => setRenaming(null) } : undefined} + badges={} + captions={[isCurrent ? t('sidebar.currentSession') : '', sessionCountsText(t, s), + grouped ? '' : formatCompactTime(sessionTime(s))]} + actions={(!s.read_only || !isCurrent) ? <> + {!isCurrent && } onClick={() => openSessionInNewTab(s.id)} />} + {!s.read_only && <> + void actions.toggleStar(s)} /> + } + onClick={() => setRenaming({ id: s.id, draft: s.display_name })} /> + } + onClick={() => void actions.exportSession(s.id, s.display_name)} /> + {wormholeAvailable && } + onClick={() => requestWormholeDialog({ kind: 'send', workspaceId: s.id, displayName: s.display_name })} />} + } + onClick={() => void actions.remove(s.id)} /> + } + : undefined} />; + }} /> + ; +}; diff --git a/src/views/AppSandbox.tsx b/src/views/AppSandbox.tsx new file mode 100644 index 000000000..01981bb05 --- /dev/null +++ b/src/views/AppSandbox.tsx @@ -0,0 +1,490 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +/** + * Host for sandboxed app artifacts (HTML and React). Runs the app document in an + * opaque-origin iframe inside a container that blocks navigation, serves the + * app's data queries for the tables its manifest declares, and shows errors with + * an optional "Ask agent to fix" action: an app that cannot render at all is + * replaced by a crash page, other errors show in a banner above the running app. + */ + +import React, { FC, useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import { useSelector } from 'react-redux'; +import { Alert, Box, Button, Checkbox, CircularProgress, Dialog, DialogActions, DialogContent, DialogTitle, FormControlLabel, Typography } from '@mui/material'; +import SentimentDissatisfiedOutlinedIcon from '@mui/icons-material/SentimentDissatisfiedOutlined'; +import { alpha, useTheme } from '@mui/material/styles'; +import { useTranslation } from 'react-i18next'; + +import { + APP_SANDBOX, + CONTAINER_DOCUMENT, + collectLinks, + collectRowLinks, + ignoredFieldsMessage, + normalizeAppQuery, + normalizeSelection, + stripRowIds, + webLink, + type HtmlAppManifest, + type HtmlAppTheme, +} from '../app/htmlApp/htmlAppDocument'; +import { apiRequest } from '../app/apiClient'; +import type { DataFormulatorState } from '../app/dfSlice'; +import { useLayout } from '../app/LayoutProvider'; +import { borderColorValue, readingTypography, paper, weight } from '../app/tokens'; +import { appLook } from '../app/look'; +import { getUrls } from '../app/utils'; + +const MAX_CONCURRENT_QUERIES = 4; +const MAX_QUEUED_QUERIES = 100; +const MAX_ERRORS = 3; +export const APP_PALETTE = ['#4c78a8', '#f58518', '#e45756', '#72b7b2', '#54a24b', '#eeca3b', '#b279a2', '#ff9da6', '#9d755d', '#bab0ac']; + +type QueryJob = + | { kind: 'query'; id: number; table: unknown; options: unknown } + | { kind: 'sql'; id: number; sql: unknown; params: unknown; options: unknown } + | { kind: 'source'; id: number; source: unknown; query: unknown; options: unknown }; + +/** A connected source an app declared, as the backend addresses it. */ +export type AppSource = { connectorId: string; tableKey: string }; + +const requestLimit = (options: unknown): number | undefined => { + const limit = options && typeof options === 'object' ? (options as { limit?: unknown }).limit : undefined; + return typeof limit === 'number' && Number.isInteger(limit) ? limit : undefined; +}; + +const newChannel = () => (globalThis.crypto?.randomUUID?.() ?? `${Date.now()}-${Math.random()}`); + +/** Open a web page outside the app; a plain link also takes the desktop wrapper's system-browser route. */ +const openWebLink = (href: string) => { + const link = document.createElement('a'); + link.href = href; + link.target = '_blank'; + link.rel = 'noopener noreferrer'; + document.body.appendChild(link); + link.click(); + link.remove(); +}; + +/** + * Results the app could not have composed text in: plain table queries and structured source + * queries. SQL and native source queries can build any string, such as an address carrying data. + */ +const servesStoredValues = (job: QueryJob) => job.kind === 'query' + || (job.kind === 'source' && !(job.query && typeof job.query === 'object' && 'native' in job.query)); + +/** DF's design tokens for apps, following the active palette and density. */ +export function useAppTheme(): HtmlAppTheme { + const muiTheme = useTheme(); + const { density, tokens } = useLayout(); + return useMemo(() => { + const palette = muiTheme.palette as unknown as Record; + // A dark look's page and panels; the light looks keep the kit's white tiles on a pale page. + const dark = muiTheme.palette.mode === 'dark'; + return { + font: readingTypography.fontFamily, + fontMono: getComputedStyle(document.documentElement).getPropertyValue('--df-font-mono').trim() || 'ui-monospace, monospace', + text: muiTheme.palette.text.primary, + muted: muiTheme.palette.text.secondary, + bg: dark ? muiTheme.palette.background.paper : '#ffffff', + canvas: dark ? muiTheme.palette.background.default : '#f6f7f9', + surface: dark ? muiTheme.palette.background.paper : '#ffffff', + border: dark ? muiTheme.palette.divider : borderColorValue.divider, + primary: muiTheme.palette.primary.main, + primarySoft: palette.primary.bgcolor ?? alpha(muiTheme.palette.primary.main, 0.1), + primaryText: palette.primary.textColor ?? muiTheme.palette.primary.main, + secondary: muiTheme.palette.secondary.main, + accent: palette.custom?.main ?? muiTheme.palette.secondary.main, + positive: muiTheme.palette.success.main, + negative: muiTheme.palette.error.main, + warning: muiTheme.palette.warning.main, + textSize: { xxs: tokens.text.xxs, xs: tokens.text.xs, sm: tokens.text.sm, md: tokens.text.md, lg: tokens.text.lg, xl: tokens.text.xl, xxl: tokens.text.xxl }, + palette: APP_PALETTE, + lookVars: appLook(muiTheme).vars, + }; + // Tokens only change with density; the object identity changes on every resize. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [muiTheme, density]); +} + +export interface AppSandboxProps { + title: string; + manifest: HtmlAppManifest; + /** Build the app document for a bridge channel; null when the app cannot run. */ + buildDocument: ((channel: string) => string) | null; + /** Errors known before the app runs (e.g. compile errors); the app cannot render. */ + initialErrors?: string[]; + reloadKey?: number; + /** Leave room in the error banner for controls floating over the app. */ + reserveTopRight?: boolean; + /** Offer "Ask agent to fix" with the current errors. */ + onAskFix?: (errors: string[]) => void; + /** + * The agent just wrote this app: if it fails when it opens, ask the agent to fix it right away and + * show that it is being fixed instead of the broken app. + */ + autoFix?: boolean; + /** The app opened without errors (only reported with `autoFix`). */ + onHealthy?: () => void; + /** The agent is working (or about to): an automatic repair is still on its way. */ + fixPending?: boolean; + /** Resolve a source the app declared (an external reference id) for live queries. */ + resolveSource?: (source: string) => AppSource | undefined; + /** The session the app's queries read (by default the open one), e.g. a sample shown outside its session. */ + workspaceId?: string; + /** Draw the app as a picture once it has loaded its data and gone quiet (for the agent's view requests): + * `script` is the capture library's source, which the app frame cannot load itself; the preview builds it into + * the app document, so no code is ever sent to the frame in a message. */ + capture?: AppCapture; + /** The app's code: web addresses written in it, like those in table data it reads, open without asking. */ + linkSource?: string; +} + +export interface AppCapture { + script: string; + /** Pixels per CSS pixel of the picture (1 by default). */ + scale?: number; + onImage: (dataUrl: string) => void; + onError: (message: string) => void; +} + +/** An app is captured once it has gone this long without a data request (and has run at least as long). */ +const CAPTURE_QUIET_MS = 1200; +/** An app that never goes quiet (or never starts) is not captured. */ +const CAPTURE_TIMEOUT_MS = 30_000; + +/** Errors within this long after an app opens are failures of the app as written, not of later use. */ +const AUTO_FIX_WINDOW_MS = 8000; + +export const AppSandbox: FC = ({ title, manifest, buildDocument, initialErrors, reloadKey = 0, reserveTopRight = false, onAskFix, + autoFix = false, onHealthy, fixPending = false, resolveSource, workspaceId, capture, linkSource }) => { + const { t } = useTranslation(); + const containerRef = useRef(null); + const [containerReady, setContainerReady] = useState(false); + const [errors, setErrors] = useState([]); + const [stopped, setStopped] = useState(false); + // The app cannot render at all: it did not compile, failed to start, or crashed. + const [fatal, setFatal] = useState(false); + const [askedFix, setAskedFix] = useState(false); + // The app failed when it opened and the agent was asked to fix it: show that, not the broken app. + const [autoFixing, setAutoFixing] = useState(false); + const [openedAt, setOpenedAt] = useState(0); + // Read when a query runs, so a change to the session's sources does not reload the app. + const resolveSourceRef = useRef(resolveSource); + resolveSourceRef.current = resolveSource; + const captureRef = useRef(capture); + captureRef.current = capture; + const linkSourceRef = useRef(linkSource); + linkSourceRef.current = linkSource; + // A web address the app asked to open that it may have built itself: the user decides. + const [pendingLink, setPendingLink] = useState(null); + const [trustSite, setTrustSite] = useState(false); + // Sites the user chose to open without asking, for as long as this app runs. + const trustedSitesRef = useRef(new Set()); + useEffect(() => { + const containerWindow = containerRef.current?.contentWindow; + const containerDocument = containerRef.current?.contentDocument; + setErrors(initialErrors ?? []); + setFatal(!!initialErrors?.length); + setAskedFix(false); + setAutoFixing(false); + setOpenedAt(Date.now()); + setStopped(false); + setPendingLink(null); + trustedSitesRef.current = new Set(); + if (initialErrors?.length) captureRef.current?.onError(initialErrors[0]); + if (!containerReady || !containerWindow || !containerDocument || !buildDocument) return; + let disposed = false; + let loads = 0; + let active = 0; + const queue: QueryJob[] = []; + const channel = newChannel(); + // Addresses the app cannot have built from data: written in its code or read from stored values. + const knownLinks = new Set(); + collectLinks(linkSourceRef.current ?? '', knownLinks); + // Capturing for a view request: when the app last asked for data, and whether it was captured. + let startedAt = Date.now(); + let hiddenSince: number | undefined; + let lastActivity = startedAt; + let captured = false; + const captureId = newChannel(); + const finishCapture = (result: { image?: string; error?: string }) => { + if (captured) return; + captured = true; + window.clearInterval(captureTimer); + if (result.image) captureRef.current?.onImage(result.image); + else captureRef.current?.onError(result.error || 'The app could not be drawn.'); + }; + const captureTimer = captureRef.current === undefined ? undefined : window.setInterval(() => { + const request = captureRef.current; + if (!request || captured || disposed) return; + const now = Date.now(); + // A hidden page does not lay out, so charts sized to their container are not drawn: only time spent + // visible counts, toward going quiet and toward giving up. + if (document.visibilityState !== 'visible') { + hiddenSince = hiddenSince ?? now; + return; + } + if (hiddenSince !== undefined) { + startedAt += now - hiddenSince; + if (lastActivity !== Infinity) lastActivity = now; + hiddenSince = undefined; + } + if (now - startedAt > CAPTURE_TIMEOUT_MS) { + finishCapture({ error: 'The app did not finish loading.' }); + } else if (!active && !queue.length && now - lastActivity >= CAPTURE_QUIET_MS && now - startedAt >= CAPTURE_QUIET_MS) { + lastActivity = Infinity; + post({ type: 'capture', id: captureId, scale: request.scale }); + } + }, 250); + + const frame = containerDocument.createElement('iframe'); + frame.setAttribute('sandbox', APP_SANDBOX); + frame.setAttribute('referrerpolicy', 'no-referrer'); + frame.setAttribute('title', manifest.title || title); + + const post = (message: Record) => { + if (!disposed) frame.contentWindow?.postMessage({ dfApp: channel, ...message }, '*'); + }; + const reportError = (message: string) => { + if (!disposed) setErrors(current => current.includes(message) ? current : [...current, message].slice(-MAX_ERRORS)); + }; + /** Validate a job against the manifest and turn it into an API request; throws for app bugs. */ + const toRequest = (job: QueryJob): { label: string; url: string; body: unknown } => { + if (job.kind === 'query') { + return { label: 'DF.query', url: getUrls().SAMPLE_TABLE, body: normalizeAppQuery(job.table, job.options, manifest) }; + } + if (job.kind === 'sql') { + if (typeof job.sql !== 'string' || !job.sql.trim()) throw new Error('Pass the SQL text to run.'); + if (!manifest.tables.length) throw new Error('Declare the tables the SQL reads in the app manifest.'); + if (!Array.isArray(job.params) || job.params.length > 100) throw new Error('params must be a list of at most 100 values.'); + const selection = (job.options as { selection?: unknown } | undefined)?.selection; + return { label: 'DF.sql', url: getUrls().APP_SQL, body: { + tables: manifest.tables, sql: job.sql, params: job.params, limit: requestLimit(job.options), + ...(selection !== undefined && selection !== null ? { selection: normalizeSelection(selection) } : {}) } }; + } + const declared = typeof job.source === 'string' && (manifest.sources ?? []).includes(job.source); + const target = declared ? resolveSourceRef.current?.(job.source as string) : undefined; + if (!declared) throw new Error(`Source "${String(job.source)}" is not declared in the app manifest.`); + if (!target) throw new Error(`Source "${String(job.source)}" is not connected in this session.`); + return { label: 'DF.sourceQuery', url: getUrls().APP_SOURCE_QUERY, body: { + connector_id: target.connectorId, table_key: target.tableKey, query: job.query ?? {}, limit: requestLimit(job.options) } }; + }; + const pump = () => { + while (!disposed && active < MAX_CONCURRENT_QUERIES && queue.length) { + const job = queue.shift()!; + active += 1; + let request: ReturnType; + try { + request = toRequest(job); + } catch (error) { + active -= 1; + // Invalid queries are app bugs; surface them even if the app catches the rejection. + const label = job.kind === 'query' ? 'DF.query' : job.kind === 'sql' ? 'DF.sql' : 'DF.sourceQuery'; + reportError(`${label}: ${(error as Error).message}`); + post({ type: 'result', id: job.id, error: (error as Error).message }); + continue; + } + apiRequest<{ rows: unknown; total_row_count?: number; truncated?: boolean; ignored_fields?: { field: string; use: string }[]; + unlinked_fields?: string[]; filterable_columns?: string[] }>(request.url, { + method: 'POST', + headers: { 'Content-Type': 'application/json', ...(workspaceId ? { 'X-Workspace-Id': workspaceId } : {}) }, + body: JSON.stringify(request.body), + }) + .then(({ data }) => { + const rows = stripRowIds(data.rows); + if (servesStoredValues(job)) collectRowLinks(rows, knownLinks); + if (job.kind === 'query' && data.ignored_fields?.length) reportError(ignoredFieldsMessage(job.table, data.ignored_fields)); + post({ type: 'result', id: job.id, rows, totalRowCount: data.total_row_count ?? (Array.isArray(rows) ? rows.length : 0), + ...(data.truncated !== undefined ? { truncated: data.truncated } : {}), + ...(Array.isArray(data.unlinked_fields) ? { unlinked: data.unlinked_fields } : {}), + ...(Array.isArray(data.filterable_columns) ? { filterable: data.filterable_columns } : {}) }); + }) + .catch(error => { + const message = error instanceof Error ? error.message : 'Query failed'; + reportError(`${request.label}: ${message}`); + post({ type: 'result', id: job.id, error: message }); + }) + .finally(() => { active -= 1; if (lastActivity !== Infinity) lastActivity = Date.now(); pump(); }); + } + }; + const onMessage = (event: MessageEvent) => { + if (disposed || event.source !== frame.contentWindow) return; + const data = event.data; + if (!data || typeof data !== 'object' || data.dfApp !== channel) return; + if (data.type === 'hello') { + post({ type: 'init' }); + if (lastActivity !== Infinity) lastActivity = Date.now(); + } else if (data.type === 'openExternal') { + const url = webLink(data.url); + if (!url) { + reportError('Only absolute HTTP(S) web links without embedded credentials can be opened.'); + return; + } + // A click in the app frame activates this page too. Without the API (older WebKit), ask instead. + const clicked = navigator.userActivation?.isActive; + if (clicked === false) { + reportError('External links must be opened by a user click.'); + } else if (clicked && (knownLinks.has(url.href) || trustedSitesRef.current.has(url.origin))) { + openWebLink(url.href); + } else { + setTrustSite(false); + setPendingLink(url); + } + } else if (data.type === 'captured' && data.id === captureId) { + finishCapture({ image: typeof data.image === 'string' && data.image.startsWith('data:image/png') ? data.image : undefined, + error: typeof data.error === 'string' ? data.error : undefined }); + } else if ((data.type === 'query' || data.type === 'sql' || data.type === 'source') && typeof data.id === 'number') { + if (queue.length >= MAX_QUEUED_QUERIES) { + post({ type: 'result', id: data.id, error: t('htmlApp.tooManyQueries') }); + return; + } + queue.push(data.type === 'query' ? { kind: 'query', id: data.id, table: data.table, options: data.options } + : data.type === 'sql' ? { kind: 'sql', id: data.id, sql: data.sql, params: data.params, options: data.options } + : { kind: 'source', id: data.id, source: data.source, query: data.query, options: data.options }); + if (lastActivity !== Infinity) lastActivity = Date.now(); + pump(); + } else if (data.type === 'error') { + reportError(String(data.message || '').slice(0, 500)); + if (data.fatal === true && !disposed) { + setFatal(true); + finishCapture({ error: String(data.message || 'The app crashed.').slice(0, 300) }); + } + } + }; + frame.addEventListener('load', () => { + loads += 1; + // A second load means the app navigated; navigation away is blocked + // by the container CSP, so stop serving data to whatever loaded. + if (loads > 1 && !disposed) { + disposed = true; + frame.remove(); + setStopped(true); + } + }); + containerWindow.addEventListener('message', onMessage); + frame.srcdoc = buildDocument(channel); + containerDocument.body.appendChild(frame); + return () => { + disposed = true; + window.clearInterval(captureTimer); + queue.length = 0; + containerWindow.removeEventListener('message', onMessage); + frame.remove(); + }; + }, [containerReady, buildDocument, initialErrors, manifest, title, reloadKey, t, workspaceId]); + + const askFix = onAskFix && !askedFix ? () => { setAskedFix(true); onAskFix(errors); } : undefined; + + // An app the agent just wrote that fails when it opens goes straight back to the agent. + const onAskFixRef = useRef(onAskFix); + onAskFixRef.current = onAskFix; + const onHealthyRef = useRef(onHealthy); + onHealthyRef.current = onHealthy; + useEffect(() => { + if (!autoFix || askedFix || stopped || !errors.length || !onAskFixRef.current) return; + if (!fatal && Date.now() - openedAt > AUTO_FIX_WINDOW_MS) return; + setAskedFix(true); + setAutoFixing(true); + onAskFixRef.current(errors); + }, [autoFix, askedFix, stopped, errors, fatal, openedAt]); + useEffect(() => { + if (!autoFix || !buildDocument || errors.length) return; + const timer = setTimeout(() => onHealthyRef.current?.(), AUTO_FIX_WINDOW_MS); + return () => clearTimeout(timer); + }, [autoFix, buildDocument, errors.length, openedAt]); + // The agent finished without changing the app: show its errors (and the button to ask again). + useEffect(() => { + if (!autoFixing || fixPending) return; + const timer = setTimeout(() => setAutoFixing(false), 2000); + return () => clearTimeout(timer); + }, [autoFixing, fixPending]); + + return ( + + {!fatal && !autoFixing && (errors.length > 0 || stopped) && ( + + {askedFix ? t('htmlApp.askedAgentToFix', { defaultValue: 'Sent to the agent' }) : t('htmlApp.askAgentToFix')} : undefined} + sx={{ flexShrink: 0, borderRadius: 0, pr: reserveTopRight ? 19 : 2, '& .MuiAlert-message': { minWidth: 0 } }}> + {stopped ? t('htmlApp.navigationBlocked') : <> + {t('htmlApp.appError')} + {errors.map(message => {message})} + } + + )} + +