fix(training): 修复课程学习倒计时停顿

This commit is contained in:
2026-10-20 16:54:17 +08:00
parent 27be1f30ed
commit 186e9ad3e4
6 changed files with 341 additions and 26 deletions
@@ -203,6 +203,93 @@ final class TrainingDocumentPreviewTests: XCTestCase {
XCTAssertFalse(calls.contains { ["sections", "section"].contains($0.name) })
}
/// 实际课程滚动回调持续触发时,按钮倒计时仍随有效阅读时间减少。
func testContinuousCourseScrollingKeepsCountdownRunning() async throws {
let document = try temporaryDocument(text: (1...120).map { "第 \($0) 行:滑动阅读时仍应累计有效读时。" }.joined(separator: "\n"), kind: .txt)
defer { try? FileManager.default.removeItem(at: document.fileURL.deletingLastPathComponent()) }
let (controller, _, scroll, window) = try await makeCourseWindow(document: document, readingSeconds: 0)
defer { closeWindow(window) }
let action = try XCTUnwrap(allViews(controller.view).compactMap { $0 as? UIButton }
.first { $0.accessibilityIdentifier == "training.reading.action" })
func remainingSeconds() -> Int? {
guard let title = action.configuration?.title, let start = title.lastIndex(of: "("),
let end = title.range(of: "s)")?.lowerBound else { return nil }
return Int(title[title.index(after: start)..<end])
}
try await waitUntil { remainingSeconds() != nil }
let before = try XCTUnwrap(remainingSeconds())
let deadline = ContinuousClock.now.advanced(by: .milliseconds(3200))
var frame = 0
while ContinuousClock.now < deadline {
scroll.setContentOffset(CGPoint(x: 0, y: 220 + frame % 80), animated: false)
frame += 1
try await Task.sleep(for: .milliseconds(16))
}
XCTAssertGreaterThan(frame, 60)
let after = try XCTUnwrap(remainingSeconds())
XCTAssertLessThanOrEqual(after, before - 2, "正文持续可见时,滚动不能重置计时起点")
record(UIGraphicsImageRenderer(size: controller.view.bounds.size).image { _ in
controller.view.drawHierarchy(in: controller.view.bounds, afterScreenUpdates: true)
}, name: "课程持续滚动倒计时")
}
/// 慢心跳不能冻结真实页面倒计时,读满后仍须等待后端确认才能开始考试。
func testSlowHeartbeatKeepsCountdownRunningUntilServerConfirmsReading() async throws {
let document = try temporaryDocument(text: (1...120).map { "第 \($0) 行:课程阅读期间上报进度不应打断倒计时。" }.joined(separator: "\n"), kind: .txt)
defer { try? FileManager.default.removeItem(at: document.fileURL.deletingLastPathComponent()) }
let gate = TrainingCourseHeartbeatGate()
defer { Task { await gate.releaseAll() } }
var configuration = TrainingDataStub.Configuration()
configuration.readingSeconds = 14
let source = TrainingDataStub(configuration: configuration)
await source.configure {
$0.heartbeatHandler = { call in
await gate.wait(sequence: call.sequence)
return TrainingHeartbeatConfirmation(sessionID: call.sessionID, acceptedSequence: call.sequence,
acceptedActiveSecondsTotal: call.activeSecondsTotal, sessionClosed: call.final,
progress: TrainingRemoteFixtures.progress(seconds: min(20, 14 + call.activeSecondsTotal)))
}
}
let controller = TrainingCourseViewController(taskID: "task_1", service: source,
documentLoader: TrainingFixtureDocumentLoader { _, _ in document })
let navigation = UINavigationController(rootViewController: controller)
let window = try makeWindow(navigation)
defer { closeWindow(window) }
let action = try XCTUnwrap(allViews(controller.view).compactMap { $0 as? UIButton }
.first { $0.accessibilityIdentifier == "training.reading.action" })
try await waitUntil {
await source.heartbeats.count == 1 && action.configuration?.title == "开始考试(1s)"
}
let firstHeartbeats = await source.heartbeats
let first = try XCTUnwrap(firstHeartbeats.first)
XCTAssertEqual(first.sequence, 1)
XCTAssertEqual(first.activeSecondsTotal, 5)
XCTAssertFalse(first.final)
try await waitUntil { action.configuration?.title == "开始考试(0s)" }
XCTAssertFalse(action.isEnabled, "本地读满而首个心跳尚未返回,不能提前开始考试")
let heldHeartbeats = await source.heartbeats
XCTAssertEqual(heldHeartbeats.count, 1, "同一会话的心跳必须串行发送")
action.sendActions(for: .touchUpInside)
XCTAssertTrue(navigation.topViewController === controller)
let callsBeforeConfirmation = await source.calls
XCTAssertFalse(callsBeforeConfirmation.contains { ["paper", "questions", "draft"].contains($0.name) })
await gate.release(sequence: 1)
try await waitUntil { await source.heartbeats.count == 2 }
let finalHeartbeats = await source.heartbeats
let final = try XCTUnwrap(finalHeartbeats.last)
XCTAssertEqual(final.sessionID, first.sessionID)
XCTAssertEqual(final.sequence, 2)
XCTAssertEqual(final.activeSecondsTotal, 6)
XCTAssertTrue(final.final)
XCTAssertEqual(action.configuration?.title, "开始考试(0s)")
XCTAssertFalse(action.isEnabled, "后端只确认了 19 秒,最终 20 秒确认返回前仍应禁用")
await gate.release(sequence: 2)
try await waitUntil { action.isEnabled && action.configuration?.title == "开始考试" }
XCTAssertTrue(navigation.topViewController === controller)
}
/// 长文件由课程页面统一滚动,原生信息随正文离屏,换为短文件后不残留空白高度。
func testLongTextUsesOuterPageScrollingAndShrinksForNextDocument() async throws {
let lines = (1...120).map { "第 \($0) 行:这是完整课程阅读内容,向上滑动时标题和正文应一同移动。" }
@@ -374,8 +461,10 @@ final class TrainingDocumentPreviewTests: XCTestCase {
return TrainingLocalDocument(fileURL: file, kind: kind, name: file.lastPathComponent, temporaryDirectory: nil)
}
private func makeCourseWindow(document: TrainingLocalDocument) async throws -> (TrainingCourseViewController, TrainingDocumentPreviewView, UIScrollView, UIWindow) {
let source = TrainingDataStub()
private func makeCourseWindow(document: TrainingLocalDocument, readingSeconds: Int = 20) async throws -> (TrainingCourseViewController, TrainingDocumentPreviewView, UIScrollView, UIWindow) {
var configuration = TrainingDataStub.Configuration()
configuration.readingSeconds = readingSeconds
let source = TrainingDataStub(configuration: configuration)
let name = document.name
let mime: String
switch document.kind {
@@ -469,3 +558,27 @@ final class TrainingDocumentPreviewTests: XCTestCase {
guard reached else { throw CancellationError() }
}
}
/// 精确挂起课程心跳响应,确保超时或断言失败后也能释放所有等待。
private actor TrainingCourseHeartbeatGate {
private var releasedSequences: Set<Int> = []
private var didReleaseAll = false
private var waiters: [Int: [CheckedContinuation<Void, Never>]] = [:]
func wait(sequence: Int) async {
guard !didReleaseAll, !releasedSequences.contains(sequence) else { return }
await withCheckedContinuation { waiters[sequence, default: []].append($0) }
}
func release(sequence: Int) {
releasedSequences.insert(sequence)
waiters.removeValue(forKey: sequence)?.forEach { $0.resume() }
}
func releaseAll() {
didReleaseAll = true
let pending = waiters.values.flatMap { $0 }
waiters.removeAll()
pending.forEach { $0.resume() }
}
}
@@ -112,7 +112,9 @@ struct TrainingFeatureTests {
func foregroundClock() {
var clock = TrainingReadingClock()
clock.resume(at: 10)
clock.resume(at: 10.5)
let partial = clock.takeSecond(at: 10.99)
clock.resume(at: 10.99)
let whole = clock.takeSecond(at: 11)
#expect(!partial)
#expect(whole)
+185 -7
View File
@@ -97,6 +97,153 @@ struct TrainingRemoteReadingTests {
#expect(model.remainingSeconds == 0)
}
/// 滚动每帧重新确认正文可见,不能重置已经运行的整秒计时片段。
@Test("持续滚动十秒仍正常倒计时,只按五秒间隔上报")
func continuousScrollingPreservesReadingTime() async {
let source = source()
let model = model(source)
await loadRendered(model)
await model.startReading(at: 0)
for frame in 1...600 {
let uptime = Double(frame) / 60
await model.startReading(at: uptime)
if frame.isMultiple(of: 15) { await model.recordVisibleTime(at: uptime) }
}
#expect(model.isReading)
#expect(model.activeSecondsTotal == 10)
#expect(model.remainingSeconds == 10)
#expect(model.progress?.readingSeconds == 10)
#expect(await source.startReadingRequests.count == 1)
let heartbeats = await source.heartbeats
#expect(heartbeats.map(\.activeSecondsTotal) == [5, 10])
#expect(heartbeats.map(\.sequence) == [1, 2])
#expect(heartbeats.allSatisfy { !$0.final })
}
/// 请求等待响应期间,本地倒计时继续;迟到确认不能覆盖后续可见读时。
@Test("五秒心跳挂起时继续累计到八秒,确认后倒计时不回跳")
func slowHeartbeatDoesNotBlockLocalCountdown() async {
let source = source()
let gate = TrainingReadingHeartbeatGate()
await source.configure { $0.heartbeatHandler = { await gate.confirm($0) } }
let model = model(source)
await loadRendered(model)
await model.startReading(at: 0)
for second in 1...4 { await model.recordVisibleTime(at: Double(second)) }
let operation = Task { await model.recordVisibleTime(at: 5) }
await gate.waitUntilRequested()
for second in 6...8 { #expect(model.accumulateVisibleTime(at: Double(second))) }
#expect(model.activeSecondsTotal == 8)
#expect(model.remainingSeconds == 12)
#expect(model.progress?.readingSeconds == 0)
#expect(!model.needsReadingFlush)
#expect(await source.heartbeats.count == 1)
await gate.release()
await operation.value
#expect(model.activeSecondsTotal == 8)
#expect(model.remainingSeconds == 12)
#expect(model.progress?.readingSeconds == 5)
#expect(!model.needsReadingFlush)
#expect(model.accumulateVisibleTime(at: 9))
#expect(!model.needsReadingFlush)
#expect(model.accumulateVisibleTime(at: 10))
#expect(model.needsReadingFlush)
await model.flush()
let heartbeats = await source.heartbeats
#expect(heartbeats.map(\.activeSecondsTotal) == [5, 10])
#expect(heartbeats.map(\.sequence) == [1, 2])
#expect(heartbeats.allSatisfy { !$0.final })
#expect(model.activeSecondsTotal == 10)
#expect(model.remainingSeconds == 10)
#expect(model.progress?.readingSeconds == 10)
#expect(await source.startReadingRequests.count == 1)
}
/// 慢请求已经提交但丢响应时,后续本地读时不能混入同序号重试负载。
@Test("慢心跳丢响应后冻结五秒负载重试,后续读时使用新序号")
func slowHeartbeatResponseLossKeepsFrozenPayload() async {
let source = source()
let server = TrainingReadingReplyController(loseHeartbeatResponse: true)
let gate = TrainingReadingHeartbeatGate()
await bind(server, to: source)
await source.configure { $0.heartbeatHandler = { call in
_ = await gate.confirm(call)
return try await server.confirm(call)
} }
let model = model(source)
await loadRendered(model)
await model.startReading(at: 0)
for second in 1...4 { await model.recordVisibleTime(at: Double(second)) }
let operation = Task { await model.recordVisibleTime(at: 5) }
await gate.waitUntilRequested()
for second in 6...8 { #expect(model.accumulateVisibleTime(at: Double(second))) }
await gate.release()
await operation.value
#expect(model.readingErrorMessage != nil)
#expect(!model.isReading)
#expect(model.activeSecondsTotal == 8)
#expect(model.remainingSeconds == 12)
#expect(!model.needsReadingFlush)
#expect(!model.accumulateVisibleTime(at: 9))
await model.flush()
let retried = await source.heartbeats
#expect(retried.count == 2)
#expect(retried[0] == retried[1])
#expect(retried[0].activeSecondsTotal == 5 && !retried[0].final)
#expect(model.progress?.readingSeconds == 5)
#expect(model.activeSecondsTotal == 8)
#expect(model.remainingSeconds == 12)
await model.startReading(at: 100)
#expect(model.accumulateVisibleTime(at: 101))
#expect(model.accumulateVisibleTime(at: 102))
#expect(model.needsReadingFlush)
await model.flush()
let heartbeats = await source.heartbeats
#expect(heartbeats.map(\.activeSecondsTotal) == [5, 5, 10])
#expect(heartbeats.map(\.sequence) == [1, 1, 2])
#expect(model.progress?.readingSeconds == 10)
#expect(model.remainingSeconds == 10)
#expect(await source.startReadingRequests.count == 1)
}
/// 首次建会话期间到达的重复恢复,等待完成后也不能覆盖首个计时起点。
@Test("并发恢复等待同一会话,返回后不重置正在运行的时钟")
func concurrentResumesPreserveFirstReadingStart() async {
let source = source()
let server = TrainingReadingReplyController()
let gate = TrainingReadingSessionGate()
await bind(server, to: source)
await source.configure { $0.startReadingHandler = { requestID in
let session = try await server.create(requestID: requestID)
await gate.wait()
return session
} }
let model = model(source)
await loadRendered(model)
let starting = Task { await model.startReading(at: 0) }
await gate.waitUntilRequested()
let probes = (0..<3).map { _ in TrainingReadingResumeProbe() }
let repeated = probes.map { probe in
Task {
probe.started = true
await model.startReading(at: 0.75)
probe.finished = true
}
}
while probes.contains(where: { !$0.started }) { await Task.yield() }
#expect(probes.allSatisfy { !$0.finished })
#expect(await source.startReadingRequests.count == 1)
await gate.release()
await starting.value
for operation in repeated { await operation.value }
await model.recordVisibleTime(at: 1)
#expect(model.isReading)
#expect(model.activeSecondsTotal == 1)
#expect(model.remainingSeconds == 19)
#expect(await source.startReadingRequests.count == 1)
#expect(await source.heartbeats.isEmpty)
}
/// 已保存读时不混入会话累计;不足五秒的门槛片段也即时确认。
@Test("历史十二秒加新会话八秒,心跳总数仍从零开始")
func historyAndSessionAreSeparate() async {
@@ -201,8 +348,8 @@ struct TrainingRemoteReadingTests {
#expect(model.activeSecondsTotal == 0)
}
/// 暂停发生在网络请求中间时,先确认旧负载,再以新序号关闭。
@Test("普通心跳请求中途暂停,确认后再发送 final")
/// 慢请求中新增读时先留在本地,暂停后确认旧负载,再以新序号关闭全部片段。
@Test("普通心跳请求中继续累计后暂停,确认旧负载再 final 保存全部读时")
func pauseDuringHeartbeatFinishesSequentially() async {
let source = source()
let gate = TrainingReadingHeartbeatGate()
@@ -213,9 +360,15 @@ struct TrainingRemoteReadingTests {
for second in 1...4 { await model.recordVisibleTime(at: Double(second)) }
let operation = Task { await model.recordVisibleTime(at: 5) }
await gate.waitUntilRequested()
#expect(model.accumulateVisibleTime(at: 6))
#expect(model.accumulateVisibleTime(at: 7))
#expect(model.activeSecondsTotal == 7)
#expect(model.remainingSeconds == 13)
model.pauseReading()
#expect(!model.accumulateVisibleTime(at: 8))
let closing = Task { await model.flush() }
#expect(await source.heartbeats.count == 1)
#expect(await source.heartbeats.first?.activeSecondsTotal == 5)
await gate.release()
await operation.value
await closing.value
@@ -223,9 +376,10 @@ struct TrainingRemoteReadingTests {
#expect(calls.count == 2)
#expect(calls[0].sequence == 1 && !calls[0].final)
#expect(calls[1].sequence == 2 && calls[1].final)
#expect(calls[0].activeSecondsTotal == calls[1].activeSecondsTotal)
#expect(calls[0].activeSecondsTotal == 5)
#expect(calls[1].activeSecondsTotal == 7)
#expect(!model.isReading)
#expect(model.progress?.readingSeconds == 5)
#expect(model.progress?.readingSeconds == 7)
}
/// 前台恢复发生在 final 请求中途,等待结束后必须真正建立新会话。
@@ -740,13 +894,13 @@ private actor TrainingReadingAttachmentGate {
}
}
/// 精确挂起首个普通心跳,验证暂停不会并行发送或更改该请求。
/// 精确挂起首个普通心跳,验证后续读时、暂停和重试不会更改已发送负载。
private actor TrainingReadingHeartbeatGate {
private var response: CheckedContinuation<Void, Never>?
private var waiters: [CheckedContinuation<Void, Never>] = []
private var hasDelayed = false
/// 首个请求等待测试释放,后续最终心跳立即确认。
/// 首个请求等待测试释放,后续请求立即确认。
func confirm(_ call: TrainingDataStub.HeartbeatCall) async -> TrainingHeartbeatConfirmation {
if !hasDelayed {
hasDelayed = true
@@ -767,7 +921,31 @@ private actor TrainingReadingHeartbeatGate {
await withCheckedContinuation { waiters.append($0) }
}
/// 让普通心跳完成,页面随后应使用新序号发送 final。
/// 释放已挂起的普通心跳,让测试检查迟到确认之后的状态。
func release() { response?.resume(); response = nil }
}
/// 挂起首次建会话响应,让并发可见性恢复请求稳定进入等待队列。
private actor TrainingReadingSessionGate {
private var response: CheckedContinuation<Void, Never>?
private var waiters: [CheckedContinuation<Void, Never>] = []
/// 等待测试释放创建响应,不使用真实时间延时。
func wait() async {
await withCheckedContinuation {
response = $0
waiters.forEach { $0.resume() }
waiters = []
}
}
/// 等待首次会话创建已在响应边界挂起。
func waitUntilRequested() async {
if response != nil { return }
await withCheckedContinuation { waiters.append($0) }
}
/// 允许首次创建完成,其余恢复应复用已经运行的会话。
func release() { response?.resume(); response = nil }
}