Files
life-helper/app/lib/ui/screens/habit_create_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

218 lines
7.4 KiB
Dart

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../core/constants.dart';
import '../../core/time.dart';
import '../../data/ai/model_lifecycle.dart';
import '../../data/db/daos/habit_dao.dart';
import '../../domain/ai/frame_candidate.dart';
import '../../domain/models/habit.dart';
import '../../domain/rules/active_habit_quota.dart';
import '../../state/ai_providers.dart';
import '../../state/providers.dart';
import '../widgets/frame_suggestion_dialog.dart';
class HabitCreateScreen extends ConsumerStatefulWidget {
const HabitCreateScreen({super.key});
@override
ConsumerState<HabitCreateScreen> createState() => _HabitCreateScreenState();
}
class _HabitCreateScreenState extends ConsumerState<HabitCreateScreen> {
final _formKey = GlobalKey<FormState>();
final _titleCtrl = TextEditingController();
final _framedCtrl = TextEditingController();
HabitType _type = HabitType.build;
FrameLevel _level = FrameLevel.l2;
bool _saving = false;
@override
void dispose() {
_titleCtrl.dispose();
_framedCtrl.dispose();
super.dispose();
}
Future<void> _save() async {
if (!_formKey.currentState!.validate()) return;
setState(() => _saving = true);
try {
final dao = ref.read(habitDaoProvider);
final count = await dao.countActive(
userId: kLocalDefaultUserId,
type: _type,
);
final quota = judgeActiveHabitQuota(type: _type, currentActiveCount: count);
if (!quota.allowed) {
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(quota.reason)),
);
return;
}
await dao.insertWithVariants(HabitDraft(
userId: kLocalDefaultUserId,
type: _type,
title: _titleCtrl.text.trim(),
// Placeholder: vertical-slice uses the first seeded protocol.
protocolId: _type == HabitType.build ? 'morning_sunlight' : null,
breakProtocolId: _type == HabitType.breakHabit ? 'alcohol' : null,
frameLevel: _level,
frameFramedText: _framedCtrl.text.trim(),
startedAt: _ymd(nowKst()),
));
if (!mounted) return;
Navigator.of(context).pop();
} catch (e) {
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('저장 실패: $e')),
);
} finally {
if (mounted) setState(() => _saving = false);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('새 습관')),
body: Padding(
padding: const EdgeInsets.all(16),
child: Form(
key: _formKey,
child: ListView(
children: [
TextFormField(
controller: _titleCtrl,
decoration: const InputDecoration(labelText: '제목'),
validator: (v) =>
(v == null || v.trim().isEmpty) ? '제목을 입력하세요' : null,
),
const SizedBox(height: 16),
DropdownButtonFormField<HabitType>(
initialValue: _type,
items: const [
DropdownMenuItem(value: HabitType.build, child: Text('만들기 (build)')),
DropdownMenuItem(
value: HabitType.breakHabit, child: Text('없애기 (break)')),
],
onChanged: (v) => setState(() => _type = v ?? HabitType.build),
decoration: const InputDecoration(labelText: '타입'),
),
const SizedBox(height: 16),
DropdownButtonFormField<FrameLevel>(
initialValue: _level,
items: const [
DropdownMenuItem(value: FrameLevel.l2, child: Text('L2 · 조건부 긍정')),
DropdownMenuItem(value: FrameLevel.l3, child: Text('L3 · 정체성')),
],
onChanged: (v) => setState(() => _level = v ?? FrameLevel.l2),
decoration: const InputDecoration(labelText: '프레임 레벨'),
),
const SizedBox(height: 16),
TextFormField(
controller: _framedCtrl,
decoration: const InputDecoration(
labelText: '프레임 문구',
hintText: '예: 아침 햇빛을 10분 받는다',
),
maxLines: 2,
validator: (v) =>
(v == null || v.trim().isEmpty) ? '프레임 문구를 입력하세요' : null,
),
const SizedBox(height: 8),
_AiSuggestButton(
titleCtrl: _titleCtrl,
framedCtrl: _framedCtrl,
habitType: _type,
onSelectLevel: (level) => setState(() => _level = level),
),
const SizedBox(height: 16),
FilledButton(
onPressed: _saving ? null : _save,
child: Text(_saving ? '저장 중...' : '저장'),
),
],
),
),
),
);
}
}
String _ymd(DateTime d) =>
'${d.year.toString().padLeft(4, '0')}-'
'${d.month.toString().padLeft(2, '0')}-'
'${d.day.toString().padLeft(2, '0')}';
/// "AI 제안" button — three states (AC3, AC6, AC7):
/// - opt-in OFF → hidden (discoverability gated by Settings)
/// - opt-in ON && model not ready → visible but DISABLED + tooltip
/// - opt-in ON && model ready → enabled
class _AiSuggestButton extends ConsumerWidget {
final TextEditingController titleCtrl;
final TextEditingController framedCtrl;
final HabitType habitType;
final ValueChanged<FrameLevel> onSelectLevel;
const _AiSuggestButton({
required this.titleCtrl,
required this.framedCtrl,
required this.habitType,
required this.onSelectLevel,
});
@override
Widget build(BuildContext context, WidgetRef ref) {
final optIn = ref.watch(aiSettingsProvider).maybeWhen(
data: (v) => v,
orElse: () => false,
);
if (!optIn) return const SizedBox.shrink();
final ready = ref.watch(modelAvailabilityProvider).maybeWhen(
data: (a) => a == ModelAvailability.ready,
orElse: () => false,
);
final button = TextButton.icon(
icon: const Icon(Icons.auto_awesome),
label: const Text('AI 제안'),
onPressed: ready
? () async {
final raw = titleCtrl.text.trim();
if (raw.isEmpty) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('먼저 제목을 입력해주세요')),
);
return;
}
final picked = await FrameSuggestionDialog.show(
context,
input: SuggestFrameInput(
rawText: raw,
habitType: habitType,
),
);
if (picked != null) {
framedCtrl.text = picked.framedText;
// AC5: use the candidate's explicit level, not a heuristic.
onSelectLevel(picked.level);
}
}
: null,
);
return Align(
alignment: Alignment.centerRight,
child: ready
? button
: Tooltip(
message: 'AI 도움을 먼저 켜주세요',
child: button,
),
);
}
}