added chat app

This commit is contained in:
tom.hempel
2025-09-30 18:07:12 +02:00
parent 9f67723754
commit 617ee0757d
178 changed files with 40482 additions and 0 deletions

27
Chat-App/lib/main.dart Normal file
View File

@ -0,0 +1,27 @@
import 'package:flutter/material.dart';
import 'package:ai_chat_lab/screens/startup_screen.dart';
void main() {
runApp(const MainApp());
}
class MainApp extends StatelessWidget {
const MainApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Convai Chat',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(
seedColor: const Color(0xFF4F8CFF),
brightness: Brightness.light,
),
useMaterial3: true,
fontFamily: 'Segoe UI',
),
home: const StartupScreen(),
debugShowCheckedModeBanner: false,
);
}
}

View File

@ -0,0 +1,11 @@
class ChatMessage {
final String text;
final bool isUser;
final DateTime timestamp;
ChatMessage({
required this.text,
required this.isUser,
DateTime? timestamp,
}) : timestamp = timestamp ?? DateTime.now();
}

View File

@ -0,0 +1,552 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:ai_chat_lab/services/convai_service.dart';
import 'package:ai_chat_lab/services/storage_service.dart';
import 'package:ai_chat_lab/screens/settings_screen.dart';
import 'package:ai_chat_lab/models/chat_message.dart';
import 'dart:async';
class ChatScreen extends StatefulWidget {
const ChatScreen({super.key});
@override
State<ChatScreen> createState() => _ChatScreenState();
}
class _ChatScreenState extends State<ChatScreen> {
final TextEditingController _messageController = TextEditingController();
final TextEditingController _participantController = TextEditingController();
final ScrollController _scrollController = ScrollController();
final ConvaiService _convaiService = ConvaiService();
final StorageService _storageService = StorageService();
List<ChatMessage> messages = [];
bool isLoading = false;
String participantId = '';
bool _supervisedMode = false;
bool _initialTurnPending = false;
String _initialPrompt = '';
bool _timedExperiment = false;
int _experimentDuration = 5;
DateTime? _experimentStartTime;
Timer? _experimentTimer;
bool _experimentExpired = false;
Duration _timeRemaining = Duration.zero;
@override
void initState() {
super.initState();
_loadSettings();
}
Future<void> _loadSettings() async {
await _convaiService.loadSettings();
final supervised = await _convaiService.isSupervisedModeEnabled();
final initPrompt = await _convaiService.getCharacterInitialPrompt(_convaiService.characterId);
final timedExperiment = await _convaiService.isTimedExperimentEnabled();
final duration = await _convaiService.getExperimentDurationMinutes();
setState(() {
_supervisedMode = supervised;
_initialPrompt = initPrompt;
_initialTurnPending = supervised; // first message gated
_timedExperiment = timedExperiment;
_experimentDuration = duration;
});
}
void _startExperiment() {
if (_timedExperiment && _experimentStartTime == null) {
_experimentStartTime = DateTime.now();
_startExperimentTimer();
}
}
void _startExperimentTimer() {
_experimentTimer?.cancel();
_experimentTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
final now = DateTime.now();
final elapsed = now.difference(_experimentStartTime!);
final totalDuration = Duration(minutes: _experimentDuration);
if (elapsed >= totalDuration) {
setState(() {
_experimentExpired = true;
_timeRemaining = Duration.zero;
});
_experimentTimer?.cancel();
} else {
setState(() {
_timeRemaining = totalDuration - elapsed;
});
}
});
}
Future<void> _sendMessage() async {
final text = _messageController.text.trim();
if (text.isEmpty || isLoading) return;
// Start experiment timer on first message
if (messages.isEmpty) {
_startExperiment();
}
setState(() {
messages.add(ChatMessage(text: text, isUser: true));
isLoading = true;
});
_messageController.clear();
_scrollToBottom();
try {
final response = await _convaiService.sendMessage(text);
setState(() {
messages.add(ChatMessage(text: response, isUser: false));
isLoading = false;
});
if (await _storageService.isSavingEnabled()) {
await _storageService.saveConversation(participantId, text, response);
}
} catch (e) {
setState(() {
messages.add(ChatMessage(text: 'Error: ${e.toString()}', isUser: false));
isLoading = false;
});
}
_scrollToBottom();
}
Future<void> _sendInitialPrompt() async {
// If no initial prompt, just allow typing without sending anything
if (_initialPrompt.trim().isEmpty) {
setState(() {
_initialTurnPending = false;
});
_startExperiment();
return;
}
if (isLoading) return;
setState(() {
isLoading = true;
_initialTurnPending = false;
});
_startExperiment();
try {
final response = await _convaiService.sendMessage(_initialPrompt);
setState(() {
// Do not attribute initial prompt as a user message in the chat transcript
messages.add(ChatMessage(text: response, isUser: false));
isLoading = false;
});
if (await _storageService.isSavingEnabled()) {
await _storageService.saveConversation(participantId, _initialPrompt, response);
}
} catch (e) {
setState(() {
messages.add(ChatMessage(text: 'Error: ${e.toString()}', isUser: false));
isLoading = false;
});
}
_scrollToBottom();
}
void _scrollToBottom() {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (_scrollController.hasClients) {
_scrollController.animateTo(
_scrollController.position.maxScrollExtent,
duration: const Duration(milliseconds: 300),
curve: Curves.easeOut,
);
}
});
}
void _clearChat() async {
final bool? shouldClear = await showDialog<bool>(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: const Text('Clear Chat'),
content: const Text(
'This will clear all messages and start a new session with the character. Are you sure?',
),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(false),
child: const Text('Cancel'),
),
TextButton(
onPressed: () => Navigator.of(context).pop(true),
style: TextButton.styleFrom(
foregroundColor: Colors.red,
),
child: const Text('Clear'),
),
],
);
},
);
if (shouldClear == true) {
setState(() {
messages.clear();
_initialTurnPending = _supervisedMode; // reset gating
_experimentStartTime = null;
_experimentExpired = false;
_timeRemaining = Duration.zero;
});
_experimentTimer?.cancel();
_convaiService.resetSession();
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Chat cleared and new session started'),
duration: Duration(seconds: 2),
),
);
}
}
String _formatDuration(Duration duration) {
String twoDigits(int n) => n.toString().padLeft(2, '0');
final minutes = twoDigits(duration.inMinutes.remainder(60));
final seconds = twoDigits(duration.inSeconds.remainder(60));
return '$minutes:$seconds';
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: const Color(0xFFF8FAFC),
appBar: AppBar(
title: const Text(
'Convai Chat',
style: TextStyle(
fontWeight: FontWeight.w600,
letterSpacing: 1,
),
),
backgroundColor: Colors.white,
elevation: 0,
foregroundColor: const Color(0xFF2D3748),
actions: [
IconButton(
icon: const Icon(Icons.clear_all),
onPressed: _clearChat,
tooltip: 'Clear Chat',
),
IconButton(
icon: const Icon(Icons.settings),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const SettingsScreen(),
),
).then((_) => _loadSettings());
},
tooltip: 'Settings',
),
],
),
body: Column(
children: [
Container(
padding: const EdgeInsets.all(16),
decoration: const BoxDecoration(
color: Colors.white,
border: Border(
bottom: BorderSide(color: Color(0xFFE0E7EF)),
),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
TextField(
controller: _participantController,
onChanged: (value) => participantId = value,
decoration: InputDecoration(
labelText: 'Participant ID',
hintText: 'Enter participant ID for this session',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
borderSide: const BorderSide(color: Color(0xFFCBD5E1)),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
borderSide: const BorderSide(color: Color(0xFF4F8CFF), width: 2),
),
contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
filled: true,
fillColor: const Color(0xFFF8FAFC),
),
),
if (_timedExperiment && _experimentStartTime != null && !_experimentExpired)
Padding(
padding: const EdgeInsets.only(top: 8.0),
child: Row(
children: [
const Icon(Icons.timer, size: 16, color: Color(0xFF4F8CFF)),
const SizedBox(width: 6),
Text(
'Time remaining: ${_formatDuration(_timeRemaining)}',
style: const TextStyle(fontSize: 12, color: Color(0xFF64748B), fontWeight: FontWeight.w500),
),
],
),
),
if (_supervisedMode)
Padding(
padding: const EdgeInsets.only(top: 8.0),
child: Row(
children: [
const Icon(Icons.flag, size: 16, color: Color(0xFF4F8CFF)),
const SizedBox(width: 6),
Expanded(
child: Text(
_initialTurnPending
? 'Supervised Mode: Press "Start Experiment" to begin.'
: 'Supervised Mode: You may now type.',
style: const TextStyle(fontSize: 12, color: Color(0xFF64748B)),
),
),
],
),
),
],
),
),
if (_timedExperiment && _experimentExpired)
Expanded(
child: Container(
margin: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(12),
border: Border.all(color: const Color(0xFFE0E7EF)),
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.05),
blurRadius: 10,
offset: const Offset(0, 2),
),
],
),
child: const Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Icons.timer_off, size: 64, color: Color(0xFF64748B)),
SizedBox(height: 16),
Text(
'Experiment Time Expired',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.w600,
color: Color(0xFF2D3748),
),
),
SizedBox(height: 8),
Text(
'The chat is now hidden as the time limit has been reached.',
style: TextStyle(
fontSize: 14,
color: Color(0xFF64748B),
),
textAlign: TextAlign.center,
),
],
),
),
),
)
else
Expanded(
child: Container(
margin: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(12),
border: Border.all(color: const Color(0xFFE0E7EF)),
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.05),
blurRadius: 10,
offset: const Offset(0, 2),
),
],
),
child: Column(
children: [
Expanded(
child: ListView.builder(
controller: _scrollController,
padding: const EdgeInsets.all(16),
itemCount: messages.length + (isLoading ? 1 : 0),
itemBuilder: (context, index) {
if (index == messages.length && isLoading) {
return const Padding(
padding: EdgeInsets.all(8.0),
child: Row(
children: [
SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(strokeWidth: 2),
),
SizedBox(width: 12),
Text('Thinking...'),
],
),
);
}
final message = messages[index];
return Container(
margin: const EdgeInsets.only(bottom: 8),
child: Row(
mainAxisAlignment: message.isUser
? MainAxisAlignment.end
: MainAxisAlignment.start,
children: [
Container(
constraints: BoxConstraints(
maxWidth: MediaQuery.of(context).size.width * 0.7,
),
padding: const EdgeInsets.symmetric(
horizontal: 16,
vertical: 12,
),
decoration: BoxDecoration(
color: message.isUser
? const Color(0xFF4F8CFF)
: const Color(0xFFF1F5FB),
borderRadius: BorderRadius.circular(16).copyWith(
bottomRight: message.isUser
? const Radius.circular(4)
: const Radius.circular(16),
bottomLeft: message.isUser
? const Radius.circular(16)
: const Radius.circular(4),
),
),
child: Text(
message.text,
style: TextStyle(
color: message.isUser
? Colors.white
: const Color(0xFF2D3748),
fontSize: 16,
height: 1.4,
),
),
),
],
),
);
},
),
),
],
),
),
),
if (!(_timedExperiment && _experimentExpired))
Container(
padding: const EdgeInsets.fromLTRB(16, 0, 16, 16),
child: Row(
children: [
if (_supervisedMode && _initialTurnPending)
Expanded(
child: SizedBox(
height: 48,
child: ElevatedButton.icon(
onPressed: isLoading ? null : _sendInitialPrompt,
icon: const Icon(Icons.play_arrow),
label: const Text('Start Experiment'),
style: ElevatedButton.styleFrom(
backgroundColor: const Color(0xFF4F8CFF),
foregroundColor: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
),
),
),
)
else ...[
Expanded(
child: KeyboardListener(
focusNode: FocusNode(),
onKeyEvent: (KeyEvent event) {
if (event is KeyDownEvent) {
if (event.logicalKey == LogicalKeyboardKey.enter) {
if (!HardwareKeyboard.instance.isShiftPressed) {
_sendMessage();
}
}
}
},
child: TextField(
controller: _messageController,
decoration: InputDecoration(
hintText: 'Type your message... (Enter to send, Shift+Enter for new line)',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(24),
borderSide: const BorderSide(color: Color(0xFFCBD5E1)),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(24),
borderSide: const BorderSide(color: Color(0xFF4F8CFF), width: 2),
),
contentPadding: const EdgeInsets.symmetric(horizontal: 20, vertical: 12),
filled: true,
fillColor: Colors.white,
),
keyboardType: TextInputType.multiline,
maxLines: null,
minLines: 1,
textCapitalization: TextCapitalization.sentences,
),
),
),
const SizedBox(width: 8),
Container(
decoration: const BoxDecoration(
color: Color(0xFF4F8CFF),
shape: BoxShape.circle,
),
child: IconButton(
icon: const Icon(Icons.send, color: Colors.white),
onPressed: isLoading ? null : _sendMessage,
),
),
],
],
),
),
],
),
);
}
@override
void dispose() {
_experimentTimer?.cancel();
_messageController.dispose();
_participantController.dispose();
_scrollController.dispose();
super.dispose();
}
}

