diff --git a/.changeset/34610-ai-build-app-in-main-area.md b/.changeset/34610-ai-build-app-in-main-area.md new file mode 100644 index 00000000000..7cbbb3e34cc --- /dev/null +++ b/.changeset/34610-ai-build-app-in-main-area.md @@ -0,0 +1,26 @@ +--- +'@object-ui/app-shell': patch +'@object-ui/console': patch +'@object-ui/plugin-chatbot': patch +'@object-ui/i18n': patch +--- + +feat(console-ai): an AI build shows the app itself in the main area, with one Publish on screen + +Clause-②: yes (widening — new @object-ui/i18n locale keys, so `TranslationKeys` grows; and two additive @object-ui/plugin-chatbot changes, the optional `ChatbotEnhanced` prop `publishFromShellBar` and the optional `opts.appSegment` argument of `onBuildMaterialized`); nothing removed or renamed +Metadata-protocol: none + +Building with AI happens in the console's right-side drawer, and the app it builds shows in the page beside it (ui ADR-0057 Amendment A3, ADR-0037 as amended). There is no nested preview any more. + +- Changes to a published app show on the page you are on, in draft mode, with the draft bar on top. A new app shows in the main area once the build creates its package. Before that, the page stays. A new app is materialized (ADR-0045), so it shows as the real, not-yet-published app. The main area refreshes as each drafted item lands, and once more when the build's turn ends. Opening an older conversation from the history does not move the page. +- The screen has one Publish: the draft bar, or the "not published yet" bar for an app that has never been published. The chat's result cards and the line above the composer no longer publish. The line says where to publish, or offers "Show draft" when the page is elsewhere. After a publish from the bar, the chat shows a receipt. +- One count: the draft bar, its changes panel and the chat all count the current app's pending changes. An app's changes are those in its package and in its customization package (ADR-0146), where changes to an app installed from code are saved. The bar no longer counts the whole environment, and its separate "on this page" count is gone. Publishing from the draft bar publishes that app's changes and no longer reloads the page. +- Publishing from the "not published yet" bar works for an app opened at its package id: the app is saved under its own name. Before, that save was refused. +- The bar for an app that is not published yet says so. The draft bar says how many unpublished changes the app has. +- In Studio, the AI copilot's expand button widens the copilot beside the page instead of leaving Studio. The copilot's cards no longer draw a Preview or Publish of their own. Studio's own top bar publishes. + +`@object-ui/console`: ships the console with the changes above (it bundles `@object-ui/app-shell`). + +`@object-ui/plugin-chatbot`: `ChatbotEnhanced` takes `publishFromShellBar`. When it is set, the draft cards draw no Publish button, and the build result card no longer says to click Publish in the chat. The Published badge, auto-publish and Preview stay. `onBuildMaterialized` also receives `{ appSegment }`, the built app's package id. + +`@object-ui/i18n`: new keys `preview.draftBar.pendingInApp` (with plural forms), `preview.unpublishedBar.notPublishedYet`, and `console.ai.pendingDrafts.publishFromBar`, `showDraftToPublish` (both with plural forms), `showDraft`, `receipt` and `dismissReceipt`, in every locale pack, so the `TranslationKeys` type grows by those keys. No key was removed or changed. The console no longer reads `preview.draftBar.pendingHere`, `preview.unpublishedBar.message`, `console.ai.pendingDrafts.count`, `publish`, `published`, `failed`, `publishedWithFindings`, `console.ai.previewApp`, `console.ai.resizeSplit`, `console.ai.liveCanvas`, `console.ai.liveCanvasLive` or `console.ai.liveCanvasUnlisted`. Retiring them is a separate change. diff --git a/ui/packages/app-shell/src/assistant/assistantBus.ts b/ui/packages/app-shell/src/assistant/assistantBus.ts index a647394b9e6..2463421f033 100644 --- a/ui/packages/app-shell/src/assistant/assistantBus.ts +++ b/ui/packages/app-shell/src/assistant/assistantBus.ts @@ -308,3 +308,30 @@ export function requestAssistantOpen(): void { export function requestAssistantReview(target: AssistantReviewTarget): void { assistantBus.requestReview(target); } + +// ── objectstack#34610 — a publish landed ─────────────────────────────────── +// The screen's one Publish is the shell's bar (the draft bar, or the +// unpublished-app bar for an app not yet published), and the chat draws none +// of its own. So the chat learns a publish landed from here and shows a +// receipt for it. Fire-and-forget, off the snapshot bus, like the two +// signals above; `emitMetadataRefresh` still carries the "re-read" half. + +export interface PublishReceipt { + /** The package the publish covered; null when it covered the whole environment. */ + packageId: string | null; +} + +const publishReceiptListeners = new Set<(receipt: PublishReceipt) => void>(); + +/** Announce that a publish from the shell's bar landed. */ +export function emitPublishReceipt(receipt: PublishReceipt): void { + for (const l of publishReceiptListeners) l(receipt); +} + +/** Subscribe to landed publishes; returns an unsubscriber. */ +export function subscribePublishReceipt(listener: (receipt: PublishReceipt) => void): () => void { + publishReceiptListeners.add(listener); + return () => { + publishReceiptListeners.delete(listener); + }; +} diff --git a/ui/packages/app-shell/src/chrome/KeyboardShortcutsDialog.wiredOnly-11674.test.tsx b/ui/packages/app-shell/src/chrome/KeyboardShortcutsDialog.wiredOnly-11674.test.tsx index 6e87272dd04..0d702ccf89b 100644 --- a/ui/packages/app-shell/src/chrome/KeyboardShortcutsDialog.wiredOnly-11674.test.tsx +++ b/ui/packages/app-shell/src/chrome/KeyboardShortcutsDialog.wiredOnly-11674.test.tsx @@ -54,14 +54,11 @@ vi.mock('../layout/ChatDock', () => ({ expanded: false, width: 420, dragging: false, - maximized: false, fullWindow: false, setFullWindow: vi.fn(), toggle: () => {}, expand: () => {}, collapse: () => {}, - maximize: () => {}, - restore: () => {}, onResizePointerDown: () => {}, }), ChatDockPanel: () => null, diff --git a/ui/packages/app-shell/src/console/ai/AiChatPage.tsx b/ui/packages/app-shell/src/console/ai/AiChatPage.tsx index 3240d4c55c7..2969ba231c6 100644 --- a/ui/packages/app-shell/src/console/ai/AiChatPage.tsx +++ b/ui/packages/app-shell/src/console/ai/AiChatPage.tsx @@ -56,10 +56,9 @@ import { DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, - useIsMobile, cn, } from '@object-ui/components'; -import { Bug, Check, ChevronDown, Eye, PanelLeft, PanelLeftClose, PanelLeftOpen, PanelRightOpen, Share2 } from 'lucide-react'; +import { Bug, Check, ChevronDown, PanelLeft, PanelLeftClose, PanelLeftOpen, PanelRightOpen, Share2 } from 'lucide-react'; import { ChatbotEnhanced, useObjectChat, @@ -119,7 +118,8 @@ import { import { AppHeader } from '../../layout/AppHeader.js'; import { readBuilderHandoffState, type BuilderHandoffState } from '../../layout/chatDockTarget.js'; -import { useOpenAssistant } from '../../layout/chatDockControl.js'; +import { useChatDockControl, useOpenAssistant } from '../../layout/chatDockControl.js'; +import { markPreviewExit, usePreviewDrafts } from '../../preview/PreviewModeContext.js'; import { CONSOLE_TOP_BAR } from '../../layout/consoleTopBar.js'; import { armChatDockExpanded, readDockReturnLocation } from '../../layout/chatDockState.js'; import type { ChatSurfaceContext } from '../../layout/chatSurfaceContext.js'; @@ -129,8 +129,14 @@ import { type ShortcutLabelTranslate, } from '../../chrome/advertisedShortcuts.js'; import { fetchPendingDraftCount } from '../../preview/draftStatus.js'; +import { appPackageOf } from '../../preview/usePendingDrafts.js'; import { draftPreviewPath } from '../../preview/draftSurface.js'; -import { emitMetadataRefresh, publishPlanApprovalPending, subscribeMetadataRefresh } from '../../assistant/assistantBus.js'; +import { + emitCanvasInvalidate, + emitMetadataRefresh, + publishPlanApprovalPending, + subscribeMetadataRefresh, +} from '../../assistant/assistantBus.js'; import { getRuntimeConfig, isAiStudioEnabled } from '../../runtime-config.js'; import { makerConvergedOnBuild, makerVisibleAgents } from '../../hooks/surfaceAgent.js'; import { useCanAuthorMetadata } from '../../hooks/useCanAuthorMetadata.js'; @@ -149,7 +155,7 @@ import { useReconcileOnError } from '../../hooks/useReconcileOnError.js'; import { useAiUsage } from '../../hooks/useAiUsage.js'; import { chatConversationScope, chatProductOfAgent } from '../../hooks/chatScope.js'; import { ConversationsSidebar } from './ConversationsSidebar.js'; -import { LiveCanvas } from './LiveCanvas.js'; +import { mainAreaDraftMove, type MainAreaDraftTarget } from './mainAreaDraft.js'; import { artifactStudioPath } from './artifactStudioPath.js'; import { studioChangesReviewTarget } from '../../views/studio-design/studioChangesLink.js'; import { BuildDebugDrawer } from './BuildDebugDrawer.js'; @@ -404,6 +410,39 @@ interface PackageBearingMessage { builderHandoff?: { packageId?: string }; }>; } +/** + * objectstack#34610 — what the LAST turn drafted, read off its own tool + * results: the newest draft review after the last user message, or null when + * the turn drafted nothing. `items` are what it drafted; `packageId` is the + * review's (absent when the producer named none); `materialized` is + * ADR-0045's in-turn build. Exported for tests. + */ +export function turnDraftPackage( + messages: readonly { + role?: string; + toolInvocations?: ReadonlyArray<{ + draftReview?: { packageId?: string; materialized?: boolean; items?: ReadonlyArray<{ type: string; name: string }> }; + }>; + }[], +): { packageId?: string; materialized?: boolean; items: ReadonlyArray<{ type: string; name: string }> } | null { + for (let i = messages.length - 1; i >= 0; i--) { + const message = messages[i]; + if (message.role === 'user') return null; + const tools = message.toolInvocations ?? []; + for (let j = tools.length - 1; j >= 0; j--) { + const dr = tools[j].draftReview; + if (dr?.items && dr.items.length > 0) { + return { + items: dr.items, + ...(dr.packageId ? { packageId: dr.packageId } : {}), + ...(dr.materialized ? { materialized: true } : {}), + }; + } + } + } + return null; +} + export function deriveBoundPackageId( messages: readonly PackageBearingMessage[], editPackageId: string | undefined, @@ -560,23 +599,17 @@ const CHATS_COLLAPSED_STORAGE_KEY = 'ai-chats-collapsed'; export interface CollapsibleChatsList { /** Whether the desktop conversations list is currently hidden. */ collapsed: boolean; - /** User-driven collapse/expand; persists the preference and takes manual control. */ + /** User-driven collapse/expand; persists the preference. */ toggle: () => void; - /** Wire to the preview pane: auto-tucks the list when it opens, restores on close. */ - handleCanvasOpenChange: (open: boolean) => void; } /** * State for the collapsible desktop conversations list. Exported for tests. + * `toggle()` flips it and PERSISTS the preference (localStorage). * - * Two drivers, one rule — never fight the user: - * - **Manual** `toggle()` flips it and PERSISTS the preference (localStorage), - * and marks the user as having taken control. - * - **Auto** `handleCanvasOpenChange(open)` tucks the list away when the Live - * Canvas preview opens (the chat + preview split is tight) and restores it on - * close — but ONLY if the auto-collapse is what hid it. A manual toggle (or a - * list the user already collapsed) is never overridden, and auto-collapse is - * transient (not persisted). + * objectstack#34610 — the Live Canvas split that used to tuck the list away + * while a preview was open is gone (the draft is the main area now), so the + * user's toggle is the only driver. */ export function useCollapsibleChatsList(): CollapsibleChatsList { const [collapsed, setCollapsed] = useState(() => { @@ -586,10 +619,7 @@ export function useCollapsibleChatsList(): CollapsibleChatsList { return false; } }); - const autoCollapsedRef = useRef(false); - const toggle = useCallback(() => { - autoCollapsedRef.current = false; // an explicit toggle is the user taking control setCollapsed((prev) => { const next = !prev; try { @@ -601,182 +631,7 @@ export function useCollapsibleChatsList(): CollapsibleChatsList { }); }, []); - const handleCanvasOpenChange = useCallback((open: boolean) => { - if (open) { - setCollapsed((prev) => { - if (!prev) { - autoCollapsedRef.current = true; - return true; - } - return prev; // already collapsed (manual) — leave it, don't claim it - }); - } else if (autoCollapsedRef.current) { - autoCollapsedRef.current = false; - setCollapsed(false); - } - }, []); - - return { collapsed, toggle, handleCanvasOpenChange }; -} - -const CHAT_PANE_WIDTH_STORAGE_KEY = 'ai-chat-pane-width'; -/** Default chat-column width (px) when the preview opens. */ -const CHAT_PANE_DEFAULT_WIDTH = 480; -/** Chat column never narrower than this. */ -const CHAT_PANE_MIN_WIDTH = 360; -/** Preview pane always keeps at least this much room (caps how wide chat can grow). */ -const CHAT_PREVIEW_MIN_WIDTH = 420; -/** Keyboard resize step (px) when the divider is focused. */ -const CHAT_PANE_KEYBOARD_STEP = 24; - -/** - * Clamp a desired chat-column width so neither pane collapses: at least - * `min`, and never so wide that the preview drops below `previewMin`. Pure + - * exported for tests. `containerWidth <= 0` (unmeasured) skips the upper bound. - */ -export function clampChatPaneWidth( - desired: number, - opts: { min: number; previewMin: number; containerWidth: number }, -): number { - const upper = opts.containerWidth > 0 ? Math.max(opts.min, opts.containerWidth - opts.previewMin) : Infinity; - return Math.min(Math.max(desired, opts.min), upper); -} - -/** - * True when a container cannot hold the chat and the preview side by side at - * their minimums (`CHAT_PANE_MIN_WIDTH + CHAT_PREVIEW_MIN_WIDTH`). The pane - * then previews the way a phone does (#2481) instead of pushing the preview - * past the container's edge, as the console dock at a 1024 px window did. - * Pure + exported for tests. `containerWidth <= 0` (unmeasured) is not narrow. - */ -export function isTooNarrowForSplit(containerWidth: number): boolean { - return containerWidth > 0 && containerWidth < CHAT_PANE_MIN_WIDTH + CHAT_PREVIEW_MIN_WIDTH; -} - -interface ResizableChatPane { - /** Current chat-column width in px (clamped). */ - width: number; - /** True while a drag is in progress (for cursor/overlay styling). */ - dragging: boolean; - /** Ref for the split container — measures available width to bound the preview. */ - containerRef: React.RefObject; - /** Start a pointer drag from the divider. */ - onHandlePointerDown: (e: React.PointerEvent) => void; - /** Keyboard resize (←/→) when the divider is focused. */ - onHandleKeyDown: (e: React.KeyboardEvent) => void; - /** Reset to the default width (double-click the divider). */ - reset: () => void; - /** The container is too narrow for the split (`isTooNarrowForSplit`), measured whether or not it is open. */ - tooNarrow: boolean; -} - -/** - * Draggable width for the chat column when the Live Canvas preview is open - * (ChatGPT/Claude-style split). Width persists; drags and keyboard nudges are - * clamped against the live container so the preview always keeps room, and a - * ResizeObserver re-clamps when the window shrinks. All DOM reads happen in - * handlers/effects, never during render. - */ -export function useResizableChatPane(active: boolean): ResizableChatPane { - const containerRef = useRef(null); - const [width, setWidth] = useState(() => { - try { - const saved = Number(localStorage.getItem(CHAT_PANE_WIDTH_STORAGE_KEY)); - return Number.isFinite(saved) && saved > 0 ? saved : CHAT_PANE_DEFAULT_WIDTH; - } catch { - return CHAT_PANE_DEFAULT_WIDTH; - } - }); - const [dragging, setDragging] = useState(false); - - const clampToContainer = useCallback( - (desired: number) => - clampChatPaneWidth(desired, { - min: CHAT_PANE_MIN_WIDTH, - previewMin: CHAT_PREVIEW_MIN_WIDTH, - containerWidth: containerRef.current?.clientWidth ?? 0, - }), - [], - ); - - const persist = useCallback((w: number) => { - try { - localStorage.setItem(CHAT_PANE_WIDTH_STORAGE_KEY, String(Math.round(w))); - } catch { - /* storage disabled — width just won't persist */ - } - }, []); - - // Re-clamp when the available width changes (window resize, sidebar collapse), - // so a previously-saved wide chat can't starve the preview. - useEffect(() => { - if (!active) return; - const el = containerRef.current; - if (!el || typeof ResizeObserver === 'undefined') return; - const ro = new ResizeObserver(() => setWidth((w) => clampToContainer(w))); - ro.observe(el); - return () => ro.disconnect(); - }, [active, clampToContainer]); - - // Whether the split fits at all. Read from the same container in both - // presentations and observed even while the split is closed, so the answer - // never depends on which presentation is showing: the container's width does - // not change when the pane switches, so there is no threshold to oscillate on. - // A layout effect, so a narrow container never paints the split first. - const [tooNarrow, setTooNarrow] = useState(false); - useLayoutEffect(() => { - const el = containerRef.current; - if (!el) return; - const read = () => setTooNarrow(isTooNarrowForSplit(el.clientWidth)); - read(); - if (typeof ResizeObserver === 'undefined') return; - const ro = new ResizeObserver(read); - ro.observe(el); - return () => ro.disconnect(); - }, []); - - const onHandlePointerDown = useCallback( - (e: React.PointerEvent) => { - e.preventDefault(); - const startX = e.clientX; - const startWidth = width; // state is the style source, so it == the rendered width - setDragging(true); - const onMove = (ev: PointerEvent) => setWidth(clampToContainer(startWidth + (ev.clientX - startX))); - const onUp = (ev: PointerEvent) => { - const final = clampToContainer(startWidth + (ev.clientX - startX)); - setWidth(final); - persist(final); - setDragging(false); - window.removeEventListener('pointermove', onMove); - window.removeEventListener('pointerup', onUp); - }; - window.addEventListener('pointermove', onMove); - window.addEventListener('pointerup', onUp); - }, - [clampToContainer, persist, width], - ); - - const onHandleKeyDown = useCallback( - (e: React.KeyboardEvent) => { - const delta = e.key === 'ArrowLeft' ? -CHAT_PANE_KEYBOARD_STEP : e.key === 'ArrowRight' ? CHAT_PANE_KEYBOARD_STEP : 0; - if (!delta) return; - e.preventDefault(); - setWidth((w) => { - const next = clampToContainer(w + delta); - persist(next); - return next; - }); - }, - [clampToContainer, persist], - ); - - const reset = useCallback(() => { - const next = clampToContainer(CHAT_PANE_DEFAULT_WIDTH); - setWidth(next); - persist(next); - }, [clampToContainer, persist]); - - return { width, dragging, containerRef, onHandlePointerDown, onHandleKeyDown, reset, tooNarrow }; + return { collapsed, toggle }; } export type AiChatShortcut = 'toggle-list' | 'new-chat'; @@ -1511,11 +1366,7 @@ export function AiChatPage({ apiBase: apiBaseProp, defaultAgent: defaultAgentPro const [shareOpen, setShareOpen] = useState(false); const [debugOpen, setDebugOpen] = useState(false); const [mobileChatsOpen, setMobileChatsOpen] = useState(false); - const { - collapsed: chatsCollapsed, - toggle: toggleChatsCollapsed, - handleCanvasOpenChange, - } = useCollapsibleChatsList(); + const { collapsed: chatsCollapsed, toggle: toggleChatsCollapsed } = useCollapsibleChatsList(); // Keyboard shortcuts (ChatGPT/Claude parity): ⌘⇧O new chat, ⌘⇧S toggle list. useEffect(() => { const onKeyDown = (e: KeyboardEvent) => { @@ -1838,7 +1689,6 @@ export function AiChatPage({ apiBase: apiBaseProp, defaultAgent: defaultAgentPro onShare={() => setShareOpen(true)} onDebug={() => setDebugOpen(true)} showDebug={agentHasCapability(agents, activeAgent, 'debug')} - onCanvasOpenChange={handleCanvasOpenChange} /> @@ -1933,8 +1783,6 @@ interface ChatPaneProps { onDebug?: () => void; /** Show the Build Doctor button — true only for build-agent conversations. */ showDebug?: boolean; - /** Reports the Live Canvas preview opening/closing so the page can auto-tuck the chats list. */ - onCanvasOpenChange?: (open: boolean) => void; } export function ChatPane({ @@ -1964,7 +1812,6 @@ export function ChatPane({ onShare, onDebug, showDebug, - onCanvasOpenChange, }: ChatPaneProps) { const { t, language } = useObjectTranslation(); const navigate = useNavigate(); @@ -2083,29 +1930,6 @@ export function ChatPane({ [navigate, location], ); - // ── ADR-0037 Live Canvas ──────────────────────────────────────────────── - // When a build session drafts an `app`, open the split-view canvas: the - // drafted app rendered as-if-published (`?preview=draft`) beside the chat. - // Per-artifact signals coalesce (800 ms) into one pane refresh so a - // whole-app build doesn't trigger an invalidation storm. - // objectui#12968 — `path`: a drafted page / view / object surface to show - // instead of the app's landing (`draftPreviewPath`, `onPreviewDraft` below). - const [canvasApp, setCanvasApp] = useState< - { name: string; segment?: string; materialized: boolean; path?: string } | null - >(null); - const [canvasRefreshKey, setCanvasRefreshKey] = useState(0); - // #2481 — a phone can't do the beside-chat split (chat's fixed min-width + - // the preview together overflow the viewport, and the resize handle is - // desktop-only). So under `md` the canvas is OPT-IN and FULL-SCREEN: the - // build streams in the (full-width) chat as usual; when the user taps Preview - // the canvas takes over the screen, and closing returns to the chat. This - // flag is that overlay's open state — distinct from `canvasApp` (which only - // means a preview is AVAILABLE), so an auto-drafted app never covers the chat. - const isMobile = useIsMobile(); - const [mobileCanvasOpen, setMobileCanvasOpen] = useState(false); - useEffect(() => { - if (!canvasApp) setMobileCanvasOpen(false); - }, [canvasApp]); // cloud#797 Excel→App: the attached spreadsheet the user can load real rows // from (into a built object) via ExcelImportBar. Set when a sheet is sent, // cleared on import/dismiss. `dataSource` drives the wizard's schema + import. @@ -2137,70 +1961,17 @@ export function ChatPane({ [dataSource], ); const [pendingSheet, setPendingSheet] = useState(null); - const canvasTimerRef = useRef(null); - useEffect(() => () => { - if (canvasTimerRef.current) window.clearTimeout(canvasTimerRef.current); - }, []); - // Tell the page when the preview pane opens/closes so it can tuck the chats - // list away for the (tight) chat + preview split, and restore it after. - const canvasOpen = canvasApp !== null; - useEffect(() => { - onCanvasOpenChange?.(canvasOpen); - }, [canvasOpen, onCanvasOpenChange]); - // Draggable chat ↔ preview split (active only while the preview is open). - const split = useResizableChatPane(canvasOpen); + // The pane's root, measured by the composer-draft handoff below. + const paneRef = useRef(null); // objectstack#33674 — what is typed into the composer before this pane knows // its conversation outlives the id-keyed remount. See useComposerDraftHandoff. const noteComposerInput = useComposerDraftHandoff({ hostStash: pendingFirstMessageRef, - containerRef: split.containerRef, + containerRef: paneRef, chatApi, conversationId, requestedConversationId, }); - // A pane too narrow for the split (the console dock at a laptop width, the - // Studio copilot's slot) previews the way a phone does: full-width chat, the - // pill, the full-surface overlay. Every phone switch below reads this. - const phonePreview = isMobile || split.tooNarrow; - const handleDraftArtifacts = useCallback((artifacts: Array<{ type: string; name: string }>, appSegment?: string) => { - const app = artifacts.find((a) => a.type === 'app'); - // Route the preview on the app's package id (ADR-0048), not its name. - if (app) setCanvasApp((prev) => prev ?? { name: app.name, segment: appSegment, materialized: false }); - if (canvasTimerRef.current) window.clearTimeout(canvasTimerRef.current); - canvasTimerRef.current = window.setTimeout(() => setCanvasRefreshKey((k) => k + 1), 800); - }, []); - // ADR-0045: the build finished and was materialized (real tables + data, - // app unlisted). Switch the open canvas from the draft overlay to the REAL - // app URL — the reload that follows shows live rows in every list. - const handleBuildMaterialized = useCallback((appName: string) => { - setCanvasApp((prev) => - prev && prev.name === appName && !prev.materialized - ? { ...prev, materialized: true } // keep the package-id segment - : prev ?? { name: appName, materialized: true }, - ); - }, []); - // The chat's build card's own answer per built app (its label and whether it - // says the app is live), keyed by the app's machine name. The canvas header - // reads it instead of deriving a publish state of its own, so the two can - // never disagree, and it follows the card when the build is published. - const [buildResults, setBuildResults] = useState>({}); - const handleBuildResult = useCallback( - ({ appName, label, live }: { appName: string; label?: string; live: boolean }) => { - setBuildResults((prev) => { - const cur = prev[appName]; - if (cur && cur.label === label && cur.live === live) return prev; - return { ...prev, [appName]: { ...(label ? { label } : {}), live } }; - }); - }, - [], - ); - const canvasBuild = canvasApp ? buildResults[canvasApp.name] : undefined; - // A different conversation is a different build session — close the pane. - useEffect(() => { - setCanvasApp(null); - setBuildResults({}); - }, [conversationId]); - const activeAgentLabel = useMemo(() => { const found = agents.find((a) => a.name === activeAgent); return localizeAgentLabel(t, activeAgent, found?.label ?? activeAgent ?? t('console.ai.assistant')); @@ -2395,20 +2166,6 @@ export function ChatPane({ [t], ); - // ADR-0037: refresh the live preview when a turn finishes while the canvas is - // open. The per-artifact `onDraftArtifacts` signal covers a build streaming in, - // but an incremental edit (add a field, rename) can land without growing the - // de-duped artifact set — so its draft never reached the iframe and the pane - // (and its "Changes (N)" count) went stale until a manual reload. Bumping on - // the loading falling-edge guarantees the preview reflects every change. - const prevLoadingRef = useRef(false); - useEffect(() => { - if (prevLoadingRef.current && !isLoading && canvasApp) { - setCanvasRefreshKey((k) => k + 1); - } - prevLoadingRef.current = isLoading; - }, [isLoading, canvasApp]); - const hitl = useHitlInChat({ messages: runtimeMessages, apiBase, @@ -2691,6 +2448,145 @@ export function ChatPane({ onPackageBound?.(boundPackageId); }, [isBuildSurface, canBind, boundPackageId, editPackageId, isLoading, onPackageBound]); + // ── objectstack#34610 — the draft is the main area ───────────────────────── + // The build runs in the console's drawer, and what it builds shows in the + // page beside it (ADR-0057 Amendment A3, ADR-0037 as amended): no nested + // preview. Under a drawer host (`useChatDockControl`, the console and Home + // shells) the main area moves to the app, in the regime the build is in + // (ADR-0045): the real unpublished app for a materialized build or an app + // not published yet, `?preview=draft` for changes to a published app. With + // no drawer host (the Studio copilot, whose design surface already shows + // the drafts) nothing moves; only the per-artifact refresh below runs. + const dockControl = useChatDockControl(); + const showsMainArea = dockControl !== null; + const mainAreaInPreview = usePreviewDrafts(); + // An app the registry lists as materialized-but-unpublished (ADR-0045) + // takes no draft overlay: its changes materialize into it directly, and in + // preview mode its own Publish bar would yield to an empty draft bar. + const unpublishedApp = useCallback( + (segment: string) => + (metadataApps ?? []).some( + (a) => (a._packageId === segment || a.name === segment) && (a as { _unpublished?: unknown })._unpublished === true, + ), + [metadataApps], + ); + // Only a turn THIS pane streamed moves the main area. The chat reports a + // reopened conversation's drafts and materialized builds on mount too, and + // opening an old thread from the history must not navigate the page. + const liveTurnRef = useRef(false); + useEffect(() => { + if (isLoading) liveTurnRef.current = true; + }, [isLoading]); + // Keyed by the conversation: another conversation is another build session, + // and its target (none yet) is not this one's. + const [mainAreaState, setMainAreaState] = useState<{ + conversationId: string | undefined; + target: MainAreaDraftTarget; + } | null>(null); + const mainAreaTarget = + mainAreaState && mainAreaState.conversationId === conversationId ? mainAreaState.target : null; + const shownTargetRef = useRef(null); + // Move the main area to the latest target. Entering draft mode on the page + // the user is on is a query change and happens at once; a move to another + // page waits for the turn to end (A1: the main area keeps its page until + // the build binds, and the bind lands when the turn does), so a stream in + // flight is never cut by a shell switch. + useEffect(() => { + if (!showsMainArea || !mainAreaTarget || shownTargetRef.current === mainAreaTarget) return; + const move = mainAreaDraftMove(mainAreaTarget, location, mainAreaTarget.segment === activeAppPackageId); + if (move && !move.replace && isLoading) return; + shownTargetRef.current = mainAreaTarget; + if (!move) return; + if (move.leavesPreview) markPreviewExit(); + navigate(move.to, { replace: move.replace }); + }, [showsMainArea, mainAreaTarget, location, activeAppPackageId, isLoading, navigate]); + const showAppInMainArea = useCallback( + (packageId: string, opts: { materialized?: boolean; path?: string } = {}) => { + // An edit to a code-shipped app is drafted into its customization pair + // (ADR-0146): the app it shows in is the pair's base. + const segment = appPackageOf(packageId); + const materialized = opts.materialized === true || unpublishedApp(segment); + setMainAreaState({ + conversationId, + target: { + segment, + ...(materialized ? { materialized: true } : {}), + ...(opts.path && !materialized ? { path: opts.path } : {}), + }, + }); + }, + [unpublishedApp, conversationId], + ); + // ADR-0037 Phase 2 — refresh in place per artifact: each drafted artifact is + // announced on the assistant bus, and every metadata tree in preview mode + // (the main area's) refetches that type. Coalesced (~200 ms) by type, so a + // whole-app build is not an invalidation storm. + const invalidateTimerRef = useRef(null); + const pendingInvalidationsRef = useRef>(new Map()); + useEffect( + () => () => { + if (invalidateTimerRef.current) window.clearTimeout(invalidateTimerRef.current); + }, + [], + ); + const queueInvalidations = useCallback((artifacts: ReadonlyArray<{ type: string; name: string }>) => { + for (const a of artifacts) { + if (!pendingInvalidationsRef.current.has(a.type)) pendingInvalidationsRef.current.set(a.type, a); + } + if (invalidateTimerRef.current) window.clearTimeout(invalidateTimerRef.current); + invalidateTimerRef.current = window.setTimeout(() => { + const batch = [...pendingInvalidationsRef.current.values()]; + pendingInvalidationsRef.current.clear(); + for (const inv of batch) emitCanvasInvalidate(inv); + }, 200); + }, []); + const handleDraftArtifacts = useCallback( + (artifacts: Array<{ type: string; name: string }>, appSegment?: string) => { + queueInvalidations(artifacts); + // The app the draft belongs to: the drafted set's own package, else the + // package this conversation is bound to (an edit drafts no `app`). + // Unbound (a new build before its package exists), the page stays. + const segment = appSegment ?? boundPackageId; + if (liveTurnRef.current && segment) showAppInMainArea(segment); + }, + [boundPackageId, showAppInMainArea, queueInvalidations], + ); + // ADR-0045: the build materialized — the real, unlisted app. + const handleBuildMaterialized = useCallback( + (appName: string, opts?: { appSegment?: string }) => { + if (liveTurnRef.current) showAppInMainArea(opts?.appSegment ?? appName, { materialized: true }); + }, + [showAppInMainArea], + ); + // A finished turn refreshes the main area once more (and every pending + // count): an incremental edit can land without growing the drafted set, so + // the per-artifact signal above does not always fire for it. + // + // objectstack#34610 — for the same reason a finished turn that drafted + // shows its app in the main area itself: an edit that re-drafts an artifact + // the conversation already listed (the object a build made, edited in the + // next turn) never reaches `handleDraftArtifacts`, and read live it left the + // main area out of draft mode with the edit pending. + const prevLoadingRef = useRef(false); + useEffect(() => { + const ended = prevLoadingRef.current && !isLoading; + prevLoadingRef.current = isLoading; + if (!ended) return; + if (liveTurnRef.current) { + const drafted = turnDraftPackage(messages); + const segment = drafted?.packageId ?? (drafted ? boundPackageId : undefined); + if (drafted && segment) { + showAppInMainArea(segment, drafted.materialized ? { materialized: true } : {}); + // …and refreshes what it drafted, once the main area is in draft + // mode (the coalescing delay outlasts the move). + queueInvalidations(drafted.items); + } + } + if (shownTargetRef.current) emitMetadataRefresh(); + // Re-runs on the other deps find no turn end (`prevLoadingRef` already + // holds the current value), so only the end of a turn acts. + }, [isLoading, messages, boundPackageId, showAppInMainArea, queueInvalidations]); + // objectui#12724 — a finished build STAYS on the conversation. The // built-moment transition (objectui#5799) used to move the thread into the // Studio workbench the moment a whole-app build existed, and objectui#11658 @@ -2990,55 +2886,27 @@ export function ChatPane({ ); - // The beside-chat split needs room for both panes: on a phone, or in a pane - // narrower than that (`phonePreview`), the chat keeps full width and the - // canvas becomes a full-surface overlay instead (see #2481 below). - const desktopSplit = canvasApp !== null && !phonePreview; - - // objectui#5694 — the standing unpublished-changes affordance: shown while - // the bound package has pending drafts, so the publish entry point survives - // scrolling (the inline card button does not). It renders nothing when the - // count is 0 or the conversation is unbound. + // objectui#5694 — the standing unpublished-changes line: shown while the + // bound package has pending drafts, so it survives scrolling. It renders + // nothing when the count is 0 or the conversation is unbound. // objectui#12965 — not drawn in the package's own Studio: there the Studio // top bar's 变更 and 发布 and the applied card's 查看变更并发布 are the ways // to review and publish (objectui#12725's ruled artboard draws no bar). + // objectstack#34610 — it publishes nothing: it points to the shell's draft + // bar, offers to show the draft when the main area is elsewhere, and shows + // the receipt of a publish from that bar. const pendingDraftsBar = isBuildSurface && !onBoundPackageStudio ? ( - + showAppInMainArea(boundPackageId) : undefined} + /> ) : null; - // #2481 — on a phone a built app is previewed full-screen, on request: the - // pill below offers it, and closing the overlay brings the pill back. - // objectui#13068 — the pill is a row of the composer's own area, like the - // drafts bar (objectui#12978). It used to float (`absolute bottom-24`) over - // the chat, and on a phone that box sat on the input's first line. - // The rows share one column, pill above bar, from the moment a preview is - // available until it goes away, so opening and closing the overlay never - // remounts the bar (its count would re-read and blink). That column exists - // only then: without a preview the slot holds the bar alone, as before, and - // stays empty, taking no space, while the bar renders nothing. - const mobilePreviewAvailable = canvasApp !== null && phonePreview; - const promptHeaderRows = mobilePreviewAvailable ? ( -
- {!mobileCanvasOpen ? ( - - ) : null} - {pendingDraftsBar} -
- ) : ( - pendingDraftsBar ?? undefined - ); - return ( -
+
{/* Excel→App (cloud#797): float the real-data import affordance above the chat when a spreadsheet was attached. Absolute so it doesn't disturb the chat/canvas flex layout; the ImportWizard it opens is a modal. */} @@ -3048,7 +2916,6 @@ export function ChatPane({ setPendingSheet(null)} />
@@ -3064,12 +2931,7 @@ export function ChatPane({ and the summary truncates as it was written to. */}
{ - const pkg = appSegment ?? canvasApp?.segment; + const pkg = appSegment ?? boundPackageId; if (!pkg) return; navigate(`/studio/${encodeURIComponent(pkg)}/interfaces`); }} @@ -3266,7 +3128,7 @@ export function ChatPane({ // Automations, dashboard/page/view/app → Interfaces). Returns null for // types with no direct-edit home (seed/dataset) → rendered as text. getArtifactAction={(artifact, appSegment) => { - const path = artifactStudioPath(appSegment ?? canvasApp?.segment, artifact); + const path = artifactStudioPath(appSegment ?? boundPackageId, artifact); return path ? () => navigate(path) : null; }} // Live lifecycle truth for draft cards: the server's pending count per @@ -3363,6 +3225,11 @@ export function ChatPane({ return false; } }} + // objectstack#34610 — the cards draw no Publish: the screen's one is + // the shell's bar (the draft bar or the unpublished-app bar; in + // Studio, its top bar), and the drafts line above points to it. + // `onPublishDrafts` stays for auto-publish and the Published badge. + publishFromShellBar // objectui#12894 — the applied card's two doors (handlers above). With // the review door wired, the card offers 查看变更并发布 in place of its // inline Publish; 撤销 is drawn only while the adapter is up. @@ -3433,107 +3300,36 @@ export function ChatPane({ // app automatically the moment the agent finishes — no manual click; the // user refreshes and sees it live WITH data. Same governed endpoint. autoPublishDrafts={getRuntimeConfig().features.autoPublishAiBuilds} - // ADR-0037 Live Canvas: open/refresh the draft-preview pane as the - // agent's artifacts land; Preview buttons deep-link the same route. + // objectstack#34610 — each drafted artifact refreshes the main area in + // place (ADR-0037 Phase 2) and, in a turn this pane streams, moves it + // to the app (handlers above). onDraftArtifacts={handleDraftArtifacts} - onPreviewDraftApp={(appName, opts) => { - setCanvasApp({ name: appName, segment: opts?.appSegment, materialized: opts?.materialized === true }); - // #2481 — a Preview tap is an explicit request to SEE it, so on a - // phone open the full-screen overlay (desktop shows the split pane). - if (phonePreview) setMobileCanvasOpen(true); - }} - // objectui#12968 (objectstack#24324 ruling A) — any other draft's - // Preview: the Live Canvas opens the affected surface (a page, the - // object's list on a view, the object's default list) in draft - // preview, at the path `draftPreviewPath` builds from the drafted - // items in the app routed at the package id (ADR-0048). - onPreviewDraft={(items, { appSegment }) => { - setCanvasApp({ - name: appSegment, - segment: appSegment, - materialized: false, - path: draftPreviewPath(items, appSegment), - }); - if (phonePreview) setMobileCanvasOpen(true); - }} - // ADR-0045: build materialized → canvas leaves the draft overlay for - // the real (unlisted) app; the reload shows live seed rows. + // A draft card's Preview puts the main area on what it drafted: the + // app (`onPreviewDraftApp`), or the affected surface — a page, the + // object's list on a view, the object's default list — at the path + // `draftPreviewPath` builds in the app routed at the package id + // (objectui#12968, ADR-0048). With no main area to move (the Studio + // copilot, whose canvas shows the drafts) the cards draw no Preview. + onPreviewDraftApp={ + showsMainArea + ? (appName, opts) => + showAppInMainArea(opts?.appSegment ?? appName, { materialized: opts?.materialized === true }) + : undefined + } + onPreviewDraft={ + showsMainArea + ? (items, { appSegment }) => showAppInMainArea(appSegment, { path: draftPreviewPath(items, appSegment) }) + : undefined + } + // ADR-0045: build materialized → the main area shows the real + // (unlisted) app, whose own bar publishes it. onBuildMaterialized={handleBuildMaterialized} - onBuildResult={handleBuildResult} // objectui#11666 — mirrored onto the assistant bus (effect above). onPlanApprovalPendingChange={onPlanApprovalPendingChange} previewDraftLabel={t('console.ai.previewDraft', { defaultValue: 'Preview' })} data-testid="ai-chat-panel" />
- {desktopSplit ? ( - <> - {/* Draggable divider — resize the chat ↔ preview split. */} - - setCanvasApp(null)} - /> - {/* While dragging, an overlay above the canvas iframe keeps pointer - events flowing to the window listeners (an iframe would otherwise - swallow them) and shows the resize cursor everywhere. */} - {split.dragging ?
: null} - - ) : null} - {/* #2481 — MOBILE preview. The beside-chat split has no room on a phone, - nor in a pane too narrow for it (`phonePreview`), so the canvas is opt-in and full-screen: the pill above the composer - (`promptHeaderRows`) offers it (build streams uninterrupted in the - chat), and tapping it — or a Preview button on a draft card — takes - over the screen. Closing the overlay returns to the chat with the - preview still one tap away. */} - {canvasApp && phonePreview && mobileCanvasOpen ? ( -
- setMobileCanvasOpen(false)} - /> -
- ) : null}
); } diff --git a/ui/packages/app-shell/src/console/ai/LiveCanvas.header-26469.test.tsx b/ui/packages/app-shell/src/console/ai/LiveCanvas.header-26469.test.tsx deleted file mode 100644 index a919d789aab..00000000000 --- a/ui/packages/app-shell/src/console/ai/LiveCanvas.header-26469.test.tsx +++ /dev/null @@ -1,57 +0,0 @@ -/** - * ObjectUI - * Copyright (c) 2024-present ObjectStack Inc. - * - * objectstack#26469 — the Live Canvas header names the app by the label the - * chat's build card uses and says what the card says about publishing: a - * build the card calls live carries no 「未发布 · 仅自己可见」, a materialized - * build the card does not call live keeps it. Rendered through the shipped zh - * pack, since the wording is the point. - */ -import '@testing-library/jest-dom/vitest'; -import { describe, it, expect } from 'vitest'; -import { render, screen } from '@testing-library/react'; -import { MemoryRouter } from 'react-router-dom'; -import { I18nProvider } from '@object-ui/i18n'; -import { LiveCanvas, type LiveCanvasProps } from './LiveCanvas'; - -function renderZh(props: Partial) { - render( - - - {}} - {...props} - /> - - , - ); - return screen.getByTestId('live-canvas').firstElementChild as HTMLElement; -} - -describe('LiveCanvas header — the build card is the source (objectstack#26469)', () => { - it('a published build: the label, and no 未发布 badge', () => { - const header = renderZh({ appLabel: '家装项目管理', materialized: true, live: true }); - expect(header).toHaveTextContent('运行预览 · 家装项目管理'); - expect(header).not.toHaveTextContent('未发布'); - expect(header).not.toHaveTextContent('home_renovation_management'); - }); - - it('a materialized build the card does not call live keeps the 未发布 badge', () => { - const header = renderZh({ appLabel: '家装项目管理', materialized: true }); - expect(header).toHaveTextContent('运行预览 · 家装项目管理(未发布 · 仅自己可见)'); - }); - - it('without a label the header falls back to the machine name', () => { - const header = renderZh({ materialized: true, live: true }); - expect(header).toHaveTextContent('运行预览 · home_renovation_management'); - }); - - it('a draft preview stays a draft preview, by label', () => { - const header = renderZh({ appLabel: '家装项目管理' }); - expect(header).toHaveTextContent('草稿预览 · 家装项目管理'); - }); -}); diff --git a/ui/packages/app-shell/src/console/ai/LiveCanvas.test.tsx b/ui/packages/app-shell/src/console/ai/LiveCanvas.test.tsx deleted file mode 100644 index 515c088870b..00000000000 --- a/ui/packages/app-shell/src/console/ai/LiveCanvas.test.tsx +++ /dev/null @@ -1,87 +0,0 @@ -/** - * ObjectUI - * Copyright (c) 2024-present ObjectStack Inc. - * - * ADR-0080 reverse bridge: the Live Canvas (the build session's result pane, - * which renders the RUNNING app) must offer an explicit jump into the Studio - * design surface — otherwise a builder who wants to fine-tune structure after a - * build is stranded (the pane's only other action is close). - */ -import '@testing-library/jest-dom/vitest'; -import { describe, it, expect, vi, beforeEach } from 'vitest'; -import { render, screen, fireEvent } from '@testing-library/react'; -import { LiveCanvas } from './LiveCanvas'; - -vi.mock('@object-ui/i18n', async (importOriginal) => ({ - ...(await importOriginal>()), - useObjectTranslation: () => ({ - t: (key: string, options?: Record) => String(options?.defaultValue ?? key), - }), -})); - -const navigate = vi.fn(); -vi.mock('react-router-dom', async (importActual) => ({ - ...(await importActual()), - useNavigate: () => navigate, -})); - -describe('LiveCanvas — Design in Studio bridge', () => { - beforeEach(() => navigate.mockClear()); - - it('renders a Design in Studio control that opens the package’s design surface', () => { - render( - {}} />, - ); - const btn = screen.getByTestId('live-canvas-open-designer'); - expect(btn).toBeInTheDocument(); - fireEvent.click(btn); - expect(navigate).toHaveBeenCalledWith('/studio/app.v6gq/interfaces'); - }); - - it('omits the bridge when the app has no addressable package segment', () => { - render( {}} />); - expect(screen.queryByTestId('live-canvas-open-designer')).not.toBeInTheDocument(); - }); - - it('still renders the close control', () => { - render( {}} />); - expect(screen.getByTestId('live-canvas-close')).toBeInTheDocument(); - }); -}); - -describe('LiveCanvas — a drafted surface beside the app segment (objectui#12968)', () => { - it('opens the full preview path the host names, in draft preview', () => { - render( - {}} - />, - ); - expect(screen.getByTestId('live-canvas-frame')).toHaveAttribute( - 'src', - '/apps/app.crm/crm_account/view/crm_account.pipeline?preview=draft', - ); - }); - - it('CONTROL: without a path the canvas opens the app in draft preview, as before', () => { - render( {}} />); - expect(screen.getByTestId('live-canvas-frame')).toHaveAttribute('src', '/apps/app.crm?preview=draft'); - }); - - it('a materialized build shows the real app, whatever path was named', () => { - render( - {}} - />, - ); - expect(screen.getByTestId('live-canvas-frame')).toHaveAttribute('src', '/apps/app.crm'); - }); -}); diff --git a/ui/packages/app-shell/src/console/ai/LiveCanvas.tsx b/ui/packages/app-shell/src/console/ai/LiveCanvas.tsx deleted file mode 100644 index 9817608677b..00000000000 --- a/ui/packages/app-shell/src/console/ai/LiveCanvas.tsx +++ /dev/null @@ -1,185 +0,0 @@ -/** - * ObjectUI - * Copyright (c) 2024-present ObjectStack Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -/** - * ADR-0037 Live Canvas — the result pane of a build session. Chat on the - * left, the user's app rendered from the DRAFT overlay on the right, taking - * shape while they talk. - * - * Deliberately an iframe onto `/apps/:name?preview=draft`: the canvas mounts - * the EXISTING app renderers in preview mode through the same route a user - * could open by hand — no second renderer, no canvas-only store (ADR-0037 - * boundary rules: one truth, the canvas never edits in place). Per-artifact - * invalidations from the chat coalesce into a reload of the pane, so during - * an `apply_blueprint` the app grows step-by-step with the build tree. - */ - -import { useEffect, useRef } from 'react'; -import { useNavigate } from 'react-router-dom'; -import { X, Eye, Hammer } from 'lucide-react'; -import { Button } from '@object-ui/components'; -import { useObjectTranslation } from '@object-ui/i18n'; - -export interface LiveCanvasProps { - /** The drafted app to render (its `app` metadata name). */ - appName: string; - /** - * The app's display label, as the chat's build card names it - * (`checklist.app.label`). The header shows it in place of `appName`. - */ - appLabel?: string; - /** - * The chat's build card says the app is live (published). The header then - * names the app as live and drops the unlisted note, whatever - * `materialized` says — the card is the one source of the publish state. - */ - live?: boolean; - /** - * ADR-0048: the app's ROUTE SEGMENT — its package id (`app.`), which is - * globally unique, unlike the display name (two AI apps can both be `library`). - * The iframe URL keys on this; falls back to `appName` when absent. - */ - appSegment?: string; - /** - * ADR-0045: the build was materialized — the app is live (real tables and - * seed rows) but unlisted. The canvas then renders the REAL app URL: full - * data, full interaction; the in-app UnpublishedAppBar narrates the state. - * False (default) keeps the ADR-0037 draft-overlay preview for mutations. - */ - materialized?: boolean; - /** - * objectui#12968 — the full router path to preview, beside the app segment: - * a drafted page, view or object surface (`draftPreviewPath`'s answer, - * `/apps//…?preview=draft`) instead of the app's landing. Ignored - * once `materialized`, which shows the real app. - */ - path?: string; - /** Bump to reload the pane (the host coalesces invalidation storms). */ - refreshKey: number; - onClose: () => void; -} - -/** - * The SPA's mount prefix for ABSOLUTE urls (the iframe bypasses the router's - * basename, unlike navigate()). The console ships under `/_console`; bare - * mounts (tests, custom hosts) fall back to ''. - */ -function spaBase(): string { - if (typeof window === 'undefined') return ''; - return window.location.pathname.startsWith('/_console') ? '/_console' : ''; -} - -/** - * Canvas iframe target: the REAL app once materialized; otherwise the drafted - * surface's path when the host named one, else the app in the draft overlay. - */ -function canvasSrc(appName: string, materialized: boolean, path?: string): string { - const base = `${spaBase()}/apps/${encodeURIComponent(appName)}`; - if (materialized) return base; - return path ? `${spaBase()}${path}` : `${base}?preview=draft`; -} - -export function LiveCanvas({ - appName, - appLabel, - live = false, - appSegment, - materialized = false, - path, - refreshKey, - onClose, -}: LiveCanvasProps) { - const { t } = useObjectTranslation(); - const navigate = useNavigate(); - const iframeRef = useRef(null); - // Route on the package-id segment (unique), display by name (friendly). - const routeSeg = appSegment && appSegment.length ? appSegment : appName; - const displayName = appLabel || appName; - // Materialized world swap: changing src on the SAME iframe element - // navigates it in place (no white-flash remount). - useEffect(() => { - if (!iframeRef.current) return; - const next = canvasSrc(routeSeg, materialized, path); - try { - if (iframeRef.current.getAttribute('src') !== next) iframeRef.current.setAttribute('src', next); - } catch { - /* not ready — the mount src covers it */ - } - }, [routeSeg, materialized, path]); - - // Refresh in place (src reload) instead of remounting the iframe — keeps - // the pane from flashing white on every invalidation. - useEffect(() => { - if (refreshKey > 0) { - try { - iframeRef.current?.contentWindow?.location.reload(); - } catch { - /* cross-origin or not ready — the next mount picks it up */ - } - } - }, [refreshKey]); - - return ( -
-
- - - {live - ? t('console.ai.liveCanvasLive', { - app: displayName, - defaultValue: 'Live app — {{app}}', - }) - : materialized - ? t('console.ai.liveCanvasUnlisted', { - app: displayName, - defaultValue: 'Live app — {{app}} (unlisted until published)', - }) - : t('console.ai.liveCanvas', { - app: displayName, - defaultValue: 'Live preview — {{app}} (draft)', - })} - - {/* Bridge to the design surface — this pane is the RUNNING app, so the - builder needs an explicit way to jump into the Studio designer to - fine-tune structure/layout (previously the only action here was - close, stranding users who wanted to keep editing). ADR-0080 reverse - bridge, mirroring the running app's own "Design in Studio" header. */} - {appSegment && ( - - )} - -
-