[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>
This commit is contained in:
2026-06-12 12:30:16 +09:00
parent 6ab4c0da7d
commit 1e019c6dc7
9 changed files with 603 additions and 47 deletions

View File

@@ -56,8 +56,8 @@ String buildFewShotPrompt(
}
buf.writeln();
buf.writeln(
'위 raw_text 를 L2(조건부 긍정) 또는 L3(정체성) 후보 3개로 변환하세요. '
'emit_frame_candidates 함수로 호출하세요.',
'위 raw_text 를 정확히 L2(조건부 긍정) 2개 + L3(정체성) 1개, 총 3개 후보로 '
'변환하세요. 순서는 L2 → L2 → L3. emit_frame_candidates 함수로 호출하세요.',
);
return buf.toString();
}

View File

@@ -1,6 +1,7 @@
import '../../data/ai/llm_service.dart';
import '../frame/validate_frame_level.dart';
import '../models/frame_pattern.dart';
import '../models/habit.dart';
import 'few_shot_builder.dart';
import 'frame_candidate.dart';
import 'parse_response.dart';
@@ -77,7 +78,30 @@ Future<List<FrameCandidate>> suggestFrame(
);
if (result.status == FrameValidationStatus.reject) continue;
validated.add(c);
if (validated.length >= 3) break;
}
return validated;
// AC4: Enforce L2:2 + L3:1 distribution. Take L2 first (up to 2), then L3
// (up to 1). If a slot is short, leave it short rather than pad with the
// other level — graceful: caller sees fewer cards but never a wrong shape.
return _shapeDistribution(validated, l2Quota: 2, l3Quota: 1);
}
List<FrameCandidate> _shapeDistribution(
List<FrameCandidate> all, {
required int l2Quota,
required int l3Quota,
}) {
final out = <FrameCandidate>[];
var l2Taken = 0;
var l3Taken = 0;
for (final c in all) {
if (c.level == FrameLevel.l2 && l2Taken < l2Quota) {
out.add(c);
l2Taken += 1;
} else if (c.level == FrameLevel.l3 && l3Taken < l3Quota) {
out.add(c);
l3Taken += 1;
}
if (l2Taken >= l2Quota && l3Taken >= l3Quota) break;
}
return out;
}

View File

