From 51af6befe72e1f7f26daaa65c1f30f0eba70fff2 Mon Sep 17 00:00:00 2001 From: John Taylor Date: Wed, 12 Aug 2026 20:05:15 -0400 Subject: [PATCH] fix(ai): recognize an installed model on launch; never ask macOS for the GPU MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two defects from one device session. The interpreter boots at needsDownload and only refresh() consults the disk, but nothing ever called refresh() — so an already-downloaded model read as missing on every launch, and the shell's onPause dispose() had no mirror, dropping the same way on a background cycle. HomeShell now restores on mount and on onRestart, gated on aiEnabled so an AI-off run never constructs the interpreter at all. The "Download model" tap that followed then found the file already installed and fell straight through to the load, which SIGSEGV'd the process on macOS: with backend=gpu, LiteRT's ReplaceMagicNumbersIfAny reads a garbage config count (num_configs=4294967300, i.e. 4 + 2^32), walks off the array, and faults inside its own logger on a null char*. That is the same shape as the iOS Metal null-deref already handled here — a native crash, so _loadModel's step-down ladder can never catch it and fall back. The backend list moves into a testable backendsFor(platform); macOS joins iOS as CPU-only, which is the path that had been loading the file successfully all along. Device-verified on macOS: the app restores the model on launch and stays up where it previously died about two seconds in. Co-Authored-By: Claude --- lib/shared/home_shell.dart | 15 +++++ lib/state/interpreter_gemma.dart | 46 +++++++++----- test/interpreter_restore_test.dart | 96 ++++++++++++++++++++++++++++++ 3 files changed, 141 insertions(+), 16 deletions(-) create mode 100644 test/interpreter_restore_test.dart diff --git a/lib/shared/home_shell.dart b/lib/shared/home_shell.dart index c3cbd207..69c83b42 100644 --- a/lib/shared/home_shell.dart +++ b/lib/shared/home_shell.dart @@ -79,10 +79,25 @@ class _HomeShellState extends ConsumerState { if (!kIsWeb) { _lifecycle = AppLifecycleListener( onPause: () => ref.read(interpreterServiceProvider).dispose(), + // The mirror of onPause (paused -> hidden): reload what it freed, + // otherwise the AI affordances stay hidden for the rest of the run. + onRestart: _restoreInterpreter, ); + _restoreInterpreter(); } } + /// Recognize an already-downloaded model. The service boots at + /// `needsDownload` and only `refresh()` consults the disk, so without this + /// every launch claims the model is missing — and the resulting "Download + /// model" tap drops straight into warmUp's load path with no consent step. + Future _restoreInterpreter() async { + // Read the flag first: AI off must not construct the interpreter at all. + if (!await ref.read(aiEnabledProvider.future)) return; + if (!mounted) return; + await ref.read(interpreterServiceProvider).refresh(); + } + @override void dispose() { _lifecycle?.dispose(); diff --git a/lib/state/interpreter_gemma.dart b/lib/state/interpreter_gemma.dart index f6d2b38f..cda23fcf 100644 --- a/lib/state/interpreter_gemma.dart +++ b/lib/state/interpreter_gemma.dart @@ -126,22 +126,37 @@ class GemmaInterpreterService implements InterpreterService { } } + /// Backends to try, in order, on [platform]. + /// + /// Apple platforms never get the GPU backend, because a native crash kills + /// the process before [_loadModel]'s catch runs — the step-down ladder + /// cannot recover from one, so the only safe move is to not attempt the + /// accelerator at all. Two device crashes, same class: + /// + /// - iOS: LiteRT-LM's Metal accelerator null-derefs loading E4B on iPhone + /// (SIGSEGV at 0x0 in AGX buffer setup — crash log 2026-07-11, iPhone 15 + /// Pro Max; upstream flutter_gemma #218). + /// - macOS: with `backend=gpu`, LiteRT's `ReplaceMagicNumbersIfAny` reads a + /// garbage config count (`num_configs=4294967300`, i.e. 4 + 2^32) and + /// walks off the array, SIGSEGV'ing inside its own logger on a null + /// `char*` (crash log 2026-08-12). The CPU/XNNPACK path loads the same + /// file fine. + @visibleForTesting + static List backendsFor(TargetPlatform platform) => + switch (platform) { + TargetPlatform.iOS || TargetPlatform.macOS => const [ + PreferredBackend.cpu + ], + _ => const [PreferredBackend.gpu, PreferredBackend.cpu], + }; + /// Try a roomy context first (E4B handles far more than the retired web /// model's 1280; 4096 gives the loosened recall caps + few-shot prompts real - /// headroom); some artifacts cap the KV cache, so step down, and from the - /// GPU backend to CPU. - /// - /// iOS never gets the GPU backend: LiteRT-LM's Metal accelerator null-derefs - /// loading E4B on iPhone (SIGSEGV at 0x0 in AGX buffer setup — device crash - /// log 2026-07-11, iPhone 15 Pro Max; same class as upstream flutter_gemma - /// #218). A native crash kills the process before this catch runs, so the - /// step-down ladder cannot recover from it — the only safe move is to not - /// attempt Metal at all. + /// headroom); some artifacts cap the KV cache, so step down, and (where the + /// GPU is attempted at all) from the GPU backend to CPU. Future _loadModel() async { Object? firstError; - final backends = defaultTargetPlatform == TargetPlatform.iOS - ? const [PreferredBackend.cpu] - : const [PreferredBackend.gpu, PreferredBackend.cpu]; + final backends = backendsFor(defaultTargetPlatform); for (final maxTokens in const [4096, 2048, 1280]) { for (final backend in backends) { try { @@ -181,8 +196,7 @@ class GemmaInterpreterService implements InterpreterService { /// One prompt → raw model text, the shared generation discipline for /// every seam: fresh chat + inter-token watchdog. Future _generate(String prompt, - {String? systemInstruction, - double temperature = _kCreativeTemp}) async { + {String? systemInstruction, double temperature = _kCreativeTemp}) async { final model = _model; if (model == null) throw StateError('Interpreter not ready'); final chat = await _createChat(model, @@ -234,8 +248,8 @@ class GemmaInterpreterService implements InterpreterService { @override Future rankSuggestions(RankSuggestionsSeed seed) async { - return parseRankResult(await _generate(buildRankPrompt(seed), - temperature: _kPreciseTemp)); + return parseRankResult( + await _generate(buildRankPrompt(seed), temperature: _kPreciseTemp)); } @override diff --git a/test/interpreter_restore_test.dart b/test/interpreter_restore_test.dart new file mode 100644 index 00000000..60dbaac0 --- /dev/null +++ b/test/interpreter_restore_test.dart @@ -0,0 +1,96 @@ +/// Two regressions from one device session (macOS, 2026-08-12): +/// +/// 1. A downloaded model read as missing on every relaunch — the service +/// starts at needsDownload and only refresh() consults the disk, but +/// NOTHING called refresh(). +/// 2. Tapping "Download model" then took warmUp's already-installed path +/// straight into _loadModel, whose GPU-first backend ladder SIGSEGV'd the +/// process inside LiteRT-LM (see interpreter_gemma.dart's ladder comment). +library; + +import 'dart:convert'; +import 'dart:io'; + +import 'package:flutter/material.dart'; +import 'package:flutter_gemma/flutter_gemma.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:loreseer/engine/emulator_data.dart'; +import 'package:loreseer/engine/oracle.dart'; +import 'package:loreseer/engine/oracle_data.dart'; +import 'package:loreseer/engine/verdant_data.dart'; +import 'package:loreseer/shared/home_shell.dart'; +import 'package:loreseer/state/interpreter.dart'; +import 'package:loreseer/state/interpreter_gemma.dart'; +import 'package:loreseer/state/providers.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import 'fake_interpreter.dart'; + +Oracle _oracle() => Oracle(OracleData( + jsonDecode(File('assets/oracle_data.json').readAsStringSync()) + as Map)); + +// Loaded from file, not rootBundle, which hangs the headless runner. +final _verdantOverride = verdantDataProvider.overrideWith((ref) async => + VerdantData(jsonDecode(File('assets/verdant_data.json').readAsStringSync()) + as Map)); +final _emulatorOverride = emulatorDataProvider.overrideWith((ref) async => + EmulatorData( + jsonDecode(File('assets/emulator_data.json').readAsStringSync()) + as Map)); + +void main() { + group('backendsFor', () { + test('Apple platforms are CPU-only', () { + for (final p in [TargetPlatform.iOS, TargetPlatform.macOS]) { + expect(GemmaInterpreterService.backendsFor(p), + const [PreferredBackend.cpu], + reason: '$p must never attempt the GPU backend'); + } + }); + + test('other platforms try GPU first, then CPU', () { + for (final p in [ + TargetPlatform.android, + TargetPlatform.linux, + TargetPlatform.windows, + ]) { + expect(GemmaInterpreterService.backendsFor(p), + const [PreferredBackend.gpu, PreferredBackend.cpu]); + } + }); + }); + + group('model restore on launch', () { + testWidgets('refreshes the interpreter when AI is enabled', (t) async { + SharedPreferences.setMockInitialValues({'loreseer.ai_enabled.v1': true}); + final fake = FakeInterpreterService(); + await t.pumpWidget(ProviderScope( + overrides: [ + _verdantOverride, + _emulatorOverride, + interpreterServiceProvider.overrideWithValue(fake), + ], + child: MaterialApp(home: HomeShell(oracle: _oracle())), + )); + await t.pumpAndSettle(); + expect(fake.refreshCalls, 1); + }); + + testWidgets('leaves the interpreter alone when AI is off', (t) async { + SharedPreferences.setMockInitialValues({}); + final fake = FakeInterpreterService(); + await t.pumpWidget(ProviderScope( + overrides: [ + _verdantOverride, + _emulatorOverride, + interpreterServiceProvider.overrideWithValue(fake), + ], + child: MaterialApp(home: HomeShell(oracle: _oracle())), + )); + await t.pumpAndSettle(); + expect(fake.refreshCalls, 0); + }); + }); +}