Compare commits

...

4 Commits

Author SHA1 Message Date
78452bf995 Package the desktop app as the web build, and delete the Linux embedder
Completes the move off Flutter's Linux embedder, which manages ~20fps at 4K
against ~144fps for the same Dart code in Chrome (measured end-to-end: the real
app, fullscreen at 4K, sustains 144fps scrolling a 300-note list).

`linux/` is gone. Its icons and .desktop installer move to `desktop/`, since
those are still needed and are not Flutter platform scaffolding. install_arch.sh
now builds the web bundle plus an AOT wrapper; run.sh does the same for
development.

Four things this took to get right, each found by actually installing and
launching the package rather than assuming:

- `dart compile exe` refuses to build the package: transitive dependencies
  (sqlite3, objective_c) have native build hooks. `dart build cli` handles them,
  and emits bin/ + lib/, so the wrapper resolves its assets at ../web.
- `options=('!strip')` is load-bearing. makepkg stripped the AOT executable
  (7.0M -> 5.7M), discarding the embedded snapshot; the result still ran but was
  the bare Dart VM printing a usage message instead of the app.
- No hard browser dependency. Declaring `depends=('chromium')` made makepkg
  install it, and this machine has a policy that uninstalls chromium three
  seconds later, which then failed dependency resolution. The wrapper discovers
  whatever browser exists (Thorium included) and TODO_BROWSER overrides.
- The server no longer dies with the browser process. Chrome exits immediately
  when handing off to an instance that owns the profile -- or when a stale
  SingletonLock is left behind -- which killed the server out from under a live
  window.

Chrome gets --class=todo so WM_CLASS matches the .desktop StartupWMClass and
the taskbar shows the app icon rather than a browser icon.

Verified: `todo` launches, serves, opens a window titled todo, and recovers the
backlog through the wrapper.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-20 14:08:00 +02:00
3704d34f74 Fix the web instrument's arming flag, and let the wrapper redirect its paths
Two things found while verifying the >=100fps done-condition at 4K.

`bool.fromEnvironment` only accepts the literal `true`, so
`--dart-define=TODO_FRAME_STATS=1` silently evaluated to false and the web
instrument emitted nothing at all -- a whole measurement run produced no data
and looked like the callback was broken. It now reads the value as a string and
accepts either form.

The wrapper gains --backlog-path/--log-path. Verification needs to point the
server somewhere harmless: it starts an app whose store may be empty, and an
empty store exports over the real ~/todo/BACKLOG.md through the very endpoint
being tested.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-20 13:47:38 +02:00
c37a9ef118 Add the desktop wrapper, and stop the test suite eating BACKLOG.md
The desktop app is a browser now, so it cannot write files. This adds the other
half: a loopback HTTP server that serves the web build and owns the two files
the browser cannot touch -- `~/todo/BACKLOG.md`, which the user's tooling and
the todo MCP server read, and a disk copy of the note log so a wiped Chrome
profile is not a total-loss event for unsynced notes.

Notable details:

- Binds to 127.0.0.1 only. The endpoints overwrite files in the user's home
  with no authentication, so a routable bind would let anything on the network
  rewrite the backlog.
- Serves explicit content types. CanvasKit refuses a `.wasm` labelled anything
  else and the app then renders nothing at all.
- Mirroring to disk is debounced. The store persists on every keystroke, so
  mirroring eagerly meant an HTTP request plus a whole-log write per character;
  IndexedDB still gets every keystroke, only the durability copy waits.

Separately, this fixes a pre-existing destructive bug found while testing:
`settings_screen_test` did real file I/O and overwrote the user's canonical
`~/todo/BACKLOG.md` with a single fake note on *every* `flutter test` run. It
went unnoticed because the app rewrites the file whenever it launches. The
export destination is now injectable and the test redirects it to a temp dir;
verified that a full suite run leaves the real file byte-identical.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-20 13:33:25 +02:00
66143bdfe3 Make the app compile and run for web, behind platform seams
First step of moving the desktop app off Flutter's Linux embedder, which tops
out at ~20fps at 4K (see docs/desktop-performance-findings.md). Android is
unaffected and keeps every existing code path.

The blocker was that `dart:io` was imported by note_repository, capture_screen
and settings_screen. On web it compiles to a stub and then throws at runtime --
the first web build rendered a blank white window. So each `dart:io` use now
sits behind a conditional export, with the shared logic hoisted into pure Dart:

- note_repository loses `dart:io`/sqlite entirely. Platform wiring moves to
  repository_factory{,_io,_web}, and the legacy sqlite import moves to its own
  io-only library. The HLC-from-updated_at seeding is preserved verbatim, so
  independently-migrating devices still resolve pre-cutover edits by real edit
  time.
- Notes persist to IndexedDB on web, not localStorage: the log is the primary
  copy of the backlog and localStorage caps at ~5-10MB and is evicted eagerly.
- BACKLOG.md and the explicit Export keep working through a local wrapper
  (added next). A browser cannot write `~/todo/BACKLOG.md`, and the user's
  tooling plus the todo MCP server read that path, so leaving it to rot was not
  an option. Writes are best-effort so the app still works with no wrapper.
- Notes are also mirrored to the wrapper's on-disk copy, so a wiped Chrome
  profile is not a total-loss event for notes that have not reached GitHub yet.

`openRepository` is split so `openRepositoryIn` keeps the migration tests; the
suite stays at 174 green and 100% coverage.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-20 13:14:03 +02:00
58 changed files with 1395 additions and 821 deletions

View File

@ -4,7 +4,7 @@
# This file should be version controlled and should not be manually edited.
version:
revision: "c9a6c484230f8b5e408ec57be1ef71dee1e77020"
revision: "ee80f08bbf97172ec030b8751ceab557177a34a6"
channel: "stable"
project_type: app
@ -13,14 +13,11 @@ project_type: app
migration:
platforms:
- platform: root
create_revision: c9a6c484230f8b5e408ec57be1ef71dee1e77020
base_revision: c9a6c484230f8b5e408ec57be1ef71dee1e77020
- platform: android
create_revision: c9a6c484230f8b5e408ec57be1ef71dee1e77020
base_revision: c9a6c484230f8b5e408ec57be1ef71dee1e77020
- platform: linux
create_revision: c9a6c484230f8b5e408ec57be1ef71dee1e77020
base_revision: c9a6c484230f8b5e408ec57be1ef71dee1e77020
create_revision: ee80f08bbf97172ec030b8751ceab557177a34a6
base_revision: ee80f08bbf97172ec030b8751ceab557177a34a6
- platform: web
create_revision: ee80f08bbf97172ec030b8751ceab557177a34a6
base_revision: ee80f08bbf97172ec030b8751ceab557177a34a6
# User provided section

View File

@ -1,6 +1,13 @@
# CLAUDE.md — todo
Offline-first, CRDT-synced notes app. Flutter, targets **Android + Linux**.
Offline-first, CRDT-synced notes app. Flutter, targets **Android + web**.
The **desktop app is the web build**, served by a small local wrapper
(`bin/todo_desktop.dart`) and shown in a Chrome `--app` window. Flutter's Linux
embedder was removed: it manages only ~20fps at 4K while the same Dart code in
Chrome sustains ~144fps. See `docs/desktop-performance-findings.md` for the
measurements. Do not re-add `linux/` — `flutter create --platforms linux` would
silently bring the slow path back.
Capture an idea instantly (persisted on every keystroke), browse/filter notes,
and sync peer-to-peer through a GitHub repo used as dumb storage.
@ -24,7 +31,12 @@ and sync peer-to-peer through a GitHub repo used as dumb storage.
- Coverage summary: `lcov --list coverage/lcov.info`.
- Static analysis: `flutter analyze` (must be clean before committing).
- Format: `dart format lib/ test/`.
- Run the app: `flutter run` (Linux desktop or a connected Android device).
- Run the desktop app: `./run.sh` (builds the web bundle, starts the wrapper,
opens Chrome). Mobile: `flutter run` with a connected Android device.
- The wrapper serves on a **fixed** port 8730 with a **fixed** Chrome profile
dir. Both must stay fixed: the GitHub token (`localStorage`) and the notes
(IndexedDB) are keyed by origin and live in that profile, so changing either
silently logs you out and hides your notes.
- Release APK: `flutter build apk --release` (signs with the debug key; debug
builds are janky — always measure smoothness on a release build).
- Sync smoke test (hits real GitHub, needs a token): `dart run tool/sync_smoke.dart`.

112
bin/todo_desktop.dart Normal file
View File

@ -0,0 +1,112 @@
// coverage:ignore-file
// Entry point for the desktop wrapper: resolves real paths, starts the server,
// and launches the browser. The serving logic it delegates to is covered by
// test/wrapper_server_test.dart.
import 'dart:io';
import 'package:path/path.dart' as p;
import 'package:todo/desktop/wrapper_server.dart';
/// Port must stay fixed: the browser keys `localStorage` (the GitHub token) and
/// IndexedDB (the notes) by origin, so a different port looks like a different
/// app with no token and no notes. Kept in step with lib/sync/desktop_wrapper.
const _port = 8730;
Future<void> main(List<String> args) async {
final home = Platform.environment['HOME'];
if (home == null) {
stderr.writeln('HOME is not set; cannot resolve the backlog path.');
exit(1);
}
// `dart build cli` emits bundle/bin/<exe> alongside bundle/lib/, so the
// installed layout is /opt/todo/bin/todo-desktop with the web assets one
// level up at /opt/todo/web. --web-root overrides for development runs
// straight out of the repo.
final webRoot = _argValue(args, '--web-root') ??
p.normalize(p.join(p.dirname(Platform.resolvedExecutable), '..', 'web'));
if (!Directory(webRoot).existsSync()) {
stderr.writeln('web assets not found at $webRoot');
exit(1);
}
// Overridable so a verification run cannot point at the real backlog: an
// app that starts with an empty store would export over it.
final server = WrapperServer(
webRoot: webRoot,
backlogPath:
_argValue(args, '--backlog-path') ?? p.join(home, 'todo', 'BACKLOG.md'),
logPath: _argValue(args, '--log-path') ??
p.join(home, '.local', 'share', 'todo-desktop', 'todo_notes.json'),
);
await server.start(_port);
stdout.writeln('todo desktop serving on http://localhost:$_port');
// A bare flag, not a valued option: requiring a dummy value meant passing a
// stray positional, which the AOT runtime tries to interpret as a snapshot.
if (!args.contains('--no-browser')) {
final ranLongEnough = await _launchBrowser(home);
if (!ranLongEnough) {
// Chrome exits immediately when it hands the URL to an instance that
// already owns the profile directory (or when a stale SingletonLock is
// left behind). Shutting down here would pull the server out from under
// a window that is still open, so keep serving instead.
stdout.writeln(
'Browser returned immediately (handed off to an existing window). '
'Still serving on http://localhost:$_port — Ctrl-C to stop.',
);
return;
}
// Otherwise the browser owned the session: its window closed, so we exit.
await server.stop();
}
}
/// Launches the app in a Chrome-family browser with a **stable** profile
/// directory, since the token and notes live in that profile.
/// Returns true when the browser ran long enough to have owned the session.
Future<bool> _launchBrowser(String home) async {
// Ordered by preference, and deliberately broad: this machine runs Thorium
// behind /opt/google/chrome, and has a policy that uninstalls the `chromium`
// package, so assuming any single browser is wrong. TODO_BROWSER overrides.
final candidates = [
Platform.environment['TODO_BROWSER'] ?? '',
'/opt/google/chrome/chrome',
'/opt/thorium-browser/thorium-browser',
'/usr/bin/google-chrome-stable',
'/usr/bin/chromium',
'/usr/bin/brave',
];
final browser = candidates.firstWhere(
(path) => path.isNotEmpty && File(path).existsSync(),
orElse: () => '',
);
if (browser.isEmpty) {
stderr.writeln('No Chrome-family browser found; open '
'http://localhost:$_port manually.');
return false;
}
// The profile directory must stay stable: the GitHub token (localStorage)
// and the notes (IndexedDB) live inside it, so a changing path silently
// logs the user out and hides their notes.
final profile = p.join(home, '.local', 'share', 'todo-desktop', 'profile');
final process = await Process.start(browser, [
'--app=http://localhost:$_port',
'--user-data-dir=$profile',
// Sets WM_CLASS, which the .desktop entry matches on via StartupWMClass.
// Without it the window inherits the browser's class and the taskbar shows
// a browser icon instead of todo's.
'--class=todo',
'--no-first-run',
]);
final started = DateTime.now();
await process.exitCode;
return DateTime.now().difference(started) > const Duration(seconds: 5);
}
String? _argValue(List<String> args, String name) {
final index = args.indexOf(name);
if (index == -1 || index + 1 >= args.length) return null;
return args[index + 1];
}

View File

Before

Width:  |  Height:  |  Size: 1.3 KiB

