Files
hub/frontend/lib/agent_list_screen.dart
T

201 lines
7.6 KiB
Dart

import 'package:flutter/material.dart';
import 'backend.dart';
import 'chat_screen.dart';
import 'agent_screen.dart';
class AgentEntry {
final int id;
final String name;
AgentEntry({required this.id, required this.name});
}
class AgentListScreen extends StatelessWidget {
const AgentListScreen({super.key});
static Future<List<AgentEntry>> getChats() async {
final response = await Backend.sendAction("get-agents", {});
List<dynamic> chatObjects = response['agents'];
List<AgentEntry> chats = chatObjects
.map((msg) => AgentEntry(
id: msg['id'],
name: msg['name']?.isNotEmpty == true ? msg['name'] : '[Agent ${msg['id']}]',
))
.toList();
return chats;
}
static Future<List<String>> getAgentKinds() async {
final response = await Backend.sendAction("get-agent-kinds", {});
return response['kinds'];
}
// Function to create a new agent and navigate
Future<void> createAgent(BuildContext context, String name, String kind) async {
try {
// Pass the 'kind' to the backend as well
final response = await Backend.sendAction("create-agent", {"name": name, "kind": kind});
final int newAgentId = response['agentId']; // Assuming your backend returns the new agent's ID
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Agent $name created.')),
);
// Navigate to the new agent's chat screen
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => AgentScreen(agentId: newAgentId),
),
);
}
} catch (e) {
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Failed to create agent: $e')),
);
}
}
}
// Function to show the create agent dialog
void _showCreateAgentDialog(BuildContext context) {
TextEditingController usernameController = TextEditingController();
String? selectedKind; // To hold the selected kind value
showDialog(
context: context,
builder: (BuildContext dialogContext) {
return AlertDialog(
title: const Text('Create New Agent'),
content: SingleChildScrollView( // Use SingleChildScrollView to prevent overflow
child: ListBody(
children: <Widget>[
TextField(
controller: usernameController,
decoration: const InputDecoration(hintText: "Enter agent name"),
),
const SizedBox(height: 16.0), // Spacing between fields
FutureBuilder<List<String>>(
future: getAgentKinds(), // Call the asynchronous function to get kinds
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const Center(child: CircularProgressIndicator());
} else if (snapshot.hasError) {
return Center(child: Text('Error loading kinds: ${snapshot.error}'));
} else if (!snapshot.hasData || snapshot.data!.isEmpty) {
return const Center(child: Text('No agent kinds available.'));
} else {
final kinds = snapshot.data!;
// Ensure a default selection if none is made, or allow null
if (selectedKind == null && kinds.isNotEmpty) {
selectedKind = kinds.first; // Set the first item as default
}
return StatefulBuilder( // Use StatefulBuilder to update dropdown state
builder: (context, setState) {
return DropdownButtonFormField<String>(
value: selectedKind,
hint: const Text('Select Kind'),
decoration: const InputDecoration(
labelText: 'Kind',
border: OutlineInputBorder(),
),
items: kinds.map((String kind) {
return DropdownMenuItem<String>(
value: kind,
child: Text(kind),
);
}).toList(),
onChanged: (String? newValue) {
setState(() {
selectedKind = newValue;
});
},
);
},
);
}
},
),
],
),
),
actions: <Widget>[
TextButton(
child: const Text('Cancel'),
onPressed: () {
Navigator.of(dialogContext).pop(); // Dismiss the dialog
},
),
TextButton(
child: const Text('Create'),
onPressed: () {
if (usernameController.text.isNotEmpty && selectedKind != null) {
Navigator.of(dialogContext).pop(); // Dismiss the dialog first
createAgent(context, usernameController.text, selectedKind!); // Pass selectedKind
} else {
if (dialogContext.mounted) {
ScaffoldMessenger.of(dialogContext).showSnackBar(
const SnackBar(content: Text('Agent name and kind cannot be empty')),
);
}
}
},
),
],
);
},
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Agents')),
body: Column(
children: [
ListTile(
leading: const Icon(Icons.add),
title: const Text('Create'),
onTap: () => _showCreateAgentDialog(context), // Open the dialog
),
const Divider(height: 1),
Expanded(
child: FutureBuilder<List<AgentEntry>>(
future: getChats(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const Center(child: CircularProgressIndicator());
} else if (snapshot.hasError) {
return Center(child: Text('Error: ${snapshot.error}'));
} else if (!snapshot.hasData || snapshot.data!.isEmpty) {
return const Center(child: Text('No agents available.'));
} else {
final agents = snapshot.data!;
return ListView.builder(
itemCount: agents.length,
itemBuilder: (context, index) {
final agent = agents[index];
return ListTile(
title: Text(agent.name),
onTap: () {
print("Navigate to agent ${agent.id}");
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => AgentScreen(agentId: agent.id),
),
);
},
);
},
);
}
},
),
),
],
),
);
}
}