Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions lib/shared/home_shell.dart
Original file line number Diff line number Diff line change
Expand Up @@ -79,10 +79,25 @@ class _HomeShellState extends ConsumerState<HomeShell> {
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<void> _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();
Expand Down
46 changes: 30 additions & 16 deletions lib/state/interpreter_gemma.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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<PreferredBackend> 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<InferenceModel> _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 {
Expand Down Expand Up @@ -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<String> _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,
Expand Down Expand Up @@ -234,8 +248,8 @@ class GemmaInterpreterService implements InterpreterService {

@override
Future<RankResult> rankSuggestions(RankSuggestionsSeed seed) async {
return parseRankResult(await _generate(buildRankPrompt(seed),
temperature: _kPreciseTemp));
return parseRankResult(
await _generate(buildRankPrompt(seed), temperature: _kPreciseTemp));
}

@override
Expand Down
96 changes: 96 additions & 0 deletions test/interpreter_restore_test.dart
Original file line number Diff line number Diff line change
@@ -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<String, dynamic>));

// 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<String, dynamic>));
final _emulatorOverride = emulatorDataProvider.overrideWith((ref) async =>
EmulatorData(
jsonDecode(File('assets/emulator_data.json').readAsStringSync())
as Map<String, dynamic>));

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);
});
});
}
Loading