Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

Fix playground model selection and UI improvements (#1030)

Sarina Li6e59ef4da9f7
diff --git a/libs/typescript/playground/src/components/Playground.tsx b/libs/typescript/playground/src/components/Playground.tsx
index 8e598597dd..79d4240e63 100644
--- a/libs/typescript/playground/src/components/Playground.tsx
+++ b/libs/typescript/playground/src/components/Playground.tsx
@@ -88,12 +88,25 @@ function PlaygroundContentInternal({
);
// Handle creating a new chat and sending the first message
- const handleCreateAndSend = async (message: string) => {
+ const handleCreateAndSend = async (
+ message: string,
+ selectedModel?: Chat['model'],
+ selectedComputer?: Chat['computer']
+ ) => {
+ // Use model/computer from empty state picker, or fall back to defaults
+ const model = selectedModel ?? defaultModel;
+ const computer =
+ selectedComputer ??
+ (currentComputer
+ ? { id: currentComputer.id, name: currentComputer.name, url: currentComputer.agentUrl }
+ : undefined);
+
const newChat: Chat = {
id: crypto.randomUUID(),
name: message.slice(0, 50) || 'New Chat',
messages: [],
- model: defaultModel,
+ model,
+ computer,
created: new Date(),
updated: new Date(),
};
diff --git a/libs/typescript/playground/src/components/composed/ChatContent.tsx b/libs/typescript/playground/src/components/composed/ChatContent.tsx
index 6a0b27e02a..33487e8942 100644
--- a/libs/typescript/playground/src/components/composed/ChatContent.tsx
+++ b/libs/typescript/playground/src/components/composed/ChatContent.tsx
@@ -176,6 +176,8 @@ export function ChatContent({
};
// Render VM status banner if provided
+ // Use selectedComputerForInput to show the banner for the currently selected computer in dropdown
+ // This ensures the banner updates immediately when user selects an offline VM
const vmStatusBanner = renderVMStatusBanner?.({
onRestartVM,
onStartVM,
@@ -183,7 +185,7 @@ export function ChatContent({
hasWorkspace,
hasCredits,
orgSlug,
- computer,
+ computer: selectedComputerForInput,
computers,
});
diff --git a/libs/typescript/playground/src/components/composed/ChatList.tsx b/libs/typescript/playground/src/components/composed/ChatList.tsx
index cccea9e2df..241f9059ce 100644
--- a/libs/typescript/playground/src/components/composed/ChatList.tsx
+++ b/libs/typescript/playground/src/components/composed/ChatList.tsx
@@ -25,7 +25,7 @@ import {
useIsChatGenerating,
usePlayground,
} from '../../hooks/usePlayground';
-import type { Chat } from '../../types';
+import type { Chat, Computer } from '../../types';
import { cn } from '../../utils/cn';
interface ChatListProps {
@@ -51,7 +51,7 @@ export function ChatList({
onToast,
}: ChatListProps) {
const { state, dispatch, adapters } = usePlayground();
- const { chats, activeChatId } = state;
+ const { chats, activeChatId, computers, currentComputerId } = state;
const activeChat = useActiveChat();
const defaultModel = useFindDefaultModel();
const [isCreating, setIsCreating] = useState(false);
@@ -67,11 +67,35 @@ export function ChatList({
setIsCreating(true);
try {
+ // Priority: use currently selected computer (currentComputerId), then fall back to first available
+ const selectedComputer = currentComputerId
+ ? computers.find((c) => c.id === currentComputerId)
+ : undefined;
+ const computerInfo = selectedComputer ?? (computers.length > 0 ? computers[0] : undefined);
+
+ // Check if the computer is stopped
+ if (computerInfo && computerInfo.status === 'stopped') {
+ onToast?.('Cannot create chat: The sandbox is stopped. Please start it first.', 'error');
+ setIsCreating(false);
+ return;
+ }
+
+ // Convert ComputerInfo to Computer type for the chat
+ let computer: Computer | undefined;
+ if (computerInfo) {
+ const { agentUrl, ...rest } = computerInfo;
+ computer = {
+ ...rest,
+ url: agentUrl,
+ } as Computer;
+ }
+
// Create local chat object
const newChat: Chat = {
id: crypto.randomUUID(), // Temporary ID, adapter may replace it
name: 'New Chat',
messages: [],
+ computer,
model: defaultModel,
created: new Date(),
updated: new Date(),
@@ -91,7 +115,16 @@ export function ChatList({
} finally {
setIsCreating(false);
}
- }, [defaultModel, dispatch, isCreating, adapters.persistence, onCreateChat, onToast]);
+ }, [
+ computers,
+ currentComputerId,
+ defaultModel,
+ dispatch,
+ isCreating,
+ adapters.persistence,
+ onCreateChat,
+ onToast,
+ ]);
const handleDeleteConfirm = async () => {
if (!deleteConfirmChat) return;
diff --git a/libs/typescript/playground/src/components/composed/ChatSidebar.tsx b/libs/typescript/playground/src/components/composed/ChatSidebar.tsx
index 8906950865..f967d91e29 100644
--- a/libs/typescript/playground/src/components/composed/ChatSidebar.tsx
+++ b/libs/typescript/playground/src/components/composed/ChatSidebar.tsx
@@ -26,7 +26,6 @@ import {
usePlayground,
} from '../../hooks/usePlayground';
import type { Chat, Computer } from '../../types';
-import { isVM } from '../../types';
import { cn } from '../../utils/cn';
interface ChatSidebarProps {
@@ -76,8 +75,8 @@ export function ChatSidebar({
const computer = selectedComputer ?? (computers.length > 0 ? computers[0] : undefined);
// Check if the computer is stopped
- if (computer && isVM(computer) && computer.status === 'stopped') {
- onToast?.('Cannot create chat: The sandbox is stopped. Please start it first.', 'error');
+ if (computer && computer.status === 'stopped') {
+ onToast?.('Cannot create chat: The sandbox is stopped. Please start it first.');
return;
}
@@ -116,7 +115,15 @@ export function ChatSidebar({
} finally {
setIsCreating(false);
}
- }, [computers, currentComputerId, defaultModel, dispatch, isCreating, adapters.persistence, onToast]);
+ }, [
+ computers,
+ currentComputerId,
+ defaultModel,
+ dispatch,
+ isCreating,
+ adapters.persistence,
+ onToast,
+ ]);
const handleDeleteConfirm = async () => {
if (!deleteConfirmChat) return;
diff --git a/libs/typescript/playground/src/components/composed/EmptyState.tsx b/libs/typescript/playground/src/components/composed/EmptyState.tsx
index 8bc78c7378..709a92bcc1 100644
--- a/libs/typescript/playground/src/components/composed/EmptyState.tsx
+++ b/libs/typescript/playground/src/components/composed/EmptyState.tsx
@@ -11,7 +11,11 @@ import type { Chat, Computer } from '../../types';
interface EmptyStateWithInputProps {
/** Callback when user sends a message to create a new chat */
- onCreateAndSend: (message: string) => Promise<void>;
+ onCreateAndSend: (
+ message: string,
+ model?: Chat['model'],
+ computer?: Chat['computer']
+ ) => Promise<void>;
/** Whether in mobile layout */
isMobile: boolean;
/** Draft chat for UI consistency */
@@ -61,7 +65,11 @@ export function EmptyStateWithInput({
}
interface EmptyStateContentProps {
- onCreateAndSend: (message: string) => Promise<void>;
+ onCreateAndSend: (
+ message: string,
+ model?: Chat['model'],
+ computer?: Chat['computer']
+ ) => Promise<void>;
isMobile: boolean;
logo?: {
lightSrc: string;
@@ -95,7 +103,8 @@ function EmptyStateContent({
if (!chatState.currentInput.trim() || isCreating) return;
setIsCreating(true);
try {
- await onCreateAndSend(chatState.currentInput.trim());
+ // Pass the model and computer selected in the empty state picker
+ await onCreateAndSend(chatState.currentInput.trim(), chatState.model, chatState.computer);
chatDispatch({ type: 'CLEAR_INPUT' });
} catch (error) {
console.error('Failed to create chat:', error);
diff --git a/libs/typescript/playground/src/components/composed/PlaygroundContent.tsx b/libs/typescript/playground/src/components/composed/PlaygroundContent.tsx
index 3110f7c0d6..5a4dccb190 100644
--- a/libs/typescript/playground/src/components/composed/PlaygroundContent.tsx
+++ b/libs/typescript/playground/src/components/composed/PlaygroundContent.tsx
@@ -13,7 +13,6 @@ import {
usePlayground,
} from '../../hooks/usePlayground';
import type { Chat, Computer } from '../../types';
-import { isVM } from '../../types';
// Re-export for convenience
export { EmptyStateWithInput } from './EmptyState';
@@ -148,32 +147,47 @@ export function PlaygroundContent({
}, [initialized, activeChat, defaultModel, dispatch]);
// Create a new chat and send the first message
- const handleCreateChatWithMessage = async (message: string) => {
- // Priority: use currently selected computer (currentComputerId), then fall back to first running, then first available
- const selectedComputer = state.currentComputerId
- ? computers.find((c) => c.id === state.currentComputerId)
- : undefined;
- const runningComputer = computers.find((c) => c.status === 'running');
- const computerInfo = selectedComputer ?? runningComputer ?? computers[0];
-
- if (!computerInfo) {
- onToast?.('Please select a sandbox to interact with.', 'error');
- return;
- }
-
- // Check if the selected computer is stopped
- if (isVM(computerInfo) && computerInfo.status === 'stopped') {
- onToast?.('Cannot start chat: The selected sandbox is stopped. Please start it first.', 'error');
- return;
+ const handleCreateChatWithMessage = async (
+ message: string,
+ selectedModel?: Chat['model'],
+ selectedChatComputer?: Chat['computer']
+ ) => {
+ // Use the model passed from empty state picker, or fall back to default
+ const model = selectedModel ?? defaultModel;
+
+ // Use computer from empty state picker, or fall back to global selection
+ let computer: Computer | undefined = selectedChatComputer;
+
+ if (!computer) {
+ // Fall back to global computer selection
+ const selectedComputer = state.currentComputerId
+ ? computers.find((c) => c.id === state.currentComputerId)
+ : undefined;
+ const runningComputer = computers.find((c) => c.status === 'running');
+ const computerInfo = selectedComputer ?? runningComputer ?? computers[0];
+
+ if (!computerInfo) {
+ onToast?.('Please select a sandbox to interact with.', 'error');
+ return;
+ }
+
+ // Check if the selected computer is stopped
+ if (computerInfo.status === 'stopped') {
+ onToast?.(
+ 'Cannot start chat: The selected sandbox is stopped. Please start it first.',
+ 'error'
+ );
+ return;
+ }
+
+ // Convert ComputerInfo to Computer
+ computer = {
+ id: computerInfo.id,
+ name: computerInfo.name,
+ url: computerInfo.agentUrl,
+ };
}
- // Convert ComputerInfo to Computer
- const computer: Computer = {
- id: computerInfo.id,
- name: computerInfo.name,
- url: computerInfo.agentUrl,
- };
-
try {
// Create chat title from first message
const base = message.trim().replace(/\s+/g, ' ');
@@ -192,7 +206,7 @@ export function PlaygroundContent({
name: title,
messages: [userMessage],
computer,
- model: defaultModel,
+ model,
created: new Date(),
updated: new Date(),
};
diff --git a/libs/typescript/playground/src/components/modals/ReplayTrajectoryModal.tsx b/libs/typescript/playground/src/components/modals/ReplayTrajectoryModal.tsx
index ab22f7d8e2..9dc2d0ec28 100644
--- a/libs/typescript/playground/src/components/modals/ReplayTrajectoryModal.tsx
+++ b/libs/typescript/playground/src/components/modals/ReplayTrajectoryModal.tsx
@@ -173,9 +173,17 @@ export default function ReplayTrajectoryModal({
const selectedRun = runs.find((r) => r.index === selectedRunIndex);
+ // Use compact size for loading, empty, or no-screenshot states
+ const hasScreenshots = selectedRun && selectedRun.screenshotCount > 0 && zipUrl;
+ const isCompactView = loading || runs.length === 0 || generatingZip || !hasScreenshots;
+
+ const modalSizeClass = isCompactView ? 'w-full max-w-md' : 'h-[90vh] w-[95vw] max-w-7xl';
+
return (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
- <div className="relative flex h-[90vh] w-[95vw] max-w-7xl flex-col overflow-hidden rounded-lg bg-white shadow-xl dark:bg-neutral-900">
+ <div
+ className={`relative flex flex-col overflow-hidden rounded-lg bg-white shadow-xl dark:bg-neutral-900 ${modalSizeClass}`}
+ >
{/* Header */}
<div className="flex items-center justify-between border-neutral-200 border-b px-4 py-3 dark:border-neutral-700">
<div className="flex items-center gap-3">
@@ -218,9 +226,9 @@ export default function ReplayTrajectoryModal({
)}
{/* Main content */}
- <div className="flex-1 overflow-hidden">
+ <div className={isCompactView ? 'p-6' : 'flex-1 overflow-hidden'}>
{loading ? (
- <div className="flex h-full items-center justify-center">
+ <div className="flex items-center justify-center py-8">
<div className="flex flex-col items-center gap-3">
<Loader2 className="h-8 w-8 animate-spin text-blue-500" />
<p className="text-neutral-600 text-sm dark:text-neutral-400">
@@ -229,13 +237,13 @@ export default function ReplayTrajectoryModal({
</div>
</div>
) : runs.length === 0 ? (
- <div className="flex h-full items-center justify-center">
+ <div className="flex items-center justify-center py-8">
<p className="text-neutral-500 dark:text-neutral-400">
No trajectory runs found in this chat.
</p>
</div>
) : generatingZip ? (
- <div className="flex h-full items-center justify-center">
+ <div className="flex items-center justify-center py-8">
<div className="flex flex-col items-center gap-3">
<Loader2 className="h-8 w-8 animate-spin text-blue-500" />
<p className="text-neutral-600 text-sm dark:text-neutral-400">
@@ -244,7 +252,7 @@ export default function ReplayTrajectoryModal({
</div>
</div>
) : selectedRun && selectedRun.screenshotCount === 0 ? (
- <div className="flex h-full items-center justify-center">
+ <div className="flex items-center justify-center py-8">
<div className="text-center">
<p className="text-neutral-500 dark:text-neutral-400">
This run has no screenshots to replay.
@@ -270,8 +278,8 @@ export default function ReplayTrajectoryModal({
) : null}
</div>
- {/* Footer with run info */}
- {selectedRun && !loading && (
+ {/* Footer with run info - only show when viewing actual trajectory */}
+ {selectedRun && !loading && !isCompactView && (
<div className="flex items-center justify-between border-neutral-200 border-t bg-neutral-50 px-4 py-2 text-xs dark:border-neutral-700 dark:bg-neutral-800/50">
<span className="text-neutral-500 dark:text-neutral-400">
{selectedRun.screenshotCount} screenshot
diff --git a/libs/typescript/playground/src/context/ChatProvider.tsx b/libs/typescript/playground/src/context/ChatProvider.tsx
index 93acb9c0a4..3c16ddb172 100644
--- a/libs/typescript/playground/src/context/ChatProvider.tsx
+++ b/libs/typescript/playground/src/context/ChatProvider.tsx
@@ -1,7 +1,7 @@
// Per-chat context provider
// Adapted from cloud/src/website/app/contexts/ChatContext.tsx
-import { useReducer, useEffect, useRef, type ReactNode } from 'react';
+import { useReducer, useEffect, useRef, useCallback, type ReactNode } from 'react';
import {
ChatStateContext,
ChatDispatchContext,
@@ -115,7 +115,19 @@ export function ChatProvider({ chat, children, isGenerating = false }: ChatProvi
waitingForResponse: isGenerating,
}));
- const { dispatch: playgroundDispatch } = usePlayground();
+ const { adapters, state: playgroundState, dispatch: playgroundDispatch } = usePlayground();
+
+ // Persist chat metadata to storage
+ const persistChat = useCallback(
+ async (chatToSave: Chat) => {
+ try {
+ await adapters.persistence.saveChat(chatToSave);
+ } catch (error) {
+ console.error('Failed to persist chat metadata:', error);
+ }
+ },
+ [adapters.persistence]
+ );
// Reset state when chat changes (different chat selected)
useEffect(() => {
@@ -137,6 +149,23 @@ export function ChatProvider({ chat, children, isGenerating = false }: ChatProvi
}
}, [chat.computer, state.computer]);
+ // If chat doesn't have a computer, sync from the currently selected computer in playground state
+ useEffect(() => {
+ if (!state.computer && playgroundState.currentComputerId) {
+ const computerInfo = playgroundState.computers.find(
+ (c) => c.id === playgroundState.currentComputerId
+ );
+ if (computerInfo) {
+ const computer: Chat['computer'] = {
+ id: computerInfo.id,
+ name: computerInfo.name,
+ url: computerInfo.agentUrl,
+ };
+ dispatch({ type: 'SET_COMPUTER', payload: computer });
+ }
+ }
+ }, [state.computer, playgroundState.currentComputerId, playgroundState.computers]);
+
// Sync messages from global state when they change
useEffect(() => {
if (chat.id === state.id && chat.messages && chat.messages.length > state.messages.length) {
@@ -149,7 +178,7 @@ export function ChatProvider({ chat, children, isGenerating = false }: ChatProvi
const prevComputerRef = useRef(state.computer);
const prevNameRef = useRef(state.name);
- // Sync chat metadata back to global store only when values actually change
+ // Sync chat metadata back to global store and persist when values actually change
useEffect(() => {
const modelChanged = prevModelRef.current !== state.model;
const computerChanged = prevComputerRef.current !== state.computer;
@@ -160,6 +189,7 @@ export function ChatProvider({ chat, children, isGenerating = false }: ChatProvi
prevComputerRef.current = state.computer;
prevNameRef.current = state.name;
+ // Update global store
playgroundDispatch({
type: 'UPDATE_CHAT',
payload: {
@@ -172,8 +202,34 @@ export function ChatProvider({ chat, children, isGenerating = false }: ChatProvi
},
},
});
+
+ // Persist to storage (only for existing chats with valid IDs)
+ // New chats (with temp IDs) will be persisted when first message is sent
+ const isExistingChat =
+ state.id && !Number.isNaN(Number(state.id)) && Number.isInteger(Number(state.id));
+ if (isExistingChat) {
+ // Build the chat object from current state and global chat data
+ const globalChat = playgroundState.chats.find((c) => c.id === state.id);
+ if (globalChat) {
+ persistChat({
+ ...globalChat,
+ name: state.name,
+ model: state.model,
+ computer: state.computer,
+ updated: new Date(),
+ });
+ }
+ }
}
- }, [state.name, state.model, state.computer, state.id, playgroundDispatch]);
+ }, [
+ state.name,
+ state.model,
+ state.computer,
+ state.id,
+ playgroundDispatch,
+ playgroundState.chats,
+ persistChat,
+ ]);
return (
<ChatStateContext.Provider value={state}>
diff --git a/libs/typescript/playground/src/context/PlaygroundProvider.tsx b/libs/typescript/playground/src/context/PlaygroundProvider.tsx
index ab145eb16e..70c94844c0 100644
--- a/libs/typescript/playground/src/context/PlaygroundProvider.tsx
+++ b/libs/typescript/playground/src/context/PlaygroundProvider.tsx
@@ -177,9 +177,11 @@ export function PlaygroundProvider({ adapters, children, initialChats }: Playgro
dispatch({ type: 'SET_COMPUTERS', payload: computers });
dispatch({ type: 'SET_MODELS', payload: models });
- // Set defaults
+ // Set defaults - prefer first running computer, then fall back to first available
if (computers.length > 0) {
- dispatch({ type: 'SET_CURRENT_COMPUTER', payload: computers[0].id });
+ const runningComputer = computers.find((c) => c.status === 'running');
+ const defaultComputer = runningComputer ?? computers[0];
+ dispatch({ type: 'SET_CURRENT_COMPUTER', payload: defaultComputer.id });
}
if (models.length > 0 && models[0].models.length > 0) {
dispatch({ type: 'SET_SELECTED_MODEL', payload: models[0].models[0].id });
diff --git a/libs/typescript/playground/src/hooks/useAgentRequest.ts b/libs/typescript/playground/src/hooks/useAgentRequest.ts
index 588754f926..50f24e3dfc 100644
--- a/libs/typescript/playground/src/hooks/useAgentRequest.ts
+++ b/libs/typescript/playground/src/hooks/useAgentRequest.ts
@@ -1,7 +1,7 @@
// Hook for making agent requests
// Adapted from cloud/src/website/app/hooks/playground/useAgentRequest.ts
-import { useEffect, useRef, useCallback } from 'react';
+import { useRef, useCallback } from 'react';
import { usePlayground, useChat, useChatDispatch } from './usePlayground';
import { usePlaygroundTelemetry } from '../telemetry';
import type { AgentMessage, UserMessage } from '../types';
@@ -127,10 +127,9 @@ export function useAgentRequest() {
} | null>(null);
// Keep a ref to the latest chat state to avoid stale closure issues
+ // Update synchronously during render (not in useEffect) to ensure it's always current
const chatStateRef = useRef(chatState);
- useEffect(() => {
- chatStateRef.current = chatState;
- });
+ chatStateRef.current = chatState;
// Helper to set generating state globally
const setGlobalGenerating = useCallback(
@@ -184,7 +183,9 @@ export function useAgentRequest() {
const sendAgentRequest = useCallback(
async (messages: (UserMessage | AgentMessage)[], abortController: AbortController) => {
- const { model, computer } = chatState;
+ // Use ref to get the latest chat state to avoid stale closure issues
+ const latestChatState = chatStateRef.current;
+ const { model, computer } = latestChatState;
if (!model || !computer) {
return;
@@ -395,7 +396,7 @@ export function useAgentRequest() {
}
},
[
- chatState,
+ // Note: chatState is accessed via chatStateRef to avoid stale closures
state.computers,
state.currentComputerId,
adapters.inference,
@@ -416,11 +417,29 @@ export function useAgentRequest() {
if (!currentInput.trim()) return;
if (!model) {
- console.warn('Please select a model.');
+ console.warn('[useAgentRequest] No model selected. Chat state:', { chatId, model, computer });
+ chatDispatch({
+ type: 'SET_ERROR',
+ payload: {
+ message: 'Please select a model before sending a message.',
+ timestamp: new Date(),
+ },
+ });
return;
}
if (!computer) {
- console.warn('Please select a computer.');
+ console.warn('[useAgentRequest] No computer selected. Chat state:', {
+ chatId,
+ model,
+ computer,
+ });
+ chatDispatch({
+ type: 'SET_ERROR',
+ payload: {
+ message: 'Please select a sandbox before sending a message.',
+ timestamp: new Date(),
+ },
+ });
return;
}