View File

@ -0,0 +1,907 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:ai_chat_lab/services/convai_service.dart';
import 'package:ai_chat_lab/services/storage_service.dart';
import 'package:ai_chat_lab/screens/chat_screen.dart';
class SettingsScreen extends StatefulWidget {
const SettingsScreen({super.key});
@override
State<SettingsScreen> createState() => _SettingsScreenState();
}
class _SettingsScreenState extends State<SettingsScreen> {
final TextEditingController _apiKeyController = TextEditingController();
final TextEditingController _characterIdController = TextEditingController();
final TextEditingController _newCharacterController = TextEditingController();
final TextEditingController _characterNameController = TextEditingController();
final TextEditingController _initialPromptController = TextEditingController();
final TextEditingController _newCharacterNameController = TextEditingController();
final TextEditingController _newCharacterPromptController = TextEditingController();
final ConvaiService _convaiService = ConvaiService();
final StorageService _storageService = StorageService();
// DeepL
final TextEditingController _deeplApiKeyController = TextEditingController();
bool _deeplEnabled = false;
bool _deeplUseFreeApi = true;
String _deeplSourceLang = 'AUTO';
String _deeplTargetLang = 'EN';
bool _savingEnabled = false;
bool _supervisedMode = false;
bool _timedExperiment = false;
int _experimentDuration = 5;
List<String> _savedCharacters = [];
Map<String, String> _characterNames = {};
bool _showApiKey = false;
@override
void initState() {
super.initState();
_loadSettings();
}
Future<void> _loadSettings() async {
await _convaiService.loadSettings();
_apiKeyController.text = _convaiService.apiKey;
_characterIdController.text = _convaiService.characterId;
final saving = await _storageService.isSavingEnabled();
final characters = await _convaiService.getSavedCharacters();
final supervised = await _convaiService.isSupervisedModeEnabled();
final timedExperiment = await _convaiService.isTimedExperimentEnabled();
final duration = await _convaiService.getExperimentDurationMinutes();
final names = await _convaiService.getAllCharacterNames();
final selectedPrompt = await _convaiService.getCharacterInitialPrompt(_convaiService.characterId);
final prefs = await SharedPreferences.getInstance();
final deeplEnabled = prefs.getBool('deepl_enabled') ?? false;
final deeplApiKey = prefs.getString('deepl_api_key') ?? '';
final deeplUseFree = prefs.getBool('deepl_use_free') ?? true;
final deeplSource = prefs.getString('deepl_source_lang') ?? 'AUTO';
final deeplTarget = prefs.getString('deepl_target_lang') ?? 'EN';
setState(() {
_savingEnabled = saving;
_savedCharacters = characters;
_supervisedMode = supervised;
_timedExperiment = timedExperiment;
_experimentDuration = duration;
_characterNames = names;
_initialPromptController.text = selectedPrompt;
_deeplEnabled = deeplEnabled;
_deeplApiKeyController.text = deeplApiKey;
_deeplUseFreeApi = deeplUseFree;
_deeplSourceLang = deeplSource;
_deeplTargetLang = deeplTarget;
});
_characterNameController.text = names[_characterIdController.text.trim()] ?? '';
}
Future<void> _applySelectedCharacterChange() async {
final id = _characterIdController.text.trim();
_characterNameController.text = await _convaiService.getCharacterName(id);
_initialPromptController.text = await _convaiService.getCharacterInitialPrompt(id);
setState(() {});
}
void _saveSettings() async {
try {
await _convaiService.saveSettings(
_apiKeyController.text.trim(),
_characterIdController.text.trim(),
);
await _storageService.setSavingEnabled(_savingEnabled);
await _convaiService.setSupervisedModeEnabled(_supervisedMode);
await _convaiService.setTimedExperimentEnabled(_timedExperiment);
await _convaiService.setExperimentDurationMinutes(_experimentDuration);
final prefs = await SharedPreferences.getInstance();
await prefs.setBool('deepl_enabled', _deeplEnabled);
await prefs.setString('deepl_api_key', _deeplApiKeyController.text.trim());
await prefs.setBool('deepl_use_free', _deeplUseFreeApi);
await prefs.setString('deepl_source_lang', _deeplSourceLang.toUpperCase());
await prefs.setString('deepl_target_lang', _deeplTargetLang.toUpperCase());
// Save name/prompt for current character if provided
final currentId = _characterIdController.text.trim();
if (currentId.isNotEmpty) {
await _convaiService.saveCharacter(currentId);
await _convaiService.setCharacterName(currentId, _characterNameController.text.trim());
await _convaiService.setCharacterInitialPrompt(currentId, _initialPromptController.text.trim());
// Reload settings to refresh lists and maps
await _loadSettings();
}
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Settings saved successfully!'),
backgroundColor: Colors.green,
),
);
if (_convaiService.isConfigured) {
Navigator.of(context).pushReplacement(
MaterialPageRoute(builder: (context) => const ChatScreen()),
);
}
}
} catch (e) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Error saving settings: $e'),
backgroundColor: Colors.red,
),
);
}
}
}
void _addCharacter() async {
final characterId = _newCharacterController.text.trim();
final characterName = _newCharacterNameController.text.trim();
final characterPrompt = _newCharacterPromptController.text.trim();
if (characterId.isNotEmpty) {
await _convaiService.saveCharacter(characterId);
if (characterName.isNotEmpty) {
await _convaiService.setCharacterName(characterId, characterName);
}
if (characterPrompt.isNotEmpty) {
await _convaiService.setCharacterInitialPrompt(characterId, characterPrompt);
}
_newCharacterController.clear();
_newCharacterNameController.clear();
_newCharacterPromptController.clear();
_loadSettings();
}
}
void _removeCharacter(String characterId) async {
await _convaiService.removeCharacter(characterId);
_loadSettings();
}
void _selectCharacter(String characterId) async {
setState(() {
_characterIdController.text = characterId;
});
await _applySelectedCharacterChange();
}
Future<void> _editCharacter(String characterId) async {
final existingName = await _convaiService.getCharacterName(characterId);
final existingPrompt = await _convaiService.getCharacterInitialPrompt(characterId);
final idController = TextEditingController(text: characterId);
final nameController = TextEditingController(text: existingName);
final promptController = TextEditingController(text: existingPrompt);
if (!mounted) return;
final bool? saved = await showDialog<bool>(
context: context,
builder: (context) {
return AlertDialog(
title: Text('Edit Avatar', style: const TextStyle(fontWeight: FontWeight.w600)),
content: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
TextField(
controller: idController,
decoration: const InputDecoration(
labelText: 'Character ID',
hintText: 'Unique character ID',
border: OutlineInputBorder(),
),
),
const SizedBox(height: 12),
Align(
alignment: Alignment.centerLeft,
child: const Text('Display Name and Prompt', style: TextStyle(fontSize: 12, color: Color(0xFF64748B))),
),
const SizedBox(height: 12),
TextField(
controller: nameController,
decoration: const InputDecoration(
labelText: 'Name',
hintText: 'e.g., Detective Bot',
border: OutlineInputBorder(),
),
),
const SizedBox(height: 12),
TextField(
controller: promptController,
maxLines: null,
decoration: const InputDecoration(
labelText: 'Initial Prompt',
hintText: 'Optional first-turn prompt (used in Supervised Mode)',
border: OutlineInputBorder(),
),
),
],
),
),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(false),
child: const Text('Cancel'),
),
ElevatedButton(
onPressed: () => Navigator.of(context).pop(true),
child: const Text('Save'),
),
],
);
},
);
if (saved == true) {
final newId = idController.text.trim();
try {
if (newId != characterId) {
await _convaiService.renameCharacterId(characterId, newId);
// Keep selection in form in sync if this was the current selection
if (_characterIdController.text.trim() == characterId) {
_characterIdController.text = newId;
}
characterId = newId;
}
await _convaiService.setCharacterName(characterId, nameController.text.trim());
await _convaiService.setCharacterInitialPrompt(characterId, promptController.text.trim());
await _loadSettings();
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Avatar updated'), backgroundColor: Colors.green),
);
}
} catch (e) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Failed to update: $e'), backgroundColor: Colors.red),
);
}
}
}
}
void _showChatDirectory() async {
final directory = await _storageService.getChatDirectory();
if (mounted) {
showDialog(
context: context,
builder: (context) => AlertDialog(
title: const Text('Chat Files Location'),
content: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text('Chat files are saved in:'),
const SizedBox(height: 8),
Container(
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: Colors.grey[100],
borderRadius: BorderRadius.circular(4),
),
child: SelectableText(
directory,
style: const TextStyle(fontFamily: 'monospace'),
),
),
],
),
actions: [
TextButton(
onPressed: () {
Clipboard.setData(ClipboardData(text: directory));
Navigator.of(context).pop();
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Path copied to clipboard')),
);
},
child: const Text('Copy Path'),
),
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: const Text('Close'),
),
],
),
);
}
}
void _resetAllData() async {
final bool? shouldReset = await showDialog<bool>(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: const Text('Reset All Data'),
content: const Text(
'This will delete all settings, saved characters, and chat files. This action cannot be undone. Are you sure?',
),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(false),
child: const Text('Cancel'),
),
TextButton(
onPressed: () => Navigator.of(context).pop(true),
style: TextButton.styleFrom(
foregroundColor: Colors.red,
),
child: const Text('Reset All'),
),
],
);
},
);
if (shouldReset == true) {
try {
final prefs = await SharedPreferences.getInstance();
await prefs.clear();
_apiKeyController.clear();
_characterIdController.clear();
_newCharacterController.clear();
_characterNameController.clear();
_initialPromptController.clear();
_newCharacterNameController.clear();
_newCharacterPromptController.clear();
setState(() {
_savingEnabled = false;
_supervisedMode = false;
_timedExperiment = false;
_experimentDuration = 5;
_savedCharacters = [];
_characterNames = {};
});
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('All data has been reset'),
backgroundColor: Colors.green,
),
);
}
} catch (e) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Error resetting data: $e'),
backgroundColor: Colors.red,
),
);
}
}
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: const Color(0xFFF8FAFC),
appBar: AppBar(
title: const Text(
'Settings',
style: TextStyle(
fontWeight: FontWeight.w600,
letterSpacing: 1,
),
),
backgroundColor: Colors.white,
elevation: 0,
foregroundColor: const Color(0xFF2D3748),
actions: [
IconButton(
icon: const Icon(Icons.save),
onPressed: _saveSettings,
tooltip: 'Save Settings',
),
],
),
body: SingleChildScrollView(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_buildSection(
'API Configuration',
[
TextField(
controller: _apiKeyController,
obscureText: !_showApiKey,
decoration: InputDecoration(
labelText: 'API Key',
hintText: 'Enter your Convai API key',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
),
suffixIcon: IconButton(
icon: Icon(_showApiKey ? Icons.visibility_off : Icons.visibility),
onPressed: () => setState(() => _showApiKey = !_showApiKey),
),
),
),
const SizedBox(height: 16),
TextField(
controller: _characterIdController,
onChanged: (_) => _applySelectedCharacterChange(),
decoration: InputDecoration(
labelText: 'Current Character ID',
hintText: 'Enter character ID to chat with',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
),
),
),
const SizedBox(height: 12),
TextField(
controller: _characterNameController,
decoration: InputDecoration(
labelText: 'Character Name (for your reference)',
hintText: 'e.g., Detective Bot',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
),
),
),
],
),
const SizedBox(height: 24),
_buildSection(
'Character Management',
[
Row(
children: [
Expanded(
flex: 2,
child: TextField(
controller: _newCharacterController,
decoration: InputDecoration(
labelText: 'New Character ID',
hintText: 'Enter character ID',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
),
),
),
),
const SizedBox(width: 8),
Expanded(
flex: 2,
child: TextField(
controller: _newCharacterNameController,
decoration: InputDecoration(
labelText: 'Name (optional)',
hintText: 'e.g., Detective Bot',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
),
),
),
),
const SizedBox(width: 8),
ElevatedButton(
onPressed: _addCharacter,
style: ElevatedButton.styleFrom(
backgroundColor: const Color(0xFF4F8CFF),
foregroundColor: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
),
),
child: const Text('Add'),
),
],
),
const SizedBox(height: 12),
TextField(
controller: _newCharacterPromptController,
maxLines: null,
decoration: InputDecoration(
labelText: 'Initial Prompt (optional)',
hintText: 'First message sent when using Supervised Mode',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
),
),
),
const SizedBox(height: 16),
if (_savedCharacters.isNotEmpty) ...[
const Text(
'Saved Characters:',
style: TextStyle(
fontWeight: FontWeight.w600,
fontSize: 16,
),
),
const SizedBox(height: 8),
...(_savedCharacters.map((character) => Container(
margin: const EdgeInsets.only(bottom: 8),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(8),
border: Border.all(color: const Color(0xFFE0E7EF)),
),
child: ListTile(
title: Text(
_characterNames[character]?.isNotEmpty == true
? '${_characterNames[character]}'
: character,
style: _characterNames[character]?.isNotEmpty == true
? const TextStyle()
: const TextStyle(fontFamily: 'monospace'),
),
subtitle: _characterNames[character]?.isNotEmpty == true
? Text('ID: $character', style: const TextStyle(fontFamily: 'monospace'))
: null,
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
IconButton(
icon: const Icon(Icons.drive_file_rename_outline, size: 20),
onPressed: () => _editCharacter(character),
tooltip: 'Edit name/prompt',
),
IconButton(
icon: const Icon(Icons.copy, size: 20),
onPressed: () {
Clipboard.setData(ClipboardData(text: character));
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Character ID copied')),
);
},
tooltip: 'Copy ID',
),
IconButton(
icon: const Icon(Icons.play_arrow, size: 20, color: Color(0xFF4F8CFF)),
onPressed: () => _selectCharacter(character),
tooltip: 'Use this character',
),
IconButton(
icon: const Icon(Icons.delete, size: 20, color: Colors.red),
onPressed: () => _removeCharacter(character),
tooltip: 'Remove',
),
],
),
),
)))
],
],
),
const SizedBox(height: 24),
_buildSection(
'Initial Prompt (per character)',
[
TextField(
controller: _initialPromptController,
maxLines: null,
decoration: InputDecoration(
labelText: 'Initial Prompt',
hintText: 'Optional system-style message to send as the first turn when supervised mode is enabled',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
),
),
),
const SizedBox(height: 8),
const Text(
'When Supervised Mode is ON, the first turn will use this prompt and the user must press Start Experiment.',
style: TextStyle(fontSize: 12, color: Color(0xFF64748B)),
),
],
),
const SizedBox(height: 24),
_buildSection(
'Chat Settings',
[
SwitchListTile(
title: const Text('Save Conversations'),
subtitle: const Text('Save chat history to text files'),
value: _savingEnabled,
onChanged: (value) => setState(() => _savingEnabled = value),
tileColor: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
side: const BorderSide(color: Color(0xFFE0E7EF)),
),
),
const SizedBox(height: 8),
SwitchListTile(
title: const Text('DeepL: Save translated copy'),
subtitle: const Text('Create an additional file translated via DeepL'),
value: _deeplEnabled,
onChanged: (value) => setState(() => _deeplEnabled = value),
tileColor: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
side: const BorderSide(color: Color(0xFFE0E7EF)),
),
),
if (_deeplEnabled) ...[
const SizedBox(height: 8),
TextField(
controller: _deeplApiKeyController,
obscureText: true,
decoration: InputDecoration(
labelText: 'DeepL API Key',
hintText: 'Enter your DeepL API key',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
),
),
),
const SizedBox(height: 12),
Row(
children: [
Expanded(
child: DropdownButtonFormField<String>(
value: _deeplSourceLang,
items: _deeplLanguageCodes(includeAuto: true)
.map((code) => DropdownMenuItem(
value: code,
child: Text(code),
))
.toList(),
onChanged: (v) => setState(() => _deeplSourceLang = (v ?? 'AUTO').toUpperCase()),
decoration: InputDecoration(
labelText: 'Source Language',
border: OutlineInputBorder(borderRadius: BorderRadius.circular(8)),
),
),
),
const SizedBox(width: 12),
Expanded(
child: DropdownButtonFormField<String>(
value: _deeplTargetLang,
items: _deeplLanguageCodes()
.where((c) => c != 'AUTO')
.map((code) => DropdownMenuItem(
value: code,
child: Text(code),
))
.toList(),
onChanged: (v) => setState(() => _deeplTargetLang = (v ?? 'EN').toUpperCase()),
decoration: InputDecoration(
labelText: 'Target Language',
border: OutlineInputBorder(borderRadius: BorderRadius.circular(8)),
),
),
),
],
),
const SizedBox(height: 8),
Row(
children: [
Checkbox(
value: _deeplUseFreeApi,
onChanged: (v) => setState(() => _deeplUseFreeApi = v ?? true),
),
const Text('Use api-free.deepl.com (Free tier)'),
],
),
],
SwitchListTile(
title: const Text('Supervised Mode'),
subtitle: const Text('Disable typing for first message; require Start Experiment'),
value: _supervisedMode,
onChanged: (value) => setState(() => _supervisedMode = value),
tileColor: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
side: const BorderSide(color: Color(0xFFE0E7EF)),
),
),
SwitchListTile(
title: const Text('Timed Experiment'),
subtitle: const Text('Hide messages after time limit expires'),
value: _timedExperiment,
onChanged: (value) => setState(() => _timedExperiment = value),
tileColor: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
side: const BorderSide(color: Color(0xFFE0E7EF)),
),
),
if (_timedExperiment) ...[
const SizedBox(height: 16),
Row(
children: [
const Text('Duration:', style: TextStyle(fontWeight: FontWeight.w500)),
const SizedBox(width: 16),
Container(
width: 80,
child: DropdownButtonFormField<int>(
value: _experimentDuration,
decoration: InputDecoration(
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
),
contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
),
items: [1, 2, 3, 5, 10, 15, 20, 30].map((minutes) {
return DropdownMenuItem<int>(
value: minutes,
child: Text('$minutes'),
);
}).toList(),
onChanged: (value) {
if (value != null) {
setState(() => _experimentDuration = value);
}
},
),
),
const SizedBox(width: 8),
const Text('minutes'),
],
),
const SizedBox(height: 8),
const Text(
'Chat will be hidden after the time limit expires from the first message.',
style: TextStyle(fontSize: 12, color: Color(0xFF64748B)),
),
],
if (_savingEnabled) ...[
const SizedBox(height: 16),
ElevatedButton.icon(
onPressed: _showChatDirectory,
icon: const Icon(Icons.folder_open),
label: const Text('Show Chat Files Location'),
style: ElevatedButton.styleFrom(
backgroundColor: Colors.white,
foregroundColor: const Color(0xFF4F8CFF),
side: const BorderSide(color: Color(0xFF4F8CFF)),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
),
),
),
],
],
),
const SizedBox(height: 24),
_buildSection(
'Reset & Data',
[
ElevatedButton.icon(
onPressed: _resetAllData,
icon: const Icon(Icons.warning, color: Colors.white),
label: const Text('Reset All Data'),
style: ElevatedButton.styleFrom(
backgroundColor: Colors.red,
foregroundColor: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
),
),
),
const SizedBox(height: 8),
const Text(
'This will clear all settings, saved characters, and preferences.',
style: TextStyle(
fontSize: 12,
color: Color(0xFF64748B),
),
),
],
),
const SizedBox(height: 24),
_buildSection(
'Information',
[
Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: const Color(0xFFF1F5FB),
borderRadius: BorderRadius.circular(8),
border: Border.all(color: const Color(0xFFE0E7EF)),
),
child: const Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Chat Format:',
style: TextStyle(fontWeight: FontWeight.w600),
),
SizedBox(height: 8),
Text(
'participant: "user message"\nagent: "bot response"',
style: TextStyle(
fontFamily: 'monospace',
fontSize: 12,
),
),
SizedBox(height: 12),
Text(
'Files are saved as: chat_[participantID]_YYYY-MM-DD.txt',
style: TextStyle(fontSize: 12, color: Color(0xFF64748B)),
),
],
),
),
],
),
],
),
),
);
}
Widget _buildSection(String title, List<Widget> children) {
return Container(
width: double.infinity,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(12),
border: Border.all(color: const Color(0xFFE0E7EF)),
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.05),
blurRadius: 10,
offset: const Offset(0, 2),
),
],
),
child: Padding(
padding: const EdgeInsets.all(20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
title,
style: const TextStyle(
fontSize: 18,
fontWeight: FontWeight.w600,
color: Color(0xFF2D3748),
),
),
const SizedBox(height: 16),
...children,
],
),
),
);
}
@override
void dispose() {
_apiKeyController.dispose();
_characterIdController.dispose();
_newCharacterController.dispose();
_characterNameController.dispose();
_initialPromptController.dispose();
_newCharacterNameController.dispose();
_newCharacterPromptController.dispose();
_deeplApiKeyController.dispose();
super.dispose();
}
List<String> _deeplLanguageCodes({bool includeAuto = false}) {
// List of DeepL supported target codes (as of 2024-2025). Keep concise.
final codes = <String>[
'BG','CS','DA','DE','EL','EN','ES','ET','FI','FR','HU','ID','IT','JA','KO','LT','LV','NB','NL','PL','PT','RO','RU','SK','SL','SV','TR','UK','ZH'
];
if (includeAuto) return ['AUTO', ...codes];
return codes;
}
}