After

Width:  |  Height:  |  Size: 1.3 KiB

View File

Before

Width:  |  Height:  |  Size: 308 B

After

Width:  |  Height:  |  Size: 308 B

View File

Before

Width:  |  Height:  |  Size: 470 B

After

Width:  |  Height:  |  Size: 470 B

View File

Before

Width:  |  Height:  |  Size: 3.4 KiB

After

Width:  |  Height:  |  Size: 3.4 KiB

View File

Before

Width:  |  Height:  |  Size: 574 B

After

Width:  |  Height:  |  Size: 574 B

View File

Before

Width:  |  Height:  |  Size: 788 B

After

Width:  |  Height:  |  Size: 788 B

View File

Before

Width:  |  Height:  |  Size: 6.9 KiB

After

Width:  |  Height:  |  Size: 6.9 KiB

View File

Before

Width:  |  Height:  |  Size: 1023 B

After

Width:  |  Height:  |  Size: 1023 B

View File

@ -3,32 +3,38 @@
# ============================================================================
# Install the todo launcher icon and .desktop entry for the Linux desktop.
#
# Flutter's GTK runner has no icon of its own: my_application.cc calls
# gtk_window_set_icon_name("todo"), which resolves through the hicolor icon
# theme. This script is what puts the icon into that theme, plus a .desktop
# entry so the app appears in application menus.
# The desktop app is a Flutter *web* build shown in a Chrome app window (the
# Linux embedder manages only ~20fps at 4K — see
# docs/desktop-performance-findings.md), so the launcher starts the wrapper,
# which serves the build and opens the browser.
#
# Icon PNGs are pre-rendered and committed under linux/icons/, so this script
# Icon PNGs are pre-rendered and committed under desktop/icons/, so this script
# needs no image tooling at run time. Regenerate them with:
# PYTHONPATH=~/testsAndMisc python3 -m python_pkg.app_icons \
# generate --app todo --linux-out linux/icons
# generate --app todo --linux-out desktop/icons
# ============================================================================
set -euo pipefail
SCRIPT_NAME="$(basename "$0")"
LINUX_DIR="$(cd "$(dirname "$0")" && pwd)"
REPO_DIR="$(dirname "$LINUX_DIR")"
readonly SCRIPT_NAME LINUX_DIR REPO_DIR
DESKTOP_DIR_SRC="$(cd "$(dirname "$0")" && pwd)"
REPO_DIR="$(dirname "$DESKTOP_DIR_SRC")"
readonly SCRIPT_NAME DESKTOP_DIR_SRC REPO_DIR
readonly ICON_NAME="todo"
readonly BINARY_NAME="todo"
# GTK derives WM_CLASS from the GApplication id in linux/CMakeLists.txt,
# not from the binary name; verified with xprop on the running window.
readonly WM_CLASS="dev.kuhy.todo"
readonly ICON_SRC_DIR="$LINUX_DIR/icons"
# Chrome sets WM_CLASS from --class, which the wrapper passes explicitly.
# Without it the window would inherit the browser's own class (e.g.
# "Google-chrome"), and the taskbar would show a browser icon for the app.
readonly WM_CLASS="todo"
readonly ICON_SRC_DIR="$DESKTOP_DIR_SRC/icons"
readonly ICON_THEME_DIR="${XDG_DATA_HOME:-$HOME/.local/share}/icons/hicolor"
readonly DESKTOP_DIR="${XDG_DATA_HOME:-$HOME/.local/share}/applications"
readonly BUNDLE_BIN="$REPO_DIR/build/linux/x64/release/bundle/$BINARY_NAME"
# Prefer the packaged launcher; fall back to running straight from the repo so
# the entry also works for a development checkout that was never installed.
LAUNCH_CMD="/usr/bin/todo"
if [[ ! -x "$LAUNCH_CMD" ]]; then
LAUNCH_CMD="$REPO_DIR/run.sh"
fi
readonly LAUNCH_CMD
usage() {
echo "Usage: $SCRIPT_NAME"
@ -79,7 +85,7 @@ install_desktop_entry() {
Type=Application
Name=todo
Comment=Offline-first, CRDT-synced notes
Exec=$BUNDLE_BIN
Exec=$LAUNCH_CMD
Icon=$ICON_NAME
Terminal=false
Categories=Utility;TextEditor;
@ -97,9 +103,9 @@ main() {
install_desktop_entry
echo "Installed $ICON_NAME icon into $ICON_THEME_DIR"
echo "Installed $DESKTOP_DIR/$ICON_NAME.desktop"
if [[ ! -x "$BUNDLE_BIN" ]]; then
echo "Note: $BUNDLE_BIN does not exist yet."
echo " Run 'flutter build linux --release' to make the entry launchable."
if [[ ! -x "$LAUNCH_CMD" ]]; then
echo "Note: $LAUNCH_CMD does not exist yet."
echo " Run ./install_arch.sh to build and install the app."
fi
}

View File

@ -6,7 +6,12 @@
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
BUNDLE_DIR="$SCRIPT_DIR/build/linux/x64/release/bundle"
# The desktop app is a Flutter *web* build served by a small local wrapper.
# Flutter's Linux embedder only reaches ~20fps at 4K on this hardware, while
# the same Dart code in Chrome sustains ~144fps — see
# docs/desktop-performance-findings.md for the measurements.
WEB_DIR="$SCRIPT_DIR/build/web"
WRAPPER_BUNDLE="$SCRIPT_DIR/build/cli/bundle"
WORK_DIR="$(mktemp -d)"
cleanup() { rm -rf "$WORK_DIR"; }
@ -15,9 +20,17 @@ trap cleanup EXIT
# Parse version from pubspec.yaml (strip build number: 1.0.0+1 → 1.0.0)
PKGVER="$(grep '^version:' "$SCRIPT_DIR/pubspec.yaml" | sed 's/^version:[[:space:]]*//' | sed 's/+.*//')"
echo "==> Building todo $PKGVER (Flutter release)..."
echo "==> Building todo $PKGVER (Flutter web release)..."
cd "$SCRIPT_DIR"
flutter build linux --release
flutter build web --release
echo "==> Compiling the desktop wrapper..."
# AOT-compiled so the installed package needs no Dart SDK at run time.
# `dart build cli`, not `dart compile exe`: the package pulls in dependencies
# with native build hooks (sqlite3, objective_c), which `dart compile` refuses
# to handle even though the wrapper itself uses none of them.
rm -rf "$SCRIPT_DIR/build/cli"
dart build cli -o "$SCRIPT_DIR/build/cli"
echo "==> Generating PKGBUILD..."
# pkgname is 'todo-flutter', NOT 'todo': the AUR already ships an unrelated
@ -33,24 +46,41 @@ pkgdesc='Offline-first notes app'
arch=('x86_64')
url='https://github.com/kuhyx/todo-app'
license=('custom')
depends=('gtk3')
# No hard browser dependency. A Chrome-family browser renders the UI, but
# naming one as a dependency is wrong here: makepkg installs it, and this
# system has a policy that immediately removes 'chromium' again, which then
# fails dependency resolution. The wrapper discovers whatever browser is
# actually present (including Thorium) and reports clearly if none is.
depends=()
optdepends=('chromium: renders the app window'
'google-chrome: renders the app window')
conflicts=('todo')
replaces=('todo')
# Flutter release binaries are already stripped/AOT-compiled with no
# extractable DWARF debug info, so a split -debug package is pointless here
# and gdb-add-index just fails noisily on every binary. Skip it, overriding
# the system-wide 'debug' OPTIONS setting.
options=('!debug')
# !strip is load-bearing: the wrapper is a Dart AOT executable with its snapshot
# embedded in the ELF, and stripping it discards that snapshot. The stripped
# binary still runs but is just the bare Dart VM, which prints a usage message
# instead of starting the app.
options=('!strip' '!debug')
package() {
# Preserve the bundle's bin/ + lib/ layout: the executable loads its
# native libraries from ../lib, and resolves the web assets from ../web.
install -dm755 "\$pkgdir/opt/todo"
cp -r "$BUNDLE_DIR/." "\$pkgdir/opt/todo/"
chmod 755 "\$pkgdir/opt/todo/todo"
cp -r "$WRAPPER_BUNDLE/bin" "\$pkgdir/opt/todo/bin"
cp -r "$WRAPPER_BUNDLE/lib" "\$pkgdir/opt/todo/lib"
chmod 755 "\$pkgdir/opt/todo/bin/todo_desktop"
install -dm755 "\$pkgdir/opt/todo/web"
cp -r "$WEB_DIR/." "\$pkgdir/opt/todo/web/"
install -dm755 "\$pkgdir/usr/bin"
cat > "\$pkgdir/usr/bin/todo" <<'WRAPPER'
#!/bin/bash
exec /opt/todo/todo "\$@"
exec /opt/todo/bin/todo_desktop "\$@"
WRAPPER
chmod 755 "\$pkgdir/usr/bin/todo"
}

View File

@ -0,0 +1,57 @@
import 'package:http/http.dart' as http;
/// Talks to the local desktop wrapper that serves the web build.
///
/// The wrapper exists because a browser cannot write to the filesystem, and two
/// things depend on it:
///
/// * `~/todo/BACKLOG.md` — read by the user's tooling and the `todo` MCP
/// server. Without this it would silently go stale after the move to a web
/// build.
/// * an on-disk copy of the note log, so a wiped Chrome profile is not a
/// total-loss event for notes that have not reached GitHub yet.
///
/// Every method is best-effort and swallows failures: the app must remain fully
/// usable when the wrapper is absent, e.g. when the build is opened in a plain
/// browser tab or on mobile.
class DesktopBackupClient {
/// Creates a client targeting [baseUrl] (the wrapper's origin).
DesktopBackupClient({required this.baseUrl, http.Client? httpClient})
: _client = httpClient ?? http.Client();
/// Origin the wrapper listens on, e.g. `http://localhost:8730`.
final String baseUrl;
final http.Client _client;
/// Writes the Markdown backlog export to disk via the wrapper.
Future<void> writeBacklog(String markdown) =>
_post('/backup/backlog', markdown);
/// Writes the serialised note log to disk via the wrapper.
Future<void> writeLog(String json) => _post('/backup/log', json);
/// Reads the wrapper's on-disk copy of the log, or null if unavailable.
Future<String?> readLog() => _get('/backup/log');
/// Reads the on-disk Markdown backlog, or null if unavailable.
Future<String?> readBacklog() => _get('/backup/backlog');
Future<String?> _get(String path) async {
try {
final response = await _client.get(Uri.parse('$baseUrl$path'));
if (response.statusCode != 200 || response.body.isEmpty) return null;
return response.body;
} on Exception {
return null;
}
}
Future<void> _post(String path, String body) async {
try {
await _client.post(Uri.parse('$baseUrl$path'), body: body);
} on Exception {
// Best-effort by design; see the class docs.
}
}
}

View File

@ -0,0 +1,90 @@
import 'dart:io';
import 'package:crdt_sync/crdt_sync.dart';
// Only SqliteCrdt/CrdtTableExecutor are needed to read the legacy DB; hide its
// Hlc so the crdt_sync Hlc (the store's clock type) is unambiguous.
import 'package:sqlite_crdt/sqlite_crdt.dart' hide Hlc;
import 'package:todo/data/note.dart';
import 'package:todo/data/note_repository.dart';
/// Reads a pre-crdt_sync `sqlite_crdt` database into a crdt_sync [Log].
///
/// Lives in its own `dart:io` library so [NoteRepository] can stay pure Dart:
/// the desktop app is a web build, and one `dart:io` import anywhere in the
/// graph fails the whole web compile. Mobile still runs this on first launch
/// after the cutover; web never does, because there is no legacy DB in a
/// browser profile.
class LegacySqliteMigration {
/// Whether a legacy database exists at [path] to migrate from.
static bool exists(String path) => File(path).existsSync();
/// Opens the legacy DB at [path] and returns its notes as a [Log], plus the
/// legacy CRDT node id.
///
/// Reusing the legacy node id keeps a device that already synced on the same
/// `devices/<id>` identity across the cutover, so it does not appear as a new
/// peer and re-upload everything.
static Future<({Log log, String nodeId})> read(
String path,
String preferredNodeId,
) async {
final legacy = await SqliteCrdt.open(
path,
version: _version,
onCreate: _onCreate,
onUpgrade: _onUpgrade,
);
final nodeId = preferredNodeId.isEmpty ? legacy.nodeId : preferredNodeId;
final rows = await legacy.query(
'SELECT id, text, priority, status, created_at, updated_at, is_deleted '
'FROM notes',
);
final log = <String, Record>{};
for (final row in rows) {
final note = Note.fromRow(row);
log[note.id] = NoteRepository.legacyRecordFor(
note,
nodeId,
deleted: (row['is_deleted'] as int? ?? 0) != 0,
);
}
await legacy.close();
return (log: log, nodeId: nodeId);
}
static const int _version = 3;
// coverage:ignore-start
// Unreachable: migration only ever opens a legacy DB that already exists
// (guarded by [exists]), so sqlite never runs onCreate. Kept because
// SqliteCrdt.open requires the callback.
static Future<void> _onCreate(CrdtTableExecutor db, int version) async {
await db.execute('''
CREATE TABLE notes (
id TEXT NOT NULL,
text TEXT NOT NULL DEFAULT '',
priority INTEGER NOT NULL DEFAULT 2,
status INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
PRIMARY KEY (id)
)
''');
}
// coverage:ignore-end
static Future<void> _onUpgrade(
CrdtTableExecutor db,
int from,
int to,
) async {
if (from < 2) {
await db.execute(
'ALTER TABLE notes ADD COLUMN status INTEGER NOT NULL DEFAULT 0',
);
}
if (from < 3) {
await db.execute('UPDATE notes SET priority = 2 WHERE priority = 0');
}
}
}

View File

@ -1,15 +1,13 @@
import 'dart:async';
import 'dart:io';
import 'package:crdt_sync/crdt_sync.dart';
import 'package:crdt_sync/crdt_sync_io.dart';
import 'package:path/path.dart' as p;
import 'package:shared_preferences/shared_preferences.dart';
// Only SqliteCrdt/CrdtTableExecutor are needed for the legacy-DB migration;
// hide its Hlc so the crdt_sync Hlc (the store's clock type) is unambiguous.
import 'package:sqlite_crdt/sqlite_crdt.dart' hide Hlc;
import 'package:todo/data/note.dart';
import 'package:uuid/uuid.dart';
// 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
// for web. Opening a repository for a real platform lives behind the
// conditional export in `repository_factory.dart`; the legacy sqlite migration
// lives in the io-only `legacy_sqlite_migration.dart`.
/// How the history list should be ordered.
enum NoteSort {
@ -77,52 +75,37 @@ class NoteRepository {
static const _fCreatedAt = 'created_at';
static const _fUpdatedAt = 'updated_at';
static const _kNodeId = 'crdt.nodeId';
static const _kMigrated = 'crdt.migratedFromSqlite';
static const _logFileName = 'todo_notes.json';
/// SharedPreferences key holding this device's stable CRDT node id.
static const kNodeId = 'crdt.nodeId';
/// Opens (or creates) the note log next to the legacy DB at [path].
/// SharedPreferences key recording that the legacy sqlite import already ran.
static const kMigrated = 'crdt.migratedFromSqlite';
/// File name of the persisted log, used by the io factory.
static const logFileName = 'todo_notes.json';
/// Opens (or creates) the note log backed by [persistence].
///
/// On first launch after the crdt_sync migration this performs a one-time,
/// idempotent import of the existing `sqlite_crdt` database at [path] into
/// the new log (guarded by a persisted "migrated" flag), so no backlog is
/// lost. The legacy DB file is left untouched as a safety net.
static Future<NoteRepository> open(String path) async {
final prefs = await SharedPreferences.getInstance();
final logFile = File(p.join(p.dirname(path), _logFileName));
final persistence = FileLogPersistence(logFile);
final migrated = prefs.getBool(_kMigrated) ?? false;
var nodeId = prefs.getString(_kNodeId) ?? '';
if (!migrated && File(path).existsSync()) {
final legacy = await SqliteCrdt.open(
path,
version: _legacyVersion,
onCreate: _legacyOnCreate,
onUpgrade: _legacyOnUpgrade,
);
// Reuse the legacy CRDT node id so a device that already synced keeps
// the same devices/<id> identity across the cutover.
if (nodeId.isEmpty) nodeId = legacy.nodeId;
final store = LogStore(persistence: persistence, nodeId: nodeId);
await store.load();
await _seedFromLegacy(legacy, store, nodeId);
await legacy.close();
await prefs.setString(_kNodeId, nodeId);
await prefs.setBool(_kMigrated, true);
return NoteRepository._(store, nodeId);
}
if (nodeId.isEmpty) {
nodeId = const Uuid().v4();
await prefs.setString(_kNodeId, nodeId);
}
/// Platform wiring — where the log lives, and the one-time legacy sqlite
/// import — belongs to the callers in `repository_factory_*.dart`, so that
/// this class stays free of `dart:io` and can compile for web.
static Future<NoteRepository> openWith({
required LogPersistence persistence,
required String nodeId,
}) async {
final store = LogStore(persistence: persistence, nodeId: nodeId);
await store.load();
return NoteRepository._(store, nodeId);
}
/// Replaces the whole log, used by the one-time legacy sqlite migration.
///
/// Distinct from [importLog], which merges: migration seeds a store that is
/// known to be empty and must preserve the records' own clocks verbatim.
Future<void> seedFrom(Log log) async {
if (log.isNotEmpty) await _store.replaceAll(log);
}
/// Opens a transient in-memory log; intended for tests.
static Future<NoteRepository> openInMemory({
String nodeId = 'test-node',
@ -132,38 +115,29 @@ class NoteRepository {
return NoteRepository._(store, nodeId);
}
/// Copies every legacy note (tombstones included) into [store] in one write.
/// Builds the record for one migrated legacy note, tombstones included.
///
/// Each note's field clocks are seeded from its own `updated_at`, not "now",
/// so that when two devices migrate independently, a pre-cutover edit still
/// wins by real edit time under per-field last-writer-wins instead of being
/// resolved arbitrarily.
static Future<void> _seedFromLegacy(
SqliteCrdt legacy,
LogStore store,
String nodeId,
) async {
final rows = await legacy.query(
'SELECT id, text, priority, status, created_at, updated_at, is_deleted '
'FROM notes',
/// resolved arbitrarily. Public because the migration that calls it lives in
/// the io-only library, which cannot reach private members here.
static Record legacyRecordFor(
Note note,
String nodeId, {
bool deleted = false,
}) {
final hlc = Hlc(
wallTimeMs: note.updatedAt.millisecondsSinceEpoch,
counter: 0,
nodeId: nodeId,
);
return Record(
id: note.id,
fields: _fieldsFor(note, hlc),
deleted: deleted,
deletedHlc: deleted ? hlc : null,
);
final log = <String, Record>{};
for (final row in rows) {
final note = Note.fromRow(row);
final hlc = Hlc(
wallTimeMs: note.updatedAt.millisecondsSinceEpoch,
counter: 0,
nodeId: nodeId,
);
final deleted = (row['is_deleted'] as int? ?? 0) != 0;
log[note.id] = Record(
id: note.id,
fields: _fieldsFor(note, hlc),
deleted: deleted,
deletedHlc: deleted ? hlc : null,
);
}
if (log.isNotEmpty) await store.replaceAll(log);
}
/// Inserts a new note or updates the existing one with the same [id].
@ -346,44 +320,6 @@ class NoteRepository {
/// Midnight (local) of [t]'s calendar day.
static DateTime _startOfDay(DateTime t) => DateTime(t.year, t.month, t.day);
// --- legacy sqlite_crdt schema, used only to read the DB during migration -
static const int _legacyVersion = 3;
// coverage:ignore-start
// Unreachable: migration only ever opens a legacy DB that already exists
// (guarded by `File(path).existsSync()`), so sqlite never runs onCreate.
// Kept because SqliteCrdt.open requires the callback.
static Future<void> _legacyOnCreate(CrdtTableExecutor db, int version) async {
await db.execute('''
CREATE TABLE notes (
id TEXT NOT NULL,
text TEXT NOT NULL DEFAULT '',
priority INTEGER NOT NULL DEFAULT 2,
status INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
PRIMARY KEY (id)
)
''');
}
// coverage:ignore-end
static Future<void> _legacyOnUpgrade(
CrdtTableExecutor db,
int from,
int to,
) async {
if (from < 2) {
await db.execute(
'ALTER TABLE notes ADD COLUMN status INTEGER NOT NULL DEFAULT 0',
);
}
if (from < 3) {
await db.execute('UPDATE notes SET priority = 2 WHERE priority = 0');
}
}
}
/// In-memory [LogPersistence] for [NoteRepository.openInMemory] (tests).

View File

@ -0,0 +1,9 @@
/// Platform entry point for opening the note store.
///
/// Conditional export because `dart:io` cannot even be *imported* in a web
/// compile: mobile gets the file-backed store plus the legacy sqlite import,
/// web gets IndexedDB plus the desktop wrapper's disk copy.
library;
export 'repository_factory_io.dart'
if (dart.library.js_interop) 'repository_factory_web.dart';

View File

@ -0,0 +1,64 @@
import 'dart:io';
import 'package:crdt_sync/crdt_sync_io.dart';
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
import 'package:todo/data/legacy_sqlite_migration.dart';
import 'package:todo/data/note_repository.dart';
import 'package:uuid/uuid.dart';
/// Opens the note store on a `dart:io` platform (Android).
///
/// Also performs the one-time, idempotent import of a pre-crdt_sync sqlite
/// database, guarded by a persisted flag. The legacy DB file is left untouched
/// as a safety net.
// coverage:ignore-start
// Resolves the real per-platform application-support directory, so it cannot
// run under test; [openRepositoryIn] holds all the logic and is covered.
Future<NoteRepository> openRepository() async {
final dir = await getApplicationSupportDirectory();
return openRepositoryIn(dir.path);
}
// coverage:ignore-end
/// Opens the note store rooted at [dirPath].
///
/// Split out from [openRepository] so tests can drive the legacy-migration
/// paths against a temporary directory without going through `path_provider`.
Future<NoteRepository> openRepositoryIn(String dirPath) async {
// Keep the FFI initialisation for any non-Android io host that still reads a
// legacy DB (and for the test host, which is Linux).
if (Platform.isLinux || Platform.isWindows || Platform.isMacOS) {
sqfliteFfiInit();
}
final dbPath = p.join(dirPath, 'todo.db');
final persistence = FileLogPersistence(
File(p.join(dirPath, NoteRepository.logFileName)),
);
final prefs = await SharedPreferences.getInstance();
final migrated = prefs.getBool(NoteRepository.kMigrated) ?? false;
var nodeId = prefs.getString(NoteRepository.kNodeId) ?? '';
if (!migrated && LegacySqliteMigration.exists(dbPath)) {
final legacy = await LegacySqliteMigration.read(dbPath, nodeId);
nodeId = legacy.nodeId;
final repository = await NoteRepository.openWith(
persistence: persistence,
nodeId: nodeId,
);
await repository.seedFrom(legacy.log);
await prefs.setString(NoteRepository.kNodeId, nodeId);
await prefs.setBool(NoteRepository.kMigrated, true);
return repository;
}
if (nodeId.isEmpty) {
nodeId = const Uuid().v4();
await prefs.setString(NoteRepository.kNodeId, nodeId);
}
return NoteRepository.openWith(persistence: persistence, nodeId: nodeId);
}

View File

@ -0,0 +1,27 @@
import 'package:idb_shim/idb_browser.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:todo/data/desktop_backup_client.dart';
import 'package:todo/data/note_repository.dart';
import 'package:todo/data/web_log_persistence.dart';
import 'package:todo/sync/desktop_wrapper.dart';
import 'package:uuid/uuid.dart';
/// Opens the note store in a browser (the desktop app).
///
/// There is no legacy sqlite database in a browser profile, so the migration
/// path is simply absent here rather than skipped at runtime.
Future<NoteRepository> openRepository() async {
final database = await WebLogPersistence.openDatabase(idbFactoryBrowser);
final persistence = WebLogPersistence(
database: database,
backup: DesktopBackupClient(baseUrl: desktopWrapperOrigin),
);
final prefs = await SharedPreferences.getInstance();
var nodeId = prefs.getString(NoteRepository.kNodeId) ?? '';
if (nodeId.isEmpty) {
nodeId = const Uuid().v4();
await prefs.setString(NoteRepository.kNodeId, nodeId);
}
return NoteRepository.openWith(persistence: persistence, nodeId: nodeId);
}

View File

@ -0,0 +1,94 @@
import 'dart:async';
import 'package:crdt_sync/crdt_sync.dart';
import 'package:idb_shim/idb.dart';
import 'package:todo/data/desktop_backup_client.dart';
/// [LogPersistence] backed by IndexedDB, with a best-effort copy pushed to the
/// desktop wrapper so the notes also exist on disk.
///
/// IndexedDB rather than `localStorage` because the latter caps at roughly
/// 5-10MB per origin and is evicted more eagerly; the note log is the primary
/// copy of the backlog and has to outlive storage pressure.
///
/// The disk copy exists because moving the desktop app into a browser would
/// otherwise leave a wiped Chrome profile as a total-loss event for notes that
/// have not synced to GitHub yet. It is deliberately fire-and-forget: the
/// wrapper is an optimisation, and the app must stay fully usable when it is
/// absent (for instance when the same build is opened in a plain browser tab).
class WebLogPersistence implements LogPersistence {
/// Creates a persistence over [database], mirroring writes to [backup].
WebLogPersistence({
required Database database,
this.backup,
this.mirrorDebounce = const Duration(seconds: 2),
}) : _db = database;
final Database _db;
/// Wrapper client that mirrors writes to disk, or null when absent.
final DesktopBackupClient? backup;
/// How long to coalesce disk mirroring after the last write.
///
/// The store persists on *every* keystroke, so mirroring eagerly would mean
/// an HTTP request and a whole-log disk write per character. IndexedDB is
/// still written synchronously with each keystroke; only the durability copy
/// is debounced.
final Duration mirrorDebounce;
Timer? _mirrorTimer;
/// Object store holding a single record: the serialised log.
static const storeName = 'log';
/// Key of that single record.
static const recordKey = 'notes';
/// IndexedDB database name.
static const databaseName = 'todo';
/// Opens (creating if needed) the IndexedDB database backing the log.
static Future<Database> openDatabase(IdbFactory factory) => factory.open(
databaseName,
version: 1,
onUpgradeNeeded: (event) {
final db = event.database;
if (!db.objectStoreNames.contains(storeName)) {
db.createObjectStore(storeName);
}
},
);
@override
Future<String?> read() async {
final txn = _db.transaction(storeName, idbModeReadOnly);
final value = await txn.objectStore(storeName).getObject(recordKey);
await txn.completed;
if (value is String && value.isNotEmpty) return value;
// Nothing local yet (fresh profile, or the browser evicted the database).
// Fall back to the wrapper's on-disk copy so a cleared profile recovers
// instead of silently starting from an empty backlog.
return backup?.readLog();
}
@override
Future<void> write(String text) async {
final txn = _db.transaction(storeName, idbModeReadWrite);
await txn.objectStore(storeName).put(text, recordKey);
await txn.completed;
_scheduleMirror(text);
}
void _scheduleMirror(String text) {
final client = backup;
if (client == null) return;
_mirrorTimer?.cancel();
_mirrorTimer = Timer(mirrorDebounce, () {
unawaited(client.writeLog(text));
});
}
/// Cancels any pending disk mirror. Call when tearing the store down.
void dispose() => _mirrorTimer?.cancel();
}

View File

@ -0,0 +1,163 @@
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:path/path.dart' as p;
/// Local HTTP server backing the desktop app.
///
/// The desktop app is a Flutter **web** build (Flutter's Linux embedder manages
/// only ~20fps at 4K — see `docs/desktop-performance-findings.md`), so it runs
/// in a browser and cannot touch the filesystem. This process is the other half
/// of the desktop app: it serves the build and owns the two files a browser
/// cannot write.
///
/// * `~/todo/BACKLOG.md` — the canonical backlog path the user's tooling and
/// the `todo` MCP server read.
/// * a copy of the note log — so a wiped Chrome profile is not a total-loss
/// event for notes that have not yet synced to GitHub.
///
/// Binds to loopback only. The endpoints read and overwrite files in the user's
/// home directory with no authentication, so exposing them on a routable
/// address would let anything on the network rewrite the backlog.
class WrapperServer {
/// Creates a server serving [webRoot] and persisting under [backlogPath] and
/// [logPath].
WrapperServer({
required this.webRoot,
required this.backlogPath,
required this.logPath,
});
/// Directory holding the built Flutter web assets.
final String webRoot;
/// Absolute path of the Markdown backlog export.
final String backlogPath;
/// Absolute path of the on-disk note-log copy.
final String logPath;
HttpServer? _server;
/// Port the server is listening on, once [start] has completed.
int get port => _server!.port;
/// Binds to loopback on [requestedPort] and begins serving.
///
/// Pass 0 to let the OS choose a port (tests do this); the desktop launcher
/// passes the fixed port, because the browser keys `localStorage` (the GitHub
/// token) and IndexedDB (the notes) by origin — a changing port would
/// silently hide both.
Future<void> start(int requestedPort) async {
_server = await HttpServer.bind(
InternetAddress.loopbackIPv4,
requestedPort,
);
unawaited(_serve(_server!));
}
/// Stops serving and releases the port.
Future<void> stop() async => _server?.close(force: true);
Future<void> _serve(HttpServer server) async {
await for (final request in server) {
try {
await _handle(request);
} on Exception {
request.response.statusCode = HttpStatus.internalServerError;
}
await request.response.close();
}
}
Future<void> _handle(HttpRequest request) async {
final path = request.uri.path;
if (path == '/backup/backlog') {
return _file(request, backlogPath);
}
if (path == '/backup/log') {
return _file(request, logPath);
}
return _static(request, path);
}
/// GET returns the file's contents (404 when absent); POST overwrites it.
Future<void> _file(HttpRequest request, String filePath) async {
final file = File(filePath);
if (request.method == 'POST') {
await file.parent.create(recursive: true);
await file.writeAsString(await utf8.decodeStream(request));
request.response.statusCode = HttpStatus.noContent;
return;
}
if (request.method != 'GET') {
request.response.statusCode = HttpStatus.methodNotAllowed;
return;
}
if (!file.existsSync()) {
request.response.statusCode = HttpStatus.notFound;
return;
}
request.response.headers.contentType = ContentType.text;
request.response.write(await file.readAsString());
}
Future<void> _static(HttpRequest request, String path) async {
final relative = path == '/' ? 'index.html' : path.substring(1);
// Reject traversal before touching the filesystem: the served root sits
// next to the user's files, so `../` must not escape it.
final resolved = p.normalize(p.join(webRoot, relative));
// coverage:ignore-start
// Defence in depth, and currently unreachable: Dart's HttpServer decodes
// and normalises the path before a handler runs, so even `%2e%2e` arrives
// already collapsed (verified in wrapper_server_test). Kept so the
// guarantee does not depend on that implementation detail holding.
if (!p.isWithin(webRoot, resolved) && resolved != p.normalize(webRoot)) {
request.response.statusCode = HttpStatus.forbidden;
return;
}
// coverage:ignore-end
final file = File(resolved);
if (!file.existsSync()) {
request.response.statusCode = HttpStatus.notFound;
return;
}
request.response.headers.contentType = contentTypeFor(resolved);
await request.response.addStream(file.openRead());
}
/// Content type for [filePath].
///
/// Flutter web is strict here: CanvasKit refuses to instantiate a `.wasm`
/// served as anything but `application/wasm`, and the app silently fails to
/// render if the bootstrap `.js` is mislabelled.
static ContentType contentTypeFor(String filePath) {
switch (p.extension(filePath).toLowerCase()) {
case '.html':
return ContentType.html;
case '.js' || '.mjs':
return ContentType('text', 'javascript', charset: 'utf-8');
case '.json':
return ContentType.json;
case '.wasm':
return ContentType('application', 'wasm');
case '.css':
return ContentType('text', 'css', charset: 'utf-8');
case '.png':
return ContentType('image', 'png');
case '.svg':
return ContentType('image', 'svg+xml');
case '.ttf':
return ContentType('font', 'ttf');
case '.otf':
return ContentType('font', 'otf');
case '.woff2':
return ContentType('font', 'woff2');
case '.bin' || '.symbols':
return ContentType.binary;
default:
return ContentType.binary;
}
}
}

View File

@ -1,84 +1,10 @@
// coverage:ignore-file
// TEMPORARY diagnostic instrument (desktop interaction-lag investigation).
// Guarded by TODO_FRAME_STATS=1 so it is inert in normal use.
//
// v3 adds an event-loop blocking monitor, which is the decisive instrument.
// Frame gaps are ambiguous in a mostly-static UI: no frame is produced when
// nothing needs drawing, so an idle user looks identical to a stalled isolate.
// A periodic timer, by contrast, is scheduled regardless of drawing -- if it
// fires late, the UI isolate was genuinely blocked, and by exactly how long.
import 'dart:async';
import 'dart:io';
/// Platform entry point for the temporary frame instrument.
///
/// Conditional export because the io version writes to `stdout` and reads
/// `Platform.environment`, neither of which exists in a browser. The web
/// version reports to the devtools console instead and is armed at build time
/// with `--dart-define=TODO_FRAME_STATS=1`.
library;
import 'package:flutter/scheduler.dart';
/// Whether the frame-stats instrument is armed for this process.
bool get frameStatsEnabled => Platform.environment['TODO_FRAME_STATS'] == '1';
/// A frame whose own work exceeded this is a hitch worth naming. Set to zero
/// by TODO_FRAME_STATS_ALL=1 so every frame is logged, which is what the
/// raster-cost-vs-window-size sweep needs.
int get _slowFrameUs =>
Platform.environment['TODO_FRAME_STATS_ALL'] == '1' ? -1 : 8000;
/// How often the event-loop probe is scheduled.
const _probePeriod = Duration(milliseconds: 16);
/// Lateness beyond this means the isolate was blocked long enough to be felt.
const _blockedMs = 24;
final Stopwatch _clock = Stopwatch();
Timer? _probe;
String get _at => (_clock.elapsedMilliseconds / 1000).toStringAsFixed(2);
/// Installs the frame-timing and event-loop instruments.
void installFrameStats() {
if (!frameStatsEnabled) return;
_clock.start();
stdout.writeln(
'[frame-stats v3] armed; logging slow frames and UI-isolate blocking',
);
_installFrameTimings();
_installEventLoopProbe();
}
void _installFrameTimings() {
SchedulerBinding.instance.addTimingsCallback((timings) {
for (final t in timings) {
final build = t.buildDuration.inMicroseconds;
final raster = t.rasterDuration.inMicroseconds;
if (build + raster > _slowFrameUs) {
stdout.writeln(
'[FRAME $_at s] total=${((build + raster) / 1000)
.toStringAsFixed(1)}ms '
'(build=${(build / 1000).toStringAsFixed(1)} '
'raster=${(raster / 1000).toStringAsFixed(1)})',
);
}
}
});
}
/// Schedules a timer every [_probePeriod] and reports how late it actually
/// fired. Lateness is time the UI isolate spent unable to run anything -- e.g.
/// a synchronous JSON serialize of the whole note log.
void _installEventLoopProbe() {
var expected = _clock.elapsedMicroseconds + _probePeriod.inMicroseconds;
void tick(Timer _) {
final now = _clock.elapsedMicroseconds;
final lateMs = (now - expected) / 1000;
if (lateMs > _blockedMs) {
stdout.writeln(
'[UI-BLOCKED $_at s] event loop stalled '
'${lateMs.toStringAsFixed(1)}ms',
);
}
expected = now + _probePeriod.inMicroseconds;
}
_probe = Timer.periodic(_probePeriod, tick);
}
/// Stops the probe. Only needed if the instrument outlives the app.
void disposeFrameStats() => _probe?.cancel();
export 'frame_stats_io.dart'
if (dart.library.js_interop) 'frame_stats_web.dart';

84
lib/frame_stats_io.dart Normal file
View File

@ -0,0 +1,84 @@
// coverage:ignore-file
// TEMPORARY diagnostic instrument (desktop interaction-lag investigation).
// Guarded by TODO_FRAME_STATS=1 so it is inert in normal use.
//
// v3 adds an event-loop blocking monitor, which is the decisive instrument.
// Frame gaps are ambiguous in a mostly-static UI: no frame is produced when
// nothing needs drawing, so an idle user looks identical to a stalled isolate.
// A periodic timer, by contrast, is scheduled regardless of drawing -- if it
// fires late, the UI isolate was genuinely blocked, and by exactly how long.
import 'dart:async';
import 'dart:io';
import 'package:flutter/scheduler.dart';
/// Whether the frame-stats instrument is armed for this process.
bool get frameStatsEnabled => Platform.environment['TODO_FRAME_STATS'] == '1';
/// A frame whose own work exceeded this is a hitch worth naming. Set to zero
/// by TODO_FRAME_STATS_ALL=1 so every frame is logged, which is what the
/// raster-cost-vs-window-size sweep needs.
int get _slowFrameUs =>
Platform.environment['TODO_FRAME_STATS_ALL'] == '1' ? -1 : 8000;
/// How often the event-loop probe is scheduled.
const _probePeriod = Duration(milliseconds: 16);
/// Lateness beyond this means the isolate was blocked long enough to be felt.
const _blockedMs = 24;
final Stopwatch _clock = Stopwatch();
Timer? _probe;
String get _at => (_clock.elapsedMilliseconds / 1000).toStringAsFixed(2);
/// Installs the frame-timing and event-loop instruments.
void installFrameStats() {
if (!frameStatsEnabled) return;
_clock.start();
stdout.writeln(
'[frame-stats v3] armed; logging slow frames and UI-isolate blocking',
);
_installFrameTimings();
_installEventLoopProbe();
}
void _installFrameTimings() {
SchedulerBinding.instance.addTimingsCallback((timings) {
for (final t in timings) {
final build = t.buildDuration.inMicroseconds;
final raster = t.rasterDuration.inMicroseconds;
if (build + raster > _slowFrameUs) {
stdout.writeln(
'[FRAME $_at s] total=${((build + raster) / 1000)
.toStringAsFixed(1)}ms '
'(build=${(build / 1000).toStringAsFixed(1)} '
'raster=${(raster / 1000).toStringAsFixed(1)})',
);
}
}
});
}
/// Schedules a timer every [_probePeriod] and reports how late it actually
/// fired. Lateness is time the UI isolate spent unable to run anything -- e.g.
/// a synchronous JSON serialize of the whole note log.
void _installEventLoopProbe() {
var expected = _clock.elapsedMicroseconds + _probePeriod.inMicroseconds;
void tick(Timer _) {
final now = _clock.elapsedMicroseconds;
final lateMs = (now - expected) / 1000;
if (lateMs > _blockedMs) {
stdout.writeln(
'[UI-BLOCKED $_at s] event loop stalled '
'${lateMs.toStringAsFixed(1)}ms',
);
}
expected = now + _probePeriod.inMicroseconds;
}
_probe = Timer.periodic(_probePeriod, tick);
}
/// Stops the probe. Only needed if the instrument outlives the app.
void disposeFrameStats() => _probe?.cancel();

89
lib/frame_stats_web.dart Normal file
View File

@ -0,0 +1,89 @@
// coverage:ignore-file
// TEMPORARY diagnostic instrument, web variant. See frame_stats_io.dart.
//
// Armed at build time (`--dart-define=TODO_FRAME_STATS=1`) rather than by an
// environment variable, which a browser does not have. Reports to the devtools
// console.
import 'dart:async';
import 'dart:ui' show FramePhase;
import 'package:flutter/foundation.dart';
import 'package:flutter/scheduler.dart';
/// Whether the frame-stats instrument is armed for this build.
///
/// Read as a string rather than `bool.fromEnvironment`, which only accepts the
/// exact literal `true` — `--dart-define=TODO_FRAME_STATS=1` silently yields
/// false and the instrument produces nothing at all.
const String _frameStatsFlag = String.fromEnvironment('TODO_FRAME_STATS');
/// Whether the instrument is armed (`--dart-define=TODO_FRAME_STATS=1`).
const bool frameStatsEnabled =
_frameStatsFlag == '1' || _frameStatsFlag == 'true';
const _slowFrameMs = 8;
const _probePeriod = Duration(milliseconds: 16);
const _blockedMs = 24;
final Stopwatch _clock = Stopwatch();
Timer? _probe;
final List<int> _cadenceUs = <int>[];
String get _at => (_clock.elapsedMilliseconds / 1000).toStringAsFixed(2);
/// Installs the frame-timing and event-loop instruments.
void installFrameStats() {
if (!frameStatsEnabled) return;
_clock.start();
debugPrint('[frame-stats web] armed');
SchedulerBinding.instance.addTimingsCallback((timings) {
for (final t in timings) {
final total = t.buildDuration.inMilliseconds +
t.rasterDuration.inMilliseconds;
if (total > _slowFrameMs) {
debugPrint(
'[SLOW-FRAME $_at s] total=${total}ms '
'(build=${t.buildDuration.inMilliseconds} '
'raster=${t.rasterDuration.inMilliseconds})',
);
}
// Cadence is the headline number for the >=100fps done-condition.
final vsync = t.timestampInMicroseconds(FramePhase.vsyncStart);
_cadenceUs.add(vsync);
}
_reportCadence();
});
var expected = _clock.elapsedMicroseconds + _probePeriod.inMicroseconds;
_probe = Timer.periodic(_probePeriod, (_) {
final now = _clock.elapsedMicroseconds;
final lateMs = (now - expected) / 1000;
if (lateMs > _blockedMs) {
debugPrint('[UI-BLOCKED $_at s] ${lateMs.toStringAsFixed(1)}ms');
}
expected = now + _probePeriod.inMicroseconds;
});
}
void _reportCadence() {
if (_cadenceUs.length < 120) return;
final deltas = <int>[];
for (var i = 1; i < _cadenceUs.length; i++) {
deltas.add(_cadenceUs[i] - _cadenceUs[i - 1]);
}
deltas.sort();
final p50 = deltas[deltas.length ~/ 2] / 1000;
final p95 = deltas[(deltas.length * 95) ~/ 100] / 1000;
debugPrint(
'[frame-stats web] cadence p50=${p50.toStringAsFixed(2)}ms '
'p95=${p95.toStringAsFixed(2)}ms (~${(1000 / p50).toStringAsFixed(1)} fps)',
);
_cadenceUs.clear();
}
/// Stops the probe.
void disposeFrameStats() {
_probe?.cancel();
}

View File

@ -1,15 +1,10 @@
// coverage:ignore-file
// App bootstrap: wires platform DB paths (path_provider) into the repository
// and calls runApp. Exercised end-to-end by running the app, not unit tests.
import 'dart:io';
import 'package:flutter/foundation.dart';
// App bootstrap: opens the platform's note store and calls runApp. Exercised
// end-to-end by running the app, not unit tests.
import 'package:flutter/material.dart';
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
import 'package:todo/data/note_repository.dart';
import 'package:todo/data/repository_factory.dart';
import 'package:todo/frame_stats.dart';
import 'package:todo/ui/capture_screen.dart';
@ -17,15 +12,10 @@ Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
installFrameStats();
// Desktop platforms need the FFI sqlite implementation initialised
// before any database is opened; mobile uses the bundled library.
if (!kIsWeb && (Platform.isLinux || Platform.isWindows || Platform.isMacOS)) {
sqfliteFfiInit();
}
final dir = await getApplicationSupportDirectory();
final dbPath = p.join(dir.path, 'todo.db');
final repository = await NoteRepository.open(dbPath);
// 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
// imported at all in a web compile, and the desktop app is now a web build.
final repository = await openRepository();
runApp(TodoApp(repository: repository));
}

View File

@ -0,0 +1,9 @@
/// Platform entry point for the explicit "Export notes" action.
///
/// Conditional export because `dart:io` is unusable in a browser: mobile shares
/// a temp file, io desktop writes `~/todo/BACKLOG.md` directly, and the web
/// desktop app asks the local wrapper to write that same path.
library;
export 'backlog_export_io.dart'
if (dart.library.js_interop) 'backlog_export_web.dart';

View File

@ -0,0 +1,43 @@
import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'package:share_plus/share_plus.dart';
/// Resolves the home directory the desktop export writes under.
///
/// Overridable **so the test suite never writes to the real `~/todo`**. This is
/// not hypothetical: before this seam existed, running `flutter test` exported
/// a fake note over the user's canonical `~/todo/BACKLOG.md` every time.
String Function() resolveExportHome =
() => Platform.environment['HOME'] ?? Directory.current.path;
/// Writes the Markdown export somewhere the user can get at it, and returns a
/// human-readable description of where it went.
///
/// On mobile this opens the system share sheet; on a `dart:io` desktop host it
/// writes the canonical `~/todo/BACKLOG.md`.
Future<String> exportBacklog(String markdown, int noteCount) async {
// coverage:ignore-start
// Mobile-only share path: Platform.isAndroid/isIOS are always false on the
// Linux test host, so these lines are structurally unreachable in CI and
// excluded from the coverage denominator. Verified on-device.
if (Platform.isAndroid || Platform.isIOS) {
final dir = await getTemporaryDirectory();
final file = File('${dir.path}/todo-backlog.md');
await file.writeAsString(markdown);
await SharePlus.instance.share(
ShareParams(
files: [XFile(file.path, mimeType: 'text/markdown')],
subject: 'todo backlog ($noteCount notes)',
),
);
return 'Shared $noteCount notes';
}
// coverage:ignore-end
final home = resolveExportHome();
final dir = Directory('$home/todo');
if (!dir.existsSync()) dir.createSync(recursive: true);
final file = File('${dir.path}/BACKLOG.md');
await file.writeAsString(markdown);
return 'Exported $noteCount notes to ${file.path}';
}

View File

@ -0,0 +1,11 @@
import 'package:todo/data/desktop_backup_client.dart';
import 'package:todo/sync/desktop_wrapper.dart';
/// Writes the Markdown export through the desktop wrapper, so an explicit
/// Export still lands at the canonical `~/todo/BACKLOG.md` path the user's
/// tooling reads — the browser itself cannot write there.
Future<String> exportBacklog(String markdown, int noteCount) async {
final client = DesktopBackupClient(baseUrl: desktopWrapperOrigin);
await client.writeBacklog(markdown);
return 'Exported $noteCount notes to ~/todo/BACKLOG.md';
}

View File

@ -0,0 +1,11 @@
/// The fixed origin the desktop wrapper serves on.
///
/// **Do not change this casually.** `localStorage` (which holds the GitHub
/// token) and IndexedDB (which holds the note log) are both keyed by origin, so
/// changing the port silently logs the user out and hides their local notes
/// behind an origin they no longer visit. The wrapper script and
/// `install_arch.sh` must use the same value.
const desktopWrapperPort = 8730;
/// Origin of the desktop wrapper, e.g. `http://localhost:8730`.
const desktopWrapperOrigin = 'http://localhost:$desktopWrapperPort';

View File

@ -0,0 +1,8 @@
/// Platform entry point for building the Markdown backlog backup.
///
/// Conditional export because `dart:io` is unusable in a browser: mobile writes
/// the file directly, the web desktop app hands it to the local wrapper.
library;
export 'local_backup_factory_io.dart'
if (dart.library.js_interop) 'local_backup_factory_web.dart';

View File

@ -0,0 +1,36 @@
// coverage:ignore-file
// Real-filesystem platform wiring, extracted verbatim from the
// `coverage:ignore` block it previously lived in inside capture_screen.dart.
// It resolves paths from the actual HOME/documents directory, so exercising it
// under test would write outside the sandbox; tests inject an in-memory
// LocalBackup instead. Verified by running the app.
import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'package:todo/data/note_repository.dart';
import 'package:todo/sync/local_backup.dart';
/// Builds the platform [LocalBackup] on a `dart:io` host (Android).
///
/// On mobile this lives in the app's documents directory, where Android Auto
/// Backup can pick it up.
LocalBackup createLocalBackup(NoteRepository repository) {
Future<File> backupFile() async {
if (Platform.isAndroid || Platform.isIOS) {
final dir = await getApplicationDocumentsDirectory();
return File('${dir.path}/todo-backlog.md');
}
final home = Platform.environment['HOME'] ?? Directory.current.path;
final dir = Directory('$home/todo')..createSync(recursive: true);
return File('${dir.path}/BACKLOG.md');
}
return LocalBackup(
fetch: repository.listNotes,
reader: () async {
final file = await backupFile();
return file.existsSync() ? file.readAsString() : null;
},
writer: (markdown) async => (await backupFile()).writeAsString(markdown),
);
}

View File

@ -0,0 +1,21 @@
import 'package:todo/data/desktop_backup_client.dart';
import 'package:todo/data/note_repository.dart';
import 'package:todo/sync/desktop_wrapper.dart';
import 'package:todo/sync/local_backup.dart';
/// Builds the [LocalBackup] for the browser-hosted desktop app.
///
/// A browser cannot write to the filesystem, so the wrapper that serves the
/// build owns the file. This keeps `~/todo/BACKLOG.md` current — the user's
/// tooling and the `todo` MCP server read it, and without this the move to a
/// web build would let it silently go stale.
LocalBackup createLocalBackup(NoteRepository repository) {
final client = DesktopBackupClient(baseUrl: desktopWrapperOrigin);
return LocalBackup(
fetch: repository.listNotes,
// Recovery reads the same file back through the wrapper, so a cleared
// browser profile can still restore from the on-disk backlog.
reader: client.readBacklog,
writer: client.writeBacklog,
);
}

View File

@ -1,16 +1,15 @@
import 'dart:async';
import 'dart:io';
import 'package:crdt_sync/crdt_sync.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:path_provider/path_provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:todo/data/note.dart';
import 'package:todo/data/note_repository.dart';
import 'package:todo/data/note_template.dart';
import 'package:todo/frame_stats.dart';
import 'package:todo/sync/local_backup.dart';
import 'package:todo/sync/local_backup_factory.dart';
import 'package:todo/sync/sync_service.dart';
import 'package:todo/sync/sync_settings.dart';
import 'package:todo/ui/note_editor.dart';
@ -197,26 +196,8 @@ class _CaptureScreenState extends State<CaptureScreen>
// (the path the user's workflow already reads), or the app documents dir on
// mobile (which Android Auto Backup includes). Exercised by running the app;
// tests inject an in-memory LocalBackup instead.
static LocalBackup _platformLocalBackup(NoteRepository repository) {
Future<File> backupFile() async {
if (Platform.isAndroid || Platform.isIOS) {
final dir = await getApplicationDocumentsDirectory();
return File('${dir.path}/todo-backlog.md');
}
final home = Platform.environment['HOME'] ?? Directory.current.path;
final dir = Directory('$home/todo')..createSync(recursive: true);
return File('${dir.path}/BACKLOG.md');
}
return LocalBackup(
fetch: repository.listNotes,
reader: () async {
final file = await backupFile();
return file.existsSync() ? file.readAsString() : null;
},
writer: (markdown) async => (await backupFile()).writeAsString(markdown),
);
}
static LocalBackup _platformLocalBackup(NoteRepository repository) =>
createLocalBackup(repository);
// coverage:ignore-end
@override

View File

@ -1,14 +1,12 @@
import 'dart:async';
import 'dart:io';
import 'package:crdt_sync/crdt_sync.dart';
import 'package:file_selector/file_selector.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:http/http.dart' as http;
import 'package:path_provider/path_provider.dart';
import 'package:share_plus/share_plus.dart';
import 'package:todo/data/note_repository.dart';
import 'package:todo/sync/backlog_export.dart';
import 'package:todo/sync/github_device_auth.dart';
import 'package:todo/sync/notes_markdown.dart';
import 'package:todo/sync/sync_service.dart';
@ -178,33 +176,8 @@ class _SettingsScreenState extends State<SettingsScreen> {
final notes = await widget.repository.listNotes();
final markdown = NotesMarkdown.export(notes);
// coverage:ignore-start
// Mobile-only share path: Platform.isAndroid/isIOS are always false on
// the Linux test host, so these lines are structurally unreachable in
// CI and excluded from the coverage denominator. Verified on-device.
if (Platform.isAndroid || Platform.isIOS) {
final dir = await getTemporaryDirectory();
final file = File('${dir.path}/todo-backlog.md');
await file.writeAsString(markdown);
await SharePlus.instance.share(
ShareParams(
files: [XFile(file.path, mimeType: 'text/markdown')],
subject: 'todo backlog (${notes.length} notes)',
),
);
} else {
// coverage:ignore-end
final home = Platform.environment['HOME'] ?? Directory.current.path;
final dir = Directory('$home/todo');
if (!dir.existsSync()) dir.createSync(recursive: true);
final file = File('${dir.path}/BACKLOG.md');
await file.writeAsString(markdown);
if (mounted) {
setState(
() => _status = 'Exported ${notes.length} notes to ${file.path}',
);
}
}
final outcome = await exportBacklog(markdown, notes.length);
if (mounted) setState(() => _status = outcome);
} on Exception catch (e) {
if (mounted) setState(() => _status = 'Export failed: $e');
}

1
linux/.gitignore vendored
View File

@ -1 +0,0 @@
flutter/ephemeral

View File

@ -1,128 +0,0 @@
# Project-level configuration.
cmake_minimum_required(VERSION 3.13)
project(runner LANGUAGES CXX)
# The name of the executable created for the application. Change this to change
# the on-disk name of your application.
set(BINARY_NAME "todo")
# The unique GTK application identifier for this application. See:
# https://wiki.gnome.org/HowDoI/ChooseApplicationID
set(APPLICATION_ID "dev.kuhy.todo")
# Explicitly opt in to modern CMake behaviors to avoid warnings with recent
# versions of CMake.
cmake_policy(SET CMP0063 NEW)
# Load bundled libraries from the lib/ directory relative to the binary.
set(CMAKE_INSTALL_RPATH "$ORIGIN/lib")
# Root filesystem for cross-building.
if(FLUTTER_TARGET_PLATFORM_SYSROOT)
set(CMAKE_SYSROOT ${FLUTTER_TARGET_PLATFORM_SYSROOT})
set(CMAKE_FIND_ROOT_PATH ${CMAKE_SYSROOT})
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
endif()
# Define build configuration options.
if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)
set(CMAKE_BUILD_TYPE "Debug" CACHE
STRING "Flutter build mode" FORCE)
set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS
"Debug" "Profile" "Release")
endif()
# Compilation settings that should be applied to most targets.
#
# Be cautious about adding new options here, as plugins use this function by
# default. In most cases, you should add new options to specific targets instead
# of modifying this function.
function(APPLY_STANDARD_SETTINGS TARGET)
target_compile_features(${TARGET} PUBLIC cxx_std_14)
target_compile_options(${TARGET} PRIVATE -Wall -Werror)
target_compile_options(${TARGET} PRIVATE "$<$<NOT:$<CONFIG:Debug>>:-O3>")
target_compile_definitions(${TARGET} PRIVATE "$<$<NOT:$<CONFIG:Debug>>:NDEBUG>")
endfunction()
# Flutter library and tool build rules.
set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter")
add_subdirectory(${FLUTTER_MANAGED_DIR})
# System-level dependencies.
find_package(PkgConfig REQUIRED)
pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0)
# Application build; see runner/CMakeLists.txt.
add_subdirectory("runner")
# Run the Flutter tool portions of the build. This must not be removed.
add_dependencies(${BINARY_NAME} flutter_assemble)
# Only the install-generated bundle's copy of the executable will launch
# correctly, since the resources must in the right relative locations. To avoid
# people trying to run the unbundled copy, put it in a subdirectory instead of
# the default top-level location.
set_target_properties(${BINARY_NAME}
PROPERTIES
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/intermediates_do_not_run"
)
# Generated plugin build rules, which manage building the plugins and adding
# them to the application.
include(flutter/generated_plugins.cmake)
# === Installation ===
# By default, "installing" just makes a relocatable bundle in the build
# directory.
set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle")
if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT)
set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE)
endif()
# Start with a clean build bundle directory every time.
install(CODE "
file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\")
" COMPONENT Runtime)
set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data")
set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib")
install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}"
COMPONENT Runtime)
install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}"
COMPONENT Runtime)
install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
COMPONENT Runtime)
foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES})
install(FILES "${bundled_library}"
DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
COMPONENT Runtime)
endforeach(bundled_library)
# Copy the native assets provided by the build.dart from all packages.
set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/linux/")
install(DIRECTORY "${NATIVE_ASSETS_DIR}"
DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
COMPONENT Runtime)
# Fully re-copy the assets directory on each build to avoid having stale files
# from a previous install.
set(FLUTTER_ASSET_DIR_NAME "flutter_assets")
install(CODE "
file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\")
" COMPONENT Runtime)
install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}"
DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime)
# Install the AOT library on non-Debug builds only.
if(NOT CMAKE_BUILD_TYPE MATCHES "Debug")
install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
COMPONENT Runtime)
endif()

