Compare commits

...

4 Commits

Author SHA1 Message Date
ded7486244 Fix lints in error icon page
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint) (push) Waiting to run
Tests / test (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 18:21:46 +01:00
8068205d0c Page loads of errors show an icon page
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 18:16:04 +01:00
91a9ee5295 Proxy errors load as an empty page
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 18:01:22 +01:00
0982565fdc Rename existing reminder channel on start
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 17:56:27 +01:00
7 changed files with 156 additions and 2 deletions

View File

@ -0,0 +1,35 @@
/// A wordless page for an error the window itself loaded: Chrome would
/// otherwise paint its own "This page isn't working" sentences over an
/// empty error body. Only the title carries the app's name (OS-level label).
library;
import 'dart:io';
/// HTML page with only an icon — no words painted by the browser.
const String errorIconPage =
'<!doctype html><html><head><meta charset="utf-8"> '
'<title>Diet Guard</title> '
'<style>html,body{margin:0;height:100%; '
'background:#211D1B;display:flex;align-items:center; '
'justify-content:center}</style></head><body> '
'<svg width="96" height="96" viewBox="0 0 24 24" fill="none" '
'stroke="#A39892" stroke-width="2" stroke-linecap="round" '
'aria-hidden="true"><circle cx="12" cy="12" r="9"/> '
'<line x1="5.6" y1="18.4" x2="18.4" y2="5.6"/></svg></body></html>';
/// Whether [request] is the window loading a page, not the app's fetch().
bool isNavigation(HttpRequest request) =>
request.headers.value('sec-fetch-mode') == 'navigate';
/// Replaces an error answer to a page load with [errorIconPage]. Does
/// nothing for fetch() calls, successes, or a response already written.
void paintErrorIcon(HttpRequest request) {
final response = request.response;
if (!isNavigation(request) || response.statusCode < 400) return;
try {
response.headers.contentType = ContentType.html;
response.write(errorIconPage);
} on Exception {
return; // body already sent: leave it alone
}
}

View File

@ -19,6 +19,7 @@ library;
import 'dart:convert';
import 'dart:io';
import 'package:diet_guard_app/desktop/error_page.dart' show isNavigation;
import 'package:http/http.dart' as http;
/// GitHub's REST API base, which [GitHubProxy] fronts.
@ -177,8 +178,13 @@ class GitHubProxy {
}
void _passThrough(HttpRequest request, http.Response response) {
request.response.statusCode = response.statusCode;
if (isNavigation(request)) {
// Top-level navigation (window load) must not paint error JSON; the app's
// own fetch() calls never send 'navigate', so they still get the body.
return;
}
request.response
..statusCode = response.statusCode
..headers.contentType = ContentType.json
..add(response.bodyBytes);
}

View File

@ -24,6 +24,7 @@ import 'dart:io';
import 'package:crdt_sync/crdt_sync.dart';
import 'package:diet_guard_app/desktop/content_types.dart' as content_types;
import 'package:diet_guard_app/desktop/error_page.dart';
import 'package:diet_guard_app/desktop/github_proxy.dart';
import 'package:diet_guard_app/services/desktop_wrapper.dart';
import 'package:path/path.dart' as p;
@ -91,6 +92,7 @@ class WrapperServer {
} on Exception {
request.response.statusCode = HttpStatus.internalServerError;
}
paintErrorIcon(request);
await request.response.close();
}
}

View File

@ -24,6 +24,20 @@ class LocalNotificationsBackend implements NotificationBackend {
android: AndroidInitializationSettings('@mipmap/ic_launcher'),
);
await plugin.initialize(settings: settings);
// Re-create the channel so Android renames it if an install still shows
// the old "Meal reminders" label.
await plugin
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin
>()
?.createNotificationChannel(
const AndroidNotificationChannel(
_channelId,
_channelName,
importance: Importance.high,
),
);
}
/// Requests Android 13+'s runtime `POST_NOTIFICATIONS` permission.

View File

@ -2,7 +2,7 @@ name: diet_guard_app
description: "Companion phone app for diet_guard: log meals on the go."
publish_to: 'none'
version: 1.0.150+1
version: 1.0.154+1
environment:
sdk: ^3.12.2

View File