View File

@ -0,0 +1,311 @@
import 'package:flutter/material.dart';
import 'package:ai_chat_lab/services/convai_service.dart';
import 'package:ai_chat_lab/screens/chat_screen.dart';
class SetupScreen extends StatefulWidget {
const SetupScreen({super.key});
@override
State<SetupScreen> createState() => _SetupScreenState();
}
class _SetupScreenState extends State<SetupScreen> {
final TextEditingController _apiKeyController = TextEditingController();
final TextEditingController _characterIdController = TextEditingController();
final ConvaiService _convaiService = ConvaiService();
bool _showApiKey = false;
bool _isLoading = false;
void _completeSetup() async {
final apiKey = _apiKeyController.text.trim();
final characterId = _characterIdController.text.trim();
if (apiKey.isEmpty) {
_showError('Please enter your API key');
return;
}
if (characterId.isEmpty) {
_showError('Please enter a character ID');
return;
}
setState(() => _isLoading = true);
try {
// Save settings
await _convaiService.saveSettings(apiKey, characterId);
// Save the character to the character management list
await _convaiService.saveCharacter(characterId);
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Setup completed successfully!'),
backgroundColor: Colors.green,
),
);
// Navigate to chat screen
Navigator.of(context).pushReplacement(
MaterialPageRoute(builder: (context) => const ChatScreen()),
);
}
} catch (e) {
_showError('Error saving settings: $e');
} finally {
if (mounted) {
setState(() => _isLoading = false);
}
}
}
void _showError(String message) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(message),
backgroundColor: Colors.red,
),
);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: const Color(0xFFF8FAFC),
body: SafeArea(
child: SingleChildScrollView(
padding: const EdgeInsets.all(24),
child: Column(
children: [
// Welcome Header
Container(
width: 120,
height: 120,
decoration: BoxDecoration(
gradient: const LinearGradient(
colors: [Color(0xFF4F8CFF), Color(0xFF6366F1)],
begin: Alignment.topLeft,
end: Alignment.bottomRight,
),
borderRadius: BorderRadius.circular(60),
boxShadow: [
BoxShadow(
color: const Color(0xFF4F8CFF).withOpacity(0.3),
blurRadius: 20,
offset: const Offset(0, 10),
),
],
),
child: const Icon(
Icons.chat_bubble_outline,
size: 60,
color: Colors.white,
),
),
const SizedBox(height: 32),
const Text(
'Welcome to AI Chat Lab!',
style: TextStyle(
fontSize: 28,
fontWeight: FontWeight.bold,
color: Color(0xFF2D3748),
),
textAlign: TextAlign.center,
),
const SizedBox(height: 32),
// Setup Form
Container(
width: double.infinity,
padding: const EdgeInsets.all(24),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(16),
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.1),
blurRadius: 20,
offset: const Offset(0, 4),
),
],
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'Step 1: API Key',
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.w600,
color: Color(0xFF2D3748),
),
),
const SizedBox(height: 8),
const Text(
'Get your API key from convai.com',
style: TextStyle(
fontSize: 14,
color: Color(0xFF64748B),
),
),
const SizedBox(height: 16),
TextField(
controller: _apiKeyController,
obscureText: !_showApiKey,
decoration: InputDecoration(
labelText: 'Convai API Key',
hintText: 'Enter your API key',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide: const BorderSide(color: Color(0xFFE0E7EF)),
),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide: const BorderSide(color: Color(0xFFE0E7EF)),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide: const BorderSide(color: Color(0xFF4F8CFF), width: 2),
),
suffixIcon: IconButton(
icon: Icon(
_showApiKey ? Icons.visibility_off : Icons.visibility,
color: const Color(0xFF64748B),
),
onPressed: () => setState(() => _showApiKey = !_showApiKey),
),
),
),
const SizedBox(height: 24),
const Text(
'Step 2: Choose a Character',
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.w600,
color: Color(0xFF2D3748),
),
),
const SizedBox(height: 8),
const Text(
'Find character IDs in your Convai dashboard',
style: TextStyle(
fontSize: 14,
color: Color(0xFF64748B),
),
),
const SizedBox(height: 16),
TextField(
controller: _characterIdController,
decoration: InputDecoration(
labelText: 'Character ID',
hintText: 'Enter character ID to chat with',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide: const BorderSide(color: Color(0xFFE0E7EF)),
),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide: const BorderSide(color: Color(0xFFE0E7EF)),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide: const BorderSide(color: Color(0xFF4F8CFF), width: 2),
),
),
),
],
),
),
const SizedBox(height: 24),
// Help Section
Container(
width: double.infinity,
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: const Color(0xFF4F8CFF).withOpacity(0.1),
borderRadius: BorderRadius.circular(12),
border: Border.all(color: const Color(0xFF4F8CFF).withOpacity(0.3)),
),
child: Row(
children: [
Container(
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: const Color(0xFF4F8CFF),
borderRadius: BorderRadius.circular(8),
),
child: const Icon(
Icons.lightbulb_outline,
color: Colors.white,
size: 20,
),
),
const SizedBox(width: 12),
const Expanded(
child: Text(
'Visit convai.com to create your account and get your API key. You can change these settings anytime later.',
style: TextStyle(
fontSize: 14,
color: Color(0xFF4A5568),
),
),
),
],
),
),
const SizedBox(height: 32),
// Continue Button
SizedBox(
width: double.infinity,
height: 56,
child: ElevatedButton(
onPressed: _isLoading ? null : _completeSetup,
style: ElevatedButton.styleFrom(
backgroundColor: const Color(0xFF4F8CFF),
foregroundColor: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
),
elevation: 0,
),
child: _isLoading
? const SizedBox(
width: 24,
height: 24,
child: CircularProgressIndicator(
strokeWidth: 2,
valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
),
)
: const Text(
'Start Chatting',
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.w600,
),
),
),
),
],
),
),
),
);
}
@override
void dispose() {
_apiKeyController.dispose();
_characterIdController.dispose();
super.dispose();
}
}