View File

@ -1,88 +0,0 @@
# This file controls Flutter-level build steps. It should not be edited.
cmake_minimum_required(VERSION 3.10)
set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral")
# Configuration provided via flutter tool.
include(${EPHEMERAL_DIR}/generated_config.cmake)
# TODO: Move the rest of this into files in ephemeral. See
# https://github.com/flutter/flutter/issues/57146.
# Serves the same purpose as list(TRANSFORM ... PREPEND ...),
# which isn't available in 3.10.
function(list_prepend LIST_NAME PREFIX)
set(NEW_LIST "")
foreach(element ${${LIST_NAME}})
list(APPEND NEW_LIST "${PREFIX}${element}")
endforeach(element)
set(${LIST_NAME} "${NEW_LIST}" PARENT_SCOPE)
endfunction()
# === Flutter Library ===
# System-level dependencies.
find_package(PkgConfig REQUIRED)
pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0)
pkg_check_modules(GLIB REQUIRED IMPORTED_TARGET glib-2.0)
pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-2.0)
set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/libflutter_linux_gtk.so")
# Published to parent scope for install step.
set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE)
set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE)
set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE)
set(AOT_LIBRARY "${PROJECT_DIR}/build/lib/libapp.so" PARENT_SCOPE)
list(APPEND FLUTTER_LIBRARY_HEADERS
"fl_basic_message_channel.h"
"fl_binary_codec.h"
"fl_binary_messenger.h"
"fl_dart_project.h"
"fl_engine.h"
"fl_json_message_codec.h"
"fl_json_method_codec.h"
"fl_message_codec.h"
"fl_method_call.h"
"fl_method_channel.h"
"fl_method_codec.h"
"fl_method_response.h"
"fl_plugin_registrar.h"
"fl_plugin_registry.h"
"fl_standard_message_codec.h"
"fl_standard_method_codec.h"
"fl_string_codec.h"
"fl_value.h"
"fl_view.h"
"flutter_linux.h"
)
list_prepend(FLUTTER_LIBRARY_HEADERS "${EPHEMERAL_DIR}/flutter_linux/")
add_library(flutter INTERFACE)
target_include_directories(flutter INTERFACE
"${EPHEMERAL_DIR}"
)
target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}")
target_link_libraries(flutter INTERFACE
PkgConfig::GTK
PkgConfig::GLIB
PkgConfig::GIO
)
add_dependencies(flutter flutter_assemble)
# === Flutter tool backend ===
# _phony_ is a non-existent file to force this command to run every time,
# since currently there's no way to get a full input/output list from the
# flutter tool.
add_custom_command(
OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS}
${CMAKE_CURRENT_BINARY_DIR}/_phony_
COMMAND ${CMAKE_COMMAND} -E env
${FLUTTER_TOOL_ENVIRONMENT}
"${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.sh"
${FLUTTER_TARGET_PLATFORM} ${CMAKE_BUILD_TYPE}
VERBATIM
)
add_custom_target(flutter_assemble DEPENDS
"${FLUTTER_LIBRARY}"
${FLUTTER_LIBRARY_HEADERS}
)

