Compare commits
71 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 7153630a2e | |||
| f20e2ab16f | |||
| a96babd8f8 | |||
| 5d83ff561e | |||
| d5764fce7b | |||
| 660d82282c | |||
| 300d50ab11 | |||
| ea216d4a59 | |||
| fafefabab6 | |||
| 5acd9d4863 | |||
| 9d2a5a0bd3 | |||
| 3a747c2e51 | |||
| 1f7c31357b | |||
| b350b3e8c1 | |||
| e885465f55 | |||
| be6bf6fc48 | |||
| b2ffc346c3 | |||
| 0ce9c42ff6 | |||
| de5ad7d2dd | |||
| cd50fd0ae2 | |||
| 19f930a93a | |||
| f7e24bbb1a | |||
| 4423937f5c | |||
| f4913daaa8 | |||
| c9eb4d6cff | |||
| 1010d96426 | |||
| 319f18d33a | |||
| c3ac6ec05d | |||
| 0e56cddd47 | |||
| 203e61d6ac | |||
| edf6969949 | |||
| 5ea7ba7b73 | |||
| 091e68a2d9 | |||
| a30e7b34a9 | |||
| 17d6d2a533 | |||
| 4e8ccd6bfd | |||
| 6bd2923f0a | |||
| 4c77dd5d2e | |||
| 757c54beda | |||
| 5c1bf75bf9 | |||
| 57019eec30 | |||
| cc9789f530 | |||
| 135f3f07ea | |||
| ba25e8f176 | |||
| beb1d1a49f | |||
| 75248e9cde | |||
| 9a8e7aefd2 | |||
| 75788c7bdb | |||
| 1baaf236d4 | |||
| dc96bff3df | |||
| b92d133c17 | |||
| a0c1938d8d | |||
| cbe3d9be59 | |||
| 67212cd7ec | |||
| 9b42ff8ba2 | |||
| dc547763fc | |||
| 4a30a52375 | |||
| 860d789864 | |||
| d09978a338 | |||
| cf01784241 | |||
| 0ff3d6f95d | |||
| d14b7e03e3 | |||
| 2a9332094a | |||
| 9e18821c7b | |||
| f7ea0ffb3d | |||
| 2ffae26f93 | |||
| 377ec17356 | |||
| 9349747629 | |||
| 64bce89d87 | |||
| c71b98c08b | |||
| 341a943277 |
5
.claude/settings.json
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
{
|
||||||
|
"enabledPlugins": {
|
||||||
|
"dart-flutter@dart-flutter": true
|
||||||
|
}
|
||||||
|
}
|
||||||
2
.dep-freshness-no-workflow
Normal file
@ -0,0 +1,2 @@
|
|||||||
|
# Dependency freshness runs locally only (pre-commit hook); no GitHub Actions
|
||||||
|
# workflow. This marker stops the fleet installer from re-adding it.
|
||||||
62
.github/workflows/dependency-freshness.yml
vendored
@ -1,62 +0,0 @@
|
|||||||
name: dependency freshness
|
|
||||||
|
|
||||||
# Every dependency on its ecosystem's newest STABLE release, enforced on push
|
|
||||||
# as well as at commit time. The local pre-commit hook only sees the manifests
|
|
||||||
# in a commit and can be skipped entirely by a fresh clone that never ran
|
|
||||||
# `pre-commit install`; this runs `--all` over the whole repo.
|
|
||||||
#
|
|
||||||
# `--strict` is CI-only. Offline the gate degrades to its cached answer and
|
|
||||||
# passes, because `--no-verify` is banned locally and a hook that hard-failed
|
|
||||||
# on a flaky connection would leave no way to commit. A runner is always
|
|
||||||
# online, so here an undeterminable answer is a real failure.
|
|
||||||
#
|
|
||||||
# Expect this to go red for reasons this repo's commit did not cause: an
|
|
||||||
# upstream release overnight is enough. That is the chosen behaviour -- the
|
|
||||||
# alternative is a gate that only notices staleness when someone remembers to
|
|
||||||
# look.
|
|
||||||
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
branches: [main]
|
|
||||||
pull_request:
|
|
||||||
workflow_dispatch:
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
dependency-freshness:
|
|
||||||
name: dependencies on newest stable
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
|
|
||||||
# The gate lives in the shared utils repo so every repo resolves the
|
|
||||||
# same "latest stable" the same way. Checking it out beats vendoring a
|
|
||||||
# copy, which is exactly how a gate and its survey start disagreeing.
|
|
||||||
- name: Check out the shared gate
|
|
||||||
uses: actions/checkout@v4
|
|
||||||
with:
|
|
||||||
repository: kuhyx/utils
|
|
||||||
path: .utils
|
|
||||||
|
|
||||||
# "3.x", never a pinned minor: the Python target IS the interpreter the
|
|
||||||
# gate runs under (registries/toolchain.python_installed), so a runner
|
|
||||||
# held a release behind this machine reports a repo's `requires-python`
|
|
||||||
# as excluding "latest" while the same check passes locally. flax-docs-mcp
|
|
||||||
# hit exactly that -- `>=3.14` green here, red on a 3.13 runner.
|
|
||||||
- name: Set up Python
|
|
||||||
uses: actions/setup-python@v5
|
|
||||||
with:
|
|
||||||
python-version: "3.x"
|
|
||||||
|
|
||||||
- name: Install the gate's two runtime dependencies
|
|
||||||
run: python -m pip install --upgrade pyyaml packaging
|
|
||||||
|
|
||||||
- name: Cache registry lookups
|
|
||||||
uses: actions/cache@v4
|
|
||||||
with:
|
|
||||||
path: ~/.cache/dep-freshness
|
|
||||||
key: dep-freshness-${{ hashFiles('**/pubspec.yaml', '**/pyproject.toml',
|
|
||||||
'**/requirements*.txt', '**/package.json', '**/Cargo.toml', '**/go.mod') }}
|
|
||||||
restore-keys: dep-freshness-
|
|
||||||
|
|
||||||
- name: Every dependency is on newest stable
|
|
||||||
run: bash .utils/scripts/check_dependency_freshness.sh --all --strict
|
|
||||||
6
.github/workflows/release-apk.yml
vendored
@ -47,7 +47,7 @@ jobs:
|
|||||||
|
|
||||||
- uses: subosito/flutter-action@v2
|
- uses: subosito/flutter-action@v2
|
||||||
with:
|
with:
|
||||||
flutter-version: 3.47.7
|
flutter-version: 3.50.1
|
||||||
channel: stable
|
channel: stable
|
||||||
cache: true
|
cache: true
|
||||||
|
|
||||||
@ -110,7 +110,9 @@ jobs:
|
|||||||
flutter build apk --release \
|
flutter build apk --release \
|
||||||
--target-platform android-arm64 \
|
--target-platform android-arm64 \
|
||||||
--build-name="${{ steps.ver.outputs.semver }}" \
|
--build-name="${{ steps.ver.outputs.semver }}" \
|
||||||
--build-number="${{ steps.vc.outputs.code }}"
|
--build-number="${{ steps.vc.outputs.code }}" \
|
||||||
|
--dart-define=APP_BUILD="${{ steps.vc.outputs.code }}" \
|
||||||
|
--dart-define=APP_VERSION="${{ steps.ver.outputs.semver }}"
|
||||||
|
|
||||||
# Fail closed. `findByName("release") ?: debug` silently falls back to
|
# Fail closed. `findByName("release") ?: debug` silently falls back to
|
||||||
# the debug key if key.properties is misplaced, producing a green build
|
# the debug key if key.properties is misplaced, producing a green build
|
||||||
|
|||||||
@ -1,10 +1,11 @@
|
|||||||
{
|
{
|
||||||
"mcpServers": {
|
"mcpServers": {
|
||||||
"todo": {
|
"todo": {
|
||||||
"type": "stdio",
|
"type": "http",
|
||||||
"command": "${HOME}/.venvs/todo-mcp/bin/python",
|
"url": "http://127.0.0.1:8735/mcp",
|
||||||
"args": ["-m", "todo_mcp._mcp"],
|
"headers": {
|
||||||
"env": {}
|
"Authorization": "Bearer ${TODO_MCP_TOKEN}"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -73,6 +73,30 @@ repos:
|
|||||||
language: system
|
language: system
|
||||||
files: \.(md|markdown)$
|
files: \.(md|markdown)$
|
||||||
|
|
||||||
|
- id: todo-closer
|
||||||
|
name: close Todo trailer tasks
|
||||||
|
entry: scripts/todo_hooks.sh closer
|
||||||
|
language: system
|
||||||
|
stages: [post-commit]
|
||||||
|
always_run: true
|
||||||
|
pass_filenames: false
|
||||||
|
|
||||||
|
- id: todo-import-pr-merge
|
||||||
|
name: import PR Todo sections (pull)
|
||||||
|
entry: scripts/todo_hooks.sh import-pr post-merge
|
||||||
|
language: system
|
||||||
|
stages: [post-merge]
|
||||||
|
always_run: true
|
||||||
|
pass_filenames: false
|
||||||
|
|
||||||
|
- id: todo-import-pr-rewrite
|
||||||
|
name: import PR Todo sections (pull --rebase)
|
||||||
|
entry: scripts/todo_hooks.sh import-pr post-rewrite
|
||||||
|
language: system
|
||||||
|
stages: [post-rewrite]
|
||||||
|
always_run: true
|
||||||
|
pass_filenames: false
|
||||||
|
|
||||||
# Every dependency on its ecosystem's newest STABLE release, exact-pinned
|
# Every dependency on its ecosystem's newest STABLE release, exact-pinned
|
||||||
# so the question is mechanically answerable at all.
|
# so the question is mechanically answerable at all.
|
||||||
#
|
#
|
||||||
@ -82,7 +106,7 @@ repos:
|
|||||||
# Runs WITHOUT --strict on purpose. Offline it degrades to the cached
|
# Runs WITHOUT --strict on purpose. Offline it degrades to the cached
|
||||||
# answer and passes with a loud banner; `--no-verify` is banned here, so
|
# answer and passes with a loud banner; `--no-verify` is banned here, so
|
||||||
# a hook that hard-failed on a flaky connection would leave no way to
|
# a hook that hard-failed on a flaky connection would leave no way to
|
||||||
# commit at all. CI, always online, is the strict authority.
|
# commit at all. Local only: no CI workflow runs this.
|
||||||
- id: dependency-freshness
|
- id: dependency-freshness
|
||||||
name: dependencies on newest stable
|
name: dependencies on newest stable
|
||||||
entry: scripts/check_dependency_freshness.sh
|
entry: scripts/check_dependency_freshness.sh
|
||||||
@ -98,4 +122,4 @@ repos:
|
|||||||
entry: scripts/check_repo_contract.sh
|
entry: scripts/check_repo_contract.sh
|
||||||
language: system
|
language: system
|
||||||
pass_filenames: false
|
pass_filenames: false
|
||||||
files: ^(CLAUDE\.md|AGENTS\.md|scripts/test_changed\.sh)$
|
files: ^(CLAUDE\.md|AGENTS\.md|scripts/test_changed\.sh)$|(^|/)(AndroidManifest\.xml|build\.gradle(\.kts)?|strings\.xml|pubspec\.yaml|repo-contract\.toml|[^/]+\.desktop|assets/icon/[^/]+\.png)$
|
||||||
|
|||||||
42
AGENTS.md
@ -43,12 +43,14 @@ 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
|
- Release APK: `flutter build apk --release` (signs with the debug key; debug
|
||||||
builds are janky — always measure smoothness on a release build).
|
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`.
|
- 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`)
|
- run: `./run.sh` (desktop; mobile: `flutter run`)
|
||||||
- test: `flutter test --reporter=compact`
|
- test: `flutter test --reporter=compact`
|
||||||
- test-changed: `scripts/test_changed.sh`
|
- test-changed: `scripts/test_changed.sh`
|
||||||
- lint: `flutter analyze`
|
- lint: `flutter analyze`
|
||||||
- coverage: `flutter test --coverage --reporter=compact`
|
- coverage: `flutter test --coverage --reporter=compact`
|
||||||
- coverage-gaps: `coverage-gaps coverage/lcov.info`
|
- coverage-gaps: `coverage-gaps coverage/lcov.info`
|
||||||
|
- deploy: `scripts/deploy.sh` (MCP service, desktop pacman package, phone release; exits non-zero unless every health check passes)
|
||||||
|
|
||||||
## Architecture
|
## Architecture
|
||||||
|
|
||||||
@ -57,10 +59,15 @@ Three layers under `lib/`, each single-purpose:
|
|||||||
- `data/` — domain + local storage.
|
- `data/` — domain + local storage.
|
||||||
- `note.dart`: `Note` model; `Priority` enum (low/medium/high, **default
|
- `note.dart`: `Note` model; `Priority` enum (low/medium/high, **default
|
||||||
medium**, no "none"); `Status` enum (todo/inProgress/done/abandoned).
|
medium**, no "none"); `Status` enum (todo/inProgress/done/abandoned).
|
||||||
- `note_repository.dart`: CRDT storage over `sqlite_crdt`. Schema is at
|
Optional repo-task fields `repo`/`doneCheck`/`by`/`evidence`: a note
|
||||||
**version 3** with `onCreate`/`onUpgrade` migrations (v1→v2 adds the
|
with `repo` is a repo task, one without is a plain idea.
|
||||||
`status` column; v2→v3 backfills legacy priority `0`→medium). Also defines
|
- `note_repository.dart`: CRDT storage over the schemaless `crdt_sync`
|
||||||
`NoteFilter` (query / priorities / statuses / created+updated date ranges,
|
`LogStore`; `note_record.dart` maps a note to record fields `text`,
|
||||||
|
`priority`, `status`, `created_at`, `updated_at` (+ `repo`, `done_check`,
|
||||||
|
`by`, `evidence`, written only when set, so an idea's record stays
|
||||||
|
v3-identical: `note_repository_sync_compat_test.dart`). The old sqlite
|
||||||
|
schema (v3) survives only in `legacy_sqlite_migration.dart`. Also defines
|
||||||
|
`NoteFilter` (query / priorities / statuses / repo / date ranges,
|
||||||
AND-combined), `NoteSort`, `watchNotes`/`watchCount` streams, and
|
AND-combined), `NoteSort`, `watchNotes`/`watchCount` streams, and
|
||||||
`importNotes` (safe newer-wins merge by id).
|
`importNotes` (safe newer-wins merge by id).
|
||||||
- `sync/` — GitHub-as-storage sync.
|
- `sync/` — GitHub-as-storage sync.
|
||||||
@ -79,8 +86,12 @@ Three layers under `lib/`, each single-purpose:
|
|||||||
- `capture_screen.dart`: landing screen; always-focused text box pre-filled
|
- `capture_screen.dart`: landing screen; always-focused text box pre-filled
|
||||||
with the structured template; lazy note creation on first keystroke.
|
with the structured template; lazy note creation on first keystroke.
|
||||||
- `notes_list_screen.dart`: list + search + sort + filter sheet + per-note
|
- `notes_list_screen.dart`: list + search + sort + filter sheet + per-note
|
||||||
sheet. **Default view hides Done/Abandoned and shows no filter badge**
|
sheet. One open note per repo (`data/repo_note.dart`). **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
|
- `settings_screen.dart`: GitHub connect/test, device-flow auth, and the
|
||||||
Export/Import backup actions.
|
Export/Import backup actions.
|
||||||
- `main.dart`: bootstrap only (`// coverage:ignore-file`) — wires platform DB
|
- `main.dart`: bootstrap only (`// coverage:ignore-file`) — wires platform DB
|
||||||
@ -135,8 +146,8 @@ rest of the wrapper one request at a time. BACKLOG.md rewrites links to
|
|||||||
|
|
||||||
## Testing
|
## Testing
|
||||||
|
|
||||||
- **The suite must stay quick and fully green.** It is currently **494 tests at
|
- **The suite must stay quick and fully green.** It is currently **604 tests at
|
||||||
100% line coverage** (2870 lines), ~40s on this machine with
|
100% line coverage** (3305 lines), ~40s on this machine with
|
||||||
`--concurrency=3` (unbounded concurrency under `capped.sh`'s 4 GiB gets its
|
`--concurrency=3` (unbounded concurrency under `capped.sh`'s 4 GiB gets its
|
||||||
test processes SIGTERMed while the wrapper still exits 0 — check the last
|
test processes SIGTERMed while the wrapper still exits 0 — check the last
|
||||||
line says "All tests passed"). Don't regress either.
|
line says "All tests passed"). Don't regress either.
|
||||||
@ -207,3 +218,18 @@ about *this repo*:
|
|||||||
|
|
||||||
Sourced from [flutter/flutter docs/rules/rules.md](https://github.com/flutter/flutter/blob/main/docs/rules/rules.md)
|
Sourced from [flutter/flutter docs/rules/rules.md](https://github.com/flutter/flutter/blob/main/docs/rules/rules.md)
|
||||||
via `~/.claude/CLAUDE.md`'s Flutter AI tooling setup. Re-fetch periodically.
|
via `~/.claude/CLAUDE.md`'s Flutter AI tooling setup. Re-fetch periodically.
|
||||||
|
|
||||||
|
## Driving the app on the phone
|
||||||
|
|
||||||
|
Tap and type by label, never by coordinate, with `android_ui` from
|
||||||
|
`~/src/testsAndMisc` (not copied here):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd ~/src/testsAndMisc && .venv/bin/python -m python_pkg.android_ui \
|
||||||
|
-s 23181JEGR08034 --display self dump
|
||||||
|
```
|
||||||
|
|
||||||
|
The same driver is the `android-ui` MCP server
|
||||||
|
(`.venv/bin/python -m python_pkg.android_ui.mcp_server`, in that repo's
|
||||||
|
`.mcp.json`). Tools and error contract:
|
||||||
|
`~/src/testsAndMisc/python_pkg/android_ui/README.md`.
|
||||||
|
|||||||
15
README.md
@ -37,3 +37,18 @@ dart run bin/todo_note.dart --delete <id>
|
|||||||
`--list` and `--get` never push; `--data-dir <dir>` selects a throwaway node.
|
`--list` and `--get` never push; `--data-dir <dir>` selects a throwaway node.
|
||||||
Exit codes: 0 ok, 1 sync/auth failure or note not found, 2 bad arguments.
|
Exit codes: 0 ok, 1 sync/auth failure or note not found, 2 bad arguments.
|
||||||
All logic is in `lib/cli/` (tested in `test/cli/`); `--help` lists every flag.
|
All logic is in `lib/cli/` (tested in `test/cli/`); `--help` lists every flag.
|
||||||
|
|
||||||
|
## Driving the app on the phone
|
||||||
|
|
||||||
|
Tap and type by label, never by coordinate, with `android_ui` from
|
||||||
|
`~/src/testsAndMisc` (not copied here):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd ~/src/testsAndMisc && .venv/bin/python -m python_pkg.android_ui \
|
||||||
|
-s 23181JEGR08034 --display self dump
|
||||||
|
```
|
||||||
|
|
||||||
|
The same driver is the `android-ui` MCP server
|
||||||
|
(`.venv/bin/python -m python_pkg.android_ui.mcp_server`, in that repo's
|
||||||
|
`.mcp.json`). Tools and error contract:
|
||||||
|
`~/src/testsAndMisc/python_pkg/android_ui/README.md`.
|
||||||
|
|||||||
@ -1,91 +0,0 @@
|
|||||||
# Design audit — todo
|
|
||||||
|
|
||||||
Generated against safe-design-rules (anthonyhobday.com/sideprojects/saferules).
|
|
||||||
Report only — nothing in this repo was changed by the audit itself.
|
|
||||||
|
|
||||||
## Flutter app (lib/)
|
|
||||||
|
|
||||||
Theme entry point: `lib/main.dart:36-39` — a single inline `ThemeData` with
|
|
||||||
`ColorScheme.fromSeed(seedColor: Colors.deepPurple)` and `useMaterial3: true`.
|
|
||||||
No dedicated theme file, no `darkTheme`, no `textTheme`/component-theme
|
|
||||||
overrides, no custom shadows or corner radii anywhere in `lib/` (confirmed by
|
|
||||||
grepping for `BoxShadow`, `elevation`, `BorderRadius`, `Card(` — zero hits
|
|
||||||
outside framework defaults). This means almost every token rule is satisfied
|
|
||||||
*by deferring to Material 3's generated palette/type scale*, which is itself a
|
|
||||||
coherent, deliberately-designed system — that counts as Pass, not as an
|
|
||||||
absence-of-system finding (contrast the web/Tkinter case where hardcoded
|
|
||||||
per-file values have no source of truth at all).
|
|
||||||
|
|
||||||
### Violations
|
|
||||||
|
|
||||||
- **Rule 4 (everything deliberate) / color consistency** — `lib/ui/settings_screen.dart:410` —
|
|
||||||
`Text(_error!, style: const TextStyle(color: Colors.red))` hardcodes a raw
|
|
||||||
`Colors.red` instead of the theme's error color. Every other error-state
|
|
||||||
text in the app uses `theme.colorScheme.error`
|
|
||||||
(`lib/ui/capture_screen.dart:522`, `lib/ui/notes_list_screen.dart:375`) —
|
|
||||||
this is the one place that breaks the pattern → change to
|
|
||||||
`Theme.of(context).colorScheme.error`.
|
|
||||||
- **Rule 11 (mathematically related measurements)** — the app's spacing is
|
|
||||||
overwhelmingly on a 4px scale (4/8/12/16/20/24/96 all appear repeatedly),
|
|
||||||
but a few values break it: `SizedBox(height: 6)` at
|
|
||||||
`lib/ui/notes_list_screen.dart:411,574,646`; `SizedBox(height: 10)` at
|
|
||||||
`lib/ui/markdown_view.dart:29`; `EdgeInsets.only(top: 8, bottom: 2)` /
|
|
||||||
`EdgeInsets.only(bottom: 4)` / `EdgeInsets.only(left: 4, top: 2)` at
|
|
||||||
`lib/ui/markdown_view.dart:35,49,78` (the `2`s). Round these to the nearest
|
|
||||||
4px step (6→8, 10→8 or 12, 2→4) for consistency.
|
|
||||||
- **Rule 21 (line length ~70 chars)** — `lib/ui/markdown_view.dart` (the
|
|
||||||
rendered-note view) and the raw-mode `TextField` in
|
|
||||||
`lib/ui/note_editor.dart:520-535` have no max-width constraint; both sit
|
|
||||||
directly in a `SingleChildScrollView`/`Expanded` that fills the available
|
|
||||||
width. Per this repo's own `CLAUDE.md`, the desktop build is a Chrome
|
|
||||||
`--app` window (potentially 4K), so body text lines run the full window
|
|
||||||
width, far past the 60-80 char readable range. Constrain text columns with
|
|
||||||
a `ConstrainedBox(maxWidth: ~640)` (or similar) centered in the available
|
|
||||||
space on wide viewports; mobile widths are already narrow enough to be fine.
|
|
||||||
|
|
||||||
### Pass (defers to Material 3 defaults from `main.dart:36-39`, or otherwise verified)
|
|
||||||
|
|
||||||
- **Rule 1** (near-black/near-white) — M3's generated tonal palette, not pure black/white.
|
|
||||||
- **Rule 2** (saturate neutrals) — M3's seed-derived neutrals carry the seed hue.
|
|
||||||
- **Rule 3** (high contrast for important elements) — `FilledButton`/`IconButton` get M3's on-primary contrast automatically.
|
|
||||||
- **Rule 6** (letter-spacing/line-height by size) — M3 `TextTheme` scale.
|
|
||||||
- **Rule 7** (container border contrast) — `OutlineInputBorder()` used throughout (e.g. `lib/ui/settings_screen.dart:244,252,268,278`) resolves via theme, no custom borders.
|
|
||||||
- **Rule 8** (align with something else) — screen-level body padding is a consistent `EdgeInsets.all(16)` across `lib/ui/capture_screen.dart:451`, `lib/ui/note_detail_screen.dart:67`, `lib/ui/settings_screen.dart:221`.
|
|
||||||
- **Rule 9** (distinct brightness per palette color) — M3 tonal palette assigns each role a distinct tone.
|
|
||||||
- **Rule 10** (warm OR cool, not both) — single seed color (`Colors.deepPurple`) drives the whole palette.
|
|
||||||
- **Rule 14** (space between high-contrast points) — standard Material component spacing, no bounding-box vs. visual-edge mismatches found.
|
|
||||||
- **Rule 17** (simple on complex) — all surfaces are plain `Scaffold`/`ListView` backgrounds, no background imagery/texture.
|
|
||||||
- **Rule 19** (outer padding ≥ inner padding) — e.g. `lib/ui/settings_screen.dart:318-331` (Export/Import button row: 12px gap between buttons) sits inside the screen's 16px outer padding; same pattern in `capture_screen.dart`'s priority/status row (12px gap inside 16px body padding).
|
|
||||||
- **Rule 20** (body text ≥16px) — `bodyLarge` (16px, M3 default) is used for all primary editable/read text (`lib/ui/note_editor.dart:528`, `lib/ui/markdown_view.dart:82-95`); `bodySmall` (12px) is reserved for secondary captions/timestamps only (`lib/ui/capture_screen.dart:511`, `lib/ui/settings_screen.dart:231`), which is the sanctioned M3 caption use, not body text.
|
|
||||||
- **Rule 22** (button padding horizontal = 2x vertical) — no custom `ButtonStyle` padding overrides found; `FilledButton`/`OutlinedButton` use M3 defaults, which follow this ratio.
|
|
||||||
- **Rule 23** (two typefaces max) — single default Material/Roboto family; `pubspec.yaml` declares no custom fonts, no `google_fonts` dependency.
|
|
||||||
- **Rule 25** (avoid adjacent hard divides) — the one `Divider` in the list (`lib/ui/notes_list_screen.dart:232`, `height: 1`) separates list rows only, no stacked borders; the settings-screen `Divider()` (`lib/ui/settings_screen.dart:308`) has 8-24px spacing on both sides, not adjacent to another edge.
|
|
||||||
- **Rule 27** (don't mix depth techniques) — no custom shadow/elevation overrides anywhere in `lib/`; consistent flat M3 default depth throughout.
|
|
||||||
- **Rule 28** (icon contrast vs. text) — icons use the default M3 `IconTheme` (tied to `onSurfaceVariant`-class roles), no hardcoded full-contrast icon colors placed next to text were found.
|
|
||||||
|
|
||||||
### Not applicable
|
|
||||||
|
|
||||||
- **Rule 5** (optical alignment) — no custom-drawn shapes/icons with off-center mass; all icons are stock `Icons.*` glyphs, whose optical centering Material already handles.
|
|
||||||
- **Rule 12** (order by visual weight) — standard `AppBar` + list/form layouts, not a composition with deliberately varied visual weights to order.
|
|
||||||
- **Rule 13** (12-column grid) — single-column mobile/narrow-desktop layouts throughout; no multi-column grid exists to check.
|
|
||||||
- **Rule 15** (closer elements lighter, light+dark) — no custom z-stacked/elevated surfaces with tuned lightness, and no `darkTheme` exists to check the dark-mode half of this rule.
|
|
||||||
- **Rule 16** (shadow blur ≈ 2x distance) — zero custom `BoxShadow` usage in the codebase (confirmed by grep); nothing to check.
|
|
||||||
- **Rule 18** (container brightness limits, light/dark) — no custom nested-container brightness steps defined; M3 default surface tones apply, and there is no dark theme to check the 12%-dark-interface half.
|
|
||||||
- **Rule 24** (nest corners properly) — no custom corner radii anywhere; all components use M3 default shapes.
|
|
||||||
- **Rule 26** (no shadows in dark interfaces) — no dark theme exists, and no shadows exist in light mode either, so this rule has nothing to trigger on.
|
|
||||||
|
|
||||||
### Notes
|
|
||||||
|
|
||||||
- No dedicated theme file exists (`ThemeData` is inline in `lib/main.dart`,
|
|
||||||
32 `.dart` files total) — this is fine at the current size but worth
|
|
||||||
extracting to `lib/ui/theme.dart` if the theme grows beyond the current
|
|
||||||
3-line `ThemeData(...)`.
|
|
||||||
- No `darkTheme` is provided. The 28 rules don't mandate one, so its absence
|
|
||||||
is not a violation — but if a dark theme is added later, re-check rules 15,
|
|
||||||
18, and 26 (shadow/lightness/brightness-limit rules only bite once a dark
|
|
||||||
surface exists).
|
|
||||||
- The single hardcoded-color violation (`Colors.red`) is also the app's only
|
|
||||||
spot where a raw `Colors.*` constant appears outside `main.dart`'s seed —
|
|
||||||
fixing it removes the last non-theme-derived color reference in the app.
|
|
||||||
|
|
||||||
REMOVE ME AFTER FINISH
|
|
||||||
@ -4,7 +4,7 @@
|
|||||||
lose all network access. -->
|
lose all network access. -->
|
||||||
<uses-permission android:name="android.permission.INTERNET"/>
|
<uses-permission android:name="android.permission.INTERNET"/>
|
||||||
<application
|
<application
|
||||||
android:label="todo"
|
android:label="Todo"
|
||||||
android:name="${applicationName}"
|
android:name="${applicationName}"
|
||||||
android:icon="@mipmap/ic_launcher"
|
android:icon="@mipmap/ic_launcher"
|
||||||
android:allowBackup="true"
|
android:allowBackup="true"
|
||||||
|
|||||||
|
Before Width: | Height: | Size: 3.1 KiB After Width: | Height: | Size: 3.2 KiB |
|
Before Width: | Height: | Size: 3.0 KiB After Width: | Height: | Size: 3.1 KiB |
|
Before Width: | Height: | Size: 2.0 KiB After Width: | Height: | Size: 2.1 KiB |
|
Before Width: | Height: | Size: 2.0 KiB After Width: | Height: | Size: 2.0 KiB |
|
Before Width: | Height: | Size: 4.0 KiB After Width: | Height: | Size: 4.2 KiB |
|
Before Width: | Height: | Size: 3.7 KiB After Width: | Height: | Size: 3.9 KiB |
|
Before Width: | Height: | Size: 5.8 KiB After Width: | Height: | Size: 6.1 KiB |
|
Before Width: | Height: | Size: 5.3 KiB After Width: | Height: | Size: 5.5 KiB |
|
Before Width: | Height: | Size: 7.9 KiB After Width: | Height: | Size: 8.2 KiB |
|
Before Width: | Height: | Size: 7.1 KiB After Width: | Height: | Size: 7.3 KiB |
|
Before Width: | Height: | Size: 1.3 KiB After Width: | Height: | Size: 1.4 KiB |
|
Before Width: | Height: | Size: 778 B After Width: | Height: | Size: 815 B |
|
Before Width: | Height: | Size: 1.5 KiB After Width: | Height: | Size: 1.5 KiB |
|
Before Width: | Height: | Size: 2.3 KiB After Width: | Height: | Size: 2.4 KiB |
|
Before Width: | Height: | Size: 2.7 KiB After Width: | Height: | Size: 2.7 KiB |
@ -1,4 +1,7 @@
|
|||||||
org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError
|
org.gradle.jvmargs=-Xmx2G -XX:MaxMetaspaceSize=1G -XX:ReservedCodeCacheSize=256m -XX:+UseSerialGC -XX:TieredStopAtLevel=1
|
||||||
|
org.gradle.caching=true
|
||||||
|
org.gradle.parallel=true
|
||||||
|
kotlin.compiler.execution.strategy=in-process
|
||||||
android.useAndroidX=true
|
android.useAndroidX=true
|
||||||
# This newDsl flag was added by the Flutter template
|
# This newDsl flag was added by the Flutter template
|
||||||
android.newDsl=false
|
android.newDsl=false
|
||||||
|
|||||||
@ -2,4 +2,4 @@ distributionBase=GRADLE_USER_HOME
|
|||||||
distributionPath=wrapper/dists
|
distributionPath=wrapper/dists
|
||||||
zipStoreBase=GRADLE_USER_HOME
|
zipStoreBase=GRADLE_USER_HOME
|
||||||
zipStorePath=wrapper/dists
|
zipStorePath=wrapper/dists
|
||||||
distributionUrl=https\://services.gradle.org/distributions/gradle-9.8.1-all.zip
|
distributionUrl=https\://services.gradle.org/distributions/gradle-9.9.1-all.zip
|
||||||
|
|||||||
|
Before Width: | Height: | Size: 16 KiB After Width: | Height: | Size: 16 KiB |
@ -1,6 +1,6 @@
|
|||||||
<svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 1024 1024">
|
<svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 1024 1024">
|
||||||
<rect width="1024" height="1024" fill="#211D1B"/>
|
<rect width="1024" height="1024" fill="#211D1B"/>
|
||||||
<g fill="none" stroke="#B8862E" stroke-width="72" stroke-linecap="round" stroke-linejoin="round" transform="translate(0,8)">
|
<g fill="none" stroke="#B8862E" stroke-width="66.2544" stroke-linecap="round" stroke-linejoin="round" transform="translate(-44.4008,-35.7071) scale(1.08672)">
|
||||||
<path d="M 272 372 L 346 446 L 478 314"/>
|
<path d="M 272 372 L 346 446 L 478 314"/>
|
||||||
<path d="M 594 400 L 752 400"/>
|
<path d="M 594 400 L 752 400"/>
|
||||||
<path d="M 272 620 L 346 694 L 478 562"/>
|
<path d="M 272 620 L 346 694 L 478 562"/>
|
||||||
|
|||||||
|
Before Width: | Height: | Size: 449 B After Width: | Height: | Size: 483 B |
|
Before Width: | Height: | Size: 16 KiB After Width: | Height: | Size: 16 KiB |
@ -1,5 +1,5 @@
|
|||||||
<svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 1024 1024">
|
<svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 1024 1024">
|
||||||
<g fill="none" stroke="#B8862E" stroke-width="72" stroke-linecap="round" stroke-linejoin="round" transform="translate(0,8)">
|
<g fill="none" stroke="#B8862E" stroke-width="66.2544" stroke-linecap="round" stroke-linejoin="round" transform="translate(-44.4008,-35.7071) scale(1.08672)">
|
||||||
<path d="M 272 372 L 346 446 L 478 314"/>
|
<path d="M 272 372 L 346 446 L 478 314"/>
|
||||||
<path d="M 594 400 L 752 400"/>
|
<path d="M 594 400 L 752 400"/>
|
||||||
<path d="M 272 620 L 346 694 L 478 562"/>
|
<path d="M 272 620 L 346 694 L 478 562"/>
|
||||||
|
|||||||
|
Before Width: | Height: | Size: 397 B After Width: | Height: | Size: 431 B |
|
Before Width: | Height: | Size: 14 KiB After Width: | Height: | Size: 14 KiB |
@ -1,5 +1,5 @@
|
|||||||
<svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 1024 1024">
|
<svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 1024 1024">
|
||||||
<g fill="none" stroke="#FFFFFF" stroke-width="72" stroke-linecap="round" stroke-linejoin="round" transform="translate(0,8)">
|
<g fill="none" stroke="#FFFFFF" stroke-width="66.2544" stroke-linecap="round" stroke-linejoin="round" transform="translate(-44.4008,-35.7071) scale(1.08672)">
|
||||||
<path d="M 272 372 L 346 446 L 478 314"/>
|
<path d="M 272 372 L 346 446 L 478 314"/>
|
||||||
<path d="M 594 400 L 752 400"/>
|
<path d="M 594 400 L 752 400"/>
|
||||||
<path d="M 272 620 L 346 694 L 478 562"/>
|
<path d="M 272 620 L 346 694 L 478 562"/>
|
||||||
|
|||||||
|
Before Width: | Height: | Size: 397 B After Width: | Height: | Size: 431 B |
16
bin/merge_repo_notes.dart
Normal file
@ -0,0 +1,16 @@
|
|||||||
|
// One-time: one open note per repo, holding all of that repo's todos.
|
||||||
|
//
|
||||||
|
// dart run bin/merge_repo_notes.dart # dry run, prints the map
|
||||||
|
// dart run bin/merge_repo_notes.dart --apply # does it and pushes
|
||||||
|
import 'dart:io';
|
||||||
|
|
||||||
|
import 'package:todo/cli/merge_repo_notes.dart';
|
||||||
|
|
||||||
|
Future<void> main(List<String> argv) async {
|
||||||
|
exitCode = await runMergeRepoNotes(
|
||||||
|
argv,
|
||||||
|
env: Platform.environment,
|
||||||
|
out: stdout,
|
||||||
|
err: stderr,
|
||||||
|
);
|
||||||
|
}
|
||||||
@ -1,8 +1,8 @@
|
|||||||
// Headless note CLI: add, list, get or delete a todo note from the PC.
|
// Headless note CLI: add, list, search, get, close or delete notes from the PC.
|
||||||
//
|
//
|
||||||
// dart run bin/todo_note.dart --text "Title\n\nbody" --priority high
|
// dart run bin/todo_note.dart --text "Title" --repo kuhyx/todo --by claude
|
||||||
// echo "Title" | dart run bin/todo_note.dart
|
// dart run bin/todo_note.dart --list --repo kuhyx/todo
|
||||||
// dart run bin/todo_note.dart --get <id>
|
// dart run bin/todo_note.dart --close <id> --evidence "<sha> exit 0"
|
||||||
//
|
//
|
||||||
// See `kUsage` in lib/cli/cli_args.dart for every flag. All behaviour lives
|
// See `kUsage` in lib/cli/cli_args.dart for every flag. All behaviour lives
|
||||||
// in lib/cli/cli_runner.dart, where the tests reach it.
|
// in lib/cli/cli_runner.dart, where the tests reach it.
|
||||||
|
|||||||
4
dependency-freshness.allowlist.yaml
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
# todo's own additions to the fleet-wide allowlist
|
||||||
|
# (~/src/utils/dependency-freshness.allowlist.yaml).
|
||||||
|
|
||||||
|
exceptions: []
|
||||||
|
Before Width: | Height: | Size: 1.3 KiB After Width: | Height: | Size: 1.9 KiB |
|
Before Width: | Height: | Size: 308 B After Width: | Height: | Size: 309 B |
|
Before Width: | Height: | Size: 470 B After Width: | Height: | Size: 439 B |
|
Before Width: | Height: | Size: 3.4 KiB After Width: | Height: | Size: 3.7 KiB |
|
Before Width: | Height: | Size: 574 B After Width: | Height: | Size: 579 B |
|
Before Width: | Height: | Size: 788 B After Width: | Height: | Size: 778 B |
|
Before Width: | Height: | Size: 6.9 KiB After Width: | Height: | Size: 7.4 KiB |
|
Before Width: | Height: | Size: 1023 B After Width: | Height: | Size: 1.1 KiB |
@ -83,7 +83,7 @@ install_desktop_entry() {
|
|||||||
cat > "$DESKTOP_DIR/$ICON_NAME.desktop" <<EOF
|
cat > "$DESKTOP_DIR/$ICON_NAME.desktop" <<EOF
|
||||||
[Desktop Entry]
|
[Desktop Entry]
|
||||||
Type=Application
|
Type=Application
|
||||||
Name=todo
|
Name=Todo
|
||||||
Comment=Offline-first, CRDT-synced notes
|
Comment=Offline-first, CRDT-synced notes
|
||||||
Exec=$LAUNCH_CMD
|
Exec=$LAUNCH_CMD
|
||||||
Icon=$ICON_NAME
|
Icon=$ICON_NAME
|
||||||
|
|||||||
@ -29,8 +29,10 @@ echo "==> Compiling the desktop wrapper..."
|
|||||||
# `dart build cli`, not `dart compile exe`: the package pulls in dependencies
|
# `dart build cli`, not `dart compile exe`: the package pulls in dependencies
|
||||||
# with native build hooks (sqlite3, objective_c), which `dart compile` refuses
|
# with native build hooks (sqlite3, objective_c), which `dart compile` refuses
|
||||||
# to handle even though the wrapper itself uses none of them.
|
# to handle even though the wrapper itself uses none of them.
|
||||||
|
# --target is required since bin/ also holds the todo_note CLI: with two
|
||||||
|
# entry points `dart build cli` refuses to guess and the install aborts.
|
||||||
rm -rf "$SCRIPT_DIR/build/cli"
|
rm -rf "$SCRIPT_DIR/build/cli"
|
||||||
dart build cli -o "$SCRIPT_DIR/build/cli"
|
dart build cli -t "$SCRIPT_DIR/bin/todo_desktop.dart" -o "$SCRIPT_DIR/build/cli"
|
||||||
|
|
||||||
echo "==> Generating PKGBUILD..."
|
echo "==> Generating PKGBUILD..."
|
||||||
# pkgname is 'todo-flutter', NOT 'todo': the AUR already ships an unrelated
|
# pkgname is 'todo-flutter', NOT 'todo': the AUR already ships an unrelated
|
||||||
|
|||||||
@ -4,37 +4,11 @@
|
|||||||
/// exact-pinned dependency under the freshness gate.
|
/// exact-pinned dependency under the freshness gate.
|
||||||
library;
|
library;
|
||||||
|
|
||||||
|
import 'package:todo/cli/cli_mode.dart';
|
||||||
import 'package:todo/data/note.dart';
|
import 'package:todo/data/note.dart';
|
||||||
|
|
||||||
/// What the CLI was asked to do.
|
export 'package:todo/cli/cli_mode.dart';
|
||||||
enum CliMode {
|
export 'package:todo/cli/cli_usage.dart';
|
||||||
/// Create a note and push it.
|
|
||||||
add,
|
|
||||||
|
|
||||||
/// Print every live note, one per line.
|
|
||||||
list,
|
|
||||||
|
|
||||||
/// Print one note in full.
|
|
||||||
get,
|
|
||||||
|
|
||||||
/// Tombstone one note and push the deletion.
|
|
||||||
delete,
|
|
||||||
|
|
||||||
/// Print usage.
|
|
||||||
help,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Thrown for a malformed command line; maps to exit code 2.
|
|
||||||
class UsageError implements Exception {
|
|
||||||
/// Creates a [UsageError] carrying [message].
|
|
||||||
UsageError(this.message);
|
|
||||||
|
|
||||||
/// What was wrong with the arguments.
|
|
||||||
final String message;
|
|
||||||
|
|
||||||
@override
|
|
||||||
String toString() => message;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The parsed command line.
|
/// The parsed command line.
|
||||||
class CliArgs {
|
class CliArgs {
|
||||||
@ -44,17 +18,23 @@ class CliArgs {
|
|||||||
this.text,
|
this.text,
|
||||||
this.id,
|
this.id,
|
||||||
this.priority = Priority.medium,
|
this.priority = Priority.medium,
|
||||||
this.status = Status.todo,
|
this.status,
|
||||||
this.dataDir,
|
this.dataDir,
|
||||||
|
this.newNote = false,
|
||||||
|
this.dryRun = false,
|
||||||
|
this.opts = (
|
||||||
|
repo: null,
|
||||||
|
query: null,
|
||||||
|
doneCheck: null,
|
||||||
|
by: null,
|
||||||
|
evidence: null,
|
||||||
|
),
|
||||||
});
|
});
|
||||||
|
|
||||||
/// Parses [argv]. Throws [UsageError] on anything it does not understand.
|
/// Parses [argv]. Throws [UsageError] on anything it does not understand.
|
||||||
factory CliArgs.parse(List<String> argv) {
|
factory CliArgs.parse(List<String> argv) {
|
||||||
String? text;
|
final opts = <String, String>{};
|
||||||
String? id;
|
String? id;
|
||||||
String? dataDir;
|
|
||||||
var priority = Priority.medium;
|
|
||||||
var status = Status.todo;
|
|
||||||
final modes = <CliMode>{};
|
final modes = <CliMode>{};
|
||||||
for (var i = 0; i < argv.length; i++) {
|
for (var i = 0; i < argv.length; i++) {
|
||||||
final arg = argv[i];
|
final arg = argv[i];
|
||||||
@ -64,67 +44,167 @@ class CliArgs {
|
|||||||
}
|
}
|
||||||
|
|
||||||
switch (arg) {
|
switch (arg) {
|
||||||
|
case '--new-note':
|
||||||
|
opts[arg] = '';
|
||||||
case '-h' || '--help':
|
case '-h' || '--help':
|
||||||
modes.add(CliMode.help);
|
modes.add(CliMode.help);
|
||||||
case '--text':
|
case '--text' || '--priority' || '--status' || '--data-dir':
|
||||||
text = value();
|
case '--repo' || '--done-check' || '--by' || '--evidence':
|
||||||
case '--priority':
|
opts[arg] = value();
|
||||||
priority = _byName(Priority.values, value(), arg);
|
|
||||||
case '--status':
|
|
||||||
status = _byName(Status.values, value(), arg, _statusName);
|
|
||||||
case '--data-dir':
|
|
||||||
dataDir = value();
|
|
||||||
case '--list':
|
case '--list':
|
||||||
modes.add(CliMode.list);
|
modes.add(CliMode.list);
|
||||||
case '--get':
|
case '--backfill-created-by':
|
||||||
modes.add(CliMode.get);
|
modes.add(CliMode.backfill);
|
||||||
|
case '--dry-run':
|
||||||
|
opts[arg] = 'true';
|
||||||
|
case '--search':
|
||||||
|
modes.add(CliMode.search);
|
||||||
|
opts[arg] = value();
|
||||||
|
case '--get' || '--delete' || '--close':
|
||||||
|
modes.add(CliMode.values.byName(arg.substring(2)));
|
||||||
id = value();
|
id = value();
|
||||||
case '--delete':
|
case '--set-text':
|
||||||
modes.add(CliMode.delete);
|
modes.add(CliMode.setText);
|
||||||
id = value();
|
id = value();
|
||||||
|
case '--set-status':
|
||||||
|
modes.add(CliMode.setStatus);
|
||||||
|
id = value();
|
||||||
|
opts[arg] = value();
|
||||||
default:
|
default:
|
||||||
throw UsageError('unknown argument: $arg');
|
throw UsageError('unknown argument: $arg');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (modes.contains(CliMode.help)) return const CliArgs(mode: CliMode.help);
|
if (modes.contains(CliMode.help)) return const CliArgs(mode: CliMode.help);
|
||||||
if (modes.length > 1) {
|
if (modes.length > 1) {
|
||||||
throw UsageError('--list, --get and --delete are mutually exclusive');
|
throw UsageError(
|
||||||
|
'--list, --search, --get, --delete, --set-status, --set-text, '
|
||||||
|
'--close and '
|
||||||
|
'--backfill-created-by are mutually exclusive',
|
||||||
|
);
|
||||||
}
|
}
|
||||||
final mode = modes.isEmpty ? CliMode.add : modes.single;
|
final mode = modes.isEmpty ? CliMode.add : modes.single;
|
||||||
if (mode != CliMode.add && text != null) {
|
_checkScopes(opts.keys, mode);
|
||||||
throw UsageError('--text only applies when adding a note');
|
final rawStatus = opts['--set-status'] ?? opts['--status'];
|
||||||
}
|
|
||||||
return CliArgs(
|
return CliArgs(
|
||||||
mode: mode,
|
mode: mode,
|
||||||
text: text,
|
text: opts['--text'],
|
||||||
id: id,
|
id: id,
|
||||||
priority: priority,
|
priority: opts['--priority'] == null
|
||||||
status: status,
|
? Priority.medium
|
||||||
dataDir: dataDir,
|
: _byName(Priority.values, opts['--priority']!, '--priority'),
|
||||||
|
status: rawStatus == null
|
||||||
|
? null
|
||||||
|
: _byName(Status.values, rawStatus, '--status', _statusName),
|
||||||
|
dataDir: opts['--data-dir'],
|
||||||
|
newNote:
|
||||||
|
opts.containsKey('--new-note') &&
|
||||||
|
(opts['--repo'] != null ||
|
||||||
|
(throw UsageError('--new-note needs --repo'))),
|
||||||
|
dryRun: opts.containsKey('--dry-run'),
|
||||||
|
opts: (
|
||||||
|
repo: _repo(opts['--repo']),
|
||||||
|
query: _nonBlank(opts['--search'], '--search'),
|
||||||
|
doneCheck: _nonBlank(opts['--done-check'], '--done-check'),
|
||||||
|
by: opts['--by'] == null ? null : _by(opts['--by']!),
|
||||||
|
evidence: _evidence(opts['--evidence'], mode),
|
||||||
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The selected mode.
|
/// The selected mode.
|
||||||
final CliMode mode;
|
final CliMode mode;
|
||||||
|
|
||||||
/// Note text from `--text`; null means "read stdin" in [CliMode.add].
|
/// Note text from `--text`; null means "read stdin" in [CliMode.add] and
|
||||||
|
/// [CliMode.setText].
|
||||||
final String? text;
|
final String? text;
|
||||||
|
|
||||||
/// Note id for [CliMode.get] / [CliMode.delete].
|
/// Full id or 8+ character prefix of the note an id mode acts on.
|
||||||
final String? id;
|
final String? id;
|
||||||
|
|
||||||
/// Priority of a new note.
|
/// Priority of a new note.
|
||||||
final Priority priority;
|
final Priority priority;
|
||||||
|
|
||||||
/// Status of a new note.
|
/// New note's status, [CliMode.setStatus]'s target, or a list filter.
|
||||||
final Status status;
|
final Status? status;
|
||||||
|
|
||||||
/// Overrides the default data dir (a second, independent node).
|
/// Overrides the default data dir (a second, independent node).
|
||||||
final String? dataDir;
|
final String? dataDir;
|
||||||
|
|
||||||
|
/// `--new-note`: the `--repo` task gets its own note.
|
||||||
|
final bool newNote;
|
||||||
|
|
||||||
|
/// Whether `--dry-run` was given: report what would change, change nothing.
|
||||||
|
final bool dryRun;
|
||||||
|
|
||||||
|
/// `--repo`, `--search`, `--done-check`, `--by` and `--evidence` values.
|
||||||
|
final ({
|
||||||
|
String? repo,
|
||||||
|
String? query,
|
||||||
|
String? doneCheck,
|
||||||
|
String? by,
|
||||||
|
String? evidence,
|
||||||
|
})
|
||||||
|
opts;
|
||||||
|
|
||||||
/// The command-line spelling of [status] (`in_progress`, not `inProgress`).
|
/// The command-line spelling of [status] (`in_progress`, not `inProgress`).
|
||||||
static String statusName(Status status) => _statusName(status);
|
static String statusName(Status status) => _statusName(status);
|
||||||
|
|
||||||
|
static const _adding = 'when adding a note';
|
||||||
|
static const Map<String, (String, Set<CliMode>)> _scopes = {
|
||||||
|
'--text': ('$_adding or to --set-text', {CliMode.add, CliMode.setText}),
|
||||||
|
'--done-check': (_adding, {CliMode.add}),
|
||||||
|
'--by': (_adding, {CliMode.add}),
|
||||||
|
'--repo': (
|
||||||
|
'$_adding, to --list or to --search',
|
||||||
|
{CliMode.add, CliMode.list, CliMode.search},
|
||||||
|
),
|
||||||
|
'--evidence': ('to --close', {CliMode.close}),
|
||||||
|
'--new-note': (_adding, {CliMode.add}),
|
||||||
|
'--dry-run': ('to --backfill-created-by', {CliMode.backfill}),
|
||||||
|
};
|
||||||
|
|
||||||
|
static void _checkScopes(Iterable<String> flags, CliMode mode) {
|
||||||
|
for (final flag in flags) {
|
||||||
|
final scope = _scopes[flag];
|
||||||
|
if (scope != null && !scope.$2.contains(mode)) {
|
||||||
|
throw UsageError('$flag only applies ${scope.$1}');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static final _repoShape = RegExp(r'^[\w.-]+/[\w.-]+$');
|
||||||
|
|
||||||
|
static String? _repo(String? raw) {
|
||||||
|
if (raw == null || _repoShape.hasMatch(raw)) return raw;
|
||||||
|
throw UsageError(
|
||||||
|
'--repo must look like owner/name (e.g. kuhyx/todo), got "$raw"',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
static String _by(String raw) {
|
||||||
|
if (kNoteAuthors.contains(raw)) return raw;
|
||||||
|
throw UsageError(
|
||||||
|
'--by must be one of ${kNoteAuthors.join('|')}, got "$raw"',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
static String? _evidence(String? raw, CliMode mode) {
|
||||||
|
if (mode == CliMode.close && (raw == null || raw.trim().isEmpty)) {
|
||||||
|
throw UsageError(
|
||||||
|
'--close needs --evidence <commit sha + done check exit code>: '
|
||||||
|
'a task is only closed with proof',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return raw;
|
||||||
|
}
|
||||||
|
|
||||||
|
static String? _nonBlank(String? raw, String flag) {
|
||||||
|
if (raw != null && raw.trim().isEmpty) {
|
||||||
|
throw UsageError('$flag must not be empty');
|
||||||
|
}
|
||||||
|
return raw;
|
||||||
|
}
|
||||||
|
|
||||||
static String _statusName(Enum value) =>
|
static String _statusName(Enum value) =>
|
||||||
value == Status.inProgress ? 'in_progress' : value.name;
|
value == Status.inProgress ? 'in_progress' : value.name;
|
||||||
|
|
||||||
@ -144,23 +224,3 @@ class CliArgs {
|
|||||||
|
|
||||||
static String _plainName(Enum value) => value.name;
|
static String _plainName(Enum value) => value.name;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Usage text printed by `--help` and after a [UsageError].
|
|
||||||
const kUsage = r'''
|
|
||||||
Usage: dart run bin/todo_note.dart [options]
|
|
||||||
|
|
||||||
Adds a note to the todo app headlessly: pulls from Firebase RTDB, writes an
|
|
||||||
ordinary CRDT change as this install's own node, pushes, and prints the id.
|
|
||||||
|
|
||||||
--text <markdown> note text (first line = title); default: read stdin
|
|
||||||
--priority <p> low|medium|high (default medium)
|
|
||||||
--status <s> todo|in_progress|done|abandoned (default todo)
|
|
||||||
--list pull, then print live notes: id, priority, status, title
|
|
||||||
--get <id> pull, then print one note in full (exit 1 if absent)
|
|
||||||
--delete <id> pull, tombstone the note, push
|
|
||||||
--data-dir <dir> local log + node id (default
|
|
||||||
$XDG_DATA_HOME/todo-cli or ~/.local/share/todo-cli)
|
|
||||||
-h, --help this text
|
|
||||||
|
|
||||||
--list and --get never push, so a throwaway --data-dir leaves nothing behind.
|
|
||||||
Exit codes: 0 ok, 1 sync/auth failure or note not found, 2 bad arguments.''';
|
|
||||||
|
|||||||
206
lib/cli/cli_commands.dart
Normal file
@ -0,0 +1,206 @@
|
|||||||
|
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:todo/data/repo_note.dart';
|
||||||
|
import 'package:todo/data/repo_note_split.dart';
|
||||||
|
import 'package:todo/sync/sync_service.dart';
|
||||||
|
import 'package:uuid/uuid.dart';
|
||||||
|
|
||||||
|
/// One CLI command per method over an open [CliSession]; each returns the
|
||||||
|
/// exit code. Id arguments are resolved by [findNote].
|
||||||
|
class CliCommands {
|
||||||
|
/// Writes results to the first sink, errors and warnings to the second.
|
||||||
|
CliCommands(this.session, this._out, this._err);
|
||||||
|
|
||||||
|
/// The open session the commands act on.
|
||||||
|
final CliSession session;
|
||||||
|
|
||||||
|
final StringSink _out;
|
||||||
|
final StringSink _err;
|
||||||
|
|
||||||
|
/// Creates a note and pushes it. A `--repo` add joins the repo's open note.
|
||||||
|
Future<int> add(CliArgs args, String text) async {
|
||||||
|
final repo = args.opts.repo;
|
||||||
|
final status = args.status ?? Status.todo;
|
||||||
|
if (repo != null && kOpenStatuses.contains(status)) {
|
||||||
|
return await _addRepoTask(args, repo, text);
|
||||||
|
}
|
||||||
|
final now = DateTime.now();
|
||||||
|
final note = Note(
|
||||||
|
id: const Uuid().v4(),
|
||||||
|
text: text,
|
||||||
|
priority: args.priority,
|
||||||
|
status: status,
|
||||||
|
createdAt: now,
|
||||||
|
updatedAt: now,
|
||||||
|
repo: repo,
|
||||||
|
doneCheck: args.opts.doneCheck,
|
||||||
|
by: args.opts.by,
|
||||||
|
createdBy: 'claude',
|
||||||
|
);
|
||||||
|
await session.repository.upsert(note);
|
||||||
|
if (!await _push('note')) return 1;
|
||||||
|
_out.writeln(note.id);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<int> _addRepoTask(CliArgs args, String repo, String text) async {
|
||||||
|
_report(await session.sync(push: true));
|
||||||
|
final (:title, :body) = splitNote(text);
|
||||||
|
if (args.newNote) return await _addSeparate(args, repo, title, body);
|
||||||
|
final added = await addRepoTask(
|
||||||
|
session.repository,
|
||||||
|
repo: repo,
|
||||||
|
title: title,
|
||||||
|
body: body,
|
||||||
|
doneCheck: args.opts.doneCheck,
|
||||||
|
priority: args.priority,
|
||||||
|
by: args.opts.by,
|
||||||
|
createdBy: 'claude',
|
||||||
|
);
|
||||||
|
await _save(added.note);
|
||||||
|
if (!await _push('note')) return 1;
|
||||||
|
if (added.appended) _err.writeln('appended to the open note for $repo');
|
||||||
|
_out.writeln(added.note.id);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<int> _addSeparate(
|
||||||
|
CliArgs args,
|
||||||
|
String repo,
|
||||||
|
String title,
|
||||||
|
String body,
|
||||||
|
) async {
|
||||||
|
final added = await addSeparateTask(
|
||||||
|
session.repository,
|
||||||
|
repo: repo,
|
||||||
|
title: title,
|
||||||
|
body: body,
|
||||||
|
doneCheck: args.opts.doneCheck,
|
||||||
|
priority: args.priority,
|
||||||
|
by: args.opts.by,
|
||||||
|
createdBy: 'claude',
|
||||||
|
);
|
||||||
|
await _save(added.note);
|
||||||
|
if (!await _push('note')) return 1;
|
||||||
|
if (added.kind == SplitKind.merged) {
|
||||||
|
_err.writeln(
|
||||||
|
'merged into the separate note with that title; '
|
||||||
|
'click Start on the board by hand',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
_out.writeln(added.note.id);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Prints [listLine] for each note matching the filters in [args].
|
||||||
|
Future<int> list(CliArgs args) async {
|
||||||
|
_report(await session.sync(push: false));
|
||||||
|
final notes = await session.repository.listNotes(
|
||||||
|
filter: NoteFilter(
|
||||||
|
query: args.opts.query ?? '',
|
||||||
|
statuses: {?args.status},
|
||||||
|
repo: args.opts.repo,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
notes.map(listLine).forEach(_out.writeln);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Prints one note in full.
|
||||||
|
Future<int> get(String ref) async {
|
||||||
|
_report(await session.sync(push: false));
|
||||||
|
_out.writeln(
|
||||||
|
noteDetail(findNote(await session.repository.listNotes(), ref)),
|
||||||
|
);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Tombstones a note and pushes the deletion.
|
||||||
|
Future<int> delete(String ref) async {
|
||||||
|
final note = await _pullAndFind(ref);
|
||||||
|
await session.repository.delete(note.id);
|
||||||
|
if (!await _push('deletion')) return 1;
|
||||||
|
_out.writeln('deleted ${note.id}');
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Changes a note's status and pushes it.
|
||||||
|
Future<int> setStatus(String ref, Status status) async {
|
||||||
|
final note = await _pullAndFind(ref);
|
||||||
|
await _save(note.copyWith(status: status));
|
||||||
|
if (!await _push('status change')) return 1;
|
||||||
|
_out.writeln('${note.id}\t${CliArgs.statusName(status)}');
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Replaces a note's whole text (title is its first line) and pushes it.
|
||||||
|
Future<int> setText(String ref, String text) async {
|
||||||
|
final note = await _pullAndFind(ref);
|
||||||
|
await _save(note.copyWith(text: text));
|
||||||
|
if (!await _push('text change')) return 1;
|
||||||
|
_out.writeln('${note.id}\ttext');
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Marks a note done with [evidence], keeping it, and pushes it.
|
||||||
|
Future<int> close(String ref, String evidence) async {
|
||||||
|
final note = await _pullAndFind(ref);
|
||||||
|
await _save(note.copyWith(status: Status.done, evidence: evidence));
|
||||||
|
if (!await _push('close')) return 1;
|
||||||
|
_out.writeln('closed ${note.id}');
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sets `created_by` where unset (see [NoteRepository.backfillCreatedBy]).
|
||||||
|
/// Prints one `<id>\t<value>\t<title>` line per note, then the totals. With
|
||||||
|
/// [dryRun] nothing is written or pushed, and peers are only read.
|
||||||
|
Future<int> backfillCreatedBy(
|
||||||
|
Set<String> claudeNodes, {
|
||||||
|
required bool dryRun,
|
||||||
|
}) async {
|
||||||
|
_report(await session.sync(push: !dryRun));
|
||||||
|
final plan = await session.repository.backfillCreatedBy(
|
||||||
|
claudeNodes,
|
||||||
|
dryRun: dryRun,
|
||||||
|
);
|
||||||
|
final titles = {
|
||||||
|
for (final n in await session.repository.listNotes()) n.id: n,
|
||||||
|
};
|
||||||
|
for (final MapEntry(:key, :value) in plan.entries) {
|
||||||
|
final note = titles[key];
|
||||||
|
final title = note == null ? '' : note.text.split('\n').first;
|
||||||
|
_out.writeln(
|
||||||
|
'${key.substring(0, key.length.clamp(0, 8))}\t$value\t$title',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
final claude = plan.values.where((v) => v == 'claude').length;
|
||||||
|
final kuhy = plan.length - claude;
|
||||||
|
_out.writeln('${dryRun ? 'dry run' : 'set'}: claude $claude, kuhy $kuhy');
|
||||||
|
if (dryRun || plan.isEmpty) return 0;
|
||||||
|
return await _push('backfill') ? 0 : 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<Note> _pullAndFind(String ref) async {
|
||||||
|
_report(await session.sync(push: true));
|
||||||
|
return findNote(await session.repository.listNotes(), ref);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _save(Note note) =>
|
||||||
|
session.repository.upsert(note.copyWith(updatedAt: DateTime.now()));
|
||||||
|
|
||||||
|
Future<bool> _push(String what) async {
|
||||||
|
if (_report(await session.sync(push: true)).pushed) return true;
|
||||||
|
_err.writeln('error: $what saved locally but nothing was pushed');
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
SyncResult _report(SyncResult result) {
|
||||||
|
for (final name in result.skippedFiles) {
|
||||||
|
_err.writeln('warning: could not merge peer file $name');
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
47
lib/cli/cli_mode.dart
Normal file
@ -0,0 +1,47 @@
|
|||||||
|
/// What the CLI can be asked to do, and how a bad command line is reported.
|
||||||
|
library;
|
||||||
|
|
||||||
|
/// What the CLI was asked to do.
|
||||||
|
enum CliMode {
|
||||||
|
/// Create a note and push it.
|
||||||
|
add,
|
||||||
|
|
||||||
|
/// Print every live note, one per line.
|
||||||
|
list,
|
||||||
|
|
||||||
|
/// Print one note in full.
|
||||||
|
get,
|
||||||
|
|
||||||
|
/// Tombstone one note and push the deletion.
|
||||||
|
delete,
|
||||||
|
|
||||||
|
/// Change one note's status and push it.
|
||||||
|
setStatus,
|
||||||
|
|
||||||
|
/// Replace one note's whole text and push it.
|
||||||
|
setText,
|
||||||
|
|
||||||
|
/// Set a task done with evidence and push it.
|
||||||
|
close,
|
||||||
|
|
||||||
|
/// Print the notes matching a query, as [list] does.
|
||||||
|
search,
|
||||||
|
|
||||||
|
/// Set `created_by` on notes that lack it.
|
||||||
|
backfill,
|
||||||
|
|
||||||
|
/// Print usage.
|
||||||
|
help,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Thrown for a malformed command line; maps to exit code 2.
|
||||||
|
class UsageError implements Exception {
|
||||||
|
/// Creates a [UsageError] carrying [message].
|
||||||
|
UsageError(this.message);
|
||||||
|
|
||||||
|
/// What was wrong with the arguments.
|
||||||
|
final String message;
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() => message;
|
||||||
|
}
|
||||||
26
lib/cli/cli_paths.dart
Normal file
@ -0,0 +1,26 @@
|
|||||||
|
import 'dart:io';
|
||||||
|
|
||||||
|
import 'package:path/path.dart' as p;
|
||||||
|
import 'package:todo/cli/cli_session.dart' show CliSession;
|
||||||
|
|
||||||
|
/// Default data dir: `$XDG_DATA_HOME/todo-cli`, else `~/.local/share/todo-cli`.
|
||||||
|
String defaultDataDir(Map<String, String> env) {
|
||||||
|
final xdg = env['XDG_DATA_HOME'] ?? '';
|
||||||
|
final base = xdg.isNotEmpty
|
||||||
|
? xdg
|
||||||
|
: p.join(env['HOME'] ?? '', '.local', 'share');
|
||||||
|
return p.join(base, 'todo-cli');
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Node ids of the installs Claude files notes through: the MCP server and
|
||||||
|
/// the CLI under the same data root as [defaultDataDir]. Missing ones are
|
||||||
|
/// skipped.
|
||||||
|
Set<String> claudeNodeIds(Map<String, String> env) {
|
||||||
|
final cli = defaultDataDir(env);
|
||||||
|
return {
|
||||||
|
for (final dir in [cli, p.join(p.dirname(cli), 'todo-mcp')])
|
||||||
|
if (File(p.join(dir, CliSession.nodeIdFileName)) case final f
|
||||||
|
when f.existsSync())
|
||||||
|
f.readAsStringSync().trim(),
|
||||||
|
}..remove('');
|
||||||
|
}
|
||||||
@ -11,10 +11,9 @@ import 'dart:io';
|
|||||||
import 'package:crdt_sync/crdt_sync.dart';
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
import 'package:path/path.dart' as p;
|
import 'package:path/path.dart' as p;
|
||||||
import 'package:todo/cli/cli_args.dart';
|
import 'package:todo/cli/cli_args.dart';
|
||||||
|
import 'package:todo/cli/cli_commands.dart';
|
||||||
import 'package:todo/cli/cli_session.dart';
|
import 'package:todo/cli/cli_session.dart';
|
||||||
import 'package:todo/data/note.dart';
|
import 'package:todo/cli/note_lookup.dart';
|
||||||
import 'package:todo/sync/sync_service.dart';
|
|
||||||
import 'package:uuid/uuid.dart';
|
|
||||||
|
|
||||||
/// Opens a [CliSession]; swapped in tests to point it at a fake backend.
|
/// Opens a [CliSession]; swapped in tests to point it at a fake backend.
|
||||||
typedef SessionOpener =
|
typedef SessionOpener =
|
||||||
@ -55,7 +54,7 @@ Future<int> runCli(
|
|||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
String? text;
|
String? text;
|
||||||
if (args.mode == CliMode.add) {
|
if (args.mode == CliMode.add || args.mode == CliMode.setText) {
|
||||||
text = args.text ?? await readStdin();
|
text = args.text ?? await readStdin();
|
||||||
if (text.trim().isEmpty) {
|
if (text.trim().isEmpty) {
|
||||||
err.writeln('error: empty note (pass --text or pipe text on stdin)');
|
err.writeln('error: empty note (pass --text or pipe text on stdin)');
|
||||||
@ -74,14 +73,24 @@ Future<int> runCli(
|
|||||||
'firebase_auth.json',
|
'firebase_auth.json',
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
final cli = _Cli(session, out, err);
|
final cli = CliCommands(session, out, err);
|
||||||
return switch (args.mode) {
|
return switch (args.mode) {
|
||||||
CliMode.add => await cli.add(args, text!),
|
CliMode.add => await cli.add(args, text!),
|
||||||
CliMode.list => await cli.list(),
|
CliMode.list || CliMode.search => await cli.list(args),
|
||||||
CliMode.get => await cli.get(args.id!),
|
CliMode.get => await cli.get(args.id!),
|
||||||
|
CliMode.setStatus => await cli.setStatus(args.id!, args.status!),
|
||||||
|
CliMode.setText => await cli.setText(args.id!, text!),
|
||||||
|
CliMode.close => await cli.close(args.id!, args.opts.evidence!),
|
||||||
|
CliMode.backfill => await cli.backfillCreatedBy(
|
||||||
|
claudeNodeIds(env),
|
||||||
|
dryRun: args.dryRun,
|
||||||
|
),
|
||||||
// Only delete is left: help returned above.
|
// Only delete is left: help returned above.
|
||||||
_ => await cli.delete(args.id!),
|
_ => await cli.delete(args.id!),
|
||||||
};
|
};
|
||||||
|
} on NoteLookupError catch (error) {
|
||||||
|
err.writeln('error: $error');
|
||||||
|
return 1;
|
||||||
} on RemoteSyncError catch (error) {
|
} on RemoteSyncError catch (error) {
|
||||||
err.writeln('error: $error');
|
err.writeln('error: $error');
|
||||||
return 1;
|
return 1;
|
||||||
@ -92,95 +101,3 @@ Future<int> runCli(
|
|||||||
await session?.close();
|
await session?.close();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class _Cli {
|
|
||||||
_Cli(this.session, this.out, this.err);
|
|
||||||
|
|
||||||
final CliSession session;
|
|
||||||
final StringSink out;
|
|
||||||
final StringSink err;
|
|
||||||
|
|
||||||
Future<int> add(CliArgs args, String text) async {
|
|
||||||
final now = DateTime.now();
|
|
||||||
final note = Note(
|
|
||||||
id: const Uuid().v4(),
|
|
||||||
text: text,
|
|
||||||
priority: args.priority,
|
|
||||||
status: args.status,
|
|
||||||
createdAt: now,
|
|
||||||
updatedAt: now,
|
|
||||||
);
|
|
||||||
await session.repository.upsert(note);
|
|
||||||
final result = _report(await session.sync(push: true));
|
|
||||||
if (!result.pushed) {
|
|
||||||
err.writeln('error: note saved locally but nothing was pushed');
|
|
||||||
return 1;
|
|
||||||
}
|
|
||||||
out.writeln(note.id);
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<int> list() async {
|
|
||||||
_report(await session.sync(push: false));
|
|
||||||
for (final note in await session.repository.listNotes()) {
|
|
||||||
out.writeln(
|
|
||||||
[
|
|
||||||
note.id,
|
|
||||||
note.priority.name,
|
|
||||||
CliArgs.statusName(note.status),
|
|
||||||
note.text.split('\n').first,
|
|
||||||
].join('\t'),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<int> get(String id) async {
|
|
||||||
_report(await session.sync(push: false));
|
|
||||||
final note = await _find(id);
|
|
||||||
if (note == null) {
|
|
||||||
err.writeln('error: no live note with id $id');
|
|
||||||
return 1;
|
|
||||||
}
|
|
||||||
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()}')
|
|
||||||
..writeln('---')
|
|
||||||
..writeln(note.text);
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<int> delete(String id) async {
|
|
||||||
// Pull first: the note may have been created on another device, and a
|
|
||||||
// tombstone for an id this node has never seen would only be noise.
|
|
||||||
_report(await session.sync(push: true));
|
|
||||||
if (await _find(id) == null) {
|
|
||||||
err.writeln('error: no live note with id $id');
|
|
||||||
return 1;
|
|
||||||
}
|
|
||||||
await session.repository.delete(id);
|
|
||||||
if (!_report(await session.sync(push: true)).pushed) {
|
|
||||||
err.writeln('error: deletion saved locally but nothing was pushed');
|
|
||||||
return 1;
|
|
||||||
}
|
|
||||||
out.writeln('deleted $id');
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<Note?> _find(String id) async {
|
|
||||||
final notes = await session.repository.listNotes();
|
|
||||||
return notes.where((n) => n.id == id).firstOrNull;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Surfaces peers that could not be merged instead of dropping them
|
|
||||||
/// silently.
|
|
||||||
SyncResult _report(SyncResult result) {
|
|
||||||
for (final name in result.skippedFiles) {
|
|
||||||
err.writeln('warning: could not merge peer file $name');
|
|
||||||
}
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@ -7,6 +7,7 @@
|
|||||||
/// records hand-written into RTDB.
|
/// records hand-written into RTDB.
|
||||||
library;
|
library;
|
||||||
|
|
||||||
|
import 'dart:convert';
|
||||||
import 'dart:io';
|
import 'dart:io';
|
||||||
|
|
||||||
import 'package:crdt_sync/crdt_sync.dart';
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
@ -15,25 +16,33 @@ import 'package:http/http.dart' as http;
|
|||||||
import 'package:path/path.dart' as p;
|
import 'package:path/path.dart' as p;
|
||||||
import 'package:todo/cli/file_credential_store.dart';
|
import 'package:todo/cli/file_credential_store.dart';
|
||||||
import 'package:todo/cli/pull_only_store.dart';
|
import 'package:todo/cli/pull_only_store.dart';
|
||||||
|
import 'package:todo/cli/timeout_client.dart';
|
||||||
import 'package:todo/data/note_repository.dart';
|
import 'package:todo/data/note_repository.dart';
|
||||||
import 'package:todo/sync/firebase_project.dart';
|
import 'package:todo/sync/firebase_project.dart';
|
||||||
import 'package:todo/sync/sync_service.dart';
|
import 'package:todo/sync/sync_service.dart';
|
||||||
import 'package:uuid/uuid.dart';
|
import 'package:uuid/uuid.dart';
|
||||||
|
|
||||||
/// Default data dir: `$XDG_DATA_HOME/todo-cli`, else `~/.local/share/todo-cli`.
|
export 'package:todo/cli/cli_paths.dart';
|
||||||
String defaultDataDir(Map<String, String> env) {
|
|
||||||
final xdg = env['XDG_DATA_HOME'] ?? '';
|
|
||||||
final base = xdg.isNotEmpty
|
|
||||||
? xdg
|
|
||||||
: p.join(env['HOME'] ?? '', '.local', 'share');
|
|
||||||
return p.join(base, 'todo-cli');
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The open state of one CLI invocation. Call [close] when done.
|
/// The open state of one CLI invocation. Call [close] when done.
|
||||||
class CliSession {
|
class CliSession {
|
||||||
/// Wraps already-open parts; [open] is the normal way in. Public so a test
|
/// Wraps already-open parts; [open] is the normal way in. Public so a test
|
||||||
/// can subclass the session and script [sync]'s outcome.
|
/// can subclass the session and script [sync]'s outcome.
|
||||||
CliSession(this.dataDir, this.repository, this._firebase);
|
CliSession(
|
||||||
|
this.dataDir,
|
||||||
|
this.repository,
|
||||||
|
this._firebase, {
|
||||||
|
this.passphraseFile,
|
||||||
|
this.sharedPasswordFile,
|
||||||
|
});
|
||||||
|
|
||||||
|
/// The fleet-wide crdt-sync password the Python daemons read too
|
||||||
|
/// (`~/.config/crdt-sync/password`), found from the seed's config root.
|
||||||
|
final File? sharedPasswordFile;
|
||||||
|
|
||||||
|
/// Where the passphrase is read from besides the environment: next to the
|
||||||
|
/// seeded Firebase session, e.g. `~/.config/todo/e2e_passphrase`.
|
||||||
|
final File? passphraseFile;
|
||||||
|
|
||||||
/// File holding this install's persisted CRDT node id.
|
/// File holding this install's persisted CRDT node id.
|
||||||
static const nodeIdFileName = 'node_id';
|
static const nodeIdFileName = 'node_id';
|
||||||
@ -55,12 +64,19 @@ class CliSession {
|
|||||||
/// Opens (creating on first use) the session rooted at [dataDir].
|
/// Opens (creating on first use) the session rooted at [dataDir].
|
||||||
///
|
///
|
||||||
/// [seedCredentials] is todo's desktop session, read once and never written.
|
/// [seedCredentials] is todo's desktop session, read once and never written.
|
||||||
/// [httpClient] replaces the real network client (tests only).
|
/// [httpClient] replaces the real network client (tests only). Either way
|
||||||
|
/// every request is bounded by [requestTimeout] (see [TimeoutClient]).
|
||||||
static Future<CliSession> open(
|
static Future<CliSession> open(
|
||||||
String dataDir, {
|
String dataDir, {
|
||||||
required String seedCredentials,
|
required String seedCredentials,
|
||||||
|
String seedApp = 'todo',
|
||||||
http.Client? httpClient,
|
http.Client? httpClient,
|
||||||
|
Duration requestTimeout = const Duration(seconds: 30),
|
||||||
}) async {
|
}) async {
|
||||||
|
final network = TimeoutClient(
|
||||||
|
httpClient ?? http.Client(),
|
||||||
|
timeout: requestTimeout,
|
||||||
|
);
|
||||||
final dir = Directory(dataDir);
|
final dir = Directory(dataDir);
|
||||||
await dir.create(recursive: true);
|
await dir.create(recursive: true);
|
||||||
// Holds a database-write credential: owner-only, like ~/.config/todo.
|
// Holds a database-write credential: owner-only, like ~/.config/todo.
|
||||||
@ -73,7 +89,7 @@ class CliSession {
|
|||||||
);
|
);
|
||||||
final auth = FirebaseTokenProvider(
|
final auth = FirebaseTokenProvider(
|
||||||
apiKey: kProject.apiKey,
|
apiKey: kProject.apiKey,
|
||||||
httpClient: httpClient,
|
httpClient: network,
|
||||||
store: FileCredentialStore(
|
store: FileCredentialStore(
|
||||||
file: File(p.join(dataDir, credentialsFileName)),
|
file: File(p.join(dataDir, credentialsFileName)),
|
||||||
seedFile: File(seedCredentials),
|
seedFile: File(seedCredentials),
|
||||||
@ -83,15 +99,25 @@ class CliSession {
|
|||||||
await repository.close();
|
await repository.close();
|
||||||
throw FirebaseAuthError(
|
throw FirebaseAuthError(
|
||||||
'no Firebase session: $seedCredentials is missing; re-seed it with '
|
'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(
|
final firebase = FirebaseRestClient(
|
||||||
databaseUrl: kProject.databaseUrl,
|
databaseUrl: kProject.databaseUrl,
|
||||||
auth: auth,
|
auth: auth,
|
||||||
httpClient: httpClient,
|
httpClient: network,
|
||||||
|
);
|
||||||
|
return CliSession(
|
||||||
|
dataDir,
|
||||||
|
repository,
|
||||||
|
firebase,
|
||||||
|
passphraseFile: File(
|
||||||
|
p.join(p.dirname(seedCredentials), e2ePassphraseFileName),
|
||||||
|
),
|
||||||
|
sharedPasswordFile: File(
|
||||||
|
p.join(p.dirname(p.dirname(seedCredentials)), 'crdt-sync', 'password'),
|
||||||
|
),
|
||||||
);
|
);
|
||||||
return CliSession(dataDir, repository, firebase);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Pull every peer's log and merge it; with [push], also publish this
|
/// Pull every peer's log and merge it; with [push], also publish this
|
||||||
@ -99,15 +125,91 @@ class CliSession {
|
|||||||
///
|
///
|
||||||
/// Without [push] nothing is written anywhere remote, and the revision cache
|
/// Without [push] nothing is written anywhere remote, and the revision cache
|
||||||
/// is bypassed so a read always sees every peer's current log.
|
/// is bypassed so a read always sees every peer's current log.
|
||||||
Future<SyncResult> sync({required bool push}) {
|
Future<SyncResult> sync({required bool push}) async {
|
||||||
|
final plainService = SyncService(
|
||||||
|
stateStore: push
|
||||||
|
? PersistedSyncStateStore(
|
||||||
|
FileLogPersistence(File(p.join(dataDir, syncStateFileName))),
|
||||||
|
)
|
||||||
|
: null,
|
||||||
|
);
|
||||||
|
final e2e = await openEncryptedStore(
|
||||||
|
store: _remote(push: push),
|
||||||
|
oldPrefix: plainService.notesDir,
|
||||||
|
readPassphrase: _readPassphrase,
|
||||||
|
// Argon2id once per install, not on every CLI/MCP call.
|
||||||
|
keyCache: E2eKeyCache(read: _readCachedKey, write: _writeCachedKey),
|
||||||
|
);
|
||||||
if (!push) {
|
if (!push) {
|
||||||
return const SyncService().sync(repository, PullOnlyStore(_firebase));
|
// Read-only during the migration: old builds still write the plaintext
|
||||||
|
// prefix, so merge it, then the encrypted one when this host has a key.
|
||||||
|
final plain = await const SyncService().sync(
|
||||||
|
repository,
|
||||||
|
_remote(push: false),
|
||||||
|
);
|
||||||
|
if (e2e is! E2eReady) return plain;
|
||||||
|
final layout = E2eLayout.of(plainService.notesDir);
|
||||||
|
return await SyncService(
|
||||||
|
notesDir: layout.prefix,
|
||||||
|
revsPath: layout.revsPath,
|
||||||
|
).sync(repository, e2e.store);
|
||||||
}
|
}
|
||||||
return SyncService(
|
if (e2e is! E2eReady) {
|
||||||
stateStore: PersistedSyncStateStore(
|
throw StateError(
|
||||||
FileLogPersistence(File(p.join(dataDir, syncStateFileName))),
|
'sync is locked: put the crdt-sync passphrase in '
|
||||||
),
|
'$e2ePassphraseEnv or ${passphraseFile?.path ?? e2ePassphraseFileName}',
|
||||||
).sync(repository, _firebase);
|
);
|
||||||
|
}
|
||||||
|
final layout = E2eLayout.of(plainService.notesDir);
|
||||||
|
return await SyncService(
|
||||||
|
notesDir: layout.prefix,
|
||||||
|
revsPath: layout.revsPath,
|
||||||
|
stateStore: plainService.stateStore,
|
||||||
|
).sync(repository, e2e.store);
|
||||||
|
}
|
||||||
|
|
||||||
|
RemoteStore _remote({required bool push}) =>
|
||||||
|
push ? _firebase : PullOnlyStore(_firebase);
|
||||||
|
|
||||||
|
/// Owner-only file in the data dir caching the derived E2E key.
|
||||||
|
static const e2eKeyFileName = 'e2e_key';
|
||||||
|
|
||||||
|
File get _keyFile => File(p.join(dataDir, e2eKeyFileName));
|
||||||
|
|
||||||
|
Future<List<int>?> _readCachedKey() async {
|
||||||
|
final file = _keyFile;
|
||||||
|
if (!file.existsSync()) return null;
|
||||||
|
try {
|
||||||
|
return base64.decode((await file.readAsString()).trim());
|
||||||
|
} on FormatException {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _writeCachedKey(List<int> bytes) async {
|
||||||
|
final file = _keyFile;
|
||||||
|
// Restrict before the key is written, never after.
|
||||||
|
await file.writeAsString('');
|
||||||
|
await Process.run('chmod', ['600', file.path]);
|
||||||
|
await file.writeAsString(base64.encode(bytes), flush: true);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Environment variable holding the shared crdt-sync passphrase.
|
||||||
|
static const e2ePassphraseEnv = 'TODO_E2E_PASSPHRASE';
|
||||||
|
|
||||||
|
/// File name of the passphrase, beside the seeded Firebase session.
|
||||||
|
static const e2ePassphraseFileName = 'e2e_passphrase';
|
||||||
|
|
||||||
|
Future<String?> _readPassphrase() async {
|
||||||
|
final fromEnv = Platform.environment[e2ePassphraseEnv];
|
||||||
|
if (fromEnv != null && fromEnv.isNotEmpty) return fromEnv;
|
||||||
|
for (final file in [passphraseFile, sharedPasswordFile]) {
|
||||||
|
if (file != null && file.existsSync()) {
|
||||||
|
final text = (await file.readAsString()).trim();
|
||||||
|
if (text.isNotEmpty) return text;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Releases the log and the HTTP client.
|
/// Releases the log and the HTTP client.
|
||||||
|
|||||||
39
lib/cli/cli_usage.dart
Normal file
@ -0,0 +1,39 @@
|
|||||||
|
/// Usage text printed by `--help` and after a usage error.
|
||||||
|
const kUsage = r'''
|
||||||
|
Usage: dart run bin/todo_note.dart [options]
|
||||||
|
|
||||||
|
Adds a note to the todo app headlessly: pulls from Firebase RTDB, writes an
|
||||||
|
ordinary CRDT change as this install's own node, pushes, and prints the id.
|
||||||
|
A note with --repo is a repo task; one without is a plain idea.
|
||||||
|
|
||||||
|
--text <markdown> note text (first line = title); default: read stdin
|
||||||
|
--priority <p> low|medium|high (default medium)
|
||||||
|
--status <s> todo|in_progress|done|abandoned (default todo);
|
||||||
|
with --list/--search: show only that status
|
||||||
|
--repo <owner/name> repo task's repository, e.g. kuhyx/todo;
|
||||||
|
with --list/--search: show only that repo's tasks
|
||||||
|
--done-check <cmd> shell command, run from the repo root, exit 0 = done
|
||||||
|
--new-note with --repo: own note, not the shared one (an exact
|
||||||
|
title in another separate note merges into it)
|
||||||
|
--by <who> claude|kuhy
|
||||||
|
--list pull, then print live notes, one per line:
|
||||||
|
8-char id, status, priority, repo (- for none), title
|
||||||
|
--search <q> as --list, only notes whose text or repo contains q
|
||||||
|
--get <id> pull, then print one note in full (exit 1 if absent)
|
||||||
|
--delete <id> pull, tombstone the note, push
|
||||||
|
--set-status <id> <s> pull, change the note's status (as --status), push
|
||||||
|
--set-text <id> pull, replace the note's whole text with --text (or
|
||||||
|
stdin; first line = title), keep its other fields, push
|
||||||
|
--close <id> --evidence <s>
|
||||||
|
pull, set status done + evidence (commit sha + done
|
||||||
|
check exit code), push; refused without --evidence
|
||||||
|
--backfill-created-by [--dry-run]
|
||||||
|
pull, set created_by (claude|kuhy) on every note that
|
||||||
|
has none, push; --dry-run prints the plan only
|
||||||
|
--data-dir <dir> local log + node id (default
|
||||||
|
$XDG_DATA_HOME/todo-cli or ~/.local/share/todo-cli)
|
||||||
|
-h, --help this text
|
||||||
|
|
||||||
|
<id> is a full id or a unique prefix of at least 8 characters.
|
||||||
|
--list, --search and --get never push.
|
||||||
|
Exit codes: 0 ok, 1 sync/auth failure or note not found, 2 bad arguments.''';
|
||||||
78
lib/cli/merge_repo_notes.dart
Normal file
@ -0,0 +1,78 @@
|
|||||||
|
/// `bin/merge_repo_notes.dart`: collapse each repo's open notes into one.
|
||||||
|
/// Dry run unless `--apply`; stdout is the `old_id<TAB>kept_id<TAB>repo` map.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
|
import 'package:path/path.dart' as p;
|
||||||
|
import 'package:todo/cli/cli_runner.dart';
|
||||||
|
import 'package:todo/cli/cli_session.dart';
|
||||||
|
import 'package:todo/data/repo_note_merge.dart';
|
||||||
|
|
||||||
|
const _usage = 'usage: merge_repo_notes [--dry-run|--apply] [--data-dir D]';
|
||||||
|
|
||||||
|
/// Runs the merge for [argv]; returns the exit code.
|
||||||
|
Future<int> runMergeRepoNotes(
|
||||||
|
List<String> argv, {
|
||||||
|
required Map<String, String> env,
|
||||||
|
required StringSink out,
|
||||||
|
required StringSink err,
|
||||||
|
SessionOpener open = CliSession.open,
|
||||||
|
}) async {
|
||||||
|
var apply = false;
|
||||||
|
String? dataDir;
|
||||||
|
for (var i = 0; i < argv.length; i++) {
|
||||||
|
switch (argv[i]) {
|
||||||
|
case '--apply':
|
||||||
|
apply = true;
|
||||||
|
case '--dry-run':
|
||||||
|
apply = false;
|
||||||
|
case '--data-dir' when i + 1 < argv.length:
|
||||||
|
dataDir = argv[++i];
|
||||||
|
default:
|
||||||
|
err.writeln(_usage);
|
||||||
|
return 2;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
CliSession? session;
|
||||||
|
try {
|
||||||
|
session = await open(
|
||||||
|
dataDir ?? defaultDataDir(env),
|
||||||
|
seedCredentials: p.join(
|
||||||
|
env['HOME'] ?? '',
|
||||||
|
'.config',
|
||||||
|
'todo',
|
||||||
|
'firebase_auth.json',
|
||||||
|
),
|
||||||
|
);
|
||||||
|
await session.sync(push: apply);
|
||||||
|
final plan = planRepoMerges(await session.repository.listNotes());
|
||||||
|
for (final (:kept, :removed) in plan) {
|
||||||
|
if (apply) {
|
||||||
|
await session.repository.upsert(
|
||||||
|
kept.copyWith(updatedAt: DateTime.now()),
|
||||||
|
);
|
||||||
|
for (final n in removed) {
|
||||||
|
await session.repository.delete(n.id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (final n in removed) {
|
||||||
|
out.writeln('${n.id}\t${kept.id}\t${kept.repo}');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
final deleted = plan.fold(0, (sum, m) => sum + m.removed.length);
|
||||||
|
err.writeln(
|
||||||
|
'${apply ? 'applied' : 'dry run'}: ${plan.length} repos, '
|
||||||
|
'$deleted notes deleted',
|
||||||
|
);
|
||||||
|
if (apply && plan.isNotEmpty && !(await session.sync(push: true)).pushed) {
|
||||||
|
err.writeln('error: saved locally but nothing was pushed');
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
} on RemoteSyncError catch (error) {
|
||||||
|
err.writeln('error: $error');
|
||||||
|
return 1;
|
||||||
|
} finally {
|
||||||
|
await session?.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
64
lib/cli/note_lookup.dart
Normal file
@ -0,0 +1,64 @@
|
|||||||
|
import 'package:todo/cli/cli_args.dart';
|
||||||
|
import 'package:todo/data/note.dart';
|
||||||
|
|
||||||
|
const _minPrefix = 8;
|
||||||
|
|
||||||
|
/// No note, or more than one, matches an id argument; [message] says which.
|
||||||
|
class NoteLookupError extends FormatException {
|
||||||
|
NoteLookupError._(super.message);
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() => message;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The note with id [ref], else the only one whose id starts with [ref].
|
||||||
|
Note findNote(Iterable<Note> notes, String ref) {
|
||||||
|
final exact = notes.where((n) => n.id == ref).firstOrNull;
|
||||||
|
if (exact != null) return exact;
|
||||||
|
if (ref.length < _minPrefix) {
|
||||||
|
throw NoteLookupError._(
|
||||||
|
'no live note with id $ref (an id prefix needs at least '
|
||||||
|
'$_minPrefix characters)',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
final matches = notes.where((n) => n.id.startsWith(ref)).toList();
|
||||||
|
if (matches.isEmpty) throw NoteLookupError._('no live note with id $ref');
|
||||||
|
if (matches.length > 1) {
|
||||||
|
throw NoteLookupError._(
|
||||||
|
'id prefix $ref matches ${matches.length} notes; give more of the id:\n'
|
||||||
|
'${matches.map((n) => ' ${n.id} ${_title(n)}').join('\n')}',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return matches.single;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `<8-char id>\t<status>\t<priority>\t<repo or ->\t<title>\t<created_by>`.
|
||||||
|
String listLine(Note note) => [
|
||||||
|
if (note.id.length <= _minPrefix)
|
||||||
|
note.id
|
||||||
|
else
|
||||||
|
note.id.substring(0, _minPrefix),
|
||||||
|
CliArgs.statusName(note.status),
|
||||||
|
note.priority.name,
|
||||||
|
note.repo ?? '-',
|
||||||
|
_title(note),
|
||||||
|
note.createdBy ?? 'kuhy',
|
||||||
|
].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',
|
||||||
|
'created_by: ${note.createdBy ?? 'kuhy'}',
|
||||||
|
'---',
|
||||||
|
note.text,
|
||||||
|
].join('\n');
|
||||||
58
lib/cli/timeout_client.dart
Normal file
@ -0,0 +1,58 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
|
||||||
|
import 'package:http/http.dart' as http;
|
||||||
|
|
||||||
|
/// An HTTP client whose every request is bounded.
|
||||||
|
///
|
||||||
|
/// `package:http` has no timeout of its own, and neither do the Firebase and
|
||||||
|
/// token clients built on it: one dead connection (after boot, a network
|
||||||
|
/// blip) made a sync wait forever and wedged the MCP server's serial queue.
|
||||||
|
/// [timeout] bounds the wait for the response headers and then each gap
|
||||||
|
/// between body chunks, so a large body that keeps moving is never cut off.
|
||||||
|
class TimeoutClient extends http.BaseClient {
|
||||||
|
/// Wraps [_inner]; each wait fails with a [TimeoutException] after [timeout].
|
||||||
|
TimeoutClient(this._inner, {this.timeout = const Duration(seconds: 30)});
|
||||||
|
|
||||||
|
final http.Client _inner;
|
||||||
|
|
||||||
|
/// Longest wait for the headers, and for the next body chunk.
|
||||||
|
final Duration timeout;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<http.StreamedResponse> send(http.BaseRequest request) async {
|
||||||
|
final response = await _inner
|
||||||
|
.send(request)
|
||||||
|
.timeout(
|
||||||
|
timeout,
|
||||||
|
onTimeout: () => throw TimeoutException(
|
||||||
|
'${request.method} ${request.url.host} got no response',
|
||||||
|
timeout,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
return http.StreamedResponse(
|
||||||
|
response.stream.timeout(
|
||||||
|
timeout,
|
||||||
|
onTimeout: (sink) {
|
||||||
|
sink
|
||||||
|
..addError(
|
||||||
|
TimeoutException(
|
||||||
|
'${request.method} ${request.url.host} body stalled',
|
||||||
|
timeout,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
..close();
|
||||||
|
},
|
||||||
|
),
|
||||||
|
response.statusCode,
|
||||||
|
contentLength: response.contentLength,
|
||||||
|
request: response.request,
|
||||||
|
headers: response.headers,
|
||||||
|
isRedirect: response.isRedirect,
|
||||||
|
persistentConnection: response.persistentConnection,
|
||||||
|
reasonPhrase: response.reasonPhrase,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void close() => _inner.close();
|
||||||
|
}
|
||||||
@ -19,10 +19,14 @@ import 'package:shared_preferences/shared_preferences.dart';
|
|||||||
/// sibling to `changesets/<nodeId>.json`.
|
/// sibling to `changesets/<nodeId>.json`.
|
||||||
const String kAdvancedModeRemotePath = 'settings/advancedMode';
|
const String kAdvancedModeRemotePath = 'settings/advancedMode';
|
||||||
|
|
||||||
/// App-wide, non-sync preferences (currently just `advancedMode`).
|
/// App-wide, non-sync preferences (`advancedMode`, `showClaudeNotes`).
|
||||||
class AppSettings {
|
class AppSettings {
|
||||||
/// Creates an [AppSettings] from its stored fields.
|
/// Creates an [AppSettings] from its stored fields.
|
||||||
const AppSettings({required this.advancedMode, this.advancedModeUpdatedAt});
|
const AppSettings({
|
||||||
|
required this.advancedMode,
|
||||||
|
this.advancedModeUpdatedAt,
|
||||||
|
this.showClaudeNotes = false,
|
||||||
|
});
|
||||||
|
|
||||||
/// Whether the priority/status/template/mode chrome and the routine
|
/// Whether the priority/status/template/mode chrome and the routine
|
||||||
/// save/sync status text are shown. Off by default: casual capture needs
|
/// save/sync status text are shown. Off by default: casual capture needs
|
||||||
@ -35,6 +39,11 @@ class AppSettings {
|
|||||||
/// a value that has never round-tripped through Firebase.
|
/// a value that has never round-tripped through Firebase.
|
||||||
final DateTime? advancedModeUpdatedAt;
|
final DateTime? advancedModeUpdatedAt;
|
||||||
|
|
||||||
|
/// Whether the notes list shows notes Claude filed. Per device: it lives
|
||||||
|
/// only in this device's preferences and is never mirrored to Firebase.
|
||||||
|
final bool showClaudeNotes;
|
||||||
|
|
||||||
|
static const _kShowClaude = 'app.showClaudeNotes';
|
||||||
static const _kAdvancedMode = 'app.advancedMode';
|
static const _kAdvancedMode = 'app.advancedMode';
|
||||||
static const _kAdvancedModeUpdatedAt = 'app.advancedMode.updatedAt';
|
static const _kAdvancedModeUpdatedAt = 'app.advancedMode.updatedAt';
|
||||||
|
|
||||||
@ -44,6 +53,7 @@ class AppSettings {
|
|||||||
final updatedAtMillis = prefs.getInt(_kAdvancedModeUpdatedAt);
|
final updatedAtMillis = prefs.getInt(_kAdvancedModeUpdatedAt);
|
||||||
return AppSettings(
|
return AppSettings(
|
||||||
advancedMode: prefs.getBool(_kAdvancedMode) ?? false,
|
advancedMode: prefs.getBool(_kAdvancedMode) ?? false,
|
||||||
|
showClaudeNotes: prefs.getBool(_kShowClaude) ?? false,
|
||||||
advancedModeUpdatedAt: updatedAtMillis == null
|
advancedModeUpdatedAt: updatedAtMillis == null
|
||||||
? null
|
? null
|
||||||
: DateTime.fromMillisecondsSinceEpoch(updatedAtMillis),
|
: DateTime.fromMillisecondsSinceEpoch(updatedAtMillis),
|
||||||
@ -71,6 +81,7 @@ class AppSettings {
|
|||||||
final updated = AppSettings(
|
final updated = AppSettings(
|
||||||
advancedMode: value,
|
advancedMode: value,
|
||||||
advancedModeUpdatedAt: updatedAt,
|
advancedModeUpdatedAt: updatedAt,
|
||||||
|
showClaudeNotes: showClaudeNotes,
|
||||||
);
|
);
|
||||||
if (client != null) {
|
if (client != null) {
|
||||||
try {
|
try {
|
||||||
@ -89,6 +100,17 @@ class AppSettings {
|
|||||||
return updated;
|
return updated;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Persists the per-device Claude-notes choice; nothing leaves the device.
|
||||||
|
Future<AppSettings> withShowClaudeNotes({required bool value}) async {
|
||||||
|
final prefs = await SharedPreferences.getInstance();
|
||||||
|
await prefs.setBool(_kShowClaude, value);
|
||||||
|
return AppSettings(
|
||||||
|
advancedMode: advancedMode,
|
||||||
|
advancedModeUpdatedAt: advancedModeUpdatedAt,
|
||||||
|
showClaudeNotes: value,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
/// Pulls the remote value from [client] and, if it is newer than the
|
/// Pulls the remote value from [client] and, if it is newer than the
|
||||||
/// local one, applies it locally and returns the reconciled settings.
|
/// local one, applies it locally and returns the reconciled settings.
|
||||||
/// Returns this instance unchanged when [client] is null, there is
|
/// Returns this instance unchanged when [client] is null, there is
|
||||||
@ -100,9 +122,7 @@ class AppSettings {
|
|||||||
try {
|
try {
|
||||||
final remote = await client.getStringMap(kAdvancedModeRemotePath);
|
final remote = await client.getStringMap(kAdvancedModeRemotePath);
|
||||||
if (!remote.containsKey('value')) return this;
|
if (!remote.containsKey('value')) return this;
|
||||||
final remoteUpdatedMillis = int.tryParse(
|
final remoteUpdatedMillis = int.tryParse(remote['updatedAtMillis'] ?? '');
|
||||||
remote['updatedAtMillis'] ?? '',
|
|
||||||
);
|
|
||||||
if (remoteUpdatedMillis == null) return this;
|
if (remoteUpdatedMillis == null) return this;
|
||||||
final remoteUpdatedAt = DateTime.fromMillisecondsSinceEpoch(
|
final remoteUpdatedAt = DateTime.fromMillisecondsSinceEpoch(
|
||||||
remoteUpdatedMillis,
|
remoteUpdatedMillis,
|
||||||
@ -110,6 +130,7 @@ class AppSettings {
|
|||||||
final candidate = AppSettings(
|
final candidate = AppSettings(
|
||||||
advancedMode: remote['value'] == 'true',
|
advancedMode: remote['value'] == 'true',
|
||||||
advancedModeUpdatedAt: remoteUpdatedAt,
|
advancedModeUpdatedAt: remoteUpdatedAt,
|
||||||
|
showClaudeNotes: showClaudeNotes,
|
||||||
);
|
);
|
||||||
final adopted = adopt(candidate);
|
final adopted = adopt(candidate);
|
||||||
if (identical(adopted, this)) return this;
|
if (identical(adopted, this)) return this;
|
||||||
|
|||||||
44
lib/data/created_by_backfill.dart
Normal file
@ -0,0 +1,44 @@
|
|||||||
|
/// Who filed a note, for notes written before `created_by` existed.
|
||||||
|
///
|
||||||
|
/// The `created_at` field's clock names the node that last wrote it. The MCP
|
||||||
|
/// and the CLI are the only nodes Claude writes through, so a note created
|
||||||
|
/// there carries one of their node ids; anything else came from kuhy's own
|
||||||
|
/// devices.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
|
import 'package:todo/data/note_record.dart';
|
||||||
|
|
||||||
|
const _createdAt = 'created_at';
|
||||||
|
|
||||||
|
/// `claude` when [record]'s `created_at` was written by one of [claudeNodes],
|
||||||
|
/// else `kuhy`.
|
||||||
|
String classifyCreatedBy(Record record, Set<String> claudeNodes) {
|
||||||
|
final node = record.fields[_createdAt]?.$2.nodeId;
|
||||||
|
return node != null && claudeNodes.contains(node) ? 'claude' : 'kuhy';
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Live records of [log] with no `created_by` yet, mapped to their value.
|
||||||
|
Map<String, String> planCreatedByBackfill(Log log, Set<String> claudeNodes) => {
|
||||||
|
for (final record in log.values)
|
||||||
|
if (!record.deleted &&
|
||||||
|
((record.fields[kCreatedByField]?.$1 as String?) ?? '').isEmpty)
|
||||||
|
record.id: classifyCreatedBy(record, claudeNodes),
|
||||||
|
};
|
||||||
|
|
||||||
|
/// [incoming], carrying [existing]'s `created_by` when [incoming] has none.
|
||||||
|
///
|
||||||
|
/// A store replaces a record wholesale, so an edit that does not know the
|
||||||
|
/// field (an import of an old backup) would otherwise drop it locally.
|
||||||
|
Record keepCreatedBy(Record incoming, Record? existing) {
|
||||||
|
final kept = existing?.fields[kCreatedByField];
|
||||||
|
if (kept == null || incoming.fields.containsKey(kCreatedByField)) {
|
||||||
|
return incoming;
|
||||||
|
}
|
||||||
|
return Record(
|
||||||
|
id: incoming.id,
|
||||||
|
fields: {...incoming.fields, kCreatedByField: kept},
|
||||||
|
deleted: incoming.deleted,
|
||||||
|
deletedHlc: incoming.deletedHlc,
|
||||||
|
);
|
||||||
|
}
|
||||||
@ -73,11 +73,7 @@ class LegacySqliteMigration {
|
|||||||
}
|
}
|
||||||
// coverage:ignore-end
|
// coverage:ignore-end
|
||||||
|
|
||||||
static Future<void> _onUpgrade(
|
static Future<void> _onUpgrade(CrdtTableExecutor db, int from, int to) async {
|
||||||
CrdtTableExecutor db,
|
|
||||||
int from,
|
|
||||||
int to,
|
|
||||||
) async {
|
|
||||||
if (from < 2) {
|
if (from < 2) {
|
||||||
await db.execute(
|
await db.execute(
|
||||||
'ALTER TABLE notes ADD COLUMN status INTEGER NOT NULL DEFAULT 0',
|
'ALTER TABLE notes ADD COLUMN status INTEGER NOT NULL DEFAULT 0',
|
||||||
|
|||||||
38
lib/data/log_watch.dart
Normal file
@ -0,0 +1,38 @@
|
|||||||
|
/// A seeded, coalesced stream over the note log's change events.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'dart:async';
|
||||||
|
|
||||||
|
/// A stream that emits `compute()` when first listened to (the seed), then
|
||||||
|
/// again after [changes] fires. Seeding in `onListen` -- rather than lazily in
|
||||||
|
/// an `async*` body -- avoids a race where a write between `listen` and the
|
||||||
|
/// first generator tick would swallow the initial snapshot.
|
||||||
|
///
|
||||||
|
/// Re-emits are coalesced: the first change of a burst arms one
|
||||||
|
/// zero-duration timer and every further change before it fires is absorbed,
|
||||||
|
/// so N back-to-back changes cost ONE `compute()` carrying the latest state
|
||||||
|
/// instead of N full re-queries (each of which repaints the whole list).
|
||||||
|
/// The timer fires on the next event-loop turn, so tests stay deterministic
|
||||||
|
/// under `pumpEventQueue` and the widget tester's `pump`.
|
||||||
|
Stream<T> watchLog<T>(Stream<void> changes, T Function() compute) {
|
||||||
|
StreamSubscription<void>? sub;
|
||||||
|
Timer? pending;
|
||||||
|
late final StreamController<T> controller;
|
||||||
|
controller = StreamController<T>(
|
||||||
|
onListen: () {
|
||||||
|
controller.add(compute());
|
||||||
|
sub = changes.listen((_) {
|
||||||
|
pending ??= Timer(Duration.zero, () {
|
||||||
|
pending = null;
|
||||||
|
controller.add(compute());
|
||||||
|
});
|
||||||
|
});
|
||||||
|
},
|
||||||
|
onCancel: () {
|
||||||
|
pending?.cancel();
|
||||||
|
pending = null;
|
||||||
|
return sub?.cancel();
|
||||||
|
},
|
||||||
|
);
|
||||||
|
return controller.stream;
|
||||||
|
}
|
||||||
@ -1,9 +1,8 @@
|
|||||||
/// Domain model for a single idea/note.
|
/// Domain model for a single idea/note.
|
||||||
///
|
///
|
||||||
/// Notes are stored locally in a CRDT-backed SQLite table (see
|
/// Notes are stored as crdt_sync records (see [NoteRepository] and
|
||||||
/// [NoteRepository]). The CRDT layer manages its own metadata columns
|
/// `note_record.dart`); the clocks and tombstones live there, the fields
|
||||||
/// (`hlc`, `node_id`, `modified`, `is_deleted`); the fields here are the
|
/// here are the user-facing data only.
|
||||||
/// user-facing data only.
|
|
||||||
library;
|
library;
|
||||||
|
|
||||||
/// Priority tier for a note, used for sorting and visual grouping.
|
/// Priority tier for a note, used for sorting and visual grouping.
|
||||||
@ -77,7 +76,16 @@ enum Status {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The values the optional `by` and `created_by` fields may hold.
|
||||||
|
const Set<String> kNoteAuthors = {'claude', 'kuhy'};
|
||||||
|
|
||||||
/// An immutable idea/note record.
|
/// An immutable idea/note record.
|
||||||
|
///
|
||||||
|
/// A note with a [repo] is a *repo task* (an outstanding piece of work in
|
||||||
|
/// that repository, closable with [evidence]); one without is a plain idea.
|
||||||
|
/// The four task fields are optional and set-once in practice: they are
|
||||||
|
/// written only when a user or the CLI sets them, never by ordinary edits of
|
||||||
|
/// an idea, which keeps such edits wire-identical to the v3 build.
|
||||||
class Note {
|
class Note {
|
||||||
/// Creates a [Note] from its stored fields.
|
/// Creates a [Note] from its stored fields.
|
||||||
const Note({
|
const Note({
|
||||||
@ -87,6 +95,11 @@ class Note {
|
|||||||
required this.status,
|
required this.status,
|
||||||
required this.createdAt,
|
required this.createdAt,
|
||||||
required this.updatedAt,
|
required this.updatedAt,
|
||||||
|
this.repo,
|
||||||
|
this.doneCheck,
|
||||||
|
this.by,
|
||||||
|
this.evidence,
|
||||||
|
this.createdBy,
|
||||||
});
|
});
|
||||||
|
|
||||||
/// Builds a [Note] from a raw CRDT query row.
|
/// Builds a [Note] from a raw CRDT query row.
|
||||||
@ -122,12 +135,41 @@ class Note {
|
|||||||
/// When the note's content was last modified locally.
|
/// When the note's content was last modified locally.
|
||||||
final DateTime updatedAt;
|
final DateTime updatedAt;
|
||||||
|
|
||||||
|
/// Repository a task belongs to (`kuhyx/<name>`); null for a plain idea.
|
||||||
|
final String? repo;
|
||||||
|
|
||||||
|
/// Shell command, run from the repo root, whose exit 0 proves the task done.
|
||||||
|
final String? doneCheck;
|
||||||
|
|
||||||
|
/// Who does the task: one of [kNoteAuthors].
|
||||||
|
final String? by;
|
||||||
|
|
||||||
|
/// Proof the task was closed (commit sha + the done check's exit code).
|
||||||
|
final String? evidence;
|
||||||
|
|
||||||
|
/// Who filed the note: one of [kNoteAuthors]; null (older notes) means kuhy.
|
||||||
|
final String? createdBy;
|
||||||
|
|
||||||
|
/// Whether Claude filed this note (hidden by default, sorted last).
|
||||||
|
bool get isClaudeMade => createdBy == 'claude';
|
||||||
|
|
||||||
|
/// Whether this note is a repo task rather than a plain idea.
|
||||||
|
bool get isRepoTask => repo != null;
|
||||||
|
|
||||||
|
/// The repo without its owner ("kartka" for "kuhyx/kartka"), or null.
|
||||||
|
String? get repoName => repo?.split('/').last;
|
||||||
|
|
||||||
/// Returns a copy with selected fields replaced.
|
/// Returns a copy with selected fields replaced.
|
||||||
Note copyWith({
|
Note copyWith({
|
||||||
String? text,
|
String? text,
|
||||||
Priority? priority,
|
Priority? priority,
|
||||||
Status? status,
|
Status? status,
|
||||||
DateTime? updatedAt,
|
DateTime? updatedAt,
|
||||||
|
String? repo,
|
||||||
|
String? doneCheck,
|
||||||
|
String? by,
|
||||||
|
String? evidence,
|
||||||
|
String? createdBy,
|
||||||
}) {
|
}) {
|
||||||
return Note(
|
return Note(
|
||||||
id: id,
|
id: id,
|
||||||
@ -136,6 +178,11 @@ class Note {
|
|||||||
status: status ?? this.status,
|
status: status ?? this.status,
|
||||||
createdAt: createdAt,
|
createdAt: createdAt,
|
||||||
updatedAt: updatedAt ?? this.updatedAt,
|
updatedAt: updatedAt ?? this.updatedAt,
|
||||||
|
repo: repo ?? this.repo,
|
||||||
|
doneCheck: doneCheck ?? this.doneCheck,
|
||||||
|
by: by ?? this.by,
|
||||||
|
evidence: evidence ?? this.evidence,
|
||||||
|
createdBy: createdBy ?? this.createdBy,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
63
lib/data/note_bulk.dart
Normal file
@ -0,0 +1,63 @@
|
|||||||
|
/// Partial logs for the multi-note writes: merged in one store write.
|
||||||
|
///
|
||||||
|
/// Each write re-serialises the whole log (over a megabyte on a real
|
||||||
|
/// device), so a bulk action must be one partial log merged once, never one
|
||||||
|
/// upsert per note. Merging is per field, so a field left out keeps its value
|
||||||
|
/// and its clock (`created_by` included).
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
|
import 'package:todo/data/note.dart';
|
||||||
|
import 'package:todo/data/note_record.dart';
|
||||||
|
|
||||||
|
/// Partial records setting [priority] and/or [status] on the live notes of
|
||||||
|
/// [log] among [ids], all at [hlc].
|
||||||
|
///
|
||||||
|
/// Only fields whose value changes are written, plus `updated_at` = [now]
|
||||||
|
/// (so "last updated" sorting and newer-wins import see the edit). A note
|
||||||
|
/// with nothing to change, an unknown id and a deleted note are left out.
|
||||||
|
Log planBulkUpdate(
|
||||||
|
Log log,
|
||||||
|
Set<String> ids, {
|
||||||
|
required Hlc hlc,
|
||||||
|
required DateTime now,
|
||||||
|
Priority? priority,
|
||||||
|
Status? status,
|
||||||
|
}) {
|
||||||
|
final plan = <String, Record>{};
|
||||||
|
for (final id in ids) {
|
||||||
|
final current = log[id];
|
||||||
|
if (current == null || current.deleted) continue;
|
||||||
|
final note = noteFromRecord(current);
|
||||||
|
final next = note.copyWith(priority: priority, status: status);
|
||||||
|
if (next.priority == note.priority && next.status == note.status) continue;
|
||||||
|
// Generated against generated, never against the stored text: a peer's
|
||||||
|
// `...00Z` (or a web build's millisecond date) would otherwise read as
|
||||||
|
// a change and get a fresh clock, erasing the `created_at` node signal.
|
||||||
|
final before = noteFields(note, hlc);
|
||||||
|
plan[id] = Record(
|
||||||
|
id: id,
|
||||||
|
fields: {
|
||||||
|
for (final MapEntry(:key, :value) in noteFields(
|
||||||
|
next.copyWith(updatedAt: now),
|
||||||
|
hlc,
|
||||||
|
).entries)
|
||||||
|
if (before[key]?.$1 != value.$1) key: value,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return plan;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// [note] at [hlc] plus a tombstone for each live note of [log] in
|
||||||
|
/// [removed] (other than [note] itself).
|
||||||
|
///
|
||||||
|
/// A merge, not a replace: a field [note] leaves unset keeps its stored
|
||||||
|
/// value, so this suits notes that only gain content (the repo note an
|
||||||
|
/// assign appends to), not edits that clear a field.
|
||||||
|
Log planReplace(Log log, Note note, Iterable<String> removed, Hlc hlc) => {
|
||||||
|
for (final id in removed)
|
||||||
|
if (log[id] case final r? when !r.deleted && id != note.id)
|
||||||
|
id: Record(id: id, fields: const {}, deleted: true, deletedHlc: hlc),
|
||||||
|
note.id: Record(id: note.id, fields: noteFields(note, hlc)),
|
||||||
|
};
|
||||||
@ -35,6 +35,9 @@ class NoteFilter {
|
|||||||
this.query = '',
|
this.query = '',
|
||||||
this.priorities = const {},
|
this.priorities = const {},
|
||||||
this.statuses = const {},
|
this.statuses = const {},
|
||||||
|
this.repo,
|
||||||
|
this.repoTasksOnly = false,
|
||||||
|
this.hideClaude = false,
|
||||||
this.createdFrom,
|
this.createdFrom,
|
||||||
this.createdTo,
|
this.createdTo,
|
||||||
this.updatedFrom,
|
this.updatedFrom,
|
||||||
@ -50,6 +53,16 @@ class NoteFilter {
|
|||||||
/// Notes must have one of these statuses. Empty means "any status".
|
/// Notes must have one of these statuses. Empty means "any status".
|
||||||
final Set<Status> statuses;
|
final Set<Status> statuses;
|
||||||
|
|
||||||
|
/// Only notes whose repo equals this. Null means any repo (or none).
|
||||||
|
final String? repo;
|
||||||
|
|
||||||
|
/// Only notes that have a repo (repo tasks). Ideas are excluded.
|
||||||
|
final bool repoTasksOnly;
|
||||||
|
|
||||||
|
/// Leave out notes Claude filed. A view preference rather than a user
|
||||||
|
/// facet, so it never counts toward [isEmpty] or [activeCount].
|
||||||
|
final bool hideClaude;
|
||||||
|
|
||||||
/// Inclusive lower bound (by calendar day) on the creation date.
|
/// Inclusive lower bound (by calendar day) on the creation date.
|
||||||
final DateTime? createdFrom;
|
final DateTime? createdFrom;
|
||||||
|
|
||||||
@ -67,6 +80,8 @@ class NoteFilter {
|
|||||||
query.trim().isEmpty &&
|
query.trim().isEmpty &&
|
||||||
priorities.isEmpty &&
|
priorities.isEmpty &&
|
||||||
statuses.isEmpty &&
|
statuses.isEmpty &&
|
||||||
|
repo == null &&
|
||||||
|
!repoTasksOnly &&
|
||||||
createdFrom == null &&
|
createdFrom == null &&
|
||||||
createdTo == null &&
|
createdTo == null &&
|
||||||
updatedFrom == null &&
|
updatedFrom == null &&
|
||||||
@ -78,6 +93,8 @@ class NoteFilter {
|
|||||||
if (query.trim().isNotEmpty) n++;
|
if (query.trim().isNotEmpty) n++;
|
||||||
if (priorities.isNotEmpty) n++;
|
if (priorities.isNotEmpty) n++;
|
||||||
if (statuses.isNotEmpty) n++;
|
if (statuses.isNotEmpty) n++;
|
||||||
|
if (repo != null) n++;
|
||||||
|
if (repoTasksOnly) n++;
|
||||||
if (createdFrom != null || createdTo != null) n++;
|
if (createdFrom != null || createdTo != null) n++;
|
||||||
if (updatedFrom != null || updatedTo != null) n++;
|
if (updatedFrom != null || updatedTo != null) n++;
|
||||||
return n;
|
return n;
|
||||||
@ -90,6 +107,9 @@ class NoteFilter {
|
|||||||
String? query,
|
String? query,
|
||||||
Set<Priority>? priorities,
|
Set<Priority>? priorities,
|
||||||
Set<Status>? statuses,
|
Set<Status>? statuses,
|
||||||
|
String? repo,
|
||||||
|
bool? repoTasksOnly,
|
||||||
|
bool? hideClaude,
|
||||||
DateTime? createdFrom,
|
DateTime? createdFrom,
|
||||||
DateTime? createdTo,
|
DateTime? createdTo,
|
||||||
DateTime? updatedFrom,
|
DateTime? updatedFrom,
|
||||||
@ -101,6 +121,9 @@ class NoteFilter {
|
|||||||
query: query ?? this.query,
|
query: query ?? this.query,
|
||||||
priorities: priorities ?? this.priorities,
|
priorities: priorities ?? this.priorities,
|
||||||
statuses: statuses ?? this.statuses,
|
statuses: statuses ?? this.statuses,
|
||||||
|
repo: repo ?? this.repo,
|
||||||
|
repoTasksOnly: repoTasksOnly ?? this.repoTasksOnly,
|
||||||
|
hideClaude: hideClaude ?? this.hideClaude,
|
||||||
createdFrom: clearCreated ? null : (createdFrom ?? this.createdFrom),
|
createdFrom: clearCreated ? null : (createdFrom ?? this.createdFrom),
|
||||||
createdTo: clearCreated ? null : (createdTo ?? this.createdTo),
|
createdTo: clearCreated ? null : (createdTo ?? this.createdTo),
|
||||||
updatedFrom: clearUpdated ? null : (updatedFrom ?? this.updatedFrom),
|
updatedFrom: clearUpdated ? null : (updatedFrom ?? this.updatedFrom),
|
||||||
@ -115,9 +138,14 @@ class NoteFilter {
|
|||||||
/// empty priority set means "any priority", not "no priorities".
|
/// empty priority set means "any priority", not "no priorities".
|
||||||
bool matchesFilter(Note note, NoteFilter filter) {
|
bool matchesFilter(Note note, NoteFilter filter) {
|
||||||
final query = filter.query.trim().toLowerCase();
|
final query = filter.query.trim().toLowerCase();
|
||||||
if (query.isNotEmpty && !note.text.toLowerCase().contains(query)) {
|
if (query.isNotEmpty &&
|
||||||
|
!note.text.toLowerCase().contains(query) &&
|
||||||
|
!(note.repo?.toLowerCase().contains(query) ?? false)) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
if (filter.repo != null && note.repo != filter.repo) return false;
|
||||||
|
if (filter.repoTasksOnly && note.repo == null) return false;
|
||||||
|
if (filter.hideClaude && note.isClaudeMade) return false;
|
||||||
if (filter.priorities.isNotEmpty &&
|
if (filter.priorities.isNotEmpty &&
|
||||||
!filter.priorities.contains(note.priority)) {
|
!filter.priorities.contains(note.priority)) {
|
||||||
return false;
|
return false;
|
||||||
@ -145,8 +173,17 @@ bool _withinDays(DateTime value, DateTime? from, DateTime? to) {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The comparator implementing [sort].
|
/// The comparator implementing [sort]: human-made notes first, Claude-made
|
||||||
|
/// ones after, and [sort] orders each group.
|
||||||
Comparator<Note> comparatorFor(NoteSort sort) {
|
Comparator<Note> comparatorFor(NoteSort sort) {
|
||||||
|
final within = _within(sort);
|
||||||
|
return (a, b) {
|
||||||
|
if (a.isClaudeMade != b.isClaudeMade) return a.isClaudeMade ? 1 : -1;
|
||||||
|
return within(a, b);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
Comparator<Note> _within(NoteSort sort) {
|
||||||
switch (sort) {
|
switch (sort) {
|
||||||
case NoteSort.createdDesc:
|
case NoteSort.createdDesc:
|
||||||
return (a, b) => b.createdAt.compareTo(a.createdAt);
|
return (a, b) => b.createdAt.compareTo(a.createdAt);
|
||||||
|
|||||||
60
lib/data/note_record.dart
Normal file
@ -0,0 +1,60 @@
|
|||||||
|
/// Note <-> crdt_sync [Record] mapping; re-exported by `note_repository.dart`.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
|
import 'package:todo/data/note.dart';
|
||||||
|
|
||||||
|
const _text = 'text';
|
||||||
|
const _priority = 'priority';
|
||||||
|
const _status = 'status';
|
||||||
|
const _createdAt = 'created_at';
|
||||||
|
const _updatedAt = 'updated_at';
|
||||||
|
const _repo = 'repo';
|
||||||
|
const _doneCheck = 'done_check';
|
||||||
|
const _by = 'by';
|
||||||
|
const _evidence = 'evidence';
|
||||||
|
|
||||||
|
/// Record field naming who filed the note (`kuhy` or `claude`).
|
||||||
|
const kCreatedByField = 'created_by';
|
||||||
|
|
||||||
|
/// Record fields for [note], all at [hlc]. Unset task fields are omitted, so
|
||||||
|
/// an idea's record is exactly the v3 field set (and cannot clear a peer's).
|
||||||
|
Map<String, Field> noteFields(Note note, Hlc hlc) => {
|
||||||
|
_text: (note.text, hlc),
|
||||||
|
_priority: (note.priority.value, hlc),
|
||||||
|
_status: (note.status.value, hlc),
|
||||||
|
_createdAt: (note.createdAt.toIso8601String(), hlc),
|
||||||
|
_updatedAt: (note.updatedAt.toIso8601String(), hlc),
|
||||||
|
if (note.repo case final v?) _repo: (v, hlc),
|
||||||
|
if (note.doneCheck case final v?) _doneCheck: (v, hlc),
|
||||||
|
if (note.by case final v?) _by: (v, hlc),
|
||||||
|
if (note.evidence case final v?) _evidence: (v, hlc),
|
||||||
|
if (note.createdBy case final v?) kCreatedByField: (v, hlc),
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Reads [record] as a [Note], ignoring unknown fields.
|
||||||
|
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) ?? '',
|
||||||
|
priority: Priority.fromValue(fields[_priority]?.$1 as int?),
|
||||||
|
status: Status.fromValue(fields[_status]?.$1 as int?),
|
||||||
|
createdAt: _parseDate(str(_createdAt)),
|
||||||
|
updatedAt: _parseDate(str(_updatedAt)),
|
||||||
|
repo: task(_repo),
|
||||||
|
doneCheck: task(_doneCheck),
|
||||||
|
by: task(_by),
|
||||||
|
evidence: task(_evidence),
|
||||||
|
createdBy: task(kCreatedByField),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
DateTime _parseDate(String? iso) =>
|
||||||
|
iso == null ? DateTime.fromMillisecondsSinceEpoch(0) : DateTime.parse(iso);
|
||||||
@ -1,12 +1,15 @@
|
|||||||
import 'dart:async';
|
|
||||||
|
|
||||||
import 'package:crdt_sync/crdt_sync.dart';
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
|
import 'package:todo/data/created_by_backfill.dart';
|
||||||
|
import 'package:todo/data/log_watch.dart';
|
||||||
import 'package:todo/data/note.dart';
|
import 'package:todo/data/note.dart';
|
||||||
|
import 'package:todo/data/note_bulk.dart';
|
||||||
import 'package:todo/data/note_import.dart';
|
import 'package:todo/data/note_import.dart';
|
||||||
import 'package:todo/data/note_query.dart';
|
import 'package:todo/data/note_query.dart';
|
||||||
|
import 'package:todo/data/note_record.dart';
|
||||||
|
|
||||||
export 'package:todo/data/note_import.dart';
|
export 'package:todo/data/note_import.dart';
|
||||||
export 'package:todo/data/note_query.dart';
|
export 'package:todo/data/note_query.dart';
|
||||||
|
export 'package:todo/data/note_record.dart';
|
||||||
|
|
||||||
// Deliberately free of `dart:io`: the desktop app is a web build, and a single
|
// Deliberately free of `dart:io`: the desktop app is a web build, and a single
|
||||||
// `dart:io` import anywhere in the graph makes the whole app fail to compile
|
// `dart:io` import anywhere in the graph makes the whole app fail to compile
|
||||||
@ -35,14 +38,6 @@ class NoteRepository {
|
|||||||
/// transitively [importNotes]). Emits `void` — pull the data on demand.
|
/// transitively [importNotes]). Emits `void` — pull the data on demand.
|
||||||
Stream<void> get changes => _store.changes;
|
Stream<void> get changes => _store.changes;
|
||||||
|
|
||||||
// Field names inside each note [Record]; kept identical to the legacy SQL
|
|
||||||
// column names so a migrated log round-trips through the same [Note] mapping.
|
|
||||||
static const _fText = 'text';
|
|
||||||
static const _fPriority = 'priority';
|
|
||||||
static const _fStatus = 'status';
|
|
||||||
static const _fCreatedAt = 'created_at';
|
|
||||||
static const _fUpdatedAt = 'updated_at';
|
|
||||||
|
|
||||||
/// SharedPreferences key holding this device's stable CRDT node id.
|
/// SharedPreferences key holding this device's stable CRDT node id.
|
||||||
static const kNodeId = 'crdt.nodeId';
|
static const kNodeId = 'crdt.nodeId';
|
||||||
|
|
||||||
@ -108,7 +103,7 @@ class NoteRepository {
|
|||||||
);
|
);
|
||||||
return Record(
|
return Record(
|
||||||
id: note.id,
|
id: note.id,
|
||||||
fields: _fieldsFor(note, hlc),
|
fields: noteFields(note, hlc),
|
||||||
deleted: deleted,
|
deleted: deleted,
|
||||||
deletedHlc: deleted ? hlc : null,
|
deletedHlc: deleted ? hlc : null,
|
||||||
);
|
);
|
||||||
@ -120,9 +115,57 @@ class NoteRepository {
|
|||||||
/// character-by-character autosave: it is cheap and idempotent. All fields
|
/// character-by-character autosave: it is cheap and idempotent. All fields
|
||||||
/// share one fresh monotonic clock (they are written together).
|
/// share one fresh monotonic clock (they are written together).
|
||||||
Future<void> upsert(Note note) async {
|
Future<void> upsert(Note note) async {
|
||||||
await _store.upsert(
|
await _put(Record(id: note.id, fields: noteFields(note, _store.nextHlc())));
|
||||||
Record(id: note.id, fields: _fieldsFor(note, _store.nextHlc())),
|
}
|
||||||
);
|
|
||||||
|
Future<void> _put(Record record) =>
|
||||||
|
_store.upsert(keepCreatedBy(record, _store.get(record.id)));
|
||||||
|
|
||||||
|
/// Sets `created_by` on every live note that has none, from the node that
|
||||||
|
/// wrote its `created_at` (see [classifyCreatedBy]); returns id -> value.
|
||||||
|
///
|
||||||
|
/// Writes only that field, at a fresh clock, so no other field's clock
|
||||||
|
/// moves (a rewrite of `created_at` would erase the signal itself). With
|
||||||
|
/// [dryRun] nothing is written.
|
||||||
|
Future<Map<String, String>> backfillCreatedBy(
|
||||||
|
Set<String> claudeNodes, {
|
||||||
|
bool dryRun = false,
|
||||||
|
}) async {
|
||||||
|
final plan = planCreatedByBackfill(_store.snapshot(), claudeNodes);
|
||||||
|
if (dryRun || plan.isEmpty) return plan;
|
||||||
|
final hlc = _store.nextHlc();
|
||||||
|
await _patch({
|
||||||
|
for (final e in plan.entries)
|
||||||
|
e.key: Record(id: e.key, fields: {kCreatedByField: (e.value, hlc)}),
|
||||||
|
});
|
||||||
|
return plan;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sets [priority] and/or [status] on the live notes [ids] in ONE store
|
||||||
|
/// write (see [planBulkUpdate]); a no-op when nothing changes.
|
||||||
|
Future<void> bulkUpdate(
|
||||||
|
Set<String> ids, {
|
||||||
|
Priority? priority,
|
||||||
|
Status? status,
|
||||||
|
}) => _patch(
|
||||||
|
planBulkUpdate(
|
||||||
|
_store.snapshot(),
|
||||||
|
ids,
|
||||||
|
hlc: _store.nextHlc(),
|
||||||
|
now: DateTime.now(),
|
||||||
|
priority: priority,
|
||||||
|
status: status,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
/// Saves [note] and deletes [removed] in ONE store write ([planReplace]).
|
||||||
|
Future<void> saveReplacing(Note note, Iterable<String> removed) =>
|
||||||
|
_patch(planReplace(_store.snapshot(), note, removed, _store.nextHlc()));
|
||||||
|
|
||||||
|
/// Merges a partial log in one write: untouched fields keep their clocks.
|
||||||
|
Future<void> _patch(Log partial) async {
|
||||||
|
if (partial.isEmpty) return;
|
||||||
|
await _store.replaceAll(mergeLogs(_store.snapshot(), partial));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Soft-deletes a note. The log keeps a sticky tombstone so the deletion
|
/// Soft-deletes a note. The log keeps a sticky tombstone so the deletion
|
||||||
@ -148,10 +191,10 @@ class NoteRepository {
|
|||||||
// the import wins locally; the clock decides whether it wins on *other*
|
// the import wins locally; the clock decides whether it wins on *other*
|
||||||
// devices, and an import must not win there simply by being recent.
|
// devices, and an import must not win there simply by being recent.
|
||||||
if (local == null) {
|
if (local == null) {
|
||||||
await _store.upsert(recordAtNoteTime(note, _nodeId));
|
await _put(recordAtNoteTime(note, _nodeId));
|
||||||
added++;
|
added++;
|
||||||
} else if (note.updatedAt.isAfter(local.updatedAt)) {
|
} else if (note.updatedAt.isAfter(local.updatedAt)) {
|
||||||
await _store.upsert(recordAtNoteTime(note, _nodeId));
|
await _put(recordAtNoteTime(note, _nodeId));
|
||||||
updated++;
|
updated++;
|
||||||
} else {
|
} else {
|
||||||
skipped++;
|
skipped++;
|
||||||
@ -171,27 +214,10 @@ class NoteRepository {
|
|||||||
Stream<List<Note>> watchNotes({
|
Stream<List<Note>> watchNotes({
|
||||||
NoteSort sort = NoteSort.priorityDesc,
|
NoteSort sort = NoteSort.priorityDesc,
|
||||||
NoteFilter filter = const NoteFilter(),
|
NoteFilter filter = const NoteFilter(),
|
||||||
}) => _watch(() => _query(sort, filter));
|
}) => watchLog(_store.changes, () => _query(sort, filter));
|
||||||
|
|
||||||
/// Emits the live count of non-deleted notes immediately and on each change.
|
/// Emits the live count of non-deleted notes immediately and on each change.
|
||||||
Stream<int> watchCount() => _watch(_liveCount);
|
Stream<int> watchCount() => watchLog(_store.changes, _liveCount);
|
||||||
|
|
||||||
/// A stream that emits `compute()` synchronously when first listened to (the
|
|
||||||
/// seed), then again on every log change. Seeding in `onListen` — rather than
|
|
||||||
/// lazily in an `async*` body — avoids a race where a write between `listen`
|
|
||||||
/// and the first generator tick would swallow the initial snapshot.
|
|
||||||
Stream<T> _watch<T>(T Function() compute) {
|
|
||||||
StreamSubscription<void>? sub;
|
|
||||||
late final StreamController<T> controller;
|
|
||||||
controller = StreamController<T>(
|
|
||||||
onListen: () {
|
|
||||||
controller.add(compute());
|
|
||||||
sub = _store.changes.listen((_) => controller.add(compute()));
|
|
||||||
},
|
|
||||||
onCancel: () => sub?.cancel(),
|
|
||||||
);
|
|
||||||
return controller.stream;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// This device's stable node id. Names its file in the sync repo so two
|
/// This device's stable node id. Names its file in the sync repo so two
|
||||||
/// devices never write the same path.
|
/// devices never write the same path.
|
||||||
@ -209,34 +235,10 @@ class NoteRepository {
|
|||||||
/// Closes the underlying log and its change stream.
|
/// Closes the underlying log and its change stream.
|
||||||
Future<void> close() => _store.close();
|
Future<void> close() => _store.close();
|
||||||
|
|
||||||
// --- note <-> record mapping & querying ------------------------------------
|
// --- querying (the note <-> record mapping is in note_record.dart) --------
|
||||||
|
|
||||||
static Map<String, Field> _fieldsFor(Note note, Hlc hlc) => {
|
|
||||||
_fText: (note.text, hlc),
|
|
||||||
_fPriority: (note.priority.value, hlc),
|
|
||||||
_fStatus: (note.status.value, hlc),
|
|
||||||
_fCreatedAt: (note.createdAt.toIso8601String(), hlc),
|
|
||||||
_fUpdatedAt: (note.updatedAt.toIso8601String(), hlc),
|
|
||||||
};
|
|
||||||
|
|
||||||
Note _toNote(Record record) {
|
|
||||||
final fields = record.fields;
|
|
||||||
return Note(
|
|
||||||
id: record.id,
|
|
||||||
text: fields[_fText]?.$1 as String? ?? '',
|
|
||||||
priority: Priority.fromValue(fields[_fPriority]?.$1 as int?),
|
|
||||||
status: Status.fromValue(fields[_fStatus]?.$1 as int?),
|
|
||||||
createdAt: _parseDate(fields[_fCreatedAt]?.$1 as String?),
|
|
||||||
updatedAt: _parseDate(fields[_fUpdatedAt]?.$1 as String?),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
static DateTime _parseDate(String? iso) => iso == null
|
|
||||||
? DateTime.fromMillisecondsSinceEpoch(0)
|
|
||||||
: DateTime.parse(iso);
|
|
||||||
|
|
||||||
Iterable<Note> _liveNotes() =>
|
Iterable<Note> _liveNotes() =>
|
||||||
_store.values.where((r) => !r.deleted).map(_toNote);
|
_store.values.where((r) => !r.deleted).map(noteFromRecord);
|
||||||
|
|
||||||
int _liveCount() => _store.values.where((r) => !r.deleted).length;
|
int _liveCount() => _store.values.where((r) => !r.deleted).length;
|
||||||
|
|
||||||
|
|||||||
75
lib/data/repo_assign.dart
Normal file
@ -0,0 +1,75 @@
|
|||||||
|
/// Assigning plain notes to a repo from the UI: each becomes a `## title`
|
||||||
|
/// section of the repo's one open note ([addRepoTask]), and the original goes.
|
||||||
|
///
|
||||||
|
/// Only the data layer: nothing here talks to the board or starts a task.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:todo/data/note.dart';
|
||||||
|
import 'package:todo/data/note_repository.dart';
|
||||||
|
import 'package:todo/data/repo_note.dart';
|
||||||
|
|
||||||
|
final _repoShape = RegExp(r'^[\w.-]+/[\w.-]+$');
|
||||||
|
final _heading = RegExp(r'^(#+)(\s.*)$');
|
||||||
|
|
||||||
|
/// Whether [value] looks like `owner/name`.
|
||||||
|
bool isRepoName(String value) => _repoShape.hasMatch(value.trim());
|
||||||
|
|
||||||
|
/// [body] with every heading outside code fences pushed below `##`.
|
||||||
|
///
|
||||||
|
/// A repo note splits into tasks at `##` headings, so a template note's own
|
||||||
|
/// `## what` / `## must` would otherwise turn into tasks of their own.
|
||||||
|
String demoteHeadings(String body) {
|
||||||
|
var fenced = false;
|
||||||
|
final out = <String>[];
|
||||||
|
for (final line in body.split('\n')) {
|
||||||
|
if (line.trimLeft().startsWith('```')) fenced = !fenced;
|
||||||
|
final m = fenced ? null : _heading.firstMatch(line);
|
||||||
|
if (m == null) {
|
||||||
|
out.add(line);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
final level = m.group(1)!.length;
|
||||||
|
out.add('${'#' * (level < 2 ? 3 : level + 1)}${m.group(2)}');
|
||||||
|
}
|
||||||
|
return out.join('\n');
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Moves the plain [notes] into [repo]'s open note in one write, creating
|
||||||
|
/// that note when the repo has none; returns the notes refused because
|
||||||
|
/// they already belong to a repo (left untouched).
|
||||||
|
Future<List<Note>> assignToRepo(
|
||||||
|
NoteRepository repository,
|
||||||
|
List<Note> notes,
|
||||||
|
String repo,
|
||||||
|
) async {
|
||||||
|
final refused = [
|
||||||
|
for (final n in notes)
|
||||||
|
if (n.repo != null) n,
|
||||||
|
];
|
||||||
|
final plain = [
|
||||||
|
for (final n in notes)
|
||||||
|
if (n.repo == null) n,
|
||||||
|
];
|
||||||
|
if (plain.isEmpty) return refused;
|
||||||
|
final first = splitNote(plain.first.text);
|
||||||
|
var target = (await addRepoTask(
|
||||||
|
repository,
|
||||||
|
repo: repo,
|
||||||
|
title: first.title,
|
||||||
|
body: demoteHeadings(first.body),
|
||||||
|
priority: plain.first.priority,
|
||||||
|
createdBy: 'kuhy',
|
||||||
|
)).note;
|
||||||
|
for (final n in plain.skip(1)) {
|
||||||
|
final (:title, :body) = splitNote(n.text);
|
||||||
|
target = target.copyWith(
|
||||||
|
text: '${target.text}\n\n${repoSection(title, demoteHeadings(body))}',
|
||||||
|
priority: maxPriority(target.priority, n.priority),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
await repository.saveReplacing(
|
||||||
|
target.copyWith(updatedAt: DateTime.now()),
|
||||||
|
plain.map((n) => n.id),
|
||||||
|
);
|
||||||
|
return refused;
|
||||||
|
}
|
||||||
107
lib/data/repo_note.dart
Normal file
@ -0,0 +1,107 @@
|
|||||||
|
/// The one-open-note-per-repo invariant. Single add path for the MCP
|
||||||
|
/// `add_task` and the CLI `--repo` add; callers persist and push.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:todo/data/note.dart';
|
||||||
|
import 'package:todo/data/note_repository.dart';
|
||||||
|
import 'package:uuid/uuid.dart';
|
||||||
|
|
||||||
|
/// Statuses that count as open.
|
||||||
|
const Set<Status> kOpenStatuses = {Status.todo, Status.inProgress};
|
||||||
|
|
||||||
|
/// The repo note's title.
|
||||||
|
String repoNoteTitle(String repo) => '${repo.split('/').last} todos';
|
||||||
|
|
||||||
|
/// A `new_note` task's own note title: `<name> todos: <title>`.
|
||||||
|
String separateNoteTitle(String repo, String title) =>
|
||||||
|
'${repoNoteTitle(repo)}: ${title.trim()}';
|
||||||
|
|
||||||
|
/// Whether [note] is a `new_note` note, which the shared add path and the
|
||||||
|
/// one-time merge leave alone.
|
||||||
|
bool isSeparateNote(Note note) {
|
||||||
|
final repo = note.repo;
|
||||||
|
return repo != null &&
|
||||||
|
splitNote(note.text).title.startsWith('${repoNoteTitle(repo)}: ');
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Joins two checks with `&&`; either may be absent.
|
||||||
|
String? composeDoneCheck(String? older, String? newer) {
|
||||||
|
final a = (older ?? '').trim();
|
||||||
|
final b = (newer ?? '').trim();
|
||||||
|
if (a.isEmpty) return b.isEmpty ? null : b;
|
||||||
|
return b.isEmpty ? a : '( $a ) && ( $b )';
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A `## title` section.
|
||||||
|
String repoSection(String title, String body) {
|
||||||
|
final text = body.trim();
|
||||||
|
return text.isEmpty ? '## $title' : '## $title\n$text';
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The higher priority.
|
||||||
|
Priority maxPriority(Priority a, Priority b) => a.value >= b.value ? a : b;
|
||||||
|
|
||||||
|
/// Title line and rest of a note's text.
|
||||||
|
({String title, String body}) splitNote(String text) {
|
||||||
|
final lines = text.split('\n');
|
||||||
|
final first = lines.indexWhere((l) => l.trim().isNotEmpty);
|
||||||
|
if (first < 0) return (title: '', body: '');
|
||||||
|
return (
|
||||||
|
title: lines[first].trim().replaceFirst(RegExp(r'^#+\s*'), ''),
|
||||||
|
body: lines.skip(first + 1).join('\n').trim(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Oldest first; ties broken by id so the choice is deterministic.
|
||||||
|
int byAge(Note a, Note b) {
|
||||||
|
final c = a.createdAt.compareTo(b.createdAt);
|
||||||
|
return c != 0 ? c : a.id.compareTo(b.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The note to save and whether it was appended.
|
||||||
|
typedef RepoAdd = ({Note note, bool appended});
|
||||||
|
|
||||||
|
/// Appends the task to [repo]'s oldest open shared note, or builds that
|
||||||
|
/// note; separate (`new_note`) notes are never joined.
|
||||||
|
Future<RepoAdd> addRepoTask(
|
||||||
|
NoteRepository repository, {
|
||||||
|
required String repo,
|
||||||
|
required String title,
|
||||||
|
String body = '',
|
||||||
|
String? doneCheck,
|
||||||
|
Priority priority = Priority.medium,
|
||||||
|
String? by,
|
||||||
|
String? createdBy,
|
||||||
|
}) async {
|
||||||
|
final section = repoSection(title, body);
|
||||||
|
final open = (await repository.listNotes(
|
||||||
|
filter: NoteFilter(statuses: kOpenStatuses, repo: repo),
|
||||||
|
)).where((n) => !isSeparateNote(n)).toList();
|
||||||
|
if (open.isNotEmpty) {
|
||||||
|
final existing = (open..sort(byAge)).first;
|
||||||
|
return (
|
||||||
|
note: existing.copyWith(
|
||||||
|
text: '${existing.text}\n\n$section',
|
||||||
|
doneCheck: composeDoneCheck(existing.doneCheck, doneCheck),
|
||||||
|
priority: maxPriority(existing.priority, priority),
|
||||||
|
),
|
||||||
|
appended: true,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
final now = DateTime.now();
|
||||||
|
return (
|
||||||
|
note: Note(
|
||||||
|
id: const Uuid().v4(),
|
||||||
|
text: '${repoNoteTitle(repo)}\n\n$section',
|
||||||
|
priority: priority,
|
||||||
|
status: Status.todo,
|
||||||
|
createdAt: now,
|
||||||
|
updatedAt: now,
|
||||||
|
repo: repo,
|
||||||
|
doneCheck: composeDoneCheck(null, doneCheck),
|
||||||
|
by: by,
|
||||||
|
createdBy: createdBy,
|
||||||
|
),
|
||||||
|
appended: false,
|
||||||
|
);
|
||||||
|
}
|
||||||
53
lib/data/repo_note_merge.dart
Normal file
@ -0,0 +1,53 @@
|
|||||||
|
/// One-time migration plan: one open note per repo, oldest id kept.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:todo/data/note.dart';
|
||||||
|
import 'package:todo/data/repo_note.dart';
|
||||||
|
|
||||||
|
/// The rewritten oldest note and the originals to delete.
|
||||||
|
typedef RepoMerge = ({Note kept, List<Note> removed});
|
||||||
|
|
||||||
|
/// A merge for every repo whose open notes are not yet one `<name> todos`
|
||||||
|
/// note; running it on its own result yields an empty plan. Separate
|
||||||
|
/// (`new_note`) notes stay out of it.
|
||||||
|
List<RepoMerge> planRepoMerges(Iterable<Note> notes) {
|
||||||
|
final byRepo = <String, List<Note>>{};
|
||||||
|
for (final n in notes) {
|
||||||
|
final repo = n.repo;
|
||||||
|
if (repo != null &&
|
||||||
|
kOpenStatuses.contains(n.status) &&
|
||||||
|
!isSeparateNote(n)) {
|
||||||
|
byRepo.putIfAbsent(repo, () => []).add(n);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
final plan = <RepoMerge>[];
|
||||||
|
for (final MapEntry(key: repo, value: group) in byRepo.entries) {
|
||||||
|
group.sort(byAge);
|
||||||
|
final title = repoNoteTitle(repo);
|
||||||
|
if (group.length == 1 && splitNote(group.single.text).title == title) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
plan.add((kept: _merged(title, group), removed: group.sublist(1)));
|
||||||
|
}
|
||||||
|
return plan;
|
||||||
|
}
|
||||||
|
|
||||||
|
Note _merged(String title, List<Note> group) {
|
||||||
|
var doneCheck = group.first.doneCheck;
|
||||||
|
var priority = group.first.priority;
|
||||||
|
final sections = <String>[];
|
||||||
|
for (final (i, n) in group.indexed) {
|
||||||
|
final (title: t, :body) = splitNote(n.text);
|
||||||
|
// An already-merged note keeps its sections as they are.
|
||||||
|
sections.add(t == title ? body : repoSection(t, body));
|
||||||
|
if (i > 0) {
|
||||||
|
doneCheck = composeDoneCheck(doneCheck, n.doneCheck);
|
||||||
|
priority = maxPriority(priority, n.priority);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return group.first.copyWith(
|
||||||
|
text: '$title\n\n${sections.where((s) => s.isNotEmpty).join('\n\n')}',
|
||||||
|
doneCheck: doneCheck,
|
||||||
|
priority: priority,
|
||||||
|
);
|
||||||
|
}
|
||||||
122
lib/data/repo_note_split.dart
Normal file
@ -0,0 +1,122 @@
|
|||||||
|
/// `new_note`: a repo task in its own open note, `<name> todos: <title>`,
|
||||||
|
/// so it can close on its own done_check. A title that already heads an open
|
||||||
|
/// section of another separate note of the repo merges into that note
|
||||||
|
/// instead (it keeps its id); the shared `<name> todos` note never counts.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:todo/data/note.dart';
|
||||||
|
import 'package:todo/data/note_repository.dart';
|
||||||
|
import 'package:todo/data/repo_note.dart';
|
||||||
|
import 'package:uuid/uuid.dart';
|
||||||
|
|
||||||
|
/// How a separate add landed.
|
||||||
|
enum SplitKind {
|
||||||
|
/// A new separate note.
|
||||||
|
added,
|
||||||
|
|
||||||
|
/// Appended to the separate note that already had the title.
|
||||||
|
merged,
|
||||||
|
|
||||||
|
/// A new separate note because the duplicate's note was busy.
|
||||||
|
fellBack,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The note to save, how it landed, and why it fell back.
|
||||||
|
typedef SplitAdd = ({Note note, SplitKind kind, String? why});
|
||||||
|
|
||||||
|
final _heading = RegExp(r'^##\s+(\[x\]\s+)?(.*)$');
|
||||||
|
|
||||||
|
/// Every `## title` heading of [text] outside code fences, open or done.
|
||||||
|
Iterable<RegExpMatch> _sections(String text) sync* {
|
||||||
|
var fenced = false;
|
||||||
|
for (final line in text.split('\n')) {
|
||||||
|
if (line.trimLeft().startsWith('```')) fenced = !fenced;
|
||||||
|
final m = fenced ? null : _heading.firstMatch(line);
|
||||||
|
if (m != null) yield m;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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].
|
||||||
|
Note? duplicateTarget(Iterable<Note> open, String repo, String title) {
|
||||||
|
final hits =
|
||||||
|
open
|
||||||
|
.where((n) => n.repo == repo && isSeparateNote(n))
|
||||||
|
.where((n) => openSections(n.text).contains(title.trim()))
|
||||||
|
.toList()
|
||||||
|
..sort(byAge);
|
||||||
|
return hits.isEmpty ? null : hits.first;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Why a merged task must not be started, or null when it may be.
|
||||||
|
String? startBlock(String? doneCheck, String body) {
|
||||||
|
final check = (doneCheck ?? '').trim().toLowerCase();
|
||||||
|
if (check.isEmpty || check == 'none') return 'done_check is none';
|
||||||
|
final first = body
|
||||||
|
.split('\n')
|
||||||
|
.firstWhere((l) => l.trim().isNotEmpty, orElse: () => '');
|
||||||
|
return first.trim().toLowerCase().startsWith('low priority')
|
||||||
|
? 'marked low priority'
|
||||||
|
: null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Adds the task as its own note, or merges it into the duplicate's note
|
||||||
|
/// unless [busy] says a board session is working on it.
|
||||||
|
Future<SplitAdd> addSeparateTask(
|
||||||
|
NoteRepository repository, {
|
||||||
|
required String repo,
|
||||||
|
required String title,
|
||||||
|
String body = '',
|
||||||
|
String? doneCheck,
|
||||||
|
Priority priority = Priority.medium,
|
||||||
|
String? by,
|
||||||
|
String? createdBy,
|
||||||
|
Future<bool> Function(Note note)? busy,
|
||||||
|
}) async {
|
||||||
|
final section = repoSection(title, body);
|
||||||
|
final open = await repository.listNotes(
|
||||||
|
filter: NoteFilter(statuses: kOpenStatuses, repo: repo),
|
||||||
|
);
|
||||||
|
final target = duplicateTarget(open, repo, title);
|
||||||
|
String? why;
|
||||||
|
if (target != null) {
|
||||||
|
if (busy == null || !await busy(target)) {
|
||||||
|
return (
|
||||||
|
note: target.copyWith(
|
||||||
|
text: '${target.text}\n\n$section',
|
||||||
|
doneCheck: composeDoneCheck(target.doneCheck, doneCheck),
|
||||||
|
priority: maxPriority(target.priority, priority),
|
||||||
|
),
|
||||||
|
kind: SplitKind.merged,
|
||||||
|
why: null,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
why =
|
||||||
|
'not merged into ${target.id.substring(0, 8)}: '
|
||||||
|
'a board session is running on it';
|
||||||
|
}
|
||||||
|
final now = DateTime.now();
|
||||||
|
return (
|
||||||
|
note: Note(
|
||||||
|
id: const Uuid().v4(),
|
||||||
|
text: '${separateNoteTitle(repo, title)}\n\n$section',
|
||||||
|
priority: priority,
|
||||||
|
status: Status.todo,
|
||||||
|
createdAt: now,
|
||||||
|
updatedAt: now,
|
||||||
|
repo: repo,
|
||||||
|
doneCheck: composeDoneCheck(null, doneCheck),
|
||||||
|
by: by,
|
||||||
|
createdBy: createdBy,
|
||||||
|
),
|
||||||
|
kind: why == null ? SplitKind.added : SplitKind.fellBack,
|
||||||
|
why: why,
|
||||||
|
);
|
||||||
|
}
|
||||||
@ -59,6 +59,11 @@ List<String> browserArgs(String home) => [
|
|||||||
// blank grey. Nothing in this profile needs OS-level encryption (the
|
// blank grey. Nothing in this profile needs OS-level encryption (the
|
||||||
// GitHub token is in localStorage, not the password store).
|
// GitHub token is in localStorage, not the password store).
|
||||||
'--password-store=basic',
|
'--password-store=basic',
|
||||||
|
// The distro wrapper appends ~/.config/chromium-flags.conf to every launch,
|
||||||
|
// which here carries `--load-extension` for Claude in Chrome. Logged out in
|
||||||
|
// this profile, it opened a claude.ai login tab in a second, normal browser
|
||||||
|
// window on every start. This flag also drops command-line extensions.
|
||||||
|
'--disable-extensions',
|
||||||
];
|
];
|
||||||
|
|
||||||
/// Launches the app in a Chrome-family browser with a **stable** profile
|
/// Launches the app in a Chrome-family browser with a **stable** profile
|
||||||
|
|||||||
@ -21,12 +21,21 @@ class LinuxSystemProbe implements SystemProbe {
|
|||||||
/// Creates the default host probe.
|
/// Creates the default host probe.
|
||||||
///
|
///
|
||||||
/// [ssExecutable] exists so a test can point at a missing binary and exercise
|
/// [ssExecutable] exists so a test can point at a missing binary and exercise
|
||||||
/// the "no `ss` on PATH" path.
|
/// the "no `ss` on PATH" path. [listProc] lets a test fail the `/proc`
|
||||||
const LinuxSystemProbe({this.ssExecutable = 'ss'});
|
/// listing on demand.
|
||||||
|
const LinuxSystemProbe({this.ssExecutable = 'ss', this.listProc = _listProc});
|
||||||
|
|
||||||
/// Name of the socket-listing tool used to find the port owner.
|
/// Name of the socket-listing tool used to find the port owner.
|
||||||
final String ssExecutable;
|
final String ssExecutable;
|
||||||
|
|
||||||
|
/// Lists `/proc`'s entries.
|
||||||
|
final List<FileSystemEntity> Function() listProc;
|
||||||
|
|
||||||
|
/// How many `/proc` listings a process exiting mid-listing may spoil.
|
||||||
|
static const _listAttempts = 3;
|
||||||
|
|
||||||
|
static List<FileSystemEntity> _listProc() => Directory('/proc').listSync();
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Future<int?> listenerPid(int port) async {
|
Future<int?> listenerPid(int port) async {
|
||||||
try {
|
try {
|
||||||
@ -56,7 +65,7 @@ class LinuxSystemProbe implements SystemProbe {
|
|||||||
@override
|
@override
|
||||||
Future<List<List<String>>> processCmdlines() async {
|
Future<List<List<String>>> processCmdlines() async {
|
||||||
final cmdlines = <List<String>>[];
|
final cmdlines = <List<String>>[];
|
||||||
for (final entry in Directory('/proc').listSync()) {
|
for (final entry in _listProcRetrying()) {
|
||||||
final pid = int.tryParse(p.basename(entry.path));
|
final pid = int.tryParse(p.basename(entry.path));
|
||||||
if (pid == null) continue;
|
if (pid == null) continue;
|
||||||
final cmdline = readCmdline(pid);
|
final cmdline = readCmdline(pid);
|
||||||
@ -65,6 +74,19 @@ class LinuxSystemProbe implements SystemProbe {
|
|||||||
return cmdlines;
|
return cmdlines;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Dart's listing lstat()s some entries, so a pid that exits between
|
||||||
|
/// readdir and that lstat fails the whole listing. A fresh listing no
|
||||||
|
/// longer holds that pid; a few failures in a row mean a real error.
|
||||||
|
List<FileSystemEntity> _listProcRetrying() {
|
||||||
|
for (var attempt = 1; ; attempt++) {
|
||||||
|
try {
|
||||||
|
return listProc();
|
||||||
|
} on PathNotFoundException {
|
||||||
|
if (attempt >= _listAttempts) rethrow;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Future<bool> portInUse(int port) async {
|
Future<bool> portInUse(int port) async {
|
||||||
try {
|
try {
|
||||||
|
|||||||
@ -7,6 +7,9 @@ import 'package:path/path.dart' as p;
|
|||||||
|
|
||||||
import 'package:todo/desktop/static_content_type.dart';
|
import 'package:todo/desktop/static_content_type.dart';
|
||||||
import 'package:todo/desktop/wrapper_image_routes.dart';
|
import 'package:todo/desktop/wrapper_image_routes.dart';
|
||||||
|
import 'package:todo/sync/e2e_passphrase_path.dart';
|
||||||
|
|
||||||
|
export 'package:todo/sync/e2e_passphrase_path.dart';
|
||||||
|
|
||||||
export 'wrapper_paths.dart';
|
export 'wrapper_paths.dart';
|
||||||
|
|
||||||
@ -86,6 +89,9 @@ class WrapperServer {
|
|||||||
/// wrappers also serve, which stays opt-in.
|
/// wrappers also serve, which stays opt-in.
|
||||||
bool _todoCredentialsServed = false;
|
bool _todoCredentialsServed = false;
|
||||||
|
|
||||||
|
/// Whether [kSyncE2ePassphrasePath] has served the passphrase yet.
|
||||||
|
bool _e2ePassphraseServed = false;
|
||||||
|
|
||||||
/// `todo`'s own seeded Firebase session, written by
|
/// `todo`'s own seeded Firebase session, written by
|
||||||
/// `crdt-sync/tool/seed_session.py --app todo` in the same
|
/// `crdt-sync/tool/seed_session.py --app todo` in the same
|
||||||
/// `{id_token, refresh_token, expires_at}` shape every other app's
|
/// `{id_token, refresh_token, expires_at}` shape every other app's
|
||||||
@ -184,6 +190,9 @@ class WrapperServer {
|
|||||||
if (path == kSyncCredentialsPath) {
|
if (path == kSyncCredentialsPath) {
|
||||||
return await _syncCredentials(request);
|
return await _syncCredentials(request);
|
||||||
}
|
}
|
||||||
|
if (path == kSyncE2ePassphrasePath) {
|
||||||
|
return await _syncE2ePassphrase(request);
|
||||||
|
}
|
||||||
if (await images.handle(request)) return;
|
if (await images.handle(request)) return;
|
||||||
return await _static(request, path);
|
return await _static(request, path);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -121,4 +121,23 @@ extension _SyncRoutes on WrapperServer {
|
|||||||
// through must remain retryable rather than burning the one serve.
|
// through must remain retryable rather than burning the one serve.
|
||||||
_todoCredentialsServed = true;
|
_todoCredentialsServed = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Serves the shared crdt-sync password as the E2E passphrase, once per
|
||||||
|
/// wrapper process, like [_syncCredentials]: the web app stores it in its
|
||||||
|
/// keystore on first sync and never asks for it.
|
||||||
|
Future<void> _syncE2ePassphrase(HttpRequest request) async {
|
||||||
|
final passwordFile = File(p.join(syncConfigDir, 'password'));
|
||||||
|
if (_e2ePassphraseServed || !passwordFile.existsSync()) {
|
||||||
|
request.response.statusCode = HttpStatus.notFound;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
final text = (await passwordFile.readAsString()).trim();
|
||||||
|
if (text.isEmpty) {
|
||||||
|
request.response.statusCode = HttpStatus.notFound;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
request.response.headers.contentType = ContentType.text;
|
||||||
|
request.response.write(text);
|
||||||
|
_e2ePassphraseServed = true;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -132,10 +132,16 @@ class ImageCacheStore {
|
|||||||
for (final ref in pending()) {
|
for (final ref in pending()) {
|
||||||
final file = fileFor(ref);
|
final file = fileFor(ref);
|
||||||
if (!file.existsSync()) continue;
|
if (!file.existsSync()) continue;
|
||||||
final length = await file.length();
|
try {
|
||||||
if (await client.upload(ref, file.openRead(), length)) {
|
final length = await file.length();
|
||||||
await _marker(ref).delete();
|
if (await client.upload(ref, file.openRead(), length)) {
|
||||||
uploaded++;
|
await _marker(ref).delete();
|
||||||
|
uploaded++;
|
||||||
|
}
|
||||||
|
} on FileSystemException {
|
||||||
|
// Deleted mid-pass (note removed, cache cleared): nothing left to
|
||||||
|
// upload. A surviving marker is skipped by the check above next time.
|
||||||
|
continue;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for (final ref in pass.referenced) {
|
for (final ref in pass.referenced) {
|
||||||
|
|||||||
@ -1,8 +1,10 @@
|
|||||||
// coverage:ignore-file
|
// coverage:ignore-file
|
||||||
// App bootstrap: opens the platform's note store and calls runApp. Exercised
|
// App bootstrap: opens the platform's note store and calls runApp. Exercised
|
||||||
// end-to-end by running the app, not unit tests.
|
// end-to-end by running the app, not unit tests.
|
||||||
|
import 'package:crdt_sync_flutter/crdt_sync_flutter.dart'
|
||||||
|
show AppErrors, AppErrorsConfig, AppErrorsRouteObserver, installAppErrors;
|
||||||
import 'package:design_system/design_system.dart';
|
import 'package:design_system/design_system.dart';
|
||||||
import 'package:flutter/material.dart';
|
import 'package:material_ui/material_ui.dart';
|
||||||
import 'package:todo/analytics/analytics_service.dart';
|
import 'package:todo/analytics/analytics_service.dart';
|
||||||
import 'package:todo/attachments/image_store.dart';
|
import 'package:todo/attachments/image_store.dart';
|
||||||
import 'package:todo/attachments/image_store_scope.dart';
|
import 'package:todo/attachments/image_store_scope.dart';
|
||||||
@ -10,16 +12,36 @@ import 'package:todo/data/app_settings.dart';
|
|||||||
import 'package:todo/data/note_repository.dart';
|
import 'package:todo/data/note_repository.dart';
|
||||||
import 'package:todo/data/repository_factory.dart';
|
import 'package:todo/data/repository_factory.dart';
|
||||||
import 'package:todo/frame_stats.dart';
|
import 'package:todo/frame_stats.dart';
|
||||||
|
import 'package:todo/sync/firebase_client.dart' show openFirebase;
|
||||||
import 'package:todo/ui/capture_screen.dart';
|
import 'package:todo/ui/capture_screen.dart';
|
||||||
|
import 'package:todo/ui/text_free_localizations.dart';
|
||||||
|
|
||||||
Future<void> main() async {
|
Future<void> main() async {
|
||||||
WidgetsFlutterBinding.ensureInitialized();
|
WidgetsFlutterBinding.ensureInitialized();
|
||||||
|
// Every error and every wait over 1 s goes to the PC's app-errors ingest,
|
||||||
|
// which files a board ticket (kuhyx/utils DOCS-app-errors.md). The release
|
||||||
|
// build passes the versionCode and name as dart-defines (release-apk.yml).
|
||||||
|
final errors = await installAppErrors(
|
||||||
|
const AppErrorsConfig(
|
||||||
|
app: 'todo',
|
||||||
|
repo: 'kuhyx/todo-app',
|
||||||
|
package: 'todo',
|
||||||
|
// 0 unless the build passes --dart-define=APP_BUILD.
|
||||||
|
// ignore: avoid_redundant_argument_values
|
||||||
|
build: int.fromEnvironment('APP_BUILD'),
|
||||||
|
version: String.fromEnvironment('APP_VERSION'),
|
||||||
|
),
|
||||||
|
);
|
||||||
installFrameStats();
|
installFrameStats();
|
||||||
|
|
||||||
// Where the log lives, and whether a legacy sqlite DB needs importing, is
|
// Where the log lives, and whether a legacy sqlite DB needs importing, is
|
||||||
// platform-specific and resolved by a conditional import: `dart:io` cannot be
|
// platform-specific and resolved by a conditional import: `dart:io` cannot be
|
||||||
// imported at all in a web compile, and the desktop app is now a web build.
|
// imported at all in a web compile, and the desktop app is now a web build.
|
||||||
final repository = await openRepository();
|
final repository = await openRepository();
|
||||||
|
errors.connect(
|
||||||
|
sink: () async => (await openFirebase())?.patchValues,
|
||||||
|
deviceId: () async => repository.nodeId,
|
||||||
|
);
|
||||||
final appSettings = ValueNotifier(await AppSettings.load());
|
final appSettings = ValueNotifier(await AppSettings.load());
|
||||||
final analytics = AnalyticsService(nodeId: repository.nodeId);
|
final analytics = AnalyticsService(nodeId: repository.nodeId);
|
||||||
// App storage + direct dufs on Android; the wrapper's /images on desktop.
|
// App storage + direct dufs on Android; the wrapper's /images on desktop.
|
||||||
@ -31,6 +53,7 @@ Future<void> main() async {
|
|||||||
appSettings: appSettings,
|
appSettings: appSettings,
|
||||||
analytics: analytics,
|
analytics: analytics,
|
||||||
imageStore: imageStore,
|
imageStore: imageStore,
|
||||||
|
errors: errors,
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@ -45,6 +68,7 @@ class TodoApp extends StatelessWidget {
|
|||||||
required this.appSettings,
|
required this.appSettings,
|
||||||
required this.analytics,
|
required this.analytics,
|
||||||
required this.imageStore,
|
required this.imageStore,
|
||||||
|
this.errors,
|
||||||
super.key,
|
super.key,
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -62,6 +86,9 @@ class TodoApp extends StatelessWidget {
|
|||||||
/// The single, app-wide store for attached images.
|
/// The single, app-wide store for attached images.
|
||||||
final ImageStore imageStore;
|
final ImageStore imageStore;
|
||||||
|
|
||||||
|
/// App-wide error reporting; null in widget tests.
|
||||||
|
final AppErrors? errors;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
// Above MaterialApp so pushed routes (note detail) see it too.
|
// Above MaterialApp so pushed routes (note detail) see it too.
|
||||||
@ -69,8 +96,12 @@ class TodoApp extends StatelessWidget {
|
|||||||
store: imageStore,
|
store: imageStore,
|
||||||
child: MaterialApp(
|
child: MaterialApp(
|
||||||
title: 'todo',
|
title: 'todo',
|
||||||
|
localizationsDelegates: kTextFreeLocalizations,
|
||||||
theme: buildLightTheme(),
|
theme: buildLightTheme(),
|
||||||
darkTheme: buildDarkTheme(),
|
darkTheme: buildDarkTheme(),
|
||||||
|
navigatorObservers: [
|
||||||
|
if (errors case final errors?) AppErrorsRouteObserver(errors),
|
||||||
|
],
|
||||||
home: CaptureScreen(
|
home: CaptureScreen(
|
||||||
repository: repository,
|
repository: repository,
|
||||||
appSettings: appSettings,
|
appSettings: appSettings,
|
||||||
|
|||||||
167
lib/mcp/board_client.dart
Normal file
@ -0,0 +1,167 @@
|
|||||||
|
/// The todoImplementer board as `add_task new_note` sees it: whether a
|
||||||
|
/// note has a session running, and a Start click on a merged task. Start
|
||||||
|
/// goes through the board's own page (CSRF meta tag, same Origin), so the
|
||||||
|
/// board needs no new endpoint. Failures come back as reasons, never throws:
|
||||||
|
/// a board that is down must not lose the task that was just saved.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'dart:async';
|
||||||
|
import 'dart:convert';
|
||||||
|
|
||||||
|
import 'package:http/http.dart' as http;
|
||||||
|
|
||||||
|
/// Where the board listens (loopback only).
|
||||||
|
final Uri kBoardBase = Uri.parse('http://127.0.0.1:8786');
|
||||||
|
|
||||||
|
/// A Start attempt: the item started, or why not.
|
||||||
|
typedef StartResult = ({bool ok, String? reason, String? item});
|
||||||
|
|
||||||
|
final _csrf = RegExp(r'<meta\s+name="todoimpl-csrf"\s+content="([^"]+)"');
|
||||||
|
|
||||||
|
/// Talks to the board over [client] at [base].
|
||||||
|
class BoardClient {
|
||||||
|
/// [client] is injectable so tests need no network. [wait] bounds how
|
||||||
|
/// long Start waits for the board to see a merged section (its note cache
|
||||||
|
/// lags ~10 s, T1863) and to confirm a Start whose reply outran
|
||||||
|
/// [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;
|
||||||
|
|
||||||
|
final http.Client _http;
|
||||||
|
|
||||||
|
/// The board's origin; also the `Origin` header of a POST.
|
||||||
|
final Uri base;
|
||||||
|
|
||||||
|
/// Longest wait for the board to catch up with the note.
|
||||||
|
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 {
|
||||||
|
final res = await _http.get(base.resolve('/api/board')).timeout(_timeout);
|
||||||
|
if (res.statusCode != 200) {
|
||||||
|
throw http.ClientException('GET /api/board ${res.statusCode}');
|
||||||
|
}
|
||||||
|
final tasks = _json(res)['tasks'];
|
||||||
|
final prefix = '${noteId.substring(0, 8)}-';
|
||||||
|
return [
|
||||||
|
for (final t in (tasks as List).cast<Map<String, dynamic>>())
|
||||||
|
if ((t['id']! as String).startsWith(prefix)) t,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether any item of the note is in the board's Running column; false
|
||||||
|
/// when the board cannot be reached.
|
||||||
|
Future<bool> running(String noteId) async {
|
||||||
|
try {
|
||||||
|
return (await _cards(noteId)).any((c) => c['column'] == 'running');
|
||||||
|
} on Object {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Clicks Start on the note's last startable item titled [title]. With
|
||||||
|
/// [sections], that is the note's last section (`<id8>-<sections - 1>`),
|
||||||
|
/// which a merge just added: waits until the board shows it.
|
||||||
|
Future<StartResult> start(
|
||||||
|
String noteId,
|
||||||
|
String title, {
|
||||||
|
int? sections,
|
||||||
|
}) async {
|
||||||
|
try {
|
||||||
|
final last = sections == null ? null : _item(noteId, sections - 1);
|
||||||
|
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))
|
||||||
|
.firstOrNull
|
||||||
|
: null;
|
||||||
|
if (card == null) return _no('no startable item');
|
||||||
|
final page = await _http.get(base).timeout(_timeout);
|
||||||
|
final token = _csrf.firstMatch(page.body)?.group(1);
|
||||||
|
if (token == null) return _no('no CSRF token on the board page');
|
||||||
|
final id = card['id']! as String;
|
||||||
|
return await _post(noteId, id, token);
|
||||||
|
} 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(
|
||||||
|
base.resolve('/api/task/$id/start'),
|
||||||
|
headers: {'Origin': base.origin, 'X-Todoimpl-Token': token},
|
||||||
|
)
|
||||||
|
.timeout(startTimeout);
|
||||||
|
} 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);
|
||||||
|
return _no('board refused start: ${res.statusCode} ${_message(res)}');
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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)
|
||||||
|
.cast<Map<String, dynamic>>()
|
||||||
|
.any((a) => a['id'] == 'start' && a['enabled'] == true);
|
||||||
|
|
||||||
|
static String _message(http.Response res) {
|
||||||
|
try {
|
||||||
|
final error = _json(res)['error'];
|
||||||
|
return (error as Map<String, dynamic>)['message'] as String;
|
||||||
|
} on Object {
|
||||||
|
return res.body;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The board's JSON is UTF-8 whatever the Content-Type says.
|
||||||
|
static Map<String, dynamic> _json(http.Response res) =>
|
||||||
|
jsonDecode(utf8.decode(res.bodyBytes)) as Map<String, dynamic>;
|
||||||
|
|
||||||
|
static StartResult _no(String reason) =>
|
||||||
|
(ok: false, reason: reason, item: null);
|
||||||
|
}
|
||||||
49
lib/mcp/mcp_main.dart
Normal file
@ -0,0 +1,49 @@
|
|||||||
|
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/board_client.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, board: BoardClient()),
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
40
lib/mcp/request_guard.dart
Normal file
@ -0,0 +1,40 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
import 'dart:io';
|
||||||
|
|
||||||
|
/// Answers 503 here because the library can only say 403 for a refusal; it
|
||||||
|
/// then fails to write its own 403 ("Header already sent", swallowed by the
|
||||||
|
/// zone guard in `TodoMcpServer.start`) and the request stays refused.
|
||||||
|
bool answerUnavailable(HttpRequest request) {
|
||||||
|
request.response
|
||||||
|
..statusCode = HttpStatus.serviceUnavailable
|
||||||
|
..write('Service Unavailable')
|
||||||
|
..close().ignore();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Closes [request]'s response with 503 once [deadline] passes, unless it was
|
||||||
|
/// answered first. Safe on any state: a response already closed or a dead
|
||||||
|
/// socket is ignored.
|
||||||
|
void guardDeadline(HttpRequest request, Duration deadline) {
|
||||||
|
if (request.method == 'GET') return;
|
||||||
|
final response = request.response;
|
||||||
|
final timer = Timer(deadline, () async {
|
||||||
|
try {
|
||||||
|
response
|
||||||
|
..statusCode = HttpStatus.serviceUnavailable
|
||||||
|
..write('Request timed out');
|
||||||
|
} on Object {
|
||||||
|
// Headers already sent: just end the stream.
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
await response.close();
|
||||||
|
} on Object {
|
||||||
|
// The peer is gone; the socket is released either way.
|
||||||
|
}
|
||||||
|
});
|
||||||
|
unawaited(
|
||||||
|
response.done
|
||||||
|
.then<void>((_) {}, onError: (_) {})
|
||||||
|
.whenComplete(timer.cancel),
|
||||||
|
);
|
||||||
|
}
|
||||||
246
lib/mcp/task_service.dart
Normal file
@ -0,0 +1,246 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
|
||||||
|
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:todo/data/repo_note.dart';
|
||||||
|
import 'package:todo/mcp/board_client.dart';
|
||||||
|
import 'package:todo/mcp/task_split.dart';
|
||||||
|
import 'package:todo/sync/sync_service.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.
|
||||||
|
/// [board] is the todoImplementer board `new_note` checks and starts on.
|
||||||
|
///
|
||||||
|
/// A call that outlives [callTimeout] (a sync stuck on a dead connection)
|
||||||
|
/// fails with a TimeoutException instead of holding every later call, so
|
||||||
|
/// the queue never wedges and abandoned requests do not pile up sockets.
|
||||||
|
TaskService(
|
||||||
|
this._session, {
|
||||||
|
this._board,
|
||||||
|
this.callTimeout = const Duration(seconds: 60),
|
||||||
|
this.readFreshness = const Duration(seconds: 2),
|
||||||
|
});
|
||||||
|
|
||||||
|
final CliSession _session;
|
||||||
|
final BoardClient? _board;
|
||||||
|
|
||||||
|
/// Longest one call may run before it fails with a TimeoutException.
|
||||||
|
final Duration callTimeout;
|
||||||
|
|
||||||
|
/// How long a finished sync still counts for the read calls (list, search,
|
||||||
|
/// get). The board reads 15 times per fetch and each sync is a Firebase
|
||||||
|
/// round trip of 0.5-1 s, so reads inside the window skip it; every write
|
||||||
|
/// still pulls and pushes. [Duration.zero] syncs on every read.
|
||||||
|
final Duration readFreshness;
|
||||||
|
final Stopwatch _since = Stopwatch();
|
||||||
|
Future<void> _tail = Future.value();
|
||||||
|
|
||||||
|
Future<T> _serial<T>(Future<T> Function() body) {
|
||||||
|
final run = _tail.then((_) => body()).timeout(callTimeout);
|
||||||
|
_tail = run.then((_) {}, onError: (_) {});
|
||||||
|
return run;
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<SyncResult> _sync() async {
|
||||||
|
final result = await _session.sync(push: true);
|
||||||
|
_since
|
||||||
|
..reset()
|
||||||
|
..start();
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Pulls every peer, unless [read] and a sync ended within [readFreshness].
|
||||||
|
Future<List<Note>> _pull({bool read = false}) async {
|
||||||
|
final fresh = _since.isRunning && _since.elapsed < readFreshness;
|
||||||
|
if (!read || !fresh) {
|
||||||
|
final skipped = (await _sync()).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 _sync();
|
||||||
|
return '$verb ${note.id}\n${listLine(note)}';
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<Note> _find(_Args a, {bool read = false}) async {
|
||||||
|
final id = a.required('id');
|
||||||
|
try {
|
||||||
|
return findNote(await _pull(read: read), id);
|
||||||
|
} on NoteLookupError catch (e) {
|
||||||
|
throw FormatException('id: $e');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `add_task`: joins the repo's open note (by: claude), or creates it. A
|
||||||
|
/// board Start after a merge runs once the other calls may go again.
|
||||||
|
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 repo = a.repo(required: true)!;
|
||||||
|
final title = a.required('title');
|
||||||
|
await _pull();
|
||||||
|
if (a.flag('new_note')) {
|
||||||
|
return await addSplit(
|
||||||
|
_session.repository,
|
||||||
|
_board,
|
||||||
|
_save,
|
||||||
|
repo: repo,
|
||||||
|
title: title,
|
||||||
|
body: a.optional('body') ?? '',
|
||||||
|
doneCheck: a.optional('done_check'),
|
||||||
|
priority: a.priority() ?? Priority.medium,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
final added = await addRepoTask(
|
||||||
|
_session.repository,
|
||||||
|
repo: repo,
|
||||||
|
title: title,
|
||||||
|
body: a.optional('body') ?? '',
|
||||||
|
doneCheck: a.optional('done_check'),
|
||||||
|
priority: a.priority() ?? Priority.medium,
|
||||||
|
by: 'claude',
|
||||||
|
createdBy: 'claude',
|
||||||
|
);
|
||||||
|
final verb = added.appended ? 'appended to' : 'added';
|
||||||
|
return (reply: await _save(added.note, verb), start: null);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `list_tasks`: repo tasks, open ones unless `status` says otherwise;
|
||||||
|
/// `no_repo: true` lists the repo-less notes (ideas) instead.
|
||||||
|
Future<String> list(Map<String, dynamic> args) => _serial(() async {
|
||||||
|
final a = _Args(args);
|
||||||
|
final repo = a.repo();
|
||||||
|
final statuses = a.statuses();
|
||||||
|
final ideas = a.flag('no_repo');
|
||||||
|
await _pull(read: true);
|
||||||
|
final notes = await _session.repository.listNotes(
|
||||||
|
filter: NoteFilter(statuses: statuses, repo: repo, repoTasksOnly: !ideas),
|
||||||
|
);
|
||||||
|
return _lines(ideas ? notes.where((n) => n.repo == null).toList() : notes);
|
||||||
|
});
|
||||||
|
|
||||||
|
/// `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(read: true);
|
||||||
|
return _lines(
|
||||||
|
await _session.repository.listNotes(
|
||||||
|
filter: NoteFilter(query: query, repoTasksOnly: true),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
/// `get_task`: one note in full.
|
||||||
|
Future<String> get(Map<String, dynamic> args) =>
|
||||||
|
_serial(() async => noteDetail(await _find(_Args(args), read: true)));
|
||||||
|
|
||||||
|
/// `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);
|
||||||
|
|
||||||
|
bool flag(String name) => switch (_args[name]) {
|
||||||
|
null || false => false,
|
||||||
|
true => true,
|
||||||
|
_ => throw FormatException('$name: must be a boolean'),
|
||||||
|
};
|
||||||
|
|
||||||
|
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"',
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
67
lib/mcp/task_split.dart
Normal file
@ -0,0 +1,67 @@
|
|||||||
|
/// `add_task` with `new_note: true`: the separate note, the guard merge and
|
||||||
|
/// the board Start that follows a merge, as one reply text.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:todo/data/note.dart';
|
||||||
|
import 'package:todo/data/note_repository.dart';
|
||||||
|
import 'package:todo/data/repo_note_split.dart';
|
||||||
|
import 'package:todo/mcp/board_client.dart';
|
||||||
|
|
||||||
|
/// Saves [note] and returns `<verb> <id>` plus its list line.
|
||||||
|
typedef SaveNote = Future<String> Function(Note note, String verb);
|
||||||
|
|
||||||
|
/// A saved split add: its reply so far, and the board Start still to run.
|
||||||
|
/// The caller runs [start] after releasing its lock, since the board learns
|
||||||
|
/// about the merged section by calling this same server (T1865).
|
||||||
|
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,
|
||||||
|
BoardClient? board,
|
||||||
|
SaveNote save, {
|
||||||
|
required String repo,
|
||||||
|
required String title,
|
||||||
|
required String body,
|
||||||
|
required String? doneCheck,
|
||||||
|
required Priority priority,
|
||||||
|
}) async {
|
||||||
|
final added = await addSeparateTask(
|
||||||
|
repository,
|
||||||
|
repo: repo,
|
||||||
|
title: title,
|
||||||
|
body: body,
|
||||||
|
doneCheck: doneCheck,
|
||||||
|
priority: priority,
|
||||||
|
by: 'claude',
|
||||||
|
createdBy: 'claude',
|
||||||
|
busy: board == null ? null : (n) => board.running(n.id),
|
||||||
|
);
|
||||||
|
if (added.kind != SplitKind.merged) {
|
||||||
|
final reply = await save(added.note, 'added');
|
||||||
|
return (
|
||||||
|
reply: added.why == null ? reply : '$reply\n${added.why}',
|
||||||
|
start: null,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
final reply = await save(added.note, 'merged into');
|
||||||
|
final block = startBlock(doneCheck, body);
|
||||||
|
if (block != null) {
|
||||||
|
return (reply: '$reply\nstart: skipped ($block)', start: null);
|
||||||
|
}
|
||||||
|
Future<String> start() async {
|
||||||
|
final s = board == null
|
||||||
|
? (ok: false, reason: 'no board configured', item: null)
|
||||||
|
: await board.start(
|
||||||
|
added.note.id,
|
||||||
|
title.trim(),
|
||||||
|
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';
|
||||||
|
}
|
||||||
|
|
||||||
|
return (reply: reply, start: start);
|
||||||
|
}
|
||||||
221
lib/mcp/todo_mcp_server.dart
Normal file
@ -0,0 +1,221 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
import 'dart:io';
|
||||||
|
|
||||||
|
import 'package:mcp_dart/mcp_dart.dart';
|
||||||
|
import 'package:todo/mcp/request_guard.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.
|
||||||
|
- A repo has ONE open note, "<repo> todos", holding all its tasks as
|
||||||
|
"## title" sections. add_task appends to it (or creates it) and returns its id.
|
||||||
|
- 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.
|
||||||
|
Done checks of appended tasks are joined with &&.
|
||||||
|
- 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 loaded once and
|
||||||
|
/// re-read when its mtime changes, errors going to [log] (default stderr).
|
||||||
|
///
|
||||||
|
/// A POST or DELETE that has no answer after [requestDeadline] is closed
|
||||||
|
/// with 503, which also frees its socket when the client already gave up
|
||||||
|
/// (Dart's HttpServer never notices a half-closed idle request). Keep it
|
||||||
|
/// above [TaskService.callTimeout] so a stuck tool call reports its own
|
||||||
|
/// error first. GET streams are long-lived by design and exempt.
|
||||||
|
static Future<TodoMcpServer> start({
|
||||||
|
required TaskService tasks,
|
||||||
|
required File tokens,
|
||||||
|
String host = '127.0.0.1',
|
||||||
|
int port = kTodoMcpPort,
|
||||||
|
Duration requestDeadline = const Duration(seconds: 90),
|
||||||
|
void Function(String)? log,
|
||||||
|
}) async {
|
||||||
|
final out = log ?? (String line) => stderr.writeln(line);
|
||||||
|
final store = TokenStore(tokens, log: out);
|
||||||
|
final http = StreamableMcpServer(
|
||||||
|
serverFactory: (_) => _server(tasks),
|
||||||
|
host: host,
|
||||||
|
port: port,
|
||||||
|
authenticator: (request) {
|
||||||
|
if (request is! HttpRequest) return false;
|
||||||
|
guardDeadline(request, requestDeadline);
|
||||||
|
return switch (store.verdict(
|
||||||
|
request.headers.value(HttpHeaders.authorizationHeader),
|
||||||
|
)) {
|
||||||
|
TokenVerdict.accepted => true,
|
||||||
|
TokenVerdict.rejected => false,
|
||||||
|
TokenVerdict.unavailable => answerUnavailable(request),
|
||||||
|
};
|
||||||
|
},
|
||||||
|
allowedHosts: const {'localhost', '127.0.0.1', '::1', _publicHost},
|
||||||
|
);
|
||||||
|
// The library runs each request as an unawaited future in the zone that
|
||||||
|
// called start(): without a guard, one failed write (a response we closed
|
||||||
|
// first) would be an uncaught error and kill the process.
|
||||||
|
await runZonedGuarded(http.start, (error, stack) {
|
||||||
|
if (error is StateError && '$error'.contains('Header already sent')) {
|
||||||
|
return; // the library answering a request we already answered
|
||||||
|
}
|
||||||
|
out('todo-mcp: request error: $error');
|
||||||
|
});
|
||||||
|
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 a task to the repo's single open note (by: claude): appended as a "
|
||||||
|
'"## title" section, or the note is created. Returns "added <full id>" '
|
||||||
|
'or "appended to <full id>", then its list line. Use when you find '
|
||||||
|
'work you will not finish now. With new_note: true the task gets '
|
||||||
|
'its own note ("added"), or, when another separate note of the repo '
|
||||||
|
'already has that exact title, "merged into" that note, followed by '
|
||||||
|
'a "start:" line for the todoImplementer board.',
|
||||||
|
{
|
||||||
|
'repo': repo,
|
||||||
|
'title': JsonSchema.string(description: 'One-line title.'),
|
||||||
|
'body': JsonSchema.string(description: 'Markdown: what/where/verify.'),
|
||||||
|
'done_check': doneCheck,
|
||||||
|
'priority': priority,
|
||||||
|
'new_note': JsonSchema.boolean(
|
||||||
|
description: 'Own note instead of joining the shared one.',
|
||||||
|
),
|
||||||
|
},
|
||||||
|
['repo', 'title'],
|
||||||
|
tasks.add,
|
||||||
|
);
|
||||||
|
tool(
|
||||||
|
'list_tasks',
|
||||||
|
'List repo tasks, one line each: 8-char id, status, priority, repo, '
|
||||||
|
'title, created_by (kuhy|claude). Default status "open" '
|
||||||
|
'(todo + in_progress). no_repo: true lists the notes WITHOUT a repo '
|
||||||
|
'(ideas) instead.',
|
||||||
|
{
|
||||||
|
'repo': repo,
|
||||||
|
'no_repo': JsonSchema.boolean(
|
||||||
|
description: 'List only notes that have no repo (repo shows as -).',
|
||||||
|
),
|
||||||
|
'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);
|
||||||
82
lib/mcp/token_file.dart
Normal file
@ -0,0 +1,82 @@
|
|||||||
|
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);
|
||||||
|
|
||||||
|
/// What the tokens file says about one `Authorization` header.
|
||||||
|
enum TokenVerdict {
|
||||||
|
/// A listed token: let the request in.
|
||||||
|
accepted,
|
||||||
|
|
||||||
|
/// Missing, malformed or unlisted: HTTP 403.
|
||||||
|
rejected,
|
||||||
|
|
||||||
|
/// No token set has ever loaded, so nothing can be judged: HTTP 503.
|
||||||
|
unavailable,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The sha256-hashed bearer tokens of [file], loaded once.
|
||||||
|
///
|
||||||
|
/// A request costs one `stat`; the file is re-read only when its mtime or
|
||||||
|
/// size changed. A failed read keeps the last good set (an exhausted fd table
|
||||||
|
/// once made every valid token read as "no tokens", i.e. 403) and is logged
|
||||||
|
/// once per distinct error. Until a first good load every well-formed bearer
|
||||||
|
/// is [TokenVerdict.unavailable], never a refusal.
|
||||||
|
class TokenStore {
|
||||||
|
/// Watches [file]; [log] gets read errors.
|
||||||
|
TokenStore(this.file, {required this.log});
|
||||||
|
|
||||||
|
/// The `<sha256> <name>` lines, `#` comments allowed.
|
||||||
|
final File file;
|
||||||
|
|
||||||
|
/// Receives read errors, one line each.
|
||||||
|
final void Function(String) log;
|
||||||
|
|
||||||
|
Set<String>? _hashes;
|
||||||
|
(DateTime, int)? _seen;
|
||||||
|
String? _lastError;
|
||||||
|
|
||||||
|
/// Judges [authorization] (an `Authorization` header value or null).
|
||||||
|
TokenVerdict verdict(String? authorization) {
|
||||||
|
const scheme = 'bearer ';
|
||||||
|
if (authorization == null ||
|
||||||
|
!authorization.toLowerCase().startsWith(scheme)) {
|
||||||
|
return TokenVerdict.rejected;
|
||||||
|
}
|
||||||
|
final token = authorization.substring(scheme.length).trim();
|
||||||
|
if (token.isEmpty) return TokenVerdict.rejected;
|
||||||
|
_refresh();
|
||||||
|
final hashes = _hashes;
|
||||||
|
if (hashes == null) return TokenVerdict.unavailable;
|
||||||
|
return hashes.contains(tokenHash(token))
|
||||||
|
? TokenVerdict.accepted
|
||||||
|
: TokenVerdict.rejected;
|
||||||
|
}
|
||||||
|
|
||||||
|
void _refresh() {
|
||||||
|
try {
|
||||||
|
final stat = file.statSync();
|
||||||
|
if (stat.type == FileSystemEntityType.notFound) {
|
||||||
|
throw FileSystemException('no such file', file.path);
|
||||||
|
}
|
||||||
|
final key = (stat.modified, stat.size);
|
||||||
|
if (key == _seen) return;
|
||||||
|
_hashes = _parse(file.readAsStringSync());
|
||||||
|
_seen = key;
|
||||||
|
_lastError = null;
|
||||||
|
} on FileSystemException catch (e) {
|
||||||
|
// Keep the last good set; `_seen` stays, so the next request retries.
|
||||||
|
final message = '${e.message} ${e.path} ${e.osError?.errorCode}';
|
||||||
|
if (message != _lastError) log('tokens: keeping last set: $message');
|
||||||
|
_lastError = message;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static Set<String> _parse(String text) => {
|
||||||
|
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(),
|
||||||
|
};
|
||||||
|
}
|
||||||
9
lib/sync/e2e_passphrase_path.dart
Normal file
@ -0,0 +1,9 @@
|
|||||||
|
/// Path of the wrapper's one-shot passphrase route.
|
||||||
|
///
|
||||||
|
/// Kept apart from `e2e_passphrase_source.dart` (which needs Flutter) so the
|
||||||
|
/// dart-only desktop wrapper can import it; `dart build cli` fails on any
|
||||||
|
/// transitive `dart:ui`.
|
||||||
|
library;
|
||||||
|
|
||||||
|
/// The route the wrapper serves the passphrase on, once.
|
||||||
|
const kSyncE2ePassphrasePath = '/sync-e2e-passphrase';
|
||||||
38
lib/sync/e2e_passphrase_source.dart
Normal file
@ -0,0 +1,38 @@
|
|||||||
|
/// Where todo gets the shared crdt-sync passphrase its E2E key comes from.
|
||||||
|
///
|
||||||
|
/// The keystore first. On the desktop (a web build behind the local
|
||||||
|
/// wrapper) an empty keystore adopts the wrapper's one-shot
|
||||||
|
/// `/sync-e2e-passphrase` route, which serves `~/.config/crdt-sync/password`,
|
||||||
|
/// so the desktop app never asks. Android has no wrapper (`Uri.base` is
|
||||||
|
/// `file:///`) and is unlocked through the settings lock tile instead.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:crdt_sync_flutter/crdt_sync_flutter.dart'
|
||||||
|
show kE2ePassphraseKey, kSecureStorage, saveE2ePassphrase;
|
||||||
|
import 'package:http/http.dart' as http;
|
||||||
|
import 'package:todo/sync/e2e_passphrase_path.dart';
|
||||||
|
|
||||||
|
export 'package:todo/sync/e2e_passphrase_path.dart';
|
||||||
|
|
||||||
|
/// Returns the passphrase, adopting the wrapper's once; null when none.
|
||||||
|
Future<String?> readE2ePassphrase({Uri? base, http.Client? client}) async {
|
||||||
|
final stored = await kSecureStorage.read(key: kE2ePassphraseKey);
|
||||||
|
if (stored != null && stored.isNotEmpty) return stored;
|
||||||
|
final origin = base ?? Uri.base;
|
||||||
|
if (origin.scheme != 'http' && origin.scheme != 'https') return null;
|
||||||
|
final httpClient = client ?? http.Client();
|
||||||
|
try {
|
||||||
|
final response = await httpClient.get(
|
||||||
|
origin.resolve(kSyncE2ePassphrasePath),
|
||||||
|
);
|
||||||
|
final text = response.body.trim();
|
||||||
|
if (response.statusCode != 200 || text.isEmpty) return null;
|
||||||
|
await saveE2ePassphrase(text);
|
||||||
|
return text;
|
||||||
|
} on Object {
|
||||||
|
// No wrapper, or it already served: this device is simply locked.
|
||||||
|
return null;
|
||||||
|
} finally {
|
||||||
|
if (client == null) httpClient.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -1,6 +1,6 @@
|
|||||||
/// Whether the programmatic Google sign-in flow exists on this platform.
|
/// Whether the programmatic Google sign-in flow exists on this platform.
|
||||||
///
|
///
|
||||||
/// The io half: Android has the Credential Manager flow; Linux desktop does
|
/// The io half: Android has the AccountManager flow; Linux desktop does
|
||||||
/// not, and this app's desktop build is the web one anyway.
|
/// not, and this app's desktop build is the web one anyway.
|
||||||
library;
|
library;
|
||||||
|
|
||||||
|
|||||||
@ -2,9 +2,9 @@
|
|||||||
///
|
///
|
||||||
/// Why this is its own file: `crdt_sync` is deliberately pure Dart (only
|
/// Why this is its own file: `crdt_sync` is deliberately pure Dart (only
|
||||||
/// `crypto` and `http`), because the same library runs on Linux desktop and
|
/// `crypto` and `http`), because the same library runs on Linux desktop and
|
||||||
/// headless under systemd, where `google_sign_in` does not exist. So the
|
/// headless under systemd, where Android's AccountManager does not exist. So
|
||||||
/// plugin lives here, in the app, and the library only ever receives a token
|
/// the platform channel lives in the google_account_token plugin, and the
|
||||||
/// string through a closure.
|
/// library only ever receives a token string through a closure.
|
||||||
///
|
///
|
||||||
/// What this buys: on a fresh install the sync account is reached by tapping
|
/// What this buys: on a fresh install the sync account is reached by tapping
|
||||||
/// one account-picker row instead of typing a long password on a phone
|
/// one account-picker row instead of typing a long password on a phone
|
||||||
@ -14,7 +14,7 @@ library;
|
|||||||
|
|
||||||
import 'dart:developer';
|
import 'dart:developer';
|
||||||
|
|
||||||
import 'package:google_sign_in/google_sign_in.dart';
|
import 'package:google_account_token/google_account_token.dart' as plugin;
|
||||||
import 'package:todo/sync/google_platform.dart' as platform_gate;
|
import 'package:todo/sync/google_platform.dart' as platform_gate;
|
||||||
|
|
||||||
/// The account the security rules pin.
|
/// The account the security rules pin.
|
||||||
@ -78,7 +78,7 @@ Future<String?> googleIdToken({
|
|||||||
if (signInFn != null) return await signInFn();
|
if (signInFn != null) return await signInFn();
|
||||||
if (serverClientId.isEmpty) {
|
if (serverClientId.isEmpty) {
|
||||||
// A build without --dart-define=GOOGLE_SERVER_CLIENT_ID would otherwise
|
// A build without --dart-define=GOOGLE_SERVER_CLIENT_ID would otherwise
|
||||||
// fail inside the plugin with a far less obvious message.
|
// fail on the platform side with a far less obvious message.
|
||||||
log(
|
log(
|
||||||
'Google sign-in unavailable: GOOGLE_SERVER_CLIENT_ID was not set at '
|
'Google sign-in unavailable: GOOGLE_SERVER_CLIENT_ID was not set at '
|
||||||
'build time; falling back to the password path',
|
'build time; falling back to the password path',
|
||||||
@ -86,37 +86,5 @@ Future<String?> googleIdToken({
|
|||||||
);
|
);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
// The plugin reaches the OS account picker through a platform channel,
|
return await plugin.googleIdToken(serverClientId: serverClientId);
|
||||||
// which `flutter test` has no binding for -- the same reason main.dart and
|
|
||||||
// firebase_backend.dart's keystore adapters are excluded. Everything above
|
|
||||||
// this point is pure Dart and is covered.
|
|
||||||
// coverage:ignore-start
|
|
||||||
try {
|
|
||||||
await GoogleSignIn.instance.initialize(serverClientId: serverClientId);
|
|
||||||
if (!GoogleSignIn.instance.supportsAuthenticate()) {
|
|
||||||
// Web/desktop: sign-in must go through the rendered GIS button, which
|
|
||||||
// this app does not host yet. Fall back rather than throwing.
|
|
||||||
log(
|
|
||||||
'Google sign-in is not available on this platform; falling back to '
|
|
||||||
'the password path',
|
|
||||||
level: 900,
|
|
||||||
);
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
final account = await GoogleSignIn.instance.authenticate();
|
|
||||||
return account.authentication.idToken;
|
|
||||||
} on GoogleSignInException catch (error, stackTrace) {
|
|
||||||
// Includes the user simply dismissing the picker, which is not an error
|
|
||||||
// worth surfacing -- but log it, because a *configuration* failure
|
|
||||||
// (unregistered SHA-1, wrong client id) arrives through the same path and
|
|
||||||
// is otherwise indistinguishable from "the user changed their mind".
|
|
||||||
log(
|
|
||||||
'Google sign-in did not complete',
|
|
||||||
level: 900,
|
|
||||||
error: error,
|
|
||||||
stackTrace: stackTrace,
|
|
||||||
);
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
// coverage:ignore-end
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -45,7 +45,8 @@ class NotesMarkdown {
|
|||||||
'<!-- @note id="${note.id}" priority="${note.priority.name}" '
|
'<!-- @note id="${note.id}" priority="${note.priority.name}" '
|
||||||
'status="${note.status.name}" '
|
'status="${note.status.name}" '
|
||||||
'created="${note.createdAt.toIso8601String()}" '
|
'created="${note.createdAt.toIso8601String()}" '
|
||||||
'updated="${note.updatedAt.toIso8601String()}" -->',
|
'updated="${note.updatedAt.toIso8601String()}"'
|
||||||
|
'${_taskAttrs(note)} -->',
|
||||||
)
|
)
|
||||||
..writeln(toBacklogAttachmentPaths(note.text))
|
..writeln(toBacklogAttachmentPaths(note.text))
|
||||||
..writeln();
|
..writeln();
|
||||||
@ -87,19 +88,58 @@ class NotesMarkdown {
|
|||||||
DateTime.tryParse(attrs['created'] ?? '') ?? DateTime.now(),
|
DateTime.tryParse(attrs['created'] ?? '') ?? DateTime.now(),
|
||||||
updatedAt:
|
updatedAt:
|
||||||
DateTime.tryParse(attrs['updated'] ?? '') ?? DateTime.now(),
|
DateTime.tryParse(attrs['updated'] ?? '') ?? DateTime.now(),
|
||||||
|
repo: attrs['repo'],
|
||||||
|
doneCheck: attrs['done_check'],
|
||||||
|
by: attrs['by'],
|
||||||
|
evidence: attrs['evidence'],
|
||||||
|
createdBy: attrs['created_by'],
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
return notes;
|
return notes;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Extracts `key="value"` pairs from a marker's attribute string.
|
/// Extracts `key="value"` pairs; an empty value counts as absent.
|
||||||
static Map<String, String> _parseAttrs(String raw) {
|
static Map<String, String> _parseAttrs(String raw) {
|
||||||
return {
|
return {
|
||||||
for (final m in _attrPattern.allMatches(raw)) m.group(1)!: m.group(2)!,
|
for (final m in _attrPattern.allMatches(raw))
|
||||||
|
if (m.group(2)!.isNotEmpty) m.group(1)!: _unescape(m.group(2)!),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Set task fields only, so an idea's marker is unchanged from v3.
|
||||||
|
static String _taskAttrs(Note note) => [
|
||||||
|
for (final (name, value) in [
|
||||||
|
('repo', note.repo),
|
||||||
|
('done_check', note.doneCheck),
|
||||||
|
('by', note.by),
|
||||||
|
('evidence', note.evidence),
|
||||||
|
('created_by', note.createdBy),
|
||||||
|
])
|
||||||
|
if (value != null) ' $name="${_escape(value)}"',
|
||||||
|
].join();
|
||||||
|
|
||||||
|
// Entities keep a value on one line, inside its quotes and the comment.
|
||||||
|
static const _entities = {
|
||||||
|
'&': '&',
|
||||||
|
'"': '"',
|
||||||
|
'<': '<',
|
||||||
|
'>': '>',
|
||||||
|
'\n': ' ',
|
||||||
|
'\r': ' ',
|
||||||
|
};
|
||||||
|
static final _escapable = RegExp('[&"<>\n\r]');
|
||||||
|
static final _entity = RegExp('&(amp|quot|lt|gt|#10|#13);');
|
||||||
|
static final Map<String, String> _decode = {
|
||||||
|
for (final e in _entities.entries) e.value: e.key,
|
||||||
|
};
|
||||||
|
|
||||||
|
static String _escape(String v) =>
|
||||||
|
v.replaceAllMapped(_escapable, (m) => _entities[m[0]]!);
|
||||||
|
|
||||||
|
static String _unescape(String v) =>
|
||||||
|
v.replaceAllMapped(_entity, (m) => _decode[m[0]]!);
|
||||||
|
|
||||||
/// Resolves an enum value by its [Enum.name], falling back to [fallback].
|
/// Resolves an enum value by its [Enum.name], falling back to [fallback].
|
||||||
static T _enumByName<T extends Enum>(
|
static T _enumByName<T extends Enum>(
|
||||||
List<T> values,
|
List<T> values,
|
||||||
|
|||||||
7
lib/sync/off_thread.dart
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
/// Runs CPU-heavy, pure work away from the UI thread where the platform can.
|
||||||
|
///
|
||||||
|
/// Conditional export because `dart:isolate` does not run in a browser: the
|
||||||
|
/// web desktop build runs the work inline, everything else on a fresh isolate.
|
||||||
|
library;
|
||||||
|
|
||||||
|
export 'off_thread_io.dart' if (dart.library.js_interop) 'off_thread_web.dart';
|
||||||
7
lib/sync/off_thread_io.dart
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
import 'dart:isolate';
|
||||||
|
|
||||||
|
/// Runs [work] on a short-lived isolate and returns its result.
|
||||||
|
///
|
||||||
|
/// The result comes back through `Isolate.exit`, so a large parsed log is
|
||||||
|
/// handed over rather than copied.
|
||||||
|
Future<R> offThread<R>(R Function() work) => Isolate.run(work);
|
||||||
2
lib/sync/off_thread_web.dart
Normal file
@ -0,0 +1,2 @@
|
|||||||
|
/// Runs [work] inline: a browser has no isolates for it.
|
||||||
|
Future<R> offThread<R>(R Function() work) async => work();
|
||||||
78
lib/sync/peer_pull.dart
Normal file
@ -0,0 +1,78 @@
|
|||||||
|
/// Pulls the peers whose logs changed, all at once and off the UI thread.
|
||||||
|
///
|
||||||
|
/// Split out of `sync_service.dart` for file size. A peer's log is about
|
||||||
|
/// 2 MB; pulling eight of them one after another, each parsed on the UI
|
||||||
|
/// isolate, kept the phone's sync spinner up for 3.9 s (todo:0c575b891b).
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
|
import 'package:todo/sync/off_thread.dart';
|
||||||
|
|
||||||
|
/// One peer file's pull result: its decoded [log] and revision, or a null
|
||||||
|
/// [log] when the file vanished, failed decryption or did not parse.
|
||||||
|
typedef PulledPeer = ({String name, String peer, Log? log, String? rev});
|
||||||
|
|
||||||
|
/// Fetches [names] (file names under [dir]) concurrently.
|
||||||
|
///
|
||||||
|
/// [knownRevs] holds each peer's published revision; a peer without one gets
|
||||||
|
/// its revision computed from the downloaded text. Any failure other than an
|
||||||
|
/// [E2eDecryptError] fails the pull, exactly as a sequential loop would.
|
||||||
|
Future<List<PulledPeer>> pullPeers(
|
||||||
|
RemoteStore remote,
|
||||||
|
String dir,
|
||||||
|
List<String> names,
|
||||||
|
Map<String, String> knownRevs,
|
||||||
|
) => Future.wait([
|
||||||
|
for (final name in names) _pull(remote, dir, name, knownRevs[peerOf(name)]),
|
||||||
|
], eagerError: true);
|
||||||
|
|
||||||
|
/// Peer id of a `<peer>.json` file name.
|
||||||
|
String peerOf(String name) =>
|
||||||
|
name.endsWith('.json') ? name.substring(0, name.length - 5) : name;
|
||||||
|
|
||||||
|
Future<PulledPeer> _pull(
|
||||||
|
RemoteStore remote,
|
||||||
|
String dir,
|
||||||
|
String name,
|
||||||
|
String? knownRev,
|
||||||
|
) async {
|
||||||
|
final peer = peerOf(name);
|
||||||
|
final String? text;
|
||||||
|
try {
|
||||||
|
text = await remote.getFileText('$dir/$name');
|
||||||
|
} on E2eDecryptError {
|
||||||
|
// Wrong key, tampered blob or a newer format: skipped and reported,
|
||||||
|
// never merged and never fatal.
|
||||||
|
return (name: name, peer: peer, log: null, rev: null);
|
||||||
|
}
|
||||||
|
if (text == null) return (name: name, peer: peer, log: null, rev: null);
|
||||||
|
final (log, rev) = await _decodeOffThread(text, knownRev);
|
||||||
|
return (name: name, peer: peer, log: log, rev: rev);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Below this many characters a log parses faster than an isolate starts.
|
||||||
|
const int _offThreadMinLength = 64 * 1024;
|
||||||
|
|
||||||
|
/// Kept separate so the isolate closure captures only [text] and [knownRev].
|
||||||
|
Future<(Log?, String)> _decodeOffThread(String text, String? knownRev) async {
|
||||||
|
(Log?, String) decode() => (decodeLog(text), knownRev ?? revisionOf(text));
|
||||||
|
return text.length < _offThreadMinLength ? decode() : await offThread(decode);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Parses a remote note log, returning `null` for a corrupt or wrong-shape
|
||||||
|
/// payload so one bad device file never aborts the whole sync.
|
||||||
|
Log? decodeLog(String text) {
|
||||||
|
try {
|
||||||
|
return logFromJson(text);
|
||||||
|
} on FormatException {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
// crdt_sync's logFromJson throws a raw TypeError (not a custom
|
||||||
|
// exception) for a wrong-shape JSON payload from an untrusted peer
|
||||||
|
// file; must be caught too so one bad device file never aborts the
|
||||||
|
// whole sync (see doc comment above).
|
||||||
|
// ignore: avoid_catching_errors
|
||||||
|
on TypeError {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -7,15 +7,26 @@
|
|||||||
library;
|
library;
|
||||||
|
|
||||||
import 'package:crdt_sync/crdt_sync.dart';
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
|
import 'package:crdt_sync_flutter/crdt_sync_flutter.dart' show keystoreKeyCache;
|
||||||
|
import 'package:flutter/foundation.dart' show ValueNotifier, visibleForTesting;
|
||||||
import 'package:http/http.dart' as http;
|
import 'package:http/http.dart' as http;
|
||||||
import 'package:todo/analytics/analytics_service.dart';
|
import 'package:todo/analytics/analytics_service.dart';
|
||||||
import 'package:todo/data/app_settings.dart';
|
import 'package:todo/data/app_settings.dart';
|
||||||
import 'package:todo/data/note_repository.dart';
|
import 'package:todo/data/note_repository.dart';
|
||||||
|
import 'package:todo/sync/e2e_passphrase_source.dart';
|
||||||
import 'package:todo/sync/firebase_backend.dart';
|
import 'package:todo/sync/firebase_backend.dart';
|
||||||
import 'package:todo/sync/sync_service.dart';
|
import 'package:todo/sync/sync_service.dart';
|
||||||
import 'package:todo/sync/sync_settings.dart';
|
import 'package:todo/sync/sync_settings.dart';
|
||||||
import 'package:todo/sync/sync_state_factory.dart';
|
import 'package:todo/sync/sync_state_factory.dart';
|
||||||
|
|
||||||
|
/// Argon2id cost for new headers; only tests lower it.
|
||||||
|
@visibleForTesting
|
||||||
|
Argon2Params e2eArgon2Params = Argon2Params.recommended;
|
||||||
|
|
||||||
|
/// Whether the last sync found no usable end-to-end key; drives the lock
|
||||||
|
/// tile in settings.
|
||||||
|
final ValueNotifier<bool> e2eLocked = ValueNotifier<bool>(false);
|
||||||
|
|
||||||
/// Bundles a [SyncResult] with the [AppSettings] as reconciled against the
|
/// Bundles a [SyncResult] with the [AppSettings] as reconciled against the
|
||||||
/// same Firebase session — so a settings change made on another device is
|
/// same Firebase session — so a settings change made on another device is
|
||||||
/// picked up without a second authenticated round trip.
|
/// picked up without a second authenticated round trip.
|
||||||
@ -44,8 +55,12 @@ class SyncRunResult {
|
|||||||
/// rather than each concern (notes, settings, analytics) opening and
|
/// rather than each concern (notes, settings, analytics) opening and
|
||||||
/// closing its own.
|
/// closing its own.
|
||||||
///
|
///
|
||||||
/// [firebaseFactory] and [stateStore] exist for tests, which must not reach
|
/// [firebaseFactory], [stateStore] and [readPassphrase] exist for tests, which
|
||||||
/// the OS keystore or an application-support directory.
|
/// must not reach the OS keystore or an application-support directory.
|
||||||
|
///
|
||||||
|
/// Everything pushed is end-to-end encrypted under the shared crdt-sync
|
||||||
|
/// passphrase; without a usable key the run is a no-op flagged
|
||||||
|
/// [SyncResult.locked] rather than a plaintext sync.
|
||||||
Future<SyncRunResult> runSync(
|
Future<SyncRunResult> runSync(
|
||||||
NoteRepository repository,
|
NoteRepository repository,
|
||||||
SyncSettings settings, {
|
SyncSettings settings, {
|
||||||
@ -54,6 +69,7 @@ Future<SyncRunResult> runSync(
|
|||||||
http.Client? httpClient,
|
http.Client? httpClient,
|
||||||
Future<FirebaseRestClient?> Function()? firebaseFactory,
|
Future<FirebaseRestClient?> Function()? firebaseFactory,
|
||||||
SyncStateStore? stateStore,
|
SyncStateStore? stateStore,
|
||||||
|
Future<String?> Function()? readPassphrase,
|
||||||
}) async {
|
}) async {
|
||||||
final github = GitHubClient(
|
final github = GitHubClient(
|
||||||
owner: settings.owner,
|
owner: settings.owner,
|
||||||
@ -72,16 +88,48 @@ Future<SyncRunResult> runSync(
|
|||||||
stateStore: stateStore ?? await openSyncStateStore(),
|
stateStore: stateStore ?? await openSyncStateStore(),
|
||||||
// coverage:ignore-end
|
// coverage:ignore-end
|
||||||
);
|
);
|
||||||
final result = await service.sync(
|
// No GitHub token means nothing to mirror: an unconfigured client still
|
||||||
repository,
|
// spends two round trips per call on 404s.
|
||||||
firebase == null
|
final backend = switch (firebase) {
|
||||||
? github
|
null => github,
|
||||||
: MirrorStore(primary: firebase, mirror: github),
|
_ when !settings.isConfigured => firebase,
|
||||||
|
_ => MirrorStore(primary: firebase, mirror: github),
|
||||||
|
};
|
||||||
|
final e2e = await openEncryptedStore(
|
||||||
|
store: backend,
|
||||||
|
oldPrefix: service.notesDir,
|
||||||
|
readPassphrase: readPassphrase ?? readE2ePassphrase,
|
||||||
|
params: e2eArgon2Params,
|
||||||
|
// Argon2id once per device, not once per tick.
|
||||||
|
keyCache: keystoreKeyCache(service.notesDir),
|
||||||
);
|
);
|
||||||
await analytics?.flush(firebase);
|
e2eLocked.value = e2e is! E2eReady;
|
||||||
|
if (e2e is! E2eReady) {
|
||||||
|
return const SyncRunResult(
|
||||||
|
syncResult: SyncResult(mergedDevices: 0, pushed: false, locked: true),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
final layout = E2eLayout.of(service.notesDir);
|
||||||
|
// Settings and analytics touch other Firebase paths than the notes, so
|
||||||
|
// they ride alongside the note sync instead of after it.
|
||||||
|
final reconciled = appSettings?.reconcileWithRemote(firebase);
|
||||||
|
final flushed = analytics?.flush(firebase);
|
||||||
|
final notes = SyncService(
|
||||||
|
notesDir: layout.prefix,
|
||||||
|
revsPath: layout.revsPath,
|
||||||
|
stateStore: service.stateStore,
|
||||||
|
).sync(repository, e2e.store);
|
||||||
|
final done = await Future.wait<Object?>([
|
||||||
|
notes,
|
||||||
|
?reconciled,
|
||||||
|
?flushed,
|
||||||
|
// Not eager: the clients are closed below, so nothing may still be in
|
||||||
|
// flight when this returns or throws.
|
||||||
|
]);
|
||||||
|
final result = done.first! as SyncResult;
|
||||||
return SyncRunResult(
|
return SyncRunResult(
|
||||||
syncResult: result.withFirebaseConnected(value: firebase != null),
|
syncResult: result.withFirebaseConnected(value: firebase != null),
|
||||||
appSettings: await appSettings?.reconcileWithRemote(firebase),
|
appSettings: await reconciled,
|
||||||
);
|
);
|
||||||
} finally {
|
} finally {
|
||||||
// Close both: unlike the long-lived desktop callers, each screen builds
|
// Close both: unlike the long-lived desktop callers, each screen builds
|
||||||
|
|||||||
@ -1,6 +1,7 @@
|
|||||||
import 'package:crdt_sync/crdt_sync.dart';
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
|
|
||||||
import 'package:todo/data/note_repository.dart';
|
import 'package:todo/data/note_repository.dart';
|
||||||
|
import 'package:todo/sync/peer_pull.dart';
|
||||||
|
|
||||||
/// Outcome of a sync run, for surfacing in the UI.
|
/// Outcome of a sync run, for surfacing in the UI.
|
||||||
class SyncResult {
|
class SyncResult {
|
||||||
@ -11,6 +12,7 @@ class SyncResult {
|
|||||||
this.skippedFiles = const [],
|
this.skippedFiles = const [],
|
||||||
this.skippedUnchanged = 0,
|
this.skippedUnchanged = 0,
|
||||||
this.firebaseConnected = false,
|
this.firebaseConnected = false,
|
||||||
|
this.locked = false,
|
||||||
});
|
});
|
||||||
|
|
||||||
/// How many other devices' logs were pulled and merged.
|
/// How many other devices' logs were pulled and merged.
|
||||||
@ -41,6 +43,10 @@ class SyncResult {
|
|||||||
/// device dropping out.
|
/// device dropping out.
|
||||||
final int skippedUnchanged;
|
final int skippedUnchanged;
|
||||||
|
|
||||||
|
/// True when end-to-end encryption has no usable key on this device, so
|
||||||
|
/// nothing was pulled, merged or pushed.
|
||||||
|
final bool locked;
|
||||||
|
|
||||||
/// Returns a copy with [firebaseConnected] set. [SyncService] never sets
|
/// Returns a copy with [firebaseConnected] set. [SyncService] never sets
|
||||||
/// it -- only [runSync], which is the layer that knows which [RemoteStore]
|
/// it -- only [runSync], which is the layer that knows which [RemoteStore]
|
||||||
/// it built -- so this is the seam that lets it do that without
|
/// it built -- so this is the seam that lets it do that without
|
||||||
@ -51,6 +57,7 @@ class SyncResult {
|
|||||||
skippedFiles: skippedFiles,
|
skippedFiles: skippedFiles,
|
||||||
skippedUnchanged: skippedUnchanged,
|
skippedUnchanged: skippedUnchanged,
|
||||||
firebaseConnected: value,
|
firebaseConnected: value,
|
||||||
|
locked: locked,
|
||||||
);
|
);
|
||||||
|
|
||||||
@override
|
@override
|
||||||
@ -73,7 +80,11 @@ class SyncResult {
|
|||||||
/// two never share a path and an old client can't misread a new file.
|
/// two never share a path and an old client can't misread a new file.
|
||||||
class SyncService {
|
class SyncService {
|
||||||
/// Creates a [SyncService], optionally overriding [notesDir].
|
/// Creates a [SyncService], optionally overriding [notesDir].
|
||||||
const SyncService({this.notesDir = 'todo-sync/notes', this.stateStore});
|
const SyncService({
|
||||||
|
this.notesDir = 'todo-sync/notes',
|
||||||
|
this.stateStore,
|
||||||
|
this.revsPath,
|
||||||
|
});
|
||||||
|
|
||||||
/// Directory in the repo under which per-device note-log files live.
|
/// Directory in the repo under which per-device note-log files live.
|
||||||
final String notesDir;
|
final String notesDir;
|
||||||
@ -87,7 +98,11 @@ class SyncService {
|
|||||||
final SyncStateStore? stateStore;
|
final SyncStateStore? stateStore;
|
||||||
|
|
||||||
/// Where revisions live, as a sibling of [notesDir].
|
/// Where revisions live, as a sibling of [notesDir].
|
||||||
String get revsDir => defaultRevsPath(notesDir);
|
/// Revision cache directory; null derives it from [notesDir].
|
||||||
|
final String? revsPath;
|
||||||
|
|
||||||
|
/// Where peers publish their revisions.
|
||||||
|
String get revsDir => revsPath ?? defaultRevsPath(notesDir);
|
||||||
|
|
||||||
/// Runs a full pull-merge-push cycle. Safe to call repeatedly.
|
/// Runs a full pull-merge-push cycle. Safe to call repeatedly.
|
||||||
///
|
///
|
||||||
@ -99,45 +114,61 @@ class SyncService {
|
|||||||
final ownFileName = '$nodeId.json';
|
final ownFileName = '$nodeId.json';
|
||||||
|
|
||||||
final state = await stateStore?.load() ?? const SyncState();
|
final state = await stateStore?.load() ?? const SyncState();
|
||||||
final remoteRevs = stateStore == null
|
// Independent reads, so one round trip instead of two. eagerError keeps
|
||||||
? const <String, String>{}
|
// the first failure's own type, which callers catch.
|
||||||
: await _revisions(remote);
|
final reads = await Future.wait<Object>([
|
||||||
|
if (stateStore == null)
|
||||||
|
Future.value(const <String, String>{})
|
||||||
|
else
|
||||||
|
_revisions(remote),
|
||||||
|
remote.listDirectory(notesDir),
|
||||||
|
], eagerError: true);
|
||||||
|
final remoteRevs = reads[0] as Map<String, String>;
|
||||||
|
final names = reads[1] as List<String>;
|
||||||
final seenRevs = <String, String>{};
|
final seenRevs = <String, String>{};
|
||||||
|
|
||||||
// 1. Pull: list all device log files, merge everyone else's.
|
// 1. Pull: every other device's log that changed since we merged it.
|
||||||
final names = await remote.listDirectory(notesDir);
|
|
||||||
var merged = 0;
|
|
||||||
var skippedUnchanged = 0;
|
var skippedUnchanged = 0;
|
||||||
final skipped = <String>[];
|
final changed = <String>[];
|
||||||
for (final name in names) {
|
for (final name in names) {
|
||||||
if (name == ownFileName) continue; // our own file; skip it.
|
if (name == ownFileName) continue; // our own file; skip it.
|
||||||
final peer = name.endsWith('.json')
|
final peer = peerOf(name);
|
||||||
? name.substring(0, name.length - 5)
|
|
||||||
: name;
|
|
||||||
final remoteRev = remoteRevs[peer];
|
final remoteRev = remoteRevs[peer];
|
||||||
if (remoteRev != null && remoteRev == state.peerRevs[peer]) {
|
if (remoteRev != null && remoteRev == state.peerRevs[peer]) {
|
||||||
// Unchanged since we last merged it, and that merge is already in the
|
// Unchanged since we last merged it, and that merge is already in the
|
||||||
// local log — so the ~150 KB download is pure waste. Carry the
|
// local log -- so the download is pure waste. Carry the revision
|
||||||
// revision forward so it stays skipped next time.
|
// forward so it stays skipped next time.
|
||||||
seenRevs[peer] = remoteRev;
|
seenRevs[peer] = remoteRev;
|
||||||
skippedUnchanged++;
|
skippedUnchanged++;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
final text = await remote.getFileText('$notesDir/$name');
|
changed.add(name);
|
||||||
final remoteLog = text == null ? null : _decodeLog(text);
|
}
|
||||||
if (remoteLog == null) {
|
var merged = 0;
|
||||||
// A vanished or undecodable peer file must not abort the sync, but
|
final skipped = <String>[];
|
||||||
// it must not vanish silently either — that's how a device drops
|
Log? incoming;
|
||||||
// out of sync unnoticed. Report it in the result instead.
|
for (final pulled in await pullPeers(
|
||||||
// Deliberately not recorded as seen: a corrupt push must be retried
|
remote,
|
||||||
// next run, not remembered as merged.
|
notesDir,
|
||||||
skipped.add(name);
|
changed,
|
||||||
|
remoteRevs,
|
||||||
|
)) {
|
||||||
|
final log = pulled.log;
|
||||||
|
if (log == null) {
|
||||||
|
// A vanished, undecryptable or undecodable peer file must not abort
|
||||||
|
// the sync, but it must not vanish silently either -- that's how a
|
||||||
|
// device drops out of sync unnoticed. Reported, and deliberately not
|
||||||
|
// recorded as seen: a corrupt push must be retried next run.
|
||||||
|
skipped.add(pulled.name);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
await repo.importLog(remoteLog);
|
// Peers merge with each other first (commutative, idempotent), so the
|
||||||
seenRevs[peer] = remoteRev ?? revisionOf(text!);
|
// local store is rewritten once rather than once per peer.
|
||||||
|
incoming = incoming == null ? log : mergeLogs(incoming, log);
|
||||||
|
seenRevs[pulled.peer] = pulled.rev!;
|
||||||
merged++;
|
merged++;
|
||||||
}
|
}
|
||||||
|
if (incoming != null) await repo.importLog(incoming);
|
||||||
|
|
||||||
// 2. Push: upload our own (now-merged) log under our node id.
|
// 2. Push: upload our own (now-merged) log under our node id.
|
||||||
// putFileText resolves our file's current sha itself.
|
// putFileText resolves our file's current sha itself.
|
||||||
@ -184,22 +215,4 @@ class SyncService {
|
|||||||
if (remote is! BulkMapReader) return const {};
|
if (remote is! BulkMapReader) return const {};
|
||||||
return await (remote as BulkMapReader).getStringMap(revsDir);
|
return await (remote as BulkMapReader).getStringMap(revsDir);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Parses a remote note log, returning `null` for a corrupt or wrong-shape
|
|
||||||
/// payload so one bad device file never aborts the whole sync.
|
|
||||||
Log? _decodeLog(String text) {
|
|
||||||
try {
|
|
||||||
return logFromJson(text);
|
|
||||||
} on FormatException {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
// crdt_sync's logFromJson throws a raw TypeError (not a custom
|
|
||||||
// exception) for a wrong-shape JSON payload from an untrusted peer
|
|
||||||
// file; must be caught too so one bad device file never aborts the
|
|
||||||
// whole sync (see doc comment above).
|
|
||||||
// ignore: avoid_catching_errors
|
|
||||||
on TypeError {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
38
lib/ui/app_route.dart
Normal file
@ -0,0 +1,38 @@
|
|||||||
|
/// The one page route every screen is pushed with.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
|
/// A route for [builder] that switches screens instantly: no fade, no slide.
|
||||||
|
///
|
||||||
|
/// Without a GPU the desktop web build repaints the whole 4K canvas in
|
||||||
|
/// software on every frame, so a 320 ms transition cost ~600 ms of main
|
||||||
|
/// thread and a 260-300 ms frame stall on every tab switch and note open.
|
||||||
|
/// The same instant switch applies on the phone. The context is unused but
|
||||||
|
/// kept so every call site stays as it was.
|
||||||
|
///
|
||||||
|
/// [name] is a route pattern (`/notes/detail`), never an id or a title: the
|
||||||
|
/// app-errors reporter stamps it on every report made on that screen.
|
||||||
|
Route<T> appRoute<T>(BuildContext _, WidgetBuilder builder, {String? name}) =>
|
||||||
|
_AppPageRoute<T>(
|
||||||
|
builder: builder,
|
||||||
|
settings: RouteSettings(name: name),
|
||||||
|
);
|
||||||
|
|
||||||
|
class _AppPageRoute<T> extends MaterialPageRoute<T> {
|
||||||
|
_AppPageRoute({required super.builder, super.settings});
|
||||||
|
|
||||||
|
@override
|
||||||
|
Duration get transitionDuration => Duration.zero;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Duration get reverseTransitionDuration => Duration.zero;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget buildTransitions(
|
||||||
|
BuildContext context,
|
||||||
|
Animation<double> animation,
|
||||||
|
Animation<double> secondaryAnimation,
|
||||||
|
Widget child,
|
||||||
|
) => child;
|
||||||
|
}
|
||||||
@ -5,8 +5,8 @@ library;
|
|||||||
import 'package:file_picker/file_picker.dart' show FilePicker;
|
import 'package:file_picker/file_picker.dart' show FilePicker;
|
||||||
import 'package:file_selector/file_selector.dart';
|
import 'package:file_selector/file_selector.dart';
|
||||||
import 'package:flutter/foundation.dart';
|
import 'package:flutter/foundation.dart';
|
||||||
import 'package:flutter/material.dart';
|
|
||||||
import 'package:image_picker/image_picker.dart';
|
import 'package:image_picker/image_picker.dart';
|
||||||
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
export 'package:file_selector/file_selector.dart' show XFile;
|
export 'package:file_selector/file_selector.dart' show XFile;
|
||||||
|
|
||||||
@ -44,18 +44,24 @@ Future<List<XFile>> pickAttachments(
|
|||||||
mainAxisSize: MainAxisSize.min,
|
mainAxisSize: MainAxisSize.min,
|
||||||
children: [
|
children: [
|
||||||
ListTile(
|
ListTile(
|
||||||
leading: const Icon(Icons.photo_camera_outlined),
|
leading: const Icon(
|
||||||
title: const Text('Camera'),
|
Icons.photo_camera_outlined,
|
||||||
|
semanticLabel: 'Camera',
|
||||||
|
),
|
||||||
onTap: () => Navigator.pop(context, AttachmentPickSource.camera),
|
onTap: () => Navigator.pop(context, AttachmentPickSource.camera),
|
||||||
),
|
),
|
||||||
ListTile(
|
ListTile(
|
||||||
leading: const Icon(Icons.photo_library_outlined),
|
leading: const Icon(
|
||||||
title: const Text('Gallery'),
|
Icons.photo_library_outlined,
|
||||||
|
semanticLabel: 'Gallery',
|
||||||
|
),
|
||||||
onTap: () => Navigator.pop(context, AttachmentPickSource.gallery),
|
onTap: () => Navigator.pop(context, AttachmentPickSource.gallery),
|
||||||
),
|
),
|
||||||
ListTile(
|
ListTile(
|
||||||
leading: const Icon(Icons.insert_drive_file_outlined),
|
leading: const Icon(
|
||||||
title: const Text('File'),
|
Icons.insert_drive_file_outlined,
|
||||||
|
semanticLabel: 'File',
|
||||||
|
),
|
||||||
onTap: () => Navigator.pop(context, AttachmentPickSource.file),
|
onTap: () => Navigator.pop(context, AttachmentPickSource.file),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
@ -102,8 +108,8 @@ class AttachButton extends StatelessWidget {
|
|||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
return IconButton(
|
return IconButton(
|
||||||
tooltip: 'Attach',
|
tooltip: 'attach',
|
||||||
icon: const Icon(Icons.attach_file),
|
icon: const Icon(Icons.attach_file, semanticLabel: 'Attach'),
|
||||||
onPressed: () async {
|
onPressed: () async {
|
||||||
final files = await (picking ?? pickAttachments)(context);
|
final files = await (picking ?? pickAttachments)(context);
|
||||||
if (files.isNotEmpty) onFiles(files);
|
if (files.isNotEmpty) onFiles(files);
|
||||||
|
|||||||
@ -4,11 +4,14 @@
|
|||||||
/// screen still owns every action; this just lays the row out.
|
/// screen still owns every action; this just lays the row out.
|
||||||
library;
|
library;
|
||||||
|
|
||||||
import 'package:flutter/material.dart';
|
import 'package:crdt_sync_flutter/crdt_sync_flutter.dart' show WaitWatch;
|
||||||
|
import 'package:flutter/foundation.dart';
|
||||||
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
import 'package:todo/data/note_repository.dart';
|
import 'package:todo/data/note_repository.dart';
|
||||||
import 'package:todo/frame_stats.dart';
|
import 'package:todo/frame_stats.dart';
|
||||||
import 'package:todo/ui/attachment_picking.dart';
|
import 'package:todo/ui/attachment_picking.dart';
|
||||||
|
import 'package:todo/ui/capture_confirm_mark.dart';
|
||||||
|
|
||||||
/// App bar for the capture screen.
|
/// App bar for the capture screen.
|
||||||
class CaptureAppBar extends StatelessWidget implements PreferredSizeWidget {
|
class CaptureAppBar extends StatelessWidget implements PreferredSizeWidget {
|
||||||
@ -22,6 +25,7 @@ class CaptureAppBar extends StatelessWidget implements PreferredSizeWidget {
|
|||||||
required this.onOpenList,
|
required this.onOpenList,
|
||||||
required this.onOpenSettings,
|
required this.onOpenSettings,
|
||||||
required this.onAttachFiles,
|
required this.onAttachFiles,
|
||||||
|
required this.captured,
|
||||||
this.attachmentPicking,
|
this.attachmentPicking,
|
||||||
super.key,
|
super.key,
|
||||||
});
|
});
|
||||||
@ -50,6 +54,9 @@ class CaptureAppBar extends StatelessWidget implements PreferredSizeWidget {
|
|||||||
/// Receives files picked with the 📎 action.
|
/// Receives files picked with the 📎 action.
|
||||||
final ValueChanged<List<XFile>> onAttachFiles;
|
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.
|
/// The picker behind 📎; null uses the platform one.
|
||||||
final AttachmentPicking? attachmentPicking;
|
final AttachmentPicking? attachmentPicking;
|
||||||
|
|
||||||
@ -80,26 +87,29 @@ class CaptureAppBar extends StatelessWidget implements PreferredSizeWidget {
|
|||||||
// Not gated on advanced mode: attaching is basic capture.
|
// Not gated on advanced mode: attaching is basic capture.
|
||||||
AttachButton(onFiles: onAttachFiles, picking: attachmentPicking),
|
AttachButton(onFiles: onAttachFiles, picking: attachmentPicking),
|
||||||
IconButton(
|
IconButton(
|
||||||
tooltip: 'New note',
|
tooltip: 'new',
|
||||||
onPressed: onNewNote,
|
onPressed: onNewNote,
|
||||||
icon: const Icon(Icons.check),
|
icon: const Icon(Icons.check, semanticLabel: 'New note'),
|
||||||
),
|
),
|
||||||
if (advanced)
|
if (advanced)
|
||||||
IconButton(
|
IconButton(
|
||||||
tooltip: 'Sync',
|
tooltip: 'sync',
|
||||||
onPressed: syncing ? null : onSync,
|
onPressed: syncing ? null : onSync,
|
||||||
icon: syncing
|
icon: syncing
|
||||||
? const SizedBox(
|
? const WaitWatch(
|
||||||
width: 18,
|
operation: 'sync.run',
|
||||||
height: 18,
|
child: SizedBox(
|
||||||
child: CircularProgressIndicator(strokeWidth: 2),
|
width: 18,
|
||||||
|
height: 18,
|
||||||
|
child: CircularProgressIndicator(strokeWidth: 2),
|
||||||
|
),
|
||||||
)
|
)
|
||||||
: const Icon(Icons.sync),
|
: const Icon(Icons.sync, semanticLabel: 'Sync'),
|
||||||
),
|
),
|
||||||
IconButton(
|
IconButton(
|
||||||
tooltip: 'Notes',
|
tooltip: 'notes',
|
||||||
onPressed: onOpenList,
|
onPressed: onOpenList,
|
||||||
icon: const Icon(Icons.list),
|
icon: const Icon(Icons.list, semanticLabel: 'Notes'),
|
||||||
),
|
),
|
||||||
// Live count of stored notes, proving local persistence. Sits directly
|
// Live count of stored notes, proving local persistence. Sits directly
|
||||||
// right of the Notes button it belongs to, and carries no icon of its
|
// right of the Notes button it belongs to, and carries no icon of its
|
||||||
@ -114,10 +124,11 @@ class CaptureAppBar extends StatelessWidget implements PreferredSizeWidget {
|
|||||||
);
|
);
|
||||||
},
|
},
|
||||||
),
|
),
|
||||||
|
CaptureConfirmMark(captured: captured),
|
||||||
IconButton(
|
IconButton(
|
||||||
tooltip: 'Settings',
|
tooltip: 'settings',
|
||||||
onPressed: onOpenSettings,
|
onPressed: onOpenSettings,
|
||||||
icon: const Icon(Icons.settings),
|
icon: const Icon(Icons.settings, semanticLabel: 'Settings'),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
|
|||||||
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:material_ui/material_ui.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.
|
/// yet, so the first write still reports the note as created.
|
||||||
bool _reserved = false;
|
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.
|
/// The draft's priority, applied to every write.
|
||||||
Priority priority = Priority.defaultValue;
|
Priority priority = Priority.defaultValue;
|
||||||
|
|
||||||
@ -98,6 +102,7 @@ class CaptureDraft {
|
|||||||
status: status,
|
status: status,
|
||||||
createdAt: _createdAt!,
|
createdAt: _createdAt!,
|
||||||
updatedAt: now,
|
updatedAt: now,
|
||||||
|
createdBy: 'kuhy',
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
if (live()) lastSavedAt.value = now;
|
if (live()) lastSavedAt.value = now;
|
||||||
|
|||||||
@ -1,10 +1,9 @@
|
|||||||
import 'dart:async';
|
import 'dart:async';
|
||||||
import 'dart:typed_data';
|
|
||||||
|
|
||||||
import 'package:crdt_sync/crdt_sync.dart';
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
import 'package:design_system/design_system.dart';
|
import 'package:flutter/services.dart';
|
||||||
import 'package:flutter/material.dart';
|
|
||||||
import 'package:http/http.dart' as http;
|
import 'package:http/http.dart' as http;
|
||||||
|
import 'package:material_ui/material_ui.dart';
|
||||||
import 'package:todo/analytics/analytics_event.dart';
|
import 'package:todo/analytics/analytics_event.dart';
|
||||||
import 'package:todo/analytics/analytics_service.dart';
|
import 'package:todo/analytics/analytics_service.dart';
|
||||||
import 'package:todo/attachments/image_store_scope.dart';
|
import 'package:todo/attachments/image_store_scope.dart';
|
||||||
@ -15,12 +14,14 @@ import 'package:todo/data/note_template.dart';
|
|||||||
import 'package:todo/sync/firebase_backend.dart';
|
import 'package:todo/sync/firebase_backend.dart';
|
||||||
import 'package:todo/sync/local_backup.dart';
|
import 'package:todo/sync/local_backup.dart';
|
||||||
import 'package:todo/sync/sync_settings.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/attachment_picking.dart';
|
||||||
import 'package:todo/ui/capture_app_bar.dart';
|
import 'package:todo/ui/capture_app_bar.dart';
|
||||||
import 'package:todo/ui/capture_draft.dart';
|
import 'package:todo/ui/capture_draft.dart';
|
||||||
import 'package:todo/ui/capture_status.dart';
|
import 'package:todo/ui/capture_status.dart';
|
||||||
import 'package:todo/ui/capture_status_footer.dart';
|
import 'package:todo/ui/capture_status_footer.dart';
|
||||||
import 'package:todo/ui/capture_sync_runner.dart';
|
import 'package:todo/ui/capture_sync_runner.dart';
|
||||||
|
import 'package:todo/ui/cue_snack.dart';
|
||||||
import 'package:todo/ui/image_attach.dart';
|
import 'package:todo/ui/image_attach.dart';
|
||||||
import 'package:todo/ui/image_input.dart';
|
import 'package:todo/ui/image_input.dart';
|
||||||
import 'package:todo/ui/note_form.dart';
|
import 'package:todo/ui/note_form.dart';
|
||||||
@ -71,6 +72,9 @@ class _CaptureScreenState extends State<CaptureScreen>
|
|||||||
|
|
||||||
final SyncStatusStore _syncStatus = SyncStatusStore();
|
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].
|
/// Runs sync passes and records their outcome; see [CaptureSyncRunner].
|
||||||
late final CaptureSyncRunner _runner = CaptureSyncRunner(
|
late final CaptureSyncRunner _runner = CaptureSyncRunner(
|
||||||
repository: widget.repository,
|
repository: widget.repository,
|
||||||
@ -130,6 +134,7 @@ class _CaptureScreenState extends State<CaptureScreen>
|
|||||||
_localBackup.dispose();
|
_localBackup.dispose();
|
||||||
_draft.dispose();
|
_draft.dispose();
|
||||||
_syncStatus.dispose();
|
_syncStatus.dispose();
|
||||||
|
_captures.dispose();
|
||||||
super.dispose();
|
super.dispose();
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -150,6 +155,7 @@ class _CaptureScreenState extends State<CaptureScreen>
|
|||||||
onOpenSettings: _openSettings,
|
onOpenSettings: _openSettings,
|
||||||
onAttachFiles: _attachFiles,
|
onAttachFiles: _attachFiles,
|
||||||
attachmentPicking: widget.attachmentPicking,
|
attachmentPicking: widget.attachmentPicking,
|
||||||
|
captured: _captures,
|
||||||
),
|
),
|
||||||
body: _captureBody(advanced: advanced),
|
body: _captureBody(advanced: advanced),
|
||||||
);
|
);
|
||||||
@ -188,7 +194,14 @@ class _CaptureScreenState extends State<CaptureScreen>
|
|||||||
Future<void> _sync() async {
|
Future<void> _sync() async {
|
||||||
final settings = _settings ?? await SyncSettings.load();
|
final settings = _settings ?? await SyncSettings.load();
|
||||||
if (!settings.isConfigured && await openFirebase() == null) {
|
if (!settings.isConfigured && await openFirebase() == null) {
|
||||||
_showSnack('Connect Firebase (or add a GitHub token) in settings');
|
// The cue plus the settings screen opening is the whole message.
|
||||||
|
if (mounted) {
|
||||||
|
showCue(
|
||||||
|
context,
|
||||||
|
Icons.cloud_off,
|
||||||
|
'Connect Firebase (or add a GitHub token) in settings',
|
||||||
|
);
|
||||||
|
}
|
||||||
await _openSettings();
|
await _openSettings();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@ -209,12 +222,7 @@ class _CaptureScreenState extends State<CaptureScreen>
|
|||||||
if (outcome.ok) 'detail': outcome.detail,
|
if (outcome.ok) 'detail': outcome.detail,
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
_showSnack(
|
_showSyncCue(outcome);
|
||||||
outcome.ok
|
|
||||||
? 'Synced: ${outcome.detail}'
|
|
||||||
: 'Sync failed: ${outcome.detail}',
|
|
||||||
isError: !outcome.ok,
|
|
||||||
);
|
|
||||||
} finally {
|
} finally {
|
||||||
if (mounted) setState(() => _syncing = false);
|
if (mounted) setState(() => _syncing = false);
|
||||||
}
|
}
|
||||||
|
|||||||