View File

@ -0,0 +1,102 @@
import 'package:flutter/material.dart';
import 'package:ai_chat_lab/screens/chat_screen.dart';
import 'package:ai_chat_lab/screens/setup_screen.dart';
import 'package:ai_chat_lab/services/convai_service.dart';
class StartupScreen extends StatefulWidget {
const StartupScreen({super.key});
@override
State<StartupScreen> createState() => _StartupScreenState();
}
class _StartupScreenState extends State<StartupScreen> {
final ConvaiService _convaiService = ConvaiService();
bool _isLoading = true;
@override
void initState() {
super.initState();
_checkConfiguration();
}
void _checkConfiguration() async {
await _convaiService.loadSettings();
setState(() {
_isLoading = false;
});
// Navigate to appropriate screen
if (mounted) {
if (_convaiService.isConfigured) {
Navigator.of(context).pushReplacement(
MaterialPageRoute(builder: (context) => const ChatScreen()),
);
} else {
Navigator.of(context).pushReplacement(
MaterialPageRoute(builder: (context) => const SetupScreen()),
);
}
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: const Color(0xFFF8FAFC),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
width: 120,
height: 120,
decoration: BoxDecoration(
color: const Color(0xFF4F8CFF),
borderRadius: BorderRadius.circular(20),
boxShadow: [
BoxShadow(
color: const Color(0xFF4F8CFF).withOpacity(0.3),
blurRadius: 20,
offset: const Offset(0, 10),
),
],
),
child: const Icon(
Icons.chat_bubble_outline,
size: 60,
color: Colors.white,
),
),
const SizedBox(height: 32),
const Text(
'Convai Chat',
style: TextStyle(
fontSize: 28,
fontWeight: FontWeight.w600,
color: Color(0xFF2D3748),
letterSpacing: 1,
),
),
const SizedBox(height: 16),
if (_isLoading) ...[
const SizedBox(height: 32),
const CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation<Color>(Color(0xFF4F8CFF)),
),
const SizedBox(height: 16),
const Text(
'Loading...',
style: TextStyle(
color: Color(0xFF64748B),
fontSize: 16,
),
),
],
],
),
),
);
}
}

