From d9ee41e1d1d3c2202af9fed234d679ec1210aefc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Park=20hyeon=20gyu=28=EB=B0=94=EA=B2=AC=EA=B7=9C=29?= Date: Wed, 21 Oct 2026 03:24:54 +0900 Subject: [PATCH] =?UTF-8?q?[NM-635]=20fix:=20=EC=95=B1=20=EB=B0=96?= =?UTF-8?q?=EC=97=90=EC=84=9C=20=EB=81=88=20=EC=95=8C=EB=9E=8C=EC=9D=98=20?= =?UTF-8?q?=ED=83=80=EC=9D=B4=EB=A8=B8=EB=A5=BC=20=EC=95=B1=EC=9D=B4=20?= =?UTF-8?q?=EC=8B=9C=EC=8A=A4=ED=85=9C=20=EC=95=8C=EB=9E=8C=EA=B3=BC=20?= =?UTF-8?q?=EB=A7=9E=EC=B6=B0=20=EC=A0=95=EB=A6=AC=ED=95=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 만료 카드는 AlarmKit 알람이 울리는 동안만 남긴다. 만료 시각이 지났는데 알람이 없으면 앱 밖(잠금화면 · Dynamic Island · 워치)에서 끈 것으로 보고 지운다 — 앱이 떠 있으면 바로, 아니면 다음 활성화 때. 예전엔 [완료]를 한 번 더 눌러야 사라졌다. Co-Authored-By: Claude Opus 5.5 --- .../Sources/Application/SceneDelegate.swift | 56 +++++++--- .../App/Sources/DI/RegisterDependencies.swift | 2 + .../TimerRepositoryInterface.swift | 10 ++ .../Domain/Sources/UseCase/TimerUseCase.swift | 37 +++++++ .../Sources/TimerSystemAlarmSyncTests.swift | 100 ++++++++++++++++++ .../Tests/Sources/HomeTestDependencies.swift | 1 + .../Alarm/AlarmKitAlarmScheduler.swift | 27 ++++- 7 files changed, 217 insertions(+), 16 deletions(-) create mode 100644 Projects/Domain/Tests/Sources/TimerSystemAlarmSyncTests.swift diff --git a/Projects/App/Sources/Application/SceneDelegate.swift b/Projects/App/Sources/Application/SceneDelegate.swift index da94158..26a42d0 100644 --- a/Projects/App/Sources/Application/SceneDelegate.swift +++ b/Projects/App/Sources/Application/SceneDelegate.swift @@ -33,6 +33,7 @@ final class SceneDelegate: UIResponder, UIWindowSceneDelegate { private var appGate: AppGate? /// 위젯에서 온 프리셋 시작의 알람 권한 게이트 구독 보관함 (NM-360). private var permissionBag = Set() + private var alarmBag = Set() /* ┌─────────────────────────────────┬───────────────────────────────────────┐ @@ -79,6 +80,13 @@ final class SceneDelegate: UIResponder, UIWindowSceneDelegate { appGate = AppGate(windowScene: windowScene) + // 앱이 떠 있는 동안 앱 밖(잠금화면 · Dynamic Island · 워치)에서 알람을 끄면 바로 반영한다 — + // 예전엔 만료 카드가 남아 [완료]를 한 번 더 눌러야 사라졌다 (NM-635). + DIContainer.shared.resolve(TimerAlarmScheduling.self).alarmsChanged + .receive(on: DispatchQueue.main) + .sink { [weak self] in self?.syncTimersWhileActive() } + .store(in: &alarmBag) + // 콜드런치 딥링크는 저장만 — 탭바가 뜬 뒤(onTabBarReady) 처리한다. // 미로그인 상태면 로그인·동의를 마치고 탭바가 뜰 때 실행된다 (NM-410). // @@ -318,6 +326,7 @@ final class SceneDelegate: UIResponder, UIWindowSceneDelegate { // App Intent(AlarmKit)가 App Group 저장소를 직접 바꿨을 수 있음 — 먼저 재동기화. useCase.reload() // 1. 디스크 → 메모리 다시 읽기 useCase.refresh() // 2. 현재 시각 기준으로 상태 재계산 + useCase.syncWithSystemAlarms() // 2-1. 앱 밖에서 끈 알람의 타이머 정리 (NM-635) // 3. 알람 권한 캐시 갱신(NM-360) — 위젯 무음-시작 라우팅과 워치 시작 게이트가 읽는 // alarmAuthorized 플래그를 실제 권한으로 최신화하고 워치에 즉시 재동기화한다. // 이게 없으면 플래그가 미기록(nil)으로 남아 워치가 권한 없이도 시작을 허용한다. @@ -326,6 +335,39 @@ final class SceneDelegate: UIResponder, UIWindowSceneDelegate { // 스토어 리뷰 요청 조건 — 첫 실행 시각 · 앱을 연 날 (NM-560). StoreReview.shared.recordAppActive() + drainOutsideTimerEvents() + if appCoordinator?.isTabBarShown == true { + StoreReview.shared.requestPendingTimerMomentIfNeeded(in: scene as? UIWindowScene) + } + + // Remote Config 최신값 fetch 후 강제 업데이트/점검 게이트 갱신(포그라운드 복귀 포함). + // + // fetch 만으로는 부족하다 — 릴리즈는 캐시가 12시간이라 그 안에는 서버로 가지 않는다. + // 점검 모드를 켜야 하는 순간의 사용자들은 전부 캐시를 갖고 있어 옛 값을 본다. + // 그래서 **사용 중 실시간 청취**를 함께 켠다(Firebase 권장 구조). + Task { @MainActor in + await RemoteConfigService.shared.fetchAndActivate() + appGate?.evaluate() + RemoteConfigService.shared.startListening() + } + } + + /// 앱이 앞에 있을 때 시스템 알람이 바뀌었다 — 앱 밖에서 끈 알람의 타이머를 지우고, 리뷰 요청도 지금 본다. + /// 뒤에 있을 때는 다음 활성화(sceneDidBecomeActive)가 같은 일을 한다. + private func syncTimersWhileActive() { + guard let scene = window?.windowScene, scene.activationState == .foregroundActive else { return } + let useCase = DIContainer.shared.resolve(TimerUseCase.self) + useCase.reload() + useCase.refresh() + useCase.syncWithSystemAlarms() + drainOutsideTimerEvents() + if appCoordinator?.isTabBarShown == true { + StoreReview.shared.requestPendingTimerMomentIfNeeded(in: scene) + } + } + + /// 앱 밖(위젯 · 알람 완료 인텐트)에서 쌓아 둔 타이머 이벤트를 꺼내 보낸다. + private func drainOutsideTimerEvents() { // 위젯이 앱 밖(백그라운드 AppIntent, iOS 26.1+ 승인)에서 시작한 타이머 지연 집계. // 위젯 프로세스는 Firebase 를 링크하지 않아 timer_start 를 직접 못 보낸다(§위젯 지연로깅). let widgetStarts = WidgetAnalyticsQueue.drainTimerStarts() @@ -350,20 +392,6 @@ final class SceneDelegate: UIResponder, UIWindowSceneDelegate { // 앱 밖(시스템 알람 · 워치)에서 끝낸 타이머 → 지금이 다음에 앱을 연 때다(NM-560). // 콜드런치는 스플래시가 떠 있으니 탭바가 뜬 뒤(onTabBarReady) 요청한다. if !outsideCompletes.isEmpty { StoreReview.shared.recordTimerCompletedOutsideApp() } - if appCoordinator?.isTabBarShown == true { - StoreReview.shared.requestPendingTimerMomentIfNeeded(in: scene as? UIWindowScene) - } - - // Remote Config 최신값 fetch 후 강제 업데이트/점검 게이트 갱신(포그라운드 복귀 포함). - // - // fetch 만으로는 부족하다 — 릴리즈는 캐시가 12시간이라 그 안에는 서버로 가지 않는다. - // 점검 모드를 켜야 하는 순간의 사용자들은 전부 캐시를 갖고 있어 옛 값을 본다. - // 그래서 **사용 중 실시간 청취**를 함께 켠다(Firebase 권장 구조). - Task { @MainActor in - await RemoteConfigService.shared.fetchAndActivate() - appGate?.evaluate() - RemoteConfigService.shared.startListening() - } } /* diff --git a/Projects/App/Sources/DI/RegisterDependencies.swift b/Projects/App/Sources/DI/RegisterDependencies.swift index 2a7d2a0..90d44a0 100644 --- a/Projects/App/Sources/DI/RegisterDependencies.swift +++ b/Projects/App/Sources/DI/RegisterDependencies.swift @@ -187,6 +187,8 @@ enum RegisterDependencies { category: info.category.displayName, durationSec: info.durationSec )) + // 앱 밖에서 끈 알람을 앱이 정리했다 — 리뷰 요청은 앱 밖 완료로 본다(NM-635 · NM-560). + if info.endedOutsideApp { StoreReview.shared.recordTimerCompletedOutsideApp() } case .cancelled: AppAnalytics.track(.timerCancel( category: info.category.displayName, diff --git a/Projects/Domain/Sources/RepositoryInterface/TimerRepositoryInterface.swift b/Projects/Domain/Sources/RepositoryInterface/TimerRepositoryInterface.swift index 5e7b75c..d3c74ea 100644 --- a/Projects/Domain/Sources/RepositoryInterface/TimerRepositoryInterface.swift +++ b/Projects/Domain/Sources/RepositoryInterface/TimerRepositoryInterface.swift @@ -43,6 +43,16 @@ public protocol TimerAlarmScheduling { func resumeAlarm(id: UUID, label: String, categoryName: String, body: String, fireDate: Date) /// 남은 시간을 바꿔 정지 상태로 다시 예약 — 정지된 알람의 남은 시간은 바꿀 수 없어서(정지 중 연장). func reschedulePausedAlarm(id: UUID, label: String, categoryName: String, body: String, remaining: Int) + /// 시스템에 살아 있는 알람 id — 앱 밖(잠금화면 · Dynamic Island · 워치)에서 끈 알람은 여기서 빠진다. + /// nil = 알 수 없음. 그때는 타이머를 정리하지 않는다 (NM-635). + func liveAlarmIDs() -> Set? + /// 시스템 알람 목록이 바뀔 때마다 — 앱 밖에서 끈 경우를 앱이 떠 있는 동안 바로 반영한다 (NM-635). + var alarmsChanged: AnyPublisher { get } +} + +public extension TimerAlarmScheduling { + func liveAlarmIDs() -> Set? { nil } + var alarmsChanged: AnyPublisher { Empty().eraseToAnyPublisher() } } public enum TimerAlarmAuthorizationStatus: Equatable, Sendable { diff --git a/Projects/Domain/Sources/UseCase/TimerUseCase.swift b/Projects/Domain/Sources/UseCase/TimerUseCase.swift index 7703b7d..ba181c5 100644 --- a/Projects/Domain/Sources/UseCase/TimerUseCase.swift +++ b/Projects/Domain/Sources/UseCase/TimerUseCase.swift @@ -21,6 +21,8 @@ public struct TimerEndInfo: Sendable { public let durationSec: Int public let elapsedSec: Int public let remainingSec: Int + /// 앱 밖(잠금화면 · Dynamic Island · 워치 알람)에서 끈 알람을 앱이 뒤늦게 정리했다 (NM-635). + public var endedOutsideApp = false } public protocol TimerUseCase { @@ -37,6 +39,8 @@ public protocol TimerUseCase { func refresh() /// 외부 프로세스(App Intent 등)가 App Group 저장소를 직접 바꾼 뒤 재동기화 func reload() + /// 시스템 알람과 맞춘다 — 만료됐는데 알람이 없으면 앱 밖에서 끈 것이라 지운다 (NM-635) + func syncWithSystemAlarms() /// 워치에서 온 명령 실행 — 알람 예약은 폰 단독이라 워치는 명령만 보낸다(NM-269) func handleWatchCommand(_ command: TimerWatchCommand) @@ -208,6 +212,39 @@ public final class DefaultTimerUseCase: TimerUseCase { timers.send(repository.loadTimers()) } + /* + 시스템 알람(AlarmKit)이 만료 카드의 기준이다 (NM-635). + + 알람을 앱 밖(잠금화면 · Dynamic Island · 워치)에서 끄면 시스템에서 사라진다. 완료 인텐트가 + 저장소를 지우지만, 인텐트가 실행되지 않는 경로가 있으면(위젯이 예약한 알람 — 인텐트가 앱에 없었다) + 타이머가 남아 앱에서 [완료]를 한 번 더 눌러야 사라졌다. + + 그래서 만료 시각이 지났는데 알람이 없는 타이머는 앱 밖에서 끝낸 것으로 보고 지운다. + 울리기 전(카운트다운) · 일시정지 타이머는 알람이 살아 있어야 정상이라 건드리지 않는다 — + 없다면 다른 문제이고, 이 규칙으로 덮을 일이 아니다. + */ + public func syncWithSystemAlarms() { + guard let live = alarmScheduler.liveAlarmIDs() else { return } + let stopped = timers.value.filter { timer in + let expired = timer.state == .ringing || (timer.state == .running && timer.remainingSeconds() == 0) + return expired && !live.contains(timer.id) + } + guard !stopped.isEmpty else { return } + for t in stopped { + var info = TimerEndInfo( + reason: .completed, + category: t.category, + durationSec: t.duration, + elapsedSec: t.duration, + remainingSec: 0 + ) + info.endedOutsideApp = true + timerEnded.send(info) + } + let ids = Set(stopped.map(\.id)) + mutate { $0.removeAll { ids.contains($0.id) } } + } + public func handleWatchCommand(_ command: TimerWatchCommand) { switch command { case .start(let presetId): diff --git a/Projects/Domain/Tests/Sources/TimerSystemAlarmSyncTests.swift b/Projects/Domain/Tests/Sources/TimerSystemAlarmSyncTests.swift new file mode 100644 index 0000000..ff589c9 --- /dev/null +++ b/Projects/Domain/Tests/Sources/TimerSystemAlarmSyncTests.swift @@ -0,0 +1,100 @@ +import XCTest +import Combine +@testable import Domain + +// 시스템 알람(AlarmKit)이 만료 카드의 기준이다 (NM-635) — +// 앱 밖에서 끈 알람은 시스템에서 사라지므로, 만료됐는데 알람이 없는 타이머는 앱이 지운다. +final class TimerSystemAlarmSyncTests: XCTestCase { + + private var scheduler: FakeAlarmScheduler! + private var cancellables = Set() + + override func setUp() { + super.setUp() + scheduler = FakeAlarmScheduler() + cancellables = [] + } + + private func makeUseCase(_ timers: [TreatmentTimerModel]) -> (DefaultTimerUseCase, TimersRepository) { + let repository = TimersRepository(timers: timers) + return (DefaultTimerUseCase(repository: repository, alarmScheduler: scheduler), repository) + } + + private func timer(_ label: String, endsIn seconds: TimeInterval, state: TreatmentTimerState = .running) -> TreatmentTimerModel { + TreatmentTimerModel(label: label, category: .examination, duration: 5, endAt: Date().addingTimeInterval(seconds), state: state) + } + + func test_만료됐는데_알람이_없으면_앱_밖_완료로_지운다() { + let ringing = timer("울림", endsIn: -10, state: .ringing) + let expired = timer("만료", endsIn: -1) + let (useCase, repository) = makeUseCase([ringing, expired]) + scheduler.live = [] + var ended: [TimerEndInfo] = [] + useCase.timerEnded.sink { ended.append($0) }.store(in: &cancellables) + + useCase.syncWithSystemAlarms() + + XCTAssertTrue(useCase.timers.value.isEmpty) + XCTAssertTrue(repository.timers.isEmpty) + XCTAssertEqual(ended.count, 2) + XCTAssertTrue(ended.allSatisfy { $0.reason == .completed && $0.endedOutsideApp }) + } + + func test_알람이_울리는_중이면_만료_카드를_남긴다() { + let ringing = timer("울림", endsIn: -10, state: .ringing) + let (useCase, _) = makeUseCase([ringing]) + scheduler.live = [ringing.id] + + useCase.syncWithSystemAlarms() + + XCTAssertEqual(useCase.timers.value.map(\.id), [ringing.id]) + } + + func test_울리기_전이나_일시정지_타이머는_알람이_없어도_건드리지_않는다() { + let running = timer("진행", endsIn: 60) + var paused = timer("정지", endsIn: -10, state: .paused) + paused.remaining = 30 + let (useCase, _) = makeUseCase([running, paused]) + scheduler.live = [] + + useCase.syncWithSystemAlarms() + + XCTAssertEqual(Set(useCase.timers.value.map(\.id)), [running.id, paused.id]) + } + + func test_알람_목록을_모르면_정리하지_않는다() { + let ringing = timer("울림", endsIn: -10, state: .ringing) + let (useCase, _) = makeUseCase([ringing]) + scheduler.live = nil + + useCase.syncWithSystemAlarms() + + XCTAssertEqual(useCase.timers.value.count, 1) + } +} + +private final class FakeAlarmScheduler: TimerAlarmScheduling { + var live: Set? + + func requestAuthorization() -> AnyPublisher { Just(true).eraseToAnyPublisher() } + func authorizationStatus() -> AnyPublisher { Just(.authorized).eraseToAnyPublisher() } + func scheduleAlarm(id: UUID, label: String, categoryName: String, body: String, fireDate: Date) {} + func cancelAlarm(id: UUID) {} + func pauseAlarm(id: UUID) {} + func resumeAlarm(id: UUID, label: String, categoryName: String, body: String, fireDate: Date) {} + func reschedulePausedAlarm(id: UUID, label: String, categoryName: String, body: String, remaining: Int) {} + func liveAlarmIDs() -> Set? { live } +} + +private final class TimersRepository: TimerRepositoryProtocol { + var timers: [TreatmentTimerModel] + + init(timers: [TreatmentTimerModel]) { self.timers = timers } + + func loadTimers() -> [TreatmentTimerModel] { timers } + func saveTimers(_ timers: [TreatmentTimerModel]) { self.timers = timers } + func loadPresets() -> [TimerPresetModel] { [] } + func savePresets(_ presets: [TimerPresetModel]) {} + func setAlarmAuthorized(_ authorized: Bool) {} + func alarmAuthorizedFlag() -> Bool? { nil } +} diff --git a/Projects/Features/HomeFeature/Tests/Sources/HomeTestDependencies.swift b/Projects/Features/HomeFeature/Tests/Sources/HomeTestDependencies.swift index 95fdb8e..ee7b5d1 100644 --- a/Projects/Features/HomeFeature/Tests/Sources/HomeTestDependencies.swift +++ b/Projects/Features/HomeFeature/Tests/Sources/HomeTestDependencies.swift @@ -55,6 +55,7 @@ final class StubTimerUseCase: TimerUseCase { func updateMemo(id: UUID, memo: String?) {} func refresh() {} func reload() {} + func syncWithSystemAlarms() {} func handleWatchCommand(_ command: TimerWatchCommand) {} func addPreset(label: String, category: TimerCategory, duration: Int) {} func updatePreset(_ preset: TimerPresetModel) {} diff --git a/Projects/Features/TimerFeature/Sources/TimerScene/Alarm/AlarmKitAlarmScheduler.swift b/Projects/Features/TimerFeature/Sources/TimerScene/Alarm/AlarmKitAlarmScheduler.swift index a935212..838ba71 100644 --- a/Projects/Features/TimerFeature/Sources/TimerScene/Alarm/AlarmKitAlarmScheduler.swift +++ b/Projects/Features/TimerFeature/Sources/TimerScene/Alarm/AlarmKitAlarmScheduler.swift @@ -8,12 +8,35 @@ import TimerShared // iOS 26 AlarmKit 알람 스케줄러 — Clock 앱 동급 시스템 알람. // 강제종료/잠금/무음/Focus 모두 뚫고 풀스크린+루핑으로 울림(AlarmManager가 시스템 수준 관리). -// [완료](stop)는 시스템 자동 처리 + TimerStopIntent가 모델 삭제. +// [완료](stop)는 시스템 자동 처리 + TimerStopIntent가 모델 삭제. 인텐트가 못 지운 타이머는 +// 앱이 알람 목록과 맞춰 정리한다(liveAlarmIDs · alarmsChanged, NM-635). // (AlarmPresentation.Alert 의 비권장 init이 iOS 26.1+ 이므로 26.1 게이트) @available(iOS 26.1, *) public final class AlarmKitAlarmScheduler: TimerAlarmScheduling { - public init() {} + private let alarmsChangedSubject = PassthroughSubject() + private var updatesTask: Task? + + public init() { + // 앱 밖(잠금화면 · Dynamic Island · 워치)에서 끈 알람도 여기로 들어온다 (NM-635). + updatesTask = Task { [weak self] in + for await _ in AlarmManager.shared.alarmUpdates { + await MainActor.run { self?.alarmsChangedSubject.send() } + } + } + } + + deinit { updatesTask?.cancel() } + + public var alarmsChanged: AnyPublisher { + alarmsChangedSubject.eraseToAnyPublisher() + } + + /// 위젯이 예약한 알람도 앱의 알람이라 함께 나온다. + public func liveAlarmIDs() -> Set? { + guard let alarms = try? AlarmManager.shared.alarms else { return nil } + return Set(alarms.map(\.id)) + } public func requestAuthorization() -> AnyPublisher { Future { promise in