View File

@ -1,23 +0,0 @@
//
// Generated file. Do not edit.
//
// clang-format off
#include "generated_plugin_registrant.h"
#include <file_selector_linux/file_selector_plugin.h>
#include <flutter_secure_storage_linux/flutter_secure_storage_linux_plugin.h>
#include <url_launcher_linux/url_launcher_plugin.h>
void fl_register_plugins(FlPluginRegistry* registry) {
g_autoptr(FlPluginRegistrar) file_selector_linux_registrar =
fl_plugin_registry_get_registrar_for_plugin(registry, "FileSelectorPlugin");
file_selector_plugin_register_with_registrar(file_selector_linux_registrar);
g_autoptr(FlPluginRegistrar) flutter_secure_storage_linux_registrar =
fl_plugin_registry_get_registrar_for_plugin(registry, "FlutterSecureStorageLinuxPlugin");
flutter_secure_storage_linux_plugin_register_with_registrar(flutter_secure_storage_linux_registrar);
g_autoptr(FlPluginRegistrar) url_launcher_linux_registrar =
fl_plugin_registry_get_registrar_for_plugin(registry, "UrlLauncherPlugin");
url_launcher_plugin_register_with_registrar(url_launcher_linux_registrar);
}

View File

@ -1,15 +0,0 @@
//
// Generated file. Do not edit.
//
// clang-format off
#ifndef GENERATED_PLUGIN_REGISTRANT_
#define GENERATED_PLUGIN_REGISTRANT_
#include <flutter_linux/flutter_linux.h>
// Registers Flutter plugins.
void fl_register_plugins(FlPluginRegistry* registry);
#endif // GENERATED_PLUGIN_REGISTRANT_

