mirror of
https://github.com/kuhyx/todo-app.git
synced 2026-11-25 23:07:19 +01:00
Compare commits
4 Commits
377ec17356
...
2a9332094a
| Author | SHA1 | Date | |
|---|---|---|---|
| 2a9332094a | |||
| 9e18821c7b | |||
| f7ea0ffb3d | |||
| 2ffae26f93 |
@ -1,10 +1,11 @@
|
||||
{
|
||||
"mcpServers": {
|
||||
"todo": {
|
||||
"type": "stdio",
|
||||
"command": "${HOME}/.venvs/todo-mcp/bin/python",
|
||||
"args": ["-m", "todo_mcp._mcp"],
|
||||
"env": {}
|
||||
"type": "http",
|
||||
"url": "http://127.0.0.1:8735/mcp",
|
||||
"headers": {
|
||||
"Authorization": "Bearer ${TODO_MCP_TOKEN}"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
11
AGENTS.md
11
AGENTS.md
@ -43,6 +43,7 @@ and sync peer-to-peer through a GitHub repo used as dumb storage.
|
||||
- Release APK: `flutter build apk --release` (signs with the debug key; debug
|
||||
builds are janky — always measure smoothness on a release build).
|
||||
- Sync smoke test (hits real GitHub, needs a token): `dart run tool/sync_smoke.dart`.
|
||||
- MCP server (`lib/mcp/`, :8735): tests `flutter test test/mcp/`, deploy `mcp/install.sh`; see `mcp/README.md`.
|
||||
- run: `./run.sh` (desktop; mobile: `flutter run`)
|
||||
- test: `flutter test --reporter=compact`
|
||||
- test-changed: `scripts/test_changed.sh`
|
||||
@ -85,7 +86,11 @@ Three layers under `lib/`, each single-purpose:
|
||||
with the structured template; lazy note creation on first keystroke.
|
||||
- `notes_list_screen.dart`: list + search + sort + filter sheet + per-note
|
||||
sheet. **Default view hides Done/Abandoned and shows no filter badge**
|
||||
(looks unfiltered).
|
||||
(looks unfiltered). Under 600dp wide (`kNotesGridMaxWidth`) the notes are
|
||||
a 2-column `NotesGrid` of compact `NoteGridTile`s (title + priority/status
|
||||
cues; body and dates are in the long-press sheet). The tile height is
|
||||
derived so whole rows exactly fill the viewport; past one screenful it
|
||||
scrolls vertically (no paging). Wider windows (desktop) keep the list.
|
||||
- `settings_screen.dart`: GitHub connect/test, device-flow auth, and the
|
||||
Export/Import backup actions.
|
||||
- `main.dart`: bootstrap only (`// coverage:ignore-file`) — wires platform DB
|
||||
@ -140,8 +145,8 @@ rest of the wrapper one request at a time. BACKLOG.md rewrites links to
|
||||
|
||||
## Testing
|
||||
|
||||
- **The suite must stay quick and fully green.** It is currently **587 tests at
|
||||
100% line coverage** (3213 lines), ~40s on this machine with
|
||||
- **The suite must stay quick and fully green.** It is currently **604 tests at
|
||||
100% line coverage** (3305 lines), ~40s on this machine with
|
||||
`--concurrency=3` (unbounded concurrency under `capped.sh`'s 4 GiB gets its
|
||||
test processes SIGTERMed while the wrapper still exits 0 — check the last
|
||||
line says "All tests passed"). Don't regress either.
|
||||
|
||||
@ -1,27 +0,0 @@
|
||||
# Fit every main screen on one phone screen
|
||||
|
||||
## what
|
||||
Todo's main screen is the notes list (ListView.separated). Convert it to a dense note-tile grid that fits the screen, paged by swipe.
|
||||
|
||||
## where
|
||||
/home/kuhy/src/todo; screens to convert:
|
||||
- lib/ui/notes_list_screen.dart: Notes — ListView.separated of notes -> 2-column title tiles with priority/status color, filter chips, paged; body/meta in long-press sheet (note_actions_sheet.dart)
|
||||
Exempt: note editor and capture form (free-text editor), settings, GitHub mirror and cloud-image settings (settings)
|
||||
|
||||
## must
|
||||
- no vertical scrolling on converted screens at 1080x2400 with status bar + nav inset
|
||||
- secondary metadata/actions behind long-press or a tap sheet, not dropped
|
||||
- must not: change data/sync/storage code
|
||||
- optional: reuse `FitGrid` from ~/src/utils/design_system (first tag after design_system-v0.2.1); bump the app's design_system pin to that tag
|
||||
|
||||
## done
|
||||
A widget test per converted screen at Pixel 6a geometry (`physicalSize = Size(1080, 2400)`, `devicePixelRatio = 2.625`, `padding = FakeViewPadding(top: 132, bottom: 63)`, real nav bar + mini-player/bottom chrome pumped) asserts no vertical Scrollable has maxScrollExtent > 0 and the primary actions are hit-testable; `flutter test --reporter=compact` exits 0.
|
||||
|
||||
## verify
|
||||
Pixel 6a 23181JEGR08034, release build via ~/.claude/scripts/phone_deploy.sh, screenshot from phone_vd.sh per converted screen.
|
||||
|
||||
## read first
|
||||
- ~/.claude/skills/build-mobile-app/SKILL.md (R7)
|
||||
- ~/src/tunedeck Home tab implementation (reference pattern)
|
||||
|
||||
REMOVE ME AFTER FINISH
|
||||
@ -55,24 +55,9 @@ class CliCommands {
|
||||
/// Prints one note in full.
|
||||
Future<int> get(String ref) async {
|
||||
_report(await session.sync(push: false));
|
||||
final note = findNote(await session.repository.listNotes(), ref);
|
||||
_out
|
||||
..writeln('id: ${note.id}')
|
||||
..writeln('priority: ${note.priority.name}')
|
||||
..writeln('status: ${CliArgs.statusName(note.status)}')
|
||||
..writeln('created: ${note.createdAt.toIso8601String()}')
|
||||
..writeln('updated: ${note.updatedAt.toIso8601String()}');
|
||||
for (final (name, value) in [
|
||||
('repo', note.repo),
|
||||
('done_check', note.doneCheck),
|
||||
('by', note.by),
|
||||
('evidence', note.evidence),
|
||||
]) {
|
||||
if (value != null) _out.writeln('$name: $value');
|
||||
}
|
||||
_out
|
||||
..writeln('---')
|
||||
..writeln(note.text);
|
||||
_out.writeln(
|
||||
noteDetail(findNote(await session.repository.listNotes(), ref)),
|
||||
);
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
@ -59,6 +59,7 @@ class CliSession {
|
||||
static Future<CliSession> open(
|
||||
String dataDir, {
|
||||
required String seedCredentials,
|
||||
String seedApp = 'todo',
|
||||
http.Client? httpClient,
|
||||
}) async {
|
||||
final dir = Directory(dataDir);
|
||||
@ -83,7 +84,7 @@ class CliSession {
|
||||
await repository.close();
|
||||
throw FirebaseAuthError(
|
||||
'no Firebase session: $seedCredentials is missing; re-seed it with '
|
||||
'`python3 ~/src/utils/crdt-sync/tool/seed_session.py --app todo`',
|
||||
'`python3 ~/src/utils/crdt-sync/tool/seed_session.py --app $seedApp`',
|
||||
);
|
||||
}
|
||||
final firebase = FirebaseRestClient(
|
||||
|
||||
@ -45,3 +45,18 @@ String listLine(Note note) => [
|
||||
].join('\t');
|
||||
|
||||
String _title(Note note) => note.text.split('\n').first;
|
||||
|
||||
/// The note's metadata lines, `---`, then its text.
|
||||
String noteDetail(Note note) => [
|
||||
'id: ${note.id}',
|
||||
'priority: ${note.priority.name}',
|
||||
'status: ${CliArgs.statusName(note.status)}',
|
||||
'created: ${note.createdAt.toIso8601String()}',
|
||||
'updated: ${note.updatedAt.toIso8601String()}',
|
||||
if (note.repo case final v?) 'repo: $v',
|
||||
if (note.doneCheck case final v?) 'done_check: $v',
|
||||
if (note.by case final v?) 'by: $v',
|
||||
if (note.evidence case final v?) 'evidence: $v',
|
||||
'---',
|
||||
note.text,
|
||||
].join('\n');
|
||||
|
||||
@ -32,6 +32,11 @@ Map<String, Field> noteFields(Note note, Hlc hlc) => {
|
||||
Note noteFromRecord(Record record) {
|
||||
final fields = record.fields;
|
||||
String? str(String name) => fields[name]?.$1 as String?;
|
||||
// '' is how a peer clears a task field: omitting it never clears.
|
||||
String? task(String name) => switch (str(name)) {
|
||||
'' => null,
|
||||
final v => v,
|
||||
};
|
||||
return Note(
|
||||
id: record.id,
|
||||
text: str(_text) ?? '',
|
||||
@ -39,10 +44,10 @@ Note noteFromRecord(Record record) {
|
||||
status: Status.fromValue(fields[_status]?.$1 as int?),
|
||||
createdAt: _parseDate(str(_createdAt)),
|
||||
updatedAt: _parseDate(str(_updatedAt)),
|
||||
repo: str(_repo),
|
||||
doneCheck: str(_doneCheck),
|
||||
by: str(_by),
|
||||
evidence: str(_evidence),
|
||||
repo: task(_repo),
|
||||
doneCheck: task(_doneCheck),
|
||||
by: task(_by),
|
||||
evidence: task(_evidence),
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
48
lib/mcp/mcp_main.dart
Normal file
48
lib/mcp/mcp_main.dart
Normal file
@ -0,0 +1,48 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:path/path.dart' as p;
|
||||
import 'package:todo/cli/cli_session.dart';
|
||||
import 'package:todo/mcp/task_service.dart';
|
||||
import 'package:todo/mcp/todo_mcp_server.dart';
|
||||
|
||||
/// Starts the server from `$HOME` paths and returns its stop function, or
|
||||
/// null after writing to [err] why it cannot run (no tokens, seed, network).
|
||||
Future<Future<void> Function()?> startTodoMcp(
|
||||
Map<String, String> env,
|
||||
StringSink err, {
|
||||
http.Client? httpClient,
|
||||
}) async {
|
||||
final home = env['HOME'] ?? '';
|
||||
final config = p.join(home, '.config', 'todo-mcp');
|
||||
final tokens = File(p.join(config, 'tokens'));
|
||||
if (!tokens.existsSync()) {
|
||||
err.writeln('error: ${tokens.path} missing; run mcp/mint_token.sh pc');
|
||||
return null;
|
||||
}
|
||||
CliSession? session;
|
||||
try {
|
||||
session = await CliSession.open(
|
||||
env['TODO_MCP_DATA_DIR'] ?? p.join(home, '.local', 'share', 'todo-mcp'),
|
||||
seedCredentials: p.join(config, 'firebase_auth.json'),
|
||||
seedApp: 'todo-mcp',
|
||||
httpClient: httpClient,
|
||||
);
|
||||
await session.sync(push: true);
|
||||
final server = await TodoMcpServer.start(
|
||||
tasks: TaskService(session),
|
||||
tokens: tokens,
|
||||
port: int.tryParse(env['TODO_MCP_PORT'] ?? '') ?? kTodoMcpPort,
|
||||
);
|
||||
err.writeln('todo-mcp: serving ${server.uri}');
|
||||
final open = session;
|
||||
return () async {
|
||||
await server.close();
|
||||
await open.close();
|
||||
};
|
||||
} on Object catch (e) {
|
||||
err.writeln('error: $e');
|
||||
await session?.close();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
190
lib/mcp/task_service.dart
Normal file
190
lib/mcp/task_service.dart
Normal file
@ -0,0 +1,190 @@
|
||||
import 'package:todo/cli/cli_args.dart';
|
||||
import 'package:todo/cli/cli_session.dart';
|
||||
import 'package:todo/cli/note_lookup.dart';
|
||||
import 'package:todo/data/note.dart';
|
||||
import 'package:todo/data/note_repository.dart';
|
||||
import 'package:uuid/uuid.dart';
|
||||
|
||||
/// The six task tools over one persistent sync node; calls run one at a time.
|
||||
class TaskService {
|
||||
/// Serves [_session]'s notes; every call pulls first, writes then push.
|
||||
TaskService(this._session);
|
||||
|
||||
final CliSession _session;
|
||||
Future<void> _tail = Future.value();
|
||||
|
||||
Future<String> _serial(Future<String> Function() body) {
|
||||
final run = _tail.then((_) => body());
|
||||
_tail = run.then((_) {}, onError: (_) {});
|
||||
return run;
|
||||
}
|
||||
|
||||
Future<List<Note>> _pull() async {
|
||||
final skipped = (await _session.sync(push: true)).skippedFiles;
|
||||
if (skipped.isNotEmpty) throw StateError('sync: unmergeable $skipped');
|
||||
return await _session.repository.listNotes();
|
||||
}
|
||||
|
||||
Future<String> _save(Note note, String verb) async {
|
||||
await _session.repository.upsert(note.copyWith(updatedAt: DateTime.now()));
|
||||
await _session.sync(push: true);
|
||||
return '$verb ${note.id}\n${listLine(note)}';
|
||||
}
|
||||
|
||||
Future<Note> _find(_Args a) async {
|
||||
final id = a.required('id');
|
||||
try {
|
||||
return findNote(await _pull(), id);
|
||||
} on NoteLookupError catch (e) {
|
||||
throw FormatException('id: $e');
|
||||
}
|
||||
}
|
||||
|
||||
/// `add_task`: a new repo task by claude; returns its full id.
|
||||
Future<String> add(Map<String, dynamic> args) => _serial(() async {
|
||||
final a = _Args(args);
|
||||
final repo = a.repo(required: true)!;
|
||||
final title = a.required('title');
|
||||
final body = a.optional('body') ?? '';
|
||||
final now = DateTime.now();
|
||||
await _pull();
|
||||
return await _save(
|
||||
Note(
|
||||
id: const Uuid().v4(),
|
||||
text: body.isEmpty ? title : '$title\n\n$body',
|
||||
priority: a.priority() ?? Priority.medium,
|
||||
status: Status.todo,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
repo: repo,
|
||||
doneCheck: a.optional('done_check'),
|
||||
by: 'claude',
|
||||
),
|
||||
'added',
|
||||
);
|
||||
});
|
||||
|
||||
/// `list_tasks`: repo tasks, open ones unless `status` says otherwise.
|
||||
Future<String> list(Map<String, dynamic> args) => _serial(() async {
|
||||
final a = _Args(args);
|
||||
final repo = a.repo();
|
||||
final statuses = a.statuses();
|
||||
await _pull();
|
||||
return _lines(
|
||||
await _session.repository.listNotes(
|
||||
filter: NoteFilter(
|
||||
statuses: statuses,
|
||||
sources: {repo ?? kRepoTasksSource},
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
/// `search_tasks`: repo tasks of any status whose text or repo matches.
|
||||
Future<String> search(Map<String, dynamic> args) => _serial(() async {
|
||||
final query = _Args(args).required('query');
|
||||
await _pull();
|
||||
return _lines(
|
||||
await _session.repository.listNotes(
|
||||
filter: NoteFilter(query: query, sources: {kRepoTasksSource}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
/// `get_task`: one note in full.
|
||||
Future<String> get(Map<String, dynamic> args) =>
|
||||
_serial(() async => noteDetail(await _find(_Args(args))));
|
||||
|
||||
/// `update_task`: changes only the keys given; `done_check: ""` clears it.
|
||||
Future<String> update(Map<String, dynamic> args) => _serial(() async {
|
||||
final a = _Args(args);
|
||||
final note = await _find(a);
|
||||
final status = a.status();
|
||||
if (status == Status.done) {
|
||||
throw const FormatException('status: use close_task with evidence');
|
||||
}
|
||||
final lines = note.text.split('\n');
|
||||
final title = a.has('title') ? a.required('title') : lines.first;
|
||||
final body = a.has('body')
|
||||
? (a.optional('body') ?? '')
|
||||
: lines.skip(1).join('\n').trimLeft();
|
||||
final reopened = status != null && note.status == Status.done;
|
||||
return await _save(
|
||||
note.copyWith(
|
||||
text: body.isEmpty ? title : '$title\n\n$body',
|
||||
priority: a.priority(),
|
||||
status: status,
|
||||
repo: a.repo(),
|
||||
doneCheck: a.has('done_check')
|
||||
? (a.optional('done_check') ?? '')
|
||||
: null,
|
||||
evidence: reopened ? '' : null,
|
||||
),
|
||||
'updated',
|
||||
);
|
||||
});
|
||||
|
||||
/// `close_task`: status done plus evidence; refused without evidence.
|
||||
Future<String> close(Map<String, dynamic> args) => _serial(() async {
|
||||
final a = _Args(args);
|
||||
final evidence = a.required('evidence');
|
||||
final note = await _find(a);
|
||||
return await _save(
|
||||
note.copyWith(status: Status.done, evidence: evidence),
|
||||
'closed',
|
||||
);
|
||||
});
|
||||
|
||||
String _lines(List<Note> notes) =>
|
||||
notes.isEmpty ? 'no tasks match' : notes.map(listLine).join('\n');
|
||||
}
|
||||
|
||||
final _repoShape = RegExp(r'^[\w.-]+/[\w.-]+$');
|
||||
final Map<String, Status> _statuses = {
|
||||
for (final s in Status.values) CliArgs.statusName(s): s,
|
||||
};
|
||||
|
||||
// Every refusal is a FormatException whose message starts with the field.
|
||||
extension type _Args(Map<String, dynamic> _args) {
|
||||
bool has(String name) => _args.containsKey(name);
|
||||
|
||||
String? optional(String name) {
|
||||
final value = _args[name];
|
||||
if (value == null) return null;
|
||||
if (value is! String) throw FormatException('$name: must be a string');
|
||||
final trimmed = value.trim();
|
||||
return trimmed.isEmpty ? null : trimmed;
|
||||
}
|
||||
|
||||
String required(String name) =>
|
||||
optional(name) ?? (throw FormatException('$name: required, not blank'));
|
||||
|
||||
String? repo({bool required = false}) {
|
||||
if (!required && !has('repo')) return null;
|
||||
final value = optional('repo') ?? '';
|
||||
if (!_repoShape.hasMatch(value)) {
|
||||
throw FormatException('repo: must look like owner/name, got "$value"');
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
Priority? priority() =>
|
||||
_pick('priority', {for (final p in Priority.values) p.name: p});
|
||||
|
||||
Status? status() => _pick('status', _statuses);
|
||||
|
||||
Set<Status> statuses() => switch (optional('status')) {
|
||||
null || 'open' => {Status.todo, Status.inProgress},
|
||||
'all' => const {},
|
||||
_ => {status()!},
|
||||
};
|
||||
|
||||
T? _pick<T>(String name, Map<String, T> choices) {
|
||||
final value = optional(name);
|
||||
if (value == null) return null;
|
||||
return choices[value] ??
|
||||
(throw FormatException(
|
||||
'$name: must be one of ${choices.keys.join('|')}, got "$value"',
|
||||
));
|
||||
}
|
||||
}
|
||||
179
lib/mcp/todo_mcp_server.dart
Normal file
179
lib/mcp/todo_mcp_server.dart
Normal file
@ -0,0 +1,179 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:mcp_dart/mcp_dart.dart';
|
||||
import 'package:todo/mcp/task_service.dart';
|
||||
import 'package:todo/mcp/token_file.dart';
|
||||
|
||||
/// Loopback port; Caddy proxies todo.kuhy.duckdns.org/mcp here.
|
||||
const kTodoMcpPort = 8735;
|
||||
|
||||
const _publicHost = 'todo.kuhy.duckdns.org';
|
||||
|
||||
const _instructions = '''
|
||||
Tasks for kuhy's repos live in the todo app (not in TODO*.md files, which are
|
||||
banned). Use this server instead of writing a TODO file.
|
||||
- At session start in a repo, call list_tasks(repo: "kuhyx/<name>") to see
|
||||
its open tasks.
|
||||
- When you find work you will not finish now, call add_task with the repo,
|
||||
a one-line title, the body (what / where / done / verify) and a done_check:
|
||||
a shell command run from the repo root that exits 0 once the work is done.
|
||||
- When a task's work lands, run its done_check; only if it exits 0 call
|
||||
close_task with evidence "<commit sha> done_check exit 0". Never close
|
||||
without running it.
|
||||
- Ids accept an 8-character prefix. Errors start with the argument to fix.''';
|
||||
|
||||
/// The task tools over Streamable HTTP, behind sha256-hashed bearer tokens.
|
||||
class TodoMcpServer {
|
||||
TodoMcpServer._(this._http);
|
||||
|
||||
final StreamableMcpServer _http;
|
||||
|
||||
/// `http://<host>:<bound port>/mcp`.
|
||||
Uri get uri => Uri.parse('http://${_http.host}:${_http.boundPort}/mcp');
|
||||
|
||||
/// Binds [host]:[port] (0 = any free port); [tokens] is read per request.
|
||||
static Future<TodoMcpServer> start({
|
||||
required TaskService tasks,
|
||||
required File tokens,
|
||||
String host = '127.0.0.1',
|
||||
int port = kTodoMcpPort,
|
||||
}) async {
|
||||
final http = StreamableMcpServer(
|
||||
serverFactory: (_) => _server(tasks),
|
||||
host: host,
|
||||
port: port,
|
||||
authenticator: (request) => tokenAccepted(
|
||||
tokens,
|
||||
request is HttpRequest
|
||||
? request.headers.value(HttpHeaders.authorizationHeader)
|
||||
: null,
|
||||
),
|
||||
allowedHosts: const {'localhost', '127.0.0.1', '::1', _publicHost},
|
||||
);
|
||||
await http.start();
|
||||
return TodoMcpServer._(http);
|
||||
}
|
||||
|
||||
/// Stops listening and closes every session.
|
||||
Future<void> close() => _http.stop();
|
||||
}
|
||||
|
||||
McpServer _server(TaskService tasks) {
|
||||
final server = McpServer(
|
||||
const Implementation(name: 'todo', version: '1.0.0'),
|
||||
options: const McpServerOptions(instructions: _instructions),
|
||||
);
|
||||
final id = JsonSchema.string(
|
||||
description: 'Task id, or a unique prefix of at least 8 characters.',
|
||||
);
|
||||
final repo = JsonSchema.string(
|
||||
description: 'GitHub repo as owner/name, e.g. kuhyx/todo.',
|
||||
);
|
||||
final priority = JsonSchema.string(description: 'low | medium | high.');
|
||||
final doneCheck = JsonSchema.string(
|
||||
description:
|
||||
'Shell command run from the repo root; exit 0 means done. '
|
||||
'In update_task, "" clears it.',
|
||||
);
|
||||
void tool(
|
||||
String name,
|
||||
String description,
|
||||
Map<String, JsonSchema> props,
|
||||
List<String> required,
|
||||
Future<String> Function(Map<String, dynamic>) run,
|
||||
) => server.registerTool(
|
||||
name,
|
||||
description: description,
|
||||
inputSchema: JsonSchema.object(properties: props, required: required),
|
||||
callback: (args, _) => _result(() => run(args)),
|
||||
);
|
||||
|
||||
tool(
|
||||
'add_task',
|
||||
'Add an open task for a repo (by: claude). Returns "added <full id>" and '
|
||||
'its list line. Use when you find work you will not finish now.',
|
||||
{
|
||||
'repo': repo,
|
||||
'title': JsonSchema.string(description: 'One-line title.'),
|
||||
'body': JsonSchema.string(description: 'Markdown: what/where/verify.'),
|
||||
'done_check': doneCheck,
|
||||
'priority': priority,
|
||||
},
|
||||
['repo', 'title'],
|
||||
tasks.add,
|
||||
);
|
||||
tool(
|
||||
'list_tasks',
|
||||
'List repo tasks, one line each: 8-char id, status, priority, repo, '
|
||||
'title. Default status "open" (todo + in_progress).',
|
||||
{
|
||||
'repo': repo,
|
||||
'status': JsonSchema.string(
|
||||
description: 'open | all | todo | in_progress | done | abandoned.',
|
||||
),
|
||||
},
|
||||
[],
|
||||
tasks.list,
|
||||
);
|
||||
tool(
|
||||
'get_task',
|
||||
'One task in full: metadata lines, then --- and the text.',
|
||||
{'id': id},
|
||||
['id'],
|
||||
tasks.get,
|
||||
);
|
||||
tool(
|
||||
'update_task',
|
||||
'Change only the arguments given; others stay as they are. Marking done '
|
||||
'is close_task. Returns "updated <id>" and its list line.',
|
||||
{
|
||||
'id': id,
|
||||
'title': JsonSchema.string(description: 'New one-line title.'),
|
||||
'body': JsonSchema.string(description: 'New body; "" empties it.'),
|
||||
'done_check': doneCheck,
|
||||
'priority': priority,
|
||||
'status': JsonSchema.string(
|
||||
description: 'todo | in_progress | abandoned.',
|
||||
),
|
||||
'repo': repo,
|
||||
},
|
||||
['id'],
|
||||
tasks.update,
|
||||
);
|
||||
tool(
|
||||
'close_task',
|
||||
'Mark a task done, keeping it. Refused without evidence. Run the '
|
||||
"task's done_check first and close only when it exits 0.",
|
||||
{
|
||||
'id': id,
|
||||
'evidence': JsonSchema.string(
|
||||
description:
|
||||
'Commit sha and done_check exit code, e.g. "abc1234 exit 0".',
|
||||
),
|
||||
},
|
||||
['id', 'evidence'],
|
||||
tasks.close,
|
||||
);
|
||||
tool(
|
||||
'search_tasks',
|
||||
'Repo tasks of any status whose text or repo contains the query '
|
||||
'(case-insensitive), one line each as list_tasks.',
|
||||
{'query': JsonSchema.string(description: 'Text to look for.')},
|
||||
['query'],
|
||||
tasks.search,
|
||||
);
|
||||
return server;
|
||||
}
|
||||
|
||||
Future<CallToolResult> _result(Future<String> Function() run) async {
|
||||
try {
|
||||
return CallToolResult.fromContent([TextContent(text: await run())]);
|
||||
} on FormatException catch (e) {
|
||||
return _error(e.message);
|
||||
} on Object catch (e) {
|
||||
return _error('$e');
|
||||
}
|
||||
}
|
||||
|
||||
CallToolResult _error(String text) =>
|
||||
CallToolResult(content: [TextContent(text: 'error: $text')], isError: true);
|
||||
31
lib/mcp/token_file.dart
Normal file
31
lib/mcp/token_file.dart
Normal file
@ -0,0 +1,31 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:crdt_sync/crdt_sync.dart';
|
||||
|
||||
/// sha256 hex of [token] (crdt_sync's `revisionOf` is exactly that).
|
||||
String tokenHash(String token) => revisionOf(token);
|
||||
|
||||
Set<String> _hashes(File tokens) {
|
||||
final String text;
|
||||
try {
|
||||
text = tokens.readAsStringSync();
|
||||
} on FileSystemException {
|
||||
return const {};
|
||||
}
|
||||
return {
|
||||
for (final line in text.split('\n'))
|
||||
if (line.trim() case final t when t.isNotEmpty && !t.startsWith('#'))
|
||||
t.split(RegExp(r'\s+')).first.toLowerCase(),
|
||||
};
|
||||
}
|
||||
|
||||
/// Whether [authorization] bears a token hashed in [tokens], read per call.
|
||||
bool tokenAccepted(File tokens, String? authorization) {
|
||||
const scheme = 'bearer ';
|
||||
if (authorization == null ||
|
||||
!authorization.toLowerCase().startsWith(scheme)) {
|
||||
return false;
|
||||
}
|
||||
final token = authorization.substring(scheme.length).trim();
|
||||
return token.isNotEmpty && _hashes(tokens).contains(tokenHash(token));
|
||||
}
|
||||
50
lib/ui/app_route.dart
Normal file
50
lib/ui/app_route.dart
Normal file
@ -0,0 +1,50 @@
|
||||
/// The one page route every screen is pushed with, on the shared motion tokens.
|
||||
library;
|
||||
|
||||
import 'package:design_system/design_system.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:todo/ui/motion.dart';
|
||||
|
||||
/// A route for [builder]: fade plus a short rise over [AppDuration.slow],
|
||||
/// instant under the OS "remove animations" setting.
|
||||
Route<T> appRoute<T>(BuildContext context, WidgetBuilder builder) =>
|
||||
_AppPageRoute<T>(
|
||||
builder: builder,
|
||||
duration: motionDuration(context, AppDuration.slow),
|
||||
);
|
||||
|
||||
class _AppPageRoute<T> extends MaterialPageRoute<T> {
|
||||
_AppPageRoute({required super.builder, required this.duration});
|
||||
|
||||
final Duration duration;
|
||||
|
||||
@override
|
||||
Duration get transitionDuration => duration;
|
||||
|
||||
@override
|
||||
Duration get reverseTransitionDuration => duration;
|
||||
|
||||
@override
|
||||
Widget buildTransitions(
|
||||
BuildContext context,
|
||||
Animation<double> animation,
|
||||
Animation<double> secondaryAnimation,
|
||||
Widget child,
|
||||
) {
|
||||
final enter = CurvedAnimation(
|
||||
parent: animation,
|
||||
curve: AppCurve.decelerate,
|
||||
reverseCurve: AppCurve.accelerate,
|
||||
);
|
||||
return FadeTransition(
|
||||
opacity: enter,
|
||||
child: SlideTransition(
|
||||
position: Tween<Offset>(
|
||||
begin: const Offset(0, 0.04),
|
||||
end: Offset.zero,
|
||||
).animate(enter),
|
||||
child: child,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -4,11 +4,13 @@
|
||||
/// screen still owns every action; this just lays the row out.
|
||||
library;
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'package:todo/data/note_repository.dart';
|
||||
import 'package:todo/frame_stats.dart';
|
||||
import 'package:todo/ui/attachment_picking.dart';
|
||||
import 'package:todo/ui/capture_confirm_mark.dart';
|
||||
|
||||
/// App bar for the capture screen.
|
||||
class CaptureAppBar extends StatelessWidget implements PreferredSizeWidget {
|
||||
@ -22,6 +24,7 @@ class CaptureAppBar extends StatelessWidget implements PreferredSizeWidget {
|
||||
required this.onOpenList,
|
||||
required this.onOpenSettings,
|
||||
required this.onAttachFiles,
|
||||
required this.captured,
|
||||
this.attachmentPicking,
|
||||
super.key,
|
||||
});
|
||||
@ -50,6 +53,9 @@ class CaptureAppBar extends StatelessWidget implements PreferredSizeWidget {
|
||||
/// Receives files picked with the 📎 action.
|
||||
final ValueChanged<List<XFile>> onAttachFiles;
|
||||
|
||||
/// Counts committed captures; each change plays the confirmation mark.
|
||||
final ValueListenable<int> captured;
|
||||
|
||||
/// The picker behind 📎; null uses the platform one.
|
||||
final AttachmentPicking? attachmentPicking;
|
||||
|
||||
@ -114,6 +120,7 @@ class CaptureAppBar extends StatelessWidget implements PreferredSizeWidget {
|
||||
);
|
||||
},
|
||||
),
|
||||
CaptureConfirmMark(captured: captured),
|
||||
IconButton(
|
||||
tooltip: 'Settings',
|
||||
onPressed: onOpenSettings,
|
||||
|
||||
91
lib/ui/capture_confirm_mark.dart
Normal file
91
lib/ui/capture_confirm_mark.dart
Normal file
@ -0,0 +1,91 @@
|
||||
/// The checkmark confirming a capture; static under "remove animations".
|
||||
library;
|
||||
|
||||
import 'package:design_system/design_system.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// Plays once each time [captured] changes value.
|
||||
class CaptureConfirmMark extends StatefulWidget {
|
||||
/// Creates the mark.
|
||||
const CaptureConfirmMark({required this.captured, super.key});
|
||||
|
||||
/// Key of the checkmark icon while it is visible.
|
||||
static const ValueKey<String> iconKey = ValueKey('capture-confirm-icon');
|
||||
|
||||
/// Width always reserved, so the counter beside it never moves.
|
||||
static const double slotWidth = 24;
|
||||
|
||||
/// Fade in, hold and fade out: three [AppDuration.base] thirds.
|
||||
static final Duration duration = AppDuration.base * 3;
|
||||
|
||||
/// Counts captures; each change plays the confirmation.
|
||||
final ValueListenable<int> captured;
|
||||
|
||||
@override
|
||||
State<CaptureConfirmMark> createState() => _CaptureConfirmMarkState();
|
||||
}
|
||||
|
||||
class _CaptureConfirmMarkState extends State<CaptureConfirmMark>
|
||||
with SingleTickerProviderStateMixin {
|
||||
late final AnimationController _controller = AnimationController(
|
||||
vsync: this,
|
||||
duration: CaptureConfirmMark.duration,
|
||||
animationBehavior: AnimationBehavior.preserve,
|
||||
);
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
widget.captured.addListener(_play);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
widget.captured.removeListener(_play);
|
||||
_controller.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _play() => _controller.forward(from: 0);
|
||||
|
||||
double _opacity({required bool reduced}) {
|
||||
final t = _controller.value;
|
||||
if (reduced || (t >= 1 / 3 && t < 2 / 3)) return 1;
|
||||
if (t < 1 / 3) return AppCurve.decelerate.transform(t * 3);
|
||||
return 1 - AppCurve.accelerate.transform((t - 2 / 3) * 3);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final reduced = MediaQuery.disableAnimationsOf(context);
|
||||
return SizedBox(
|
||||
width: CaptureConfirmMark.slotWidth,
|
||||
child: AnimatedBuilder(
|
||||
animation: _controller,
|
||||
builder: (context, _) {
|
||||
if (!_controller.isAnimating) return const SizedBox.shrink();
|
||||
return Opacity(
|
||||
opacity: _opacity(reduced: reduced),
|
||||
child: const _CheckIcon(),
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _CheckIcon extends StatelessWidget {
|
||||
const _CheckIcon();
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final color = Theme.of(context).colorScheme.primary;
|
||||
return Icon(
|
||||
Icons.check_circle,
|
||||
key: CaptureConfirmMark.iconKey,
|
||||
size: 18,
|
||||
color: color,
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -38,6 +38,10 @@ class CaptureDraft {
|
||||
/// yet, so the first write still reports the note as created.
|
||||
bool _reserved = false;
|
||||
|
||||
/// Whether a note with content has been persisted for this draft, i.e.
|
||||
/// whether committing it is a real capture.
|
||||
bool get hasCapture => _id != null && !_reserved && _text.trim().isNotEmpty;
|
||||
|
||||
/// The draft's priority, applied to every write.
|
||||
Priority priority = Priority.defaultValue;
|
||||
|
||||
|
||||
@ -1,9 +1,9 @@
|
||||
import 'dart:async';
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:crdt_sync/crdt_sync.dart';
|
||||
import 'package:design_system/design_system.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:todo/analytics/analytics_event.dart';
|
||||
import 'package:todo/analytics/analytics_service.dart';
|
||||
@ -15,6 +15,7 @@ import 'package:todo/data/note_template.dart';
|
||||
import 'package:todo/sync/firebase_backend.dart';
|
||||
import 'package:todo/sync/local_backup.dart';
|
||||
import 'package:todo/sync/sync_settings.dart';
|
||||
import 'package:todo/ui/app_route.dart';
|
||||
import 'package:todo/ui/attachment_picking.dart';
|
||||
import 'package:todo/ui/capture_app_bar.dart';
|
||||
import 'package:todo/ui/capture_draft.dart';
|
||||
@ -71,6 +72,9 @@ class _CaptureScreenState extends State<CaptureScreen>
|
||||
|
||||
final SyncStatusStore _syncStatus = SyncStatusStore();
|
||||
|
||||
/// Bumped once per committed capture; drives the confirmation checkmark.
|
||||
final ValueNotifier<int> _captures = ValueNotifier<int>(0);
|
||||
|
||||
/// Runs sync passes and records their outcome; see [CaptureSyncRunner].
|
||||
late final CaptureSyncRunner _runner = CaptureSyncRunner(
|
||||
repository: widget.repository,
|
||||
@ -130,6 +134,7 @@ class _CaptureScreenState extends State<CaptureScreen>
|
||||
_localBackup.dispose();
|
||||
_draft.dispose();
|
||||
_syncStatus.dispose();
|
||||
_captures.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@ -150,6 +155,7 @@ class _CaptureScreenState extends State<CaptureScreen>
|
||||
onOpenSettings: _openSettings,
|
||||
onAttachFiles: _attachFiles,
|
||||
attachmentPicking: widget.attachmentPicking,
|
||||
captured: _captures,
|
||||
),
|
||||
body: _captureBody(advanced: advanced),
|
||||
);
|
||||
|
||||
@ -66,8 +66,9 @@ extension _CaptureSyncBehaviour on _CaptureScreenState {
|
||||
final current = _settings ?? await SyncSettings.load();
|
||||
if (!mounted) return;
|
||||
await Navigator.of(context).push<SyncSettings>(
|
||||
MaterialPageRoute(
|
||||
builder: (_) => SettingsScreen(
|
||||
appRoute(
|
||||
context,
|
||||
(_) => SettingsScreen(
|
||||
initial: current,
|
||||
repository: widget.repository,
|
||||
appSettings: widget.appSettings,
|
||||
@ -87,8 +88,9 @@ extension _CaptureSyncBehaviour on _CaptureScreenState {
|
||||
void _openList() {
|
||||
_logEvent('screen_view', params: {'screen': 'notes_list'});
|
||||
Navigator.of(context).push<void>(
|
||||
MaterialPageRoute(
|
||||
builder: (_) => NotesListScreen(
|
||||
appRoute(
|
||||
context,
|
||||
(_) => NotesListScreen(
|
||||
repository: widget.repository,
|
||||
appSettings: widget.appSettings,
|
||||
),
|
||||
@ -206,10 +208,15 @@ extension _CaptureSyncBehaviour on _CaptureScreenState {
|
||||
}
|
||||
|
||||
/// Finalises the current idea and resets the field to a fresh template.
|
||||
/// The field going blank is the only feedback needed — autosave already
|
||||
/// persisted every keystroke, so there is nothing left to confirm.
|
||||
/// Autosave already persisted every keystroke, so the only thing left to
|
||||
/// give is the confirmation -- and only when a note was really captured.
|
||||
/// The haptic fires here, on the tap, before anything touches the network.
|
||||
void _saveAndReset() {
|
||||
_logEvent('new_note_reset');
|
||||
if (_draft.hasCapture) {
|
||||
unawaited(HapticFeedback.lightImpact());
|
||||
_captures.value++;
|
||||
}
|
||||
_rebuild(() {
|
||||
// Bumping the generation remounts NoteForm, which resets the chrome
|
||||
// gate to visible for free -- no separate flag to keep in step.
|
||||
|
||||
@ -17,6 +17,7 @@ import 'package:todo/attachments/image_password_store.dart';
|
||||
import 'package:todo/attachments/image_store_api.dart';
|
||||
import 'package:todo/attachments/image_store_scope.dart';
|
||||
import 'package:todo/images/dufs_image_client.dart';
|
||||
import 'package:todo/ui/app_route.dart';
|
||||
|
||||
/// The command that creates the login, shown wherever it is missing.
|
||||
const kAddLoginCommand =
|
||||
@ -37,9 +38,7 @@ class CloudImagesTile extends StatelessWidget {
|
||||
subtitle: const Text('Where attached images and files upload (dufs)'),
|
||||
trailing: const Icon(Icons.chevron_right),
|
||||
onTap: () => Navigator.of(context).push<void>(
|
||||
MaterialPageRoute(
|
||||
builder: (_) => CloudImagesScreen(httpClient: httpClient),
|
||||
),
|
||||
appRoute(context, (_) => CloudImagesScreen(httpClient: httpClient)),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@ -7,6 +7,7 @@ import 'package:flutter/material.dart';
|
||||
import 'package:todo/attachments/image_store_api.dart';
|
||||
import 'package:todo/attachments/image_store_scope.dart';
|
||||
import 'package:todo/images/attachment_ref.dart';
|
||||
import 'package:todo/ui/app_route.dart';
|
||||
import 'package:todo/ui/images/image_viewer_screen.dart';
|
||||
import 'package:todo/ui/images/local_image.dart';
|
||||
|
||||
@ -39,9 +40,7 @@ class ImageEmbed extends StatelessWidget {
|
||||
onTap: source is MissingImageSource
|
||||
? null
|
||||
: () => Navigator.of(context).push<void>(
|
||||
MaterialPageRoute(
|
||||
builder: (_) => ImageViewerScreen(source: source),
|
||||
),
|
||||
appRoute(context, (_) => ImageViewerScreen(source: source)),
|
||||
),
|
||||
child: ClipRRect(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
|
||||
10
lib/ui/motion.dart
Normal file
10
lib/ui/motion.dart
Normal file
@ -0,0 +1,10 @@
|
||||
/// Reduced-motion handling shared by every animated surface.
|
||||
library;
|
||||
|
||||
import 'package:design_system/design_system.dart';
|
||||
import 'package:flutter/widgets.dart';
|
||||
|
||||
/// [token] unless the OS "remove animations" setting is on, in which case
|
||||
/// [AppDuration.instant]. Haptics are not motion and never go through this.
|
||||
Duration motionDuration(BuildContext context, Duration token) =>
|
||||
MediaQuery.disableAnimationsOf(context) ? AppDuration.instant : token;
|
||||
@ -10,6 +10,7 @@ import 'package:design_system/design_system.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:todo/data/note.dart';
|
||||
import 'package:todo/data/note_template.dart';
|
||||
import 'package:todo/ui/note_sheet_details.dart';
|
||||
import 'package:todo/ui/note_task_details.dart';
|
||||
|
||||
/// The per-note bottom sheet: status/priority chips, and delete.
|
||||
@ -66,6 +67,7 @@ class _NoteActionsSheetState extends State<NoteActionsSheet> {
|
||||
maxLines: 2,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
NoteSheetDetails(note: widget.note),
|
||||
const SizedBox(height: 16),
|
||||
_EnumChips<Status>(
|
||||
label: 'Status',
|
||||
|
||||
@ -11,9 +11,11 @@
|
||||
/// structure here is load-bearing rather than incidental.
|
||||
library;
|
||||
|
||||
import 'package:design_system/design_system.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'package:todo/data/note_template.dart';
|
||||
import 'package:todo/ui/motion.dart';
|
||||
|
||||
/// One step of the guided editor: label, guidance, input, and navigation.
|
||||
class NoteEditorStepPage extends StatelessWidget {
|
||||
@ -77,7 +79,13 @@ class NoteEditorStepPage extends StatelessWidget {
|
||||
Text('${index + 1} / $total', style: theme.textTheme.labelMedium),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: LinearProgressIndicator(value: (index + 1) / total),
|
||||
child: TweenAnimationBuilder<double>(
|
||||
tween: Tween<double>(end: (index + 1) / total),
|
||||
duration: motionDuration(context, AppDuration.base),
|
||||
curve: AppCurve.standard,
|
||||
builder: (_, value, _) =>
|
||||
LinearProgressIndicator(value: value),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
|
||||
115
lib/ui/note_grid_tile.dart
Normal file
115
lib/ui/note_grid_tile.dart
Normal file
@ -0,0 +1,115 @@
|
||||
/// One compact tile of the notes grid: title plus priority and status cues.
|
||||
library;
|
||||
|
||||
import 'package:design_system/design_system.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'package:todo/data/note.dart';
|
||||
import 'package:todo/data/note_template.dart';
|
||||
|
||||
/// A note as a grid cell. It fills whatever cell it is given.
|
||||
class NoteGridTile extends StatelessWidget {
|
||||
/// Creates a tile for [note].
|
||||
const NoteGridTile({
|
||||
required this.note,
|
||||
required this.onTap,
|
||||
required this.onActions,
|
||||
super.key,
|
||||
});
|
||||
|
||||
/// The note this tile displays.
|
||||
final Note note;
|
||||
|
||||
/// Open the full note.
|
||||
final VoidCallback onTap;
|
||||
|
||||
/// Open the per-note sheet (body, dates, priority/status, delete).
|
||||
final VoidCallback onActions;
|
||||
|
||||
/// Danger for high, the accent for medium, muted for low.
|
||||
Color accentFor(ColorScheme scheme) => switch (note.priority) {
|
||||
Priority.high => scheme.error,
|
||||
Priority.medium => scheme.primary,
|
||||
Priority.low => scheme.outline,
|
||||
};
|
||||
|
||||
static IconData _statusIcon(Status s) => switch (s) {
|
||||
Status.todo => Icons.radio_button_unchecked,
|
||||
Status.inProgress => Icons.timelapse,
|
||||
Status.done => Icons.check_circle_outline,
|
||||
Status.abandoned => Icons.cancel_outlined,
|
||||
};
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
final scheme = theme.colorScheme;
|
||||
final title = noteTitle(note.text);
|
||||
final cue = theme.textTheme.labelSmall;
|
||||
final closed =
|
||||
note.status == Status.done || note.status == Status.abandoned;
|
||||
return Material(
|
||||
color: scheme.surfaceContainerHigh,
|
||||
borderRadius: BorderRadius.circular(AppRadius.md),
|
||||
clipBehavior: Clip.antiAlias,
|
||||
child: InkWell(
|
||||
onTap: onTap,
|
||||
onLongPress: onActions,
|
||||
child: Container(
|
||||
decoration: BoxDecoration(
|
||||
border: Border(
|
||||
left: BorderSide(color: accentFor(scheme), width: 4),
|
||||
),
|
||||
),
|
||||
padding: const EdgeInsets.fromLTRB(
|
||||
AppSpacing.sm,
|
||||
AppSpacing.sm,
|
||||
AppSpacing.sm,
|
||||
AppSpacing.xs,
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
// Expanded: a big text scale shortens the title, never overflows.
|
||||
Expanded(
|
||||
child: Text(
|
||||
title.isEmpty ? '(empty)' : title,
|
||||
maxLines: 3,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: theme.textTheme.bodyMedium?.copyWith(
|
||||
color: closed ? scheme.onSurfaceVariant : null,
|
||||
decoration: closed ? TextDecoration.lineThrough : null,
|
||||
),
|
||||
),
|
||||
),
|
||||
Row(
|
||||
children: [
|
||||
Icon(
|
||||
_statusIcon(note.status),
|
||||
size: 14,
|
||||
color: scheme.onSurfaceVariant,
|
||||
),
|
||||
const SizedBox(width: AppSpacing.xs),
|
||||
Flexible(
|
||||
child: Text(
|
||||
note.status.label,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: cue,
|
||||
),
|
||||
),
|
||||
const Spacer(),
|
||||
Text(
|
||||
note.priority.label,
|
||||
maxLines: 1,
|
||||
style: cue?.copyWith(color: accentFor(scheme)),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
50
lib/ui/note_sheet_details.dart
Normal file
50
lib/ui/note_sheet_details.dart
Normal file
@ -0,0 +1,50 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'package:todo/data/note.dart';
|
||||
import 'package:todo/images/attachment_links.dart';
|
||||
|
||||
/// [text] without the line that serves as the title.
|
||||
String noteBodyOf(String text) {
|
||||
final lines = text.split('\n');
|
||||
final title = lines.indexWhere(
|
||||
(l) => l.trim().isNotEmpty && attachmentOfLine(l.trim()) == null,
|
||||
);
|
||||
if (title < 0) return text.trim();
|
||||
return [...lines.take(title), ...lines.skip(title + 1)].join('\n').trim();
|
||||
}
|
||||
|
||||
String _stamp(DateTime t) {
|
||||
String two(int n) => n.toString().padLeft(2, '0');
|
||||
final date = '${t.year}-${two(t.month)}-${two(t.day)}';
|
||||
return '$date ${two(t.hour)}:${two(t.minute)}';
|
||||
}
|
||||
|
||||
/// What a grid tile leaves out: the note body and its two dates.
|
||||
class NoteSheetDetails extends StatelessWidget {
|
||||
/// Shows the body and the dates of [note].
|
||||
const NoteSheetDetails({required this.note, super.key});
|
||||
|
||||
/// The note being shown.
|
||||
final Note note;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context).textTheme;
|
||||
final body = noteBodyOf(note.text);
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
if (body.isNotEmpty) ...[
|
||||
const SizedBox(height: 12),
|
||||
Text(body, style: theme.bodyMedium),
|
||||
],
|
||||
const SizedBox(height: 12),
|
||||
Text(
|
||||
'Edited ${_stamp(note.updatedAt)}'
|
||||
' · Created ${_stamp(note.createdAt)}',
|
||||
style: theme.bodySmall,
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
76
lib/ui/notes_grid.dart
Normal file
76
lib/ui/notes_grid.dart
Normal file
@ -0,0 +1,76 @@
|
||||
import 'dart:math' as math;
|
||||
|
||||
import 'package:design_system/design_system.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'package:todo/data/note.dart';
|
||||
import 'package:todo/ui/note_grid_tile.dart';
|
||||
|
||||
/// Below this width the notes list is a grid; at or above it, the list.
|
||||
const double kNotesGridMaxWidth = 600;
|
||||
|
||||
const _columns = 2;
|
||||
const double _gap = AppSpacing.sm;
|
||||
const double _sidePadding = AppSpacing.md - AppSpacing.xs;
|
||||
const _minTileHeight = 96.0;
|
||||
|
||||
double _tileHeightFor(double height) {
|
||||
final rows = math.max(1, ((height + _gap) / (_minTileHeight + _gap)).floor());
|
||||
return (height + _gap) / rows - _gap;
|
||||
}
|
||||
|
||||
/// Phone notes list: two columns, scrolling only past one screenful.
|
||||
class NotesGrid extends StatelessWidget {
|
||||
/// Creates the grid; [onOpen] and [onActions] get the tapped note.
|
||||
const NotesGrid({
|
||||
required this.notes,
|
||||
required this.onOpen,
|
||||
required this.onActions,
|
||||
super.key,
|
||||
});
|
||||
|
||||
/// Notes in display order.
|
||||
final List<Note> notes;
|
||||
|
||||
/// Tap on a tile.
|
||||
final ValueChanged<Note> onOpen;
|
||||
|
||||
/// Long-press on a tile.
|
||||
final ValueChanged<Note> onActions;
|
||||
|
||||
Widget _tile(Note note) {
|
||||
return NoteGridTile(
|
||||
key: ValueKey(note.id),
|
||||
note: note,
|
||||
onTap: () => onOpen(note),
|
||||
onActions: () => onActions(note),
|
||||
);
|
||||
}
|
||||
|
||||
SliverGridDelegate _delegate(double viewportHeight) {
|
||||
return SliverGridDelegateWithFixedCrossAxisCount(
|
||||
crossAxisCount: _columns,
|
||||
mainAxisSpacing: _gap,
|
||||
crossAxisSpacing: _gap,
|
||||
mainAxisExtent: _tileHeightFor(viewportHeight),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(top: _gap),
|
||||
child: SafeArea(
|
||||
top: false,
|
||||
child: LayoutBuilder(
|
||||
builder: (context, box) => GridView.builder(
|
||||
padding: const EdgeInsets.symmetric(horizontal: _sidePadding),
|
||||
gridDelegate: _delegate(box.maxHeight),
|
||||
itemCount: notes.length,
|
||||
itemBuilder: (context, i) => _tile(notes[i]),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -10,6 +10,7 @@ import 'package:flutter/material.dart';
|
||||
import 'package:todo/data/app_settings.dart';
|
||||
import 'package:todo/data/note.dart';
|
||||
import 'package:todo/data/note_repository.dart';
|
||||
import 'package:todo/ui/app_route.dart';
|
||||
import 'package:todo/ui/note_actions_sheet.dart';
|
||||
import 'package:todo/ui/note_detail_screen.dart';
|
||||
|
||||
@ -24,8 +25,9 @@ Future<void> openNote(
|
||||
// re-focuses it on return, so backing out of a note would pop the keyboard.
|
||||
FocusManager.instance.primaryFocus?.unfocus();
|
||||
await Navigator.of(context).push<void>(
|
||||
MaterialPageRoute(
|
||||
builder: (_) => NoteDetailScreen(
|
||||
appRoute(
|
||||
context,
|
||||
(_) => NoteDetailScreen(
|
||||
note: note,
|
||||
repository: repository,
|
||||
appSettings: appSettings,
|
||||
|
||||
@ -7,6 +7,7 @@ import 'package:todo/data/note.dart';
|
||||
import 'package:todo/data/note_repository.dart';
|
||||
import 'package:todo/ui/note_tile.dart';
|
||||
import 'package:todo/ui/notes_filter_sheet.dart';
|
||||
import 'package:todo/ui/notes_grid.dart';
|
||||
import 'package:todo/ui/notes_list_defaults.dart';
|
||||
import 'package:todo/ui/notes_list_navigation.dart';
|
||||
|
||||
@ -197,21 +198,27 @@ class _NotesListScreenState extends State<NotesListScreen> {
|
||||
),
|
||||
);
|
||||
}
|
||||
return ListView.separated(
|
||||
itemCount: notes.length,
|
||||
separatorBuilder: (_, _) => const Divider(height: 1),
|
||||
itemBuilder: (context, i) => NoteTile(
|
||||
key: ValueKey(notes[i].id),
|
||||
note: notes[i],
|
||||
onTap: () => openNote(
|
||||
context,
|
||||
notes[i],
|
||||
widget.repository,
|
||||
widget.appSettings,
|
||||
),
|
||||
onActions: () =>
|
||||
openNoteActions(context, notes[i], widget.repository),
|
||||
),
|
||||
void open(Note n) =>
|
||||
openNote(context, n, widget.repository, widget.appSettings);
|
||||
void actions(Note n) =>
|
||||
openNoteActions(context, n, widget.repository);
|
||||
return LayoutBuilder(
|
||||
builder: (context, box) => box.maxWidth < kNotesGridMaxWidth
|
||||
? NotesGrid(
|
||||
notes: notes,
|
||||
onOpen: open,
|
||||
onActions: actions,
|
||||
)
|
||||
: ListView.separated(
|
||||
itemCount: notes.length,
|
||||
separatorBuilder: (_, _) => const Divider(height: 1),
|
||||
itemBuilder: (context, i) => NoteTile(
|
||||
key: ValueKey(notes[i].id),
|
||||
note: notes[i],
|
||||
onTap: () => open(notes[i]),
|
||||
onActions: () => actions(notes[i]),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
|
||||
@ -14,6 +14,7 @@ import 'package:todo/sync/firebase_backend.dart';
|
||||
import 'package:todo/sync/google_sign_in_backend.dart';
|
||||
import 'package:todo/sync/notes_markdown.dart';
|
||||
import 'package:todo/sync/sync_settings.dart';
|
||||
import 'package:todo/ui/app_route.dart';
|
||||
import 'package:todo/ui/cloud_images_settings.dart';
|
||||
import 'package:todo/ui/github_mirror_screen.dart';
|
||||
|
||||
@ -168,8 +169,9 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
|
||||
Future<void> _openSyncSettings() async {
|
||||
await Navigator.of(context).push<void>(
|
||||
MaterialPageRoute(
|
||||
builder: (_) => SyncSettingsScreen(
|
||||
appRoute(
|
||||
context,
|
||||
(_) => SyncSettingsScreen(
|
||||
accountLoader: widget.accountLoader ?? loadAccount,
|
||||
accountSaver: widget.accountSaver ?? saveAccount,
|
||||
accountClearer: widget.accountClearer ?? clearAccount,
|
||||
@ -186,8 +188,9 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
|
||||
Future<void> _openGitHubMirror() async {
|
||||
await Navigator.of(context).push<SyncSettings>(
|
||||
MaterialPageRoute(
|
||||
builder: (_) => GitHubMirrorScreen(
|
||||
appRoute(
|
||||
context,
|
||||
(_) => GitHubMirrorScreen(
|
||||
initial: widget.initial,
|
||||
repository: widget.repository,
|
||||
appSettings: widget.appSettings,
|
||||
|
||||
6
mcp/.gitignore
vendored
6
mcp/.gitignore
vendored
@ -1,6 +0,0 @@
|
||||
__pycache__/
|
||||
*.egg-info/
|
||||
*.pyc
|
||||
.pytest_cache/
|
||||
.mypy_cache/
|
||||
.ruff_cache/
|
||||
@ -1,47 +1,30 @@
|
||||
# todo backlog MCP server
|
||||
# todo MCP server
|
||||
|
||||
A small, standalone, **read-only** [MCP](https://modelcontextprotocol.io)
|
||||
server that lets Claude Code (and its subagents) query the todo app's backlog.
|
||||
Repo tasks for any Claude session (local or cloud): `add_task`, `list_tasks`,
|
||||
`get_task`, `update_task`, `close_task` (refused without evidence),
|
||||
`search_tasks`. Dart, Streamable HTTP on `127.0.0.1:8735/mcp`; Caddy
|
||||
publishes it as `https://todo.kuhy.duckdns.org/mcp`.
|
||||
|
||||
The todo app is Dart/Flutter and stores notes in a `sqlite_crdt` database that
|
||||
must never be touched from outside the app (CRDT writes corrupt cross-device
|
||||
merge). Instead, this server reads the app's exported `BACKLOG.md` — the
|
||||
canonical NotesMarkdown snapshot written by **Settings → "Export notes"**.
|
||||
The server is one more sync node: it reuses `lib/cli` (`CliSession`,
|
||||
`SyncService`) and writes its own CRDT log at
|
||||
`todo-sync/notes/<node id>.json` plus `todo-sync/revs/<node id>`.
|
||||
Code: `lib/mcp/`, entrypoint `mcp/todo_mcp.dart`, tests `test/mcp/`.
|
||||
|
||||
## Staleness note
|
||||
| What | Where |
|
||||
|---|---|
|
||||
| Firebase seed (read once) | `~/.config/todo-mcp/firebase_auth.json` |
|
||||
| Bearer token hashes | `~/.config/todo-mcp/tokens` (`<sha256> <env>`) |
|
||||
| Log, node id, session copy (0600) | `~/.local/share/todo-mcp/` |
|
||||
| Binary | `~/.local/lib/todo-mcp/todo_mcp` |
|
||||
|
||||
`BACKLOG.md` is a *manual* export, so it can be out of date. Every tool result
|
||||
includes the file's modification time (`mtime`) so you can judge freshness. If
|
||||
the file is missing, tools return `backlog_found: false` with a message telling
|
||||
you to export it from the app — they never crash.
|
||||
|
||||
## Tools (all read-only)
|
||||
|
||||
- `list_backlog(priority: str | None = None, status: str | None = None, limit: int = 100)`
|
||||
— notes, optionally filtered by `priority` (`low`/`medium`/`high`) and/or
|
||||
`status` (`todo`/`inProgress`/`done`/`abandoned`), plus `total`, `returned`,
|
||||
and `mtime`.
|
||||
- `get_note(note_id: str)` — one note by id, or `found: false`.
|
||||
- `backlog_stats()` — counts `by_status` and `by_priority`, `total`, and `mtime`.
|
||||
|
||||
Nothing here writes to the database or to `BACKLOG.md`.
|
||||
|
||||
## Setup
|
||||
## One-time setup
|
||||
|
||||
```bash
|
||||
mcp/scripts/setup_mcp.sh
|
||||
python3 ~/src/utils/crdt-sync/tool/seed_session.py --app todo-mcp
|
||||
mcp/mint_token.sh pc # prints the token once; export it as TODO_MCP_TOKEN
|
||||
mcp/install.sh # build + install the unit
|
||||
systemctl --user enable --now todo-mcp.service
|
||||
```
|
||||
|
||||
This creates `~/.venvs/todo-mcp`, installs this package (which pulls in the
|
||||
`mcp` SDK), and verifies the imports. The server is registered via the
|
||||
repo-root `.mcp.json`; restart Claude Code in this repo and approve the project
|
||||
MCP server prompt. Override the backlog location with `TODO_BACKLOG_PATH`
|
||||
(defaults to `~/src/todo/BACKLOG.md`).
|
||||
|
||||
## Development
|
||||
|
||||
```bash
|
||||
~/.venvs/todo-mcp/bin/pip install -e mcp pytest pytest-cov ruff mypy
|
||||
~/.venvs/todo-mcp/bin/python -m pytest mcp/todo_mcp/tests \
|
||||
--cov=todo_mcp --cov-branch --cov-report=term-missing --cov-fail-under=100
|
||||
```
|
||||
Deploy a new build: `mcp/install.sh` (restarts a running unit).
|
||||
Revoke a token: delete its line in `tokens`; no restart needed.
|
||||
|
||||
27
mcp/install.sh
Executable file
27
mcp/install.sh
Executable file
@ -0,0 +1,27 @@
|
||||
#!/bin/bash
|
||||
# Deploy: frozen binary + systemd --user unit; restarts the unit if running.
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
readonly ROOT
|
||||
readonly BIN_DIR="${HOME}/.local/lib/todo-mcp"
|
||||
readonly UNIT_DIR="${HOME}/.config/systemd/user"
|
||||
readonly UNIT="todo-mcp.service"
|
||||
|
||||
main() {
|
||||
mkdir -p "$BIN_DIR" "$UNIT_DIR"
|
||||
(cd "$ROOT" && flutter pub get >/dev/null)
|
||||
(cd "$ROOT" && dart compile exe mcp/todo_mcp.dart -o "$BIN_DIR/todo_mcp.new")
|
||||
mv "$BIN_DIR/todo_mcp.new" "$BIN_DIR/todo_mcp"
|
||||
install -m 644 "$ROOT/mcp/$UNIT" "$UNIT_DIR/$UNIT"
|
||||
systemctl --user daemon-reload
|
||||
if systemctl --user is-active --quiet "$UNIT"; then
|
||||
systemctl --user restart "$UNIT"
|
||||
echo "restarted $UNIT"
|
||||
else
|
||||
echo "installed; start with: systemctl --user enable --now $UNIT"
|
||||
fi
|
||||
}
|
||||
|
||||
main "$@"
|
||||
29
mcp/mint_token.sh
Executable file
29
mcp/mint_token.sh
Executable file
@ -0,0 +1,29 @@
|
||||
#!/bin/bash
|
||||
# Prints a new <env> token once; ~/.config/todo-mcp/tokens keeps only its sha256.
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
readonly CONFIG_DIR="${HOME}/.config/todo-mcp"
|
||||
readonly TOKENS="${CONFIG_DIR}/tokens"
|
||||
|
||||
main() {
|
||||
local env="${1:-}"
|
||||
if [[ ! "$env" =~ ^[a-z0-9_-]+$ ]]; then
|
||||
echo "usage: $(basename "$0") <env> (e.g. pc, cloud)" >&2
|
||||
exit 2
|
||||
fi
|
||||
umask 077
|
||||
mkdir -p "$CONFIG_DIR"
|
||||
local token hash tmp
|
||||
token="$(head -c 32 /dev/urandom | od -An -tx1 | tr -d ' \n')"
|
||||
hash="$(printf '%s' "$token" | sha256sum | cut -d' ' -f1)"
|
||||
tmp="$(mktemp "${TOKENS}.XXXXXX")"
|
||||
if [[ -f "$TOKENS" ]]; then
|
||||
awk -v env="$env" '$2 != env' "$TOKENS" >"$tmp"
|
||||
fi
|
||||
printf '%s %s\n' "$hash" "$env" >>"$tmp"
|
||||
mv "$tmp" "$TOKENS"
|
||||
echo "$token"
|
||||
}
|
||||
|
||||
main "$@"
|
||||
@ -1,134 +0,0 @@
|
||||
[project]
|
||||
name = "todo-mcp"
|
||||
version = "1.0.0"
|
||||
description = "Read-only MCP server over the todo app's exported BACKLOG.md"
|
||||
requires-python = ">=3.14"
|
||||
dependencies = [
|
||||
# The MCP SDK is the only runtime dependency: FastMCP powers the stdio
|
||||
# server. It lives in a dedicated venv (see scripts/setup_mcp.sh /
|
||||
# ../.mcp.json), kept entirely separate from the Dart/Flutter app.
|
||||
"mcp==2.3.0",
|
||||
]
|
||||
|
||||
# Explicit package discovery so ``pip install -e .`` picks up the package and
|
||||
# not the scripts/ dir.
|
||||
[tool.setuptools.packages.find]
|
||||
include = ["todo_mcp*"]
|
||||
|
||||
# ============================================================================
|
||||
# RUFF - Fast Python linter and formatter
|
||||
# ============================================================================
|
||||
[tool.ruff]
|
||||
target-version = "py314"
|
||||
include = ["*.py", "**/*.py"]
|
||||
exclude = [".git", ".venv", "__pycache__", "build", "dist", ".eggs"]
|
||||
|
||||
[tool.ruff.lint]
|
||||
select = ["ALL"]
|
||||
ignore = [
|
||||
"D203", # conflicts with D211
|
||||
"D213", # conflicts with D212
|
||||
"COM812", # formatter handles this
|
||||
"ISC001", # formatter may create these
|
||||
"S603", # prone to false positives
|
||||
]
|
||||
fixable = ["ALL"]
|
||||
unfixable = []
|
||||
|
||||
[tool.ruff.lint.per-file-ignores]
|
||||
"**/tests/**/*.py" = ["ARG", "D", "PLC0415", "PLR2004", "S101", "SLF001"]
|
||||
"**/test_*.py" = ["ARG", "D", "PLC0415", "PLR2004", "S101", "SLF001"]
|
||||
|
||||
[tool.ruff.lint.pydocstyle]
|
||||
convention = "google"
|
||||
|
||||
[tool.ruff.lint.isort]
|
||||
force-single-line = false
|
||||
force-sort-within-sections = true
|
||||
known-first-party = ["todo_mcp"]
|
||||
|
||||
[tool.ruff.lint.flake8-quotes]
|
||||
docstring-quotes = "double"
|
||||
inline-quotes = "double"
|
||||
|
||||
[tool.ruff.lint.flake8-tidy-imports]
|
||||
ban-relative-imports = "all"
|
||||
|
||||
[tool.ruff.format]
|
||||
quote-style = "double"
|
||||
indent-style = "space"
|
||||
skip-magic-trailing-comma = false
|
||||
line-ending = "auto"
|
||||
docstring-code-format = true
|
||||
|
||||
# ============================================================================
|
||||
# MYPY - Static type checker
|
||||
# ============================================================================
|
||||
[tool.mypy]
|
||||
python_version = "3.14"
|
||||
strict = true
|
||||
warn_return_any = true
|
||||
warn_unused_configs = true
|
||||
disallow_untyped_defs = true
|
||||
disallow_incomplete_defs = true
|
||||
check_untyped_defs = true
|
||||
disallow_untyped_decorators = true
|
||||
no_implicit_optional = true
|
||||
warn_redundant_casts = true
|
||||
warn_unused_ignores = true
|
||||
warn_no_return = true
|
||||
warn_unreachable = true
|
||||
disallow_any_unimported = true
|
||||
disallow_any_explicit = false
|
||||
disallow_any_generics = true
|
||||
disallow_subclassing_any = true
|
||||
strict_equality = true
|
||||
extra_checks = true
|
||||
ignore_missing_imports = true
|
||||
show_error_codes = true
|
||||
color_output = true
|
||||
exclude = [".venv/"]
|
||||
|
||||
# ============================================================================
|
||||
# PYTEST
|
||||
# ============================================================================
|
||||
[tool.pytest.ini_options]
|
||||
testpaths = ["todo_mcp/tests"]
|
||||
python_files = ["test_*.py", "*_test.py"]
|
||||
python_classes = ["Test*"]
|
||||
python_functions = ["test_*"]
|
||||
addopts = [
|
||||
"-v",
|
||||
"--strict-markers",
|
||||
"--strict-config",
|
||||
"-ra",
|
||||
"--cov=todo_mcp",
|
||||
"--cov-branch",
|
||||
"--cov-report=term-missing",
|
||||
]
|
||||
filterwarnings = [
|
||||
"error",
|
||||
"ignore::DeprecationWarning",
|
||||
"default::pytest.PytestUnraisableExceptionWarning",
|
||||
]
|
||||
|
||||
# ============================================================================
|
||||
# COVERAGE
|
||||
# ============================================================================
|
||||
[tool.coverage.run]
|
||||
source = ["todo_mcp"]
|
||||
branch = true
|
||||
omit = ["*/__pycache__/*", "*/tests/*", "*/.venv/*"]
|
||||
|
||||
[tool.coverage.report]
|
||||
fail_under = 100
|
||||
show_missing = true
|
||||
skip_covered = false
|
||||
exclude_lines = [
|
||||
"pragma: no cover",
|
||||
"raise NotImplementedError",
|
||||
"raise AssertionError",
|
||||
"if TYPE_CHECKING:",
|
||||
'if __name__ == "__main__":',
|
||||
]
|
||||
partial_branches = ["pragma: no branch"]
|
||||
@ -1,41 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
# ============================================================================
|
||||
# Set up the dedicated virtualenv that hosts the todo backlog MCP server.
|
||||
# Claude Code spawns this interpreter (see the repo-root .mcp.json) to run
|
||||
# `python -m todo_mcp._mcp` over stdio.
|
||||
#
|
||||
# The MCP SDK (`mcp`) and the `todo_mcp` package live ONLY in this venv — the
|
||||
# todo app itself is Dart/Flutter and has no Python, so this is fully separate.
|
||||
# Both `mcp` and `todo_mcp` must be importable by this one interpreter or the
|
||||
# MCP server fails to start silently.
|
||||
#
|
||||
# Idempotent: safe to re-run to pick up dependency changes.
|
||||
# ============================================================================
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
readonly SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
readonly PKG_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)"
|
||||
readonly VENV_DIR="${HOME}/.venvs/todo-mcp"
|
||||
|
||||
main() {
|
||||
echo "== Setting up MCP venv at ${VENV_DIR} =="
|
||||
|
||||
if [[ ! -d "${VENV_DIR}" ]]; then
|
||||
python3 -m venv "${VENV_DIR}"
|
||||
fi
|
||||
|
||||
"${VENV_DIR}/bin/pip" install --quiet --upgrade pip
|
||||
"${VENV_DIR}/bin/pip" install --quiet -e "${PKG_DIR}"
|
||||
|
||||
echo "== Verifying imports =="
|
||||
"${VENV_DIR}/bin/python" -c \
|
||||
"import mcp, todo_mcp; print('mcp + todo_mcp import OK')"
|
||||
|
||||
echo
|
||||
echo "Done. The server is registered via $(cd "${PKG_DIR}/.." && pwd)/.mcp.json"
|
||||
echo "Restart Claude Code in this repo and approve the project MCP server prompt."
|
||||
}
|
||||
|
||||
main "$@"
|
||||
12
mcp/todo-mcp.service
Normal file
12
mcp/todo-mcp.service
Normal file
@ -0,0 +1,12 @@
|
||||
[Unit]
|
||||
Description=todo MCP server (Streamable HTTP, loopback :8735)
|
||||
After=network-online.target
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
ExecStart=%h/.local/lib/todo-mcp/todo_mcp
|
||||
Restart=on-failure
|
||||
RestartSec=30
|
||||
|
||||
[Install]
|
||||
WantedBy=default.target
|
||||
15
mcp/todo_mcp.dart
Normal file
15
mcp/todo_mcp.dart
Normal file
@ -0,0 +1,15 @@
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:todo/mcp/mcp_main.dart';
|
||||
|
||||
Future<void> main() async {
|
||||
final stop = await startTodoMcp(Platform.environment, stderr);
|
||||
if (stop == null) exit(1);
|
||||
await Future.any([
|
||||
ProcessSignal.sigterm.watch().first,
|
||||
ProcessSignal.sigint.watch().first,
|
||||
]);
|
||||
await stop();
|
||||
exit(0);
|
||||
}
|
||||
@ -1,17 +0,0 @@
|
||||
"""Read-only MCP server package for the ``todo`` Flutter app's backlog.
|
||||
|
||||
The ``todo`` app is Dart/Flutter and stores notes in a ``sqlite_crdt`` database
|
||||
that must never be touched from here (CRDT writes corrupt cross-device merge).
|
||||
Instead, this package reads the app's exported ``BACKLOG.md`` file — the
|
||||
canonical, human-exportable "NotesMarkdown" snapshot — and exposes it to MCP
|
||||
clients (Claude Code and its subagents) as a handful of read-only tools.
|
||||
|
||||
See :mod:`todo_mcp._backlog` for the parser and :mod:`todo_mcp._mcp` for the
|
||||
MCPServer stdio server.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
__all__ = ["__version__"]
|
||||
|
||||
__version__ = "1.0.0"
|
||||
@ -1,141 +0,0 @@
|
||||
"""Parser for the ``todo`` app's exported ``BACKLOG.md`` (NotesMarkdown) file.
|
||||
|
||||
This is a faithful Python re-implementation of the Dart exporter/parser in
|
||||
``todo/lib/sync/notes_markdown.dart``. The exported document is valid Markdown:
|
||||
a one-line header (``<!-- todo-backlog v1 -->``) followed by, per note, an HTML
|
||||
comment metadata marker::
|
||||
|
||||
<!-- @note id="..." priority="medium" status="todo" created="..." updated="..." -->
|
||||
|
||||
whose body (everything up to the next marker, trimmed) is the note's Markdown.
|
||||
|
||||
The functions here are pure and side-effect free so they can be unit-tested in
|
||||
isolation; the MCP layer (:mod:`todo_mcp._mcp`) handles file I/O and staleness.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
import re
|
||||
import uuid
|
||||
|
||||
# Priority/status vocabularies mirror the Dart ``Priority``/``Status`` enums,
|
||||
# which are serialised by their ``.name`` (e.g. ``priority="medium"``). Unknown
|
||||
# or missing values fall back to the same defaults the Dart parser uses, so a
|
||||
# hand-edited file never yields an invalid note.
|
||||
_PRIORITIES = ("low", "medium", "high")
|
||||
_STATUSES = ("todo", "inProgress", "done", "abandoned")
|
||||
_DEFAULT_PRIORITY = "medium"
|
||||
_DEFAULT_STATUS = "todo"
|
||||
|
||||
# Matches a per-note metadata marker at the start of a line (multi-line mode).
|
||||
# The body is everything between one marker and the next (or end of file).
|
||||
_MARKER_PATTERN = re.compile(r"^<!--\s*@note\s+(.*?)\s*-->[ \t]*$", re.MULTILINE)
|
||||
|
||||
# Matches ``key="value"`` attribute pairs inside a marker.
|
||||
_ATTR_PATTERN = re.compile(r'(\w+)="([^"]*)"')
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Note:
|
||||
"""A single parsed backlog note.
|
||||
|
||||
Attributes:
|
||||
id: Stable UUID from the marker, or a freshly minted one when the
|
||||
source marker had no (or a blank) ``id``.
|
||||
title: Human-readable title derived from the body's first line.
|
||||
body: The note's Markdown body, verbatim but trimmed.
|
||||
priority: One of ``low`` / ``medium`` / ``high``.
|
||||
status: One of ``todo`` / ``inProgress`` / ``done`` / ``abandoned``.
|
||||
"""
|
||||
|
||||
id: str
|
||||
title: str
|
||||
body: str
|
||||
priority: str
|
||||
status: str
|
||||
|
||||
|
||||
def _parse_attrs(raw: str) -> dict[str, str]:
|
||||
"""Extract ``key="value"`` pairs from a marker's attribute string.
|
||||
|
||||
Args:
|
||||
raw: The captured text between ``@note`` and the closing ``-->``.
|
||||
|
||||
Returns:
|
||||
A mapping of attribute name to its (possibly empty) string value.
|
||||
"""
|
||||
return {m.group(1): m.group(2) for m in _ATTR_PATTERN.finditer(raw)}
|
||||
|
||||
|
||||
def _normalize(value: str | None, allowed: tuple[str, ...], fallback: str) -> str:
|
||||
"""Return ``value`` if it is a recognised token, else ``fallback``.
|
||||
|
||||
Mirrors the Dart parser's tolerant enum resolution: a missing (``None``) or
|
||||
unknown value degrades to the enum's default rather than raising.
|
||||
|
||||
Args:
|
||||
value: The raw attribute value, or ``None`` if the marker omitted it.
|
||||
allowed: The permitted tokens for this field.
|
||||
fallback: The default token to use when ``value`` is unrecognised.
|
||||
|
||||
Returns:
|
||||
A valid token drawn from ``allowed``.
|
||||
"""
|
||||
return value if value in allowed else fallback
|
||||
|
||||
|
||||
def _derive_title(body: str) -> str:
|
||||
"""Derive a display title from a note's (already-trimmed) body.
|
||||
|
||||
Uses the first line, stripping any leading Markdown heading hashes so a
|
||||
``# Set up my own mail`` heading becomes ``Set up my own mail``. An empty
|
||||
body yields an empty title.
|
||||
|
||||
Args:
|
||||
body: The trimmed Markdown body of the note.
|
||||
|
||||
Returns:
|
||||
The derived title, or an empty string for an empty body.
|
||||
"""
|
||||
if not body:
|
||||
return ""
|
||||
return body.splitlines()[0].lstrip("#").strip()
|
||||
|
||||
|
||||
def parse_backlog(text: str) -> list[Note]:
|
||||
"""Parse an exported ``BACKLOG.md`` document into typed notes.
|
||||
|
||||
Tolerant by design (matching the Dart parser): a missing/blank ``id`` is
|
||||
replaced with a fresh UUID, and unknown/missing ``priority``/``status``
|
||||
values fall back to their defaults, so a partially hand-edited file never
|
||||
raises. The header line and any content before the first marker are ignored.
|
||||
|
||||
Args:
|
||||
text: The full contents of an exported NotesMarkdown document.
|
||||
|
||||
Returns:
|
||||
The notes in document order (empty if there are no ``@note`` markers).
|
||||
"""
|
||||
markers = list(_MARKER_PATTERN.finditer(text))
|
||||
notes: list[Note] = []
|
||||
for i, marker in enumerate(markers):
|
||||
attrs = _parse_attrs(marker.group(1))
|
||||
body_start = marker.end()
|
||||
body_end = markers[i + 1].start() if i + 1 < len(markers) else len(text)
|
||||
body = text[body_start:body_end].strip()
|
||||
|
||||
raw_id = attrs.get("id", "")
|
||||
note_id = raw_id or str(uuid.uuid4())
|
||||
notes.append(
|
||||
Note(
|
||||
id=note_id,
|
||||
title=_derive_title(body),
|
||||
body=body,
|
||||
priority=_normalize(
|
||||
attrs.get("priority"), _PRIORITIES, _DEFAULT_PRIORITY
|
||||
),
|
||||
status=_normalize(attrs.get("status"), _STATUSES, _DEFAULT_STATUS),
|
||||
)
|
||||
)
|
||||
return notes
|
||||
@ -1,214 +0,0 @@
|
||||
"""Read-only MCP server exposing the ``todo`` app's exported backlog.
|
||||
|
||||
Run via the dedicated venv that has ``mcp`` and ``todo_mcp`` installed::
|
||||
|
||||
~/.venvs/todo-mcp/bin/python -m todo_mcp._mcp
|
||||
|
||||
(see ``mcp/scripts/setup_mcp.sh`` and the repo-root ``.mcp.json``).
|
||||
|
||||
Safety invariants (do not break when adding tools):
|
||||
* **READ-ONLY.** Every tool only *reads* ``BACKLOG.md``. Nothing here writes
|
||||
to the file, and nothing ever touches the app's ``sqlite_crdt`` database
|
||||
(CRDT writes corrupt cross-device merge). There is no write tool.
|
||||
* **stdout is the JSON-RPC channel.** This module must never write to stdout;
|
||||
all logging is routed to STDERR below.
|
||||
* **No secret ever leaves.** The backlog holds only user-authored note text;
|
||||
there are no credentials to expose, and no config/token is ever read.
|
||||
|
||||
Because ``BACKLOG.md`` is a *manual* export (the app writes it from Settings →
|
||||
"Export notes"), it may be stale. Every result therefore includes the file's
|
||||
modification time (``mtime``) so a client can judge freshness, and a missing
|
||||
file yields a graceful "please export it" message rather than an error.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
from typing import Any
|
||||
|
||||
from mcp.server.mcpserver import MCPServer
|
||||
|
||||
from todo_mcp._backlog import Note, parse_backlog
|
||||
|
||||
# Log to STDERR only — STDOUT carries the MCP JSON-RPC protocol frames, so a
|
||||
# single stray stdout write would corrupt the stream and kill the session.
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
stream=sys.stderr,
|
||||
format="%(asctime)s [%(levelname)s] todo-mcp: %(message)s",
|
||||
)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# mcp 2.x renamed FastMCP to MCPServer; the decorator and run() API are
|
||||
# unchanged, so only the import and the constructor moved.
|
||||
mcp = MCPServer("todo")
|
||||
|
||||
_DEFAULT_LIST_LIMIT = 100
|
||||
|
||||
|
||||
def _backlog_path() -> Path:
|
||||
"""Resolve the ``BACKLOG.md`` path (env override, else the default).
|
||||
|
||||
Returns:
|
||||
``$TODO_BACKLOG_PATH`` when set, otherwise ``~/src/todo/BACKLOG.md``.
|
||||
"""
|
||||
override = os.environ.get("TODO_BACKLOG_PATH")
|
||||
if override:
|
||||
return Path(override)
|
||||
return Path.home() / "src/todo" / "BACKLOG.md"
|
||||
|
||||
|
||||
def _missing_message() -> str:
|
||||
"""Return the user-facing hint shown when the backlog file is absent."""
|
||||
return (
|
||||
f"BACKLOG.md not found at {_backlog_path()}. Export it from the todo "
|
||||
"app (Settings -> Export notes), then try again."
|
||||
)
|
||||
|
||||
|
||||
def _load_backlog() -> tuple[bool, list[Note], str | None]:
|
||||
"""Load and parse the backlog, reporting existence and file mtime.
|
||||
|
||||
Returns:
|
||||
A ``(found, notes, mtime)`` triple. When the file is absent ``found``
|
||||
is ``False`` and ``notes``/``mtime`` are empty; otherwise ``mtime`` is
|
||||
the file's UTC modification time as an ISO-8601 string.
|
||||
"""
|
||||
path = _backlog_path()
|
||||
try:
|
||||
stat = path.stat()
|
||||
except OSError:
|
||||
return False, [], None
|
||||
mtime = datetime.fromtimestamp(stat.st_mtime, tz=UTC).isoformat()
|
||||
notes = parse_backlog(path.read_text(encoding="utf-8"))
|
||||
return True, notes, mtime
|
||||
|
||||
|
||||
def _note_to_dict(note: Note) -> dict[str, str]:
|
||||
"""Project a :class:`Note` into a JSON-serialisable dict for a tool result.
|
||||
|
||||
Args:
|
||||
note: The parsed note to serialise.
|
||||
|
||||
Returns:
|
||||
The note's fields as a plain string-keyed dict.
|
||||
"""
|
||||
return {
|
||||
"id": note.id,
|
||||
"title": note.title,
|
||||
"priority": note.priority,
|
||||
"status": note.status,
|
||||
"body": note.body,
|
||||
}
|
||||
|
||||
|
||||
@mcp.tool()
|
||||
def list_backlog(
|
||||
priority: str | None = None,
|
||||
status: str | None = None,
|
||||
limit: int = _DEFAULT_LIST_LIMIT,
|
||||
) -> dict[str, Any]:
|
||||
"""List backlog notes, optionally filtered by priority and/or status.
|
||||
|
||||
Args:
|
||||
priority: If given, keep only notes with this priority
|
||||
(``low`` / ``medium`` / ``high``).
|
||||
status: If given, keep only notes with this status
|
||||
(``todo`` / ``inProgress`` / ``done`` / ``abandoned``).
|
||||
limit: Maximum number of notes to return (non-positive returns none).
|
||||
|
||||
Returns:
|
||||
A dict with the matching ``notes`` (capped at ``limit``), the total
|
||||
match count, the number returned, and the backlog file ``mtime``. If
|
||||
the file is missing, ``backlog_found`` is ``False`` and a ``note`` field
|
||||
explains how to export it.
|
||||
"""
|
||||
found, notes, mtime = _load_backlog()
|
||||
if not found:
|
||||
return {"backlog_found": False, "note": _missing_message()}
|
||||
matches = [
|
||||
n
|
||||
for n in notes
|
||||
if (priority is None or n.priority == priority)
|
||||
and (status is None or n.status == status)
|
||||
]
|
||||
capped = matches[: max(0, limit)]
|
||||
return {
|
||||
"backlog_found": True,
|
||||
"mtime": mtime,
|
||||
"total": len(matches),
|
||||
"returned": len(capped),
|
||||
"notes": [_note_to_dict(n) for n in capped],
|
||||
}
|
||||
|
||||
|
||||
@mcp.tool()
|
||||
def get_note(note_id: str) -> dict[str, Any]:
|
||||
"""Fetch a single backlog note by its id.
|
||||
|
||||
Args:
|
||||
note_id: The note's UUID (the ``id`` from its marker).
|
||||
|
||||
Returns:
|
||||
A dict with ``found`` and, on a hit, the ``note`` plus the backlog
|
||||
``mtime``. If the file is missing, ``backlog_found`` is ``False`` and a
|
||||
``note`` field explains how to export it.
|
||||
"""
|
||||
found, notes, mtime = _load_backlog()
|
||||
if not found:
|
||||
return {"backlog_found": False, "found": False, "note": _missing_message()}
|
||||
for note in notes:
|
||||
if note.id == note_id:
|
||||
return {
|
||||
"backlog_found": True,
|
||||
"found": True,
|
||||
"mtime": mtime,
|
||||
"note": _note_to_dict(note),
|
||||
}
|
||||
return {
|
||||
"backlog_found": True,
|
||||
"found": False,
|
||||
"mtime": mtime,
|
||||
"note_id": note_id,
|
||||
}
|
||||
|
||||
|
||||
@mcp.tool()
|
||||
def backlog_stats() -> dict[str, Any]:
|
||||
"""Summarise the backlog: note counts by status and by priority.
|
||||
|
||||
Returns:
|
||||
A dict with the ``total`` note count, ``by_status`` and ``by_priority``
|
||||
count maps, and the backlog ``mtime``. If the file is missing,
|
||||
``backlog_found`` is ``False`` and a ``note`` field explains how to
|
||||
export it.
|
||||
"""
|
||||
found, notes, mtime = _load_backlog()
|
||||
if not found:
|
||||
return {"backlog_found": False, "note": _missing_message()}
|
||||
by_status: dict[str, int] = {}
|
||||
by_priority: dict[str, int] = {}
|
||||
for note in notes:
|
||||
by_status[note.status] = by_status.get(note.status, 0) + 1
|
||||
by_priority[note.priority] = by_priority.get(note.priority, 0) + 1
|
||||
return {
|
||||
"backlog_found": True,
|
||||
"mtime": mtime,
|
||||
"total": len(notes),
|
||||
"by_status": by_status,
|
||||
"by_priority": by_priority,
|
||||
}
|
||||
|
||||
|
||||
def main() -> None:
|
||||
"""Run the MCP server over stdio (STDOUT = JSON-RPC, STDERR = logs)."""
|
||||
logger.info("Starting todo MCP server (python=%s)", sys.executable)
|
||||
mcp.run() # pragma: no cover
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@ -1 +0,0 @@
|
||||
"""Test package for todo_mcp."""
|
||||
@ -1,96 +0,0 @@
|
||||
"""Tests for the NotesMarkdown backlog parser in ``_backlog``."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
|
||||
from todo_mcp._backlog import Note, parse_backlog
|
||||
|
||||
HEADER = "<!-- todo-backlog v1 -->\n\n"
|
||||
|
||||
|
||||
def _marker(**attrs: str) -> str:
|
||||
pairs = " ".join(f'{k}="{v}"' for k, v in attrs.items())
|
||||
return f"<!-- @note {pairs} -->"
|
||||
|
||||
|
||||
class TestParseBacklog:
|
||||
def test_empty_document_has_no_notes(self) -> None:
|
||||
assert parse_backlog("") == []
|
||||
|
||||
def test_header_only_has_no_notes(self) -> None:
|
||||
assert parse_backlog(HEADER) == []
|
||||
|
||||
def test_parses_a_single_note_with_heading_title(self) -> None:
|
||||
doc = (
|
||||
HEADER
|
||||
+ _marker(
|
||||
id="abc",
|
||||
priority="high",
|
||||
status="inProgress",
|
||||
)
|
||||
+ "\n# Set up my own mail\n\nbody text here\n"
|
||||
)
|
||||
notes = parse_backlog(doc)
|
||||
assert len(notes) == 1
|
||||
note = notes[0]
|
||||
assert note == Note(
|
||||
id="abc",
|
||||
title="Set up my own mail",
|
||||
body="# Set up my own mail\n\nbody text here",
|
||||
priority="high",
|
||||
status="inProgress",
|
||||
)
|
||||
|
||||
def test_plain_first_line_becomes_title_verbatim(self) -> None:
|
||||
doc = _marker(id="x", priority="low", status="todo") + "\nInfakt api + mcp\n"
|
||||
(note,) = parse_backlog(doc)
|
||||
assert note.title == "Infakt api + mcp"
|
||||
|
||||
def test_multiple_notes_split_on_markers(self) -> None:
|
||||
doc = (
|
||||
HEADER
|
||||
+ _marker(id="1", priority="low", status="todo")
|
||||
+ "\nfirst\n\n"
|
||||
+ _marker(id="2", priority="medium", status="done")
|
||||
+ "\nsecond\n"
|
||||
)
|
||||
notes = parse_backlog(doc)
|
||||
assert [n.id for n in notes] == ["1", "2"]
|
||||
assert notes[0].body == "first"
|
||||
assert notes[1].body == "second"
|
||||
|
||||
def test_missing_id_gets_fresh_uuid(self) -> None:
|
||||
doc = _marker(priority="low", status="todo") + "\nno id here\n"
|
||||
(note,) = parse_backlog(doc)
|
||||
# A valid UUID string was minted for the absent id.
|
||||
assert uuid.UUID(note.id)
|
||||
|
||||
def test_blank_id_gets_fresh_uuid(self) -> None:
|
||||
doc = _marker(id="", priority="low", status="todo") + "\nblank id\n"
|
||||
(note,) = parse_backlog(doc)
|
||||
assert uuid.UUID(note.id)
|
||||
|
||||
def test_unknown_priority_and_status_fall_back_to_defaults(self) -> None:
|
||||
doc = _marker(id="z", priority="urgent", status="waiting") + "\nx\n"
|
||||
(note,) = parse_backlog(doc)
|
||||
assert note.priority == "medium"
|
||||
assert note.status == "todo"
|
||||
|
||||
def test_absent_priority_and_status_fall_back_to_defaults(self) -> None:
|
||||
doc = _marker(id="z") + "\nx\n"
|
||||
(note,) = parse_backlog(doc)
|
||||
assert note.priority == "medium"
|
||||
assert note.status == "todo"
|
||||
|
||||
def test_empty_body_yields_empty_title(self) -> None:
|
||||
# Two adjacent markers => the first note's body is empty.
|
||||
doc = (
|
||||
_marker(id="1", priority="low", status="todo")
|
||||
+ "\n"
|
||||
+ _marker(id="2", priority="low", status="todo")
|
||||
+ "\nsecond\n"
|
||||
)
|
||||
notes = parse_backlog(doc)
|
||||
assert notes[0].body == ""
|
||||
assert notes[0].title == ""
|
||||
@ -1,129 +0,0 @@
|
||||
"""Tests for the read-only MCP tools in ``_mcp``.
|
||||
|
||||
Tools are driven directly (``@mcp.tool()`` leaves the function callable). File
|
||||
I/O is exercised for real against a temp ``BACKLOG.md`` pointed at via the
|
||||
``TODO_BACKLOG_PATH`` env var, so ``_backlog_path``'s override branch runs on
|
||||
every call; one test covers the default-path branch explicitly.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from todo_mcp import _mcp
|
||||
|
||||
_DOC = """<!-- todo-backlog v1 -->
|
||||
|
||||
<!-- @note id="n1" priority="high" status="todo" -->
|
||||
# First task
|
||||
alpha
|
||||
|
||||
<!-- @note id="n2" priority="low" status="done" -->
|
||||
# Second task
|
||||
beta
|
||||
|
||||
<!-- @note id="n3" priority="high" status="done" -->
|
||||
# Third task
|
||||
gamma
|
||||
"""
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def backlog(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
|
||||
path = tmp_path / "BACKLOG.md"
|
||||
path.write_text(_DOC, encoding="utf-8")
|
||||
monkeypatch.setenv("TODO_BACKLOG_PATH", str(path))
|
||||
return path
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def missing(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
|
||||
path = tmp_path / "absent.md"
|
||||
monkeypatch.setenv("TODO_BACKLOG_PATH", str(path))
|
||||
return path
|
||||
|
||||
|
||||
class TestBacklogPath:
|
||||
def test_default_path_when_env_unset(self, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.delenv("TODO_BACKLOG_PATH", raising=False)
|
||||
assert _mcp._backlog_path() == Path.home() / "src/todo" / "BACKLOG.md"
|
||||
|
||||
|
||||
class TestListBacklog:
|
||||
def test_lists_all_notes_with_mtime(self, backlog: Path) -> None:
|
||||
out = _mcp.list_backlog()
|
||||
assert out["backlog_found"] is True
|
||||
assert out["total"] == 3
|
||||
assert out["returned"] == 3
|
||||
assert out["mtime"] is not None
|
||||
assert [n["id"] for n in out["notes"]] == ["n1", "n2", "n3"]
|
||||
|
||||
def test_filter_by_priority(self, backlog: Path) -> None:
|
||||
out = _mcp.list_backlog(priority="high")
|
||||
assert [n["id"] for n in out["notes"]] == ["n1", "n3"]
|
||||
|
||||
def test_filter_by_status(self, backlog: Path) -> None:
|
||||
out = _mcp.list_backlog(status="done")
|
||||
assert [n["id"] for n in out["notes"]] == ["n2", "n3"]
|
||||
|
||||
def test_filter_by_priority_and_status(self, backlog: Path) -> None:
|
||||
out = _mcp.list_backlog(priority="high", status="done")
|
||||
assert [n["id"] for n in out["notes"]] == ["n3"]
|
||||
|
||||
def test_limit_caps_results(self, backlog: Path) -> None:
|
||||
out = _mcp.list_backlog(limit=1)
|
||||
assert out["total"] == 3
|
||||
assert out["returned"] == 1
|
||||
|
||||
def test_negative_limit_returns_none(self, backlog: Path) -> None:
|
||||
out = _mcp.list_backlog(limit=-3)
|
||||
assert out["returned"] == 0
|
||||
assert out["notes"] == []
|
||||
|
||||
def test_missing_file_is_graceful(self, missing: Path) -> None:
|
||||
out = _mcp.list_backlog()
|
||||
assert out["backlog_found"] is False
|
||||
assert "Export it" in out["note"]
|
||||
|
||||
|
||||
class TestGetNote:
|
||||
def test_found(self, backlog: Path) -> None:
|
||||
out = _mcp.get_note("n2")
|
||||
assert out["found"] is True
|
||||
assert out["note"]["title"] == "Second task"
|
||||
assert out["mtime"] is not None
|
||||
|
||||
def test_not_found_in_present_file(self, backlog: Path) -> None:
|
||||
out = _mcp.get_note("nope")
|
||||
assert out["backlog_found"] is True
|
||||
assert out["found"] is False
|
||||
assert out["note_id"] == "nope"
|
||||
|
||||
def test_missing_file_is_graceful(self, missing: Path) -> None:
|
||||
out = _mcp.get_note("n1")
|
||||
assert out["backlog_found"] is False
|
||||
assert out["found"] is False
|
||||
assert "Export it" in out["note"]
|
||||
|
||||
|
||||
class TestBacklogStats:
|
||||
def test_counts_by_status_and_priority(self, backlog: Path) -> None:
|
||||
out = _mcp.backlog_stats()
|
||||
assert out["total"] == 3
|
||||
assert out["by_status"] == {"todo": 1, "done": 2}
|
||||
assert out["by_priority"] == {"high": 2, "low": 1}
|
||||
assert out["mtime"] is not None
|
||||
|
||||
def test_missing_file_is_graceful(self, missing: Path) -> None:
|
||||
out = _mcp.backlog_stats()
|
||||
assert out["backlog_found"] is False
|
||||
assert "Export it" in out["note"]
|
||||
|
||||
|
||||
def test_main_runs_stdio_server(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
calls: list[tuple[()]] = []
|
||||
monkeypatch.setattr(_mcp.mcp, "run", lambda: calls.append(()))
|
||||
_mcp.main()
|
||||
assert calls == [()]
|
||||
@ -1,220 +0,0 @@
|
||||
> **This file is a ready-to-use prompt.** Open this repo and say
|
||||
> "do dopamine-ux-todo". It is self-contained -- it needs no context from
|
||||
> any other session.
|
||||
>
|
||||
> Canonical copy: `~/src/utils/dopamine-ux/06-todo.md` (source of truth; this is a
|
||||
> distributed copy). Running order and cross-prompt rules: `~/src/utils/dopamine-ux/00-INDEX.md`.
|
||||
> Generated 2026-08-16 from a survey of this repo -- line numbers are accurate
|
||||
> as of that date; **anchor on the symbol names, not the line numbers.**
|
||||
|
||||
## ⛔ WHEN YOU FINISH THIS PROMPT
|
||||
|
||||
Do **both**, in the same session that completes the work:
|
||||
|
||||
1. **Delete this file** and commit that deletion together with the
|
||||
implementation:
|
||||
```bash
|
||||
git rm prompts/dopamine-ux-todo.md
|
||||
```
|
||||
Do not leave a finished prompt lying in the repo -- a stale prompt is
|
||||
indistinguishable from a pending one, and the next session will re-run it.
|
||||
|
||||
2. **Log completion in the canonical index**, in `~/src/utils` (a *different* repo,
|
||||
so it needs its own commit):
|
||||
```bash
|
||||
cd ~/src/utils
|
||||
# append to the "Completion log" table in dopamine-ux/00-INDEX.md:
|
||||
# | 06-todo.md | DONE <YYYY-MM-DD> | <impl commit sha> | <one-line note> |
|
||||
git add dopamine-ux/00-INDEX.md
|
||||
git commit -m "dopamine-ux: mark 06-todo.md done"
|
||||
git push
|
||||
```
|
||||
|
||||
If you finish only part of the prompt, do **neither** -- instead edit this file
|
||||
to strike out what is done and state what remains, so the next session starts
|
||||
from the true state. Partial completion must never be recorded as DONE.
|
||||
|
||||
---
|
||||
|
||||
Adopt the motion tokens in todo, and make capture feel immediate
|
||||
|
||||
## findings (3, ranked by value over effort)
|
||||
|
||||
1. **Capture gives no confirmation** — a successful capture is indistinguishable
|
||||
from a no-op unless you go looking for the note.
|
||||
2. **Zero motion, zero haptics** — despite being the only app already wired to
|
||||
the shared package, so adoption here is cheapest.
|
||||
3. **The pinned `design_system` tag predates the motion tokens** — nothing
|
||||
compiles until the ref is bumped. Easy to forget, fatal if skipped.
|
||||
|
||||
## what
|
||||
|
||||
`todo` is the only app in kuhy's fleet already wired to the shared
|
||||
`design_system` package — it has **deliberately no local `theme.dart`** (the
|
||||
pubspec comment says so: nothing to drift from the frozen table). That makes it
|
||||
the cheapest place to adopt the motion tokens added by prompt 01, and the
|
||||
reference implementation the other apps get compared against.
|
||||
|
||||
Today it has **zero motion and zero haptics**. Verified 2026-08-16: no
|
||||
`Animated*`, no `AnimationController`, no `HapticFeedback`, no audio. Its only
|
||||
progress UI is the note-editor wizard bar. Capturing a note — the app's whole
|
||||
purpose, and the thing that has to feel frictionless enough to actually do —
|
||||
gives nothing back beyond a toast on error.
|
||||
|
||||
Per kuhy's rule for this project: **reward the capture, never the completion
|
||||
count.** A todo app that celebrates finishing things teaches you to log easy
|
||||
things; one that celebrates *capturing* keeps the backlog honest.
|
||||
|
||||
## where
|
||||
|
||||
Repo: `~/src/todo`.
|
||||
|
||||
**First step — bump the dependency.** `pubspec.yaml` pins `design_system` at git
|
||||
ref `design_system-v0.1.0`, which predates the motion tokens. Bump it to
|
||||
**`design_system-v0.2.0`** (cut by prompt 01) or the tag that prompt actually
|
||||
printed. Without this, `AppDuration` does not exist and nothing else here compiles.
|
||||
|
||||
Primary:
|
||||
- `lib/ui/capture_screen.dart`, `lib/ui/capture_screen_widget.dart`,
|
||||
`lib/ui/capture_screen_sync.dart` — the capture path. `showError` ~:76 and
|
||||
`showToast` ~:78 in `capture_screen_sync.dart` are the fleet's only uses of the
|
||||
shared feedback helpers.
|
||||
- `lib/ui/capture_app_bar.dart` — progress indicators ~:66, :84.
|
||||
- `lib/ui/note_editor.dart` — `showError` ~:115.
|
||||
- `lib/ui/note_editor_step_page.dart` ~:80 — `LinearProgressIndicator(value:
|
||||
(index+1)/total)`, the wizard step bar. The one honest progress surface.
|
||||
- `lib/ui/notes_list_screen.dart` — `_searchDebounce = 250ms` ~:45 (**not**
|
||||
animation; do not tokenise it).
|
||||
- `lib/ui/notes_list_navigation.dart`, `lib/ui/settings_screen.dart` (2×),
|
||||
`lib/ui/capture_screen.dart` — the `MaterialPageRoute` sites, all using the
|
||||
default platform transition.
|
||||
|
||||
Settings — **this app has the only working toggle in the fleet; it is the
|
||||
pattern the other prompts copy**:
|
||||
- `lib/ui/settings_screen.dart` ~:213-225 — `ValueListenableBuilder<AppSettings>`
|
||||
wrapping a `SwitchListTile`; setter ~:111-140 (logs an `AnalyticsEvent`, opens
|
||||
a Firebase client, calls `withAdvancedMode`).
|
||||
- `lib/data/app_settings.dart` — `AppSettings` immutable class,
|
||||
`SharedPreferences` keys ~:38-39, `load()` ~:42, `withAdvancedMode` ~:60,
|
||||
`reconcileWithRemote` ~:98, `adopt` ~:132 (last-writer-wins cross-device sync
|
||||
via `settings/advancedMode` ~:20). Held app-wide as a `ValueNotifier`.
|
||||
|
||||
Theme: no local file. `lib/main.dart` ~:4 imports `design_system`; ~:60-61 wires
|
||||
`theme: buildLightTheme(), darkTheme: buildDarkTheme()`. Source of truth is
|
||||
`~/src/utils/design_system/lib/src/theme.dart`.
|
||||
|
||||
## must
|
||||
|
||||
**Step 1 — motion + haptics (no new dependency).**
|
||||
|
||||
- Bump `design_system` to the new tag **first**, and confirm `AppDuration` /
|
||||
`AppCurve` resolve before writing any other code.
|
||||
- Add `HapticFeedback.selectionClick()` (or the token vocabulary's "confirm" cue)
|
||||
on **successful note capture**. `HapticFeedback` comes from
|
||||
`package:flutter/services.dart` — no pubspec change. Add
|
||||
`<uses-permission android:name="android.permission.VIBRATE"/>` to
|
||||
`android/app/src/main/AndroidManifest.xml`; it is absent today.
|
||||
- Fire the haptic **on the tap**, not after the Firebase sync returns. The whole
|
||||
point of the micro-animation idea is that immediate feedback removes the
|
||||
perceived latency; a cue gated on a network round-trip reintroduces it.
|
||||
- Give the capture a visible confirmation — currently a successful capture is
|
||||
indistinguishable from a no-op unless you go looking.
|
||||
- Animate the wizard `LinearProgressIndicator` between steps rather than jumping.
|
||||
- Apply the shared page-transition/motion tokens to the `MaterialPageRoute` sites
|
||||
so navigation matches the rest of the system.
|
||||
- Honour `MediaQuery.of(context).disableAnimations`: durations collapse to zero,
|
||||
haptics still fire.
|
||||
|
||||
**Step 2 — sound (separate, independently revertable).**
|
||||
|
||||
- Add an audio dependency and an `assets:` block to `pubspec.yaml` (neither
|
||||
exists) plus a short capture-confirm cue.
|
||||
- Sound ships **on**, with an opt-out `SwitchListTile` — copy the
|
||||
`advancedMode` pattern verbatim (widget ~:213-225, setter ~:111-140, field in
|
||||
`app_settings.dart`). It is the fleet's proven toggle; do not invent a new one.
|
||||
- Consider whether the sound preference should sync across devices like
|
||||
`advancedMode` does, or stay local. Local is the safer default — a per-device
|
||||
audio choice is usually what people mean.
|
||||
|
||||
**Both steps:**
|
||||
|
||||
- must not: reward **completing** a todo more than capturing one. No streak on
|
||||
completions, no counter that makes finishing feel better than recording. The
|
||||
backlog is only useful if capture stays frictionless and honest.
|
||||
- must not: add a variable/random reward to capture. There is no real pool to
|
||||
draw from here, so any variance would be manufactured — which fails the
|
||||
project's second test.
|
||||
- must not: fabricate progress. The wizard bar's `(index+1)/total` is true; keep
|
||||
it that way.
|
||||
- must not: hand-copy token values into a local `theme.dart`. This app
|
||||
deliberately has none — that is a feature, and the pubspec comment says so.
|
||||
- must not: add `# noqa`-equivalents or suppress analyzer warnings.
|
||||
|
||||
- optional: animate the notes-list reordering/filtering, if it falls out cheaply
|
||||
from the shared tokens.
|
||||
|
||||
## done
|
||||
|
||||
1. `pubspec.yaml` references the new `design_system` tag and `flutter pub get`
|
||||
resolves it.
|
||||
2. Capturing a note produces a haptic within ~50ms of the tap and a visible
|
||||
confirmation.
|
||||
3. Wizard step transitions and page navigation use shared motion tokens; no
|
||||
inline `Duration` remains for animation purposes (the 250ms search debounce
|
||||
and 5s auto-sync debounce stay as they are — they are not motion).
|
||||
4. `cd ~/src/todo && flutter analyze` is clean.
|
||||
5. `cd ~/src/todo && flutter test` passes.
|
||||
6. With OS "remove animations" enabled, the app works and durations are zero.
|
||||
7. Step 2: the sound toggle flips, persists across restart, and silences the cue.
|
||||
|
||||
## verify
|
||||
|
||||
**On the phone — todo is mobile-primary.**
|
||||
|
||||
```
|
||||
adb devices # confirm 23181JEGR08034
|
||||
cd ~/src/todo
|
||||
flutter build apk --release
|
||||
adb install -r build/app/outputs/flutter-apk/app-release.apk
|
||||
```
|
||||
|
||||
Never `flutter install`, never `adb uninstall`, never `pm clear` — those wipe
|
||||
real notes. `adb install -r` preserves them.
|
||||
|
||||
Then capture a real note on the device and report what the phone did. A haptic is
|
||||
a physical outcome: say what you felt, do not infer it from code. Also step
|
||||
through the note-editor wizard to confirm the progress bar animates.
|
||||
|
||||
If the app also has a desktop/web surface deployed under `/opt/`, note that it
|
||||
can go stale independently — but this prompt's done-condition is the phone.
|
||||
|
||||
## read first
|
||||
|
||||
- `lib/ui/settings_screen.dart` ~:213-225 and `lib/data/app_settings.dart` — the
|
||||
toggle pattern, in full, before writing the sound switch.
|
||||
- `lib/ui/capture_screen_sync.dart` ~:76-78 — how `showToast`/`showError` are
|
||||
used today; the shared helpers live in
|
||||
`~/src/utils/design_system/lib/src/feedback.dart`.
|
||||
- `~/src/utils/design_system/lib/src/feedback.dart` — `showToast`/`showError`, `_show`
|
||||
~:50. `confirm.dart` beside it **already imports `flutter/services.dart`**, so
|
||||
if prompt 01 added a shared haptic helper it lives near here.
|
||||
- `~/src/utils/unified-design-system/motion.md` — the vocabulary from prompt 01.
|
||||
**Prompt 01 must have run first, and its tag must be cut.**
|
||||
- `pubspec.yaml` — read the comment explaining why there is no local theme.
|
||||
|
||||
## context you would otherwise rediscover
|
||||
|
||||
- `showToast` and `showError` already carry fixed dwell times in the shared
|
||||
package (`_toastDuration = 3s`, `_errorDuration = 5s`,
|
||||
`feedback.dart` ~:14, :18). Those are **not** motion tokens; leave them.
|
||||
- This is the **only** app on `design_system`. diet-guard, workout_app and
|
||||
wake_alarm hand-transcribe tokens into local theme files, so a widget copied
|
||||
from this app into one of those will not compile unmodified.
|
||||
- The app has no streaks, no rings, no history charts, and no completion counts
|
||||
today. That is a deliberate starting point for this prompt, not an oversight to
|
||||
fix wholesale.
|
||||
- Settings sync cross-device last-writer-wins through Firebase
|
||||
(`settings/advancedMode`). If you add a synced preference, follow
|
||||
`reconcileWithRemote`/`adopt`; if local-only, skip that path entirely.
|
||||
|
||||
REMOVE ME AFTER FINISH
|
||||
66
pubspec.lock
66
pubspec.lock
@ -5,10 +5,10 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: android_file_picker
|
||||
sha256: "14ab27769b54c48d5a8a71aa9858372b7a3ae77572ea0a8aee744643c5d8c53d"
|
||||
sha256: "03d3dd3cb578ab26b1e528aeea27bf6b976942f5a24e3da82d270369b8e161a8"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.0.0"
|
||||
version: "2.1.2"
|
||||
archive:
|
||||
dependency: transitive
|
||||
description:
|
||||
@ -109,11 +109,11 @@ packages:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
path: crdt_sync_dart
|
||||
ref: "crdt_sync_dart-v0.11.1"
|
||||
resolved-ref: "978d32af3af66f0d6500c4c6c0c6df5370ebe9a2"
|
||||
ref: "crdt_sync_dart-v0.11.2"
|
||||
resolved-ref: "1b5515fd8b1192207896c409212483aeb09704ea"
|
||||
url: "https://github.com/kuhyx/utils"
|
||||
source: git
|
||||
version: "0.11.1"
|
||||
version: "0.11.2"
|
||||
cross_file:
|
||||
dependency: transitive
|
||||
description:
|
||||
@ -150,11 +150,11 @@ packages:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
path: design_system
|
||||
ref: "design_system-v0.2.1"
|
||||
resolved-ref: "978d32af3af66f0d6500c4c6c0c6df5370ebe9a2"
|
||||
ref: "design_system-v0.3.0"
|
||||
resolved-ref: b3c9611af212880301ca79ed21f909bc4640f81f
|
||||
url: "https://github.com/kuhyx/utils"
|
||||
source: git
|
||||
version: "0.2.1"
|
||||
version: "0.3.0"
|
||||
dev_build:
|
||||
dependency: transitive
|
||||
description:
|
||||
@ -199,42 +199,42 @@ packages:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: file_picker
|
||||
sha256: "98c0b156b6380ba55bc767a14e2e6b3feb246e713ad40092424596fa79005bea"
|
||||
sha256: "02f2945a7f29535c735f6b283c3c5553810566d3052d730429aec78fe9d06592"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "13.1.0"
|
||||
version: "13.3.1"
|
||||
file_picker_darwin:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: file_picker_darwin
|
||||
sha256: "51aef9f4c80449c736e7cc02198675fda73689f0bd45a84da642cfeab0250d46"
|
||||
sha256: b845af092ca7a3cff0e768029f835157d371a8341750f4158a7ad358143b0e54
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.1.2"
|
||||
version: "2.4.1"
|
||||
file_picker_linux:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: file_picker_linux
|
||||
sha256: "9c870771500c758eb46506c98532c3ee60e6e51d0a62dcde24a849ef213ea5ce"
|
||||
sha256: c6562fc7d426db2fb85ea66fe2627953d2709932df5584ceaacf0aa5e39cf4da
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.0.1"
|
||||
version: "2.0.2"
|
||||
file_picker_platform_interface:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: file_picker_platform_interface
|
||||
sha256: bbdc085a6f168e63f147e9ce8988f79fa0800a58e7f25a48f762c60837107ba5
|
||||
sha256: "336e7168306834a2b68e6168ed768e00d3fabeac23154d5793e277ca9f97cf20"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "4.0.0"
|
||||
version: "4.2.0"
|
||||
file_picker_web:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: file_picker_web
|
||||
sha256: b3004268da0c1b52baa18df430e7ec4438194de855a807d26b447cbf07ef3496
|
||||
sha256: a2288008280aabe371aff029466b3405e60838e0a1d714767488c59b926c8b8c
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "4.0.0"
|
||||
version: "4.2.0"
|
||||
file_selector:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
@ -479,10 +479,10 @@ packages:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: idb_shim
|
||||
sha256: "4f32cd03ce97e2996b57cea03b2d098f5153ac55435a27cf2c89716db571728d"
|
||||
sha256: "923c92ef88569de4ec1b257b6a6d10360dc3407179f61d0c73329701a7d7b12e"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.10.1+1"
|
||||
version: "2.11.1"
|
||||
image:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
@ -627,6 +627,14 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.13.0"
|
||||
mcp_dart:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: mcp_dart
|
||||
sha256: af0b2e25412f70440c881314a0b70a56ef87fd090b3eb71f31c356313096e6f5
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.4.3"
|
||||
meta:
|
||||
dependency: transitive
|
||||
description:
|
||||
@ -956,10 +964,10 @@ packages:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: sqflite_common_ffi
|
||||
sha256: "4cb6179390549743fc1a5a2fb8f134e5ad87ce459f6f4e563531487dadd81710"
|
||||
sha256: "119d730460264a1f11f414d9eaa43fb686789357e81ce35f9e8ccb66ddd040e4"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.4.4"
|
||||
version: "2.4.5"
|
||||
sqflite_common_ffi_web:
|
||||
dependency: transitive
|
||||
description:
|
||||
@ -1028,11 +1036,11 @@ packages:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
path: sync_settings_ui
|
||||
ref: "sync_settings_ui-v0.4.1"
|
||||
resolved-ref: "51700aa89eaf1789ae98491aaa854c54d35b4170"
|
||||
ref: "sync_settings_ui-v0.4.2"
|
||||
resolved-ref: a4c7d29595bb9cf75f06877545249ed77d5560a9
|
||||
url: "https://github.com/kuhyx/utils"
|
||||
source: git
|
||||
version: "0.4.1"
|
||||
version: "0.4.2"
|
||||
synchronized:
|
||||
dependency: transitive
|
||||
description:
|
||||
@ -1165,10 +1173,10 @@ packages:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: web
|
||||
sha256: "868d88a33d8a87b18ffc05f9f030ba328ffefba92d6c127917a2ba740f9cfe4a"
|
||||
sha256: e119e82ac4795c7925103b7cf3768191f33941b99e7ccffbd6c645201d9f606b
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.1.1"
|
||||
version: "1.1.2"
|
||||
win32:
|
||||
dependency: transitive
|
||||
description:
|
||||
@ -1181,10 +1189,10 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: windows_file_picker
|
||||
sha256: "9f3aa833068b09e380fdc59560ad260a4a14e9397173abb533699f967443602e"
|
||||
sha256: "18452aa293de3b6961c6d05b0e71b4be7bb90c67635abdd3aa5c4e75dd875072"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.0.0"
|
||||
version: "2.0.1"
|
||||
xdg_directories:
|
||||
dependency: transitive
|
||||
description:
|
||||
|
||||
19
pubspec.yaml
19
pubspec.yaml
@ -16,7 +16,7 @@ publish_to: 'none' # Remove this line if you wish to publish to pub.dev
|
||||
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
|
||||
# In Windows, build-name is used as the major, minor, and patch parts
|
||||
# of the product and file versions while build-number is used as the build suffix.
|
||||
version: 1.0.49+1
|
||||
version: 1.0.50+1
|
||||
|
||||
environment:
|
||||
sdk: ^3.12.2
|
||||
@ -33,7 +33,7 @@ dependencies:
|
||||
crdt_sync:
|
||||
git:
|
||||
url: https://github.com/kuhyx/utils
|
||||
ref: crdt_sync_dart-v0.11.1
|
||||
ref: crdt_sync_dart-v0.11.2
|
||||
path: crdt_sync_dart
|
||||
|
||||
# The following adds the Cupertino Icons font to your application.
|
||||
@ -45,9 +45,9 @@ dependencies:
|
||||
design_system:
|
||||
git:
|
||||
url: https://github.com/kuhyx/utils
|
||||
ref: design_system-v0.2.1
|
||||
ref: design_system-v0.3.0
|
||||
path: design_system
|
||||
file_picker: 13.1.0
|
||||
file_picker: 13.3.1
|
||||
file_selector: 1.1.0
|
||||
flutter:
|
||||
sdk: flutter
|
||||
@ -66,12 +66,15 @@ dependencies:
|
||||
# this plugin does not exist. See lib/sync/google_sign_in_backend.dart.
|
||||
google_sign_in: 7.2.0
|
||||
http: 1.6.0
|
||||
idb_shim: 2.10.1+1
|
||||
idb_shim: 2.11.1
|
||||
# Re-encodes attached images (resize, EXIF strip) in pure Dart, so the
|
||||
# phone and the desktop wrapper share one code path.
|
||||
image: 4.12.0
|
||||
# Camera + gallery picks for image attachments on Android.
|
||||
image_picker: 1.2.4
|
||||
# The todo MCP server (lib/mcp/): Streamable HTTP transport + tool
|
||||
# registry. Only mcp/todo_mcp.dart imports it; the app never does.
|
||||
mcp_dart: 2.4.3
|
||||
# Hands an attached non-image file to whichever Android app opens its
|
||||
# type (FileProvider intent). Adds no permissions to the manifest.
|
||||
open_file: 4.0.0
|
||||
@ -79,7 +82,7 @@ dependencies:
|
||||
path_provider: 2.1.6
|
||||
share_plus: 13.3.1
|
||||
shared_preferences: 2.5.6
|
||||
sqflite_common_ffi: 2.4.4
|
||||
sqflite_common_ffi: 2.4.5
|
||||
# Retained only to read the legacy on-device DB during the one-time
|
||||
# migration in NoteRepository.open; remove once all devices are migrated.
|
||||
sqlite_crdt: 3.0.4
|
||||
@ -91,12 +94,12 @@ dependencies:
|
||||
sync_settings_ui:
|
||||
git:
|
||||
url: https://github.com/kuhyx/utils
|
||||
ref: sync_settings_ui-v0.4.1
|
||||
ref: sync_settings_ui-v0.4.2
|
||||
path: sync_settings_ui
|
||||
url_launcher: 6.3.3
|
||||
uuid: 4.6.0
|
||||
# Paste and drag-and-drop listeners on the desktop (web) page.
|
||||
web: 1.1.1
|
||||
web: 1.1.2
|
||||
dev_dependencies:
|
||||
# Virtual clock for unit-testing debounced timers (e.g. LocalBackup).
|
||||
fake_async: 1.3.3
|
||||
|
||||
55
test/mcp/mcp_auth_test.dart
Normal file
55
test/mcp/mcp_auth_test.dart
Normal file
@ -0,0 +1,55 @@
|
||||
// Bearer tokens are checked against sha256 hashes in the tokens file, re-read
|
||||
// per request so revoking a line takes effect without a restart; the Host
|
||||
// check admits loopback and the public proxy name only.
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
import 'mcp_harness.dart';
|
||||
|
||||
void main() {
|
||||
late McpHarness h;
|
||||
|
||||
setUp(() async {
|
||||
h = McpHarness();
|
||||
await h.start();
|
||||
});
|
||||
tearDown(() => h.dispose());
|
||||
|
||||
const ok = 'Bearer ${McpHarness.token}';
|
||||
|
||||
test('a listed token is admitted', () async {
|
||||
expect(await h.rawInitialize({'authorization': ok}), 200);
|
||||
});
|
||||
|
||||
test('no token or a wrong token is refused', () async {
|
||||
expect(await h.rawInitialize({}), anyOf(401, 403));
|
||||
expect(
|
||||
await h.rawInitialize({'authorization': 'Bearer nope'}),
|
||||
anyOf(401, 403),
|
||||
);
|
||||
});
|
||||
|
||||
test('removing the line revokes without a restart', () async {
|
||||
h.tokens.writeAsStringSync('# revoked\n');
|
||||
expect(await h.rawInitialize({'authorization': ok}), anyOf(401, 403));
|
||||
});
|
||||
|
||||
test('a missing tokens file admits nobody', () async {
|
||||
h.tokens.deleteSync();
|
||||
expect(await h.rawInitialize({'authorization': ok}), anyOf(401, 403));
|
||||
});
|
||||
|
||||
test('the proxy host is admitted, a foreign host is not', () async {
|
||||
expect(
|
||||
await h.rawInitialize({
|
||||
'authorization': ok,
|
||||
'host': 'todo.kuhy.duckdns.org',
|
||||
'origin': 'https://todo.kuhy.duckdns.org',
|
||||
}),
|
||||
200,
|
||||
);
|
||||
expect(
|
||||
await h.rawInitialize({'authorization': ok, 'host': 'evil.example'}),
|
||||
anyOf(400, 403),
|
||||
);
|
||||
});
|
||||
}
|
||||
125
test/mcp/mcp_contract_test.dart
Normal file
125
test/mcp/mcp_contract_test.dart
Normal file
@ -0,0 +1,125 @@
|
||||
// Spec B / Q6 contract: over real Streamable HTTP, add -> list -> update
|
||||
// (explicit clear of done_check) -> close with evidence, refused without;
|
||||
// the result is visible to `todo_note.dart --list --repo` after a sync.
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:mcp_dart/mcp_dart.dart';
|
||||
import 'package:todo/cli/cli_runner.dart';
|
||||
import 'package:todo/cli/cli_session.dart';
|
||||
import 'package:todo/sync/notes_markdown.dart';
|
||||
|
||||
import '../cli/fake_rtdb.dart';
|
||||
import 'mcp_harness.dart';
|
||||
|
||||
const _repo = 'kuhyx/todo';
|
||||
|
||||
void main() {
|
||||
late McpHarness h;
|
||||
late McpClient c;
|
||||
|
||||
setUp(() async {
|
||||
h = McpHarness();
|
||||
await h.start();
|
||||
c = await h.connect();
|
||||
});
|
||||
tearDown(() => h.dispose());
|
||||
|
||||
Future<String> addTask() async => idIn(
|
||||
await h.call(c, 'add_task', {
|
||||
'repo': _repo,
|
||||
'title': 'Fix the "quoted" thing',
|
||||
'body': 'what: details',
|
||||
'done_check': 'grep -q "ok" f',
|
||||
'priority': 'high',
|
||||
}),
|
||||
);
|
||||
|
||||
test('add, list, update clearing done_check, close with evidence', () async {
|
||||
final id = await addTask();
|
||||
final prefix = id.substring(0, 8);
|
||||
|
||||
final listed = await h.call(c, 'list_tasks', {'repo': _repo});
|
||||
expect(listed, contains(prefix));
|
||||
expect(listed, contains('Fix the "quoted" thing'));
|
||||
expect(listed, isNot(contains('"')));
|
||||
|
||||
var got = await h.call(c, 'get_task', {'id': prefix});
|
||||
expect(got, contains('done_check: grep -q "ok" f'));
|
||||
expect(got, contains('by: claude'));
|
||||
|
||||
await h.call(c, 'update_task', {'id': prefix, 'done_check': ''});
|
||||
got = await h.call(c, 'get_task', {'id': prefix});
|
||||
expect(got, isNot(contains('done_check')));
|
||||
|
||||
for (final args in [
|
||||
{'id': prefix},
|
||||
{'id': prefix, 'evidence': ' '},
|
||||
]) {
|
||||
expect(await h.refused(c, 'close_task', args), contains('evidence'));
|
||||
}
|
||||
await h.call(c, 'close_task', {
|
||||
'id': prefix,
|
||||
'evidence': 'abc1234 "done_check" exit 0',
|
||||
});
|
||||
got = await h.call(c, 'get_task', {'id': id});
|
||||
expect(got, contains('status: done'));
|
||||
expect(got, contains('evidence: abc1234 "done_check" exit 0'));
|
||||
|
||||
// Another node (the CLI) sees the closed task, done_check cleared.
|
||||
final out = StringBuffer();
|
||||
final code = await runCli(
|
||||
['--list', '--repo', _repo, '--data-dir', '${h.tmp.path}/cli'],
|
||||
env: {'HOME': h.tmp.path},
|
||||
out: out,
|
||||
err: StringBuffer(),
|
||||
readStdin: () async => '',
|
||||
open: (d, {required seedCredentials}) => CliSession.open(
|
||||
d,
|
||||
seedCredentials: writeSeedCredentials(h.tmp).path,
|
||||
httpClient: h.db.client,
|
||||
),
|
||||
);
|
||||
expect(code, 0);
|
||||
expect(out.toString(), contains('$prefix\tdone\thigh\t$_repo'));
|
||||
|
||||
// BACKLOG.md escapes `"` as "; parsing decodes it back.
|
||||
final notes = await h.session.repository.listNotes();
|
||||
final md = NotesMarkdown.export(notes);
|
||||
expect(md, contains('"'));
|
||||
final back = NotesMarkdown.parse(md).single;
|
||||
expect(back.evidence, 'abc1234 "done_check" exit 0');
|
||||
expect(back.doneCheck, isNull);
|
||||
});
|
||||
|
||||
test('errors name the field to fix', () async {
|
||||
final id = await addTask();
|
||||
expect(
|
||||
await h.refused(c, 'update_task', {'id': id, 'priority': 'urgent'}),
|
||||
contains('priority'),
|
||||
);
|
||||
expect(
|
||||
await h.refused(c, 'add_task', {'repo': 'no-slash', 'title': 't'}),
|
||||
contains('repo'),
|
||||
);
|
||||
expect(
|
||||
await h.refused(c, 'add_task', {'repo': _repo, 'title': ' '}),
|
||||
contains('title'),
|
||||
);
|
||||
expect(await h.refused(c, 'get_task', {'id': 'abc'}), contains('id'));
|
||||
expect(
|
||||
await h.refused(c, 'list_tasks', {'status': 'finished'}),
|
||||
contains('status'),
|
||||
);
|
||||
});
|
||||
|
||||
test('search finds tasks by text; instructions say when to use', () async {
|
||||
final id = await addTask();
|
||||
expect(
|
||||
await h.call(c, 'search_tasks', {'query': 'QUOTED'}),
|
||||
contains(id.substring(0, 8)),
|
||||
);
|
||||
final how = c.getInstructions()!;
|
||||
for (final tool in ['add_task', 'list_tasks', 'close_task']) {
|
||||
expect(how, contains(tool));
|
||||
}
|
||||
});
|
||||
}
|
||||
133
test/mcp/mcp_harness.dart
Normal file
133
test/mcp/mcp_harness.dart
Normal file
@ -0,0 +1,133 @@
|
||||
/// Runs the todo MCP server in-process over real HTTP, backed by a
|
||||
/// [FakeRtdb] and a temp data dir. Never the real RTDB or ~/.local/share.
|
||||
///
|
||||
/// Not named `*_test.dart`: the runner would collect it and fail on the
|
||||
/// missing `main()`.
|
||||
library;
|
||||
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:mcp_dart/mcp_dart.dart';
|
||||
import 'package:todo/cli/cli_session.dart';
|
||||
import 'package:todo/mcp/task_service.dart';
|
||||
import 'package:todo/mcp/todo_mcp_server.dart';
|
||||
import 'package:todo/mcp/token_file.dart';
|
||||
|
||||
import '../cli/fake_rtdb.dart';
|
||||
|
||||
class McpHarness {
|
||||
static const token = 'test-token-for-pc';
|
||||
|
||||
final tmp = Directory.systemTemp.createTempSync('mcp_harness');
|
||||
final db = FakeRtdb();
|
||||
late final File tokens = File('${tmp.path}/tokens');
|
||||
late final CliSession session;
|
||||
late final TodoMcpServer server;
|
||||
final _clients = <McpClient>[];
|
||||
|
||||
Future<void> start() async {
|
||||
tokens.writeAsStringSync('${tokenHash(token)} pc\n');
|
||||
session = await CliSession.open(
|
||||
'${tmp.path}/data',
|
||||
seedCredentials: writeSeedCredentials(tmp).path,
|
||||
httpClient: db.client,
|
||||
);
|
||||
server = await TodoMcpServer.start(
|
||||
tasks: TaskService(session),
|
||||
tokens: tokens,
|
||||
port: 0,
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> dispose() async {
|
||||
for (final c in _clients) {
|
||||
await c.close();
|
||||
}
|
||||
await server.close();
|
||||
await session.close();
|
||||
tmp.deleteSync(recursive: true);
|
||||
}
|
||||
|
||||
/// A connected MCP client sending `Authorization: Bearer <bearer>`.
|
||||
Future<McpClient> connect({String bearer = token}) async {
|
||||
final client = McpClient(
|
||||
const Implementation(name: 'contract-test', version: '1.0.0'),
|
||||
);
|
||||
await client.connect(
|
||||
StreamableHttpClientTransport(
|
||||
server.uri,
|
||||
opts: StreamableHttpClientTransportOptions(
|
||||
requestInit: {
|
||||
'headers': {'Authorization': 'Bearer $bearer'},
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
_clients.add(client);
|
||||
return client;
|
||||
}
|
||||
|
||||
/// Calls [tool] and returns its text, failing the test on a tool error.
|
||||
Future<String> call(
|
||||
McpClient client,
|
||||
String tool,
|
||||
Map<String, dynamic> args,
|
||||
) async {
|
||||
final (text, isError) = await _call(client, tool, args);
|
||||
expect(isError, isFalse, reason: '$tool failed: $text');
|
||||
return text;
|
||||
}
|
||||
|
||||
/// Calls [tool], expects it to be refused, and returns the error text.
|
||||
Future<String> refused(
|
||||
McpClient client,
|
||||
String tool,
|
||||
Map<String, dynamic> args,
|
||||
) async {
|
||||
final (text, isError) = await _call(client, tool, args);
|
||||
expect(isError, isTrue, reason: '$tool should be refused: $text');
|
||||
return text;
|
||||
}
|
||||
|
||||
Future<(String, bool)> _call(
|
||||
McpClient client,
|
||||
String tool,
|
||||
Map<String, dynamic> args,
|
||||
) async {
|
||||
final result = await client.callTool(
|
||||
CallToolRequest(name: tool, arguments: args),
|
||||
);
|
||||
final text = result.content
|
||||
.whereType<TextContent>()
|
||||
.map((c) => c.text)
|
||||
.join('\n');
|
||||
return (text, result.isError);
|
||||
}
|
||||
|
||||
/// POSTs a raw `initialize` with the given headers; returns the status.
|
||||
Future<int> rawInitialize(Map<String, String> headers) async {
|
||||
final http = HttpClient();
|
||||
try {
|
||||
final req = await http.postUrl(server.uri);
|
||||
req.headers
|
||||
..set('content-type', 'application/json')
|
||||
..set('accept', 'application/json, text/event-stream');
|
||||
headers.forEach(req.headers.set);
|
||||
req.write(
|
||||
'{"jsonrpc":"2.0","id":1,"method":"initialize","params":'
|
||||
'{"protocolVersion":"2025-06-18","capabilities":{},'
|
||||
'"clientInfo":{"name":"raw","version":"1"}}}',
|
||||
);
|
||||
final res = await req.close();
|
||||
await res.drain<void>();
|
||||
return res.statusCode;
|
||||
} finally {
|
||||
http.close(force: true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The first full uuid in [text].
|
||||
String idIn(String text) =>
|
||||
RegExp(r'[0-9a-f]{8}-[0-9a-f-]{27}').firstMatch(text)!.group(0)!;
|
||||
69
test/mcp/mcp_main_test.dart
Normal file
69
test/mcp/mcp_main_test.dart
Normal file
@ -0,0 +1,69 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:todo/mcp/mcp_main.dart';
|
||||
import 'package:todo/mcp/token_file.dart';
|
||||
|
||||
import '../cli/fake_rtdb.dart';
|
||||
|
||||
void main() {
|
||||
late Directory home;
|
||||
late FakeRtdb db;
|
||||
late StringBuffer err;
|
||||
late Map<String, String> env;
|
||||
|
||||
setUp(() {
|
||||
home = Directory.systemTemp.createTempSync('mcp_main');
|
||||
db = FakeRtdb();
|
||||
err = StringBuffer();
|
||||
env = {
|
||||
'HOME': home.path,
|
||||
'TODO_MCP_PORT': '0',
|
||||
'TODO_MCP_DATA_DIR': '${home.path}/data',
|
||||
};
|
||||
});
|
||||
tearDown(() => home.deleteSync(recursive: true));
|
||||
|
||||
Future<Future<void> Function()?> start() =>
|
||||
startTodoMcp(env, err, httpClient: db.client);
|
||||
|
||||
void writeTokens() => File('${home.path}/.config/todo-mcp/tokens')
|
||||
..createSync(recursive: true)
|
||||
..writeAsStringSync('${tokenHash('t')} pc\n');
|
||||
|
||||
test('refuses to start without a tokens file', () async {
|
||||
expect(await start(), isNull);
|
||||
expect(err.toString(), contains('mint_token.sh'));
|
||||
});
|
||||
|
||||
test('refuses to start without a seeded session, naming the app', () async {
|
||||
writeTokens();
|
||||
expect(await start(), isNull);
|
||||
expect(err.toString(), contains('--app todo-mcp'));
|
||||
});
|
||||
|
||||
test('refuses to start when the first sync fails', () async {
|
||||
writeTokens();
|
||||
writeSeedCredentials(
|
||||
Directory('${home.path}/.config/todo-mcp'),
|
||||
name: 'firebase_auth.json',
|
||||
);
|
||||
db.failWith = 503;
|
||||
expect(await start(), isNull);
|
||||
expect(err.toString(), startsWith('error:'));
|
||||
});
|
||||
|
||||
test('starts, publishes its own node log, and stops', () async {
|
||||
writeTokens();
|
||||
writeSeedCredentials(
|
||||
Directory('${home.path}/.config/todo-mcp'),
|
||||
name: 'firebase_auth.json',
|
||||
);
|
||||
final stop = await start();
|
||||
expect(stop, isNotNull);
|
||||
expect(err.toString(), contains('serving http://127.0.0.1:'));
|
||||
expect(db.files.keys, contains(startsWith('todo-sync/notes/')));
|
||||
expect(db.files.keys, contains(startsWith('todo-sync/revs/')));
|
||||
await stop!();
|
||||
});
|
||||
}
|
||||
67
test/mcp/mcp_update_test.dart
Normal file
67
test/mcp/mcp_update_test.dart
Normal file
@ -0,0 +1,67 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:mcp_dart/mcp_dart.dart';
|
||||
|
||||
import 'mcp_harness.dart';
|
||||
|
||||
void main() {
|
||||
late McpHarness h;
|
||||
late McpClient c;
|
||||
late String id;
|
||||
|
||||
setUp(() async {
|
||||
h = McpHarness();
|
||||
await h.start();
|
||||
c = await h.connect();
|
||||
id = idIn(
|
||||
await h.call(c, 'add_task', {
|
||||
'repo': 'kuhyx/todo',
|
||||
'title': 'Old title',
|
||||
'body': 'old body',
|
||||
}),
|
||||
);
|
||||
});
|
||||
tearDown(() => h.dispose());
|
||||
|
||||
test('title, body, priority and repo change independently', () async {
|
||||
await h.call(c, 'update_task', {'id': id, 'title': 'New title'});
|
||||
var got = await h.call(c, 'get_task', {'id': id});
|
||||
expect(got, endsWith('---\nNew title\n\nold body'));
|
||||
|
||||
await h.call(c, 'update_task', {
|
||||
'id': id,
|
||||
'body': '',
|
||||
'priority': 'low',
|
||||
'repo': 'kuhyx/utils',
|
||||
});
|
||||
got = await h.call(c, 'get_task', {'id': id});
|
||||
expect(got, endsWith('---\nNew title'));
|
||||
expect(got, contains('priority: low'));
|
||||
expect(got, contains('repo: kuhyx/utils'));
|
||||
});
|
||||
|
||||
test('done only via close; reopening drops the evidence', () async {
|
||||
expect(
|
||||
await h.refused(c, 'update_task', {'id': id, 'status': 'done'}),
|
||||
startsWith('error: status:'),
|
||||
);
|
||||
expect(
|
||||
await h.refused(c, 'update_task', {'id': id, 'title': ' '}),
|
||||
startsWith('error: title:'),
|
||||
);
|
||||
await h.call(c, 'close_task', {'id': id, 'evidence': 'abc exit 0'});
|
||||
expect(
|
||||
await h.call(c, 'list_tasks', {'status': 'all'}),
|
||||
contains('\tdone\t'),
|
||||
);
|
||||
expect(await h.call(c, 'list_tasks', {}), 'no tasks match');
|
||||
await h.call(c, 'update_task', {'id': id, 'status': 'in_progress'});
|
||||
final got = await h.call(c, 'get_task', {'id': id});
|
||||
expect(got, contains('status: in_progress'));
|
||||
expect(got, isNot(contains('evidence')));
|
||||
});
|
||||
|
||||
test('an unmergeable peer log is reported, not hidden', () async {
|
||||
h.db.files['todo-sync/notes/broken~2Ejson'] = 'not a log';
|
||||
expect(await h.refused(c, 'list_tasks', {}), contains('unmergeable'));
|
||||
});
|
||||
}
|
||||
138
test/motion/capture_confirmation_test.dart
Normal file
138
test/motion/capture_confirmation_test.dart
Normal file
@ -0,0 +1,138 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:todo/ui/capture_confirm_mark.dart';
|
||||
|
||||
import '../capture_screen_harness.dart';
|
||||
import 'motion_harness.dart';
|
||||
|
||||
const _lightImpact = 'HapticFeedbackType.lightImpact';
|
||||
final _mark = find.byKey(CaptureConfirmMark.iconKey);
|
||||
|
||||
double _opacity(WidgetTester tester) => tester
|
||||
.widget<Opacity>(find.ancestor(of: _mark, matching: find.byType(Opacity)))
|
||||
.opacity;
|
||||
|
||||
Future<void> _type(WidgetTester tester) async {
|
||||
await tester.enterText(find.byType(TextField), 'buy milk');
|
||||
await tester.pump();
|
||||
}
|
||||
|
||||
void main() {
|
||||
testWidgets('typing alone neither vibrates nor shows the checkmark', (
|
||||
tester,
|
||||
) async {
|
||||
final haptics = recordHaptics(tester);
|
||||
await pumpCapture(tester);
|
||||
await _type(tester);
|
||||
await tester.enterText(find.byType(TextField), 'buy milk and eggs');
|
||||
await tester.pump(const Duration(milliseconds: 100));
|
||||
|
||||
expect(haptics, isEmpty);
|
||||
expect(_mark, findsNothing);
|
||||
});
|
||||
|
||||
testWidgets('committing a captured note vibrates once, immediately', (
|
||||
tester,
|
||||
) async {
|
||||
final haptics = recordHaptics(tester);
|
||||
await pumpCapture(tester);
|
||||
await _type(tester);
|
||||
|
||||
await tester.tap(find.byTooltip('New note'));
|
||||
await tester.pump(); // one frame: the cue must not wait for anything
|
||||
|
||||
expect(haptics, [_lightImpact]);
|
||||
await tester.pump(const Duration(milliseconds: 700));
|
||||
});
|
||||
|
||||
testWidgets('the checkmark fades in, holds, fades out in ~600 ms', (
|
||||
tester,
|
||||
) async {
|
||||
recordHaptics(tester);
|
||||
await pumpCapture(tester);
|
||||
await _type(tester);
|
||||
|
||||
await tester.tap(find.byTooltip('New note'));
|
||||
await tester.pump();
|
||||
await tester.pump(const Duration(milliseconds: 100));
|
||||
expect(_mark, findsOneWidget);
|
||||
expect(_opacity(tester), inExclusiveRange(0, 1)); // fading in
|
||||
|
||||
await tester.pump(const Duration(milliseconds: 200)); // t = 300 ms
|
||||
expect(_opacity(tester), 1); // holding
|
||||
|
||||
await tester.pump(const Duration(milliseconds: 200)); // t = 500 ms
|
||||
expect(_opacity(tester), inExclusiveRange(0, 1)); // fading out
|
||||
|
||||
await tester.pump(const Duration(milliseconds: 200)); // t = 700 ms
|
||||
expect(_mark, findsNothing);
|
||||
});
|
||||
|
||||
testWidgets('an empty draft is not a capture: no haptic, no checkmark', (
|
||||
tester,
|
||||
) async {
|
||||
final haptics = recordHaptics(tester);
|
||||
await pumpCapture(tester);
|
||||
|
||||
await tester.tap(find.byTooltip('New note'));
|
||||
await tester.pump(const Duration(milliseconds: 100));
|
||||
|
||||
expect(haptics, isEmpty);
|
||||
expect(_mark, findsNothing);
|
||||
});
|
||||
|
||||
testWidgets('each capture confirms once; tapping the reset box does not', (
|
||||
tester,
|
||||
) async {
|
||||
final haptics = recordHaptics(tester);
|
||||
await pumpCapture(tester);
|
||||
await _type(tester);
|
||||
await tester.tap(find.byTooltip('New note'));
|
||||
await tester.pump(); // the ticker's clock starts on its first frame
|
||||
await tester.pump(const Duration(milliseconds: 700));
|
||||
await tester.tap(find.byTooltip('New note')); // nothing new to capture
|
||||
await tester.pump(const Duration(milliseconds: 100));
|
||||
expect(haptics, hasLength(1));
|
||||
expect(_mark, findsNothing);
|
||||
|
||||
await _type(tester);
|
||||
await tester.tap(find.byTooltip('New note'));
|
||||
await tester.pump(const Duration(milliseconds: 100));
|
||||
expect(haptics, hasLength(2));
|
||||
expect(_mark, findsOneWidget);
|
||||
await tester.pump(const Duration(milliseconds: 700));
|
||||
});
|
||||
|
||||
testWidgets('remove-animations: still vibrates, checkmark static', (
|
||||
tester,
|
||||
) async {
|
||||
final haptics = recordHaptics(tester);
|
||||
disableAnimations(tester);
|
||||
await pumpCapture(tester);
|
||||
await _type(tester);
|
||||
|
||||
await tester.tap(find.byTooltip('New note'));
|
||||
await tester.pump();
|
||||
expect(haptics, [_lightImpact]);
|
||||
|
||||
await tester.pump(const Duration(milliseconds: 1));
|
||||
expect(_opacity(tester), 1); // no fade-in
|
||||
await tester.pump(const Duration(milliseconds: 400));
|
||||
expect(_opacity(tester), 1); // no fade-out either
|
||||
await tester.pump(const Duration(milliseconds: 300));
|
||||
expect(_mark, findsNothing);
|
||||
});
|
||||
|
||||
testWidgets('the checkmark reserves its width so the counter never jumps', (
|
||||
tester,
|
||||
) async {
|
||||
recordHaptics(tester);
|
||||
await pumpCapture(tester);
|
||||
final before = tester.getTopLeft(find.text('0'));
|
||||
await _type(tester);
|
||||
await tester.tap(find.byTooltip('New note'));
|
||||
await tester.pump(const Duration(milliseconds: 300));
|
||||
expect(tester.getTopLeft(find.text('1')), before);
|
||||
await tester.pump(const Duration(milliseconds: 400));
|
||||
});
|
||||
}
|
||||
37
test/motion/motion_harness.dart
Normal file
37
test/motion/motion_harness.dart
Normal file
@ -0,0 +1,37 @@
|
||||
/// Shared helpers for the motion / haptic tests.
|
||||
///
|
||||
/// Deliberately NOT named `*_test.dart`: the runner would collect it and fail
|
||||
/// on the missing `main()`.
|
||||
library;
|
||||
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
/// Records the arguments of every `HapticFeedback.*` call for the test's
|
||||
/// lifetime. Matches the platform channel Flutter's [HapticFeedback] uses.
|
||||
List<String> recordHaptics(WidgetTester tester) {
|
||||
final calls = <String>[];
|
||||
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
|
||||
SystemChannels.platform,
|
||||
(call) async {
|
||||
if (call.method == 'HapticFeedback.vibrate') {
|
||||
calls.add(call.arguments as String);
|
||||
}
|
||||
return null;
|
||||
},
|
||||
);
|
||||
addTearDown(
|
||||
() => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
|
||||
SystemChannels.platform,
|
||||
null,
|
||||
),
|
||||
);
|
||||
return calls;
|
||||
}
|
||||
|
||||
/// Turns the OS "remove animations" setting on for this test.
|
||||
void disableAnimations(WidgetTester tester) {
|
||||
tester.platformDispatcher.accessibilityFeaturesTestValue =
|
||||
const FakeAccessibilityFeatures(disableAnimations: true);
|
||||
addTearDown(tester.platformDispatcher.clearAccessibilityFeaturesTestValue);
|
||||
}
|
||||
96
test/motion/motion_tokens_test.dart
Normal file
96
test/motion/motion_tokens_test.dart
Normal file
@ -0,0 +1,96 @@
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:design_system/design_system.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:todo/ui/app_route.dart';
|
||||
|
||||
import '../note_editor_harness.dart';
|
||||
import 'motion_harness.dart';
|
||||
|
||||
double _barValue(WidgetTester tester) => tester
|
||||
.widget<LinearProgressIndicator>(find.byType(LinearProgressIndicator))
|
||||
.value!;
|
||||
|
||||
Future<void> _pushPage(WidgetTester tester) async {
|
||||
late BuildContext ctx;
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
home: Builder(
|
||||
builder: (c) {
|
||||
ctx = c;
|
||||
return const Scaffold(body: Text('home'));
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
unawaited(
|
||||
Navigator.of(
|
||||
ctx,
|
||||
).push<void>(appRoute(ctx, (_) => const Scaffold(body: Text('page')))),
|
||||
);
|
||||
await tester.pump();
|
||||
}
|
||||
|
||||
void main() {
|
||||
test('every page route goes through appRoute', () {
|
||||
final offenders = <String>[];
|
||||
for (final f in Directory('lib').listSync(recursive: true)) {
|
||||
if (f is! File || !f.path.endsWith('.dart')) continue;
|
||||
if (f.path.endsWith('ui/app_route.dart')) continue;
|
||||
if (f.readAsStringSync().contains('MaterialPageRoute(')) {
|
||||
offenders.add(f.path);
|
||||
}
|
||||
}
|
||||
expect(offenders, isEmpty);
|
||||
});
|
||||
|
||||
testWidgets('a pushed page eases in over AppDuration.slow', (tester) async {
|
||||
await _pushPage(tester);
|
||||
await tester.pump(AppDuration.slow ~/ 4);
|
||||
expect(find.text('page'), findsOneWidget);
|
||||
final fade = tester.widget<FadeTransition>(
|
||||
find
|
||||
.ancestor(
|
||||
of: find.text('page'),
|
||||
matching: find.byType(FadeTransition),
|
||||
)
|
||||
.first,
|
||||
);
|
||||
expect(fade.opacity.value, inExclusiveRange(0, 1));
|
||||
|
||||
await tester.pump(AppDuration.slow);
|
||||
expect(find.text('home'), findsNothing); // fully covered, route settled
|
||||
});
|
||||
|
||||
testWidgets('remove-animations: the page is there at once', (tester) async {
|
||||
disableAnimations(tester);
|
||||
await _pushPage(tester);
|
||||
await tester.pump(const Duration(milliseconds: 1));
|
||||
expect(find.text('home'), findsNothing);
|
||||
expect(find.text('page'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('wizard progress bar animates between steps', (tester) async {
|
||||
await pumpEditor(tester, initialTemplate: spec);
|
||||
final total = spec.sections.length;
|
||||
expect(_barValue(tester), closeTo(1 / total, 1e-9));
|
||||
|
||||
await tester.tap(find.text('Next'));
|
||||
await tester.pump();
|
||||
await tester.pump(AppDuration.base ~/ 2);
|
||||
expect(_barValue(tester), inExclusiveRange(1 / total, 2 / total));
|
||||
|
||||
await tester.pump(AppDuration.base);
|
||||
expect(_barValue(tester), closeTo(2 / total, 1e-9));
|
||||
});
|
||||
|
||||
testWidgets('remove-animations: the progress bar jumps', (tester) async {
|
||||
disableAnimations(tester);
|
||||
await pumpEditor(tester, initialTemplate: spec);
|
||||
await tester.tap(find.text('Next'));
|
||||
await tester.pump();
|
||||
expect(_barValue(tester), closeTo(2 / spec.sections.length, 1e-9));
|
||||
});
|
||||
}
|
||||
166
test/notes_grid_geometry_test.dart
Normal file
166
test/notes_grid_geometry_test.dart
Normal file
@ -0,0 +1,166 @@
|
||||
/// Pixel 6a geometry of the notes grid: whole tiles only, nothing under the
|
||||
/// status bar or the navigation bar, no overflow, scrolls only past a screen.
|
||||
library;
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:todo/data/note.dart';
|
||||
import 'package:todo/ui/note_grid_tile.dart';
|
||||
|
||||
import 'notes_list_harness.dart';
|
||||
|
||||
const _dpr = 2.625;
|
||||
const _navBar = 63 / _dpr;
|
||||
const _statusBar = 132 / _dpr;
|
||||
const _screenHeight = 2400 / _dpr;
|
||||
|
||||
/// 1080x2400 px at 2.625, with the real system-bar insets.
|
||||
void _pixel6a(WidgetTester t, {double keyboardDp = 0}) {
|
||||
const bars = FakeViewPadding(top: 132, bottom: 63);
|
||||
t.view
|
||||
..physicalSize = const Size(1080, 2400)
|
||||
..devicePixelRatio = _dpr
|
||||
..padding = bars
|
||||
..viewPadding = bars
|
||||
..viewInsets = FakeViewPadding(bottom: keyboardDp * _dpr);
|
||||
addTearDown(t.view.reset);
|
||||
}
|
||||
|
||||
List<Note> _notes(int n) => [
|
||||
for (var i = 0; i < n; i++)
|
||||
note(
|
||||
'n$i',
|
||||
'Note $i with a rather long title that wraps onto several lines',
|
||||
priority: Priority.values[i % 3],
|
||||
),
|
||||
];
|
||||
|
||||
Rect _viewport(WidgetTester t) => t.getRect(find.byType(GridView));
|
||||
|
||||
/// Tiles whose rect touches the viewport.
|
||||
List<Rect> _shown(WidgetTester t) {
|
||||
final view = _viewport(t);
|
||||
return [
|
||||
for (final e in find.byType(NoteGridTile).evaluate())
|
||||
t.getRect(find.byWidget(e.widget)),
|
||||
].where((r) => r.overlaps(view)).toList();
|
||||
}
|
||||
|
||||
double _maxScroll(WidgetTester t) => t
|
||||
.state<ScrollableState>(
|
||||
find.descendant(
|
||||
of: find.byType(GridView),
|
||||
matching: find.byType(Scrollable),
|
||||
),
|
||||
)
|
||||
.position
|
||||
.maxScrollExtent;
|
||||
|
||||
void _expectWholeTilesOnly(WidgetTester t) {
|
||||
final view = _viewport(t);
|
||||
final shown = _shown(t);
|
||||
expect(shown, isNotEmpty);
|
||||
for (final r in shown) {
|
||||
expect(r.top, greaterThanOrEqualTo(view.top - 0.01), reason: '$r');
|
||||
expect(r.bottom, lessThanOrEqualTo(view.bottom + 0.01), reason: '$r');
|
||||
}
|
||||
// The rows use up the whole viewport: no strip of dead space under them.
|
||||
final lastBottom = shown.map((r) => r.bottom).reduce((a, b) => a > b ? a : b);
|
||||
expect(lastBottom, closeTo(view.bottom, 0.01));
|
||||
}
|
||||
|
||||
void main() {
|
||||
testWidgets('Pixel 6a: whole tiles between the system bars', (t) async {
|
||||
_pixel6a(t);
|
||||
await pumpList(t, seed: _notes(300));
|
||||
|
||||
expect(t.takeException(), isNull);
|
||||
final view = _viewport(t);
|
||||
expect(view.top, greaterThanOrEqualTo(_statusBar + kToolbarHeight));
|
||||
expect(view.bottom, closeTo(_screenHeight - _navBar, 0.01));
|
||||
_expectWholeTilesOnly(t);
|
||||
// Two columns, a real screenful, and tiles big enough to read.
|
||||
final shown = _shown(t);
|
||||
expect(shown.length.isEven, isTrue);
|
||||
expect(shown.length, greaterThanOrEqualTo(10));
|
||||
expect(shown.first.height, greaterThanOrEqualTo(88));
|
||||
expect(shown.first.width, closeTo(shown[1].width, 0.01));
|
||||
expect(shown[1].left, greaterThan(shown.first.right));
|
||||
});
|
||||
|
||||
testWidgets('Pixel 6a: 300 notes scroll vertically to the last one', (
|
||||
t,
|
||||
) async {
|
||||
_pixel6a(t);
|
||||
await pumpList(t, seed: _notes(300));
|
||||
|
||||
expect(_maxScroll(t), greaterThan(0));
|
||||
await t.drag(find.byType(GridView), const Offset(0, -500000));
|
||||
await t.pump();
|
||||
await t.pump(const Duration(seconds: 1));
|
||||
|
||||
expect(find.textContaining('Note 299 '), findsOneWidget);
|
||||
expect(find.textContaining('Note 299 ').hitTestable(), findsOneWidget);
|
||||
expect(_viewport(t).bottom, closeTo(_screenHeight - _navBar, 0.01));
|
||||
});
|
||||
|
||||
testWidgets('Pixel 6a: exactly one screenful does not scroll', (t) async {
|
||||
_pixel6a(t);
|
||||
await pumpList(t, seed: _notes(300));
|
||||
final perScreen = _shown(t).length;
|
||||
|
||||
await t.pumpWidget(const SizedBox());
|
||||
await pumpList(t, seed: _notes(perScreen));
|
||||
expect(_maxScroll(t), 0);
|
||||
_expectWholeTilesOnly(t);
|
||||
expect(_shown(t), hasLength(perScreen));
|
||||
});
|
||||
|
||||
testWidgets('Pixel 6a: a few notes keep full-size tiles at the top', (
|
||||
t,
|
||||
) async {
|
||||
_pixel6a(t);
|
||||
await pumpList(t, seed: _notes(300));
|
||||
final full = _shown(t).first;
|
||||
|
||||
await t.pumpWidget(const SizedBox());
|
||||
await pumpList(t, seed: _notes(3));
|
||||
expect(_maxScroll(t), 0);
|
||||
expect(t.takeException(), isNull);
|
||||
final first = t.getRect(find.byType(NoteGridTile).first);
|
||||
expect(first.size, full.size);
|
||||
expect(first.top, closeTo(_viewport(t).top, 0.01));
|
||||
});
|
||||
|
||||
testWidgets('Pixel 6a: toolbar, search and a tile are all tappable', (
|
||||
t,
|
||||
) async {
|
||||
_pixel6a(t);
|
||||
await pumpList(t, seed: _notes(20));
|
||||
|
||||
expect(find.byIcon(Icons.sort).hitTestable(), findsOneWidget);
|
||||
expect(find.byIcon(Icons.filter_list).hitTestable(), findsOneWidget);
|
||||
expect(find.byType(TextField).hitTestable(), findsOneWidget);
|
||||
expect(find.byType(NoteGridTile).hitTestable(), findsWidgets);
|
||||
});
|
||||
|
||||
testWidgets('Pixel 6a with the keyboard open: still whole tiles', (t) async {
|
||||
_pixel6a(t, keyboardDp: 300);
|
||||
await pumpList(t, seed: _notes(300));
|
||||
|
||||
expect(t.takeException(), isNull);
|
||||
_expectWholeTilesOnly(t);
|
||||
});
|
||||
|
||||
testWidgets('Pixel 6a at 2x text scale: no overflow, tiles stay whole', (
|
||||
t,
|
||||
) async {
|
||||
_pixel6a(t);
|
||||
t.platformDispatcher.textScaleFactorTestValue = 2;
|
||||
addTearDown(t.platformDispatcher.clearTextScaleFactorTestValue);
|
||||
await pumpList(t, seed: _notes(300));
|
||||
|
||||
expect(t.takeException(), isNull);
|
||||
_expectWholeTilesOnly(t);
|
||||
});
|
||||
}
|
||||
161
test/notes_grid_test.dart
Normal file
161
test/notes_grid_test.dart
Normal file
@ -0,0 +1,161 @@
|
||||
/// What the narrow notes grid shows and does, apart from its geometry.
|
||||
library;
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:todo/data/note.dart';
|
||||
import 'package:todo/ui/note_grid_tile.dart';
|
||||
|
||||
import 'notes_list_harness.dart';
|
||||
|
||||
void _phone(WidgetTester t) {
|
||||
t.view
|
||||
..physicalSize = const Size(1080, 2400)
|
||||
..devicePixelRatio = 2.625;
|
||||
addTearDown(t.view.reset);
|
||||
}
|
||||
|
||||
Future<void> _openSheet(WidgetTester t, String title) async {
|
||||
await t.longPress(find.text(title));
|
||||
await t.pump();
|
||||
await t.pump(const Duration(milliseconds: 300));
|
||||
}
|
||||
|
||||
void main() {
|
||||
testWidgets('phone width shows tiles, desktop width keeps the list', (
|
||||
t,
|
||||
) async {
|
||||
_phone(t);
|
||||
await pumpList(t, seed: [note('a', 'Buy milk')]);
|
||||
expect(find.byType(NoteGridTile), findsOneWidget);
|
||||
expect(find.byType(ListTile), findsNothing);
|
||||
|
||||
t.view
|
||||
..physicalSize = const Size(3840, 2160)
|
||||
..devicePixelRatio = 1;
|
||||
await t.pump();
|
||||
expect(find.byType(NoteGridTile), findsNothing);
|
||||
expect(find.byType(ListTile), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('a tile is title plus priority and status cues only', (t) async {
|
||||
_phone(t);
|
||||
await pumpList(
|
||||
t,
|
||||
seed: [
|
||||
note(
|
||||
'a',
|
||||
'Buy milk\n\n## what\nTwo litres',
|
||||
priority: Priority.high,
|
||||
status: Status.inProgress,
|
||||
),
|
||||
],
|
||||
);
|
||||
|
||||
expect(find.text('Buy milk'), findsOneWidget);
|
||||
expect(find.text('High'), findsOneWidget);
|
||||
expect(find.text('In progress'), findsOneWidget);
|
||||
expect(find.textContaining('Two litres'), findsNothing);
|
||||
expect(find.textContaining('edited'), findsNothing);
|
||||
expect(find.byTooltip('Quick actions'), findsNothing);
|
||||
});
|
||||
|
||||
testWidgets('priority and status each get their own cue', (t) async {
|
||||
_phone(t);
|
||||
await pumpList(
|
||||
t,
|
||||
seed: [
|
||||
note('h', 'H', priority: Priority.high),
|
||||
note('m', 'M'),
|
||||
note('l', 'L', priority: Priority.low, status: Status.inProgress),
|
||||
],
|
||||
);
|
||||
final scheme = Theme.of(t.element(find.byType(Scaffold))).colorScheme;
|
||||
final accents = {
|
||||
for (final id in ['h', 'm', 'l'])
|
||||
t.widget<NoteGridTile>(find.byKey(ValueKey(id))).accentFor(scheme),
|
||||
};
|
||||
expect(accents, hasLength(3));
|
||||
expect(find.byIcon(Icons.radio_button_unchecked), findsNWidgets(2));
|
||||
expect(find.byIcon(Icons.timelapse), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('every status has an icon', (t) async {
|
||||
_phone(t);
|
||||
await pumpList(
|
||||
t,
|
||||
seed: [for (final s in Status.values) note(s.name, s.name, status: s)],
|
||||
);
|
||||
expect(find.byIcon(Icons.check_circle_outline), findsOneWidget);
|
||||
expect(find.byIcon(Icons.cancel_outlined), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('an empty note reads (empty)', (t) async {
|
||||
_phone(t);
|
||||
await pumpList(t, seed: [note('a', '')]);
|
||||
expect(find.text('(empty)'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('tap opens the note', (t) async {
|
||||
_phone(t);
|
||||
await pumpList(t, seed: [note('a', 'Open me')]);
|
||||
|
||||
await t.tap(find.text('Open me'));
|
||||
await t.pumpAndSettle();
|
||||
|
||||
expect(find.text('Priority'), findsOneWidget);
|
||||
expect(find.text('View'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('long-press opens the sheet with body, dates and actions', (
|
||||
t,
|
||||
) async {
|
||||
_phone(t);
|
||||
final repo = await pumpList(
|
||||
t,
|
||||
seed: [note('a', 'Buy milk\n\n## what\nTwo litres of oat')],
|
||||
);
|
||||
|
||||
await _openSheet(t, 'Buy milk');
|
||||
|
||||
expect(find.textContaining('Two litres of oat'), findsOneWidget);
|
||||
expect(find.textContaining('Edited'), findsOneWidget);
|
||||
expect(find.textContaining('Created'), findsOneWidget);
|
||||
await t.tap(find.text('In progress'));
|
||||
await t.pump();
|
||||
expect((await repo.listNotes()).single.status, Status.inProgress);
|
||||
expect(find.text('Delete note'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('a title-only note adds no body to the sheet', (t) async {
|
||||
_phone(t);
|
||||
await pumpList(t, seed: [note('a', 'Just a title')]);
|
||||
|
||||
await _openSheet(t, 'Just a title');
|
||||
|
||||
expect(find.text('Just a title'), findsNWidgets(2));
|
||||
expect(find.textContaining('Edited'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('the sheet can delete a grid note', (t) async {
|
||||
_phone(t);
|
||||
final repo = await pumpList(t, seed: [note('a', 'Delete me')]);
|
||||
|
||||
await _openSheet(t, 'Delete me');
|
||||
await t.tap(find.text('Delete note'));
|
||||
await t.pumpAndSettle();
|
||||
await t.tap(find.text('Delete'));
|
||||
await t.pumpAndSettle();
|
||||
|
||||
expect(await repo.listNotes(), isEmpty);
|
||||
});
|
||||
|
||||
testWidgets('empty state and the default filter survive the grid', (t) async {
|
||||
_phone(t);
|
||||
final repo = await pumpList(t);
|
||||
|
||||
expect(find.textContaining('No notes'), findsOneWidget);
|
||||
expect(repo.lastFilter!.statuses, {Status.todo, Status.inProgress});
|
||||
expect(t.widget<Badge>(find.byType(Badge)).isLabelVisible, isFalse);
|
||||
});
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user