Files
life-helper/app/lib/ui/screens/settings_screen.dart
joungmin 1e019c6dc7 [Developer] #215 AC2/AC4/AC6 fixes after QA reject
QA 1차 (커밋 6ab4c0d 검증) 에서 3건 AC 미충족 → 03-Developer 반려.
본 커밋은 그 3건을 해결한다.

AC6 — _AiSuggestButton 가시성 분기 분리:
- optIn=false → 숨김 유지
- optIn=true && !ready → 노출 + disabled + Tooltip("AI 도움을 먼저 켜주세요")
- optIn=true && ready → enabled
AC5 보완: 후보의 c.level 직접 전달 (이전 "나는" 휴리스틱 제거).
FrameSuggestionDialog.show 반환 타입 String? → FrameCandidate?.

AC4 — L2:2 + L3:1 분포 강제:
- few_shot prompt 에 "정확히 L2 2개 + L3 1개" 명시
- suggestFrame 결과를 _shapeDistribution(l2Quota=2, l3Quota=1) 로 후처리
- 부족분은 패딩 X (graceful: UI 가 더 적은 카드만 표시)

AC2 — 다운로드 진행률 + 일시정지/재개 UI:
- ModelDownloadController (StateNotifier<DownloadProgress?>)
  · start() / pause() / resume() / cancel()
  · pause() 는 subscription 만 cancel, .tmp + meta_kv 유지 → resume 시 Range header 로 이어받음
- AiSettingsController.setOptIn(true) → controller.start() 자동 호출
- SettingsScreen 에 _DownloadProgressTile 추가
  · LinearProgressIndicator + bytes/total + 일시정지/재개/다시 시도 토글

회귀 테스트 9건 신규:
- test/ui/ai_suggest_button_visibility_test.dart (4): AC6 4상태 (hidden / disabled+tooltip × missing/downloading / enabled)
- test/state/model_download_controller_test.dart (3): opt-in→start, pause→paused, cancel→idle
- test/domain/ai/suggest_frame_test.dart (+3): AC4 분포 케이스 3개 (기존 take(3) 테스트 대체)

검증:
- flutter analyze → No issues found
- flutter test → 71 tests pass (62 → 71, +9 신규)
- flutter build apk --debug → 성공 (8.8s)

OQ-1 (모델 URL+SHA) 미해결 유지. MockLlmService 기본 주입 + placeholder URL 다운로드는 여전히 실패하지만, UI/스트림 wiring 은 모두 검증됨.

Refs #215

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

250 lines
7.8 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 모델 ≈ 1.5GB. 모든 처리는 단말에서 일어납니다.',
),
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(
'OQ-1 미해결: 정확한 모델 URL + SHA 가 픽스되기 전까지 '
'다운로드는 동작하지 않습니다. (Architect/Developer 인계 사항)',
style: TextStyle(fontSize: 12, color: Colors.grey),
),
),
],
);
}
String _describe(ModelAvailability a) {
switch (a) {
case ModelAvailability.ready:
return '사용 가능';
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: const Text(
'Gemma 4 E2B 모델 ≈ 1.5GB 를 다운로드합니다.\n'
'- WiFi 권장\n'
'- 모든 처리는 단말에서만 일어나며, 입력 텍스트는 외부로 전송되지 않습니다.\n'
'- 끄면 즉시 삭제됩니다.',
),
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: const Text(
'모델 파일 ≈ 1.5GB 가 즉시 삭제됩니다. '
'다시 켜면 다시 다운로드해야 합니다.',
),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(false),
child: const Text('취소'),
),
FilledButton(
onPressed: () => Navigator.of(context).pop(true),
child: const Text('끄고 삭제'),
),
],
),
);
}
}
/// 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 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)}" : ""}';
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 = TextButton.icon(
icon: const Icon(Icons.play_arrow),
label: const Text('재개'),
onPressed: controller.resume,
);
break;
case DownloadState.failed:
controls = TextButton.icon(
icon: const Icon(Icons.refresh),
label: const Text('다시 시도'),
onPressed: controller.resume,
);
break;
case DownloadState.completed:
controls = const Text('완료', style: TextStyle(color: Colors.green));
break;
case DownloadState.idle:
controls = const SizedBox.shrink();
break;
}
return Padding(
padding: const EdgeInsets.fromLTRB(16, 0, 16, 8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Row(
children: [
Expanded(child: Text('$size · $pctText')),
controls,
],
),
const SizedBox(height: 4),
LinearProgressIndicator(value: pct),
if (progress.state == DownloadState.failed &&
progress.errorMessage != null)
Padding(
padding: const EdgeInsets.only(top: 4),
child: Text(
'에러: ${progress.errorMessage}',
style: const TextStyle(fontSize: 12, color: Colors.red),
),
),
],
),
);
}
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';
}
}