View File

@ -0,0 +1,252 @@
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';
class ConvaiService {
static const String _baseUrl = 'https://api.convai.com/character/getResponse';
String _apiKey = '';
String _characterId = '';
String _sessionId = '-1';
// Remove default values for security - users must set their own
static const String defaultApiKey = '';
static const String defaultCharacterId = '';
Future<void> loadSettings() async {
final prefs = await SharedPreferences.getInstance();
_apiKey = prefs.getString('api_key') ?? defaultApiKey;
_characterId = prefs.getString('character_id') ?? defaultCharacterId;
}
Future<void> saveSettings(String apiKey, String characterId) async {
final prefs = await SharedPreferences.getInstance();
await prefs.setString('api_key', apiKey);
await prefs.setString('character_id', characterId);
_apiKey = apiKey;
_characterId = characterId;
}
String get apiKey => _apiKey;
String get characterId => _characterId;
bool get isConfigured => _apiKey.isNotEmpty && _characterId.isNotEmpty;
void resetSession() {
_sessionId = '-1';
}
Future<String> sendMessage(String userText) async {
if (_apiKey.isEmpty || _characterId.isEmpty) {
throw Exception('API key or Character ID not set. Please check settings.');
}
try {
final request = http.MultipartRequest('POST', Uri.parse(_baseUrl));
// Add headers
request.headers['CONVAI-API-KEY'] = _apiKey;
// Add form fields
request.fields['userText'] = userText;
request.fields['charID'] = _characterId;
request.fields['sessionID'] = _sessionId;
request.fields['voiceResponse'] = 'False';
final streamedResponse = await request.send();
final response = await http.Response.fromStream(streamedResponse);
if (response.statusCode == 200) {
final data = json.decode(response.body);
_sessionId = data['sessionID'] ?? _sessionId;
return data['text'] ?? 'No response received';
} else {
throw Exception('HTTP ${response.statusCode}: ${response.reasonPhrase}');
}
} catch (e) {
throw Exception('Failed to send message: $e');
}
}
// Get list of saved character IDs
Future<List<String>> getSavedCharacters() async {
final prefs = await SharedPreferences.getInstance();
return prefs.getStringList('saved_characters') ?? [];
}
// Save a new character ID
Future<void> saveCharacter(String characterId) async {
final prefs = await SharedPreferences.getInstance();
final characters = await getSavedCharacters();
if (!characters.contains(characterId)) {
characters.add(characterId);
await prefs.setStringList('saved_characters', characters);
}
}
// Remove a character ID
Future<void> removeCharacter(String characterId) async {
final prefs = await SharedPreferences.getInstance();
final characters = await getSavedCharacters();
characters.remove(characterId);
await prefs.setStringList('saved_characters', characters);
// Clean up name and initial prompt entries for this character
final names = await _getCharacterNamesMap();
if (names.remove(characterId) != null) {
await _setCharacterNamesMap(names);
}
final prompts = await _getCharacterInitialPromptsMap();
if (prompts.remove(characterId) != null) {
await _setCharacterInitialPromptsMap(prompts);
}
}
// Rename an existing character ID and migrate associated name and initial prompt
Future<void> renameCharacterId(String oldCharacterId, String newCharacterId) async {
final oldId = oldCharacterId.trim();
final newId = newCharacterId.trim();
if (newId.isEmpty) {
throw Exception('New character ID cannot be empty');
}
if (oldId == newId) return;
final prefs = await SharedPreferences.getInstance();
final characters = await getSavedCharacters();
if (!characters.contains(oldId)) {
throw Exception('Character not found');
}
if (characters.contains(newId)) {
throw Exception('A character with this ID already exists');
}
// Replace in list preserving order
final index = characters.indexOf(oldId);
characters[index] = newId;
await prefs.setStringList('saved_characters', characters);
// Migrate name
final names = await _getCharacterNamesMap();
if (names.containsKey(oldId)) {
names[newId] = names[oldId] ?? '';
names.remove(oldId);
await _setCharacterNamesMap(names);
}
// Migrate initial prompt
final prompts = await _getCharacterInitialPromptsMap();
if (prompts.containsKey(oldId)) {
prompts[newId] = prompts[oldId] ?? '';
prompts.remove(oldId);
await _setCharacterInitialPromptsMap(prompts);
}
// Update current configured character if it matches
if (_characterId == oldId) {
await prefs.setString('character_id', newId);
_characterId = newId;
}
}
// Character names management
Future<Map<String, String>> _getCharacterNamesMap() async {
final prefs = await SharedPreferences.getInstance();
final raw = prefs.getString('character_names_json');
if (raw == null || raw.isEmpty) return {};
try {
final decoded = json.decode(raw) as Map<String, dynamic>;
return decoded.map((k, v) => MapEntry(k, v?.toString() ?? ''));
} catch (_) {
return {};
}
}
Future<void> _setCharacterNamesMap(Map<String, String> map) async {
final prefs = await SharedPreferences.getInstance();
await prefs.setString('character_names_json', json.encode(map));
}
Future<String> getCharacterName(String characterId) async {
final map = await _getCharacterNamesMap();
return map[characterId] ?? '';
}
Future<void> setCharacterName(String characterId, String name) async {
final map = await _getCharacterNamesMap();
if (name.isEmpty) {
map.remove(characterId);
} else {
map[characterId] = name;
}
await _setCharacterNamesMap(map);
}
Future<Map<String, String>> getAllCharacterNames() async {
return _getCharacterNamesMap();
}
// Character initial prompts management
Future<Map<String, String>> _getCharacterInitialPromptsMap() async {
final prefs = await SharedPreferences.getInstance();
final raw = prefs.getString('character_initial_prompts_json');
if (raw == null || raw.isEmpty) return {};
try {
final decoded = json.decode(raw) as Map<String, dynamic>;
return decoded.map((k, v) => MapEntry(k, v?.toString() ?? ''));
} catch (_) {
return {};
}
}
Future<void> _setCharacterInitialPromptsMap(Map<String, String> map) async {
final prefs = await SharedPreferences.getInstance();
await prefs.setString('character_initial_prompts_json', json.encode(map));
}
Future<String> getCharacterInitialPrompt(String characterId) async {
final map = await _getCharacterInitialPromptsMap();
return map[characterId] ?? '';
}
Future<void> setCharacterInitialPrompt(String characterId, String prompt) async {
final map = await _getCharacterInitialPromptsMap();
if (prompt.isEmpty) {
map.remove(characterId);
} else {
map[characterId] = prompt;
}
await _setCharacterInitialPromptsMap(map);
}
// Supervised mode
Future<bool> isSupervisedModeEnabled() async {
final prefs = await SharedPreferences.getInstance();
return prefs.getBool('supervised_mode') ?? false;
}
Future<void> setSupervisedModeEnabled(bool enabled) async {
final prefs = await SharedPreferences.getInstance();
await prefs.setBool('supervised_mode', enabled);
}
// Timed experiment settings
Future<bool> isTimedExperimentEnabled() async {
final prefs = await SharedPreferences.getInstance();
return prefs.getBool('timed_experiment_enabled') ?? false;
}
Future<void> setTimedExperimentEnabled(bool enabled) async {
final prefs = await SharedPreferences.getInstance();
await prefs.setBool('timed_experiment_enabled', enabled);
}
Future<int> getExperimentDurationMinutes() async {
final prefs = await SharedPreferences.getInstance();
return prefs.getInt('experiment_duration_minutes') ?? 5;
}
Future<void> setExperimentDurationMinutes(int minutes) async {
final prefs = await SharedPreferences.getInstance();
await prefs.setInt('experiment_duration_minutes', minutes);
}
}

