Files
life-helper/app/lib/ui/screens/settings_screen.dart
joungmin 9a9eb2abd5 [Developer] #218 Real Gemma 4 E2B integration via flutter_gemma 0.16.5
Implements the OQ-1 follow-up to #215 v0.2.0: replace the placeholder
GemmaLlmService stub with a real flutter_gemma 0.16.5 backend driving
Gemma 4 E2B (litert-community/gemma-4-E2B-it-litert-lm, 2.41GB).

Highlights:
- GemmaLlmService.load → FlutterGemma.initialize + installModel.fromFile +
  getActiveModel; idempotent + FileSystemException on missing file.
- generateStructured uses Gemma 4 native function calling via
  createChat(tools: [Tool(...)], toolChoice: required). Stream parsed by
  collectFunctionCall — first FCR wins, ParallelFCR first-call wins,
  TextResponse/ThinkingResponse skipped, errors sanitized to prevent
  prompt leakage.
- main.dart wires _LazyLlmService adapter that resolves to GemmaLlmService
  when ModelLifecycle reports ready, MockLlmService otherwise.
- ai_providers.dart pins real model URL + SHA-256 (181938...39a63c).
- F2 hardening: ModelLifecycle.purge wraps each delete + meta remove in
  try/catch so a single OS-level flake cannot block opt-out.
- Android: INTERNET / FOREGROUND_SERVICE / POST_NOTIFICATIONS permissions
  + R8 proguard-rules.pro keeping MediaPipe / LiteRT / TFLite / protobuf
  JNI entry points (release builds otherwise crash on first inference).

Design-First: fn-gemma_llm_service.md updated to v2 — §C
(_appendSchemaInstruction) deprecated after reading flutter_gemma
0.16.5 source (Gemma 4 SDK injects tool declarations via template;
prompt-side append would double-wrap).

Tests:
- 10 new unit tests for collectFunctionCall covering all 8 fn-spec
  cases + 2 ParallelFunctionCallResponse paths.
- All 81 existing tests still pass.
- flutter analyze: 0 issues.

Refs #218

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-06-12 15:18:08 +09:00