View File

@ -1,27 +0,0 @@
#
# Generated file, do not edit.
#
list(APPEND FLUTTER_PLUGIN_LIST
file_selector_linux
flutter_secure_storage_linux
url_launcher_linux
)
list(APPEND FLUTTER_FFI_PLUGIN_LIST
jni
)
set(PLUGIN_BUNDLED_LIBRARIES)
foreach(plugin ${FLUTTER_PLUGIN_LIST})
add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/linux plugins/${plugin})
target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin)
list(APPEND PLUGIN_BUNDLED_LIBRARIES $<TARGET_FILE:${plugin}_plugin>)
list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries})
endforeach(plugin)
foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST})
add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/linux plugins/${ffi_plugin})
list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries})
endforeach(ffi_plugin)

View File

@ -1,26 +0,0 @@
cmake_minimum_required(VERSION 3.13)
project(runner LANGUAGES CXX)
# Define the application target. To change its name, change BINARY_NAME in the
# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer
# work.
#
# Any new source files that you add to the application should be added here.
add_executable(${BINARY_NAME}
"main.cc"
"my_application.cc"
"${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc"
)
# Apply the standard set of build settings. This can be removed for applications
# that need different build settings.
apply_standard_settings(${BINARY_NAME})
# Add preprocessor definitions for the application ID.
add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}")
# Add dependency libraries. Add any application-specific dependencies here.
target_link_libraries(${BINARY_NAME} PRIVATE flutter)
target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK)
target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}")