@@ -1,3 +1,5 @@
import 'dart:async';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../data/ai/llm_service.dart';
@@ -33,6 +35,8 @@ final aiSettingsProvider = FutureProvider<bool>((ref) async {
});
/// Toggles opt-in. On opt-out, purges model file via [ModelLifecycle.purge].
/// On opt-in, kicks off `ModelDownloadController.start()` so AC2 (progress UI)
/// has a stream to subscribe to.
class AiSettingsController {
AiSettingsController(this.ref);
final Ref ref;
@@ -43,8 +47,13 @@ class AiSettingsController {
await meta.put(AiMetaKeys.optIn, 'true');
ref.invalidate(aiSettingsProvider);
ref.invalidate(modelAvailabilityProvider);
// AC2: opt-in triggers download stream so Settings UI can render
// progress + pause/resume. Fire-and-forget; controller emits states.
ref.read(modelDownloadControllerProvider.notifier).start();
return 0;
}
// opt-out: cancel any in-flight download, then purge.
ref.read(modelDownloadControllerProvider.notifier).cancel();
final freed = await ref.read(modelLifecycleProvider).purge();
await meta.put(AiMetaKeys.optIn, 'false');
ref.invalidate(aiSettingsProvider);
@@ -57,6 +66,72 @@ final aiSettingsControllerProvider = Provider<AiSettingsController>((ref) {
return AiSettingsController(ref);
});
/// AC2: streams DownloadProgress + supports pause/resume/cancel.
/// State `null` means idle (no active subscription).
class ModelDownloadController extends StateNotifier<DownloadProgress?> {
ModelDownloadController(this.ref) : super(null);
final Ref ref;
StreamSubscription<DownloadProgress>? _sub;
void start() {
cancel();
final lc = ref.read(modelLifecycleProvider);
_sub = lc.download().listen(
(p) {
state = p;
if (p.state == DownloadState.completed) {
ref.invalidate(modelAvailabilityProvider);
}
},
onError: (Object e) {
state = DownloadProgress(
bytesReceived: state?.bytesReceived ?? 0,
totalBytes: state?.totalBytes ?? -1,
state: DownloadState.failed,
errorMessage: e.toString(),
);
},
onDone: () {
_sub = null;
},
);
}
/// Pauses by cancelling the subscription. .tmp file + meta_kv preserved so
/// `start()` resumes via HTTP Range header.
void pause() {
_sub?.cancel();
_sub = null;
final cur = state;
if (cur != null && cur.state != DownloadState.completed) {
state = DownloadProgress(
bytesReceived: cur.bytesReceived,
totalBytes: cur.totalBytes,
state: DownloadState.paused,
);
}
}
void resume() => start();
void cancel() {
_sub?.cancel();
_sub = null;
state = null;
}
@override
void dispose() {
_sub?.cancel();
super.dispose();
}
}
final modelDownloadControllerProvider =
StateNotifierProvider<ModelDownloadController, DownloadProgress?>(
(ref) => ModelDownloadController(ref),
);
final modelAvailabilityProvider =
FutureProvider<ModelAvailability>((ref) async {
final lc = ref.watch(modelLifecycleProvider);

View File

@@ -147,8 +147,10 @@ String _ymd(DateTime d) =>
'${d.month.toString().padLeft(2, '0')}-'
'${d.day.toString().padLeft(2, '0')}';
/// "AI 제안" button — only visible when opt-in is ON and model is ready.
/// Graceful: hidden otherwise (AC-5, AC-9).
/// "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;
@@ -163,46 +165,53 @@ class _AiSuggestButton extends ConsumerWidget {
@override
Widget build(BuildContext context, WidgetRef ref) {
final settings = ref.watch(aiSettingsProvider);
final availability = ref.watch(modelAvailabilityProvider);
final visible = settings.maybeWhen(
final optIn = ref.watch(aiSettingsProvider).maybeWhen(
data: (v) => v,
orElse: () => false,
) &&
availability.maybeWhen(
);
if (!optIn) return const SizedBox.shrink();
final ready = ref.watch(modelAvailabilityProvider).maybeWhen(
data: (a) => a == ModelAvailability.ready,
orElse: () => false,
);
if (!visible) return const SizedBox.shrink();
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: TextButton.icon(
icon: const Icon(Icons.auto_awesome),
label: const Text('AI 제안'),
onPressed: () 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,
child: ready
? button
: Tooltip(
message: 'AI 도움을 먼저 켜주세요',
child: button,
),
);
if (picked != null) {
framedCtrl.text = picked;
// Heuristic: identity-style ("나는") → L3, else L2.
onSelectLevel(
picked.startsWith('나는') ? FrameLevel.l3 : FrameLevel.l2,
);
}
},
),
);
}
}

View File

@@ -43,6 +43,8 @@ class _AiSection extends ConsumerWidget {
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: [
@@ -51,10 +53,7 @@ class _AiSection extends ConsumerWidget {
subtitle: const Text(
'Gemma 4 E2B 모델 ≈ 1.5GB. 모든 처리는 단말에서 일어납니다.',
),
value: settings.maybeWhen(
data: (v) => v,
orElse: () => false,
),
value: optIn,
onChanged: (v) async {
if (v) {
final ok = await _confirmOptIn(context);
@@ -81,6 +80,8 @@ class _AiSection extends ConsumerWidget {
subtitle: Text(_describe(a)),
),
),
if (optIn && download != null)
_DownloadProgressTile(progress: download, ref: ref),
const Padding(
padding: EdgeInsets.fromLTRB(16, 8, 16, 16),
child: Text(
@@ -159,3 +160,90 @@ class _AiSection extends ConsumerWidget {
);
}
}
/// 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';
}
}

View File

@@ -6,16 +6,16 @@ import '../../domain/models/habit.dart';
import '../../state/ai_providers.dart';
/// Shows L2/L3 suggestion cards from suggestFrame. Returns the selected
/// framed_text via `Navigator.pop(context, candidate.framedText)`.
/// FrameCandidate (with level + framedText) via Navigator.pop.
class FrameSuggestionDialog extends ConsumerWidget {
final SuggestFrameInput input;
const FrameSuggestionDialog({super.key, required this.input});
static Future<String?> show(
static Future<FrameCandidate?> show(
BuildContext context, {
required SuggestFrameInput input,
}) {
return showDialog<String>(
return showDialog<FrameCandidate>(
context: context,
builder: (_) => FrameSuggestionDialog(input: input),
);
@@ -64,7 +64,7 @@ class FrameSuggestionDialog extends ConsumerWidget {
for (final c in candidates)
_CandidateCard(
candidate: c,
onTap: () => Navigator.of(context).pop(c.framedText),
onTap: () => Navigator.of(context).pop(c),
),
],
);

View File

@@ -142,7 +142,7 @@ void main() {
expect(result, isEmpty);
});
test('result truncated at 3 even if more valid candidates returned',
test('AC4: L2-only input shaped to L2 quota (2), no padding with L3',
() async {
final llm = MockLlmService();
await llm.load();
@@ -160,6 +160,52 @@ void main() {
llm: llm,
framePatterns: _patterns,
);
expect(result, hasLength(2));
expect(result.every((c) => c.level == FrameLevel.l2), isTrue);
});
test('AC4: L3-only input shaped to L3 quota (1)', () async {
final llm = MockLlmService();
await llm.load();
llm.enqueueResponse({
'candidates': [
{'level': 'L3', 'framed_text': '나는 운동인이다'},
{'level': 'L3', 'framed_text': '나는 건강한 사람이다'},
{'level': 'L3', 'framed_text': '나는 일찍 자는 사람이다'},
],
});
final result = await suggestFrame(
_input,
llm: llm,
framePatterns: _patterns,
);
expect(result, hasLength(1));
expect(result.single.level, FrameLevel.l3);
});
test('AC4: mixed L2:3 + L3:2 input shaped to exactly L2:2 + L3:1',
() async {
final llm = MockLlmService();
await llm.load();
llm.enqueueResponse({
'candidates': [
{'level': 'L2', 'framed_text': 'L2-A'},
{'level': 'L3', 'framed_text': '나는 A'},
{'level': 'L2', 'framed_text': 'L2-B'},
{'level': 'L3', 'framed_text': '나는 B'},
{'level': 'L2', 'framed_text': 'L2-C'},
],
});
final result = await suggestFrame(
_input,
llm: llm,
framePatterns: _patterns,
);
expect(result, hasLength(3));
expect(result.where((c) => c.level == FrameLevel.l2).length, 2);
expect(result.where((c) => c.level == FrameLevel.l3).length, 1);
// Order preserves original LLM-emitted ordering
expect(result.map((c) => c.framedText).toList(),
['L2-A', '나는 A', 'L2-B']);
});
}

View File

@@ -0,0 +1,193 @@
// AC2 regression: opt-in toggle triggers ModelDownloadController.start(),
// which subscribes to ModelLifecycle.download() and emits DownloadProgress
// states. pause() / resume() / cancel() control the lifecycle so Settings UI
// has stream to render. QA reject (2026-06-12) caught that setOptIn(true)
// previously persisted only the meta flag — no download stream was started.
import 'dart:async';
import 'dart:io';
import 'package:drift/native.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart' as http;
import 'package:life_helper/data/ai/model_lifecycle.dart';
import 'package:life_helper/data/db/app_database.dart';
import 'package:life_helper/data/db/daos/meta_dao.dart';
import 'package:life_helper/state/ai_providers.dart';
import 'package:life_helper/state/providers.dart';
class _FakeStorage implements StorageAdapter {
final Directory tempDir;
final Future<http.StreamedResponse> Function(Uri url, int from) handler;
_FakeStorage(this.tempDir, this.handler);
@override
Future<Directory> supportDir() async => tempDir;
@override
Future<http.StreamedResponse> rangeGet(Uri url, int from) =>
handler(url, from);
}
http.StreamedResponse _okResponse(List<int> bytes) {
return http.StreamedResponse(
Stream.value(bytes),
200,
contentLength: bytes.length,
);
}
http.StreamedResponse _slowResponse(List<int> bytes) {
// Drip the bytes one chunk per tick so pause() has time to bite.
late StreamController<List<int>> ctrl;
ctrl = StreamController<List<int>>(
onListen: () async {
for (final b in bytes) {
await Future<void>.delayed(const Duration(milliseconds: 5));
if (ctrl.isClosed) return;
ctrl.add([b]);
}
await ctrl.close();
},
);
return http.StreamedResponse(
ctrl.stream,
200,
contentLength: bytes.length,
);
}
void main() {
test('AC2: opt-in triggers ModelDownloadController.start() and emits states',
() async {
final tempDir = await Directory.systemTemp.createTemp('ai-dl-');
addTearDown(() async {
if (tempDir.existsSync()) await tempDir.delete(recursive: true);
});
// Deterministic payload + matching SHA so download completes successfully.
final payload = List<int>.generate(16, (i) => i);
final fake = _FakeStorage(
tempDir,
(_, _) async => _okResponse(payload),
);
final db = AppDatabase(NativeDatabase.memory());
addTearDown(db.close);
final container = ProviderContainer(overrides: [
appDatabaseProvider.overrideWithValue(db),
modelLifecycleProvider.overrideWithValue(
ModelLifecycle(
meta: MetaDao(db),
config: ModelConfig(
url: Uri.parse('https://example.invalid/x.bin'),
expectedSha256:
'be45cb2605bf36bebde684841a28f0fd43c69850a3dce5fedba69928ee3a8991',
),
storage: fake,
),
),
]);
addTearDown(container.dispose);
// Capture emitted states.
final states = <DownloadProgress?>[];
container.listen(
modelDownloadControllerProvider,
(_, next) => states.add(next),
);
// Act: opt-in via the public controller. This is the AC2 entry point.
await container.read(aiSettingsControllerProvider).setOptIn(true);
// Wait for stream to drain.
await Future<void>.delayed(const Duration(milliseconds: 50));
// Assert: at least one downloading + final completed state seen.
expect(states.any((s) => s?.state == DownloadState.downloading), isTrue);
expect(states.last?.state, DownloadState.completed);
expect(states.last?.bytesReceived, payload.length);
});
test('AC2: pause() halts emission, resume() picks up', () async {
final tempDir = await Directory.systemTemp.createTemp('ai-dl-');
addTearDown(() async {
if (tempDir.existsSync()) await tempDir.delete(recursive: true);
});
final payload = List<int>.generate(8, (i) => i);
final fake = _FakeStorage(
tempDir,
(_, _) async => _slowResponse(payload),
);
final db = AppDatabase(NativeDatabase.memory());
addTearDown(db.close);
final container = ProviderContainer(overrides: [
appDatabaseProvider.overrideWithValue(db),
modelLifecycleProvider.overrideWithValue(
ModelLifecycle(
meta: MetaDao(db),
config: ModelConfig(
url: Uri.parse('https://example.invalid/x.bin'),
// Any sha — pause/resume tested before SHA verification reached.
expectedSha256: 'PENDING',
),
storage: fake,
),
),
]);
addTearDown(container.dispose);
final notifier =
container.read(modelDownloadControllerProvider.notifier);
// Wait deterministically for the first chunk-bearing state.
final firstChunk = Completer<void>();
final sub = container.listen(
modelDownloadControllerProvider,
(_, next) {
if (next != null &&
next.state == DownloadState.downloading &&
next.bytesReceived > 0 &&
!firstChunk.isCompleted) {
firstChunk.complete();
}
},
);
notifier.start();
await firstChunk.future.timeout(const Duration(seconds: 2));
notifier.pause();
sub.close();
final pausedState =
container.read(modelDownloadControllerProvider);
expect(pausedState?.state, DownloadState.paused);
expect(pausedState!.bytesReceived, greaterThan(0));
expect(pausedState.bytesReceived, lessThanOrEqualTo(payload.length));
// Allow the cancelled subscription's async cleanup to drain BEFORE
// teardown closes the db (otherwise lingering meta.put races the close).
await Future<void>.delayed(const Duration(milliseconds: 150));
});
test('AC2: cancel() clears state to idle (null)', () {
final db = AppDatabase(NativeDatabase.memory());
addTearDown(db.close);
final tempDirPath = Directory.systemTemp.path;
final fake = _FakeStorage(
Directory(tempDirPath),
(_, _) async => _okResponse(const [1, 2, 3]),
);
final container = ProviderContainer(overrides: [
appDatabaseProvider.overrideWithValue(db),
modelLifecycleProvider.overrideWithValue(
ModelLifecycle(
meta: MetaDao(db),
config: ModelConfig(
url: Uri.parse('https://example.invalid/x.bin'),
expectedSha256: 'PENDING',
),
storage: fake,
),
),
]);
addTearDown(container.dispose);
container.read(modelDownloadControllerProvider.notifier).cancel();
expect(container.read(modelDownloadControllerProvider), isNull);
});
}

View File

@@ -0,0 +1,121 @@
// AC6 regression: button is hidden when opt-in OFF, but visible-but-disabled
// with a Tooltip when opt-in ON and model is not ready.
//
// The QA reject (2026-06-12) caught that the prior implementation rendered
// `SizedBox.shrink()` in BOTH cases, eliminating discoverability for opted-in
// users still downloading.
import 'package:drift/native.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:life_helper/data/ai/llm_service.dart';
import 'package:life_helper/data/ai/model_lifecycle.dart';
import 'package:life_helper/data/db/app_database.dart';
import 'package:life_helper/state/ai_providers.dart';
import 'package:life_helper/state/providers.dart';
import 'package:life_helper/ui/screens/habit_create_screen.dart';
Future<AppDatabase> _memDb() async {
return AppDatabase(NativeDatabase.memory());
}
ProviderContainer _container({
required AppDatabase db,
required bool optIn,
required ModelAvailability availability,
}) {
return ProviderContainer(overrides: [
appDatabaseProvider.overrideWithValue(db),
llmServiceProvider.overrideWithValue(MockLlmService()),
aiSettingsProvider.overrideWith((_) async => optIn),
modelAvailabilityProvider.overrideWith((_) async => availability),
]);
}
Widget _wrap(ProviderContainer container) {
return UncontrolledProviderScope(
container: container,
child: const MaterialApp(home: Scaffold(body: HabitCreateScreen())),
);
}
void main() {
testWidgets('AC6: optIn=false → button hidden entirely', (tester) async {
final db = await _memDb();
addTearDown(db.close);
final c = _container(
db: db,
optIn: false,
availability: ModelAvailability.ready,
);
addTearDown(c.dispose);
await tester.pumpWidget(_wrap(c));
await tester.pumpAndSettle();
expect(find.text('AI 제안'), findsNothing);
expect(find.byTooltip('AI 도움을 먼저 켜주세요'), findsNothing);
});
testWidgets(
'AC6: optIn=true, availability=missing → button visible, disabled, tooltip',
(tester) async {
final db = await _memDb();
addTearDown(db.close);
final c = _container(
db: db,
optIn: true,
availability: ModelAvailability.missing,
);
addTearDown(c.dispose);
await tester.pumpWidget(_wrap(c));
await tester.pumpAndSettle();
// Visible
expect(find.text('AI 제안'), findsOneWidget);
// Wrapped in tooltip with the AC6 exact message
expect(find.byTooltip('AI 도움을 먼저 켜주세요'), findsOneWidget);
// Disabled
final TextButton btn = tester.widget(find.byType(TextButton).first);
expect(btn.onPressed, isNull);
});
testWidgets(
'AC6: optIn=true, availability=downloading → button visible+disabled',
(tester) async {
final db = await _memDb();
addTearDown(db.close);
final c = _container(
db: db,
optIn: true,
availability: ModelAvailability.downloading,
);
addTearDown(c.dispose);
await tester.pumpWidget(_wrap(c));
await tester.pumpAndSettle();
expect(find.text('AI 제안'), findsOneWidget);
expect(find.byTooltip('AI 도움을 먼저 켜주세요'), findsOneWidget);
final TextButton btn = tester.widget(find.byType(TextButton).first);
expect(btn.onPressed, isNull);
});
testWidgets(
'AC6: optIn=true, availability=ready → button enabled, no tooltip wrapper',
(tester) async {
final db = await _memDb();
addTearDown(db.close);
final c = _container(
db: db,
optIn: true,
availability: ModelAvailability.ready,
);
addTearDown(c.dispose);
await tester.pumpWidget(_wrap(c));
await tester.pumpAndSettle();
expect(find.text('AI 제안'), findsOneWidget);
expect(find.byTooltip('AI 도움을 먼저 켜주세요'), findsNothing);
final TextButton btn = tester.widget(find.byType(TextButton).first);
expect(btn.onPressed, isNotNull);
});
}