From 0b5c22b79a75f7699c510550c90a689dddab1538 Mon Sep 17 00:00:00 2001 From: wsp Date: Sat, 14 Nov 2026 16:23:33 +0800 Subject: [PATCH] fix(web-ui): Clear lint and check failures Separate component exports from helpers, contexts, and registries so Fast Refresh boundaries no longer produce lint warnings. Preserve settings search invalidation when translation resources change. Clean up regex escapes and clipboard declarations, document intentional control-character sanitization, and use a semantic dialog leading token without changing its default value. Validation: lint:web, check:web, focused Web UI regressions, and all 12 Dialog and ConfirmDialog package tests pass. Remote coverage uses simulated Peer fixtures; live remote scenarios were not exercised. --- .../src/components/Dialog/Dialog.module.css | 2 +- .../DesktopCardCustomFrame.test.ts | 2 +- .../DesktopCard/DesktopCardCustomFrame.tsx | 117 +----- .../DesktopCard/desktopCardSrcDoc.ts | 112 ++++++ .../devices/BackgroundSessionList.tsx | 3 +- .../sections/devices/CatalogSessionMenu.tsx | 27 +- .../sections/devices/catalogSessionActions.ts | 28 ++ .../panels/content-canvas/CanvasToolbar.tsx | 16 +- .../panels/content-canvas/ContentCanvas.tsx | 3 +- .../content-canvas/canvasToolbarContext.ts | 15 + .../src/app/scenes/settings/SettingsNav.tsx | 7 +- .../pages/ai/OpenCodeModelQuota.test.ts | 2 +- .../settings/pages/ai/OpenCodeModelQuota.tsx | 8 +- .../pages/ai/openCodeQuotaEligibility.ts | 9 + .../src/flow_chat/components/FlowToolCard.tsx | 2 +- .../components/WindowedCodeContent.test.tsx | 3 +- .../components/WindowedCodeContent.tsx | 25 +- .../components/btw/BtwVirtualSessionList.tsx | 2 +- .../flow_chat/components/codeLineMetrics.ts | 23 ++ .../components/modern/TurnFooter.test.tsx | 3 +- .../components/modern/VirtualItemRenderer.tsx | 2 +- .../components/modern/VirtualMessageList.tsx | 2 +- .../subagent/SubagentProjectionView.tsx | 3 +- .../ConversationExcerptMarkers.test.tsx | 3 +- .../selection/ConversationExcerptMarkers.tsx | 111 +----- .../useConversationExcerptMarkers.tsx | 110 ++++++ .../timeline/FlowChatReaderProvider.tsx | 10 + .../src/flow_chat/timeline/readerContexts.ts | 5 + .../timeline/readerLifecycle.test.tsx | 3 +- .../{readerState.tsx => readerState.ts} | 11 +- .../tool-cards/ModelThinkingDisplay.test.tsx | 3 +- .../file-export/saveHtmlFile.ts | 2 + .../markdown/remarkStreamingTableLinks.ts | 2 +- .../commands/builtin/PasteCommand.ts | 4 +- .../src/shared/utils/ModuleLoadFailure.tsx | 33 ++ .../src/shared/utils/lazyWithRecovery.tsx | 34 +- .../tools/editor/languages/latex.language.ts | 2 +- .../tools/generative-ui/GenUIApplication.tsx | 4 +- .../generative-ui/GenUIHtmlDocument.test.tsx | 2 +- .../tools/generative-ui/GenUIHtmlDocument.tsx | 334 +----------------- .../generative-ui/GenUISourceDocument.tsx | 2 +- .../components/oiComponentHelpers.tsx | 88 +++++ .../components/oiComponentRenderers.tsx | 198 +++++++++++ .../generative-ui/components/oiComponents.tsx | 287 +-------------- .../generative-ui/components/openui/extra.tsx | 2 +- .../components/openui/inlineMarkdown.tsx | 44 +++ .../components/openui/markdown.tsx | 45 +-- .../generative-ui/components/openui/svg.tsx | 2 - .../components/openui/svgComponents.ts | 3 + .../generative-ui/components/openui/table.tsx | 2 +- .../generative-ui/components/openui/text.tsx | 3 +- .../components/openuiLibrary.tsx | 2 +- .../tools/generative-ui/genUIHtmlSource.ts | 334 ++++++++++++++++++ .../src/tools/generative-ui/genUILayout.ts | 2 +- .../tools/generative-ui/genUIOpenUI.test.tsx | 3 +- .../src/tools/generative-ui/genUIOpenUI.tsx | 39 +- .../tools/generative-ui/genUIOpenUISchema.ts | 39 ++ 57 files changed, 1119 insertions(+), 1065 deletions(-) create mode 100644 src/web-ui/src/app/components/DesktopCard/desktopCardSrcDoc.ts create mode 100644 src/web-ui/src/app/components/NavPanel/sections/devices/catalogSessionActions.ts create mode 100644 src/web-ui/src/app/components/panels/content-canvas/canvasToolbarContext.ts create mode 100644 src/web-ui/src/app/scenes/settings/pages/ai/openCodeQuotaEligibility.ts create mode 100644 src/web-ui/src/flow_chat/components/codeLineMetrics.ts create mode 100644 src/web-ui/src/flow_chat/selection/useConversationExcerptMarkers.tsx create mode 100644 src/web-ui/src/flow_chat/timeline/FlowChatReaderProvider.tsx create mode 100644 src/web-ui/src/flow_chat/timeline/readerContexts.ts rename src/web-ui/src/flow_chat/timeline/{readerState.tsx => readerState.ts} (91%) create mode 100644 src/web-ui/src/shared/utils/ModuleLoadFailure.tsx create mode 100644 src/web-ui/src/tools/generative-ui/components/oiComponentHelpers.tsx create mode 100644 src/web-ui/src/tools/generative-ui/components/oiComponentRenderers.tsx create mode 100644 src/web-ui/src/tools/generative-ui/components/openui/inlineMarkdown.tsx create mode 100644 src/web-ui/src/tools/generative-ui/components/openui/svgComponents.ts create mode 100644 src/web-ui/src/tools/generative-ui/genUIHtmlSource.ts create mode 100644 src/web-ui/src/tools/generative-ui/genUIOpenUISchema.ts diff --git a/design-system/packages/ui/src/components/Dialog/Dialog.module.css b/design-system/packages/ui/src/components/Dialog/Dialog.module.css index c7e4308360..a523b48397 100644 --- a/design-system/packages/ui/src/components/Dialog/Dialog.module.css +++ b/design-system/packages/ui/src/components/Dialog/Dialog.module.css @@ -74,7 +74,7 @@ font-family: var(--openbitfun-type-heading-section-font-family); font-size: var(--openbitfun-type-heading-section-font-size); font-weight: var(--openbitfun-type-heading-section-font-weight); - line-height: var(--openbitfun-line-height-snug); + line-height: var(--openbitfun-type-modifier-leading-snug-line-height); letter-spacing: var(--openbitfun-type-heading-section-letter-spacing); white-space: normal; overflow-wrap: anywhere; diff --git a/src/web-ui/src/app/components/DesktopCard/DesktopCardCustomFrame.test.ts b/src/web-ui/src/app/components/DesktopCard/DesktopCardCustomFrame.test.ts index 8b23b781e0..ab1d034d81 100644 --- a/src/web-ui/src/app/components/DesktopCard/DesktopCardCustomFrame.test.ts +++ b/src/web-ui/src/app/components/DesktopCard/DesktopCardCustomFrame.test.ts @@ -1,7 +1,7 @@ import { readFileSync } from 'node:fs'; import { describe, expect, it } from 'vitest'; -import { buildDesktopCardSrcDoc, DESKTOP_CARD_WIDGET_CSS } from './DesktopCardCustomFrame'; +import { buildDesktopCardSrcDoc, DESKTOP_CARD_WIDGET_CSS } from './desktopCardSrcDoc'; const TOOL_SOURCE = readFileSync( new URL('../../../../../../src/crates/assembly/core/src/agentic/tools/implementations/desktop_card_tool.rs', import.meta.url), diff --git a/src/web-ui/src/app/components/DesktopCard/DesktopCardCustomFrame.tsx b/src/web-ui/src/app/components/DesktopCard/DesktopCardCustomFrame.tsx index 5ea2ad6040..87069440f9 100644 --- a/src/web-ui/src/app/components/DesktopCard/DesktopCardCustomFrame.tsx +++ b/src/web-ui/src/app/components/DesktopCard/DesktopCardCustomFrame.tsx @@ -1,18 +1,7 @@ import React, { useEffect, useMemo, useRef, useState } from 'react'; import { widgetAppearanceAdapter } from '@/infrastructure/appearance/adapters/WidgetAppearanceAdapter'; -import { - createWidgetAppearanceFallbackCss, - readWidgetAppearancePayload, -} from '@/tools/generative-widget/appearancePayload'; - -const FRAME_MESSAGE_SOURCE = 'openbitfun-desktop-card'; -const HOST_MESSAGE_SOURCE = 'openbitfun-desktop-card-host'; - -export interface DesktopCardCustomPayload { - data: unknown; - card: { id: string; title: string; subtitle?: string }; - error?: string; -} +import { readWidgetAppearancePayload } from '@/tools/generative-widget/appearancePayload'; +import { buildDesktopCardSrcDoc, FRAME_MESSAGE_SOURCE, HOST_MESSAGE_SOURCE, type DesktopCardCustomPayload, type DesktopCardWidgetAppearance } from './desktopCardSrcDoc'; interface DesktopCardCustomFrameProps { html: string; @@ -21,113 +10,11 @@ interface DesktopCardCustomFrameProps { onOpenLink: (url: string) => void; } -// The widget runs in an opaque-origin sandbox and talks to the card only through this bridge. -const BRIDGE_SCRIPT = `(function () { - var handlers = []; - var latest = null; - function deliver(handler) { - try { handler(latest); } catch (error) { console.error(error); } - } - window.openbitfunCard = { - onData: function (handler) { - if (typeof handler !== 'function') return; - handlers.push(handler); - if (latest) deliver(handler); - }, - openLink: function (url) { - parent.postMessage({ source: '${FRAME_MESSAGE_SOURCE}', type: 'open-link', url: String(url) }, '*'); - } - }; - window.addEventListener('message', function (event) { - if (event.source !== parent) return; - var message = event.data; - if (!message || message.source !== '${HOST_MESSAGE_SOURCE}' || message.type !== 'data') return; - latest = message.payload; - handlers.forEach(deliver); - }); - parent.postMessage({ source: '${FRAME_MESSAGE_SOURCE}', type: 'ready' }, '*'); -})();`; - -export const DESKTOP_CARD_WIDGET_CSS = ` -* { box-sizing: border-box; } -html, body { margin: 0; padding: 0; width: 100%; height: 100%; background: transparent; overflow: auto; } -html { scrollbar-width: thin; scrollbar-color: var(--openbitfun-color-scrollbar-thumb) transparent; } -body { - color: var(--openbitfun-color-content-primary); - font-family: var(--openbitfun-type-body-sm-font-family); - font-size: var(--openbitfun-type-label-md-font-size); - line-height: var(--openbitfun-type-body-sm-line-height); -} -a { color: var(--openbitfun-color-accent-default); text-decoration: none; } -img, svg, canvas { max-width: 100%; height: auto; } -.openbitfun-card-stack { display: flex; flex-direction: column; gap: var(--openbitfun-space-2); } -.openbitfun-card-row { display: flex; align-items: center; justify-content: space-between; gap: var(--openbitfun-space-3); min-width: 0; } -.openbitfun-card-value { - font-family: var(--openbitfun-type-heading-page-font-family); - font-size: var(--openbitfun-type-heading-page-font-size); - font-weight: var(--openbitfun-type-heading-page-font-weight); - line-height: var(--openbitfun-type-heading-page-line-height); - font-variant-numeric: tabular-nums; -} -.openbitfun-card-muted { color: var(--openbitfun-color-content-secondary); font-size: var(--openbitfun-type-body-sm-font-size); } -.openbitfun-card-truncate { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } -.openbitfun-card-list { display: flex; flex-direction: column; margin: 0; padding: 0; list-style: none; } -.openbitfun-card-item { - display: flex; - align-items: center; - gap: var(--openbitfun-space-2); - min-width: 0; - padding: var(--openbitfun-space-1) var(--openbitfun-space-1); - border-radius: var(--openbitfun-radius-sm); -} -.openbitfun-card-item > .openbitfun-card-truncate { flex: 1 1 auto; } -.openbitfun-card-list > .openbitfun-card-item + .openbitfun-card-item { border-top: var(--openbitfun-border-width-default) solid var(--openbitfun-color-border-subtle); } -.openbitfun-card-item[role='link'], .openbitfun-card-item[data-url] { cursor: pointer; } -.openbitfun-card-item[role='link']:hover, .openbitfun-card-item[data-url]:hover { background: var(--openbitfun-color-action-quiet-hover); } -.openbitfun-card-good { color: var(--openbitfun-color-status-success-content); } -.openbitfun-card-warn { color: var(--openbitfun-color-status-warning-content); } -.openbitfun-card-bad { color: var(--openbitfun-color-status-danger-content); } -`; - -export interface DesktopCardWidgetAppearance { - mode?: string; - vars: Record; -} - -function escapeStyleText(value: string): string { - return value.replace(/<\/style/gi, '<\\/style'); -} - function readAppearance(): DesktopCardWidgetAppearance { const payload = readWidgetAppearancePayload(); return { mode: payload?.mode, vars: payload?.vars ?? {} }; } -export function buildDesktopCardSrcDoc(html: string, appearance: DesktopCardWidgetAppearance): string { - const themeCss = Object.entries(appearance.vars) - .filter(([name, value]) => /^--[a-z0-9-]+$/i.test(name) && !/[;{}<>]/.test(value)) - .map(([name, value]) => `${name}: ${value};`) - .join(' '); - const mode = appearance.mode === 'light' || appearance.mode === 'dark' ? appearance.mode : undefined; - // A color-scheme that differs from the card window's makes Chromium (WebView2) - // paint an opaque light canvas and light scrollbars behind the widget. - return ` - - - - - - - -${html} -`; -} - export function DesktopCardCustomFrame({ html, title, payload, onOpenLink }: DesktopCardCustomFrameProps) { const iframeRef = useRef(null); const payloadRef = useRef(payload); diff --git a/src/web-ui/src/app/components/DesktopCard/desktopCardSrcDoc.ts b/src/web-ui/src/app/components/DesktopCard/desktopCardSrcDoc.ts new file mode 100644 index 0000000000..9ed83c1158 --- /dev/null +++ b/src/web-ui/src/app/components/DesktopCard/desktopCardSrcDoc.ts @@ -0,0 +1,112 @@ +import { createWidgetAppearanceFallbackCss } from '@/tools/generative-widget/appearancePayload'; + +export const FRAME_MESSAGE_SOURCE = 'openbitfun-desktop-card'; +export const HOST_MESSAGE_SOURCE = 'openbitfun-desktop-card-host'; + +export interface DesktopCardCustomPayload { + data: unknown; + card: { id: string; title: string; subtitle?: string }; + error?: string; +} + +// The widget runs in an opaque-origin sandbox and talks to the card only through this bridge. +const BRIDGE_SCRIPT = `(function () { + var handlers = []; + var latest = null; + function deliver(handler) { + try { handler(latest); } catch (error) { console.error(error); } + } + window.openbitfunCard = { + onData: function (handler) { + if (typeof handler !== 'function') return; + handlers.push(handler); + if (latest) deliver(handler); + }, + openLink: function (url) { + parent.postMessage({ source: '${FRAME_MESSAGE_SOURCE}', type: 'open-link', url: String(url) }, '*'); + } + }; + window.addEventListener('message', function (event) { + if (event.source !== parent) return; + var message = event.data; + if (!message || message.source !== '${HOST_MESSAGE_SOURCE}' || message.type !== 'data') return; + latest = message.payload; + handlers.forEach(deliver); + }); + parent.postMessage({ source: '${FRAME_MESSAGE_SOURCE}', type: 'ready' }, '*'); +})();`; + +export const DESKTOP_CARD_WIDGET_CSS = ` +* { box-sizing: border-box; } +html, body { margin: 0; padding: 0; width: 100%; height: 100%; background: transparent; overflow: auto; } +html { scrollbar-width: thin; scrollbar-color: var(--openbitfun-color-scrollbar-thumb) transparent; } +body { + color: var(--openbitfun-color-content-primary); + font-family: var(--openbitfun-type-body-sm-font-family); + font-size: var(--openbitfun-type-label-md-font-size); + line-height: var(--openbitfun-type-body-sm-line-height); +} +a { color: var(--openbitfun-color-accent-default); text-decoration: none; } +img, svg, canvas { max-width: 100%; height: auto; } +.openbitfun-card-stack { display: flex; flex-direction: column; gap: var(--openbitfun-space-2); } +.openbitfun-card-row { display: flex; align-items: center; justify-content: space-between; gap: var(--openbitfun-space-3); min-width: 0; } +.openbitfun-card-value { + font-family: var(--openbitfun-type-heading-page-font-family); + font-size: var(--openbitfun-type-heading-page-font-size); + font-weight: var(--openbitfun-type-heading-page-font-weight); + line-height: var(--openbitfun-type-heading-page-line-height); + font-variant-numeric: tabular-nums; +} +.openbitfun-card-muted { color: var(--openbitfun-color-content-secondary); font-size: var(--openbitfun-type-body-sm-font-size); } +.openbitfun-card-truncate { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.openbitfun-card-list { display: flex; flex-direction: column; margin: 0; padding: 0; list-style: none; } +.openbitfun-card-item { + display: flex; + align-items: center; + gap: var(--openbitfun-space-2); + min-width: 0; + padding: var(--openbitfun-space-1) var(--openbitfun-space-1); + border-radius: var(--openbitfun-radius-sm); +} +.openbitfun-card-item > .openbitfun-card-truncate { flex: 1 1 auto; } +.openbitfun-card-list > .openbitfun-card-item + .openbitfun-card-item { border-top: var(--openbitfun-border-width-default) solid var(--openbitfun-color-border-subtle); } +.openbitfun-card-item[role='link'], .openbitfun-card-item[data-url] { cursor: pointer; } +.openbitfun-card-item[role='link']:hover, .openbitfun-card-item[data-url]:hover { background: var(--openbitfun-color-action-quiet-hover); } +.openbitfun-card-good { color: var(--openbitfun-color-status-success-content); } +.openbitfun-card-warn { color: var(--openbitfun-color-status-warning-content); } +.openbitfun-card-bad { color: var(--openbitfun-color-status-danger-content); } +`; + +export interface DesktopCardWidgetAppearance { + mode?: string; + vars: Record; +} + +function escapeStyleText(value: string): string { + return value.replace(/<\/style/gi, '<\\/style'); +} + +export function buildDesktopCardSrcDoc(html: string, appearance: DesktopCardWidgetAppearance): string { + const themeCss = Object.entries(appearance.vars) + .filter(([name, value]) => /^--[a-z0-9-]+$/i.test(name) && !/[;{}<>]/.test(value)) + .map(([name, value]) => `${name}: ${value};`) + .join(' '); + const mode = appearance.mode === 'light' || appearance.mode === 'dark' ? appearance.mode : undefined; + // A color-scheme that differs from the card window's makes Chromium (WebView2) + // paint an opaque light canvas and light scrollbars behind the widget. + return ` + + + + + + + +${html} +`; +} diff --git a/src/web-ui/src/app/components/NavPanel/sections/devices/BackgroundSessionList.tsx b/src/web-ui/src/app/components/NavPanel/sections/devices/BackgroundSessionList.tsx index 68d1d7f62a..7349370bcf 100644 --- a/src/web-ui/src/app/components/NavPanel/sections/devices/BackgroundSessionList.tsx +++ b/src/web-ui/src/app/components/NavPanel/sections/devices/BackgroundSessionList.tsx @@ -44,7 +44,8 @@ import { getChildSessionBadge } from '../sessions/sessionRowBadges'; import { resolveSessionRelationship } from '@/flow_chat/utils/sessionMetadata'; import { sessionBelongsToWorkspaceNavRow } from '@/flow_chat/utils/sessionOrdering'; import type { SidebarDeviceSlot } from './useSidebarDevices'; -import { CatalogSessionMenu, catalogSessionActionKey, runCatalogSessionAction } from './CatalogSessionMenu'; +import { CatalogSessionMenu } from './CatalogSessionMenu'; +import { catalogSessionActionKey, runCatalogSessionAction } from './catalogSessionActions'; export interface BackgroundActions { pendingKey: string | null; diff --git a/src/web-ui/src/app/components/NavPanel/sections/devices/CatalogSessionMenu.tsx b/src/web-ui/src/app/components/NavPanel/sections/devices/CatalogSessionMenu.tsx index 1422b0ad24..4c00801e29 100644 --- a/src/web-ui/src/app/components/NavPanel/sections/devices/CatalogSessionMenu.tsx +++ b/src/web-ui/src/app/components/NavPanel/sections/devices/CatalogSessionMenu.tsx @@ -23,33 +23,10 @@ import { sessionWorktreeRootPath } from '@/flow_chat/utils/sessionWorktree'; import { useSideAnchoredPopoverPosition } from '@/shared/utils/useSideAnchoredPopoverPosition'; import ArchivedSessionMenuItems from '../sessions/ArchivedSessionMenuItems'; import SessionDeleteMenuItem from '../sessions/SessionDeleteMenuItem'; -import { activateDeviceSlot, runDeviceSessionAction, type DeviceSessionAction } from './openOnDevice'; +import { activateDeviceSlot, type DeviceSessionAction } from './openOnDevice'; import type { BackgroundActions } from './BackgroundSessionList'; import type { SidebarDeviceSlot } from './useSidebarDevices'; - -/** Intent key of a catalog session action; the row shows progress while it runs. */ -export const catalogSessionActionKey = (sessionId: string, kind: string) => `session-action:${sessionId}:${kind}`; - -const FAILURE_KEYS: Partial> = { - duplicate: 'nav.sessions.duplicateFailed', - 'open-worktree': 'nav.sessions.openWorktreeWorkspaceFailed', - 'reveal-storage': 'nav.sessions.openStorageDirectoryFailed', -}; - -export function runCatalogSessionAction( - actions: BackgroundActions, - peer: ReturnType, - slot: SidebarDeviceSlot, - sessionId: string, - action: DeviceSessionAction, - t: (key: string, options?: Record) => string, -): void { - actions.run( - catalogSessionActionKey(sessionId, action.kind), - () => runDeviceSessionAction(peer, slot, sessionId, action, t), - FAILURE_KEYS[action.kind] ?? 'nav.devices.sessionActionFailed', - ); -} +import { catalogSessionActionKey, runCatalogSessionAction } from './catalogSessionActions'; export const CatalogSessionMenu: React.FC<{ slot: SidebarDeviceSlot; diff --git a/src/web-ui/src/app/components/NavPanel/sections/devices/catalogSessionActions.ts b/src/web-ui/src/app/components/NavPanel/sections/devices/catalogSessionActions.ts new file mode 100644 index 0000000000..ea5e09176b --- /dev/null +++ b/src/web-ui/src/app/components/NavPanel/sections/devices/catalogSessionActions.ts @@ -0,0 +1,28 @@ +import type { usePeerDeviceModeOptional } from '@/infrastructure/peer-device/peerDeviceContextState'; +import type { BackgroundActions } from './BackgroundSessionList'; +import type { SidebarDeviceSlot } from './useSidebarDevices'; +import { runDeviceSessionAction, type DeviceSessionAction } from './openOnDevice'; + +/** Intent key of a catalog session action; the row shows progress while it runs. */ +export const catalogSessionActionKey = (sessionId: string, kind: string) => `session-action:${sessionId}:${kind}`; + +const FAILURE_KEYS: Partial> = { + duplicate: 'nav.sessions.duplicateFailed', + 'open-worktree': 'nav.sessions.openWorktreeWorkspaceFailed', + 'reveal-storage': 'nav.sessions.openStorageDirectoryFailed', +}; + +export function runCatalogSessionAction( + actions: BackgroundActions, + peer: ReturnType, + slot: SidebarDeviceSlot, + sessionId: string, + action: DeviceSessionAction, + t: (key: string, options?: Record) => string, +): void { + actions.run( + catalogSessionActionKey(sessionId, action.kind), + () => runDeviceSessionAction(peer, slot, sessionId, action, t), + FAILURE_KEYS[action.kind] ?? 'nav.devices.sessionActionFailed', + ); +} diff --git a/src/web-ui/src/app/components/panels/content-canvas/CanvasToolbar.tsx b/src/web-ui/src/app/components/panels/content-canvas/CanvasToolbar.tsx index d4816a7a49..b5ca081c7b 100644 --- a/src/web-ui/src/app/components/panels/content-canvas/CanvasToolbar.tsx +++ b/src/web-ui/src/app/components/panels/content-canvas/CanvasToolbar.tsx @@ -1,14 +1,7 @@ -import React, { createContext, useCallback, useContext, useLayoutEffect, useMemo, useRef, useState } from 'react'; +import React, { useCallback, useContext, useLayoutEffect, useMemo, useRef, useState } from 'react'; import type { EditorGroupId } from './types'; import { CanvasStoreModeContext } from './stores'; - -type ToolbarEntry = { owner: symbol; content: React.ReactNode }; -type ToolbarRegistry = Partial>; -const RegistrationContext = createContext<{ - register: (id: EditorGroupId, owner: symbol, content: React.ReactNode) => void; - remove: (id: EditorGroupId, owner: symbol) => void; -} | null>(null); -const ContentContext = createContext({}); +import { RegistrationContext, ContentContext, type ToolbarRegistry } from './canvasToolbarContext'; /** A host chooses toolbar placement; canvas groups continue to own tab behavior. */ export function CanvasToolbarProvider({ children }: { children: React.ReactNode }) { @@ -31,11 +24,6 @@ export function CanvasToolbarProvider({ children }: { children: React.ReactNode ; } -export function useExternalCanvasToolbar(enabled: boolean) { - const registration = useContext(RegistrationContext); - return enabled && registration !== null; -} - export function CanvasToolbarContribution({ groupId, children }: { groupId: EditorGroupId; children: React.ReactNode; }) { diff --git a/src/web-ui/src/app/components/panels/content-canvas/ContentCanvas.tsx b/src/web-ui/src/app/components/panels/content-canvas/ContentCanvas.tsx index 5dc6cf56f6..5725edc508 100644 --- a/src/web-ui/src/app/components/panels/content-canvas/ContentCanvas.tsx +++ b/src/web-ui/src/app/components/panels/content-canvas/ContentCanvas.tsx @@ -5,7 +5,8 @@ import React, { useCallback, useEffect, useMemo, useRef, useSyncExternalStore } from 'react'; import { Toolbar } from '@openbitfun/ui'; -import { CanvasToolbarContribution, useExternalCanvasToolbar } from './CanvasToolbar'; +import { CanvasToolbarContribution } from './CanvasToolbar'; +import { useExternalCanvasToolbar } from './canvasToolbarContext'; import { EditorArea } from './editor-area'; import { AnchorZone } from './anchor-zone'; import { MissionControl } from './mission-control'; diff --git a/src/web-ui/src/app/components/panels/content-canvas/canvasToolbarContext.ts b/src/web-ui/src/app/components/panels/content-canvas/canvasToolbarContext.ts new file mode 100644 index 0000000000..b4fabdea33 --- /dev/null +++ b/src/web-ui/src/app/components/panels/content-canvas/canvasToolbarContext.ts @@ -0,0 +1,15 @@ +import { createContext, useContext, type ReactNode } from 'react'; +import type { EditorGroupId } from './types'; + +type ToolbarEntry = { owner: symbol; content: ReactNode }; +export type ToolbarRegistry = Partial>; +export const RegistrationContext = createContext<{ + register: (id: EditorGroupId, owner: symbol, content: ReactNode) => void; + remove: (id: EditorGroupId, owner: symbol) => void; +} | null>(null); +export const ContentContext = createContext({}); + +export function useExternalCanvasToolbar(enabled: boolean) { + const registration = useContext(RegistrationContext); + return enabled && registration !== null; +} diff --git a/src/web-ui/src/app/scenes/settings/SettingsNav.tsx b/src/web-ui/src/app/scenes/settings/SettingsNav.tsx index 0a7af86ead..1a6b3b3cfc 100644 --- a/src/web-ui/src/app/scenes/settings/SettingsNav.tsx +++ b/src/web-ui/src/app/scenes/settings/SettingsNav.tsx @@ -136,7 +136,12 @@ function useSettingsSearchIndex(t: SettingsT, i18n: I18nApi, hasSearched: boolea }, [hasSearched, languages, store]); return useMemo( - () => hasSearched ? buildSettingsSearchIndex(t, i18n) : [], + () => { + // i18next mutates its resource store without changing the i18n identity. + // Resource events must invalidate the cached search index. + void resourcesRevision; + return hasSearched ? buildSettingsSearchIndex(t, i18n) : []; + }, [hasSearched, i18n, resourcesRevision, t], ); } diff --git a/src/web-ui/src/app/scenes/settings/pages/ai/OpenCodeModelQuota.test.ts b/src/web-ui/src/app/scenes/settings/pages/ai/OpenCodeModelQuota.test.ts index 3deaeff297..4e61b79c0c 100644 --- a/src/web-ui/src/app/scenes/settings/pages/ai/OpenCodeModelQuota.test.ts +++ b/src/web-ui/src/app/scenes/settings/pages/ai/OpenCodeModelQuota.test.ts @@ -1,5 +1,5 @@ import { expect, it } from 'vitest'; -import { canReadSavedOpenCodeQuota } from './OpenCodeModelQuota'; +import { canReadSavedOpenCodeQuota } from './openCodeQuotaEligibility'; import type { AIModelConfig } from '@/infrastructure/config/types'; it('queries only the saved connection and keeps draft credentials away from the billing API', () => { diff --git a/src/web-ui/src/app/scenes/settings/pages/ai/OpenCodeModelQuota.tsx b/src/web-ui/src/app/scenes/settings/pages/ai/OpenCodeModelQuota.tsx index 575d8cda54..79b61c5a2a 100644 --- a/src/web-ui/src/app/scenes/settings/pages/ai/OpenCodeModelQuota.tsx +++ b/src/web-ui/src/app/scenes/settings/pages/ai/OpenCodeModelQuota.tsx @@ -1,4 +1,5 @@ import { useMemo } from 'react'; +import { canReadSavedOpenCodeQuota } from './openCodeQuotaEligibility'; import { Button } from '@openbitfun/ui'; import { ConfigPageRow } from '@/infrastructure/config/components/common'; import type { AIModelConfig } from '@/infrastructure/config/types'; @@ -9,13 +10,6 @@ import { SubscriptionQuotaPanel } from './SubscriptionQuotaPanel'; let observationEpoch = 0; -export function canReadSavedOpenCodeQuota(draft: Partial, saved?: AIModelConfig): saved is AIModelConfig & { id: string } { - return !!saved?.id && isOpenCodeApiKeyConfig(saved) && isOpenCodeApiKeyConfig(draft) - && draft.id === saved.id && draft.base_url === saved.base_url - && draft.api_key === saved.api_key - && JSON.stringify(draft.custom_headers || {}) === JSON.stringify(saved.custom_headers || {}); -} - export function OpenCodeModelQuota({ draft, saved, active, supported }: { draft: Partial; saved?: AIModelConfig; active: boolean; supported: boolean; }) { diff --git a/src/web-ui/src/app/scenes/settings/pages/ai/openCodeQuotaEligibility.ts b/src/web-ui/src/app/scenes/settings/pages/ai/openCodeQuotaEligibility.ts new file mode 100644 index 0000000000..847d870f70 --- /dev/null +++ b/src/web-ui/src/app/scenes/settings/pages/ai/openCodeQuotaEligibility.ts @@ -0,0 +1,9 @@ +import type { AIModelConfig } from '@/infrastructure/config/types'; +import { isOpenCodeApiKeyConfig } from '@/infrastructure/config/components/openCodeApiKeyRouting'; + +export function canReadSavedOpenCodeQuota(draft: Partial, saved?: AIModelConfig): saved is AIModelConfig & { id: string } { + return !!saved?.id && isOpenCodeApiKeyConfig(saved) && isOpenCodeApiKeyConfig(draft) + && draft.id === saved.id && draft.base_url === saved.base_url + && draft.api_key === saved.api_key + && JSON.stringify(draft.custom_headers || {}) === JSON.stringify(saved.custom_headers || {}); +} diff --git a/src/web-ui/src/flow_chat/components/FlowToolCard.tsx b/src/web-ui/src/flow_chat/components/FlowToolCard.tsx index d8d9f13283..d45f641661 100644 --- a/src/web-ui/src/flow_chat/components/FlowToolCard.tsx +++ b/src/web-ui/src/flow_chat/components/FlowToolCard.tsx @@ -4,7 +4,7 @@ */ import React from 'react'; -import { FlowChatCardReaderProvider } from '../timeline/readerState'; +import { FlowChatCardReaderProvider } from '../timeline/FlowChatReaderProvider'; import { ToolCapsulePresentationProvider } from '@openbitfun/ui/flow-chat'; import { getToolCardComponent } from '../tool-cards'; import { DefaultToolCard } from '../tool-cards/DefaultToolCard'; diff --git a/src/web-ui/src/flow_chat/components/WindowedCodeContent.test.tsx b/src/web-ui/src/flow_chat/components/WindowedCodeContent.test.tsx index 6d10350100..0a8298c7a3 100644 --- a/src/web-ui/src/flow_chat/components/WindowedCodeContent.test.tsx +++ b/src/web-ui/src/flow_chat/components/WindowedCodeContent.test.tsx @@ -2,7 +2,8 @@ import React, { act } from 'react'; import { createRoot } from 'react-dom/client'; import { expect, it, vi } from 'vitest'; -import { getVisibleCodeLineCount, readLineHeight, WindowedCodeContent } from './WindowedCodeContent'; +import { WindowedCodeContent } from './WindowedCodeContent'; +import { getVisibleCodeLineCount, readLineHeight } from './codeLineMetrics'; const highlights = vi.hoisted(() => ({ ready: false })); vi.mock('../timeline/highlightResources', () => ({ useHighlightedLines: (content: string) => content.split('\n').map(line => diff --git a/src/web-ui/src/flow_chat/components/WindowedCodeContent.tsx b/src/web-ui/src/flow_chat/components/WindowedCodeContent.tsx index 2f8fe045e0..8d090ec829 100644 --- a/src/web-ui/src/flow_chat/components/WindowedCodeContent.tsx +++ b/src/web-ui/src/flow_chat/components/WindowedCodeContent.tsx @@ -1,3 +1,4 @@ +import { readLineHeight, getVisibleCodeLineCount } from './codeLineMetrics'; import React, { useLayoutEffect, useMemo, useRef, useState, type RefObject } from 'react'; import { useVirtualizer } from '@tanstack/react-virtual'; import { useHighlightedLines } from '../timeline/highlightResources'; @@ -11,30 +12,6 @@ function tokenNode(token: PrismToken, key: number): React.ReactNode { : typeof token.content === 'string' ? token.content : tokenNode(token.content, 0)}; } -/** - * Resolve the source line box to pixels before feeding it to the virtualizer. - * - * `line-height` is a unitless design token (`1.52` in the code role). The - * computed style keeps that value unitless, while the virtualizer's offsets - * are pixels. Treating the result of `parseFloat` as pixels makes every later - * decoration row drift farther from the native text row. - */ -export function readLineHeight(source: HTMLElement): number | null { - const computed = getComputedStyle(source); - const rawLineHeight = computed.lineHeight.trim(); - const value = Number.parseFloat(rawLineHeight); - if (!Number.isFinite(value) || value <= 0) return null; - - if (rawLineHeight.endsWith('px')) return value; - - const fontSize = Number.parseFloat(computed.fontSize); - return Number.isFinite(fontSize) && fontSize > 0 ? value * fontSize : null; -} - -export function getVisibleCodeLineCount(splitLineCount: number, hasTrailingNewline: boolean): number { - return Math.max(1, splitLineCount - (hasTrailingNewline ? 1 : 0)); -} - function readNativeLineRect(source: HTMLElement, lineIndex: number): { top: number; height: number } | null { const text = source.firstChild; if (!text || text.nodeType !== Node.TEXT_NODE) return null; diff --git a/src/web-ui/src/flow_chat/components/btw/BtwVirtualSessionList.tsx b/src/web-ui/src/flow_chat/components/btw/BtwVirtualSessionList.tsx index 0720768fd1..514e8e0a41 100644 --- a/src/web-ui/src/flow_chat/components/btw/BtwVirtualSessionList.tsx +++ b/src/web-ui/src/flow_chat/components/btw/BtwVirtualSessionList.tsx @@ -16,7 +16,7 @@ import { resolveExcerptRange } from '../../selection/flowChatSelection'; import { resolveFlowChatFocusTarget } from '../modern/flowChatFocusTarget'; import { useFlowChatContext } from '../modern/FlowChatContext'; import { useConversationTimeline } from '../../timeline/useConversationTimeline'; -import { FlowChatReaderProvider } from '../../timeline/readerState'; +import { FlowChatReaderProvider } from '../../timeline/FlowChatReaderProvider'; import { useTimelineInteraction } from '../../timeline/useTimelineInteraction'; import { TimelineMutationBoundary } from '../../timeline/TimelineMutationBoundary'; import { findTimelineBlockIndex } from '../../timeline/document'; diff --git a/src/web-ui/src/flow_chat/components/codeLineMetrics.ts b/src/web-ui/src/flow_chat/components/codeLineMetrics.ts new file mode 100644 index 0000000000..55c1884aa6 --- /dev/null +++ b/src/web-ui/src/flow_chat/components/codeLineMetrics.ts @@ -0,0 +1,23 @@ +/** + * Resolve the source line box to pixels before feeding it to the virtualizer. + * + * `line-height` is a unitless design token (`1.52` in the code role). The + * computed style keeps that value unitless, while the virtualizer's offsets + * are pixels. Treating the result of `parseFloat` as pixels makes every later + * decoration row drift farther from the native text row. + */ +export function readLineHeight(source: HTMLElement): number | null { + const computed = getComputedStyle(source); + const rawLineHeight = computed.lineHeight.trim(); + const value = Number.parseFloat(rawLineHeight); + if (!Number.isFinite(value) || value <= 0) return null; + + if (rawLineHeight.endsWith('px')) return value; + + const fontSize = Number.parseFloat(computed.fontSize); + return Number.isFinite(fontSize) && fontSize > 0 ? value * fontSize : null; +} + +export function getVisibleCodeLineCount(splitLineCount: number, hasTrailingNewline: boolean): number { + return Math.max(1, splitLineCount - (hasTrailingNewline ? 1 : 0)); +} diff --git a/src/web-ui/src/flow_chat/components/modern/TurnFooter.test.tsx b/src/web-ui/src/flow_chat/components/modern/TurnFooter.test.tsx index 791f85f7fa..e3a1af772b 100644 --- a/src/web-ui/src/flow_chat/components/modern/TurnFooter.test.tsx +++ b/src/web-ui/src/flow_chat/components/modern/TurnFooter.test.tsx @@ -2,7 +2,8 @@ import React, { act } from 'react'; import { createRoot, type Root } from 'react-dom/client'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; -import { FlowChatReaderProvider, FlowChatReaderState } from '../../timeline/readerState'; +import { FlowChatReaderState } from '../../timeline/readerState'; +import { FlowChatReaderProvider } from '../../timeline/FlowChatReaderProvider'; import { TurnFooter } from './TurnFooter'; import { useTurnFooterInteraction } from './useTurnFooterInteraction'; diff --git a/src/web-ui/src/flow_chat/components/modern/VirtualItemRenderer.tsx b/src/web-ui/src/flow_chat/components/modern/VirtualItemRenderer.tsx index 265ecb2431..8b72b864f0 100644 --- a/src/web-ui/src/flow_chat/components/modern/VirtualItemRenderer.tsx +++ b/src/web-ui/src/flow_chat/components/modern/VirtualItemRenderer.tsx @@ -16,7 +16,7 @@ import { TurnFailureNoticeItem } from './TurnFailureNoticeItem'; import './VirtualItemRenderer.scss'; import { getVirtualItemBookmarkKey, getVirtualItemStableKey } from './virtualItemIdentity'; import { useFlowChatSearchPresentation } from './useFlowChatSearchPresentation'; -import { useConversationExcerptMarkers } from '../../selection/ConversationExcerptMarkers'; +import { useConversationExcerptMarkers } from '../../selection/useConversationExcerptMarkers'; import { getKnownVirtualItemHeightPx } from './virtualItemHeightEstimators'; import { Icon } from '@openbitfun/ui'; import { TimelineContentBlock } from '../../timeline/TimelineContentBlock'; diff --git a/src/web-ui/src/flow_chat/components/modern/VirtualMessageList.tsx b/src/web-ui/src/flow_chat/components/modern/VirtualMessageList.tsx index d095e3fc7a..b98e6bca3c 100644 --- a/src/web-ui/src/flow_chat/components/modern/VirtualMessageList.tsx +++ b/src/web-ui/src/flow_chat/components/modern/VirtualMessageList.tsx @@ -98,7 +98,7 @@ import { resolveVisibleFlowChatTurnIds } from './flowChatVisibleTurns'; import type { FlowChatViewportSnapshot } from './flowChatViewportSnapshot'; import { getVirtualItemBookmarkKey, getVirtualItemStableKey } from './virtualItemIdentity'; import { useConversationTimeline } from '../../timeline/useConversationTimeline'; -import { FlowChatReaderProvider } from '../../timeline/readerState'; +import { FlowChatReaderProvider } from '../../timeline/FlowChatReaderProvider'; import { retainedTranscriptRowSizes } from '../../timeline/retainedViewMemory'; import { findTimelineBlockIndex } from '../../timeline/document'; import { localizeMarkdownMatch } from '../../timeline/markdownSectionSearch'; diff --git a/src/web-ui/src/flow_chat/components/subagent/SubagentProjectionView.tsx b/src/web-ui/src/flow_chat/components/subagent/SubagentProjectionView.tsx index 8b8ee52de9..535e52e7b9 100644 --- a/src/web-ui/src/flow_chat/components/subagent/SubagentProjectionView.tsx +++ b/src/web-ui/src/flow_chat/components/subagent/SubagentProjectionView.tsx @@ -1,7 +1,8 @@ import { useFlowChatVirtualizer } from '../modern/useFlowChatVirtualizer'; import { useFlowChatViewportOwner } from '../modern/useFlowChatViewportOwner'; import { estimateFlowItemHeight } from '../modern/virtualItemHeightEstimators'; -import { FlowChatReaderProvider, useFlowChatReaderScope, useFlowChatReaderValue } from '../../timeline/readerState'; +import { useFlowChatReaderScope, useFlowChatReaderValue } from '../../timeline/readerState'; +import { FlowChatReaderProvider } from '../../timeline/FlowChatReaderProvider'; import { useEmbeddedTimelineFollow } from '../../timeline/useEmbeddedTimelineFollow'; import { useTimelineInteraction } from '../../timeline/useTimelineInteraction'; import { TimelineMutationBoundary } from '../../timeline/TimelineMutationBoundary'; diff --git a/src/web-ui/src/flow_chat/selection/ConversationExcerptMarkers.test.tsx b/src/web-ui/src/flow_chat/selection/ConversationExcerptMarkers.test.tsx index cca5b7a87d..a5f66fa9e6 100644 --- a/src/web-ui/src/flow_chat/selection/ConversationExcerptMarkers.test.tsx +++ b/src/web-ui/src/flow_chat/selection/ConversationExcerptMarkers.test.tsx @@ -3,7 +3,8 @@ import { act, useRef } from 'react'; import { createRoot, type Root } from 'react-dom/client'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import type { ConversationExcerptContext } from '@/shared/types/context'; -import { ConversationExcerptMarkers, useConversationExcerptMarkers } from './ConversationExcerptMarkers'; +import { ConversationExcerptMarkers } from './ConversationExcerptMarkers'; +import { useConversationExcerptMarkers } from './useConversationExcerptMarkers'; import { ConversationExcerptSourceContext } from './conversationExcerptSourceContext'; vi.mock('./ConversationExcerptAttachments', () => ({ ConversationExcerptPreview: () => null })); diff --git a/src/web-ui/src/flow_chat/selection/ConversationExcerptMarkers.tsx b/src/web-ui/src/flow_chat/selection/ConversationExcerptMarkers.tsx index 470b27a321..832039b286 100644 --- a/src/web-ui/src/flow_chat/selection/ConversationExcerptMarkers.tsx +++ b/src/web-ui/src/flow_chat/selection/ConversationExcerptMarkers.tsx @@ -1,113 +1,4 @@ -import { useLayoutEffect, useRef, useState, type RefObject } from 'react'; -import type { ConversationExcerptContext } from '@/shared/types/context'; -import { excerptNumber } from '@/shared/utils/conversationExcerpt'; -import { findExcerptSource, resolveExcerptRange } from './flowChatSelection'; -import { useConversationExcerptSources } from './conversationExcerptSourceContext'; -import { ConversationExcerptPreview } from './ConversationExcerptAttachments'; -import { measureExcerptMarkerPosition, type ExcerptMarkerPosition } from './conversationExcerptMarkerPosition'; -import { createExcerptHighlights } from './conversationExcerptHighlights'; - -interface MarkerGroup { - key: string; - element: HTMLElement; - range: Range; - excerpts: readonly ConversationExcerptContext[]; -} - -/** Row-local overlays: annotation marks never modify transcript text or row height. */ -export function useConversationExcerptMarkers(target: HTMLElement | RefObject | null, turnId: string) { - const excerpts = useConversationExcerptSources(turnId); - const [groups, setGroups] = useState([]); - const markerRefs = useRef(new Map()); - const [positions, setPositions] = useState(new Map()); - useLayoutEffect(() => { - const wrapper = target && 'current' in target ? target.current : target; - if (!wrapper || !excerpts.length) { setGroups(previous => previous.length ? [] : previous); return; } - const view = wrapper.ownerDocument.defaultView; - if (!view) return; - const highlights = createExcerptHighlights(wrapper.ownerDocument); - let frame: number | null = null; - const refresh = () => { - frame = null; - const next = new Map(); - const ranges: Range[] = []; - for (const excerpt of excerpts) { - for (const fragment of excerpt.fragments) { - if (fragment.turnId !== turnId) continue; - const element = findExcerptSource(wrapper, fragment); - const range = element && resolveExcerptRange(element, fragment); - if (range) ranges.push(range); - if (!excerptNumber(excerpt)) continue; - if (!element || !range) continue; - // Separate selections in one text block keep their own superscripts. - const key = JSON.stringify([fragment.flowItemId ?? null, fragment.markdownStart, fragment.start, fragment.end]); - const previous = next.get(key); - if (previous) { - if (!previous.excerpts.some(item => item.id === excerpt.id)) previous.excerpts = [...previous.excerpts, excerpt]; - } else next.set(key, { - key, element, range, excerpts: [excerpt], - }); - } - } - highlights.update(ranges); - setGroups([...next.values()]); - }; - const schedule = () => { if (frame === null) frame = view.requestAnimationFrame(refresh); }; - const mutation = new MutationObserver(records => { - if (records.some(record => { - const target = record.target instanceof Element ? record.target : record.target.parentElement; - return !target?.closest('[data-openbitfun-product-part="markers"]'); - })) schedule(); - }); - mutation.observe(wrapper, { childList: true, characterData: true, subtree: true, attributes: true, - attributeFilter: ['class', 'style', 'hidden', 'aria-hidden', 'open', 'data-expanded'] }); - const resize = new ResizeObserver(schedule); - resize.observe(wrapper); - wrapper.ownerDocument.addEventListener('scroll', schedule, { capture: true, passive: true }); - wrapper.ownerDocument.fonts?.addEventListener('loadingdone', schedule); - refresh(); - return () => { - highlights.dispose(); - if (frame !== null) view.cancelAnimationFrame(frame); - mutation.disconnect(); resize.disconnect(); - wrapper.ownerDocument.removeEventListener('scroll', schedule, true); - wrapper.ownerDocument.fonts?.removeEventListener('loadingdone', schedule); - }; - }, [target, excerpts, turnId]); - - useLayoutEffect(() => { - const wrapper = target && 'current' in target ? target.current : target; - if (!wrapper) return; - const update = () => { - const next = new Map(); - for (const group of groups) { - const marker = markerRefs.current.get(group.key); - if (!marker) continue; - const size = marker.getBoundingClientRect(); - const position = measureExcerptMarkerPosition(wrapper, group.element, group.range, size); - if (!position) continue; - next.set(group.key, position); - } - setPositions(previous => previous.size === next.size && [...next].every(([key, value]) => - previous.get(key)?.left === value.left && previous.get(key)?.top === value.top) ? previous : next); - }; - update(); - const resize = new ResizeObserver(update); - markerRefs.current.forEach(marker => resize.observe(marker)); - return () => resize.disconnect(); - }, [target, groups]); - - return <>{groups.map(group => ( - { if (element) markerRefs.current.set(group.key, element); else markerRefs.current.delete(group.key); }} - data-openbitfun-product-component="conversation-excerpt" data-openbitfun-product-part="markers" - className="conversation-excerpt__markers" data-flowchat-selection-ignore="true" - style={{ left: positions.get(group.key)?.left ?? 0, top: positions.get(group.key)?.top ?? 0, - visibility: positions.has(group.key) ? 'visible' : 'hidden' }}> - {group.excerpts.map(excerpt => )} - - ))}; -} +import { useConversationExcerptMarkers } from './useConversationExcerptMarkers'; export function ConversationExcerptMarkers({ wrapper, turnId }: { wrapper: HTMLElement | null; turnId: string }) { return useConversationExcerptMarkers(wrapper, turnId); diff --git a/src/web-ui/src/flow_chat/selection/useConversationExcerptMarkers.tsx b/src/web-ui/src/flow_chat/selection/useConversationExcerptMarkers.tsx new file mode 100644 index 0000000000..302ce3ac21 --- /dev/null +++ b/src/web-ui/src/flow_chat/selection/useConversationExcerptMarkers.tsx @@ -0,0 +1,110 @@ +import { useLayoutEffect, useRef, useState, type RefObject } from 'react'; +import type { ConversationExcerptContext } from '@/shared/types/context'; +import { excerptNumber } from '@/shared/utils/conversationExcerpt'; +import { findExcerptSource, resolveExcerptRange } from './flowChatSelection'; +import { useConversationExcerptSources } from './conversationExcerptSourceContext'; +import { ConversationExcerptPreview } from './ConversationExcerptAttachments'; +import { measureExcerptMarkerPosition, type ExcerptMarkerPosition } from './conversationExcerptMarkerPosition'; +import { createExcerptHighlights } from './conversationExcerptHighlights'; + +interface MarkerGroup { + key: string; + element: HTMLElement; + range: Range; + excerpts: readonly ConversationExcerptContext[]; +} + +/** Row-local overlays: annotation marks never modify transcript text or row height. */ +export function useConversationExcerptMarkers(target: HTMLElement | RefObject | null, turnId: string) { + const excerpts = useConversationExcerptSources(turnId); + const [groups, setGroups] = useState([]); + const markerRefs = useRef(new Map()); + const [positions, setPositions] = useState(new Map()); + useLayoutEffect(() => { + const wrapper = target && 'current' in target ? target.current : target; + if (!wrapper || !excerpts.length) { setGroups(previous => previous.length ? [] : previous); return; } + const view = wrapper.ownerDocument.defaultView; + if (!view) return; + const highlights = createExcerptHighlights(wrapper.ownerDocument); + let frame: number | null = null; + const refresh = () => { + frame = null; + const next = new Map(); + const ranges: Range[] = []; + for (const excerpt of excerpts) { + for (const fragment of excerpt.fragments) { + if (fragment.turnId !== turnId) continue; + const element = findExcerptSource(wrapper, fragment); + const range = element && resolveExcerptRange(element, fragment); + if (range) ranges.push(range); + if (!excerptNumber(excerpt)) continue; + if (!element || !range) continue; + // Separate selections in one text block keep their own superscripts. + const key = JSON.stringify([fragment.flowItemId ?? null, fragment.markdownStart, fragment.start, fragment.end]); + const previous = next.get(key); + if (previous) { + if (!previous.excerpts.some(item => item.id === excerpt.id)) previous.excerpts = [...previous.excerpts, excerpt]; + } else next.set(key, { + key, element, range, excerpts: [excerpt], + }); + } + } + highlights.update(ranges); + setGroups([...next.values()]); + }; + const schedule = () => { if (frame === null) frame = view.requestAnimationFrame(refresh); }; + const mutation = new MutationObserver(records => { + if (records.some(record => { + const target = record.target instanceof Element ? record.target : record.target.parentElement; + return !target?.closest('[data-openbitfun-product-part="markers"]'); + })) schedule(); + }); + mutation.observe(wrapper, { childList: true, characterData: true, subtree: true, attributes: true, + attributeFilter: ['class', 'style', 'hidden', 'aria-hidden', 'open', 'data-expanded'] }); + const resize = new ResizeObserver(schedule); + resize.observe(wrapper); + wrapper.ownerDocument.addEventListener('scroll', schedule, { capture: true, passive: true }); + wrapper.ownerDocument.fonts?.addEventListener('loadingdone', schedule); + refresh(); + return () => { + highlights.dispose(); + if (frame !== null) view.cancelAnimationFrame(frame); + mutation.disconnect(); resize.disconnect(); + wrapper.ownerDocument.removeEventListener('scroll', schedule, true); + wrapper.ownerDocument.fonts?.removeEventListener('loadingdone', schedule); + }; + }, [target, excerpts, turnId]); + + useLayoutEffect(() => { + const wrapper = target && 'current' in target ? target.current : target; + if (!wrapper) return; + const update = () => { + const next = new Map(); + for (const group of groups) { + const marker = markerRefs.current.get(group.key); + if (!marker) continue; + const size = marker.getBoundingClientRect(); + const position = measureExcerptMarkerPosition(wrapper, group.element, group.range, size); + if (!position) continue; + next.set(group.key, position); + } + setPositions(previous => previous.size === next.size && [...next].every(([key, value]) => + previous.get(key)?.left === value.left && previous.get(key)?.top === value.top) ? previous : next); + }; + update(); + const resize = new ResizeObserver(update); + markerRefs.current.forEach(marker => resize.observe(marker)); + return () => resize.disconnect(); + }, [target, groups]); + + return <>{groups.map(group => ( + { if (element) markerRefs.current.set(group.key, element); else markerRefs.current.delete(group.key); }} + data-openbitfun-product-component="conversation-excerpt" data-openbitfun-product-part="markers" + className="conversation-excerpt__markers" data-flowchat-selection-ignore="true" + style={{ left: positions.get(group.key)?.left ?? 0, top: positions.get(group.key)?.top ?? 0, + visibility: positions.has(group.key) ? 'visible' : 'hidden' }}> + {group.excerpts.map(excerpt => )} + + ))}; +} diff --git a/src/web-ui/src/flow_chat/timeline/FlowChatReaderProvider.tsx b/src/web-ui/src/flow_chat/timeline/FlowChatReaderProvider.tsx new file mode 100644 index 0000000000..1a6a9c3e54 --- /dev/null +++ b/src/web-ui/src/flow_chat/timeline/FlowChatReaderProvider.tsx @@ -0,0 +1,10 @@ +import type { ReactNode } from 'react'; +import type { FlowChatReaderState } from './readerState'; +import { ReaderContext, ItemContext } from './readerContexts'; + +export function FlowChatReaderProvider({ store, children }: { store: FlowChatReaderState; children: ReactNode }) { + return {children}; +} +export function FlowChatCardReaderProvider({ itemKey, children }: { itemKey: string; children: ReactNode }) { + return {children}; +} diff --git a/src/web-ui/src/flow_chat/timeline/readerContexts.ts b/src/web-ui/src/flow_chat/timeline/readerContexts.ts new file mode 100644 index 0000000000..5fecd91978 --- /dev/null +++ b/src/web-ui/src/flow_chat/timeline/readerContexts.ts @@ -0,0 +1,5 @@ +import { createContext } from 'react'; +import type { FlowChatReaderState } from './readerState'; + +export const ReaderContext = createContext(null); +export const ItemContext = createContext(''); diff --git a/src/web-ui/src/flow_chat/timeline/readerLifecycle.test.tsx b/src/web-ui/src/flow_chat/timeline/readerLifecycle.test.tsx index 2d5af3387b..d2119df6d5 100644 --- a/src/web-ui/src/flow_chat/timeline/readerLifecycle.test.tsx +++ b/src/web-ui/src/flow_chat/timeline/readerLifecycle.test.tsx @@ -3,7 +3,8 @@ import React, { act } from 'react'; import { createRoot } from 'react-dom/client'; import { expect, it, vi } from 'vitest'; import { TimelineContentBlock } from './TimelineContentBlock'; -import { FlowChatReaderProvider, FlowChatReaderState, useFlowChatReaderValue } from './readerState'; +import { FlowChatReaderState, useFlowChatReaderValue } from './readerState'; +import { FlowChatReaderProvider } from './FlowChatReaderProvider'; import type { VirtualItem } from '../types/flow-chat-projection'; vi.mock('@/infrastructure/i18n', () => ({ useI18n: () => ({ t: (key: string) => key, formatNumber: String }) })); diff --git a/src/web-ui/src/flow_chat/timeline/readerState.tsx b/src/web-ui/src/flow_chat/timeline/readerState.ts similarity index 91% rename from src/web-ui/src/flow_chat/timeline/readerState.tsx rename to src/web-ui/src/flow_chat/timeline/readerState.ts index c88907995f..2b6243d373 100644 --- a/src/web-ui/src/flow_chat/timeline/readerState.tsx +++ b/src/web-ui/src/flow_chat/timeline/readerState.ts @@ -1,4 +1,5 @@ -import { createContext, useCallback, useContext, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore, type Dispatch, type ReactNode, type SetStateAction } from 'react'; +import { ReaderContext, ItemContext } from './readerContexts'; +import { useCallback, useContext, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore, type Dispatch, type SetStateAction } from 'react'; type ReaderValue = boolean | number | string; type Listener = () => void; @@ -124,15 +125,7 @@ export function getFlowChatReaderState(scope: string): FlowChatReaderState { return store; } -const ReaderContext = createContext(null); export const useFlowChatReaderStore = () => useContext(ReaderContext); -const ItemContext = createContext(''); -export function FlowChatReaderProvider({ store, children }: { store: FlowChatReaderState; children: ReactNode }) { - return {children}; -} -export function FlowChatCardReaderProvider({ itemKey, children }: { itemKey: string; children: ReactNode }) { - return {children}; -} /** Reader choices survive viewport recycling; execution/completion never resets them. */ export function useFlowChatReaderValue(key: string, initial: T): [T, Dispatch>] { diff --git a/src/web-ui/src/flow_chat/tool-cards/ModelThinkingDisplay.test.tsx b/src/web-ui/src/flow_chat/tool-cards/ModelThinkingDisplay.test.tsx index 5382304087..2c4fc25795 100644 --- a/src/web-ui/src/flow_chat/tool-cards/ModelThinkingDisplay.test.tsx +++ b/src/web-ui/src/flow_chat/tool-cards/ModelThinkingDisplay.test.tsx @@ -10,7 +10,8 @@ import { ModelThinkingDisplay } from './ModelThinkingDisplay'; import { latestReasoningSummaryPreview } from '../utils/reasoningSummaryPresentation'; import { openThinkingPanel } from '../services/openThinkingPanel'; import { FlowChatContext } from '../components/modern/FlowChatContext'; -import { FlowChatReaderProvider, FlowChatReaderState } from '../timeline/readerState'; +import { FlowChatReaderState } from '../timeline/readerState'; +import { FlowChatReaderProvider } from '../timeline/FlowChatReaderProvider'; import { activateSurface, getActiveSurfaceId } from '@/infrastructure/peer-device/deviceSurface'; vi.mock('../utils/reasoningSummaryPresentation', { spy: true }); diff --git a/src/web-ui/src/infrastructure/file-export/saveHtmlFile.ts b/src/web-ui/src/infrastructure/file-export/saveHtmlFile.ts index 4739a3522e..350485c59f 100644 --- a/src/web-ui/src/infrastructure/file-export/saveHtmlFile.ts +++ b/src/web-ui/src/infrastructure/file-export/saveHtmlFile.ts @@ -2,6 +2,8 @@ import { downloadTextFileInBrowser } from '@/shared/utils/browserDownload'; export function safeHtmlFileName(title: string): string { let stem = title.trim().replace(/\.html?$/i, '') + // Windows filenames must replace C0 control characters as well as reserved punctuation. + // eslint-disable-next-line no-control-regex .replace(/[\\/:*?"<>|\u0000-\u001f]+/g, '-') .slice(0, 96).replace(/[.\s]+$/g, '').trim(); if (!stem) stem = 'OpenBitFun'; diff --git a/src/web-ui/src/infrastructure/markdown/remarkStreamingTableLinks.ts b/src/web-ui/src/infrastructure/markdown/remarkStreamingTableLinks.ts index ade0da6d84..22552dee2d 100644 --- a/src/web-ui/src/infrastructure/markdown/remarkStreamingTableLinks.ts +++ b/src/web-ui/src/infrastructure/markdown/remarkStreamingTableLinks.ts @@ -1,7 +1,7 @@ import type { Nodes, Parent, Root, TableCell } from 'mdast'; import { parseEntities } from 'parse-entities'; -const ESCAPE = /[!-/:-@\[-`{-~]/; +const ESCAPE = /[!-/:-@[-`{-~]/; const OPAQUE = new Set(['inlineCode', 'inlineMath', 'html', 'link', 'linkReference', 'image', 'imageReference']); /** Decode a sliced text node without interpreting escaped ampersands as entities. */ diff --git a/src/web-ui/src/shared/context-menu-system/commands/builtin/PasteCommand.ts b/src/web-ui/src/shared/context-menu-system/commands/builtin/PasteCommand.ts index 12be3f649f..ab749b6c4f 100644 --- a/src/web-ui/src/shared/context-menu-system/commands/builtin/PasteCommand.ts +++ b/src/web-ui/src/shared/context-menu-system/commands/builtin/PasteCommand.ts @@ -46,13 +46,11 @@ export class PasteCommand extends BaseCommand { return await this.executeForTextInput(context as TextInputContext); } - let text: string; - const clipboardText = await readClipboardText(); if (clipboardText === null) { return this.failure(t('errors:contextMenu.clipboardUnavailable')); } - text = clipboardText; + const text = clipboardText; if (!text) { return this.failure(t('errors:contextMenu.clipboardEmpty')); diff --git a/src/web-ui/src/shared/utils/ModuleLoadFailure.tsx b/src/web-ui/src/shared/utils/ModuleLoadFailure.tsx new file mode 100644 index 0000000000..1e30a9e088 --- /dev/null +++ b/src/web-ui/src/shared/utils/ModuleLoadFailure.tsx @@ -0,0 +1,33 @@ +import { Alert, Button } from '@openbitfun/ui'; +import { useTranslation } from 'react-i18next'; + +export function ModuleLoadFailure({ error, retry }: { error: Error; retry: () => void }) { + // Errors is a bootstrap namespace. The fallback must not load another module + // or pull the application service graph into every lazy declaration. + const { t } = useTranslation('errors', { useSuspense: false }); + return ( +
+ + + + + } + /> + {import.meta.env.DEV && ( +
+ {t('boundary.technicalDetails')} + {error.message} +
+ )} +
+ ); +} diff --git a/src/web-ui/src/shared/utils/lazyWithRecovery.tsx b/src/web-ui/src/shared/utils/lazyWithRecovery.tsx index a87cd86cc5..d6aa0d1349 100644 --- a/src/web-ui/src/shared/utils/lazyWithRecovery.tsx +++ b/src/web-ui/src/shared/utils/lazyWithRecovery.tsx @@ -9,8 +9,7 @@ import { type ForwardRefExoticComponent, type LazyExoticComponent, } from 'react'; -import { Alert, Button } from '@openbitfun/ui'; -import { useTranslation } from 'react-i18next'; +import { ModuleLoadFailure } from './ModuleLoadFailure'; import { createLogger } from './logger'; import { createModuleLoader, subscribeToModuleRecovery } from './moduleLoader'; @@ -23,37 +22,6 @@ class ModuleImportError extends Error { } } -function ModuleLoadFailure({ error, retry }: { error: ModuleImportError; retry: () => void }) { - // Errors is a bootstrap namespace. The fallback must not load another module - // or pull the application service graph into every lazy declaration. - const { t } = useTranslation('errors', { useSuspense: false }); - return ( -
- - - - - } - /> - {import.meta.env.DEV && ( -
- {t('boundary.technicalDetails')} - {error.message} -
- )} -
- ); -} - export type RecoverableLazyComponent> = ForwardRefExoticComponent> & { preload: () => Promise<{ default: T }> }; diff --git a/src/web-ui/src/tools/editor/languages/latex.language.ts b/src/web-ui/src/tools/editor/languages/latex.language.ts index dd34ba1210..979ee850e0 100644 --- a/src/web-ui/src/tools/editor/languages/latex.language.ts +++ b/src/web-ui/src/tools/editor/languages/latex.language.ts @@ -16,7 +16,7 @@ export function registerLatexLanguage(monaco: typeof Monaco): void { indentationRules: { increaseIndentPattern: /\\begin\{(?!document)[^}]+\}|\{\s*$/, decreaseIndentPattern: /^\s*(\\end\{|\})/ }, }); monaco.languages.setMonarchTokensProvider('latex', { - tokenizer: { root: [[/\\(?:[A-Za-z@]+|.)/, 'keyword'], [/%.*$/, 'comment'], [/\$\$?/, 'delimiter'], [/[{}\[\]]/, '@brackets']] }, + tokenizer: { root: [[/\\(?:[A-Za-z@]+|.)/, 'keyword'], [/%.*$/, 'comment'], [/\$\$?/, 'delimiter'], [/[{}[\]]/, '@brackets']] }, }); monaco.languages.registerCompletionItemProvider('latex', { triggerCharacters: ['\\', '{', ','], diff --git a/src/web-ui/src/tools/generative-ui/GenUIApplication.tsx b/src/web-ui/src/tools/generative-ui/GenUIApplication.tsx index 1e8f615a49..9a9770e0d0 100644 --- a/src/web-ui/src/tools/generative-ui/GenUIApplication.tsx +++ b/src/web-ui/src/tools/generative-ui/GenUIApplication.tsx @@ -8,9 +8,9 @@ import type { GenUIVerification } from './genUIVerification'; import './GenUIApplication.scss'; import GenUIHostSurface from './GenUIHostSurface'; import GenUISourceDocument from './GenUISourceDocument'; -import { inspectGenUIHtmlSource } from './GenUIHtmlDocument'; +import { inspectGenUIHtmlSource } from './genUIHtmlSource'; import type { GenUIOpenUIActionEvent, GenUIOpenUIToolProvider } from './genUIOpenUI'; -import type { GenUIHtmlBridge } from './GenUIHtmlDocument'; +import type { GenUIHtmlBridge } from './genUIHtmlSource'; import { GenUIStream } from './genUIStream'; import { genUIProduct, type GenUIProduct } from './genUIProduct'; import type { GenUIAsyncRuntime, GenUIProviderInput, GenUITargetEvent } from './genUIAsyncCapabilities'; diff --git a/src/web-ui/src/tools/generative-ui/GenUIHtmlDocument.test.tsx b/src/web-ui/src/tools/generative-ui/GenUIHtmlDocument.test.tsx index 06f361ee72..1ba708a206 100644 --- a/src/web-ui/src/tools/generative-ui/GenUIHtmlDocument.test.tsx +++ b/src/web-ui/src/tools/generative-ui/GenUIHtmlDocument.test.tsx @@ -1,6 +1,6 @@ // @vitest-environment jsdom import { describe, expect, it } from 'vitest'; -import { GENUI_HTML_RUNTIME, inspectGenUIHtmlSource, sanitizeGenUIHtmlSource } from './GenUIHtmlDocument'; +import { GENUI_HTML_RUNTIME, inspectGenUIHtmlSource, sanitizeGenUIHtmlSource } from './genUIHtmlSource'; import { genUICatalog } from './genUIContract'; describe('GenUI HTML documents', () => { diff --git a/src/web-ui/src/tools/generative-ui/GenUIHtmlDocument.tsx b/src/web-ui/src/tools/generative-ui/GenUIHtmlDocument.tsx index 2a8acec4cb..7e30f09af0 100644 --- a/src/web-ui/src/tools/generative-ui/GenUIHtmlDocument.tsx +++ b/src/web-ui/src/tools/generative-ui/GenUIHtmlDocument.tsx @@ -1,340 +1,10 @@ import { useMemo } from 'react'; import { useEffect, useRef } from 'react'; import { useColorScheme } from './components/openui/scheme'; -import { genUICatalog, type GenUIDesignSpec } from './genUIContract'; +import { type GenUIDesignSpec } from './genUIContract'; import type { GenUIHtmlDocumentSource } from './genUITypes'; -export interface GenUIHtmlSanitizeResult { - document: string; - diagnostics: string[]; -} - -export interface GenUIHtmlBridgeContext { - appId: string; - sourceKey: string; - designSpec?: { id: string; revision: number }; - signal: AbortSignal; -} -export interface GenUIHtmlBridgeSchema { - type?: 'object' | 'array' | 'string' | 'number' | 'boolean' | 'null'; - properties?: Record; - required?: string[]; - items?: GenUIHtmlBridgeSchema; - additionalProperties?: boolean; -} -export interface GenUIHtmlBridgeCapability { - payload?: GenUIHtmlBridgeSchema; - permission: string; - remote: 'local' | 'workspace' | 'peer' | 'unsupported'; -} -export interface GenUIHtmlBridge { - capabilities: Record; - handlers: Record unknown | Promise>; -} - -export interface GenUIHtmlFrameReport { - viewportWidth: number; - viewportHeight: number; - clientWidth: number; - clientHeight: number; - scrollWidth: number; - scrollHeight: number; - visibleElementCount: number; - contentBounds: { left: number; top: number; right: number; bottom: number } | null; - renderedEvidence: Array<{ ref: string; label?: string; text?: string; role?: string }>; -} - -export interface GenUIHtmlInspection { - onReport: (report: GenUIHtmlFrameReport) => void; -} - -/** Versioned host capabilities are part of HTML delivery evidence. */ -export const GENUI_HTML_RUNTIME = { - ...genUICatalog.htmlRuntime, -} as const; - -/** - * HTML documents are deliberately accepted as documents, but the document - * boundary is still structural. Keep the active surface small and explicit; - * anything outside this list is removed before the opaque frame is mounted. - * This is the sanitizer contract for revision 2 of the HTML runtime. - */ -const ALLOWED_ELEMENTS = new Set([ - 'html', 'head', 'body', 'title', 'style', - 'main', 'section', 'article', 'header', 'footer', 'aside', 'nav', 'div', 'span', - 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'p', 'br', 'hr', 'strong', 'em', 'b', 'i', 'small', 'sub', 'sup', 'code', 'pre', 'blockquote', - 'ul', 'ol', 'li', 'dl', 'dt', 'dd', - 'figure', 'figcaption', 'details', 'summary', - 'label', 'fieldset', 'legend', 'button', 'input', 'select', 'option', 'textarea', - 'table', 'caption', 'thead', 'tbody', 'tfoot', 'tr', 'th', 'td', - 'a', 'img', 'canvas', 'video', 'audio', - 'svg', 'g', 'path', 'circle', 'ellipse', 'line', 'polyline', 'polygon', 'rect', 'defs', 'lineargradient', 'radialgradient', 'stop', 'clippath', 'mask', 'pattern', 'symbol', 'text', 'tspan', 'marker', 'use', -]); - -const ALLOWED_ATTRIBUTES = new Set([ - 'id', 'class', 'title', 'role', 'tabindex', 'dir', 'lang', 'hidden', 'slot', 'style', - 'href', 'target', 'rel', 'download', 'src', 'alt', 'width', 'height', 'loading', 'decoding', - 'type', 'name', 'value', 'placeholder', 'checked', 'disabled', 'readonly', 'required', 'multiple', 'selected', 'min', 'max', 'step', 'rows', 'cols', 'for', 'autocomplete', 'inputmode', 'accept', - 'viewbox', 'preserveaspectratio', 'fill', 'stroke', 'stroke-width', 'stroke-linecap', 'stroke-linejoin', 'fill-rule', 'clip-rule', 'd', 'cx', 'cy', 'r', 'rx', 'ry', 'x', 'x1', 'x2', 'y', 'y1', 'y2', 'points', 'transform', 'opacity', 'offset', 'stop-color', 'stop-opacity', 'gradientunits', 'gradienttransform', 'patternunits', 'patterncontentunits', 'patterntransform', 'xmlns', 'version', -]); - -function sanitizeCss(css: string): string { - return css - .replace(/@import[^;]+;?/gi, '') - .replace(/url\s*\(\s*['"]?(?:https?:|data:|javascript:|vbscript:|\/\/)[^)]*\)/gi, 'none'); -} - -function sanitizeControlledScript(script: string): string { - // Keep the bridge deliberately small. Dynamic code loading and code - // generation would escape the owner-reviewed source boundary. - return script - .replace(/\beval\s*\(/gi, '/* blocked eval */ (') - .replace(/\bnew\s+Function\s*\(/gi, '/* blocked Function */ (') - .replace(/\bimport\s*\(/gi, '/* blocked import */ ('); -} - -function createCspNonce(): string { - const bytes = new Uint8Array(16); - if (globalThis.crypto?.getRandomValues) globalThis.crypto.getRandomValues(bytes); - else for (let index = 0; index < bytes.length; index += 1) bytes[index] = Math.floor(Math.random() * 256); - return Array.from(bytes, byte => byte.toString(16).padStart(2, '0')).join(''); -} - -function validateBridgePayload(value: unknown, schema: GenUIHtmlBridgeSchema | undefined, path = 'payload'): string | undefined { - if (!schema) return undefined; - const validType = schema.type === undefined - || (schema.type === 'null' ? value === null - : schema.type === 'array' ? Array.isArray(value) - : schema.type === 'object' ? Boolean(value && typeof value === 'object' && !Array.isArray(value)) - : typeof value === schema.type && (schema.type !== 'number' || (typeof value === 'number' && Number.isFinite(value)))); - if (!validType) return `${path} has the wrong type`; - if (Array.isArray(value)) { - for (const [index, item] of value.entries()) { - const error = validateBridgePayload(item, schema.items, `${path}[${index}]`); - if (error) return error; - } - } - if (value && typeof value === 'object' && !Array.isArray(value)) { - const object = value as Record; - for (const key of schema.required ?? []) if (!Object.prototype.hasOwnProperty.call(object, key)) return `${path}.${key} is required`; - for (const [key, entry] of Object.entries(object)) { - const child = schema.properties?.[key]; - if (!child && schema.additionalProperties === false) return `${path}.${key} is unsupported`; - const error = validateBridgePayload(entry, child, `${path}.${key}`); - if (error) return error; - } - } - return undefined; -} - -function bridgeBootstrap(): string { - return `(() => { - const pending = new Map(); - let sequence = 0; - const request = (capability, payload) => new Promise((resolve, reject) => { - const requestId = 'genui-' + (++sequence); - pending.set(requestId, { resolve, reject }); - parent.postMessage({ kind: 'openbitfun.genui.bridge.request', requestId, capability, payload }, '*'); - }); - Object.defineProperty(window, 'openbitfunWidget', { value: Object.freeze({ request }), configurable: false, writable: false }); - addEventListener('message', event => { - if (event.source !== parent || !event.data || event.data.kind !== 'openbitfun.genui.bridge.response') return; - const pendingRequest = pending.get(event.data.requestId); - if (!pendingRequest) return; - pending.delete(event.data.requestId); - if (event.data.ok) pendingRequest.resolve(event.data.value); - else pendingRequest.reject(new Error(String(event.data.error || 'GenUI bridge request failed'))); - }); - })();`; -} - -function inspectionBootstrap(): string { - // This is host-owned, read-only evidence. It is injected only for the - // delivery checker; candidate scripts remain disabled in that path. - return `(() => { - const report = () => { - const body = document.body; - const elements = body ? [...body.querySelectorAll('*')] : []; - let visibleElementCount = 0; - let contentBounds = null; - const renderedEvidence = []; - const seenRefs = new Set(); - for (const element of elements) { - if (['SCRIPT', 'STYLE', 'META', 'LINK'].includes(element.tagName)) continue; - const style = getComputedStyle(element); - const rect = element.getBoundingClientRect(); - if (style.display === 'none' || style.visibility === 'hidden' || rect.width <= 0 || rect.height <= 0) continue; - visibleElementCount += 1; - contentBounds = contentBounds - ? { left: Math.min(contentBounds.left, rect.left), top: Math.min(contentBounds.top, rect.top), right: Math.max(contentBounds.right, rect.right), bottom: Math.max(contentBounds.bottom, rect.bottom) } - : { left: rect.left, top: rect.top, right: rect.right, bottom: rect.bottom }; - const text = (element.textContent || '').replace(/\\s+/g, ' ').trim().slice(0, 120); - const label = element.getAttribute('aria-label') || element.getAttribute('data-genui-ref') || ''; - const id = element.id || ''; - const role = element.getAttribute('role') || element.tagName.toLowerCase(); - const ref = id ? 'id:' + id : label ? 'aria:' + label : /^(H1|H2|H3|BUTTON|INPUT|SELECT|TEXTAREA|SVG)$/.test(element.tagName) && text ? 'text:' + element.tagName.toLowerCase() + ':' + text : ''; - if (ref && !seenRefs.has(ref)) { seenRefs.add(ref); renderedEvidence.push({ ref, label: label || undefined, text: text || undefined, role }); } - } - const seenText = new Set(); - const textWalker = body ? document.createTreeWalker(body, NodeFilter.SHOW_TEXT) : null; - let textIndex = 0; - for (let node = textWalker?.nextNode(); node; node = textWalker?.nextNode()) { - const text = (node.textContent || '').replace(/\\s+/g, ' ').trim().slice(0, 240); - if (!text || seenText.has(text)) continue; - const parentElement = node.parentElement; - if (!parentElement) continue; - const style = getComputedStyle(parentElement); - if (style.display === 'none' || style.visibility === 'hidden') continue; - seenText.add(text); - const ref = 'text:' + textIndex++; - if (!seenRefs.has(ref)) { seenRefs.add(ref); renderedEvidence.push({ ref, text, role: parentElement.getAttribute('role') || parentElement.tagName.toLowerCase() }); } - } - parent.postMessage({ - kind: 'openbitfun.genui.inspection.report', - report: { - viewportWidth: window.innerWidth, - viewportHeight: window.innerHeight, - clientWidth: document.documentElement?.clientWidth || body?.clientWidth || 0, - clientHeight: document.documentElement?.clientHeight || body?.clientHeight || 0, - scrollWidth: Math.max(document.documentElement?.scrollWidth || 0, body?.scrollWidth || 0), - scrollHeight: Math.max(document.documentElement?.scrollHeight || 0, body?.scrollHeight || 0), - visibleElementCount, - contentBounds, - renderedEvidence, - }, - }, '*'); - }; - addEventListener('message', event => { - if (event.source === parent && event.data?.kind === 'openbitfun.genui.inspection.request') { - setTimeout(report, 0); - requestAnimationFrame(() => requestAnimationFrame(report)); - } - }); - setTimeout(report, 0); - requestAnimationFrame(() => requestAnimationFrame(report)); - })();`; -} - -/** - * Keep free documents as documents. The parser only removes host escape paths; - * it does not translate the document into the component graph. Scripts are - * retained in the source record but are deliberately disabled by this static - * renderer until a host has negotiated the controlled bridge capability. - */ -export function sanitizeGenUIHtmlSource(source: GenUIHtmlDocumentSource, specification?: GenUIDesignSpec, hostStyleResourceCss = '', scriptEnabled = false, inspectionEnabled = false, inlineScriptEnabled = false, colorScheme: 'light' | 'dark' = 'light'): GenUIHtmlSanitizeResult { - const diagnostics: string[] = []; - const allowControlledScript = scriptEnabled && !inspectionEnabled; - const scriptNonce = allowControlledScript || inspectionEnabled ? createCspNonce() : undefined; - const parsed = new DOMParser().parseFromString(source.html, 'text/html'); - // HtmlView is a trusted product component with a separate opt-in for its - // local animation script. Free HTML documents keep scripts in their own - // source.script field, so inline document scripts remain disabled there. - const inlineScript = inlineScriptEnabled - ? [...parsed.querySelectorAll('script')].map(script => script.textContent ?? '').filter(Boolean).join('\n') - : ''; - parsed.querySelectorAll('*').forEach(element => { - const tagName = element.tagName.toLowerCase(); - if (!ALLOWED_ELEMENTS.has(tagName)) { - if (tagName === 'script' && inlineScriptEnabled) { - element.remove(); - return; - } - diagnostics.push(`Removed unsupported element: <${tagName}>`); - element.remove(); - return; - } - for (const attribute of [...element.attributes]) { - const attributeName = attribute.name.toLowerCase(); - if (attributeName.startsWith('on') || (!ALLOWED_ATTRIBUTES.has(attributeName) && !attributeName.startsWith('aria-') && !attributeName.startsWith('data-'))) { - diagnostics.push(`Removed unsupported attribute: ${attribute.name}`); - element.removeAttribute(attribute.name); - continue; - } - if (attributeName === 'style') { - element.setAttribute(attribute.name, sanitizeCss(attribute.value)); - } - if ((attributeName === 'href' || attributeName === 'src' || attributeName === 'xlink:href') - && /^(?:https?:|data:|javascript:|vbscript:|\/\/)/i.test(attribute.value.trim())) { - diagnostics.push(`Removed unsafe URL from ${attribute.name}`); - element.removeAttribute(attribute.name); - } - } - }); - parsed.querySelectorAll('style').forEach(style => { - style.textContent = sanitizeCss(style.textContent ?? ''); - }); - const css = sanitizeCss(source.css ?? ''); - if (css.trim()) { - const style = parsed.createElement('style'); - style.setAttribute('data-gen-ui-source-style', 'true'); - style.textContent = css; - parsed.head.appendChild(style); - } - if (specification) { - const identity = parsed.createElement('meta'); - identity.name = 'openbitfun-design-spec'; - identity.content = `${specification.label}@${specification.revision}`; - parsed.head.appendChild(identity); - const resources = parsed.createElement('meta'); - resources.name = 'openbitfun-style-resources'; - resources.content = specification.styleResources.join(','); - parsed.head.appendChild(resources); - } - if (hostStyleResourceCss.trim()) { - const style = parsed.createElement('style'); - style.setAttribute('data-gen-ui-host-style-resources', 'true'); - style.textContent = hostStyleResourceCss; - parsed.head.appendChild(style); - } - const policy = parsed.createElement('meta'); - policy.httpEquiv = 'Content-Security-Policy'; - policy.content = `default-src 'none'; style-src 'unsafe-inline'; img-src data: blob:; font-src data:; connect-src 'none'; frame-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'; script-src 'none'`; - parsed.head.prepend(policy); - const scripts = [source.script?.trim() ?? '', inlineScript.trim()].filter(Boolean).join('\n'); - if (scripts) { - if (!allowControlledScript) diagnostics.push('Controlled script execution is disabled on this host'); - else { - const script = parsed.createElement('script'); - script.setAttribute('nonce', scriptNonce!); - script.textContent = `${bridgeBootstrap()}\n${sanitizeControlledScript(scripts)}`.replace(/<\/script/gi, '<\\/script'); - parsed.body.appendChild(script); - } - } - if (inspectionEnabled) { - const script = parsed.createElement('script'); - script.setAttribute('nonce', scriptNonce!); - script.textContent = inspectionBootstrap(); - parsed.body.appendChild(script); - } - if (scriptNonce) policy.setAttribute('content', `default-src 'none'; style-src 'unsafe-inline'; img-src data: blob:; font-src data:; connect-src 'none'; frame-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'; script-src 'nonce-${scriptNonce}'`); - return { - document: `${parsed.head.innerHTML}${parsed.body.innerHTML}`, - diagnostics, - }; -} - -export function inspectGenUIHtmlSource(source: GenUIHtmlDocumentSource, specification?: GenUIDesignSpec): string[] { - const { diagnostics } = sanitizeGenUIHtmlSource(source); - const issues = diagnostics.filter(message => message.startsWith('Removed unsafe URL')); - if (specification && !specification.sourceKinds.includes('html-document')) issues.push(`UI specification ${specification.label} does not allow HTML documents`); - const parsed = new DOMParser().parseFromString(source.html, 'text/html'); - for (const selector of specification?.shell.forbiddenContentSelectors ?? []) { - try { - if (parsed.querySelector(selector)) issues.push('Generated document duplicates host-owned shell part: ' + selector); - } catch { - issues.push('Invalid host-owned content selector in UI specification: ' + selector); - } - } - // Reject the unconditionally empty case before mounting an opaque iframe. - // Actual browser inspection still owns visibility, geometry and overflow - // checks for documents that contain content but may be hidden or misplaced - // by their CSS. - const body = parsed.body; - const hasBodyText = Boolean(body?.textContent?.trim()); - const hasRenderableElement = Boolean(body?.querySelector('svg,img,canvas,video,audio,input,button,select,textarea,[role],iframe')); - if (!hasBodyText && !hasRenderableElement) issues.push('HTML document has no visible rendered content'); - return issues; -} +import { sanitizeGenUIHtmlSource, validateBridgePayload, type GenUIHtmlBridge, type GenUIHtmlInspection, type GenUIHtmlFrameReport } from './genUIHtmlSource'; export default function GenUIHtmlDocument({ source, specification, designSpecId, appId = 'unknown', sourceKey = 'unknown', bridge, scriptEnabled = false, inspection }: { source: GenUIHtmlDocumentSource; diff --git a/src/web-ui/src/tools/generative-ui/GenUISourceDocument.tsx b/src/web-ui/src/tools/generative-ui/GenUISourceDocument.tsx index a1fc66cbaa..a6b9dd12ed 100644 --- a/src/web-ui/src/tools/generative-ui/GenUISourceDocument.tsx +++ b/src/web-ui/src/tools/generative-ui/GenUISourceDocument.tsx @@ -1,7 +1,7 @@ import type { GenUIDesignSpec } from './genUIContract'; import type { GenUIRenderDiagnostic } from './genUIRenderDiagnostics'; import GenUIHtmlDocument from './GenUIHtmlDocument'; -import type { GenUIHtmlBridge } from './GenUIHtmlDocument'; +import type { GenUIHtmlBridge } from './genUIHtmlSource'; import GenUIOpenUIDocument from './genUIOpenUI'; import type { GenUIOpenUIActionEvent, GenUIOpenUIToolProvider } from './genUIOpenUI'; import type { GenUILibrary } from './genUILibrary'; diff --git a/src/web-ui/src/tools/generative-ui/components/oiComponentHelpers.tsx b/src/web-ui/src/tools/generative-ui/components/oiComponentHelpers.tsx new file mode 100644 index 0000000000..712aa0dbbc --- /dev/null +++ b/src/web-ui/src/tools/generative-ui/components/oiComponentHelpers.tsx @@ -0,0 +1,88 @@ +import type { ReactNode } from 'react'; +import { iconNames, type IconName } from 'lucide-react/dynamic'; +import type { GenUIComponentImplementation, GenUIComponentProps } from '../genUILibrary'; + +export const str = (value: unknown) => value == null ? '' : String(value); +export const node = (value: unknown) => Boolean(value && typeof value === 'object' && (value as { type?: unknown }).type === 'element'); +export const safeUrl = (value: unknown) => { try { const url = new URL(str(value)); return ['http:', 'https:'].includes(url.protocol) ? url.toString() : ''; } catch { return ''; } }; +export const inlineText = (value: string): ReactNode => { + const pieces: ReactNode[] = []; + const pattern = /(\*\*[^*]+\*\*|__[^_]+__|`[^`]+`|\*[^*]+\*|_[^_]+_|\[[^\]]+\]\([^\s)]+\))/g; + let cursor = 0; + for (const match of value.matchAll(pattern)) { + const start = match.index ?? 0; + if (start > cursor) pieces.push(value.slice(cursor, start)); + const token = match[0]; + if (token.startsWith('**') || token.startsWith('__')) pieces.push({token.slice(2, -2)}); + else if (token.startsWith('`')) pieces.push({token.slice(1, -1)}); + else if (token.startsWith('*') || token.startsWith('_')) pieces.push({token.slice(1, -1)}); + else { + const parts = /^\[([^\]]+)\]\(([^\s)]+)\)$/.exec(token); + const href = parts ? safeUrl(parts[2]) : ''; + pieces.push(href ? {parts?.[1]} : token); + } + cursor = start + token.length; + } + if (cursor < value.length) pieces.push(value.slice(cursor)); + return pieces.length ? pieces : value; +}; +export const render = (value: unknown, renderNode: GenUIComponentProps['renderNode']): ReactNode => { + if (node(value)) return renderNode(value); + if (Array.isArray(value)) return value.flat().map((part, index) => {render(part, renderNode)}); + return inlineText(str(value)); +}; +const inspect = () => true; +export const define = (renderFn: GenUIComponentImplementation['render'], exercise?: GenUIComponentImplementation['exercise']): GenUIComponentImplementation => ({ render: renderFn, inspect, ...(exercise ? { exercise } : {}) }); +export const options = (value: unknown): Array<{ value: string; label: string; description?: string }> => Array.isArray(value) ? value.flat().filter(Boolean).map(item => typeof item === 'string' ? { value: item, label: item } : item as { value: string; label: string; description?: string }) : []; +export const controlOptions = (value: unknown, name: string) => { + const parsed = options(value); + if (parsed.some(option => !option.value) || new Set(parsed.map(option => option.value)).size !== parsed.length) throw new Error(`${name} requires unique options`); + return parsed; +}; +const COLOR_TOKENS: Record = { + ink: 'var(--openbitfun-color-content-primary)', + muted: 'var(--openbitfun-color-content-secondary)', + faint: 'var(--openbitfun-color-content-secondary)', + primary: 'var(--openbitfun-color-accent-default)', + accent: 'var(--openbitfun-color-accent-default)', + border: 'var(--openbitfun-color-border-default)', + canvas: 'var(--openbitfun-color-surface-canvas)', + surface: 'var(--openbitfun-color-surface-panel)', + info: 'var(--openbitfun-color-status-info-content)', + success: 'var(--openbitfun-color-status-success-content)', + warning: 'var(--openbitfun-color-status-warning-content)', + danger: 'var(--openbitfun-color-status-danger-content)', + purple: 'var(--openbitfun-color-accent-default)', + pink: 'var(--openbitfun-color-accent-default)', +}; +export const color = (value: unknown) => typeof value === 'string' ? COLOR_TOKENS[value] ?? value : undefined; +export const length = (value: unknown) => { + if (typeof value === 'number' && Number.isFinite(value)) return `${Math.max(0, value)}px`; + if (typeof value !== 'string') return undefined; + const trimmed = value.trim(); + return /^\d+(?:\.\d+)?(?:px|%|em|rem|vh|vw|fr)$|^auto$/.test(trimmed) ? trimmed : undefined; +}; +export const radius = (value: unknown) => typeof value === 'string' + ? ({ sm: '6px', md: '10px', lg: '14px', xl: '18px', full: '999px' }[value] ?? value) + : length(value); +export const space = (value: unknown) => typeof value === 'number' && Number.isFinite(value) ? `${Math.max(0, value) * 4}px` : undefined; +export const paint = (view: GenUIComponentProps['view']) => ({ fill: color(view.props.fill), stroke: color(view.props.stroke), strokeWidth: typeof view.props.strokeWidth === 'number' ? view.props.strokeWidth : undefined, opacity: typeof view.props.opacity === 'number' ? Math.max(0, Math.min(1, view.props.opacity)) : undefined }); + +const lucideNames = new Set(iconNames); +export function normalizedIconName(value: unknown): IconName | null { + if (typeof value !== 'string') return null; + const normalized = value.trim().replace(/([a-z0-9])([A-Z])/g, '$1-$2').replace(/[\s_]+/g, '-').toLowerCase(); + return lucideNames.has(normalized) ? normalized as IconName : null; +} + +const NUMERIC_TABLE_CELL = /^[-+−]?[$€£¥₹]?\s?\d[\d,]*(\.\d+)?\s?(%|[kKmMbB]|bn)?$/; +export const isNumericTableCell = (value: unknown) => typeof value === 'number' || (typeof value === 'string' && !/^(n\/a|—|–|-)$/i.test(value.trim()) && NUMERIC_TABLE_CELL.test(value.trim())); +const CHART_COLORS = [ + 'var(--openbitfun-color-accent-default)', + 'var(--openbitfun-color-status-warning-content)', + 'var(--openbitfun-color-status-success-content)', + 'var(--openbitfun-color-status-info-content)', + 'var(--openbitfun-color-status-danger-content)', + 'var(--openbitfun-color-content-primary)', +] as const; +export const chartColor = (index: number) => CHART_COLORS[index % CHART_COLORS.length]; diff --git a/src/web-ui/src/tools/generative-ui/components/oiComponentRenderers.tsx b/src/web-ui/src/tools/generative-ui/components/oiComponentRenderers.tsx new file mode 100644 index 0000000000..020bed49ad --- /dev/null +++ b/src/web-ui/src/tools/generative-ui/components/oiComponentRenderers.tsx @@ -0,0 +1,198 @@ +import { useEffect, useLayoutEffect, useRef, useState, type CSSProperties } from 'react'; +import { ImageIcon } from 'lucide-react'; +import { i18nService } from '@/infrastructure/i18n'; +import type { GenUIComponentProps } from '../genUILibrary'; +import type { GenUIAsyncRuntime, GenUIAsyncExecuteOptions } from '../genUIAsyncCapabilities'; +import { isAbortError } from '../genUIAsyncCapabilities'; +import { str, safeUrl, inlineText, color, length, radius, space, chartColor } from './oiComponentHelpers'; + +export function Layout({ view, slots }: GenUIComponentProps) { + const props = view.props; + const direction = props.direction === 'row' ? 'row' : 'column'; + const style: CSSProperties = { gap: space(props.gap), padding: space(props.padding), alignItems: props.align === 'start' ? 'flex-start' : props.align === 'end' ? 'flex-end' : props.align === 'center' ? 'center' : props.align === 'stretch' ? 'stretch' : undefined, justifyContent: props.justify === 'between' ? 'space-between' : props.justify === 'start' ? 'flex-start' : props.justify === 'end' ? 'flex-end' : props.justify === 'center' ? 'center' : undefined, flexWrap: props.wrap ? 'wrap' : undefined, background: color(props.background), borderRadius: radius(props.radius), overflow: props.radius !== undefined ? 'clip' : undefined, border: props.border ? '1px solid var(--openbitfun-color-border-default)' : undefined, width: length(props.width), height: length(props.height), flex: typeof props.flex === 'number' ? `${Math.max(0, props.flex)} 1 0%` : typeof props.width === 'number' ? '0 0 auto' : undefined }; + return
{slots.children}
; +} + +function imageUrls(value: unknown): string[] { + const record = value && typeof value === 'object' && !Array.isArray(value) ? value as Record : undefined; + const nested = record && Array.isArray(record.results) ? record.results : []; + const providerBuckets = record + ? ['wiki', 'imageSearch', 'image_search', 'search'].flatMap(key => { + const bucket = record[key]; + if (!bucket || typeof bucket !== 'object') return []; + const nestedRecord = bucket as Record; + return [ + ...(Array.isArray(nestedRecord.photos) ? nestedRecord.photos : []), + ...(Array.isArray(nestedRecord.images) ? nestedRecord.images : []), + ...(Array.isArray(nestedRecord.results) ? nestedRecord.results : []), + ]; + }) + : []; + const values = Array.isArray(value) ? value : record + ? [ + ...(Array.isArray(record.images) ? record.images : []), + ...(Array.isArray(record.photos) ? record.photos : []), + ...(Array.isArray(record.urls) ? record.urls : []), + ...nested, + ...providerBuckets, + record.src, + record.url, + record.image_url, + ] + : [value]; + const normalized = values.flatMap(item => item && typeof item === 'object' ? [ + (item as Record).src, + (item as Record).url, + (item as Record).image_url, + (item as Record).imageUrl, + (item as Record).thumbnail, + (item as Record).thumbnailUrl, + (item as Record).original, + (item as Record).originalUrl, + ] : [item]); + return [...new Set(normalized.filter((item): item is string => typeof item === 'string' && Boolean(safeUrl(item))))]; +} +// Provider results can be host- or target-specific, so cache only within the +// owning async runtime rather than sharing URLs between sessions or peers. +const imageResultCaches = new WeakMap>(); +function imageResultCacheFor(runtime: GenUIAsyncRuntime): Map { + const owner = runtime as object; + let cache = imageResultCaches.get(owner); + if (!cache) { + cache = new Map(); + imageResultCaches.set(owner, cache); + } + return cache; +} +function useSearchImage(query: string, explicit: string | undefined, asyncRuntime?: GenUIAsyncRuntime) { + const [fallbackQuery, setFallbackQuery] = useState(''); + const [state, setState] = useState<{ query: string; candidates: string[]; failed: string[]; loading?: boolean; error?: string }>({ query: '', candidates: [], failed: [] }); + useEffect(() => { + const candidate = safeUrl(explicit); + if (!query.trim()) { setState({ query, candidates: [], failed: [] }); return undefined; } + const shouldSearch = !candidate || fallbackQuery === query; + if (!shouldSearch) { + setState({ query, candidates: [candidate], failed: [] }); + return undefined; + } + const controller = new AbortController(); + const runtime = asyncRuntime; + const imageCapability = runtime?.can('image.search') ? 'image.search' : runtime?.can('SearchImage') ? 'SearchImage' : undefined; + if (!runtime || !imageCapability) { + setState({ query, candidates: candidate ? [candidate] : [], failed: [], error: 'Image search is unavailable on this host' }); + return () => controller.abort('Image search effect was replaced'); + } + const imageResultCache = imageResultCacheFor(runtime); + const cached = imageResultCache.get(query); + if (cached?.length) { + setState({ query, candidates: cached, failed: [] }); + return undefined; + } + setState({ query, candidates: candidate ? [candidate] : [], failed: [], loading: true }); + const timer = window.setTimeout(() => { + const options: GenUIAsyncExecuteOptions = { kind: 'image-search', signal: controller.signal }; + void runtime.execute(imageCapability, { query }, options).then(result => { + if (!controller.signal.aborted) { + const candidates = imageUrls(result); + if (candidates.length) { + if (imageResultCache.size >= 200) imageResultCache.delete(imageResultCache.keys().next().value!); + imageResultCache.set(query, candidates); + } + setState({ query, candidates, failed: [], error: candidates.length ? undefined : 'No image found' }); + } + }).catch(error => { + if (!controller.signal.aborted && !isAbortError(error)) setState({ query, candidates: [], failed: [], error: error instanceof Error ? error.message : String(error) }); + }); + }, 500); + return () => { controller.abort('Image query was replaced'); window.clearTimeout(timer); }; + }, [asyncRuntime, explicit, fallbackQuery, query]); + const current = state.query === query ? state.candidates.find(src => !state.failed.includes(src)) : undefined; + const onError = current ? () => { + const shouldFallback = state.query === query + && state.candidates.filter(src => !state.failed.includes(src)).length <= 1 + && Boolean(safeUrl(explicit)) + && fallbackQuery !== query; + if (shouldFallback) setFallbackQuery(query); + setState(previous => { + if (previous.query !== query || previous.failed.includes(current)) return previous; + const failed = [...previous.failed, current]; + if (previous.candidates.some(src => !failed.includes(src))) return { ...previous, failed }; + if (shouldFallback) return { ...previous, failed, loading: true, error: undefined }; + return { ...previous, failed, error: 'Image could not be loaded' }; + }); + } : undefined; + return { src: current, onError, loading: state.query === query && state.loading === true, error: state.query === query ? state.error : undefined }; +} +export function ImageView({ view, asyncRuntime }: Pick) { + const alt = str(view.props.alt ?? view.props.query); + const image = useSearchImage(str(view.props.query ?? alt), str(view.props.src), asyncRuntime); + const aspectRatio = typeof view.props.aspectRatio === 'number' && view.props.aspectRatio > 0.2 && view.props.aspectRatio < 5 ? view.props.aspectRatio : 1.5; + return
+ {image.src ? {alt} : image.loading ? null :
} +
{view.props.caption ? inlineText(str(view.props.caption)) : image.error ? image.error : null}
+
; +} + +type ChartRow = Record; +const chartNumber = (value: unknown) => typeof value === 'number' && Number.isFinite(value) ? value : Number(value) || 0; +function chartFormat(value: number, kind: unknown, currency: unknown, compact = false) { + if (kind === 'percent') return `${Number(value.toFixed(compact ? 1 : 2))}%`; + const code = typeof currency === 'string' && /^[A-Za-z]{3}$/.test(currency) ? currency.toUpperCase() : 'USD'; + const options: Intl.NumberFormatOptions = { maximumFractionDigits: compact ? 1 : 2, notation: compact && Math.abs(value) >= 1000 ? 'compact' : 'standard' }; + return i18nService.formatNumber(value, kind === 'currency' ? { ...options, style: 'currency', currency: code } : options); +} +function chartAxis(values: number[]) { + const min = Math.min(0, ...values), max = Math.max(1, ...values), step = (max - min || 1) / 4; + return { min, max, step }; +} +export function ChartView({ view }: Pick) { + const containerRef = useRef(null); + const [containerWidth, setContainerWidth] = useState(640); + useLayoutEffect(() => { + const measure = () => { + const measured = containerRef.current?.clientWidth; + if (measured) setContainerWidth(Math.max(280, Math.min(720, measured))); + }; + measure(); + if (typeof ResizeObserver === 'undefined' || !containerRef.current) return; + const observer = new ResizeObserver(measure); + observer.observe(containerRef.current); + return () => observer.disconnect(); + }, []); + const data = Array.isArray(view.props.data) ? view.props.data.filter((row): row is ChartRow => Boolean(row && typeof row === 'object' && !Array.isArray(row))) : []; + const type = ['bar', 'line', 'area', 'pie', 'donut', 'scatter'].includes(str(view.props.type)) ? str(view.props.type) : 'bar'; + const first = data[0] ?? {}; + const keys = Object.keys(first); + const x = typeof view.props.x === 'string' && keys.includes(view.props.x) ? view.props.x : keys[0] ?? 'x'; + const series = Array.isArray(view.props.series) && view.props.series.length ? view.props.series.map(String) : keys.filter(key => key !== x && data.some(row => typeof row[key] === 'number')); + const stacked = view.props.stacked === true && type !== 'line'; + const width = containerWidth; + const height = typeof view.props.height === 'number' ? Math.min(480, Math.max(150, view.props.height)) : 240; + const [hover, setHover] = useState(null); + if (!data.length || !series.length) return
; + if (type === 'pie' || type === 'donut') { + const valueKey = series[0]; + const values = data.map(row => Math.max(0, chartNumber(row[valueKey]))); + const total = values.reduce((sum, value) => sum + value, 0) || 1; + const cx = 130, cy = 120, radius = 92, inner = type === 'donut' ? 54 : 0; + let angle = -Math.PI / 2; + const point = (r: number, a: number) => `${cx + r * Math.cos(a)},${cy + r * Math.sin(a)}`; + return
{values.map((value, index) => { const sweep = value / total * Math.PI * 2; const start = angle; angle += sweep; const end = angle; if (sweep > Math.PI * 2 - 0.001) return ; const large = sweep > Math.PI ? 1 : 0; const path = inner ? `M${point(radius, start)}A${radius},${radius} 0 ${large} 1 ${point(radius, end)}L${point(inner, end)}A${inner},${inner} 0 ${large} 0 ${point(inner, start)}Z` : `M${cx},${cy}L${point(radius, start)}A${radius},${radius} 0 ${large} 1 ${point(radius, end)}Z`; return {`${str(data[index][x])}: ${chartFormat(value, view.props.format, view.props.currency)}`}; })}
{data.map((row, index) => {str(row[x])} {Math.round(values[index] / total * 1000) / 10}%)}
; + } + const tops = data.map(row => { + let total = 0; + return series.map(key => total += Math.max(0, chartNumber(row[key]))); + }); + const allValues = stacked ? tops.map(values => values.at(-1) ?? 0) : data.flatMap(row => series.map(key => chartNumber(row[key]))); + const axis = chartAxis(allValues); + const pad = { top: 14, right: 12, bottom: 34, left: 58 }; + const plotW = width - pad.left - pad.right, plotH = height - pad.top - pad.bottom; + const xAt = (index: number) => pad.left + plotW * (data.length === 1 ? 0.5 : index / (data.length - 1)); + const yAt = (value: number) => pad.top + plotH - ((value - axis.min) / (axis.max - axis.min || 1)) * plotH; + const labelEvery = Math.max(1, Math.ceil(data.length / 8)); + const scatterX = (row: ChartRow, index: number) => typeof row[x] === 'number' ? chartNumber(row[x]) : index; + const scatterValues = data.map(scatterX); + const scatterAxis = type === 'scatter' ? chartAxis(scatterValues) : axis; + const scatterXAt = (value: number) => pad.left + ((value - scatterAxis.min) / (scatterAxis.max - scatterAxis.min || 1)) * plotW; + return
setHover(null)}>{[0, 1, 2, 3, 4].map(tick => { const value = axis.min + (axis.max - axis.min) * tick / 4; return {chartFormat(value, view.props.format, view.props.currency, true)}; })}{data.map((row, index) => index % labelEvery === 0 ? {str(row[x])} : null)}{type === 'bar' && data.map((row, index) => { const groupW = plotW / Math.max(1, data.length); const inner = Math.min(groupW * 0.7, 72 * Math.max(1, stacked ? 1 : series.length)); if (stacked) return series.map((key, seriesIndex) => { const top = yAt(tops[index][seriesIndex]); const base = yAt(tops[index][seriesIndex - 1] ?? 0); return setHover(index)} />; }); const barW = Math.max(4, inner / series.length); return series.map((key, seriesIndex) => { const value = chartNumber(row[key]); const xPos = xAt(index) - inner / 2 + seriesIndex * barW; return setHover(index)} />; }); })}{(type === 'line' || type === 'area') && series.map((key, seriesIndex) => { const top = (index: number) => stacked ? tops[index][seriesIndex] : chartNumber(data[index][key]); const base = (index: number) => stacked ? (tops[index][seriesIndex - 1] ?? 0) : 0; const points = data.map((_, index) => `${xAt(index)},${yAt(top(index))}`).join(' '); const under = data.map((_, index) => `${xAt(index)},${yAt(base(index))}`).reverse().join(' '); return {type === 'area' ? : null} setHover(null)} />{data.map((_, index) => setHover(index)} />)}; })}{type === 'scatter' && series.map((key, seriesIndex) => data.map((row, index) => setHover(index)} />))}{hover !== null ?
{str(data[hover]?.[x])}{series.map(key => {key}: {chartFormat(chartNumber(data[hover]?.[key]), view.props.format, view.props.currency)})}
: null}
{series.length > 1 ? series.map((key, index) => {key}) : null}
; +} diff --git a/src/web-ui/src/tools/generative-ui/components/oiComponents.tsx b/src/web-ui/src/tools/generative-ui/components/oiComponents.tsx index 5a24f32c52..632dee9fb1 100644 --- a/src/web-ui/src/tools/generative-ui/components/oiComponents.tsx +++ b/src/web-ui/src/tools/generative-ui/components/oiComponents.tsx @@ -1,293 +1,18 @@ import katex from 'katex'; import 'katex/dist/katex.min.css'; -import { Children, useEffect, useLayoutEffect, useRef, useState, type CSSProperties, type ReactNode } from 'react'; +import { Children, useEffect, useLayoutEffect, useRef, useState } from 'react'; import { Portal } from '@openbitfun/ui'; import { getAppearanceOverlayHost } from '@/infrastructure/appearance/runtime/AppearanceOverlayHost'; import ReactMarkdown from 'react-markdown'; import remarkGfm from 'remark-gfm'; -import { DynamicIcon, iconNames, type IconName } from 'lucide-react/dynamic'; -import { ImageIcon } from 'lucide-react'; +import { DynamicIcon } from 'lucide-react/dynamic'; import { i18nService } from '@/infrastructure/i18n'; -import type { GenUIComponentImplementation, GenUIComponentProps, GenUIImplementations } from '../genUILibrary'; -import { sanitizeGenUIHtmlSource } from '../GenUIHtmlDocument'; -import type { GenUIAsyncRuntime, GenUIAsyncExecuteOptions } from '../genUIAsyncCapabilities'; -import { isAbortError } from '../genUIAsyncCapabilities'; +import type { GenUIImplementations } from '../genUILibrary'; +import { sanitizeGenUIHtmlSource } from '../genUIHtmlSource'; import MapView from './map/MapView'; -const str = (value: unknown) => value == null ? '' : String(value); -const node = (value: unknown) => Boolean(value && typeof value === 'object' && (value as { type?: unknown }).type === 'element'); -const safeUrl = (value: unknown) => { try { const url = new URL(str(value)); return ['http:', 'https:'].includes(url.protocol) ? url.toString() : ''; } catch { return ''; } }; -const inlineText = (value: string): ReactNode => { - const pieces: ReactNode[] = []; - const pattern = /(\*\*[^*]+\*\*|__[^_]+__|`[^`]+`|\*[^*]+\*|_[^_]+_|\[[^\]]+\]\([^\s)]+\))/g; - let cursor = 0; - for (const match of value.matchAll(pattern)) { - const start = match.index ?? 0; - if (start > cursor) pieces.push(value.slice(cursor, start)); - const token = match[0]; - if (token.startsWith('**') || token.startsWith('__')) pieces.push({token.slice(2, -2)}); - else if (token.startsWith('`')) pieces.push({token.slice(1, -1)}); - else if (token.startsWith('*') || token.startsWith('_')) pieces.push({token.slice(1, -1)}); - else { - const parts = /^\[([^\]]+)\]\(([^\s)]+)\)$/.exec(token); - const href = parts ? safeUrl(parts[2]) : ''; - pieces.push(href ? {parts?.[1]} : token); - } - cursor = start + token.length; - } - if (cursor < value.length) pieces.push(value.slice(cursor)); - return pieces.length ? pieces : value; -}; -const render = (value: unknown, renderNode: GenUIComponentProps['renderNode']): ReactNode => { - if (node(value)) return renderNode(value); - if (Array.isArray(value)) return value.flat().map((part, index) => {render(part, renderNode)}); - return inlineText(str(value)); -}; -const inspect = () => true; -const define = (renderFn: GenUIComponentImplementation['render'], exercise?: GenUIComponentImplementation['exercise']): GenUIComponentImplementation => ({ render: renderFn, inspect, ...(exercise ? { exercise } : {}) }); -const options = (value: unknown): Array<{ value: string; label: string; description?: string }> => Array.isArray(value) ? value.flat().filter(Boolean).map(item => typeof item === 'string' ? { value: item, label: item } : item as { value: string; label: string; description?: string }) : []; -const controlOptions = (value: unknown, name: string) => { - const parsed = options(value); - if (parsed.some(option => !option.value) || new Set(parsed.map(option => option.value)).size !== parsed.length) throw new Error(`${name} requires unique options`); - return parsed; -}; -const COLOR_TOKENS: Record = { - ink: 'var(--openbitfun-color-content-primary)', - muted: 'var(--openbitfun-color-content-secondary)', - faint: 'var(--openbitfun-color-content-secondary)', - primary: 'var(--openbitfun-color-accent-default)', - accent: 'var(--openbitfun-color-accent-default)', - border: 'var(--openbitfun-color-border-default)', - canvas: 'var(--openbitfun-color-surface-canvas)', - surface: 'var(--openbitfun-color-surface-panel)', - info: 'var(--openbitfun-color-status-info-content)', - success: 'var(--openbitfun-color-status-success-content)', - warning: 'var(--openbitfun-color-status-warning-content)', - danger: 'var(--openbitfun-color-status-danger-content)', - purple: 'var(--openbitfun-color-accent-default)', - pink: 'var(--openbitfun-color-accent-default)', -}; -const color = (value: unknown) => typeof value === 'string' ? COLOR_TOKENS[value] ?? value : undefined; -const length = (value: unknown) => { - if (typeof value === 'number' && Number.isFinite(value)) return `${Math.max(0, value)}px`; - if (typeof value !== 'string') return undefined; - const trimmed = value.trim(); - return /^\d+(?:\.\d+)?(?:px|%|em|rem|vh|vw|fr)$|^auto$/.test(trimmed) ? trimmed : undefined; -}; -const radius = (value: unknown) => typeof value === 'string' - ? ({ sm: '6px', md: '10px', lg: '14px', xl: '18px', full: '999px' }[value] ?? value) - : length(value); -const space = (value: unknown) => typeof value === 'number' && Number.isFinite(value) ? `${Math.max(0, value) * 4}px` : undefined; -const paint = (view: GenUIComponentProps['view']) => ({ fill: color(view.props.fill), stroke: color(view.props.stroke), strokeWidth: typeof view.props.strokeWidth === 'number' ? view.props.strokeWidth : undefined, opacity: typeof view.props.opacity === 'number' ? Math.max(0, Math.min(1, view.props.opacity)) : undefined }); - -const lucideNames = new Set(iconNames); -function normalizedIconName(value: unknown): IconName | null { - if (typeof value !== 'string') return null; - const normalized = value.trim().replace(/([a-z0-9])([A-Z])/g, '$1-$2').replace(/[\s_]+/g, '-').toLowerCase(); - return lucideNames.has(normalized) ? normalized as IconName : null; -} - -function Layout({ view, slots }: GenUIComponentProps) { - const props = view.props; - const direction = props.direction === 'row' ? 'row' : 'column'; - const style: CSSProperties = { gap: space(props.gap), padding: space(props.padding), alignItems: props.align === 'start' ? 'flex-start' : props.align === 'end' ? 'flex-end' : props.align === 'center' ? 'center' : props.align === 'stretch' ? 'stretch' : undefined, justifyContent: props.justify === 'between' ? 'space-between' : props.justify === 'start' ? 'flex-start' : props.justify === 'end' ? 'flex-end' : props.justify === 'center' ? 'center' : undefined, flexWrap: props.wrap ? 'wrap' : undefined, background: color(props.background), borderRadius: radius(props.radius), overflow: props.radius !== undefined ? 'clip' : undefined, border: props.border ? '1px solid var(--openbitfun-color-border-default)' : undefined, width: length(props.width), height: length(props.height), flex: typeof props.flex === 'number' ? `${Math.max(0, props.flex)} 1 0%` : typeof props.width === 'number' ? '0 0 auto' : undefined }; - return
{slots.children}
; -} - -function imageUrls(value: unknown): string[] { - const record = value && typeof value === 'object' && !Array.isArray(value) ? value as Record : undefined; - const nested = record && Array.isArray(record.results) ? record.results : []; - const providerBuckets = record - ? ['wiki', 'imageSearch', 'image_search', 'search'].flatMap(key => { - const bucket = record[key]; - if (!bucket || typeof bucket !== 'object') return []; - const nestedRecord = bucket as Record; - return [ - ...(Array.isArray(nestedRecord.photos) ? nestedRecord.photos : []), - ...(Array.isArray(nestedRecord.images) ? nestedRecord.images : []), - ...(Array.isArray(nestedRecord.results) ? nestedRecord.results : []), - ]; - }) - : []; - const values = Array.isArray(value) ? value : record - ? [ - ...(Array.isArray(record.images) ? record.images : []), - ...(Array.isArray(record.photos) ? record.photos : []), - ...(Array.isArray(record.urls) ? record.urls : []), - ...nested, - ...providerBuckets, - record.src, - record.url, - record.image_url, - ] - : [value]; - const normalized = values.flatMap(item => item && typeof item === 'object' ? [ - (item as Record).src, - (item as Record).url, - (item as Record).image_url, - (item as Record).imageUrl, - (item as Record).thumbnail, - (item as Record).thumbnailUrl, - (item as Record).original, - (item as Record).originalUrl, - ] : [item]); - return [...new Set(normalized.filter((item): item is string => typeof item === 'string' && Boolean(safeUrl(item))))]; -} -// Provider results can be host- or target-specific, so cache only within the -// owning async runtime rather than sharing URLs between sessions or peers. -const imageResultCaches = new WeakMap>(); -function imageResultCacheFor(runtime: GenUIAsyncRuntime): Map { - const owner = runtime as object; - let cache = imageResultCaches.get(owner); - if (!cache) { - cache = new Map(); - imageResultCaches.set(owner, cache); - } - return cache; -} -function useSearchImage(query: string, explicit: string | undefined, asyncRuntime?: GenUIAsyncRuntime) { - const [fallbackQuery, setFallbackQuery] = useState(''); - const [state, setState] = useState<{ query: string; candidates: string[]; failed: string[]; loading?: boolean; error?: string }>({ query: '', candidates: [], failed: [] }); - useEffect(() => { - const candidate = safeUrl(explicit); - if (!query.trim()) { setState({ query, candidates: [], failed: [] }); return undefined; } - const shouldSearch = !candidate || fallbackQuery === query; - if (!shouldSearch) { - setState({ query, candidates: [candidate], failed: [] }); - return undefined; - } - const controller = new AbortController(); - const runtime = asyncRuntime; - const imageCapability = runtime?.can('image.search') ? 'image.search' : runtime?.can('SearchImage') ? 'SearchImage' : undefined; - if (!runtime || !imageCapability) { - setState({ query, candidates: candidate ? [candidate] : [], failed: [], error: 'Image search is unavailable on this host' }); - return () => controller.abort('Image search effect was replaced'); - } - const imageResultCache = imageResultCacheFor(runtime); - const cached = imageResultCache.get(query); - if (cached?.length) { - setState({ query, candidates: cached, failed: [] }); - return undefined; - } - setState({ query, candidates: candidate ? [candidate] : [], failed: [], loading: true }); - const timer = window.setTimeout(() => { - const options: GenUIAsyncExecuteOptions = { kind: 'image-search', signal: controller.signal }; - void runtime.execute(imageCapability, { query }, options).then(result => { - if (!controller.signal.aborted) { - const candidates = imageUrls(result); - if (candidates.length) { - if (imageResultCache.size >= 200) imageResultCache.delete(imageResultCache.keys().next().value!); - imageResultCache.set(query, candidates); - } - setState({ query, candidates, failed: [], error: candidates.length ? undefined : 'No image found' }); - } - }).catch(error => { - if (!controller.signal.aborted && !isAbortError(error)) setState({ query, candidates: [], failed: [], error: error instanceof Error ? error.message : String(error) }); - }); - }, 500); - return () => { controller.abort('Image query was replaced'); window.clearTimeout(timer); }; - }, [asyncRuntime, explicit, fallbackQuery, query]); - const current = state.query === query ? state.candidates.find(src => !state.failed.includes(src)) : undefined; - const onError = current ? () => { - const shouldFallback = state.query === query - && state.candidates.filter(src => !state.failed.includes(src)).length <= 1 - && Boolean(safeUrl(explicit)) - && fallbackQuery !== query; - if (shouldFallback) setFallbackQuery(query); - setState(previous => { - if (previous.query !== query || previous.failed.includes(current)) return previous; - const failed = [...previous.failed, current]; - if (previous.candidates.some(src => !failed.includes(src))) return { ...previous, failed }; - if (shouldFallback) return { ...previous, failed, loading: true, error: undefined }; - return { ...previous, failed, error: 'Image could not be loaded' }; - }); - } : undefined; - return { src: current, onError, loading: state.query === query && state.loading === true, error: state.query === query ? state.error : undefined }; -} -function ImageView({ view, asyncRuntime }: Pick) { - const alt = str(view.props.alt ?? view.props.query); - const image = useSearchImage(str(view.props.query ?? alt), str(view.props.src), asyncRuntime); - const aspectRatio = typeof view.props.aspectRatio === 'number' && view.props.aspectRatio > 0.2 && view.props.aspectRatio < 5 ? view.props.aspectRatio : 1.5; - return
- {image.src ? {alt} : image.loading ? null :
} -
{view.props.caption ? inlineText(str(view.props.caption)) : image.error ? image.error : null}
-
; -} - -type ChartRow = Record; -const NUMERIC_TABLE_CELL = /^[-+−]?[$€£¥₹]?\s?\d[\d,]*(\.\d+)?\s?(%|[kKmMbB]|bn)?$/; -const isNumericTableCell = (value: unknown) => typeof value === 'number' || (typeof value === 'string' && !/^(n\/a|—|–|-)$/i.test(value.trim()) && NUMERIC_TABLE_CELL.test(value.trim())); -const chartNumber = (value: unknown) => typeof value === 'number' && Number.isFinite(value) ? value : Number(value) || 0; -const CHART_COLORS = [ - 'var(--openbitfun-color-accent-default)', - 'var(--openbitfun-color-status-warning-content)', - 'var(--openbitfun-color-status-success-content)', - 'var(--openbitfun-color-status-info-content)', - 'var(--openbitfun-color-status-danger-content)', - 'var(--openbitfun-color-content-primary)', -] as const; -const chartColor = (index: number) => CHART_COLORS[index % CHART_COLORS.length]; -function chartFormat(value: number, kind: unknown, currency: unknown, compact = false) { - if (kind === 'percent') return `${Number(value.toFixed(compact ? 1 : 2))}%`; - const code = typeof currency === 'string' && /^[A-Za-z]{3}$/.test(currency) ? currency.toUpperCase() : 'USD'; - const options: Intl.NumberFormatOptions = { maximumFractionDigits: compact ? 1 : 2, notation: compact && Math.abs(value) >= 1000 ? 'compact' : 'standard' }; - return i18nService.formatNumber(value, kind === 'currency' ? { ...options, style: 'currency', currency: code } : options); -} -function chartAxis(values: number[]) { - const min = Math.min(0, ...values), max = Math.max(1, ...values), step = (max - min || 1) / 4; - return { min, max, step }; -} -function ChartView({ view }: Pick) { - const containerRef = useRef(null); - const [containerWidth, setContainerWidth] = useState(640); - useLayoutEffect(() => { - const measure = () => { - const measured = containerRef.current?.clientWidth; - if (measured) setContainerWidth(Math.max(280, Math.min(720, measured))); - }; - measure(); - if (typeof ResizeObserver === 'undefined' || !containerRef.current) return; - const observer = new ResizeObserver(measure); - observer.observe(containerRef.current); - return () => observer.disconnect(); - }, []); - const data = Array.isArray(view.props.data) ? view.props.data.filter((row): row is ChartRow => Boolean(row && typeof row === 'object' && !Array.isArray(row))) : []; - const type = ['bar', 'line', 'area', 'pie', 'donut', 'scatter'].includes(str(view.props.type)) ? str(view.props.type) : 'bar'; - const first = data[0] ?? {}; - const keys = Object.keys(first); - const x = typeof view.props.x === 'string' && keys.includes(view.props.x) ? view.props.x : keys[0] ?? 'x'; - const series = Array.isArray(view.props.series) && view.props.series.length ? view.props.series.map(String) : keys.filter(key => key !== x && data.some(row => typeof row[key] === 'number')); - const stacked = view.props.stacked === true && type !== 'line'; - const width = containerWidth; - const height = typeof view.props.height === 'number' ? Math.min(480, Math.max(150, view.props.height)) : 240; - const [hover, setHover] = useState(null); - if (!data.length || !series.length) return
; - if (type === 'pie' || type === 'donut') { - const valueKey = series[0]; - const values = data.map(row => Math.max(0, chartNumber(row[valueKey]))); - const total = values.reduce((sum, value) => sum + value, 0) || 1; - const cx = 130, cy = 120, radius = 92, inner = type === 'donut' ? 54 : 0; - let angle = -Math.PI / 2; - const point = (r: number, a: number) => `${cx + r * Math.cos(a)},${cy + r * Math.sin(a)}`; - return
{values.map((value, index) => { const sweep = value / total * Math.PI * 2; const start = angle; angle += sweep; const end = angle; if (sweep > Math.PI * 2 - 0.001) return ; const large = sweep > Math.PI ? 1 : 0; const path = inner ? `M${point(radius, start)}A${radius},${radius} 0 ${large} 1 ${point(radius, end)}L${point(inner, end)}A${inner},${inner} 0 ${large} 0 ${point(inner, start)}Z` : `M${cx},${cy}L${point(radius, start)}A${radius},${radius} 0 ${large} 1 ${point(radius, end)}Z`; return {`${str(data[index][x])}: ${chartFormat(value, view.props.format, view.props.currency)}`}; })}
{data.map((row, index) => {str(row[x])} {Math.round(values[index] / total * 1000) / 10}%)}
; - } - const tops = data.map(row => { - let total = 0; - return series.map(key => total += Math.max(0, chartNumber(row[key]))); - }); - const allValues = stacked ? tops.map(values => values.at(-1) ?? 0) : data.flatMap(row => series.map(key => chartNumber(row[key]))); - const axis = chartAxis(allValues); - const pad = { top: 14, right: 12, bottom: 34, left: 58 }; - const plotW = width - pad.left - pad.right, plotH = height - pad.top - pad.bottom; - const xAt = (index: number) => pad.left + plotW * (data.length === 1 ? 0.5 : index / (data.length - 1)); - const yAt = (value: number) => pad.top + plotH - ((value - axis.min) / (axis.max - axis.min || 1)) * plotH; - const labelEvery = Math.max(1, Math.ceil(data.length / 8)); - const scatterX = (row: ChartRow, index: number) => typeof row[x] === 'number' ? chartNumber(row[x]) : index; - const scatterValues = data.map(scatterX); - const scatterAxis = type === 'scatter' ? chartAxis(scatterValues) : axis; - const scatterXAt = (value: number) => pad.left + ((value - scatterAxis.min) / (scatterAxis.max - scatterAxis.min || 1)) * plotW; - return
setHover(null)}>{[0, 1, 2, 3, 4].map(tick => { const value = axis.min + (axis.max - axis.min) * tick / 4; return {chartFormat(value, view.props.format, view.props.currency, true)}; })}{data.map((row, index) => index % labelEvery === 0 ? {str(row[x])} : null)}{type === 'bar' && data.map((row, index) => { const groupW = plotW / Math.max(1, data.length); const inner = Math.min(groupW * 0.7, 72 * Math.max(1, stacked ? 1 : series.length)); if (stacked) return series.map((key, seriesIndex) => { const top = yAt(tops[index][seriesIndex]); const base = yAt(tops[index][seriesIndex - 1] ?? 0); return setHover(index)} />; }); const barW = Math.max(4, inner / series.length); return series.map((key, seriesIndex) => { const value = chartNumber(row[key]); const xPos = xAt(index) - inner / 2 + seriesIndex * barW; return setHover(index)} />; }); })}{(type === 'line' || type === 'area') && series.map((key, seriesIndex) => { const top = (index: number) => stacked ? tops[index][seriesIndex] : chartNumber(data[index][key]); const base = (index: number) => stacked ? (tops[index][seriesIndex - 1] ?? 0) : 0; const points = data.map((_, index) => `${xAt(index)},${yAt(top(index))}`).join(' '); const under = data.map((_, index) => `${xAt(index)},${yAt(base(index))}`).reverse().join(' '); return {type === 'area' ? : null} setHover(null)} />{data.map((_, index) => setHover(index)} />)}; })}{type === 'scatter' && series.map((key, seriesIndex) => data.map((row, index) => setHover(index)} />))}{hover !== null ?
{str(data[hover]?.[x])}{series.map(key => {key}: {chartFormat(chartNumber(data[hover]?.[key]), view.props.format, view.props.currency)})}
: null}
{series.length > 1 ? series.map((key, index) => {key}) : null}
; -} +import { Layout, ImageView, ChartView } from './oiComponentRenderers'; +import { str, node, safeUrl, inlineText, render, define, options, controlOptions, color, length, radius, space, paint, normalizedIconName, isNumericTableCell, chartColor } from './oiComponentHelpers'; const inputExercise = (selector: string, event: string, value: unknown, element: HTMLElement) => { const input = element.querySelector(selector); if (event !== 'change' || !input || input.disabled) throw new Error('OpenUI input is unavailable'); const setter = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(input), 'value')?.set; setter?.call(input, String(value)); input.dispatchEvent(new Event('input', { bubbles: true })); input.dispatchEvent(new Event('change', { bubbles: true })); }; diff --git a/src/web-ui/src/tools/generative-ui/components/openui/extra.tsx b/src/web-ui/src/tools/generative-ui/components/openui/extra.tsx index b78fb0f517..ce8deff3d6 100644 --- a/src/web-ui/src/tools/generative-ui/components/openui/extra.tsx +++ b/src/web-ui/src/tools/generative-ui/components/openui/extra.tsx @@ -8,7 +8,7 @@ import { useEffect, useLayoutEffect, useRef, useState, type ReactNode } from "re import { Portal } from "@openbitfun/ui"; import { getAppearanceOverlayHost } from "@/infrastructure/appearance/runtime/AppearanceOverlayHost"; import { z } from "zod/v4"; -import { inline } from "./markdown"; +import { inline } from './inlineMarkdown'; import { children, cx } from "./style"; const str = (value: unknown) => (value == null ? "" : String(value)); diff --git a/src/web-ui/src/tools/generative-ui/components/openui/inlineMarkdown.tsx b/src/web-ui/src/tools/generative-ui/components/openui/inlineMarkdown.tsx new file mode 100644 index 0000000000..14af928482 --- /dev/null +++ b/src/web-ui/src/tools/generative-ui/components/openui/inlineMarkdown.tsx @@ -0,0 +1,44 @@ +import { Fragment, type ReactNode } from "react"; +import { webUrl } from "./style"; + +// A small Markdown renderer that builds React elements and never injects HTML. +// Inline: **bold**, *italic*, ~~strike~~, `code`, [text](https://...). +// Blocks: paragraphs, # headings, - and 1. lists, > quotes, ``` code, ---, | tables |. + +const INLINE = /(`[^`\n]+`)|(\*\*[^*\n]+?\*\*|__[^_\n]+?__)|(~~[^~\n]+?~~)|(\*[^*\s][^*\n]*?\*|_[^_\s][^_\n]*?_)|(\[[^\]\n]+\]\([^)\s]+\))/; + +export function inline(text: string, key = "i"): ReactNode { + const out: ReactNode[] = []; + let rest = text; + let n = 0; + while (rest) { + const m = INLINE.exec(rest); + if (!m) { + out.push(rest); + break; + } + if (m.index) out.push(rest.slice(0, m.index)); + const token = m[0]; + const k = `${key}-${n++}`; + if (m[1]) out.push({token.slice(1, -1)}); + else if (m[2]) out.push({inline(token.slice(2, -2), k)}); + else if (m[3]) out.push({inline(token.slice(2, -2), k)}); + else if (m[4]) out.push({inline(token.slice(1, -1), k)}); + else { + const close = token.indexOf("]("); + const label = token.slice(1, close); + const href = webUrl(token.slice(close + 2, -1)); + out.push( + href ? ( + + {inline(label, k)} + + ) : ( + {inline(label, k)} + ), + ); + } + rest = rest.slice(m.index + token.length); + } + return out.length === 1 ? out[0] : out; +} diff --git a/src/web-ui/src/tools/generative-ui/components/openui/markdown.tsx b/src/web-ui/src/tools/generative-ui/components/openui/markdown.tsx index a7524fe5da..07e04452d3 100644 --- a/src/web-ui/src/tools/generative-ui/components/openui/markdown.tsx +++ b/src/web-ui/src/tools/generative-ui/components/openui/markdown.tsx @@ -1,47 +1,4 @@ -import { Fragment, type ReactNode } from "react"; -import { webUrl } from "./style"; - -// A small Markdown renderer that builds React elements and never injects HTML. -// Inline: **bold**, *italic*, ~~strike~~, `code`, [text](https://...). -// Blocks: paragraphs, # headings, - and 1. lists, > quotes, ``` code, ---, | tables |. - -const INLINE = /(`[^`\n]+`)|(\*\*[^*\n]+?\*\*|__[^_\n]+?__)|(~~[^~\n]+?~~)|(\*[^*\s][^*\n]*?\*|_[^_\s][^_\n]*?_)|(\[[^\]\n]+\]\([^)\s]+\))/; - -export function inline(text: string, key = "i"): ReactNode { - const out: ReactNode[] = []; - let rest = text; - let n = 0; - while (rest) { - const m = INLINE.exec(rest); - if (!m) { - out.push(rest); - break; - } - if (m.index) out.push(rest.slice(0, m.index)); - const token = m[0]; - const k = `${key}-${n++}`; - if (m[1]) out.push({token.slice(1, -1)}); - else if (m[2]) out.push({inline(token.slice(2, -2), k)}); - else if (m[3]) out.push({inline(token.slice(2, -2), k)}); - else if (m[4]) out.push({inline(token.slice(1, -1), k)}); - else { - const close = token.indexOf("]("); - const label = token.slice(1, close); - const href = webUrl(token.slice(close + 2, -1)); - out.push( - href ? ( - - {inline(label, k)} - - ) : ( - {inline(label, k)} - ), - ); - } - rest = rest.slice(m.index + token.length); - } - return out.length === 1 ? out[0] : out; -} +import { inline } from './inlineMarkdown'; type Block = | { kind: "p" | "quote"; text: string } diff --git a/src/web-ui/src/tools/generative-ui/components/openui/svg.tsx b/src/web-ui/src/tools/generative-ui/components/openui/svg.tsx index c2760bec56..52bbe1acca 100644 --- a/src/web-ui/src/tools/generative-ui/components/openui/svg.tsx +++ b/src/web-ui/src/tools/generative-ui/components/openui/svg.tsx @@ -147,5 +147,3 @@ export const SvgText = defineComponent({ ), }); - -export const svgComponents = [Svg, Circle, Ellipse, Rect, Line, Path, Polyline, Polygon, G, SvgText]; diff --git a/src/web-ui/src/tools/generative-ui/components/openui/svgComponents.ts b/src/web-ui/src/tools/generative-ui/components/openui/svgComponents.ts new file mode 100644 index 0000000000..ec1e1aded4 --- /dev/null +++ b/src/web-ui/src/tools/generative-ui/components/openui/svgComponents.ts @@ -0,0 +1,3 @@ +import { Svg, Circle, Ellipse, Rect, Line, Path, Polyline, Polygon, G, SvgText } from './svg'; + +export const svgComponents = [Svg, Circle, Ellipse, Rect, Line, Path, Polyline, Polygon, G, SvgText]; diff --git a/src/web-ui/src/tools/generative-ui/components/openui/table.tsx b/src/web-ui/src/tools/generative-ui/components/openui/table.tsx index fa0e2cd1fc..ee00f9148f 100644 --- a/src/web-ui/src/tools/generative-ui/components/openui/table.tsx +++ b/src/web-ui/src/tools/generative-ui/components/openui/table.tsx @@ -3,7 +3,7 @@ import { defineComponent } from "@openuidev/react-lang"; import { z } from "zod/v4"; import { i18nService } from "@/infrastructure/i18n"; -import { inline } from "./markdown"; +import { inline } from './inlineMarkdown'; import { cx } from "./style"; const NUMERIC = /^[-+−]?[$€£¥₹]?\s?\d[\d,]*(\.\d+)?\s?(%|[kKmMbB]|bn)?$/; diff --git a/src/web-ui/src/tools/generative-ui/components/openui/text.tsx b/src/web-ui/src/tools/generative-ui/components/openui/text.tsx index 1f46b0f8a7..0beeb61df7 100644 --- a/src/web-ui/src/tools/generative-ui/components/openui/text.tsx +++ b/src/web-ui/src/tools/generative-ui/components/openui/text.tsx @@ -5,7 +5,8 @@ import { ArrowUpRight } from "lucide-react"; import { Fragment } from "react"; import { z } from "zod/v4"; import { Glyph } from "./glyph"; -import { inline, MarkdownBlocks } from "./markdown"; +import { MarkdownBlocks } from './markdown'; +import { inline } from './inlineMarkdown'; import { children, color, cx, fg, webUrl } from "./style"; const str = (value: unknown) => (value == null ? "" : String(value)); diff --git a/src/web-ui/src/tools/generative-ui/components/openuiLibrary.tsx b/src/web-ui/src/tools/generative-ui/components/openuiLibrary.tsx index 1d24b96e41..7464039878 100644 --- a/src/web-ui/src/tools/generative-ui/components/openuiLibrary.tsx +++ b/src/web-ui/src/tools/generative-ui/components/openuiLibrary.tsx @@ -32,7 +32,7 @@ import { HtmlView } from './openui/html-view'; import { Box, Card, Col, Divider, Form, Grid, Row, Spacer } from './openui/layout'; import { MapMarker, MapView } from './openui/map/map'; import { Icon, Image, SearchImage } from './openui/media'; -import { svgComponents } from './openui/svg'; +import { svgComponents } from './openui/svgComponents'; import { Table } from './openui/table'; import { Badge, Caption, Label, Link, List, ListItem, Markdown, Text, Title } from './openui/text'; diff --git a/src/web-ui/src/tools/generative-ui/genUIHtmlSource.ts b/src/web-ui/src/tools/generative-ui/genUIHtmlSource.ts new file mode 100644 index 0000000000..fe7d86de11 --- /dev/null +++ b/src/web-ui/src/tools/generative-ui/genUIHtmlSource.ts @@ -0,0 +1,334 @@ +import { genUICatalog, type GenUIDesignSpec } from './genUIContract'; +import type { GenUIHtmlDocumentSource } from './genUITypes'; + +export interface GenUIHtmlSanitizeResult { + document: string; + diagnostics: string[]; +} + +export interface GenUIHtmlBridgeContext { + appId: string; + sourceKey: string; + designSpec?: { id: string; revision: number }; + signal: AbortSignal; +} +export interface GenUIHtmlBridgeSchema { + type?: 'object' | 'array' | 'string' | 'number' | 'boolean' | 'null'; + properties?: Record; + required?: string[]; + items?: GenUIHtmlBridgeSchema; + additionalProperties?: boolean; +} +export interface GenUIHtmlBridgeCapability { + payload?: GenUIHtmlBridgeSchema; + permission: string; + remote: 'local' | 'workspace' | 'peer' | 'unsupported'; +} +export interface GenUIHtmlBridge { + capabilities: Record; + handlers: Record unknown | Promise>; +} + +export interface GenUIHtmlFrameReport { + viewportWidth: number; + viewportHeight: number; + clientWidth: number; + clientHeight: number; + scrollWidth: number; + scrollHeight: number; + visibleElementCount: number; + contentBounds: { left: number; top: number; right: number; bottom: number } | null; + renderedEvidence: Array<{ ref: string; label?: string; text?: string; role?: string }>; +} + +export interface GenUIHtmlInspection { + onReport: (report: GenUIHtmlFrameReport) => void; +} + +/** Versioned host capabilities are part of HTML delivery evidence. */ +export const GENUI_HTML_RUNTIME = { + ...genUICatalog.htmlRuntime, +} as const; + +/** + * HTML documents are deliberately accepted as documents, but the document + * boundary is still structural. Keep the active surface small and explicit; + * anything outside this list is removed before the opaque frame is mounted. + * This is the sanitizer contract for revision 2 of the HTML runtime. + */ +const ALLOWED_ELEMENTS = new Set([ + 'html', 'head', 'body', 'title', 'style', + 'main', 'section', 'article', 'header', 'footer', 'aside', 'nav', 'div', 'span', + 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'p', 'br', 'hr', 'strong', 'em', 'b', 'i', 'small', 'sub', 'sup', 'code', 'pre', 'blockquote', + 'ul', 'ol', 'li', 'dl', 'dt', 'dd', + 'figure', 'figcaption', 'details', 'summary', + 'label', 'fieldset', 'legend', 'button', 'input', 'select', 'option', 'textarea', + 'table', 'caption', 'thead', 'tbody', 'tfoot', 'tr', 'th', 'td', + 'a', 'img', 'canvas', 'video', 'audio', + 'svg', 'g', 'path', 'circle', 'ellipse', 'line', 'polyline', 'polygon', 'rect', 'defs', 'lineargradient', 'radialgradient', 'stop', 'clippath', 'mask', 'pattern', 'symbol', 'text', 'tspan', 'marker', 'use', +]); + +const ALLOWED_ATTRIBUTES = new Set([ + 'id', 'class', 'title', 'role', 'tabindex', 'dir', 'lang', 'hidden', 'slot', 'style', + 'href', 'target', 'rel', 'download', 'src', 'alt', 'width', 'height', 'loading', 'decoding', + 'type', 'name', 'value', 'placeholder', 'checked', 'disabled', 'readonly', 'required', 'multiple', 'selected', 'min', 'max', 'step', 'rows', 'cols', 'for', 'autocomplete', 'inputmode', 'accept', + 'viewbox', 'preserveaspectratio', 'fill', 'stroke', 'stroke-width', 'stroke-linecap', 'stroke-linejoin', 'fill-rule', 'clip-rule', 'd', 'cx', 'cy', 'r', 'rx', 'ry', 'x', 'x1', 'x2', 'y', 'y1', 'y2', 'points', 'transform', 'opacity', 'offset', 'stop-color', 'stop-opacity', 'gradientunits', 'gradienttransform', 'patternunits', 'patterncontentunits', 'patterntransform', 'xmlns', 'version', +]); + +function sanitizeCss(css: string): string { + return css + .replace(/@import[^;]+;?/gi, '') + .replace(/url\s*\(\s*['"]?(?:https?:|data:|javascript:|vbscript:|\/\/)[^)]*\)/gi, 'none'); +} + +function sanitizeControlledScript(script: string): string { + // Keep the bridge deliberately small. Dynamic code loading and code + // generation would escape the owner-reviewed source boundary. + return script + .replace(/\beval\s*\(/gi, '/* blocked eval */ (') + .replace(/\bnew\s+Function\s*\(/gi, '/* blocked Function */ (') + .replace(/\bimport\s*\(/gi, '/* blocked import */ ('); +} + +function createCspNonce(): string { + const bytes = new Uint8Array(16); + if (globalThis.crypto?.getRandomValues) globalThis.crypto.getRandomValues(bytes); + else for (let index = 0; index < bytes.length; index += 1) bytes[index] = Math.floor(Math.random() * 256); + return Array.from(bytes, byte => byte.toString(16).padStart(2, '0')).join(''); +} + +export function validateBridgePayload(value: unknown, schema: GenUIHtmlBridgeSchema | undefined, path = 'payload'): string | undefined { + if (!schema) return undefined; + const validType = schema.type === undefined + || (schema.type === 'null' ? value === null + : schema.type === 'array' ? Array.isArray(value) + : schema.type === 'object' ? Boolean(value && typeof value === 'object' && !Array.isArray(value)) + : typeof value === schema.type && (schema.type !== 'number' || (typeof value === 'number' && Number.isFinite(value)))); + if (!validType) return `${path} has the wrong type`; + if (Array.isArray(value)) { + for (const [index, item] of value.entries()) { + const error = validateBridgePayload(item, schema.items, `${path}[${index}]`); + if (error) return error; + } + } + if (value && typeof value === 'object' && !Array.isArray(value)) { + const object = value as Record; + for (const key of schema.required ?? []) if (!Object.prototype.hasOwnProperty.call(object, key)) return `${path}.${key} is required`; + for (const [key, entry] of Object.entries(object)) { + const child = schema.properties?.[key]; + if (!child && schema.additionalProperties === false) return `${path}.${key} is unsupported`; + const error = validateBridgePayload(entry, child, `${path}.${key}`); + if (error) return error; + } + } + return undefined; +} + +function bridgeBootstrap(): string { + return `(() => { + const pending = new Map(); + let sequence = 0; + const request = (capability, payload) => new Promise((resolve, reject) => { + const requestId = 'genui-' + (++sequence); + pending.set(requestId, { resolve, reject }); + parent.postMessage({ kind: 'openbitfun.genui.bridge.request', requestId, capability, payload }, '*'); + }); + Object.defineProperty(window, 'openbitfunWidget', { value: Object.freeze({ request }), configurable: false, writable: false }); + addEventListener('message', event => { + if (event.source !== parent || !event.data || event.data.kind !== 'openbitfun.genui.bridge.response') return; + const pendingRequest = pending.get(event.data.requestId); + if (!pendingRequest) return; + pending.delete(event.data.requestId); + if (event.data.ok) pendingRequest.resolve(event.data.value); + else pendingRequest.reject(new Error(String(event.data.error || 'GenUI bridge request failed'))); + }); + })();`; +} + +function inspectionBootstrap(): string { + // This is host-owned, read-only evidence. It is injected only for the + // delivery checker; candidate scripts remain disabled in that path. + return `(() => { + const report = () => { + const body = document.body; + const elements = body ? [...body.querySelectorAll('*')] : []; + let visibleElementCount = 0; + let contentBounds = null; + const renderedEvidence = []; + const seenRefs = new Set(); + for (const element of elements) { + if (['SCRIPT', 'STYLE', 'META', 'LINK'].includes(element.tagName)) continue; + const style = getComputedStyle(element); + const rect = element.getBoundingClientRect(); + if (style.display === 'none' || style.visibility === 'hidden' || rect.width <= 0 || rect.height <= 0) continue; + visibleElementCount += 1; + contentBounds = contentBounds + ? { left: Math.min(contentBounds.left, rect.left), top: Math.min(contentBounds.top, rect.top), right: Math.max(contentBounds.right, rect.right), bottom: Math.max(contentBounds.bottom, rect.bottom) } + : { left: rect.left, top: rect.top, right: rect.right, bottom: rect.bottom }; + const text = (element.textContent || '').replace(/\\s+/g, ' ').trim().slice(0, 120); + const label = element.getAttribute('aria-label') || element.getAttribute('data-genui-ref') || ''; + const id = element.id || ''; + const role = element.getAttribute('role') || element.tagName.toLowerCase(); + const ref = id ? 'id:' + id : label ? 'aria:' + label : /^(H1|H2|H3|BUTTON|INPUT|SELECT|TEXTAREA|SVG)$/.test(element.tagName) && text ? 'text:' + element.tagName.toLowerCase() + ':' + text : ''; + if (ref && !seenRefs.has(ref)) { seenRefs.add(ref); renderedEvidence.push({ ref, label: label || undefined, text: text || undefined, role }); } + } + const seenText = new Set(); + const textWalker = body ? document.createTreeWalker(body, NodeFilter.SHOW_TEXT) : null; + let textIndex = 0; + for (let node = textWalker?.nextNode(); node; node = textWalker?.nextNode()) { + const text = (node.textContent || '').replace(/\\s+/g, ' ').trim().slice(0, 240); + if (!text || seenText.has(text)) continue; + const parentElement = node.parentElement; + if (!parentElement) continue; + const style = getComputedStyle(parentElement); + if (style.display === 'none' || style.visibility === 'hidden') continue; + seenText.add(text); + const ref = 'text:' + textIndex++; + if (!seenRefs.has(ref)) { seenRefs.add(ref); renderedEvidence.push({ ref, text, role: parentElement.getAttribute('role') || parentElement.tagName.toLowerCase() }); } + } + parent.postMessage({ + kind: 'openbitfun.genui.inspection.report', + report: { + viewportWidth: window.innerWidth, + viewportHeight: window.innerHeight, + clientWidth: document.documentElement?.clientWidth || body?.clientWidth || 0, + clientHeight: document.documentElement?.clientHeight || body?.clientHeight || 0, + scrollWidth: Math.max(document.documentElement?.scrollWidth || 0, body?.scrollWidth || 0), + scrollHeight: Math.max(document.documentElement?.scrollHeight || 0, body?.scrollHeight || 0), + visibleElementCount, + contentBounds, + renderedEvidence, + }, + }, '*'); + }; + addEventListener('message', event => { + if (event.source === parent && event.data?.kind === 'openbitfun.genui.inspection.request') { + setTimeout(report, 0); + requestAnimationFrame(() => requestAnimationFrame(report)); + } + }); + setTimeout(report, 0); + requestAnimationFrame(() => requestAnimationFrame(report)); + })();`; +} + +/** + * Keep free documents as documents. The parser only removes host escape paths; + * it does not translate the document into the component graph. Scripts are + * retained in the source record but are deliberately disabled by this static + * renderer until a host has negotiated the controlled bridge capability. + */ +export function sanitizeGenUIHtmlSource(source: GenUIHtmlDocumentSource, specification?: GenUIDesignSpec, hostStyleResourceCss = '', scriptEnabled = false, inspectionEnabled = false, inlineScriptEnabled = false, colorScheme: 'light' | 'dark' = 'light'): GenUIHtmlSanitizeResult { + const diagnostics: string[] = []; + const allowControlledScript = scriptEnabled && !inspectionEnabled; + const scriptNonce = allowControlledScript || inspectionEnabled ? createCspNonce() : undefined; + const parsed = new DOMParser().parseFromString(source.html, 'text/html'); + // HtmlView is a trusted product component with a separate opt-in for its + // local animation script. Free HTML documents keep scripts in their own + // source.script field, so inline document scripts remain disabled there. + const inlineScript = inlineScriptEnabled + ? [...parsed.querySelectorAll('script')].map(script => script.textContent ?? '').filter(Boolean).join('\n') + : ''; + parsed.querySelectorAll('*').forEach(element => { + const tagName = element.tagName.toLowerCase(); + if (!ALLOWED_ELEMENTS.has(tagName)) { + if (tagName === 'script' && inlineScriptEnabled) { + element.remove(); + return; + } + diagnostics.push(`Removed unsupported element: <${tagName}>`); + element.remove(); + return; + } + for (const attribute of [...element.attributes]) { + const attributeName = attribute.name.toLowerCase(); + if (attributeName.startsWith('on') || (!ALLOWED_ATTRIBUTES.has(attributeName) && !attributeName.startsWith('aria-') && !attributeName.startsWith('data-'))) { + diagnostics.push(`Removed unsupported attribute: ${attribute.name}`); + element.removeAttribute(attribute.name); + continue; + } + if (attributeName === 'style') { + element.setAttribute(attribute.name, sanitizeCss(attribute.value)); + } + if ((attributeName === 'href' || attributeName === 'src' || attributeName === 'xlink:href') + && /^(?:https?:|data:|javascript:|vbscript:|\/\/)/i.test(attribute.value.trim())) { + diagnostics.push(`Removed unsafe URL from ${attribute.name}`); + element.removeAttribute(attribute.name); + } + } + }); + parsed.querySelectorAll('style').forEach(style => { + style.textContent = sanitizeCss(style.textContent ?? ''); + }); + const css = sanitizeCss(source.css ?? ''); + if (css.trim()) { + const style = parsed.createElement('style'); + style.setAttribute('data-gen-ui-source-style', 'true'); + style.textContent = css; + parsed.head.appendChild(style); + } + if (specification) { + const identity = parsed.createElement('meta'); + identity.name = 'openbitfun-design-spec'; + identity.content = `${specification.label}@${specification.revision}`; + parsed.head.appendChild(identity); + const resources = parsed.createElement('meta'); + resources.name = 'openbitfun-style-resources'; + resources.content = specification.styleResources.join(','); + parsed.head.appendChild(resources); + } + if (hostStyleResourceCss.trim()) { + const style = parsed.createElement('style'); + style.setAttribute('data-gen-ui-host-style-resources', 'true'); + style.textContent = hostStyleResourceCss; + parsed.head.appendChild(style); + } + const policy = parsed.createElement('meta'); + policy.httpEquiv = 'Content-Security-Policy'; + policy.content = `default-src 'none'; style-src 'unsafe-inline'; img-src data: blob:; font-src data:; connect-src 'none'; frame-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'; script-src 'none'`; + parsed.head.prepend(policy); + const scripts = [source.script?.trim() ?? '', inlineScript.trim()].filter(Boolean).join('\n'); + if (scripts) { + if (!allowControlledScript) diagnostics.push('Controlled script execution is disabled on this host'); + else { + const script = parsed.createElement('script'); + script.setAttribute('nonce', scriptNonce!); + script.textContent = `${bridgeBootstrap()}\n${sanitizeControlledScript(scripts)}`.replace(/<\/script/gi, '<\\/script'); + parsed.body.appendChild(script); + } + } + if (inspectionEnabled) { + const script = parsed.createElement('script'); + script.setAttribute('nonce', scriptNonce!); + script.textContent = inspectionBootstrap(); + parsed.body.appendChild(script); + } + if (scriptNonce) policy.setAttribute('content', `default-src 'none'; style-src 'unsafe-inline'; img-src data: blob:; font-src data:; connect-src 'none'; frame-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'; script-src 'nonce-${scriptNonce}'`); + return { + document: `${parsed.head.innerHTML}${parsed.body.innerHTML}`, + diagnostics, + }; +} + +export function inspectGenUIHtmlSource(source: GenUIHtmlDocumentSource, specification?: GenUIDesignSpec): string[] { + const { diagnostics } = sanitizeGenUIHtmlSource(source); + const issues = diagnostics.filter(message => message.startsWith('Removed unsafe URL')); + if (specification && !specification.sourceKinds.includes('html-document')) issues.push(`UI specification ${specification.label} does not allow HTML documents`); + const parsed = new DOMParser().parseFromString(source.html, 'text/html'); + for (const selector of specification?.shell.forbiddenContentSelectors ?? []) { + try { + if (parsed.querySelector(selector)) issues.push('Generated document duplicates host-owned shell part: ' + selector); + } catch { + issues.push('Invalid host-owned content selector in UI specification: ' + selector); + } + } + // Reject the unconditionally empty case before mounting an opaque iframe. + // Actual browser inspection still owns visibility, geometry and overflow + // checks for documents that contain content but may be hidden or misplaced + // by their CSS. + const body = parsed.body; + const hasBodyText = Boolean(body?.textContent?.trim()); + const hasRenderableElement = Boolean(body?.querySelector('svg,img,canvas,video,audio,input,button,select,textarea,[role],iframe')); + if (!hasBodyText && !hasRenderableElement) issues.push('HTML document has no visible rendered content'); + return issues; +} diff --git a/src/web-ui/src/tools/generative-ui/genUILayout.ts b/src/web-ui/src/tools/generative-ui/genUILayout.ts index ff573f1add..9da1fe96a3 100644 --- a/src/web-ui/src/tools/generative-ui/genUILayout.ts +++ b/src/web-ui/src/tools/generative-ui/genUILayout.ts @@ -1,4 +1,4 @@ -import type { GenUIHtmlFrameReport } from './GenUIHtmlDocument'; +import type { GenUIHtmlFrameReport } from './genUIHtmlSource'; /** Geometry checks require a live browser layout engine. Zero geometry is * unsupported evidence, never a pass (including jsdom). */ diff --git a/src/web-ui/src/tools/generative-ui/genUIOpenUI.test.tsx b/src/web-ui/src/tools/generative-ui/genUIOpenUI.test.tsx index 1f0459ec57..5d7cbb323c 100644 --- a/src/web-ui/src/tools/generative-ui/genUIOpenUI.test.tsx +++ b/src/web-ui/src/tools/generative-ui/genUIOpenUI.test.tsx @@ -2,7 +2,8 @@ import React, { act } from 'react'; import { createRoot, type Root } from 'react-dom/client'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import GenUIOpenUIDocument, { zodForSchema } from './genUIOpenUI'; +import GenUIOpenUIDocument from './genUIOpenUI'; +import { zodForSchema } from './genUIOpenUISchema'; import GenUIApplication from './GenUIApplication'; import { genUIProduct } from './genUIProduct'; import { genUICatalog } from './genUIContract'; diff --git a/src/web-ui/src/tools/generative-ui/genUIOpenUI.tsx b/src/web-ui/src/tools/generative-ui/genUIOpenUI.tsx index 11cf94397d..c650434541 100644 --- a/src/web-ui/src/tools/generative-ui/genUIOpenUI.tsx +++ b/src/web-ui/src/tools/generative-ui/genUIOpenUI.tsx @@ -1,3 +1,4 @@ +import { zodForSchema } from './genUIOpenUISchema'; import './disableOpenUIDevtools'; import type { OpenUIError, ParseResult } from '@openuidev/lang-core'; import { mergeGenUIRenderDiagnostics, type GenUIRenderDiagnostic } from './genUIRenderDiagnostics'; @@ -124,44 +125,6 @@ function renderInspectableComponent( : rendered; } -export function zodForSchema(schema: Record | undefined): z.ZodTypeAny { - if (!schema) return z.any(); - if (Array.isArray(schema.enum) && schema.enum.length > 0 && schema.enum.every(value => typeof value === 'string')) { - return z.enum(schema.enum as [string, ...string[]]); - } - const union = Array.isArray(schema.anyOf) ? schema.anyOf : Array.isArray(schema.oneOf) ? schema.oneOf : undefined; - if (union) { - const branches = union.map(branch => zodForSchema(branch as Record)); - return branches.length > 1 ? z.union(branches as [z.ZodTypeAny, z.ZodTypeAny, ...z.ZodTypeAny[]]) : branches[0] ?? z.any(); - } - switch (schema.type) { - case 'string': return z.string(); - case 'number': return z.number(); - case 'integer': return z.number().int(); - // Models commonly serialize boolean component flags as 0/1. Accept those - // exact JSON equivalents at the library boundary so one malformed flag - // does not leave a visible render error above an otherwise valid page. - case 'boolean': return z.union([ - z.boolean(), - z.literal(0), - z.literal(1), - ]); - case 'array': return z.array(zodForSchema(schema.items as Record | undefined)); - case 'object': { - const properties = (schema.properties ?? {}) as Record>; - const required = new Set(Array.isArray(schema.required) ? schema.required.filter((value): value is string => typeof value === 'string') : []); - const shape = Object.fromEntries(Object.entries(properties).map(([key, value]) => { - const field = zodForSchema(value); - return [key, required.has(key) ? field : field.optional()]; - })); - const object = z.object(shape); - return schema.additionalProperties === false ? object.strict() : object.catchall(z.any()); - } - case 'null': return z.null(); - default: return z.any(); - } -} - /** * Adapt the selected product library to OpenUI's language runtime. The * catalog remains the source of truth for names, required fields and slot diff --git a/src/web-ui/src/tools/generative-ui/genUIOpenUISchema.ts b/src/web-ui/src/tools/generative-ui/genUIOpenUISchema.ts new file mode 100644 index 0000000000..19fa2681bb --- /dev/null +++ b/src/web-ui/src/tools/generative-ui/genUIOpenUISchema.ts @@ -0,0 +1,39 @@ +import { z } from 'zod/v4'; + +export function zodForSchema(schema: Record | undefined): z.ZodTypeAny { + if (!schema) return z.any(); + if (Array.isArray(schema.enum) && schema.enum.length > 0 && schema.enum.every(value => typeof value === 'string')) { + return z.enum(schema.enum as [string, ...string[]]); + } + const union = Array.isArray(schema.anyOf) ? schema.anyOf : Array.isArray(schema.oneOf) ? schema.oneOf : undefined; + if (union) { + const branches = union.map(branch => zodForSchema(branch as Record)); + return branches.length > 1 ? z.union(branches as [z.ZodTypeAny, z.ZodTypeAny, ...z.ZodTypeAny[]]) : branches[0] ?? z.any(); + } + switch (schema.type) { + case 'string': return z.string(); + case 'number': return z.number(); + case 'integer': return z.number().int(); + // Models commonly serialize boolean component flags as 0/1. Accept those + // exact JSON equivalents at the library boundary so one malformed flag + // does not leave a visible render error above an otherwise valid page. + case 'boolean': return z.union([ + z.boolean(), + z.literal(0), + z.literal(1), + ]); + case 'array': return z.array(zodForSchema(schema.items as Record | undefined)); + case 'object': { + const properties = (schema.properties ?? {}) as Record>; + const required = new Set(Array.isArray(schema.required) ? schema.required.filter((value): value is string => typeof value === 'string') : []); + const shape = Object.fromEntries(Object.entries(properties).map(([key, value]) => { + const field = zodForSchema(value); + return [key, required.has(key) ? field : field.optional()]; + })); + const object = z.object(shape); + return schema.additionalProperties === false ? object.strict() : object.catchall(z.any()); + } + case 'null': return z.null(); + default: return z.any(); + } +}