import { Button } from 'open-design-ui/button'; import { IconButton } from 'open-design-ui/icon-button'; import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react'; import { createPortal } from 'react-dom'; import { gameGenres, gameSettings, gameStyles, isReadyBuiltInTemplate, type GameCard, type GameCreated, type GameGenre, type GameSetting, type GameStyle } from '../../../../shared/game-contract'; import { rankSearchResults } from '../../../../shared/fuzzy-search'; import { buildSuperAgentHandoff } from '../../../../shared/capability-hub'; import { preservePresentation } from '../../../../shared/workspace-url'; import { StudioToastViewport } from '../../components/StudioToastViewport'; import { WebPublishPopover } from '../../components/WebPublishPopover'; import { useToast } from '../../hooks/useToast'; import { useI18n } from '../../i18n/I18n'; import { useVisibilityPolling } from '../../hooks/useVisibilityPolling'; import { useDeferredIframeSource } from '../../utils/useDeferredIframeSource'; import { RemixIcon } from '../../icons/RemixIcons'; import { WorkspaceBack } from '../WorkspaceBack'; import { useOptionalWorkspaceChrome } from '../WorkspaceChromeContext'; import { MotionIcon } from '../icons'; import { projectHref } from '../workspaceRouting'; import { Tooltip } from '../../components/ui/Tooltip'; import { GameMasonry, interleavePortrait } from './GameMasonry'; import { bundledGames, communityGames, communityRemixPrompt, composeBrief, coverUrl, formatPlays, gameApi, gameSource, isIsolatedGameFrame, isTopEarningGame, storedInstruction, genreCovers, genreLabels, settingCovers, styleCovers, genrePlaceholders, isLocalOnly, playableUrl, rememberInstruction, settingLabels, styleLabels, TOP_EARNING_TAG } from './gameCatalog'; import { buildGameContextTags, buildGameHiddenInstructions, buildGameUserPrompt, toGameArtifact, toGameCapabilityRef } from './gameSuperAgent'; import { optionId as optionFilter } from '../reporting'; import { reportGameAction, reportGameClick, reportGameCreate, reportGameDetailShown, reportGameHandoffShown, reportGameSearch } from './gameTracking'; import { newTrackingId } from '../reporting'; import './gameStudio.css'; type Menu = 'genre' | 'style' | 'setting'; type Sort = 'relevance' | 'plays' | 'newest'; const pending = (game: GameCard) => game.source === 'mine' && (game.status === 'draft' || game.status === 'building'); /** * Game Studio. The page is the game market; the composer is docked at the bottom. Picking a genre, style and * setting (and optionally one line of text) creates a local game draft and hands it off to Super Agent (or the * user's external MCP Agent) to build, validate and publish through the OpenMotion MCP game tools. Drafts refresh * until the Agent finishes, so their state changes here without reloading. */ export function GameStudio({ onExplore, onOpenMcp, initialGameId = null, }: { onExplore: () => void; onOpenMcp: () => void; initialGameId?: string | null; }) { const { t, locale } = useI18n(); const chrome = useOptionalWorkspaceChrome(); const getGameTitle = useGameTitle(); const toast = useToast(); const [genre, setGenre] = useState('shooter'); const [style, setStyle] = useState(null); const [setting, setSetting] = useState(null); const [orientation, setOrientation] = useState<'landscape' | 'portrait'>('landscape'); // Portrait games default to a playable ad. const [playableAd, setPlayableAd] = useState(true); const adBuild = orientation === 'portrait' && playableAd; const [prompt, setPrompt] = useState(''); const [menu, setMenu] = useState('genre'); const [submitting, setSubmitting] = useState(false); const [games, setGames] = useState(bundledGames); const [offline, setOffline] = useState(false); const [query, setQuery] = useState(''); const [category, setCategory] = useState('all'); const [sort, setSort] = useState('relevance'); // The open project is tracked by id so polling updates reach it. // ?game= opens that game's detail page directly (used by links from Assets and Super Agent). const [openId, setOpenIdState] = useState(() => initialGameId ?? new URLSearchParams(location.search).get('game')); const setOpenId = (id: string | null) => { setOpenIdState(id); const url = new URL(location.href); if (id) url.searchParams.set('game', id); else url.searchParams.delete('game'); history.replaceState(history.state, '', url); }; useEffect(() => { if (initialGameId) setOpenIdState(initialGameId); }, [initialGameId]); useEffect(() => { const onPopState = () => setOpenIdState(new URLSearchParams(location.search).get('game')); addEventListener('popstate', onPopState); return () => removeEventListener('popstate', onPopState); }, []); // The full composer sits at the top of the page. Once it scrolls away, a docked copy floats over the bottom edge: one line // while scrolling down, full size while scrolling up. It overlays the page, so its size never moves the content. const [scrolledUp, setScrolledUp] = useState(false); const [heroVisible, setHeroVisible] = useState(true); const hero = useRef(null); const [toggled, setToggled] = useState(null); const [focused, setFocused] = useState(false); const root = useRef(null), input = useRef(null); const expanded = toggled ?? (scrolledUp || focused); const notify = (message: string, tone: 'info' | 'error') => toast.showToast(message, tone); const statuses = useRef(new Map()); const loaded = useRef(false), openRef = useRef(openId); openRef.current = openId; const load = () => gameApi.catalog().then(catalog => { // A draft that appears without this page creating it was started by an Agent from its own chat (openmotion_game_create). // Jump to it when nothing else is open; otherwise point to the side list without interrupting the game being played. if (loaded.current) { const fresh = catalog.games.find(game => game.source === 'mine' && pending(game) && !statuses.current.has(game.id)); if (fresh) { if (!openRef.current) setOpenId(fresh.id); else notify(t('Your Agent started {title}. Find it in My games.', { title: fresh.title }), 'info'); } } loaded.current = true; // Announce drafts that the Agent finished or abandoned since the last refresh. for (const game of catalog.games) { const before = statuses.current.get(game.id); if (before && before !== game.status && game.source === 'mine') { if (game.status === 'published' || game.status === 'ready') notify(t('{title} is ready to play.', { title: game.title }), 'info'); if (game.status === 'failed') notify(t('{title} could not be finished. Hand it to your Agent again.', { title: game.title }), 'error'); } statuses.current.set(game.id, game.status); } setGames(catalog.games); setOffline(false); }).catch(() => { setGames(current => current.some(game => game.source === 'mine') ? current : bundledGames); setOffline(true); }); useEffect(() => { void load(); }, []); // Poll every 4 s while the page is visible, so drafts an Agent starts from its chat show up and open on their own. useVisibilityPolling(() => load(), { intervalMs: 4000, immediate: false }); useEffect(() => { const scroller = root.current; if (!scroller) return; let last = scroller.scrollTop, settledAt = 0; const onScroll = () => { const top = scroller.scrollTop; // Ignore small movements and anything within 250 ms of the previous change so the dock never oscillates. if (performance.now() - settledAt < 250) { last = top; return; } if (top < last - 24) { setScrolledUp(true); settledAt = performance.now(); } else if (top > last + 24) { setScrolledUp(false); settledAt = performance.now(); } else return; if (Math.abs(top - last) > 6) setToggled(null); last = top; }; scroller.addEventListener('scroll', onScroll, { passive: true }); const observer = new IntersectionObserver(([entry]) => { setHeroVisible(entry.isIntersecting); if (entry.isIntersecting) { setScrolledUp(false); setToggled(null); } }, { root: scroller, threshold: 0.15 }); if (hero.current) observer.observe(hero.current); return () => { scroller.removeEventListener('scroll', onScroll); observer.disconnect(); }; }, []); const update = (card: GameCard) => setGames(list => list.map(game => game.id === card.id ? card : game)); const brief = composeBrief({ prompt, genre, style, setting, multiplayer: false }); const failure = (error: unknown) => error instanceof TypeError || offline ? t('The local game service is not available. Update OpenMotion and try again.') : t('The game could not be created: {reason}', { reason: (error as Error).message }); const started = ( created: GameCreated, options?: { builtInTemplateRemix?: boolean }, ): 'super_agent' | 'detail' => { rememberInstruction(created.game.id, created.agentInstruction); statuses.current.set(created.game.id, created.game.status); setGames(list => [created.game, ...list.filter(game => game.id !== created.game.id)]); if (chrome?.openInSuperAgent) { const displayTitle = getGameTitle(created.game); const ready = created.game.status === 'ready' || created.game.status === 'published'; setOpenIdState(null); const handoff = buildSuperAgentHandoff(toGameCapabilityRef(created.game, displayTitle), { prompt: buildGameUserPrompt(created.game, locale), hiddenInstructions: buildGameHiddenInstructions( created.game, created.agentInstruction, undefined, options?.builtInTemplateRemix ? { builtInTemplateRemix: true, hasUserPromptText: false, locale } : undefined, ), contextTags: buildGameContextTags(created.game, t), locale, newChat: true, autoSend: true, ...(ready ? { initialArtifact: toGameArtifact(created.game, displayTitle) } : {}), }); chrome.openInSuperAgent({ ...handoff, title: ready ? displayTitle : undefined }); return 'super_agent'; } setOpenId(created.game.id); return 'detail'; }; const createError = (error: unknown) => error instanceof TypeError || offline ? 'service_unavailable' as const : 'rejected' as const; const continueInSuperAgent = (game: GameCard, instruction: string) => { if (!chrome?.openInSuperAgent || game.multiplayer) return; const displayTitle = getGameTitle(game); setOpenIdState(null); const handoff = buildSuperAgentHandoff(toGameCapabilityRef(game, displayTitle), { prompt: buildGameUserPrompt(game, locale), hiddenInstructions: buildGameHiddenInstructions(game, instruction), contextTags: buildGameContextTags(game, t), locale, newChat: true, autoSend: true, }); chrome.openInSuperAgent({ ...handoff, title: undefined }); }; const editInSuperAgent = (game: GameCard) => { if (!chrome?.openInSuperAgent || game.multiplayer) return; const displayTitle = getGameTitle(game); setOpenIdState(null); chrome.openInSuperAgent({ ...buildSuperAgentHandoff(toGameCapabilityRef(game, displayTitle), { locale, newChat: true, autoSend: false, initialArtifact: toGameArtifact(game, displayTitle), }), prompt: '', }); }; const submit = async () => { if (!brief || submitting) return; setSubmitting(true); const tracked = { brief: { genre, style, setting, orientation, multiplayer: false, playableAd: adBuild, hasPrompt: Boolean(prompt.trim()) } }; // Choosing options without typing is enough to start: the composed brief becomes the prompt. try { const created = await gameApi.create({ prompt: prompt.trim() || brief, genre, style, setting, multiplayer: false, orientation, playableAd: adBuild }); reportGameCreate('brief', { game: created.game, handoff: started(created) }, tracked); setPrompt(''); } catch (error) { reportGameCreate('brief', { error: createError(error) }, tracked); notify(failure(error), 'error'); } finally { setSubmitting(false); } }; const remix = async (game: GameCard) => { if (game.multiplayer) return; // Community games are not copied: a new original game is briefed from their genre, style and description. try { const created = game.external ? await gameApi.create({ prompt: communityRemixPrompt(game), genre: game.genre, style: game.style, setting: game.setting, multiplayer: false, orientation: game.orientation ?? 'landscape' }) : await gameApi.remix(game.id); const builtInTemplateRemix = isReadyBuiltInTemplate(game); reportGameCreate('remix', { game: created.game, handoff: started(created, { builtInTemplateRemix }) }, { source: game }); } catch (error) { reportGameCreate('remix', { error: createError(error) }, { source: game }); notify(failure(error), 'error'); } }; const open = (game: GameCard, area: 'game_market' | 'game_sidebar' = 'game_market', position?: number) => { reportGameClick(area, 'open_game', game, position === undefined ? {} : { position }); // Sites that refuse to be embedded open in a new window; everything else plays in the project view. setOpenId(game.id); }; // Popular games from social media lead the market, followed by the built-in templates and the user's games. const all = useMemo(() => [...communityGames, ...games], [games]); const opened = openId ? all.find(game => game.id === openId) ?? null : null; const fanned = all.filter(game => game.source !== 'mine' && game.status === 'published' && coverUrl(game)).slice(0, 5); const visible = useMemo(() => { const needle = query.trim(); // Explore lists templates and community games only; games made here live in Assets → Games. const byCategory = all.filter(game => game.source !== 'mine' && game.status === 'published' && (category === 'all' || (category === 'portrait' ? game.orientation === 'portrait' : category === 'top-earning' ? isTopEarningGame(game) : game.genre === category))); const list = needle ? rankSearchResults(byCategory, needle, game => ({ id: game.id, title: game.i18n?.[locale]?.title ?? game.title, subtitle: t(genreLabels[game.genre]), description: game.i18n?.[locale]?.description ?? game.description, tags: [game.genre, ...(game.style ? [game.style] : []), ...(game.setting ? [game.setting] : []), ...(game.tags ?? [])], aliases: [ game.title, game.description, ...Object.values(game.i18n ?? {}).flatMap(loc => [loc?.title ?? '', loc?.description ?? '']), ], })).map(r => r.item) : byCategory; if (sort === 'plays') return [...list].sort((a, b) => b.plays - a.plays); if (sort === 'newest') return [...list].sort((a, b) => b.createdAt.localeCompare(a.createdAt)); return needle ? list : interleavePortrait(list); }, [all, category, query, sort, t, locale]); // The user's own games, newest first, live in the side list like projects in the Motion editor. const mine = useMemo(() => games.filter(game => game.source === 'mine').sort((a, b) => b.updatedAt.localeCompare(a.updatedAt)), [games]); const lastSearchKey = useRef(''); useEffect(() => { const trimmed = query.trim(); if (!trimmed) { lastSearchKey.current = ''; return; } const key = `${trimmed}\0${category}\0${visible.length}`; if (key === lastSearchKey.current) return; const timer = window.setTimeout(() => { lastSearchKey.current = key; reportGameSearch(newTrackingId(), trimmed, visible.length, category); }, 400); return () => window.clearTimeout(timer); }, [query, category, visible.length]); const browsing = category === 'all' && !query.trim(); const rows = [ ...(browsing ? [ { id: 'featured', title: t('Templates'), icon: 'gamepad-line', games: visible }, ] : [{ id: 'all', title: category === 'all' ? t('All games') : category === 'portrait' ? t('Portrait games') : category === 'top-earning' ? TOP_EARNING_TAG : t('{genre} games', { genre: t(genreLabels[category]) }), icon: category === 'top-earning' ? 'sparkling-fill' : 'gamepad-line', games: visible, }]), ]; const options: { id: string; label: string; cover?: string | null; selected: boolean; pick: () => void }[] = menu === 'genre' ? gameGenres.map(id => ({ id, label: t(genreLabels[id]), cover: genreCovers[id], selected: genre === id, pick: () => setGenre(genre === id ? null : id) })) : menu === 'style' ? gameStyles.map(id => ({ id, label: t(styleLabels[id]), cover: styleCovers[id], selected: style === id, pick: () => { setStyle(style === id ? null : id); setMenu('genre'); } })) : gameSettings.map(id => ({ id, label: t(settingLabels[id]), cover: settingCovers[id], selected: setting === id, pick: () => { setSetting(setting === id ? null : id); setMenu('genre'); } })); // The same composer renders inline at the top of the page and, once that scrolls away, docked at the bottom. const renderComposer = (mode: 'hero' | 'dock') =>
mode === 'dock' && setFocused(true)} onBlur={event => { if (!event.currentTarget.contains(event.relatedTarget as Node | null)) setFocused(false); }}> {mode === 'dock' && { setToggled(!expanded); if (expanded) { setFocused(false); setMenu('genre'); input.current?.blur(); } }} icon={} />}
{options.map(option => )}