Change PIN to 1451
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
13
apps/captain-mobile-v2/flutter/lib/config/api_config.dart
Normal file
13
apps/captain-mobile-v2/flutter/lib/config/api_config.dart
Normal file
@@ -0,0 +1,13 @@
|
||||
class ApiConfig {
|
||||
// Captain Mobile v2 API
|
||||
static const String baseUrl = 'http://69.62.126.110:3030';
|
||||
static const String wsUrl = 'ws://69.62.126.110:3030';
|
||||
|
||||
// For local development
|
||||
// static const String baseUrl = 'http://localhost:3030';
|
||||
// static const String wsUrl = 'ws://localhost:3030';
|
||||
|
||||
static const Duration connectionTimeout = Duration(seconds: 30);
|
||||
static const Duration reconnectDelay = Duration(seconds: 3);
|
||||
static const int maxReconnectAttempts = 5;
|
||||
}
|
||||
78
apps/captain-mobile-v2/flutter/lib/main.dart
Normal file
78
apps/captain-mobile-v2/flutter/lib/main.dart
Normal file
@@ -0,0 +1,78 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import 'providers/auth_provider.dart';
|
||||
import 'providers/chat_provider.dart';
|
||||
import 'screens/login_screen.dart';
|
||||
import 'screens/chat_screen.dart';
|
||||
|
||||
void main() {
|
||||
WidgetsFlutterBinding.ensureInitialized();
|
||||
SystemChrome.setSystemUIOverlayStyle(
|
||||
const SystemUiOverlayStyle(
|
||||
statusBarColor: Colors.transparent,
|
||||
statusBarIconBrightness: Brightness.light,
|
||||
),
|
||||
);
|
||||
runApp(const CaptainClaudeApp());
|
||||
}
|
||||
|
||||
class CaptainClaudeApp extends StatelessWidget {
|
||||
const CaptainClaudeApp({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return MultiProvider(
|
||||
providers: [
|
||||
ChangeNotifierProvider(create: (_) => AuthProvider()..init()),
|
||||
ChangeNotifierProvider(create: (_) => ChatProvider()),
|
||||
],
|
||||
child: MaterialApp(
|
||||
title: 'Captain Claude',
|
||||
debugShowCheckedModeBanner: false,
|
||||
theme: ThemeData(
|
||||
brightness: Brightness.dark,
|
||||
primaryColor: Colors.orange.shade700,
|
||||
scaffoldBackgroundColor: const Color(0xFF1A1A1A),
|
||||
colorScheme: ColorScheme.dark(
|
||||
primary: Colors.orange.shade700,
|
||||
secondary: Colors.orange.shade400,
|
||||
surface: const Color(0xFF2D2D2D),
|
||||
),
|
||||
appBarTheme: const AppBarTheme(
|
||||
backgroundColor: Color(0xFF2D2D2D),
|
||||
elevation: 0,
|
||||
),
|
||||
fontFamily: 'Roboto',
|
||||
),
|
||||
home: const AuthWrapper(),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class AuthWrapper extends StatelessWidget {
|
||||
const AuthWrapper({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Consumer<AuthProvider>(
|
||||
builder: (context, auth, _) {
|
||||
if (auth.isLoading) {
|
||||
return const Scaffold(
|
||||
backgroundColor: Color(0xFF1A1A1A),
|
||||
body: Center(
|
||||
child: CircularProgressIndicator(color: Colors.orange),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
if (auth.isAuthenticated) {
|
||||
return const ChatScreen();
|
||||
}
|
||||
|
||||
return const LoginScreen();
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
38
apps/captain-mobile-v2/flutter/lib/models/conversation.dart
Normal file
38
apps/captain-mobile-v2/flutter/lib/models/conversation.dart
Normal file
@@ -0,0 +1,38 @@
|
||||
class Conversation {
|
||||
final String id;
|
||||
final String? title;
|
||||
final DateTime createdAt;
|
||||
final DateTime updatedAt;
|
||||
final int messageCount;
|
||||
|
||||
Conversation({
|
||||
required this.id,
|
||||
this.title,
|
||||
required this.createdAt,
|
||||
required this.updatedAt,
|
||||
this.messageCount = 0,
|
||||
});
|
||||
|
||||
factory Conversation.fromJson(Map<String, dynamic> json) {
|
||||
return Conversation(
|
||||
id: json['id'],
|
||||
title: json['title'],
|
||||
createdAt: DateTime.parse(json['created_at']),
|
||||
updatedAt: DateTime.parse(json['updated_at']),
|
||||
messageCount: json['message_count'] ?? 0,
|
||||
);
|
||||
}
|
||||
|
||||
String get displayTitle => title ?? 'New Conversation';
|
||||
|
||||
String get timeAgo {
|
||||
final now = DateTime.now();
|
||||
final diff = now.difference(updatedAt);
|
||||
|
||||
if (diff.inMinutes < 1) return 'Just now';
|
||||
if (diff.inMinutes < 60) return '${diff.inMinutes}m ago';
|
||||
if (diff.inHours < 24) return '${diff.inHours}h ago';
|
||||
if (diff.inDays < 7) return '${diff.inDays}d ago';
|
||||
return '${updatedAt.day}/${updatedAt.month}/${updatedAt.year}';
|
||||
}
|
||||
}
|
||||
85
apps/captain-mobile-v2/flutter/lib/models/message.dart
Normal file
85
apps/captain-mobile-v2/flutter/lib/models/message.dart
Normal file
@@ -0,0 +1,85 @@
|
||||
class ToolUse {
|
||||
final String tool;
|
||||
final dynamic input;
|
||||
final String? output;
|
||||
|
||||
ToolUse({
|
||||
required this.tool,
|
||||
this.input,
|
||||
this.output,
|
||||
});
|
||||
|
||||
factory ToolUse.fromJson(Map<String, dynamic> json) {
|
||||
return ToolUse(
|
||||
tool: json['tool'] ?? 'unknown',
|
||||
input: json['input'],
|
||||
output: json['output'],
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
'tool': tool,
|
||||
'input': input,
|
||||
'output': output,
|
||||
};
|
||||
}
|
||||
|
||||
class Message {
|
||||
final String id;
|
||||
final String role;
|
||||
final String content;
|
||||
final List<ToolUse>? toolUses;
|
||||
final bool isStreaming;
|
||||
final bool isThinking;
|
||||
final DateTime createdAt;
|
||||
|
||||
Message({
|
||||
String? id,
|
||||
required this.role,
|
||||
required this.content,
|
||||
this.toolUses,
|
||||
this.isStreaming = false,
|
||||
this.isThinking = false,
|
||||
DateTime? createdAt,
|
||||
}) : id = id ?? DateTime.now().millisecondsSinceEpoch.toString(),
|
||||
createdAt = createdAt ?? DateTime.now();
|
||||
|
||||
Message copyWith({
|
||||
String? id,
|
||||
String? role,
|
||||
String? content,
|
||||
List<ToolUse>? toolUses,
|
||||
bool? isStreaming,
|
||||
bool? isThinking,
|
||||
DateTime? createdAt,
|
||||
}) {
|
||||
return Message(
|
||||
id: id ?? this.id,
|
||||
role: role ?? this.role,
|
||||
content: content ?? this.content,
|
||||
toolUses: toolUses ?? this.toolUses,
|
||||
isStreaming: isStreaming ?? this.isStreaming,
|
||||
isThinking: isThinking ?? this.isThinking,
|
||||
createdAt: createdAt ?? this.createdAt,
|
||||
);
|
||||
}
|
||||
|
||||
factory Message.fromJson(Map<String, dynamic> json) {
|
||||
return Message(
|
||||
id: json['id'],
|
||||
role: json['role'],
|
||||
content: json['content'],
|
||||
toolUses: json['tool_uses'] != null
|
||||
? (json['tool_uses'] as List)
|
||||
.map((e) => ToolUse.fromJson(e))
|
||||
.toList()
|
||||
: null,
|
||||
createdAt: json['created_at'] != null
|
||||
? DateTime.parse(json['created_at'])
|
||||
: DateTime.now(),
|
||||
);
|
||||
}
|
||||
|
||||
bool get isUser => role == 'user';
|
||||
bool get isAssistant => role == 'assistant';
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
import '../services/auth_service.dart';
|
||||
|
||||
class AuthProvider with ChangeNotifier {
|
||||
final AuthService _authService = AuthService();
|
||||
|
||||
bool _isLoading = false;
|
||||
String? _error;
|
||||
|
||||
bool get isLoading => _isLoading;
|
||||
bool get isAuthenticated => _authService.isAuthenticated;
|
||||
String? get token => _authService.token;
|
||||
String? get username => _authService.username;
|
||||
String? get error => _error;
|
||||
|
||||
Future<void> init() async {
|
||||
_isLoading = true;
|
||||
notifyListeners();
|
||||
|
||||
await _authService.loadStoredAuth();
|
||||
|
||||
_isLoading = false;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
Future<bool> login(String username, String password) async {
|
||||
_isLoading = true;
|
||||
_error = null;
|
||||
notifyListeners();
|
||||
|
||||
final success = await _authService.login(username, password);
|
||||
|
||||
if (!success) {
|
||||
_error = _authService.lastError ?? 'Login failed';
|
||||
}
|
||||
|
||||
_isLoading = false;
|
||||
notifyListeners();
|
||||
|
||||
return success;
|
||||
}
|
||||
|
||||
Future<void> logout() async {
|
||||
await _authService.logout();
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void clearError() {
|
||||
_error = null;
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
295
apps/captain-mobile-v2/flutter/lib/providers/chat_provider.dart
Normal file
295
apps/captain-mobile-v2/flutter/lib/providers/chat_provider.dart
Normal file
@@ -0,0 +1,295 @@
|
||||
import 'dart:async';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import '../models/message.dart';
|
||||
import '../services/chat_service.dart';
|
||||
import '../providers/auth_provider.dart';
|
||||
|
||||
/// Chat provider for v3 API (dynamic Claude sessions)
|
||||
class ChatProvider with ChangeNotifier {
|
||||
final ChatService _chatService = ChatService();
|
||||
final List<Message> _messages = [];
|
||||
static const int _maxMessages = 500;
|
||||
|
||||
AuthProvider? _authProvider;
|
||||
StreamSubscription? _messageSubscription;
|
||||
StreamSubscription? _stateSubscription;
|
||||
StreamSubscription? _errorSubscription;
|
||||
|
||||
List<ChatSession> _sessions = [];
|
||||
ChatSession? _currentSession;
|
||||
bool _isProcessing = false;
|
||||
String? _error;
|
||||
|
||||
List<Message> get messages => List.unmodifiable(_messages);
|
||||
List<ChatSession> get sessions => List.unmodifiable(_sessions);
|
||||
ChatSession? get currentSession => _currentSession;
|
||||
bool get isProcessing => _isProcessing;
|
||||
bool get isConnected => _chatService.currentState == ChatConnectionState.connected;
|
||||
bool get isSessionConnected => _currentSession != null;
|
||||
ChatConnectionState get connectionState => _chatService.currentState;
|
||||
String? get error => _error;
|
||||
|
||||
void updateAuth(AuthProvider auth) {
|
||||
_authProvider = auth;
|
||||
_chatService.setToken(auth.token);
|
||||
|
||||
if (auth.isAuthenticated && !isConnected) {
|
||||
connect();
|
||||
} else if (!auth.isAuthenticated && isConnected) {
|
||||
disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> connect() async {
|
||||
if (_authProvider?.token == null) return;
|
||||
|
||||
_chatService.setToken(_authProvider!.token);
|
||||
|
||||
_stateSubscription?.cancel();
|
||||
_stateSubscription = _chatService.connectionState.listen((state) {
|
||||
notifyListeners();
|
||||
});
|
||||
|
||||
_errorSubscription?.cancel();
|
||||
_errorSubscription = _chatService.errors.listen((error) {
|
||||
_error = error;
|
||||
notifyListeners();
|
||||
});
|
||||
|
||||
_messageSubscription?.cancel();
|
||||
_messageSubscription = _chatService.messages.listen(_handleMessage);
|
||||
|
||||
await _chatService.connect();
|
||||
}
|
||||
|
||||
void _handleMessage(Map<String, dynamic> data) {
|
||||
final type = data['type'];
|
||||
debugPrint('ChatProvider: type=$type');
|
||||
|
||||
switch (type) {
|
||||
// Initial state with sessions
|
||||
case 'init':
|
||||
final sessionsList = data['sessions'] as List<dynamic>?;
|
||||
if (sessionsList != null) {
|
||||
_sessions = sessionsList
|
||||
.map((s) => ChatSession.fromJson(s))
|
||||
.toList();
|
||||
}
|
||||
notifyListeners();
|
||||
break;
|
||||
|
||||
// Sessions list update
|
||||
case 'sessions_list':
|
||||
final sessionsList = data['sessions'] as List<dynamic>?;
|
||||
if (sessionsList != null) {
|
||||
_sessions = sessionsList
|
||||
.map((s) => ChatSession.fromJson(s))
|
||||
.toList();
|
||||
}
|
||||
notifyListeners();
|
||||
break;
|
||||
|
||||
// Session created (v3)
|
||||
case 'session_created':
|
||||
final sessionId = data['session_id'] as String?;
|
||||
final name = data['name'] as String?;
|
||||
if (sessionId != null) {
|
||||
final newSession = ChatSession(
|
||||
sessionId: sessionId,
|
||||
name: name ?? 'New Session',
|
||||
);
|
||||
_sessions.add(newSession);
|
||||
_messages.add(Message(
|
||||
role: 'system',
|
||||
content: 'Sesión creada: ${newSession.name}',
|
||||
));
|
||||
// Auto-connect to new session
|
||||
connectToSession(sessionId);
|
||||
}
|
||||
notifyListeners();
|
||||
break;
|
||||
|
||||
// Connected to session (v3)
|
||||
case 'session_connected':
|
||||
final sessionId = data['session_id'] as String?;
|
||||
final name = data['name'] as String?;
|
||||
if (sessionId != null) {
|
||||
_currentSession = _sessions.firstWhere(
|
||||
(s) => s.sessionId == sessionId,
|
||||
orElse: () => ChatSession(
|
||||
sessionId: sessionId,
|
||||
name: name ?? 'Session',
|
||||
),
|
||||
);
|
||||
_messages.clear();
|
||||
_messages.add(Message(
|
||||
role: 'system',
|
||||
content: 'Conectado a: ${_currentSession!.name}',
|
||||
));
|
||||
}
|
||||
notifyListeners();
|
||||
break;
|
||||
|
||||
// Output from Claude (v3)
|
||||
case 'output':
|
||||
final content = data['content'] as String? ?? '';
|
||||
if (content.isEmpty) break;
|
||||
|
||||
debugPrint('ChatProvider: OUTPUT "${content.substring(0, content.length > 50 ? 50 : content.length)}"');
|
||||
_isProcessing = true;
|
||||
|
||||
// Check if it's a progress indicator
|
||||
if (content.startsWith('procesando')) {
|
||||
// Update or create progress message
|
||||
if (_messages.isNotEmpty && _messages.last.role == 'assistant' && _messages.last.isStreaming == true) {
|
||||
final lastIndex = _messages.length - 1;
|
||||
_messages[lastIndex] = Message(
|
||||
role: 'assistant',
|
||||
content: content,
|
||||
isStreaming: true,
|
||||
);
|
||||
} else {
|
||||
_messages.add(Message(
|
||||
role: 'assistant',
|
||||
content: content,
|
||||
isStreaming: true,
|
||||
));
|
||||
}
|
||||
} else {
|
||||
// Real content - replace progress or add new
|
||||
if (_messages.isNotEmpty && _messages.last.role == 'assistant' && _messages.last.isStreaming == true) {
|
||||
final lastIndex = _messages.length - 1;
|
||||
final lastContent = _messages[lastIndex].content;
|
||||
// If last message was progress, replace it. Otherwise append.
|
||||
if (lastContent.startsWith('procesando')) {
|
||||
_messages[lastIndex] = Message(
|
||||
role: 'assistant',
|
||||
content: content,
|
||||
isStreaming: true,
|
||||
);
|
||||
} else {
|
||||
// Append to existing response
|
||||
_messages[lastIndex] = Message(
|
||||
role: 'assistant',
|
||||
content: lastContent + content,
|
||||
isStreaming: true,
|
||||
);
|
||||
}
|
||||
} else {
|
||||
_messages.add(Message(
|
||||
role: 'assistant',
|
||||
content: content,
|
||||
isStreaming: true,
|
||||
));
|
||||
}
|
||||
}
|
||||
_trimMessages();
|
||||
notifyListeners();
|
||||
break;
|
||||
|
||||
// Response complete (v3)
|
||||
case 'done':
|
||||
_isProcessing = false;
|
||||
// Mark last assistant message as complete
|
||||
if (_messages.isNotEmpty && _messages.last.role == 'assistant') {
|
||||
final lastIndex = _messages.length - 1;
|
||||
_messages[lastIndex] = Message(
|
||||
role: 'assistant',
|
||||
content: _messages[lastIndex].content,
|
||||
isStreaming: false,
|
||||
);
|
||||
}
|
||||
notifyListeners();
|
||||
break;
|
||||
|
||||
case 'error':
|
||||
_isProcessing = false;
|
||||
final errorMsg = data['message'] ?? data['content'] ?? 'Error';
|
||||
if (errorMsg.toString().isNotEmpty) {
|
||||
_error = errorMsg;
|
||||
_messages.add(Message(
|
||||
role: 'system',
|
||||
content: 'Error: $errorMsg',
|
||||
));
|
||||
}
|
||||
notifyListeners();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void _trimMessages() {
|
||||
while (_messages.length > _maxMessages) {
|
||||
_messages.removeAt(0);
|
||||
}
|
||||
}
|
||||
|
||||
/// Create and connect to a new session
|
||||
void createSession(String name) {
|
||||
_chatService.createSession(name);
|
||||
}
|
||||
|
||||
/// Connect to an existing session
|
||||
void connectToSession(String sessionId) {
|
||||
_chatService.connectToSession(sessionId);
|
||||
}
|
||||
|
||||
/// Refresh sessions list
|
||||
void refreshSessions() {
|
||||
_chatService.listSessions();
|
||||
}
|
||||
|
||||
/// Send message to current session
|
||||
void sendMessage(String content) {
|
||||
if (content.trim().isEmpty) return;
|
||||
if (!isConnected) {
|
||||
_error = 'No conectado al servidor';
|
||||
notifyListeners();
|
||||
return;
|
||||
}
|
||||
if (_currentSession == null) {
|
||||
_error = 'No hay sesión activa';
|
||||
notifyListeners();
|
||||
return;
|
||||
}
|
||||
if (_isProcessing) {
|
||||
_error = 'Espera a que termine la respuesta anterior';
|
||||
notifyListeners();
|
||||
return;
|
||||
}
|
||||
|
||||
_messages.add(Message(
|
||||
role: 'user',
|
||||
content: content,
|
||||
));
|
||||
_trimMessages();
|
||||
_isProcessing = true;
|
||||
notifyListeners();
|
||||
|
||||
_chatService.sendMessage(content);
|
||||
}
|
||||
|
||||
void clearMessages() {
|
||||
_messages.clear();
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void clearError() {
|
||||
_error = null;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void disconnect() {
|
||||
_chatService.disconnect();
|
||||
_messageSubscription?.cancel();
|
||||
_stateSubscription?.cancel();
|
||||
_errorSubscription?.cancel();
|
||||
_currentSession = null;
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
disconnect();
|
||||
_chatService.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
358
apps/captain-mobile-v2/flutter/lib/screens/chat_screen.dart
Normal file
358
apps/captain-mobile-v2/flutter/lib/screens/chat_screen.dart
Normal file
@@ -0,0 +1,358 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import '../providers/auth_provider.dart';
|
||||
import '../providers/chat_provider.dart';
|
||||
import '../services/chat_service.dart';
|
||||
import '../widgets/message_bubble.dart';
|
||||
import '../widgets/chat_input.dart';
|
||||
|
||||
class ChatScreen extends StatefulWidget {
|
||||
const ChatScreen({super.key});
|
||||
|
||||
@override
|
||||
State<ChatScreen> createState() => _ChatScreenState();
|
||||
}
|
||||
|
||||
class _ChatScreenState extends State<ChatScreen> with WidgetsBindingObserver {
|
||||
final _scrollController = ScrollController();
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
WidgetsBinding.instance.addObserver(this);
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
final auth = context.read<AuthProvider>();
|
||||
final chat = context.read<ChatProvider>();
|
||||
chat.updateAuth(auth);
|
||||
chat.addListener(_onChatUpdate);
|
||||
});
|
||||
}
|
||||
|
||||
String? _lastError;
|
||||
void _onChatUpdate() {
|
||||
final chat = context.read<ChatProvider>();
|
||||
if (chat.error != null && chat.error != _lastError) {
|
||||
_lastError = chat.error;
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(chat.error!),
|
||||
backgroundColor: Colors.red.shade700,
|
||||
action: SnackBarAction(
|
||||
label: 'OK',
|
||||
textColor: Colors.white,
|
||||
onPressed: () => chat.clearError(),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
WidgetsBinding.instance.removeObserver(this);
|
||||
_scrollController.dispose();
|
||||
try {
|
||||
final chat = context.read<ChatProvider>();
|
||||
chat.removeListener(_onChatUpdate);
|
||||
} catch (_) {}
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
void didChangeAppLifecycleState(AppLifecycleState state) {
|
||||
if (state == AppLifecycleState.resumed) {
|
||||
final chat = context.read<ChatProvider>();
|
||||
if (!chat.isConnected) {
|
||||
chat.connect();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void _scrollToBottom() {
|
||||
if (_scrollController.hasClients) {
|
||||
_scrollController.animateTo(
|
||||
_scrollController.position.maxScrollExtent,
|
||||
duration: const Duration(milliseconds: 300),
|
||||
curve: Curves.easeOut,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
void _sendMessage(String message) {
|
||||
final chat = context.read<ChatProvider>();
|
||||
chat.sendMessage(message);
|
||||
Future.delayed(const Duration(milliseconds: 100), _scrollToBottom);
|
||||
}
|
||||
|
||||
void _newChat() {
|
||||
final chat = context.read<ChatProvider>();
|
||||
final name = 'Chat ${DateTime.now().hour}:${DateTime.now().minute.toString().padLeft(2, '0')}';
|
||||
chat.createSession(name);
|
||||
}
|
||||
|
||||
void _logout() {
|
||||
final auth = context.read<AuthProvider>();
|
||||
final chat = context.read<ChatProvider>();
|
||||
chat.disconnect();
|
||||
auth.logout();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
backgroundColor: const Color(0xFF1A1A1A),
|
||||
appBar: AppBar(
|
||||
backgroundColor: const Color(0xFF2D2D2D),
|
||||
elevation: 0,
|
||||
title: Consumer<ChatProvider>(
|
||||
builder: (context, chat, _) {
|
||||
return Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(Icons.auto_awesome, color: Colors.orange.shade400, size: 24),
|
||||
const SizedBox(width: 8),
|
||||
Text(
|
||||
chat.currentSession?.name ?? 'Captain Claude',
|
||||
style: const TextStyle(fontSize: 18),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
actions: [
|
||||
Consumer<ChatProvider>(
|
||||
builder: (context, chat, _) {
|
||||
return IconButton(
|
||||
icon: const Icon(Icons.add),
|
||||
onPressed: _newChat,
|
||||
tooltip: 'Nuevo Chat',
|
||||
);
|
||||
},
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.logout),
|
||||
onPressed: _logout,
|
||||
tooltip: 'Salir',
|
||||
),
|
||||
],
|
||||
),
|
||||
body: Column(
|
||||
children: [
|
||||
// Connection status bar
|
||||
Consumer<ChatProvider>(
|
||||
builder: (context, chat, _) {
|
||||
return _buildConnectionBar(chat);
|
||||
},
|
||||
),
|
||||
// Messages list
|
||||
Expanded(
|
||||
child: Consumer<ChatProvider>(
|
||||
builder: (context, chat, _) {
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (chat.isProcessing) _scrollToBottom();
|
||||
});
|
||||
|
||||
if (!chat.isSessionConnected) {
|
||||
return _buildStartState();
|
||||
}
|
||||
|
||||
if (chat.messages.isEmpty) {
|
||||
return _buildEmptyState();
|
||||
}
|
||||
|
||||
return ListView.builder(
|
||||
controller: _scrollController,
|
||||
padding: const EdgeInsets.only(top: 8, bottom: 8),
|
||||
itemCount: chat.messages.length,
|
||||
itemBuilder: (context, index) {
|
||||
return MessageBubble(message: chat.messages[index]);
|
||||
},
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
// Input area
|
||||
Consumer<ChatProvider>(
|
||||
builder: (context, chat, _) {
|
||||
return ChatInput(
|
||||
onSend: _sendMessage,
|
||||
isConnected: chat.isConnected && chat.isSessionConnected,
|
||||
isLoading: chat.isProcessing,
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildConnectionBar(ChatProvider chat) {
|
||||
if (chat.connectionState == ChatConnectionState.connected) {
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
|
||||
Color backgroundColor;
|
||||
String text;
|
||||
IconData icon;
|
||||
|
||||
switch (chat.connectionState) {
|
||||
case ChatConnectionState.connecting:
|
||||
backgroundColor = Colors.blue.shade700;
|
||||
text = 'Conectando...';
|
||||
icon = Icons.sync;
|
||||
break;
|
||||
case ChatConnectionState.reconnecting:
|
||||
backgroundColor = Colors.orange.shade700;
|
||||
text = 'Reconectando...';
|
||||
icon = Icons.sync;
|
||||
break;
|
||||
case ChatConnectionState.error:
|
||||
backgroundColor = Colors.red.shade700;
|
||||
text = 'Error de conexión';
|
||||
icon = Icons.error_outline;
|
||||
break;
|
||||
default:
|
||||
backgroundColor = Colors.grey.shade700;
|
||||
text = 'Desconectado';
|
||||
icon = Icons.cloud_off;
|
||||
}
|
||||
|
||||
final showRetry = chat.connectionState == ChatConnectionState.error ||
|
||||
chat.connectionState == ChatConnectionState.disconnected;
|
||||
|
||||
return GestureDetector(
|
||||
onTap: showRetry ? () => chat.connect() : null,
|
||||
child: Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
|
||||
color: backgroundColor,
|
||||
child: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Icon(icon, size: 16, color: Colors.white),
|
||||
const SizedBox(width: 8),
|
||||
Text(
|
||||
showRetry ? '$text - Toca para reintentar' : text,
|
||||
style: const TextStyle(color: Colors.white, fontSize: 13),
|
||||
),
|
||||
if (chat.connectionState == ChatConnectionState.connecting ||
|
||||
chat.connectionState == ChatConnectionState.reconnecting) ...[
|
||||
const SizedBox(width: 8),
|
||||
const SizedBox(
|
||||
width: 12,
|
||||
height: 12,
|
||||
child: CircularProgressIndicator(
|
||||
strokeWidth: 2,
|
||||
color: Colors.white,
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildStartState() {
|
||||
return Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(32),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(
|
||||
Icons.chat_bubble_outline,
|
||||
size: 80,
|
||||
color: Colors.orange.shade400.withOpacity(0.5),
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
Text(
|
||||
'Captain Claude',
|
||||
style: TextStyle(
|
||||
color: Colors.grey.shade300,
|
||||
fontSize: 24,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
Text(
|
||||
'Toca el botón + para iniciar un chat',
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(
|
||||
color: Colors.grey.shade500,
|
||||
fontSize: 15,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 32),
|
||||
ElevatedButton.icon(
|
||||
onPressed: _newChat,
|
||||
icon: const Icon(Icons.add),
|
||||
label: const Text('Nuevo Chat'),
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: Colors.orange.shade700,
|
||||
foregroundColor: Colors.white,
|
||||
padding: const EdgeInsets.symmetric(horizontal: 32, vertical: 16),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildEmptyState() {
|
||||
return Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(32),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(
|
||||
Icons.auto_awesome,
|
||||
size: 80,
|
||||
color: Colors.orange.shade400.withOpacity(0.5),
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
Text(
|
||||
'Chat Conectado',
|
||||
style: TextStyle(
|
||||
color: Colors.grey.shade300,
|
||||
fontSize: 24,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
Text(
|
||||
'Escribe un mensaje para hablar con Claude',
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(
|
||||
color: Colors.grey.shade500,
|
||||
fontSize: 15,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 32),
|
||||
Wrap(
|
||||
spacing: 8,
|
||||
runSpacing: 8,
|
||||
alignment: WrapAlignment.center,
|
||||
children: [
|
||||
_buildSuggestionChip('Hola'),
|
||||
_buildSuggestionChip('Estado del sistema'),
|
||||
_buildSuggestionChip('Ayuda'),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildSuggestionChip(String text) {
|
||||
return ActionChip(
|
||||
label: Text(text),
|
||||
backgroundColor: const Color(0xFF2D2D2D),
|
||||
labelStyle: TextStyle(color: Colors.grey.shade300, fontSize: 13),
|
||||
side: BorderSide(color: Colors.grey.shade700),
|
||||
onPressed: () => _sendMessage(text),
|
||||
);
|
||||
}
|
||||
}
|
||||
255
apps/captain-mobile-v2/flutter/lib/screens/history_screen.dart
Normal file
255
apps/captain-mobile-v2/flutter/lib/screens/history_screen.dart
Normal file
@@ -0,0 +1,255 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import '../providers/auth_provider.dart';
|
||||
import '../services/api_service.dart';
|
||||
import '../models/conversation.dart';
|
||||
|
||||
class HistoryScreen extends StatefulWidget {
|
||||
final Function(String) onSelectConversation;
|
||||
|
||||
const HistoryScreen({
|
||||
super.key,
|
||||
required this.onSelectConversation,
|
||||
});
|
||||
|
||||
@override
|
||||
State<HistoryScreen> createState() => _HistoryScreenState();
|
||||
}
|
||||
|
||||
class _HistoryScreenState extends State<HistoryScreen> {
|
||||
final ApiService _apiService = ApiService();
|
||||
List<Conversation> _conversations = [];
|
||||
bool _isLoading = true;
|
||||
String? _error;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_loadConversations();
|
||||
}
|
||||
|
||||
Future<void> _loadConversations() async {
|
||||
final auth = context.read<AuthProvider>();
|
||||
_apiService.setToken(auth.token);
|
||||
|
||||
setState(() {
|
||||
_isLoading = true;
|
||||
_error = null;
|
||||
});
|
||||
|
||||
try {
|
||||
final conversations = await _apiService.getConversations();
|
||||
setState(() {
|
||||
_conversations = conversations;
|
||||
_isLoading = false;
|
||||
});
|
||||
} catch (e) {
|
||||
setState(() {
|
||||
_error = e.toString();
|
||||
_isLoading = false;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _deleteConversation(String id) async {
|
||||
try {
|
||||
await _apiService.deleteConversation(id);
|
||||
setState(() {
|
||||
_conversations.removeWhere((c) => c.id == id);
|
||||
});
|
||||
} catch (e) {
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text('Failed to delete: $e'),
|
||||
backgroundColor: Colors.red.shade700,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
IconData _getTitleIcon(String title) {
|
||||
final lower = title.toLowerCase();
|
||||
if (lower.contains('error') || lower.contains('fix') || lower.contains('bug')) {
|
||||
return Icons.bug_report;
|
||||
}
|
||||
if (lower.contains('test')) {
|
||||
return Icons.science;
|
||||
}
|
||||
if (lower.contains('backup') || lower.contains('restore')) {
|
||||
return Icons.backup;
|
||||
}
|
||||
if (lower.contains('deploy') || lower.contains('build')) {
|
||||
return Icons.rocket_launch;
|
||||
}
|
||||
if (lower.contains('install') || lower.contains('setup')) {
|
||||
return Icons.download;
|
||||
}
|
||||
return Icons.chat_bubble_outline;
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
backgroundColor: const Color(0xFF1A1A1A),
|
||||
appBar: AppBar(
|
||||
backgroundColor: const Color(0xFF2D2D2D),
|
||||
title: const Text('Conversations'),
|
||||
actions: [
|
||||
IconButton(
|
||||
icon: const Icon(Icons.refresh),
|
||||
onPressed: _loadConversations,
|
||||
),
|
||||
],
|
||||
),
|
||||
body: _buildBody(),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildBody() {
|
||||
if (_isLoading) {
|
||||
return const Center(
|
||||
child: CircularProgressIndicator(color: Colors.orange),
|
||||
);
|
||||
}
|
||||
|
||||
if (_error != null) {
|
||||
return Center(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(Icons.error_outline, size: 48, color: Colors.red.shade400),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
_error!,
|
||||
style: TextStyle(color: Colors.grey.shade400),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
ElevatedButton(
|
||||
onPressed: _loadConversations,
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: Colors.orange.shade700,
|
||||
),
|
||||
child: const Text('Retry'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
if (_conversations.isEmpty) {
|
||||
return Center(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(Icons.chat_bubble_outline, size: 64, color: Colors.grey.shade700),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
'No conversations yet',
|
||||
style: TextStyle(
|
||||
color: Colors.grey.shade400,
|
||||
fontSize: 18,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
'Start a new chat to get started',
|
||||
style: TextStyle(
|
||||
color: Colors.grey.shade600,
|
||||
fontSize: 14,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return RefreshIndicator(
|
||||
onRefresh: _loadConversations,
|
||||
color: Colors.orange,
|
||||
child: ListView.builder(
|
||||
padding: const EdgeInsets.symmetric(vertical: 8),
|
||||
itemCount: _conversations.length,
|
||||
itemBuilder: (context, index) {
|
||||
final conv = _conversations[index];
|
||||
return Dismissible(
|
||||
key: Key(conv.id),
|
||||
direction: DismissDirection.endToStart,
|
||||
background: Container(
|
||||
alignment: Alignment.centerRight,
|
||||
padding: const EdgeInsets.only(right: 20),
|
||||
color: Colors.red.shade700,
|
||||
child: const Icon(Icons.delete, color: Colors.white),
|
||||
),
|
||||
confirmDismiss: (_) async {
|
||||
return await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (context) => AlertDialog(
|
||||
backgroundColor: const Color(0xFF2D2D2D),
|
||||
title: const Text(
|
||||
'Delete Conversation?',
|
||||
style: TextStyle(color: Colors.white),
|
||||
),
|
||||
content: const Text(
|
||||
'This action cannot be undone.',
|
||||
style: TextStyle(color: Colors.white70),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(context, false),
|
||||
child: const Text('Cancel'),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(context, true),
|
||||
style: TextButton.styleFrom(
|
||||
foregroundColor: Colors.red.shade400,
|
||||
),
|
||||
child: const Text('Delete'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
onDismissed: (_) => _deleteConversation(conv.id),
|
||||
child: ListTile(
|
||||
leading: CircleAvatar(
|
||||
backgroundColor: const Color(0xFF3D3D3D),
|
||||
child: Icon(
|
||||
_getTitleIcon(conv.displayTitle),
|
||||
color: Colors.orange.shade400,
|
||||
size: 20,
|
||||
),
|
||||
),
|
||||
title: Text(
|
||||
conv.displayTitle,
|
||||
style: const TextStyle(
|
||||
color: Colors.white,
|
||||
fontWeight: FontWeight.w500,
|
||||
),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
subtitle: Text(
|
||||
'${conv.timeAgo} • ${conv.messageCount} messages',
|
||||
style: TextStyle(
|
||||
color: Colors.grey.shade500,
|
||||
fontSize: 12,
|
||||
),
|
||||
),
|
||||
trailing: Icon(
|
||||
Icons.chevron_right,
|
||||
color: Colors.grey.shade600,
|
||||
),
|
||||
onTap: () {
|
||||
widget.onSelectConversation(conv.id);
|
||||
Navigator.pop(context);
|
||||
},
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
193
apps/captain-mobile-v2/flutter/lib/screens/login_screen.dart
Normal file
193
apps/captain-mobile-v2/flutter/lib/screens/login_screen.dart
Normal file
@@ -0,0 +1,193 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import '../providers/auth_provider.dart';
|
||||
|
||||
class LoginScreen extends StatefulWidget {
|
||||
const LoginScreen({super.key});
|
||||
|
||||
@override
|
||||
State<LoginScreen> createState() => _LoginScreenState();
|
||||
}
|
||||
|
||||
class _LoginScreenState extends State<LoginScreen> {
|
||||
final _usernameController = TextEditingController();
|
||||
final _passwordController = TextEditingController();
|
||||
bool _obscurePassword = true;
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_usernameController.dispose();
|
||||
_passwordController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Future<void> _login() async {
|
||||
final username = _usernameController.text.trim();
|
||||
final password = _passwordController.text;
|
||||
|
||||
if (username.isEmpty || password.isEmpty) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(
|
||||
content: Text('Please enter username and password'),
|
||||
backgroundColor: Colors.orange,
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
final auth = context.read<AuthProvider>();
|
||||
await auth.login(username, password);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
backgroundColor: const Color(0xFF1A1A1A),
|
||||
body: SafeArea(
|
||||
child: SingleChildScrollView(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
const SizedBox(height: 60),
|
||||
// Logo
|
||||
Icon(
|
||||
Icons.auto_awesome,
|
||||
size: 80,
|
||||
color: Colors.orange.shade400,
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
// Title
|
||||
const Text(
|
||||
'Captain Claude',
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 32,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
'Your AI Command Center',
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(
|
||||
color: Colors.grey.shade400,
|
||||
fontSize: 16,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 60),
|
||||
// Username field
|
||||
TextField(
|
||||
controller: _usernameController,
|
||||
style: const TextStyle(color: Colors.white),
|
||||
decoration: InputDecoration(
|
||||
labelText: 'Username',
|
||||
labelStyle: TextStyle(color: Colors.grey.shade400),
|
||||
prefixIcon: Icon(Icons.person, color: Colors.grey.shade400),
|
||||
filled: true,
|
||||
fillColor: const Color(0xFF2D2D2D),
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
borderSide: BorderSide.none,
|
||||
),
|
||||
focusedBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
borderSide: BorderSide(color: Colors.orange.shade400),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
// Password field
|
||||
TextField(
|
||||
controller: _passwordController,
|
||||
obscureText: _obscurePassword,
|
||||
style: const TextStyle(color: Colors.white),
|
||||
decoration: InputDecoration(
|
||||
labelText: 'Password',
|
||||
labelStyle: TextStyle(color: Colors.grey.shade400),
|
||||
prefixIcon: Icon(Icons.lock, color: Colors.grey.shade400),
|
||||
suffixIcon: IconButton(
|
||||
icon: Icon(
|
||||
_obscurePassword
|
||||
? Icons.visibility_off
|
||||
: Icons.visibility,
|
||||
color: Colors.grey.shade400,
|
||||
),
|
||||
onPressed: () {
|
||||
setState(() => _obscurePassword = !_obscurePassword);
|
||||
},
|
||||
),
|
||||
filled: true,
|
||||
fillColor: const Color(0xFF2D2D2D),
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
borderSide: BorderSide.none,
|
||||
),
|
||||
focusedBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
borderSide: BorderSide(color: Colors.orange.shade400),
|
||||
),
|
||||
),
|
||||
onSubmitted: (_) => _login(),
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
// Error message
|
||||
Consumer<AuthProvider>(
|
||||
builder: (context, auth, _) {
|
||||
if (auth.error != null) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(bottom: 16),
|
||||
child: Text(
|
||||
auth.error!,
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(
|
||||
color: Colors.red.shade400,
|
||||
fontSize: 14,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
return const SizedBox.shrink();
|
||||
},
|
||||
),
|
||||
// Login button
|
||||
Consumer<AuthProvider>(
|
||||
builder: (context, auth, _) {
|
||||
return ElevatedButton(
|
||||
onPressed: auth.isLoading ? null : _login,
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: Colors.orange.shade700,
|
||||
foregroundColor: Colors.white,
|
||||
padding: const EdgeInsets.symmetric(vertical: 16),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
disabledBackgroundColor: Colors.grey.shade800,
|
||||
),
|
||||
child: auth.isLoading
|
||||
? const SizedBox(
|
||||
width: 24,
|
||||
height: 24,
|
||||
child: CircularProgressIndicator(
|
||||
strokeWidth: 2,
|
||||
color: Colors.white,
|
||||
),
|
||||
)
|
||||
: const Text(
|
||||
'Sign In',
|
||||
style: TextStyle(
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
55
apps/captain-mobile-v2/flutter/lib/services/api_service.dart
Normal file
55
apps/captain-mobile-v2/flutter/lib/services/api_service.dart
Normal file
@@ -0,0 +1,55 @@
|
||||
import 'dart:convert';
|
||||
import 'package:http/http.dart' as http;
|
||||
import '../config/api_config.dart';
|
||||
import '../models/conversation.dart';
|
||||
import '../models/message.dart';
|
||||
|
||||
class ApiService {
|
||||
String? _token;
|
||||
|
||||
void setToken(String? token) {
|
||||
_token = token;
|
||||
}
|
||||
|
||||
Map<String, String> get _headers => {
|
||||
'Content-Type': 'application/json',
|
||||
if (_token != null) 'Authorization': 'Bearer $_token',
|
||||
};
|
||||
|
||||
Future<List<Conversation>> getConversations() async {
|
||||
final response = await http.get(
|
||||
Uri.parse('${ApiConfig.baseUrl}/conversations'),
|
||||
headers: _headers,
|
||||
).timeout(ApiConfig.connectionTimeout);
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
final List<dynamic> data = jsonDecode(response.body);
|
||||
return data.map((e) => Conversation.fromJson(e)).toList();
|
||||
}
|
||||
throw Exception('Failed to load conversations');
|
||||
}
|
||||
|
||||
Future<List<Message>> getConversationMessages(String conversationId) async {
|
||||
final response = await http.get(
|
||||
Uri.parse('${ApiConfig.baseUrl}/conversations/$conversationId'),
|
||||
headers: _headers,
|
||||
).timeout(ApiConfig.connectionTimeout);
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
final List<dynamic> data = jsonDecode(response.body);
|
||||
return data.map((e) => Message.fromJson(e)).toList();
|
||||
}
|
||||
throw Exception('Failed to load messages');
|
||||
}
|
||||
|
||||
Future<void> deleteConversation(String conversationId) async {
|
||||
final response = await http.delete(
|
||||
Uri.parse('${ApiConfig.baseUrl}/conversations/$conversationId'),
|
||||
headers: _headers,
|
||||
).timeout(ApiConfig.connectionTimeout);
|
||||
|
||||
if (response.statusCode != 200) {
|
||||
throw Exception('Failed to delete conversation');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import 'dart:convert';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import '../config/api_config.dart';
|
||||
|
||||
class AuthService {
|
||||
static const String _tokenKey = 'auth_token';
|
||||
static const String _expiresKey = 'token_expires';
|
||||
static const String _usernameKey = 'username';
|
||||
|
||||
String? _token;
|
||||
DateTime? _expiresAt;
|
||||
String? _username;
|
||||
|
||||
String? get token => _token;
|
||||
String? get username => _username;
|
||||
bool get isAuthenticated => _token != null && !isExpired;
|
||||
bool get isExpired =>
|
||||
_expiresAt != null && DateTime.now().isAfter(_expiresAt!);
|
||||
|
||||
Future<void> loadStoredAuth() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
_token = prefs.getString(_tokenKey);
|
||||
_username = prefs.getString(_usernameKey);
|
||||
final expiresStr = prefs.getString(_expiresKey);
|
||||
if (expiresStr != null) {
|
||||
_expiresAt = DateTime.tryParse(expiresStr);
|
||||
}
|
||||
}
|
||||
|
||||
String? lastError;
|
||||
|
||||
Future<bool> login(String username, String password) async {
|
||||
lastError = null;
|
||||
try {
|
||||
final response = await http.post(
|
||||
Uri.parse('${ApiConfig.baseUrl}/auth/login'),
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: jsonEncode({'username': username, 'password': password}),
|
||||
).timeout(ApiConfig.connectionTimeout);
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
final data = jsonDecode(response.body);
|
||||
_token = data['token'];
|
||||
_expiresAt = DateTime.parse(data['expires_at']);
|
||||
_username = username;
|
||||
|
||||
// Save to storage
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setString(_tokenKey, _token!);
|
||||
await prefs.setString(_expiresKey, _expiresAt!.toIso8601String());
|
||||
await prefs.setString(_usernameKey, _username!);
|
||||
|
||||
return true;
|
||||
}
|
||||
lastError = 'Invalid credentials (${response.statusCode})';
|
||||
return false;
|
||||
} catch (e) {
|
||||
lastError = 'Connection error: $e';
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> logout() async {
|
||||
_token = null;
|
||||
_expiresAt = null;
|
||||
_username = null;
|
||||
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.remove(_tokenKey);
|
||||
await prefs.remove(_expiresKey);
|
||||
await prefs.remove(_usernameKey);
|
||||
}
|
||||
}
|
||||
223
apps/captain-mobile-v2/flutter/lib/services/chat_service.dart
Normal file
223
apps/captain-mobile-v2/flutter/lib/services/chat_service.dart
Normal file
@@ -0,0 +1,223 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'package:web_socket_channel/web_socket_channel.dart';
|
||||
import '../config/api_config.dart';
|
||||
|
||||
enum ChatConnectionState {
|
||||
disconnected,
|
||||
connecting,
|
||||
connected,
|
||||
reconnecting,
|
||||
error,
|
||||
}
|
||||
|
||||
/// Chat session info (v3 - dynamic sessions)
|
||||
class ChatSession {
|
||||
final String sessionId;
|
||||
final String name;
|
||||
final String? createdAt;
|
||||
|
||||
ChatSession({
|
||||
required this.sessionId,
|
||||
required this.name,
|
||||
this.createdAt,
|
||||
});
|
||||
|
||||
factory ChatSession.fromJson(Map<String, dynamic> json) {
|
||||
return ChatSession(
|
||||
sessionId: json['session_id'] ?? '',
|
||||
name: json['name'] ?? 'Session',
|
||||
createdAt: json['created_at'],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Chat service that connects to Claude sessions (v3)
|
||||
class ChatService {
|
||||
WebSocketChannel? _channel;
|
||||
String? _token;
|
||||
|
||||
final _messagesController = StreamController<Map<String, dynamic>>.broadcast();
|
||||
final _stateController = StreamController<ChatConnectionState>.broadcast();
|
||||
final _errorController = StreamController<String>.broadcast();
|
||||
|
||||
ChatConnectionState _currentState = ChatConnectionState.disconnected;
|
||||
int _reconnectAttempts = 0;
|
||||
Timer? _reconnectTimer;
|
||||
Timer? _pingTimer;
|
||||
bool _intentionalDisconnect = false;
|
||||
|
||||
Stream<Map<String, dynamic>> get messages => _messagesController.stream;
|
||||
Stream<ChatConnectionState> get connectionState => _stateController.stream;
|
||||
Stream<String> get errors => _errorController.stream;
|
||||
ChatConnectionState get currentState => _currentState;
|
||||
|
||||
void setToken(String? token) {
|
||||
_token = token;
|
||||
}
|
||||
|
||||
void _setState(ChatConnectionState state) {
|
||||
_currentState = state;
|
||||
_stateController.add(state);
|
||||
}
|
||||
|
||||
Future<void> connect() async {
|
||||
if (_token == null) return;
|
||||
if (_currentState == ChatConnectionState.connecting) return;
|
||||
|
||||
_intentionalDisconnect = false;
|
||||
_setState(ChatConnectionState.connecting);
|
||||
|
||||
try {
|
||||
_channel?.sink.close();
|
||||
_channel = WebSocketChannel.connect(
|
||||
Uri.parse('${ApiConfig.wsUrl}/ws/chat'),
|
||||
);
|
||||
|
||||
// Send auth token immediately
|
||||
_channel!.sink.add(jsonEncode({'token': _token}));
|
||||
|
||||
_channel!.stream.listen(
|
||||
(data) {
|
||||
try {
|
||||
final message = jsonDecode(data);
|
||||
_handleMessage(message);
|
||||
} catch (e) {
|
||||
_errorController.add('Failed to parse message: $e');
|
||||
}
|
||||
},
|
||||
onError: (error) {
|
||||
_errorController.add('WebSocket error: $error');
|
||||
_setState(ChatConnectionState.error);
|
||||
if (!_intentionalDisconnect) {
|
||||
_scheduleReconnect();
|
||||
}
|
||||
},
|
||||
onDone: () {
|
||||
_setState(ChatConnectionState.disconnected);
|
||||
if (!_intentionalDisconnect) {
|
||||
_scheduleReconnect();
|
||||
}
|
||||
},
|
||||
cancelOnError: false,
|
||||
);
|
||||
} catch (e) {
|
||||
_errorController.add('Connection failed: $e');
|
||||
_setState(ChatConnectionState.error);
|
||||
if (!_intentionalDisconnect) {
|
||||
_scheduleReconnect();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void _handleMessage(Map<String, dynamic> message) {
|
||||
final type = message['type'];
|
||||
|
||||
switch (type) {
|
||||
case 'init':
|
||||
// Initial state with sessions list
|
||||
_setState(ChatConnectionState.connected);
|
||||
_reconnectAttempts = 0;
|
||||
_startPingTimer();
|
||||
_messagesController.add(message);
|
||||
break;
|
||||
|
||||
case 'error':
|
||||
final errorMsg = message['message'] ?? message['content'] ?? 'Unknown error';
|
||||
_errorController.add(errorMsg);
|
||||
break;
|
||||
|
||||
case 'pong':
|
||||
break;
|
||||
|
||||
default:
|
||||
// Forward all other messages (output, done, session_connected, etc.)
|
||||
_messagesController.add(message);
|
||||
}
|
||||
}
|
||||
|
||||
void _startPingTimer() {
|
||||
_pingTimer?.cancel();
|
||||
_pingTimer = Timer.periodic(const Duration(seconds: 30), (_) {
|
||||
if (_currentState == ChatConnectionState.connected) {
|
||||
sendRaw({'type': 'ping'});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void _scheduleReconnect() {
|
||||
if (_intentionalDisconnect) return;
|
||||
if (_reconnectAttempts >= ApiConfig.maxReconnectAttempts) {
|
||||
_errorController.add('Max reconnection attempts reached');
|
||||
return;
|
||||
}
|
||||
|
||||
_reconnectTimer?.cancel();
|
||||
final delay = Duration(
|
||||
seconds: ApiConfig.reconnectDelay.inSeconds * (1 << _reconnectAttempts),
|
||||
);
|
||||
_reconnectAttempts++;
|
||||
_setState(ChatConnectionState.reconnecting);
|
||||
|
||||
_reconnectTimer = Timer(delay, () {
|
||||
if (_token != null && !_intentionalDisconnect) {
|
||||
connect();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Create a new chat session
|
||||
void createSession(String name) {
|
||||
sendRaw({
|
||||
'type': 'create_session',
|
||||
'name': name,
|
||||
});
|
||||
}
|
||||
|
||||
/// Connect to an existing session by session_id
|
||||
void connectToSession(String sessionId) {
|
||||
sendRaw({
|
||||
'type': 'connect_session',
|
||||
'session_id': sessionId,
|
||||
});
|
||||
}
|
||||
|
||||
/// Send message to connected session
|
||||
void sendMessage(String content) {
|
||||
if (_currentState != ChatConnectionState.connected) {
|
||||
_errorController.add('Not connected');
|
||||
return;
|
||||
}
|
||||
|
||||
sendRaw({
|
||||
'type': 'message',
|
||||
'content': content,
|
||||
});
|
||||
}
|
||||
|
||||
/// Request sessions list
|
||||
void listSessions() {
|
||||
sendRaw({'type': 'list_sessions'});
|
||||
}
|
||||
|
||||
void sendRaw(Map<String, dynamic> data) {
|
||||
if (_channel != null) {
|
||||
_channel!.sink.add(jsonEncode(data));
|
||||
}
|
||||
}
|
||||
|
||||
void disconnect() {
|
||||
_intentionalDisconnect = true;
|
||||
_pingTimer?.cancel();
|
||||
_reconnectTimer?.cancel();
|
||||
_channel?.sink.close();
|
||||
_setState(ChatConnectionState.disconnected);
|
||||
}
|
||||
|
||||
void dispose() {
|
||||
disconnect();
|
||||
_messagesController.close();
|
||||
_stateController.close();
|
||||
_errorController.close();
|
||||
}
|
||||
}
|
||||
128
apps/captain-mobile-v2/flutter/lib/widgets/chat_input.dart
Normal file
128
apps/captain-mobile-v2/flutter/lib/widgets/chat_input.dart
Normal file
@@ -0,0 +1,128 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
class ChatInput extends StatefulWidget {
|
||||
final Function(String) onSend;
|
||||
final bool isConnected;
|
||||
final bool isLoading;
|
||||
|
||||
const ChatInput({
|
||||
super.key,
|
||||
required this.onSend,
|
||||
this.isConnected = true,
|
||||
this.isLoading = false,
|
||||
});
|
||||
|
||||
@override
|
||||
State<ChatInput> createState() => _ChatInputState();
|
||||
}
|
||||
|
||||
class _ChatInputState extends State<ChatInput> {
|
||||
final _controller = TextEditingController();
|
||||
final _focusNode = FocusNode();
|
||||
|
||||
bool get _canSend =>
|
||||
widget.isConnected &&
|
||||
!widget.isLoading &&
|
||||
_controller.text.trim().isNotEmpty;
|
||||
|
||||
void _send() {
|
||||
if (!_canSend) return;
|
||||
|
||||
final text = _controller.text.trim();
|
||||
_controller.clear();
|
||||
widget.onSend(text);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_controller.dispose();
|
||||
_focusNode.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Container(
|
||||
padding: EdgeInsets.only(
|
||||
left: 12,
|
||||
right: 12,
|
||||
top: 8,
|
||||
bottom: MediaQuery.of(context).padding.bottom + 8,
|
||||
),
|
||||
decoration: BoxDecoration(
|
||||
color: const Color(0xFF1A1A1A),
|
||||
border: Border(
|
||||
top: BorderSide(color: Colors.grey.shade800),
|
||||
),
|
||||
),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.end,
|
||||
children: [
|
||||
// Input field
|
||||
Expanded(
|
||||
child: Container(
|
||||
constraints: const BoxConstraints(maxHeight: 120),
|
||||
decoration: BoxDecoration(
|
||||
color: const Color(0xFF2D2D2D),
|
||||
borderRadius: BorderRadius.circular(24),
|
||||
border: Border.all(
|
||||
color: widget.isConnected
|
||||
? Colors.grey.shade700
|
||||
: Colors.red.shade700,
|
||||
),
|
||||
),
|
||||
child: TextField(
|
||||
controller: _controller,
|
||||
focusNode: _focusNode,
|
||||
maxLines: null,
|
||||
textInputAction: TextInputAction.newline,
|
||||
onChanged: (_) => setState(() {}),
|
||||
style: const TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 15,
|
||||
),
|
||||
decoration: InputDecoration(
|
||||
hintText: widget.isConnected
|
||||
? 'Message Claude...'
|
||||
: 'Disconnected',
|
||||
hintStyle: TextStyle(
|
||||
color: Colors.grey.shade500,
|
||||
),
|
||||
contentPadding: const EdgeInsets.symmetric(
|
||||
horizontal: 16,
|
||||
vertical: 12,
|
||||
),
|
||||
border: InputBorder.none,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
// Send button
|
||||
Container(
|
||||
decoration: BoxDecoration(
|
||||
color: _canSend ? Colors.orange.shade700 : Colors.grey.shade800,
|
||||
shape: BoxShape.circle,
|
||||
),
|
||||
child: IconButton(
|
||||
onPressed: _canSend ? _send : null,
|
||||
icon: widget.isLoading
|
||||
? SizedBox(
|
||||
width: 20,
|
||||
height: 20,
|
||||
child: CircularProgressIndicator(
|
||||
strokeWidth: 2,
|
||||
color: Colors.grey.shade400,
|
||||
),
|
||||
)
|
||||
: Icon(
|
||||
Icons.send,
|
||||
color: _canSend ? Colors.white : Colors.grey.shade600,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
84
apps/captain-mobile-v2/flutter/lib/widgets/code_block.dart
Normal file
84
apps/captain-mobile-v2/flutter/lib/widgets/code_block.dart
Normal file
@@ -0,0 +1,84 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_highlight/flutter_highlight.dart';
|
||||
import 'package:flutter_highlight/themes/atom-one-dark.dart';
|
||||
|
||||
class CodeBlock extends StatelessWidget {
|
||||
final String code;
|
||||
final String? language;
|
||||
|
||||
const CodeBlock({
|
||||
super.key,
|
||||
required this.code,
|
||||
this.language,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Container(
|
||||
margin: const EdgeInsets.symmetric(vertical: 8),
|
||||
decoration: BoxDecoration(
|
||||
color: const Color(0xFF282C34),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
border: Border.all(color: Colors.grey.shade800),
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
// Header with language and copy button
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.grey.shade900,
|
||||
borderRadius: const BorderRadius.only(
|
||||
topLeft: Radius.circular(8),
|
||||
topRight: Radius.circular(8),
|
||||
),
|
||||
),
|
||||
child: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
Text(
|
||||
language ?? 'code',
|
||||
style: TextStyle(
|
||||
color: Colors.grey.shade500,
|
||||
fontSize: 12,
|
||||
),
|
||||
),
|
||||
InkWell(
|
||||
onTap: () {
|
||||
Clipboard.setData(ClipboardData(text: code));
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(
|
||||
content: Text('Copied to clipboard'),
|
||||
duration: Duration(seconds: 1),
|
||||
),
|
||||
);
|
||||
},
|
||||
child: Icon(
|
||||
Icons.copy,
|
||||
size: 16,
|
||||
color: Colors.grey.shade500,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
// Code content
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(12),
|
||||
child: HighlightView(
|
||||
code,
|
||||
language: language ?? 'plaintext',
|
||||
theme: atomOneDarkTheme,
|
||||
textStyle: const TextStyle(
|
||||
fontFamily: 'JetBrainsMono',
|
||||
fontSize: 13,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
195
apps/captain-mobile-v2/flutter/lib/widgets/message_bubble.dart
Normal file
195
apps/captain-mobile-v2/flutter/lib/widgets/message_bubble.dart
Normal file
@@ -0,0 +1,195 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_markdown/flutter_markdown.dart';
|
||||
import '../models/message.dart';
|
||||
import 'code_block.dart';
|
||||
import 'tool_use_card.dart';
|
||||
import 'thinking_indicator.dart';
|
||||
|
||||
class MessageBubble extends StatelessWidget {
|
||||
final Message message;
|
||||
|
||||
const MessageBubble({super.key, required this.message});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
|
||||
child: message.isUser ? _buildUserBubble() : _buildAssistantBubble(),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildUserBubble() {
|
||||
return Row(
|
||||
mainAxisAlignment: MainAxisAlignment.end,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
const SizedBox(width: 48), // Spacing for alignment
|
||||
Flexible(
|
||||
child: Container(
|
||||
padding: const EdgeInsets.all(12),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.orange.shade700,
|
||||
borderRadius: const BorderRadius.only(
|
||||
topLeft: Radius.circular(16),
|
||||
topRight: Radius.circular(16),
|
||||
bottomLeft: Radius.circular(16),
|
||||
bottomRight: Radius.circular(4),
|
||||
),
|
||||
),
|
||||
child: Text(
|
||||
message.content,
|
||||
style: const TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 15,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
CircleAvatar(
|
||||
radius: 16,
|
||||
backgroundColor: Colors.orange.shade800,
|
||||
child: const Icon(Icons.person, size: 18, color: Colors.white),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildAssistantBubble() {
|
||||
return Row(
|
||||
mainAxisAlignment: MainAxisAlignment.start,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
CircleAvatar(
|
||||
radius: 16,
|
||||
backgroundColor: const Color(0xFF2D2D2D),
|
||||
child: Icon(Icons.auto_awesome, size: 18, color: Colors.orange.shade400),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Flexible(
|
||||
child: Container(
|
||||
padding: const EdgeInsets.all(12),
|
||||
decoration: BoxDecoration(
|
||||
color: const Color(0xFF2D2D2D),
|
||||
borderRadius: const BorderRadius.only(
|
||||
topLeft: Radius.circular(4),
|
||||
topRight: Radius.circular(16),
|
||||
bottomLeft: Radius.circular(16),
|
||||
bottomRight: Radius.circular(16),
|
||||
),
|
||||
),
|
||||
child: _buildContent(),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 48), // Spacing for alignment
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildContent() {
|
||||
if (message.isThinking && message.content.isEmpty) {
|
||||
return const ThinkingIndicator();
|
||||
}
|
||||
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
// Tool uses first
|
||||
if (message.toolUses != null && message.toolUses!.isNotEmpty)
|
||||
...message.toolUses!.map((tool) => ToolUseCard(toolUse: tool)),
|
||||
// Then the text content with Markdown
|
||||
if (message.content.isNotEmpty)
|
||||
MarkdownBody(
|
||||
data: message.content,
|
||||
selectable: true,
|
||||
styleSheet: MarkdownStyleSheet(
|
||||
p: const TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 15,
|
||||
height: 1.5,
|
||||
),
|
||||
h1: const TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 22,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
h2: const TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 20,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
h3: const TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 18,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
code: TextStyle(
|
||||
color: Colors.orange.shade300,
|
||||
backgroundColor: Colors.black26,
|
||||
fontFamily: 'JetBrainsMono',
|
||||
fontSize: 13,
|
||||
),
|
||||
codeblockDecoration: BoxDecoration(
|
||||
color: const Color(0xFF282C34),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
blockquote: const TextStyle(
|
||||
color: Colors.white70,
|
||||
fontStyle: FontStyle.italic,
|
||||
),
|
||||
blockquoteDecoration: BoxDecoration(
|
||||
border: Border(
|
||||
left: BorderSide(color: Colors.orange.shade400, width: 3),
|
||||
),
|
||||
),
|
||||
listBullet: const TextStyle(color: Colors.white70),
|
||||
a: TextStyle(color: Colors.orange.shade300),
|
||||
),
|
||||
builders: {
|
||||
'code': _CodeBlockBuilder(),
|
||||
},
|
||||
),
|
||||
// Streaming indicator
|
||||
if (message.isStreaming && !message.isThinking)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 8),
|
||||
child: SizedBox(
|
||||
width: 12,
|
||||
height: 12,
|
||||
child: CircularProgressIndicator(
|
||||
strokeWidth: 2,
|
||||
color: Colors.orange.shade400,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _CodeBlockBuilder extends MarkdownElementBuilder {
|
||||
@override
|
||||
Widget? visitElementAfter(element, preferredStyle) {
|
||||
// Check if it's a fenced code block
|
||||
final content = element.textContent;
|
||||
String? language;
|
||||
|
||||
// Try to detect language from class attribute
|
||||
if (element.attributes.containsKey('class')) {
|
||||
final classes = element.attributes['class']!;
|
||||
if (classes.startsWith('language-')) {
|
||||
language = classes.substring(9);
|
||||
}
|
||||
}
|
||||
|
||||
// For inline code, use default style
|
||||
if (!content.contains('\n') && content.length < 50) {
|
||||
return null; // Use default styling
|
||||
}
|
||||
|
||||
return CodeBlock(
|
||||
code: content,
|
||||
language: language,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
class ThinkingIndicator extends StatefulWidget {
|
||||
const ThinkingIndicator({super.key});
|
||||
|
||||
@override
|
||||
State<ThinkingIndicator> createState() => _ThinkingIndicatorState();
|
||||
}
|
||||
|
||||
class _ThinkingIndicatorState extends State<ThinkingIndicator>
|
||||
with SingleTickerProviderStateMixin {
|
||||
late AnimationController _controller;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_controller = AnimationController(
|
||||
vsync: this,
|
||||
duration: const Duration(milliseconds: 1500),
|
||||
)..repeat();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_controller.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
AnimatedBuilder(
|
||||
animation: _controller,
|
||||
builder: (context, child) {
|
||||
return Row(
|
||||
children: List.generate(3, (index) {
|
||||
final delay = index * 0.2;
|
||||
final value = (_controller.value + delay) % 1.0;
|
||||
final opacity = (value < 0.5 ? value * 2 : 2 - value * 2);
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 2),
|
||||
child: Opacity(
|
||||
opacity: 0.3 + opacity * 0.7,
|
||||
child: Container(
|
||||
width: 8,
|
||||
height: 8,
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.orange.shade400,
|
||||
shape: BoxShape.circle,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}),
|
||||
);
|
||||
},
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Text(
|
||||
'Claude is thinking...',
|
||||
style: TextStyle(
|
||||
color: Colors.grey.shade400,
|
||||
fontSize: 14,
|
||||
fontStyle: FontStyle.italic,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
165
apps/captain-mobile-v2/flutter/lib/widgets/tool_use_card.dart
Normal file
165
apps/captain-mobile-v2/flutter/lib/widgets/tool_use_card.dart
Normal file
@@ -0,0 +1,165 @@
|
||||
import 'dart:convert';
|
||||
import 'package:flutter/material.dart';
|
||||
import '../models/message.dart';
|
||||
|
||||
class ToolUseCard extends StatefulWidget {
|
||||
final ToolUse toolUse;
|
||||
|
||||
const ToolUseCard({super.key, required this.toolUse});
|
||||
|
||||
@override
|
||||
State<ToolUseCard> createState() => _ToolUseCardState();
|
||||
}
|
||||
|
||||
class _ToolUseCardState extends State<ToolUseCard> {
|
||||
bool _isExpanded = false;
|
||||
|
||||
IconData get _toolIcon {
|
||||
switch (widget.toolUse.tool.toLowerCase()) {
|
||||
case 'bash':
|
||||
return Icons.terminal;
|
||||
case 'read':
|
||||
return Icons.description;
|
||||
case 'write':
|
||||
case 'edit':
|
||||
return Icons.edit_document;
|
||||
case 'grep':
|
||||
case 'glob':
|
||||
return Icons.search;
|
||||
default:
|
||||
return Icons.build;
|
||||
}
|
||||
}
|
||||
|
||||
String get _inputDisplay {
|
||||
final input = widget.toolUse.input;
|
||||
if (input == null) return '';
|
||||
if (input is String) return input;
|
||||
if (input is Map) {
|
||||
// For Bash tool, show command
|
||||
if (input.containsKey('command')) {
|
||||
return input['command'];
|
||||
}
|
||||
// For Read tool, show file path
|
||||
if (input.containsKey('file_path')) {
|
||||
return input['file_path'];
|
||||
}
|
||||
// Otherwise show JSON
|
||||
try {
|
||||
return const JsonEncoder.withIndent(' ').convert(input);
|
||||
} catch (_) {
|
||||
return input.toString();
|
||||
}
|
||||
}
|
||||
return input.toString();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final hasOutput = widget.toolUse.output != null &&
|
||||
widget.toolUse.output!.isNotEmpty;
|
||||
|
||||
return Container(
|
||||
margin: const EdgeInsets.symmetric(vertical: 4),
|
||||
decoration: BoxDecoration(
|
||||
color: const Color(0xFF2D2D2D),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
border: Border.all(color: Colors.orange.shade700.withOpacity(0.3)),
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
// Header
|
||||
InkWell(
|
||||
onTap: hasOutput
|
||||
? () => setState(() => _isExpanded = !_isExpanded)
|
||||
: null,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(12),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(_toolIcon, size: 18, color: Colors.orange.shade400),
|
||||
const SizedBox(width: 8),
|
||||
Text(
|
||||
widget.toolUse.tool,
|
||||
style: TextStyle(
|
||||
color: Colors.orange.shade400,
|
||||
fontWeight: FontWeight.bold,
|
||||
fontSize: 13,
|
||||
),
|
||||
),
|
||||
const Spacer(),
|
||||
if (hasOutput)
|
||||
Icon(
|
||||
_isExpanded ? Icons.expand_less : Icons.expand_more,
|
||||
color: Colors.grey.shade500,
|
||||
size: 20,
|
||||
),
|
||||
if (!hasOutput && widget.toolUse.output == null)
|
||||
SizedBox(
|
||||
width: 14,
|
||||
height: 14,
|
||||
child: CircularProgressIndicator(
|
||||
strokeWidth: 2,
|
||||
color: Colors.orange.shade400,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
// Input/Command
|
||||
if (_inputDisplay.isNotEmpty)
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.black.withOpacity(0.2),
|
||||
),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
'▶',
|
||||
style: TextStyle(
|
||||
color: Colors.green.shade400,
|
||||
fontFamily: 'JetBrainsMono',
|
||||
fontSize: 12,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: Text(
|
||||
_inputDisplay,
|
||||
style: const TextStyle(
|
||||
color: Colors.white70,
|
||||
fontFamily: 'JetBrainsMono',
|
||||
fontSize: 12,
|
||||
),
|
||||
maxLines: 3,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
// Output (collapsible)
|
||||
if (_isExpanded && hasOutput)
|
||||
Container(
|
||||
constraints: const BoxConstraints(maxHeight: 200),
|
||||
padding: const EdgeInsets.all(12),
|
||||
child: SingleChildScrollView(
|
||||
child: Text(
|
||||
widget.toolUse.output!,
|
||||
style: const TextStyle(
|
||||
color: Colors.white60,
|
||||
fontFamily: 'JetBrainsMono',
|
||||
fontSize: 11,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user