Files
life-helper/app/test/state/model_download_controller_test.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

194 lines
6.6 KiB
Dart

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