Files

1145 lines
36 KiB
Dart
Raw Permalink Normal View History

// The project knowledge tab: notes, todos and plans stored by the server in
// the project context (`/api/project-context`), with search across all three.
import 'package:flutter/material.dart';
import '../api/client.dart';
import '../api/models.dart';
import '../state.dart';
import '../widgets/markdown_view.dart';
import '../l10n.dart';
class KnowledgePanel extends StatefulWidget {
final AppState app;
final String directory;
const KnowledgePanel({super.key, required this.app, required this.directory});
@override
State<KnowledgePanel> createState() => _KnowledgePanelState();
}
class _KnowledgePanelState extends State<KnowledgePanel> {
ProjectContext? _context;
/// Null when the server has agent memory switched off, in which case the
/// memory section is not offered at all.
AgentMemorySnapshot? _memory;
bool _loading = true;
String? _error;
String _section = 'notes';
String _query = '';
final TextEditingController _search = TextEditingController();
String get _projectId => Client.projectIdFor(widget.directory);
Client? get _client => widget.app.client;
@override
void initState() {
super.initState();
_load();
}
@override
void dispose() {
_search.dispose();
super.dispose();
}
Future<void> _load() async {
final client = _client;
if (client == null || _projectId.isEmpty) {
setState(() {
_loading = false;
_error = tr('This session has no directory');
});
return;
}
setState(() {
_loading = true;
_error = null;
});
try {
// Both reads in one go: the memory tab appears with the rest instead of
// popping in a moment later.
final results = await Future.wait([
client.projectContext(_projectId, directory: widget.directory),
client.agentMemory(_projectId, directory: widget.directory),
]);
if (!mounted) return;
final context = results[0] as ProjectContext;
final memory = results[1] as AgentMemorySnapshot?;
setState(() {
_context = context;
_memory = memory;
if (memory == null && _section == 'memory') _section = 'notes';
_loading = false;
});
} catch (error) {
if (!mounted) return;
setState(() {
_loading = false;
_error = '$error';
});
}
}
/// Applies a mutation's fresh context without a second round trip.
void _apply(ProjectContext context) {
if (!mounted) return;
setState(() => _context = context);
}
void _fail(Object error) {
if (!mounted) return;
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text('$error')));
}
bool _matches(Iterable<String> fields) {
final query = _query.trim().toLowerCase();
if (query.isEmpty) return true;
return fields.any((field) => field.toLowerCase().contains(query));
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return Column(
children: [
Padding(
padding: const EdgeInsets.fromLTRB(12, 6, 4, 0),
child: Row(
children: [
Expanded(
child: TextField(
controller: _search,
onChanged: (value) => setState(() => _query = value),
style: const TextStyle(fontSize: 13),
decoration: InputDecoration(
isDense: true,
hintText: _memory == null
? tr('Search notes, todos, and plans')
: tr('Search notes, todos, plans, and memory'),
prefixIcon: const Icon(Icons.search, size: 18),
suffixIcon: _query.isEmpty
? null
: IconButton(
icon: const Icon(Icons.close, size: 16),
onPressed: () {
_search.clear();
setState(() => _query = '');
},
),
border:
OutlineInputBorder(borderRadius: BorderRadius.circular(8)),
),
),
),
IconButton(
tooltip: tr('Refresh'),
visualDensity: VisualDensity.compact,
icon: const Icon(Icons.refresh, size: 20),
onPressed: _load,
),
],
),
),
_sections(theme),
Expanded(child: _body(theme)),
],
);
}
List<(String, String, int)> get _sectionsList {
final context = _context;
return [
('notes', tr('Notes'), context?.notes.length ?? 0),
('todos', tr('Todos'), context?.todos.length ?? 0),
('plans', tr('Plans'), context?.plans.length ?? 0),
if (_memory != null)
('memory', tr('Memory'),
(_memory!.global.length + _memory!.project.length)),
];
}
Widget _sections(ThemeData theme) {
final sections = _sectionsList;
return Padding(
padding: const EdgeInsets.fromLTRB(12, 8, 12, 6),
child: SegmentedButton<String>(
showSelectedIcon: false,
style: const ButtonStyle(
visualDensity: VisualDensity.compact,
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
),
segments: [
for (final (key, label, count) in sections)
ButtonSegment(value: key, label: AppText('$label $count')),
],
selected: {_section},
onSelectionChanged: (value) => setState(() => _section = value.first),
),
);
}
Widget _body(ThemeData theme) {
if (_loading) return const Center(child: CircularProgressIndicator());
if (_error != null) {
return Center(
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(_error!,
textAlign: TextAlign.center,
style: TextStyle(color: theme.colorScheme.error, fontSize: 13)),
const SizedBox(height: 8),
FilledButton(onPressed: _load, child: const AppText('Retry')),
],
),
),
);
}
switch (_section) {
case 'todos':
return _todos(theme);
case 'plans':
return _plans(theme);
case 'memory':
return _memoryBody(theme);
default:
return _notes(theme);
}
}
// --------------------------------------------------------------- notes
Widget _notes(ThemeData theme) {
final notes = (_context?.notes ?? [])
.where((note) => _matches([note.body]))
.toList()
..sort((a, b) {
if (a.pinned != b.pinned) return a.pinned ? -1 : 1;
return b.updatedAt.compareTo(a.updatedAt);
});
return Column(
children: [
_sectionHeader(theme, trArgs('{0} notes', [notes.length]),
'New note', _addNote),
Expanded(
child: notes.isEmpty
? _empty(theme, Icons.sticky_note_2_outlined,
_query.isEmpty ? 'No notes yet' : 'No matching notes')
: ListView.builder(
padding: const EdgeInsets.fromLTRB(12, 0, 12, 12),
itemCount: notes.length,
itemBuilder: (context, index) {
final note = notes[index];
return _noteCard(theme, note);
},
),
),
],
);
}
Widget _noteCard(ThemeData theme, ProjectNote note) {
final scheme = theme.colorScheme;
return Card(
margin: const EdgeInsets.only(bottom: 8),
child: InkWell(
borderRadius: BorderRadius.circular(12),
onTap: () => _editNote(note),
child: Padding(
padding: const EdgeInsets.fromLTRB(12, 8, 4, 8),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
note.body.trim(),
maxLines: 5,
overflow: TextOverflow.ellipsis,
style: const TextStyle(fontSize: 13.5, height: 1.35),
),
const SizedBox(height: 4),
Row(
children: [
if (note.pinned)
Padding(
padding: const EdgeInsets.only(right: 4),
child: Icon(Icons.push_pin,
size: 12, color: scheme.primary),
),
Text(
_stamp(note.updatedAt),
style:
TextStyle(fontSize: 11, color: theme.hintColor),
),
],
),
],
),
),
PopupMenuButton<String>(
icon: const Icon(Icons.more_vert, size: 18),
onSelected: (value) async {
final client = _client;
if (client == null) return;
try {
switch (value) {
case 'edit':
await _editNote(note);
break;
case 'pin':
_apply(await client.updateNote(
_projectId, note.id,
pinned: !note.pinned, directory: widget.directory));
break;
case 'delete':
_apply(await client.deleteNote(_projectId, note.id,
directory: widget.directory));
break;
}
} catch (error) {
_fail(error);
}
},
itemBuilder: (_) => [
const PopupMenuItem(value: 'edit', child: AppText('Edit')),
PopupMenuItem(
value: 'pin', child: AppText(note.pinned ? 'Unpin' : 'Pin')),
const PopupMenuItem(value: 'delete', child: AppText('Delete')),
],
),
],
),
),
),
);
}
// --------------------------------------------------------------- todos
Widget _todos(ThemeData theme) {
final todos = (_context?.todos ?? [])
.where((todo) => _matches([todo.text]))
.toList();
final done = todos.where((todo) => todo.completed).length;
return Column(
children: [
_sectionHeader(theme, trArgs('{0}/{1} done', [done, todos.length]),
'New todo', _addTodo),
Expanded(
child: todos.isEmpty
? _empty(theme, Icons.checklist,
_query.isEmpty ? 'No todos yet' : 'No matching todos')
: ListView.builder(
padding: const EdgeInsets.fromLTRB(8, 0, 8, 12),
itemCount: todos.length,
itemBuilder: (context, index) {
final todo = todos[index];
return CheckboxListTile(
dense: true,
value: todo.completed,
onChanged: (value) => _toggleTodo(todo, value ?? false),
controlAffinity: ListTileControlAffinity.leading,
title: AppText(
todo.text,
style: TextStyle(
fontSize: 13.5,
decoration: todo.completed
? TextDecoration.lineThrough
: null,
color: todo.completed ? theme.hintColor : null,
),
),
secondary: PopupMenuButton<String>(
icon: const Icon(Icons.more_vert, size: 18),
onSelected: (value) async {
final client = _client;
if (client == null) return;
try {
if (value == 'delete') {
_apply(await client.deleteTodo(
_projectId, todo.id,
directory: widget.directory));
}
} catch (error) {
_fail(error);
}
},
itemBuilder: (_) => const [
PopupMenuItem(value: 'delete', child: AppText('Delete')),
],
),
);
},
),
),
],
);
}
Future<void> _toggleTodo(ProjectTodo todo, bool completed) async {
final client = _client;
if (client == null) return;
try {
_apply(await client.updateTodo(_projectId, todo.id,
completed: completed, directory: widget.directory));
} catch (error) {
_fail(error);
}
}
// --------------------------------------------------------------- plans
Widget _plans(ThemeData theme) {
final plans = (_context?.plans ?? [])
.where((plan) => _matches([plan.title, plan.file]))
.toList()
..sort((a, b) {
if (a.pinned != b.pinned) return a.pinned ? -1 : 1;
return b.createdAt.compareTo(a.createdAt);
});
return Column(
children: [
_sectionHeader(theme, trArgs('{0} plans', [plans.length]),
'New plan', _newPlan),
Expanded(
child: plans.isEmpty
? _empty(theme, Icons.description_outlined,
_query.isEmpty ? 'No plans yet' : 'No matching plans')
: ListView.builder(
padding: const EdgeInsets.fromLTRB(8, 0, 8, 12),
itemCount: plans.length,
itemBuilder: (context, index) =>
_planTile(theme, plans[index]),
),
),
],
);
}
Widget _planTile(ThemeData theme, ProjectPlanLink plan) {
final scheme = theme.colorScheme;
return Card(
margin: const EdgeInsets.only(bottom: 8),
child: ListTile(
dense: true,
title: Row(
children: [
if (plan.pinned)
Padding(
padding: const EdgeInsets.only(right: 4),
child: Icon(Icons.push_pin, size: 13, color: scheme.primary),
),
Expanded(
child: Text(plan.title.isEmpty ? plan.file : plan.title,
maxLines: 2, overflow: TextOverflow.ellipsis),
),
],
),
subtitle: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (plan.hasProgress) ...[
const SizedBox(height: 4),
Row(
children: [
Expanded(
child: ClipRRect(
borderRadius: BorderRadius.circular(2),
child: LinearProgressIndicator(
value: plan.progressDone / plan.progressTotal,
minHeight: 4,
backgroundColor: scheme.surfaceContainerHighest,
),
),
),
const SizedBox(width: 6),
Text('${plan.progressDone}/${plan.progressTotal}',
style:
TextStyle(fontSize: 11, color: theme.hintColor)),
],
),
],
const SizedBox(height: 2),
AppText(
plan.source == 'shared' ? 'Shared' : 'Personal',
style: TextStyle(fontSize: 11, color: theme.hintColor),
),
],
),
trailing: PopupMenuButton<String>(
icon: const Icon(Icons.more_vert, size: 18),
onSelected: (value) async {
final client = _client;
if (client == null) return;
try {
switch (value) {
case 'pin':
_apply(await client.setPlanPinned(
_projectId, plan.id, !plan.pinned,
directory: widget.directory));
break;
case 'delete':
_apply(await client.deletePlan(_projectId, plan.id,
directory: widget.directory));
break;
}
} catch (error) {
_fail(error);
}
},
itemBuilder: (_) => [
PopupMenuItem(
value: 'pin', child: AppText(plan.pinned ? 'Unpin' : 'Pin')),
const PopupMenuItem(value: 'delete', child: AppText('Delete')),
],
),
onTap: () => _viewPlan(plan),
),
);
}
// -------------------------------------------------------------- memory
Widget _memoryBody(ThemeData theme) {
final snapshot = _memory;
if (snapshot == null) {
return _empty(theme, Icons.psychology_outlined, 'Memory is not enabled');
}
final global = snapshot.global
.where((m) => _matches([m.title, m.body]))
.toList();
final project = snapshot.project
.where((m) => _matches([m.title, m.body]))
.toList();
if (global.isEmpty && project.isEmpty) {
return _empty(
theme,
Icons.psychology_outlined,
_query.isEmpty ? 'No memories yet' : 'No matching memories');
}
return ListView(
padding: const EdgeInsets.fromLTRB(12, 0, 12, 12),
children: [
_memoryGroup(theme, tr('Global memory'), global, 'global',
failed: snapshot.globalFailed),
const SizedBox(height: 8),
_memoryGroup(theme, tr('Project memory'), project, 'project',
failed: snapshot.projectFailed),
Padding(
padding: const EdgeInsets.only(top: 6),
child: AppText(
'Memory is recorded by the agent during sessions; you can edit or delete it here.',
style: TextStyle(fontSize: 11.5, color: theme.hintColor),
),
),
],
);
}
Widget _memoryGroup(
ThemeData theme, String title, List<AgentMemoryEntry> entries, String scope,
{required bool failed}) {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Padding(
padding: const EdgeInsets.only(bottom: 4),
child: AppText(trArgs('{0} ({1})', [title, entries.length]),
style: TextStyle(fontSize: 12, color: theme.hintColor)),
),
if (failed)
Padding(
padding: const EdgeInsets.only(bottom: 4),
child: AppText('Could not load, refresh to retry',
style: TextStyle(
fontSize: 12, color: theme.colorScheme.error)),
)
else if (entries.isEmpty)
Padding(
padding: const EdgeInsets.only(bottom: 4),
child: AppText('None', style: TextStyle(fontSize: 12, color: theme.hintColor)),
),
for (final entry in entries) _memoryCard(theme, entry, scope),
],
);
}
Widget _memoryCard(ThemeData theme, AgentMemoryEntry entry, String scope) {
final scheme = theme.colorScheme;
return Card(
margin: const EdgeInsets.only(bottom: 8),
child: InkWell(
borderRadius: BorderRadius.circular(12),
onTap: () => _editMemory(entry, scope),
child: Padding(
padding: const EdgeInsets.fromLTRB(12, 8, 4, 8),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Flexible(
child: Text(entry.title,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontSize: 13.5, fontWeight: FontWeight.w600)),
),
const SizedBox(width: 6),
Container(
padding: const EdgeInsets.symmetric(
horizontal: 5, vertical: 1),
decoration: BoxDecoration(
color: scheme.surfaceContainerHighest,
borderRadius: BorderRadius.circular(4),
),
child: Text(entry.typeLabel,
style: TextStyle(
fontSize: 10, color: theme.hintColor)),
),
if (entry.flagged)
Padding(
padding: const EdgeInsets.only(left: 4),
child: Icon(Icons.flag_outlined,
size: 13, color: scheme.error),
),
],
),
const SizedBox(height: 3),
Text(entry.body,
maxLines: 4,
overflow: TextOverflow.ellipsis,
style: const TextStyle(fontSize: 12.5, height: 1.35)),
],
),
),
PopupMenuButton<String>(
icon: const Icon(Icons.more_vert, size: 18),
onSelected: (value) async {
if (value == 'edit') {
await _editMemory(entry, scope);
} else if (value == 'delete') {
await _deleteMemory(entry, scope);
}
},
itemBuilder: (_) => const [
PopupMenuItem(value: 'edit', child: AppText('Edit')),
PopupMenuItem(value: 'delete', child: AppText('Delete')),
],
),
],
),
),
),
);
}
Future<void> _editMemory(AgentMemoryEntry entry, String scope) async {
final client = _client;
if (client == null) return;
final result = await showDialog<(String, String, String)>(
context: context,
builder: (_) => _MemoryDialog(entry: entry),
);
if (result == null) return;
try {
await client.updateMemory(entry.id,
scope: scope,
projectId: _projectId,
title: result.$1,
body: result.$2,
type: result.$3,
directory: widget.directory);
await _reloadMemory();
} catch (error) {
_fail(error);
}
}
Future<void> _deleteMemory(AgentMemoryEntry entry, String scope) async {
final client = _client;
if (client == null) return;
try {
await client.deleteMemory(entry.id,
scope: scope,
projectId: _projectId,
directory: widget.directory);
await _reloadMemory();
} catch (error) {
_fail(error);
}
}
Future<void> _reloadMemory() async {
final client = _client;
if (client == null) return;
try {
final memory = await client.agentMemory(_projectId,
directory: widget.directory);
if (!mounted) return;
setState(() => _memory = memory);
} catch (error) {
_fail(error);
}
}
// -------------------------------------------------------------- dialogs
Widget _sectionHeader(
ThemeData theme, String summary, String action, VoidCallback onTap) {
return Padding(
padding: const EdgeInsets.fromLTRB(14, 0, 8, 2),
child: Row(
children: [
Expanded(
child: AppText(summary,
style: TextStyle(fontSize: 12, color: theme.hintColor)),
),
TextButton.icon(
style: TextButton.styleFrom(
visualDensity: VisualDensity.compact,
padding: const EdgeInsets.symmetric(horizontal: 8),
minimumSize: const Size(0, 32),
),
onPressed: onTap,
icon: const Icon(Icons.add, size: 16),
label: AppText(action, style: const TextStyle(fontSize: 12.5)),
),
],
),
);
}
Widget _empty(ThemeData theme, IconData icon, String text) {
return Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(icon, size: 36, color: theme.hintColor),
const SizedBox(height: 8),
AppText(text, style: TextStyle(fontSize: 13, color: theme.hintColor)),
],
),
);
}
Future<void> _addNote() => _editNote(null);
Future<void> _editNote(ProjectNote? note) async {
final text = await showDialog<String>(
context: context,
builder: (_) => _TextPromptDialog(
title: note == null ? 'New note' : 'Edit note',
hint: tr('Write something for later sessions to read'),
initial: note?.body ?? '',
maxLength: 3000,
maxLines: 10,
minLines: 4,
action: 'Save',
),
);
if (text == null || text.isEmpty) return;
final client = _client;
if (client == null) return;
try {
if (note == null) {
_apply(await client.createNote(_projectId, text,
directory: widget.directory));
} else {
_apply(await client.updateNote(_projectId, note.id,
body: text, directory: widget.directory));
}
} catch (error) {
_fail(error);
}
}
Future<void> _addTodo() async {
final text = await showDialog<String>(
context: context,
builder: (_) => _TextPromptDialog(
title: 'New todo',
hint: tr('What needs doing'),
maxLength: 1000,
maxLines: 1,
minLines: 1,
action: 'Save',
),
);
if (text == null || text.isEmpty) return;
final client = _client;
if (client == null) return;
try {
_apply(await client.createTodo(_projectId, text,
directory: widget.directory));
} catch (error) {
_fail(error);
}
}
Future<void> _newPlan() async {
final result = await showDialog<(String, String)>(
context: context,
builder: (_) => const _NewPlanDialog(),
);
if (result == null || result.$2.trim().isEmpty) return;
final client = _client;
if (client == null) return;
try {
_apply(await client.createPlan(_projectId,
title: result.$1, body: result.$2, directory: widget.directory));
} catch (error) {
_fail(error);
}
}
Future<void> _viewPlan(ProjectPlanLink plan) async {
final client = _client;
if (client == null) return;
ProjectPlanContent content;
try {
content = await client.planContent(_projectId, plan.id,
directory: widget.directory);
} catch (error) {
_fail(error);
return;
}
if (!mounted) return;
// A full page, not a dialog: a plan is long, and a page keeps the editor
// and the scroll view in their own hit-testable surface.
await Navigator.of(context).push(MaterialPageRoute<void>(
builder: (context) => _PlanPage(
title: content.title.isEmpty ? plan.file : content.title,
raw: content.raw,
onSave: (raw) async {
_apply(await client.savePlan(_projectId, plan.id, raw,
directory: widget.directory));
},
),
));
}
String _stamp(int millis) {
if (millis <= 0) return '';
final time = DateTime.fromMillisecondsSinceEpoch(millis);
String two(int value) => value.toString().padLeft(2, '0');
return '${time.year}-${two(time.month)}-${two(time.day)} '
'${two(time.hour)}:${two(time.minute)}';
}
}
/// One plan, rendered; 编辑 swaps in the raw Markdown, 保存 writes it back.
class _PlanPage extends StatefulWidget {
final String title;
final String raw;
final Future<void> Function(String raw) onSave;
const _PlanPage({
required this.title,
required this.raw,
required this.onSave,
});
@override
State<_PlanPage> createState() => _PlanPageState();
}
class _PlanPageState extends State<_PlanPage> {
late final TextEditingController _controller =
TextEditingController(text: widget.raw);
bool _editing = false;
bool _saving = false;
@override
void dispose() {
_controller.dispose();
super.dispose();
}
Future<void> _save() async {
setState(() => _saving = true);
try {
await widget.onSave(_controller.text);
if (mounted) setState(() => _editing = false);
} catch (error) {
if (mounted) {
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text('$error')));
}
} finally {
if (mounted) setState(() => _saving = false);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title, maxLines: 1, overflow: TextOverflow.ellipsis),
actions: [
if (_editing)
TextButton(
onPressed: _saving ? null : () => setState(() => _editing = false),
child: const AppText('Cancel'),
),
TextButton(
onPressed: _saving
? null
: (_editing ? _save : () => setState(() => _editing = true)),
child: AppText(_saving ? 'Saving…' : (_editing ? 'Save' : 'Edit')),
),
],
),
body: _editing
? Padding(
padding: const EdgeInsets.all(12),
child: TextField(
controller: _controller,
expands: true,
maxLines: null,
minLines: null,
textAlignVertical: TextAlignVertical.top,
style: const TextStyle(fontFamily: 'monospace', fontSize: 13),
decoration: const InputDecoration(
border: OutlineInputBorder(),
contentPadding: EdgeInsets.all(10),
),
),
)
: SingleChildScrollView(
padding: const EdgeInsets.all(16),
child: MarkdownView(_controller.text, fontSize: 14.5),
),
);
}
}
/// A one-field prompt that owns its controller (a controller created outside
/// a dialog is disposed while the dialog is still animating out, which trips a
/// framework assertion in debug builds).
class _TextPromptDialog extends StatefulWidget {
final String title;
final String hint;
final String initial;
final int maxLength;
final int maxLines;
final int minLines;
final String action;
const _TextPromptDialog({
required this.title,
required this.hint,
required this.maxLength,
required this.maxLines,
required this.minLines,
required this.action,
this.initial = '',
});
@override
State<_TextPromptDialog> createState() => _TextPromptDialogState();
}
class _TextPromptDialogState extends State<_TextPromptDialog> {
late final TextEditingController _controller =
TextEditingController(text: widget.initial);
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return AlertDialog(
title: AppText(widget.title),
content: SizedBox(
width: double.maxFinite,
child: TextField(
controller: _controller,
autofocus: true,
maxLength: widget.maxLength,
maxLines: widget.maxLines,
minLines: widget.minLines,
decoration: InputDecoration(
hintText: widget.hint,
border: const OutlineInputBorder(),
),
),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const AppText('Cancel')),
FilledButton(
onPressed: () => Navigator.pop(context, _controller.text.trim()),
child: AppText(widget.action)),
],
);
}
}
/// Title plus Markdown body, as one dialog.
class _NewPlanDialog extends StatefulWidget {
const _NewPlanDialog();
@override
State<_NewPlanDialog> createState() => _NewPlanDialogState();
}
class _NewPlanDialogState extends State<_NewPlanDialog> {
final TextEditingController _title = TextEditingController();
final TextEditingController _body = TextEditingController();
@override
void dispose() {
_title.dispose();
_body.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return AlertDialog(
title: const AppText('New plan'),
content: SizedBox(
width: double.maxFinite,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
TextField(
controller: _title,
autofocus: true,
maxLength: 160,
decoration: InputDecoration(
labelText: tr('Title'),
border: const OutlineInputBorder(),
),
),
const SizedBox(height: 8),
TextField(
controller: _body,
maxLines: 10,
minLines: 6,
decoration: InputDecoration(
alignLabelWithHint: true,
labelText: tr('Plan body (Markdown)'),
border: const OutlineInputBorder(),
),
),
],
),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const AppText('Cancel')),
FilledButton(
onPressed: () => Navigator.pop(
context, (_title.text.trim(), _body.text)),
child: const AppText('Create')),
],
);
}
}
/// Edit one memory entry: its title, its text, and what kind it is.
class _MemoryDialog extends StatefulWidget {
final AgentMemoryEntry entry;
const _MemoryDialog({required this.entry});
@override
State<_MemoryDialog> createState() => _MemoryDialogState();
}
class _MemoryDialogState extends State<_MemoryDialog> {
late final TextEditingController _title =
TextEditingController(text: widget.entry.title);
late final TextEditingController _body =
TextEditingController(text: widget.entry.body);
late String _type = widget.entry.type;
@override
void dispose() {
_title.dispose();
_body.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return AlertDialog(
title: const AppText('Edit memory'),
content: SizedBox(
width: double.maxFinite,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
TextField(
controller: _title,
autofocus: true,
maxLength: 120,
decoration: InputDecoration(
labelText: tr('Title'),
border: const OutlineInputBorder(),
),
),
const SizedBox(height: 8),
SegmentedButton<String>(
showSelectedIcon: false,
style: const ButtonStyle(
visualDensity: VisualDensity.compact,
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
),
segments: const [
ButtonSegment(value: 'fact', label: AppText('Fact')),
ButtonSegment(value: 'preference', label: AppText('Preference')),
ButtonSegment(value: 'reference', label: AppText('Reference')),
],
selected: {_type},
onSelectionChanged: (value) =>
setState(() => _type = value.first),
),
const SizedBox(height: 8),
TextField(
controller: _body,
maxLength: 2000,
maxLines: 6,
minLines: 4,
decoration: InputDecoration(
alignLabelWithHint: true,
labelText: tr('Content'),
border: const OutlineInputBorder(),
),
),
],
),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context), child: const AppText('Cancel')),
FilledButton(
onPressed: () {
final title = _title.text.trim();
if (title.isEmpty) return;
Navigator.pop(context, (title, _body.text.trim(), _type));
},
child: const AppText('Save'),
),
],
);
}
}