View File

@ -0,0 +1,50 @@
import 'dart:convert';
import 'package:http/http.dart' as http;
class DeepLService {
Future<String?> translateText({
required String apiKey,
required String text,
required String targetLang,
String sourceLang = 'AUTO',
bool useFreeApi = true,
}) async {
if (apiKey.isEmpty || text.trim().isEmpty) return null;
final base = useFreeApi ? 'https://api-free.deepl.com' : 'https://api.deepl.com';
final uri = Uri.parse('$base/v2/translate');
try {
final response = await http.post(
uri,
headers: {
'Authorization': 'DeepL-Auth-Key $apiKey',
'Content-Type': 'application/x-www-form-urlencoded',
},
body: {
'text': text,
'target_lang': targetLang,
if (sourceLang.isNotEmpty && sourceLang.toUpperCase() != 'AUTO')
'source_lang': sourceLang,
'preserve_formatting': '1',
},
);
if (response.statusCode == 200) {
final jsonBody = json.decode(utf8.decode(response.bodyBytes));
final translations = jsonBody['translations'] as List<dynamic>?;
if (translations != null && translations.isNotEmpty) {
return translations.first['text']?.toString();
}
return null;
} else {
// Swallow errors and return null to avoid blocking the main save flow
return null;
}
} catch (_) {
return null;
}
}
}