@ -13,6 +13,16 @@ import 'package:http/http.dart' as http;
import 'package:http/testing.dart';
import 'package:path/path.dart' as p;
/// Removes <title> and <style> tags, strips all remaining HTML tags, and
/// returns every [A-Za-z]{2,} match — i.e. all visible words the browser would
/// paint for a top-level navigation.
List<String> paintedWords(String html) {
var noTitle = html.replaceAll(RegExp(r'<title>.*?</title>', dotAll: true), '');
var noStyle = noTitle.replaceAll(RegExp(r'<style>.*?</style>', dotAll: true), '');
var noTags = noStyle.replaceAll(RegExp(r'<[^>]*>'), '');
return RegExp(r'[A-Za-z]{2,}').allMatches(noTags).map((m) => m.group(0)!).toList();
}
void main() {
late Directory tempDir;
late WrapperServer server;
@ -69,5 +79,75 @@ void main() {
expect(response.statusCode, status);
expect(response.body, isEmpty, reason: 'nothing painted in the window');
});
test('$method $path loaded as a page shows only an icon', () async {
final request = http.Request(method, url(path))
..headers['sec-fetch-mode'] = 'navigate';
final response = await http.Response.fromStream(
await http.Client().send(request),
);
expect(response.statusCode, status);
expect(response.headers['content-type'], contains('text/html'));
expect(response.body, contains('<svg'));
expect(paintedWords(response.body), isEmpty);
});
}
group('proxy error responses', () {
late Directory tempDir;
late WrapperServer server;
setUp(() async {
tempDir = await Directory.systemTemp.createTemp('diet_guard_proxy_err_');
final webRoot = p.join(tempDir.path, 'web');
final dataDir = p.join(tempDir.path, 'data');
await Directory(webRoot).create(recursive: true);
File(p.join(webRoot, 'index.html')).writeAsStringSync('<html></html>');
await Directory(dataDir).create(recursive: true);
File(p.join(dataDir, 'documents')).writeAsStringSync('');
final tokenPath = p.join(tempDir.path, 'sync_token');
await File(tokenPath).writeAsString('t');
server = WrapperServer(
webRoot: webRoot,
dataDir: dataDir,
gitHubProxy: GitHubProxy(
tokenPath: tokenPath,
fallbackTokenPath: p.join(tempDir.path, 'fallback_token'),
httpClient: MockClient((_) async =>
http.Response('{"message": "Bad credentials"}', 401)),
),
);
await server.start(0);
});
tearDown(() async {
await server.stop();
await tempDir.delete(recursive: true);
});
Uri url(String path) => Uri.parse('http://localhost:${server.port}$path');
test('a proxy error loaded as a page shows only an icon', () async {
final request = http.Request('GET', url('/github/api/repos/o/r/contents/x'))
..headers['sec-fetch-mode'] = 'navigate';
final response = await http.Response.fromStream(
await http.Client().send(request),
);
expect(response.statusCode, HttpStatus.unauthorized);
expect(response.headers['content-type'], contains('text/html'));
expect(response.body, contains('<svg'));
expect(paintedWords(response.body), isEmpty);
});
test('the app fetch still gets the proxy error body', () async {
final response = await http.Response.fromStream(
await http.Client().send(http.Request(
'GET',
url('/github/api/repos/o/r/contents/x'),
)),
);
expect(response.statusCode, HttpStatus.unauthorized);
expect(response.body, contains('Bad credentials'));
});
});
}

View File

@ -34,6 +34,23 @@ void main() {
expect(log.where((c) => c.method == 'initialize'), hasLength(1));
});
test('init renames the reminder channel to the app name', () async {
final log = installFakeAndroidNotifications();
NotificationService.resetForTesting(
backend: LocalNotificationsBackend(FlutterLocalNotificationsPlugin()),
);
await NotificationService.init();
final createCall = log.firstWhere(
(c) => c.method == 'createNotificationChannel',
orElse: () => throw StateError('no createNotificationChannel call logged'),
);
final args = createCall.arguments as Map;
expect(args['id'], reminderChannelId);
expect(args['name'], 'DietGuard');
});
test('requestPermission delegates to the Android implementation', () async {
installFakeAndroidNotifications();
NotificationService.resetForTesting(