View File

@ -1,6 +0,0 @@
#include "my_application.h"
int main(int argc, char** argv) {
g_autoptr(MyApplication) app = my_application_new();
return g_application_run(G_APPLICATION(app), argc, argv);
}

View File

@ -1,153 +0,0 @@
#include "my_application.h"
#include <flutter_linux/flutter_linux.h>
#ifdef GDK_WINDOWING_X11
#include <gdk/gdkx.h>
#endif
#include "flutter/generated_plugin_registrant.h"
struct _MyApplication {
GtkApplication parent_instance;
char** dart_entrypoint_arguments;
};
G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION)
// Called when first Flutter frame received.
static void first_frame_cb(MyApplication* self, FlView* view) {
gtk_widget_show(gtk_widget_get_toplevel(GTK_WIDGET(view)));
}
// Implements GApplication::activate.
static void my_application_activate(GApplication* application) {
MyApplication* self = MY_APPLICATION(application);
GtkWindow* window =
GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application)));
// Use a header bar when running in GNOME as this is the common style used
// by applications and is the setup most users will be using (e.g. Ubuntu
// desktop).
// If running on X and not using GNOME then just use a traditional title bar
// in case the window manager does more exotic layout, e.g. tiling.
// If running on Wayland assume the header bar will work (may need changing
// if future cases occur).
gboolean use_header_bar = TRUE;
#ifdef GDK_WINDOWING_X11
GdkScreen* screen = gtk_window_get_screen(window);
if (GDK_IS_X11_SCREEN(screen)) {
const gchar* wm_name = gdk_x11_screen_get_window_manager_name(screen);
if (g_strcmp0(wm_name, "GNOME Shell") != 0) {
use_header_bar = FALSE;
}
}
#endif
if (use_header_bar) {
GtkHeaderBar* header_bar = GTK_HEADER_BAR(gtk_header_bar_new());
gtk_widget_show(GTK_WIDGET(header_bar));
gtk_header_bar_set_title(header_bar, "todo");
gtk_header_bar_set_show_close_button(header_bar, TRUE);
gtk_window_set_titlebar(window, GTK_WIDGET(header_bar));
} else {
gtk_window_set_title(window, "todo");
}
gtk_window_set_default_size(window, 1280, 720);
// Resolved from the hicolor icon theme, which linux/install_desktop_entry.sh
// populates from linux/icons/. Without this the GTK runner shows a generic
// placeholder in the taskbar, since Flutter never sets a window icon itself.
gtk_window_set_icon_name(window, "todo");
g_autoptr(FlDartProject) project = fl_dart_project_new();
fl_dart_project_set_dart_entrypoint_arguments(
project, self->dart_entrypoint_arguments);
FlView* view = fl_view_new(project);
GdkRGBA background_color;
// Background defaults to black, override it here if necessary, e.g. #00000000
// for transparent.
gdk_rgba_parse(&background_color, "#000000");
fl_view_set_background_color(view, &background_color);
gtk_widget_show(GTK_WIDGET(view));
gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view));
// Show the window when Flutter renders.
// Requires the view to be realized so we can start rendering.
g_signal_connect_swapped(view, "first-frame", G_CALLBACK(first_frame_cb),
self);
gtk_widget_realize(GTK_WIDGET(view));
fl_register_plugins(FL_PLUGIN_REGISTRY(view));
gtk_widget_grab_focus(GTK_WIDGET(view));
}
// Implements GApplication::local_command_line.
static gboolean my_application_local_command_line(GApplication* application,
gchar*** arguments,
int* exit_status) {
MyApplication* self = MY_APPLICATION(application);
// Strip out the first argument as it is the binary name.
self->dart_entrypoint_arguments = g_strdupv(*arguments + 1);
g_autoptr(GError) error = nullptr;
if (!g_application_register(application, nullptr, &error)) {
g_warning("Failed to register: %s", error->message);
*exit_status = 1;
return TRUE;
}
g_application_activate(application);
*exit_status = 0;
return TRUE;
}
// Implements GApplication::startup.
static void my_application_startup(GApplication* application) {
// MyApplication* self = MY_APPLICATION(object);
// Perform any actions required at application startup.
G_APPLICATION_CLASS(my_application_parent_class)->startup(application);
}
// Implements GApplication::shutdown.
static void my_application_shutdown(GApplication* application) {
// MyApplication* self = MY_APPLICATION(object);
// Perform any actions required at application shutdown.
G_APPLICATION_CLASS(my_application_parent_class)->shutdown(application);
}
// Implements GObject::dispose.
static void my_application_dispose(GObject* object) {
MyApplication* self = MY_APPLICATION(object);
g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev);
G_OBJECT_CLASS(my_application_parent_class)->dispose(object);
}
static void my_application_class_init(MyApplicationClass* klass) {
G_APPLICATION_CLASS(klass)->activate = my_application_activate;
G_APPLICATION_CLASS(klass)->local_command_line =
my_application_local_command_line;
G_APPLICATION_CLASS(klass)->startup = my_application_startup;
G_APPLICATION_CLASS(klass)->shutdown = my_application_shutdown;
G_OBJECT_CLASS(klass)->dispose = my_application_dispose;
}
static void my_application_init(MyApplication* self) {}
MyApplication* my_application_new() {
// Set the program name to the application ID, which helps various systems
// like GTK and desktop environments map this running application to its
// corresponding .desktop file. This ensures better integration by allowing
// the application to be recognized beyond its binary name.
g_set_prgname(APPLICATION_ID);
return MY_APPLICATION(g_object_new(my_application_get_type(),
"application-id", APPLICATION_ID, "flags",
G_APPLICATION_NON_UNIQUE, nullptr));
}

