feat: enhance dialog and drawer components with new styles and functionality

- Updated Dialog component to support fullscreen mode and added a back button.
- Introduced Drawer component for side navigation with customizable size and position.
- Added DialogStyleContext for managing dialog style preferences including smart mode and drawer settings.
- Implemented pending question service for managing persistent storage of pending questions.
- Enhanced WebSocket handling to request pending questions upon frontend readiness.
- Created dashboard launcher utility to manage the Dashboard server lifecycle.
This commit is contained in:
catlog22
2026-02-16 10:58:40 +08:00
parent 4f085242b5
commit 2e018520c3
8 changed files with 1100 additions and 46 deletions

View File

@@ -7,7 +7,8 @@ import type { Duplex } from 'stream';
import http from 'http';
import type { IncomingMessage } from 'http';
import { createWebSocketFrame, parseWebSocketFrame, wsClients } from '../websocket.js';
import type { QuestionAnswer, AskQuestionParams, Question } from './A2UITypes.js';
import type { QuestionAnswer, AskQuestionParams, Question, PendingQuestion } from './A2UITypes.js';
import { getAllPendingQuestions } from '../services/pending-question-service.js';
const DASHBOARD_PORT = Number(process.env.CCW_PORT || 3456);
@@ -604,6 +605,215 @@ export class A2UIWebSocketHandler {
// ========== WebSocket Integration ==========
/**
* Generate A2UI surface for a pending question
* This is used to resend pending questions when frontend reconnects
*/
function generatePendingQuestionSurface(pq: PendingQuestion): {
surfaceId: string;
components: unknown[];
initialState: Record<string, unknown>;
displayMode?: 'popup' | 'panel';
} | null {
const question = pq.question;
const components: unknown[] = [];
// Add title
components.push({
id: 'title',
component: {
Text: {
text: { literalString: question.title },
usageHint: 'h3',
},
},
});
// Add message if provided
if (question.message) {
components.push({
id: 'message',
component: {
Text: {
text: { literalString: question.message },
usageHint: 'p',
},
},
});
}
// Add description if provided
if (question.description) {
components.push({
id: 'description',
component: {
Text: {
text: { literalString: question.description },
usageHint: 'small',
},
},
});
}
// Add interactive components based on question type
switch (question.type) {
case 'confirm':
components.push({
id: 'confirm-btn',
component: {
Button: {
onClick: { actionId: 'confirm', parameters: { questionId: question.id } },
content: { Text: { text: { literalString: 'Confirm' } } },
variant: 'primary',
},
},
});
components.push({
id: 'cancel-btn',
component: {
Button: {
onClick: { actionId: 'cancel', parameters: { questionId: question.id } },
content: { Text: { text: { literalString: 'Cancel' } } },
variant: 'secondary',
},
},
});
break;
case 'select':
if (question.options && question.options.length > 0) {
const options = question.options.map((opt) => ({
label: { literalString: opt.label },
value: opt.value,
description: opt.description ? { literalString: opt.description } : undefined,
isDefault: question.defaultValue !== undefined && opt.value === String(question.defaultValue),
}));
options.push({
label: { literalString: 'Other' },
value: '__other__',
description: { literalString: 'Provide a custom answer' },
isDefault: false,
});
components.push({
id: 'radio-group',
component: {
RadioGroup: {
options,
selectedValue: question.defaultValue ? { literalString: String(question.defaultValue) } : undefined,
onChange: { actionId: 'select', parameters: { questionId: question.id } },
},
},
});
components.push({
id: 'submit-btn',
component: {
Button: {
onClick: { actionId: 'submit', parameters: { questionId: question.id } },
content: { Text: { text: { literalString: 'Submit' } } },
variant: 'primary',
},
},
});
components.push({
id: 'cancel-btn',
component: {
Button: {
onClick: { actionId: 'cancel', parameters: { questionId: question.id } },
content: { Text: { text: { literalString: 'Cancel' } } },
variant: 'secondary',
},
},
});
}
break;
case 'multi-select':
if (question.options && question.options.length > 0) {
question.options.forEach((opt, idx) => {
components.push({
id: `checkbox-${idx}`,
component: {
Checkbox: {
label: { literalString: opt.label },
...(opt.description && { description: { literalString: opt.description } }),
onChange: { actionId: 'toggle', parameters: { questionId: question.id, value: opt.value } },
checked: { literalBoolean: false },
},
},
});
});
components.push({
id: 'checkbox-other',
component: {
Checkbox: {
label: { literalString: 'Other' },
description: { literalString: 'Provide a custom answer' },
onChange: { actionId: 'toggle', parameters: { questionId: question.id, value: '__other__' } },
checked: { literalBoolean: false },
},
},
});
components.push({
id: 'submit-btn',
component: {
Button: {
onClick: { actionId: 'submit', parameters: { questionId: question.id } },
content: { Text: { text: { literalString: 'Submit' } } },
variant: 'primary',
},
},
});
components.push({
id: 'cancel-btn',
component: {
Button: {
onClick: { actionId: 'cancel', parameters: { questionId: question.id } },
content: { Text: { text: { literalString: 'Cancel' } } },
variant: 'secondary',
},
},
});
}
break;
case 'input':
components.push({
id: 'input',
component: {
TextField: {
value: question.defaultValue ? { literalString: String(question.defaultValue) } : undefined,
onChange: { actionId: 'answer', parameters: { questionId: question.id } },
placeholder: question.placeholder || 'Enter your answer',
type: 'text',
},
},
});
break;
default:
return null;
}
return {
surfaceId: pq.surfaceId,
components,
initialState: {
questionId: question.id,
questionType: question.type,
options: question.options,
required: question.required,
timeoutAt: new Date(pq.timestamp + pq.timeout).toISOString(),
...(question.defaultValue !== undefined && { defaultValue: question.defaultValue }),
},
displayMode: 'popup',
};
}
/**
* Handle A2UI messages in WebSocket data handler
* Called from main WebSocket handler
@@ -620,6 +830,23 @@ export function handleA2UIMessage(
try {
const data = JSON.parse(payload);
// Handle FRONTEND_READY - frontend requesting pending questions
if (data.type === 'FRONTEND_READY' && data.payload?.action === 'requestPendingQuestions') {
console.log('[A2UI] Frontend ready, sending pending questions...');
const pendingQuestions = getAllPendingQuestions();
for (const pq of pendingQuestions) {
// Regenerate surface for each pending question
const surfaceUpdate = generatePendingQuestionSurface(pq);
if (surfaceUpdate) {
a2uiHandler.sendSurface(surfaceUpdate);
}
}
console.log(`[A2UI] Sent ${pendingQuestions.length} pending questions to frontend`);
return true;
}
// Handle A2UI action messages
if (data.type === 'a2ui-action') {
const action = data as A2UIActionMessage;

View File

@@ -0,0 +1,244 @@
// ========================================
// Pending Question Service
// ========================================
// Manages persistent storage of pending questions for ask_question tool
import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'fs';
import { join } from 'path';
import { homedir } from 'os';
import type { PendingQuestion } from '../a2ui/A2UITypes.js';
// Storage configuration
const STORAGE_DIR = join(homedir(), '.ccw', 'pending-questions');
const STORAGE_FILE = join(STORAGE_DIR, 'questions.json');
// In-memory cache of pending questions
const pendingQuestions = new Map<string, PendingQuestion>();
// Flag to track if service has been initialized
let initialized = false;
/**
* Serializable representation of a pending question (without resolve/reject functions)
*/
interface SerializedPendingQuestion {
id: string;
surfaceId: string;
question: {
id: string;
type: string;
title: string;
message?: string;
description?: string;
options?: Array<{ value: string; label: string; description?: string }>;
defaultValue?: string | string[] | boolean;
required?: boolean;
placeholder?: string;
timeout?: number;
};
timestamp: number;
timeout: number;
}
/**
* Initialize the service by loading pending questions from disk.
* Called automatically on module load.
*/
function initialize(): void {
if (initialized) return;
try {
// Ensure storage directory exists
if (!existsSync(STORAGE_DIR)) {
mkdirSync(STORAGE_DIR, { recursive: true });
}
// Load existing questions from disk
if (existsSync(STORAGE_FILE)) {
const content = readFileSync(STORAGE_FILE, 'utf8');
const serialized: SerializedPendingQuestion[] = JSON.parse(content);
for (const sq of serialized) {
// Create a PendingQuestion with placeholder resolve/reject
// These will be replaced when the question is actually awaited
const pendingQ: PendingQuestion = {
id: sq.id,
surfaceId: sq.surfaceId,
question: sq.question as PendingQuestion['question'],
timestamp: sq.timestamp,
timeout: sq.timeout,
resolve: () => {
console.warn(`[PendingQuestionService] Resolve called for restored question ${sq.id} - no promise attached`);
},
reject: () => {
console.warn(`[PendingQuestionService] Reject called for restored question ${sq.id} - no promise attached`);
},
};
pendingQuestions.set(sq.id, pendingQ);
}
console.log(`[PendingQuestionService] Loaded ${pendingQuestions.size} pending questions from storage`);
}
initialized = true;
} catch (error) {
console.error('[PendingQuestionService] Failed to initialize:', error);
initialized = true; // Still mark as initialized to prevent retry loops
}
}
/**
* Persist current pending questions to disk.
*/
function persistQuestions(): void {
try {
// Ensure storage directory exists
if (!existsSync(STORAGE_DIR)) {
mkdirSync(STORAGE_DIR, { recursive: true });
}
const serialized: SerializedPendingQuestion[] = [];
for (const pq of pendingQuestions.values()) {
serialized.push({
id: pq.id,
surfaceId: pq.surfaceId,
question: {
id: pq.question.id,
type: pq.question.type,
title: pq.question.title,
message: pq.question.message,
description: pq.question.description,
options: pq.question.options,
defaultValue: pq.question.defaultValue,
required: pq.question.required,
placeholder: pq.question.placeholder,
timeout: pq.timeout,
},
timestamp: pq.timestamp,
timeout: pq.timeout,
});
}
writeFileSync(STORAGE_FILE, JSON.stringify(serialized, null, 2), 'utf8');
} catch (error) {
console.error('[PendingQuestionService] Failed to persist questions:', error);
}
}
/**
* Add a pending question to storage.
* @param pendingQ - The pending question to add
*/
export function addPendingQuestion(pendingQ: PendingQuestion): void {
initialize();
pendingQuestions.set(pendingQ.id, pendingQ);
persistQuestions();
console.log(`[PendingQuestionService] Added pending question: ${pendingQ.id}`);
}
/**
* Get a pending question by ID.
* @param questionId - The question ID
* @returns The pending question or undefined
*/
export function getPendingQuestion(questionId: string): PendingQuestion | undefined {
initialize();
return pendingQuestions.get(questionId);
}
/**
* Update an existing pending question (e.g., to attach new resolve/reject).
* @param questionId - The question ID
* @param pendingQ - The updated pending question
*/
export function updatePendingQuestion(questionId: string, pendingQ: PendingQuestion): boolean {
initialize();
if (pendingQuestions.has(questionId)) {
pendingQuestions.set(questionId, pendingQ);
// Don't persist here - resolve/reject functions aren't serializable
return true;
}
return false;
}
/**
* Remove a pending question from storage.
* @param questionId - The question ID to remove
* @returns True if the question was found and removed
*/
export function removePendingQuestion(questionId: string): boolean {
initialize();
const existed = pendingQuestions.delete(questionId);
if (existed) {
persistQuestions();
console.log(`[PendingQuestionService] Removed pending question: ${questionId}`);
}
return existed;
}
/**
* Get all pending questions.
* @returns Array of all pending questions
*/
export function getAllPendingQuestions(): PendingQuestion[] {
initialize();
return Array.from(pendingQuestions.values());
}
/**
* Check if a pending question exists.
* @param questionId - The question ID to check
* @returns True if the question exists
*/
export function hasPendingQuestion(questionId: string): boolean {
initialize();
return pendingQuestions.has(questionId);
}
/**
* Get the count of pending questions.
* @returns Number of pending questions
*/
export function getPendingQuestionCount(): number {
initialize();
return pendingQuestions.size;
}
/**
* Clear all pending questions from storage.
*/
export function clearAllPendingQuestions(): void {
initialize();
pendingQuestions.clear();
persistQuestions();
console.log(`[PendingQuestionService] Cleared all pending questions`);
}
/**
* Clean up expired questions (older than their timeout).
* This can be called periodically to prevent stale data accumulation.
* @returns Number of questions removed
*/
export function cleanupExpiredQuestions(): number {
initialize();
const now = Date.now();
let removed = 0;
for (const [id, pq] of pendingQuestions) {
if (now - pq.timestamp > pq.timeout) {
pendingQuestions.delete(id);
removed++;
}
}
if (removed > 0) {
persistQuestions();
console.log(`[PendingQuestionService] Cleaned up ${removed} expired questions`);
}
return removed;
}
// Initialize on module load
initialize();