View File

@ -0,0 +1,97 @@
import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:ai_chat_lab/services/deepl_service.dart';
class StorageService {
Future<bool> isSavingEnabled() async {
final prefs = await SharedPreferences.getInstance();
return prefs.getBool('save_conversations') ?? false;
}
Future<void> setSavingEnabled(bool enabled) async {
final prefs = await SharedPreferences.getInstance();
await prefs.setBool('save_conversations', enabled);
}
Future<void> saveConversation(String participantId, String userMessage, String agentResponse) async {
if (!await isSavingEnabled()) return;
try {
final directory = await getApplicationDocumentsDirectory();
final chatDir = Directory('${directory.path}/convai_chats');
if (!await chatDir.exists()) {
await chatDir.create(recursive: true);
}
final timestamp = DateTime.now();
final dateStr = '${timestamp.year}-${timestamp.month.toString().padLeft(2, '0')}-${timestamp.day.toString().padLeft(2, '0')}';
final baseName = 'chat_${participantId.isNotEmpty ? participantId : 'default'}_$dateStr';
final file = File('${chatDir.path}/$baseName.txt');
final timeStr = '${timestamp.hour.toString().padLeft(2, '0')}:${timestamp.minute.toString().padLeft(2, '0')}:${timestamp.second.toString().padLeft(2, '0')}';
final entry = '\n[$timeStr]\nparticipant: "$userMessage"\nagent: "$agentResponse"\n';
await file.writeAsString(entry, mode: FileMode.append);
// Also save DeepL-translated variant if enabled/configured
final prefs = await SharedPreferences.getInstance();
final deeplEnabled = prefs.getBool('deepl_enabled') ?? false;
final deeplApiKey = prefs.getString('deepl_api_key') ?? '';
final deeplUseFree = prefs.getBool('deepl_use_free') ?? true;
final deeplTargetLang = (prefs.getString('deepl_target_lang') ?? 'EN').toUpperCase();
final deeplSourceLang = (prefs.getString('deepl_source_lang') ?? 'AUTO').toUpperCase();
if (deeplEnabled && deeplApiKey.isNotEmpty) {
final deepl = DeepLService();
final translatedUser = await deepl.translateText(
apiKey: deeplApiKey,
text: userMessage,
targetLang: deeplTargetLang,
sourceLang: deeplSourceLang,
useFreeApi: deeplUseFree,
);
final translatedAgent = await deepl.translateText(
apiKey: deeplApiKey,
text: agentResponse,
targetLang: deeplTargetLang,
sourceLang: deeplSourceLang,
useFreeApi: deeplUseFree,
);
if ((translatedUser ?? '').isNotEmpty || (translatedAgent ?? '').isNotEmpty) {
final translatedFile = File('${chatDir.path}/$baseName.${deeplTargetLang.toLowerCase()}.txt');
final entryTranslated = '\n[$timeStr]\nparticipant: "${translatedUser ?? userMessage}"\nagent: "${translatedAgent ?? agentResponse}"\n';
await translatedFile.writeAsString(entryTranslated, mode: FileMode.append);
}
}
} catch (e) {
print('Error saving conversation: $e');
}
}
Future<List<File>> getChatFiles() async {
try {
final directory = await getApplicationDocumentsDirectory();
final chatDir = Directory('${directory.path}/convai_chats');
if (!await chatDir.exists()) {
return [];
}
final files = await chatDir.list().where((entity) => entity is File && entity.path.endsWith('.txt')).cast<File>().toList();
files.sort((a, b) => b.lastModifiedSync().compareTo(a.lastModifiedSync()));
return files;
} catch (e) {
print('Error getting chat files: $e');
return [];
}
}
Future<String> getChatDirectory() async {
final directory = await getApplicationDocumentsDirectory();
return '${directory.path}/convai_chats';
}
}