View File

@ -1,21 +0,0 @@
#ifndef FLUTTER_MY_APPLICATION_H_
#define FLUTTER_MY_APPLICATION_H_
#include <gtk/gtk.h>
G_DECLARE_FINAL_TYPE(MyApplication,
my_application,
MY,
APPLICATION,
GtkApplication)
/**
* my_application_new:
*
* Creates a new Flutter-based application.
*
* Returns: a new #MyApplication.
*/
MyApplication* my_application_new();
#endif // FLUTTER_MY_APPLICATION_H_

View File

@ -110,10 +110,10 @@ packages:
dependency: transitive
description:
name: cross_file
sha256: "28bb3ae56f117b5aec029d702a90f57d285cd975c3c5c281eaca38dbc47c5937"
sha256: "92c9c43c383bfa1c32079d3bc492d55d6d4318044b7b47edaff8971cbb555c51"
url: "https://pub.dev"
source: hosted
version: "0.3.5+2"
version: "0.3.5+4"
crypto:
dependency: transitive
description:
@ -134,10 +134,10 @@ packages:
dependency: transitive
description:
name: dev_build
sha256: "21df3f741f0f5fc7c45f618e68e206b9f021b1adf83db4004dfaa032996cb0c1"
sha256: f639b36c1cf845c11b506b562e162eca84f2cb368cf9cca48117069f881d4be8
url: "https://pub.dev"
source: hosted
version: "1.1.8+2"
version: "1.1.8+3"
fake_async:
dependency: "direct dev"
description:
@ -345,6 +345,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "4.1.2"
idb_shim:
dependency: "direct main"
description:
name: idb_shim
sha256: "3448298f244bc76a14aca71461eeab6add2b8a877930521c42c2e8b71b644590"
url: "https://pub.dev"
source: hosted
version: "2.9.6+2"
image:
dependency: transitive
description:
@ -445,10 +453,10 @@ packages:
dependency: transitive
description:
name: native_toolchain_c
sha256: f59351d28f49520cd3a74eb1f41c5f19ae15e53c65a3231d14af672e46510a96
sha256: f9c168717100ae6d9fee9ffb0be379bf1f8b26b0f6bcbd4fdddcd931993a6a72
url: "https://pub.dev"
source: hosted
version: "0.19.1"
version: "0.19.2"
objective_c:
dependency: transitive
description:
@ -477,10 +485,10 @@ packages:
dependency: "direct main"
description:
name: path_provider
sha256: "50c5dd5b6e1aaf6fb3a78b33f6aa3afca52bf903a8a5298f53101fdaee55bbcd"
sha256: a7f4874f987173da295a61c181b8ee71dab59b332a486b391babf26a1b884825
url: "https://pub.dev"
source: hosted
version: "2.1.5"
version: "2.1.6"
path_provider_android:
dependency: transitive
description:
@ -501,18 +509,18 @@ packages:
dependency: transitive
description:
name: path_provider_linux
sha256: f7a1fe3a634fe7734c8d3f2766ad746ae2a2884abe22e241a8b301bf5cac3279
sha256: "58c2005f147315b11e9b4a7bc889cd5203e250cba8e3f012dae259b4972b5c16"
url: "https://pub.dev"
source: hosted
version: "2.2.1"
version: "2.2.2"
path_provider_platform_interface:
dependency: transitive
description:
name: path_provider_platform_interface
sha256: "88f5779f72ba699763fa3a3b06aa4bf6de76c8e5de842cf6f29e2e06476c2334"
sha256: "484838772624c3a4b94f1e44a3e19897fee738f2d5c4ce448443b0417f7c9dda"
url: "https://pub.dev"
source: hosted
version: "2.1.2"
version: "2.1.3"
path_provider_windows:
dependency: transitive
description:
@ -565,10 +573,10 @@ packages:
dependency: transitive
description:
name: process_run
sha256: "3af4220bdee974fd6305caab920c8af07cd846696f825e6e84fb4e123b13fde9"
sha256: dadbf4986ddab79086a107b2f893bacd580a523453f76238bc0c13a9faa982af
url: "https://pub.dev"
source: hosted
version: "1.3.4"
version: "1.3.4+1"
pub_semver:
dependency: transitive
description:
@ -585,14 +593,22 @@ packages:
url: "https://pub.dev"
source: hosted
version: "0.6.0"
sembast:
dependency: transitive
description:
name: sembast
sha256: a58b26925e23071cf0f4754d8449aabe829e9a9930a872fb18e6ae4c2c88e025
url: "https://pub.dev"
source: hosted
version: "3.8.9+1"
share_plus:
dependency: "direct main"
description:
name: share_plus
sha256: a857d8b1479250aff6b57a51b2c02d31ca05848d441817c43f1640c885c286c0
sha256: "02180b01c1237b9706b663d9402b2cf2402b3407f48cce99cc19e3200f095b8a"
url: "https://pub.dev"
source: hosted
version: "13.1.0"
version: "13.2.1"
share_plus_platform_interface:
dependency: transitive
description:
@ -613,10 +629,10 @@ packages:
dependency: transitive
description:
name: shared_preferences_android
sha256: "93ae5884a9df5d3bb696825bceb3a17590754548b5d740eba51500afc8d088f5"
sha256: "0634e64bd719f89c012f392938e173521f535d3ecaf66558fa94a056d22b5cc7"
url: "https://pub.dev"
source: hosted
version: "2.4.26"
version: "2.4.27"
shared_preferences_foundation:
dependency: transitive
description:
@ -706,10 +722,10 @@ packages:
dependency: transitive
description:
name: sqlite3
sha256: "37356bcb56ce0d9404d602c41e4bdb7765e7e9732a3e47adb3d98c556a6abdad"
sha256: c73fd75df1332d76a6257f4823ae4df9c791f522b97e4a60cbcad214de1becf4
url: "https://pub.dev"
source: hosted
version: "3.3.3"
version: "3.5.0"
sqlite_crdt:
dependency: "direct main"
description:
@ -850,10 +866,10 @@ packages:
dependency: "direct main"
description:
name: uuid
sha256: "1fef9e8e11e2991bb773070d4656b7bd5d850967a2456cfc83cf47925ba79489"
sha256: "9b129329f58692f6e6578329498a8fe9fbe98f090beb764ffbb8ee2eadd01dcd"
url: "https://pub.dev"
source: hosted
version: "4.5.3"
version: "4.6.0"
vector_math:
dependency: transitive
description:

View File

@ -47,6 +47,7 @@ dependencies:
# libsecret) instead of plaintext SharedPreferences.
flutter_secure_storage: ^10.3.1
http: ^1.6.0
idb_shim: ^2.9.6+2
path: ^1.9.1
path_provider: ^2.1.5
share_plus: ^13.1.0

10
run.sh
View File

@ -119,11 +119,17 @@ main() {
command -v flutter >/dev/null 2>&1 || { err "flutter still not on PATH after install"; exit 1; }
cd "${SCRIPT_DIR}"
flutter config --enable-linux-desktop >/dev/null
flutter config --enable-web >/dev/null
log "fetching pub packages"
flutter pub get
# The desktop app is a web build served by the local wrapper: Flutter's
# Linux embedder manages only ~20fps at 4K, while the same Dart code in
# Chrome sustains ~144fps (docs/desktop-performance-findings.md).
log "building the web bundle"
flutter build web --release
log "launching the app"
exec flutter run -d linux
exec dart run bin/todo_desktop.dart --web-root "${SCRIPT_DIR}/build/web"
}
main "$@"

