Compare commits

..

No commits in common. "cc9789f5308381257e5c70ba97b363ae293dac63" and "beb1d1a49f95cd78e88361e6267b835cc5a089b4" have entirely different histories.

8 changed files with 49 additions and 381 deletions

View File

@ -26,24 +26,16 @@ typedef SplitAdd = ({Note note, SplitKind kind, String? why});
final _heading = RegExp(r'^##\s+(\[x\]\s+)?(.*)$'); final _heading = RegExp(r'^##\s+(\[x\]\s+)?(.*)$');
/// Every `## title` heading of [text] outside code fences, open or done. /// The open `## title` headings of [text], outside code fences.
Iterable<RegExpMatch> _sections(String text) sync* { Iterable<String> openSections(String text) sync* {
var fenced = false; var fenced = false;
for (final line in text.split('\n')) { for (final line in text.split('\n')) {
if (line.trimLeft().startsWith('```')) fenced = !fenced; if (line.trimLeft().startsWith('```')) fenced = !fenced;
final m = fenced ? null : _heading.firstMatch(line); final m = fenced ? null : _heading.firstMatch(line);
if (m != null) yield m; if (m != null && m.group(1) == null) yield m.group(2)!.trim();
} }
} }
/// The open `## title` headings of [text], outside code fences.
Iterable<String> openSections(String text) => _sections(
text,
).where((m) => m.group(1) == null).map((m) => m.group(2)!.trim());
/// How many board items [text] splits into: one per section, done or not.
int sectionCount(String text) => _sections(text).length;
/// The separate open note of [repo] with an open section titled [title]. /// The separate open note of [repo] with an open section titled [title].
Note? duplicateTarget(Iterable<Note> open, String repo, String title) { Note? duplicateTarget(Iterable<Note> open, String repo, String title) {
final hits = final hits =

View File

@ -5,7 +5,6 @@
/// a board that is down must not lose the task that was just saved. /// a board that is down must not lose the task that was just saved.
library; library;
import 'dart:async';
import 'dart:convert'; import 'dart:convert';
import 'package:http/http.dart' as http; import 'package:http/http.dart' as http;
@ -20,17 +19,9 @@ final _csrf = RegExp(r'<meta\s+name="todoimpl-csrf"\s+content="([^"]+)"');
/// Talks to the board over [client] at [base]. /// Talks to the board over [client] at [base].
class BoardClient { class BoardClient {
/// [client] is injectable so tests need no network. [wait] bounds how /// [client] is injectable so tests need no network.
/// long Start waits for the board to see a merged section (its note cache BoardClient({http.Client? client, Uri? base})
/// lags ~10 s, T1863) and to confirm a Start whose reply outran : _http = client ?? http.Client(),
/// [startTimeout] (T1864); [poll] is the gap between board reads.
BoardClient({
http.Client? client,
Uri? base,
this.wait = const Duration(seconds: 30),
this.poll = const Duration(seconds: 1),
this.startTimeout = const Duration(seconds: 30),
}) : _http = client ?? http.Client(),
base = base ?? kBoardBase; base = base ?? kBoardBase;
final http.Client _http; final http.Client _http;
@ -38,16 +29,7 @@ class BoardClient {
/// The board's origin; also the `Origin` header of a POST. /// The board's origin; also the `Origin` header of a POST.
final Uri base; final Uri base;
/// Longest wait for the board to catch up with the note. static const _timeout = Duration(seconds: 5);
final Duration wait;
/// Gap between two board reads while waiting.
final Duration poll;
/// Longest wait for the reply to a Start POST.
final Duration startTimeout;
static const _timeout = Duration(seconds: 10);
Future<List<Map<String, dynamic>>> _cards(String noteId) async { Future<List<Map<String, dynamic>>> _cards(String noteId) async {
final res = await _http.get(base.resolve('/api/board')).timeout(_timeout); final res = await _http.get(base.resolve('/api/board')).timeout(_timeout);
@ -72,78 +54,29 @@ class BoardClient {
} }
} }
/// Clicks Start on the note's last startable item titled [title]. With /// Clicks Start on the note's last startable item titled [title].
/// [sections], that is the note's last section (`<id8>-<sections - 1>`), Future<StartResult> start(String noteId, String title) async {
/// which a merge just added: waits until the board shows it.
Future<StartResult> start(
String noteId,
String title, {
int? sections,
}) async {
try { try {
final last = sections == null ? null : _item(noteId, sections - 1); final card = (await _cards(noteId)).reversed
bool seen(List<Map<String, dynamic>> cs) =>
last == null || cs.any((c) => c['id'] == last);
final cards = await _until(noteId, seen);
// Exactly the merged item: never an older same-titled one, which the
// board may list last (it orders by column, T1866).
final card = seen(cards)
? cards.reversed
.where((c) => last == null || c['id'] == last)
.where((c) => c['title'] == title && _startable(c)) .where((c) => c['title'] == title && _startable(c))
.firstOrNull .firstOrNull;
: null;
if (card == null) return _no('no startable item'); if (card == null) return _no('no startable item');
final page = await _http.get(base).timeout(_timeout); final page = await _http.get(base).timeout(_timeout);
final token = _csrf.firstMatch(page.body)?.group(1); final token = _csrf.firstMatch(page.body)?.group(1);
if (token == null) return _no('no CSRF token on the board page'); if (token == null) return _no('no CSRF token on the board page');
final id = card['id']! as String; final id = card['id']! as String;
return await _post(noteId, id, token); final res = await _http
} on Object catch (e) {
return _no('board unreachable: $e');
}
}
Future<StartResult> _post(String noteId, String id, String token) async {
final http.Response res;
try {
res = await _http
.post( .post(
base.resolve('/api/task/$id/start'), base.resolve('/api/task/$id/start'),
headers: {'Origin': base.origin, 'X-Todoimpl-Token': token}, headers: {'Origin': base.origin, 'X-Todoimpl-Token': token},
) )
.timeout(startTimeout); .timeout(_timeout);
} on TimeoutException catch (e) {
// The board may still be starting it: a card that left Start took it.
final cards = await _until(
noteId,
(cs) => cs.any((c) => c['id'] == id && !_startable(c)),
);
if (cards.any((c) => c['id'] == id && !_startable(c))) {
return (ok: true, reason: null, item: id);
}
return _no('board unreachable: $e');
}
if (res.statusCode == 200) return (ok: true, reason: null, item: id); if (res.statusCode == 200) return (ok: true, reason: null, item: id);
return _no('board refused start: ${res.statusCode} ${_message(res)}'); return _no('board refused start: ${res.statusCode} ${_message(res)}');
} on Object catch (e) {
return _no('board unreachable: $e');
} }
/// The note's cards once [done] holds, or the last read after [wait].
Future<List<Map<String, dynamic>>> _until(
String noteId,
bool Function(List<Map<String, dynamic>>) done,
) async {
final deadline = DateTime.now().add(wait);
var cards = await _cards(noteId);
while (!done(cards) && DateTime.now().isBefore(deadline)) {
await Future<void>.delayed(poll);
cards = await _cards(noteId);
} }
return cards;
}
static String _item(String noteId, int index) =>
'${noteId.substring(0, 8)}-$index';
static bool _startable(Map<String, dynamic> card) => (card['actions'] as List) static bool _startable(Map<String, dynamic> card) => (card['actions'] as List)
.cast<Map<String, dynamic>>() .cast<Map<String, dynamic>>()

View File

@ -17,7 +17,7 @@ class TaskService {
final BoardClient? _board; final BoardClient? _board;
Future<void> _tail = Future.value(); Future<void> _tail = Future.value();
Future<T> _serial<T>(Future<T> Function() body) { Future<String> _serial(Future<String> Function() body) {
final run = _tail.then((_) => body()); final run = _tail.then((_) => body());
_tail = run.then((_) {}, onError: (_) {}); _tail = run.then((_) {}, onError: (_) {});
return run; return run;
@ -44,14 +44,8 @@ class TaskService {
} }
} }
/// `add_task`: joins the repo's open note (by: claude), or creates it. A /// `add_task`: joins the repo's open note (by: claude), or creates it.
/// board Start after a merge runs once the other calls may go again. Future<String> add(Map<String, dynamic> args) => _serial(() async {
Future<String> add(Map<String, dynamic> args) async {
final (:reply, :start) = await _serial(() => _add(args));
return start == null ? reply : '$reply\n${await start()}';
}
Future<SplitReply> _add(Map<String, dynamic> args) async {
final a = _Args(args); final a = _Args(args);
final repo = a.repo(required: true)!; final repo = a.repo(required: true)!;
final title = a.required('title'); final title = a.required('title');
@ -77,9 +71,8 @@ class TaskService {
priority: a.priority() ?? Priority.medium, priority: a.priority() ?? Priority.medium,
by: 'claude', by: 'claude',
); );
final verb = added.appended ? 'appended to' : 'added'; return await _save(added.note, added.appended ? 'appended to' : 'added');
return (reply: await _save(added.note, verb), start: null); });
}
/// `list_tasks`: repo tasks, open ones unless `status` says otherwise. /// `list_tasks`: repo tasks, open ones unless `status` says otherwise.
Future<String> list(Map<String, dynamic> args) => _serial(() async { Future<String> list(Map<String, dynamic> args) => _serial(() async {

View File

@ -10,14 +10,9 @@ import 'package:todo/mcp/board_client.dart';
/// Saves [note] and returns `<verb> <id>` plus its list line. /// Saves [note] and returns `<verb> <id>` plus its list line.
typedef SaveNote = Future<String> Function(Note note, String verb); typedef SaveNote = Future<String> Function(Note note, String verb);
/// A saved split add: its reply so far, and the board Start still to run. /// Adds a separate task, merging into a duplicate's note when it is idle,
/// The caller runs [start] after releasing its lock, since the board learns /// and clicks Start on the board after a merge that may run.
/// about the merged section by calling this same server (T1865). Future<String> addSplit(
typedef SplitReply = ({String reply, Future<String> Function()? start});
/// Adds a separate task, merging into a duplicate's note when it is idle;
/// a merge that may run comes back with the Start to click on the board.
Future<SplitReply> addSplit(
NoteRepository repository, NoteRepository repository,
BoardClient? board, BoardClient? board,
SaveNote save, { SaveNote save, {
@ -39,28 +34,15 @@ Future<SplitReply> addSplit(
); );
if (added.kind != SplitKind.merged) { if (added.kind != SplitKind.merged) {
final reply = await save(added.note, 'added'); final reply = await save(added.note, 'added');
return ( return added.why == null ? reply : '$reply\n${added.why}';
reply: added.why == null ? reply : '$reply\n${added.why}',
start: null,
);
} }
final reply = await save(added.note, 'merged into'); final reply = await save(added.note, 'merged into');
final block = startBlock(doneCheck, body); final block = startBlock(doneCheck, body);
if (block != null) { if (block != null) return '$reply\nstart: skipped ($block)';
return (reply: '$reply\nstart: skipped ($block)', start: null); final start = board == null
}
Future<String> start() async {
final s = board == null
? (ok: false, reason: 'no board configured', item: null) ? (ok: false, reason: 'no board configured', item: null)
: await board.start( : await board.start(added.note.id, title.trim());
added.note.id, if (start.ok) return '$reply\nstart: ok ${start.item}';
title.trim(), return '$reply\nstart: {ok: false, reason: "${start.reason}"}; '
sections: sectionCount(added.note.text),
);
if (s.ok) return 'start: ok ${s.item}';
return 'start: {ok: false, reason: "${s.reason}"}; '
'the merge is saved, click Start on the board by hand'; 'the merge is saved, click Start on the board by hand';
}
return (reply: reply, start: start);
} }

View File

@ -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 # 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 # 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. # of the product and file versions while build-number is used as the build suffix.
version: 1.0.65+1 version: 1.0.63+1
environment: environment:
sdk: ^3.12.2 sdk: ^3.12.2

View File

@ -32,26 +32,13 @@ class _Board {
String startBody = '{"ok":false,"error":{"message":"nope"}}'; String startBody = '{"ok":false,"error":{"message":"nope"}}';
String page = '<meta name="todoimpl-csrf" content="tok-1">'; String page = '<meta name="todoimpl-csrf" content="tok-1">';
/// Board reads so far; [onRead] may change [cards] between reads. BoardClient client() => BoardClient(
int reads = 0;
void Function(int read)? onRead;
Duration postDelay = Duration.zero;
BoardClient client({
Duration wait = Duration.zero,
Duration startTimeout = const Duration(seconds: 5),
}) => BoardClient(
wait: wait,
poll: const Duration(milliseconds: 5),
startTimeout: startTimeout,
client: MockClient((req) async { client: MockClient((req) async {
if (req.method == 'POST') { if (req.method == 'POST') {
posts.add(req); posts.add(req);
await Future<void>.delayed(postDelay);
return http.Response(startBody, startStatus); return http.Response(startBody, startStatus);
} }
if (req.url.path == '/api/board') { if (req.url.path == '/api/board') {
onRead?.call(++reads);
return http.Response.bytes( return http.Response.bytes(
utf8.encode(jsonEncode({'tasks': cards})), utf8.encode(jsonEncode({'tasks': cards})),
boardStatus, boardStatus,
@ -137,78 +124,6 @@ void main() {
); );
}); });
test('T1863: waits for the board to see a freshly merged section', () async {
final b = _Board([_card('cccccccc-0', 'Młody')]);
b.onRead = (n) {
if (n == 3) b.cards.add(_card('cccccccc-1', 'Młody'));
};
final r = await b
.client(wait: const Duration(seconds: 2))
.start(_id, 'Młody', sections: 2);
expect(r, (ok: true, reason: null, item: 'cccccccc-1'));
});
test('T1863: a board that never shows the section gives up', () async {
final b = _Board([_card('cccccccc-0', 'Młody')]);
final r = await b
.client(wait: const Duration(milliseconds: 50))
.start(_id, 'Młody', sections: 2);
expect(r.ok, isFalse);
expect(r.reason, 'no startable item');
expect(b.posts, isEmpty);
});
test('T1866: starts the merged item, not a re-startable older one', () async {
// The board lists by column: a cancelled older item may come last.
final b = _Board([
_card('cccccccc-0', 'Młody'),
_card('cccccccc-2', 'Młody'),
_card('cccccccc-1', 'Młody', column: 'done'),
]);
final r = await b.client().start(_id, 'Młody', sections: 3);
expect(r, (ok: true, reason: null, item: 'cccccccc-2'));
final other = _Board([
_card('cccccccc-1', 'Młody', column: 'done'),
_card('cccccccc-0', 'Młody', start: false),
]);
final none = await other.client().start(_id, 'Młody', sections: 1);
expect(none.reason, 'no startable item');
expect(other.posts, isEmpty);
});
test('T1864: a slow Start that took effect is ok, not unreachable', () async {
final b = _Board([_card('cccccccc-0', 'Młody')])
..postDelay = const Duration(milliseconds: 200);
b.onRead = (n) {
// After the POST was sent the card has left backlog (no Start action).
if (b.posts.isNotEmpty) {
b.cards[0] = _card(
'cccccccc-0',
'Młody',
column: 'running',
start: false,
);
}
};
final r = await b
.client(startTimeout: const Duration(milliseconds: 50))
.start(_id, 'Młody');
expect(r, (ok: true, reason: null, item: 'cccccccc-0'));
});
test(
'T1864: a slow Start that did not take effect is still a reason',
() async {
final b = _Board([_card('cccccccc-0', 'Młody')])
..postDelay = const Duration(milliseconds: 200);
final r = await b
.client(startTimeout: const Duration(milliseconds: 50))
.start(_id, 'Młody');
expect(r.ok, isFalse);
expect(r.reason, startsWith('board unreachable'));
},
);
test('the default client targets the loopback board', () { test('the default client targets the loopback board', () {
expect(BoardClient().base.toString(), 'http://127.0.0.1:8786'); expect(BoardClient().base.toString(), 'http://127.0.0.1:8786');
}); });

View File

@ -1,108 +0,0 @@
// T1865: the real board learns about notes by calling this MCP server, so a
// merged add_task must not hold the server while it waits for the board.
import 'dart:async';
import 'dart:convert';
import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart' as http;
import 'package:http/testing.dart';
import 'package:mcp_dart/mcp_dart.dart';
import 'package:todo/mcp/board_client.dart';
import 'mcp_harness.dart';
void main() {
late McpHarness h;
late McpClient c;
late McpClient boardSide;
String? note;
var cards = <Map<String, dynamic>>[];
final posts = <String>[];
// A board whose every read refreshes its cards from this MCP server, as
// the real one does; a refresh that cannot get through keeps stale cards.
Future<List<Map<String, dynamic>>> refresh() async {
final id = note;
if (id == null) return cards;
try {
final text = await h
.call(boardSide, 'get_task', {'id': id})
.timeout(const Duration(milliseconds: 300));
final n = '\n$text'.split('\n## ').length - 1;
cards = [
for (var i = 0; i < n; i++)
{
'id': '${id.substring(0, 8)}-$i',
'title': 'Młody',
'column': 'backlog',
'actions': [
{'id': 'start', 'enabled': true},
],
},
];
} on TimeoutException {
// Stale, like the real cache when the server does not answer.
}
return cards;
}
final board = BoardClient(
wait: const Duration(seconds: 2),
poll: const Duration(milliseconds: 20),
client: MockClient((req) async {
if (req.method == 'POST') {
posts.add(req.url.path);
return http.Response('{"ok":true}', 200);
}
if (req.url.path == '/api/board') {
return http.Response.bytes(
utf8.encode(jsonEncode({'tasks': await refresh()})),
200,
);
}
return http.Response('<meta name="todoimpl-csrf" content="t">', 200);
}),
);
setUp(() async {
note = null;
cards = [];
posts.clear();
h = McpHarness(board: board);
await h.start();
c = await h.connect();
boardSide = await h.connect();
});
tearDown(() => h.dispose());
test('T1865: Start after a merge sees the board refreshed', () async {
final args = {
'repo': 'kuhyx/herosi',
'title': 'Młody',
'body': 'what',
'new_note': true,
'done_check': 'true',
};
note = idIn(await h.call(c, 'add_task', args));
final r = await h.call(c, 'add_task', args);
expect(r, startsWith('merged into $note'));
expect(r, contains('start: ok ${note!.substring(0, 8)}-1'));
expect(posts, ['/api/task/${note!.substring(0, 8)}-1/start']);
});
test('a merge with no board configured says click Start', () async {
final bare = McpHarness();
await bare.start();
addTearDown(bare.dispose);
final client = await bare.connect();
final args = {'repo': 'kuhyx/herosi', 'title': 'A', 'new_note': true};
final x = idIn(await bare.call(client, 'add_task', args));
final r = await bare.call(client, 'add_task', {
...args,
'done_check': 'true',
});
expect(r, startsWith('merged into $x'));
expect(r, contains('reason: "no board configured"'));
expect(r, contains('click Start on the board by hand'));
});
}

View File

@ -6,7 +6,6 @@ import 'package:http/http.dart' as http;
import 'package:http/testing.dart'; import 'package:http/testing.dart';
import 'package:mcp_dart/mcp_dart.dart'; import 'package:mcp_dart/mcp_dart.dart';
import 'package:todo/mcp/board_client.dart'; import 'package:todo/mcp/board_client.dart';
import 'package:todo/mcp/task_service.dart';
import 'mcp_harness.dart'; import 'mcp_harness.dart';
@ -16,14 +15,9 @@ void main() {
late McpHarness h; late McpHarness h;
late McpClient c; late McpClient c;
var cards = <Map<String, dynamic>>[]; var cards = <Map<String, dynamic>>[];
// Cards the board shows only from its next read on (its note cache lags).
var late_ = <Map<String, dynamic>>[];
var lag = 0; // board reads before [late_] shows
var up = true; var up = true;
final posts = <String>[]; final posts = <String>[];
final board = BoardClient( final board = BoardClient(
wait: const Duration(seconds: 2),
poll: const Duration(milliseconds: 5),
client: MockClient((req) async { client: MockClient((req) async {
if (!up) throw http.ClientException('connection refused'); if (!up) throw http.ClientException('connection refused');
if (req.method == 'POST') { if (req.method == 'POST') {
@ -31,26 +25,17 @@ void main() {
return http.Response('{"ok":true}', 200); return http.Response('{"ok":true}', 200);
} }
if (req.url.path == '/api/board') { if (req.url.path == '/api/board') {
if (lag-- == 0) {
cards = [...cards, ...late_];
late_ = [];
}
final shown = [...cards];
return http.Response.bytes( return http.Response.bytes(
utf8.encode(jsonEncode({'tasks': shown})), utf8.encode(jsonEncode({'tasks': cards})),
200, 200,
); );
} }
return http.Response('<meta name="todoimpl-csrf" content="t">', 200); return http.Response('<meta name="todoimpl-csrf" content="t">', 200);
}), }),
); );
List<Map<String, dynamic>> cardsOf( List<Map<String, dynamic>> cardsOf(String id, String column) => [
String id,
String column, [
int index = 0,
]) => [
{ {
'id': '${id.substring(0, 8)}-$index', 'id': '${id.substring(0, 8)}-0',
'title': 'Młody', 'title': 'Młody',
'column': column, 'column': column,
'actions': [ 'actions': [
@ -61,8 +46,6 @@ void main() {
setUp(() async { setUp(() async {
cards = []; cards = [];
late_ = [];
lag = 0;
up = true; up = true;
posts.clear(); posts.clear();
h = McpHarness(board: board); h = McpHarness(board: board);
@ -95,22 +78,16 @@ void main() {
expect(posts, isEmpty); expect(posts, isEmpty);
}); });
test( test('C3/C6: a duplicate merges and Start is POSTed', () async {
'C3/C6/T1863: a duplicate merges, Start waits for the new item',
() async {
final x = idIn(await add({'done_check': 'true'})); final x = idIn(await add({'done_check': 'true'}));
cards = cardsOf(x, 'backlog'); cards = cardsOf(x, 'backlog');
// The merged section shows up one read later than the merge itself.
late_ = cardsOf(x, 'backlog', 1);
lag = 2; // past the guard's running read and the first Start read
final r = await add({'done_check': 'true'}); final r = await add({'done_check': 'true'});
expect(r, startsWith('merged into $x')); expect(r, startsWith('merged into $x'));
expect(r, contains('start: ok ${x.substring(0, 8)}-1')); expect(r, contains('start: ok ${x.substring(0, 8)}-0'));
expect(posts, ['/api/task/${x.substring(0, 8)}-1/start']); expect(posts, ['/api/task/${x.substring(0, 8)}-0/start']);
final listed = await h.call(c, 'list_tasks', {'repo': _repo}); final listed = await h.call(c, 'list_tasks', {'repo': _repo});
expect(listed.trim().split('\n'), hasLength(1)); expect(listed.trim().split('\n'), hasLength(1));
}, });
);
test('C6: done_check none or low priority merges without Start', () async { test('C6: done_check none or low priority merges without Start', () async {
final x = idIn(await add({})); final x = idIn(await add({}));
@ -143,22 +120,6 @@ void main() {
expect(r, contains('click Start on the board by hand')); expect(r, contains('click Start on the board by hand'));
}); });
test('a non-boolean new_note is refused by the service too', () {
// The MCP schema rejects it first; the service guards its own callers.
expect(
TaskService(
h.session,
).add({'repo': _repo, 'title': 'Młody', 'new_note': 'yes'}),
throwsA(
isA<FormatException>().having(
(e) => e.message,
'message',
'new_note: must be a boolean',
),
),
);
});
test('the add_task schema offers new_note', () async { test('the add_task schema offers new_note', () async {
final tools = (await c.listTools()).tools; final tools = (await c.listTools()).tools;
final add = tools.singleWhere((t) => t.name == 'add_task'); final add = tools.singleWhere((t) => t.name == 'add_task');