348 lines
11 KiB
Dart

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../data/ai/model_lifecycle.dart';
import '../../state/ai_providers.dart';
class SettingsScreen extends ConsumerWidget {
const SettingsScreen({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
return Scaffold(
appBar: AppBar(title: const Text('설정')),
body: ListView(
children: const [
_SectionHeader('AI 도움'),
_AiSection(),
],
),
);
}
}
class _SectionHeader extends StatelessWidget {
final String title;
const _SectionHeader(this.title);
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.fromLTRB(16, 16, 16, 4),
child: Text(
title,
style: Theme.of(context).textTheme.titleSmall,
),
);
}
}
class _AiSection extends ConsumerWidget {
const _AiSection();
@override
Widget build(BuildContext context, WidgetRef ref) {
final settings = ref.watch(aiSettingsProvider);
final availability = ref.watch(modelAvailabilityProvider);
final download = ref.watch(modelDownloadControllerProvider);
final optIn = settings.maybeWhen(data: (v) => v, orElse: () => false);
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
SwitchListTile(
title: const Text('AI 도움 켜기'),
subtitle: const Text(
'Gemma 4 E2B 모델 ≈ 2.4GB. 모든 처리는 단말에서 일어납니다.',
),
value: optIn,
onChanged: (v) async {
if (v) {
final ok = await _confirmOptIn(context);
if (ok != true) return;
} else {
final ok = await _confirmOptOut(context);
if (ok != true) return;
}
final freed =
await ref.read(aiSettingsControllerProvider).setOptIn(v);
if (!context.mounted) return;
if (!v && freed > 0) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('공간 확보됨 ${_fmtMB(freed)}')),
);
}
},
),
availability.when(
loading: () => const ListTile(title: Text('상태 확인 중...')),
error: (e, _) => ListTile(title: Text('상태 오류: $e')),
data: (a) => ListTile(
title: const Text('모델 상태'),
subtitle: Text(_describe(a)),
),
),
if (optIn && download != null)
_DownloadProgressTile(progress: download, ref: ref),
const Padding(
padding: EdgeInsets.fromLTRB(16, 8, 16, 16),
child: Text(
'베타 기능 · 모델 다운로드가 정식 제공되기 전까지 일부 동작이 제한됩니다.',
style: TextStyle(fontSize: 12, color: Colors.grey),
),
),
],
);
}
String _describe(ModelAvailability a) {
switch (a) {
case ModelAvailability.ready:
return '준비 완료 — 새 습관 만들기에서 ✨ AI 제안을 쓸 수 있어요';
case ModelAvailability.missing:
return '아직 받지 않았어요 — 위 토글을 켜면 다운로드합니다';
case ModelAvailability.corrupt:
return '파일이 손상됐어요 — 끄고 다시 켜면 새로 받습니다';
case ModelAvailability.downloading:
return '다운로드 중';
}
}
String _fmtMB(int bytes) {
final mb = bytes / (1024 * 1024);
return '${mb.toStringAsFixed(1)} MB';
}
Future<bool?> _confirmOptIn(BuildContext context) {
return showDialog<bool>(
context: context,
builder: (_) => AlertDialog(
title: const Text('AI 도움 켜기'),
content: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: const [
Text(
'단말에서 동작하는 AI 모델을 내려받습니다.',
style: TextStyle(fontWeight: FontWeight.w600),
),
SizedBox(height: 12),
_Bullet('파일 크기: 약 2.4GB'),
_Bullet('WiFi 연결을 권장합니다'),
_Bullet('모든 처리는 단말에서만 일어나며, 입력 텍스트는 외부로 전송되지 않습니다'),
_Bullet('Gemma 이용약관(ai.google.dev/gemma/terms)에 동의합니다'),
],
),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(false),
child: const Text('취소'),
),
FilledButton(
onPressed: () => Navigator.of(context).pop(true),
child: const Text('동의하고 다운로드'),
),
],
),
);
}
Future<bool?> _confirmOptOut(BuildContext context) {
return showDialog<bool>(
context: context,
builder: (_) => AlertDialog(
title: const Text('AI 도움 끄기'),
content: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: const [
Text('모델 파일이 단말에서 삭제됩니다.'),
SizedBox(height: 8),
Text(
'약 2.4GB 의 저장공간이 확보돼요.',
style: TextStyle(fontSize: 13, color: Colors.grey),
),
SizedBox(height: 4),
Text(
'다시 켜면 다시 다운로드해야 합니다.',
style: TextStyle(fontSize: 13, color: Colors.grey),
),
],
),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(false),
child: const Text('취소'),
),
FilledButton(
onPressed: () => Navigator.of(context).pop(true),
child: const Text('끄고 삭제'),
),
],
),
);
}
}
class _Bullet extends StatelessWidget {
final String text;
const _Bullet(this.text);
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(bottom: 4),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Padding(
padding: EdgeInsets.only(top: 6, right: 8),
child: Icon(Icons.circle, size: 5),
),
Expanded(child: Text(text, style: const TextStyle(fontSize: 14))),
],
),
);
}
}
/// AC2: shows download progress + pause/resume/restart controls.
class _DownloadProgressTile extends StatelessWidget {
final DownloadProgress progress;
final WidgetRef ref;
const _DownloadProgressTile({required this.progress, required this.ref});
@override
Widget build(BuildContext context) {
final scheme = Theme.of(context).colorScheme;
final controller = ref.read(modelDownloadControllerProvider.notifier);
final pct = progress.totalBytes > 0
? (progress.bytesReceived / progress.totalBytes).clamp(0.0, 1.0)
: null;
final pctText = pct != null
? '${(pct * 100).toStringAsFixed(0)}%'
: '계산 중';
final size =
'${_fmtBytes(progress.bytesReceived)}'
'${progress.totalBytes > 0 ? " / ${_fmtBytes(progress.totalBytes)}" : ""}';
final (stateLabel, stateColor) = switch (progress.state) {
DownloadState.downloading => ('다운로드 중', scheme.primary),
DownloadState.paused => ('일시정지됨', scheme.outline),
DownloadState.failed => ('실패', scheme.error),
DownloadState.completed => ('준비 완료', Colors.green.shade700),
DownloadState.idle => ('대기 중', scheme.outline),
};
Widget controls;
switch (progress.state) {
case DownloadState.downloading:
controls = TextButton.icon(
icon: const Icon(Icons.pause),
label: const Text('일시정지'),
onPressed: controller.pause,
);
break;
case DownloadState.paused:
controls = FilledButton.tonalIcon(
icon: const Icon(Icons.play_arrow),
label: const Text('재개'),
onPressed: controller.resume,
);
break;
case DownloadState.failed:
controls = FilledButton.tonalIcon(
icon: const Icon(Icons.refresh),
label: const Text('다시 시도'),
onPressed: controller.resume,
);
break;
case DownloadState.completed:
case DownloadState.idle:
controls = const SizedBox.shrink();
break;
}
return Padding(
padding: const EdgeInsets.fromLTRB(16, 0, 16, 12),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Row(
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
stateLabel,
style: TextStyle(
fontSize: 13,
fontWeight: FontWeight.w600,
color: stateColor,
),
),
const SizedBox(height: 2),
Text(
progress.state == DownloadState.completed
? size
: '$size · $pctText',
style: TextStyle(
fontSize: 12,
color: scheme.onSurfaceVariant,
),
),
],
),
),
controls,
],
),
const SizedBox(height: 6),
ClipRRect(
borderRadius: BorderRadius.circular(4),
child: LinearProgressIndicator(
value: pct,
minHeight: 6,
),
),
if (progress.state == DownloadState.failed)
Padding(
padding: const EdgeInsets.only(top: 6),
child: Text(
_friendlyError(progress.errorMessage),
style: TextStyle(fontSize: 12, color: scheme.error),
),
),
],
),
);
}
/// Maps internal error codes to user-friendly Korean messages.
/// Hides technical detail (HTTP status, stack) — keeps the next action
/// obvious instead.
String _friendlyError(String? raw) {
if (raw == null) return '다운로드에 실패했어요. 다시 시도해주세요.';
if (raw.startsWith('network:')) {
return '네트워크 연결을 확인하고 다시 시도해주세요.';
}
if (raw.startsWith('http ')) {
return '서버 응답이 올바르지 않습니다. 잠시 후 다시 시도해주세요.';
}
if (raw.startsWith('stream:')) {
return '다운로드가 중단되었어요. 다시 시도하면 이어받습니다.';
}
if (raw == 'sha mismatch') {
return '파일이 손상되었어요. 다시 시도하면 처음부터 받습니다.';
}
return '다운로드에 실패했어요. 다시 시도해주세요.';
}
String _fmtBytes(int bytes) {
if (bytes < 1024) return '$bytes B';
if (bytes < 1024 * 1024) return '${(bytes / 1024).toStringAsFixed(1)} KB';
if (bytes < 1024 * 1024 * 1024) {
return '${(bytes / (1024 * 1024)).toStringAsFixed(1)} MB';
}
return '${(bytes / (1024 * 1024 * 1024)).toStringAsFixed(2)} GB';
}
}