View File

@ -102,6 +102,9 @@ class FakeNoteRepository implements NoteRepository {
@override
Future<void> importLog(Log remote) async {}
@override
Future<void> seedFrom(Log log) async {}
@override
Future<void> close() async {
await _controller.close();

View File

@ -7,8 +7,10 @@ import 'package:sqflite_common_ffi/sqflite_ffi.dart';
// SqliteCrdt is needed to seed the legacy DB in migration tests; hide its Hlc
// so the crdt_sync Hlc/Record are unambiguous.
import 'package:sqlite_crdt/sqlite_crdt.dart' hide Hlc;
import 'package:path/path.dart' as p;
import 'package:todo/data/note.dart';
import 'package:todo/data/note_repository.dart';
import 'package:todo/data/repository_factory_io.dart';
void main() {
setUpAll(sqfliteFfiInit);
@ -292,7 +294,7 @@ void main() {
test('v2→v3 migration backfills priority 0 to medium', () async {
SharedPreferences.setMockInitialValues({});
final dir = await Directory.systemTemp.createTemp('todo_migration');
final path = '${dir.path}/notes.db';
final path = '${dir.path}/todo.db';
addTearDown(() => dir.delete(recursive: true));
// Build a v2 database (status column present, no priority backfill) and
@ -323,7 +325,7 @@ void main() {
await v2.close();
// Reopening through the repository runs onUpgrade to v3.
final repo = await NoteRepository.open(path);
final repo = await openRepositoryIn(p.dirname(path));
addTearDown(repo.close);
final notes = await repo.listNotes();
@ -334,7 +336,7 @@ void main() {
test('v1→v2 migration adds the status column with a default', () async {
SharedPreferences.setMockInitialValues({});
final dir = await Directory.systemTemp.createTemp('todo_migration_v1');
final path = '${dir.path}/notes.db';
final path = '${dir.path}/todo.db';
addTearDown(() => dir.delete(recursive: true));
// v1 schema predates the status column entirely.
@ -363,7 +365,7 @@ void main() {
await v1.close();
// Reopening runs onUpgrade v1→v2 (adds status, default todo) then v2→v3.
final repo = await NoteRepository.open(path);
final repo = await openRepositoryIn(p.dirname(path));
addTearDown(repo.close);
final notes = await repo.listNotes();
expect(notes.single.id, 'old');
@ -453,7 +455,7 @@ void main() {
addTearDown(() => dir.delete(recursive: true));
final path = await seedLegacyDb(dir.path);
final repo = await NoteRepository.open(path);
final repo = await openRepositoryIn(p.dirname(path));
addTearDown(repo.close);
// The live note migrated with its fields intact...
@ -469,7 +471,7 @@ void main() {
// survives, and the (still-present) legacy DB is not re-imported.
await repo.upsert(note('new', 'added post-migration'));
await repo.close();
final reopened = await NoteRepository.open(path);
final reopened = await openRepositoryIn(p.dirname(path));
addTearDown(reopened.close);
final texts = (await reopened.listNotes()).map((n) => n.text).toSet();
expect(texts, {'kept idea', 'added post-migration'});
@ -480,7 +482,7 @@ void main() {
final dir = await Directory.systemTemp.createTemp('todo_fresh');
addTearDown(() => dir.delete(recursive: true));
final repo = await NoteRepository.open('${dir.path}/todo.db');
final repo = await openRepositoryIn(dir.path);
addTearDown(repo.close);
expect(await repo.listNotes(), isEmpty);

View File

@ -1,3 +1,4 @@
import 'dart:io';
import 'dart:convert';
import 'package:file_selector_platform_interface/file_selector_platform_interface.dart';
@ -8,6 +9,7 @@ import 'package:http/http.dart' as http;
import 'package:http/testing.dart';
import 'package:plugin_platform_interface/plugin_platform_interface.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:todo/sync/backlog_export_io.dart';
import 'package:todo/data/note.dart';
import 'package:todo/data/note_repository.dart';
import 'package:todo/sync/notes_markdown.dart';
@ -275,7 +277,26 @@ void main() {
expect(find.textContaining('sync failed'), findsOneWidget);
});
test('the default export home is the real HOME', () {
// Guards the production default, which every other test overrides so the
// suite cannot write to the user's ~/todo.
expect(resolveExportHome(), Platform.environment['HOME']);
});
testWidgets('Export notes writes the backlog file (desktop)', (tester) async {
// Redirect HOME: this test does real file I/O, and without the override it
// overwrites the user's canonical ~/todo/BACKLOG.md with the fake note
// below on every test run.
// Sync creation: awaiting real file I/O under the widget tester's fake
// clock never completes.
final home = Directory.systemTemp.createTempSync('todo_export_home');
resolveExportHome = () => home.path;
addTearDown(() {
resolveExportHome =
() => Platform.environment['HOME'] ?? Directory.current.path;
home.deleteSync(recursive: true);
});
await pumpSettings(
tester,
seed: [

View File

@ -0,0 +1,153 @@
import 'dart:convert';
import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart' as http;
import 'package:path/path.dart' as p;
import 'package:todo/desktop/wrapper_server.dart';
void main() {
late Directory root;
late WrapperServer server;
late String base;
setUp(() async {
root = await Directory.systemTemp.createTemp('wrapper');
final webRoot = Directory(p.join(root.path, 'web'))..createSync();
File(p.join(webRoot.path, 'index.html')).writeAsStringSync('<h1>todo</h1>');
File(p.join(webRoot.path, 'main.dart.js')).writeAsStringSync('console;');
File(p.join(webRoot.path, 'canvaskit.wasm')).writeAsStringSync('binary');
server = WrapperServer(
webRoot: webRoot.path,
backlogPath: p.join(root.path, 'todo', 'BACKLOG.md'),
logPath: p.join(root.path, 'state', 'todo_notes.json'),
);
// Port 0 lets the OS pick, so tests never collide with a running app.
await server.start(0);
base = 'http://localhost:${server.port}';
});
tearDown(() async {
await server.stop();
root.deleteSync(recursive: true);
});
test('serves index.html at the root', () async {
final response = await http.get(Uri.parse('$base/'));
expect(response.statusCode, 200);
expect(response.body, contains('todo'));
});
test('serves nested assets and 404s unknown paths', () async {
expect((await http.get(Uri.parse('$base/main.dart.js'))).statusCode, 200);
expect((await http.get(Uri.parse('$base/nope.js'))).statusCode, 404);
});
test('refuses to serve outside the web root', () async {
// The served directory sits beside the user's files, so traversal must not
// be able to read them. Sent over a raw socket because http.get normalises
// `..` away client-side, so the server would never see the attack.
File(p.join(root.path, 'secret')).writeAsStringSync('do not serve me');
// Percent-encoded, because both the http client and Dart's HttpServer
// collapse a literal `..` before any handler sees it; `%2e%2e` survives
// that and is decoded into the path afterwards.
final socket = await Socket.connect('localhost', server.port);
socket.write('GET /%2e%2e/secret HTTP/1.1\r\nHost: localhost\r\n\r\n');
await socket.flush();
final response = await utf8.decoder.bind(socket).first;
await socket.close();
// Dart's HttpServer decodes and then normalises, so traversal is already
// collapsed before any handler runs and this comes back 404 rather than
// 403. What matters is the property, not which code rejected it: the file
// outside the web root is never served.
expect(response, isNot(contains('do not serve me')));
expect(response, anyOf(contains('403'), contains('404')));
});
test('a failing write reports a server error rather than crashing', () async {
// Parent path is a regular file, so creating the directory for the backup
// throws. The serve loop must survive it and keep answering requests.
final blocked = Directory(p.join(root.path, 'blocked'))..createSync();
File(p.join(blocked.path, 'wall')).writeAsStringSync('');
final wedged = WrapperServer(
webRoot: p.join(root.path, 'web'),
backlogPath: p.join(blocked.path, 'wall', 'nested', 'BACKLOG.md'),
logPath: p.join(root.path, 'state', 'todo_notes.json'),
);
await wedged.start(0);
addTearDown(wedged.stop);
final response = await http.post(
Uri.parse('http://localhost:${wedged.port}/backup/backlog'),
body: 'x',
);
expect(response.statusCode, 500);
// Still alive afterwards.
final after = await http.get(
Uri.parse('http://localhost:${wedged.port}/'),
);
expect(after.statusCode, 200);
});
test('POST then GET round-trips the backlog', () async {
final posted = await http.post(
Uri.parse('$base/backup/backlog'),
body: '# backlog\n\nnote one\n',
);
expect(posted.statusCode, 204);
// Written to the real path, which is what the user's tooling reads.
final onDisk = File(p.join(root.path, 'todo', 'BACKLOG.md'));
expect(onDisk.existsSync(), isTrue);
expect(onDisk.readAsStringSync(), contains('note one'));
final fetched = await http.get(Uri.parse('$base/backup/backlog'));
expect(fetched.statusCode, 200);
expect(fetched.body, contains('note one'));
});
test('POST then GET round-trips the note log', () async {
await http.post(Uri.parse('$base/backup/log'), body: '{"a":1}');
final fetched = await http.get(Uri.parse('$base/backup/log'));
expect(fetched.body, '{"a":1}');
});
test('GET on a backup that does not exist yet 404s', () async {
expect((await http.get(Uri.parse('$base/backup/log'))).statusCode, 404);
});
test('rejects unsupported methods on a backup path', () async {
final response = await http.delete(Uri.parse('$base/backup/log'));
expect(response.statusCode, 405);
});
test('labels wasm and js correctly', () async {
// CanvasKit refuses a .wasm served as anything else, and the app then
// renders nothing at all.
final wasm = await http.get(Uri.parse('$base/canvaskit.wasm'));
expect(wasm.headers['content-type'], contains('application/wasm'));
final js = await http.get(Uri.parse('$base/main.dart.js'));
expect(js.headers['content-type'], contains('javascript'));
});
test('contentTypeFor covers the asset kinds the build emits', () {
String kind(String name) =>
WrapperServer.contentTypeFor(name).mimeType;
expect(kind('a.html'), 'text/html');
expect(kind('a.json'), 'application/json');
expect(kind('a.css'), 'text/css');
expect(kind('a.png'), 'image/png');
expect(kind('a.svg'), 'image/svg+xml');
expect(kind('a.ttf'), 'font/ttf');
expect(kind('a.otf'), 'font/otf');
expect(kind('a.woff2'), 'font/woff2');
expect(kind('a.mjs'), 'text/javascript');
expect(kind('a.bin'), 'application/octet-stream');
expect(kind('a.unknown'), 'application/octet-stream');
});
}

BIN
web/favicon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 917 B

BIN
web/icons/Icon-192.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

BIN
web/icons/Icon-512.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

46
web/index.html Normal file
View File

@ -0,0 +1,46 @@
<!DOCTYPE html>
<html>
<head>
<!--
If you are serving your web app in a path other than the root, change the
href value below to reflect the base path you are serving from.
The path provided below has to start and end with a slash "/" in order for
it to work correctly.
For more details:
* https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base
This is a placeholder for base href that will be replaced by the value of
the `--base-href` argument provided to `flutter build`.
-->
<base href="$FLUTTER_BASE_HREF">
<meta charset="UTF-8">
<meta content="IE=Edge" http-equiv="X-UA-Compatible">
<meta name="description" content="A new Flutter project.">
<!-- iOS meta tags & icons -->
<meta name="mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="apple-mobile-web-app-title" content="todo">
<link rel="apple-touch-icon" href="icons/Icon-192.png">
<!-- Favicon -->
<link rel="icon" type="image/png" href="favicon.png"/>
<title>todo</title>
<link rel="manifest" href="manifest.json">
</head>
<body>
<!--
You can customize the "flutter_bootstrap.js" script.
This is useful to provide a custom configuration to the Flutter loader
or to give the user feedback during the initialization process.
For more details:
* https://docs.flutter.dev/platform-integration/web/initialization
-->
<script src="flutter_bootstrap.js" async></script>
</body>
</html>

35
web/manifest.json Normal file
View File

@ -0,0 +1,35 @@
{
"name": "todo",
"short_name": "todo",
"start_url": ".",
"display": "standalone",
"background_color": "#0175C2",
"theme_color": "#0175C2",
"description": "A new Flutter project.",
"orientation": "portrait-primary",
"prefer_related_applications": false,
"icons": [
{
"src": "icons/Icon-192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "icons/Icon-512.png",
"sizes": "512x512",
"type": "image/png"
},
{
"src": "icons/Icon-maskable-192.png",
"sizes": "192x192",
"type": "image/png",
"purpose": "maskable"
},
{
"src": "icons/Icon-maskable-512.png",
"sizes": "512x512",
"type": "image/png",
"purpose": "maskable"
}
]
}