Add end-to-end tests for workspace switching and backend tests for ask_question tool

- Implemented E2E tests for workspace switching functionality, covering scenarios such as switching workspaces, data isolation, language preference maintenance, and UI updates.
- Added tests to ensure workspace data is cleared on logout and handles unsaved changes during workspace switches.
- Created comprehensive backend tests for the ask_question tool, validating question creation, execution, answer handling, cancellation, and timeout scenarios.
- Included edge case tests to ensure robustness against duplicate questions and invalid answers.
This commit is contained in:
catlog22
2026-01-31 16:02:20 +08:00
parent 715ef12c92
commit 345437415f
33 changed files with 7049 additions and 105 deletions

View File

@@ -0,0 +1,325 @@
// ========================================
// AskQuestionDialog Component
// ========================================
// Dialog for handling ask_question MCP tool with all question types
import { useState, useCallback, useEffect } from 'react';
import { useIntl } from 'react-intl';
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/Button';
import { Input } from '@/components/ui/Input';
import { Textarea } from '@/components/ui/Textarea';
import { Checkbox } from '@/components/ui/checkbox';
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group';
import { Label } from '@/components/ui/label';
import { AlertCircle } from 'lucide-react';
import { cn } from '@/lib/utils';
import { useNotificationStore } from '@/stores';
import type { AskQuestionPayload, Question, QuestionType } from '@/types/store';
// ========== Types ==========
interface AskQuestionDialogProps {
/** Question payload from ask_question tool */
payload: AskQuestionPayload;
/** Callback when dialog is closed (cancelled or confirmed) */
onClose: () => void;
}
/** Answer value per question */
type AnswerValue = string | string[];
/** Answers record keyed by question ID */
interface Answers {
[questionId: string]: AnswerValue;
}
// ========== Component ==========
export function AskQuestionDialog({ payload, onClose }: AskQuestionDialogProps) {
const { formatMessage } = useIntl();
const sendA2UIAction = useNotificationStore((state) => state.sendA2UIAction);
// Initialize answers with default values
const [answers, setAnswers] = useState<Answers>(() => {
const initial: Answers = {};
for (const question of payload.questions) {
if (question.default !== undefined) {
initial[question.id] = question.default;
} else if (question.type === 'multi') {
initial[question.id] = [];
} else if (question.type === 'yes_no') {
initial[question.id] = 'yes';
} else {
initial[question.id] = '';
}
}
return initial;
});
// Validation error state
const [errors, setErrors] = useState<Record<string, string>>({});
const [hasValidationError, setHasValidationError] = useState(false);
// Clear validation error when answers change
useEffect(() => {
if (hasValidationError) {
setHasValidationError(false);
setErrors({});
}
}, [answers, hasValidationError]);
// ========== Question Renderers ==========
const renderQuestion = useCallback((question: Question) => {
const value = answers[question.id] || '';
const setValue = (newValue: AnswerValue) => {
setAnswers((prev) => ({ ...prev, [question.id]: newValue }));
};
const error = errors[question.id];
switch (question.type) {
case 'single':
return (
<div key={question.id} className="space-y-3">
<Label className={cn('text-sm font-medium', question.required && "after:content-['*'] after:ml-0.5 after:text-destructive")}>
{question.question}
</Label>
<RadioGroup
value={String(value)}
onValueChange={(v) => setValue(v)}
className="space-y-2"
>
{question.options?.map((option) => (
<div key={option} className="flex items-center space-x-2">
<RadioGroupItem value={option} id={`${question.id}-${option}`} />
<Label
htmlFor={`${question.id}-${option}`}
className="cursor-pointer text-sm font-normal"
>
{option}
</Label>
</div>
))}
</RadioGroup>
{error && (
<p className="text-xs text-destructive flex items-center gap-1">
<AlertCircle className="h-3 w-3" />
{error}
</p>
)}
</div>
);
case 'multi':
return (
<div key={question.id} className="space-y-3">
<Label className={cn('text-sm font-medium', question.required && "after:content-['*'] after:ml-0.5 after:text-destructive")}>
{question.question}
</Label>
<div className="space-y-2">
{question.options?.map((option) => {
const checked = Array.isArray(value) && value.includes(option);
return (
<div key={option} className="flex items-center space-x-2">
<Checkbox
id={`${question.id}-${option}`}
checked={checked}
onCheckedChange={(checked) => {
const currentArray = Array.isArray(value) ? value : [];
if (checked) {
setValue([...currentArray, option]);
} else {
setValue(currentArray.filter((v) => v !== option));
}
}}
/>
<Label
htmlFor={`${question.id}-${option}`}
className="cursor-pointer text-sm font-normal"
>
{option}
</Label>
</div>
);
})}
</div>
{error && (
<p className="text-xs text-destructive flex items-center gap-1">
<AlertCircle className="h-3 w-3" />
{error}
</p>
)}
</div>
);
case 'text':
return (
<div key={question.id} className="space-y-2">
<Label className={cn('text-sm font-medium', question.required && "after:content-['*'] after:ml-0.5 after:text-destructive")}>
{question.question}
</Label>
<Textarea
value={String(value)}
onChange={(e) => setValue(e.target.value)}
placeholder={formatMessage({ id: 'askQuestion.textPlaceholder' }) || 'Enter your answer...'}
rows={3}
className={cn(error && 'border-destructive')}
/>
{error && (
<p className="text-xs text-destructive flex items-center gap-1">
<AlertCircle className="h-3 w-3" />
{error}
</p>
)}
</div>
);
case 'yes_no':
return (
<div key={question.id} className="space-y-3">
<Label className={cn('text-sm font-medium', question.required && "after:content-['*'] after:ml-0.5 after:text-destructive")}>
{question.question}
</Label>
<RadioGroup
value={String(value)}
onValueChange={(v) => setValue(v)}
className="flex gap-4"
>
<div className="flex items-center space-x-2">
<RadioGroupItem value="yes" id={`${question.id}-yes`} />
<Label
htmlFor={`${question.id}-yes`}
className="cursor-pointer text-sm font-normal"
>
{formatMessage({ id: 'askQuestion.yes' }) || 'Yes'}
</Label>
</div>
<div className="flex items-center space-x-2">
<RadioGroupItem value="no" id={`${question.id}-no`} />
<Label
htmlFor={`${question.id}-no`}
className="cursor-pointer text-sm font-normal"
>
{formatMessage({ id: 'askQuestion.no' }) || 'No'}
</Label>
</div>
</RadioGroup>
{error && (
<p className="text-xs text-destructive flex items-center gap-1">
<AlertCircle className="h-3 w-3" />
{error}
</p>
)}
</div>
);
default:
return null;
}
}, [answers, errors, formatMessage]);
// ========== Handlers ==========
const validate = useCallback((): boolean => {
const newErrors: Record<string, string> = {};
let isValid = true;
for (const question of payload.questions) {
if (question.required) {
const answer = answers[question.id];
// Check if answer is empty
const isEmpty = (
answer === undefined ||
answer === null ||
answer === '' ||
(Array.isArray(answer) && answer.length === 0)
);
if (isEmpty) {
newErrors[question.id] = formatMessage({ id: 'askQuestion.required' }) || 'This question is required';
isValid = false;
}
}
}
setErrors(newErrors);
return isValid;
}, [answers, payload.questions, formatMessage]);
const handleConfirm = useCallback(() => {
if (!validate()) {
setHasValidationError(true);
return;
}
// Send answer via notificationStore
sendA2UIAction('submit-answer', payload.surfaceId, {
type: 'a2ui-answer',
cancelled: false,
answers,
});
onClose();
}, [validate, sendA2UIAction, payload.surfaceId, answers, onClose]);
const handleCancel = useCallback(() => {
// Send cancellation via notificationStore
sendA2UIAction('cancel-question', payload.surfaceId, {
type: 'a2ui-answer',
cancelled: true,
answers: {},
});
onClose();
}, [sendA2UIAction, payload.surfaceId, onClose]);
// ========== Render ==========
const title = payload.title || formatMessage({ id: 'askQuestion.defaultTitle' }) || 'Questions';
return (
<Dialog open onOpenChange={(open) => !open && handleCancel()}>
<DialogContent className="sm:max-w-[500px] max-h-[80vh] overflow-y-auto">
<DialogHeader>
<DialogTitle>{title}</DialogTitle>
<DialogDescription>
{formatMessage({ id: 'askQuestion.description' }) || 'Please answer the following questions'}
</DialogDescription>
</DialogHeader>
<div className="space-y-6 py-4">
{payload.questions.map(renderQuestion)}
</div>
<DialogFooter className="flex-col sm:flex-row gap-2">
<Button
variant="outline"
onClick={handleCancel}
className="w-full sm:w-auto"
>
{formatMessage({ id: 'common.actions.cancel' }) || 'Cancel'}
</Button>
<Button
variant="default"
onClick={handleConfirm}
className="w-full sm:w-auto"
>
{formatMessage({ id: 'common.actions.confirm' }) || 'Confirm'}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
export default AskQuestionDialog;

View File

@@ -0,0 +1,7 @@
// ========================================
// A2UI Components Barrel Export
// ========================================
// Export all A2UI-related components
export { AskQuestionDialog } from './AskQuestionDialog';
export { default as AskQuestionDialog } from './AskQuestionDialog';

View File

@@ -10,7 +10,8 @@ import { Sidebar } from './Sidebar';
import { MainContent } from './MainContent';
import { CliStreamMonitor } from '@/components/shared/CliStreamMonitor';
import { NotificationPanel } from '@/components/notification';
import { useNotificationStore } from '@/stores';
import { AskQuestionDialog } from '@/components/a2ui/AskQuestionDialog';
import { useNotificationStore, selectCurrentQuestion } from '@/stores';
import { useWebSocketNotifications } from '@/hooks';
export interface AppShellProps {
@@ -57,6 +58,10 @@ export function AppShell({
(state) => state.loadPersistentNotifications
);
// Current question dialog state
const currentQuestion = useNotificationStore(selectCurrentQuestion);
const setCurrentQuestion = useNotificationStore((state) => state.setCurrentQuestion);
// Initialize WebSocket notifications handler
useWebSocketNotifications();
@@ -106,6 +111,10 @@ export function AppShell({
useNotificationStore.getState().setPanelVisible(false);
}, []);
const handleQuestionDialogClose = useCallback(() => {
setCurrentQuestion(null);
}, [setCurrentQuestion]);
return (
<div className="flex flex-col min-h-screen bg-background">
{/* Header - fixed at top */}
@@ -150,6 +159,14 @@ export function AppShell({
isOpen={isNotificationPanelVisible}
onClose={handleNotificationPanelClose}
/>
{/* Ask Question Dialog - For ask_question MCP tool */}
{currentQuestion && (
<AskQuestionDialog
payload={currentQuestion}
onClose={handleQuestionDialogClose}
/>
)}
</div>
);
}

View File

@@ -16,6 +16,7 @@ import {
User,
LogOut,
Terminal,
Bell,
} from 'lucide-react';
import { cn } from '@/lib/utils';
import { Button } from '@/components/ui/Button';
@@ -24,6 +25,7 @@ import { useTheme } from '@/hooks';
import { LanguageSwitcher } from './LanguageSwitcher';
import { WorkspaceSelector } from '@/components/workspace/WorkspaceSelector';
import { useCliStreamStore, selectActiveExecutionCount } from '@/stores/cliStreamStore';
import { useNotificationStore } from '@/stores';
export interface HeaderProps {
/** Callback to toggle mobile sidebar */
@@ -49,6 +51,13 @@ export function Header({
const { isDark, toggleTheme } = useTheme();
const activeCliCount = useCliStreamStore(selectActiveExecutionCount);
// Notification state for badge
const persistentNotifications = useNotificationStore((state) => state.persistentNotifications);
const togglePanel = useNotificationStore((state) => state.togglePanel);
// Calculate unread count
const unreadCount = persistentNotifications.filter((n) => !n.read).length;
const handleRefresh = useCallback(() => {
if (onRefresh && !isRefreshing) {
onRefresh();
@@ -105,6 +114,23 @@ export function Header({
{/* Workspace selector */}
{projectPath && <WorkspaceSelector />}
{/* Notification badge */}
<Button
variant="ghost"
size="icon"
onClick={togglePanel}
aria-label={formatMessage({ id: 'common.aria.notifications' }) || 'Notifications'}
title={formatMessage({ id: 'common.aria.notifications' }) || 'Notifications'}
className="relative"
>
<Bell className="w-5 h-5" />
{unreadCount > 0 && (
<span className="absolute -top-1 -right-1 h-4 w-4 rounded-full bg-destructive text-[10px] text-destructive-foreground flex items-center justify-center font-medium">
{unreadCount > 9 ? '9+' : unreadCount}
</span>
)}
</Button>
{/* Refresh button */}
{onRefresh && (
<Button

View File

@@ -20,6 +20,7 @@ import {
import { cn } from '@/lib/utils';
import { Button } from '@/components/ui/Button';
import { Badge } from '@/components/ui/Badge';
import { A2UIRenderer } from '@/packages/a2ui-runtime/renderer/A2UIRenderer';
import { useNotificationStore, selectPersistentNotifications } from '@/stores';
import type { Toast } from '@/types/store';
@@ -161,6 +162,9 @@ function NotificationItem({ notification, onDelete }: NotificationItemProps) {
const hasDetails = notification.message && notification.message.length > 100;
const { formatMessage } = useIntl();
// Check if this is an A2UI notification
const isA2UI = notification.type === 'a2ui' && notification.a2uiSurface;
return (
<div
className={cn(
@@ -194,44 +198,54 @@ function NotificationItem({ notification, onDelete }: NotificationItemProps) {
</div>
</div>
{notification.message && (
<p className="text-xs text-muted-foreground mt-1 line-clamp-2">
{isExpanded || !hasDetails
? notification.message
: notification.message.slice(0, 100) + '...'}
</p>
)}
{/* Expand toggle */}
{hasDetails && (
<button
onClick={() => setIsExpanded(!isExpanded)}
className="flex items-center gap-1 mt-1 text-xs text-muted-foreground hover:text-foreground transition-colors"
>
{isExpanded ? (
<>
<ChevronUp className="h-3 w-3" />
{formatMessage({ id: 'notificationPanel.showLess' }) || 'Show less'}
</>
) : (
<>
<ChevronDown className="h-3 w-3" />
{formatMessage({ id: 'notificationPanel.showMore' }) || 'Show more'}
</>
{/* A2UI Surface Content */}
{isA2UI && notification.a2uiSurface ? (
<div className="mt-2">
<A2UIRenderer surface={notification.a2uiSurface} />
</div>
) : (
<>
{/* Regular message content */}
{notification.message && (
<p className="text-xs text-muted-foreground mt-1 line-clamp-2">
{isExpanded || !hasDetails
? notification.message
: notification.message.slice(0, 100) + '...'}
</p>
)}
</button>
)}
{/* Action button */}
{notification.action && (
<Button
variant="outline"
size="sm"
onClick={notification.action.onClick}
className="mt-2 h-7 text-xs"
>
{notification.action.label}
</Button>
{/* Expand toggle */}
{hasDetails && (
<button
onClick={() => setIsExpanded(!isExpanded)}
className="flex items-center gap-1 mt-1 text-xs text-muted-foreground hover:text-foreground transition-colors"
>
{isExpanded ? (
<>
<ChevronUp className="h-3 w-3" />
{formatMessage({ id: 'notificationPanel.showLess' }) || 'Show less'}
</>
) : (
<>
<ChevronDown className="h-3 w-3" />
{formatMessage({ id: 'notificationPanel.showMore' }) || 'Show more'}
</>
)}
</button>
)}
{/* Action button */}
{notification.action && (
<Button
variant="outline"
size="sm"
onClick={notification.action.onClick}
className="mt-2 h-7 text-xs"
>
{notification.action.label}
</Button>
)}
</>
)}
</div>
</div>
@@ -316,9 +330,21 @@ export function NotificationPanel({ isOpen, onClose }: NotificationPanelProps) {
// Delete handler
const handleDelete = useCallback(
(id: string) => {
// Find the notification being deleted
const notification = persistentNotifications.find((n) => n.id === id);
// If it's an A2UI notification, also remove from a2uiSurfaces Map
if (notification?.type === 'a2ui' && notification.a2uiSurface) {
const store = useNotificationStore.getState();
const newSurfaces = new Map(store.a2uiSurfaces);
newSurfaces.delete(notification.a2uiSurface.surfaceId);
// Update the store's a2uiSurfaces directly
useNotificationStore.setState({ a2uiSurfaces: newSurfaces });
}
removePersistentNotification(id);
},
[removePersistentNotification]
[removePersistentNotification, persistentNotifications]
);
// Mark all read handler

View File

@@ -0,0 +1,41 @@
import * as React from "react";
import * as RadioGroupPrimitive from "@radix-ui/react-radio-group";
import { Circle } from "lucide-react";
import { cn } from "@/lib/utils";
const RadioGroup = React.forwardRef<
React.ElementRef<typeof RadioGroupPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof RadioGroupPrimitive.Root>
>(({ className, ...props }, ref) => {
return (
<RadioGroupPrimitive.Root
className={cn("grid gap-2", className)}
{...props}
ref={ref}
/>
);
});
RadioGroup.displayName = RadioGroupPrimitive.Root.displayName;
const RadioGroupItem = React.forwardRef<
React.ElementRef<typeof RadioGroupPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof RadioGroupPrimitive.Item>
>(({ className, ...props }, ref) => {
return (
<RadioGroupPrimitive.Item
ref={ref}
className={cn(
"aspect-square h-4 w-4 rounded-full border border-primary text-primary ring-offset-background focus:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",
className
)}
{...props}
>
<RadioGroupPrimitive.Indicator className="flex items-center justify-center">
<Circle className="h-2.5 w-2.5 fill-current text-current" />
</RadioGroupPrimitive.Indicator>
</RadioGroupPrimitive.Item>
);
});
RadioGroupItem.displayName = RadioGroupPrimitive.Item.displayName;
export { RadioGroup, RadioGroupItem };